diff --git "a/4060.jsonl" "b/4060.jsonl" new file mode 100644--- /dev/null +++ "b/4060.jsonl" @@ -0,0 +1,476 @@ +{"seq_id":"632188370","text":"#!/usr/bin/python\n\nimport os, requests, json, sys, subprocess\nfrom requests.auth import HTTPBasicAuth\nimport socket\n\nzabbix_server = \"192.168.19.10/zabbix\"\nzabbix_api_admin_name = \"Admin\"\nzabbix_api_admin_password = \"zabbix\"\n\ncustom_group_name = 'CloudHosts'\ncustom_template_name = 'MegaCustomTemplate'\n\ndef post(request):\n headers = {'content-type': 'application/json'}\n return requests.post(\n \"http://\" + zabbix_server + \"/api_jsonrpc.php\",\n data=json.dumps(request),\n headers=headers,\n auth=HTTPBasicAuth(zabbix_api_admin_name, zabbix_api_admin_password)\n )\n\n\nauth_token = post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"user.login\",\n \"params\": {\n \"user\": zabbix_api_admin_name,\n \"password\": zabbix_api_admin_password\n },\n \"auth\": None,\n \"id\": 0}\n).json()[\"result\"]\n\n\ndef host_get():\n return post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"host.get\",\n \"params\": {\n \"output\": [\n \"hostid\",\n \"host\"\n ]\n },\n \"id\": 2,\n \"auth\": auth_token\n }).json()[\"result\"]\nserver_hostname = host_get()[0]['host']\nserver_hostid = host_get()[0]['hostid']\n\ndef template_get():\n return post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"template.get\",\n \"params\": {\n \"output\": \"extend\",\n \"filter\": {\n \"name\": custom_template_name\n }\n },\n \"id\": 3,\n \"auth\": auth_token\n }).json()[\"result\"]\n\n\ndef template_create(groupid):\n return post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"template.create\",\n \"params\": {\n \"host\": custom_template_name,\n \"groups\": {\n \"groupid\": groupid\n }\n },\n \"id\": 6,\n \"auth\": auth_token\n }).json()[\"result\"]\n\n\ndef create_custom_group(custom_group_name):\n return post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"hostgroup.create\",\n \"params\": {\n \"name\": custom_group_name\n },\n \"id\": 5,\n \"auth\": auth_token\n }).json()[\"result\"]\n\ndef get_custom_group():\n return post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"hostgroup.get\",\n \"params\": {\n \"output\": \"extend\",\n \"filter\": {\n \"name\": custom_group_name\n }\n },\n \"id\": 4,\n \"auth\": auth_token\n }).json()[\"result\"]\n\n\ngroupid = 0\ntemplateid = 0\nif len(get_custom_group()) == 0:\n print(\"There isn't the group with name: %s\" % custom_group_name)\n groupid = create_custom_group(custom_group_name)['groupids'][0]\n templateid = template_create(groupid)['templateids'][0]\n print(\"Group \\\"%s\\\" was successfully created, \" % custom_group_name)\n print(\"groupid=%s, templateid=%s\" % (groupid, templateid))\nelse:\n groupid = get_custom_group()[0]['groupid']\n templateid = template_get()[0]['templateid']\n print(\"Group \\\"%s\\\" already exists with groupid=%s, templateid=%s\" % (custom_group_name, groupid, templateid))\n\n\nhostname = socket.gethostname()\nproc = subprocess.Popen(['hostname', '-I'], stdout=subprocess.PIPE)\nipaddress = str(proc.stdout.read()).split()[1]\n\ndef register_host(hostname, ipaddress, groupid, templateid):\n return post({\n \"jsonrpc\": \"2.0\",\n \"method\": \"host.create\",\n \"params\": {\n \"host\": hostname,\n \"templates\": [{\n \"templateid\": templateid\n }],\n \"interfaces\": [{\n \"type\": 1,\n \"main\": 1,\n \"useip\": 1,\n \"ip\": ipaddress,\n \"dns\": \"\",\n \"port\": \"10050\"\n }],\n \"groups\": [\n {\"groupid\": groupid}\n ]\n },\n \"auth\": auth_token,\n \"id\": 1\n })\n\nprint(register_host(hostname, ipaddress, groupid, templateid))\nprint(\"%s was sucessfully registered on zabbix server in %s.\" % (hostname, custom_group_name))","sub_path":"02/scripts/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":3961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"170877664","text":"\nimport sklearn\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn import linear_model\nfrom matplotlib import style\n\ndataset1 = pd.read_csv('Resources/Student_mat.csv')\n\ndata = dataset1[['G1','G2','G3','studytime','failures','absences']]\n\npredict = 'G3'\n\nX = np.array(data.drop([predict],1))\ny = np.array(data[predict])\n\nX_train,X_test,y_train,y_test = sklearn.model_selection.train_test_split(X, y, test_size = 0.1)\n\nlinear = linear_model.LinearRegression()\nlinear.fit(X_train,y_train)\naccuracy = linear.score(X_test,y_test)\n\nprint(accuracy)\nprint(\"Coefficient = \",linear.coef_)\nprint(\"Intercept = \",linear.intercept_)\n\npredictions = linear.predict(X_test)\nfor x in range(len(predictions)):\n print(predictions[x],X_test[x],y_test[x])\n\n\np = 'G1'\nstyle.use(\"ggplot\")\nplt.scatter(data[p], data['G3'])\nplt.xlabel(p)\nplt.ylabel(\"Final Grade\")\nplt.show()\n","sub_path":"Student Marks Prediction/Project1.py","file_name":"Project1.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"549846731","text":"\"\"\"\nPlot the beta distribution.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\ndef Beta(x, alpha, beta):\n pmf = x ** (alpha - 1) * (1 - x) ** (beta - 1)\n norm_const = np.trapz(pmf, x)\n pmf /= norm_const\n return pmf\n\ndef Gaussian(x, mu, sigma):\n pmf = (1 / np.sqrt(2 * math.pi * sigma ** 2)) * np.exp(- (x - mu ) ** 2 / (2 * sigma ** 2))\n return pmf\n\n# The Beta distribution is defined for a range of x between 0 and 1.\n# The smaller the step size in x, the better the normalisation.\n\nx = np.arange(0.0001, 1, 0.0001) # Exclude 0 and 1 from the range of x for alpha, beta < 1, otherwise we get divide by zero errors\n\n#plt.plot(x, Beta(x, 0.5, 1)) # pmf tends to infinity at x = 0, and 0.5 at x = 1\n#plt.plot(x, Beta(x, 0.5, 0.5)) # U-shaped pmf, tending to infinity at x = 0 and x = 1\n\nx = np.arange(0, 1.0001, 0.0001) # Include 0 and 1 in the range of x for values of alpha and beta >= 1 \n\n#plt.plot(x, Beta(x, 1, 1)) # Uniform pmf, equal to 1 for all x\n#plt.plot(x, Beta(x, 2, 1)) # Straight line with positive gradient, from 0 at x = 0 to 2 at x = 1\n#plt.plot(x, Beta(x, 1, 2)) # Straight line with negative gradient, from 2 at x = 0 to 0 at x = 1\n#plt.plot(x, Beta(x, 2, 2)) # Upside-down parabola centred on x = 0.5\n#plt.plot(x, Beta(x, 3, 2)) # Broad, skewed distribution with bump on right\n#plt.plot(x, Beta(x, 3, 3)) # Broad symmetric distribution centred on x = 0.5\nplt.plot(x, Beta(x, 10, 10)) # Symmetric distribution centred on x = 0.5 (medium width)\n#plt.plot(x, Beta(x, 100, 100)) # Narrow symmetric distribution centred on x = 0.5\n#plt.plot(x, Beta(x, 30, 100)) # Almost symmetric distribution centred on x ~ 0.226\n#plt.plot(x, Beta(x, 30, 50)) # Almost symmetric distribution centred on x ~ 0.372\n\nplt.plot(x, Gaussian(x, 0.5, 0.112)) # Gaussian distribution most similar to Beta(10, 10)\n\nprint(np.trapz(Gaussian(x, 0.5, 0.3), x))\n\nplt.show()","sub_path":"chw/beta.py","file_name":"beta.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"70766918","text":"# extract raw image physical size\nrawDir = \"/home/hxie1/data/BES_3K/raw\"\npatientIDPath =\"/home/hxie1/data/BES_3K/GTs/HypertensionStudyID_IncludeIncompleteClinic_20211009.txt\"\noutputPath = \"/home/hxie1/data/BES_3K/GTs/HypertensionStudyID_IncludeIncompleteClinic_20210917_rawPhysicalSizePxPy.txt\"\n\nimport os\nimport glob as glob\n\nwith open(patientIDPath,'r') as patientIDFile:\n IDList = patientIDFile.readlines()\n IDList = [x[0:x.find(\"\\n\")] for x in IDList] # erase \"\\n\"\n\nwith open(outputPath, 'w') as outputFile:\n for ID in IDList:\n volumeDir = os.path.join(rawDir, ID+\"_Volume\")\n infoPathList = glob.glob(volumeDir + f\"/*_Info.txt\")\n if len(infoPathList) != 1:\n print(f\"in {volumeDir}, program found {len(infoPathList)} info files. Program ignore this volume.\")\n continue\n infoPath = infoPathList[0]\n with open(infoPath, 'r') as infoFile:\n lines = infoFile.readlines()\n '''\n A-Scan Width (optical res): 11.872869916260242 um/pixel\n A-Scan Height (oct res): 252.9579997062683 um/pixel\n cSLO Width (optical res): 11.872869916260242 um/pixel\n cSLO Height (optical res): 11.872869916260242 um/pixel\n \n '''\n px = 0\n py = 0\n for line in lines:\n if \"A-Scan Width (optical res):\" in line:\n line = line.replace(\"A-Scan Width (optical res):\", \"\")\n line = line.strip()\n strings = line.split(\" \")\n px = float(strings[0])\n elif \"A-Scan Height (oct res):\" in line:\n line = line.replace(\"A-Scan Height (oct res):\", \"\")\n line = line.strip()\n strings = line.split(\" \")\n py= float(strings[0])\n else:\n continue\n\n if (px ==0) or (py ==0):\n print(f\"{ID} can not find correct physical size in dir: {volumeDir}\")\n else:\n outputFile.write(f\"{ID}\\t{px}\\t{py}\\n\")\n\nprint(f\"============== Output XY physical size in the {outputPath} ===================\")\n","sub_path":"OCT2SysDisease/HypertensionAssociation/extractRawPhysicalSize.py","file_name":"extractRawPhysicalSize.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"58693934","text":"import requests\nfrom majesticseo.items import Item\n\n# -*- coding: utf-8 -*-\n\n\nclass Majestic(object):\n\n \"\"\"\n Core class which create a Majestic object which will trigger requests to the API\n \"\"\"\n def __init__(self, api_key):\n self.api_key = api_key\n self.endpoint = 'https://api.majestic.com/api/json?'\n self.subscription_info = self.get_subscription_info()\n # self.res_units = self.subscription_info['TotalAnalysisResUnits']\n\n def get_subscription_info(self):\n params = {\n 'cmd': 'GetSubscriptionInfo',\n 'app_api_key': self.api_key\n }\n r = requests.get(self.endpoint, params=params)\n return r.json()\n\n def get_info(self, items):\n \"\"\"\n Standard method that takes a list of items (Urls, subdomains or domains) and return\n description data of each item.\n :param items: List of domains/subdomains\n :return: List of Item objects.\n \"\"\"\n params = {\n 'items': len(items),\n 'app_api_key': self.api_key,\n 'cmd': 'GetIndexItemInfo',\n 'datasource': 'fresh'\n }\n for i, item in enumerate(items):\n params['item{}'.format(i)] = item\n r = requests.get(self.endpoint, params=params)\n response_object = InfoResponse(r.json())\n return response_object\n\n def get_backlinks(self, item, max_results=1000, max_per_domain=1, max_per_source=1, remove_deleted=True):\n params = {\n 'app_api_key': self.api_key,\n 'cmd': 'GetBackLinkData',\n 'MaxSourceURLsPerRefDomain': max_per_domain,\n 'MaxSameSourceURLs': max_per_source,\n 'Mode': int(remove_deleted),\n 'Count': max_results,\n 'item': item\n }\n r = requests.get(self.endpoint, params=params)\n return r.json()\n\n\nclass InfoResponse(object):\n\n def __init__(self, response):\n self.json = response\n self.code = response['Code']\n self.error_message = response['ErrorMessage']\n self.index_type = self.parse_index_type()\n self.domains_analysed = response['QueriedRootDomains']\n self.subdomains_analysed = response['QueriedSubDomains']\n self.urls_analysed = response['QueriedURLs']\n self.items = self.parse_response_items()\n\n def parse_index_type(self):\n if self.json.get('IndexType') == 0:\n return 'historic'\n return 'fresh'\n\n def parse_response_items(self):\n items = list()\n for item in self.json['DataTables']['Results']['Data']:\n item = self.create_item(item)\n items.append(item)\n return items\n\n def create_item(self, item):\n item = Item(item)\n return item\n\n\nif __name__ == '__main__':\n majestic = Majestic(api_key='770234E562D7E51D66DCB1138DBB27B3')\n print(majestic.subscription_info)\n","sub_path":"majesticseo/majestic.py","file_name":"majestic.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"440054576","text":"qi = int(input(\"Quantia inicial: \"))\ntempo = int(input(\"Tempo de investimento: \"))\njuros = 4.0\nsaldo = qi # Variavel acumuladora\n# Valor inicial da variável contadora\nt = 0\n# Atualizacao de saldo\nwhile (t <= tempo):\n rend = saldo * juros/100\n saldo = saldo + rend\n t = t + qi\nprint(\"Saldo: R$\", round(saldo, 2)) ","sub_path":"exs-s/1135/1561-1135.py","file_name":"1561-1135.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"637117108","text":"\"\"\"\r\n Автор программы: Алексей Л.\r\n schizm.one@gmail.com\r\n\r\n Данная программа предназначена для вывода суммы цифр факториала какого-\r\n либо введенного пользователем числа.\r\n\"\"\"\r\n\r\nif __name__ == \"__main__\":\r\n # Введем число, для которого вычислим факториал.\r\n inputnumber = int(input(\\\r\n \"Введите число, сумму цифр факториала которого, вы хотите получить: \"))\r\n\r\n # Начинаем вычислять факториал по формуле: n! = n × (n − 1) × ... × 3 × 2 × 1\r\n # т.е. мы запоминаем максимальное число и просто начинаем уменьшать его на\r\n # единицу при каждой итерации цикла.\r\n factorial = inputnumber\r\n for i in range(inputnumber, 0, -1):\r\n factorial *= i\r\n\r\n # Выведем на экран вычисленный факториал.\r\n print(\"Факториал числа %d:\\n%d\" %\\\r\n (inputnumber, factorial) )\r\n\r\n # Теперь, преобразуем вычисленный факториал в строку, чтобы можно было\r\n # пройти по каждому символу в этой строке, т.е. по каждой цифре.\r\n factorialstr = str(factorial)\r\n\r\n # Начинаем проход по всем цифрам в этой строке, суммируя их, перед этим\r\n # преобразовывая в целочисленные значения.\r\n factsumstr = 0\r\n for i in factorialstr:\r\n factsumstr += int(i)\r\n\r\n # Выводим конечный результат на экран.\r\n print(\"Cумма цифр в факториале от числа %d:\\n%d\" %\\\r\n (inputnumber, factsumstr) )","sub_path":"taskfactorial.py","file_name":"taskfactorial.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"195914875","text":"# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport logging\nfrom typing import Optional, Union\n\nfrom model_navigator import Format, Precision\nfrom model_navigator.config import ModelNavigatorBaseConfig\nfrom model_navigator.config.config_field import ConfigField\nfrom model_navigator.config.config_list_numeric import ConfigListNumeric\nfrom model_navigator.config.config_list_string import ConfigListString\nfrom model_navigator.config.config_primitive import ConfigPrimitive\nfrom model_navigator.tensor import TensorSpec\n\nLOGGER = logging.getLogger(__name__)\n\nTRITON_SUPPORTED_FORMATS = [\n Format.TS_TRACE,\n Format.TS_SCRIPT,\n Format.TF_SAVEDMODEL,\n Format.ONNX,\n Format.TRT,\n]\n\n\ndef parse_tensor_spec(shapes):\n return [TensorSpec.from_command_line(s) for s in shapes]\n\n\ndef parse_precisions(precisions):\n return [p if isinstance(p, Precision) else Precision(p) for p in precisions]\n\n\ndef parse_format(format_: Optional[Union[str, Format]]):\n if format_ is None or isinstance(format_, Format):\n return format_\n return Format(format_)\n\n\ndef parse_value_range(value_ranges):\n results = []\n for value_range in value_ranges:\n name, range_str = value_range.split(\":\")\n min_value, max_value = range_str.split(\",\")\n\n has_dot = \".\" in min_value or \".\" in max_value\n min_value, max_value = float(min_value), float(max_value)\n if min_value.is_integer() and max_value.is_integer() and not has_dot:\n min_value, max_value = int(min_value), int(max_value)\n\n results.append((name, (min_value, max_value)))\n return results\n\n\ndef parse_error_thresholds(thresholds):\n def _parse_entry(entry):\n items = entry.split(\":\")\n name = items[0] if len(items) == 2 else \"\"\n value = float(items[-1])\n return name, value\n\n return [_parse_entry(t) for t in thresholds]\n\n\nclass OptimizerConfig(ModelNavigatorBaseConfig):\n def _fill_config(self):\n # common config fields\n self._add_config(\n ConfigField(\n \"model_name\",\n flags=[\"--model-name\"],\n field_type=ConfigPrimitive(str, required=True),\n description=\"Name of model.\",\n )\n )\n\n self._add_config(\n ConfigField(\n \"model_path\",\n flags=[\"--model-path\"],\n default_value=\"\",\n field_type=ConfigPrimitive(str, required=True),\n description=\"Path to file with model.\",\n )\n )\n self._add_config(\n ConfigField(\n \"config_file\",\n field_type=ConfigPrimitive(str),\n flags=[\"-f\", \"--config-file\"],\n description=\"Path to Model Navigator Config File.\",\n )\n )\n self._add_config(\n ConfigField(\n \"workspace_path\",\n flags=[\"--workspace-path\"],\n default_value=\"workspace\",\n field_type=ConfigPrimitive(str),\n description=\"Path to output directory.\",\n )\n )\n self._add_config(\n ConfigField(\n \"verbose\",\n field_type=ConfigPrimitive(bool),\n parser_args={\"action\": \"store_true\"},\n default_value=False,\n flags=[\"--verbose\"],\n description=\"Enable verbose mode.\",\n )\n )\n\n # optimizer specific fields\n self._add_config(\n ConfigField(\n \"target_format\",\n field_type=ConfigPrimitive(str, output_mapper=parse_format),\n flags=[\"--target-format\"],\n description=\"Target format to generate. If not provided, all supported formats will be generated.\",\n )\n )\n self._add_config(\n ConfigField(\n \"max_workspace_size\",\n field_type=ConfigPrimitive(int),\n flags=[\"--max-workspace-size\"],\n description=\"The amount of workspace the ICudaEngine uses.\",\n )\n )\n self._add_config(\n ConfigField(\n \"target_precisions\",\n field_type=ConfigListString(output_mapper=parse_precisions),\n flags=[\"--target-precisions\"],\n default_value=[\"fp16\", \"tf32\"],\n description=\"Configure TensorRT builder for precision layer selection.\",\n parser_args={\"nargs\": \"+\"},\n )\n )\n self._add_config(\n ConfigField(\n \"onnx_opsets\",\n field_type=ConfigListNumeric(int),\n flags=[\"--onnx-opsets\"],\n default_value=[12, 13],\n description=\"Generate ONNX graph that uses only ops available in given opset.\",\n parser_args={\"nargs\": \"+\"},\n )\n )\n\n self._add_config(\n ConfigField(\n \"min_shapes\",\n field_type=ConfigListString(output_mapper=parse_tensor_spec),\n flags=[\"--min-shapes\"],\n description=\"The minimum shapes the TensorRT optimization profile(s) will support. \"\n \"Format: --min-shapes :D0,D1,..,DN .. :D0,D1,..,DN\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"opt_shapes\",\n field_type=ConfigListString(output_mapper=parse_tensor_spec),\n flags=[\"--opt-shapes\"],\n description=\"The optimal shapes the TensorRT optimization profile(s) will support.\"\n \"Format: --opt-shapes :D0,D1,..,DN .. :D0,D1,..,DN\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"max_shapes\",\n field_type=ConfigListString(output_mapper=parse_tensor_spec),\n flags=[\"--max-shapes\"],\n description=\"The maximum shapes the TensorRT optimization profile(s) will support. \"\n \"Also defines shapes of input data used during performance analysis. \"\n \"Format: --max-shapes :D0,D1,..,DN .. :D0,D1,..,DN\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"value_ranges\",\n field_type=ConfigListString(output_mapper=parse_value_range),\n flags=[\"--value-ranges\"],\n description=\"Range of values used during performance analysis defined per input. \"\n \"Format: --value-ranges input_name0:min_value,max_value .. input_nameN:min_value,max_value\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"inputs\",\n field_type=ConfigListString(output_mapper=parse_tensor_spec),\n flags=[\"--inputs\"],\n description=\"\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"outputs\",\n field_type=ConfigListString(output_mapper=parse_tensor_spec),\n flags=[\"--outputs\"],\n description=\"\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"rtol\",\n field_type=ConfigListString(output_mapper=parse_error_thresholds),\n flags=[\"--rtol\"],\n description=\"Relative tolerance parameter for output comparison. \"\n \"To specify per-output tolerances, use the format: --rtol [:]. \"\n \"Example: --rtol 1e-5 out0:1e-4 out1:1e-3\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n self._add_config(\n ConfigField(\n \"atol\",\n field_type=ConfigListString(output_mapper=parse_error_thresholds),\n flags=[\"--atol\"],\n description=\"Absolute tolerance parameter for output comparison. \"\n \"To specify per-output tolerances, use the format: --atol [:]. \"\n \"Example: --atol 1e-5 out0:1e-4 out1:1e-3\",\n parser_args={\"nargs\": \"*\"},\n )\n )\n","sub_path":"model_navigator/optimizer/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":8972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"551993753","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/ryosukekita/Desktop/DesktopFiles/PROJECTS/DSVISUALIZER/dataspectra/aefiles/scripts/upload_datasets.py\n# Compiled at: 2018-02-15 14:09:14\nimport webapp2\nfrom google.appengine.ext import ndb\nimport load_funcs as LF, os\n\nclass LocalUploadDatastore(webapp2.RequestHandler):\n \"\"\"\n Dynamically creates each model separately\n \"\"\"\n\n def get(self):\n datasets = LF.json_load_byteified(open('static/datasets.json'))\n numberOfDatasets = len(datasets)\n datasetModelDict = dict()\n for datasetParam in datasets.values():\n datasetModel = type(datasetParam['datasetkey'], (\n ndb.Model,), dict(searchTerm=ndb.StringProperty(), data=ndb.StringProperty(repeated=True, indexed=False)))\n datasetModelDict[datasetParam['datasetkey']] = datasetModel\n\n for datasetParam in datasets.values():\n datasetModel = datasetModelDict[datasetParam['datasetkey']]\n datasetfile = os.path.join('static', datasetParam['samplefile'])\n searchcol = int(datasetParam['searchcol'])\n with open(datasetfile) as (F):\n for i in range(int(datasetParam['searchrowstart'])):\n F.readline()\n\n for i in F:\n i = i.rstrip().split(',')\n newEntity = datasetModel(searchTerm=i[(searchcol - 1)], data=i)\n k = newEntity.put()\n\n searchLookupDict = LF.json_load_byteified(open('static/search_lookup.json'))\n searchTermModel = type('searchterm', (\n ndb.Model,), dict(searchTerm=ndb.StringProperty(), data=ndb.StringProperty(repeated=True, indexed=False)))\n searchlookupfile = os.path.join('static', searchLookupDict['samplefile'])\n with open(searchlookupfile) as (F):\n for i in F:\n i = i.rstrip().split(',')\n newEntity = searchTermModel(searchTerm=i[0], data=i)\n k = newEntity.put()","sub_path":"pycfiles/dataspectra-0.3.5.tar/upload_datasets.py","file_name":"upload_datasets.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"577106309","text":"import datamapping as dm\nimport point\n\ndef initParam(filename):\n #the data file\n raw_data = dm.Importer()\n raw_data.import_data(filename)\n #vehicle capacity\n capacity = int(raw_data.info[\"CAPACITY\"])\n # coordination\n coordination = raw_data.node_coordinates_list \n # node demand\n demand_list = raw_data.demand_array\n # distance and fitness\n distance_matrix = raw_data.distance_matrix\n # depot\n depot_lists = raw_data.depot\n depot_lists = [i-1 for i in depot_lists]\n #depot list\n Depots = []\n for depot in depot_lists:\n # [index, coordination, duration, capacity, vehicle number]\n d = point.Depot(*tuple([depot, coordination[depot][0], coordination[depot][1], None, capacity, None]))\n Depots.append(d)\n Customers = [] \n for customer in range(raw_data.depot_num, raw_data.depot_num+raw_data.customer_num):\n# print customer, coordination[customer][0], coordination[customer][1], None, demand_list[customer] \n c = point.Customer(*tuple([customer, coordination[customer][0], coordination[customer][1], None, demand_list[customer]]))\n Customers.append(c)\n\n return coordination, distance_matrix, Customers, Depots, depot_lists \n\nif __name__ == '__main__':\n coordination, distance_matrix, Customers, Depots, depot_lists = initParam(\"A-n32-k5.vrp\")\n for depot in Depots:\n print ('The depot_id %s and max vehicle %s'%(depot.id, depot.max_vehicle_num))\n for customer in Customers:\n print ('The customer_id %s and demand %s'%(customer.id, customer.demand))\n ","sub_path":"VRP_algorithm/recycle/VRP_GA_20181119_v2/Init_parameter.py","file_name":"Init_parameter.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"18647923","text":"import os\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nROOT_URLCONF = 'apps.urls'\nWSGI_APPLICATION = 'apps.wsgi.application'\n\nINSTALLED_APPS = [\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'rest_framework',\n 'core.applications',\n]\n\nMIDDLEWARE = [\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n]\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework.renderers.JSONRenderer',\n )\n}\n\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\nSTATIC_URL = '/static/'\nMEDIA_URL = '/media/'\n","sub_path":"apps/env/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"292251345","text":"from itertools import permutations\ndef isPrime(n):\n n = int(n)\n if n == 0 or n == 1:\n return False\n for i in range(2, n):\n if n % i == 0:\n return False\n return True\n\ndef solution(numbers):\n answer = 0\n nums = list(numbers)\n num_list = []\n for i in range(1, len(numbers)+1):\n for j in list(permutations(nums, i)):\n new_num = ''\n for k in j:\n new_num += k\n if new_num not in num_list:\n if new_num.startswith('0'):\n continue\n else:\n if isPrime(new_num):\n answer += 1\n num_list.append(new_num)\n return answer","sub_path":"Week12/findPrime/hyewon.py","file_name":"hyewon.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"612498582","text":"'''\r\nCreated on Sep 22, 2018\r\n\r\n@author: l0t0y\r\n'''\r\n\r\nfrom threading import Thread\r\nfrom random import uniform\r\nfrom time import sleep\r\nfrom labs.common.SensorData import SensorData\r\nfrom labs.module02.SmtpClientConnector import SmtpClientConnector\r\n\r\n\r\nclass TempSensorEmulator(Thread):\r\n\r\n curTemp = 0\r\n highVal = 0\r\n lowVal = 0\r\n enableTempEmulator = False\r\n updateTime = 0\r\n rateInSec = 0\r\n sensorData = 0\r\n connector = 0\r\n alertDiff = 0\r\n\r\n def __init__(self, rateInSec):\r\n Thread.__init__(self)\r\n self.highVal = 30\r\n self.lowVal = 0\r\n self.updateTime = 2\r\n self.rateInSec = rateInSec\r\n self.sensorData = SensorData()\r\n self.connector = SmtpClientConnector()\r\n self.alertDiff = 10\r\n\r\n def getCurrValue(self):\r\n\r\n return self.currValue\r\n\r\n def setEnableTempEmulator(self, flag):\r\n self.enableTempEmulator = flag\r\n\r\n def run(self):\r\n while True:\r\n if self.enableTempEmulator:\r\n self.sensorData.setName('Temperature')\r\n self.curTemp = uniform(float(self.lowVal), float(self.highVal))\r\n self.sensorData.addValue(self.curTemp)\r\n print('\\n--------------------')\r\n print('New sensor readings: \\n')\r\n print(' ' + str(self.sensorData))\r\n\r\n if (abs(self.curTemp - self.sensorData.getAvgValue()) >= self.alertDiff):\r\n print('\\n Current temp exceeds average by > ' + str(self.alertDiff) + '. Triggering alert...')\r\n self.connector.publishMessage('Exceptional sensor data [test]', self.sensorData)\r\n sleep(self.rateInSec)\r\n\r\n sleep(self.updateTime)\r\n","sub_path":"iot-device/apps/labs/module02/TempSensorEmulator.py","file_name":"TempSensorEmulator.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"24097230","text":"import streamlit as st\nfrom apps import firestore_calls as fc\n\ndef show(sel_model, type_m_p):\n \n \"\"\"Shows the sidebar components for the template and returns user inputs as dict.\"\"\"\n \n # `show()` is the only method required in this module. You can add any other code \n # you like above or below. \n \n inputs = {} # dict to store all user inputs until return\n \n pipeline = True\n\n #with st.sidebar:\n \n # Render all template-specific sidebar components here. \n \n # Store all user inputs in the `inputs` dict. This will be passed to the code\n # template later.\n \n #sel_model = ...\n #type_m_p = ...\n #pipeline = ...\n \n with st.beta_expander(label='Fairness Frameworks and Practices'):\n \n #Query the relevant practices based on the fairness requirements indicated by the model owner\n fc.get_recommended_practices(sel_model, type_m_p, pipeline = True);\n \n with st.beta_expander(label='Fairness Mitigation Methods'): \n\n #Query the relevant mititgation methods based on the fairness requirements indicated by the model owner\n fc.get_recommended_practices(sel_model, type_m_p, pipeline = True);\n\n \n\n\n\n\n\n\n\n\n","sub_path":"technical_data/Per Pipeline Stage/sidebar.py","file_name":"sidebar.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"548847225","text":"import math\nimport numpy as np\nimport unittest\n\nimport preprocess\n\nfrom numpy.polynomial.chebyshev import Chebyshev\ncb = Chebyshev.basis\n\n\nclass TestSolver(unittest.TestCase):\n def test_shift_powers(self):\n n = 10000\n k = 10\n xs = np.linspace(0, 100, n)\n\n amin = np.min(xs)\n amax = np.max(xs)\n xr = (amax - amin)/2\n xc = (amax + amin)/2\n\n power_sums = np.array([np.sum(xs**i) for i in range(k)])\n s_sums = preprocess.shift_power_sum(\n power_sums,\n xr,\n xc\n )\n s_sums /= s_sums[0]\n self.assertAlmostEqual(1, s_sums[0], 10)\n self.assertAlmostEqual(0, s_sums[1], 3)\n self.assertAlmostEqual(1.0/3, s_sums[2], 3)\n\n c_moments = preprocess.power_sum_to_cheby(\n power_sums,\n amin=amin,\n amax=amax,\n )\n self.assertAlmostEqual(-1.0/3, c_moments[2], 3)\n","sub_path":"pysolver/tests/test_preprocess.py","file_name":"test_preprocess.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"13126088","text":"################################################################\n# Author : yiorgosynkl (find me in Github: https://github.com/yiorgosynkl)\n# Date created : 20210115\n# Problem link : https://leetcode.com/problems/get-maximum-in-generated-array/\n################################################################\n\nclass Solution:\n def getMaximumGenerated(self, n: int) -> int:\n if n <= 1: return n\n arr = [0, 1] + [0]*(n-1)\n ans = 1\n for i in range(2, n+1):\n arr[i] = arr[i//2] + (i%2)*arr[i//2+1]\n ans = max(ans, arr[i])\n return ans\n \n# # less memory\n# def getMaximumGenerated(self, n: int) -> int:\n# if n <= 1: return n\n# q, ans = deque([1]), 1 \n# for i in range(2, n, 2):\n# q.append(q[0])\n# q.append(q[0] + q[1])\n# ans = max(ans, q[-1])\n# q.popleft()\n# return ans\n ","sub_path":"30_day_challenge_2021_January/1646_get_maximum_in_generated_array.py","file_name":"1646_get_maximum_in_generated_array.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"39481828","text":"from django.shortcuts import render\nfrom django.utils.translation import ugettext_lazy as _\nfrom jwkest.jwt import JWT\n\n_author_ = \"Alan Viars\"\n\n\ndef authenticated_home(request):\n if request.user.is_authenticated:\n\n try:\n vmi = request.user.social_auth.filter(\n provider='verifymyidentity-openidconnect')[0]\n extra_data = vmi.extra_data\n if 'id_token' in vmi.extra_data.keys():\n id_token = extra_data.get('id_token')\n parsed_id_token = JWT().unpack(id_token)\n parsed_id_token = parsed_id_token.payload()\n\n except Exception:\n id_token = \"No ID token.\"\n parsed_id_token = \"No ID token.\"\n\n name = _('Authenticated Home')\n try:\n profile = request.user.userprofile\n except Exception:\n profile = None\n\n # this is a GET\n context = {'name': name, 'profile': profile,\n 'id_token': id_token,\n 'id_token_payload': parsed_id_token}\n\n template = 'authenticated-home.html'\n else:\n name = ('home')\n context = {'name': name}\n template = 'index.html'\n return render(request, template, context)\n","sub_path":"apps/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"293594765","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nfrom copy import deepcopy\nfrom typing import Any, Awaitable, TYPE_CHECKING\n\nfrom azure.core.rest import AsyncHttpResponse, HttpRequest\nfrom azure.mgmt.core import AsyncARMPipelineClient\n\nfrom .. import models as _models\nfrom ..._serialization import Deserializer, Serializer\nfrom ._configuration import WebSiteManagementClientConfiguration\nfrom .operations import (\n AppServiceCertificateOrdersOperations,\n AppServiceEnvironmentsOperations,\n AppServicePlansOperations,\n CertificateOrdersDiagnosticsOperations,\n CertificateRegistrationProviderOperations,\n CertificatesOperations,\n ContainerAppsOperations,\n ContainerAppsRevisionsOperations,\n DeletedWebAppsOperations,\n DiagnosticsOperations,\n DomainRegistrationProviderOperations,\n DomainsOperations,\n GlobalOperations,\n KubeEnvironmentsOperations,\n ProviderOperations,\n RecommendationsOperations,\n ResourceHealthMetadataOperations,\n StaticSitesOperations,\n TopLevelDomainsOperations,\n WebAppsOperations,\n WebSiteManagementClientOperationsMixin,\n WorkflowRunActionRepetitionsOperations,\n WorkflowRunActionRepetitionsRequestHistoriesOperations,\n WorkflowRunActionScopeRepetitionsOperations,\n WorkflowRunActionsOperations,\n WorkflowRunsOperations,\n WorkflowTriggerHistoriesOperations,\n WorkflowTriggersOperations,\n WorkflowVersionsOperations,\n WorkflowsOperations,\n)\n\nif TYPE_CHECKING:\n # pylint: disable=unused-import,ungrouped-imports\n from azure.core.credentials_async import AsyncTokenCredential\n\n\nclass WebSiteManagementClient(\n WebSiteManagementClientOperationsMixin\n): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes\n \"\"\"WebSite Management Client.\n\n :ivar app_service_certificate_orders: AppServiceCertificateOrdersOperations operations\n :vartype app_service_certificate_orders:\n azure.mgmt.web.v2022_09_01.aio.operations.AppServiceCertificateOrdersOperations\n :ivar certificate_orders_diagnostics: CertificateOrdersDiagnosticsOperations operations\n :vartype certificate_orders_diagnostics:\n azure.mgmt.web.v2022_09_01.aio.operations.CertificateOrdersDiagnosticsOperations\n :ivar certificate_registration_provider: CertificateRegistrationProviderOperations operations\n :vartype certificate_registration_provider:\n azure.mgmt.web.v2022_09_01.aio.operations.CertificateRegistrationProviderOperations\n :ivar domains: DomainsOperations operations\n :vartype domains: azure.mgmt.web.v2022_09_01.aio.operations.DomainsOperations\n :ivar top_level_domains: TopLevelDomainsOperations operations\n :vartype top_level_domains: azure.mgmt.web.v2022_09_01.aio.operations.TopLevelDomainsOperations\n :ivar domain_registration_provider: DomainRegistrationProviderOperations operations\n :vartype domain_registration_provider:\n azure.mgmt.web.v2022_09_01.aio.operations.DomainRegistrationProviderOperations\n :ivar app_service_environments: AppServiceEnvironmentsOperations operations\n :vartype app_service_environments:\n azure.mgmt.web.v2022_09_01.aio.operations.AppServiceEnvironmentsOperations\n :ivar app_service_plans: AppServicePlansOperations operations\n :vartype app_service_plans: azure.mgmt.web.v2022_09_01.aio.operations.AppServicePlansOperations\n :ivar certificates: CertificatesOperations operations\n :vartype certificates: azure.mgmt.web.v2022_09_01.aio.operations.CertificatesOperations\n :ivar container_apps: ContainerAppsOperations operations\n :vartype container_apps: azure.mgmt.web.v2022_09_01.aio.operations.ContainerAppsOperations\n :ivar container_apps_revisions: ContainerAppsRevisionsOperations operations\n :vartype container_apps_revisions:\n azure.mgmt.web.v2022_09_01.aio.operations.ContainerAppsRevisionsOperations\n :ivar deleted_web_apps: DeletedWebAppsOperations operations\n :vartype deleted_web_apps: azure.mgmt.web.v2022_09_01.aio.operations.DeletedWebAppsOperations\n :ivar diagnostics: DiagnosticsOperations operations\n :vartype diagnostics: azure.mgmt.web.v2022_09_01.aio.operations.DiagnosticsOperations\n :ivar global_operations: GlobalOperations operations\n :vartype global_operations: azure.mgmt.web.v2022_09_01.aio.operations.GlobalOperations\n :ivar kube_environments: KubeEnvironmentsOperations operations\n :vartype kube_environments:\n azure.mgmt.web.v2022_09_01.aio.operations.KubeEnvironmentsOperations\n :ivar provider: ProviderOperations operations\n :vartype provider: azure.mgmt.web.v2022_09_01.aio.operations.ProviderOperations\n :ivar recommendations: RecommendationsOperations operations\n :vartype recommendations: azure.mgmt.web.v2022_09_01.aio.operations.RecommendationsOperations\n :ivar resource_health_metadata: ResourceHealthMetadataOperations operations\n :vartype resource_health_metadata:\n azure.mgmt.web.v2022_09_01.aio.operations.ResourceHealthMetadataOperations\n :ivar static_sites: StaticSitesOperations operations\n :vartype static_sites: azure.mgmt.web.v2022_09_01.aio.operations.StaticSitesOperations\n :ivar web_apps: WebAppsOperations operations\n :vartype web_apps: azure.mgmt.web.v2022_09_01.aio.operations.WebAppsOperations\n :ivar workflows: WorkflowsOperations operations\n :vartype workflows: azure.mgmt.web.v2022_09_01.aio.operations.WorkflowsOperations\n :ivar workflow_runs: WorkflowRunsOperations operations\n :vartype workflow_runs: azure.mgmt.web.v2022_09_01.aio.operations.WorkflowRunsOperations\n :ivar workflow_run_actions: WorkflowRunActionsOperations operations\n :vartype workflow_run_actions:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowRunActionsOperations\n :ivar workflow_run_action_repetitions: WorkflowRunActionRepetitionsOperations operations\n :vartype workflow_run_action_repetitions:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowRunActionRepetitionsOperations\n :ivar workflow_run_action_repetitions_request_histories:\n WorkflowRunActionRepetitionsRequestHistoriesOperations operations\n :vartype workflow_run_action_repetitions_request_histories:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowRunActionRepetitionsRequestHistoriesOperations\n :ivar workflow_run_action_scope_repetitions: WorkflowRunActionScopeRepetitionsOperations\n operations\n :vartype workflow_run_action_scope_repetitions:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowRunActionScopeRepetitionsOperations\n :ivar workflow_triggers: WorkflowTriggersOperations operations\n :vartype workflow_triggers:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowTriggersOperations\n :ivar workflow_trigger_histories: WorkflowTriggerHistoriesOperations operations\n :vartype workflow_trigger_histories:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowTriggerHistoriesOperations\n :ivar workflow_versions: WorkflowVersionsOperations operations\n :vartype workflow_versions:\n azure.mgmt.web.v2022_09_01.aio.operations.WorkflowVersionsOperations\n :param credential: Credential needed for the client to connect to Azure. Required.\n :type credential: ~azure.core.credentials_async.AsyncTokenCredential\n :param subscription_id: Your Azure subscription ID. This is a GUID-formatted string (e.g.\n 00000000-0000-0000-0000-000000000000). Required.\n :type subscription_id: str\n :param base_url: Service URL. Default value is \"https://management.azure.com\".\n :type base_url: str\n :keyword api_version: Api Version. Default value is \"2022-09-01\". Note that overriding this\n default value may result in unsupported behavior.\n :paramtype api_version: str\n :keyword int polling_interval: Default waiting time between two polls for LRO operations if no\n Retry-After header is present.\n \"\"\"\n\n def __init__(\n self,\n credential: \"AsyncTokenCredential\",\n subscription_id: str,\n base_url: str = \"https://management.azure.com\",\n **kwargs: Any\n ) -> None:\n self._config = WebSiteManagementClientConfiguration(\n credential=credential, subscription_id=subscription_id, **kwargs\n )\n self._client: AsyncARMPipelineClient = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)\n\n client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)}\n self._serialize = Serializer(client_models)\n self._deserialize = Deserializer(client_models)\n self._serialize.client_side_validation = False\n self.app_service_certificate_orders = AppServiceCertificateOrdersOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.certificate_orders_diagnostics = CertificateOrdersDiagnosticsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.certificate_registration_provider = CertificateRegistrationProviderOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.domains = DomainsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.top_level_domains = TopLevelDomainsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.domain_registration_provider = DomainRegistrationProviderOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.app_service_environments = AppServiceEnvironmentsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.app_service_plans = AppServicePlansOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.certificates = CertificatesOperations(self._client, self._config, self._serialize, self._deserialize)\n self.container_apps = ContainerAppsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.container_apps_revisions = ContainerAppsRevisionsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.deleted_web_apps = DeletedWebAppsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.diagnostics = DiagnosticsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.global_operations = GlobalOperations(self._client, self._config, self._serialize, self._deserialize)\n self.kube_environments = KubeEnvironmentsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.provider = ProviderOperations(self._client, self._config, self._serialize, self._deserialize)\n self.recommendations = RecommendationsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.resource_health_metadata = ResourceHealthMetadataOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.static_sites = StaticSitesOperations(self._client, self._config, self._serialize, self._deserialize)\n self.web_apps = WebAppsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.workflows = WorkflowsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.workflow_runs = WorkflowRunsOperations(self._client, self._config, self._serialize, self._deserialize)\n self.workflow_run_actions = WorkflowRunActionsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.workflow_run_action_repetitions = WorkflowRunActionRepetitionsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.workflow_run_action_repetitions_request_histories = WorkflowRunActionRepetitionsRequestHistoriesOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.workflow_run_action_scope_repetitions = WorkflowRunActionScopeRepetitionsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.workflow_triggers = WorkflowTriggersOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.workflow_trigger_histories = WorkflowTriggerHistoriesOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n self.workflow_versions = WorkflowVersionsOperations(\n self._client, self._config, self._serialize, self._deserialize\n )\n\n def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]:\n \"\"\"Runs the network request through the client's chained policies.\n\n >>> from azure.core.rest import HttpRequest\n >>> request = HttpRequest(\"GET\", \"https://www.example.org/\")\n \n >>> response = await client._send_request(request)\n \n\n For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request\n\n :param request: The network request you want to make. Required.\n :type request: ~azure.core.rest.HttpRequest\n :keyword bool stream: Whether the response payload will be streamed. Defaults to False.\n :return: The response of your network call. Does not do error handling on your response.\n :rtype: ~azure.core.rest.AsyncHttpResponse\n \"\"\"\n\n request_copy = deepcopy(request)\n request_copy.url = self._client.format_url(request_copy.url)\n return self._client.send_request(request_copy, **kwargs)\n\n async def close(self) -> None:\n await self._client.close()\n\n async def __aenter__(self) -> \"WebSiteManagementClient\":\n await self._client.__aenter__()\n return self\n\n async def __aexit__(self, *exc_details: Any) -> None:\n await self._client.__aexit__(*exc_details)\n","sub_path":"sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2022_09_01/aio/_web_site_management_client.py","file_name":"_web_site_management_client.py","file_ext":"py","file_size_in_byte":14508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"237407656","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pywt\nimport pyarrow.parquet as pq\nimport pandas as pd\n\nimport scipy\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV, cross_val_score\nfrom sklearn.metrics import matthews_corrcoef, make_scorer, roc_auc_score\nfrom sklearn.ensemble import AdaBoostRegressor, ExtraTreesRegressor, RandomForestRegressor\nfrom sklearn.neural_network import MLPRegressor, MLPClassifier\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.utils import shuffle\nfrom collections import Counter\n\nfrom tqdm import tqdm\nfrom numba import jit\n\ndef calculate_entropy(list_values):\n counter_values = Counter(list_values).most_common()\n probabilities = [elem[1]/len(list_values) for elem in counter_values]\n entropy=scipy.stats.entropy(probabilities)\n return entropy\n \n@jit('float32(float32[:])')\ndef calculate_statistics(list_values):\n n5 = np.nanpercentile(list_values, 5)\n n25 = np.nanpercentile(list_values, 25)\n n75 = np.nanpercentile(list_values, 75)\n n95 = np.nanpercentile(list_values, 95)\n median = np.nanpercentile(list_values, 50)\n mean = np.nanmean(list_values)\n std = np.nanstd(list_values)\n var = np.nanvar(list_values)\n rms = np.nanmean(np.sqrt(list_values**2))\n return [n5, n25, n75, n95, median, mean, std, var, rms]\n \ndef get_features(list_values):\n entropy = calculate_entropy(list_values)\n statistics = calculate_statistics(list_values)\n return [entropy] + statistics\n\ndef get_uci_har_features(dataset, labels, waveletname):\n uci_har_features = []\n for signal_no in tqdm(range(0, len(dataset))):\n features = []\n signal = dataset[signal_no, :]\n list_coeff = pywt.wavedec(signal, waveletname)\n for coeff in list_coeff:\n features += get_features(coeff)\n uci_har_features.append(features)\n X = np.array(uci_har_features)\n Y = np.array(labels)\n return X, Y\n\n\n#X_index, Y_data = np.array([], dtype=np.int), np.array([])\n#meta_set = pd.read_csv('data/metadata_train.csv')\n#signal_id = meta_set.loc[(meta_set.target == 1), 'signal_id']\n#X_index = np.append(X_index, signal_id.values)\n#Y_data = np.ones(len(X_index))\n#Y_data = np.append(Y_data, np.zeros(len(X_index)) )\n#\n#signal_id = meta_set.loc[(meta_set.target == 0), 'signal_id']\n#X_index = np.append(X_index, signal_id.values[:len(X_index)])\n#\n#train_set = pq.read_table('data/train.parquet', columns=[str(i) for i in X_index]).to_pandas()\n#signal = np.array(train_set).T.reshape(-1, 800000)\n\nX_data, Y_data = np.loadtxt('X_data.txt'), np.loadtxt('Y_data.txt') #get_uci_har_features(signal, Y_data, 'db4')\nX_data, Y_data = shuffle(X_data, Y_data)\n\n#np.savetxt('X_data.txt', X_data)\n#np.savetxt('Y_data.txt', Y_data)\n\n#X_train, X_test, y_train, y_test = train_test_split(X_data, Y_data, test_size=0.3, shuffle=True)\n#\n#min_max_scaler = MinMaxScaler()\n##y_test, y_train = np.array(y_test, dtype='int'), np.array(y_train, dtype='int')\n#\n#ma_depth:60, b_estimators:1000\n#clf = RandomForestRegressor(n_estimators=1000, max_depth=60)\n\nmc = make_scorer(matthews_corrcoef)\n#cv5 = cross_val_score(clf, X_data, Y_data, scoring=mc, cv=5)\n#cv6 = cross_val_score(clf, X_data, Y_data, scoring=mc, cv=6)\n#cv7 = cross_val_score(clf, X_data, Y_data, scoring=mc, cv=7)\n#\n#cv_mean = [np.mean(cv5), np.mean(cv6), np.mean(cv7)]\n#cv_std = [np.std(cv5), np.std(cv6), np.std(cv7)]\n#\n#for i in range(len(cv_mean)):\n# print(\"cv\",i+5,\": \", cv_mean[i], \" +/- \", cv_std[i])\n#print(\"cv: \", np.mean(cv_mean), \" +/- \", np.mean(cv_std))\n\nra = make_scorer(roc_auc_score)\n#3000, max_depth: 50\n#clf = ExtraTreesRegressor()\n\nclf = MLPClassifier()\nparam_grid = { \n 'solver': ['lbfgs'],\n 'max_iter': [2000, 3000], \n 'alpha': 10.0 ** -np.arange(1, 4), \n 'hidden_layer_sizes':np.arange(2000, 3000, 500), \n 'activation': ['tanh', 'relu']\n}\n\nCV_rfc = GridSearchCV(estimator=clf, param_grid=param_grid, cv=5, scoring=mc)\nprint(\"start fitiing...\")\nCV_rfc.fit(X_data, Y_data)\nbp = CV_rfc.best_params_\nbs = CV_rfc.best_score_\nprint(bp)\nprint(bs)","sub_path":"clf_grb.py","file_name":"clf_grb.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"233796407","text":"# Imports arcade library\nimport arcade\n# From constants import all\nfrom game.constants import *\n# Import flying_object imports Flying_Object\nfrom game.flying_object import Flying_Object\n\n\nclass Shooter(Flying_Object):\n \"\"\"Creates and control the shooter\"\"\"\n\n def __init__(self):\n super().__init__()\n\n self.radius = SHOOTER_RADIUS\n self.center.x = SCREEN_WIDTH / 2\n self.center.y = 0 + SHOOTER_SIZE\n self.velocity.dx = 0\n self.velocity.dy = 0\n self.fire_rate = BULLET_FIRE_RATE\n self.lives = START_LIVES\n self.damage = 1\n\n def move_right(self):\n \"\"\"Move to the right\"\"\"\n if self.center.x < SCREEN_WIDTH - SHOOTER_SIZE / 2:\n self.velocity.dx = 1 * SHOOTER_SPEED\n else:\n self.center.x = SCREEN_WIDTH - SHOOTER_SIZE / 2\n\n def move_left(self):\n \"\"\"Move to the left\"\"\"\n if self.center.x > 0 + SHOOTER_SIZE / 2:\n self.velocity.dx = -1 * SHOOTER_SPEED\n else:\n self.center.x = 0 + SHOOTER_SIZE / 2\n\n def collide(self):\n \"\"\"Handle collisions\"\"\"\n self.lives -= 1\n if self.lives <= 0:\n \"\"\"Determine if shooter is alive\"\"\"\n self.alive = False\n\n def draw(self):\n \"\"\"Display the alive and dead shooter\"\"\"\n\n img = \"assets/alive_shooter.png\"\n texture = arcade.load_texture(img)\n img_hit = \"assets/dead_shooter.png\"\n texture2 = arcade.load_texture(img_hit)\n\n width = texture.width / 8\n height = texture.height / 8\n alpha = 255\n x = self.center.x\n y = self.center.y\n angle = self.angle + 90\n\n arcade.draw_text(f\"Power: {self.damage}\", SCREEN_WIDTH*.8,\n SCREEN_HEIGHT*.95, arcade.color.PURPLE_HEART, 20)\n\n arcade.draw_text(f\"Lives: {self.lives}\", 15,\n SCREEN_HEIGHT*.9, arcade.color.RED, 20)\n if self.alive:\n arcade.draw_texture_rectangle(\n x, y, width, height, texture, angle, alpha)\n\n else:\n arcade.draw_texture_rectangle(\n x + 10, y+5, 50, 50, texture2, angle, alpha)\n","sub_path":"street_shooter/game/shooter.py","file_name":"shooter.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"392132654","text":"# -*- coding: utf-8 -*-\nimport math\nimport sys\n\n# yahoo!形態素解析\nimport morphological\n\n\ndef getwords(doc):\n words = [s.lower() for s in morphological.split(doc)]\n return tuple(w for w in words)\n\n\nclass NaiveBayes:\n\n def __init__(self):\n self.vocabularies = set() # 単語の集合\n self.wordcount = {} # {category : { words : n, ...}}\n self.catcount = {} # {category : n}\n\n def wordcountup(self, word, cat):\n self.wordcount.setdefault(cat, {})\n self.wordcount[cat].setdefault(word, 0)\n self.wordcount[cat][word] += 1\n self.vocabularies.add(word)\n\n def catcountup(self, cat):\n self.catcount.setdefault(cat, 0)\n self.catcount[cat] += 1\n\n def train(self, doc, cat):\n word = getwords(doc)\n for w in word:\n self.wordcountup(w, cat)\n self.catcountup(cat)\n\n def classifier(self, doc):\n best = None # 最適なカテゴリ\n max = -sys.maxsize\n word = getwords(doc)\n\n # カテゴリ毎に確率の対数を求める\n for cat in list(self.catcount.keys()):\n prob = self.score(word, cat)\n if prob > max:\n max = prob\n best = cat\n\n return best\n\n def score(self, word, cat):\n score = math.log(self.priorprob(cat))\n for w in word:\n score += math.log(self.wordprob(w, cat))\n return score\n\n def priorprob(self, cat):\n return float(self.catcount[cat]) / sum(self.catcount.values())\n\n def incategory(self, word, cat):\n # あるカテゴリの中に単語が登場した回数を返す\n if word in self.wordcount[cat]:\n return float(self.wordcount[cat][word])\n return 0.0\n\n def wordprob(self, word, cat):\n # P(word|cat)が生起する確率を求める\n prob = \\\n (self.incategory(word, cat) + 1.0) / \\\n (sum(self.wordcount[cat].values()) +\n len(self.vocabularies) * 1.0)\n return prob\n","sub_path":"naivebayes.py","file_name":"naivebayes.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"66660646","text":"import pygame\r\nimport time\r\nimport random\r\nimport BoyoRPG\r\n\r\n#pygame.init()\r\n\r\n\r\nclass Player(object):\r\n def __init__(self, x, y, image, health=None):\r\n self.x = x\r\n self.y = y\r\n self.health = health\r\n self.image = image\r\n self.rotate = False\r\n \r\n def displayCharacter(self, xN):\r\n image2 = pygame.transform.flip(self.image, 1, 0)\r\n if xN < 0: \r\n self.rotate = True\r\n elif xN > 0:\r\n self.rotate = False\r\n if self.rotate:\r\n BoyoRPG.gameDisplay.blit(image2, (self.x,self.y))\r\n else:\r\n BoyoRPG.gameDisplay.blit(self.image, (self.x,self.y))\r\n\r\n def move(self, xN, yN):\r\n self.x += xN\r\n self.y += yN\r\n if self.x > BoyoRPG.display_width-9:\r\n self.x = self.x - 5\r\n if self.x < 0:\r\n self.x = 0\r\n if self.y > BoyoRPG.display_height - 10:\r\n self.y = self.y - 5\r\n if self.y < 0:\r\n self.y = 0\r\n\r\n \r\n \r\n#class Mob(object):\r\n# def __init__(self, x, y, image, health=None, scale1=None):\r\n# def displayMob(self, xN):\r\n# def moveMob(self, xN, yN):\r\n\r\n\r\nclass World(object):\r\n def __init__(self, x, y, image, button=None):\r\n self.x = x\r\n self.y = y\r\n self.image = image\r\n self.button = button\r\n \r\n def displayWorld(self):\r\n BoyoRPG.gameDisplay.blit(self.image, (self.x,self.y))\r\n \r\n def makeWorld(self, x1):\r\n self.displayWorld()\r\n #print(x1)\r\n \r\n def button(self, x, y, w, h, px, py, action, *args):\r\n mouse = BoyoRPG.pygame.mouse.get_pos()\r\n click = BoyoRPG.pygame.mouse.get_pressed()\r\n #global enter\r\n \r\n if x + w > px > x and y + h > py > y:\r\n print('almost') \r\n if click[0] == 1 and action != None:\r\n print('yea')\r\n #enter = not enter\r\n action(*args) #runs object as function\r\n else:\r\n print('no')\r\n\r\n","sub_path":"BoyoRPG 001/PlayerTest.py","file_name":"PlayerTest.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"185297803","text":"from pexif import JpegFile\r\nimport sys\r\nimport exifread\r\nimport os\r\nimport glob\r\n\r\ndef get_folder_name(directory):\r\n\treturn os.listdir(directory)\r\n\r\ndef set_gps(filename,lat,lon):\r\n\ttry:\r\n\t ef = JpegFile.fromFile(filename)\r\n\t ef.set_geo(float(lat), float(lon))\r\n\texcept IOError:\r\n\t type, value, traceback = sys.exc_info()\r\n\t print >> sys.stderr, \"Error opening file:\", value\r\n\texcept JpegFile.InvalidFile:\r\n\t type, value, traceback = sys.exc_info()\r\n\t print >> sys.stderr, \"Error opening file:\", value\r\n\r\n\ttry:\r\n\t ef.writeFile(filename)\r\n\texcept IOError:\r\n\t type, value, traceback = sys.exc_info()\r\n\t print >> sys.stderr, \"Error saving file:\", value\r\n\r\ndef get_exif_location(exif_data):\r\n lat = None\r\n lon = None\r\n\r\n gps_latitude = _get_if_exist(exif_data, 'GPS GPSLatitude')\r\n gps_latitude_ref = _get_if_exist(exif_data, 'GPS GPSLatitudeRef')\r\n gps_longitude = _get_if_exist(exif_data, 'GPS GPSLongitude')\r\n gps_longitude_ref = _get_if_exist(exif_data, 'GPS GPSLongitudeRef')\r\n\r\n if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref:\r\n lat = _convert_to_degress(gps_latitude)\r\n if gps_latitude_ref.values[0] != 'N':\r\n lat = 0 - lat\r\n\r\n lon = _convert_to_degress(gps_longitude)\r\n if gps_longitude_ref.values[0] != 'E':\r\n lon = 0 - lon\r\n\r\n return lat, lon\r\n\r\ndef _get_if_exist(data, key):\r\n if key in data:\r\n return data[key]\r\n\r\n return None\r\n\r\ndef _convert_to_degress(value):\r\n d = float(value.values[0].num) / float(value.values[0].den)\r\n m = float(value.values[1].num) / float(value.values[1].den)\r\n s = float(value.values[2].num) / float(value.values[2].den)\r\n\r\n return d + (m / 60.0) + (s / 3600.0)\r\n\r\ndef open_img(filename,dir):\r\n\t#dir_coordinates = 'E:\\\\Photos\\\\coordinates.csv'\r\n\tdir_coordinates = sys.argv[2]\r\n\r\n\tfile_coordinates = open(dir_coordinates)\r\n\tfor i,line in enumerate(file_coordinates):\r\n\t\tid,lonVal,latVal,dis,blk,vil = line.strip().split(',')\r\n\t\t\r\n\t\tif len(id) <= 2:\r\n\t\t\tid = '0'+id\r\n\r\n\t\tif (id == dir):\r\n\t\t\tf = open(filename)\r\n\t\t\t#tags = exifread.process_file(f)\r\n\r\n\t\t\t#lat,lon = get_exif_location(tags)\t\r\n\t\t\t#if lat == None and lon == None:\r\n\t\t\tprint (filename+' new lat = '+str(latVal)+', lon = '+str(lonVal))\r\n\t\t\tset_gps(filename,latVal,lonVal)\r\n\t\t\t#else:\r\n\t\t\t#\tprint (filename+' skipped')\r\n\r\nif __name__ == '__main__':\r\n\t#root = 'E:\\\\Photos\\\\Balasore\\\\'\r\n\troot = sys.argv[1]+'\\\\'\r\n\tlist_dir = []\t\r\n\tlist_dir = get_folder_name(root)\t\r\n\r\n\tfor i,dir in enumerate(list_dir):\r\n\t\tfolder = root+list_dir[i]\r\n\t\t#print (list_dir[i])\r\n\t\tfor file in os.listdir(folder):\r\n\t\t\tif file.endswith(\".jpg\"):\r\n\t\t\t\timg_file = os.path.join(root,folder,file)\r\n\t\t\t\t#print (dir+'\\\\'+file)\r\n\t\t\t\topen_img(img_file,dir)\r\n","sub_path":"extractPexif.py","file_name":"extractPexif.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"232765355","text":"from psychopy import visual, core, event # import some libraries from PsychoPy\nimport random\nimport csv\n\n\n# converts word bank into list of individual words\nwith open('wordBank.txt') as f:\n wordCue = [word for line in f for word in line.split()]\n\n\n# Create all basic objects (window, fixation-cross, timer)\ntimer = core.Clock()\nmywin = visual.Window([800,600], monitor=\"testMonitor\", units=\"deg\")\nfixCross = visual.TextStim(mywin, text = '+', height = 0.1)\n\n# Key list variables that participants will use to indicate whether word is related to self or not\n# right = self, left = other, q = quit game; the key left and right refer to arrows keys\nkeyL = [\"right\", \"left\", \"q\"]\n\n# Other global variables\ntrial = 0\n\n\ndef startExperiment():\n instructions = ['This is a test', \n 'you will now see a series of words',\n 'press `->` for self and `<-` for other',\n 'press any key to continue']\n pos = [[-9,8],[-4,6],[-4,4],[-6,2]]\n for i in range(len(instructions)):\n visual.TextStim(win=mywin, text=instructions[i], pos=pos[i], wrapWidth=500).draw()\n mywin.flip()\n thisResp=None\n while thisResp==None:\n allKeys=event.waitKeys()\n if len(allKeys) > 0:\n thisResp = allKeys[0]\n sessions = [[\"Self\",\"Other\"]*3,[\"Joy\", \"Vomit\"]*3,[\"Self\", \"Joy\", \"Other\", \"Vomit\"]*3]\n sessions.append(sessions[1])\n sessions.append(sessions[2])\n for i,current in enumerate(sessions):\n random.shuffle(current)\n practice(i+1,current)\n visual.TextStim(win=mywin, text='End Of Experiment', pos=[0,0], wrapWidth=500).draw()\n mywin.flip()\n core.wait(5.0)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"624976055","text":"import multiprocessing as mp\n\nimport sys\n\nfrom Csv2ir import Csv2ir\n\n# Test that has to be ran if this script needs to be executed on Windows. Without this check and without \n# mp.freeze_support() following right after this check, Windows will not be able to properly run multicore\n# Python functionality\n# This check evaluates to True when you are running this file as python make_imgs.py\nif __name__ == \"__main__\":\n mp.freeze_support()\n\n # Default folder names\n input_dir_name = 'csv'\n output_dir_name = 'ir'\n\n # Check if CLI parameters are present\n if len(sys.argv) == 3:\n input_dir_name = sys.argv[1]\n output_dir_name = sys.argv[2]\n\n Csv2ir.create_images(input_dir_name, output_dir_name)","sub_path":"make_imgs.py","file_name":"make_imgs.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"150482800","text":"from azure.storage.blob import BlobServiceClient\nimport os\nfrom flask import Flask\nimport zipfile\nimport asyncio\nfrom azure.eventhub.aio import EventHubProducerClient\nfrom azure.eventhub import EventData\n\napp = Flask(__name__)\n\nconnect_str = \"...\"\nblob_service_client = BlobServiceClient.from_connection_string(connect_str)\nos.mkdir(\"./data2\")\nos.mkdir(\"./data2/images\")\nblob_client = blob_service_client.get_blob_client(container='images', blob='images_zipped.zip')\n\nwith open('./data2/images_zipped.zip', \"wb\") as download_file:\n download_file.write(blob_client.download_blob().readall())\n\nwith zipfile.ZipFile('./data2/images_zipped.zip', 'r') as zip_ref:\n zip_ref.extractall('./data2/images/')\n\nloop = asyncio.get_event_loop()\n\n@app.route(\"/doit\")\ndef hello():\n async def run():\n # create a producer client to send messages to the event hub\n # specify connection string to your event hubs namespace and\n # the event hub name\n producer = EventHubProducerClient.from_connection_string(conn_str=\"...\")\n async with producer:\n # create a batch\n event_data_batch = await producer.create_batch()\n\n for i in os.listdir('./data2/images/'):\n blob_client = blob_service_client.get_blob_client(container='images', blob=i)\n upload_file_path = './data2/images/'+i\n\n # Upload the created file to storage\n with open(upload_file_path, \"rb\") as data:\n blob_client.upload_blob(data)\n\n # add events to the batch\n event_data_batch.add(EventData(i))\n\n # send the batch of events to the event hub\n await producer.send_batch(event_data_batch) \n \n\n loop.run_until_complete(run())\n\n return \"unzipped and sent to blob and hub\"","sub_path":"project/webapp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"558779520","text":"\"\"\"\nThis script is used to sample yellow and white lane marker colors from images\ngiven their overall appearance.\n\"\"\"\n\nimport csv\nimport os\nfrom typing import List\n\nimport cv2\nimport numpy as np\nfrom notebooks.scripts.histogram import histogram_vec\n\nfrom pipeline import CameraCalibration, BirdsEyeView, ImageSection, Point\n\nRETURN = 13\nSPACE = 32\nBACKSPACE = 8\n\nNBINS = 16\n\n# PATH = 'harder_challenge_video.mp4'\nPATH = 'challenge_video.mp4'\n\n\nclass Frame:\n def __init__(self, path: str, frame: int):\n self._path = path\n self._frame = frame\n self._white = []\n self._yellow = []\n self._dirty = False\n self._hist = None\n\n def set_histogram(self, histogram: np.ndarray):\n self._hist = histogram\n\n def add_white(self, value: np.ndarray):\n self._white.append(value)\n self._dirty = True\n\n def add_yellow(self, value: np.ndarray):\n self._yellow.append(value)\n self._dirty = True\n\n @property\n def hist(self):\n return self._hist\n\n @property\n def white(self):\n return self._white\n\n @property\n def yellow(self):\n return self._yellow\n\n @property\n def changed(self):\n return self._dirty\n\n\ndef onMouse(event, x, y, flags, params):\n img = params['yuv']\n frame = params['frame']\n h, w = img.shape[:2]\n value = img[y, x]\n\n is_shift = (flags & cv2.EVENT_FLAG_SHIFTKEY) > 0\n sample_white = not is_shift\n\n if event == 0 or event == 4:\n return\n if event == 1:\n if sample_white:\n print('Adding white sample: {}'.format(value))\n frame.add_white(value)\n else:\n print('Adding yellow sample: {}'.format(value))\n frame.add_yellow(value)\n else:\n print('Unhandled mouse event: {}, {}'.format(event, flags))\n\n\ndef main():\n basename = os.path.splitext(os.path.basename(PATH))[0]\n\n cc = CameraCalibration.from_pickle('calibration.pkl')\n\n section = ImageSection(\n top_left=Point(x=580, y=461.75),\n top_right=Point(x=702, y=461.75),\n bottom_right=Point(x=1013, y=660),\n bottom_left=Point(x=290, y=660),\n )\n\n bev = BirdsEyeView(section,\n section_width=3.6576, # one lane width in meters\n section_height=2 * 13.8826) # two dash distances in meters\n\n cap = cv2.VideoCapture(PATH)\n length = cap.get(cv2.CAP_PROP_FRAME_COUNT)\n current_pos, last_pos = 0, None\n\n frame = None\n frames = [] # type: List[Frame]\n\n window = 'Video'\n cv2.namedWindow(window, cv2.WINDOW_KEEPRATIO)\n while True:\n current_pos = min(length, max(0, current_pos))\n cap.set(cv2.CAP_PROP_POS_FRAMES, current_pos)\n ret, img = cap.retrieve()\n if not ret:\n print('End of video.')\n break\n\n img, _ = cc.undistort(img, False)\n img = bev.warp(img)\n\n # Stretch for better sampling\n img = cv2.resize(img, (0, 0), fx=3, fy=1)\n\n current_pos = cap.get(cv2.CAP_PROP_POS_FRAMES)\n if last_pos != current_pos:\n if frame is not None and frame.changed:\n frames.append(frame)\n\n print('Video progress: {}/{} ({:.2f}%)'.format(current_pos, length, 100*current_pos/length))\n # Prepare the frame\n frame = Frame(PATH, current_pos)\n last_pos = current_pos\n\n # Take YUV histogram\n yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)\n histogram = histogram_vec(yuv, NBINS) / np.prod(yuv.shape[:2])\n assert frame is not None\n frame.set_histogram(histogram)\n\n # Hook up the window callback\n params = dict(bgr=img, yuv=yuv, frame=frame)\n cv2.setMouseCallback(window, onMouse, params)\n\n cv2.imshow(window, img)\n key = cv2.waitKey()\n if key == 27:\n break\n if key == SPACE:\n current_pos += 1\n elif key == BACKSPACE:\n current_pos -= 1\n elif key == RETURN:\n current_pos += 60\n\n cap.release()\n\n # Dangling frames are considered as well\n if frame is not None and frame.changed and ((len(frames) > 0 and frames[-1] != frame) or len(frames) == 0):\n frames.append(frame)\n\n if len(frames) == 0:\n return\n\n # Store the frames\n with open('lane-samples-{}.csv'.format(basename), 'w') as f:\n hist_fields = ['h{}'.format(i) for i in range(0, 3 * NBINS)]\n fieldnames = ['id', 'white', 'y', 'u', 'v', 'y_mean', 'u_mean', 'v_mean', 'y_std', 'u_std', 'v_std', *hist_fields]\n writer = csv.writer(f, fieldnames)\n writer.writerow(fieldnames)\n i = 0\n for frame in frames:\n if len(frame.white) > 0:\n white_mean = np.mean(frame.white, axis=0)\n white_std = np.std(frame.white, axis=0)\n for sample in frame.white:\n values = [i, 1, sample[0], sample[1], sample[2], *white_mean, *white_std, *frame.hist]\n writer.writerow(values)\n i += 1\n\n if len(frame.yellow) > 0:\n yellow_mean = np.mean(frame.yellow, axis=0)\n yellow_std = np.std(frame.yellow, axis=0)\n for sample in frame.white:\n values = [i, 0, sample[0], sample[1], sample[2], *yellow_mean, *yellow_std, *frame.hist]\n writer.writerow(values)\n i += 1\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"sample_colors.py","file_name":"sample_colors.py","file_ext":"py","file_size_in_byte":5462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"295617131","text":"from pathlib import Path\nfrom argparse import ArgumentParser\n\nimport h5py\nimport numpy as np\n\nparser = ArgumentParser()\nparser.add_argument('data_path', type=str, help='Path to HDF5 dataset')\nargs = parser.parse_args()\n\npath = Path(args.data_path)\n\nwith h5py.File(path) as f:\n phases = f['Phase'][:]\n exp_counts = f['ExpCounts'][:]\n\nwith h5py.File(path.with_stem(f'{path.stem}-corrected'), 'w') as f:\n phases[:, 1::2] += np.pi\n f.create_dataset('/Phase', data=phases)\n f.create_dataset('/ExpCounts', data=exp_counts)\n","sub_path":"code/scripts/recalib.py","file_name":"recalib.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"105545735","text":"import unittest\n\nfrom trainer.utils.scheduler import constant_lr_schedule, linear_lr_schedule\n\n\nclass TestLRSchedule(unittest.TestCase):\n def test_raise_bad_args(self):\n with self.assertRaises(ValueError):\n constant_lr_schedule(2e-5, init_lr=None, warmup=True, warmup_steps=500)\n linear_lr_schedule(2e-5, init_lr=None, warmup=True, warmup_steps=500)\n with self.assertRaises(ValueError):\n constant_lr_schedule(2e-5, init_lr=0, warmup=True, warmup_steps=None)\n linear_lr_schedule(2e-5, init_lr=0, warmup=True, warmup_steps=None)\n\n def test_constant_schedule_no_warmup(self):\n schedule = constant_lr_schedule(lr=2e-5, init_lr=None, warmup_steps=None, warmup=False)\n lrs = [schedule(i) for i in range(10000)]\n\n self.assertTrue(all(lr == lrs[0] for lr in lrs))\n\n def test_constant_schedule_with_warmup(self):\n schedule = constant_lr_schedule(lr=2e-5, init_lr=0, warmup_steps=500, warmup=True)\n lrs = [schedule(i) for i in range(1000)]\n\n self.assertTrue(all(lrs[i] < 2e-5 and lrs[i] >= 0 for i in range(500)))\n self.assertTrue(all(lrs[i] == 2e-5 for i in range(500, 1000)))\n\n def test_linear_schedule_no_warmup(self):\n num_steps = 1000\n\n schedule = linear_lr_schedule(lr=1e-3, end_lr=1e-5, num_train_steps=num_steps)\n\n lrs = [schedule(i) for i in range(num_steps)]\n\n self.assertTrue(all(lrs[i] <= 1e-3 and lrs[i] >= 1e-5 for i in range(num_steps)))\n\n def test_linear_schedule_with_warmup(self):\n num_steps = 1000\n decay_steps = 500\n\n schedule = linear_lr_schedule(\n lr=1e-3,\n end_lr=1e-5,\n num_train_steps=num_steps,\n warmup_steps=500,\n init_lr=0,\n warmup=True,\n )\n\n lrs = [schedule(i) for i in range(num_steps)]\n\n self.assertTrue(all(lrs[i] >= 0 and lrs[i] <= 1e-3 for i in range(decay_steps)))\n self.assertTrue(\n all(lrs[i] <= 1e-3 and lrs[i] >= 1e-5 for i in range(decay_steps, num_steps))\n )\n","sub_path":"tests/test_lr.py","file_name":"test_lr.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"256691216","text":"from collections import deque\n\nname = {\n\n \"Roman\": [\"Lily\", \"Sophy\"],\n\n \"Lily\": [\"Amy\", \"Bob\"],\n\n \"Bob\": [\"Darel\", \"Dima\", \"Sasha\"]\n\n}\ndef doter(x):\n\n return not len(x) % 2 and x[0] == \"D\"\n\na = deque(name[\"Pavel\"])\n\nb = []\n\nwhile name:\n\n person = a.popleft()\n\n if person not in b:\n\n if doter(person):\n\n print(person)\n\n break\n\n else:\n\n a += name.get(person, [])\n\n b.append(person)\n","sub_path":"dz5/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"332857480","text":"import numpy as np\nimport gridWorld\nimport helper\n\n\nclass MonteCarlo():\n def __init__(self, dimensions=(4, 5)):\n self.gw = gridWorld.Grid()\n self.dimensions = dimensions\n self.gw.init_sample_grid_world(dimensions)\n self.q = np.zeros(shape=(dimensions[0], dimensions[1], 4))\n self.returns = np.zeros(shape=(dimensions[0], dimensions[1], 4, 2))\n self.policy = np.zeros(shape=(dimensions[0], dimensions[1], 4))\n self.policy[:, :, :] = 0.25\n self.eps = 0.4\n\n def learn(self):\n s_k = (0, 0)\n # (a)\n occurrences = []\n while True:\n policy = self.get_behaviour_policy(s_k)\n a_k = self.gw.actions[policy]\n s_kk = self.gw.get_next_state(s_k, a_k)\n occurrences.append([s_k, policy, self.gw.get_reward(s_k, a_k, s_kk)])\n if self.gw.is_terminal_state(s_k):\n break\n s_k = s_kk\n\n # (b)\n computed_state_actions = []\n for i in range(len(occurrences)):\n if (occurrences[i][0], occurrences[i][1]) in computed_state_actions:\n continue\n for j in np.arange(i, len(occurrences)):\n self.returns[occurrences[i][0][0], occurrences[i][0][1], occurrences[i][1], 0] += occurrences[j][2]\n\n self.returns[occurrences[i][0][0], occurrences[i][0][1], occurrences[i][1], 1] += 1\n total_R = self.returns[occurrences[i][0][0], occurrences[i][0][1], occurrences[i][1], 0]\n number_of_Rs = self.returns[occurrences[i][0][0], occurrences[i][0][1], occurrences[i][1], 1]\n self.q[occurrences[i][0][0], occurrences[i][0][1], occurrences[i][1]] = total_R / float(number_of_Rs)\n computed_state_actions.append((occurrences[i][0], occurrences[i][1]))\n\n # (c)\n computed_states = []\n for occurrence in occurrences:\n state = occurrence[0]\n if state in computed_states:\n continue\n opt_action = np.argmax(self.q[state[0], state[1], :])\n for action_number in range(4):\n if action_number == opt_action:\n self.policy[state[0], state[1], action_number] = 1 - self.eps + self.eps/4\n else:\n self.policy[state[0], state[1], action_number] = self.eps/4\n computed_states.append(state)\n\n def get_policy(self, state):\n argmax_a = np.argmax(self.q[state[0], state[1], :])\n return self.gw.actions[argmax_a]\n\n def get_behaviour_policy(self, state):\n weights = []\n for action_number in range(4):\n weights.append(self.policy[state[0], state[1], action_number])\n return helper.weighted_choice(weights)\n\n @staticmethod\n def is_online():\n return True\n\n\nif __name__ == \"__main__\":\n mc = MonteCarlo()\n for it in range(5000):\n mc.learn()\n for row in range(4):\n for col in range(5):\n print(row, col, mc.gw.actions[np.argmax(mc.q[row, col, :])])","sub_path":"monteCarlo.py","file_name":"monteCarlo.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"15426096","text":"import pytest\nimport tensorflow as tf\n\nfrom hungry_geese.utils import (\n random_legal_action, get_timestamp,\n log_to_tensorboard, log_configuration_to_tensorboard)\n\n@pytest.mark.parametrize('previous_action, ilegal_next_action', [\n ('NORTH', 'SOUTH'),\n ('SOUTH', 'NORTH'),\n ('EAST', 'WEST'),\n ('WEST', 'EAST'),\n])\ndef test_random_legal_action(previous_action, ilegal_next_action):\n assert ilegal_next_action not in [random_legal_action(previous_action) for _ in range(10)]\n\ndef test_get_timestamp_is_callable():\n get_timestamp()\n\ndef test_log_to_tensorboard(tmpdir):\n tensorboard_writer = tf.summary.create_file_writer(str(tmpdir))\n log_to_tensorboard('key', 0, 0, tensorboard_writer)\n\ndef test_log_configuration_to_tensorboard(tmpdir):\n tensorboard_writer = tf.summary.create_file_writer(str(tmpdir))\n log_configuration_to_tensorboard(dict(key=0), tensorboard_writer)\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"342868642","text":"import sys\nimport os.path as o\nimport os\nsys.path.append(o.abspath(o.join(o.dirname(sys.modules[__name__].__file__), \"..\")))\n# os.chdir('../')\n\n# from oracles.mm1queue import MM1Queue\nfrom data_farming_base import DesignPoint, DataFarmingExperiment, DataFarmingMetaExperiment\nfrom csv import DictReader\n\n\n# factor_headers = [\"purchase_price\", \"sales_price\", \"salvage_price\", \"order_quantity\"]\n# myexperiment = DataFarmingExperiment(oracle_name=\"CNTNEWS\", factor_settings_filename=\"oracle_factor_settings\", factor_headers=factor_headers, design_filename=None, oracle_fixed_factors={})\n# myexperiment.run(n_reps=10, crn_across_design_pts=False)\n# myexperiment.print_to_csv(csv_filename=\"cntnews_data_farming_output\")\n\nsolver_factor_headers = [\"sample_size\"]\nmyMetaExperiment = DataFarmingMetaExperiment(solver_name=\"RNDSRCH\",\n problem_name=\"FACSIZE-2\",\n solver_factor_headers=solver_factor_headers,\n solver_factor_settings_filename=\"\", # solver_factor_settings\",\n design_filename=\"random_search_design\",\n solver_fixed_factors={},\n problem_fixed_factors={},\n oracle_fixed_factors={})\nmyMetaExperiment.run(n_macroreps=20)\nmyMetaExperiment.post_replicate(n_postreps=100, n_postreps_init_opt=100, crn_across_budget=True, crn_across_macroreps=False)\n# myMetaExperiment.calculate_statistics() # solve_tols=[0.10], beta=0.50)\n# myMetaExperiment.print_to_csv(csv_filename=\"meta_raw_results\")\n\nprint(\"I ran this.\")\n\n\n# SCRATCH\n# --------------------------------\n# from csv import DictReader\n# # open file in read mode\n# with open('example_design_matrix.csv', 'r') as read_obj:\n# # pass the file object to DictReader() to get the DictReader object\n# csv_dict_reader = DictReader(read_obj)\n# # iterate over each line as a ordered dictionary\n# for row in csv_dict_reader:\n# # row variable is a dictionary that represents a row in csv\n# print(row)","sub_path":"simopt/demo/demo_df_wrapper.py","file_name":"demo_df_wrapper.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"136432704","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\nfrom func_omniglot import VAE, Loss, data_folders,get_data_loader, create_task\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport os\nimport numpy as np\nimport random\n\ndef count_acc(logits,labels):\n pred = torch.argmax(logits, dim=1)\n return (pred == labels).type(torch.FloatTensor).mean().item()\n\nnum_epochs = 1000\nlearning_rate = 0.001\ncnt = 0\nn_batch_train = 100 #(way+15)*shot\nn_batch_val = 400 #(way+15)*shot 20 or 100\n\nn_train_way = 20\nn_val_way = 5\n\nn_train_shot = 1\nn_val_shot = 1\n# MNIST dataset\n#train_dataset = torchvision.datasets.MNIST(root='../../sharedLocal/',train=True,transform=transforms.ToTensor(),download=True)\n#val_dataset = torchvision.datasets.MNIST(root='../../sharedLocal/',train=False,transform=transforms.ToTensor())\n\ntrain_folders,test_folders = data_folders(data_folder = '../../sharedLocal/traffic')\n\npn_loss_list = []\npn_acc_list = []\nval_loss_list = []\nval_acc_list = []\n\ntorch.cuda.set_device(3)\nmodel = VAE().cuda()\ncrit = Loss()\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n\nprint('training....')\nfor epoch in range(num_epochs):\n model.train()\n if epoch%10 == 0:\n print(\"epoch {}...\".format(epoch))\n task = create_task(train_folders,n_train_way,n_train_shot,15)\n degrees = random.choice([0])\n support_dataloader = get_data_loader(task,'../../sharedLocal/traffic',num_per_class=n_train_shot,split=\"train\",shuffle=False,rotation=degrees)\n query_dataloader = get_data_loader(task,'../../sharedLocal/traffic',num_per_class=15,split=\"test\",shuffle=False,rotation=degrees)\n\n support,support_labels = support_dataloader.__iter__().next()\n query,query_labels = query_dataloader.__iter__().next()\n total_loss = 0\n total_acc = 0\n\n x_support,x_support_labels = support.cuda(), support_labels.cuda()\n x_query,x_query_labels = query.cuda(), query_labels.cuda()\n\n change_support = []\n for j in range(n_train_shot):\n change_support += [i for i in range(j,len(x_support),n_train_shot)]\n x_support = x_support[change_support,:,:,:]\n change_query = []\n for j in range(15):\n change_query += [i for i in range(j,len(x_query),15)]\n x_query = x_query[change_query,:,:,:]\n\n optimizer.zero_grad()\n embedding_support, recon_support, mu_support, logvar_support = model([x_support,'support'])\n embedding_query, recon_query, mu_query, logvar_query = model([x_query,'query'])\n labels = torch.arange(n_train_way).repeat(15)\n labels = labels.type(torch.cuda.LongTensor)\n loss, logits = crit(embedding_support,recon_support, mu_support, logvar_support, x_support, embedding_query,recon_query, mu_query, logvar_query, x_query, labels)\n accuracy = count_acc(logits, labels)\n total_loss = total_loss + loss.item()\n total_acc += accuracy\n loss.backward()\n optimizer.step()\n pn_loss_list.append(total_loss)\n pn_acc_list.append(total_acc)\n\n if (epoch)%10 == 0:\n print('validation....')\n val_loss = 0\n val_acc = 0.\n for _ in range(100):\n degrees = random.choice([0])\n task = create_task(test_folders,n_val_way,n_val_shot,15)\n support_dataloader = get_data_loader(task,'../../sharedLocal/traffic',num_per_class=n_val_shot,split=\"train\",shuffle=False,rotation=degrees)\n test_dataloader = get_data_loader(task,'../../sharedLocal/traffic',num_per_class=15,split=\"test\",shuffle=False,rotation=degrees)\n\n support_images,support_labels = support_dataloader.__iter__().next()\n test_images,test_labels = test_dataloader.__iter__().next()\n\n x_support,x_support_labels = support_images.cuda(), support_labels.cuda()\n x_query,x_query_labels = test_images.cuda(), test_labels.cuda()\n\n change_support = []\n for j in range(n_val_shot):\n change_support += [i for i in range(j,len(x_support),n_val_shot)]\n x_support = x_support[change_support,:,:,:]\n change_query = []\n for j in range(15):\n change_query += [i for i in range(j,len(x_query),15)]\n x_query = x_query[change_query,:,:,:]\n\n embedding_support, recon_support, mu_support, logvar_support = model([x_support,'support'])\n embedding_query, recon_query, mu_query, logvar_query = model([x_query,'query'])\n labels = torch.arange(n_val_way).repeat(15)\n labels = labels.type(torch.cuda.LongTensor)\n# print(embedding_support.shape,recon_support.shape,mu_support.shape,x_support.shape)\n# print(embedding_query.shape,recon_query.shape,mu_query.shape,x_query.shape)\n loss, logits = crit(embedding_support,recon_support, mu_support, logvar_support, x_support, embedding_query,recon_query, mu_query, logvar_query, x_query, labels)\n acc = count_acc(logits, labels)\n #val_loss += loss.item()\n #val_acc += acc\n\n val_loss_list.append(loss.item())\n val_acc_list.append(acc)\n print(pn_acc_list[-1],val_acc_list[-1])\n\nwith open('pn_loss_list.txt','w') as f:\n for item in pn_loss_list:\n f.write('%s\\n'%item)\nwith open('pn_acc_list.txt','w') as f:\n for item in pn_acc_list:\n f.write('%s\\n'%item)\nwith open('val_loss_list.txt','w') as f:\n for item in val_loss_list:\n f.write('%s\\n'%item)\nwith open('val_acc_list.txt','w') as f:\n for item in val_acc_list:\n f.write('%s\\n'%item)\n","sub_path":"models/traffic/train_omniglot.py","file_name":"train_omniglot.py","file_ext":"py","file_size_in_byte":5614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"263499945","text":"# -*-coding:utf-8 -*-\n# 协程\n\nimport time\n\n\ndef consumer():\n res = 0\n while True:\n n = yield res\n time.sleep(1)\n print('消费了一个产品%s * %s' % (n, n))\n res = n*n\n\ndef producer(c):\n c.send(None)\n n = 0\n while n <= 5:\n n += 1\n print('生产了1个产品:%s' % n)\n r = c.send(n)\n print('消费返回 %s' % r)\n\nc = consumer()\n\nproducer(c)\n\n","sub_path":"basic/coroutine_sample.py","file_name":"coroutine_sample.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"298687193","text":"#辞書ファイルを読み込むテスト\ndef read_dictionary():\n # 単語による判定\n file = open(\"dict/dict1.txt\",\"r\")\n read_data = {}\n for line in file:\n read_line = line.split('\\t')\n read_data[read_line[0]] = read_line[1]\n file.close()\n return read_data\n\n\ndef enp_hantei(yousos):\n dictionary = read_dictionary()\n texts = yousos\n print('-----------感情解析-----------')\n kanjou = 0\n count = 0\n for text in texts:\n if text in dictionary:\n print(text+'\\t'+dictionary[text])\n if dictionary[text] == 'ポジティブ':\n kanjou += 1\n count += 1\n elif dictionary[text] == 'ネガティブ':\n kanjou -= 1\n count += 1\n else: \n print(text+'\\t'+'none')\n if kanjou == 0:\n r = '感情数値:'+str(0)\n else:\n suuchi = kanjou/count\n r = '感情数値:'+str(suuchi)\n return(r)","sub_path":"src/read_dict.py","file_name":"read_dict.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"400310379","text":"# -*- coding: utf-8 -*-\n\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.feature_extraction.text import TfidfTransformer \nfrom sklearn.feature_extraction.text import CountVectorizer \nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.metrics import mean_squared_error, accuracy_score\nfrom sklearn.svm import SVR\nfrom sklearn import linear_model\nfrom sklearn.feature_selection import chi2\nfrom sklearn.feature_selection import SelectKBest\nfrom scipy.sparse import csr_matrix, vstack, hstack\nfrom sklearn.ensemble import (RandomTreesEmbedding, RandomForestClassifier,\n GradientBoostingClassifier)\nfrom sklearn.cross_validation import train_test_split \nimport matplotlib.pyplot as plt \n\ndef read_data(filename):\n df1 = pd.read_csv(filename, header = None, encoding = \"utf8\")\n np1 = np.array(df1)\n data = np1[:, 0:-1]\n label = np1[:, -1]\n return data, label.astype('float32')\n \n \nif __name__ == \"__main__\":\n data, label = read_data(\"../input/data_clean.csv\")\n data_combine = np.hstack((data[:, 0], data[:, 1]))\n vectorizer = CountVectorizer()\n transformer = TfidfTransformer()\n label_up = np.hstack((label, label)).astype(\"float32\")\n similarity = np.zeros((data.shape[0], 1))\n tfidf = transformer.fit_transform(vectorizer.fit_transform(data_combine))\n question = csr_matrix(tfidf[0:data.shape[0]])\n answer = csr_matrix(tfidf[data.shape[0]:])\n data_sparse = hstack([question, answer])\n plt.figure()\n \n \n similarity_all = cosine_similarity(question, answer)\n for i in range(similarity_all.shape[0]):\n similarity[i] = similarity_all[i, i]\n\n for i in range(data.shape[0]):\n try:\n tfidf = transformer.fit_transform(vectorizer.fit_transform(data[i, :]))\n similarity[i] = (cosine_similarity(tfidf)[0, 1])\n except:\n similarity[i] = 0\n label[i] = 0\n# print(data[i])\n \n train_X,test_X, train_y, test_y = train_test_split(similarity, label, test_size = 0.2, random_state = 0) \n\n mse_train = []\n mse_test = []\n for model in ['logistic', 'linear', 'GBDT', 'NN']:\n\n if model == 'NN':\n clf = MLPClassifier(solver='lbfgs', alpha=1e-5, \n hidden_layer_sizes=(50, 10), random_state=1)\n n_estimator = 10 \n# clf = SVR(C=1.0, epsilon=0.2)\n if model == 'linear':\n clf = linear_model.LinearRegression()\n if model == 'logistic':\n clf = linear_model.LogisticRegression()\n if model == 'GBDT':\n clf = GradientBoostingClassifier(n_estimators=n_estimator)\n clf.fit(train_X, train_y) \n# predict_train = clf.predict(train_X)\n# mse_train.append(mean_squared_error(predict_train, train_y))\n# print(\"error in train set\", mean_squared_error(predict_train, train_y))\n predict_test = clf.predict(test_X)\n# mse_test.append(mean_squared_error(predict_test, test_y))\n # print(\"error in test set\", mean_squared_error(predict_test, test_y))\n# plt.plot(range(len(mse_train)), mse_train, label = 'train')\n print(\"accuracy of {} is \\t:{}\".format(model, mean_squared_error(predict_test, test_y)))\n# plt.plot(range(len(mse_test)), mse_test, label = model)\n# plt.ylim(0.4,1.2)\n# plt.legend()\n# plt.show()\n ","sub_path":"code/tfidf_similiar.py","file_name":"tfidf_similiar.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"304367126","text":"# -*- coding: utf-8 -*-\n\n# FLO-2D Preprocessor tools for QGIS\n\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version\n\nfrom qgis.PyQt.QtCore import Qt\nfrom ..flo2dobjects import InletRatingTable\nfrom qgis.PyQt.QtWidgets import QInputDialog, QTableWidgetItem, QDialogButtonBox, QApplication\nfrom qgis.PyQt.QtGui import QColor\nfrom .ui_utils import load_ui, set_icon\nfrom ..geopackage_utils import GeoPackageUtils\nfrom ..user_communication import UserCommunication\nfrom ..utils import m_fdata, float_or_zero, int_or_zero, is_number\nfrom .table_editor_widget import StandardItemModel, StandardItem, CommandItemEdit\nfrom math import isnan\n\nuiDialog, qtBaseClass = load_ui(\"bridges\")\n\n\nclass BridgesDialog(qtBaseClass, uiDialog):\n def __init__(self, iface, lyrs, structName):\n qtBaseClass.__init__(self)\n uiDialog.__init__(self)\n self.iface = iface\n self.lyrs = lyrs\n self.structName = structName\n self.structFid = 0\n self.setupUi(self)\n self.uc = UserCommunication(iface, \"FLO-2D\")\n self.con = None\n self.gutils = None\n\n self.setup_connection()\n self.populate_bridge()\n\n def setup_connection(self):\n con = self.iface.f2d[\"con\"]\n if con is None:\n return\n else:\n self.con = con\n self.gutils = GeoPackageUtils(self.con, self.iface)\n\n def populate_bridge(self):\n struct_fid = self.gutils.execute(\"SELECT fid FROM struct WHERE structname = ?;\", (self.structName,)).fetchone()\n if struct_fid:\n self.structFid = struct_fid[0]\n if not self.structFid:\n self.uc.warn_bar(\"No data for structure \" + structName)\n else:\n bridge_qry = \"SELECT * FROM bridge_variables WHERE struct_fid = ?;\"\n row = self.gutils.execute(bridge_qry, (self.structFid,)).fetchone()\n if not row:\n insert_bridge_sql = \"\"\"INSERT INTO bridge_variables\n (struct_fid, IBTYPE, COEFF, C_PRIME_USER, KF_COEF, \n KWW_COEF, KPHI_COEF, KY_COEF, KX_COEF, KJ_COEF, \n BOPENING, BLENGTH, BN_VALUE, UPLENGTH12, LOWCHORD,\n DECKHT, DECKLENGTH, PIERWIDTH, SLUICECOEFADJ, ORIFICECOEFADJ, \n COEFFWEIRB, WINGWALL_ANGLE, PHI_ANGLE, LBTOEABUT, RBTOEABUT)\n VALUES (?, 1, 0.1, 0.5, 0.9, \n 1.0, 0.7, 0.85, 1.0, 0.6, \n 0.0, 0.0, 0.030, 0.0, 0.0, \n 0.0, 0.0, 0.0, 0.0, 0.0, \n 2.65, 30, 0, 0, 0);\"\"\"\n self.gutils.execute(insert_bridge_sql, (self.structFid,))\n row = self.gutils.execute(bridge_qry, (self.structFid,)).fetchone()\n\n self.IBTYPE_cbo.setCurrentIndex(int_or_zero(row[2] - 1))\n self.COEFF_dbox.setValue(float_or_zero(row[3]))\n self.C_PRIME_USER_dbox.setValue(float_or_zero(row[4]))\n self.KF_COEF_dbox.setValue(float_or_zero(row[5]))\n self.KWW_COEF_dbox.setValue(float_or_zero(row[6]))\n self.KPHI_COEF_dbox.setValue(float_or_zero(row[7]))\n self.KY_COEF_dbox.setValue(float_or_zero(row[8]))\n self.KX_COEF_dbox.setValue(float_or_zero(row[9]))\n self.KJ_COEF_dbox.setValue(float_or_zero(row[10]))\n self.BOPENING_dbox.setValue(float_or_zero(row[11]))\n self.BLENGTH_dbox.setValue(float_or_zero(row[12]))\n self.BN_VALUE_dbox.setValue(float_or_zero(row[13]))\n self.UPLENGTH12_dbox.setValue(float_or_zero(row[14]))\n self.LOWCHORD_dbox.setValue(float_or_zero(row[15]))\n self.DECKHT_dbox.setValue(float_or_zero(row[16]))\n self.DECKLENGTH_dbox.setValue(float_or_zero(row[17]))\n self.PIERWIDTH_dbox.setValue(float_or_zero(row[18]))\n self.SLUICECOEFADJ_dbox.setValue(float_or_zero(row[19]))\n self.ORIFICECOEFADJ_dbox.setValue(float_or_zero(row[20]))\n self.COEFFWEIRB_dbox.setValue(float_or_zero(row[21]))\n self.WINGWALL_ANGLE_dbox.setValue(float_or_zero(row[22]))\n self.PHI_ANGLE_dbox.setValue(float_or_zero(row[23]))\n self.LBTOEABUT_dbox.setValue(float_or_zero(row[24]))\n self.RBTOEABUT_dbox.setValue(float_or_zero(row[25]))\n\n def save_bridge_variables(self):\n \"\"\"\n Save changes to bridge variables.\n \"\"\"\n\n try:\n update_qry = \"\"\"\n UPDATE bridge_variables\n SET \n IBTYPE = ?,\n COEFF = ?,\n C_PRIME_USER = ?,\n KF_COEF = ?,\n KWW_COEF = ?,\n KPHI_COEF = ?,\n KY_COEF = ?,\n KX_COEF = ?,\n KJ_COEF = ?,\n BOPENING = ?,\n BLENGTH = ?,\n BN_VALUE = ?,\n UPLENGTH12 = ?,\n LOWCHORD = ?,\n DECKHT = ?,\n DECKLENGTH = ?,\n PIERWIDTH = ?,\n SLUICECOEFADJ = ?,\n ORIFICECOEFADJ = ?,\n COEFFWEIRB = ?,\n WINGWALL_ANGLE = ?,\n PHI_ANGLE = ?,\n LBTOEABUT = ?,\n RBTOEABUT = ?\n WHERE struct_fid = ? ; \"\"\"\n\n self.gutils.execute(\n update_qry,\n (\n self.IBTYPE_cbo.currentIndex() + 1,\n self.COEFF_dbox.value(),\n self.C_PRIME_USER_dbox.value(),\n self.KF_COEF_dbox.value(),\n self.KWW_COEF_dbox.value(),\n self.KPHI_COEF_dbox.value(),\n self.KY_COEF_dbox.value(),\n self.KX_COEF_dbox.value(),\n self.KJ_COEF_dbox.value(),\n self.BOPENING_dbox.value(),\n self.BLENGTH_dbox.value(),\n self.BN_VALUE_dbox.value(),\n self.UPLENGTH12_dbox.value(),\n self.LOWCHORD_dbox.value(),\n self.DECKHT_dbox.value(),\n self.DECKLENGTH_dbox.value(),\n self.PIERWIDTH_dbox.value(),\n self.SLUICECOEFADJ_dbox.value(),\n self.ORIFICECOEFADJ_dbox.value(),\n self.COEFFWEIRB_dbox.value(),\n self.WINGWALL_ANGLE_dbox.value(),\n self.PHI_ANGLE_dbox.value(),\n self.LBTOEABUT_dbox.value(),\n self.RBTOEABUT_dbox.value(),\n self.structFid,\n ),\n )\n\n return True\n except Exception as e:\n QApplication.restoreOverrideCursor()\n self.uc.show_error(\n \"ERROR 030220.0743: update of hydraulic structure bridge variables failed!\"\n + \"\\n__________________________________________________\",\n e,\n )\n return False\n pass\n","sub_path":"flo2d/gui/dlg_bridges.py","file_name":"dlg_bridges.py","file_ext":"py","file_size_in_byte":7594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"172432071","text":"##\n## update the labels \n##\n## id ss_id lang_id label\n## \n## FIXME: not checking for confidence\n##\n\nimport sys, sqlite3\nfrom warnings import warn\n\nfrom collections import defaultdict as dd\n\n# It takes one argument: the name of the db\nif (len(sys.argv) < 2):\n sys.stderr.write('You need to give the name of the DB\\n')\n sys.exit(1)\nelse:\n u = sys.argv[0]\n dbfile = sys.argv[1]\n\n\n# dbfile = \"omw.db\"\ncon = sqlite3.connect(dbfile)\nc = con.cursor()\n###\n### get the frequency (from sm)\n###\nsfreq=dd(int)\nc.execute(\"\"\"SELECT id FROM smt WHERE tag='freq'\"\"\")\nr = c.fetchone()\n#print (r[0])\nif r:\n c.execute(\"\"\"SELECT s_id, sml_id FROM sm WHERE smt_id=?\"\"\", str(r[0]))\n for s_id, sml_id in c:\n sfreq[s_id]=sml_id\n \n###\n### get the senses (from sm)\n###\n\nc.execute(\"\"\"\nSELECT s_id, ss_id, lemma, lang_id\n FROM (SELECT w_id, canon, ss_id, s_id \n FROM (SELECT id as s_id, ss_id, w_id FROM s) \n JOIN w ON w_id = w.id ) \n JOIN f ON canon = f.id\n\"\"\")\n\nsenses =dd(lambda: dd(list))\n#senses[ss_id][lang_id]=[(ls_id, lemma, freq), ...]\nforms = dd(lambda: dd(int))\n#forms[lang][word] = freq\n\nlangs=set()\neng_id=1 ### we know this :-)\nfor (s_id, ss_id, lemma, lang_id) in c:\n senses[ss_id][lang_id].append((s_id, lemma, sfreq[s_id]))\n forms[lang_id][lemma] += 1\n langs.add(lang_id)\n #print (s_id, ss_id, lemma, lang_id)\n\n\n###\n### sort the things\n### prefer frequent sense; infrequent form; short; alphabetical\n \nfor ss in senses:\n for l in senses[ss]:\n senses[ss][l].sort(key=lambda x: (-x[2], ### sense freq (freq is good)\n forms[l][x[1]], ### uniqueness (freq is bad) \n len(x[1]), ### length (short is good)\n x[1])) ### lemma (so it is the same)\n# print(ss, l, \", \".join(\"{} {}-{}\".format(lm,f, forms[l][lm])\n# for (s,lm,f) in senses[ss][l]))\n\n# print(\"==================================\")\n\n#label[ss_id][lang_id] = label || '?????'\n#\n# make the labels\n#\n\nlabel = dd(lambda: dd(str))\n\nlgs=sorted(langs)\n\nvalues=list()\nfor ss in senses:\n for l in lgs:\n if senses[ss][l]:\n label[ss][l]=senses[ss][l][0][1]\n else:\n for lx in lgs: ### start with eng and go through till you find one\n ##print (\"Looking elsewhere\", ss, l, lx,senses[ss][lx])\n if senses[ss][lx]:\n label[ss][l]=senses[ss][lx][0][1]\n break\n else:\n label[ss][l]=\"?????\"\n values.append((ss, l, label[ss][l]))\n #print(\"V\", ss, l, label[ss][l])\n###\n### write the labels (delete old ones first)\n###\nc.execute(\"\"\"DELETE FROM label\"\"\")\nc.executemany(\"\"\"INSERT INTO label(ss_id, lang_id, label, u) \nVALUES (?,?,?,\"omw\")\"\"\", values)\n \ncon.commit() \n\n\n","sub_path":"omw/bin/update-label.py","file_name":"update-label.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"62960608","text":"\"\"\"\n DWF Python Example\n Author: Digilent, Inc.\n Revision: 2019-07-12\n\n Requires: \n Python 2.7, 3\n\"\"\"\n\nfrom ctypes import *\nfrom dwfconstants import *\nimport math\nimport time\nimport sys\nimport numpy\nimport matplotlib.pyplot as plt\n\nif sys.platform.startswith(\"win\"):\n dwf = cdll.LoadLibrary(\"dwf.dll\")\nelif sys.platform.startswith(\"darwin\"):\n dwf = cdll.LoadLibrary(\"/Library/Frameworks/dwf.framework/dwf\")\nelse:\n dwf = cdll.LoadLibrary(\"libdwf.so\")\n\nversion = create_string_buffer(16)\ndwf.FDwfGetVersion(version)\nprint(\"DWF Version: \"+str(version.value))\n\nhdwf = c_int()\nszerr = create_string_buffer(512)\nprint(\"Opening first device\")\ndwf.FDwfDeviceOpen(c_int(-1), byref(hdwf))\n\nif hdwf.value == hdwfNone.value:\n dwf.FDwfGetLastErrorMsg(szerr)\n print(str(szerr.value))\n print(\"failed to open device\")\n quit()\n\n# this option will enable dynamic adjustment of analog out settings like: frequency, amplitude...\ndwf.FDwfDeviceAutoConfigureSet(hdwf, c_int(3)) \n\nsts = c_byte()\nsteps = 151\nstart = 1e2\nstop = 1e5\nreference = 1e3\namplitude = 1\n\nt1 = c_double()\nt2 = c_double()\n\nprint(\"Frequency: \"+str(start)+\" Hz ... \"+str(stop/1e3)+\" kHz Steps: \"+str(steps))\ndwf.FDwfAnalogImpedanceReset(hdwf)\ndwf.FDwfAnalogImpedanceModeSet(hdwf, c_int(0)) # 0 = W1-C1-DUT-C2-R-GND, 1 = W1-C1-R-C2-DUT-GND, 8 = AD IA adapter\ndwf.FDwfAnalogImpedanceReferenceSet(hdwf, c_double(reference)) # reference resistor value in Ohms\ndwf.FDwfAnalogImpedanceFrequencySet(hdwf, c_double(start)) # frequency in Hertz\ndwf.FDwfAnalogImpedanceAmplitudeSet(hdwf, c_double(amplitude)) # 1V amplitude = 2V peak2peak signal\ndwf.FDwfAnalogImpedanceConfigure(hdwf, c_int(1)) # start\ntime.sleep(2)\n\nrgHz = [0.0]*steps\nrgGaC2 = [0.0]*steps\nrgPhC2 = [0.0]*steps\nrgCs = [0.0]*steps\nfor i in range(steps):\n hz = stop * pow(10.0, 1.0*(1.0*i/(steps-1)-1)*math.log10(stop/start)) # exponential frequency steps\n rgHz[i] = hz\n dwf.FDwfAnalogImpedanceFrequencySet(hdwf, c_double(hz)) # frequency in Hertz\n time.sleep(0.01) \n dwf.FDwfAnalogImpedanceStatus(hdwf, None) # ignore last capture since we changed the frequency\n while True:\n if dwf.FDwfAnalogImpedanceStatus(hdwf, byref(sts)) == 0:\n dwf.FDwfGetLastErrorMsg(szerr)\n print(str(szerr.value))\n quit()\n if sts.value == 2:\n break\n gain2 = c_double()\n phase2 = c_double()\n dwf.FDwfAnalogImpedanceStatusInput(hdwf, c_int(1), byref(gain2), byref(phase2)) # relative to Channel 1, C1/C#\n rgGaC2[i] = 20.0*math.log10(abs(gain2.value-1.0))\n rgPhC2[i] = phase2.value*180/math.pi\n cs = c_double()\n dwf.FDwfAnalogImpedanceStatusMeasure(hdwf, DwfAnalogImpedanceSeriesCapactance, byref(cs)) \n rgCs[i] = cs.value\n \n\ndwf.FDwfAnalogImpedanceConfigure(hdwf, c_int(0)) # stop\ndwf.FDwfDeviceClose(hdwf)\n\n\nplt.subplot(311)\nplt.plot(rgHz, rgGaC2, color='blue')\nax = plt.gca()\nax.set_title(\"{0:.2f}Hz : {1:.2f}dB {2:.2f}* {3:.2f}nF\".format(rgHz[0], rgGaC2[0], rgPhC2[0], rgCs[0]*1e9))\nax.set_xscale('log')\nplt.subplot(312)\nplt.plot(rgHz, rgPhC2)\nax = plt.gca()\nax.set_xscale('log')\nplt.subplot(313)\nplt.plot(rgHz, rgCs)\nax = plt.gca()\nax.set_xscale('log')\nplt.show()\n\n","sub_path":"py/AnalogImpedance_Input.py","file_name":"AnalogImpedance_Input.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"80808739","text":"from helicontrollers.AbstractController import AbstractController\nfrom helicontrollers.util import ModelType, compute_feed_forward_flatness\nfrom gui.ParameterFrame import ParamEnum, ParamFloatArray\nimport control as ctr\nimport numpy as np\n\nfrom ModelConstants import OriginalConstants as mc\nfrom numpy.ma import cos, sin\n\nL1 = mc.l_p\nL2 = mc.g * (mc.l_c * mc.m_c - 2 * mc.l_h * mc.m_p)\nL3 = mc.l_h\nL4 = mc.l_h\n\nJp = 2 * mc.m_p * mc.l_p ** 2\nJe = mc.m_c * mc.l_c ** 2 + 2 * mc.m_p * mc.l_h ** 2\nJl = mc.m_c * mc.l_c ** 2 + 2 * mc.m_p * (mc.l_h ** 2 + mc.l_p ** 2)\n\n#ToDo Unite these calculations for the controller with the other flatness-based formulas\n\n\ndef getLinearizedMatrices(model_type: ModelType, operating_point, Vf_op, Vb_op):\n \"\"\"Computes the matrices of the linearized model at the given operating point.\n\n :param model_type: the type of model that should be linearized\n :param operating_point: list of state variables (p, e, lambda, dp, de, dlambda)\n :param Vf_op: value of Vf for linearization\n :param Vb_op: value of Vb for linearization\"\"\"\n\n p_op, e_op, lamb_op, dp_op, de_op, dlamb_op = operating_point\n\n # Vf_op, Vb_op = compute_feed_forward_flatness(e_and_derivatives, lambda_and_derivatives)\n Vs_op = Vf_op + Vb_op\n Vd_op = Vf_op - Vb_op\n\n if model_type == ModelType.EASY:\n A = np.array([[0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0],\n [-L3 * Vs_op * sin(p_op) / Je, -L2 * sin(e_op) / Je, 0, 0, 0, 0],\n [L4 * Vs_op * cos(p_op) * cos(e_op) / Jl, 0, 0, 0, 0, 0]])\n elif model_type == ModelType.FRICTION:\n A = np.array([[0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, -mc.mu_phi / Jp, 0, 0],\n [-L3 * Vs_op * sin(p_op) / Je, -L2 * sin(e_op) / Je, 0, 0, -mc.mu_eps / Je, 0],\n [L4 * Vs_op * cos(p_op) * cos(e_op) / Jl, -L4 * Vs_op * sin(p_op) * sin(e_op) / Jl, 0, 0, 0, -mc.mu_lamb / Jl]])\n elif model_type == ModelType.CENTRIPETAL:\n A = np.array([[0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1],\n [-(de_op ** 2 - dlamb_op ** 2 * cos(e_op) ** 2) * sin(p_op) ** 2 + (de_op ** 2 - dlamb_op ** 2 * cos(e_op) ** 2) * cos(p_op) ** 2, 2 * dlamb_op ** 2 * sin(p_op) * sin(e_op) * cos(p_op) * cos(e_op), 0, -mc.mu_phi / Jp, 2 * de_op * sin(p_op) * cos(p_op), -2 * dlamb_op * sin(p_op) * cos(p_op) * cos(e_op) ** 2],\n [-L3 * Vs_op * sin(p_op) / Je, dlamb_op ** 2 * sin(e_op) ** 2 - dlamb_op ** 2 * cos(e_op) ** 2 - L2 * sin(e_op) / Je, 0, 0, -mc.mu_eps / Je, -2 * dlamb_op * sin(e_op) * cos(e_op)],\n [L4 * Vs_op * cos(p_op) * cos(e_op) / Jl, -L4 * Vs_op * sin(p_op) * sin(e_op) / Jl, 0, 0, 0, -mc.mu_lamb / Jl]])\n\n B = np.array([[0, 0],\n [0, 0],\n [0, 0],\n [L1 / Jp, -L1 / Jp],\n [L3 / Je * cos(p_op), L3 / Je * cos(p_op)],\n [L4 * sin(p_op) * cos(e_op) / Jl, L4 * sin(p_op) * cos(e_op) / Jl]])\n\n return A, B, Vf_op, Vb_op\n\n\ndef get_p_and_first_derivative(model_type: ModelType, e_and_derivatives, lambda_and_derivatives):\n if model_type == ModelType.EASY:\n return get_p_and_first_derivative_simple(model_type, e_and_derivatives, lambda_and_derivatives)\n elif model_type == ModelType.CENTRIPETAL:\n return get_p_and_first_derivative_centripetal(model_type, e_and_derivatives, lambda_and_derivatives)\n else:\n raise NotImplementedError(\"get_p_and_first_derivative is not implemented for other model types than EASY and CENTRIPETAL.\")\n\ndef get_p_and_first_derivative_centripetal(model_type: ModelType, e_and_derivatives, lambda_and_derivatives):\n \"\"\"copied from util.compute_pitch_and_inputs_flatness_centripetal\"\"\"\n e = e_and_derivatives[0]\n de1 = e_and_derivatives[1]\n de2 = e_and_derivatives[2]\n de3 = e_and_derivatives[3]\n de4 = e_and_derivatives[4]\n\n l = lambda_and_derivatives[0]\n dl1 = lambda_and_derivatives[1]\n dl2 = lambda_and_derivatives[2]\n dl3 = lambda_and_derivatives[3]\n dl4 = lambda_and_derivatives[4]\n\n a = Jl * dl2\n b = mc.mu_lamb * dl1\n c = cos(e)\n d = Je * de2\n e_ = mc.mu_eps * de1\n f = Je * cos(e) * sin(e) * dl1**2\n g = -L2 * cos(e)\n\n da1 = Jl * dl3\n db1 = mc.mu_lamb * dl2\n dc1 = -sin(e) * de1\n dd1 = Je * de3\n de_1 = mc.mu_eps * de2\n # f\n k = cos(e) * sin(e)\n l_ = dl1**2\n dk1 = de1 * (cos(e)**2 - sin(e)**2)\n dl_1 = 2 * dl1 * dl2\n df1 = Je * (dk1 * l_ + k * dl_1)\n dg1 = L2 * sin(e) * de1\n\n da2 = Jl * dl4\n db2 = mc.mu_lamb * dl3\n dc2 = -cos(e) * de1 ** 2 - sin(e) * de2\n dd2 = Je * de4\n de_2 = mc.mu_eps * de3\n # f\n dk2 = de2 * (cos(e)**2 - sin(e)**2) - 4 * sin(e) * cos(e) * de1 **2\n dl2 = 2 * (dl2**2 + dl1 * dl3)\n df2 = Je * (dk2 * l + 2*dk1 *dl1 + k * dl2)\n dg2 = L2 * (cos(e) * de1**2 + sin(e) * de2)\n\n h = a+b\n i = d + e_ + f + g\n j = c * i\n\n dh1 = da1 + db1\n di1 = dd1 + de_1 + df1 + dg1\n dj1 = dc1 * i + c * di1\n\n dh2 = da2 + db2\n di2 = dd2 + de_2 + df2 + dg2\n dj2 = dc2 * i + 2*dc1*di1 + c * di2\n\n A = h / j\n dA1 = (dh1 * j - h * dj1) / (j ** 2)\n dA2 = ((dh2 * j - h * dj2) * j - (dh1 *j -h * dj1) * 2 * dj1) / (j**3)\n\n x = (L3/L4) * A\n dx1 = (L3/L4) * dA1\n dx2 = (L3/L4) * dA2\n\n # p = arctan((L3/L4) * A)\n # dp1 = (L3 / L4) * 1/(1+((L3/L4) * A)**2) * dA1\n # dp2 = (L3 / L4) * (dA2 * (1+((L3/L4) * A)**2) - (L3/L4) * dA1**2) / ((1+((L3/L4) * A)**2)**2)\n p = np.arctan(x)\n dp1 = dx1/(1+x**2)\n return p, dp1\n\n\n\ndef get_p_and_first_derivative_simple(model_type: ModelType, e_and_derivatives, lambda_and_derivatives):\n \"Computes p and dp from the flat output and its derivatives.\"\n if model_type != ModelType.EASY:\n print(\"model_type = \" + str(model_type))\n raise NotImplementedError(\"get_p_and_first_derivative is not implemented for other model types than EASY.\")\n\n p = np.arctan((Jl * L3 * lambda_and_derivatives[2]) /\n (L4 * cos(e_and_derivatives[0]) *(Je * e_and_derivatives[2] - L2 * cos(e_and_derivatives[0]))))\n # the following part is partly copied from compute_feed_forward_flatness\n e = e_and_derivatives[0]\n de1 = e_and_derivatives[1]\n de2 = e_and_derivatives[2]\n de3 = e_and_derivatives[3]\n de4 = e_and_derivatives[4]\n\n l = lambda_and_derivatives[0]\n dl1 = lambda_and_derivatives[1]\n dl2 = lambda_and_derivatives[2]\n dl3 = lambda_and_derivatives[3]\n dl4 = lambda_and_derivatives[4]\n\n b = L3 * Jl * dl2\n c = L4 * cos(e)\n d = Je * de2 - L2 * cos(e)\n a = b * c / d\n\n db1 = L3 * Jl * dl3\n db2 = L3 * Jl * dl4\n dc1 = - L4 * sin(e) * de1\n dc2 = - L4 * (cos(e) * de1 ** 2 + sin(e) * de2)\n dd1 = Je * de3 + L2 * sin(e) * de1\n dd2 = Je * de4 + L2 * (cos(e) * de1 ** 2 + sin(e) * de2)\n f = db1 * c * d\n g = dc1 * d + c * dd1\n h = c * c * d * d\n da1 = (f - b * g) / h\n\n dp = (1/(1+a*a)) * da1\n return p, dp\n\ndef get_current_operating_point(model_type: ModelType, e_and_derivatives, lambda_and_derivatives):\n \"\"\"Wrapper function for getLinearizedMatrices. Computes the linearized matrices from the current flat output\n and its derivative.\n :param model_type: the type of model that should be linearized\n :param e_and_derivatives: planned trajectory for e\n :param lambda_and_derivatives: planned trajectory for lambda\n :return operating point vector, Vf_op, Vb_op\"\"\"\n e_op = e_and_derivatives[0]\n de_op = e_and_derivatives[1]\n lamb_op = lambda_and_derivatives[0]\n dlamb_op = lambda_and_derivatives[1]\n Vf_op, Vb_op = compute_feed_forward_flatness(model_type, e_and_derivatives, lambda_and_derivatives)\n p_op, dp_op = get_p_and_first_derivative(model_type, e_and_derivatives, lambda_and_derivatives)\n operating_point = [p_op, e_op, lamb_op, dp_op, de_op, dlamb_op]\n return operating_point, Vf_op, Vb_op\n\nclass TimeVariantController(AbstractController):\n def __init__(self):\n self.operating_point = [0, 0] # travel, elevation\n self.linearization_model_type = ModelType.EASY\n self.flatness_model_type = ModelType.EASY\n self.poles = [-1, -2, -3, -4, -5, -6]\n self.Vf_op = 0\n self.Vb_op = 0\n self.K = np.zeros((2, 6))\n self.time_variant_feedback = True\n self.feedback_computed = False\n\n super().__init__(\"TimeVariantController\", {\n \"Linearization Model type\": ParamEnum([\"Simple\", \"Friction\", \"Centripetal\", \"Rotorspeed\"],\n [ModelType.EASY, ModelType.FRICTION, ModelType.CENTRIPETAL, ModelType.ROTORSPEED],\n self.linearization_model_type),\n \"Flatness-calculation model type\": ParamEnum([\"Simple\", \"Centripetal\"],\n [ModelType.EASY, ModelType.CENTRIPETAL],\n self.flatness_model_type),\n \"Poles\": ParamFloatArray(self.poles)\n })\n\n def control(self, t, x, e_traj, lambda_traj):\n # delete front and back speed because we dont need it here\n x = x[:6]\n # p, e, lamb, dp, de, dlamb = x\n # u_op = np.array([self.Vf_op, self.Vb_op])\n # x_op = np.array([0, self.operating_point[1], self.operating_point[0], 0, 0, 0])\n\n operating_point, Vf_op, Vb_op = get_current_operating_point(self.flatness_model_type, e_traj, lambda_traj)\n A, B, Vf_op, Vb_op = getLinearizedMatrices(self.linearization_model_type, operating_point, Vf_op, Vb_op)\n\n linearized_state = x - operating_point\n\n # compute K for this time step\n try:\n K_now = ctr.place(A, B, self.poles)\n except Exception as e:\n print(\"Error during pole placement: \" + str(e))\n\n u = - K_now @ linearized_state\n return u\n\n def initialize(self, param_value_dict):\n self.linearization_model_type = param_value_dict[\"Linearization Model type\"]\n self.flatness_model_type = param_value_dict[\"Flatness-calculation model type\"]\n self.poles = param_value_dict[\"Poles\"]\n self.feedback_computed = False\n","sub_path":"helicontrollers/unused/TimeVariantController.py","file_name":"TimeVariantController.py","file_ext":"py","file_size_in_byte":10391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"640050095","text":"import os\nimport pandas as pd\nimport numpy as np\nimport load_md as foo # 根据数据集编写, 用来读取数据的文件\nimport time\nfrom multiprocessing import Pool\n\ndef task(n, days, codes):\n print('Start process %d to read data.' % os.getpid())\n data = pd.DataFrame()\n for d in days:\n df = data_processing(d, codes)\n data = data.append(df)\n print(data.shape)\n data.to_csv('./data/temp/data_%02d.csv' % n)\n\ndef dataset(start=20180701, end=20181231, parallel_lines=12):\n codes = pd.read_csv('./data/code.csv', index_col=0)\n codes.loc[:, 'code'] = codes['code'].apply(lambda x: str(x).zfill(6))\n codes = codes.code.values\n\n df = pd.read_csv('./data/raw_data/target.csv', index_col=0)\n start = np.unique(df[df.date < start].date.values)[-106]\n\n target = read_target(start, end)\n date = np.unique(target.date.values)\n pd.DataFrame({'date': date}).to_csv('./data/date.csv')\n date = date[:-1]\n target.to_csv('./data/target.csv')\n\n if date.shape[0] < parallel_lines:\n parallel_lines = date.shape[0]\n\n n = date.shape[0] // parallel_lines\n k = date.shape[0] % parallel_lines\n p = Pool(parallel_lines)\n for i in range(k):\n p.apply_async(task, args=(i, date[i * (n + 1):(i + 1) * (n + 1)], codes))\n date2 = date[k*(n+1):]\n for i in range(k, parallel_lines):\n p.apply_async(task, args=(i, date2[(i-k)*n:(i-k+1)*n], codes))\n p.close()\n p.join()\n\n def generate_dataset():\n data = pd.DataFrame()\n for j in range(0, parallel_lines):\n df = pd.read_csv('./data/temp/data_%02d.csv' % j, index_col=0)\n data = data.append(df)\n print(data.shape)\n data.to_csv('./data/data.csv')\n\n generate_dataset()\n print('Finished!')\n\n return date.shape[0]\n\ndef data_processing(date, codes=['000002']):\n\n keys = ['totbid', 'totoff', 'vol', 'last', 'low', 'high', 'open']\n keys.extend(['bid' + str(x) for x in range(1, 11)])\n keys.extend(['ask' + str(x) for x in range(1, 11)])\n keys.extend(['bid_vol' + str(x) for x in range(1, 11)])\n keys.extend(['ask_vol' + str(x) for x in range(1, 11)])\n\n data = pd.DataFrame()\n\n df = read_data(date, codes, keys)\n t1 = time.time()\n for c in codes:\n temp = pd.DataFrame(df[c].values)\n temp.columns = keys\n temp['code'] = c\n\n if temp.isnull().sum().max() >= 4802:\n continue\n\n temp['vol'] = temp['vol'].diff().fillna(0)\n\n temp['ask'] = temp[['ask' + str(x) for x in range(1, 11)]].mean(axis=1)\n temp['bid'] = temp[['bid' + str(x) for x in range(1, 11)]].mean(axis=1)\n temp.drop(['ask' + str(x) for x in range(1, 11)], axis=1, inplace=True)\n temp.drop(['bid' + str(x) for x in range(1, 11)], axis=1, inplace=True)\n\n temp['ask_vol'] = temp[['ask_vol' + str(x) for x in range(1, 11)]].mean(axis=1)\n temp['bid_vol'] = temp[['bid_vol' + str(x) for x in range(1, 11)]].mean(axis=1)\n temp.drop(['ask_vol' + str(x) for x in range(1, 11)], axis=1, inplace=True)\n temp.drop(['bid_vol' + str(x) for x in range(1, 11)], axis=1, inplace=True)\n\n m_lst = ['last', 'bid', 'ask']\n for i in m_lst:\n temp[i+'_mean'] = temp[i].ewm(span=4).mean()\n temp.drop(i, axis=1, inplace=True)\n\n print('Finished %d data processing, cost %.3fs' % (date, time.time() - t1))\n return data\n\ndef read_data(date, codes=['000002'], keys=None):\n fp64_keys = keys[:3]\n fp32_keys = keys[3:]\n\n t1 = time.time()\n data = pd.DataFrame()\n for i in fp64_keys:\n df = foo.get_mem_data_by_tick(date, i, codes=codes, dtype='float64').astype('float32')\n data = pd.concat([data, df], axis=1)\n\n for i in fp32_keys:\n df = foo.get_mem_data_by_tick(date, i, codes=codes, dtype='float32')\n data = pd.concat([data, df], axis=1)\n\n print('Finished %d, cost %.3fs' % (date, time.time() - t1))\n return data\n\ndef read_target(start=20180701, end=20181231):\n df = pd.read_csv('./data/raw_data/target.csv', index_col=0)\n df.columns = ['date', 'code', 'change']\n\n target = pd.DataFrame()\n target = target.append(df[(start <= df.date) & (df.date <= end)])\n target['change'] = target['change'].apply(lambda x: x*100)\n\n return target\n\ndef get_data(i=0):\n data = pd.read_csv('./data/data.csv', index_col=0).groupby('code')\n target = pd.read_csv('./data/target.csv').groupby('code')\n\n codes = pd.read_csv('./data/r_code.csv', index_col=0).code.values\n x_train, y_train, x_test, y_test = [], [], [], []\n \n for c in codes:\n df = data.get_group(c)\n obj = target.get_group(c)\n\n df.drop('code', axis=1, inplace=True)\n\n df = df.fillna(method='bfill').fillna(method='ffill')\n df = df.apply(lambda x: (x - np.min(x[:(i+106)*49])) / (np.max(x[:(i+106)*49]) - np.min(x[:(i+106)*49])))\n \n for j in range(i+15, i+107):\n if j < i+105:\n x_train.append(df[(j-15)*49:j*49].values)\n y_train.append(obj['change'][j:j+1].values)\n elif j > i+105:\n x_test.append(df[(j-15)*49:j*49].values)\n y_test.append(obj['change'][j:j+1].values)\n\n x_train = np.array(x_train)\n y_train = np.array(y_train)\n y_train = y_train / 20 + 0.5\n y_train = np.clip(y_train, 0, 1)\n \n x_test = np.array(x_test)\n y_test = np.array(y_test)\n y_test = y_test / 20 + 0.5\n \n return x_train, y_train, x_test, y_test\n\nif __name__ == '__main__':\n start, end = 20190610, 20190731\n l = dataset(start, end, parallel_lines=12)\n\n data = pd.read_csv('./data/data.csv', index_col=0).groupby('code')\n\n codes = pd.read_csv('./data/code.csv', index_col=0).code.values\n r_codes = []\n for c in codes:\n try:\n\t df = data.get_group(c)\n except KeyError:\n continue\n\n if df.shape[0] < 49*l:\n continue\n r_codes.append(c)\n \n pd.DataFrame({'code': np.array(r_codes)}).to_csv('./data/r_code.csv')\n","sub_path":"load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"370433127","text":"#!/usr/bin/env python\n\n# return the % difference of two given images\n# only works with images of the same file type\n\nfrom PIL import Image, ImageChops, ImageStat\nfrom os import remove\n\ndiff_img_file = 'diff_img.jpg'\n\ndef diff(im1_file, \n im2_file, \n delete_diff_file=False, \n diff_img_file=diff_img_file):\n im1 = Image.open(im1_file)\n im2 = Image.open(im2_file)\n diff_img = ImageChops.difference(im1,im2)\n diff_img.convert('RGB').save(diff_img_file)\n stat = ImageStat.Stat(diff_img)\n # can be [r,g,b] or [r,g,b,a]\n sum_channel_values = sum(stat.mean)\n max_all_channels = len(stat.mean) * 100\n diff_ratio = sum_channel_values/max_all_channels\n if delete_diff_file:\n remove(diff_img_file)\n return diff_ratio\n","sub_path":"diffimg/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"460172714","text":"# ##### BEGIN GPL LICENSE BLOCK #####\r\n#\r\n# This program is free software; you can redistribute it and/or\r\n# modify it under the terms of the GNU General Public License\r\n# as published by the Free Software Foundation; either version 2\r\n# of the License, or (at your option) any later version.\r\n#\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with this program; if not, write to the Free Software Foundation,\r\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n#\r\n# ##### END GPL LICENSE BLOCK #####\r\n\r\n# \r\n\r\nbl_info = {\r\n \"name\": \"Export Materials to GLSL\",\r\n \"author\": \"Vitor Balbio & Sybren A. Stüvel\",\r\n \"version\": (1, 1),\r\n \"blender\": (2, 6, 0),\r\n \"api\": 40838,\r\n \"location\": \"Material Properties\",\r\n \"description\": \"Export one or more materials to GLSL Code\",\r\n \"warning\": \"\",\r\n \"wiki_url\": \"http://wiki.blender.org/index.php/Extensions:2.5/Py/Scripts/Game_Engine/Export_GLSL\",\r\n \"tracker_url\": \"http://projects.blender.org/tracker/index.php?func=detail&aid=28839&group_id=153&atid=467\",\r\n \"category\": \"Game Engine\"}\r\n\r\nimport bpy\r\nimport gpu\r\nimport os\r\n\r\n\r\nclass EXPORT_OT_GLSLmat(bpy.types.Operator):\r\n \"\"\"Export all materials of this scene to GLSL (.frag and .vert files) \"\"\"\r\n bl_idname = \"export.glslmat\"\r\n bl_label = \"Export Material To GLSL\"\r\n\r\n filepath = bpy.props.StringProperty(subtype=\"FILE_PATH\")\r\n\r\n def write_shader(self, scene, mat):\r\n \"\"\"Writes a shader for the given material to two GLSL files.\"\"\"\r\n\r\n shader = gpu.export_shader(scene, mat)\r\n\r\n path = os.path.join(self.filepath, \"mat_%s.%%s\" % mat.name)\r\n with open(path % \"frag\", \"w\") as frag:\r\n frag.write(shader[\"fragment\"])\r\n\r\n with open(path % \"vert\", \"w\") as vertex:\r\n vertex.write(shader[\"vertex\"])\r\n\r\n self.export_count += 1\r\n\r\n def execute(self, context):\r\n\r\n scene = bpy.context.scene\r\n materials = bpy.data.materials\r\n export_glsl_options = bpy.context.window_manager.exportGlslOptions\r\n\r\n self.filepath = os.path.dirname(self.filepath)\r\n self.export_count = 0\r\n\r\n print('Writing GLSL files to %s' % self.filepath)\r\n\r\n if export_glsl_options == \"ALL\":\r\n for mat in materials:\r\n self.write_shader(scene, mat)\r\n\r\n elif export_glsl_options == \"SELECTED\":\r\n for obj in bpy.context.selected_objects:\r\n print(' - exporting materials for object %s' % obj)\r\n for matsl in obj.material_slots:\r\n self.write_shader(scene, matsl.material)\r\n\r\n elif export_glsl_options == \"ACTIVE\":\r\n self.write_shader(scene, bpy.context.material)\r\n\r\n self.report({'INFO'}, 'Exported %i materials to GLSL files' % self.export_count)\r\n\r\n return {'FINISHED'}\r\n\r\n def invoke(self, context, event):\r\n context.window_manager.fileselect_add(self)\r\n return {'RUNNING_MODAL'}\r\n\r\n\r\nclass GlslExportPanel(bpy.types.Panel):\r\n bl_idname = \"Export_Material2GLSL\"\r\n bl_label = \"Export Material To GLSL\"\r\n bl_space_type = 'PROPERTIES'\r\n bl_region_type = 'WINDOW'\r\n bl_context = \"material\"\r\n\r\n bpy.types.WindowManager.exportGlslOptions = bpy.props.EnumProperty(\r\n name=\"Export\",\r\n description=\"\",\r\n items=((\"ALL\", \"All Materials\", \"Export all materials from all scenes\"),\r\n (\"SELECTED\", \"Selected Object Materials \",\r\n \"Export all materials from the selected objects\"),\r\n (\"ACTIVE\", \"Active Material\", \"Export just this active material\")),\r\n default=\"ALL\")\r\n\r\n def draw(self, context):\r\n self.layout.prop(context.window_manager, \"exportGlslOptions\")\r\n self.layout.operator(\"export.glslmat\")\r\n\r\n\r\ndef register():\r\n bpy.utils.register_class(EXPORT_OT_GLSLmat)\r\n bpy.utils.register_class(GlslExportPanel)\r\n\r\n\r\ndef unregister():\r\n bpy.utils.unregister_class(EXPORT_OT_GLSLmat)\r\n bpy.utils.unregister_class(GlslExportPanel)\r\n","sub_path":".config/blender/2.75/scripts/addons/game_export_GLSL_Shader.py","file_name":"game_export_GLSL_Shader.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"477204836","text":"from os.path import exists as __exists, join as __join\n\ndeck_folder_path = \"./deck/\"\n\n\ndef __filter_card_id(cards: list[str]):\n \"\"\"Filters an list with card ids to remove\n repeating ones and non-ids\"\"\"\n\n ids = list()\n for c in cards:\n try:\n int(c)\n except Exception:\n pass\n else:\n if c not in ids:\n ids.append(c)\n return ids\n\n\ndef get_deck(deck_name: str):\n \"\"\"Reads a deck file and returns the\n ids of the cards in it\"\"\"\n\n deck_path = __join(deck_folder_path, f\"{deck_name}.ydk\")\n deck_exists = __exists(deck_path)\n if not deck_exists:\n return None\n deck = open(deck_path, mode=\"r\", encoding=\"utf8\")\n cards = __filter_card_id([l.strip() for l in deck.readlines()])\n return cards\n","sub_path":"deckread.py","file_name":"deckread.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"537789982","text":"class ProtocolDef(object):\n\n def __init__(self, ether_type, transport_type, port):\n self.ether_type = ether_type\n self.transport_type = transport_type\n self.port = port\n self.key = int(str(self.ether_type) + str(self.transport_type) + str(self.port))\n\n\nclass BaseHandler(object):\n\n # http://www.iana.org/assignments/ieee-802-numbers/ieee-802-numbers.xhtml\n # http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml\n def __init__(self, protocol_def, display_col):\n self.protocol_def = protocol_def\n self.display_col = display_col","sub_path":"handlers/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"597702038","text":"import sys\nfrom time import sleep\nimport pygame\nfrom utils import fleet_utils, shooting_utils\n\n\ndef check_keydown_events(event, ai_settings, screen, stats, sb, ship, aliens, bullets):\n if event.key == pygame.K_RIGHT:\n ship.moving_right = True\n\n elif event.key == pygame.K_LEFT:\n ship.moving_left = True\n\n elif event.key == pygame.K_SPACE:\n shooting_utils.fire_bullet(ai_settings, screen, ship, bullets)\n\n elif event.key == pygame.K_q:\n sys.exit()\n\n elif event.key == pygame.K_p:\n start_game(ai_settings, screen, stats, sb, ship, aliens, bullets)\n\n\ndef check_keyup_events(event, ship):\n if event.key == pygame.K_RIGHT:\n ship.moving_right = False\n elif event.key == pygame.K_LEFT:\n ship.moving_left = False\n\n\ndef check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n check_keydown_events(event, ai_settings, screen, stats, sb, ship, aliens, bullets)\n\n elif event.type == pygame.KEYUP:\n check_keyup_events(event, ship)\n\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mouse_x, mouse_y = pygame.mouse.get_pos()\n check_play_button(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y)\n\n\ndef check_play_button(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y):\n button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)\n if button_clicked and not stats.game_active:\n start_game(ai_settings, screen, stats, sb, ship, aliens, bullets)\n\n\ndef start_game(ai_settings, screen, stats, sb, ship, aliens, bullets):\n ai_settings.initialize_dynamic_settings()\n pygame.mouse.set_visible(False)\n stats.reset_stats()\n stats.game_active = True\n\n sb.prep_score()\n sb.prep_high_score()\n sb.prep_level()\n sb.prep_ships()\n\n aliens.empty()\n bullets.empty()\n\n fleet_utils.create_fleet(ai_settings, screen, ship, aliens)\n ship.center_ship()\n\n\ndef update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button, aliens_bullets):\n screen.fill(ai_settings.bg_color)\n for bullet in bullets.sprites():\n bullet.draw_bullet()\n ship.blitme()\n aliens.draw(screen)\n if fleet_utils.get_number_rows == 1:\n for alien_bullet in aliens_bullets.sprites():\n alien_bullet.draw_aliens_bullets()\n sb.show_score()\n\n if not stats.game_active:\n play_button.draw_button()\n\n pygame.display.flip()\n\n\ndef ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets):\n if stats.ships_left > 0:\n stats.ships_left -= 1\n\n sb.prep_ships()\n\n aliens.empty()\n bullets.empty()\n\n fleet_utils.create_fleet(ai_settings, screen, ship, aliens)\n ship.center_ship()\n\n sleep(0.5)\n else:\n stats.game_active = False\n pygame.mouse.set_visible(True)\n\n\ndef check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets):\n screen_rect = screen.get_rect()\n for alien in aliens.sprites():\n if alien.rect.bottom >= screen_rect.bottom:\n ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets)\n break\n\n\ndef update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets):\n fleet_utils.check_fleet_edges(ai_settings, aliens)\n aliens.update()\n if pygame.sprite.spritecollideany(ship, aliens):\n ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets)\n check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets)\n\n","sub_path":"game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"39583902","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.model_zoo as model_zoo\n\nmodel_urls = {\n 'resnet18':\n 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34':\n 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50':\n 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101':\n 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152':\n 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n 'resnext50_32x4d':\n 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',\n 'resnext101_32x8d':\n 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',\n 'wide_resnet50_2':\n 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',\n 'wide_resnet101_2':\n 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',\n}\n\n\nclass FixedBatchNorm(nn.BatchNorm2d):\n def forward(self, input):\n return F.batch_norm(input,\n self.running_mean,\n self.running_var,\n self.weight,\n self.bias,\n training=False,\n eps=self.eps)\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes,\n out_planes,\n kernel_size=3,\n stride=stride,\n padding=1,\n bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self,\n inplanes,\n planes,\n stride=1,\n downsample=None,\n dilation=1):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n self.dilation = dilation\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self,\n inplanes,\n planes,\n stride=1,\n downsample=None,\n dilation=1):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = FixedBatchNorm(planes)\n self.conv2 = nn.Conv2d(planes,\n planes,\n kernel_size=3,\n stride=stride,\n padding=dilation,\n bias=False,\n dilation=dilation)\n self.bn2 = FixedBatchNorm(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = FixedBatchNorm(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n self.dilation = dilation\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self,\n block,\n layers,\n strides=(2, 2, 2, 2),\n dilations=(1, 1, 1, 1)):\n self.inplanes = 64\n super(ResNet, self).__init__()\n self.conv1 = nn.Conv2d(3,\n 64,\n kernel_size=7,\n stride=strides[0],\n padding=3,\n bias=False)\n self.bn1 = FixedBatchNorm(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block,\n 64,\n layers[0],\n stride=1,\n dilation=dilations[0])\n self.layer2 = self._make_layer(block,\n 128,\n layers[1],\n stride=strides[1],\n dilation=dilations[1])\n self.layer3 = self._make_layer(block,\n 256,\n layers[2],\n stride=strides[2],\n dilation=dilations[2])\n self.layer4 = self._make_layer(block,\n 512,\n layers[3],\n stride=strides[3],\n dilation=dilations[3])\n self.inplanes = 1024\n\n def _make_layer(self, block, planes, blocks, stride=1, dilation=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes,\n planes * block.expansion,\n kernel_size=1,\n stride=stride,\n bias=False),\n FixedBatchNorm(planes * block.expansion),\n )\n\n layers = [block(self.inplanes, planes, stride, downsample, dilation=1)]\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, dilation=dilation))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n return x\n\n\ndef resnet18(pretrained=True, **kwargs):\n \"\"\"\n >>> import torch\n >>> x = torch.randn((2, 3, 512, 512))\n >>> y = resnet18()(x)\n >>> assert y.shape == torch.Size([2, 512, 16, 16])\n \"\"\"\n model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)\n if pretrained:\n state_dict = model_zoo.load_url(model_urls['resnet18'])\n state_dict.pop('fc.weight')\n state_dict.pop('fc.bias')\n model.load_state_dict(state_dict)\n return model\n\n\ndef resnet34(pretrained=True, **kwargs):\n \"\"\"\n >>> import torch\n >>> x = torch.randn((2, 3, 512, 512))\n >>> y = resnet34()(x)\n >>> assert y.shape == torch.Size([2, 512, 16, 16])\n \"\"\"\n model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)\n if pretrained:\n state_dict = model_zoo.load_url(model_urls['resnet34'])\n state_dict.pop('fc.weight')\n state_dict.pop('fc.bias')\n model.load_state_dict(state_dict)\n return model\n\n\ndef resnet50(pretrained=True, **kwargs):\n \"\"\"\n >>> import torch\n >>> x = torch.randn((2, 3, 512, 512))\n >>> y = resnet50()(x)\n >>> assert y.shape == torch.Size([2, 2048, 16, 16])\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)\n if pretrained:\n state_dict = model_zoo.load_url(model_urls['resnet50'])\n state_dict.pop('fc.weight')\n state_dict.pop('fc.bias')\n model.load_state_dict(state_dict)\n return model\n\n\ndef resnet101(pretrained=True, **kwargs):\n \"\"\"\n >>> import torch\n >>> x = torch.randn((2, 3, 512, 512))\n >>> y = resnet101()(x)\n >>> assert y.shape == torch.Size([2, 2048, 16, 16])\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)\n if pretrained:\n state_dict = model_zoo.load_url(model_urls['resnet101'])\n state_dict.pop('fc.weight')\n state_dict.pop('fc.bias')\n model.load_state_dict(state_dict)\n return model\n\n\ndef resnet152(pretrained=True, **kwargs):\n \"\"\"\n >>> import torch\n >>> x = torch.randn((2, 3, 512, 512))\n >>> y = resnet152()(x)\n >>> assert y.shape == torch.Size([2, 2048, 16, 16])\n \"\"\"\n model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)\n if pretrained:\n state_dict = model_zoo.load_url(model_urls['resnet152'])\n state_dict.pop('fc.weight')\n state_dict.pop('fc.bias')\n model.load_state_dict(state_dict)\n return model\n\n\nif __name__ == '__main__':\n import doctest\n\n doctest.testmod()\n","sub_path":"wsl_survey/segmentation/irn_unique/net/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":9093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"629063820","text":"from ..nodes import TestNode\nfrom ..teensy_libs import FlexCAN\n\ndef test_register(virtualbus):\n node = TestNode()\n node.CANbus.set_bus(virtualbus)\n\n fc = FlexCAN(500000, virtualbus)\n fc.begin()\n\n node.setup()\n\n assert fc.available() == 1\n","sub_path":"systems/tests/test_node.py","file_name":"test_node.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"489560493","text":"# Q002\n# Created by JKChang\n# 16/02/2017, 21:16\n# Tag: recursion\n# Description: Write a program which can compute the factorial of a given numbers.\n# The results should be printed in a comma-separated sequence on a single line.\n# Suppose the following input is supplied to the program:\n#\n# Suppose the following input is supplied to the program:\n# 8\n# Then, the output should be:\n# 40320\n\ndef fact(x):\n if x == 0:\n return 1\n return fact(x - 1) * x\n\nx = int(input('pls input a number: '))\nprint(fact(x))\n","sub_path":"100 python/Q002.py","file_name":"Q002.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"410367666","text":"class MainPage(webapp.RequestHandler):\n \n def render_template(self, filename, context={}):\n path = os.path.join(os.path.dirname(__file__), filename)\n self.response.out.write(template.render(path, context))\n \n def get(self):\n # Disable the reflected XSS filter for demonstration purposes\n self.response.headers.add_header(\"X-XSS-Protection\", \"0\")\n \n if not self.request.get('timer'):\n # Show main timer page\n self.render_template('index.html')\n else:\n # Show the results page\n timer= self.request.get('timer', 0)\n self.render_template('timer.html', { 'timer' : timer })\n \n return\n \napplication = webapp.WSGIApplication([ ('.*', MainPage), ], debug=False)\n","sub_path":"level4/level.py","file_name":"level.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"210809118","text":"import torch\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, get_worker_info\nfrom tqdm import tqdm\n\nfrom word2vec.data_reader import DataReader, Word2vecDataset\nfrom word2vec.model import SkipGramModel\n\n\nclass Word2VecTrainer:\n def __init__(self, input_file, output_file, emb_dimension=100, batch_size=32, window_size=5, iterations=3,\n initial_lr=0.001, min_count=12, num_workers=0, collate_fn='custom', iprint=500, t=1e-3, ns_exponent=0.75, \n optimizer='adam', optimizer_kwargs = None, warm_start_model = None, lr_schedule = True, sparse = True):\n\n\n self.data = DataReader(input_file, min_count,t=t, ns_exponent=ns_exponent)\n dataset = Word2vecDataset(self.data, window_size)\n if collate_fn == 'custom':\n collate_fn = dataset.collate\n else:\n collate_fn = None\n self.dataloader = DataLoader(dataset, batch_size=batch_size,\n shuffle=False, num_workers=num_workers, \n collate_fn=collate_fn, worker_init_fn=dataset.worker_init_fn)\n\n self.output_file_name = output_file\n self.emb_size = len(self.data.word2id)\n self.emb_dimension = emb_dimension\n self.iprint = iprint\n self.batch_size = batch_size\n self.iterations = iterations\n self.initial_lr = initial_lr\n self.skip_gram_model = SkipGramModel(self.emb_size, self.emb_dimension, sparse = sparse)\n\n if warm_start_model is not None:\n self.skip_gram_model.load_state_dict(torch.load(warm_start_model), strict=False)\n self.optimizer = optimizer\n if optimizer_kwargs is None:\n optimizer_kwargs = {}\n self.optimizer_kwargs = optimizer_kwargs\n self.lr_schedule = lr_schedule\n self.use_cuda = torch.cuda.is_available()\n self.device = torch.device(\"cuda\" if self.use_cuda else \"cpu\")\n if self.use_cuda:\n self.skip_gram_model.cuda()\n\n def train(self):\n if self.optimizer == 'adam':\n optimizer = optim.Adam(self.skip_gram_model.parameters(), lr=self.initial_lr, **self.optimizer_kwargs)\n elif self.optimizer == 'sparse_adam':\n optimizer = optim.SparseAdam(self.skip_gram_model.parameters(), lr=self.initial_lr, **self.optimizer_kwargs)\n elif self.optimizer == 'sgd':\n optimizer = optim.SGD(self.skip_gram_model.parameters(), lr=self.initial_lr, **self.optimizer_kwargs)\n elif self.optimizer == 'asgd':\n optimizer = optim.ASGD(self.skip_gram_model.parameters(), lr=self.initial_lr, **self.optimizer_kwargs)\n elif self.optimizer == 'adagrad':\n optimizer = optim.Adagrad(self.skip_gram_model.parameters(), lr=self.initial_lr, **self.optimizer_kwargs)\n else:\n raise Exception('Unknown optimizer!')\n\n for iteration in range(self.iterations):\n\n print(\"\\n\\n\\nIteration: \" + str(iteration + 1))\n\n if self.lr_schedule:\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, len(self.dataloader))\n running_loss = 0.0\n iprint = len(self.dataloader) // 20\n for i, sample_batched in enumerate(tqdm(self.dataloader)):\n\n if len(sample_batched[0]) > 1:\n pos_u = sample_batched[0].to(self.device)\n pos_v = sample_batched[1].to(self.device)\n neg_v = sample_batched[2].to(self.device)\n \n optimizer.zero_grad()\n loss = self.skip_gram_model.forward(pos_u, pos_v, neg_v)\n loss.backward()\n optimizer.step()\n if self.lr_schedule:\n scheduler.step()\n\n running_loss = running_loss * (1 - 5/iprint) + loss.item() * (5/iprint)\n if i > 0 and i % iprint == 0:\n print(\" Loss: \" + str(running_loss) + ' lr: ' \n + str([param_group['lr'] for param_group in optimizer.param_groups]))\n print(\" Loss: \" + str(running_loss))\n\n self.skip_gram_model.save_embedding(self.data.id2word, self.output_file_name)\n \n\n\nif __name__ == '__main__':\n w2v = Word2VecTrainer(input_file=\"input.txt\", output_file=\"out.vec\")\n w2v.train()\n","sub_path":"word2vec/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":4379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"391572083","text":"import math\nimport pytest\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\n@pytest.fixture(scope=\"function\")\ndef browser():\n browser = webdriver.Chrome()\n browser.implicitly_wait(20)\n yield browser\n browser.quit()\n\n\n@pytest.fixture(scope=\"function\")\ndef get_answer():\n\tanswer = math.log(int(time.time()))\n\tprint(str(answer))\n\treturn str(answer)\n\n\n@pytest.mark.parametrize('lesson_id', \n\t[\"236895\", \"236896\", \"236897\", \"236898\", \"236899\", \"236903\", \"236904\", \"236905\"])\ndef test_user_should_get_correct_optional_feedback(browser, get_answer, lesson_id):\n\tlink = f\"https://stepik.org/lesson/{lesson_id}/step/1\"\n\tbrowser.get(link)\n\n\tWebDriverWait(browser, 20).until(EC.visibility_of_element_located(\n\t\t(By.CSS_SELECTOR, \".ember-text-area.ember-view.textarea.string-quiz__textarea\"))).send_keys(get_answer)\n\n\tWebDriverWait(browser, 20).until(EC.element_to_be_clickable(\n\t\t(By.CSS_SELECTOR, \".submit-submission\"))).click()\n\n\toptional_feedback = WebDriverWait(browser, 20).until(EC.visibility_of_element_located(\n\t\t(By.CSS_SELECTOR, \".smart-hints__hint\"))).text\n\n\tassert optional_feedback == \"Correct!\", f\"Otional feedback is incorrect on page {link}\"\n","sub_path":"selenium_course/chapter3/lesson6_step3.py","file_name":"lesson6_step3.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"476817030","text":"import numpy as np\n\n\nclass EpsGreedy:\n def __init__(self, epsilon, eps_decay, officers, events):\n super().__init__()\n # Set number of arms\n self.narms = 0\n # Exploration probability\n self.epsilon = epsilon\n # Decay rate\n self.eps_decay = eps_decay\n # Total step count\n self.step_n = 0\n\n # officers and events\n self.officers = officers\n self.events = events\n\n # Play one round and return the action (chosen arm)\n def play(self, tround, context=None):\n # Generate random number\n p = np.random.rand()\n\n # Edge case, epsilon = 0, and the first step, we still random\n if self.epsilon == 0 and self.step_n == 0:\n action = self.random_action()\n\n # This case, it goes exploration\n elif p < self.epsilon:\n action = self.random_action()\n # Here, it goes exploitation\n else:\n arm = self.AM_reward.argMax()\n action = np.fromstring(arm, dtype=int).reshape((self.events.num_event, self.events.num_task))\n\n self.tround = tround\n # get the chosen arm\n self.arm = action.tostring()\n self.action = action\n\n self.epsilon = max(0, self.epsilon - self.eps_decay)\n\n # print(\"Action chosen: \\n{}\".format(self.action))\n return action\n\n def random_action(self):\n action = np.random.randint(0, self.officers.num_officer,\n size=(self.events.num_event, self.events.num_task))\n return action\n\n def update(self, action, reward, context=None):\n # get the context (may be None)\n self.context = context\n # update the overall step of the model\n self.step_n += 1\n # update the step of individual arms\n self.step_arm[self.arm] += 1\n # update average mean reward of each arm\n self.AM_reward[self.arm] = ((self.step_arm[self.arm] - 1)\n / float(self.step_arm[self.arm])\n * self.AM_reward[self.arm]\n + (1 / float(self.step_arm[self.arm])) * reward)\n","sub_path":"agents.py","file_name":"agents.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"115294111","text":"import urllib.request as ur\nfrom tkinter import *\n\n# Auf boerse.ard.de spezifische URL des gewünschten Aktienkurses\n# Elemente können beliebig hinzugefügt werden, müssen allerdings auch\n# zu original_price_list sowie amount_list hinzugefügt werden\nsymbols_list = [\"96056\", \"97183\", \"113397\", \"2588247\", \"107654\"]\n# Preis zu dem die Aktie gekauft wurde\noriginal_price_list = [80.5, 60.75, 129.2, 35.04, 23.189]\n# Anzahl der Aktien die gekauft wurden\namount_list = [100, 30, 12, 95, 70]\n\ntotal_change_list = []\nprice_list = []\npercent_list = []\nchange_list = []\nname_list = []\n\n\n# Erstellen der UI\nroot = Tk()\nroot.wm_title(\"PythonScripts\")\nroot.resizable(width=FALSE, height=FALSE)\n\n\n# Aktienkurse von boerse.ard.de abfragen\n# price_list zeigt aktuellen Kurs an\n# percent_list zeigt Kurs des Vortages\n# change_list zeigt prozentuale Änderung\n# name_list zeigt Name der Aktie an\ndef main():\n price_list.clear()\n percent_list.clear()\n change_list.clear()\n total_change_list.clear()\n\n # Speichert gesamtes HTML Dokument in htmltext\n # regex sucht nach Wert zwischen den angegebenen Tags und Zeichen\n # speichern des Werts in priceList sowie percentList\n i = 0\n while i < len(symbols_list):\n url = \"http://kurse.boerse.ard.de/ard/kurse_einzelkurs_uebersicht.htn?i=\" + symbols_list[i]\n htmlfile = ur.urlopen(url)\n htmltext = htmlfile.read().decode('utf8')\n\n regex = ' (.+?) €'\n pattern = re.compile(regex)\n price_list.extend(re.findall(pattern, htmltext))\n\n regex = '(.+?) €'\n pattern_percent = re.compile(regex)\n percent_list.extend(re.findall(pattern_percent, htmltext))\n\n regex = '

News zu (.+?)

'\n patter_name = re.compile(regex)\n name_list.extend(re.findall(patter_name, htmltext))\n i += 1\n\n # Berechnung der Prozentualen Änderung des Kurses\n # Aktueller Kurs - Kurs des Vortags / 100\n i = 0\n while i < len(price_list):\n new = read_float_with_comma(price_list[i])\n old = read_float_with_comma(percent_list[i])\n result = (new - old)\n change_list.append(result)\n result_total = (new * amount_list[i]) - (original_price_list[i] * amount_list[i])\n total_change_list.append(result_total)\n i += 1\n\n # Erstellen des Labels am oberen Rand\n top_label = Label(root, text=\"Aktienkurse\")\n top_label.grid(row=0, column=1, pady=(0, 20), padx=(0, 20))\n\n total = sum(total_change_list)\n if total > 0:\n total_label = Label(root, text=str(\"+\" + \"{0:.2f}\".format(total) + \"€\"), fg=\"green\")\n else:\n if total < 0:\n total_label = Label(root, text=str(\"{0:.2f}\".format(total) + \"€\"), fg=\"red\")\n else:\n total_label = Label(root, text=str(\"{0:.2f}\".format(total) + \"€\"))\n total_label.grid(row=0, column=2, pady=(0, 20))\n\n # Automatisches erstellen der UI\n i = 0\n while i < len(price_list):\n stock_label = Label(root, text=str(name_list[i]))\n stock_label.grid(row=i+1)\n stock_price = Label(root, text=str(price_list[i]) + \"€\")\n stock_price.grid(row=i+1, column=1)\n\n # Wenn die tägliche Änderung positiv ist grüner Text\n # Bei negativer Änderung roter Text\n # Bei 0 schwarzer Text\n if change_list[i] > 0:\n stock_change = Label(root, text=str(\"+\" + \"{0:.2f}\".format(change_list[i]) + \"€\"), fg=\"green\")\n else:\n if change_list[i] < 0:\n stock_change = Label(root, text=str(\"{0:.2f}\".format(change_list[i]) + \"€\"), fg=\"red\")\n else:\n stock_change = Label(root, text=str(\"{0:.2f}\".format(change_list[i])) + \"€\")\n stock_change.grid(row=i+1, column=2)\n\n # Gibt die gesamte Änderung unter Einbeziehung der Besitzanteile und des Kaufkurses wieder\n # Positiv = Grün, Negativ = Rot, Neutral = Schwarz\n if total_change_list[i] > 0:\n stock_total_change = Label(root, text=str(\"+\" + \"{0:.2f}\".format(total_change_list[i]) + \"€\"), fg=\"green\")\n else:\n if total_change_list[i] < 0:\n stock_total_change = Label(root, text=str(\"{0:.2f}\".format(total_change_list[i]) + \"€\"), fg=\"red\")\n else:\n stock_total_change = Label(root, text=str(\"{0:.2f}\".format(total_change_list[i])) + \"€\")\n stock_total_change.grid(row=i+1, column=3, padx=(20, 0))\n i += 1\n\n # Erstellen des Buttons welcher zum Neustarten des main() loops verwendet wird\n # Aktualisieren der aktuellen Börsenkurse\n button_restart = Button(root, text=\"Aktualisieren\", command=main)\n button_restart.grid(row=7, column=0, columnspan=4, pady=(20, 0), padx=(0, 0))\n\n root.mainloop()\n\n\n# Gibt den erhaltenen String als float zurück\n# Ersetzt hierbei \",\" durch \".\" um den Wert zu transformieren\ndef read_float_with_comma(num):\n return float(num.replace(\",\", \".\"))\n\n# Ruft die main() Funktion auf\nif __name__ == '__main__':\n main()\n","sub_path":"StockScraper.py","file_name":"StockScraper.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"347954686","text":"from server import db, app\nimport datetime\nimport jwt\n\n\nclass Patient(db.Model):\n id = db.Column(db.String(20), primary_key=True)\n firstNames = db.Column(db.String(40))\n lastNames = db.Column(db.String(40))\n gender = db.Column(db.String(8))\n dateOfBirth = db.Column(db.String(20))\n\n ehrId = db.Column(db.String(20))\n Personnummer = db.Column(db.String(13))\n\n pulse = db.Column(db.Integer)\n oxSaturation = db.Column(db.Integer)\n sysBloodPressure = db.Column(db.Integer)\n diaBloodPressure = db.Column(db.Integer)\n\n breathingFreq = db.Column(db.Integer)\n alertness = db.Column(db.String(10))\n bodyTemp = db.Column(db.Float)\n\n def serialize(self):\n return {\n 'demographics': {\n 'id': self.id,\n 'firstNames': self.firstNames,\n 'lastNames': self.lastNames,\n 'gender': self.gender,\n 'dateOfBirth': self.dateOfBirth,\n 'additionalInfo': {\n 'ehrId': self.ehrId,\n 'Personnummer': self.Personnummer\n }\n },\n 'vital_signs': {\n 'body_temperature': [\n {\n 'any_event': [\n {\n 'temperature': [\n {\n '|magnitude': self.bodyTemp,\n '|unit': '°C'\n }\n ]\n }\n ]\n }\n ],\n 'blood_pressure': [\n {\n 'any_event': [\n {\n 'systolic': [\n {\n '|unit': 'mm[Hg]',\n '|magnitude': self.sysBloodPressure\n }\n ],\n 'diastolic': [\n {\n '|unit': 'mm[Hg]',\n '|magnitude': self.diaBloodPressure\n }\n ],\n 'position': [\n {\n '|code': 'at1001',\n '|value': 'Sitting'\n }\n ]\n }\n ]\n }\n ]\n },\n 'pulse': self.pulse,\n 'oxygen_saturation': self.oxSaturation,\n 'breathing_frequency': self.breathingFreq,\n 'alertness': self.alertness\n }\n\n def short_form(self):\n return {\n 'firstNames': self.firstNames,\n 'lastNames': self.lastNames,\n 'pid': self.Personnummer,\n 'ehrId': self.ehrId\n }\n\n\nclass Staff(db.Model):\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n username = db.Column(db.String(20), unique=True)\n password = db.Column(db.String(20))\n firstNames = db.Column(db.String(40))\n lastNames = db.Column(db.String(40))\n position = db.Column(db.String(20))\n\n def serialize(self):\n return {\n 'firstNames': self.firstNames,\n 'lastNames': self.lastNames,\n 'position': self.position\n }\n\n def short_form(self):\n return {\n 'username': self.username,\n 'password': self.password\n }\n\n def encode_token(self, user_id):\n payload = {\n 'exp' : datetime.datetime.utcnow() + datetime.timedelta(days=0,seconds=60, hours=1),\n 'iat' : datetime.datetime.utcnow(),\n 'sub' : user_id\n }\n return jwt.encode(\n payload,\n app.config.get('SECRET_KEY'),\n algorithm='HS256'\n )\n\n @staticmethod\n def decode_token(token):\n try:\n payload = jwt.decode(token, app.config.get('SECRET_KEY'))\n if BlacklistToken.check_blacklist(token):\n return 'Blacklisted token please log in again.'\n else:\n return payload['sub']\n except jwt.ExpiredSignatureError:\n return 'Token expired please log in again'\n except jwt.InvalidTokenError:\n return 'Invalid token'\n\n\nclass BlacklistToken(db.Model):\n id = db.Column(db.Integer,primary_key=True, autoincrement=True)\n token = db.Column(db.String(500), unique=True, nullable=False)\n blacklisted_on = db.Column(db.DateTime, nullable=False)\n\n def __init__(self,token):\n self.token = token\n self.blacklisted_on = datetime.datetime.now()\n\n @staticmethod\n def check_blacklist(token):\n res = BlacklistToken.query.filter_by(token=str(token)).first()\n if res:\n return True\n else:\n return False\n\n","sub_path":"Backend/server/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"124250694","text":"import numpy as np\nimport copy\nimport math\n\nclass Matrix:\n def identityMat4x4():\n data = np.zeros((4,4))\n for i in range(0,4):\n data[i][i]=1\n\n return data\n\n def linear(data):\n #ldata = copy.deepcopy(data[0:3,0:3])\n ldata = data[0:3,0:3]\n return ldata\n\n def col(data,i):\n #cData = copy.deepcopy(data[0:,i])\n cData = data[0:,i]\n return cData\n\n def UnitY():\n data = np.zeros((1,3))\n data[0][1] = 1\n\n return data\n\n def size(data):\n sum = 0\n for i in range(0,3):\n #print(i)\n sum = sum + data[i]*data[i]\n #print(sum)\n #print(sum)\n #quit()\n sum = math.sqrt(sum)\n\n return sum\n\n def normalize(data):\n #print(data)\n \n result = []\n sum = Matrix.size(data)\n if np.abs(sum) < 1e-6:\n print(data)\n input()\n sum = 1\n for i in data:\n result.append(i/sum)\n \n return result\n def size_2D(data):\n sum = 0\n for i in data:\n for j in i:\n sum = sum + j*j\n #print(sum)\n #quit()\n sum = math.sqrt(sum)\n return sum\n \n def normalize_2D(data):\n result = []\n sum = Matrix.size_2D(data)\n for i in data:\n for j in i:\n result.append(j/sum)\n #print(\"555\")\n\n #print(result)\n\n return result\n def setTranslation(data, trans):\n data[0:3,3] = trans\n\n def setlinearCol(data, i, setData):\n #print(setData)\n #quit()\n data[0:3,i] = setData\n\n def getTranslation(data):\n #return copy.deepcopy(data[0:3,3])\n return data[0:3,3]\n\n def multTrans(transM, pos):\n pos = np.append(pos,1)\n pos =np.dot(transM, pos)\n return pos[0:3]\n\n def getNormal(a,b,c):\n ab = np.subtract(b,a)\n ac = np.subtract(c,a)\n nor = np.cross(ab,ac)\n nnor = Matrix.normalize(nor)\n\n return nnor\n\nif __name__ == \"__main__\":\n data = Matrix.identityMat4x4()\n data2 =Matrix.linear(data)\n print(data)\n print(data2)\n data2[1][0] = 3\n \n data3 = Matrix.col(data2,0)\n data3[0]=5\n print(data)\n print(data2)\n print(data3) \n\n Unityy = Matrix.UnitY()\n\n print(Unityy)\n \n data4=Matrix.normalize(data3)\n print(data3)\n print(data4)\n\n newData = Matrix.identityMat4x4()\n\n trans = [3,5,7]\n xx = [1,2,3]\n yy = [4,5,6]\n zz = [7,8,9]\n\n xx = Matrix.normalize(xx)\n\n Matrix.setTranslation(newData,trans)\n\n Matrix.setlinearCol(newData,0,xx)\n Matrix.setlinearCol(newData,1,yy)\n Matrix.setlinearCol(newData,2,zz)\n\n print(newData)\n\n trrr = Matrix.getTranslation(newData)\n\n print(trrr)\n\n","sub_path":"gym-foo/cMat.py","file_name":"cMat.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"498629282","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2010-2015 Mag. Christian Tanzer All rights reserved\n# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at\n# ****************************************************************************\n# This module is part of the package TFL.\n#\n# This module is licensed under the terms of the BSD 3-Clause License\n# .\n# ****************************************************************************\n#\n#++\n# Name\n# TFL.Url\n#\n# Purpose\n# Model a URL and its parts\n#\n# Revision Dates\n# 23-Jun-2010 (CT) Creation\n# 24-Jun-2010 (CT) `new` added\n# 24-Jun-2010 (CT) Optional argument `fs_path` added\n# 13-Jul-2010 (CT) `__contains__` and `split` added\n# 13-Jul-2010 (CT) `__init__` changed to accept `Url` instance as `value`\n# 28-Jan-2013 (CT) Add `abs_path`\n# 16-Oct-2015 (CT) Add `__future__` imports\n# ««revision-date»»···\n#--\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom _TFL import TFL\nfrom _TFL.pyk import pyk\n\nfrom _TFL.Regexp import *\n\nimport _TFL._Meta.Object\nimport _TFL._Meta.Once_Property\n\nimport _TFL.Accessor\nimport _TFL.Record\n\nclass Url (TFL.Meta.Object) :\n \"\"\"Model a URL and its parts as defined by RFC 3986.\n\n >>> Url (\"http://www.ics.uci.edu/pub/ietf/uri/#Related\")\n Url (authority = 'www.ics.uci.edu', fragment = 'Related', path = '/pub/ietf/uri/', query = '', scheme = 'http')\n >>> Url (\"scheme://username:password@domain:port/path?foo=bar#anchor\")\n Url (authority = 'username:password@domain:port', fragment = 'anchor', path = '/path', query = 'foo=bar', scheme = 'scheme')\n >>> Url (\"foo://example.com:8042/over/there?name=ferret#nose\")\n Url (authority = 'example.com:8042', fragment = 'nose', path = '/over/there', query = 'name=ferret', scheme = 'foo')\n >>> Url (\"/tmp/foo.bar\")\n Url (authority = '', fragment = '', path = '/tmp/foo.bar', query = '', scheme = '')\n >>> Url (\"http://a/b/c/g;x?y#s\")\n Url (authority = 'a', fragment = 's', path = '/b/c/g;x', query = 'y', scheme = 'http')\n >>> Url (\"ftp://cnn.example.com&story=breaking_news@10.0.0.1/top_story.htm\")\n Url (authority = 'cnn.example.com&story=breaking_news@10.0.0.1', fragment = '', path = '/top_story.htm', query = '', scheme = 'ftp')\n\n >>> Url (\"sqlite://\")\n Url (authority = '', fragment = '', path = '', query = '', scheme = 'sqlite')\n >>> Url (\"sqlite:///foo.db\")\n Url (authority = '', fragment = '', path = '/foo.db', query = '', scheme = 'sqlite')\n >>> Url (\"sqlite:////foo.db\")\n Url (authority = '', fragment = '', path = '//foo.db', query = '', scheme = 'sqlite')\n\n >>> Url (\"postgresql://scott:tiger@localhost/mydatabase\")\n Url (authority = 'scott:tiger@localhost', fragment = '', path = '/mydatabase', query = '', scheme = 'postgresql')\n >>> Url (\"postgresql+pg8000://scott:tiger@localhost/mydatabase\")\n Url (authority = 'scott:tiger@localhost', fragment = '', path = '/mydatabase', query = '', scheme = 'postgresql+pg8000')\n\n >>> Url (\"hps://test.foo\")\n Url (authority = 'test.foo', fragment = '', path = '', query = '', scheme = 'hps')\n >>> Url (\"hps:///test.foo\")\n Url (authority = '', fragment = '', path = '/test.foo', query = '', scheme = 'hps')\n >>> Url (\"hps://\")\n Url (authority = '', fragment = '', path = '', query = '', scheme = 'hps')\n >>> Url (\"hps:\")\n Url (authority = '', fragment = '', path = '', query = '', scheme = 'hps')\n\n >>> u = Url (\"hps://\")\n >>> Url.new (u, path = \"test.foo\")\n Url (authority = '', fragment = '', path = '/test.foo', query = '', scheme = 'hps')\n >>> Url.new (u, path = \"/test.foo\")\n Url (authority = '', fragment = '', path = '//test.foo', query = '', scheme = 'hps')\n\n >>> Url.new (u, path = \"test.foo\", fs_path = True)\n Url (authority = '', fragment = '', path = 'test.foo', query = '', scheme = 'hps')\n >>> Url.new (u, path = \"/test.foo\", fs_path = True)\n Url (authority = '', fragment = '', path = '/test.foo', query = '', scheme = 'hps')\n\n \"\"\"\n\n _format = \"%(scheme)s://%(authority)s/%(path)s\"\n\n ### Use regexp as given by http://www.ietf.org/rfc/rfc3986.txt\n ### and http://www.apps.ietf.org/rfc/rfc3986.html\n ###\n ### (urlparse is broken because it doesn't parse `query` and `fragments`\n ### for unknown schemes)\n _matcher = Regexp \\\n ( r\"\"\"^(?:(?P[^:/?#]+):)?\"\"\"\n r\"\"\"(?://(?P[^/?#]*))?\"\"\"\n r\"\"\"(?P[^?#]*)\"\"\"\n r\"\"\"(?:\\?(?P[^#]*))?\"\"\"\n r\"\"\"(?:#(?P.*))?\"\"\"\n )\n\n authority = property (TFL.Getter._parsed.authority)\n fragment = property (TFL.Getter._parsed.fragment)\n path = property (TFL.Getter._parsed.path)\n query = property (TFL.Getter._parsed.query)\n scheme = property (TFL.Getter._parsed.scheme)\n value = property (TFL.Getter._value)\n\n def __init__ (self, value, fs_path = False) :\n if isinstance (value, Url) :\n self._value = value._value\n self._parsed = TFL.Record (** value._parsed._kw)\n elif self._matcher.match (value) :\n self._value = value\n attrs = dict \\\n ( (k, v or \"\")\n for (k, v) in pyk.iteritems (self._matcher.groupdict ())\n )\n self._parsed = p = TFL.Record (** attrs)\n if fs_path and p.path.startswith (\"/\") :\n p.path = p.path [1:]\n else :\n raise ValueError (value)\n # end def __init__\n\n @classmethod\n def new (cls, proto = None, ** kw) :\n dct = {}\n if proto is not None :\n dct.update (proto._parsed._kw)\n dct.update (kw)\n result = cls._format % dct\n q = dct [\"query\"]\n if q :\n result = \"%s?%s\" % (result, q)\n f = dct [\"fragment\"]\n if f :\n result = \"%s#%s\" % (result, f)\n return cls (result, fs_path = kw.get (\"fs_path\"))\n # end def new\n\n @TFL.Meta.Once_Property\n def abs_path (self) :\n from _TFL import sos\n return sos.path.abspath (self.path)\n # end def abs_path\n\n def split (self, sep, * args, ** kw) :\n return self._value.split (sep, * args, ** kw)\n # end def split\n\n def __contains__ (self, item) :\n return item in self._value\n # end def __contains__\n\n def __repr__ (self) :\n return \"Url \" + str (self._parsed)\n # end def __repr__\n\n def __str__ (self) :\n return self._value\n # end def __str__\n\n# end class Url\n\nif __name__ != \"__main__\" :\n TFL._Export (\"*\")\n### __END__ TFL.Url\n","sub_path":"Functions/venv/lib/python3.6/site-packages/_TFL/Url.py","file_name":"Url.py","file_ext":"py","file_size_in_byte":6878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"317947301","text":"import streamlit as st\nimport warnings\nwarnings.filterwarnings('ignore')\nimport pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use('fivethirtyeight')\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 10, 6\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom statsmodels.tsa.arima_model import ARIMA\nfrom pmdarima.arima import auto_arima\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\nimport math\nimport numpy as np\nfrom yahooquery import Ticker\nimport datetime as dt\n\nasset = st.text_input(\"Enter here: \")\n\nticker_input_ti = Ticker(asset)\nhistory_args = {\n \"period\": \"1y\",\n \"interval\": \"1d\",\n \"start\": dt.datetime.now() - dt.timedelta(days=365),\n \"end\": None,\n}\noption_1 = st.selectbox(\"Select Period or Start / End Dates\", [\"Period\", \"Dates\"], 0)\nif option_1 == \"Period\":\n history_args[\"period\"] = st.selectbox(\n \"Select Period\", options=Ticker.PERIODS, index=5 # pylint: disable=protected-access\n )\n\n history_args[\"start\"] = None\n history_args[\"end\"] = None\nelse:\n history_args[\"start\"] = st.date_input(\"Select Start Date\", value=history_args[\"start\"])\n history_args[\"end\"] = st.date_input(\"Select End Date\")\n history_args[\"period\"] = None\n\nst.markdown(\"**THEN**\")\nhistory_args[\"interval\"] = st.selectbox(\n \"Select Interval\", options=Ticker.INTERVALS, index=8 # pylint: disable=protected-access\n)\nargs_string = [str(k) + \"='\" + str(v) + \"'\" for k, v in history_args.items() if v is not None]\nst.write(\"Dataframe\")\ndataframe_ti = ticker_input_ti.history(**history_args)\nif isinstance(dataframe_ti, dict):\n st.write(dataframe_ti)\nelse:\n st.dataframe(dataframe_ti)\n\n\ndateparse = lambda dates: pd.datetime.strptime(dates, '%Y-%m-%d')\ndata = pd.read_csv('data//AAPL.csv',sep=',', index_col='Date', parse_dates=['Date'], date_parser=dateparse).fillna(0)\n\n#plot close price\nfig_1 = plt.figure(figsize=(10,6))\nplt.grid(True)\nplt.xlabel('Dates')\nplt.ylabel('Close Prices')\nplt.plot(data['Close'])\nplt.title('Apple Inc. (AAPL) closing price')\n\nst.subheader(\"Figure 1\")\nst.pyplot(fig_1)\n\n\ndf_close = data['Close']\ndf_close.plot(style='k.')\nplt.title('Scatter plot of closing price')\nst.subheader(\"Figure 2\")\nst.pyplot(fig_1)\n\n# Test for staionarity\ndef test_stationarity(timeseries):\n # Determing rolling statistics\n rolmean = timeseries.rolling(12).mean()\n rolstd = timeseries.rolling(12).std()\n # Plot rolling statistics:\n plt.plot(timeseries, color='blue', label='Original')\n plt.plot(rolmean, color='red', label='Rolling Mean')\n plt.plot(rolstd, color='black', label='Rolling Std')\n plt.legend(loc='best')\n plt.title('Rolling Mean and Standard Deviation')\n plt.show(block=False)\n\n adft = adfuller(timeseries, autolag='AIC')\n # output for dft will give us without defining what the values are.\n # hence we manually write what values does it explains using a for loop\n output = pd.Series(adft[0:4],\n index=['Test Statistics', 'p-value', 'No. of lags used', 'Number of observations used'])\n for key, values in adft[4].items():\n output['critical value (%s)' % key] = values\n\n\n\n\nresult = seasonal_decompose(df_close, model='multiplicative', freq = 30)\nfig_3 = plt.figure()\nfig_3 = result.plot()\nfig_3.set_size_inches(16, 9)\n\nrcParams['figure.figsize'] = 10, 6\ndf_log = np.log(df_close)\nmoving_avg = df_log.rolling(12).mean()\nstd_dev = df_log.rolling(12).std()\nplt.legend(loc='best')\nplt.title('Moving Average')\nplt.plot(std_dev, color =\"black\", label = \"Standard Deviation\")\nplt.plot(moving_avg, color=\"red\", label = \"Mean\")\nplt.legend()\nst.subheader(\"Figure 3\")\nst.write(fig_3)\n\n#split data into train and training set\ntrain_data, test_data = df_log[3:int(len(df_log)*0.9)], df_log[int(len(df_log)*0.9):]\nfig_4 = plt.figure(figsize=(10,6))\nplt.grid(True)\nplt.xlabel('Dates')\nplt.ylabel('Closing Prices')\nplt.plot(df_log, 'green', label='Train data')\nplt.plot(test_data, 'blue', label='Test data')\nplt.legend()\nst.write(fig_4)\n\nmodel_autoARIMA = auto_arima(train_data, start_p=0, start_q=0,\n test='adf', # use adftest to find optimal 'd'\n max_p=3, max_q=3, # maximum p and q\n m=1, # frequency of series\n d=None, # let model determine 'd'\n seasonal=False, # No Seasonality\n start_P=0,\n D=0,\n trace=True,\n error_action='ignore',\n suppress_warnings=True,\n stepwise=True)\n\n\n\nfig_5 = model_autoARIMA.plot_diagnostics(figsize=(15,8))\n\nst.write(fig_5)\n\nmodel = ARIMA(train_data, order=(3, 1, 2))\nfitted = model.fit(disp=-1)\n\n\n# Forecast\nfc, se, conf = fitted.forecast(544, alpha=0.05) # 95% confidence\nfc_series = pd.Series(fc, index=test_data.index)\nlower_series = pd.Series(conf[:, 0], index=test_data.index)\nupper_series = pd.Series(conf[:, 1], index=test_data.index)\nfig_6 = plt.figure(figsize=(12,5), dpi=100)\nplt.plot(train_data, label='training')\nplt.plot(test_data, color = 'blue', label='Actual Stock Price')\nplt.plot(fc_series, color = 'orange',label='Predicted Stock Price')\nplt.fill_between(lower_series.index, lower_series, upper_series,\n color='k', alpha=.10)\nplt.title('Apple Inc. Stock Price Prediction')\nplt.xlabel('Time')\nplt.ylabel('Actual Stock Price')\nplt.legend(loc='upper left', fontsize=8)\n\nst.write(fig_6)\n\n\n\n\n","sub_path":"predict2.py","file_name":"predict2.py","file_ext":"py","file_size_in_byte":5525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"200233350","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\nimport Functions\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import NoAlertPresentException\nimport unittest, re, string, sys\nimport time as time1\nfrom datetime import date\nfrom datetime import time \nfrom datetime import datetime\nfrom datetime import timedelta\n\nclass Test_FilterByStatus(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Firefox()\n self.base_url = \"http://portal.qa.calipercorp.com/users/sign_in\"\n self.verificationErrors = []\n self.accept_next_alert = True\n\n def is_element_present(self, how, what):\n try:\n self.driver.find_element(by=how, value=what)\n except NoSuchElementException as e:\n return False\n return True\n\n def is_alert_present(self):\n try:\n self.driver.switch_to_alert()\n except NoAlertPresentException as e:\n return False\n return True\n\n def close_alert_and_get_its_text(self):\n try:\n alert = self.driver.switch_to_alert()\n alert_text = alert.text\n if self.accept_next_alert:\n alert.accept()\n else:\n alert.dismiss()\n return alert_text\n finally:\n self.accept_next_alert = True\n\n def tearDown(self):\n self.driver.quit()\n self.assertEqual([], self.verificationErrors)\n\n def test_FilterByHiringStatus(self):\n import Functions\n import automatedSmokeTest\n # checkNumError = 0\n Functions.GUIdisplay.testName = \"Filter by Status\"\n driver = Functions.Functions.hiringOPL(self)\n\n # filter by Pending\n buttonStatus = 'Pending'\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"1. Filter by %s\" %buttonStatus, Functions.GUIdisplay.testName,'display')\n driver.find_element_by_xpath(\"//div[@id='statusTypes']/div[1]/label[1]\").click()\n time1.sleep(4)\n\n checkEmpty = Test_FilterByStatus.is_element_present(self, By.XPATH, \"//td[@class='dataTables_empty']\")\n if checkEmpty == True:\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"There are no %S assessees.\" %(buttonStatus), Functions.GUIdisplay.testName,'display')\n else:\n tableText = driver.find_element_by_id(\"hiring-status-table_info\").text\n systemAssessee, listAssessee = Functions.Functions.howmanyAssesseeListSystem(tableText)\n filterWorks = Functions.Functions.checkStatusList(driver, listAssessee, buttonStatus)\n if filterWorks == 0: \n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"The list is not filtered by %s status.\" %(buttonStatus), Functions.GUIdisplay.testName,'se')\n else:\n # filter by Hired\n buttonStatus = 'Hired'\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"2. Filter by %s\" %buttonStatus, Functions.GUIdisplay.testName,'display')\n driver.find_element_by_xpath(\"//div[@id='statusTypes']/div[1]/label[1]\").click()\n driver.find_element_by_xpath(\"//div[@id='statusTypes']/div[2]/label[1]\").click()\n time1.sleep(4)\n\n checkEmpty = Test_FilterByStatus.is_element_present(self, By.XPATH, \"//td[@class='dataTables_empty']\")\n if checkEmpty == True:\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"There are no %S assessees.\" %(buttonStatus), Functions.GUIdisplay.testName,'display')\n else:\n tableText = driver.find_element_by_id(\"hiring-status-table_info\").text\n systemAssessee, listAssessee = Functions.Functions.howmanyAssesseeListSystem(tableText)\n filterWorks = Functions.Functions.checkStatusList(driver, listAssessee, buttonStatus)\n if filterWorks == 0: \n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"The list is not filtered by %s status.\" %(buttonStatus), Functions.GUIdisplay.testName,'se')\n else:\n # filter by Hired\n buttonStatus = 'Not hired'\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"3. Filter by %s\" %buttonStatus, Functions.GUIdisplay.testName,'display')\n driver.find_element_by_xpath(\"//div[@id='statusTypes']/div[2]/label[1]\").click()\n driver.find_element_by_xpath(\"//div[@id='statusTypes']/div[3]/label[1]\").click()\n time1.sleep(4)\n\n checkEmpty = Test_FilterByStatus.is_element_present(self, By.XPATH, \"//td[@class='dataTables_empty']\")\n if checkEmpty == True:\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"There are no %S assessees.\" %(buttonStatus), Functions.GUIdisplay.testName,'display')\n else:\n tableText = driver.find_element_by_id(\"hiring-status-table_info\").text\n systemAssessee, listAssessee = Functions.Functions.howmanyAssesseeListSystem(tableText)\n filterWorks = Functions.Functions.checkStatusList(driver, listAssessee, buttonStatus)\n if filterWorks == 0: \n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"The list is not filtered by %s status.\" %(buttonStatus), Functions.GUIdisplay.testName,'se')\n else:\n automatedSmokeTest.GUIFunctions.outputDisplayConsole(\"The list is correctly filtered according to the status.\", Functions.GUIdisplay.testName,'s')\n\n\nif __name__ == \"__main__\":\n unittest.main(warnings ='ignore')","sub_path":"src/Test_FilterByStatus.py","file_name":"Test_FilterByStatus.py","file_ext":"py","file_size_in_byte":5358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"543541033","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure as fig\nimport funcs\nimport atsFuncs as ats\n\n# 11/15/19 ARoG\n# Process adaptive time-stepping with alpha eigenvalue results for single pin\n# transients\n\n# color scheme for the plots\ncol4 = ('--k','-k','-b','-r',':k',':b',':r')\n\n# only looking at pin03 right now, the most interesting case\nfor ip in range(3,4):\n # get data\n pID = 'pin0'+str(ip)\n # various configurations to be analyzed\n fns = (pID+'.noF.ref',pID+'.noF.cts', \\\n pID+'.noF.ctsA.abs',pID+'.noF.ctsA.rel',pID+'.noF.ctsFD.abs',pID+'.noF.ctsFD.rel', \\\n pID+'.noF.atsA.abs',pID+'.noF.atsA.rel',pID+'.noF.atsFD.abs',pID+'.noF.atsFD.rel', \\\n pID+'.wF.ref',pID+'.wF.cts', \\\n pID+'.wF.ctsA.abs',pID+'.wF.ctsA.rel',pID+'.wF.ctsFD.abs',pID+'.wF.ctsFD.rel', \\\n pID+'.wF.atsA.abs',pID+'.wF.atsA.rel',pID+'.wF.atsFD.abs',pID+'.wF.atsFD.rel')\n ncs = int(len(fns)/2)\n lA = []; lA.append(False); lA.append(False);\n pDat = []; pDat.append(True); pDat.append(True);\n # set flags for all non-reference cases\n for i in range(2,ncs):\n lA.append((fns[i][(fns[i].find('ts')+2)] == 'A'))\n pDat.append((fns[i][(fns[i].find('ts')-1)] == 'a'))\n # data labels\n labs = ('CTS ref','CTS noF','Alpha ATS abs','Alpha ATS rel','FD ATS abs','FD ATS rel')\n # initialize data storage\n ns = []; ts = []; ps = []; ds = []; dts = []; rs = []; pars = []; alphas = [];\n # get the data\n for j in range(2):\n for i in range(ncs):\n n,t,p,r,d,dt,params,a,ait,atit = ats.procTR('files/'+fns[j*ncs+i])\n # no 'd' values for reference solution, set to dt\n if all(k == 0 for k in d):\n d = dt\n ns.append(n); ts.append(t); ps.append(p); ds.append(d); dts.append(dt);\n rs.append(r); pars.append(params); alphas.append(a);\n\n # feedback labels\n fb = ('Feedback Off','Feedback On','noF','wF')\n crit = ('abs','rel')\n for j in range(2): # loop over feedback option\n for k in range(2): # loop over criteria type\n\n # Comparison of FD and Alpha dt used during ATS\n x1 = ts[j*ncs:j*ncs+2]; y1 = ps[j*ncs:j*ncs+2]; dlabs = [];\n dlabs.append(labs[0]+' ('+str(ns[j*ncs])+')')\n dlabs.append(labs[1]+' ('+str(ns[j*ncs+1])+')')\n alabs = ('Time [ms]','Power [%]','Time step size [ms]')\n for i in range(6+k,10,2):\n # ats power\n x1.append(ts[j*ncs+i][1:ns[j*ncs+i]])\n y1.append(ps[j*ncs+i][1:ns[j*ncs+i]])\n dlabs.append(labs[i-4]+' ('+str(ns[j*ncs+i])+')')\n x2 = []; y2 = [];\n x2.append(ts[j*ncs+1][1:ns[j*ncs+1]])\n y2.append(ds[j*ncs+1][1:ns[j*ncs+1]])\n dlabs.append(labs[1])\n for i in range(6+k,10,2):\n x2.append(ts[j*ncs+i][1:ns[j*ncs+i]])\n y2.append(ds[j*ncs+i][1:ns[j*ncs+i]])\n dlabs.append(labs[i-4])\n tit = fb[j]+' calculated during ATS ('+crit[k]+')'\n fn = pID+'_FDvAdt_'+fb[j+2]+'_'+crit[k]+'.png'\n funcs.dualPlot(4,x1,y1,3,x2,y2,dlabs,alabs,col4,typ=('n','sly'),fn=fn)\n\n","sub_path":"alphaATS.py","file_name":"alphaATS.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"237859976","text":"\n\nimport requests\nimport os\n\npath='/Users/zc/Desktop/try2/'\nmain='https://nhentai.net/g/'\nDnumber=241736 #递减 (数字文件夹)\nNo=1 #(第几张)\n\nfor i in range(0,10): #循环 10 本\n while 1:\n \n strDnumber=str(Dnumber) #转字符串 (网页文件夹)\n strNo=str(No) #转字符串 (第几张)\n url=main+strDnumber+'/'+strNo+'/' #组合(第几张)\n r=requests.get(url) #连接网页\n \n try:#连接200!\n \n r.raise_for_status()\n \n theJPG=r.text.split('\"https://i.nhentai.net/galleries/')[-1].split('\"')[0] #图片地址\n #theJPG=theJPG.encode('utf-8') #转成字符串\n theJPG='https://i.nhentai.net/galleries/'+theJPG\n \n theD=theJPG.split('/')[-2] #文件夹名称\n theF=theJPG.split('/')[-1] #文件名称\n r=requests.get(theJPG) #连接图片\n \n #创建路径\n if No==1:\n os.makedirs(path+theD)\n #保存\n with open(path+theD+'/'+theF,'wb') as f:\n f.write(r.content)\n \n \n f.close()\n print(theD+'/'+theF+' ok')\n No=No+1 #下一张\n\n except:#连接非200!\n No=1 #初始化No\n Dnumber=Dnumber-1 #上一目录\n break\n","sub_path":"无文件名 不可搜索.py","file_name":"无文件名 不可搜索.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"953055","text":"from models.CycleGAN import CycleGAN\nfrom models.GAN import GAN\nfrom models.LGAN import LGAN\nfrom models.LCycleGAN import LCycleGAN\nfrom models.Unet import Unet\nfrom tools.data_loader import load_image_s,load_image_u\nfrom tools.output import generate_multi_images\nfrom tools.args import create_parser\nimport tensorflow as tf\nimport time\nimport os\n\n\n\ndef get_trainer(model_name):\n if (model_name == 'gan'):\n return GAN(), False\n if (model_name == 'lgan'):\n return LGAN(), False\n if (model_name == 'unet'):\n return Unet(), False\n if (model_name == 'cyclegan'):\n return CycleGAN(), True\n if (model_name == 'lcyclegan'):\n return LCycleGAN(), True\n if (model_name == 'cyclegan_inria'):\n return CycleGAN(cX=3,cY=1), True\n return None\n\n\n\ndef fit(train_ds, test_ds,epochs,model_name, restore = False, Supervised = True, train_dsB = None, test_dsB = None):\n Trainer, is_cycle = get_trainer(model_name)\n if restore:\n Trainer.checkpoint.restore(tf.train.latest_checkpoint(Trainer.checkpoint_dir))\n for epoch in range(epochs):\n start = time.time()\n\n if not Supervised:\n generate_multi_images(Trainer, test_ds,6,epoch,cycle = is_cycle, Supervised = False, datasetB = test_dsB)\n print(\"Epoch: \", epoch)\n # Train\n n=0\n for (X,Y) in zip(train_ds,train_dsB):\n print('.', end='')\n if (n+1)%100 == 0:\n print()\n n +=1\n Trainer.train_step(X,Y,epoch)\n \n else:\n generate_multi_images(Trainer, test_ds,6,epoch,cycle = is_cycle)\n print(\"Epoch: \", epoch)\n # Train\n for n, (input_image, target) in enumerate(train_ds):\n print('.', end='')\n if (n+1) % 100 == 0:\n print()\n Trainer.train_step(input_image, target, epoch)\n print()\n\n if not os.path.exists(Trainer.checkpoint_prefix):\n os.makedirs(Trainer.checkpoint_prefix)\n\n # saving (checkpoint) the model every 20 epochs\n if (epoch + 1) % 20 == 0:\n Trainer.checkpoint.save(file_prefix = Trainer.checkpoint_prefix)\n\n print ('Time taken for epoch {} is {} sec\\n'.format(epoch + 1,\n time.time()-start))\n Trainer.checkpoint.save(file_prefix = Trainer.checkpoint_prefix)\n\n\nif __name__ == \"__main__\":\n\n opts = create_parser()\n model_name = opts.model\n epoch = opts.epochs\n restore = opts.load\n\n if opts.dataset == 'inria':\n dataloader = load_image_u(path = './data/Inria/', inria = True,name_X = 'A', name_Y = 'B')\n train_dataset_X,train_dataset_Y = dataloader.get_train_set()\n test_dataset_X = dataloader.get_test_set()\n model_name = 'cyclegan_inria'\n fit(train_dataset_X, test_dataset_X, epoch,model_name,restore,Supervised=False, train_dsB = train_dataset_Y)\n else:\n dataloader = load_image_s()\n train_dataset = dataloader.get_train_set()\n test_dataset = dataloader.get_test_set()\n fit(train_dataset, test_dataset, epoch,model_name,restore)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"481600058","text":"class Bank_Account():\n def __init__(self, name, balance):\n self.name=name\n self.balance=balance\n def withdraw(self, amount):\n if(self.balance < amount):\n print(f\"insufficient funds, Available balance is: {self.balance}\")\n else:\n self.balance -= amount\n print(f\"Available balance after withdrawal: {self.balance}\")\n\n def deposite(self, amount):\n self.balance+=amount\n print(f\"Available balance after deposit: {self.balance}\")\n \n def __str__(self):\n return f\"name: {self.name}, available balance: {self.balance}\"\n\naccount = Bank_Account(\"Bhavana\", 10000)\nprint(f\"Account Created, name: {account.name}, available balance: {account.balance}\")\ndef switch():\n while(True):\n print(\"Press d for Deposit\\npress w for Withdraw \\npress p for display account\\npress e for Exit \")\n option = input(\"your option : \")\n if option == 'd':\n amount=(int(input(\"enter the amount to be deposited: \")))\n account.deposite(amount)\n continue\n elif option == 'w':\n amount=(int(input(\"enter the amount to be withdrawn: \")))\n account.withdraw(amount)\n continue\n elif option == 'p':\n print(account)\n continue\n elif option == 'e':\n print(\"Thank You\")\n break\n else:\n print(\"Incorrect option\")\nswitch() \n","sub_path":"day-1/bank_account.py","file_name":"bank_account.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"298126352","text":"import urllib2, json, getpass, time\nfrom pymongo import MongoClient\nfrom pprint import pprint\nimport numpy as np\nfrom datetime import date, timedelta, datetime\n\n\napiKey = 'l1g165k002v7w3gtzaa683qp'\napiCnt = 0\nbaseURI = 'https://openapi.etsy.com/v2'\nmyShopID = 9816366\nlimit = 100\noffset = 0\ncount = 1\nfavorsMin = 0\ndateMin = date.today() - timedelta(days=180)\n\nuserNm = 'tfische'\npassWd = getpass.getpass()\nopener = urllib2.build_opener(urllib2.ProxyHandler({'https': 'https://tfische:' + passWd + '@proxy-newyork.aexp.com:8080'}))\nproxyFlag = 1;\n\nclient = MongoClient('localhost', 27017)\ndb = client.etsy\n\ndef getJson(uri, opener, proxyFlag):\n global apiCnt\n apiCnt = apiCnt + 1\n \n time.sleep( .1 )\n\n if proxyFlag == 1:\n response = opener.open(uri)\n return json.loads(response.read())\n else:\n response = urllib2.urlopen(uri)\n return json.loads(response.read())\n\n\n# [Etsy API Doc](https://www.etsy.com/developers/documentation/reference/shop)\n# getShop\ndef getShop(baseURI, shopID, apiKey, opener, proxyFlag):\n uri = baseURI + '/shops/' + str(shopID) + '?api_key=' + apiKey\n return getJson(uri, opener, proxyFlag)\n\nfrom collections import OrderedDict\nshopDict = OrderedDict()\ndata = getShop(baseURI, myShopID, apiKey, opener, proxyFlag)\n#Add error handling for not finding shop\n\nshopDict['shopID'] = data['results'][0]['shop_id']\nshopDict['listings'] = []\n#Maybe add more attributes in the future if needed\n\n\n# [Etsy API Doc](https://www.etsy.com/developers/documentation/reference/listing)\n# findAllShopListingsActive\ndef getShopListings(baseURI, shopID, apiKey, limit, offset, opener, proxyFlag):\n uri = baseURI + '/shops/' + str(shopID) + '/listings/active?api_key=' + apiKey + \"&limit=\" + str(limit) + \"&offset=\" + str(offset)\n return getJson(uri, opener, proxyFlag)\n\nmyListings = {}\noffset = 0\ncount = 1\nwhile (offset < count):\n data = getShopListings(baseURI, myShopID, apiKey, limit, offset, opener, proxyFlag)\n #pprint(data)\n\n count = data[\"count\"]\n effective_limit = min(data[\"pagination\"][\"effective_limit\"], len(data[\"results\"]))\n\n for i in range(0,effective_limit):\n if \"listing_id\" in data[\"results\"][i]:\n if data[\"results\"][i][\"num_favorers\"] >= favorsMin:\n myListings[data[\"results\"][i][\"listing_id\"]] = data[\"results\"][i][\"num_favorers\"]\n shopDict['listings'].append({\"listingID\": data[\"results\"][i][\"listing_id\"], \n \"createDt\": data[\"results\"][i][\"original_creation_tsz\"],\n \"modifyDt\": data[\"results\"][i][\"last_modified_tsz\"],\n \"tags\": data[\"results\"][i][\"tags\"]})\n offset = offset + limit\n\n\n# In[10]:\n\n#Load shopDict into mongoDB\n#db.shops.insert_one(shopDict)\n#db.shops.find_one({\"shopID\": myShopID})\nresult = db.shops.update_one(\n {\"shopID\": shopDict['shopID']},\n {'$set': shopDict},\n upsert = True\n )\n","sub_path":"extraction/insertUpdateShop.py","file_name":"insertUpdateShop.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"17839419","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Oct 29 09:48:03 2018\r\nadd a pretrained words embeddings as a new channel\r\nthere are two channels in input\r\n@author: Allen\r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport data_helpers\r\nfrom preprocessor import vocabulary\r\nfrom preprocessor import pretrained \r\n\r\n# Parameters\r\npretrain_embeds_size=200\r\nembedding_dim=200 \r\n# Dimensionality of character embedding\r\nfilter_sizes=[3,4,5] # Comma-separated filter sizes\r\nnum_filters=128 # Number of filters per filter size\r\nkeep_prob=0.5 # Dropout keep probability \r\nl2_reg_lambda=0 # L2 regularizaion lambda\r\nbatch_size=64 # Batch Size\r\nnum_epochs=200 # Number of training epochs\r\nevaluate_every=100 # Evaluate model on dev set after this many steps\r\ncheckpoint_every=100 # Save model after this many steps\r\nnum_classes=2 # the number of output layer\r\n\r\n# data\r\nx_text, y = data_helpers.load_data_and_labels()\r\nvoc = vocabulary(x_text)\r\nx=np.array(voc.data)\r\n\r\n# get pretrained embeddings\r\nfname = './data/glove.twitter.27B.200d.txt'\r\npt = pretrained(fname, voc.vocab, pretrain_embeds_size)\r\n\r\n# Randomly shuffle data\r\nnp.random.seed(10)\r\nshuffle_indices = np.random.permutation(np.arange(len(y)))\r\nx_shuffled = x[shuffle_indices]\r\ny_shuffled = y[shuffle_indices]\r\n\r\n# Split train/test set\r\n# TODO: This is very crude, should use cross-validation\r\nx_train, x_dev = x_shuffled[:-1000], x_shuffled[-1000:]\r\ny_train, y_dev = y_shuffled[:-1000], y_shuffled[-1000:]\r\n#print(\"Vocabulary Size: {:d}\".format(len(vocab_processor.vocabulary_)))\r\nprint(\"Vocabulary Size: {:d}\".format(len(voc.vocab)))\r\nprint(\"Train/Dev split: {:d}/{:d}\".format(len(y_train), len(y_dev)))\r\n\r\n# build cnn model\r\nsequence_length=x_train.shape[1]\r\n\r\ninput_x = tf.placeholder(tf.int32, [None, sequence_length], name=\"input_x\")\r\ninput_y = tf.placeholder(tf.float32, [None, num_classes], name=\"input_y\")\r\ndropout_keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\")\r\n\r\n#vocab_size=len(voc.vocab)\r\n#C = tf.Variable(tf.random_uniform([vocab_size, embedding_dim], -1.0, 1.0), name=\"lookuptable\")\r\n#embedded_chars = tf.nn.embedding_lookup(C, input_x)\r\n#embedded_chars_expanded = tf.expand_dims(embedded_chars, -1)\r\n\r\nembeds_pretrain_data = tf.placeholder(tf.float32, [None, pretrain_embeds_size])\r\nembedded_pretrain = tf.nn.embedding_lookup(embeds_pretrain_data, input_x)\r\nembedded_pretrain_expanded = tf.expand_dims(embedded_pretrain, -1)\r\nembedded_chars_expanded=embedded_pretrain_expanded\r\n#print(embedded_pretrain_expanded)\r\nprint(embedded_chars_expanded)\r\n\r\npooled_outputs = []\r\nfor i, filter_size in enumerate(filter_sizes):\r\n # Convolution Layer\r\n filter_shape = [filter_size, embedding_dim, 1, num_filters]\r\n W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name=\"W\")\r\n b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name=\"b\")\r\n conv = tf.nn.conv2d(\r\n embedded_chars_expanded,\r\n W,\r\n strides=[1, 1, 1, 1],\r\n padding=\"VALID\",\r\n name=\"conv\")\r\n \r\n # Apply nonlinearity\r\n h = tf.nn.relu(tf.nn.bias_add(conv, b), name=\"relu\")\r\n \r\n # Maxpooling over the outputs\r\n pooled = tf.nn.max_pool(\r\n h,\r\n ksize=[1, sequence_length - filter_size + 1, 1, 1],\r\n strides=[1, 1, 1, 1],\r\n padding='VALID',\r\n name=\"pool\")\r\n pooled_outputs.append(pooled)\r\n\r\n# Combine all the pooled features\r\nnum_filters_total = num_filters * len(filter_sizes)\r\nh_pool = tf.concat(axis=3, values=pooled_outputs)\r\nh_pool_flat = tf.reshape(h_pool, [-1, num_filters_total])\r\n\r\n# Add dropout\r\nh_drop = tf.nn.dropout(h_pool_flat, dropout_keep_prob)\r\n\r\n# output layer\r\nW_output_shape=[num_filters_total, num_classes]\r\nW_output = tf.Variable(tf.truncated_normal(W_output_shape, stddev=0.1))\r\nb_output = tf.Variable(tf.constant(0.1, shape=[num_classes]))\r\n\r\n# Final (unnormalized) scores and predictions\r\nscores = tf.nn.xw_plus_b(h_drop, W_output, b_output, name=\"scores\")\r\npredictions = tf.argmax(scores, 1, name=\"predictions\")\r\nlosses = tf.nn.softmax_cross_entropy_with_logits(logits=scores, labels=input_y)\r\nl2_loss = tf.nn.l2_loss(W_output)\r\nl2_loss += tf.nn.l2_loss(b_output)\r\n\r\nloss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss\r\n\r\noptimizer = tf.train.AdamOptimizer(0.0001)\r\ngrads_and_vars = optimizer.compute_gradients(loss)\r\nglobal_step = tf.Variable(0, name=\"global_step\", trainable=False)\r\ntrain_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)\r\n\r\ncorrect_predictions = tf.equal(predictions, tf.argmax(input_y, 1))\r\naccuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"), name=\"accuracy\")\r\n\r\n\r\nloss_summary = tf.summary.scalar(\"loss\", loss)\r\n\r\nsess = tf.Session()\r\nsess.run(tf.initialize_all_variables())\r\n#res=sess.run(C)\r\n#print(\"C:\",res[0,1])\r\n\r\n # Generate batches\r\nbatches = data_helpers.batch_iter(list(zip(x_train, y_train)), batch_size, num_epochs)\r\n\r\nfor batch in batches:\r\n x_batch, y_batch = zip(*batch)\r\n feed_dict = {\r\n input_x: x_batch,\r\n input_y: y_batch,\r\n dropout_keep_prob: keep_prob,\r\n embeds_pretrain_data:pt.embeds\r\n }\r\n _, step, summaries, loss_val,acc_val = sess.run(\r\n [train_op, global_step, loss_summary, loss, accuracy],\r\n feed_dict)\r\n print(\"step {}, loss {:g}, acc {:g}\".format(step, loss_val, acc_val))\r\n current_step = tf.train.global_step(sess, global_step)\r\n\r\n\r\n# validation\r\nfeed_dict = {\r\n input_x: x_dev,\r\n input_y: y_dev,\r\n dropout_keep_prob: 1,\r\n embeds_pretrain_data:pt.embeds\r\n}\r\nacc_val = sess.run([accuracy],feed_dict)\r\nprint(\"Accuracy in dev: \", acc_val)\r\n","sub_path":"mycnn4text_pretrain.py","file_name":"mycnn4text_pretrain.py","file_ext":"py","file_size_in_byte":5695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"207647839","text":"#####################\n### ATBASH CIPHER#######\n#####################\n#INPUT\ninput = input()\ninput = input.upper()\n\n# Dict for Cipher \ntest_input = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nList_1, List_2 = [],[]\nfor i in test_input:\n\tList_1.append(i)\nReverse_List = List_1[::-1]\nfor j in Reverse_List:\n\tList_2.append(j)\n\n# ENCODING\ndictonary = dict(zip(List_1,List_2))\nFin_list = []\no =\"\"\nfor p in input:\n\tfor k,l in dictonary.items():\n\t\tif p == k:\n\t\t\to+=l\n\t\telif p ==\"\":\n\t\t\to+=\" \"\t\nFin_list.append(o)\n\nstr1 = ' '.join(str(e) for e in Fin_list)\nprint(\"The Encoded string is \"+str1)\n\n\n# DECODING\ndictonary_2 = dict(zip(List_2,List_1))\nFin_list_2 = []\no1 = \"\"\nfor p1 in str1:\n\tfor k1,l1 in dictonary_2.items():\n\t\tif p1 == k1:\n\t\t\to1+=l1\n\t\telif p1 == \"\":\n\t\t\to1+=\" \"\nFin_list_2.append(o1)\n\nstr2 = ' '.join(str(e1) for e1 in Fin_list_2)\nprint(\"The Decoded string is \"+str2)","sub_path":"Atbash_cipher.py","file_name":"Atbash_cipher.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"59985855","text":"import time \r\nimport threading\r\nimport pynput.mouse \r\nimport Button, Controller\r\n\r\n\r\nfrom pynput.keyboard import Listener, KeyCode\r\n\r\ndelay = 0.001\r\nbutton = Button.RIGHT\r\nstart_stop_key = KeyCode(char='a')\r\nstop_key= KeyCode(char='b')\r\n\r\nclass ClickMouse(threading.Thread):\r\n\r\n def __init__(self, delay, button):\r\n super(ClickMouse, self).__init__()\r\n self.delay = delay\r\n self.button= button\r\n self.running = False\r\n self.program_running = True\r\n\r\n def start_clicking(self):\r\n self.running= True\r\n\r\n def stop_clicking(self):\r\n self.running = False\r\n\r\n def exit(self):\r\n self.start_clicking()\r\n self.program_running = False\r\n\r\n def run(self):\r\n while self.program_running:\r\n while self.running:\r\n mouse.click(self.button)\r\n time.sleep(self.delay)\r\n time.sleep(0.1)\r\n \r\nmouse = Controller()\r\nclick_thread = ClickMouse(delay, button)\r\nclick_thread.start()\r\n\r\ndef on_press(key):\r\n if key == start_stop_key:\r\n click_thread.exit()\r\n Listener.stop()\r\n\r\nwith Listener(on_press= on_press) as listener:\r\n listener.join() \r\n\r\n\r\n","sub_path":"Auto_Clicker.py","file_name":"Auto_Clicker.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"304185015","text":"# Definition for a binary tree node.\nfrom typing import List\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n \nclass Solution:\n def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:\n stack = [root]\n flipped_nodes = []\n voyage_idx = 0\n \n while stack:\n node = stack.pop()\n \n if node.val != voyage[voyage_idx]:\n return [-1]\n if node.left and node.left.val != voyage[voyage_idx + 1]:\n node.left, node.right = node.right, node.left\n flipped_nodes.append(node.val)\n \n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\n voyage_idx += 1\n \n return flipped_nodes\n \n","sub_path":"Full-timePrep/Week1-Tree/FlipBinaryTreeToMatchPreorderTraversal.py","file_name":"FlipBinaryTreeToMatchPreorderTraversal.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"302420856","text":"\nData = []\nimport sys\nimport copy\nEpochs = 100\nTrainingPortion = 0.9\n\nclass Perceptron:\n def __init__(self, num_inputs, Eta):\n self.weights = [1]*(num_inputs+1) #+1 is for W0, the threshold weight\n self.eta = Eta\n\n def copy(self):\n p = Perceptron(len(self.weights)-1, self.eta)\n for i in range(len(self.weights)):\n p.weights[i] = self.weights[i]\n return p\n\n def learn(self, inputs, correct_output):\n prediction = self.predict(inputs)\n if prediction * correct_output <= 0: #if prediction and the correct output have a different sign:\n for i in range(len(self.weights)):\n new = self.weights[i] - (self.eta * (prediction - correct_output) * inputs[i])\n self.weights[i] = new\n else:\n return\n\n def test(self, inputs, correct_output):\n prediction = self.predict(inputs)\n return not(prediction * correct_output <= 0) # if prediction and the correct output have a different sign, return false\n\n def predict(self, inputs):\n total = 0\n for i in range(len(self.weights)):\n total += self.weights[i] * inputs[i]\n return total\n\n def listWeights(self):\n for i in range(len(self.weights)):\n sys.stdout.write(\"w\" + str(i) + \" = \" + str(self.weights[i]) + \" \")\n sys.stdout.flush()\n return\n\n\nclass Numimg:\n def __init__(self, data = \"\"):\n self.label = data[0]\n temp = data[1:].split(\"\\n\") #like firewood\n self.Array = []\n for i in temp:\n self.Array.append(i.split(\" \")[1:]) #because\n self.rows = len(self.Array)\n self.cols = len(self.Array[0])\n num_ones = self.num_ones()\n self.density = num_ones / (self.rows * self.cols)\n self.h_symmetry = self.__h_symmetry__() / num_ones\n self.v_symmetry = self.__v_symmetry__() / num_ones\n self.min_h_intercepts, self.max_h_intercepts = self.__h_intercepts__()\n self.min_v_intercepts, self.max_v_intercepts = self.__v_intercepts__()\n\n def print(self):\n print(\"Label:\", self.label)\n print(\"density:\", self.density)\n print(\"h_symmetry:\", self.h_symmetry)\n print(\"v_symmetry:\", self.v_symmetry)\n print(\"h intercepts(min,max):\", self.min_h_intercepts, self.max_h_intercepts)\n print(\"v intercepts(min,max):\", self.min_v_intercepts, self.max_v_intercepts)\n for i in self.Array:\n print(i)\n\n def num_ones(self):\n counter = 0\n for i in self.Array:\n for j in i:\n if(j == '1'):\n counter += 1\n\n return counter\n\n def __h_symmetry__(self):\n temp = 0\n for i in range(self.rows//2):\n for j in range(self.cols//2):\n if(self.Array[i][j] != self.Array[i][self.cols-(j+1)]):\n temp += 1\n return temp\n\n def __v_symmetry__(self):\n temp = 0\n for i in range(self.rows//2):\n for j in range(self.cols//2):\n if(self.Array[i][j] != self.Array[self.rows-(i+1)][j]):\n temp += 1\n return temp\n\n def __h_intercepts__(self):\n min = sys.maxsize\n max = 0\n for i in range(self.rows):\n count = 0\n prev = '0'\n for j in range(self.cols): #following will count the number of 1 to 0 borders in current row\n curr = self.Array[i][j]\n if prev != curr:\n if prev == '1':\n count += 1\n prev = curr\n if count < min:\n min = count\n if count > max:\n max = count\n return min, max\n\n def __v_intercepts__(self):\n min = sys.maxsize\n max = 0\n for i in range(self.cols):\n count = 0\n prev = '0'\n for j in range(self.rows): #following will count the number of 1 to 0 borders in current col\n curr = self.Array[j][i]\n if prev != curr:\n if prev == '1':\n count += 1\n prev = curr\n if count < min:\n min = count\n if count > max:\n max = count\n return min, max\n\n def inputs(self):\n return [-1,\n self.density,\n self.h_symmetry,\n self.v_symmetry,\n self.min_h_intercepts,\n self.max_h_intercepts,\n self.min_v_intercepts,\n self.max_v_intercepts]\n\n\n\n\n\ndef parseData():\n global Data\n global cols, rows\n\n print(\"Opening Test Data File\")\n f = open('testdata', 'r')\n print(\"Reading File to String\")\n tempdata = f.read()\n print(\"Splitting into Samples\")\n dataarray = tempdata.split(\"\\n\\n\\n\") #yep\n dataarray.pop()\n for i in dataarray:\n Data.append(Numimg(i)) #you know it\n\ndef printData():\n global Data\n for i in Data:\n i.print()\n\ndef main():\n global Epochs\n global TrainingPortion\n global Data\n ErrorArray = []\n PArray = []\n parseData()\n TrainingSize = int(len(Data) * TrainingPortion)\n BestP = None\n BestError = sys.maxsize\n CurrP = Perceptron(7, 0.05)\n CurrError = 0\n for i in range(TrainingSize, len(Data)):\n correct_out = (-1 if Data[i].label == '5' else 1)\n if not (CurrP.test(Data[i].inputs(), correct_out)):\n CurrError += 1\n ErrorArray.append(CurrError)\n PArray.append(CurrP.copy())\n if CurrError < BestError:\n BestError = CurrError\n BestP = CurrP.copy()\n for e in range(Epochs):\n CurrError = 0\n for i in range(TrainingSize):\n correct_out = (-1 if Data[i].label == '5' else 1)\n CurrP.learn(Data[i].inputs(), correct_out)\n\n for i in range(TrainingSize, len(Data)):\n correct_out = (-1 if Data[i].label == '5' else 1)\n if not(CurrP.test(Data[i].inputs(), correct_out)):\n CurrError += 1\n ErrorArray.append(CurrError)\n PArray.append(CurrP.copy())\n if CurrError < BestError:\n BestError = CurrError\n BestP = CurrP.copy()\n print(\"The best perceptron of\", Epochs, \"epochs has the following weights, where w0 is the threshold\")\n BestP.listWeights()\n print()\n print(\"This results in\", BestError, \"Errors out of\", len(Data) - TrainingSize, \"Test Cases\")\n print(\"Which is an accuracy of\", round(1 - (BestError/(len(Data) - TrainingSize)), 2))\n return 0\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Q4.py","file_name":"Q4.py","file_ext":"py","file_size_in_byte":6616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"540686751","text":"#函数的参数\ndef power(x): #自定义函数,求平方\n return x*x\nprint(power(3))\n\ndef power(x, n):\n s = 1\n while(n > 0):\n s = s * x\n n = n - 1\n return s\nprint(power(3,1))\n\n#默认参数\ndef power(x, n=2): #n的默认参数为2,如果不输入则n=2\n s = 1\n while(n > 0):\n s = s * x\n n = n - 1\n return s\nprint(power(3, 1))\nprint(power(3))\n\ndef enroll(name, gender, age=6, city='Beijing'): #可以用x=xx来选择默认参数\n print('name:', name)\n print('gender:', gender)\n print('age:', age)\n print('city:', city)\nenroll(\"Jack\", \"1\") #name: Jack gender: 1 age: 6 city: Beijing\nenroll(\"Jack\", \"1\", age=1) #name: Jack gender: 1 age: 1 city: Beijing\nenroll(\"Jack\", \"1\", city=\"TianJin\")#name: Jack gender: 1 age: 6 city: TianJin\n\n#可变参数\ndef calc(*numbers): #a2 + b2 + c2 + ……\n sum = 0\n for n in numbers:\n sum = sum + n * n\n return sum\nprint(calc(1, 3, 5))\n\nnums = [1, 2, 3]\nprint(calc(*nums)) #把list或tuple的元素变成可变参数\n\n#关键字参数\ndef person(name, age, **kw): #关键字参数在函数内部自动组装为一个dict\n print('name:', name, 'age:', age, 'other:', kw)\nperson(\"Jack\", 23) #name: Jack age: 23 other: {}\nperson(\"Jack\", 23, city=\"Beijing\", word=\"Chinese\") #name: Jack age: 23 other: {'city': 'Beijing', 'word': 'Chinese'}\n\nextra = {'city': 'Beijing', 'job': 'Engineer'}\nperson('Jack', 24, **extra) #和可变参数类似,也可以先组装出一个dict,然后,把该dict转换为关键字参数传进去\n\n#命名关键字参数\ndef person(name, age, *, city, job): #命名关键字参数必须传入参数名,这和位置参数不同。如果没有传入参数名,调用将报错\n print(name, age, city, job)\nperson('Jack', 24, city='Beijing', job='Engineer') #Jack 24 Beijing Engineer\n\ndef person(name, age, *, city='Beijing', job): #命名关键字参数可以有缺省值\n print(name, age, city, job)\n\nperson('Jack', 24, job='Engineer') #Jack 24 Beijing Engineer\n\n#参数组合\n#在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,\n# 这5种参数都可以组合使用,除了可变参数无法和命名关键字参数混合。\n# 但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数/命名关键字参数和关键字参数\ndef f1(a, b, c=0, *args, **kw):\n print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)\n\ndef f2(a, b, c=0, *, d, **kw):\n print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)\n\nf1(1, 2) #a = 1 b = 2 c = 0 args = () kw = {}\nf1(1, 2, c=3) #a = 1 b = 2 c = 3 args = () kw = {}\nf1(1, 2, 3, 'a', 'b') #a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}\nf1(1, 2, 3, 'a', 'b', x=99) #a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}\nf2(1, 2, d=99, ext=None) #a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}\n\nargs = (1, 2, 3, 4)\nkw = {'d': 99, 'x': '#'}\nf1(*args, **kw) #a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'}\n\nargs = (1, 2, 3)\nkw = {'d': 88, 'x': '#'}\nf2(*args, **kw) #a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}\n\n","sub_path":"learn/3.function/3.3 funcion's param.py","file_name":"3.3 funcion's param.py","file_ext":"py","file_size_in_byte":3276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"612010300","text":"from datetime import datetime\nimport time\nimport sched\nimport requests\nimport json\n\nmember_list = [\"15703086151\",\n \"17723526243\",\n \"15923251976\",\n \"17323717050\",\n \"15802314793\",\n \"17774983794\",\n \"13022333596\"]\n\nmember_dict = {\"15703086151\": \"勾雷\",\n \"17723526243\": \"李刚\",\n \"15923251976\": \"李鑫瑜\",\n \"17323717050\": \"龚权\",\n \"15802314793\": \"张森林\",\n \"17774983794\": \"张志苗\",\n \"13022333596\": \"章强\"}\n\nscheduler = sched.scheduler(time.time, time.sleep)\n\nurl = \"https://oapi.dingtalk.com/robot/send?access_token=\" \\\n \"7baa061c818611898f806f70f67c01475907abe6d3268e974007ef7fc091bfdb\"\n\nh = [10, 15, 19, 20, 21]\nm = [0, ]\n\n\ndef get_shovel():\n return member_list[datetime.now().weekday()]\n\n\ndef task():\n now = datetime.now()\n if now.hour in h and now.minute in m:\n print(\"[\" + datetime.now().strftime(\"%Y-%m-%d %H:%M:%S %A\") + \"]\", end=\" \")\n scheduler.enter(60, 1, task)\n notice()\n else:\n scheduler.enter(60, 1, task)\n\n\ndef timedTask():\n scheduler.enter(0, 1, task)\n scheduler.run()\n\n\ndef notice():\n headers = {\"Content-Type\": \"application/json; charset=utf-8\"}\n\n post_data = {\n \"msgtype\": \"text\",\n \"text\": {\n \"content\": \"@\" + get_shovel() + \" 快来给我铲屎啦 ( • ̀ω•́ )✧\"\n },\n \"at\": {\n \"atMobiles\": [get_shovel()]\n }\n }\n\n r = requests.post(url, headers=headers, data=json.dumps(post_data))\n print(\"发送消息:“@\" + member_dict[get_shovel()] + \" 快来给我铲屎啦 ( • ̀ω•́ )✧” \" + str(r.content))\n\n\nif __name__ == \"__main__\":\n try:\n print(\"[\" + datetime.now().strftime(\"%Y-%m-%d %H:%M:%S %A\") + \"] NSB 启动成功!\")\n timedTask()\n except Exception as error:\n print(\"[ERROR] : %s\" % error)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"6902343","text":"'''\r\n有台奇怪的打印机有以下两个特殊要求:\r\n\r\n打印机每次只能打印由 同一个字符 组成的序列。\r\n每次可以在任意起始和结束位置打印新字符,并且会覆盖掉原来已有的字符。\r\n给你一个字符串 s ,你的任务是计算这个打印机打印它需要的最少打印次数。\r\n\r\n示例 1:\r\n输入:s = \"aaabbb\"\r\n输出:2\r\n解释:首先打印 \"aaa\" 然后打印 \"bbb\"。\r\n\r\n示例 2:\r\n输入:s = \"aba\"\r\n输出:2\r\n解释:首先打印 \"aaa\" 然后在第二个位置打印 \"b\" 覆盖掉原来的字符 'a'。\r\n\r\n提示:\r\n1 <= s.length <= 100\r\ns 由小写英文字母组成\r\n'''\r\nclass Solution:\r\n '''\r\n 动态规划\r\n '''\r\n def strangePrinter(self, s: str) -> int:\r\n ret = [[0 for i in range(len(s))] for i in range(len(s))]\r\n for i in range(len(s) - 1, -1, -1):\r\n for j in range(i, len(s)):\r\n if i == j:\r\n ret[i][j] = 1\r\n elif s[i] == s[j]:\r\n ret[i][j] = ret[i][j - 1]\r\n else:\r\n ret[i][j] = float('inf')\r\n for k in range(i, j):\r\n ret[i][j] = min(ret[i][j], ret[i][k] + ret[k + 1][j])\r\n return ret[0][len(s) - 1]\r\n\r\ns = \"tbgtgb\"\r\nso = Solution()\r\nprint(so.strangePrinter(s))","sub_path":"leetcode/0664_H_奇怪的打印机_DP.py","file_name":"0664_H_奇怪的打印机_DP.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"246183731","text":"from __future__ import print_function\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\nfrom graph import *\nimport time\nfrom getmodel import getmodels, getmodel\n\ndef parse_args():\n\n parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter,\n conflict_handler='resolve')\n # input files\n parser.add_argument('--input', required=True,\n help='Input graph file')\n parser.add_argument('--output', required=True,\n help='Output embedding file')\n parser.add_argument('--graph-format', default='adjlist', choices=['adjlist', 'edgelist'],\n help='Input graph format')\n parser.add_argument('--weighted', action='store_true',\n help='Treat graph as weighted')\n parser.add_argument('--directed', action='store_true',\n help='Treat graph as directed.')\n\n\n parser.add_argument('--epoch-fac', default=50, type=int,\n help='epoch-fac * node num in graph = node num per epoch')\n\n # algorithm parameters\n parser.add_argument('--model-v', required=True,\n help='The vertex sampling model')\n\n # APP\n parser.add_argument('--app-jump-factor', default=0.15, type=float,\n help='Jump factor (APP)')\n parser.add_argument('--app-step', default=80, type=int,\n help='Maximum number of walking steps(APP)')\n\n # deepwalk\n parser.add_argument('--degree-power', default=1.0, type=float,\n help='Bound of degree for sample_v of deepwalk.')\n parser.add_argument('--degree-bound', default=0, type=int,\n help='Bound of degree for sample_v of deepwalk.')\n parser.add_argument('--window-size', default=10, type=int,\n help='Window size of skipgram model.')\n\n # combination\n parser.add_argument('--combine', default=0.5, type=float,\n help='Combine A and B with how much A.')\n\n args = parser.parse_args()\n\n return args\n\ndef print_args(args):\n print(\"==================\")\n for arg in vars(args):\n print(\"{}={}\".format(arg, getattr(args, arg)))\n print(\"==================\")\n\ndef main(args):\n print_args(args)\n\n print(\"Reading Graph ...\")\n g = Graph()\n if args.graph_format == 'adjlist':\n g.read_adjlist(filename=args.input)\n elif args.graph_format == 'edgelist':\n g.read_edgelist(filename=args.input, weighted=args.weighted,\n directed=args.directed)\n\n model = getmodel(args.model_v, g, args)\n model.gendata(args.output)\n\nif __name__ == \"__main__\":\n random.seed()\n np.random.seed()\n main(parse_args())\n","sub_path":"gemb_sys/train/genpairs.py","file_name":"genpairs.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"70486324","text":"from flask import Flask, url_for, redirect, request, render_template\n\n\napp=Flask(__name__)\n\n@app.route('/')\n\ndef principal():\n return redirect(url_for('static', filename=\"index.html\"))\n\n\n@app.route('/login', methods=[\"POST\",\"GET\"])\ndef login():\n if request.method == 'POST':\n login = request.form['login']\n senha = request.form['senha']\n\n if (login== 'viniciussds') & (senha==\"123456\"):\n return render_template('oi.html',nome=login)\n else:\n return redirect(url_for('static',filename='index.html'))\n else:\n return redirect(url_for('static',filename=\"index.html\"))\n\n\n\nif __name__== '__main__':\n app.run(debug=True)\n","sub_path":"escolar.py","file_name":"escolar.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"208299260","text":"class Solution:\n def rotateRight(self, head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n dummy = ListNode(0)\n dummy.next = head\n if head is None:\n return None\n \n #先数链表有几个节点\n i = head\n count = 1\n while i.next is not None:\n i = i.head\n count += 1\n #抛掉重复的转圈\n k = k%count\n if (k == 0) or count == 1:\n return head\n #把链表头尾连起来\n i.next = head\n\n #从dummy开始运动\n i = dummy\n #运动到新的链表的头的上一个节点\n for _ in range(count - k):\n i = i.next\n\n j = i.next\n i.next = None\n return j\n ","sub_path":"61翻转链表.py","file_name":"61翻转链表.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"392469663","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 10 20:18:21 2018\n\n@author: user\n\"\"\"\nimport pandas as pd\n\nresult={\"name\":[\"viredra\",\"atuk\",\"sid\",\"khan\",\"akram\",\"shahid\"],\"score\":[33,23,45,34,45,55],\"no_of_attempts\":[1,3,4,4,4,4],\"qualify\":[\"yes\",\"no\",\"no\",\"no\",\"no\",\"yes\"]}\nname=result.get(\"name\")\nscare=result.get(\"score\")\nattempts=result.get(\"no_of_attempts\")\nqualify=result.get(\"qualify\")\nlabels={\"labels\":[\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"]}\ndf=pd.DataFrame(result,index=labels[\"labels\"])\nprint(df)\n\nprint(df.head(4))\n\nprint(pd.DataFrame(qualify,index=df[\"name\"]))\n\ntotalattpt=0\nfor i in range(len(df[\"name\"])):\n if(df[\"score\"][i]>20 and df[\"score\"][i]<35):\n print(\"%s score= %d \\t no of attempts= %d \"% (df[\"name\"][i],df[\"score\"][i],df[\"no_of_attempts\"][i]))\n totalattpt+=df[\"no_of_attempts\"][i]\nprint(\"total attempts by these students %d\"%totalattpt)\n\n\n\n","sub_path":"10 apr/dictStudents.py","file_name":"dictStudents.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"205222365","text":"import os\nimport sqlite3\nfrom alayatodo import app\n\n\ndef migrate_db():\n\n try:\n\n with sqlite3.connect(app.config['DATABASE']) as connection:\n c = connection.cursor()\n\n c.execute(\"ALTER TABLE todos RENAME TO old_todos\")\n c.execute(\"SELECT * FROM old_todos\")\n\n data = [(row[1],row[2],1)for row in c.fetchall()]\n\n c.execute(\"DROP TABLE IF EXISTS todos;\")\n c.execute(\"\"\"\n CREATE TABLE todos (\n id INTEGER PRIMARY KEY,\n user_id INT(11) NOT NULL,\n description VARCHAR(255),\n status INTEGER NOT NULL,\n FOREIGN KEY (user_id) REFERENCES users(id)\n );\n \"\"\")\n c.executemany(\"INSERT INTO todos (user_id, description, status) VALUES (?,?,?)\",data)\n c.execute(\"DROP TABLE old_todos\")\n\n except sqlite3.OperationalError as ex:\n print(ex)\n os.exit(1)\n\nif __name__ == \"__main__\":\n migrate_db()\n","sub_path":"resources/migrate.py","file_name":"migrate.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"91212904","text":"from django.db import models\n\n# Create your models here.\nclass CanalEntrada(models.Model):\n \"\"\"Canal de entrada onde esse LEAD foi adquirido, seja Consórcio, Facebook, Instagram\"\"\"\n\n canal_entrada = models.CharField('Canal de Entrada', max_length=255)\n\n def __str__(self):\n return self.canal_entrada\n\n class Meta:\n verbose_name_plural = 'Canal de Entrada'\n\n\n\nclass Status(models.Model):\n\n\n status = models.CharField(max_length=255)\n descricao = models.TextField('Descrição', max_length=1000)\n data = models.DateField('Data do Status')\n\n def __str__(self):\n return self.status\n\n class Meta:\n verbose_name_plural = 'Status'\n\n\nclass Etapas(models.Model):\n \"\"\"Irá medir a etapa em qual o cliente está ou já passou, servirá como uma Timeline\"\"\"\n\n def __str__(self):\n return self.titulo\n\n titulo = models.CharField('Título da Etapa', max_length=255)\n descricao = models.TextField('Descrição', max_length=1000)\n arquivo = models.FileField('Arquivo Anexado', upload_to='leads/uploads/')\n data = models.DateField()\n\n class Meta:\n verbose_name_plural = 'Etapas'\n\n\nclass Leads(models.Model):\n SEXO_CHOICES = (\n ('M', 'Masculino'),\n ('F', 'Feminino'),\n )\n\n cpf = models.CharField(max_length=11)\n canal_entrada = models.ForeignKey(CanalEntrada)\n nome = models.CharField(max_length=255)\n sexo = models.CharField(max_length=1, choices=SEXO_CHOICES)\n endereco = models.CharField('Endereço', max_length=400)\n numero = models.CharField('Número', max_length=10)\n complemento = models.CharField(max_length=255, blank=True)\n bairro = models.CharField(max_length=255)\n cidade = models.CharField(max_length=255)\n uf = models.CharField(max_length=10)\n cep = models.CharField(max_length=10, blank=True)\n fixo1 = models.CharField('Fixo 1', max_length=20, blank=True)\n fixo2 = models.CharField('Fixo 2', max_length=20, blank=True)\n fixo3 = models.CharField('Fixo 3', max_length=20, blank=True)\n cel1 = models.CharField('Celular 1', max_length=20, blank=True)\n cel2 = models.CharField('Celular 2', max_length=20, blank=True)\n cel3 = models.CharField('Celular 3', max_length=20, blank=True)\n data_nasc = models.DateField('Data de Nascimento', blank=True)\n renda = models.DecimalField(max_length=20, max_digits=18, decimal_places=2, blank=True)\n email1 = models.EmailField('Email 1', blank=True)\n email2 = models.EmailField('Email 2', blank=True)\n email3 = models.EmailField('Email 3', blank=True)\n ## fk?\n produto = models.CharField(max_length=255)\n cod_produto = models.CharField('Código do produto', max_length=100)\n ## ?\n data_inicio = models.DateField('Data de Início', blank=True)\n data_conclusao = models.DateField('Data de Conclusão', blank=True)\n valor_produto = models.DecimalField('Valor do Produto', max_length=20, max_digits=18, decimal_places=2)\n valor_negociado = models.DecimalField('Valor Negociado', max_length=20, max_digits=18, decimal_places=2)\n moeda = models.CharField(max_length=100)\n metodo_pagto = models.CharField('Método de Pagamento', max_length=100)\n plano_pagto = models.CharField('Plano de Pagamento', max_length=100)\n bandeira = models.CharField(max_length=100)\n status = models.ForeignKey(Status)\n prox_contato = models.CharField('Próximo Contato', max_length=255)\n observacao = models.TextField('Observação', max_length=1000)\n etapas = models.ForeignKey(Etapas, null=True, blank=True)\n\n def __str__(self):\n return self.nome\n\n class Meta:\n verbose_name_plural = 'Leads'\n","sub_path":"goldentravel/apps/leads/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"133000594","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nfrom net.utils.tgcn import ConvTemporalGraphical\nfrom net.utils.graph import Graph\nimport random\n\nSEED = 2020\n\nclass Flatten(nn.Module):\n def forward(self, input):\n return input.view(input.size(0), -1)\n\n\nclass UnFlatten(nn.Module):\n def __init__(self, size):\n super().__init__()\n self.size = size\n \n def forward(self, input):\n return input.view(input.size(0), self.size, 1, 19)\n\n\nclass Model(nn.Module):\n r\"\"\"Graph Autoenconder (GAE).\n\n Args:\n in_channels (int): Number of channels in the input data\n edge_importance_weighting (bool): If ``True``, adds a learnable\n importance weighting to the edges of the graph\n predict_frames (int): Number of forecasted frames for the long-term head pose forecasting task\n embedd_dim (int): Size of the dimensionality of the latent embeddings \n device (str): 'cpu' or 'cuda'\n **kwargs (optional): Other parameters for graph convolution units\n\n Shape:\n - Input: :math:`(N, in_channels, T_{in}, V_{in}, C_{in})`\n - Output: #head pose (N, T, 1, 3), landmark (N, T, 19, 2), embeddings (N, embedd_dim)\n :math:`(N, T, 1, 3) & (N, T, 19, 2)` where\n :math:`N` is a batch size,\n :math:`T` is a number of forecasted frames for the long-term head pose forecasting task\n\n \"\"\"\n\n def __init__(self, in_channels,\n edge_importance_weighting, predict_frames=5, embedd_dim=64, device='cpu', **kwargs):\n super().__init__()\n torch.manual_seed(SEED)\n random.seed(2020)\n # load graph_encoder\n self.graph = Graph(layout='FAN_19', strategy='uniform') #(1, 19, 19)\n A = torch.tensor(self.graph.A, dtype=torch.float32, requires_grad=False, device=device)\n self.register_buffer('A', A)\n \n # load graph_decoder\n self.graph_de = Graph(layout='FAN_19', strategy='spatial') #(1, 19, 19)\n A_d = torch.tensor(self.graph_de.A, dtype=torch.float32, requires_grad=False, device=device)\n self.register_buffer('A_d', A_d)\n\n # build networks\n spatial_kernel_size = A.size(0) \n temporal_kernel_size = 3\n kernel_size = (temporal_kernel_size, spatial_kernel_size) #(3, 1)\n self.data_bn_en = nn.BatchNorm1d(in_channels * A.size(1)) # 2 * 19\n kwargs0 = {k: v for k, v in kwargs.items() if k != 'dropout'}\n self.st_gcn_encoder = nn.ModuleList((\n\n # --------------------------------------------------encoder -----------------------------------------\n st_gcn(in_channels, embedd_dim //2, kernel_size, 1, residual=False, **kwargs0), #(N, 16, 5, 19) \n \n st_gcn(embedd_dim //2, embedd_dim //2, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim //2, embedd_dim //2, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim //2, embedd_dim, kernel_size, 2, **kwargs), #(N, 32, 3, 19) \n st_gcn(embedd_dim, embedd_dim, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim, embedd_dim, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim, embedd_dim *2, kernel_size, 2, **kwargs), #(N, 64, 2, 19) \n st_gcn(embedd_dim *2, embedd_dim *2, kernel_size, 1, **kwargs), \n st_gcn(embedd_dim *2, embedd_dim *2, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim *2, embedd_dim *4, kernel_size, 2, **kwargs), #(N, 128, 1, 19) \n st_gcn(embedd_dim *4, embedd_dim *4, kernel_size, 1, **kwargs)\n \n ))\n\n self.flat = Flatten()\n self.fc1 = nn.Linear(embedd_dim *4 *A.size(1), embedd_dim) # for self.mean\n self.fc2 = nn.Linear(embedd_dim *4 *A.size(1), embedd_dim) # for self.logvar\n self.unflat = UnFlatten(embedd_dim)\n \n self.fc3 = nn.Sequential(\n nn.Linear(embedd_dim, embedd_dim *A.size(1)),\n nn.PReLU()\n )\n \n self.data_bn_decoder = nn.BatchNorm1d(embedd_dim *A.size(1)) # embedd_dim * 19\n self.st_gcn_decoder_land = nn.ModuleList((\n\n # --------------------------------------------------decoder -----------------------------------------\n st_gcn(embedd_dim, embedd_dim, kernel_size, 1, **kwargs), #(N, 32, 1, 19) \n st_gcn(embedd_dim, embedd_dim //2, (2, spatial_kernel_size), 1, **kwargs), #(N, 16, 2, 19) \n st_gcn(embedd_dim //2, embedd_dim //2, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim //2, embedd_dim //4, (3, spatial_kernel_size), 1, decoder_layer=True, **kwargs), #(N, 8, 4, 19) \n st_gcn(embedd_dim //4, embedd_dim //4, kernel_size, 1, **kwargs),\n st_gcn(embedd_dim //4, 2, (2, spatial_kernel_size), 1, last_layer=True, **kwargs) #(N, 2, 5, 19) \n # -------------------------------------------------------------------------------------------------------\n ))\n \n self.land_layer = nn.Sequential(\n nn.Linear(2 * 5 *self.A.size(1), 2*19*predict_frames)\n )\n \n self.data_bn = nn.BatchNorm1d(2 *A.size(1)) \n \n self.st_gcn_networks = nn.ModuleList((\n\n # --------------------------------------------------decoder -----------------------------------------\n st_gcn(2, 64, (1, 3), 1, residual=False, **kwargs0),\n st_gcn(64, 64, (1, 3), 1, **kwargs),\n st_gcn(64, 64, (1, 3), 1, **kwargs),\n st_gcn(64, 64, (1, 3), 1, **kwargs),\n st_gcn(64, 128, (1, 3), 2, **kwargs),\n# st_gcn(128, 128, (1, 3), 1, **kwargs),\n # -------------------------------------------------------------------------------------------------------\n ))\n \n # fcn for prediction\n self.fcn = nn.Conv2d(128, 256, kernel_size=1)\n \n # linear layer\n self.linear = nn.Linear(256, 3)\n \n # initialize parameters for edge importance weighting\n if edge_importance_weighting:\n self.edge_importance_encoder = nn.ParameterList([ #encoder graph edge \n nn.Parameter(torch.ones(self.A.size()))\n for i in self.st_gcn_encoder\n ])\n\n self.edge_importance_mean = nn.Parameter(torch.ones(self.A.size()))\n self.edge_importance_std = nn.Parameter(torch.ones(self.A.size()))\n\n self.edge_importance_decoder_land = nn.ParameterList([ #decoder_land graph edge \n nn.Parameter(torch.ones(self.A.size()))\n for i in self.st_gcn_decoder_land\n ])\n \n self.edge_importance = nn.ParameterList([ #decoder_pose graph edge \n nn.Parameter(torch.ones(self.A_d.size()))\n for i in self.st_gcn_networks\n ])\n\n else:\n self.edge_importance = [1] * len(self.st_gcn_encoder)\n \n\n def encode(self, x):\n\n x = x[:,:5,:19,:2] #(N, T, 19, C)\n\n # data normalization\n N, T, V, C = x.size() # input tensor:(N, T, V, C)\n x = x.permute(0, 2, 3, 1).contiguous() # (N, V, C, T)\n x = x.view(N, V * C, T)\n x = self.data_bn_en(x)\n x = x.view(N, V, C, T)\n x = x.permute(0, 2, 3, 1).contiguous() # (N, C, T, V) --> (N, 2, 5, 19)\n \n # forward\n for gcn, importance in zip(self.st_gcn_encoder, self.edge_importance_encoder):\n x, _ = gcn(x, self.A * importance) # (N, C, T=2, V=19)\n\n # print(x.shape)\n\n x = self.flat(x)\n\n self.mean = self.fc1(x)\n sampled_z = self.mean\n\n return sampled_z\n\n def decode_land(self, z):\n \n z = self.fc3(z)\n z = self.unflat(z)\n \n N, C, T, V = z.size() # 输入tensor:(N, C, T, V)\n z = z.permute(0, 3, 1, 2).contiguous() # (N, V, C, T)\n z = z.view(N, V * C, T)\n z = self.data_bn_decoder(z)\n z = z.view(N, V, C, T)\n z = z.permute(0, 2, 3, 1).contiguous() # (N, C, T, V) --> (N, 64, 1, 21)\n \n z_land = z #(N, 64, 1, 21)\n #print(z.shape)\n\n for gcn, importance in zip(self.st_gcn_decoder_land, self.edge_importance_decoder_land):\n z_land, A = gcn(z_land, self.A * importance) # (N, C=2, T=5, V=19)\n\n z_land = z_land.view(N, -1)\n y_pred = self.land_layer(z_land) #(N, 2*19)\n \n y_pred = y_pred.view(N, -1, 19, 2) \n\n return y_pred, A\n\n def decode_pose(self, z):\n \n \n N, V, C = z.size() # 输入tensor:(N, V, C)\n T = 1\n z = z.view(N, V * C, T)\n z = self.data_bn(z)\n z = z.view(N, V, C, T)\n z = z.permute(0, 2, 3, 1).contiguous() # (N, C, T, V) --> (N, 64, 1, 21)\n \n z_pose = z #(N, 64, 1, 21)\n\n for gcn, importance in zip(self.st_gcn_networks, self.edge_importance):\n z_pose, A = gcn(z_pose, self.A_d * importance) # (N, C=128, T=1, V=19)\n \n y = F.avg_pool2d(z_pose, z_pose.size()[2:]) \n y = y.view(N, -1, 1, 1) #(N, 128, 1, 1)\n \n # prediction \n y = self.fcn(y) #(N, 256, 1, 1)\n \n y = y.view(y.size(0), -1)\n\n y_pose = self.linear(y) #(N, 3)\n y_pose = y_pose.view(N, -1, 1, 3)\n \n return y_pose, A\n\n def forward(self, x, predict_frames):\n \n z = self.encode(x) # z: (N, 64, 1, 19)\n #print(f'Z: {z.shape}')\n \n y_land, A_pred = self.decode_land(z)\n pose_result = []\n for i in range(predict_frames):\n y_pose, _ = self.decode_pose(y_land[:,i,:,:])\n pose_result.append(y_pose)\n \n pose_result = torch.cat(pose_result, dim=1)\n \n return pose_result, y_land, z\n\n\n\nclass st_gcn(nn.Module):\n r\"\"\"Spatial temporal graph convolution network (ST-GCN).\n\n Args:\n in_channels (int): Number of channels in the input sequence data\n out_channels (int): Number of channels produced by the convolution\n kernel_size (tuple): Size of the temporal convolving kernel and graph convolving kernel\n stride (int, optional): Stride of the temporal convolution. Default: 1\n dropout (int, optional): Dropout rate of the final output. Default: 0\n residual (bool, optional): If ``True``, applies a residual mechanism. Default: ``True``\n\n Shape:\n - Input[0]: Input graph sequence in :math:`(N, in_channels, T_{in}, V)` format\n - Input[1]: Input graph adjacency matrix in :math:`(K, V, V)` format\n - Output[0]: Output graph sequence in :math:`(N, out_channels, T_{out}, V)` format\n - Output[1]: Graph adjacency matrix for output data in :math:`(K, V, V)` format\n\n where\n :math:`N` is a batch size,\n :math:`K` is the spatial kernel size, as :math:`K == kernel_size[1]`,\n :math:`T_{in}/T_{out}` is a length of input/output sequence,\n :math:`V` is the number of graph nodes.\n\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n stride=1,\n dropout=0,\n residual=True,\n last_layer=False,\n decoder_layer=False,\n re_layer=False):\n super().__init__()\n\n assert len(kernel_size) == 2\n #print(kernel_size[0])\n if kernel_size[0] == 3 and not decoder_layer:\n padding = ((kernel_size[0] - 1) // 2, 0)\n stride_res = 2\n elif re_layer:\n padding = (0, 0)\n stride_res = 2\n elif last_layer:\n padding = ((kernel_size[0] + 1) //2, 0) \n stride_res = 4\n elif not last_layer and kernel_size[0] != 1: \n padding = ((kernel_size[0] + 1) //2, 0) \n stride_res = 2\n elif kernel_size[0] == 1:\n padding = ((kernel_size[0] - 1) // 2, 0)\n stride_res = stride\n\n # GCN\n self.gcn = ConvTemporalGraphical(in_channels, out_channels,\n kernel_size[1])\n\n # TCN\n self.tcn = nn.Sequential(\n nn.BatchNorm2d(out_channels),\n nn.ReLU(),\n nn.Conv2d(\n out_channels,\n out_channels,\n (kernel_size[0], 1),\n (stride, 1),\n padding,\n ),\n nn.BatchNorm2d(out_channels),\n nn.Dropout(dropout, inplace=True),\n )\n\n if not residual:\n self.residual = lambda x: 0\n\n elif (in_channels == out_channels) and (stride == 1):\n self.residual = lambda x: x\n\n else: \n self.residual = nn.Sequential(\n nn.Conv2d(\n in_channels,\n out_channels,\n kernel_size=1,\n stride=(stride_res, 1)),\n nn.BatchNorm2d(out_channels),\n )\n self.relu = nn.ReLU(inplace=True)\n self.kernel_size = kernel_size\n\n def forward(self, x, A):\n res = self.residual(x)\n x, A = self.gcn(x, A)\n tcn = self.tcn(x)\n x = tcn + res\n\n return self.relu(x), A\n","sub_path":"model/model_GAE.py","file_name":"model_GAE.py","file_ext":"py","file_size_in_byte":13407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"508133077","text":"\"\"\"\nAltere o programa de cálculo do fatorial, permitindo ao usuário calcular o fatorial várias vezes e limitando o\nfatorial a números inteiros positivos e menores que 16.\n\"\"\"\n\nwhile True:\n while True:\n try:\n fat = int(input('Fatorial de: '))\n if fat <= 16:\n break\n else:\n print('[ERRO]: Digite um numero menor ou igual a 16!\\n')\n except ValueError:\n print('Valor Invalido!\\n')\n\n fatorial = 1\n\n print(f'{fat}!=', end='')\n for f in range(fat, 0, -1):\n fatorial *= f\n print(f, end='')\n if f == 1:\n print('=', end='')\n else:\n print('.', end='')\n\n print(fatorial)\n\n sair = input('\\nDeseja encerrar o programa? [S/N]: ').lower()\n if sair == 's':\n break\n","sub_path":"03_Estrutura_de_Repeticao/20-Fatorial_v2.py","file_name":"20-Fatorial_v2.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"162262869","text":"\"\"\"\n@Project :协程\n@Time :2018/8/28 20:25\n@Author :Zhenxian\n@File :利用gevent爬虫.py\n@Software :PyCharm\n\"\"\"\nfrom gevent import monkey\n\nmonkey.patch_all()\nimport gevent\nimport requests\nimport time\n\n\ndef get_page(url):\n print('GET: %s' % url)\n response = requests.get(url)\n if response.status_code == 200:\n print('%s:%d bytes' % (url, len(response.text)))\n\n\nstart_time = time.time()\ngevent.joinall([\n gevent.spawn(get_page, 'https://www.python.org/'),\n gevent.spawn(get_page, 'https://www.yahoo.com/'),\n gevent.spawn(get_page, 'https://github.com/'),\n])\nstop_time = time.time()\nprint('run time is %s' % (stop_time - start_time))\n","sub_path":"协程/利用gevent爬虫.py","file_name":"利用gevent爬虫.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"236440295","text":"import cv2, random, math\n#pym='LD_PRELOAD=/usr/lib/arm-linux-gnueabihf/libatomic.so.1 python3'\n#import numpy as np\n#print(\"yoyo\")\ndebug = False\nradius = 0.9\nksize = int(6 * round(radius) + 1)\nminLineLength = 1\nmaxLineGap = 100\nred = [0, 80]\ngreen = [80, 255]\nblue = [0, 105]\nimgwidth = 640\nimgheight = 480\nfld = cv2.ximgproc.createFastLineDetector(_length_threshold=3, _distance_threshold=2.5, _canny_th1=100, _canny_th2=100, _canny_aperture_size=7, _do_merge=True)\n#part1 = cv2.GaussianBlur(src, (ksize, ksize), round(radius))\npoint_tolerance = 0.08\ncoloriters = [0xFFFFFF, 0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, 0xFF7F7F]\n\n\ndef detectPoints(image):\n\tstep1 = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\tstep2 = cv2.inRange(step1, (red[0], green[0], blue[0]), (red[1], green[1], blue[1]))\n\tlines = None\n\tlines = fld.detect(step2)\n\tif lines is None:\n\t\tprint(\"lol\")\n\t\treturn []\n\tif len(lines) < 6:\n\t#\tpass\n\t\tprint(\"hehe\")\n\t\treturn []\n\tlinestr = \"\"\n\tstep3 = image\n\tcoloriter = 0xFF0000\n\tmaxlen = 0\n\tlinelengths = []\n\tfor i in range(len(lines)):\n\t\tline = lines[i][0]\n\t\tlinelength = math.sqrt(math.pow((line[0] - line[2]), 2) + math.pow((line[1] - line[3]), 2))\n\t\tif linelength > maxlen:\n\t\t\tmaxlen = linelength\n\t\tlinelengths.append((i, linelength))\n\tlinelengths.sort(key = lambda x: x[1], reverse=True)\n\t#print(linelengths)\n\tfor i in range(len(lines)):\n\t\tline = lines[linelengths[i][0]][0]\n\t\tlinestr += str(line)\n\t#\tcv2.line(step3, (line[0], line[1]), (line[2], line[3]), (coloriter >> 0x10, (coloriter >> 0x8) & 0xFF, coloriter & 0xFF))\n\t#\tcoloriter = coloriters[i % 8]\n\t#cv2.imwrite(\"lines.png\", step3)\n\t#print(len(lines), linestr)\n\tpoints = []\n\tif len(linelengths) >= 6:\n\t\tfor i in range(len(linelengths)):\n\t\t\tline = lines[linelengths[i][0]][0]\n\t\t\tnotinpointsA = True\n\t\t\tnotinpointsB = True\n\t\t\tfor point in points:\n\t\t\t\tif abs(line[0] - point[0]) < maxlen * point_tolerance and abs(line[1] - point[1]) < maxlen * point_tolerance:\n\t\t\t\t\tnotinpointsA = False\n\t\t\t\tif abs(line[2] - point[0]) < maxlen * point_tolerance and abs(line[3] - point[1]) < maxlen * point_tolerance:\n\t\t\t\t\tnotinpointsB = False\n\t\t\tif len(points) == 0:\n\t\t\t\tpoints.append((line[0], line[1]))\n\t\t\t\tpoints.append((line[2], line[3]))\n\t\t\telse:\n\t\t\t\tif notinpointsA:\n\t\t\t\t\tpoints.append((line[0], line[1]))\n\t\t\t\tif notinpointsB:\n\t\t\t\t\tpoints.append((line[2], line[3]))\n\telse:\n\t\tprint(\"keke\")\n\t\treturn []\n\tif len(points) < 8:\n\t#\tpass\n\t\t#print(\"pepe\")\n\t\treturn []\n\tif len(points) > 8:\n\t\tpoints = points[0:8]\n\tfor x in range(len(points)):\n\t\tpoint = points[x]\n\t\tintx = int(round(point[0]))\n\t\tinty = int(round(point[1]))\n\t\tcv2.rectangle(step3, (intx-2, inty-2), (intx+1, inty+1), coloriters[x % 8])\n\t\tpoints[x] = (point[0] / imgwidth, point[1] / imgheight)\n\t#print(len(points), points)\n\t#return step3\n\t#print(points)\n\tif debug:\n\t\tcv2.imshow(\"frame\", step3)\n\treturn points\n\nif __name__ == \"__main__\" and debug:\n\tcap = cv2.VideoCapture(\"http://10.65.0.100:1181/stream.mjpg\")\n\n\twhile(True):\n\t\tret, image = cap.read()\n\t\t\n\t\tif ret:\n\t\t\tdetectPoints(image)\n\t\t\t#part5 = fld.drawSegments(image, detectPoints(image))\n\t\t\t#print(detectPoints(image))\n\t\t\t#part6 = cv2.resize(part5, (640, 480))\n\t#\t\t\n\t\tif cv2.waitKey(1) & 0xFF == ord(\"q\"):\n\t\t\tbreak\n\n\t#part4 = part3\n\t#part5 = cv2.Canny(part4,10,255,apertureSize=7)\n\t#lines = cv2.HoughLinesP(part5,1,np.pi/180,100,minLineLength,maxLineGap)\n\t#for x1,y1,x2,y2 in lines[0]:\n\t# cv2.line(src,(x1,y1),(x2,y2),(0xFF,0,0),2)\n\tcap.release()\n\tcv2.destroyAllWindows()\nprint(\"hey\")\n","sub_path":"pointgrabber.py","file_name":"pointgrabber.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"235220978","text":"\"\"\"Constants for 1-Wire component.\"\"\"\nfrom homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN\n\nCONF_MOUNT_DIR = \"mount_dir\"\nCONF_NAMES = \"names\"\n\nCONF_TYPE_OWFS = \"OWFS\"\nCONF_TYPE_OWSERVER = \"OWServer\"\nCONF_TYPE_SYSBUS = \"SysBus\"\n\nDEFAULT_OWSERVER_PORT = 4304\nDEFAULT_SYSBUS_MOUNT_DIR = \"/sys/bus/w1/devices/\"\n\nDOMAIN = \"onewire\"\n\nPRESSURE_CBAR = \"cbar\"\n\nSUPPORTED_PLATFORMS = [\n SENSOR_DOMAIN,\n]\n","sub_path":"homeassistant/components/onewire/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"267217989","text":"from django.urls import path\nfrom .views import SignUpView, AboutView, ShowProfileView, EditProfilePageView\n\n# from .views import\napp_name = \"users\"\n\nurlpatterns = [\n path(\"signup/\", SignUpView.as_view(), name=\"signup\"),\n path(\"about/\", AboutView.as_view(), name=\"about\"),\n path(\"/profile\", ShowProfileView.as_view(), name=\"show_profile\"),\n path(\n \"/edit_profile\",\n EditProfilePageView.as_view(),\n name=\"edit_profile\",\n ),\n]\n","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"309102159","text":"import pennylane as qml\nfrom pennylane.optimize import GradientDescentOptimizer\n# Create device\ndev = qml.device('default.qubit', wires=1)\n# Quantum node\n@qml.qnode(dev)\ndef circuit1(var):\n qml.RX(var[0], wires=0)\n qml.RY(var[1], wires=0)\n return qml.expval(qml.PauliZ(0))\n# Create optimizer\nopt = GradientDescentOptimizer(0.25)\n# Optimize circuit output\nvar = [0.5, 0.2]\nfor it in range(30):\n var = opt.step(circuit1, var)\n print(\"Step {}: cost: {}\".format(it, circuit1(var)))\n","sub_path":"MLGdansk101/pennylane_example.py","file_name":"pennylane_example.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"358653502","text":"########################################################\n# Author: Druddigon\n# Date Created: 16/1/2015\n# Challenge: http://www.reddit.com/r/dailyprogrammer/comments/2s7ezp/20150112_challenge_197_easy_isbn_validator/\n########################################################\n\nfrom random import randint\n\ndef main():\n print(validate_isbn(\"0-7475-3269-9\"))\n\n an_isbn = generate_isbn()\n\n print(validate_isbn(an_isbn))\n\n\ndef generate_isbn():\n isbn = [randint(0,9) for _ in range(0,9)]\n remainder = sum([isbn[n] * (10-n) for n in range(0,9)]) % 11\n if (11 - remainder) == 10:\n checksum = \"X\"\n else:\n checksum = 11 - remainder\n\n isbn.append(checksum)\n\n return \"\".join(map(str, isbn))\n\n\n\ndef validate_isbn(isbn_num):\n isbn_str = str(isbn_num)\n # Strip away all non numeric digits\n isbn_str = \"\".join(d for d in isbn_str if (d.isdigit() or d == \"X\"))\n\n # ISBN must be 10 digits\n if len(isbn_str) != 10:\n return False\n \n multiplier = 10\n validator_sum = 0\n\n for n in range(0,10):\n if isbn_str[n].isdigit():\n int_digit = int(isbn_str[n])\n elif isbn_str[n] == \"X\":\n int_digit = 10\n else:\n return False\n\n validator_sum += (10-n) * int_digit\n\n return (validator_sum % 11 == 0)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/isbn_validator.py","file_name":"isbn_validator.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"254765847","text":"import json\nfrom ruamel.yaml import YAML\n\nwith open('../files/to_convert.json') as json_file:\n data = json.load(json_file)\n\nwith open('files/alan_convert.yaml', 'w') as yaml_file:\n yaml = YAML()\n yaml.indent(mapping=2, sequence=4, offset=2)\n yaml.dump(data, yaml_file)\n","sub_path":"activities/alan_convert.py","file_name":"alan_convert.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"294754339","text":"from src.modeling import util\nfrom src.modeling.models.neural_net import visualization, get_model, display_model, save_model\n\nimport pickle\n\nHISTORYS_FILE = \"historys_nn.sav\"\n\n\ndef _test_model(neurons, x_train,y_train,x_test,y_test,epochs=10,):\n # get model\n input_size = x_train.shape[1]\n\n if len(y_train.shape) == 1:\n output_size = 1\n else:\n output_size = y_train.shape[1]\n\n model = get_model(input_size, output_size, neurons=neurons)\n display_model(model)\n\n # train\n history = model.fit(x_train, y_train,\n validation_data=(x_test, y_test),\n epochs=epochs,\n batch_size=12,\n verbose=0)\n\n return model, neurons, history.history\n\n\ndef test_models(init, final, sep=1, epochs=10):\n # read data\n x_train, y_train, _ = util.read_train_data()\n x_test, y_test, _ = util.read_test_data()\n\n historys = []\n for i in range(init, final + 1, sep):\n print(\"\\nNeurons {} - start\".format(i))\n\n model, neurons, history = _test_model([i], epochs, x_train, y_train,x_test, y_test)\n historys.append((neurons, history))\n\n save_model(model, sufix=\"_\" + str(i))\n\n print(\"Neurons {} - done\".format(i))\n\n pickle.dump(historys, open(HISTORYS_FILE, 'wb'))\n\n\ndef display_models_exploration():\n historys = pickle.load(open(HISTORYS_FILE, 'rb'))\n\n # graphs\n visualization.accuracy_graphs(historys)\n visualization.loss_graphs(historys)\n visualization.metrics_table(historys)\n\n\nif __name__ == '__main__':\n test_models(1, 15, epochs=200)\n","sub_path":"src/modeling/models/neural_net/exploration.py","file_name":"exploration.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"643924774","text":"import typing as t\r\n\r\n\r\nclass Request(t.NamedTuple):\r\n id: str\r\n field1: str\r\n field2: str\r\n\r\n def to_json(self):\r\n return self._asdict()\r\n\r\n\r\nrequests_map = {item.id: item for item in [\r\n Request(\"1\", \"test\", \"test\"),\r\n Request(\"2\", \"test\", \"test\"),\r\n Request(\"3\", \"test\", \"test\"),\r\n]}\r\n\r\n\r\ndef get_response_by_request_id(request_id: str) -> dict:\r\n if request_id == \"Cham\":\r\n name = \"Cham\"\r\n elif request_id == \"Serhii\":\r\n name = \"Serhii\"\r\n elif request_id == \"Ivan\":\r\n name = \"Ivan\"\r\n else:\r\n return {}\r\n return {\"hello\": name}\r\n\r\n\r\ndef get_request_list() -> t.List[Request]:\r\n return list(requests_map.values())\r\n\r\n\r\ndef create_request(data: dict) -> t.Union[Request, None]:\r\n item = Request(**data)\r\n if requests_map.get(item.id):\r\n return None\r\n requests_map[item.id] = item\r\n return item\r\n\r\n\r\ndef get_request(request_id: str) -> t.Union[Request, None]:\r\n return requests_map.get(request_id)\r\n\r\n\r\ndef edit_request(request_id, data) -> t.Union[Request, None]:\r\n new_item = Request(**data)\r\n if not requests_map.get(request_id):\r\n return None\r\n requests_map[request_id] = new_item\r\n return new_item\r\n\r\n\r\ndef delete_request(request_id: str) -> bool:\r\n if not requests_map.get(requests_map):\r\n return False\r\n del requests_map[request_id]\r\n return True\r\n","sub_path":"awsgi_poc/server/apis/privacy/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"38865008","text":"from django.urls import path\nfrom .views import LoginView,RegisterView,ActiveView,ForgetPwdView,ModifyPwdView,ResetView,user_logout\nfrom . import views\napp_name = 'users'\n\nurlpatterns = [\n path('login/',LoginView.as_view(),name='login'),\n path('register/',RegisterView.as_view(),name='register'),\n path('active//',ActiveView.as_view(),name='active'),\n path('forget/',ForgetPwdView.as_view(),name='forget'),\n path('reset//',ResetView.as_view(),name='reset'),\n path('modify_pwd/',ModifyPwdView.as_view(),name='modify_pwd'),\n path(\"logout/\",user_logout,name='logout'),\n path(\"info/\",views.UserinfoView.as_view(),name='user_info'),\n path(\"image/upload/\",views.UploadImageView.as_view(),name='image_upload'),\n path(\"update/pwd/\",views.UpdatePwdView.as_view(),name='update_pwd'),\n path(\"send_email_code/\",views.SendEmailCodeView.as_view(),name='send_email_coe'),\n path(\"update_email/\",views.UpdateEmailView.as_view(),name='update_email'),\n path(\"my_course/\",views.MyCourseView.as_view(),name='my_course'),\n path('my_fav/org/',views.MyFavOrgView.as_view(),name='myfav_org'),\n path(\"my_fav/teacher/\",views.MyFavTeacher.as_view(),name='myfav_teacher'),\n path('my_fav/course/',views.MyFavCourse.as_view(),name='myfav_course'),\n path('my_message/',views.MyMessageView.as_view(),name='my_message')\n]\n\n","sub_path":"apps/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"433849539","text":"import const_dbms\nimport dbms\n\nconstSQLSelect = \"SELECT substr(a.pubdate,1,4) || '-' || substr(a.pubdate,5,2) || '-' || substr(a.pubdate,7,2) pubdate, a.seq, a.title, a.itemcount, a.firstitemseq FROM tb_article a ORDER BY a.pubdate DESC\"\n\ndef selectArticle():\n print(\"Start selectArticle\")\n conn = const_dbms.get_conn()\n cur = conn.cursor()\n cur.execute(constSQLSelect)\n return cur.fetchall()\n\nif __name__ == '__main__':\n selectArticle()\n","sub_path":"db_article_list.py","file_name":"db_article_list.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"93969112","text":"# credit to: https://leetcode.com/problems/stone-game-ii/discuss/345354/Java-DP-with-memorization-easy-to-understand(with-explanation)\n# Min max problem\n\nclass Solution(object):\n def stoneGameII(self, piles):\n \"\"\"\n :type piles: List[int]\n :rtype: int\n \"\"\"\n n = len(piles)\n if n < 1:\n return 0\n total = [0] * n\n total[-1] = piles[-1]\n for i in range(n-2, -1, -1):\n total[i] = total[i+1] + piles[i]\n \n dp = [[0] * n for _ in range(n)]\n \n def helper(i, M):\n if i == n:\n return 0\n if 2*M >= n - i:\n return total[i]\n if dp[i][M] != 0:\n return dp[i][M]\n min_ = float('inf')\n for x in range(1, 2*M+1):\n min_ = min(min_, helper(i+x, max(M, x)))\n dp[i][M] = total[i] - min_\n return dp[i][M]\n \n return helper(0, 1)\n \nclass Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n n = len(piles)\n dp = [[0 for _ in range(n)] for _ in range(n+1)]\n \n def solve(s, M):\n if s >= n:\n return 0\n M = min(n, M)\n if dp[s][M]:\n return dp[s][M]\n if s + 2 * M >= n:\n dp[s][M] = sum(piles[s:])\n return dp[s][M]\n \n best = float('-inf')\n curr = 0\n for x in range(1, 2 * M + 1):\n curr += piles[s+x-1]\n best = max(best, curr - solve(s+x, max(x, M)))\n dp[s][M] = best\n return dp[s][M]\n \n return (sum(piles) + solve(0, 1)) // 2\n \n \n","sub_path":"python/1140 Stone Game II.py","file_name":"1140 Stone Game II.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"383328434","text":"from linkedListFIFO import LinkedListFIFO\nfrom node import Node\n\nclass KthFromLast(LinkedListFIFO):\n def find_kth_to_last(self, k):\n p1, p2 = self.head, self.head\n i = 0\n while p1:\n if i > k-1:\n try:\n p2 = p2.pointer\n except AttributeError:\n break\n p1 = p1.pointer\n i += 1\n return p2.value\n\nk = KthFromLast()\nfor i in range(1, 11):\n k.addNode(i)\nk._printList()\n\nk_from_last = k.find_kth_to_last(3)\n\nprint(k_from_last)","sub_path":"파이썬 자료구조와 알고리즘/Algorithm/7. 추상 데이터 타입/eg_find_kth_from_the_end.py","file_name":"eg_find_kth_from_the_end.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"2937418","text":"\"\"\"\nterraclimate19611990\n global 1/24deg M:Monthly normals using TerraClimate\n\"\"\"\n\n# http://thredds.northwestknowledge.net:8080/thredds/terraclimate_aggregated.html\n\nimport pandas as pd\nfrom toolbox_utils import tsutils\n\nfrom tsgettoolbox import utils\n\n__all__ = [\"terraclimate19611990\"]\n\n_avail_vars = {\n \"aet\": {\n \"sname\": \"aet\",\n \"lname\": \"actual_et\",\n \"standard_name\": \"aet\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_aet.nc\",\n },\n \"def\": {\n \"sname\": \"def\",\n \"lname\": \"climate_water_deficit\",\n \"standard_name\": \"def\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_def.nc\",\n },\n \"pet\": {\n \"sname\": \"pet\",\n \"lname\": \"potential_et\",\n \"standard_name\": \"pet\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_pet.nc\",\n },\n \"ppt\": {\n \"sname\": \"ppt\",\n \"lname\": \"precipitation\",\n \"standard_name\": \"ppt\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_ppt.nc\",\n },\n \"q\": {\n \"sname\": \"q\",\n \"lname\": \"runoff\",\n \"standard_name\": \"q\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_q.nc\",\n },\n \"soil\": {\n \"sname\": \"soil\",\n \"lname\": \"soil_moisture\",\n \"standard_name\": \"soil\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_soil.nc\",\n },\n \"swe\": {\n \"sname\": \"swe\",\n \"lname\": \"snow_water_equivalent\",\n \"standard_name\": \"swe\",\n \"units\": \"mm\",\n \"vname\": \"TerraClimate19611990_swe.nc\",\n },\n \"tmin\": {\n \"sname\": \"tmin\",\n \"lname\": \"minimum_daily_temperature\",\n \"standard_name\": \"tmin\",\n \"units\": \"degC\",\n \"vname\": \"TerraClimate19611990_tmin.nc\",\n },\n \"tmax\": {\n \"sname\": \"tmax\",\n \"lname\": \"maximum_daily_temperature\",\n \"standard_name\": \"tmax\",\n \"units\": \"degC\",\n \"vname\": \"TerraClimate19611990_tmax.nc\",\n },\n}\n\n\n@tsutils.transform_args(start_date=pd.to_datetime, end_date=pd.to_datetime)\n@tsutils.doc(tsutils.docstrings)\ndef terraclimate19611990(\n lat: float,\n lon: float,\n variables=None,\n start_date=None,\n end_date=None,\n):\n r\"\"\"global:1/24deg::M:Monthly normals using TerraClimate monthly data from 1961 to 1990.\n\n method: These layers from TerraClimate were derived from the essential\n climate variables of TerraClimate. Water balance variables, actual\n evapotranspiration, climatic water deficit, runoff, soil moisture, and snow\n water equivalent were calculated using a water balance model and plant\n extractable soil water capacity derived from Wang-Erlandsson et al (2016).\n\n title: TerraClimate: monthly climate and climatic water balance for global\n land surfaces\n\n summary: This archive contains a dataset of high-spatial resolution\n (1/24deg, ~4-km) monthly climate and climatic water balance for global\n terrestrial surfaces from 1958-2015. These data were created by using\n climatically aided interpolation, combining high-spatial resolution\n climatological normals from the WorldClim version 1.4 and version\n 2 datasets, with coarser resolution time varying (i.e. monthly) data from\n CRU Ts4.0 and JRA-55 to produce a monthly dataset of precipitation, maximum\n and minimum temperature, wind speed, vapor pressure, and solar radiation.\n TerraClimate additionally produces monthly surface water balance datasets\n using a water balance model that incorporates reference evapotranspiration,\n precipitation, temperature, and interpolated plant extractable soil water\n capacity.\n\n method: These layers from TerraClimate were creating using climatically\n aided interpolation of monthly anomalies from the CRU Ts4.0 and Japanese\n 55-year Reanalysis (JRA-55) datasets with WorldClim v2.0 climatologies.\n\n keywords: WORLDCLIM,global,monthly,\n temperature,precipitation,wind,radiation,vapor\n pressure,evapotranspiration,water balance,soil water capacity,snow water\n equivalent,runoff\n\n history: Created by John Abatzoglou, University of California Merced\n\n creator_url: climate.nkn.uidaho.edu/TerraClimate\n\n creator_email: jabatzoglou at ucmerced.edu\n\n institution: University of California Merced\n\n project: Global Dataset of Monthly Climate and Climatic Water Balance\n (1958-2015)\n\n acknowledgment: Please cite the references included herein. We also\n acknowledge the WorldClim datasets (Fick and Hijmans, 2017; Hijmans et al.,\n 2005) and the CRU Ts4.0 (Harris et al., 2014) and JRA-55 (Kobayashi et al.,\n 2015) datasets.\n\n geospatial_lat_min: -89.979164\n\n geospatial_lat_max: 89.979164\n\n geospatial_lon_min: -179.97917\n\n geospatial_lon_max: 179.97917\n\n time_coverage_start: 1958-01-01T00:0\n\n time_coverage_end: present\n\n time_coverage_resolution: P1M\n\n standard_nam_vocabulary: CF-1.0\n\n license: No restrictions\n\n geospatial_lat_units: decimal degrees north\n\n geospatial_lat_resolution: -0.041666668\n\n geospatial_lon_units: decimal degrees east\n\n geospatial_lon_resolution: 0.041666668\n\n references: Abatzoglou, J.T., S.Z. Dobrowski, S.A. Parks, and K.C.\n Hegewisch, 2017, High-resolution global dataset of monthly climate and\n climatic water balance from 1958-2015, submitted to Scientific Data.\n\n source: WorldClim v2.0 (2.5m), CRU Ts4.0, JRA-55\n\n version: v1.0\n\n Conventions: CF-1.6\n\n Parameters\n ----------\n ${lat}\n\n ${lon}\n\n variables : str\n At the command line can supply a comma separated list of variable\n names. Using the Python API needs to be a Python list of strings.\n\n The current list of available variables are in the following table.\n\n +--------+----------------------------------+-----------+\n | Short | Long | Units |\n +========+==================================+===========+\n | aet | Actual ET | mm |\n +--------+----------------------------------+-----------+\n | def | Climate water deficit | mm |\n +--------+----------------------------------+-----------+\n | pet | Reference ET | mm |\n +--------+----------------------------------+-----------+\n | q | Runoff | mm |\n +--------+----------------------------------+-----------+\n | soil | Soil moisture | mm |\n +--------+----------------------------------+-----------+\n | swe | Snow water equivalence | mm |\n +--------+----------------------------------+-----------+\n | tmax | maximum temperature | degC |\n +--------+----------------------------------+-----------+\n | tmin | minimum temperature | degC |\n +--------+----------------------------------+-----------+\n | vap | Vapor pressure | kPa |\n +--------+----------------------------------+-----------+\n | vpd | Vapor pressure deficit | kPa |\n +--------+----------------------------------+-----------+\n | ws | wind_speed | m/s |\n +--------+----------------------------------+-----------+\n\n ${start_date}\n\n ${end_date}\n \"\"\"\n turl = \"http://thredds.northwestknowledge.net:8080/thredds/dodsC/TERRACLIMATE_ALL/summaries/TerraClimate19611990_{}.nc\"\n\n df = utils.opendap(\n turl,\n lat,\n lon,\n _avail_vars,\n variables=variables,\n start_date=start_date,\n end_date=end_date,\n time_name=\"time\",\n single_var_url=True,\n )\n\n df = df.rename(columns=lambda x: f\"{x}:19611990\")\n\n return df\n\n\nif __name__ == \"__main__\":\n r = terraclimate19611990(29.6, -82.3)\n print(r)\n","sub_path":"src/tsgettoolbox/functions/terraclimate19611990.py","file_name":"terraclimate19611990.py","file_ext":"py","file_size_in_byte":7966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"645498652","text":"import sys\nimport os\nimport json\nimport multiprocessing\n\nimport line_plotter\nimport load_csv\n\nkColors = ('red', 'green', 'blue', 'cyan', 'yellow', 'magenta')\n\n\ndef plot(plot_config: dict):\n plotter = line_plotter.LinePlotter()\n data = load_csv.load(filename=plot_config['file'],\n index=plot_config['index'])\n data = tuple(zip(*data))\n for i, y in enumerate(data[1:]):\n plotter.add_line(ys=y, xs=data[0], color=kColors[i % len(kColors)])\n plotter.draw(title=plot_config['title'])\n\n\ndef main():\n assert len(sys.argv) == 2, 'no parameter, it should be one json config'\n path_config = sys.argv[1]\n assert os.path.isfile(path_config), 'config not found'\n assert path_config.endswith('.json'), 'run tk_plotter.py CONFIG.json'\n with open(path_config) as fi:\n config = json.loads(fi.read())\n assert type(config) == type([]), 'config must contain a list'\n assert all(type(e) == type(dict())\n for e in config), 'each element must be dict'\n assert all(i in e for e in config\n for i in ('file', 'index', 'title')), 'config not complete'\n assert all(len(pc['index']) >= 2\n for pc in config), 'index not enough, must be at least [x,y1]'\n if any(len(pc['index']) >= len(kColors) for pc in config):\n print('too many lines, will reuse color')\n\n processes = []\n for plot_config in config:\n print(plot_config)\n processes.append(\n multiprocessing.Process(target=plot, args=(plot_config, )))\n processes[-1].start()\n for p in processes:\n p.join()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tk_plotter.py","file_name":"tk_plotter.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"613326835","text":"import risar\r\nimport random\r\nfrom random import randint\r\nimport math\r\nimport time\r\n\r\nclass Krog:\r\n\r\n def __init__(self):\r\n zacetna = self.zaceznaPozicija()\r\n self.x = zacetna[0]\r\n self.y = zacetna[1]\r\n self.vX = random.uniform(-5.0, 5.0)\r\n self.vY = randint(0, 1)\r\n self.polmer = 10\r\n self.barva = risar.barva(randint(0, 255), randint(0, 255), randint(0, 255))\r\n self.sirina = 2\r\n self.krog = risar.krog(self.x, self.y, self.polmer, self.barva, self.sirina)\r\n\r\n def zaceznaPozicija(self):\r\n while(1):\r\n tmp = risar.nakljucne_koordinate()\r\n if tmp[0] >= 15 and tmp[0] <= risar.maxX - 15 and tmp[1] >= 15 and tmp[1] <= risar.maxY - 15:\r\n return tmp\r\n\r\n def novaPozicija(self):\r\n self.x += self.vX\r\n if self.vY:\r\n self.y += math.sqrt(5**2 - self.vX**2)\r\n else:\r\n self.y -= math.sqrt(5**2 - self.vX**2)\r\n\r\n def preveri(self):\r\n if self.x > risar.maxX - 15 or self.x < 15:\r\n self.vX *= -1\r\n if self.y > risar.maxY - 15:\r\n self.vY = False\r\n if self.y < 15:\r\n self.vY = True\r\n\r\nkrogci = []\r\nfor i in range(30):\r\n krogci.append(Krog())\r\n\r\nrisar.cakaj(0.5)\r\nkonec = time.time() + 20\r\n\r\nwhile(1):\r\n if time.time() > konec:\r\n break\r\n\r\n for a in krogci:\r\n a.preveri()\r\n a.novaPozicija()\r\n a.krog.setPos(a.x, a.y)\r\n\r\n risar.obnovi()\r\n risar.cakaj(0.02)\r\n","sub_path":"code/batch-2/vse-naloge-brez-testov/DN14-M-047.py","file_name":"DN14-M-047.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"346453377","text":"import os\nimport sys\n\nimport xlrd, xlwt\nimport numpy as np\nimport csv\n\n\ndef create():\n xlses = []\n\n for xls in xlses:\n print(xls)\n mouses_info = [[[] for i in range(8)] for j in range(8)]\n\n dates = [[], []]\n\n with open(os.path.join('csvs', xls), newline='') as csvfile:\n data = list(csv.reader(csvfile))[1:]\n\n print(data[:10])\n if len(data) > 20:\n data = np.array(data).T.tolist()\n\n mouses_info = [[data[8 * m + i] for i in range(8)] for m in range(8)]\n dates = data[-2:]\n\n for m in range(8):\n mouses_info[m] = np.array(mouses_info[m]).T.astype(float).tolist()\n\n for m in range(8):\n # sheet1 = xlwt.Workbook()\n # table = sheet1.add_sheet('data from mouse %d' % m)\n\n to_csv = []\n\n xls_ind = 0\n for _ in range(len(mouses_info[m])):\n if _ == 0:\n body_speed = 0\n head_speed = 0\n speed_vect = [1, 0]\n prev_head_body_dist = 10\n prev_head_body_vect = [1, 0]\n else:\n body_speed = np.sum((np.array([mouses_info[m][_][0], mouses_info[m][_][1]]) - np.array(\n [mouses_info[m][_ - 1][0], mouses_info[m][_ - 1][1]])) ** 2)\n body_speed = np.sqrt(body_speed)\n\n head_speed = np.sum((np.array([mouses_info[m][_][2], mouses_info[m][_][3]]) - np.array(\n [mouses_info[m][_ - 1][2], mouses_info[m][_ - 1][3]])) ** 2)\n head_speed = np.sqrt(head_speed)\n\n speed_vect = np.array([mouses_info[m][_][0], mouses_info[m][_][1]]) - np.array([mouses_info[m][_ - 1][0], mouses_info[m][_ - 1][1]])\n\n if _ != len(mouses_info[m]) - 1:\n next_body_speed = np.sum((np.array([mouses_info[m][_ + 1][0], mouses_info[m][_ + 1][1]]) - np.array(\n [mouses_info[m][_][0], mouses_info[m][_][1]])) ** 2)\n next_body_speed = np.sqrt(next_body_speed)\n\n next_head_speed = np.sum((np.array([mouses_info[m][_ + 1][2], mouses_info[m][_ + 1][3]]) - np.array(\n [mouses_info[m][_][2], mouses_info[m][_][3]])) ** 2)\n next_head_speed = np.sqrt(next_head_speed)\n else:\n next_body_speed = 0\n next_head_speed = 0\n\n # acceleration\n body_acceleration = next_body_speed - body_speed\n head_acceleration = next_head_speed - head_speed\n\n # mean coordinates (percent of cage size)\n body_coord = [mouses_info[m][_][0], mouses_info[m][_][1] / 480]\n # if m == 0:\n # body_coord[0] = float(body_coord[0]) / 270 # left cage\n # if m == 1:\n # body_coord[0] = float(body_coord[0] - 270) / 270 # right cage\n\n head_coord = [mouses_info[m][_][2], mouses_info[m][_][3] / 480]\n # if m == 0:\n # head_coord[0] = float(head_coord[0]) / 270 # left cage\n # if m == 1:\n # head_coord[0] = float(head_coord[0] - 270) / 270 # right cage\n\n head_body_vect = np.array([mouses_info[m][_][2], mouses_info[m][_][3]]) - np.array([mouses_info[m][_][0], mouses_info[m][_][1]])\n head_body_dist = np.linalg.norm(head_body_vect)\n head_body_dist_change = head_body_dist - prev_head_body_dist\n\n if np.linalg.norm(speed_vect) != 0:\n cos = np.dot(head_body_vect, speed_vect) / (np.linalg.norm(speed_vect) * head_body_dist)\n\n if np.isnan(cos):\n cos = 1\n\n sin = np.sqrt(1 - cos * cos)\n\n else:\n cos = 1\n sin = 0\n body_speed_x = body_speed * cos\n body_speed_y = body_speed * sin\n\n head_speed_x = head_speed * cos\n head_speed_y = head_speed * sin\n\n if head_body_dist != 0 and prev_head_body_dist != 0:\n if np.array_equal(head_body_vect, prev_head_body_vect):\n head_rotation = 0\n else:\n head_rotation = np.arccos(np.dot(head_body_vect, prev_head_body_vect) / (head_body_dist * prev_head_body_dist))\n\n if np.isnan(head_rotation):\n head_rotation = 0\n else:\n head_rotation = 0\n\n\n # avg temperature\n temp = mouses_info[m][_][6]\n\n # time\n\n # print(dates[1])\n h, minutes, s = (dates[1][_].split()[1]).split(':')\n h, minutes, s = int(h), int(minutes), int(s)\n if 'PM' in dates[1][_] and h != 12:\n h += 12\n if h == 12 and 'AM' in dates[1][_]:\n h = 0\n\n time = h * 3600 + minutes * 60 + s\n\n # TABLE\n\n # SHAPE\n # table.write(xls_ind, 0, head_body_dist)\n #\n # # MOTION\n # table.write(xls_ind, 1, body_speed_x)\n # table.write(xls_ind, 2, body_speed_y)\n # table.write(xls_ind, 3, head_speed_x)\n # table.write(xls_ind, 4, head_speed_y)\n # table.write(xls_ind, 5, head_body_dist_change)\n # table.write(xls_ind, 6, head_rotation)\n # table.write(xls_ind, 7, body_speed)\n # table.write(xls_ind, 8, head_speed)\n # table.write(xls_ind, 9, body_acceleration)\n # table.write(xls_ind, 10, head_acceleration)\n #\n # # WINDOW\n # table.write(xls_ind, 11, body_coord[0])\n # table.write(xls_ind, 12, body_coord[1])\n # table.write(xls_ind, 13, head_coord[0])\n # table.write(xls_ind, 14, head_coord[1])\n #\n # # OTHER\n # table.write(xls_ind, 15, temp)\n # table.write(xls_ind, 16, time)\n #\n # # DATES\n # table.write(xls_ind, 17, dates[0][_])\n # table.write(xls_ind, 18, dates[1][_])\n\n to_csv.append([head_body_dist,\n body_speed_x,\n body_speed_y,\n head_speed_x,\n head_speed_y,\n head_body_dist_change,\n head_rotation,\n body_speed,\n head_speed,\n body_acceleration,\n head_acceleration,\n body_coord[0],\n body_coord[1],\n head_coord[0],\n head_coord[1],\n temp,\n # time,\n dates[0][_],\n dates[1][_]])\n prev_head_body_dist = head_body_dist\n prev_head_body_vect = head_body_vect[:]\n\n xls_ind += 1\n\n with open(os.path.join('data_csv', '{}_{}'.format(m, xls)), 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerows(to_csv)\n #sheet1.save(os.path.join('check', dirname, 'xlses', 'data', '{}_{}.xls'.format(m, subdirname)))\n\n\nif __name__ == '__main__':\n create()","sub_path":"new_recording/create_data.py","file_name":"create_data.py","file_ext":"py","file_size_in_byte":7765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"511062880","text":"import sys\n\n\ndef show_sizeof(x, level=0):\n print(\"\\t\" * level, x.__class__, sys.getsizeof(x), x)\n if hasattr(x, '__iter__'):\n if hasattr(x, 'items'):\n for xx in x.items:\n show_sizeof(xx, level + 1)\n else:\n for xx in x:\n show_sizeof(xx, level + 1)\n\nd_letter= {}\nd = {}\nfile = open('text.txt', 'r')\nfor line in file:\n line = line.rstrip()\n for words in line.split(' '):\n for letters in words:\n if d_letter.get(letters) != None:\n d_letter[letters] += 1\n else:\n d_letter[letters] = 1\n\n if d.get(words) != None:\n d[words] += 1\n else:\n d[words] = 1\n\nmax = 0\nword = 'a'\nfor i in d:\n if d[i]>max:\n max = d[i]\n word = i\nprint(max, word)\nmax = 0\nletter = 'a'\nfor i in d_letter:\n if d_letter[i]>max:\n max = d_letter[i]\n letter = i\nprint(max, letter)\n","sub_path":"StandLib.py","file_name":"StandLib.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"49950974","text":"from flask import Flask\nfrom . import main\nfrom flask import render_template,redirect, request, url_for,abort,flash\nfrom flask_login import login_required, current_user\nfrom ..models import User,Blog,Comment\nfrom .forms import BlogForm,UpdateProfile,CommentForm\nfrom .. import db, photos\n\n\napp = Flask(__name__)\n\n\n# views\n@main.route(\"/\")\ndef index():\n\n title = 'Get started with a HURRICANE CLEANING SERVICES'\n blogs= Blog.query.all()\n\n return render_template('index.html', title= title,blogs=blogs)\n\n@main.route('/user/')\ndef profile(uname):\n user = User.query.filter_by(username = uname).first()\n\n if user is None:\n abort(404)\n\n return render_template(\"profile/profile.html\", user = user)\n\n@main.route('/user//update',methods = ['GET','POST'])\n@login_required\ndef update_profile(uname):\n user = User.query.filter_by(username = uname).first()\n if user is None:\n abort(404)\n\n form = UpdateProfile()\n\n if form.validate_on_submit():\n user.bio = form.bio.data\n\n db.session.add(user)\n db.session.commit()\n\n return redirect(url_for('.profile',uname=user.username))\n\n return render_template('profile/update.html',form =form)\n\n@main.route('/user//update/pic',methods= ['POST'])\n@login_required\ndef update_pic(uname):\n user = User.query.filter_by(username = uname).first()\n if 'photo' in request.files:\n filename = photos.save(request.files['photo'])\n path = f'photos/{filename}'\n user.profile_pic_path = path\n db.session.commit()\n\n\n return redirect(url_for('main.profile',uname=uname))\n\n\n\n@main.route('/blog/new', methods=['GET', 'POST'])\n@login_required\ndef new_blog():\n form= BlogForm()\n\n if form.validate_on_submit():\n title = form.title.data\n content = form.content.data\n category = form.category.data\n\n blog = Blog(title = title,content = content, category = category)\n\n db.session.add(blog)\n db.session.commit()\n\n print('blog')\n flash('Creating blog has been successful!')\n return redirect(url_for('main.one_blog', id = blog.id))\n\n\n return render_template('new_blog.html', title='New Blog',blog_form = form, legend = 'New Blog')\n\n@main.route('/blog/new/')\ndef one_blog(id):\n blog = Blog.query.get(id)\n return render_template('blog.html', blog = blog)\n\n\n\n@main.route('/blog//',methods = [\"GET\",\"POST\"])\ndef blog(blog_id):\n blog = Blog.query.filter_by(id=blog_id)\n form = CommentForm()\n\n if form.validate_on_submit():\n\n comment = form.comment.data\n new_blog_comment = Comment(comment=comment,blog_id = blog_id)\n\n db.session.add(new_blog_comment)\n db.session.commit()\n\n comments = Comment.query.filter_by(blog_id=blog_id)\n return render_template('comments.html', title = 'blog', blog =blog, blog_form = form, comments = comments)\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"532588642","text":"import itertools,sys,math\n\ndef divisor(number):\n for i in range(2,number):\n if number % i == 0:\n# print(i, 'divisor')\n return i\n\ndef not_prime(n):\n for i in range(3,n):\n if n % i != 0:\n return True\n return False\n\ndef is_primeX(n):\n for i in range(3, n):\n if n % i == 0:\n# print(i, 'prime False')\n return False\n #print(i, 'prime True')\n return True\n\ndef is_prime(n):\n if n % 2 == 0 and n > 2: \n return False\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef isJamX(number):\n if(number[0] == '1' and number[-1] == '1'):\n arr = []\n for i in range(2,11):\n num = int(number,i)\n if(not_prime(num)):\n arr.append(divisor(num))\n else:\n return(False,[])\n return(True, arr)\n \n return(False,[])\n\ndef isJam(number):\n if(number[0] == '1' and number[-1] == '1'):\n arr = []\n for i in range(2,11):\n num = int(number,i)\n# print(i, num, 'isJam')\n #print(num, is_prime(num), divisor(num))\n if(is_prime(num)):\n return (False,[])\n arr.append(divisor(num))\n return (True,arr)\n return (False,[])\n\ndef makeJam(N, J):\n\n num = 0\n arr = list(itertools.product([0,1], repeat = N))\n ret = []\n for i in arr:\n if(num == J): return ret\n temp1 = ''.join(map(str,i))\n temp2 = isJam(temp1)\n if(temp2[0]):\n #print(temp1, ' '.join(map(str,temp2[1])))\n ret.append(temp1 + ' ' + ' '.join(map(str,temp2[1])))\n num += 1\n \n\nif __name__ == \"__main__\":\n f = sys.stdin\n t = int(f.readline())\n arr = dict()\n for i in range(1,t+1):\n line = f.readline().strip().split()\n arr[i] = makeJam(int(line[0]),int(line[1]))\n for j in arr:\n print(\"Case #%d:\" % (j))\n for k in arr[j]:\n print(k)\n","sub_path":"codes/CodeJamCrawler/16_0_3_neat/16_0_3_iammatis_JamCoin.py","file_name":"16_0_3_iammatis_JamCoin.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"499876960","text":"import paho.mqtt.client as mqtt\nimport json\nimport fastavro\nfrom io import BytesIO\nimport logging\n\nlogger = logging.getLogger(\"AstroPlant\")\n\nclass Client(object):\n \"\"\"\n AstroPlant API Client class implementing methods to interact with the AstroPlant API.\n \"\"\"\n\n def __init__(self, host, port, keepalive=60, auth={}):\n self.connected = False\n \n self._mqtt_client = mqtt.Client()\n self._mqtt_client.on_connect = self._on_connect\n self._mqtt_client.on_disconnect = self._on_disconnect\n self._mqtt_client.on_message = self._on_message\n \n self._mqtt_client.reconnect_delay_set(min_delay=1, max_delay=128)\n\n with open('./schema/aggregate.avsc', 'r') as f:\n self._aggregate_schema = fastavro.parse_schema(json.load(f))\n\n with open('./schema/stream.avsc', 'r') as f:\n self._stream_schema = fastavro.parse_schema(json.load(f))\n\n if auth:\n self.serial = auth['serial']\n self._mqtt_client.username_pw_set(username=auth['serial'], password=auth['secret'])\n else:\n self.serial = 'anon'\n \n self._mqtt_client.connect_async(host=host, port=port, keepalive=keepalive)\n\n def start(self):\n \"\"\"\n Start the client background thread.\n \"\"\"\n self._mqtt_client.loop_start()\n\n def stop(self):\n \"\"\"\n Stop the client background thread.\n \"\"\"\n self._mqtt_client.loop_stop()\n\n def _on_connect(self, client, user_data, flags, rc):\n self.connected = True\n\n def _on_disconnect(self, client, user_data, rc):\n self.connected = False\n\n def _on_message(self, client, user_data, msg):\n topic = msg.topic\n payload = msg.payload\n\n def publish_stream_measurement(self, measurement):\n \"\"\"\n Publish a (real-time) stream measurement.\n \"\"\"\n msg = BytesIO()\n fastavro.schemaless_writer(\n msg,\n self._stream_schema,\n {\n 'peripheral': measurement.peripheral.get_name(),\n 'physical_quantity': measurement.physical_quantity,\n 'physical_unit': measurement.physical_unit,\n 'datetime': round(measurement.end_datetime.timestamp() * 1000),\n 'value': measurement.value\n }\n )\n\n self._mqtt_client.publish(\n topic = f\"kit/{self.serial}/measurement/stream\",\n payload = msg.getvalue(),\n qos = 0 # Deliver at most once.\n )\n\n def publish_aggregate_measurement(self, measurement):\n \"\"\"\n Publish an aggregate measurement.\n \"\"\"\n msg = BytesIO()\n fastavro.schemaless_writer(\n msg,\n self._aggregate_schema,\n {\n 'kit_serial': '', # Filled on the backend-side for security reasons.\n 'peripheral': measurement.peripheral.get_name(),\n 'physical_quantity': measurement.physical_quantity,\n 'physical_unit': measurement.physical_unit,\n 'start_datetime': round(measurement.start_datetime.timestamp() * 1000),\n 'end_datetime': round(measurement.end_datetime.timestamp() * 1000),\n 'type': measurement.aggregate_type,\n 'value': measurement.value\n }\n )\n\n self._mqtt_client.publish(\n topic = f\"kit/{self.serial}/measurement/aggregate\",\n payload = msg.getvalue(),\n qos = 2 # Deliver exactly once. Maybe downgrade to `1`: deliver at least once.\n )\n","sub_path":"astroplant_kit/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"523318070","text":"class Solution(object):\n def reorderLogFiles(self, logs):\n \"\"\"\n :type logs: List[str]\n :rtype: List[str]\n \"\"\"\n\n\n lets = sorted([x for x in logs if x.split()[1].islower()], key = lambda a: a.split()[1:])\n digs = [x for x in logs if x.split()[1].isdigit()]\n return lets + digs\n\nprint(Solution().reorderLogFiles([\"27 85717 7\", \"2 y xyr fc\", \"52 314 99\", \"d 046099 0\", \"m azv x f\", \"7e apw c y\", \"8 hyyq z p\", \"6 3272401\", \"c otdk cl\", \"8 ksif m u\"]))\n","sub_path":"LeetCodeContests/110/reorder_log_files.py","file_name":"reorder_log_files.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"182978645","text":"# -*- coding: UTF-8 -*-\nimport string\nimport nonebot\nimport urllib\nimport traceback\nimport os\n#引入配置\nimport config\n#日志输出\nfrom helper import data_read,data_save,getlogger,msgSendToBot\nlogger = getlogger(__name__)\n#引入测试方法\ntest = None\ntry:\n import test\nexcept:\n pass\n'''\n推送列表维护,及推送处理模版类定义\n'''\n\nPushList_config_name = 'PushListData.json'\nbase_tweet_id = config.base_tweet_id\n\n#10进制转64进制\ndef encode_b64(n:int) -> str:\n table = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'\n result = []\n temp = n - 1253881609540800000\n if 0 == temp:\n result.append('0')\n else:\n while 0 < temp:\n result.append(table[int(temp) % 64])\n temp = int(temp)//64\n return ''.join([x for x in reversed(result)])\ndef decode_b64(str):\n table = {\"0\": 0, \"1\": 1, \"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5,\n \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9,\n \"a\": 10, \"b\": 11, \"c\": 12, \"d\": 13, \"e\": 14, \"f\": 15, \"g\": 16,\n \"h\": 17, \"i\": 18, \"j\": 19, \"k\": 20, \"l\": 21, \"m\": 22, \"n\": 23,\n \"o\": 24, \"p\": 25, \"q\": 26, \"r\": 27, \"s\": 28, \"t\": 29, \"u\": 30,\n \"v\": 31, \"w\": 32, \"x\": 33, \"y\": 34, \"z\": 35,\n \"A\": 36, \"B\": 37, \"C\": 38, \"D\": 39, \"E\": 40, \"F\": 41, \"G\": 42,\n \"H\": 43, \"I\": 44, \"J\": 45, \"K\": 46, \"L\": 47, \"M\": 48, \"N\": 49,\n \"O\": 50, \"P\": 51, \"Q\": 52, \"R\": 53, \"S\": 54, \"T\": 55, \"U\": 56,\n \"V\": 57, \"W\": 58, \"X\": 59, \"Y\": 60, \"Z\": 61,\n \"$\": 62, \"_\": 63}\n result = 0\n for i in range(len(str)):\n result *= 64\n result += table[str[i]]\n return result + 1253881609540800000\n#推送列表\nclass PushList:\n #映射推送关联(推送对象(type:str,ID:int)->推送单元)\n __push_list = {\n 'private':{},\n 'group':{}\n } \n __spy_relate = {} #映射对象关联(监测ID(ID:int)->推送单元)\n spylist = [str(base_tweet_id)] #流监测列表\n \n #支持的消息类型\n message_type_list = ('private','group') \n #推送单元允许编辑的配置_布尔类型\n Pushunit_allowEdit = (\n #携带图片发送\n 'upimg',\n #消息模版\n 'retweet_template','quoted_template','reply_to_status_template',\n 'reply_to_user_template','none_template',\n #推特转发各类型开关\n 'retweet','quoted','reply_to_status',\n 'reply_to_user','none',\n #推特个人信息变动推送开关\n 'change_ID','change_name','change_description',\n 'change_headimgchange'\n )\n \"\"\"\n 推送列表-》推送列表、监测人信息关联表及监测人单的列表-》推送单元\n 注:每个推送单元绑定一个推特用户ID以及一个推送对象(群或QQ)\n 注:推送单元的配置由其推送对象全局配置以及自身DIY设置共同完成\n \"\"\"\n #清空推送设置\n def clear(self):\n self.__push_list = {\n 'private':{},\n 'group':{}\n } \n self.__spy_relate = {} #映射对象关联(监测ID(ID:int)->推送单元)\n self.spylist = [str(base_tweet_id)] #流监测列表\n #获取所有推送单元\n def getAllPushUnit(self) -> list:\n sourcedata = self.__spy_relate.copy()\n PushUnits = []\n for PushUnitList in sourcedata.values():\n for PushUnit in PushUnitList:\n PushUnits.append(PushUnit)\n return PushUnits\n #获取所有推送对象的全局设置信息\n def getAllPushTo(self) -> list:\n PushToAttrList = []\n sourcedata = self.__push_list.copy()\n for pushTo,frameunit in sourcedata['private'].items():\n PushToAttrList.append({\n 'message_type':'private',\n 'pushTo':pushTo,\n 'Pushunitattr':frameunit['Pushunitattr'].copy()\n })\n for pushTo,frameunit in sourcedata['group'].items():\n PushToAttrList.append({\n 'message_type':'group',\n 'pushTo':pushTo,\n 'Pushunitattr':frameunit['Pushunitattr'].copy()\n })\n return PushToAttrList\n def savePushList(self) -> tuple:\n PushUnits = self.getAllPushUnit()\n PushToAttrList = self.getAllPushTo()\n return data_save(\n PushList_config_name,\n {\n 'PushUnits':PushUnits,\n 'PushToAttrList':PushToAttrList\n },\n 'config'\n )\n def readPushList(self) -> tuple:\n data = data_read(PushList_config_name,'config')\n if data[0] != False:\n self.clear()\n for PushUnit in data[2]['PushUnits']:\n self.addPushunit(PushUnit)\n for PushToAttrs in data[2]['PushToAttrList']:\n if PushToAttrs['pushTo'] not in self.__push_list[PushToAttrs['message_type']]:\n continue\n self.__push_list[PushToAttrs['message_type']][PushToAttrs['pushTo']]['Pushunitattr'] = PushToAttrs['Pushunitattr'].copy()\n return (True,data[1])\n return data\n #打包成推送单元中(推送类型-群/私聊,推送对象-群号/Q号,绑定的推特用户ID,单元描述,绑定的酷Q账号,推送模版,各推送开关)\n def baleToPushUnit(self,bindCQID:int,\n pushtype:str,\n pushID:int,\n tweet_user_id:int,\n des:str,\n nick:str='',**config):\n Pushunit = {}\n if not config:\n config = {}\n #固有属性\n Pushunit['bindCQID'] = bindCQID #绑定的酷Q帐号(正式上线时将使用此帐户进行发送,用于适配多酷Q账号)\n Pushunit['type'] = pushtype #group/private\n Pushunit['pushTo'] = pushID #QQ号或者群号\n Pushunit['tweet_user_id'] = tweet_user_id #监测ID\n Pushunit['nick'] = nick #推送昵称(默认推送昵称为推特screen_name)\n Pushunit['des'] = des #单元描述\n Pushunit['config'] = config\n return Pushunit\n #增加一个推送单元,返回状态元组(布尔型-是否成功,字符串-消息)\n def addPushunit(self,Pushunit) -> tuple:\n if Pushunit['pushTo'] in self.__push_list[Pushunit['type']]:\n if Pushunit['tweet_user_id'] in self.__push_list[Pushunit['type']][Pushunit['pushTo']]['pushunits']:\n return ( False, '推送单元已存在' )\n else:\n #初始化推送对象(推送全局属性)\n self.__push_list[Pushunit['type']][Pushunit['pushTo']] = {\n #为推送对象设置全局默认属性\n 'Pushunitattr':config.pushunit_default_config.copy(),\n #推送单元组\n 'pushunits':{}\n }\n #添加单元至推送列表\n self.__push_list[Pushunit['type']][Pushunit['pushTo']]['pushunits'][Pushunit['tweet_user_id']] = Pushunit\n #同步监测关联(内部同步了监测列表)\n if Pushunit['tweet_user_id'] not in self.__spy_relate:\n self.__spy_relate[Pushunit['tweet_user_id']] = []\n if str(Pushunit['tweet_user_id']) != base_tweet_id:\n self.spylist.append(str(Pushunit['tweet_user_id']))\n self.__spy_relate[Pushunit['tweet_user_id']].append(Pushunit)\n return ( True, '添加成功!' )\n #删除一个推送单元,没有返回值\n def delPushunit(self,Pushunit):\n #从推送列表中移除推送单元\n del self.__push_list[Pushunit['type']][Pushunit['pushTo']]['pushunits'][Pushunit['tweet_user_id']]\n #从监测列表中移除推送单元\n self.__spy_relate[Pushunit['tweet_user_id']].remove(Pushunit)\n #检查监测对象的推送单元是否为空,为空则移出监测列表\n if self.__spy_relate[Pushunit['tweet_user_id']] == []:\n del self.__spy_relate[Pushunit['tweet_user_id']]\n if str(Pushunit['tweet_user_id']) != base_tweet_id:\n self.spylist.remove(str(Pushunit['tweet_user_id']))\n #鲨掉自己\n del Pushunit\n #获取一个推送单元,返回状态列表(布尔型-是否成功,字符串-消息/Pushunit)\n def getPushunit(self,message_type:str,pushTo:int,tweet_user_id:int) -> list:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if pushTo not in self.__push_list[message_type]:\n return (False,'推送对象不存在!')\n if tweet_user_id not in self.__push_list[message_type][pushTo]['pushunits']:\n return (False,'推送单元不存在!')\n return (True,self.__push_list[message_type][pushTo]['pushunits'][tweet_user_id])\n\n #获取推送单元某个属性的值 返回值-(布尔型-是否成功,字符串-消息/属性内容)\n def getPuslunitAttr(self,Pushunit,key) -> tuple:\n if key in Pushunit['config']:\n return (True,Pushunit['config'][key])\n if key not in self.__push_list[Pushunit['type']][Pushunit['pushTo']]['Pushunitattr']:\n return (False,'不存在此属性')\n res = self.__push_list[Pushunit['type']][Pushunit['pushTo']]['Pushunitattr'][key]\n return (True,res)\n \n #返回监测对象关联的推送单元组,监测对象不存在时返回空列表[]\n def getLitsFromTweeUserID(self,tweet_user_id:int) -> list:\n if tweet_user_id not in self.__spy_relate:\n return []\n return self.__spy_relate[tweet_user_id].copy()\n #返回推送对象关联的推送单元组,推送对象不存在时返回空列表[]\n def getLitsFromPushTo(self,message_type:str,pushTo:int) -> list:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if pushTo not in self.__push_list[message_type]:\n return []\n dict_ = self.__push_list[message_type][pushTo]['pushunits']\n res = []\n for v in dict_.values():\n res.append(v)\n return res\n #返回推送对象关联的推送单元组-带ID,推送对象不存在时返回空列表{}\n def getLitsFromPushToAndID(self,message_type:str,pushTo:int) -> dict:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if pushTo not in self.__push_list[message_type]:\n return {}\n return self.__push_list[message_type][pushTo]['pushunits']\n #返回推送对象关联的推送属性组,推送对象不存在时返回空字典{}\n def getAttrLitsFromPushTo(self,message_type:str,pushTo:int) -> dict:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if pushTo not in self.__push_list[message_type]:\n return {}\n return self.__push_list[message_type][pushTo]['Pushunitattr']\n\n #移除某个监测对象关联的所有推送单元,参数-推特用户ID 返回值-(布尔型-是否成功,字符串-消息)\n def delPushunitFromTweeUserID(self,tweet_user_id:int) -> tuple:\n if tweet_user_id not in self.__spy_relate:\n return (False,'此用户不在监测列表中!')\n table = self.getLitsFromTweeUserID(tweet_user_id)\n if table == []:\n return (True,'移除成功!')\n for Pushunit in table:\n self.delPushunit(Pushunit)\n return (True,'移除成功!')\n #移除某个推送对象关联的所有推送单元,参数-消息类型,对象ID,CQID 返回值-(布尔型-是否成功,字符串-消息)\n def delPushunitFromPushTo(self,message_type:str,pushTo:int,self_id:int = 0) -> tuple:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n table = self.getLitsFromPushTo(message_type,pushTo)\n if table == []:\n return (True,'移除成功!')\n for Pushunit in table:\n if self_id == 0 or self_id == Pushunit['bindCQID']:\n self.delPushunit(Pushunit)\n return (True,'移除成功!')\n #移除某个推送单元,参数-消息类型,对象ID 返回值-(布尔型-是否成功,字符串-消息)\n def delPushunitFromPushToAndTweetUserID(self,message_type:str,pushTo:int,tweet_user_id:int) -> tuple:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if pushTo not in self.__push_list[message_type]:\n return (False,'推送对象不存在!')\n if tweet_user_id not in self.__push_list[message_type][pushTo]['pushunits']:\n return (False,'推送单元不存在!')\n self.delPushunit(self.__push_list[message_type][pushTo]['pushunits'][tweet_user_id])\n return (True,'移除成功!')\n\n #设置指定推送对象的全局属性\n def PushTo_setAttr(self,message_type:str,pushTo:int,key:str,value) -> tuple:\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if key not in self.Pushunit_allowEdit:\n return (False,'指定属性不存在!')\n if pushTo not in self.__push_list[message_type]:\n return (False,'推送对象不存在!')\n self.__push_list[message_type][pushTo]['Pushunitattr'][key] = value\n return (True,'属性已更新')\n #设置指定推送单元的特定属性\n def setPushunitAttr(self,message_type:str,pushTo:int,tweet_user_id:int,key:str,value):\n if message_type not in self.message_type_list:\n raise Exception(\"无效的消息类型!\",message_type)\n if key not in self.Pushunit_allowEdit and key != 'nick' and key != 'des':\n return (False,'指定属性不存在!')\n if pushTo not in self.__push_list[message_type]:\n return (False,'推送对象不存在!')\n if tweet_user_id not in self.__push_list[message_type][pushTo]['pushunits']:\n return (False,'推送单元不存在!')\n if key == 'nick' or key == 'des':\n self.__push_list[message_type][pushTo]['pushunits'][tweet_user_id][key] = value\n else:\n self.__push_list[message_type][pushTo]['pushunits'][tweet_user_id]['config'][key] = value\n return (True,'属性已更新')\n#字符串模版\nclass tweetToStrTemplate(string.Template):\n delimiter = '$'\n idpattern = '[a-z]+_[a-z_]+'\n\nclass tweetEventDeal:\n #用户信息维护列表\n userinfolist = {}\n #检测个人信息更新\n def check_userinfo(self, userinfo):\n \"\"\"\n 运行数据比较\n 用于监测用户的信息修改\n 用户ID screen_name\n 用户昵称 name\n 描述 description\n 头像 profile_image_url\n \"\"\"\n \"\"\"\n tweetinfo['user']['id'] = tweet.user.id\n tweetinfo['user']['id_str'] = tweet.user.id_str\n tweetinfo['user']['name'] = tweet.user.name\n tweetinfo['user']['description'] = tweet.user.description\n tweetinfo['user']['screen_name'] = tweet.user.screen_name\n tweetinfo['user']['profile_image_url'] = tweet.user.profile_image_url\n tweetinfo['user']['profile_image_url_https'] = tweet.user.profile_image_url_https\n \"\"\"\n if userinfo['id'] in self.userinfolist:\n old_userinfo = self.userinfolist[userinfo['id']]\n data = {}\n str = ''\n if old_userinfo['name'] != userinfo['name']:\n data['type'] = 'change_name'\n str = old_userinfo['name'] + \"(\" + old_userinfo['screen_name'] + \")\" + \\\n ' 的昵称已更新为 ' + userinfo['name'] + \"(\" + userinfo['screen_name'] + \")\"\n old_userinfo['name'] = userinfo['name']\n if old_userinfo['description'] != userinfo['description']:\n data['type'] = 'change_description'\n str = old_userinfo['name'] + \"(\" + old_userinfo['screen_name'] + \")\" + ' 的描述已更新为 ' + userinfo['description']\n old_userinfo['description'] = userinfo['description']\n if old_userinfo['screen_name'] != userinfo['screen_name']:\n data['type'] = 'change_ID'\n str = old_userinfo['name'] + \"(\" + old_userinfo['screen_name'] + \")\" + \\\n ' 的ID已更新为 ' + userinfo['name'] + \"(\" + userinfo['screen_name'] + \")\"\n old_userinfo['screen_name'] = userinfo['screen_name']\n if old_userinfo['profile_image_url_https'] != userinfo['profile_image_url_https']:\n data['type'] = 'change_headimgchange'\n str = old_userinfo['name'] + \"(\" + old_userinfo['screen_name'] + \")\" + '的头像已更新'\n old_userinfo['profile_image_url'] = userinfo['profile_image_url']\n old_userinfo['profile_image_url_https'] = userinfo['profile_image_url_https']\n\n if str != '':\n data['user_id'] = userinfo['id']\n data['user_id_str'] = userinfo['id_str']\n data['str'] = str\n eventunit = self.bale_event(data['type'],data['user_id'],data)\n self.deal_event(eventunit)\n else:\n if userinfo['id_str'] in push_list.spylist:\n self.userinfolist[userinfo['id']] = userinfo\n #打包事件(事件类型,引起变化的用户ID,事件数据)\n def bale_event(self, event_type,user_id:int,event_data):\n eventunit = {\n 'type':event_type,\n 'user_id':user_id,\n 'data':event_data\n }\n return eventunit\n #事件预处理-发送事件\n def deal_event(self, event):\n table = push_list.getLitsFromTweeUserID(event['user_id'])\n if test != None:\n test.event_push(event)\n for Pushunit in table:\n #获取属性判断是否可以触发事件\n res = push_list.getPuslunitAttr(Pushunit,event['type'])\n if res[0] == False:\n raise Exception(\"获取Pushunit属性值失败\",Pushunit)\n if res[1] == 1:\n self.deal_event_unit(event,Pushunit)\n def deal_event_unit(self,event,Pushunit):\n raise Exception('未定义事件处理单元')\n #推特标识到中文\n def type_to_str(self, tweettype):\n if tweettype == 'retweet':\n return '转推' #纯转推\n elif tweettype == 'quoted':\n return '转推并评论' #推特内含引用推文(带评论转推)\n elif tweettype == 'reply_to_status':\n return '回复' #回复(推特下评论)\n elif tweettype == 'reply_to_user':\n return '提及' #提及(猜测就是艾特)\n else:\n return '发推' #未分类(估计是主动发推)\n #将推特数据应用到模版\n def tweetToStr(self, tweetinfo, nick, upimg=config.pushunit_default_config['upimg'], template_text=''):\n if nick == '':\n if tweetinfo['user']['name']:\n nick = tweetinfo['user']['name']\n else:\n nick = tweetinfo['user']['screen_name']\n #模版变量初始化\n template_value = {\n 'tweet_id':tweetinfo['id_str'], #推特ID\n 'tweet_id_min':encode_b64(tweetinfo['id']),#��缩推特id\n 'tweet_nick':nick, #操作人昵称\n 'tweet_user_id':tweetinfo['user']['screen_name'], #操作人ID\n 'tweet_text':tweetinfo['text'], #发送推特的完整内容\n 'related_user_id':'', #关联用户ID\n 'related_user_name':'', #关联用户昵称-昵称-昵称查询不到时为ID(被评论/被转发/被提及)\n 'related_tweet_id':'', #关联推特ID(被评论/被转发)\n 'related_tweet_id_min':'', #关联推特ID的压缩(被评论/被转发)\n 'related_tweet_text':'', #关联推特内容(被转发或被转发并评论时存在)\n }\n if tweetinfo['type'] != 'none':\n template_value['related_tweet_id'] = tweetinfo['Related_tweet']['id_str']\n template_value['related_tweet_id_min'] = encode_b64(tweetinfo['Related_tweet']['id'])\n template_value['related_tweet_text'] = tweetinfo['Related_tweet']['text']\n\n if tweetinfo['type'] != 'none':\n template_value['related_user_id'] = tweetinfo['Related_user']['screen_name']\n if tweetinfo['Related_user']['id'] in self.userinfolist:\n template_value['related_user_name'] = self.userinfolist[tweetinfo['Related_user']['id']]['name']\n else:\n if hasattr(tweetinfo['Related_user'],'name'):\n template_value['related_user_name'] = tweetinfo['Related_user']['name']\n else:\n template_value['related_user_name'] = tweetinfo['Related_user']['screen_name']\n\n #生成模版类\n s = \"\"\n t = None\n if template_text == '':\n #默认模版\n if tweetinfo['type'] == 'none':\n deftemplate_none = \"推特ID:$tweet_id_min,【$tweet_nick】发布了:\\n$tweet_text\"\n t = tweetToStrTemplate(deftemplate_none)\n elif tweetinfo['type'] == 'retweet':\n deftemplate_another = \"推特ID:$tweet_id_min,【$tweet_nick】转了【$related_user_name】的推特:\\n$tweet_text\"\n t = tweetToStrTemplate(deftemplate_another)\n elif tweetinfo['type'] == 'quoted':\n deftemplate_another = \"推特ID:$tweet_id_min,【$tweet_nick】转发并评论了【$related_user_name】的推特:\\n$tweet_text\\n====================\\n$related_tweet_text\"\n t = tweetToStrTemplate(deftemplate_another)\n else:\n deftemplate_another = \"推特ID:$tweet_id_min,【$tweet_nick】回复了【$related_user_name】:\\n$tweet_text\"\n t = tweetToStrTemplate(deftemplate_another)\n else:\n #自定义模版\n template_text = template_text.replace(\"\\\\n\",\"\\n\")\n t = tweetToStrTemplate(template_text)\n\n #转换为字符串\n s = t.safe_substitute(template_value)\n #组装图片\n if upimg == 1:\n s = s + \"\\n\"\n if 'extended_entities' in tweetinfo:\n for media_unit in tweetinfo['extended_entities']:\n #组装CQ码\n file_suffix = os.path.splitext(media_unit['media_url'])[1]\n s = s + '[CQ:image,timeout='+config.img_time_out+',file='+config.img_path+'tweet/' + media_unit['id_str'] + file_suffix + ']'\n return s\n #尝试从缓存中获取昵称\n def tryGetNick(self, tweet_user_id,nick):\n if tweet_user_id in self.userinfolist:\n return self.userinfolist[tweet_user_id]['name']\n return nick\n #尝试从缓存中获取用户信息,返回用户信息表\n def tryGetUserInfo(self, tweet_user_id) -> list:\n if tweet_user_id in self.userinfolist:\n return self.userinfolist[tweet_user_id]\n return {}\n #消息发送(消息类型,消息发送到,消息内容)\n def send_msg(self, message_type:str, send_id:int, message:str,bindCQID:int = config.default_bot_QQ):\n bot = nonebot.get_bot()\n try:\n if message_type == 'private':\n bot.sync.send_msg_rate_limited(self_id=bindCQID,user_id=send_id,message=message)\n elif message_type == 'group':\n bot.sync.send_msg_rate_limited(self_id=bindCQID,group_id=send_id,message=message)\n except:\n s = traceback.format_exc(limit=5)\n logger.error(s)\n pass\n #图片保存\n def seve_image(self, name, url, file_path='img',canCover=False):\n #保存图片到磁盘文件夹 cache/file_path中,默认为当前脚本运行目录下的 cache/img 文件夹\n base_path = 'cache' #基准路径\n try:\n if not os.path.exists(os.path.join(base_path,file_path)):\n logger.info('文件夹' + os.path.join(base_path,file_path) + '不存在,重新建立')\n #os.mkdir(file_path)\n os.makedirs(os.path.join(base_path,file_path))\n #获得图片后缀\n file_suffix = os.path.splitext(url)[1]\n #拼接图片名(包含路径)\n filename = os.path.join(base_path,file_path,name+file_suffix)\n #下载图片,并保存到文件夹中\n if os.path.isfile(filename):\n if canCover:\n os.remove(filename)\n else:\n return\n urllib.request.urlretrieve(url,filename=filename)\n except IOError:\n s = traceback.format_exc(limit=5)\n logger.error('文件操作失败'+s+\"\\n文件路径:\"+filename)\n except Exception:\n s = traceback.format_exc(limit=5)\n logger.error(s)\n#建立列表\npush_list = PushList()\n\n\n","sub_path":"module/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":25259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"438968590","text":"# coding: utf-8\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError\n\n\nclass VerboseChoiceField(serializers.ChoiceField):\n def to_internal_value(self, data):\n if isinstance(data, dict):\n value = data['key']\n else:\n value = data\n if value not in dict(self.choices):\n raise ValidationError(self.error_messages.get('invalid_choice', '不在枚举范围内'))\n return value\n\n def to_representation(self, value):\n verbose = dict(self.choices).get(value)\n return {'key': value, 'verbose': verbose}","sub_path":"utils/serializer_fields.py","file_name":"serializer_fields.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"358018372","text":"disabled = 0\ntime_is_set = 0\ntime_raw = \"\"\ntime_lol = 0\ntime_lol_x100 = 0\ntime_lol_2 = 0\ntime_final = 0\nscren: grove.TM1637 = None\n\ndef on_button_pressed_a():\n timeanddate.advance_by(1, timeanddate.TimeUnit.MINUTES)\ninput.on_button_pressed(Button.A, on_button_pressed_a)\n\ndef on_button_pressed_b():\n global disabled\n disabled = 1\n basic.clear_screen()\n basic.pause(1000)\n disabled = 0\ninput.on_button_pressed(Button.B, on_button_pressed_b)\n\ndef on_forever():\n global time_is_set, time_raw, time_lol, time_lol_x100, time_lol_2, time_final, scren\n if disabled == 0:\n if time_is_set == 0:\n timeanddate.set_time(11, 59, 0, timeanddate.MornNight.PM)\n time_is_set = 1\n basic.pause(200)\n time_raw = timeanddate.time(timeanddate.TimeFormat.HHMM2_4HR)\n basic.pause(200)\n time_lol = parse_float(timeanddate.time(timeanddate.TimeFormat.HHMM2_4HR))\n time_lol_x100 = time_lol * 100\n if time_lol_2 == 0:\n time_lol = 12\n time_lol_2 = parse_float(time_raw.substr(3, 2))\n basic.pause(200)\n time_final = time_lol_x100 + time_lol_2\n basic.pause(1000)\n scren = grove.create_display(DigitalPin.P0, DigitalPin.P14)\n scren.point(True)\n scren.show(time_final)\n basic.show_string(\"\" + str((time_final)))\nbasic.forever(on_forever)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"232672577","text":"# Etem Kaya 15-Mar-2019\n\n# Solution to Problem-9.\n# File name: \"second.py\".\n\n# Problem-9: Write a program that reads in a text file and outputs every second line. \n# The program should take the filename from an argument on the command line.\n\n# first import sys library.\nimport sys\n\n# raise error if file doesn't exist or wrong filename supplied.\ntry:\n # count the number of arguments supplied via command-line\n if len(sys.argv) == 2: # sys.argv is a list contains commandline arguments.\n # open a text file in read only mode, which the filename _\n # is supplied from an argument on the command line.\n with open(sys.argv[1], 'r') as f:\n\n # assign the lines of the text file to a variable.\n s = f.readlines()\n\n # starting from line zero, loop through the every second line of_\n # the file (increment by 2) so lines 0, 2, 4, 6, etc.\n for i in range(0, len(s), 2):\n\n # print every second line of the file starting from line zero_\n # but ignore the empty lines e.g. 1, 3, 5, 7 etc.\n print(s[i], end='')\n # no need to close the file as it was opened in a 'with' statement.\n print (\"\\n \\nFile is now closed.\")\n # if sys function has less than or more than 2 elements. \n else:\n print (\"You should supply a single text file.\")\n sys.exit()\n# error detection on file errors e.g. file doesn't exist or wrong filename or_\n# file extension is not valid or corruption where file cant be read etc.\nexcept OSError:\n print(\"File error. Cann't open the file. Check the filename again.\")","sub_path":"second.py","file_name":"second.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"558392467","text":"from PeopleConnection import Connection\nimport datetime\n\n\ndef load(path, history, connector):\n with open(path, \"r\") as histories:\n for raw in histories:\n raw = raw.replace(\"\\n\", \"\")\n date, caller_phone_number, receiver_phone_number = raw.split(\",\")\n caller = [i for i in connector.user_list if i.phone_number == caller_phone_number][0]\n receiver = [i for i in connector.user_list if i.phone_number == receiver_phone_number][0]\n date = datetime.datetime.strptime(date, '%Y-%m-%d')\n history.connections = Connection.Connection(caller=caller, receiver=receiver, date=date)\n\n\ndef save(path, history):\n with open(path, \"a\") as histories:\n for connection in history.connections:\n caller = connection.caller.phone_number\n receiver = connection.receiver.phone_number\n date = str(connection.date).split(\" \")[0]\n histories.write(f\"{date},{caller},{receiver}\\n\")\n","sub_path":"FileIO/SaveLoadHistory.py","file_name":"SaveLoadHistory.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"230910971","text":"# Uses python3\nimport sys\n\ndef binary_search(a, x):\n left, right = 0, len(a)\n \n #since list is sorted\n if a[left] > x or a[right-1] < x:\n return -1\n \n \t\n while left < right:\n #print(f'left is {left}')\n mid = (left+right)//2\n #print(f'Mid is {mid}')\n tempVal=a[mid]\n #print(f'tempVal is {tempVal}')\n if tempVal==x:\n \t\treturn mid\n elif tempVal>x:\n \t\tright = mid\n else:\n \t\tleft= mid+1\n return -1\t\n\t\t\t\n\n\ndef linear_search(a, x):\n\tfor i in range(len(a)):\n\t\tif a[i] == x:\n\t\t\treturn i\n\treturn -1\n\nif __name__ == '__main__':\n\tinput = sys.stdin.read()\n\tdata = list(map(int, input.split()))\n\tn = data[0]\n\tm = data[n + 1]\n\ta = data[1 : n + 1]\n\tfor x in data[n + 2:]:\n\t\t# replace with the call to binary_search when implemented\n\t\tprint(binary_search(a, x), end = ' ')","sub_path":"Crs1Algos/Week4Solutions/BinSearch.py","file_name":"BinSearch.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"169534971","text":"from flask import Blueprint,render_template\nfrom myproject.models import Gamer\nfrom myproject import active_users\nfrom myproject.profile.forms import UploadForm\nfrom werkzeug.utils import secure_filename\nfrom myproject.models import Photo\n\nprofile_blueprint = Blueprint(\"profile\",__name__,template_folder=\"templates/profile\")\n\n@profile_blueprint.route(\"/profile/\",methods=[\"GET\",\"POST\"])\ndef profile_view(user_id):\n global active_users\n user = Gamer.query.get(user_id)\n active = False\n\n form = UploadForm()\n\n if user_id in active_users:\n active = True\n\n if form.validate_on_submit():\n filename = secure_filename(form.file.data.filename)\n form.file.data.save('static/uploads/'+filename)\n newPhoto = Photo('uploads/'+filename,user_id)\n print(\"photo added 11111111111111111111111111111111\")\n\n return render_template(\"profile.html\",user=user,active=active,form=form)","sub_path":"myproject/profile/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"500848368","text":"n=int(input())\r\na=[]\r\nq=0\r\nfor i in range(n):\r\n x=int(input())\r\n y=int(input())\r\n t=y.split( )\r\n sum=0\r\n t1=int(t[0])\r\n t2=int(t[-1])\r\n if (t1>t2):\r\n for m in range(x):\r\n for j in range(x):\r\n t[j]=t[j]*t[m]\r\n sum=sum+t[m]\r\n if t2>t1:\r\n for m1 in range(x-1,0,-1):\r\n for j1 in range(x-1,0,-1):\r\n t[j1]=t[j1]*t[m1]\r\n sum=sum+t[m1]\r\n a.append(sum)\r\nfor j in a:\r\n print(j,end=\"\\n\")\r\n \r\n","sub_path":"grharsh.py","file_name":"grharsh.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"617204401","text":"from string import Template\r\nclass MyTemplate(Template):\r\n delimiter='#'\r\ndef Main():\r\n cart=[]\r\n n=raw_input(\"Enter Your item:\")\r\n p=int(input(\"Enter Your Price:\"))\r\n q=int(input(\"Enter Your quantiuty:\"))\r\n cart.append(dict(item=n,price=p,quantity=q))\r\n \r\n t=MyTemplate(\"#quantity x #item=#price\")\r\n total=0\r\n print(\"cart:\")\r\n for data in cart:\r\n print(t.substitute(data))\r\n total +=data[\"price\"]\r\n print (\"Total:\"+str(total))\r\nif __name__==\"__main__\":\r\n Main()\r\n \r\n","sub_path":"templateProgramUsingClass.py","file_name":"templateProgramUsingClass.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"384003700","text":"# -*- coding: utf-8 -*-\n\nimport os\nfrom apscheduler.schedulers.blocking import BlockingScheduler\n\ndef job():\n os.system(\"scrapy crawl GetVidSpider\")\n\ndef cron_job():\n sched = BlockingScheduler()\n sched.add_job(job, 'cron', hour='12', minute='10', id='GetVidSpider')\n sched.start()\n\nif __name__ == '__main__':\n cron_job()","sub_path":"start_GetVidSpider.py","file_name":"start_GetVidSpider.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"291786111","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"This file contains tests for the Announcements_Table class\"\"\"\n\n\nimport os\nimport unittest\nimport logging\nfrom collections import Counter\nfrom .test_database import TestDatabase\nfrom ..logger import Logger\nfrom ..database import Announcements_Table\n\n__author__ = \"Justin Furuness\"\n__credits__ = [\"Justin Furuness\"]\n__Lisence__ = \"MIT\"\n__Version__ = \"0.1.0\"\n__maintainer__ = \"Justin Furuness\"\n__email__ = \"jfuruness@gmail.com\"\n__status__ = \"Development\"\n\n\nclass TestAnnouncements_Table(TestDatabase):\n \"\"\"Tests Announcements_table class, inherits tests from TestDatabase\"\"\"\n\n def setUp(self):\n \"\"\"Initializes db and connects\"\"\"\n\n # Up the logging level so we don't get useless info\n args = {\"stream_level\": logging.ERROR}\n self.db = Announcements_Table(self._initialize_logger(args=args))\n\n def test_init(self):\n \"\"\"tests connection\"\"\"\n\n pass\n\n def test_create_tables(self):\n \"\"\"Tests creation of tables\"\"\"\n\n self.db._create_tables()\n\n def test_columns(self):\n \"\"\"Makes sure columns are correct\"\"\"\n\n sql = \"\"\"select column_name from information_schema.columns where\n table_schema='public' and table_name='mrt_announcements';\n \"\"\"\n cols = self.db.execute(sql)\n print(cols)\n cols = cols[0]\n cols = [key for key in cols if 'id' not in key]\n cols = cols.sort()\n cols_2 = self.db.columns.sort()\n # self.db.logger.error(cols.sort())\n # self.db.logger.error(self.db.columns.sort())\n self.assertTrue(Counter(cols) == Counter(cols_2))\n","sub_path":"lib_clickbot/test/test_announcements_table.py","file_name":"test_announcements_table.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"583345327","text":"'''\n이름, 전화번호, 이메일, 주소를 받아서\n연락처 입력, 출력, 삭제\n'''\n\nclass Contacts:\n def __init__(self, name, phone, email, address):\n self.name = name\n self.phone = phone\n self.email = email\n self.address = address\n\n def print_info(self):\n print(f'이름: {self.name}')\n print(f'전화번호: {self.phone}')\n print(f'메일: {self.email}')\n print(f'주소: {self.address}')\n\n @staticmethod\n def set_contact():\n name = input(\"이름: \")\n phone = input(\"전화번호: \")\n email = input(\"메일: \")\n address = input(\"주소: \")\n return Contacts(name, phone, email, address)\n\n @staticmethod\n def get_contacts(ls):\n for i in ls:\n i.print_info()\n\n @staticmethod\n def del_contact(ls, name):\n for i, j in enumerate(ls): # enumerate: 인자 안에서 검색 = ls 안에서 j 검색. i = index\n if j.name == name:\n del ls[i]\n\n @staticmethod\n def print_menu():\n print(\"1. 연락처 입력\")\n print(\"2. 연락처 출력\")\n print(\"3. 연락처 삭제\")\n print(\"4. 종료\")\n menu = input(\"메뉴선택 : \")\n return int(menu)\n\n @staticmethod\n def main():\n ls = []\n while 1:\n menu = Contacts.print_menu()\n if menu == 1:\n t = Contacts.set_contact()\n ls.append(t)\n elif menu == 2:\n Contacts.get_contacts(ls)\n elif menu == 3:\n name = input(\"삭제할 이름: \")\n Contacts.del_contact(ls, name)\n elif menu == 4:\n break\n\n\nif __name__ == '__main__':\n Contacts.main()","sub_path":"step1_oop/contacts.py","file_name":"contacts.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"260649609","text":"import pandas\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\nfrom time import time, ctime, localtime\nfrom datetime import datetime\n\n\n# kalibr_bagextractor --bag ./zeiss_data.bag --image-topics /mynteye/left/image_raw --imu-topics /mynteye/imu/data_raw --output-folder ./test_output_zeiss/\n\ndata_imu = pandas.read_csv(\"./test_output_zeiss/imu0.csv\")\ntimestamps_imu = data_imu[\"timestamp\"].tolist()\ntimestamps_imu_format = []\nfor tps in timestamps_imu:\n temp = str(tps)[:10]\n temp2 = str(tps)[10:]\n timestamps_imu_format.append(np.double(temp+\".\"+temp2))\ntimestamps_imu_format.sort()\n\nlist_img = os.listdir(\"./test_output_zeiss/cam0/\")\ntimestamps_img_format = []\nfor name in list_img:\n name_time = name.split(\".\")[0]\n temp = name_time[:10]\n temp2 = name_time[10:]\n timestamps_img_format.append(np.double(temp+\".\"+temp2))\ntimestamps_img_format.sort()\n\n\n# imu time diff\nimu_time_diff = [0]\nfor i in range(len(timestamps_imu_format)-1):\n time_left = timestamps_imu_format[i]\n time_right = timestamps_imu_format[i+1]\n time_diff = (time_right-time_left)*1000\n imu_time_diff.append(time_diff)\n\n# image time diff\nimg_time_diff = [0]\nfor i in range(len(timestamps_img_format)-1):\n time_left = timestamps_img_format[i]\n time_right = timestamps_img_format[i+1]\n time_diff = (time_right-time_left)*1000\n img_time_diff.append(time_diff)\n\nprint(len(imu_time_diff))\nprint(len(img_time_diff))\n\nnum = 400\nplt.subplot(211)\nplt.plot(timestamps_img_format[1:num],\n img_time_diff[1:num])\nplt.title(\"Image data captured by MYNTEYE (30Hz)\")\nplt.xlabel(\"Image timestamps (unix time)\")\nplt.ylabel(\"time diff (ms)\")\n\nplt.subplot(212)\nplt.plot(timestamps_imu_format[1:num],\n imu_time_diff[1:num])\nplt.title(\"IMU data captured by MYNTEYE (200Hz)\")\nplt.xlabel(\"IMU timestamps (unix time)\")\nplt.ylabel(\"time diff (ms)\")\n# plt.show()\n\nplt.show()\n\n","sub_path":"utility_python/check_time_diff_IMUandCamera.py","file_name":"check_time_diff_IMUandCamera.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"346371507","text":"from skimage import data, io, filters\nfrom matplotlib import pyplot as plt\nfrom sklearn import manifold, datasets\nfrom skimage.transform import rescale, resize, downscale_local_mean\n\ndef toBinary(path):\n image= io.imread('C:/Users/Malikoto/unet-master/data/Dataset/train/label/'+path,as_grey=True)\n print('b4',len(image[0]), len(image))\n \n for i in range(0,len(image)):\n for j in range(0,len(image[0])):\n if image[i][j] == 0:\n image[i][j] = 255\n elif image[i][j] == 128:\n image[i][j] = 0\n elif image[i][j] == 255:\n image[i][j] = 255\n \n image = resize(image, (100,100))\n print('after',len(image[0]), len(image))\n \n return image\n\nN=210 #number of images\n\nfor i in range (1,N+1):\n if i < 10 :\n path = '00'+str(i)+'.png'\n elif i < 100:\n path = '0'+str(i)+'.png'\n elif i >= 100:\n path = str(i)+'.png'\n print(path)\n \n binary = toBinary(path)\n \n# plt.gray()\n# plt.imshow(binary)\n# plt.show()\n# print(binary.shape)\n path=str(i)+'.png'\n \n io.imsave('C:/Users/Malikoto/unet-master/data/Dataset/train/tif label/'+path,binary)\n","sub_path":"convert2Binary.py","file_name":"convert2Binary.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"374007489","text":"from bs4 import BeautifulSoup\nimport commons.source_urls\nimport logging\nimport datetime\nimport requests\n\nclass PatagoniaQuotation():\n\n def __set_url(self):\n self.url = commons.source_urls.Patagonia\n\n def __parsing(self, soup):\n currencyBox = soup.find(\"div\", {\"id\": \"principal\"})\n cells = soup.findAll('tbody')[0].findAll('tr')[0].findAll('td')\n self.buying = float(cells[1].string.replace(',', '.')[2:])\n self.selling = float(cells[2].string.replace(',', '.')[2:])\n\n def log(self):\n logging.info('Cotizacion Patagonia')\n logging.info('Compra: ' + str(self.buying))\n logging.info('Venta: ' + str(self.selling))\n\n def __init__(self):\n self.timestamp = datetime.datetime.now()\n try:\n self.__set_url()\n self.__parsing(BeautifulSoup(requests.get(self.url).text, \"html.parser\"))\n except:\n self.buying = None\n self.selling = None\n","sub_path":"models/patagonia_quotation.py","file_name":"patagonia_quotation.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"424242227","text":"try:\n import configparser\nexcept:\n import ConfigParser as configparser\n\nconfig_file = \"/etc/mopidy/mopidy.conf\"\nconfig = configparser.ConfigParser()\nconfig.read(config_file)\ndef core_defaults():\n config['core']['cache_dir'] = '/var/cache/mopidy'\n config['core']['config_dir'] = '/etc/mopidy'\n config['core']['data_dir'] = '/var/lib/mopidy'\n\ndef logging_defaults():\n config['logging']['config_file'] = '/etc/mopidy/logging.conf'\n config['logging']['debug_file'] = '/var/log/mopidy/mopidy-debug.log'\n\ndef local_defaults():\n config['local']['enabled'] = 'True'\n config['local']['media_dir'] = '/Music \\n /usbdrives'\n config['local']['library'] = 'sqlite'\n config['local']['scan_timeout'] = '1000'\n config['local']['scan_flush_threshold'] = '100'\n config['local']['scan_follow_symlinks'] = 'true'\n config['local']['excluded_file_extensions'] = '\\n .directory\\n .html\\n .jpeg\\n .jpg\\n .log\\n .nfo\\n .png\\n .txt\\n .db\\n .ini'\n\ndef file_defaults():\n config['file']['enabled'] = 'True'\n config['file']['media_dirs'] = '/Music \\n /usbdrives'\n config['file']['excluded_file_extensions'] = '\\n .directory\\n .html\\n .jpeg\\n .jpg\\n .log\\n .nfo\\n .png\\n .txt\\n .db\\n .ini'\n config['file']['show_dotfiles'] = 'false'\n config['file']['follow_symlinks'] = 'false'\n config['file']['metadata_timeout'] = '1000'\n\ndef m3u_defaults():\n config['m3u']['playlists_dir'] = '/var/lib/mopidy/playlists'\n\ndef http_defaults():\n config['http']['enabled'] = 'True'\n config['http']['hostname'] = '::'\n config['http']['port'] = '8888'\n config['http']['static_dir'] = \"\"\n config['http']['zeroconf'] = 'Mopidy HTTP server on $hostname'\n\ndef mpd_defaults():\n config['mpd']['enabled'] = 'True'\n config['mpd']['hostname'] = '::'\n config['mpd']['port'] = '6600'\n config['mpd']['password'] = ''\n config['mpd']['max_connections'] = '20'\n config['mpd']['connection_timeout'] = '60'\n config['mpd']['zeroconf'] = 'Mopidy MPD server on $hostname'\n config['mpd']['command_blacklist'] = ' listall\\n listallinfo'\n config['mpd']['default_playlist_scheme'] = 'm3u'\n\ndef websettings_defaults():\n config['websettings']['enabled'] = 'True'\n config['websettings']['musicbox'] = 'True'\n config['websettings']['config_file'] = '/etc/mopidy/mopidy.conf'\n\ndef spotify_defaults(spotify_user = '', spotify_client_id = '', spotify_client_secret = '', spotify_password = ''):\n config['spotify']['enabled'] = 'True'\n config['spotify']['username'] = spotify_user\n config['spotify']['client_id'] = spotify_client_id\n config['spotify']['client_secret'] = spotify_client_secret\n config['spotify']['password'] = spotify_password\n config['spotify']['bitrate'] = '320'\n\ndef spotify_web_defaults(spotify_user = '', spotify_client_id = '', spotify_client_secret = '', spotify_password = ''):\n config['spotify_web']['enabled'] = 'True'\n config['spotify_web']['username'] = spotify_user\n config['spotify_web']['client_id'] = spotify_client_id\n config['spotify_web']['client_secret'] = spotify_client_secret\n config['spotify_web']['password'] = spotify_password\n config['spotify_web']['bitrate'] = '320'\n\ndef audio_defaults():\n config['audio']['mixer_volume'] = '100'\n config['audio']['mixer'] = 'software'\n# config['audio']['output'] = 'alsasink device=hw:1,0'\n config['audio']['output'] = 'alsasink device=default'\n\nif not config.has_section('core'):\n config.add_section('core')\n\nif not config.has_section('logging'):\n config.add_section('logging')\n\nif not config.has_section('local'):\n config.add_section('local')\n\nif not config.has_section('file'):\n config.add_section('file')\n\nif not config.has_section('m3u'):\n config.add_section('m3u')\n\nif not config.has_section('http'):\n config.add_section('http')\n\nif not config.has_section('mpd'):\n config.add_section('mpd')\n\nif not config.has_section('websettings'):\n config.add_section('websettings')\n\nif not config.has_section('spotify'):\n config.add_section('spotify')\n\nif not config.has_section('spotify_web'):\n config.add_section('spotify_web')\n\nif not config.has_section('audio'):\n config.add_section('audio')\n\ncore_defaults()\nlogging_defaults()\nlocal_defaults()\nfile_defaults()\nm3u_defaults()\nhttp_defaults()\nmpd_defaults()\nwebsettings_defaults()\nspotify_defaults()\nspotify_web_defaults()\naudio_defaults()\nwith open(config_file, 'wb') as configfile:\n config.write(configfile)\n","sub_path":"defaultConfigMopidy.py","file_name":"defaultConfigMopidy.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"471097717","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.4'\n# jupytext_version: 1.1.1\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# ## Performance testing of acceleration structures\n#\n# This test checks performance of acceleration structure implemented in the framework for various scenes.\n\nimport os\nimport imageio\nimport pandas as pd\nimport numpy as np\nimport timeit\n# %matplotlib inline\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport lmfunctest as ft\nimport lmscene\nimport lightmetrica as lm\n\n# %load_ext lightmetrica_jupyter\n\nlm.init('user::default', {})\nlm.parallel.init('parallel::openmp', {\n 'numThreads': -1\n})\nlm.log.init('logger::jupyter', {})\nlm.info()\n\nlm.comp.loadPlugin(os.path.join(ft.env.bin_path, 'accel_nanort'))\nlm.comp.loadPlugin(os.path.join(ft.env.bin_path, 'accel_embree'))\n\naccels = [\n 'accel::sahbvh',\n 'accel::nanort',\n 'accel::embree',\n 'accel::embreeinstanced'\n]\nscenes = lmscene.scenes_small()\n\nbuild_time_df = pd.DataFrame(columns=accels, index=scenes)\nrender_time_df = pd.DataFrame(columns=accels, index=scenes)\nfor scene in scenes:\n lm.reset()\n lmscene.load(ft.env.scene_path, scene)\n for accel in accels:\n lm.asset('film_output', 'film::bitmap', {\n 'w': 1920,\n 'h': 1080\n })\n \n def build():\n lm.build(accel, {})\n build_time = timeit.timeit(stmt=build, number=1)\n build_time_df[accel][scene] = build_time\n\n def render():\n lm.render('renderer::raycast', {\n 'output': lm.asset('film_output')\n })\n render_time = timeit.timeit(stmt=render, number=1)\n render_time_df[accel][scene] = render_time\n\nbuild_time_df\n\nrender_time_df\n","sub_path":"functest/perf_accel.py","file_name":"perf_accel.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"457135961","text":"import pandas as pd\nfrom pandarallel.utils.tools import chunk\n\n\nclass SeriesRolling:\n @staticmethod\n def reduce(results, _):\n return pd.concat(results, copy=False)\n\n @staticmethod\n def get_chunks(nb_workers, rolling, *args, **kwargs):\n chunks = chunk(rolling.obj.size, nb_workers, rolling.window)\n\n for chunk_ in chunks:\n yield rolling.obj[chunk_]\n\n @staticmethod\n def att2value(rolling):\n return {\n attribute: getattr(rolling, attribute) for attribute in rolling._attributes\n }\n\n @staticmethod\n def worker(\n series, index, attribue2value, _progress_bar, _queue, func, *args, **kwargs\n ):\n result = series.rolling(**attribue2value).apply(func, *args, **kwargs)\n\n return result if index == 0 else result[attribue2value[\"window\"] :]\n","sub_path":"pandarallel/data_types/series_rolling.py","file_name":"series_rolling.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"138383240","text":"import numpy as np\nfrom PIL import Image\nimport torchvision.transforms as TTF\nimport random\nimport os\n\ndef randomCrop(imgs, size):\n if type(size) == int:\n size = (size, size)\n w, h = imgs[0].size\n ws, hs = random.randint(0, w - size[0]), random.randint(0, h - size[1])\n wt, ht = ws + size[0], hs + size[1]\n return [img.crop((ws, hs, wt, ht)) for img in imgs]\n\n\nimg2tensor = TTF.ToTensor()\ntrain_data_augmentation = TTF.Compose([\n TTF.Lambda(lambda imgs: imgs if random.random() > 0.5 else [img.transpose(Image.FLIP_LEFT_RIGHT) for img in imgs]),\n TTF.Lambda(lambda imgs: imgs if random.random() > 0.5 else [img.transpose(Image.FLIP_TOP_BOTTOM) for img in imgs]),\n TTF.Lambda(lambda imgs: [img2tensor(img) for img in imgs]),\n TTF.Lambda(lambda xs: xs if random.random() > 0.5 else [x.permute(0, 2, 1) for x in xs])\n])\n\neval_data_augmentation = TTF.Compose([\n TTF.Lambda(lambda imgs: [img2tensor(img) for img in imgs])\n])\ntest_data_augmentation = TTF.Compose([\n TTF.ToTensor()\n])\n\ndef saveimg(img, savedir, imgname):\n os.makedirs(savedir, exist_ok=True)\n img.save(os.path.join(savedir, imgname))","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"487355542","text":"import datetime\nimport mimetypes\nimport os\nimport re\nimport time\nimport zipfile\n\nfrom django.core.files.storage import default_storage\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseNotFound\nfrom django.http import HttpResponseServerError\nfrom django.http.response import FileResponse\nfrom django.http.response import HttpResponseNotModified\nfrom django.utils.http import http_date\nfrom django.views.decorators.clickjacking import xframe_options_exempt\nfrom django.views.generic.base import View\nfrom le_utils.constants import exercises\nfrom raven.contrib.django.raven_compat.models import client\n\nfrom contentcuration.models import generate_object_storage_name\n\ntry:\n pass\nexcept ImportError:\n pass\n\n\n# valid storage filenames consist of 32-char hex plus a file extension\nVALID_STORAGE_FILENAME = re.compile(\"[0-9a-f]{32}(-data)?\\.[0-9a-z]+\")\n\n# set of file extensions that should be considered zip files and allow access to internal files\nPOSSIBLE_ZIPPED_FILE_EXTENSIONS = set([\".perseus\", \".zip\", \".epub\", \".epub3\"])\n\n\ndef _add_access_control_headers(request, response):\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"GET, OPTIONS\"\n requested_headers = request.META.get(\"HTTP_ACCESS_CONTROL_REQUEST_HEADERS\", \"\")\n if requested_headers:\n response[\"Access-Control-Allow-Headers\"] = requested_headers\n\n\n# DISK PATHS\n\nclass ZipContentView(View):\n\n @xframe_options_exempt\n def options(self, request, *args, **kwargs):\n \"\"\"\n Handles OPTIONS requests which may be sent as \"preflight CORS\" requests to check permissions.\n \"\"\"\n response = HttpResponse()\n _add_access_control_headers(request, response)\n return response\n\n @xframe_options_exempt # noqa\n def get(self, request, zipped_filename, embedded_filepath):\n \"\"\"\n Handles GET requests and serves a static file from within the zip file.\n \"\"\"\n if not VALID_STORAGE_FILENAME.match(zipped_filename):\n return HttpResponseNotFound(\"'{}' is not a valid URL for this zip file\".format(zipped_filename))\n\n storage = default_storage\n\n # calculate the local file path to the zip file\n filename, ext = os.path.splitext(zipped_filename)\n zipped_path = generate_object_storage_name(filename, zipped_filename)\n\n # file size\n file_size = 0\n\n # if the zipfile does not exist on disk, return a 404\n if not storage.exists(zipped_path):\n return HttpResponseNotFound('\"%(filename)s\" does not exist in storage' % {'filename': zipped_path})\n\n # if client has a cached version, use that (we can safely assume nothing has changed, due to MD5)\n if request.META.get('HTTP_IF_MODIFIED_SINCE'):\n return HttpResponseNotModified()\n\n zf_obj = storage.open(zipped_path)\n\n try:\n with zipfile.ZipFile(zf_obj) as zf:\n # if no path, or a directory, is being referenced, look for an index.html file\n if not embedded_filepath or embedded_filepath.endswith(\"/\"):\n embedded_filepath += \"index.html\"\n\n # get the details about the embedded file, and ensure it exists\n try:\n info = zf.getinfo(embedded_filepath)\n except KeyError:\n return HttpResponseNotFound('\"{}\" does not exist inside \"{}\"'.format(embedded_filepath, zipped_filename))\n\n # try to guess the MIME type of the embedded file being referenced\n content_type = mimetypes.guess_type(embedded_filepath)[0] or 'application/octet-stream'\n\n if not os.path.splitext(embedded_filepath)[1] == '.json':\n # generate a streaming response object, pulling data from within the zip file\n response = FileResponse(zf.open(info), content_type=content_type)\n file_size = info.file_size\n else:\n # load the stream from json file into memory, replace the path_place_holder.\n content = zf.open(info).read()\n str_to_be_replaced = ('$' + exercises.IMG_PLACEHOLDER).encode()\n zipcontent = ('/' + request.resolver_match.url_name + \"/\" + zipped_filename).encode()\n content_with_path = content.replace(str_to_be_replaced, zipcontent)\n response = HttpResponse(content_with_path, content_type=content_type)\n file_size = len(content_with_path)\n except zipfile.BadZipfile:\n just_downloaded = getattr(zf_obj, 'just_downloaded', \"Unknown (Most likely local file)\")\n client.captureMessage(\"Unable to open zip file. File info: name={}, size={}, mode={}, just_downloaded={}\".format(\n zf_obj.name, zf_obj.size, zf_obj.mode, just_downloaded))\n return HttpResponseServerError(\"Attempt to open zip file failed. Please try again, and if you continue to receive this message, please check that the zip file is valid.\")\n\n # set the last-modified header to the date marked on the embedded file\n if info.date_time:\n response[\"Last-Modified\"] = http_date(time.mktime(datetime.datetime(*info.date_time).timetuple()))\n\n # cache these resources forever; this is safe due to the MD5-naming used on content files\n response[\"Expires\"] = \"Sun, 17-Jan-2038 19:14:07 GMT\"\n\n # set the content-length header to the size of the embedded file\n if file_size:\n response[\"Content-Length\"] = file_size\n\n # ensure the browser knows not to try byte-range requests, as we don't support them here\n response[\"Accept-Ranges\"] = \"none\"\n\n _add_access_control_headers(request, response)\n\n # restrict CSP to only allow resources to be loaded from the Studio host, to prevent info leakage\n # (e.g. via passing user info out as GET parameters to an attacker's server), or inadvertent data usage\n host = request.build_absolute_uri('/').strip(\"/\")\n response[\"Content-Security-Policy\"] = \"default-src 'self' 'unsafe-inline' 'unsafe-eval' data: \" + host\n\n return response\n","sub_path":"contentcuration/contentcuration/views/zip.py","file_name":"zip.py","file_ext":"py","file_size_in_byte":6221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"503935286","text":"# MIT License\n#\n# Copyright (c) 2020 Aruba, a Hewlett Packard Enterprise company\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# import getpass\nfrom pycentral.base import ArubaCentralBase\nimport requests\n# import yaml\nimport pprint\n# import os\nimport json\nfrom typing import Union\nimport urllib.parse\nimport csv\nfrom . import MyLogger, Response, config, log\n# Get instance of ArubaCentralBase from the central_filename\n# from pycentral.workflows.workflows_utils import get_conn_from_file\n# from pathlib import Path\n\ntry:\n from . import utils\nexcept ImportError:\n from utils import Utils # type: ignore\n utils = Utils()\n\n\n# _refresh_file = os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\", \"..\", \"config\", \".refresh_token.yaml\"))\n# _refresh_file = Path.joinpath(Path(__file__), \"config\", \".refresh_token.yaml\")\n# _config_file = Path.joinpath(Path(__file__).parent.parent.parent, \"config\", \"config.yaml\")\n# _bulk_edit_file = _config_file.parent.joinpath('bulkedit.csv')\n\n# TODO build own function for this so we can set token_store vs overriding it in cli.py\n# central = get_conn_from_file(filename=config.config_file)\nDEFAULT_TOKEN_STORE = {\n \"type\": \"local\",\n \"path\": f\"{config.dir.joinpath('.cache')}\"\n}\n\n\ndef get_conn_from_file(account_name, logger: MyLogger = log):\n \"\"\"Creates an instance of class`pycentral.ArubaCentralBase` based on the information\n provided in the YAML/JSON file. \\n\n * keyword central_info: A dict containing arguments as accepted by class`pycentral.ArubaCentralBase` \\n\n * keyword ssl_verify: A boolean when set to True, the python client validates Aruba Central's SSL certs. \\n\n * keyword token_store: Optional. Defaults to None. \\n\n\n :param filename: Name of a JSON/YAML file containing the keywords required for class:`pycentral.ArubaCentralBase`\n :type filename: str\n :return: An instance of class:`pycentral.ArubaCentralBase` to make API calls and manage access tokens.\n :rtype: class:`pycentral.ArubaCentralBase`\n \"\"\"\n conn = None\n if account_name not in config.data:\n exit(f\"exiting... {account_name} missing from {config.file}\")\n central_info = config.data[account_name]\n token_store = config.get(\"token_store\", DEFAULT_TOKEN_STORE)\n ssl_verify = config.get(\"ssl_verify\", True)\n\n conn = ArubaCentralBase(central_info=central_info,\n token_store=token_store,\n ssl_verify=ssl_verify,\n logger=logger\n )\n return conn\n\n\nclass CentralApi:\n log = log\n\n # def __init__(self, central: CentralApiAuth = CentralApiAuth()):\n def __init__(self, account_name):\n self.central = get_conn_from_file(account_name)\n # self.headers = {\"authorization\": f\"Bearer {self.central.central_info['token']['access_token']}\"}\n # Temp Refactor to use ArubaBaseClass without changing all my methods\n # self.central.get = self.get\n self.central.get = self.get\n\n # def get(self, url: str, params: dict = {}, data: dict = {},\n # headers: dict = {}, files: dict = {}, retry_api_call: bool = True) -> dict:\n # return self.central.command(\"GET\", apiPath=url, apiData=data, apiParams=params,\n # headers=headers, files=files, retry_api_call=retry_api_call)\n\n def get(self, url, params: dict = None, headers: dict = None):\n \"\"\"Generic GET call\n\n :param vars: Imported variables\n :type vars: Python dict\n :param url: GET call URL\n :type url: String\n :param header: GET call parameters\n :type header: Python dict\n :return: GET call response JSON\n :rtype: Python dict\n \"\"\"\n f_url = self.central.central_info[\"base_url\"] + url\n return Response(self.central.requestUrl, f_url, params=params, headers=headers)\n\n def post(self, url, params: dict = None, payload: dict = None, headers: dict = None, **kwargs) -> Response:\n f_url = self.central.central_info[\"base_url\"] + url\n return Response(self.central.requestUrl, f_url, data=payload, params=params, headers=headers, **kwargs)\n\n # doesn't appear to work. referenced in swagger to get listing of types (New Device Inventory: Get Devices...)\n def get_dev_types(self):\n url = \"/platform/orders/v1/skus?sku_type=all\"\n return self.central.get(url)\n\n def get_ap(self):\n \"\"\"GET call for AP data\n\n :param access_token: Access token from tokens func\n :type access_token: String\n \"\"\"\n url = \"/monitoring/v1/aps\"\n # return self.central.get(url)\n return self.central.get(url)\n\n def get_swarms_by_group(self, group: str):\n url = \"/monitoring/v1/swarms\"\n params = {\"group\": group}\n return self.central.get(url, params=params)\n\n def get_swarm_details(self, swarm_id: str):\n url = f\"/monitoring/v1/swarms/{swarm_id}\"\n return self.central.get(url)\n\n def get_all_clients(self, group: str = None, swarm_id: str = None, label: str = None, ssid: str = None,\n serial: str = None, os_type: str = None, cluster_id: str = None, band: str = None) -> None:\n params = {}\n for k, v in zip([\"group\", \"swarm_id\", \"label\", \"ssid\", \"serial\", \"os_type\", \"cluster_id\", \"band\"],\n [group, swarm_id, label, ssid, serial, os_type, cluster_id, band]\n ):\n if v:\n params[k] = v\n\n # return structure: {'clients': [], 'count': 0}\n resp = self.get_wlan_clients(**params)\n if resp.ok:\n wlan_resp = resp\n resp = self.get_wired_clients(**params)\n if resp.ok:\n resp.output = wlan_resp.output.get(\"clients\") + resp.output.get(\"clients\")\n return resp\n\n def get_wlan_clients(self, group: str = None, swarm_id: str = None, label: str = None, ssid: str = None,\n serial: str = None, os_type: str = None, cluster_id: str = None, band: str = None) -> None:\n params = {}\n for k, v in zip([\"group\", \"swarm_id\", \"label\", \"ssid\", \"serial\", \"os_type\", \"cluster_id\", \"band\"],\n [group, swarm_id, label, ssid, serial, os_type, cluster_id, band]\n ):\n if v:\n params[k] = v\n\n url = \"/monitoring/v1/clients/wireless\"\n return self.central.get(url, params=params)\n\n def get_wired_clients(self, group: str = None, swarm_id: str = None, label: str = None, ssid: str = None,\n serial: str = None, cluster_id: str = None, stack_id: str = None) -> None:\n params = {}\n for k, v in zip([\"group\", \"swarm_id\", \"label\", \"ssid\", \"serial\", \"cluster_id\", \"stack_id\"],\n [group, swarm_id, label, ssid, serial, cluster_id, stack_id]\n ):\n if v:\n params[k] = v\n\n url = \"/monitoring/v1/clients/wired\"\n return self.central.get(url, params=params)\n\n def get_client_details(self, mac: str):\n url = f\"/monitoring/v1/clients/wired/{urllib.parse.quote(mac)}\"\n return self.central.get(url)\n\n def get_certificates(self):\n url = \"/configuration/v1/certificates\"\n params = {\"limit\": 20, \"offset\": 0}\n return self.central.get(url, params=params)\n\n def get_template(self, group, template):\n url = f\"/configuration/v1/groups/{group}/templates/{template}\"\n return self.central.get(url)\n\n def get_all_groups(self): # DONE\n url = \"/configuration/v2/groups?limit=20&offset=0\"\n params = {\"limit\": 20, \"offset\": 0}\n return self.central.get(url, params=params)\n\n def get_sku_types(self):\n url = \"/platform/orders/v1/skus\"\n params = {\"sku_type\": \"all\"}\n return self.central.get(url, params=params)\n\n def get_dev_by_type(self, dev_type: str):\n url = \"/platform/device_inventory/v1/devices\"\n if dev_type.lower() in [\"aps\", \"ap\"]:\n dev_type = \"iap\"\n params = {\"sku_type\": dev_type}\n return self.central.get(url, params=params)\n\n def get_variablised_template(self, serialnum: str) -> Response:\n url = f\"/configuration/v1/devices/{serialnum}/variablised_template\"\n return self.central.get(url)\n\n def get_variables(self, serialnum: str = None):\n if serialnum:\n url = f\"/configuration/v1/devices/{serialnum}/template_variables\"\n params = {}\n else:\n url = \"/configuration/v1/devices/template_variables\"\n params = {\"limit\": 20, \"offset\": 0}\n # TODO generator for returns > 20 devices\n return self.central.get(url, params=params)\n\n # TODO self.central.patch\n def update_variables(self, serialnum: str, var_dict: dict):\n url = f\"/configuration/v1/devices/{serialnum}/template_variables\"\n header = {\n \"authorization\": f\"Bearer {self.central.access_token}\",\n \"Content-type\": \"application/json\"\n }\n var_dict = json.dumps(var_dict)\n resp = requests.patch(self.central.vars[\"base_url\"] + url, data=var_dict, headers=header)\n return(resp.ok)\n\n def get_devices(self, dev_type: str, group: str = None, label: str = None, stack_id: str = None,\n status: str = None, fields: list = None, show_stats: bool = False, calc_clients: bool = False,\n pub_ip: str = None, limit: int = None, offset: int = None, sort: str = None):\n _strip = [\"self\", \"dev_type\", \"url\", \"_strip\"]\n params = {k: v for k, v in locals().items() if k not in _strip and v}\n url = f\"/monitoring/v1/{dev_type}\"\n return self.central.get(url, params=params)\n\n def get_ssids_by_group(self, group):\n url = \"/monitoring/v1/networks\"\n params = {\"group\": group}\n return self.central.get(url, params=params)\n\n def get_gateways_by_group(self, group):\n url = \"/monitoring/v1/mobility_controllers\"\n params = {\"group\": group}\n return self.central.get(url, params=params)\n\n def get_group_for_dev_by_serial(self, serial_num):\n return self.central.get(f\"/configuration/v1/devices/{serial_num}/group\")\n\n def get_dhcp_client_info_by_gw(self, serial_num):\n url = f\"/monitoring/v1/mobility_controllers/{serial_num}/dhcp_clients\"\n params = {\"reservation\": False}\n return self.central.get(url, params=params)\n\n def get_vlan_info_by_gw(self, serial_num):\n return self.central.get(f\"/monitoring/v1/mobility_controllers/{serial_num}/vlan\")\n\n def get_uplink_info_by_gw(self, serial_num, timerange: str = \"3H\"):\n url = f\"/monitoring/v1/mobility_controllers/{serial_num}/uplinks\"\n params = {\"timerange\": timerange}\n return self.central.get(url, params)\n\n def get_uplink_tunnel_stats_by_gw(self, serial_num):\n url = f\"/monitoring/v1/mobility_controllers/{serial_num}/uplinks/tunnel_stats\"\n return self.central.get(url)\n\n def get_uplink_state_by_group(self, group):\n url = f\"/monitoring/v1/mobility_controllers/uplinks/distribution?group={group}\"\n return self.central.get(url)\n\n def get_all_sites(self):\n return self.central.get(\"/central/v2/sites\")\n\n def get_site_details(self, site_id):\n return self.central.get(f\"/central/v2/sites/{site_id}\")\n\n def get_events_by_group(self, group):\n url = f\"/monitoring/v1/events?group={group}\"\n params = {\"group\": group}\n return self.central.get(url, params=params)\n\n def bounce_poe(self, serial_num: str, port: Union[str, int]) -> Response:\n url = f\"/device_management/v1/device/{serial_num}/action/bounce_poe_port/port/{port}\"\n return self.central.post(url)\n\n def kick_users(self, serial_num, kick_all=False, mac=None, ssid=None):\n url = f\"/device_management/v1/device/{serial_num}/action/disconnect_user\"\n header = {\n \"authorization\": f\"Bearer {self.access_token}\",\n \"Content-type\": \"application/json\"\n }\n if kick_all:\n payload = {\"disconnect_user_all\": True}\n elif mac:\n payload = {\"disconnect_user_mac\": f\"{mac}\"}\n elif ssid:\n payload = {\"disconnect_user_network\": f\"{ssid}\"}\n else:\n payload = {}\n\n if payload:\n resp = requests.post(self.central.vars[\"base_url\"] + url, headers=header, json=payload)\n pprint.pprint(resp.json())\n else:\n print(\"Missing Required Parameters\")\n\n def get_task_status(self, task_id):\n return self.central.get(f\"/device_management/v1/status/{task_id}\")\n\n def add_dev(self, mac: str, serial_num: str):\n \"\"\"\n {'code': 'ATHENA_ERROR_NO_DEVICE',\n 'extra': {'error_code': 'ATHENA_ERROR_NO_DEVICE',\n 'message': {'available_device': [],\n 'blocked_device': [],\n 'invalid_device': [{'mac': '20:4C:03:26:28:4c',\n 'serial': 'CNF7JSP0N0',\n 'status': 'ATHENA_ERROR_DEVICE_ALREADY_EXIST'}]}},\n 'message': 'Bad Request'}\n \"\"\"\n url = \"/platform/device_inventory/v1/devices\"\n payload = [\n {\n \"mac\": mac,\n \"serial\": serial_num\n }\n ]\n header = {\n \"authorization\": f\"Bearer {self.central.access_token}\",\n \"Content-type\": \"application/json\"\n }\n\n resp = requests.post(self.central.vars[\"base_url\"] + url, headers=header, json=payload)\n pprint.pprint(resp.json())\n\n def verify_add_dev(self, mac: str, serial_num: str):\n \"\"\"\n {\n 'available_device': [],\n 'blocked_device': [],\n 'invalid_device': [\n {\n 'mac': '20:4C:03:26:28:4c',\n 'serial': 'CNF7JSP0N0',\n 'status': 'ATHENA_ERROR_DEVICE_ALREADY_EXIST'\n }\n ]\n }\n \"\"\"\n url = \"/platform/device_inventory/v1/devices/verify\"\n payload = [\n {\n \"mac\": mac,\n \"serial\": serial_num\n }\n ]\n header = {\n \"authorization\": f\"Bearer {self.central.access_token}\",\n \"Content-type\": \"application/json\"\n }\n\n resp = requests.post(self.central.vars[\"base_url\"] + url, headers=header, json=payload)\n pprint.pprint(resp.json())\n\n def move_dev_to_group(self, group: str, serial_num: Union[str, list]):\n url = \"/configuration/v1/devices/move\"\n if not isinstance(serial_num, list):\n serial_num = [serial_num]\n payload = {\n \"group\": group,\n \"serials\": serial_num\n }\n header = {\n \"authorization\": f\"Bearer {self.central.access_token}\",\n \"Content-type\": \"application/json\"\n }\n\n resp = requests.post(self.central.vars[\"base_url\"] + url, headers=header, json=payload)\n return resp.ok\n\n def caasapi(self, group_dev: str, cli_cmds: list = None):\n cfg_dict = self.central.central_info\n tok_dict = cfg_dict[\"token\"]\n if \":\" in group_dev and len(group_dev) == 17:\n key = \"node_name\"\n else:\n key = \"group_name\"\n\n url = \"/caasapi/v1/exec/cmd\"\n\n params = {\n \"cid\": cfg_dict[\"customer_id\"],\n key: group_dev\n }\n\n headers = {\n \"authorization\": f\"{tok_dict.get('token_type', 'Bearer')} {tok_dict['access_token']}\",\n \"Content-type\": \"application/json\"\n }\n\n payload = {\"cli_cmds\": cli_cmds or []}\n\n f_url = self.central.central_info[\"base_url\"] + url\n return Response(requests.post, f_url, params=params, json=payload, headers=headers)\n\n # return requests.post(self.central.vars[\"base_url\"] + url, params=params, headers=header, json=payload)\n # TODO use my resp generator\n\n\n# t = CentralApi()\n# t.get_ap()\n# t.get_swarms_by_group(\"Branch1\")\n# t.get_swarm_details(\"fbe90101014332bf0dabfa5d2cf4ae7a0917a04127f864e047\")\n# t.get_wlan_clients(group=\"Branch1\")\n# t.get_wired_clients()\n# t.get_wired_clients(group=\"Branch1\")\n# t.get_client_details(\"20:4c:03:30:4c:4c\")\n# t.get_certificates()\n# t.get_template(\"WadeLab\", \"2930F-8\")\n# t.get_all_groups()\n# t.get_dev_by_type(\"iap\")\n# t.get_dev_by_type(\"switch\")\n# t.get_dev_by_type(\"gateway\")\n# t.get_variablised_template(\"CN71HKZ1CL\")\n# t.get_ssids_by_group(\"Branch1\")\n# t.get_gateways_by_group(\"Branch1\")\n# t.get_group_for_dev_by_serial(\"CNHPKLB030\")\n# t.get_dhcp_client_info_by_gw(\"CNF7JSP0N0\")\n# t.get_vlan_info_by_gw(\"CNHPKLB030\")\n# t.get_uplink_info_by_gw(\"CNF7JSP0N0\")\n# t.get_uplink_tunnel_stats_by_gw(\"CNF7JSP0N0\")\n# t.get_uplink_state_by_group(\"Branch1\")\n# t.get_all_sites()\n# t.get_site_details(10)\n# t.get_events_by_group(\"Branch1\")\n# t.bounce_poe(\"CN71HKZ1CL\", 2)\n# t.kick_users(\"CNC7J0T0GK\", kick_all=True)\n# t.get_task_status(15983230525575)\n# group_dev = \"Branch1/20:4C:03:26:28:4C\"\n# cli_cmds = [\"netdestination delme\", \"host 1.2.3.4\", \"!\"]\n# t.caasapi(group_dev, cli_cmds)\n# mac = \"20:4C:03:81:E8:FA\"\n# serial_num = \"CNHPKLB030\"\n# t.add_dev(mac, serial_num)\n# t.verify_add_dev(mac, serial_num)\n# t.move_dev_to_group(\"Branch1\", serial_num)\n\n\nclass BuildCLI:\n def __init__(self, data: dict = None, session=None, filename: str = None):\n filename = filename or config.bulk_edit_file\n\n self.session = session\n self.dev_info = None\n if data:\n self.data = data\n else:\n self.data = self.get_bulkedit_data(filename)\n self.cmds = []\n self.build_cmds()\n\n @staticmethod\n def get_bulkedit_data(filename: str):\n cli_data = {}\n _common = {}\n _vlans = []\n _mac = \"error\"\n _exclude_start = ''\n with open(filename) as csv_file:\n csv_reader = csv.reader([line for line in csv_file.readlines() if not line.startswith('#')])\n\n csv_rows = [r for r in csv_reader]\n\n for data_row in csv_rows[1:]:\n vlan_data = {}\n for k, v in zip(csv_rows[0], data_row):\n k = k.strip().lower().replace(' ', '_')\n # print(f\"{k}: {v}\")\n if k == \"mac_address\":\n _mac = v\n cli_data[v] = {}\n elif k in [\"group\", \"model\", \"hostname\", \"bg_peer_ip\", \"controller_vlan\",\n \"zs_site_to_site_map_name\", \"source_fqdn\"]:\n _common[k] = v\n elif k.startswith((\"vlan\", \"dhcp\", \"domain\", \"dns\", \"vrrp\", \"access_port\", \"ppoe\")):\n if k == \"vlan_id\":\n if vlan_data:\n _vlans.append(vlan_data)\n vlan_data = {k: v}\n elif k.startswith(\"dns_server_\"):\n vlan_data[\"dns_servers\"] = [v] if \"dns_servers\" not in vlan_data else \\\n [*vlan_data[\"dns_servers\"], *[v]]\n elif k.startswith(\"dhcp_default_router\"):\n vlan_data[\"dhcp_def_gws\"] = [v] if \"dhcp_def_gws\" not in vlan_data else \\\n [*vlan_data[\"dhcp_def_gws\"], *[v]]\n elif k.startswith(\"dhcp_exclude_start\"):\n _exclude_start = v\n elif k.startswith(\"dhcp_exclude_end\"):\n if _exclude_start:\n _line = f\"ip dhcp exclude-address {_exclude_start} {v}\"\n vlan_data[\"dhcp_excludes\"] = [_line] if \"dhcp_excludes\" not in vlan_data else \\\n [*vlan_data[\"dhcp_excludes\"], *[_line]]\n _exclude_start, _line = '', ''\n else:\n print(f\"Validation Error DHCP Exclude End with no preceding start ({v})... Ignoring\")\n else:\n vlan_data[k] = v\n\n _vlans.append(vlan_data)\n cli_data[_mac] = {\"_common\": _common, \"vlans\": _vlans}\n\n return cli_data\n\n def build_cmds(self):\n for dev in self.data:\n common = self.data[dev][\"_common\"]\n vlans = self.data[dev][\"vlans\"]\n _pretty_name = common.get('hostname', dev)\n print(f\"Verifying {_pretty_name} is in Group {common['group']}...\", end='')\n # group_devs = self.session.get_gateways_by_group(self.data[dev][\"_common\"][\"group\"])\n gateways = self.session.get_dev_by_type(\"gateway\")\n self.dev_info = [_dev for _dev in gateways if _dev.get('macaddr', '').lower() == dev.lower()]\n if self.dev_info:\n self.dev_info = self.dev_info[0]\n if common[\"group\"] == self.session.get_group_for_dev_by_serial(self.dev_info[\"serial\"]):\n print(' Confirmed', end='\\n')\n else:\n print(\" it is *Not*\", end=\"\\n\")\n print(f\"Moving {_pretty_name} to Group {common['group']}\")\n res = self.session.move_dev_to_group(common[\"group\"], self.dev_info[\"serial\"])\n if not res:\n print(f\"Error Returned Moving {common['hostname']} to Group {common['group']}\")\n\n print(f\"Building cmds for {_pretty_name}\")\n if common.get(\"hostname\"):\n self.cmds += [f\"hostname {common['hostname']}\", \"!\"]\n\n for v in vlans:\n self.cmds += [f\"vlan {v['vlan_id']}\", \"!\"]\n if v.get(\"vlan_ip\"):\n if not v.get(\"vlan_subnet\"):\n print(f\"Validation Error No subnet mask for VLAN {v['vlan_id']} \")\n # TODO handle the error\n self.cmds += [f\"interface vlan {v['vlan_id']}\", f\"ip address {v['vlan_ip']} {v['vlan_subnet']}\"]\n # TODO should VLAN description also be vlan name - check what bulk edit does\n if v.get(\"vlan_interface_description\"):\n self.cmds.append(f\"description {v['vlan_interface_description']}\")\n if v.get(\"vlan_helper_addr\"):\n self.cmds.append(f\"ip helper-address {v['vlan_helper_addr']}\")\n if v.get(\"vlan_interface_operstate\"):\n self.cmds.append(f\"operstate {v['vlan_interface_operstate']}\")\n self.cmds.append(\"!\")\n\n if v.get(\"pppoe_username\"):\n print(\"Warning PPPoE not supported by this tool yet\")\n\n if v.get(\"access_port\"):\n if \"thernet\" not in v[\"access_port\"] and not v[\"access_port\"].startswith(\"g\"):\n _line = f\"interface gigabitethernet {v['access_port']}\"\n else:\n _line = f\"interface {v['access_port']}\"\n self.cmds += [_line, f\"switchport access vlan {v['vlan_id']}\", \"!\"]\n\n if v.get(\"dhcp_pool_name\"):\n self.cmds.append(f\"ip dhcp pool {v['dhcp_pool_name']}\")\n if v.get(\"dhcp_def_gws\"):\n for gw in v[\"dhcp_def_gws\"]:\n self.cmds.append(f\"default-router {gw}\")\n if v.get(\"dns_servers\"):\n self.cmds.append(f\"dns-server {' '.join(v['dns_servers'])}\")\n if v.get(\"domain_name\"):\n self.cmds.append(f\"domain-name {v['domain_name']}\")\n if v.get(\"dhcp_network\"):\n if v.get(\"dhcp_mask\"):\n self.cmds.append(f\"network {v['dhcp_network']} {v['dhcp_mask']}\")\n elif v.get(\"dhcp_network_prefix\"):\n self.cmds.append(f\"network {v['dhcp_network']} /{v['dhcp_network_prefix']}\")\n self.cmds.append(\"!\")\n\n if v.get(\"dhcp_excludes\"):\n # dhcp exclude lines are fully formatted as data is collected\n for _line in v[\"dhcp_excludes\"]:\n self.cmds.append(_line)\n\n if v.get(\"vrrp_id\"):\n if v.get(\"vrrp_ip\"):\n self.cmds += [f\"vrrp {v['vrrp_id']}\", f\"ip address {v['vrrp_ip']}\", f\"vlan {v['vlan_id']}\"]\n if v.get(\"vrrp_priority\"):\n self.cmds.append(f\"priority {v['vrrp_priority']}\")\n self.cmds += [\"no shutdown\", \"!\"]\n else:\n print(f\"Validation Error VRRP ID {v['vrrp_id']} VLAN {v['vlan_id']} No VRRP IP provided... Skipped\")\n\n if v.get(\"bg_peer_ip\"):\n # _as = self.session.get_bgp_as()\n # self.cmds.append(f\"router bgp neighbor {v['bg_peer_ip']} as {_as}\")\n print(\"bgp peer ip Not Supported by Script yet\")\n\n if v.get(\"zs_site_to_site_map_name\") or v.get(\"source_fqdn\"):\n print(\"Zscaler Configuration Not Supported by Script Yet\")\n\n\nif __name__ == \"__main__\":\n cli = BuildCLI(session=CentralApi())\n for c in cli.cmds:\n print(c)\n","sub_path":"lib/centralCLI/central.py","file_name":"central.py","file_ext":"py","file_size_in_byte":26766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"592343771","text":"inputPath = 'c:\\Programing\\Python\\sequences.fasta'\noutputPath = 'c:\\Programing\\Python\\sequencesR.fasta'\n\nprefixToDelete = 'A00721:127:HW5KYDSXX:4:'\nsuffixToDelete = '_1:N:0:GGTCTGGT+AAGGCCGT'\n\nwith open(inputPath, 'r') as inputFile, open(outputPath, 'w') as outputFile:\n line = inputFile.readline()\n while line:\n\n if line[0] == '>':\n leftIndex = line.find(prefixToDelete) + len(prefixToDelete)\n rightIndex = len(line) - line.find(suffixToDelete)\n\n if leftIndex > 0 and len(prefixToDelete) > 0:\n line = line[leftIndex:]\n if rightIndex > 0 and len(suffixToDelete) > 0:\n line = line[:-rightIndex]\n line = '>' + line + '\\n'\n\n outputFile.write(line)\n line = inputFile.readline()\n","sub_path":"Misc. programs/shortenFastaName.py","file_name":"shortenFastaName.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"541700611","text":"from view.input_nilai import input_data\ndata = {}\n\ndef tambah_data():\n d = input_data()\n data[d['nama']]=d\n\ndef ubah_data():\n nama = input(\"Masukan nama untuk mengubah data: \")\n if nama in data.keys():\n print(\"Masukan Data yang diubah :\")\n ubah = input(\"(Semua), (Nama), (NIM), \"\n \"(Tugas), (UTS), (UAS) : \")\n if ubah.lower() == \"semua\":\n print(\"_______________________\")\n print(\"Ubah Data {}\".format(nama))\n print(\"-----------------------\")\n data[nama]['nim'] = input(\"Ubah NIM : \")\n data[nama]['tugas'] = int(input(\"Ubah Nilai Tugas: \"))\n data[nama]['uas'] = int(input(\"Ubah Nilai UAS : \"))\n data[nama]['uts'] = int(input(\"Ubah Nilai UTS : \"))\n elif ubah.lower() == \"nim\":\n data[nama]['nim'] = input(\"Ubah Nim : \")\n elif ubah.lower() == \"tugas\":\n data[nama]['tugas'] = int(input(\"Ubah Nilai Tugas : \"))\n elif ubah.lower() == \"uts\":\n data[nama]['uts'] = int(input(\"Ubah Nilai UTS : \"))\n elif ubah.lower() == \"uas\":\n data[nama]['uas'] = int(input(\"Ubah Nilai UAS : \"))\n\n else:\n print(\"'{}' Tidak Ditemukan\".format(nama))\n print(data)\ndef hapus_data():\n nama = input(\"Masukan nama untuk menghapus data : \")\n if nama in data.keys():\n del data[nama]\n print(\"Data '{}' dihapus\".format(nama))\n return True\n else:\n print(\"'{}' Tidak Ditemukan\".format(nama))\n return False\ndef cari_data():\n print(\"Mencari Daftar Nilai : \")\n print(\"=======================\")\n nama = input(\"Masukan nama untuk mencari daftar nilai : \")\n if nama in data.keys():\n print(\"Nama {0}, dengan NIM : {1}\\n\"\n \"Nilai Tugas: {2}, UTS: {3}, dan UAS: {4}\\n\"\n \"dan nilai akhir {5}\".format(nama, d['nim'],\n d['tugas'], d['uts'],\n d['uas'], d['akhir']))","sub_path":"model/daftar_nilai.py","file_name":"daftar_nilai.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"65033736","text":"import random\n\nfrom classes.game import Person, bcolors\nfrom classes.magic import Spell\nfrom classes.inventory import Item\n\n\n# black magic\nfire=Spell(\"Fire\", 10, 500, \"black\")\nthunder=Spell(\"Thunder\", 12, 580, \"black\")\nblizzard=Spell(\"Blizzard\", 14, 640, \"black\")\nmeteor=Spell(\"Meteor\", 16, 720, \"black\")\nblake=Spell(\"Blake\", 18, 800, \"black\")\n\n# white magic\ncure = Spell(\"Cure\", 12, 620, \"white\")\ncura = Spell(\"Cura\", 16, 1500, \"white\")\n\nplayer_magic = [fire,thunder,blizzard,meteor,blake,cure,cura]\n\n\npotion = Item(\"Potion\", \"potion\", \"Heals 50 HP\", 50)\nhipotion = Item(\"Hi-Potion\", \"potion\", \"Heals 100 HP\", 100)\nsuperpotion = Item(\"Super Potion\", \"potion\", \"Heals 500 HP\", 500)\nelixir = Item(\"Elixir\", \"elixer\", \"Fullly restores HP on one member\", 99999)\nhielixir = Item(\"MegaElixir\", \"elixer\", \"Fullly restores HP for all\", 99999)\n\ngrenade = Item(\"Grenade\", \"attack\", \"Deals 500 damage\", 500)\n\nplayer1_items =[{\"item\": potion, \"quantity\": 5},{\"item\": hipotion, \"quantity\": 3},\n {\"item\": superpotion, \"quantity\": 1},{\"item\": elixir, \"quantity\": 3},\n {\"item\": hielixir, \"quantity\": 1},{\"item\": grenade, \"quantity\": 3}]\nplayer2_items =[{\"item\": potion, \"quantity\": 5},{\"item\": hipotion, \"quantity\": 3},\n {\"item\": superpotion, \"quantity\": 1},{\"item\": elixir, \"quantity\": 3},\n {\"item\": hielixir, \"quantity\": 1},{\"item\": grenade, \"quantity\": 3}]\nplayer3_items =[{\"item\": potion, \"quantity\": 5},{\"item\": hipotion, \"quantity\": 3},\n {\"item\": superpotion, \"quantity\": 1},{\"item\": elixir, \"quantity\": 3},\n {\"item\": hielixir, \"quantity\": 1},{\"item\": grenade, \"quantity\": 3}]\n\n#instantiate people\nplayer1 = Person(\"Valos\",3260, 132, 300, 34, player_magic, player1_items)\nplayer2 = Person(\"Nick \",4160, 176, 310, 34, player_magic, player2_items)\nplayer3 = Person(\"Robot\",3940, 168, 290, 34, player_magic, player3_items)\n\nenemy1 = Person(\"Magus\",17500, 130, 285, 25, player_magic, [])\nenemy2 = Person(\"Imper\",11200, 100, 340, 25, player_magic, [])\nenemy3 = Person(\"Impro\",11200, 100, 340, 25, player_magic, [])\n\nplayers = [player1,player2,player3]\nenemies = [enemy1,enemy2,enemy3]\n\nrunning = True\ni=0\n\nwhile running:\n print(\"===================================\")\n\n print(\"\\n\\n\")\n print(\"NAME HP MP\")\n for player in players:\n player.get_stats()\n\n for enemy in enemies:\n enemy.get_enemy_stats()\n print(\"\\n\\n\")\n\n\n for player in players:\n\n player.choose_action()\n choice = input(\"Choose action: \")\n index = int(choice)-1\n\n if index == 0:\n dmg = player.generate_damage()\n enemy = player.choose_target(enemies)\n enemies[enemy].take_damage(dmg)\n print(\"you attacked\", enemies[enemy].name, \"for \", dmg )\n\n if enemies[enemy].get_hp() == 0:\n print(bcolors.OKGREEN + enemies[enemy].name + \" had died.\" + bcolors.ENDC)\n del enemies[enemy]\n\n elif index==1:\n player.choose_magic()\n magic_choice = int(input(\"Choose magic: \")) - 1\n\n if magic_choice < -1 or magic_choice >= len(player.magic):\n continue\n\n spell = player.magic[magic_choice]\n magic_dmg = spell.generate_spell_damage()\n\n current_mp = player.get_mp()\n\n if spell.cost > current_mp:\n print(bcolors.FAIL + \"\\nNot Enough Magic Points to do this Magic\" + bcolors.ENDC)\n continue\n\n player.reduce_mp(spell.cost)\n if spell.type == \"black\":\n enemy = player.choose_target(enemies)\n enemies[enemy].take_damage(magic_dmg)\n\n print(bcolors.OKBLUE + \"\\n\" + spell.name + \" deals\", str(magic_dmg),\n \"points of damage to \" + enemies[enemy].name + bcolors.ENDC + \"\\n\")\n\n if enemies[enemy].get_hp() == 0:\n print(bcolors.OKGREEN + enemies[enemy].name + \" had died.\" + bcolors.ENDC)\n del enemies[enemy]\n\n elif spell.type == \"white\":\n player.heal(magic_dmg)\n\n print(bcolors.OKBLUE + \"\\n\" + spell.name + \" heals\", str(magic_dmg),\n \"points of HP \" + bcolors.ENDC + \"\\n\")\n\n\n elif index == 2:\n\n player.choose_item()\n\n item_choice = int(input(\"choose Item: \"))-1\n\n if item_choice < -1 or item_choice >= len(player.items):\n continue\n\n item = player.items[item_choice][\"item\"]\n\n if player.items[item_choice][\"quantity\"] > 0:\n\n if item.type == \"potion\":\n player.heal(item.prop)\n print(bcolors.OKGREEN + \"\\n\" + item.name + \" heals for \" + str(item.prop) + bcolors.ENDC)\n\n elif item.type == \"elixer\":\n if item.name == \"Elixir\":\n player.hp = player.max_hp\n player.mp = player.max_mp\n\n print(bcolors.OKGREEN + \"\\n\" + item.name + \" restored all you\" + bcolors.ENDC)\n\n elif item.name == \"MegaElixir\":\n for target in players:\n target.hp = target.max_hp\n target.mp = target.max_mp\n\n print(bcolors.OKGREEN + \"\\n\" + item.name + \" restored your team.\" + bcolors.ENDC)\n\n elif item.type == \"attack\":\n\n enemy = player.choose_target(enemies)\n enemies[enemy].take_damage(item.prop)\n\n print(bcolors.OKGREEN + \"\\n\" + item.name + \" deals damage of \" + str(item.prop) + \" to \" + enemies[enemy].name + bcolors.ENDC)\n\n if enemies[enemy].get_hp() == 0:\n print(bcolors.OKGREEN + enemies[enemy].name + \" had died.\" + bcolors.ENDC)\n del enemies[enemy]\n\n player.reduce_item(item_choice)\n\n else:\n print(bcolors.FAIL + \"you have no \" +item.name + bcolors.ENDC)\n continue\n\n # check for defeats\n defeated_enemies = 0\n for enemy in enemies:\n if enemy.get_hp() == 0:\n defeated_enemies += 1\n\n if defeated_enemies > 2:\n print(bcolors.OKGREEN + \"you won!\" + bcolors.ENDC)\n running = False\n\n defeated_players = 0\n for player in players:\n if player.get_hp() == 0:\n defeated_players += 1\n\n if defeated_players > 2:\n print(bcolors.FAIL + \"you lost!\" + bcolors.ENDC)\n running = False\n\n\n for enemy in enemies:\n enemy_choice = random.randrange(0,2)\n\n if enemy_choice == 0:\n target = random.randrange(0,len(players))\n enemy_dmg = enemy.generate_damage()\n players[target].take_damage(enemy_dmg)\n print(bcolors.FAIL + enemy.name + \" attacked \" + players[target].name + \" for \" + str(enemy_dmg) + bcolors.ENDC)\n\n elif enemy_choice ==1:\n\n if enemy.get_mp() > 10:\n spell = enemy.choose_enemy_spell()\n\n magic_dmg = spell.generate_spell_damage()\n\n if spell.type == \"black\":\n target = random.randrange(0,len(players))\n players[target].take_damage(magic_dmg)\n\n print(bcolors.FAIL + spell.name + \" of \" + enemy.name + \" deals\", str(magic_dmg),\n \"points of damage to \" + players[target].name + bcolors.ENDC )\n\n if players[target].get_hp() == 0:\n print(bcolors.FAIL + players[target].name + \" had died.\" + bcolors.ENDC)\n del players[target]\n\n elif spell.type == \"white\":\n enemy.heal(magic_dmg)\n\n print(bcolors.WARNING + spell.name + \" heals\", str(magic_dmg),\n \"points of HP of \" + enemy.name + bcolors.ENDC )\n\n\n\n else:\n target = random.randrange(0, len(players))\n enemy_dmg = enemy.generate_damage()\n players[target].take_damage(enemy_dmg)\n print(bcolors.FAIL + enemy.name + \" attacked \" + players[target].name + \" for \" + str(\n enemy_dmg) + bcolors.ENDC)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"127754763","text":"\"\"\"\n\nFunctions for calculating common analysis measures, such as total fixation\nduration or initial landing position.\n\n\"\"\"\n\n\nimport numpy as _np\nfrom .fixation import FixationSequence as _FixationSequence, Fixation as _Fixation\nfrom .text import TextBlock as _TextBlock, InterestArea as _InterestArea\n\n\ndef initial_fixation_duration(interest_areas, fixation_sequence):\n \"\"\"\n\n Given an interest area or collection of interest areas, return the\n duration of the initial fixation on each interest area. Returns a\n dictionary in which the keys are interest area IDs and the values are\n initial fixation durations.\n\n \"\"\"\n if isinstance(interest_areas, _InterestArea):\n interest_areas = [interest_areas]\n if not isinstance(fixation_sequence, _FixationSequence):\n raise TypeError(\"fixation_sequence should be of type FixationSequence\")\n durations = {}\n for interest_area in interest_areas:\n if not isinstance(interest_area, _InterestArea):\n raise TypeError(f\"{str(interest_area)} is not of type InterestArea\")\n durations[interest_area.id] = 0\n for fixation in fixation_sequence.iter_without_discards():\n if fixation in interest_area:\n durations[interest_area.id] = fixation.duration\n break\n return durations\n\n\ndef total_fixation_duration(interest_areas, fixation_sequence):\n \"\"\"\n\n Given an interest area or collection of interest areas, return the total\n fixation duration on each interest area. Returns a dictionary in which the\n keys are interest area IDs and the values are total fixation durations.\n\n \"\"\"\n if isinstance(interest_areas, _InterestArea):\n interest_areas = [interest_areas]\n if not isinstance(fixation_sequence, _FixationSequence):\n raise TypeError(\"fixation_sequence should be of type FixationSequence\")\n durations = {}\n for interest_area in interest_areas:\n if not isinstance(interest_area, _InterestArea):\n raise TypeError(f\"{str(interest_area)} is not of type InterestArea\")\n durations[interest_area.id] = 0\n for fixation in fixation_sequence.iter_without_discards():\n if fixation in interest_area:\n durations[interest_area.id] += fixation.duration\n return durations\n\n\ndef gaze_duration(interest_areas, fixation_sequence):\n \"\"\"\n\n Given an interest area or collection of interest areas, return the gaze\n duration on each interest area. Gaze duration is the sum duration of all\n fixations inside an interest area until the area is exited for the first\n time. Returns a dictionary in which the keys are interest area IDs and the\n values are gaze durations.\n\n \"\"\"\n if isinstance(interest_areas, _InterestArea):\n interest_areas = [interest_areas]\n if not isinstance(fixation_sequence, _FixationSequence):\n raise TypeError(\"fixation_sequence should be of type FixationSequence\")\n durations = {}\n for interest_area in interest_areas:\n if not isinstance(interest_area, _InterestArea):\n raise TypeError(f\"{str(interest_area)} is not of type InterestArea\")\n durations[interest_area.id] = 0\n for fixation in fixation_sequence.iter_without_discards():\n if fixation in interest_area:\n durations[interest_area.id] += fixation.duration\n elif durations[interest_area.id] > 0:\n break # at least one previous fixation was inside the IA and this fixation is not, so break\n return durations\n\n\ndef initial_landing_position(interest_areas, fixation_sequence):\n \"\"\"\n\n Given an interest area or collection of interest areas, return the initial\n landing position (expressed in character positions) on each interest area.\n Counting is from 1, so a 1 indicates that the fixation landed on the first\n character and so forth. If the interest area represents right-to-left\n text, the first character is the rightmost one. Returns a dictionary in\n which the keys are interest area IDs and the values are initial landing\n positions.\n\n \"\"\"\n if isinstance(interest_areas, _InterestArea):\n interest_areas = [interest_areas]\n if not isinstance(fixation_sequence, _FixationSequence):\n raise TypeError(\"fixation_sequence should be of type FixationSequence\")\n positions = {}\n for interest_area in interest_areas:\n if not isinstance(interest_area, _InterestArea):\n raise TypeError(f\"{str(interest_area)} is not of type InterestArea\")\n positions[interest_area.id] = None\n for fixation in fixation_sequence.iter_without_discards():\n if fixation in interest_area:\n for position, char in enumerate(interest_area, 1):\n if fixation in char:\n positions[interest_area.id] = position\n break\n break\n return positions\n\n\ndef initial_landing_x(interest_areas, fixation_sequence):\n \"\"\"\n\n Given an interest area or collection of interest areas, return the initial\n landing position (expressed in pixel distance from the start of the\n interest area) on each interest area. If the interest area represents\n right-to-left text, the start of the interest area is defined as the right\n edge. Returns a dictionary in which the keys are interest area IDs and the\n values are initial landing positions.\n\n \"\"\"\n if isinstance(interest_areas, _InterestArea):\n interest_areas = [interest_areas]\n if not isinstance(fixation_sequence, _FixationSequence):\n raise TypeError(\"fixation_sequence should be of type FixationSequence\")\n positions = {}\n for interest_area in interest_areas:\n if not isinstance(interest_area, _InterestArea):\n raise TypeError(f\"{str(interest_area)} is not of type InterestArea\")\n positions[interest_area.id] = None\n for fixation in fixation_sequence.iter_without_discards():\n if fixation in interest_area:\n if interest_area.right_to_left:\n positions[interest_area.id] = interest_area.x_br - fixation.x\n else:\n positions[interest_area.id] = fixation.x - interest_area.x_tl\n break\n return positions\n\n\ndef duration_mass(text_block, fixation_sequence, n=1, gamma=30):\n \"\"\"\n\n Given a `eyekit.text.TextBlock` and `eyekit.fixation.FixationSequence`,\n distribute the durations of the fixations probabilistically across the\n `eyekit.text.TextBlock`. Specifically, the duration of fixation *f* is\n distributed over all characters *C* in its line according to the\n probability that the reader is \"seeing\" each character (see\n `p_characters_fixation()`), and this is summed over all fixations:\n\n $$\\\\sum_{f \\\\in F} p(C|f) \\\\cdot f_\\\\mathrm{dur}$$\n\n Returns a 2D Numpy array, the sum of which is equal to the total duration\n of all fixations. This can be passed to `eyekit.vis.Image.draw_text_block_heatmap()`\n for visualization. Duration mass reveals the parts of the text that\n received the most attention. Optionally, this can be performed over\n higher-level ngrams by setting `n` > 1.\n\n \"\"\"\n if not isinstance(text_block, _TextBlock):\n raise TypeError(\"text_block should be of type TextBlock\")\n if not isinstance(fixation_sequence, _FixationSequence):\n raise TypeError(\"fixation_sequence should be of type FixationSequence\")\n shape = text_block.n_rows, text_block.n_cols - (n - 1)\n distribution = _np.zeros(shape, dtype=float)\n for fixation in fixation_sequence.iter_without_discards():\n distribution += (\n p_characters_fixation(text_block, fixation, n=n, gamma=gamma)\n * fixation.duration\n )\n return distribution\n\n\ndef p_characters_fixation(text_block, fixation, n=1, gamma=30):\n \"\"\"\n\n Given a `eyekit.text.TextBlock` and `eyekit.fixation.Fixation`, calculate\n the probability that the reader is \"seeing\" each character in the text. We\n assume that the closer a character is to the fixation point, the greater\n the probability that the participant is \"seeing\" (i.e., processing) that\n character. Specifically, for a given fixation *f*, we compute a Gaussian\n distribution over all characters in the line according to:\n\n $$p(c|f) \\\\propto \\\\mathrm{exp} \\\\frac{ -\\\\mathrm{ED}(f_\\\\mathrm{pos}, c_\\\\mathrm{pos})^2 }{2\\\\gamma^2}$$\n\n where *γ* (`gamma`) is a free parameter controlling the rate at which\n probability decays with the Euclidean distance (ED) between the position\n of fixation *f* and the position of character *c*.\n\n Returns a 2D Numpy array representing a probability distribution over all\n characters, with all its mass confined to the line that the fixation\n occurred inside, and with greater mass closer to fixation points. This\n array can be passed to `eyekit.vis.Image.draw_text_block_heatmap()` for\n visualization. Optionally, this calculation can be performed over\n higher-level ngrams by setting `n` > 1.\n\n \"\"\"\n if not isinstance(fixation, _Fixation):\n raise TypeError(\"fixation should be of type Fixation\")\n line_n = _np.argmin(abs(_np.array(text_block.midlines) - fixation.y))\n shape = text_block.n_rows, text_block.n_cols - (n - 1)\n distribution = _np.zeros(shape, dtype=float)\n fixation_xy = _np.array(fixation.xy, dtype=int)\n two_gamma_squared = 2 * gamma ** 2\n for ngram in text_block.ngrams(n, line_n=line_n):\n ngram_xy = _np.array(ngram.center, dtype=int)\n r, s, e = ngram.id.split(\":\")\n distribution[(int(r), int(s))] = _np.exp(\n -((fixation_xy - ngram_xy) ** 2).sum() / two_gamma_squared\n )\n return distribution / distribution.sum()\n","sub_path":"eyekit/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":9786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"199561443","text":"# Copyright 2018 The Pontem 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\"\"\"Wrapper for Compute API service proxy.\"\"\"\nimport re\nimport subprocess\nimport time\nimport uuid\n\nfrom googleapiclient import errors\nfrom httplib2 import HttpLib2Error\n\n\nimport google.auth\n\nfrom google.cloud.pontem.sql.replicator.util import gcp_api_util\n\nCOMPUTE_SERVICE = 'compute'\nCOMPUTE_SERVICE_VERSION = 'v1'\nALLOW_SSH_FIREWALL_RULE = 'allow_replicator_ssh'\n# RFC 1035 regex (https://www.ietf.org/rfc/rfc1035.txt) for firewall rule names\nRFC1035_REGEX = r'(?:[a-z]([-a-z0-9]*[a-z0-9])?)\\Z'\n# Amount of seconds to wait prior to throwing error\nFIREWALL_RULE_TIMEOUT = 300\nFIREWALL_RULE_INTERVAL = 10\n\n\nclass TimeoutError(Exception):\n \"\"\"Timeout error raised if operation takes too long.\"\"\"\n\n\nclass SCPError(Exception):\n \"\"\"Error raised if there was a problem copying a file with SCP.\"\"\"\n\n\nclass FirewallRule(object):\n \"\"\"Configuration for firewall rule.\"\"\"\n def __init__(self, name=None, description=None):\n \"\"\"Constructor.\n\n Args:\n name (str): Name for firewall rule. Must comply with RFC 1035.\n description (str): Description of firewall rule.\n\n Raises:\n ValueError: Exception if name does not conform to RFC1035.\n \"\"\"\n self.name = name or 'firewall_rule_{}'.format(uuid.uuid4())\n if re.match(RFC1035_REGEX, name) is None:\n raise ValueError('{} does not conform to RFC1035'.format(name))\n self.description = description or 'User defined firewall rule.'\n self.protocol = 'TCP'\n self.is_allowed = True,\n self.ports = None\n self.is_ingress = True\n self.network = None\n\n\ndef build_compute_service(credentials=None):\n \"\"\"Builds an authorized compute service proxy with a custom user agent.\n\n Args:\n credentials (google.auth.Credentials): Credentials to authorize client.\n\n Returns:\n Resource: Authorized compute service proxy with custom user agent.\n \"\"\"\n service = gcp_api_util.build_authorized_service(\n COMPUTE_SERVICE,\n COMPUTE_SERVICE_VERSION,\n credentials\n )\n\n return service\n\n\ndef create_firewall_rule(firewall_rule,\n project=None, credentials=None):\n \"\"\"Creates a firewall rule in a Google Cloud Project.\n\n Args:\n firewall_rule (FirewallRule): Configuration for firewall rule.\n project (str): Project ID where firewall rule will be created.\n credentials (google.auth.Credentials): Credentials to authorize client.\n\n Returns:\n JSON: Response from request.\n \"\"\"\n\n default_credentials, default_project = google.auth.default()\n service = build_compute_service(credentials or default_credentials)\n\n if firewall_rule.ports is None:\n ports = ['3306']\n else:\n ports = firewall_rule.ports\n\n request_body = {\n 'name': firewall_rule.name,\n 'description': firewall_rule.description,\n 'sourceRanges': firewall_rule.source_ip_range,\n 'allowed' if firewall_rule.is_allowed else 'denied': [{\n 'IPProtocol': firewall_rule.protocol,\n 'ports': ports,\n }],\n 'network': firewall_rule.network,\n 'direction': 'INGRESS' if firewall_rule.is_ingress else 'EGRESS',\n }\n\n request = service.firewalls().insert(\n project=project or default_project,\n body=request_body\n )\n response = request.execute()\n\n return response\n\n\ndef is_firewall_rule_active(firewall, project=None, credentials=None):\n \"\"\"Checks if a firewall rule active.\n\n Args:\n firewall (str): The name of the firewall rule.\n project (str): Project ID where firewall rule may be active.\n credentials (google.auth.Credentials): Credentials to authorize client.\n\n Returns:\n bool: True if firewall rule is active, False otherwise.\n \"\"\"\n default_credentials, default_project = google.auth.default()\n service = build_compute_service(credentials or default_credentials)\n try:\n _ = service.firewalls().get(project=project or default_project,\n firewall=firewall)\n\n except (errors.HttpError, HttpLib2Error) as e:\n if isinstance(e, errors.HttpError) and e.resp.status == 404:\n return False\n return True\n\n\ndef enable_ssh(network=None, project=None, credentials=None):\n \"\"\"Enables SSH on the network if rule note enabled.\n\n Args:\n network (str): Network to allow SSH on.\n project (str): Project ID where firewall rule will be activated.\n credentials (google.auth.Credentials): Credentials to authorize client.\n\n Raises:\n TimeoutError: Operation took too long.\n \"\"\"\n if not is_firewall_rule_active(ALLOW_SSH_FIREWALL_RULE,\n project, credentials):\n firewall_rule = FirewallRule(ALLOW_SSH_FIREWALL_RULE,\n description='Allow SSH.')\n firewall_rule.ports = ['22']\n firewall_rule.network = network\n create_firewall_rule(firewall_rule, project, credentials)\n\n start_time = time.time()\n while not is_firewall_rule_active(ALLOW_SSH_FIREWALL_RULE,\n project, credentials):\n elapsed_time = time.time() - start_time\n if elapsed_time > FIREWALL_RULE_TIMEOUT:\n raise TimeoutError(\n 'Creating Allow SSH Firewall Rule took too long.')\n time.sleep(FIREWALL_RULE_INTERVAL)\n return\n\n\ndef get_remote_file(remote_host, remote_file_path, zone, local_dir='.'):\n \"\"\"Copies file from remote GCP host to local directory.\n\n Args:\n remote_host (str): Remote host file exists on.\n remote_file_path (str): File to copy\n zone (str): Zone remote host resides in.\n local_dir (str): Local directory where file will be copied.\n\n Raises:\n SCPError: Something went wrong during the SCP operation.\n \"\"\"\n gcloud = subprocess.Popen(('gcloud',\n 'compute',\n 'scp',\n '{}:{}'.format(remote_host, remote_file_path),\n local_dir, '--zone', zone))\n _, error = gcloud.communicate()\n if error:\n raise SCPError(error.strip())\n return\n\n\ndef write_remote_file(remote_host, remote_dir, zone, local_file_path):\n \"\"\"Copies a local file to a remote host directory.\n\n Args:\n remote_host (str): Remote host file exists on.\n remote_dir (str): Remote directory to copy file to.\n zone (str): Zone remote host resides in.\n local_file_path (str): Local file to be copied.\n\n Raises:\n SCPError: Something went wrong during the SCP operation.\n \"\"\"\n gcloud = subprocess.Popen(('gcloud',\n 'compute',\n 'scp',\n local_file_path,\n '{}:{}'.format(remote_host, remote_dir),\n '--zone', zone))\n _, error = gcloud.communicate()\n if error:\n raise SCPError(error.strip())\n return\n","sub_path":"CloudSQLReplicator/google/cloud/pontem/sql/replicator/util/compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":7704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"497004565","text":"# Copyright (c) 2019 Neel Network\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ---------------------------------------------------------------------------\n\nimport rethinkdb as re\nfrom rethinkdb.errors import ReqlNonExistenceError\n\nfrom api.errors import ApiBadRequest\n\nfrom db.common import fetch_holdings\nfrom db.common import fetch_latest_block_num\n\nr = re.RethinkDB()\n\nasync def fetch_all_account_resources(conn):\n return await r.table('accounts')\\\n .filter((fetch_latest_block_num() >= r.row['start_block_num'])\n & (fetch_latest_block_num() < r.row['end_block_num']))\\\n .map(lambda account: account.merge(\n {'publicKey': account['public_key']}))\\\n .map(lambda account: account.merge(\n {'holdings': fetch_holdings(account['holdings'])}))\\\n .map(lambda account: (account['label'] == \"\").branch(\n account.without('label'), account))\\\n .map(lambda account: (account['description'] == \"\").branch(\n account.without('description'), account))\\\n .without('public_key', 'delta_id',\n 'start_block_num', 'end_block_num')\\\n .coerce_to('array').run(conn)\n\n\nasync def fetch_account_resource(conn, public_key, auth_key):\n try:\n return await r.table('accounts')\\\n .get_all(public_key, index='public_key')\\\n .max('start_block_num')\\\n .merge({'publicKey': r.row['public_key']})\\\n .merge({'holdings': fetch_holdings(r.row['holdings'])})\\\n .do(lambda account: (r.expr(auth_key).eq(public_key)).branch(\n account.merge(_fetch_email(public_key)), account))\\\n .do(lambda account: (account['label'] == \"\").branch(\n account.without('label'), account))\\\n .do(lambda account: (account['description'] == \"\").branch(\n account.without('description'), account))\\\n .without('public_key', 'delta_id',\n 'start_block_num', 'end_block_num')\\\n .run(conn)\n except ReqlNonExistenceError:\n raise ApiBadRequest(\n \"No account with the public key {} exists\".format(public_key))\n\n\ndef _fetch_email(public_key):\n return r.table('auth')\\\n .get_all(public_key, index='public_key')\\\n .pluck('email')\\\n .coerce_to('array')[0]\n","sub_path":"rest_api/db/accounts_query.py","file_name":"accounts_query.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"493844276","text":"from tornado.web import RequestHandler\nfrom tornado.web import Application\nimport tornado.ioloop\n\nclass IndexHandler(RequestHandler):\n def get(self, *args, **kwargs):\n if self.get_argument('u', None) in ['alex', 'eric']:\n\n # self.set_cookie(\"name\", self.get_argument('u'))\n self.set_secure_cookie(\"name\", self.get_argument('u'))\n else:\n self.write(\"请登录\")\n\nclass ManagerHandler(RequestHandler):\n def get(self, *args, **kwargs):\n print(self.get_cookie('name'))\n\n if str(self.get_secure_cookie('name', None),encoding='utf-8') in ['alex', 'eric']:\n self.write('欢迎登录: '+ str(self.get_secure_cookie('name', None),encoding='utf-8'))\n else:\n self.redirect(\"/index\")\n\nsettings = {\n \"cookie_secret\": \"asdfasdf\",\n}\n\napplication = Application(\n [\n (r'/index', IndexHandler),\n (r'/manager', ManagerHandler),\n ], **settings\n)\n\nif __name__ == \"__main__\":\n application.listen(8888)\n tornado.ioloop.IOLoop.instance().start()","sub_path":"home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"539466778","text":"import requests, time, re, os, datetime\nfrom bs4 import BeautifulSoup\nfrom multiprocessing import Queue\nfrom threading import Thread\n\n\nclass Code_spider(object):\n def __init__(self):\n self.urls_file = 'ProjectUrl_stars.txt' # 存放项目链接的文件\n self.folder = 'F:/PyProject/GetCode_MyStar/projects(stars)/' # 项目存放目录(需修改)\n self.headers = {'User-Agent': 'Mozilla/5.0'}\n self.urlCount = 0\n self.q1 = Queue() # 创建消息队列,存放项目主页的链接\n self.q2 = Queue() # 创建消息队列,存放下载链接和对应项目名\n\n # 根据方法名称启动线程\n def work(self, methode_name):\n L = []\n for i in range(50):\n if methode_name == 'get_DownUrl':\n th = Thread(target=self.get_DownUrl, args=(i + 1,))\n th.start()\n L.append(th)\n elif methode_name == 'down_load':\n th = Thread(target=self.down_load, args=(i + 1,))\n th.start()\n L.append(th)\n else:\n exit('方法名称有误,线程终止')\n for th in L:\n th.join()\n\n # 从文件读取各项目主页链接\n def get_MainUrl(self):\n fp = open(self.urls_file, 'r')\n for url in fp.readlines():\n self.q1.put(url.strip())\n fp.close()\n print(\"本次将爬取\", self.q1.qsize(), \"个下载链接\")\n\n # 多线程循环获取项目主页面上的下载链接\n def get_DownUrl(self, n):\n while True:\n try:\n mainUrl = self.q1.get(block=True, timeout=2).strip()\n except:\n # print('爬取不到链接了,%s号线程结束工作' % n)\n break\n response = requests.get(mainUrl, self.headers)\n content = response.text\n soup = BeautifulSoup(content, \"html.parser\")\n a = soup.find_all('a', class_=re.compile(\"btn btn-outline get-repo-btn\")) # 获取下载zip的链接\n zip_url = ''\n for k in a:\n zip_url = 'https://github.com' + k['href']\n linkAndFilename = []\n linkAndFilename.append(mainUrl.split('/')[-1])\n linkAndFilename.append(zip_url)\n self.q2.put(linkAndFilename)\n self.urlCount += 1\n print('已爬取%s个下载链接\\n' % self.urlCount, end='')\n\n # 多线程循环执行的下载函数\n def down_load(self, n):\n while True:\n try:\n linkAndFilename = self.q2.get(block=True, timeout=2)\n filename = linkAndFilename[0].strip()\n link = linkAndFilename[1]\n except:\n # print('取不到链接了,%s号线程结束工作' % n)\n break\n # 文件的绝对路径\n abs_filename = self.folder + filename + '.zip'\n # 只下载本地不存在或文件大小为0的链接\n if (not os.path.exists(abs_filename)) or os.path.getsize(abs_filename) == 0:\n with open(abs_filename, 'wb') as code:\n print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \"线程%s开始下载:%s\\n\" % (n, filename),\n end='')\n # 若网络情况的变化导致异常,则3s后重新请求,一直循环,直到访问站点成功\n while True:\n try:\n code.write(requests.get(link, self.headers).content)\n break\n except:\n print('%s号线程网络请求发生异常,尝试重新下载...' % n)\n time.sleep(3)\n self.urlCount -= 1\n print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + \"线程%s完成下载:%s,共剩余%s个项目正在下载\\n\" % (\n n, filename, self.urlCount), end='')\n else:\n self.urlCount -= 1\n print('%s文件已存在,无需下载,共剩余%s个项目正在下载\\n' % (abs_filename, self.urlCount), end='')\n\n\nif __name__ == '__main__':\n start_time = time.time()\n\n spider = Code_spider()\n spider.get_MainUrl()\n print('开始爬取下载链接...')\n spider.work('get_DownUrl')\n print('开始下载文件...')\n spider.work('down_load')\n\n end_time = time.time()\n print(\"下载总时间:\", end_time - start_time)\n","sub_path":"mtp_getProject.py","file_name":"mtp_getProject.py","file_ext":"py","file_size_in_byte":4529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"525894958","text":"from bs4 import BeautifulSoup\nimport urllib.request\nimport os\nimport time\nimport platform\nimport time\nimport sys\n\ncontract = sys.argv[1]\n#contract = 'CZ14'\n\n#yahoo url to find the commodity price\nurl = \"http://finance.yahoo.com/q?s={0}.CBT\".format(contract)\n\n#downloads the html page to memory\nhtmlcontent = urllib.request.urlopen(url).read()\n\n#converts to beautiful soup content\nsoup = BeautifulSoup(htmlcontent)\n\n#parses out the line with price\nsoup_price = soup.find_all(id='yfs_l10_{0}.cbt'.format(contract.lower()))\n\n#parses out the price from line\nprice = str(soup_price[0]).split('<')[1].split('>')[-1]\n\n#parses out the line with the time\nsoup_time = soup.find_all(id='yfs_market_time')\n\n#parses out the time from the line\ntmp_time = str(soup_time).split('>')[1].split('-')[0].split(',')[1:4]\n\n#pulls out all the time variables\nmon = tmp_time[0].strip().split()[0]\nday = tmp_time[0].strip().split()[1]\nyear = tmp_time[1].strip()\nhour = tmp_time[2].strip().split(':')[0]\nminute = tmp_time[2].strip().split(':')[1][0:2]\nper = tmp_time[2].strip().split(':')[1][2:4]\n\n#turns hour into 24 hour notation\nif per == 'PM':\n hour = str(int(hour) + 12)\n\n#converts to python time format\ndatetime = time.strptime(\"{0} {1} {2} {3} {4}\".format(day, mon, year, hour, minute), \"%d %b %Y %H %M\")\n\n#pulls out time into different variables\nd_mon = str(datetime.tm_mon).zfill(2)\nd_day = str(datetime.tm_mday).zfill(2)\nd_year = datetime.tm_year\nd_hour = str(datetime.tm_hour).zfill(2)\nd_min = str(datetime.tm_min).zfill(2)\n\n#creates the time output\nout_time = \"{0}-{1}-{2} {3}:{4}\".format(d_year, d_mon, d_day, d_hour, d_min)\n\n#prints price and time\nprint(contract + \": \" + price +\" \"+ out_time)\n\n","sub_path":"web_parser.py","file_name":"web_parser.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"74994093","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nimport requests\n\nfrom .tab import Tab\n\n\n__all__ = [\"Browser\"]\n\n\nclass Browser(object):\n _all_tabs = {}\n\n def __init__(self, url=\"http://127.0.0.1:9222\"):\n self.dev_url = url\n\n if self.dev_url not in self._all_tabs:\n self._tabs = self._all_tabs[self.dev_url] = {}\n else:\n self._tabs = self._all_tabs[self.dev_url]\n rp = requests.get(\"%s/json/version\" % self.dev_url)\n version_data = rp.json()\n self.websocket_url = version_data['webSocketDebuggerUrl']\n self._connection = None # type: Tab\n\n @property\n def connection(self):\n \"\"\"\n The main websocket connection to the remote browser.\n If a connection is not active it will be created.\n\n :rtype: Tab\n \"\"\"\n if self._connection is None:\n self._connection = Tab(\n id='browser', type='browser', webSocketDebuggerUrl=self.websocket_url)\n self._connection.start()\n return self._connection\n\n @connection.deleter\n def connection(self):\n if self._connection is not None:\n self._connection.stop()\n self._connection = None\n\n def new_tab(self, url=None, timeout=None):\n url = url or ''\n rp = requests.get(\"%s/json/new?%s\" % (self.dev_url, url), json=True, timeout=timeout)\n tab = Tab(**rp.json())\n self._tabs[tab.id] = tab\n return tab\n\n def new_context_tab(self, url=None, timeout=None, browser_context=None):\n \"\"\"\n Create a new tab in a new browser context. This tab will then have it's own\n cookies, storage etc. The Tab will have the 'browser_context' property set\n\n :param url: Url to start new tab with\n :param timeout: How long to wait for a response from the remote browser\n :param browser_context: If supplide reuses existing browser context to create tab\n :return: The Tab object for the new context\n :rtype: Tab\n \"\"\"\n url = url or 'about:blank'\n connection = self.connection\n if not browser_context:\n context = connection.Target.createBrowserContext()\n browser_context = context['browserContextId']\n target = connection.Target.createTarget(\n url=url, browserContextId=browser_context)\n self.list_tab(timeout=timeout)\n if target['targetId'] in self._tabs:\n tab = self._tabs[target['targetId']]\n tab.browser_context = browser_context\n else:\n raise KeyError(\"Failed to find tab with target ID: {}\".format(target['targetId']))\n return tab\n\n def list_tab(self, timeout=None):\n rp = requests.get(\"%s/json\" % self.dev_url, json=True, timeout=timeout)\n tabs_map = {}\n for tab_json in rp.json():\n if tab_json['type'] != 'page': # pragma: no cover\n continue\n\n if tab_json['id'] in self._tabs and self._tabs[tab_json['id']].status != Tab.status_stopped:\n tabs_map[tab_json['id']] = self._tabs[tab_json['id']]\n else:\n tabs_map[tab_json['id']] = Tab(**tab_json)\n\n self._tabs = tabs_map\n return list(self._tabs.values())\n\n def activate_tab(self, tab_id, timeout=None):\n if isinstance(tab_id, Tab):\n tab_id = tab_id.id\n\n rp = requests.get(\"%s/json/activate/%s\" % (self.dev_url, tab_id), timeout=timeout)\n return rp.text\n\n def close_tab(self, tab_id, timeout=None):\n if isinstance(tab_id, Tab):\n tab_id = tab_id.id\n\n tab = self._tabs.pop(tab_id, None)\n if tab and tab.status == Tab.status_started: # pragma: no cover\n tab.stop()\n\n rp = requests.get(\"%s/json/close/%s\" % (self.dev_url, tab_id), timeout=timeout)\n return rp.text\n\n def version(self, timeout=None):\n rp = requests.get(\"%s/json/version\" % self.dev_url, json=True, timeout=timeout)\n return rp.json()\n\n def __str__(self):\n return '' % self.dev_url\n\n __repr__ = __str__\n","sub_path":"pychrome/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":4133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"279492151","text":"\n# coding: utf-8\n\n# # Iterating and concatenating all matches\n\n# In[1]:\n\nimport pandas as pd\n\n\n# In[2]:\n\nimport glob\n\n\n# In[3]:\n\npwd\n\n\n# In[4]:\n\nsearch_pattern = 'Datasets/132719078_T_T100D_MARKET_US_CARRIER_ONLY_????.csv'\n\n\n# In[5]:\n\ncsv_files = glob.glob(search_pattern)\n\n\n# In[6]:\n\ncsv_files\n\n\n# In[9]:\n\nframes = []\n\n\n# In[10]:\n\nfor csv in csv_files:\n df = pd.read_csv(csv, low_memory=False)\n frames.append(df)\n\n\n# In[11]:\n\n# frames\n\n\n# In[12]:\n\non_time_data = pd.concat(frames)\n\n\n# In[13]:\n\non_time_data.shape\n\n\n# In[14]:\n\non_time_data.dtypes\n\n\n# In[15]:\n\non_time_data.info()\n\n\n# In[ ]:\n\n\n\n","sub_path":"python/Iterating_and_concatenating_all_matches.py","file_name":"Iterating_and_concatenating_all_matches.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"618218335","text":"from django.core.mail import EmailMultiAlternatives\n\ndef make_random_string(length=10,\n allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):\n import random\n try:\n random = random.SystemRandom()\n except NotImplementedError:\n pass\n return ''.join([random.choice(allowed_chars) for i in range(length)])\n\n\nclass lazy_string(object):\n \"\"\"This is a function that allows other functions\n to be lazy when they are read\"\"\"\n def __init__(self, function, *args, **kwargs):\n self.function = function\n self.args = args\n self.kwargs = kwargs\n\n def __str__(self):\n if not hasattr(self, 'str'):\n self.str = self.function(*self.args, **self.kwargs)\n return self.str\n\n\ndef reverse_lazy(*args, **kwargs):\n \"\"\"Lazy version of reverse using lazy_string above\"\"\"\n from django.core.urlresolvers import reverse\n return lazy_string(reverse, *args, **kwargs)\n\ndef send_email(subject, plaintext_content, to_email, html_content):\n msg = EmailMultiAlternatives(subject, plaintext_content, 'flightspyer@gmail.com', [to_email])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n \n","sub_path":"flightspyer/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"323087170","text":"\"\"\"\ntracking job\n\"\"\"\nimport logging\nimport base64\nimport datetime\nimport time\nimport random\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom patch_tracking.util.gitee_api import create_branch, upload_patch, create_gitee_issue\nfrom patch_tracking.util.gitee_api import create_pull_request, get_path_content, upload_spec, create_spec\nfrom patch_tracking.database.models import Tracking\nfrom patch_tracking.api.business import update_tracking, create_issue\nfrom patch_tracking.task import scheduler\nfrom patch_tracking.util.spec import Spec\nfrom patch_tracking.util.upstream import Factory\n\nlogger = logging.getLogger(__name__)\n\n\ndef upload_patch_to_gitee(track):\n \"\"\"\n upload a patch file to Gitee\n \"\"\"\n cur_time = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n with scheduler.app.app_context():\n logger.info('[Patch Tracking %s] track.scm_commit_id: %s.', cur_time, track.scm_commit)\n git_api = Factory.create(track)\n patch = get_scm_patch(track, git_api)\n if patch:\n issue = create_patch_issue_pr(patch, cur_time, git_api)\n if issue:\n create_issue_db(issue)\n else:\n logger.info('[Patch Tracking %s] No issue need to create.', cur_time)\n else:\n logger.debug('[Patch Tracking %s] No new commit.', cur_time)\n\n\ndef get_scm_patch(track, git_api):\n \"\"\"\n Traverse the Tracking data table to get the patch file of enabled warehouse.\n Different warehouse has different acquisition methods\n :return:\n \"\"\"\n scm_dict = dict(\n scm_repo=track.scm_repo,\n scm_branch=track.scm_branch,\n scm_commit=track.scm_commit,\n enabled=track.enabled,\n repo=track.repo,\n branch=track.branch,\n version_control=track.version_control\n )\n\n commit_list = git_api.get_scm_patch()\n if commit_list:\n scm_dict['commit_list'] = commit_list\n return scm_dict\n logger.info('repo: %s branch: %s. get_latest_commit is None.', scm_dict['scm_repo'], scm_dict['scm_branch'])\n\n return None\n\n\ndef create_patch_issue_pr(patch, cur_time, git_api):\n \"\"\"\n Create temporary branches, submit files, and create PR and issue\n :return:\n \"\"\"\n issue_dict = dict()\n gitee_repo = patch[\"repo\"].replace(\"https://gitee.com/\", \"\")\n issue_dict['repo'] = patch['repo']\n issue_dict['branch'] = patch['branch']\n new_branch = 'patch-tracking/' + cur_time\n result = create_branch(gitee_repo, patch['branch'], new_branch)\n if result == 'success':\n logger.info('[Patch Tracking %s] Successful create branch: %s', cur_time, new_branch)\n else:\n logger.error('[Patch Tracking %s] Fail to create branch: %s', cur_time, new_branch)\n return None\n patch_lst = list()\n for latest_commit in patch['commit_list']:\n scm_commit_url = '/'.join(['https://github.com', patch['scm_repo'], 'commit', latest_commit['commit_id']])\n latest_commit['message'] = latest_commit['message'].replace(\"\\r\", \"\").replace(\"\\n\", \"
\")\n\n patch_file_content = latest_commit['patch_content']\n post_data = {\n 'repo': gitee_repo,\n 'branch': new_branch,\n 'latest_commit_id': latest_commit['commit_id'],\n 'patch_file_content': str(patch_file_content),\n 'cur_time': cur_time,\n 'commit_url': scm_commit_url\n }\n result = upload_patch(post_data)\n if result == 'success':\n logger.info(\n '[Patch Tracking %s] Successfully upload patch file of commit: %s', cur_time, latest_commit['commit_id']\n )\n else:\n logger.error(\n '[Patch Tracking %s] Fail to upload patch file of commit: %s', cur_time, latest_commit['commit_id']\n )\n return None\n patch_lst.append(str(latest_commit['commit_id']))\n\n result = upload_spec_to_repo(patch, patch_lst, cur_time)\n if result == \"success\":\n logger.info('[Patch Tracking %s] Successfully upload spec file.', cur_time)\n else:\n logger.error('[Patch Tracking %s] Fail to upload spec file. Result: %s', cur_time, result)\n return None\n\n issue_table = git_api.issue_table(patch['commit_list'])\n logger.debug(issue_table)\n result = create_gitee_issue(gitee_repo, patch['branch'], issue_table, cur_time)\n if result[0] == 'success':\n issue_num = result[1]\n logger.info('[Patch Tracking %s] Successfully create issue: %s', cur_time, issue_num)\n\n retry_count = 10\n while retry_count > 0:\n ret = create_pull_request(gitee_repo, patch['branch'], new_branch, issue_num, cur_time)\n if ret == 'success':\n logger.info('[Patch Tracking %s] Successfully create PR of issue: %s.', cur_time, issue_num)\n break\n logger.warning('[Patch Tracking %s] Fail to create PR of issue: %s. Result: %s', cur_time, issue_num, ret)\n retry_count -= 1\n time.sleep(random.random() * 5)\n if retry_count == 0:\n logger.error('[Patch Tracking %s] Fail to create PR of issue: %s.', cur_time, issue_num)\n return None\n\n issue_dict['issue'] = issue_num\n\n data = {\n 'version_control': patch['version_control'],\n 'repo': patch['repo'],\n 'branch': patch['branch'],\n 'enabled': patch['enabled'],\n 'scm_commit': patch['commit_list'][-1]['commit_id'],\n 'scm_branch': patch['scm_branch'],\n 'scm_repo': patch['scm_repo']\n }\n try:\n update_tracking(data)\n except SQLAlchemyError as err:\n logger.error('[Patch Tracking %s] Fail to update tracking: %s. Result: %s', cur_time, data, err)\n else:\n logger.error('[Patch Tracking %s] Fail to create issue: %s. Result: %s', cur_time, issue_table, result[1])\n return None\n\n return issue_dict\n\n\ndef upload_spec_to_repo(patch, patch_lst, cur_time):\n \"\"\"\n update and upload spec file\n \"\"\"\n new_branch = 'patch-tracking/' + cur_time\n gitee_repo = patch[\"repo\"].replace(\"https://gitee.com/\", \"\")\n _, repo_name = gitee_repo.split('/')\n spec_file = repo_name + '.spec'\n\n patch_file_lst = [patch + '.patch' for patch in patch_lst]\n\n log_title = \"{} patch-tracking\".format(datetime.datetime.now().strftime(\"%a %b %d %Y\"))\n log_content = \"append patch file of upstream repository from <{}> to <{}>\".format(patch_lst[0], patch_lst[-1])\n\n ret = get_path_content(gitee_repo, patch['branch'], spec_file)\n if 'content' in ret:\n spec_content = str(base64.b64decode(ret['content']), encoding='utf-8')\n spec_sha = ret['sha']\n new_spec = modify_spec(log_title, log_content, patch_file_lst, spec_content)\n result = update_spec_to_repo(gitee_repo, new_branch, cur_time, new_spec, spec_sha)\n else:\n spec_content = ''\n new_spec = modify_spec(log_title, log_content, patch_file_lst, spec_content)\n result = create_spec_to_repo(gitee_repo, new_branch, cur_time, new_spec)\n\n return result\n\n\ndef modify_spec(log_title, log_content, patch_file_lst, spec_content):\n \"\"\"\n modify spec file\n \"\"\"\n spec = Spec(spec_content)\n return spec.update(log_title, log_content, patch_file_lst)\n\n\ndef update_spec_to_repo(repo, branch, cur_time, spec_content, spec_sha):\n \"\"\"\n update spec file\n \"\"\"\n ret = upload_spec(repo, branch, cur_time, spec_content, spec_sha)\n if ret == 'success':\n logger.info('[Patch Tracking %s] Successfully update spec file.', cur_time)\n else:\n logger.error('[Patch Tracking %s] Fail to update spec file. Result: %s', cur_time, ret)\n\n return ret\n\n\ndef create_spec_to_repo(repo, branch, cur_time, spec_content):\n \"\"\"\n create new spec file\n \"\"\"\n ret = create_spec(repo, branch, spec_content, cur_time)\n if ret == 'success':\n logger.info('[Patch Tracking %s] Successfully create spec file.', cur_time)\n else:\n logger.error('[Patch Tracking %s] Fail to create spec file. Result: %s', cur_time, ret)\n\n return ret\n\n\ndef create_issue_db(issue):\n \"\"\"\n create issue into database\n \"\"\"\n issue_num = issue['issue']\n tracking = Tracking.query.filter_by(repo=issue['repo'], branch=issue['branch']).first()\n tracking_repo = tracking.repo\n tracking_branch = tracking.branch\n data = {'issue': issue_num, 'repo': tracking_repo, 'branch': tracking_branch}\n logger.debug('issue data: %s', data)\n create_issue(data)\n","sub_path":"patch_tracking/task/task_apscheduler.py","file_name":"task_apscheduler.py","file_ext":"py","file_size_in_byte":8522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"415180187","text":"#!/usr/bin/env python3\n\nimport argparse\nfrom collections import Counter\nimport gzip\nimport re\nimport sys\nimport xml.etree.ElementTree as ElementTree\n\nSIG_STARS = {\n 'practice guideline': 4,\n 'reviewed by expert panel': 3,\n 'criteria provided, multiple submitters, no conflicts': 2,\n 'criteria provided, conflicting interpretations': 1,\n 'criteria provided, single submitter': 1,\n}\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--clinvar-xml', required=True)\nargs = parser.parse_args()\n\n\ndef add_transitions(transitions_counter, transition_chain):\n \"\"\"Increments the count of a particular flow in Sankey diagram.\"\"\"\n for transition_from, transition_to in zip(transition_chain, transition_chain[1:]):\n transitions_counter[(transition_from, transition_to)] += 1\n\n\ndef find_attribute(rcv, xpath, attribute_name):\n \"\"\"Find an attribute in the RCV record which can have either zero or one occurrence. Return a textual representation\n of the attribute, including special representations for the case of zero or multiple, constructed using the\n attribute_name parameter.\"\"\"\n\n attributes = rcv.findall(xpath)\n if len(attributes) == 0:\n return '{} missing'.format(attribute_name)\n elif len(attributes) == 1:\n return attributes[0].text\n else:\n return '{} multiple'.format(attribute_name)\n\n\ndef review_status_stars(review_status):\n black_stars = SIG_STARS.get(review_status, 0)\n white_stars = 4 - black_stars\n return '★' * black_stars + '☆' * white_stars\n\n\n# The dicts store transition counts for the Sankey diagrams. Keys are (from, to), values are transition counts.\n# Sankey diagrams can be visualised with SankeyMatic (see http://www.sankeymatic.com/build/).\nvariant_type_transitions, clin_sig_transitions, review_status_transitions, inheritance_mode_transitions,\\\n allele_origin_transitions = Counter(), Counter(), Counter(), Counter(), Counter()\nall_clinical_significance_levels = set()\n\n\n# ClinVar XML have the following top-level structure:\n# \n# ...\n# ...\n# ...\n# \n# To not load everything into memory, we use iterparse, wait for a complete ClinVarSet element, and then remove it from\n# the tree because we don't need it anymore.\n\nelements_processed = 0\nfor event, elem in ElementTree.iterparse(gzip.open(args.clinvar_xml)):\n\n # Wait until we have built a complete ClinVarSet element. Skip\n if elem.tag != 'ClinVarSet':\n continue\n\n # Go to a ReferenceClinVarAssertion element. This corresponds to a single RCV record, the main unit of ClinVar.\n # There should only be one such record per ClinVarSet.\n rcv_records = elem.findall('ReferenceClinVarAssertion')\n assert len(rcv_records) == 1, 'Found multiple RCV records per ClinVarSet'\n rcv = rcv_records[0]\n rcv_id = 'RCV{:09}'.format(int(rcv.attrib['ID']))\n\n # RCV can contain either a MeasureSet, or a GenotypeSet. It must not contain both.\n measure_sets = rcv.findall('MeasureSet')\n genotype_sets = rcv.findall('GenotypeSet')\n if len(measure_sets) == 1 and len(genotype_sets) == 0:\n # Most common case. RCV directly contains one measure set.\n measure_set = measure_sets[0]\n measure_set_type = measure_set.attrib['Type']\n add_transitions(variant_type_transitions, ('RCV', 'MeasureSet', measure_set_type))\n\n if measure_set_type == 'Variant':\n # Most common case, accounting for >99.95% of all ClinVar records.. Here, we go into details on various\n # attribute distributions.\n\n # Variant type\n measures = measure_set.findall('Measure')\n assert len(measures) == 1, 'MeasureSet of type Variant must contain exactly one Measure'\n add_transitions(variant_type_transitions, (measure_set_type, measures[0].attrib['Type']))\n\n # Clinical significance\n clinical_significance = find_attribute(\n rcv, 'ClinicalSignificance/Description', 'ClinicalSignificance')\n all_clinical_significance_levels.add(clinical_significance)\n significance_type = 'Complex' if re.search('[,/]', clinical_significance) else 'Simple'\n add_transitions(clin_sig_transitions, (\n 'Variant',\n significance_type,\n clinical_significance,\n ))\n\n # Review status\n review_status = find_attribute(\n rcv, 'ClinicalSignificance/ReviewStatus', 'ReviewStatus')\n add_transitions(review_status_transitions, (\n 'Variant',\n review_status_stars(review_status),\n review_status,\n ))\n\n # Mode of inheritance\n mode_of_inheritance_xpath = 'AttributeSet/Attribute[@Type=\"ModeOfInheritance\"]'\n mode_of_inheritance = find_attribute(rcv, mode_of_inheritance_xpath, 'ModeOfInheritance')\n if mode_of_inheritance.endswith('multiple'):\n # Having multiple ModeOfInheritance is rare. Log them for further investigation\n all_modes = '|'.join(sorted(mode.text for mode in rcv.findall(mode_of_inheritance_xpath)))\n print(f'Multiple ModeOfInheritance\\t{rcv_id}\\t{all_modes}')\n add_transitions(inheritance_mode_transitions, (\n 'Variant',\n mode_of_inheritance if mode_of_inheritance.endswith('missing') else 'ModeOfInheritance present',\n ))\n if not mode_of_inheritance.endswith('missing'):\n add_transitions(inheritance_mode_transitions, (\n 'ModeOfInheritance present', mode_of_inheritance\n ))\n elif len(measure_sets) == 0 and len(genotype_sets) == 1:\n # RCV directly contains one genotype set.\n genotype_set = genotype_sets[0]\n add_transitions(variant_type_transitions, ('RCV', 'GenotypeSet', genotype_set.attrib['Type']))\n else:\n raise AssertionError('RCV must contain either exactly one measure set, or exactly one genotype set')\n\n allele_origins = {origin.text for origin in rcv.findall('ObservedIn/Sample/Origin')}\n if len(allele_origins) == 0:\n add_transitions(allele_origin_transitions, ('RCV', 'No allele origin'))\n else:\n allele_origins_count = 'Single allele origin' if len(allele_origins) == 1 else 'Multiple allele origins'\n allele_origins_text = ','.join(sorted(allele_origins))\n add_transitions(allele_origin_transitions, ('RCV', allele_origins_count, allele_origins_text))\n\n # Remove the processed element from the tree to save memory\n elem.clear()\n\n # Track the number of already processed elements\n elements_processed += 1\n if elements_processed % 10000 == 0:\n print('Processed {} elements'.format(elements_processed), file=sys.stderr)\n\n# Output the code for Sankey diagram. Transitions are sorted in decreasing number of counts, so that the most frequent\n# cases are on top.\nfor transitions_counter in (variant_type_transitions, clin_sig_transitions, review_status_transitions,\n inheritance_mode_transitions, allele_origin_transitions):\n print()\n for (transition_from, transition_to), count in sorted(transitions_counter.items(), key=lambda x: -x[1]):\n print('{transition_from} [{count}] {transition_to}'.format(**locals()))\n\nprint('\\n\\nAll clinical significance levels:')\nfor clin_sig in sorted(all_clinical_significance_levels):\n print(clin_sig)\n","sub_path":"clinvar-variant-types/clinvar-variant-types.py","file_name":"clinvar-variant-types.py","file_ext":"py","file_size_in_byte":7531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"205550789","text":"import googlemaps\nfrom datetime import datetime\nimport json\n#Will get API key when needed.\ngmaps = googlemaps.Client(key='')\n# Geocoding an address\ngeocode_result = gmaps.geocode('476 5th Ave, New York, NY 10018')\nlocation = geocode_result[0]['geometry']['location']\n\nplace_details = gmaps.places(query = '', location = location, radius = 1, type = 'restaurant')\n\nresults = []\nfor i in range(len(place_details['results'])):\n helper = gmaps.distance_matrix(location, place_details['results'][i]['geometry']['location'])\n try:\n result = ((-.5 * place_details['results'][i]['price_level']) + place_details['results'][i]['rating'])/(float(helper['rows'][0]['elements'][0]['distance']['text'].split(' ')[0]))\n results.append((place_details['results'][i]['name'], result))\n except:\n results.append((place_details['results'][i]['name'],0))\n\nprint(results)\n# Look up an address with reverse geocoding\nreverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452))\n\n# Request directions via public transit\nnow = datetime.now()\ndirections_result = gmaps.directions(\"Sydney Town Hall\",\n \"Parramatta, NSW\",\n mode=\"transit\",\n departure_time=now)\n\nprint(\"test\")\n","sub_path":"Intersections_Project.py","file_name":"Intersections_Project.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"360622397","text":"import time\nfrom naoqi import ALProxy\nfrom math import radians\n\ndef move_head(headxpos, headypos, im_width, im_height, IP, motionProxy):\n \"\"\"INFINITE MAGIC NUMBERS INCOMING.\"\"\"\n width = im_width\n height = im_height\n # for yaw:\n # 640 = pixel width using kVGA\n # camera angle is 60.97\n # 1 degree = 10.49 pixel difference\n # for pitch:\n # 480 = pixel heigth using kVGA\n # angle is 47.64\n # 1 degree = 10.075 pixel diff\n # Yaw is turning , left is positive, right is negative.\n\n # get current angles of the head\n currentAngle = motionProxy.getAngles(\"HeadYaw\", True)[0]\n # MOVE HEAD LEFT\n if headxpos < (width/2 - 5):\n pdiff = abs((width/2 - 5) - headxpos)\n turn = radians(pdiff / 10.49)\n speed = abs(0.6 * turn*2)\n if speed > 0.8:\n speed = 0.8\n if speed < 0.2:\n speed = 0.2\n if currentAngle < 1.95:\n motionProxy.setAngles(\"HeadYaw\", currentAngle + turn, speed)\n\n # MOVE HEAD RIGHT\n if headxpos > (width/2 + 5):\n pdiff = abs((width/2 + 5) - headxpos)\n turn = radians(pdiff / 10.49)\n speed = abs(0.6 * turn*2)\n if speed > 0.8:\n speed = 0.8\n if speed < 0.2:\n speed = 0.2\n if currentAngle > -1.95:\n motionProxy.setAngles(\"HeadYaw\", currentAngle - turn, speed)\n\n # MOVE HEAD UP\n currentAngle = motionProxy.getAngles(\"HeadPitch\", True)[0]\n if headypos > (height/2 - 5):\n pdiff = abs((height/2 - 5) - headypos)\n turn = radians(pdiff / 10.075)\n speed = abs(0.6 * turn*2)\n if speed > 0.8:\n speed = 0.8\n if speed < 0.2:\n speed = 0.2\n if currentAngle < 0.51:\n motionProxy.setAngles(\"HeadPitch\", currentAngle + turn, speed)\n\n # MOVE HEAD DOWN\n if headypos < (height/2 + 5):\n pdiff = abs((height/2 - 5) - headypos)\n turn = radians(pdiff / 10.075)\n speed = abs(0.6 * turn*2)\n if speed > 0.8:\n speed = 0.8\n if speed < 0.2:\n speed = 0.2\n if currentAngle > -0.65:\n motionProxy.setAngles(\"HeadPitch\", currentAngle - turn, speed)\n\n StiffnessOn(motionProxy)\n motionProxy.stiffnessInterpolation(\"Head\", 0.0, 0.5)\n motionProxy.stopMove()\n\ndef StiffnessOn(proxy):\n # We use the \"Body\" name to signify the collection of all joints\n pNames = \"Head\"\n pStiffnessLists = 1.0\n pTimeLists = 1.0\n proxy.stiffnessInterpolation(pNames, pStiffnessLists, pTimeLists)\n\ndef stiffnessOff(proxy):\n pNames = \"Body\"\n pStiffnessLists = 0.0\n pTimeLists = 1.0\n proxy.stiffnessInterpolation(pNames, pStiffnessLists, pTimeLists)\n# shut down Nao\n","sub_path":"media_conversation/headmotions.py","file_name":"headmotions.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"152591079","text":"from character import character\nfrom copy import deepcopy\nobjectThatCanKill = [\"stone\", \"sword\", \"stick\"]\nfrom random import randint\n\nclass badCharacter(character):\n def __init__(self, name, state):\n self.killMeObjects = []\n character.__init__(self, name, state)\n\n def nameCreator(self):\n nameArray = ['Norman', 'Paula', 'Devin', 'Heather', 'Taylor', 'Regina', 'Regina', 'Dylan']\n randomName = randint(0,7)\n self.nickname = nameArray[randomName]\n print(self.nickname)\n\n def canKillMe(self, objectsInGame):\n for i in objectsInGame:\n if i in objectThatCanKill:\n self.killMeObjects.append(i)\n\n def copyCharacter(self, copyFrom):\n newCharacter = badCharacter(copyFrom.name, copyFrom.state)\n newCharacter.bag = deepcopy(copyFrom.bag)\n newCharacter.location = deepcopy(copyFrom.location)\n newCharacter.killMeObjects = deepcopy(copyFrom.killMeObjects)\n newCharacter.nickname = deepcopy(copyFrom.nickname)\n return newCharacter\n\n def calcPoints(self, hero, good, currLocation):\n totalScore = 0\n if (hero.state == 2):\n totalScore += 20\n if (self.location == \"east river\"):\n totalScore += 6\n if (len(self.bag) >= 1):\n totalScore += 4\n if (self.location == \"castle\"):\n totalScore += 12\n if (good.state == 2):\n totalScore += 5\n for i in currLocation.whoIsHere:\n if (hero.name == i.name and hero.state !=2):\n totalScore -= 8\n return totalScore\n","sub_path":"badCharacter.py","file_name":"badCharacter.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"393404226","text":" # -*- coding: utf-8 -*-\nimport os\nimport hashlib\nimport datetime\nimport requests\nfrom flask import Flask\nfrom flask import render_template,jsonify,request,abort,url_for\nfrom werkzeug import secure_filename\nfrom PIL import Image\nfrom StringIO import StringIO\n\nUPLOAD_FOLDER = '/var/www/sr/env/app/static/uploads/'\n# UPLOAD_FOLDER = './static/uploads/'\nALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'md'])\n\napp = Flask(__name__)\n#app.debug = True\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 3 * 1024 * 1024\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS\n\n\ndef generate_filename(filename):\n\tnow_time = datetime.datetime.now()\n\tfilename_secure = secure_filename(filename)\n\tfilename_name, filename_type = filename_secure.rsplit('.', 1)\n\tfilename_after_hash = hashlib.sha256(filename + str(now_time)).hexdigest() + '.' + filename_type\t\n\treturn filename_after_hash\n\n@app.route('/')\ndef index(title = None):\n\ttitle = \"index\"\n\treturn render_template('index.html', title = title)\n\n@app.route('/about')\ndef about():\n\treturn render_template('about.html')\n\n@app.route('/demo',methods=['GET'])\ndef demo():\n\treturn render_template('demo.html')\n\n@app.route('/demo',methods=['POST'])\ndef upload():\n\tfile = request.files['img']\n\tif file and allowed_file(file.filename):\n\t\tfilename = generate_filename(file.filename)\n\t\tfilepath = app.config['UPLOAD_FOLDER']+filename\n\t\tfile.save(filepath)\n\t\tos.system('RUN YOUR LINUX INSTRCTION FOR PYTHON/MATLAB SCRIPTS')\n\t\t\n\t\treturn jsonify({\"status\":\"ok\",\n\t\t\t\t\t\t\"img_old_url\":url_for('static', filename='uploads/'+ filename),\n\t\t\t\t\t\t\"img_new_url\":url_for('static', filename='uploads/'+ filename + '.sr.png')\n\t\t\t\t\t\t})\n\telse:\n\t\treturn jsonify({\"status\":\"error\",\"message\":\"not vailid img type\"}),400\n\n\n@app.route('/contact')\ndef contact():\n\treturn render_template('contact.html')\n\n\nif __name__ == '__main__':\n app.run(host = '0.0.0.0')\n","sub_path":"homepage/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"612911810","text":"from common import *\n\nimport os\nfrom scipy.sparse import csr_matrix\nimport itertools\n\n\ndef _as_list(x):\n return x if type(x) == list else [x]\n\ndef _strip(df,columns):\n for c in _as_list(columns):\n df.loc[:,c] = df[c].str.strip()\n return df\n\ndef _lower(df,columns):\n for c in _as_list(columns):\n df.loc[:,c] = df[c].str.lower()\n return df\n\ndef category(type):\n if 'Homicide' in type or 'Fatality' in type:\n return 1\n else:\n return -1 \n\ndef time_category(x, type):\n x = x.split(':')\n if type == 'hour':\n return x[0]\n elif type == 'minute':\n return x[1]\n \ndef pack():\n df = pd.read_csv(\"../raw_data/crime.csv\")\n df = df.dropna(subset = ['YEAR', 'MONTH', 'DAY', 'HOUR', 'MINUTE'])\n df['DATE'] = df.YEAR.astype('str').map(str) + '/' + df.MONTH.astype('str') + '/' +df.DAY.astype('str') + ' ' + df.HOUR.astype('str') + ':' + df.MINUTE.astype('str')\n df.DATE = df.DATE.apply(pd.to_datetime).dt.date\n df['TIME'] = df.HOUR.astype('int64').astype('str') + ':' + df.MINUTE.astype('int64').astype('str')\n df['TIME_HOUR'] = df.TIME.map(lambda x: time_category(x, 'hour'))\n df['TIME_MINUTE'] = df.TIME.map(lambda x: time_category(x, 'minute'))\n df = df.dropna(subset = ['NEIGHBOURHOOD'])\n df.TYPE = df.TYPE.astype('str')\n df.NEIGHBOURHOOD = df.NEIGHBOURHOOD.astype('str')\n df['DAY_OF_WEEK'] = pd.DatetimeIndex(df['DATE']).dayofweek\n df['CLASSIFICATION'] = df.TYPE.apply(category)\n df = df.rename(columns = {'DAY': 'DAY_OF_MONTH'})\n df = df.drop(labels=['DATE','HOUR', 'MINUTE', 'HUNDRED_BLOCK', 'X', 'Y', 'TYPE', 'TIME'], axis = 1)\n class1 = df[df.CLASSIFICATION == 1]\n class2 = df[df.CLASSIFICATION == -1]\n class2 = class2.sample(49526)\n df = pd.concat([class1, class2])\n df.to_csv('../raw_data/crime_processed.csv', index_label = False)\n print ('\\n DONE \\n --x--')\nif __name__ == \"__main__\":\n pack()\n","sub_path":"517a_crime_vancouver/code/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"597400919","text":"\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport cv2\nimport numpy as np\nimport imutils\nfrom sklearn.metrics import pairwise\n \nimport webbrowser\n\n\n\ndef segment(image, threshold=20):\n global back_ground\n diff = cv2.absdiff(back_ground.astype(\"uint8\"), image)\n\n thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1]\n\n (contours, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n if len(contours) == 0:\n return\n else:\n segmented = max(contours, key=cv2.contourArea)\n return (thresholded, segmented)\n\ndef run_avg(image, aWeight):\n global back_ground\n if back_ground is None:\n back_ground = image.copy().astype(\"float\")\n return\n\n cv2.accumulateWeighted(image, back_ground, aWeight)\n\ndef count(thresholded, segmented):\n chull = cv2.convexHull(segmented)\n\n extreme_top = tuple(chull[chull[:, :, 1].argmin()][0])\n extreme_bottom = tuple(chull[chull[:, :, 1].argmax()][0])\n extreme_left = tuple(chull[chull[:, :, 0].argmin()][0])\n extreme_right = tuple(chull[chull[:, :, 0].argmax()][0])\n\n cX = int((extreme_left[0] + extreme_right[0]) / 2)\n cY = int((extreme_top[1] + extreme_bottom[1]) / 2)\n\n distance = pairwise.euclidean_distances([(cX, cY)], Y=[extreme_left, extreme_right, extreme_top, extreme_bottom])[0]\n maximum_distance = distance[distance.argmax()]\n\n radius = int(0.75 * maximum_distance)\n\n circumference = (2 * np.pi * radius)\n\n circular_roi = np.zeros(thresholded.shape[:2], dtype=\"uint8\")\n\n cv2.circle(circular_roi, (cX, cY), radius, 255, 1)\n\n circular_roi = cv2.bitwise_and(thresholded, thresholded, mask=circular_roi)\n\n (contours, _) = cv2.findContours(circular_roi.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n\n count = 0\n\n for c in contours:\n (x, y, w, h) = cv2.boundingRect(c)\n\n if ((cY + (cY * 0.25)) > (y + h)) and ((circumference * 0.25) > c.shape[0]):\n count += 1\n\n return min(count, 5), cX, cY, radius\n\n\nflag = 0\n\naWeight = 0.5\ncap = cv2.VideoCapture(0)\n\ntop, right, bottom, left = 0, 650, 500, 1000\n\nnumber_of_frames = 0\nback_ground = None\nwhile True:\n try:\n check, frame = cap.read()\n frame = imutils.resize(frame, width=1000)\n\n frame = cv2.flip(frame, 1)\n\n frame_clone = frame.copy()\n\n (height, width) = frame.shape[:2]\n\n roi = frame[top:bottom, right:left]\n\n gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (7, 7), 0)\n \n\n\n if number_of_frames < 39:\n run_avg(gray, aWeight)\n else:\n hand = segment(gray)\n\n if hand is not None:\n (thresholded, segmented) = hand\n\n cv2.drawContours(frame_clone, [segmented + (right, top)], -1, (110, 2, 76))\n\n fingers, cX, cY, radius = count(thresholded, segmented)\n\n cv2.putText(frame_clone, str(fingers), (700, 600), cv2.FONT_HERSHEY_SIMPLEX, 1, (110, 2, 76), 5)\n \n cv2.circle(thresholded, (cX, cY), radius, 255, 1)\n\n cv2.imshow(\"Thesholded\", thresholded)\n\n if fingers == 5:\n img = cv2.imread(\"/home/msd/Desktop/msd.jpg\")\n cv2.namedWindow(\"Image\")\n cv2.resizeWindow(\"Image\", 1000, 1000)\n cv2.imshow(\"Image\", img)\n\n elif fingers == 1:\n cv2.destroyWindow(\"Image\")\n \n \n elif fingers == 2:\n webbrowser.open('http://google.com', new=2)\n \n elif fingers == 3:\n flag = 1\n break\n \n \n\n cv2.rectangle(frame_clone, (left, top), (right, bottom), (245, 87, 66), 10)\n\n number_of_frames += 1\n if number_of_frames == 40:\n print(\"Back Ground is Recognized, Ready!\")\n cv2.namedWindow(\"Window\")\n cv2.resizeWindow(\"Window\", 1000, 1000)\n cv2.imshow(\"Window\", frame_clone)\n \n key = cv2.waitKey(1)\n\n if key == ord('r'):\n num_frames = 0\n back_ground = None\n elif key == ord('q'):\n break\n except:\n pass\n\ncap.release()\ncv2.destroyAllWindows()\n\nif flag == 1:\n\n\n def nothing(x):\n pass\n\n\n\n cv2.namedWindow(\"Tracking\")\n cv2.createTrackbar(\"LH\",\"Tracking\", 0, 255, nothing)\n cv2.createTrackbar(\"LS\",\"Tracking\", 0, 255, nothing)\n cv2.createTrackbar(\"LV\",\"Tracking\", 0, 255, nothing)\n cv2.createTrackbar(\"UH\",\"Tracking\", 255, 255, nothing)\n cv2.createTrackbar(\"US\",\"Tracking\", 255, 255, nothing)\n cv2.createTrackbar(\"UV\",\"Tracking\", 255, 255, nothing)\n \n\n while True:\n frame = cv2.imread('/home/msd/smarties.png')\n \n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n \n l_h =cv2.getTrackbarPos(\"LH\", \"Tracking\")\n l_s =cv2.getTrackbarPos(\"LS\", \"Tracking\") \n l_v =cv2.getTrackbarPos(\"LV\", \"Tracking\") \n \n \n u_h =cv2.getTrackbarPos(\"UH\", \"Tracking\")\n u_s =cv2.getTrackbarPos(\"US\", \"Tracking\")\n u_v =cv2.getTrackbarPos(\"UV\", \"Tracking\")\n\n \n l_b = np.array([l_h, l_s , l_v])\n u_b = np.array([u_h, u_s, u_v])\n \n mask = cv2.inRange(hsv, l_b, u_b)\n res = cv2.bitwise_and(frame, frame, mask )\n \n cv2.imshow(\"frame\", frame)\n cv2.imshow(\"mask\", mask)\n cv2.imshow(\"res\", res)\n \n key = cv2.waitKey(1)\n if key ==27 :\n break\n \n\n cv2.destroyAllWindows()\n\n","sub_path":"HandGestureRecognition.py","file_name":"HandGestureRecognition.py","file_ext":"py","file_size_in_byte":5668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"556771175","text":"import time\nimport os\nimport argparse\nimport logging\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torchvision import datasets, transforms, utils\nfrom tensorboardX import SummaryWriter\nfrom utils_student import *\nfrom pixelcnnpp_utils import *\nfrom model_student import *\nfrom model_teacher import *\nfrom PIL import Image\n\nfrom collections import OrderedDict\n\n\n\nparser = argparse.ArgumentParser()\n# data I/O\nparser.add_argument('-i', '--data_dir', type=str,\n default='data', help='Location for the dataset')\nparser.add_argument('-o', '--save_dir', type=str, default='models',\n help='Location for parameter checkpoints and samples')\nparser.add_argument('-log', '--log_dir', type=str, default='logs',\n help='Location for run logs')\nparser.add_argument('-d', '--dataset', type=str,\n default='cifar', help='Can be either cifar|mnist|svhn')\nparser.add_argument('-p', '--print_every', type=int, default=100,\n help='how many iterations between print statements')\nparser.add_argument('-t', '--save_interval', type=int, default=1,\n help='Every how many epochs to write checkpoint/samples?')\nparser.add_argument('-ss', '--save_interval_student', type=int, default=2000,\n help='Every how many epochs to write student model checkpoint/samples?')\nparser.add_argument('-r', '--load_params', type=str, default=None,\n help='Restore training from previous model checkpoint?')\n# model\nparser.add_argument('-q', '--nr_resnet', type=int, default=5,\n help='Number of residual blocks per stage of the model')\nparser.add_argument('-qs', '--nr_resnet_s', type=int, default=5,\n help='Number of residual blocks per stage of the student model')\nparser.add_argument('-lb', '--nr_layer', type=int, default=2,\n help='Number of layers in each resnet block of the student model')\nparser.add_argument('-n', '--nr_filters', type=int, default=160,\n help='Number of filters to use across the model. Higher = larger model.')\nparser.add_argument('-m', '--nr_logistic_mix', type=int, default=10,\n help='Number of logistic components in the mixture. Higher = more flexible model')\nparser.add_argument('-l', '--lr', type=float,\n default=0.0002, help='Base learning rate')\nparser.add_argument('-e', '--lr_decay', type=float, default=0.999995,\n help='Learning rate decay, applied every step of the optimization')\nparser.add_argument('-lsreg', '--ls_reg', type=float, default=0.05,\n help='Regularization factor for L2 norm of difference in student and teacher log_scales')\nparser.add_argument('-creg', '--coeff_reg', type=float, default=0.05,\n help='Regularization factor for L2 norm of difference in student and teacher coeffs')\nparser.add_argument('-b', '--batch_size', type=int, default=8,\n help='Batch size during training per GPU')\nparser.add_argument('-x', '--max_epochs', type=int,\n default=50000, help='How many epochs to run in total?')\nparser.add_argument('-s', '--seed', type=int, default=1,\n help='Random seed to use')\nargs = parser.parse_args()\n\n# reproducibility\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\n\nmodel_name = 'pcnn_lr_{:.5f}_nr-resnet{}_nr-filters{}'.format(args.lr, args.nr_resnet, args.nr_filters)\n#assert not os.path.exists(os.path.join('runs', model_name)), '{} already exists!'.format(model_name)\n#writer = SummaryWriter(log_dir=os.path.join('runs', model_name))\n\nsample_batch_size = 6 #25\nobs = (1, 28, 28) if 'mnist' in args.dataset else (3, 32, 32)\ninput_channels = obs[0]\nrescaling = lambda x : (x - .5) * 2.\nrescaling_inv = lambda x : .5 * x + .5\nkwargs = {'num_workers':1, 'pin_memory':True, 'drop_last':True}\nds_transforms = transforms.Compose([transforms.ToTensor(), rescaling])\n\n\ndef get_dataloaders(datatype):\n\n if 'mnist' in args.dataset:\n train_loader = torch.utils.data.DataLoader( datasets.MNIST( args.data_dir, download=True,\n train=True, transform=ds_transforms ),\n batch_size=args.batch_size,\n shuffle=True, **kwargs )\n\n test_loader = torch.utils.data.DataLoader( datasets.MNIST( args.data_dir, train=False,\n transform=ds_transforms ),\n batch_size=args.batch_size, shuffle=True, **kwargs )\n\n loss_op = lambda real, fake: discretized_mix_logistic_loss_1d( real, fake )\n sample_op = lambda x: sample_from_discretized_mix_logistic_1d( x, args.nr_logistic_mix )\n\n elif 'svhn' in args.dataset:\n #removed \"**kwargs\" from the argument of DataLoader\n train_loader = torch.utils.data.DataLoader(datasets.SVHN( args.data_dir, split='train',\n download=True, transform=ds_transforms ),\n batch_size=args.batch_size, shuffle=True, drop_last=True)\n\n #removed \"**kwargs\" from the argument of DataLoader\n test_loader = torch.utils.data.DataLoader(datasets.SVHN( args.data_dir, split='test',\n download=True, transform=ds_transforms),\n batch_size=args.batch_size, shuffle=True, drop_last=True)\n\n loss_op = lambda real, fake: discretized_mix_logistic_loss( real, fake )\n sample_op = lambda x: sample_from_discretized_mix_logistic( x, args.nr_logistic_mix )\n\n elif 'cifar' in args.dataset:\n #removed \"**kwargs\" from the argument of DataLoader\n train_loader = torch.utils.data.DataLoader(datasets.CIFAR10( args.data_dir, train=True,\n download=True, transform=ds_transforms ),\n batch_size=args.batch_size, shuffle=True)\n\n #removed \"**kwargs\" from the argument of DataLoader\n test_loader = torch.utils.data.DataLoader(datasets.CIFAR10( args.data_dir, train=False,\n transform=ds_transforms ),\n batch_size=args.batch_size, shuffle=True )\n\n loss_op = lambda real, fake: discretized_mix_logistic_loss( real, fake )\n sample_op = lambda x: sample_from_discretized_mix_logistic( x, args.nr_logistic_mix )\n else:\n raise Exception( '{} dataset not in {mnist, cifar10}, svhn'.format( args.dataset ) )\n\n return train_loader, test_loader, loss_op, sample_op\n\ndef sample_teacher(model):\n print( 'sample from teacher model' )\n t0 = time.time()\n\n model.train(False)\n data = torch.zeros(sample_batch_size, obs[0], obs[1], obs[2])\n data = data.cuda()\n for i in range(obs[1]):\n for j in range(obs[2]):\n data_v = Variable(data, volatile=True)\n out= model(data_v, sample=True)\n out_sample = sample_op(out)\n data[:, :, i, j] = out_sample.data[:, :, i, j]\n\n sample_t = rescaling_inv( sampled_data )\n utils.save_image( sample_t, 'images/teacher_sample/{}.png'.format( 'model_t_889' ), nrow=3, padding=0 )\n\n t1 = time.time()\n print( \"Time taken to sample from teacher model = \", t1 - t0 )\n\n return sample_t\n\ndef sample_student(model, model_name, image_count):\n\n model.train(False)\n # generate batch of random noise\n x_in = torch.tensor(torch.randn(image_count, 3, 32, 32 ), requires_grad=False )\n x_in = torch.clamp( x_in, min=-1., max=1. ).to( device )\n\n # calculate output of the student model\n # sampled image, and parameters of the final distribution\n # mean, log_s, coeffs\n img_s_out, _, _, _ = model.forward(x_in)\n np.save( 'images/student_sample/sample_s_out_data', img_s_out.cpu().detach().numpy() )\n\n sample_s = rescaling_inv(img_s_out )\n #np.save( 'images/student_sample/sample_s_out_rescaled_data', sample_s.cpu().detach().numpy() )\n utils.save_image(sample_s, 'images/student_sample/{}.png'.format(model_name ), nrow=5, padding=0 )\n\n\n\ndef train_student(model_s, model_t, optimizer_s, scheduler_s, train_loader, test_loader, cuda_present, opt):\n '''\n Perform training on the student model using a trained teacher model\n :param model: the model\n :param train_loader: dataloader for the train set\n :param test_loader: dataloader for the test set\n :param max_eopchs: toal number of epochs for training\n :param cuda_present: boolean, True if CUDA is present\n :return: nothing so far\n '''\n\n model_s = model_s.train()\n model_t = model_t.eval()\n\n batch_size = opt.batch_size\n max_epochs = opt.max_epochs\n\n logging.info(\"Starting student training\")\n t0 = time.time()\n epoch_start_time = time.time()\n for epoch in range(max_epochs):\n\n model_student.train(True )\n torch.cuda.synchronize()\n #generate batch of random noise\n x_in = torch.tensor(torch.randn(batch_size, 3, 32,32), requires_grad=False)\n x_in = torch.clamp(x_in, min=-1., max = 1.).to(device)\n\n #calculate output of the student model\n #sampled image, and parameters of the final distribution\n #mean, log_s, coeffs\n xs_out, means_tot, log_s_tot, coeffs = model_s.forward(x_in)\n\n optimizer_s.zero_grad()\n\n #sample an image from the student generated output\n #img_in = model_s.sample_operation(x_out, opt.nr_logistic_mix)\n\n #pass img_in through the teacher model, generate an output,\n xt_out = model_t(xs_out, sample=True)\n #print( \"teacher model output shape = \", x_t_out.shape, \"\\n\")\n\n # get mu, log_s and mixing coeff of the teacher network output\n (means_t, log_scales_t, coeffs_t) = pixelcnnpp_utils.extract_mu_logs(xt_out, opt.nr_logistic_mix )\n\n #Sample images from the teacher output\n #sample_t = model_t.sample_operation(x_out, opt.nr_logistic_mix)\n #print( \"teacher model sampled output image shape = \", sample_t.shape, \"\\n\" )\n\n #Calculate loss function using (x_out and img_t_out)\n\n #cross entropy between the student and teacher model --> H(P_s, P_T)\n loss_cross_entropy = model_s.cross_ent(xs_out, xt_out, opt.nr_logistic_mix)/(batch_size*3*32.0*32.0)\n loss1 = loss_cross_entropy\n\n #entropy of the student distribution --> H(P_s)\n loss_student_entropy = model_s.entropy_per_pixel(log_s_tot)\n loss2 = loss1 - loss_student_entropy\n\n #Regularization loss from log_scales between student and teacher network\n loss_reg_s = opt.ls_reg*torch.mean((log_s_tot - log_scales_t)*(log_s_tot - log_scales_t))\n loss3 = loss2 + loss_reg_s\n\n # Regularization loss from log_scales between student and teacher network\n loss_reg_coeffs = opt.coeff_reg * torch.mean( (coeffs - coeffs_t ) * (coeffs - coeffs_t) )\n loss4 = loss3+ loss_reg_coeffs\n\n #loss = H(P_s , P_T) - H(P_s)\n #loss = loss1\n #loss = loss2\n #loss = loss3\n loss = loss4\n\n #Perform back prop\n loss.backward()\n\n #clip gradients\n nn.utils.clip_grad_norm_(model_s.parameters(), 7. )\n\n #Update parameters\n optimizer_s.step()\n\n if ((epoch % opt.print_every) == 0) :\n #if ((epoch > 20) & (epoch < 40)):\n t1 = time.time()\n epoch_end_time = time.time()\n time_taken = epoch_end_time - epoch_start_time\n logging.info(\"epoch: {}, Loss_Cross_Entropy: {:02.4f}, Student_Entropy: {:02.4f}, log_scales_reg_L2_loss: {:02.4f}, coeffs_reg_L2_loss: {:02.4f},time taken: {}\".format(epoch, loss_cross_entropy.item(), loss_student_entropy.item(), loss_reg_s.item(), loss_reg_coeffs.item(), time_taken))\n #logging.info(\"lr: {}\".format(optimizer_s.state_dict()['lr']))\n t0 = time.time()\n epoch_start_time = time.time()\n if (epoch + 1) % args.save_interval_student == 0:\n model_name = 'student_2_loss4_{:.5f}_GRNBlocks_{}_layers_{}_'.format( args.lr, args.nr_resnet_s, args.nr_layer)\n model_name += '_filters_{}_batchsize_{}_{}'.format(args.nr_filters, args.batch_size,epoch)\n\n logging.info( \" saving state dict in model name **** {}\".format(model_name) )\n torch.save(model_s.state_dict(), 'trained_student_models/{}.pth'.format(model_name))\n\n logging.info( 'sampling student model ...' )\n sample_s = sample_student(model_student, model_name, 25 )\n\n\n # decrease learning rate\n scheduler_s.step()\nif __name__ == \"__main__\":\n\n args = parser.parse_args()\n max_epochs = args.max_epochs\n\n train_s = True\n student_sample = False\n teacher_sample = False\n\n # Set the logger\n log_file_name = 'train_student_model_2_loss4_'+str(args.nr_resnet_s) +'_'+str(args.nr_layer)+'_'+str(args.nr_filters)+'_'+str(args.batch_size)+ '_'+str(args.ls_reg)+'_'+str(args.lr)+'_'+str(args.coeff_reg)+'_.log'\n #log_file_name = 'generate_student_sample.log'\n set_logger(os.path.join(args.log_dir, log_file_name ) )\n logging.info(\"Using 4 loss terms: Loss_4 ****** \")\n logging.info(\"Loss Terms: Teacher negative log likelihood, student entropy\" )\n logging.info(\"layers_student: gated_resnet module output changed from : c3 = F.tanh(a) * F.sigmoid(b) to c3 = a * F.sigmoid(b)\")\n arg_options = vars(args)\n for key in arg_options:\n logging.info(\"param: {}, Value: {}\".format(key,arg_options[key]))\n\n logging.info(\"generating dataloaders\")\n (train_loader, test_loader, loss_op, sample_op) = get_dataloaders(args.dataset)\n\n #Check if CUDA is available, use GPU if available\n cuda_present = torch.cuda.is_available() # Boolean\n #device = torch.device( \"cuda\" ) if (torch.cuda.is_available() and opt.use_cuda) else torch.device( \"cpu\" )\n\n if cuda_present:\n device = torch.device( \"cuda\" )\n logging.info(\"using CUDA\" )\n else:\n torch.device( \"cpu\" )\n logging.info( \"cuda not available, using CPU\" )\n logging.info( \"Device is {}\".format( device ) )\n\n\n\n #Instantiate teacher model\n model_teacher = PixelCNN( nr_resnet=args.nr_resnet, nr_filters=args.nr_filters,\n input_channels=input_channels, nr_logistic_mix=args.nr_logistic_mix )\n\n logging.info( \"loading pretrained teacher model *** \" )\n\n # Load pre-trained teacher model state dict\n # The new few lines are manipulations to change the key value of the saved state dict\n # the model was probably saved with torch.nn.DataParallel\n\n pretrained_teacher_model = 'trained_teacher_model/pcnn_lr.0.00040_nr-resnet5_nr-filters160_889.pth'\n state_dict = torch.load(pretrained_teacher_model )\n new_state_dict = OrderedDict()\n\n for k, v in state_dict.items():\n name = k[7:]\n new_state_dict[name] = v\n\n model_teacher.load_state_dict( new_state_dict ) #Use this line if the saved model used DataParallel\n #model_teacher.load_state_dict(state_dict ) #Use this line if the saved model didn't use DataParallel\n\n logging.info( \"DONE loading pretrained teacher model *** {}\".format(pretrained_teacher_model) )\n\n model_teacher = model_teacher.to(device) #transferring teacher model to GPU\n logging.info( \"DONE transferring teacher model to CUDA\")\n\n if teacher_sample == True:\n sample_t= sample_teacher(model_teacher)\n\n if args.load_params:\n load_part_of_model( model_teacher, args.load_params )\n # model.load_state_dict(torch.load(args.load_params))\n print( 'model parameters loaded' )\n\n\n\n if train_s == True:\n model_student = PixelCNNpp_Student(resnet_blocks = args.nr_resnet_s, layers_per_blk = args.nr_layer)\n #print(model_student)\n\n pretrained_student_model = 'student_2_0.00020_GRNBlocks_5_layers_2_filters_160_batchsize_8_49999.pth'\n #state_dict_s = torch.load(pretrained_student_model )\n\n #model_student.load_state_dict(state_dict_s)\n model_student = model_student.to( device )\n\n # Optimizers\n optimizer_s = torch.optim.Adam(model_student.parameters(), lr=args.lr)\n scheduler_s = lr_scheduler.StepLR(optimizer_s, step_size=50, gamma=args.lr_decay)\n\n\n train_student(model_student, model_teacher, optimizer_s, scheduler_s,\n train_loader, test_loader, cuda_present, opt=args)\n\n\n if student_sample == True:\n print(\"sampling from the student model\")\n #model_student = PixelCNNpp_Student(resnet_blocks=args.nr_resnet_s, layers_per_blk=args.nr_layer )\n # print(model_student)\n\n #pretrained_student_model = 'trained_student_models/student_2_0.00020_GRNBlocks_5_layers_2_filters_160_lsreg_0.05_coeffreg_0.05_batchsize_8_99999.pth'\n #model_name = pretrained_student_model.split( '.' )[0].split( '/' )[-1]\n\n #pretrained_student_model = 'student_2_0.00020_GRNBlocks_5_layers_2_filters_160_batchsize_8_49999.pth'\n #model_name = pretrained_student_model.split( '.' )[0]\n #state_dict_s = torch.load(pretrained_student_model )\n #model_student = model_student.to( device )\n #sample_student(model_student, model_name, 25)\n","sub_path":"train_Student.py","file_name":"train_Student.py","file_ext":"py","file_size_in_byte":17404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"211009592","text":"# 1.Write a function called fizz_buzz that takes a number\ndef fizzbuzz(num):\n if num % 3 == 0 and num % 5 == 0:\n return \"fizz buzz\"\n elif num % 3 == 0:\n return \"fizz\"\n elif num % 5 == 0:\n return \"buzz\"\n else:\n return num\n\n\nprint(fizzbuzz(60))\n\n# 2. try and except block to avoid IndexError.\nnum_list = [5, 10, 20]\ntry:\n if num_list[5] == 20:\n print(\"number is the list\")\nexcept IndexError:\n print(\"List index out of range\")\n\n\n# 3. Create a class with arguments\nclass JetInventory():\n def __init__(self, name, country):\n self.name = name\n self.country = country\n\n def jet_details(self):\n print(f'{self.name} {self.country}')\n\n\njet_inventory1 = JetInventory(\"AirIndia\", \"India\")\njet_inventory1.jet_details()\n\n# 4. Create a notebook\n# import pandas as pd\n# df = pd.read_csv('test.csv')\n# data.head()\n\n# 5. check whether a given key already exists in a dictionary.\ndic = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}\n\n\ndef is_key_present(key):\n if key in dic:\n print('Key is present in the dictionary')\n else:\n print('Key is not present in the dictionary')\n\n\nis_key_present(5)\nis_key_present(9)\n\n\n# 6.Identify the even and odd numbers.\n\ndef show_numbers(limit):\n num = int(input(\"Enter a number: \"))\n mod = num % 2\n if mod != 0:\n print(\"{0} is odd\".format(num))\n else:\n print(\"{0} is even\".format(num))\n\nshow_numbers(5)\n\n# 7. Read the dataset\n#import pandas as pd\n#df = pd.read_csv('creditcard.csv')\n#data.head()\n#df.describe()\n#df.info()\n\n\n# 8. Create a classd Person, with firstname and lastname properties, and a print name method.\nclass Person():\n def __init__(self, first_name, last_name):\n self.first_name = first_name\n self.last_name = last_name\n\n def name(self):\n print(f\"My name is : {self.first_name} {self.last_name}\")\n\n\nperson = Person(\"Hema\", \"Gunti\")\nperson.name()\n\n# 9.Write a program asks for numeric user input.\nwhile True:\n try:\n x = int(input(\"Please enter a number: \"))\n break\n except ValueError:\n print(\"Oops! That was no valid number. Try again...\")\n\n\n# 10. Write a Python program to create two empty classes,\nclass Student:\n pass\n\n\nclass Marks:\n pass\n\n\nstudent1 = Student()\nmarks1 = Marks()\nprint(isinstance(student1, Student))\nprint(isinstance(marks1, Student))\nprint(isinstance(marks1, Marks))\nprint(isinstance(student1, Marks))\nprint(\"\\nCheck whether the said classes are subclasses of the built-in object class or not.\")\nprint(issubclass(Student, object))\nprint(issubclass(Marks, object))\n","sub_path":"week2/week2.py","file_name":"week2.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"469062229","text":"from time import time, sleep\nfrom datetime import datetime, date, time, timedelta\n\ndef wageInput():\n wageTypeStr = 'Please select your wage type (h/w/s): '\n print('Welcome to wagey!')\n wageType = input(wageTypeStr)\n while wageType not in ('h', 'w', 's'):\n print('Error: \\'' + wageType + '\\' is not a valid input.')\n print('h = hourly wage')\n print('w = weekly wage')\n print('s = annual salary')\n wageType = input(wageTypeStr)\n return wageType\n\ndef hoursWorked():\n while True:\n try:\n hours = float(input('How many hours a week do you work? '))\n break\n except ValueError:\n print('Error: Invalid number format.')\n return hours\n\ndef hourMultiplier():\n while True:\n try:\n multiplier = float(input('Enter your penalty rate: '))\n break\n except ValueError:\n print('Error: Invalid number format.')\n return multiplier\n\ndef calculateFromHourlyWage():\n while True:\n try:\n hourlyWage = float(input('Enter your hourly wage: $'))\n break\n except ValueError:\n print('Error: Invalid number format.')\n multiplier = hourMultiplier()\n print('Woah you\\'re earning $' + str(multiplier * hourlyWage) + '/hour!')\n return (hourlyWage * multiplier) / 60 / 60\n\ndef calculateFromWeeklyWage():\n while True:\n try:\n weeklyWage = float(input('Enter your weekly wage: $'))\n break\n except ValueError:\n print('Error: Invalid number format.')\n hoursInWeek = hoursWorked()\n return weeklyWage / hoursInWeek / 60 / 60\n\ndef calculateFromAnnualSalary():\n while True:\n try:\n annualSalary = float(input('Enter your annual salary: $'))\n break\n except ValueError:\n print('Error: Invalid number format.')\n hoursInWeek = hoursWorked()\n return annualSalary / 12 / 4.3 / hoursInWeek / 60 / 60\n\ndef getStartTime():\n while True:\n try:\n startTime = datetime.strptime(input('Enter your start time [hh:mm:ss]: '), '%H:%M:%S').time()\n break\n except ValueError:\n print('Error: Invalid time format.')\n return datetime.combine(date.today(), startTime)\n\ndef getFinishTime(startTime):\n while True:\n try:\n finishTime = datetime.strptime(input('Enter your finish time [hh:mm:ss]: '), '%H:%M:%S').time()\n while datetime.combine(date.today(), finishTime) < startTime:\n print('Error: Finish time cannot be before start time [' + str(finishTime) + ']')\n finishTime = datetime.strptime(input('Enter your finish time [hh:mm:ss]: '), '%H:%M:%S').time()\n break\n except ValueError:\n print('Error: Invalid time format.')\n return datetime.combine(date.today(), finishTime)\n\ndef calculateWageSoFar(secondlyWage, startTime):\n diff = (datetime.now() - startTime).total_seconds()\n return diff * secondlyWage\n\ndef wageLoop(secondlyWage, startTime, wageSoFar, finishTime):\n print('You\\'ve earned $' + str(round(wageSoFar, 2)) + ' so far!')\n print('You earn $' + str(round(secondlyWage, 3)) + '/second!')\n\n newWage = wageSoFar\n while datetime.now() < finishTime:\n sleep(1)\n newWage += secondlyWage\n print('$' + str(round(newWage, 2)))\n print('Great job you\\'ve finished your day!')\n print('You earned a total of $' + str(round(newWage, 2)) + ' at $' + str(round(secondlyWage, 3)) + '/second!')\n tryAgain = input('Would you like to do this again (y/n)? ')\n while tryAgain not in ('y', 'n'):\n print('Error: \\'' + tryAgain + '\\' is not a valid input.')\n tryAgain = input('Would you like to do this again (y/n)? ')\n if tryAgain == 'y':\n main()\n else:\n exit()\n\n# function caller helper\nwageTypes = {'h' : calculateFromHourlyWage,\n 'w' : calculateFromWeeklyWage,\n 's' : calculateFromAnnualSalary}\n\ndef main():\n wageType = wageInput()\n secondlyWage = wageTypes[wageType]()\n startTime = getStartTime()\n finishTime = getFinishTime(startTime)\n wageSoFar = calculateWageSoFar(secondlyWage, startTime)\n wageLoop(secondlyWage, startTime, wageSoFar, finishTime)\n\n# call the main function\nif __name__ == '__main__':\n main()","sub_path":"wagey.py","file_name":"wagey.py","file_ext":"py","file_size_in_byte":4331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"417821599","text":"import argparse\nimport logging\nimport os\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom PIL import Image\nfrom torchvision import transforms\n\nfrom unet import UNet\nfrom utils.data_vis import plot_img_and_mask\nfrom utils.dataset import BasicDataset\nfrom dataset_creation import CancerDataset\nfrom torch.utils.data import DataLoader, random_split\nimport cv2\nimport matplotlib.pyplot as plt\n\n\ndef predict_img(net,\n full_img,\n device,\n scale_factor=1,\n out_threshold=0.5):\n net.eval()\n\n img = torch.from_numpy(BasicDataset.preprocess(full_img, scale_factor))\n\n img = img.unsqueeze(0)\n img = img.to(device=device, dtype=torch.float32)\n\n with torch.no_grad():\n output = net(img)\n\n if net.n_classes > 1:\n probs = F.softmax(output, dim=1)\n else:\n probs = torch.sigmoid(output)\n\n probs = probs.squeeze(0)\n\n tf = transforms.Compose(\n [\n transforms.ToPILImage(),\n transforms.Resize(full_img.size[1]),\n transforms.ToTensor()\n ]\n )\n\n probs = tf(probs.cpu())\n full_mask = probs.squeeze().cpu().numpy()\n\n return full_mask > out_threshold\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description='Predict masks from input images',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--model', '-m', default='MODEL.pth',\n metavar='FILE',\n help=\"Specify the file in which the model is stored\")\n parser.add_argument('--input', '-i', metavar='INPUT', nargs='+',\n help='filenames of input images', required=True)\n\n parser.add_argument('--output', '-o', metavar='INPUT', nargs='+',\n help='Filenames of ouput images')\n parser.add_argument('--viz', '-v', action='store_true',\n help=\"Visualize the images as they are processed\",\n default=False)\n parser.add_argument('--no-save', '-n', action='store_true',\n help=\"Do not save the output masks\",\n default=False)\n parser.add_argument('--mask-threshold', '-t', type=float,\n help=\"Minimum probability value to consider a mask pixel white\",\n default=0.5)\n # parser.add_argument('--scale', '-s', type=float,\n # help=\"Scale factor for the input images\",\n # default=0.5)\n\n return parser.parse_args()\n\n\ndef get_output_filenames(args):\n in_files = args.input\n out_files = []\n\n if not args.output:\n for f in in_files:\n pathsplit = os.path.splitext(f)\n out_files.append(\"{}_OUT{}\".format(pathsplit[0], pathsplit[1]))\n elif len(in_files) != len(args.output):\n logging.error(\"Input files and output files are not of the same length\")\n raise SystemExit()\n else:\n out_files = args.output\n\n return out_files\n\n\ndef mask_to_image(mask):\n return Image.fromarray((mask * 255).astype(np.uint8))\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')\n\n model_path = \"checkpoints4/CP_epoch20.pth\"\n\n net = UNet(n_channels=3, n_classes=1)\n\n logging.info(\"Loading model {}\".format(model_path))\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n logging.info(f'Using device {device}')\n net.to(device=device)\n net.load_state_dict(torch.load(model_path, map_location=device))\n\n logging.info(\"Model loaded !\")\n\n dataset = CancerDataset()\n print(\"DATASET LOADED!!!\")\n\n val_percent = 0\n batch_size = 1\n\n train_loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=True)\n i = 0\n with torch.no_grad():\n for imgs, true_masks in train_loader:\n imgs = imgs.to(device=device, dtype=torch.float32)\n mask_type = torch.float32 if net.n_classes == 1 else torch.long\n true_masks = true_masks.to(device=device, dtype=mask_type)\n\n predicted_masks = net(imgs)\n probabilities = torch.sigmoid(predicted_masks)\n\n print(probabilities.shape)\n print(\"I: \", i)\n prob = (probabilities.cpu() * 255)[0].numpy().transpose((1, 2, 0))\n print(prob.shape)\n\n threshold = 0.5\n prob[prob < threshold * 255] = 0\n\n cv2.imwrite(\"rubbish4/{}_predicted.png\".format(i),\n cv2.applyColorMap(prob.astype(np.uint8), cv2.COLORMAP_JET))\n cv2.imwrite(\"rubbish4/{}_image.png\".format(i), (imgs.cpu() * 255)[0].numpy().transpose((1, 2, 0)))\n cv2.imwrite(\"rubbish4/{}_mask_original.png\".format(i),\n (true_masks.cpu() * 255)[0].numpy().transpose((1, 2, 0)))\n # plt.imshow(prob)\n # plt.show()\n # plt.close()\n i += 1\n if i >= 80:\n break\n","sub_path":"unet/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":5103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"601550439","text":"import unittest\nfrom ToSidewalk.node import Node\nfrom ToSidewalk.edge import Edge\nfrom ToSidewalk.path import Path\nfrom ToSidewalk.utilities import window\n\n\nclass TestPathMethods(unittest.TestCase):\n def test_get_nodes(self):\n nodes = [Node(i, i, 0) for i in range(10)]\n\n from random import shuffle\n shuffle(nodes)\n edges = [Edge(source, target) for source, target in window(nodes, 2)]\n path = Path(0, edges)\n\n for n1, n2 in zip(map(lambda e: e.source, path.edges), path.get_nodes()[:-1]):\n self.assertEqual(n1, n2)\n\n def test_merge(self):\n nodes = [Node(i, i, 0) for i in range(10)]\n edges = [Edge(source, target) for source, target in window(nodes, 2)]\n path = Path(0, edges)\n\n e1 = edges[1]\n e2 = edges[2]\n\n new_edge = path.merge_edges(edges[1], edges[2])\n self.assertFalse(e1 in nodes[1].edges)\n self.assertFalse(e2 in nodes[2].edges)\n\n self.assertTrue(path == new_edge.path)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"ToSidewalk/test/test_path.py","file_name":"test_path.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"398621005","text":"import sys\nimport pygame\n\nclass ship():\n \"\"\"description of class\"\"\"\n def __init__(self,settings, screen):\n self.screen=screen\n self.image=pygame.image.load('images\\ship.png')\n self.rect=self.image.get_rect()\n self.screen_rect=screen.get_rect()\n self.rect.centerx=self.screen_rect.centerx\n self.rect.bottom=self.screen_rect.bottom\n self.move_Left=False\n self.move_Right=False\n self.settings=settings\n self.center=float(self.rect.centerx)\n\n def update(self):\n if self.move_Left and self.rect.left>0:\n self.center-=self.settings.ship_speed_factor\n elif self.move_Right and self.rect.right 0 else 0)\n\n def pickIndex(self) -> int:\n target = random.randrange(1, self.upper[-1] + 1)\n\n i, j = 0, len(self.upper) - 1\n\n while i < j:\n mid = (i + j) // 2\n if self.upper[mid] < target:\n i = mid + 1\n else:\n j = mid\n\n return i\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()\n","sub_path":"528 Random Pick with Weight.py","file_name":"528 Random Pick with Weight.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"359300468","text":"import networkx as nx\nimport numpy as np\nfrom scipy import sparse\n\n#-- Network topologies --#\ndef barab1(n):\n \"\"\" Barabasi-Albert preferential attachment. Each node is added with one edge\n Parameter\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n m = 1\n A = nx.adj_matrix(nx.barabasi_albert_graph(n,m)).T\n return sparse.dok_matrix(A)\n\ndef barab2(n):\n \"\"\" Barabasi-Albert preferential attachment. Each node is added with two edges\n Parameter\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n m = 2\n A = nx.adj_matrix(nx.barabasi_albert_graph(n,m)).T\n return sparse.dok_matrix(A)\n\ndef barab4(n):\n \"\"\" Barabasi-Albert preferential attachment. Each node is added with two edges\n Parameter\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n m = 4\n A = nx.adj_matrix(nx.barabasi_albert_graph(n,m)).T\n return sparse.dok_matrix(A)\n\ndef erdos(mean_degree,n):\n \"\"\" Erdos-Renyi random graph.\n Parameter\n mean_degree (int): specific to this topology\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n p = mean_degree/n\n A = nx.adj_matrix(nx.erdos_renyi_graph(n,p)).T\n return sparse.dok_matrix(A)\n\ndef random_digraph(mean_degree,n):\n \"\"\" Random digraph. Each directed edge is present with probability p = mean_degree/n.\n Since this is a directed graph model, mean_degree = mean in deegree = mean out degree\n Parameter\n mean_degree (int): specific to this topology\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n p = mean_degree/n\n return sparse.random(n,n, density=p, data_rvs=np.ones, format='dok')\n\ndef watts2(p,n):\n \"\"\" Watts-Strogatz small world model\n Parameter\n p (float): specific to this topology\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n k = 2\n A = nx.adj_matrix(nx.watts_strogatz_graph(n,k,p)).T\n return sparse.dok_matrix(A)\n\ndef watts3(p,n):\n \"\"\" Watts-Strogatz small world model\n Parameter\n p (float): specific to this topology\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n k = 3\n A = nx.adj_matrix(nx.watts_strogatz_graph(n,k,p)).T\n return sparse.dok_matrix(A)\n\ndef watts4(p,n):\n \"\"\" Watts-Strogatz small world model\n Parameter\n p (float): specific to this topology\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n k = 4\n A = nx.adj_matrix(nx.watts_strogatz_graph(n,k,p)).T\n return sparse.dok_matrix(A)\n\ndef watts5(p,n):\n \"\"\" Watts-Strogatz small world model\n Parameter\n p (float): specific to this topology\n n (int): n is the size of the network\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n k = 5\n A = nx.adj_matrix(nx.watts_strogatz_graph(n,k,p)).T\n return sparse.dok_matrix(A)\n\ndef geom(mean_degree, n):\n \"\"\" Random geometric graph\n \"\"\"\n if n is None:\n n = np.random.randint(smallest_network_size,biggest_network_size)\n r = (mean_degree/(np.pi*n))**.5\n A = nx.adj_matrix(nx.random_geometric_graph(n, r)).T\n return sparse.dok_matrix(A)\n\ndef no_edges(n):\n return sparse.csr_matrix((n,n))\n\ndef chain(n):\n A = sparse.lil_matrix((n,n))\n for i in range(n - 1):\n A[i+1, i] = 1\n return A\n\ndef loop(n):\n A = sparse.lil_matrix((n,n))\n for i in range(n - 1):\n A[i+1, i] = 1\n A[0, -1] = 1\n return A\n\ndef ident(n):\n return sparse.eye(n, format=\"lil\")\n\ndef remove_edges(A,nedges):\n \"\"\" Randomly removes 'nedges' edges from a sparse adj matrix 'A'\n \"\"\"\n A = A.todok()\n # Remove Edges\n keys = list(A.keys())\n remove_idx = np.random.choice(range(len(keys)),size=nedges, replace=False)\n remove = [keys[i] for i in remove_idx]\n for e in remove:\n A[e] = 0\n return A\n\ndef generate_adj(network, n, param=None):\n \"\"\" Generate a network with the supplied topology\n Parameters\n network (str) : one of the options in the list below\n ['barab1', 'barab2', 'barab4', 'erdos', 'random_digraph',\n 'watts3', 'watts5', 'watts2','watts4', 'geom', 'no_edges',\n 'loop', 'chain', 'ident'\n ]\n param (float) : specific to the topology\n n (int) : size of the topology, optional\n Returns\n An adjacency matrix with the specified network topology\n \"\"\"\n # the directory function in parameter_experiments.py needs to have the same\n # network_options as this function, so if more topologies are added, the directory\n # function in the other file should also be edited\n network_options = ['barab1', 'barab2', 'barab4',\n 'erdos', 'random_digraph',\n 'watts3', 'watts5',\n 'watts2','watts4',\n 'geom', 'no_edges',\n 'loop', 'chain',\n 'ident'\n ]\n\n if network not in network_options:\n raise ValueError(f'{network} not in {network_options}')\n\n if network == 'barab1':\n return barab1(n)\n if network == 'barab2':\n return barab2(n)\n if network == 'barab4':\n return barab4(n)\n if network == 'erdos':\n return erdos(param, n)\n if network == 'random_digraph':\n return random_digraph(param, n)\n if network == 'watts3':\n return watts3(param, n)\n if network == 'watts5':\n return watts5(param, n)\n if network == 'watts2':\n return watts2(param, n)\n if network == 'watts4':\n return watts4(param, n)\n if network == 'geom':\n net = geom(param, n)\n if network == 'no_edges':\n net = no_edges(n)\n if network == 'chain':\n net = chain(n)\n if network == 'loop':\n net = loop(n)\n if network == 'ident':\n net = ident(n)\n return net\n","sub_path":"rescomp/complex_networks.py","file_name":"complex_networks.py","file_ext":"py","file_size_in_byte":6673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"595594017","text":"'''\nCreated on Aug 9, 2017\n\n@author: Hao Wu\n'''\n\nfrom ScopeFoundry import HardwareComponent\nfrom VOTAScopeHW.arduino_odometer.arduino_odometer_dev import ArduinoOdometerDev\nimport time\nfrom math import exp\n\nclass ArduinoOdometerHW(HardwareComponent):\n '''\n Hardware Component Class for receiving AI input for breathing, licking etc\n '''\n \n name='arduino_odometer'\n\n def setup(self,port='COM4',baud_rate=250000):\n '''\n add settings for analog input event\n '''\n self.settings.New(name='port',initial=port,dtype=str,ro=False)\n self.settings.New(name='baud_rate',initial=baud_rate,dtype=int,ro=False)\n self.settings.New(name='x',initial=0,dtype=int,ro=True)\n self.settings.New(name='y',initial=0,dtype=int,ro=True)\n self.settings.New(name='vx',initial=0,dtype=int,ro=True)\n self.settings.New(name='vy',initial=0,dtype=int,ro=True)\n\n def read(self):\n position, speed = self._dev.read()\n self.settings.x.update_value(position[0])\n self.settings.y.update_value(position[1])\n self.settings.vx.update_value(speed[0])\n self.settings.vy.update_value(speed[1])\n \n def connect(self):\n self._dev=ArduinoOdometerDev(self.settings.port.value(),\n self.settings.baud_rate.value())\n\n\n \n \n def start(self):\n self._dev.open()\n \n def stop(self):\n self._dev.close()\n \n def disconnect(self):\n try:\n self.stop()\n del self._dev\n del self.write\n \n except AttributeError:\n pass\n","sub_path":"arduino_odometer/arduino_odometer_hw.py","file_name":"arduino_odometer_hw.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"363135134","text":"from __future__ import division\r\nfrom __future__ import unicode_literals\r\nfrom __future__ import print_function\r\nfrom __future__ import absolute_import\r\nfrom builtins import int\r\nfrom future import standard_library\r\nstandard_library.install_aliases()\r\nimport cv2\r\nimport numpy as np\r\nimport gripit.edgelib.util as util\r\nimport gripit.edgelib.draw_edge_list as de\r\nimport gripit.edgelib.edge_detect as ed\r\nimport copy\r\n\r\n\r\n\r\ndef roipoly(src, poly):\r\n mask = np.zeros_like(src, dtype=np.uint8)\r\n win = util.swap_indices(poly)\r\n cv2.fillConvexPoly(mask, win.astype(np.int32), 255) # Create the ROI\r\n res = src * mask\r\n # cv2.imshow(\"roi\", res)\r\n # cv2.waitKey(0)\r\n return res\r\n\r\n\r\ndef get_orientation(line, window_size):\r\n dy = abs(line[0] - line[2])\r\n dx = abs(line[1] - line[3])\r\n # Vertical or horizontal line test\r\n if dy > dx or dy == dx:\r\n pt1 = [line[0], line[1] - window_size]\r\n pt2 = [line[0], line[1] + window_size]\r\n pt3 = [line[2], line[3] - window_size]\r\n pt4 = [line[2], line[3] + window_size]\r\n return pt1, pt2, pt3, pt4\r\n else:\r\n pt1 = [line[0] - window_size, line[1]]\r\n pt2 = [line[0] + window_size, line[1]]\r\n pt3 = [line[2] - window_size, line[3]]\r\n pt4 = [line[2] + window_size, line[3]]\r\n return pt1, pt2, pt3, pt4\r\n\r\n\r\ndef get_ordering(pt1, pt2, pt3, pt4):\r\n temp1 = np.linalg.norm(np.subtract((np.add(pt1, pt3) / 2.0), (np.add(pt2, pt4) / 2.0)))\r\n temp2 = np.linalg.norm(np.subtract((np.add(pt1, pt4) / 2.0), (np.add(pt2, pt3) / 2.0)))\r\n res = np.array([pt1, pt3, pt4, pt2]) if temp1 > temp2 else np.array([pt1, pt4, pt3, pt2])\r\n return [[int(i) for i in pt] for pt in res]\r\n\r\n\r\ndef get_lin_index(x1, y1, imgsize):\r\n return np.ravel_multi_index((y1, x1), imgsize, order='F')\r\n\r\n\r\n# ref: https://stackoverflow.com/questions/29519726/find-matching-points-in-2-separate-numpy-arrays\r\ndef set_intersection(pA, pB):\r\n # Form concatenate array of pA and pB\r\n pts = np.concatenate((pA, pB), axis=0)\r\n\r\n # Sort pts by rows\r\n spts = pts[pts[:, 1].argsort(),]\r\n\r\n # Finally get counts by DIFFing along rows and counting all zero rows\r\n counts = np.sum(np.diff(np.all(np.diff(spts, axis=0) == 0, 1) + 0) == 1)\r\n\r\n return counts\r\n\r\n\r\ndef count_roi(im, win):\r\n roi = roipoly(im, win)\r\n line_c = np.where(roi == 255)\r\n pts = np.array(get_lin_index(line_c[1], line_c[0], roi.shape))\r\n return len(pts)\r\n\r\n\r\ndef classify_curves(curve_im, depth_im, list_lines, list_points, P):\r\n window_size = copy.deepcopy(P[\"classification_area\"][\"value\"])\r\n line_new = []\r\n # show both images to see where the lines belong\r\n # if settings.dev_mode is True:\r\n # cv2.imshow(\"curve im\", ed.create_img(curve_im))\r\n # cv2.imshow(\"depth im\", ed.create_img(depth_im))\r\n # going through each line\r\n for i, line in enumerate(list_lines):\r\n # strategy:\r\n # check the curve and depth image\r\n # whichever one has more tells us what kind of line it is\r\n\r\n pt1, pt2, pt3, pt4 = get_orientation(line, window_size)\r\n win = np.array(get_ordering(pt1, pt2, pt3, pt4))\r\n\r\n count_c = count_roi(curve_im, win)\r\n count_d = count_roi(depth_im, win)\r\n\r\n # determine if the line is a discontinuity if\r\n # it shows up in both curve and depth\r\n if abs(count_c - count_d) <= line[4] * .50:\r\n line_new.append(np.append(list_lines[i], [13]))\r\n # print(\"14, hole\", count_c, count_d)\"\"\"\r\n elif count_c > count_d:\r\n # Line is a curvature\r\n line_new.append(np.append(list_lines[i], [12]))\r\n # print(\"12, curv\", count_c, count_d)\r\n else:\r\n # discontinuity\r\n line_new.append(np.append(list_lines[i], [13]))\r\n # print(\"13, disc\", count_c, count_d)\r\n\r\n return np.array(line_new)\r\n\r\n\r\n\r\n\r\n","sub_path":"src/gripit/edgelib/classify_curves.py","file_name":"classify_curves.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"265868265","text":"import os\nimport sys\nimport datetime\nimport tensorflow as tf\nimport yaml\nimport time\n\nfrom baseline_action_predictor import BaselineActionPredictor\nfrom baseline_force_predictor import BaselineForcePredictor\nfrom compute_cache import ComputeCache\nfrom data_loader import DataLoader\nfrom batch_iterator import BatchIterator\nfrom distance_potential import MultipleDistancePotential\nfrom evaluation_manager import EvaluationManager\nfrom openrave_manager import OpenraveManager\nfrom performance_timer import PerformanceTimer\nfrom potential_point import PotentialPoint\nfrom saver_wrapper import SaverWrapper\nfrom shutil import copyfile\n\n\nif __name__ == '__main__':\n # disable tf warning\n # os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n # read the config\n config_path = os.path.join(os.getcwd(), 'config/config.yml')\n with open(config_path, 'r') as yml_file:\n config = yaml.load(yml_file)\n print('------------ Config ------------')\n print(yaml.dump(config))\n\n # set the name of the model\n model_name = config['general']['name']\n if model_name is None:\n model_name = \"\" if len(sys.argv) == 1 else sys.argv[1]\n\n # process potential points\n potential_points = PotentialPoint.from_config(config)\n main_openrave_manager = OpenraveManager(config, potential_points)\n\n\n\n # # compute the avg jacobian rank for all the paths:\n # for workspace_id in data_loader.configuration_paths:\n # for path_id in data_loader.configuration_paths[workspace_id]:\n # joints = [data_loader.pre_process_joints(j) for j in data_loader.configuration_paths[workspace_id][path_id]]\n # avg_rank = ros_manager.kdl_manager.compute_avg_jacobian_rank(joints, modeling_links)\n # print 'along workspace {} path {} the avg jacobian rank is {}'.format(workspace_id, path_id, avg_rank)\n\n pose_size = 2\n joints_configuration_size = 4\n batch_size = config['model']['batch_size']\n\n # where we save all the outputs\n working_dir = os.getcwd()\n now = datetime.datetime.fromtimestamp(time.time()).strftime('%Y_%m_%d_%H_%M_%S')\n saver_dir = os.path.join(working_dir, 'models', now, 'model_' + model_name)\n config_copy_path = os.path.join(working_dir, 'models', now, 'config.yml')\n summaries_dir = os.path.join(working_dir, 'tensorboard', now)\n completed_trajectories_dir = os.path.join(working_dir, 'trajectories', now)\n drift_dir = os.path.join(working_dir, 'drift', now)\n\n # load data\n data_loader = DataLoader(config)\n data_loader.load_data()\n workspace_image_shape = data_loader.workspace_image_shape\n\n def get_model(model_type):\n if model_type == 'distance_potential':\n return MultipleDistancePotential(\n config, workspace_image_shape, joints_configuration_size, pose_size)\n elif model_type == 'action_predictor':\n return BaselineActionPredictor(\n config, workspace_image_shape, joints_configuration_size, pose_size)\n elif model_type == 'force_predictor':\n # return BaselineForcePredictor(config, workspace_image_shape, joints_configuration_size, pose_size)\n # from baseline_individual_force_predictor import BaselineIndividualForcePredictor\n # return BaselineIndividualForcePredictor(config, workspace_image_shape, joints_configuration_size, pose_size)\n from baseline_direction_magnitude_force_predictor import BaselineDirectionMagnitudeForcePredictor\n return BaselineDirectionMagnitudeForcePredictor(config, workspace_image_shape, joints_configuration_size, pose_size)\n\n # generate graph:\n model = get_model(config['model']['actor'])\n model.finalize_graph()\n\n train_iterator = BatchIterator(data_loader.get_train_dataset, batch_size)\n test_iterator = BatchIterator(data_loader.get_test_dataset, batch_size)\n\n cache = ComputeCache(data_loader, main_openrave_manager, model)\n\n def create_predict_for_eval(sess, model):\n def predict_for_eval(eval_step_size, batch):\n eval_feed_dictionary = cache.make_feed_dictionary(batch, None)\n eval_feed_dictionary[model.step_size] = eval_step_size\n\n get_potential_force = model.pose_force is not None\n get_potential_centers = model.potential_centers is not None\n\n execution_list = [model.prediction]\n if get_potential_force:\n execution_list += [model.pose_force[p.tuple] for p in potential_points]\n if get_potential_centers:\n execution_list += [model.potential_centers[p.tuple] for p in potential_points]\n\n session_run_result = sess.run(execution_list, eval_feed_dictionary)\n model_prediction = session_run_result[0]\n potential_points_forces = None\n potential_centers = None\n\n if get_potential_force:\n potential_points_forces = {\n p.tuple: session_run_result[1+i] for i, p in enumerate(potential_points)}\n if get_potential_centers:\n potential_centers = {\n p.tuple: session_run_result[1 + len(potential_points) + i] for i, p in enumerate(potential_points)\n }\n return model_prediction, potential_points_forces, potential_centers\n\n return predict_for_eval\n\n def get_success_trackers():\n def _generate_success_tracker(workspace_id, path_id):\n k = (workspace_id, path_id)\n success_placeholders[k] = tf.placeholder(tf.float32)\n scalar = tf.Variable(0.0, trainable=False)\n success_assign_op[k] = tf.assign(scalar, success_placeholders[k])\n success_summaries.append(tf.summary.scalar('{}_{}_success'.format(k[0], k[1]), scalar))\n\n success_placeholders = {}\n success_assign_op = {}\n success_summaries = []\n # generate success tracker for all paths\n for workspace_id in data_loader.test_descriptions:\n for path_id in data_loader.test_descriptions[workspace_id]:\n _generate_success_tracker(workspace_id, path_id)\n # generate general success tracker\n _generate_success_tracker(None, None)\n return success_placeholders, success_assign_op, tf.summary.merge(success_summaries + [model.epoch_summary])\n\n success_placeholders, success_assign_op, merged_success_summary = get_success_trackers()\n\n # main train loop parameters\n performance_timer = PerformanceTimer()\n\n saver = SaverWrapper(saver_dir)\n global_step = 0\n epoch_learn_rate_reduction_rate = config['model']['epoch_learn_rate_reduction_rate']\n trajectory_every_epoch = config['test_trajectories']['test_every_epochs']\n # copy config to models dir\n copyfile(config_path, config_copy_path)\n\n def on_new_epoch(sess, model, epoch):\n sess.run(model.epoch_update)\n # if epoch_learn_rate_reduction_rate > 0 this means we should reduce the learn rate\n if epoch_learn_rate_reduction_rate > 0 and epoch % epoch_learn_rate_reduction_rate == (\n epoch_learn_rate_reduction_rate - 1):\n sess.run(model.reduce_learn_rate)\n print('starting epoch ' + str(epoch))\n\n def eval_trajectory(sess, summary_writer_trajectory, epoch):\n if trajectory_every_epoch > 0 and epoch % trajectory_every_epoch == trajectory_every_epoch - 1:\n performance_timer.start_timer(PerformanceTimer.TimerType.TRAJECTORY_PLANNER_ALL)\n # do trajectory evaluation\n successful_ratio, succeeded, failed_max_length, failed_collision = evaluation_manager.eval_paths(\n global_step, epoch)\n # combine to a single object\n success_per_path = {(workspace_id, path_id): 0 for workspace_id in data_loader.test_descriptions for\n path_id in data_loader.test_descriptions[workspace_id]}\n for workspace_id in succeeded:\n for path_id in succeeded[workspace_id]:\n success_per_path[(workspace_id, path_id)] = 1\n\n # update the results\n feed = {success_placeholders[k]: success_per_path[k] for k in success_per_path}\n feed[success_placeholders[(None, None)]] = successful_ratio\n ops = [success_assign_op[k] for k in success_per_path]\n ops.append(success_assign_op[(None, None)])\n ops.append(merged_success_summary)\n\n summary_writer_trajectory.add_summary(sess.run(ops, feed)[-1], global_step=global_step)\n performance_timer.stop_timer(PerformanceTimer.TimerType.TRAJECTORY_PLANNER_ALL)\n\n # main train loop\n with tf.Session(\n config=tf.ConfigProto(\n gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=config['general']['gpu_usage'])\n )\n ) as sess:\n summary_writer_train = tf.summary.FileWriter(os.path.join(summaries_dir, 'train_' + model_name), sess.graph)\n summary_writer_test = tf.summary.FileWriter(os.path.join(summaries_dir, 'test_' + model_name), sess.graph)\n summary_writer_trajectory = tf.summary.FileWriter(os.path.join(summaries_dir, 'trajectory_' + model_name),\n sess.graph)\n\n evaluation_manager = EvaluationManager(data_loader, main_openrave_manager, performance_timer,\n create_predict_for_eval(sess, model), config, completed_trajectories_dir)\n\n sess.run(tf.global_variables_initializer())\n for epoch in range(config['general']['epochs']):\n on_new_epoch(sess, model, epoch)\n for batch_index, train_batch in enumerate(train_iterator):\n performance_timer.start_timer(PerformanceTimer.TimerType.TRAIN)\n feed_dictionary = cache.make_feed_dictionary(train_batch, epoch)\n steps = [model.train_step, model.model_summary_step]\n if ((global_step + 1) % config['evaluation']['eval_after']) == 0:\n # write train summaries\n _, current_summary = sess.run(steps, feed_dictionary)\n summary_writer_train.add_summary(current_summary, global_step=global_step)\n performance_timer.stop_timer(PerformanceTimer.TimerType.TRAIN)\n # write test loss\n if epoch > 0:\n performance_timer.start_timer(PerformanceTimer.TimerType.TEST)\n for test_batch in test_iterator:\n # run one iteration\n summary_writer_test.add_summary(\n sess.run(steps[-1], cache.make_feed_dictionary(test_batch, None)),\n global_step=global_step\n )\n break\n performance_timer.stop_timer(PerformanceTimer.TimerType.TEST)\n else:\n sess.run(steps[:-1], feed_dictionary)\n performance_timer.stop_timer(PerformanceTimer.TimerType.TRAIN)\n if ((global_step + 1) % config['general']['save_model_every_train_steps']) == 0:\n # save model\n saver.save_model(sess, global_step=global_step)\n\n global_step += 1\n\n eval_trajectory(sess, summary_writer_trajectory, epoch)\n performance_timer.print_state()\n\n # at end - save model\n saver.save_model(sess, global_step=global_step)\n","sub_path":"scripts/supervised_trainer.py","file_name":"supervised_trainer.py","file_ext":"py","file_size_in_byte":11521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"427602328","text":"def read_file(f):\n '''\n Reads in a file line by line, creating an array of strings.\n '''\n urls = []\n url = ''\n for line in f:\n url = line.strip()\n if url != '':\n urls.append(url)\n return urls","sub_path":"reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"445049375","text":"import bpy\nimport os\nfrom .functions import *\n\n\n#class CAMERA_PH_presets(Menu):\n# bl_label = \"cameras presets\"\n# preset_subdir = \"ph_camera\"\n# preset_operator = \"script.execute_preset\"\n# COMPAT_ENGINES = {'BLENDER_RENDER', 'BLENDER_GAME'}\n# draw = Menu.draw_preset\n\n\nclass VIEW3D_OT_tex_to_material(bpy.types.Operator):\n \"\"\"Create texture materials for images assigned in UV editor\"\"\"\n bl_idname = \"view3d.tex_to_material\"\n bl_label = \"Texface Images to Material/Texture (Material Utils)\"\n bl_options = {'REGISTER', 'UNDO'}\n\n @classmethod\n def poll(cls, context):\n return context.active_object is not None\n\n def execute(self, context):\n if context.selected_editable_objects:\n tex_to_mat()\n return {'FINISHED'}\n else:\n self.report({'WARNING'},\n \"No editable selected objects, could not finish\")\n return {'CANCELLED'}\n\nclass OBJECT_OT_IsometricScene(bpy.types.Operator):\n bl_idname = \"isometric.scene\"\n bl_label = \"Isometric scene\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n set_up_scene(3000,3000,True)\n return {'FINISHED'}\n\nclass OBJECT_OT_Canon6Dscene(bpy.types.Operator):\n bl_idname = \"canon6d.scene\"\n bl_label = \"Canon 6D scene\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n set_up_scene(5472,3648,False)\n return {'FINISHED'}\n \nclass OBJECT_OT_nikond3200scene(bpy.types.Operator):\n bl_idname = \"nikond3200.scene\"\n bl_label = \"Nikon d3200 scene\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n set_up_scene(4512,3000,False)\n return {'FINISHED'}\n\nclass OBJECT_OT_nikond320018mm(bpy.types.Operator):\n bl_idname = \"nikond320018mm.camera\"\n bl_label = \"Set as nikond3200 18mm\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n selection = bpy.context.selected_objects\n bpy.ops.object.select_all(action='DESELECT')\n for obj in selection:\n set_up_lens(obj,23.2,15.4,18)\n return {'FINISHED'}\n\nclass OBJECT_OT_Canon6D35(bpy.types.Operator):\n bl_idname = \"canon6d35mm.camera\"\n bl_label = \"Set as Canon 6D 35mm\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n selection = bpy.context.selected_objects\n bpy.ops.object.select_all(action='DESELECT')\n for obj in selection:\n set_up_lens(obj,35.8,23.9,35)\n return {'FINISHED'}\n\nclass OBJECT_OT_Canon6D24(bpy.types.Operator):\n bl_idname = \"canon6d24mm.camera\"\n bl_label = \"Set as Canon 6D 14mm\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n selection = bpy.context.selected_objects\n bpy.ops.object.select_all(action='DESELECT')\n for obj in selection:\n set_up_lens(obj,35.8,23.9,24)\n return {'FINISHED'}\n\nclass OBJECT_OT_Canon6D14(bpy.types.Operator):\n bl_idname = \"canon6d14mm.camera\"\n bl_label = \"Set as Canon 6D 14mm\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n selection = bpy.context.selected_objects\n bpy.ops.object.select_all(action='DESELECT')\n for obj in selection:\n set_up_lens(obj,35.8,23.9,14.46)\n return {'FINISHED'}\n\nclass OBJECT_OT_BetterCameras(bpy.types.Operator):\n bl_idname = \"better.cameras\"\n bl_label = \"Better Cameras\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n selection = bpy.context.selected_objects\n bpy.ops.object.select_all(action='DESELECT')\n for cam in selection:\n cam.select = True\n cam.data.show_limits = True\n cam.data.clip_start = 0.5\n cam.data.clip_end = 4\n cam.scale[0] = 0.1\n cam.scale[1] = 0.1\n cam.scale[2] = 0.1\n return {'FINISHED'}\n\nclass OBJECT_OT_NoBetterCameras(bpy.types.Operator):\n bl_idname = \"nobetter.cameras\"\n bl_label = \"Disable Better Cameras\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n selection = bpy.context.selected_objects\n bpy.ops.object.select_all(action='DESELECT')\n for cam in selection:\n cam.select = True\n cam.data.show_limits = False\n return {'FINISHED'}\n\n#______________________________________________________________\n\nclass OBJECT_OT_CreateCameraImagePlane(bpy.types.Operator):\n \"\"\"Create image plane for camera\"\"\"\n bl_idname= \"object.createcameraimageplane\"\n bl_label=\"Camera Image Plane\"\n bl_options={'REGISTER', 'UNDO'}\n def SetupDriverVariables(self, driver, imageplane):\n camAngle = driver.variables.new()\n camAngle.name = 'camAngle'\n camAngle.type = 'SINGLE_PROP'\n camAngle.targets[0].id = imageplane.parent\n camAngle.targets[0].data_path=\"data.angle\"\n\n depth = driver.variables.new()\n depth.name = 'depth'\n depth.type = 'TRANSFORMS'\n depth.targets[0].id = imageplane\n depth.targets[0].data_path = 'location'\n depth.targets[0].transform_type = 'LOC_Z'\n depth.targets[0].transform_space = 'LOCAL_SPACE'\n\n def SetupDriversForImagePlane(self, imageplane):\n driver = imageplane.driver_add('scale',1).driver\n driver.type = 'SCRIPTED'\n self.SetupDriverVariables( driver, imageplane)\n #driver.expression =\"-depth*math.tan(camAngle/2)*resolution_y*pixel_y/(resolution_x*pixel_x)\"\n driver.expression =\"-depth*tan(camAngle/2)*bpy.context.scene.render.resolution_y * bpy.context.scene.render.pixel_aspect_y/(bpy.context.scene.render.resolution_x * bpy.context.scene.render.pixel_aspect_x)\"\n driver = imageplane.driver_add('scale',0).driver\n driver.type= 'SCRIPTED'\n self.SetupDriverVariables( driver, imageplane)\n driver.expression =\"-depth*tan(camAngle/2)\"\n\n # get selected camera (might traverse children of selected object until a camera is found?)\n # for now just pick the active object\n \n\n def createImagePlaneForCamera(self, camera):\n imageplane = None\n try:\n depth = 10\n\n #create imageplane\n bpy.ops.mesh.primitive_plane_add()#radius = 0.5)\n imageplane = bpy.context.active_object\n cameraname = correctcameraname(camera.name)\n imageplane.name = (\"objplane_\"+cameraname)\n bpy.ops.object.parent_set(type='OBJECT', keep_transform=False)\n bpy.ops.object.editmode_toggle()\n bpy.ops.mesh.select_all(action='TOGGLE')\n bpy.ops.transform.resize( value=(0.5,0.5,0.5))\n bpy.ops.uv.smart_project(angle_limit=66,island_margin=0, user_area_weight=0)\n bpy.ops.uv.select_all(action='TOGGLE')\n bpy.ops.transform.rotate(value=1.5708, axis=(0,0,1) )\n bpy.ops.object.editmode_toggle()\n\n imageplane.location = (0,0,-depth)\n imageplane.parent = camera\n\n #calculate scale\n #REPLACED WITH CREATING EXPRESSIONS\n self.SetupDriversForImagePlane(imageplane)\n\n #setup material\n if( len( imageplane.material_slots) == 0 ):\n bpy.ops.object.material_slot_add()\n #imageplane.material_slots.\n bpy.ops.material.new()\n mat_index = len(bpy.data.materials)-1\n imageplane.material_slots[0].material = bpy.data.materials[mat_index]\n material = imageplane.material_slots[0].material\n # if not returned by new use imgeplane.material_slots[0].material\n material.name = 'mat_imageplane_'+cameraname\n\n material.use_nodes = False\n\n\n activename = bpy.path.clean_name(bpy.context.scene.objects.active.name)\n\n undistortedpath = bpy.context.scene.BL_undistorted_path\n\n if not undistortedpath:\n raise Exception(\"Hey Buddy, you have to set the undistorted images path !\")\n\n bpy.context.object.data.uv_layers.active.data[0].image = bpy.data.images.load(undistortedpath+cameraname)\n\n bpy.ops.view3d.tex_to_material()\n\n except Exception as e:\n imageplane.select=False\n camera.select = True\n raise e\n return {'FINISHED'}\n\n def execute(self, context):\n# camera = bpy.context.active_object #bpy.data.objects['Camera']\n scene = context.scene\n undistortedpath = bpy.context.scene.BL_undistorted_path\n cam_ob = bpy.context.scene.camera\n\n if not undistortedpath:\n raise Exception(\"Set the Undistort path before to activate this command\")\n else:\n obj_exists = False\n for obj in cam_ob.children:\n if obj.name.startswith(\"objplane_\"):\n obj.hide = False\n obj_exists = True\n bpy.ops.object.select_all(action='DESELECT')\n scene.objects.active = obj\n obj.select_set(True)\n return {'FINISHED'}\n if obj_exists is False:\n camera = bpy.context.scene.camera\n return self.createImagePlaneForCamera(camera)\n\nclass OBJECT_OT_paintcam(bpy.types.Operator):\n bl_idname = \"paint.cam\"\n bl_label = \"Paint selected from current cam\"\n bl_options = {\"REGISTER\", \"UNDO\"}\n\n def execute(self, context):\n\n scene = context.scene\n undistortedpath = bpy.context.scene.BL_undistorted_path\n cam_ob = bpy.context.scene.camera\n\n if not undistortedpath:\n raise Exception(\"Set the Undistort path before to activate this command\")\n else:\n for obj in cam_ob.children:\n if obj.name.startswith(\"objplane_\"):\n obj.hide = True\n bpy.ops.paint.texture_paint_toggle()\n bpy.context.space_data.show_only_render = True\n bpy.ops.image.project_edit()\n obj_camera = bpy.context.scene.camera\n \n undistortedphoto = undistortedpath+correctcameraname(obj_camera.name)\n cleanpath = bpy.path.abspath(undistortedphoto)\n bpy.ops.image.external_edit(filepath=cleanpath)\n\n bpy.context.space_data.show_only_render = False\n bpy.ops.paint.texture_paint_toggle()\n\n return {'FINISHED'}\n\nclass OBJECT_OT_applypaintcam(bpy.types.Operator):\n bl_idname = \"applypaint.cam\"\n bl_label = \"Apply paint\"\n bl_options = {\"REGISTER\"}\n\n def execute(self, context):\n bpy.ops.paint.texture_paint_toggle()\n bpy.ops.image.project_apply()\n bpy.ops.paint.texture_paint_toggle()\n return {'FINISHED'}\n\n\n","sub_path":"All_In_One/addons/3D-survey-collection-master/PhotogrTool.py","file_name":"PhotogrTool.py","file_ext":"py","file_size_in_byte":10677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"108329813","text":"# -*- coding: utf-8 -*-\nfrom operator import itemgetter\n\nfrom cgi import escape\nfrom dateutil.parser import parse\nfrom dateutil.tz import gettz, UTC\nfrom flask_babelex import lazy_gettext as _\nfrom sqlalchemy import Integer, and_, false, or_, true\nfrom sqlalchemy.dialects.postgresql import array\nfrom wtforms import widgets\nfrom wtforms.compat import text_type\nfrom wtforms.widgets import html_params, HTMLString\nfrom wtforms_alchemy.fields import QuerySelectField\n\nfrom apollo import models, services\nfrom apollo.core import BooleanFilter, CharFilter, ChoiceFilter, FilterSet\nfrom apollo.helpers import _make_choices\nfrom apollo.settings import TIMEZONE\n\nAPP_TZ = gettz(TIMEZONE)\n\n\nclass TagLookupFilter(ChoiceFilter):\n def __init__(self, *args, **kwargs):\n self.contains = kwargs.pop('contains', None)\n super().__init__(*args, **kwargs)\n\n def filter(self, query, value, **kwargs):\n if value:\n if value == 'NULL':\n condition = (models.Submission.data[self.name] == None) # noqa\n elif value == 'NOT_NULL':\n condition = (models.Submission.data[self.name] != None) # noqa\n else:\n condition = (models.Submission.data[self.name] == value)\n\n return (condition, None)\n elif self.contains:\n condition = (models.Submission.data[self.name] != None) # noqa\n return (condition, None)\n\n return (None, None)\n\n\ndef make_submission_sample_filter(location_set_id):\n class SubmissionSampleFilter(ChoiceFilter):\n def __init__(self, *args, **kwargs):\n sample_choices = services.samples.find(\n location_set_id=location_set_id\n ).with_entities(models.Sample.id, models.Sample.name).all()\n\n kwargs['choices'] = _make_choices(sample_choices, _('Sample'))\n super().__init__(*args, **kwargs)\n\n def queryset_(self, query, value, **kwargs):\n if value:\n joined_classes = [mapper.class_ for mapper in query._join_entities]\n if models.Location in joined_classes:\n query1 = query\n else:\n query1 = query.join(models.Submission.location)\n query2 = query1.join(\n models.samples_locations,\n models.samples_locations.c.location_id == models.Location.id # noqa\n ).join(\n models.Sample,\n models.samples_locations.c.sample_id == models.Sample.id\n )\n return query2.filter(models.Sample.id == value)\n\n return query\n\n return SubmissionSampleFilter\n\n\ndef make_base_submission_filter(event):\n class BaseSubmissionFilterSet(FilterSet):\n sample = make_submission_sample_filter(event.location_set_id)()\n\n return BaseSubmissionFilterSet\n\n\nclass IncidentStatusFilter(ChoiceFilter):\n def __init__(self, *args, **kwargs):\n kwargs['choices'] = (\n ('', _('All Incidents')),\n ('NULL', _('Unmarked Incidents')),\n ('confirmed', _('Confirmed Incidents')),\n ('rejected', _('Rejected Incidents')),\n ('citizen', _('Citizen Report Incidents')),\n )\n super().__init__(*args, **kwargs)\n\n def filter(self, query, value, **kwargs):\n if value:\n if value == 'NULL':\n return (models.Submission.incident_status == None, None) # noqa\n\n return (models.Submission.incident_status == value, None)\n\n return (None, None)\n\n\ndef make_submission_analysis_filter(event, form):\n attributes = {}\n if form.form_type == 'INCIDENT':\n attributes['status'] = IncidentStatusFilter(default='confirmed')\n\n return type(\n 'SubmissionAnalysisFilterSet',\n (make_base_submission_filter(event),),\n attributes\n )\n\n\ndef make_incident_location_filter(event, form, tag):\n base_filter_class = make_submission_analysis_filter(event, form)\n\n attributes = {\n tag: TagLookupFilter(\n choices=(('NOT_NULL', ''),),\n contains=True,\n default='NOT_NULL',\n widget=widgets.HiddenInput()\n )\n }\n\n return type(\n 'CriticalIncidentLocationFilterSet',\n (base_filter_class,),\n attributes)\n\n\nclass FormGroupFilter(ChoiceFilter):\n def __init__(self, *args, **kwargs):\n self.formobj = kwargs.pop('form')\n self.group = kwargs.pop('group')\n super().__init__(*args, **kwargs)\n\n def filter(self, query, value, **kwargs):\n group_tags = self.formobj.get_group_tags(self.group['name'])\n\n if value == '1':\n # Partial\n if group_tags:\n constraint = and_(\n ~models.Submission.data.has_all(array(group_tags)),\n models.Submission.data.has_any(array(group_tags))\n )\n else:\n constraint = false()\n elif value == '2':\n # Missing\n if group_tags:\n constraint = or_(\n ~models.Submission.data.has_any(array(group_tags)),\n models.Submission.data == None # noqa\n )\n else:\n constraint = true()\n elif value == '3':\n # Complete\n if group_tags:\n constraint = models.Submission.data.has_all(array(group_tags))\n else:\n constraint = false()\n elif value == '4':\n # Conflict\n if group_tags:\n query_params = [\n models.Submission.conflicts.has_key(tag) # noqa\n for tag in group_tags\n ]\n constraint = or_(*query_params)\n else:\n constraint = false()\n else:\n constraint = None\n\n if constraint is None:\n return (None, None)\n else:\n form_ = kwargs['form']\n if form_.data and form_.data.get('conjunction') is True:\n # OR conjunction\n return (None, constraint)\n else:\n # AND conjunction\n return (constraint, None)\n\n\nclass FieldOptionFilter(ChoiceFilter):\n def filter(self, query, value, **kwargs):\n if value:\n return (\n models.Submission.data[self.name].astext.cast(\n Integer) == int(value),\n None\n )\n\n return (None, None)\n\n\nclass FieldValueFilter(CharFilter):\n pass\n\n\nclass ParticipantIDFilter(CharFilter):\n def filter(self, query, value, **kwargs):\n if value:\n return (\n models.Participant.participant_id == value,\n None\n )\n\n return (None, None)\n\n\nclass SubmissionQuarantineStatusFilter(ChoiceFilter):\n def filter(self, query, value, **kwargs):\n if value and value == 'N':\n return (\n or_(\n models.Submission.quarantine_status == None, # noqa\n models.Submission.quarantine_status == ''),\n None\n )\n elif value in ('A', 'R'):\n return (models.Submission.quarantine_status == value, None)\n elif value == 'AR':\n return (\n or_(\n models.Submission.quarantine_status == 'A',\n models.Submission.quarantine_status == 'R'\n ),\n None\n )\n else:\n return (None, None)\n\n\nclass SubmissionSenderVerificationFilter(ChoiceFilter):\n def filter(self, query, value, **kwargs):\n if value and value == '1':\n return (\n models.Submission.sender_verified == True, # noqa\n None\n )\n elif value:\n return (\n models.Submission.sender_verified == False, # noqa\n None\n )\n\n return (None, None)\n\n\nclass OnlineStatusFilter(ChoiceFilter):\n def filter(self, query, value, **kwargs):\n if value and value == '1':\n return (\n models.Submission.unreachable == True, # noqa\n None\n )\n elif value:\n return (\n models.Submission.unreachable == False, # noqa\n None\n )\n\n return (None, None)\n\n\nclass DateFilter(CharFilter):\n def filter(self, query, value, **kwargs):\n if value:\n try:\n dt = parse(value, dayfirst=True)\n except (OverflowError, ValueError):\n return (None, None)\n\n dt = dt.replace(tzinfo=APP_TZ)\n upper_bound = dt.replace(hour=23, minute=59, second=59).astimezone(\n UTC).replace(tzinfo=None)\n lower_bound = dt.replace(hour=0, minute=0, second=0).astimezone(\n UTC).replace(tzinfo=None)\n\n return (\n and_(\n models.Submission.participant_updated >= lower_bound,\n models.Submission.participant_updated <= upper_bound\n ),\n None\n )\n\n return (None, None)\n\n\nclass LocationSelectWidget(widgets.Select):\n @classmethod\n def render_option(cls, value, label, selected, **kwargs):\n options = dict(kwargs, value=value)\n if selected:\n options['selected'] = True\n if hasattr(label, 'location_type'):\n return HTMLString('' % (\n html_params(**options),\n escape(text_type(label.name)),\n escape(text_type(label.location_type))))\n else:\n return HTMLString('' % (\n html_params(**options),\n escape(text_type(label))))\n\n\nclass ParticipantSelectWidget(widgets.Select):\n @classmethod\n def render_option(cls, value, label, selected, **kwargs):\n options = dict(kwargs, value=value)\n if selected:\n options['selected'] = True\n if hasattr(label, 'participant_id'):\n return HTMLString('' % (\n html_params(**options),\n escape(text_type(label.participant_id)),\n escape(text_type(label.name))))\n else:\n return HTMLString('' % (\n html_params(**options),\n escape(text_type(label))))\n\n\nclass LocationQuerySelectField(QuerySelectField):\n widget = LocationSelectWidget()\n\n def process_formdata(self, valuelist):\n if valuelist and valuelist[0] and valuelist[0] != '__None':\n self.query = models.Location.query.filter(\n models.Location.id == valuelist[0])\n return super(LocationQuerySelectField, self).process_formdata(\n valuelist)\n\n\nclass ParticipantQuerySelectField(QuerySelectField):\n widget = ParticipantSelectWidget()\n\n def process_formdata(self, valuelist):\n if valuelist and valuelist[0] and valuelist[0] != '__None':\n self.query = models.Participant.query.filter(\n models.Participant.id == valuelist[0])\n return super(ParticipantQuerySelectField, self).process_formdata(\n valuelist)\n\n\nclass FormSerialNumberFilter(CharFilter):\n def filter(self, query, value, **kwargs):\n if value:\n return (\n models.Submission.serial_no == value,\n None\n )\n\n return (None, None)\n\n\ndef make_submission_location_filter(location_set_id):\n class AJAXLocationFilter(ChoiceFilter):\n field_class = LocationQuerySelectField\n\n def __init__(self, *args, **kwargs):\n kwargs['query_factory'] = lambda: []\n kwargs['get_pk'] = lambda i: i.id\n\n super().__init__(*args, **kwargs)\n\n def queryset_(self, query, value, **kwargs):\n if value:\n location_query = models.Location.query.with_entities(\n models.Location.id\n ).join(\n models.LocationPath,\n models.Location.id == models.LocationPath.descendant_id\n ).filter(models.LocationPath.ancestor_id == value.id)\n\n return query.filter(\n models.Submission.location_id.in_(location_query))\n\n return query\n\n return AJAXLocationFilter\n\n\ndef make_dashboard_filter(event):\n attributes = {}\n attributes['location'] = make_submission_location_filter(\n event.location_set_id)()\n attributes['sample'] = make_submission_sample_filter(\n event.location_set_id)()\n\n return type(\n 'SubmissionFilterSet',\n (make_base_submission_filter(event),),\n attributes)\n\n\ndef make_submission_list_filter(event, form):\n attributes = {}\n form._populate_field_cache()\n\n if form.data and form.data.get('groups'):\n if form.form_type == 'INCIDENT':\n option_fields = [\n f for f in form._field_cache.values()\n if f['type'] == 'select']\n for field in option_fields:\n choices = _make_choices(sorted(\n ((v, '{} - {}'.format(field['tag'], k)) for k, v in\n field['options'].items()),\n key=itemgetter(0)\n ), field['tag'])\n attributes[field['tag']] = FieldOptionFilter(choices=choices)\n\n for group in form.data.get('groups'):\n field_name = '{}__{}'.format(form.id, group['slug'])\n choices = [\n ('', _('%(group)s Status', group=group['name'])),\n ('1', _('%(group)s Partial', group=group['name'])),\n ('2', _('%(group)s Missing', group=group['name'])),\n ('3', _('%(group)s Complete', group=group['name'])),\n ('4', _('%(group)s Conflict', group=group['name']))\n ]\n attributes[field_name] = FormGroupFilter(\n choices=choices, form=form, group=group)\n\n if form.form_type == 'INCIDENT':\n attributes['status'] = IncidentStatusFilter()\n elif form.form_type in ['CHECKLIST', 'SURVEY']:\n attributes['quarantine_status'] = SubmissionQuarantineStatusFilter(\n choices=(\n ('', _('Quarantine Status')),\n ('A', _('Quarantine All')),\n ('R', _('Quarantine Results')),\n ('AR', _('Quarantine All + Results')),\n ('N', _('Quarantine None')),\n ), default='')\n attributes['sender_verification'] = SubmissionSenderVerificationFilter(\n choices=(\n ('', _('Phone Confirmation')),\n ('1', _('Phone Confirmed')),\n ('2', _('Phone Unconfirmed'))\n ))\n\n attributes['participant_id'] = ParticipantIDFilter()\n attributes['location'] = make_submission_location_filter(\n event.location_set_id)()\n attributes['conjunction'] = BooleanFilter(\n label=_('Optional Inclusion')\n )\n attributes['online_status'] = OnlineStatusFilter(\n choices=(\n ('', _('Signal Status')),\n ('0', _('Signal')),\n ('1', _('No Signal'))\n )\n )\n attributes['date'] = DateFilter()\n attributes['fsn'] = FormSerialNumberFilter()\n\n return type(\n 'SubmissionFilterSet',\n (make_base_submission_filter(event),),\n attributes)\n","sub_path":"apollo/submissions/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":15517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"271226301","text":"# -*- coding: utf-8 -\n#\n# This file is part of the restpose python module, released under the MIT\n# license. See the COPYING file for more information.\n\nfrom .helpers import RestPoseTestCase\nfrom .. import Server, CheckPointExpiredError, ResourceNotFound\nfrom ..client import CheckPoint\nimport sys\n\nclass IndexTest(RestPoseTestCase):\n\n def test_delete_db(self):\n \"\"\"Test that deleting a database functions correctly.\n\n \"\"\"\n coll = Server().collection(\"test_coll\")\n coll.delete()\n doc = { 'text': 'Hello world', 'tag': 'A tag', 'cat': \"greeting\",\n 'empty': \"\" }\n coll.add_doc(doc, doc_type=\"blurb\", doc_id=\"1\")\n self.wait(coll)\n self.assertEqual(coll.get_doc(\"blurb\", \"1\").data,\n dict(\n cat = ['greeting'],\n empty = [''],\n id = ['1'],\n tag = ['A tag'],\n text = ['Hello world'],\n type = ['blurb'],\n ))\n\n self.assertTrue('test_coll' in Server().collections)\n\n coll.delete()\n\n # Need to set commit=False, or the checkpoint re-creates the\n # collection.\n self.wait(coll, commit=False)\n self.assertTrue('test_coll' not in Server().collections)\n msg = None\n try:\n coll.get_doc(\"blurb\", \"1\").data\n except ResourceNotFound:\n e = sys.exc_info()[1] # Python 2/3 compatibility\n msg = e.msg\n self.assertEqual(msg, 'No collection of name \"test_coll\" exists')\n\n def test_delete_doc(self):\n \"\"\"Test that deleting a document functions correctly.\n\n \"\"\"\n coll = Server().collection(\"test_coll\")\n coll.delete()\n\n # Check deleting a document via the collection.\n doc = { 'text': 'Hello world', 'tag': 'A tag', 'cat': \"greeting\",\n 'empty': \"\" }\n coll.add_doc(doc, doc_type=\"blurb\", doc_id=\"1\")\n self.wait(coll)\n self.assertEqual(coll.get_doc(\"blurb\", \"1\").data,\n dict(\n cat = ['greeting'],\n empty = [''],\n id = ['1'],\n tag = ['A tag'],\n text = ['Hello world'],\n type = ['blurb'],\n ))\n\n coll.delete_doc(doc_type=\"blurb\", doc_id=\"1\")\n self.wait(coll)\n msg = None\n try:\n coll.get_doc(\"blurb\", \"1\").data\n except ResourceNotFound:\n e = sys.exc_info()[1] # Python 2/3 compatibility\n msg = e.msg\n self.assertEqual(msg, 'No document found of type \"blurb\" and id \"1\"')\n\n # Check deleting a document via the type object.\n t = coll.doc_type(\"blurb\")\n t.add_doc(doc, doc_id=\"1\")\n self.wait(coll)\n self.assertEqual(t.get_doc(\"1\").data,\n dict(\n cat = ['greeting'],\n empty = [''],\n id = ['1'],\n tag = ['A tag'],\n text = ['Hello world'],\n type = ['blurb'],\n ))\n\n t.delete_doc(doc_id=\"1\")\n self.wait(coll)\n msg = None\n try:\n t.get_doc(\"1\").data\n except ResourceNotFound:\n e = sys.exc_info()[1] # Python 2/3 compatibility\n msg = e.msg\n self.assertEqual(msg, 'No document found of type \"blurb\" and id \"1\"')\n\n def test_index_id_or_type_errors(self):\n \"\"\"Test that errors due to bad ID or type specifications when indexing\n are reported correctly.\n\n \"\"\"\n coll = Server().collection(\"test_coll\")\n coll.delete()\n doc = { 'text': 'test doc', 'type': 'foo', 'id': '1' }\n # All the following combinations should be successful.\n coll.add_doc(doc)\n doc['id'] = 2\n coll.add_doc(doc, doc_type='foo')\n doc['id'] = 3\n coll.add_doc(doc, doc_id=3)\n doc['id'] = 4\n coll.add_doc(doc, doc_id=\"4\")\n doc['id'] = 5\n coll.add_doc(doc, doc_type=\"foo\", doc_id=5)\n doc['id'] = \"6\"\n coll.add_doc(doc, doc_type=\"foo\", doc_id=6)\n\n coll.add_doc(doc, doc_type='oof1') # Error: mismatched types\n coll.add_doc(doc, doc_id=12) # Error: mismatched ids\n coll.doc_type('oof2').add_doc(doc) # Error: mismatched types\n coll.add_doc(doc, doc_type='oof3', doc_id=13) # Error: mismatched types\n coll.doc_type('oof4').add_doc(doc, doc_id=14) # Error: mismatched types\n coll.doc_type('foo').add_doc(doc, doc_id=15) # Error: mismatched ids\n coll.add_doc(doc, doc_id=16) # Error: mismatched ids\n doc['id'] = [7,8]\n coll.add_doc(doc)\n del doc['type']\n coll.add_doc(doc) # Error: no type specified\n\n chk = coll.checkpoint().wait()\n self.assertEqual(chk.total_errors, 9)\n self.assertEqual(len(chk.errors), 9)\n def mkkey(x): return x.get('doc_id', '') + x.get('doc_type', '') + x.get('msg')\n expected_errors = [\n {'msg': 'Indexing error in field \"type\": \"No document type supplied or stored in document.\"'},\n {'msg': 'Indexing error in field \"type\": \"Document type supplied differs from that inside document.\"', 'doc_type': 'oof1'},\n {'msg': 'Indexing error in field \"id\": \"Document id supplied (\\'12\\') differs from that inside document (\\'6\\').\"', 'doc_id': '12'},\n {'msg': 'Indexing error in field \"type\": \"Document type supplied differs from that inside document.\"', 'doc_type': 'oof2'},\n {'msg': 'Indexing error in field \"type\": \"Document type supplied differs from that inside document.\"', 'doc_type': 'oof3', 'doc_id': '13'},\n {'msg': 'Indexing error in field \"type\": \"Document type supplied differs from that inside document.\"', 'doc_type': 'oof4', 'doc_id': '14'},\n {'msg': 'Indexing error in field \"id\": \"Document id supplied (\\'15\\') differs from that inside document (\\'6\\').\"', 'doc_type': 'foo', 'doc_id': '15'},\n {'msg': 'Indexing error in field \"id\": \"Document id supplied (\\'16\\') differs from that inside document (\\'6\\').\"', 'doc_id': '16'},\n {'msg': 'Indexing error in field \"id\": \"Multiple ID values provided - must have only one\"'},\n ]\n self.assertEqual(sorted(chk.errors, key=mkkey),\n sorted(expected_errors, key=mkkey))\n\n self.assertEqual(coll.get_doc('foo', '1').data,\n dict(text=['test doc'], type=['foo'], id=['1']))\n self.assertEqual(coll.get_doc('foo', '2').data,\n dict(text=['test doc'], type=['foo'], id=[2]))\n self.assertEqual(coll.get_doc('foo', '3').data,\n dict(text=['test doc'], type=['foo'], id=[3]))\n self.assertEqual(coll.get_doc('foo', '4').data,\n dict(text=['test doc'], type=['foo'], id=[4]))\n self.assertEqual(coll.get_doc('foo', '5').data,\n dict(text=['test doc'], type=['foo'], id=[5]))\n self.assertEqual(coll.get_doc('foo', '6').data,\n dict(text=['test doc'], type=['foo'], id=[\"6\"]))\n\n def test_checkpoint(self):\n coll = Server().collection(\"test_coll\")\n\n # Check that accessing the id works.\n c = coll.checkpoint(commit=False)\n id = c.check_id\n self.assertTrue(len(id) > 10)\n\n c = CheckPoint(coll, {'checkid': 'fake_checkid'})\n self.assertEqual(c.check_id, 'fake_checkid')\n self.assertRaises(CheckPointExpiredError, getattr, c, 'reached')\n self.assertRaises(CheckPointExpiredError, getattr, c, 'errors')\n self.assertRaises(CheckPointExpiredError, getattr, c, 'total_errors')\n self.assertRaises(CheckPointExpiredError, c.wait)\n\n def test_custom_config(self):\n coll = Server().collection(\"test_coll\")\n coll.delete()\n self.wait(coll)\n config = coll.config\n self.assertEqual(config['format'], 3)\n self.assertEqual(list(config['types'].keys()), [])\n\n coll.config = {'types': {'foo': {\n 'alpha': {'type': 'text'}\n }}}\n self.wait(coll, [{'msg': 'Setting collection config failed with ' +\n 'RestPose::InvalidValueError: Member format was missing'}])\n self.assertEqual(list(config['types'].keys()), [])\n coll.config = {'format': 3,\n 'types': {'foo': {\n 'alpha': {'type': 'text'}\n }}\n }\n self.wait(coll)\n config = coll.config\n self.assertEqual(config['format'], 3)\n self.assertEqual(list(config['types'].keys()), ['foo'])\n coll.delete()\n self.wait(coll)\n\n def test_get_name(self):\n coll = Server().collection(\"test_coll\")\n self.assertEqual(coll.name, 'test_coll')\n t = coll.doc_type(\"blurb\")\n self.assertEqual(t.name, 'blurb')\n","sub_path":"restpose/unittests/index_test.py","file_name":"index_test.py","file_ext":"py","file_size_in_byte":9166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"309315319","text":"\"\"\"abc fix time\n\nRevision ID: 467de01c9a43\nRevises: 52b433e902c5\nCreate Date: 2020-05-17 22:23:55.044329\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '467de01c9a43'\ndown_revision = '52b433e902c5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('news', sa.Column('timestamp', sa.DateTime(), nullable=True))\n op.create_index(op.f('ix_news_timestamp'), 'news', ['timestamp'], unique=False)\n op.drop_index('ix_news_time', table_name='news')\n op.create_unique_constraint(None, 'news', ['picture'])\n op.drop_column('news', 'time')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('news', sa.Column('time', sa.DATETIME(), nullable=True))\n op.drop_constraint(None, 'news', type_='unique')\n op.create_index('ix_news_time', 'news', ['time'], unique=False)\n op.drop_index(op.f('ix_news_timestamp'), table_name='news')\n op.drop_column('news', 'timestamp')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/467de01c9a43_abc_fix_time.py","file_name":"467de01c9a43_abc_fix_time.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"375684009","text":"from django.urls import path\n\napp_name = 'restApp'\n\nfrom . import views\n\n\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('add_food/', views.add_food, name='add_food'),\n path('edit_food/', views.edit_food, name='edit_food'),\n path('edit_particular_food/', views.edit_particular_food, name='edit_particular_food'),\n path('update_time/', views.update_time, name='update_time'),\n path('update_logo/', views.update_logo, name='update_logo'),\n path('update_location/', views.update_location, name='update_location'),\n]\n","sub_path":"restApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"587604961","text":"#!/usr/bin/env python3\n\n# Google Code Jam\n# Qualification Round 2016\n# Problem D. Fractiles\n# Solution in Python by Smithers\n\ndef tileindex(k, c, s, i):\n n = 1\n for j in range(c):\n n += (i + j * s if i + j * s < k else 0) * (k ** j)\n return n\n\ndef solve(k, c, s):\n if s * c < k:\n return 'IMPOSSIBLE',\n \n return [tileindex(k, c, s, i) for i in range(s)]\n\nfor i in range(int(input())):\n k, c, s = (int(x) for x in input().split())\n print('Case #{}:'.format(i + 1), *solve(k, c, s))\n","sub_path":"solutions_5636311922769920_0/Python/Smithers/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"427766760","text":"# Given an integer array nums , find the sum of the elements between indices i and j ( i ≤ j ), inclusive.\n\n# Example:\n# Given nums = [-2, 0, 3, -5, 2, -1]\n\n# sumRange(0, 2) -> 1\n# sumRange(2, 5) -> -1\n# sumRange(0, 5) -> -3\n# Note:\n# You may assume that the array does not change.\n# There are many calls to sumRange function.\n\ndef range_sum_query(arr):\n\ttotal = [0] * len(arr)\n\n\tfor i in range(len(arr)):\n\t\t#print(total[i - 1])\n\t\ttotal[i] = total[i - 1] + arr[i]\n\n\tprint(total)\n\tprint(sumRange(0, 2, total))\n\tprint(sumRange(2, 5, total))\n\treturn\n\ndef sumRange(i, j, total):\n\treturn total[j] if i == 0 else total[j] - total[i - 1]\n\nprint(range_sum_query([1, 2, 3, 5, 2, 1]))\n","sub_path":"Facebook/RangeSumQuery.py","file_name":"RangeSumQuery.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"591786133","text":"# Replace spaces in the middle of a string with \"%20\" assuming the end of the\n# string contains twice as many spaces as are in the middle.\n\n\ndef escape_spaces_1(string):\n return string.strip().replace(\" \", \"%20\")\n\n#work backwards\ndef urlify(string, length):\n '''function replaces single spaces with %20 and removes trailing spaces'''\n new_index = len(string)\n print(new_index)\n\n for i in reversed(range(length)):\n if string[i] == ' ':\n # Replace spaces\n string[new_index - 3:new_index] = '%20'\n print(string)\n new_index -= 3\n else:\n # Move characters\n string[new_index - 1] = string[i]\n print('else',string)\n new_index -= 1\n\n return ''.join(string)\n\ntestString = list('much ado about nothing ')\nprint(testString)\nprint(urlify(testString, 22))\n","sub_path":"CTCI_Python/URLify.py","file_name":"URLify.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"600817593","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.init as init\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\n\nbatch_size = 256\nlearning_rate = 0.0002\nnum_epoch = 10\n\nmnist_train = dset.MNIST(\"./\", train=True, transform=transforms.ToTensor(), target_transform=None, download=True)\nmnist_test = dset.MNIST(\"./\", train=False, transform=transforms.ToTensor(), target_transform=None, download=True)\nprint(mnist_train.__getitem__(0)[0].size(), mnist_train.__len__())\nprint(mnist_test.__getitem__(0)[0].size(), mnist_test.__len__())\n\ntrain_loader = torch.utils.data.DataLoader(mnist_train,batch_size=batch_size, shuffle=True,num_workers=2,drop_last=True)\ntest_loader = torch.utils.data.DataLoader(mnist_test,batch_size=batch_size, shuffle=False,num_workers=2,drop_last=True)\n\nclass CNN(nn.Module):\n def __init__(self):\n super(CNN,self).__init__()\n self.layer = nn.Sequential(\n nn.Conv2d(1,16,3,padding=1),\n nn.ReLU(),\n nn.Conv2d(16,32,3,padding=1),\n nn.ReLU(),\n nn.MaxPool2d(2,2),\n nn.Conv2d(32,64,3,padding=1),\n nn.ReLU(),\n nn.MaxPool2d(2,2)\n )\n self.fc_layer = nn.Sequential(\n nn.Linear(64*7*7,100),\n nn.ReLU(),\n nn.Linear(100,10)\n )\n\n # weight 초기화\n # 모델의 모듈을 차례대로 불러옴\n for m in self.modules():\n # 모듈이 nn.Conv2d인 경우\n if isinstance(m, nn.Conv2d):\n \"\"\"\n # 작은 숫자 초기화\n # 가중치를 평균 0, 편차 0.02로 초기화\n # 편차를 0으로 초기화\n m.weight.data.normal_(0.0, 0.02)\n m.bias.data.fill_(0)\n\n # Xavier Initialization\n init.xavier_normal(m.weight.data)\n m.bias.data.fill_(0)\n \"\"\"\n\n # Kaiming Initialization\n init.kaiming_normal_(m.weight.data)\n m.bias.data.fill_(0)\n\n # 모듈이 nn.Linear인 경우\n elif isinstance(m, nn.Linear):\n \"\"\"\n # 작은 숫자 초기화\n # 가중치를 평균 0, 편차 0.02로 초기화\n # 편차를 0으로 초기화\n m.weight.data.normal_(0.0, 0.02)\n m.bias.data.fill_(0)\n\n # Xavier Initialization\n init.xavier_normal(m.weight.data)\n m.bias.data.fill_(0)\n \"\"\"\n\n # Kaiming Initialization\n init.kaiming_normal_(m.weight.data)\n m.bias.data.fill_(0)\n\n\n def forward(self, x):\n out = self.layer(x)\n out = out.view(batch_size, -1)\n out = self.fc_layer(out)\n return out\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\n\nmodel = CNN().to(device)\nloss_func = nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)\n\nfor i in range(num_epoch):\n for j, [image, label] in enumerate(train_loader):\n x = image.to(device)\n y_ = label.to(device)\n\n optimizer.zero_grad()\n output = model.forward(x)\n loss = loss_func(output, y_)\n loss.backward()\n optimizer.step()\n\n if i % 10 == 0:\n print(loss)\n\nparam_list = list(model.parameters())\nprint(param_list)\n\ncorrect = 0\ntotal = 0\n\nwith torch.no_grad():\n for image,label in test_loader:\n x = image.to(device)\n y_= label.to(device)\n\n output = model.forward(x)\n _,output_index = torch.max(output,1)\n\n total += label.size(0)\n correct += (output_index == y_).sum().float()\n\n print(\"Accuracy of Test Data: {}\".format(100*correct/total))","sub_path":"5. Increasing Accuracy/weight_initialization.py","file_name":"weight_initialization.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"438526199","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom .models import *\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom .forms import CommentForm, PostForm\nfrom django.db.models import Q\nfrom django.views.generic import CreateView\n\ndef get_author(user):\n qs = Author.objects.filter(user=user)\n if qs.exists():\n return qs[0]\n return None\n\ndef search(request):\n queryset = Post.objects.all()\n query = request.GET.get('q')\n if query:\n queryset = queryset.filter(\n Q(title__icontains=query)|\n Q(description__icontains=query)\n ).distinct()\n context = {\n 'queryset': queryset\n }\n return render(request, 'search_results.html', context)\n\ndef index(request):\n categories = Category.objects.all()\n queryset = Post.objects.all()\n paginator = Paginator(queryset, 2)\n page_request_var = 'page'\n page = request.GET.get(page_request_var)\n try:\n paginated_guaryset = paginator.page(page)\n except PageNotAnInteger:\n paginated_guaryset = paginator.page(1)\n except EmptyPage:\n paginated_guaryset = paginator.page(paginator.num_pages)\n context = {\n 'categories': categories,\n 'queryset': paginated_guaryset,\n 'page_request_var': page_request_var\n }\n return render(request, 'index.html', context)\n\ndef blog(request, blog_id):\n categories = Category.objects.all()\n blog = get_object_or_404(Post, id=blog_id)\n form = CommentForm(request.POST or None)\n if request.method == \"POST\":\n if form.is_valid():\n form.instance.user = request.user\n form.instance.post = blog\n form.save()\n return redirect('blog', blog_id=blog_id)\n\n context ={\n 'categories': categories,\n 'blog': blog,\n 'form': form\n }\n return render(request, 'blog.html', context)\n\ndef blog_create(request):\n title = 'Create'\n form = PostForm(request.POST or None, request.FILES or None)\n author = get_author(request.user)\n if request.method == \"POST\":\n if form.is_valid():\n form.instance.author = author\n form.save()\n\n return redirect(reverse('blog', kwargs={\n 'blog_id': form.instance.id\n }))\n context = {\n 'title': title,\n 'form': form\n }\n return render(request, 'post_create.html', context)\n\ndef blog_update(request, blog_id):\n title = 'Update'\n blog = get_object_or_404(Post, id=blog_id)\n form = PostForm(request.POST or None, request.FILES or None, instance=blog)\n author = get_author(request.user)\n if request.method == 'POST':\n if form.is_valid():\n form.instance.author = author\n form.save()\n return redirect(reverse('blog', kwargs={\n 'blog_id': form.instance.id\n }))\n context = {\n 'title': title,\n 'form': form\n }\n return render(request, 'post_create.html', context)\n\ndef blog_delete(request, blog_id):\n blog = get_object_or_404(Post, id=blog_id)\n blog.delete()\n return redirect('index')\n\ndef CategoryView(request, cats):\n category_post = Post.objects.filter(categories__title__contains=cats)\n context ={\n 'cats': cats,\n 'category_post': category_post\n }\n return render(request, 'categories.html', context)\n\nclass AddCategoryView(CreateView):\n model = Category\n template_name = 'add_category.html'\n fields = '__all__'","sub_path":"django_blog/myblog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"426962126","text":"'''\nCreated on Jan 5, 2016\n\n@author: Alex\n'''\n\nfrom geometry import Point\nfrom representative_trajectory_average_inputs import DECIMAL_MAX_DIFF_FOR_EQUALITY\nfrom representative_trajectory_average_inputs import get_representative_trajectory_average_inputs\nfrom representative_line_finding import get_average_vector\nfrom representative_line_finding import get_rotated_segment\n\ndef get_rline_pts(tls_list, min_vline, min_prev_dist):\n segments = list(map(lambda tls: tls.segment, tls_list))\n avg_vec = get_average_vector(segments)\n for tls in tls_list:\n tls.rsegment = get_rotated_segment(tls.segment, -avg_vec.angle)\n inputs = get_representative_trajectory_average_inputs(tls_list, min_vline, min_prev_dist)\n rline_pts = []\n for line_seg_averaging_input in inputs:\n vert_val = get_mean_vertical_coordinate_in_line_segments(line_seg_averaging_input)\n rline_pts.append(Point(line_seg_averaging_input['horizontal_position'], vert_val))\n return [pt.rotated(avg_vec.angle) for pt in rline_pts]\n\ndef interpolate_within_line_segment(line_segment, horizontal_coordinate):\n min_x = min(line_segment.start.x, line_segment.end.x)\n max_x = max(line_segment.start.x, line_segment.end.x)\n \n if not (min_x <= horizontal_coordinate + DECIMAL_MAX_DIFF_FOR_EQUALITY \\\n and max_x >= horizontal_coordinate - DECIMAL_MAX_DIFF_FOR_EQUALITY):\n raise Exception(\"horizontal coordinate \" + str(horizontal_coordinate) + \\\n \" not within horizontal range of line segment\" + \\\n \" with bounds \" + str(min_x) + \" and \" + str(max_x))\n elif line_segment.start.y - line_segment.end.y == 0.0:\n return line_segment.start.y\n elif line_segment.start.x - line_segment.end.x == 0.0:\n return (line_segment.end.y - line_segment.start.y) / 2.0 + line_segment.start.y\n else:\n return float((horizontal_coordinate - line_segment.start.x)) / (line_segment.end.x - line_segment.start.x) * \\\n (line_segment.end.y - line_segment.start.y) + line_segment.start.y \n \ndef line_segment_averaging_set_iterable(line_segments_to_average):\n line_segment_averaging_set = []\n horizontal_coord = line_segments_to_average['horizontal_position']\n for seg in line_segments_to_average['lines']:\n line_segment_averaging_set.append({'horizontal_pos': horizontal_coord, 'line_seg': seg})\n \n return line_segment_averaging_set\n\ndef number_average(iter_ob, func):\n count = len(iter_ob)\n if count == 0:\n raise Exception(\"no input given to take average of\")\n total = 0.0\n for item in iter_ob:\n total += func(item)\n return total / count\n \ndef get_mean_vertical_coordinate_in_line_segments(line_segments_to_average):\n def apply_interpolation_to_line_segment(interpolation_info):\n if interpolation_info['line_seg'] == None or interpolation_info['horizontal_pos'] == None:\n raise Exception(\"nil key. \" + str(interpolation_info) + \" was passed to apply_interpolation_to_line_segment\")\n return interpolate_within_line_segment(interpolation_info['line_seg'], interpolation_info['horizontal_pos'])\n \n return number_average(line_segment_averaging_set_iterable(line_segments_to_average), \\\n apply_interpolation_to_line_segment)","sub_path":"traclus_impl/line_segment_averaging.py","file_name":"line_segment_averaging.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"428470846","text":"import random\n\nclass FlipCoinGame:\n\tdef flip(self):\n\t\treturn random.choice([\"H\",\"T\"])\n\t\n\tdef flipping_loop(self, flips_number):\n\t\ttail_sum = 0\n\t\thead_sum = 0\n\t\tfor i in range(flips_number):\n\t\t\tside = self.flip()\n\t\t\tif side == \"H\":\n\t\t\t\ttail_sum+=1\n\t\t\telse:\n\t\t\t\thead_sum+=1\n\t\n\t\tprint(\"You had %s tails and %s heads.\" %(tail_sum, head_sum))\n\t\n\tdef get_input(self):\n\t\tprint(\"How many times do you want to flip?\")\n\t\n\t\tvalue = input()\n\t\ttry:\n\t\t\treturn int(value)\n\t\texcept ValueError:\n\t\t\tprint(\"Input has to be number!!!\")\n\t\t\tquit()\n\n\tdef start(self):\n\t\tflips_number = self.get_input()\n\t\tself.flipping_loop(flips_number)\n\ngame = FlipCoinGame()\ngame.start()\n","sub_path":"coin.py","file_name":"coin.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"609171751","text":"#!/usr/bin/python\nimport signal\nimport sys\n\nimport time\nimport pyupm_grove as grove\nimport pyupm_ttp223 as ttp223\nimport pyupm_i2clcd as lcd\n\nimport dweepy\n\ndef interruptHandler(signal, frame):\n\tsys.exit(0)\n\nif __name__ == '__main__':\n\tsignal.signal(signal.SIGINT, interruptHandler)\n\n\ttouch = ttp223.TTP223(6)\n\tmyLcd = lcd.Jhd1313m1(0, 0x3E, 0x62)\n\tbutton = grove.GroveButton(8)\n\n\tcount = 0\n\tmyLcd.setColor(0,0,255)\n\n# Read the input and print, waiting 1/2 second between readings\n\twhile 1:\n\t\tcontador={}\n\t\tif button.value():\n\t\t\tcount=count+1\n\t\tif touch.isPressed():\n\t\t\tcount=count-1\n\t\tmyLcd.setCursor(0,0)\n\t\tmyLcd.write('%6d'% count)\n\t\tcontador[\"conteo\"]=count\n\t\tdweepy.dweet_for(\"Legalileo_racso1290\",contador)\n\t\ttime.sleep(0.5)\n\tdel button\n\tdel touch\n","sub_path":"misprogs/prog5.py","file_name":"prog5.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"81424005","text":"# -*- coding: utf-8 -*-\nimport logging\nfrom openerp import tools\nfrom email.header import decode_header\nfrom openerp import SUPERUSER_ID\nfrom openerp.osv import osv, orm, fields\nfrom openerp.tools import html_email_clean\nfrom openerp.tools.translate import _\n_logger = logging.getLogger(__name__)\n\n\nclass mail_message(osv.Model):\n _inherit = 'mail.message'\n _message_read_fields = ['id', 'parent_id', 'model', 'res_id', 'body',\\\n 'subject', 'date', 'to_read', 'email_from',\\\n 'email_to','email_cc', 'type', 'vote_user_ids',\\\n 'attachment_ids', 'author_id', 'partner_ids',\\\n 'record_name']\n _columns = {\n 'email_to': fields.char('To',\n help=\"Email address of the Receiver. \\\n This field is set when no matching partner is found for \\\n incoming emails.\"),\n 'email_cc': fields.char('CC',\n help=\"Email address of the CC. This field is set when no matching \\\n partner is found for incoming emails.\"),\n }\n\n def _message_read_dict(self, cr, uid, message, parent_id=False, \\\n context=None):\n \"\"\" Return a dict representation of the message. This representation is\n used in the JS client code, to display the messages. Partners and\n attachments related stuff will be done in post-processing in batch.\n :param dict message: mail.message browse record\n \"\"\"\n # private message: no model, no res_id\n is_private = False\n if not message.model or not message.res_id:\n is_private = True\n # votes and favorites: res.users ids, no prefetching should be done\n vote_nb = len(message.vote_user_ids)\n has_voted = uid in [user.id for user in message.vote_user_ids]\n\n try:\n body_html = html_email_clean(message.body)\n except Exception:\n body_html = '

Encoding Error :
Unable to convert\\\n this message (id: %s).

' % message.id\n _logger.exception(Exception)\n return {'id': message.id,\n 'type': message.type,\n 'subtype': message.subtype_id.name if \\\n message.subtype_id else False,\n 'body': body_html,\n 'model': message.model,\n 'res_id': message.res_id,\n 'record_name': message.record_name,\n 'subject': message.subject,\n 'date': message.date,\n 'to_read': message.to_read,\n 'parent_id': parent_id,\n 'is_private': is_private,\n 'author_id': False,\n 'is_author': False,\n 'partner_ids': [],\n 'vote_nb': vote_nb,\n 'has_voted': has_voted,\n 'is_favorite': message.starred,\n 'attachment_ids': [],\n 'email_from':message.email_from or '',\n 'email_to': message.email_to or '',\n 'email_cc': message.email_cc or '',\n }\n\nmail_message()\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:","sub_path":"vnc_zimbra_connector/mail_message.py","file_name":"mail_message.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"491538142","text":"#!/usr/bin/env python3\nimport random\nimport sys\nn = int(sys.argv[1])\nrandom.seed(int(sys.argv[2]))\n\nassert n%4 == 0\nv1 = list(range(0, n//4))\nv2 = list(range(n//4, n//2))\nv3 = list(range(n//2, (3*n)//4))\nv4 = list(range((3*n)//4, n))\nrandom.shuffle(v1)\nrandom.shuffle(v2)\nrandom.shuffle(v3)\nrandom.shuffle(v4)\n\nv = [i+1 for i in v1+v2+v3+v4]\n\nprint(n)\nprint(*v)\n","sub_path":"ICPC/ukiepc2020problems/incompleteimplementation/generators/quarters_in_place.py","file_name":"quarters_in_place.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"407431482","text":"import numpy as np\nimport tree # dm_tree\nfrom typing import Any, Callable, Dict, List, Type\n\nfrom ray.rllib.connectors.connector import (\n ConnectorContext,\n AgentConnector,\n register_connector,\n)\nfrom ray.rllib.policy.sample_batch import SampleBatch\nfrom ray.rllib.utils.annotations import DeveloperAPI\nfrom ray.rllib.utils.typing import (\n AgentConnectorDataType,\n TensorStructType,\n)\n\n\n@DeveloperAPI\ndef register_lambda_agent_connector(\n name: str, fn: Callable[[Any], Any]\n) -> Type[AgentConnector]:\n \"\"\"A util to register any simple transforming function as an AgentConnector\n\n The only requirement is that fn should take a single data object and return\n a single data object.\n\n Args:\n name: Name of the resulting actor connector.\n fn: The function that transforms env / agent data.\n\n Returns:\n A new AgentConnector class that transforms data using fn.\n \"\"\"\n\n class LambdaAgentConnector(AgentConnector):\n def __call__(\n self, ac_data: AgentConnectorDataType\n ) -> List[AgentConnectorDataType]:\n d = ac_data.data\n return [AgentConnectorDataType(ac_data.env_id, ac_data.agent_id, fn(d))]\n\n def to_config(self):\n return name, None\n\n @staticmethod\n def from_config(ctx: ConnectorContext, params: List[Any]):\n return LambdaAgentConnector(ctx)\n\n LambdaAgentConnector.__name__ = name\n LambdaAgentConnector.__qualname__ = name\n\n register_connector(name, LambdaAgentConnector)\n\n return LambdaAgentConnector\n\n\n@DeveloperAPI\ndef flatten_data(data: Dict[str, TensorStructType]):\n assert (\n type(data) == dict\n ), \"Single agent data must be of type Dict[str, TensorStructType]\"\n\n flattened = {}\n for k, v in data.items():\n if k in [SampleBatch.INFOS, SampleBatch.ACTIONS] or k.startswith(\"state_out_\"):\n # Do not flatten infos, actions, and state_out_ columns.\n flattened[k] = v\n continue\n if v is None:\n # Keep the same column shape.\n flattened[k] = None\n continue\n flattened[k] = np.array(tree.flatten(v))\n\n return flattened\n\n\n# Flatten observation data.\nFlattenDataAgentConnector = register_lambda_agent_connector(\n \"FlattenDataAgentConnector\", flatten_data\n)\n","sub_path":"rllib/connectors/agent/lambdas.py","file_name":"lambdas.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"430160032","text":"from __future__ import print_function\nimport os\nimport sys\n\nfrom catkin_pkg.package import parse_package\nfrom catkin_pkg.packages import find_package_paths\n\n\nclass PackageData:\n\n def __init__(self, path, parse_package_arg=parse_package):\n package = parse_package_arg(path)\n self.name = package.name\n self.path = path\n self.build_depends = set([d.name for d in (package.build_depends + package.buildtool_depends)])\n message_generators = [e.content for e in package.exports if e.tagname == 'message_generator']\n self.message_generator = message_generators[0] if message_generators else None\n self.is_metapackage = 'metapackage' in [e.tagname for e in package.exports]\n\n def __repr__(self):\n return 'name=%s path=%s build_depends=%s message_generator=%s\\n' % (self.name, self.path, self.build_depends, self.message_generator)\n\n\ndef _remove_dependency(packages, name):\n for build_depends in [package_data.build_depends for package_data in packages.values()]:\n build_depends.difference_update([name])\n\n\ndef _sort_packages(packages):\n '''\n First returning packages which have message generators and then the rest based on their build_depends.\n '''\n\n ordered_packages = []\n while len(packages) > 0:\n # find all packages without build dependencies\n message_generators = []\n non_message_generators = []\n for name, data in packages.items():\n if not data.build_depends:\n if data.message_generator:\n message_generators.append(name)\n else:\n non_message_generators.append(name)\n # first choose message generators\n if message_generators:\n names = message_generators\n elif non_message_generators:\n names = non_message_generators\n else:\n # in case of a circular dependency pass the list of remaining packages\n ordered_packages.append([None, ', '.join(sorted(packages.keys()))])\n break\n\n # alphabetic order only for convenience\n names.sort()\n #print('names = %s' % names, file=sys.stderr)\n\n # add first candidates to ordered list\n # do not add all candidates since removing the depends from the first might affect the next candidates\n name = names[0]\n ordered_packages.append([name, packages[name]])\n # remove package from further processing\n del packages[name]\n _remove_dependency(packages, name)\n return ordered_packages\n\n\ndef topological_order(source_root_dir, whitelisted=None, blacklisted=None):\n paths = find_package_paths(source_root_dir)\n #print('paths = %s' % paths, file=sys.stderr)\n\n # fetch all meta data\n prefix = os.path.abspath(source_root_dir) + os.sep\n package_data_list = []\n for path in paths:\n data = PackageData(os.path.join(source_root_dir, path))\n # make path relative to root dir\n if data.path.startswith(prefix):\n data.path = data.path[len(prefix):]\n package_data_list.append(data)\n return _topological_order_packages(package_data_list, whitelisted, blacklisted)\n\n\ndef _topological_order_packages(package_data_list, whitelisted=None, blacklisted=None):\n packages = {}\n for data in package_data_list:\n # skip non-whitelisted packages\n if whitelisted and data.name not in whitelisted:\n continue\n # skip blacklisted packages\n if blacklisted and data.name in blacklisted:\n continue\n if data.name in packages:\n print('Two package with the same name \"%s\" in the workspace:\\n- %s\\n- %s' % (data.name, packages[data.name].path, data.path), file=sys.stderr)\n sys.exit(1)\n packages[data.name] = data\n\n # remove catkin from list of packages\n if 'catkin' in packages:\n del packages['catkin']\n\n # remove external dependencies from the list\n if packages:\n all_build_depends = reduce(set.union, [p.build_depends for p in packages.values()])\n external_depends = all_build_depends - set(packages.keys())\n #print('external_depends = %s' % external_depends, file=sys.stderr)\n for data in packages.values():\n data.build_depends = set(data.build_depends) - set(external_depends)\n\n return _sort_packages(packages)\n\n\ndef get_message_generators(ordered_packages):\n return [name for (name, data) in ordered_packages if hasattr(data, 'message_generator') and data.message_generator]\n","sub_path":"python/catkin/topological_order.py","file_name":"topological_order.py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"593392492","text":"from imutils.face_utils import FaceAligner\nfrom imutils.face_utils import rect_to_bb\nimport imutils\nimport dlib\nimport cv2\nimport numpy as np\nfrom skimage.measure import compare_ssim as ssim\nimport os\nimport sys\nfrom hairstylist import BASE_DIR\n\npredictor = None\ndef hog_err(source_img,images):\n global predictor\n mags = []\n detector = dlib.get_frontal_face_detector()\n if(predictor == None):\n predictor = dlib.shape_predictor(BASE_DIR+\"/hairstylist/pipeline/shape_predictor_68_face_landmarks.dat\")\n fa = FaceAligner(predictor, desiredFaceWidth=256)\n for image in images:\n #image = imutils.resize(image, width=800)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n rects = detector(gray, 2)\n if(rects):\n (x, y, w, h) = rect_to_bb(rects[0])\n #print((x,y,w,h))\n # faceOrig = imutils.resize(image[y:y + h, x:x + w], width=256)\n faceAligned = fa.align(image, gray, rects[0])\n mags.append(cv2.resize(faceAligned, (255, 255)))\n temp = rects\n else:\n (x, y, w, h) = rect_to_bb(temp[0])\n #print((x,y,w,h))\n # faceOrig = imutils.resize(image[y:y + h, x:x + w], width=256)\n faceAligned = fa.align(image, gray, temp[0])\n mags.append(cv2.resize(faceAligned, (255, 255)))\n\n #image = imutils.resize(source_img, width=800)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n rects = detector(gray, 2)\n (x, y, w, h) = rect_to_bb(rects[0])\n # faceOrig = imutils.resize(image[y:y + h, x:x + w], width=256)\n faceAligned = fa.align(image, gray, rects[0])\n mags.append(cv2.resize(faceAligned, (255, 255)))\n images = mags[:-1]\n err = []\n for image in images:\n err.append(ssim(mags[-1], image, multichannel=True))\n\n return err","sub_path":"hairstylist/pipeline/hog2.py","file_name":"hog2.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"541991468","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nimport string, re, urllib, pyglet\n\n\n\n\"\"\"\n7 smarty\n\"\"\"\nsite = \"http://www.pythonchallenge.com/pc/def/\"\nopt = \"oxygen.png\"\nanswer_to_find = \"\"\n\n# decode png\npic = pyglet.image.load('7_smarty.png')\nraw_image = pic.get_image_data()\nformat = 'RGBA'\npitch = raw_image.width * len(format)\npixels = raw_image.get_data(format, pitch)\nwidth = (pitch) # 2516\nheight = (len(pixels)/pitch) # 95\nall_pixel_count = (len(pixels)) # 239020 (mid of picture 119510)\nlti = 47 # line_to_inspect\nfor pix_in_mid in range(width * lti, width * lti + width):\n print(pixels[pix_in_mid], end=\"\")\npix_line_in_mid = pixels[width * lti : width * lti + width]\n#print(\"alpha channel value: \" + str(ord(pix_line_in_mid[3])))\nanswer_string = \"\".join(re.findall('([a-z0-9 ,])[a-z0-9 ,]+.[a-z0-9 ,]+.[a-z0-9 ,]+.[a-z0-9 ,]+.[a-z0-9 ,]+.[a-z0-9 ,]+.[a-z0-9 ,]+.', pix_line_in_mid))\n# answer_string is \"smart guy, you made it the next level is 105, 110, 116, 101, 103, 114, 105, 116, 121\"\n# -> convert last numbers from ascii to characters being able to read:\nnumber_pos = answer_string.find(\"1\")\nprint(\"\\n\")\nprint(answer_string)\nanswer_to_find = answer_string[:number_pos]\nnumber_str = answer_string[number_pos:]\nfor pos in range(number_pos, len(answer_string), 5):\n num_str = \"\"\n for n in range(3):\n num_str += answer_string[pos + n]\n print(num_str)\n char = chr(int(num_str))\n answer_to_find += char\nprint(\"convert ascii numbers to characters\")\nprint(\"answer to find is: \" + answer_to_find)\n#webbrowser.open(site + answer_to_find)\n","sub_path":"2017/pythonchallenge.com/7_smarty.py","file_name":"7_smarty.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"611019097","text":"# -*- coding: utf-8 -*-\n'''\n:url: https://leetcode.com/problems/count-primes/description/\n'''\n\n\nclass Solution:\n def countPrimes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n primes = [0, 0] + [1] * (n - 2)\n for i in range(2, int(n ** 0.5) + 1):\n if primes[i]:\n for j in range(i * i, n, i):\n primes[j] = 0\n return sum(primes)\n","sub_path":"o/countprimes.py","file_name":"countprimes.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"127356455","text":"\"\"\"*WIKI* \n\nThis algorithm creates an empty table workspace and puts it in the data service to make it available to python.\n\n*WIKI*\"\"\"\n\nfrom mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory\nfrom mantid.kernel import Direction\n\n# Create an empty table workspace to be populated by a python script.\nclass CreateEmptyTableWorkspace(PythonAlgorithm):\n \n def PyInit(self):\n # Declare properties\n self.setWikiSummary(\"Creates an empty table workspace that can be populated by python code.\")\n self.setOptionalMessage(\"Creates an empty table workspace that can be populated by python code.\")\n self.declareProperty(ITableWorkspaceProperty(\"OutputWorkspace\", \"\", Direction.Output), \"The name of the table workspace that will be created.\")\n \n def PyExec(self):\n tableWS = WorkspaceFactory.createTable()\n\n self.setProperty(\"OutputWorkspace\", tableWS)\n \n# Register algorithm with Mantid\nAlgorithmFactory.subscribe(CreateEmptyTableWorkspace)\n\n","sub_path":"Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py","file_name":"CreateEmptyTableWorkspace.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"24032094","text":"import os\r\nfilename = 'pragramming.txt' #输出的文件\r\n\r\ndef eachFile(filepath): \r\n pathDir =os.listdir(filepath) #遍历文件夹中的txt文件\r\n return pathDir\r\n\r\ndef readfile(name): \r\n fopen=open(name,'r',encoding = 'utf-8')\r\n for lines in fopen.readlines(): #按行读取txt中的内容\r\n lines = lines.replace(\"\\n\", \"\").split(\",\")\r\n if '156' not in str(lines): \r\n with open(filename,'a') as fileobject:\r\n fileobject.write(''.join(lines)+'\\n')\r\n fopen.close()\r\n\r\nfilePath = \"D:\\\\X\" #这是要查询的txt文件的目录\r\npathDir=eachFile(filePath)\r\n\r\nfor allDir in pathDir:\r\n # child = os.path.join('%s%s' % (filepath, allDir))\r\n child = \"C:\\\\X\" + '\\\\' + allDir #这好像也是可以查询的文件。把他俩一个置为空即可\r\n readfile(child)\r\n\r\n","sub_path":"得到文件名后把出符合要求的文件名写入txt文件.py","file_name":"得到文件名后把出符合要求的文件名写入txt文件.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"394201807","text":"import spacy\nfrom spacy.lang.en import English\nfrom spacy.matcher import Matcher\nfrom spacy.tokens import Span\nfrom spacy import displacy\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport requests\nfrom bs4 import BeautifulSoup\nfrom argparse import ArgumentParser\nimport pandas as pd\nimport numpy as np\nimport re\n\nnlp = spacy.load('en_core_web_sm')\n\ndef getSentences(text):\n nlp = English()\n nlp.add_pipe(nlp.create_pipe('sentencizer'))\n document = nlp(text)\n return [sent.string.strip() for sent in document.sents]\n\ndef get_entities(sent):\n ## chunk 1\n ent1 = \"\"\n ent2 = \"\"\n\n prv_tok_dep = \"\" # dependency tag of previous token in the sentence\n prv_tok_text = \"\" # previous token in the sentence\n\n prefix = \"\"\n modifier = \"\"\n\n #############################################################\n\n for tok in nlp(sent):\n ## chunk 2\n # if token is a punctuation mark then move on to the next token\n if tok.dep_ != \"punct\":\n # check: token is a compound word or not\n if tok.dep_ == \"compound\":\n prefix = tok.text\n # if the previous word was also a 'compound' then add the current word to it\n if prv_tok_dep == \"compound\":\n prefix = prv_tok_text + \" \"+ tok.text\n\n # check: token is a modifier or not\n if tok.dep_.endswith(\"mod\") == True:\n modifier = tok.text\n # if the previous word was also a 'compound' then add the current word to it\n if prv_tok_dep == \"compound\":\n modifier = prv_tok_text + \" \"+ tok.text\n\n ## chunk 3\n if tok.dep_.find(\"subj\") == True:\n ent1 = modifier +\" \"+ prefix + \" \"+ tok.text\n prefix = \"\"\n modifier = \"\"\n prv_tok_dep = \"\"\n prv_tok_text = \"\"\n\n ## chunk 4\n if tok.dep_.find(\"obj\") == True:\n ent2 = modifier +\" \"+ prefix +\" \"+ tok.text\n\n ## chunk 5\n # update variables\n prv_tok_dep = tok.dep_\n prv_tok_text = tok.text\n #############################################################\n\n return [ent1.strip(), ent2.strip()]\n\n\ndef get_relation(sent):\n\n doc = nlp(sent)\n\n # Matcher class object\n matcher = Matcher(nlp.vocab)\n\n #define the pattern\n pattern = [{'DEP':'ROOT'},\n {'DEP':'prep','OP':\"?\"},\n {'DEP':'agent','OP':\"?\"},\n {'POS':'ADJ','OP':\"?\"}]\n\n matcher.add(\"matching_1\", None, pattern)\n\n matches = matcher(doc)\n k = len(matches) - 1\n\n span = doc[matches[k][1]:matches[k][2]]\n\n return(span.text)\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(description=\"Generate a Knowledge Graph from a Webpage.\")\n parser.add_argument('--no-graph', dest=\"no_graph\",\n default=False, action=\"store_true\",\n help=\"Do not draw a graph.\")\n parser.add_argument('--no-save', dest=\"no_save\",\n default=False, action=\"store_true\",\n help=\"Do not save a triple data as a file.\")\n parser.add_argument('-u', '--url', type=str, default=None,\n help=\"Provide an URL containing text to parse.\")\n parser.add_argument('-s', '--source', type=str, default=None, nargs='*',\n help=\"Draw a Knowledge Graph only for the given source word.\")\n parser.add_argument('-t', '--target', type=str, default=None, nargs='*',\n help=\"Draw a Knowledge Graph only for the given target word.\")\n parser.add_argument('-e', '--edge', type=str, default=None, nargs='*',\n help=\"Draw a Knowledge Graph only for the given edge word.\")\n parser.add_argument('-f', '--from-file', dest='file', default='',\n help=\"Give a file path and draw a Knowledge Graph plot from the file.\")\n\n args = parser.parse_args()\n if args.file:\n kg_df = pd.read_csv(args.file)\n else:\n headers = {'user-agent': \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36\"}\n url = args.url\n page = requests.get(url, headers = headers)\n soup = BeautifulSoup(page.text, 'lxml') #using lxml parser. You can use Python’s html.parser.\n paragraphs = []\n for i, item in enumerate(soup.find_all(\"p\")):\n paragraphs.append(item.text)\n text = ''.join(paragraphs)\n text = re.sub(\"[\\(\\[].*?[\\)\\]]\", \"\", text)\n text = text.rstrip(\"\\n\")\n sentences = getSentences(text)\n triples = []\n entity_pairs = []\n relations = []\n for sent in sentences:\n entity_pairs.append(get_entities(sent))\n relations.append(get_relation(sent))\n\n # extract subject\n source = [i[0] for i in entity_pairs]\n\n # extract object\n target = [i[1] for i in entity_pairs]\n\n kg_df = pd.DataFrame({'source':source, 'target':target, 'edge':relations})\n if not args.no_save:\n fname = '_'.join(url.rsplit('/',2)[-2:])\n kg_df.to_csv('data/'+fname+'.csv',index = False)\n if not args.no_graph:\n condition = np.array([True]*len(kg_df))\n if args.source:\n condition &= kg_df['source'].isin(args.source)\n if args.target:\n condition &= kg_df['target'].isin(args.target)\n if args.edge:\n condition &= kg_df['edge'].isin(args.edge)\n G=nx.from_pandas_edgelist(kg_df[condition], \"source\", \"target\",\n edge_attr=True, create_using=nx.MultiDiGraph())\n\n\n plt.figure(figsize=(12,8))\n\n pos = nx.spring_layout(G)\n nx.draw(G, with_labels=True, node_color='skyblue', edge_cmap=plt.cm.Blues, pos = pos)\n plt.show()\n","sub_path":"knowledge_graph.py","file_name":"knowledge_graph.py","file_ext":"py","file_size_in_byte":5856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"634527763","text":"\"\"\"Contains the parent class of the Text DisplayElement\"\"\"\n\n# text.py\n# Mission Pinball Framework\n# Written by Brian Madden & Gabe Knuth\n# Released under the MIT License. (See license info at the end of this file.)\n\n# Documentation and more info at http://missionpinball.com/mpf\n\nimport re\nfrom mpf.media_controller.core.display import DisplayElement\n\n\nclass Text(DisplayElement):\n \"\"\"Represents an text display element.\n\n Args:\n slide: The Slide object this animation is being added to.\n machine: The main machine object.\n text: A string of the text you'd like to display. If you have the\n multi-language plug-in enabled, this text will be run through the\n language engine before it's displayed.\n x: The horizontal position offset for the placement of this element.\n y: The vertical position offset for the placement of this element.\n h_pos: The horizontal anchor.\n v_pos: The vertical anchor.\n\n Note: Full documentation on the use of the x, y, h_pos, and v_pos arguments\n can be found at: https://missionpinball.com/docs/displays/display-elements/positioning/\n\n \"\"\"\n\n def __init__(self, slide, machine, text, x=None, y=None, h_pos=None,\n v_pos=None, layer=0, text_variables=None, **kwargs):\n\n super(Text, self).__init__(slide, x, y, h_pos, v_pos, layer)\n\n self.text = str(text)\n self.original_text = self.text\n self.fonts = machine.display.fonts\n self.language = machine.language\n self.slide = slide\n self.machine = machine\n self.layer = layer\n\n self.config = kwargs\n\n self.var_finder = re.compile(\"(?<=%)[a-zA-Z_0-9|]+(?=%)\")\n\n if not text_variables:\n text_variables = dict()\n\n self.adjust_colors(**self.config)\n\n self.config['color'] = self.adjusted_color\n self.config['bg_color'] = self.adjusted_bg_color\n\n # Set defaults\n if 'name' in self.config:\n self.name = self.config['name']\n else:\n self.name = text\n\n self._process_text(self.text, local_replacements=text_variables,\n local_type='event')\n\n def _get_text_vars(self):\n return self.var_finder.findall(self.original_text)\n\n def _process_text(self, text, local_replacements=None, local_type=None):\n # text: source text with placeholder vars\n # local_replacements: dict of var names & their replacements\n # local_type: type specifier of local replacements. e.g. \"event\" means\n # it will look for %event|var_name% in the text string\n\n text = str(text)\n\n if not local_replacements:\n local_replacements = list()\n\n for var_string in self._get_text_vars():\n if var_string in local_replacements:\n text = text.replace('%' + var_string + '%',\n str(local_replacements[var_string]))\n self.original_text = text\n\n elif local_type and var_string.startswith(local_type + '|'):\n text = text.replace('%' + var_string + '%',\n str(local_replacements[var_string.split('|')[1]]))\n self.original_text = text\n\n if self._get_text_vars():\n self._setup_variable_monitors()\n\n self.update_vars_in_text()\n\n def update_vars_in_text(self):\n\n text = self.original_text\n\n for var_string in self._get_text_vars():\n if var_string.startswith('machine|'):\n try:\n text = text.replace('%' + var_string + '%',\n str(self.machine.machine_vars[var_string.split('|')[1]]))\n except KeyError:\n text = ''\n\n elif self.machine.player:\n if var_string.startswith('player|'):\n text = text.replace('%' + var_string + '%',\n str(self.machine.player[var_string.split('|')[1]]))\n elif var_string.startswith('player'):\n player_num, var_name = var_string.lstrip('player').split('|')\n try:\n value = self.machine.player_list[int(player_num)-1][var_name]\n\n if value is not None:\n text = text.replace('%' + var_string + '%', str(value))\n else:\n text = ''\n except IndexError:\n text = ''\n else:\n text = text.replace('%' + var_string + '%',\n str(self.machine.player[var_string]))\n\n self.update_text(text)\n\n def update_text(self, text):\n # todo auto-fit text to a certain size bounding box\n\n text = str(text)\n\n if text:\n if 'min_digits' in self.config:\n text = text.zfill(self.config['min_digits'])\n\n if ('number_grouping' in self.config and\n self.config['number_grouping']):\n\n # find the numbers in the string\n number_list = [s for s in text.split() if s.isdigit()]\n\n # group the numbers and replace them in the string\n for item in number_list:\n grouped_item = self.group_digits(item)\n text = text.replace(str(item), grouped_item)\n\n # Are we set up for multi-language?\n if self.language:\n text = self.language.text(text)\n\n self.text = text\n self.render()\n\n def _player_var_change(self, player_num, target_player, var_name, value,\n **kwargs):\n # value = str(value)\n #\n # if (player_num and target_player and\n # int(player_num) == int(target_player)):\n # player_num = str(player_num)\n # new_text = self.original_text.replace(\n # '%player{}|{}%'.format(player_num, var_name), value)\n # new_text = new_text.replace('%player|{}%'.format(var_name), value)\n # new_text = new_text.replace('%{}%'.format(var_name), value)\n #\n # self.update_text(new_text)\n #\n # elif player_num and not target_player:\n # new_text = self.original_text.replace(\n # '%player|{}%'.format(var_name), value)\n # new_text = new_text.replace('%{}%'.format(var_name), value)\n #\n # self.update_text(new_text)\n\n self.update_vars_in_text()\n\n def _machine_var_change(self, value, change, prev_value, var_name,\n **kwargs):\n\n self.update_vars_in_text()\n\n # return self.update_text(self.original_text.replace(\n # '%machine|{}%'.format(var_name), str(value)))\n\n def _setup_variable_monitors(self):\n\n for var_string in self._get_text_vars():\n if '|' not in var_string:\n self.add_player_var_handler(name=var_string, player=None)\n else:\n source, variable_name = var_string.split('|')\n if source.lower().startswith('player'):\n\n if source.lstrip('player'):\n self.add_player_var_handler(name=variable_name,\n player=source.lstrip('player'))\n else:\n self.add_player_var_handler(name=var_string,\n player=self.machine.player['number'])\n\n elif source.lower() == 'machine':\n self.add_machine_var_handler(name=variable_name)\n\n def add_player_var_handler(self, name, player):\n self.machine.events.add_handler('player_' + name,\n self._player_var_change,\n target_player=player,\n var_name=name)\n\n def add_machine_var_handler(self, name):\n self.machine.events.add_handler('machine_var_' + name,\n self._machine_var_change,\n var_name=name)\n\n def render(self):\n self.element_surface = self.fonts.render(text=self.text, **self.config)\n self.set_position(self.x, self.y, self.h_pos, self.v_pos)\n self.dirty = True\n\n self.slide.refresh(force_dirty=True)\n\n def scrub(self):\n self.machine.events.remove_handler(self._player_var_change)\n self.machine.events.remove_handler(self._machine_var_change)\n\n def group_digits(self, text, separator=',', group_size=3):\n \"\"\"Enables digit grouping (i.e. adds comma separators between\n thousands digits).\n\n Args:\n text: The incoming string of text\n separator: String of the character(s) you'd like to add between the\n digit groups. Default is a comma. (\",\")\n group_size: How many digits you want in each group. Default is 3.\n\n Returns: A string with the separator added.\n\n MPF uses this method instead of the Python locale settings because the\n locale settings are a mess. They're set system-wide and it's really hard\n to make them work cross-platform and there are all sorts of external\n dependencies, so this is just way easier.\n\n \"\"\"\n digit_list = list(text.split('.')[0])\n\n for i in range(len(digit_list))[::-group_size][1:]:\n digit_list.insert(i+1, separator)\n\n return ''.join(digit_list)\n\n\ndisplay_element_class = Text\ncreate_asset_manager = False\n\n# The MIT License (MIT)\n\n# Copyright (c) 2013-2015 Brian Madden and Gabe Knuth\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n","sub_path":"mpf/media_controller/elements/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":10728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"329487580","text":"class ServiceError(Exception):\n status_code = 400\n\n def __init__(self, message, status_message=None, status_code=None, payload=None):\n super(ServiceError, self).__init__(self)\n self.message = message\n if status_code is not None:\n self.status_code = status_code\n self.status_message = status_message\n self.payload = payload\n\n def to_dict(self):\n data_dict = dict(self.payload or ())\n data_dict['message'] = self.message\n if self.status_message:\n data_dict['status'] = self.status_message\n return data_dict\n\n\nclass InvalidUsage(ServiceError):\n def __init__(self, message, status_code=None, payload=None):\n super(InvalidUsage, self).__init__(\n message, status_message=\"invalid_usage\",\n status_code=status_code, payload=payload\n )\n\n\nclass NoDataError(ServiceError):\n def __init__(self, message, status_code=None, payload=None):\n super(NoDataError, self).__init__(\n message, status_message=\"error\",\n status_code=status_code, payload=payload\n )","sub_path":"weather_service/utils/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"622141463","text":"import random\r\n\r\nimport discord\r\nimport asyncio\r\n\r\nfrom discord import Member, Guild, User\r\n\r\nclient = discord.Client()\r\n\r\n\r\n#############################################################\r\n\r\nautoroles = {\r\n 481123510945841152: {'memberroles': [482632835195338763], 'rainbowroles': [759021202743492610]}\r\n}\r\n\r\n\r\n@client.event\r\nasync def on_ready():\r\n print(\"Welcome Home Sir\")\r\n client.loop.create_task(status_task())\r\n\r\n\r\n\r\n\r\n\r\nasync def status_task():\r\n colors = [discord.Colour.red(), discord.Colour.orange(), discord.Colour.gold(), discord.Colour.green(),\r\n discord.Colour.blue(), discord.Colour.dark_purple()]\r\n while True:\r\n await client.change_presence(activity=discord.Game(name=\"mit 187 User\"), status=discord.Status.online)\r\n await asyncio.sleep(4)\r\n\r\n guild: Guild = client.get_guild(481123510945841152)\r\n if guild:\r\n role = guild.get_role(759021202743492610)\r\n if role:\r\n if role.position < guild.get_member(client.user.id).top_role.position:\r\n await role.edit(colour=random.choice(colors))\r\n\r\ndef is_not_pinned(mess):\r\n return not mess.pinned\r\n\r\n@client.event\r\nasync def on_member_join(member):\r\n guild: Guild = member.guild\r\n if not member.bot:\r\n embed = discord.Embed(title='Willkommen auf Milfhunter-Gang 💖 {} '.format(member.name),\r\n description='Wir heißen dich herlich Willkommen auf unserem Server!', color=15158332)\r\n embed.add_field(name=\"Server beigetreten\", value=member.joined_at.strftime(\"%d.%m.%Y, %H:%M:%S\"),\r\n inline=True)\r\n embed.add_field(name=\"Discord beigetreten\", value=member.created_at.strftime(\"%d.%m.%Y, %H:%M:%S\"),\r\n inline=True)\r\n embed.set_footer(text=\"bot by @hackenistharam\")\r\n\r\n try:\r\n if not member.dm_channel:\r\n await member.create_dm()\r\n await member.dm_channel.send(embed=embed)\r\n except discord.errors.Forbidden:\r\n print(\"Es konnte keine Willkommensnachricht an {} gesendet werden.\".format(member.name))\r\n autoguild = autoroles.get(guild.id)\r\n if autoguild and autoguild['memberroles']:\r\n for roleId in autoguild['memberroles']:\r\n role = guild.get_role(roleId)\r\n if role:\r\n await member.add_roles(role, reason='AutoRoles', atomic=True)\r\n\r\n@client.event\r\nasync def on_message(message):\r\n if message.author.bot:\r\n return\r\n if (\"/help\") in message.content:\r\n embed = discord.Embed(title=\"Hilfetext\", description=\"**/help** - Zeigt diesen Text an\\r\\n\"\r\n \"**/userinfo** - Zeigt dir Informationen\\r\\n\"\r\n \"**/kill** - Tötet einen Member\\r\\n\"\r\n \"**/ban** - bannt einen Member\\r\\n\"\r\n \"**/kick** - kickt einen Member\\r\\n\"\r\n \"**/meme** - erzählt dir ein meme\\r\\n\"\r\n \"**/clear** - cleart den Chat\\r\\n\"\r\n \"**/version** - zeigt dir die Version an\",\r\n color=15158332)\r\n await message.channel.send(embed=embed)\r\n if message.content.startswith(\"/userinfo\"):\r\n args = message.content.split(' ')\r\n if len(args) == 2:\r\n member: Member = discord.utils.find(lambda m: args[1] in m.name, message.guild.members)\r\n if member:\r\n embed = discord.Embed(title=\"Userinfo für {}\".format(member.name),\r\n description=\"Dies ist eine Userinfo für den User {}\".format(member.mention),\r\n color=15158332)\r\n embed.add_field(name=\"Server beigetreten\", value=member.joined_at.strftime(\"%d.%m.%Y %H:%M:%S\"),\r\n inline=True)\r\n embed.add_field(name=\"Discord beigetreten\", value=member.created_at.strftime(\"%d.%m.%Y %H:%M:%S\"),\r\n inline=True)\r\n embed.set_footer(text=\"Invision Bot\")\r\n mess = await message.channel.send(embed=embed)\r\n await mess.add_reaction(':Brimstone_artwork:758768207531606076 ')\r\n\r\n if message.content.startswith(\"/kill\"):\r\n args = message.content.split(' ')\r\n if len(args) == 2:\r\n member: Member = discord.utils.find(lambda m: args[1] in m.name, message.guild.members)\r\n if member:\r\n await message.channel.send(\"Du hast den User {0} getötet\".format(member.mention))\r\n await message.add_reaction(\"☠\")\r\n\r\n\r\n if message.content.startswith(\"/clear\"):\r\n if message.author.permissions_in(message.channel).manage_messages:\r\n args = message.content.split(' ')\r\n if len(args) == 2:\r\n if args[1].isdigit():\r\n count = int(args[1]) + 1\r\n deleted = await message.channel.purge(limit=count, check=is_not_pinned)\r\n await message.channel.send(\"{} Nachrichten gelöscht!\".format(len(deleted)-1))\r\n\r\n if message.content.startswith(\"/ban\") and message.author.guild_permissions.ban_members:\r\n args = message.content.split(' ')\r\n if len(args) == 2:\r\n member: Member = discord.utils.find(lambda m: args[1] in m.name, message.guild.members)\r\n if member:\r\n await member.ban()\r\n await message.channel.send(f'Member {member.name} gebannt!')\r\n else:\r\n await message.channel.send(f'Kein User mit dem Namen {args[1]} gefunden.')\r\n if message.content.startswith(\"/kick\") and message.author.guild_permissions.kick_members:\r\n args = message.content.split(' ')\r\n if len(args) == 2:\r\n member: Member = discord.utils.find(lambda m: args[1] in m.name, message.guild.members)\r\n if member:\r\n await member.kick()\r\n await message.channel.send(f'Member {member.name} gekickt!')\r\n else:\r\n await message.channel.send(f'Kein User mit dem Namen {args[1]} gefunden.')\r\n\r\n\r\n if message.content.startswith(\"/meme\"):\r\n embed = discord.Embed(title=\"memes\", description=\"Du bist das meme hier ;:D\", color=15158332)\r\n embed.set_footer(text=\"by @hackenistharam\")\r\n await message.channel.send(embed=embed)\r\n\r\n if message.content.startswith(\"/team\"):\r\n embed = discord.Embed(title=\"Team Liste\", description=\"**Owner**: X-Ray.ReDeX\\r\\n\"\r\n \"\\r\\n\"\r\n \"**Admins**:\\r\\n\"\r\n \"HackenIstHaram\\r\\n\"\r\n \"EinsRandomLel\\r\\n\"\r\n \"Holyboomboomreis\\r\\n\"\r\n \"ReIndex\\r\\n\"\r\n \"X-Ray.KcRumba\\r\\n\"\r\n \"\", color=15158332)\r\n embed.set_footer(text=\"bot by @hackenistharam\")\r\n await message.channel.send(embed=embed)\r\n\r\n\r\n if message.content.startswith(\"/version\"):\r\n await message.channel.send(\"Version: 2.0\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclient.run(\"NzUyMTkzNjgyNDY3NDU1MTE2.X1UE9A.1q2Feya-v1kKwSLS4Kn44WYXM78\")","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":7765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"540346232","text":"import os\n\nimport sys\n\nsys.path.insert(1, f'{os.path.dirname(os.getcwd())}\\\\models\\\\')\n\nimport pandas as pd\n\nimport requests\n\nfrom Mapper import df_ISO3_mapper\n\n\ndef get_PL_table(url):\n x = requests.get(url)\n league_table = pd.read_html(x.content)[0]\n del league_table['Last 6']\n \n return league_table\n\n\ndef save_csv(tab):\n tab_path = f'{os.path.dirname(os.getcwd())}\\\\data\\\\Table\\\\table.csv'\n tab.to_csv(tab_path, index=0, sep=',')\n\n\n\ndef collect(mapper):\n print('Collecting current table...')\n table_url = 'https://www.skysports.com/premier-league-table'\n pl_table = get_PL_table(table_url)\n pl_table = df_ISO3_mapper(pl_table, mapper)\n save_csv(pl_table)\n","sub_path":"src/web-scrapers/GetTable.py","file_name":"GetTable.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"353697699","text":"# Author : Yangguang Shi\n# Student Number : 626689\n# Supervisor : Prof. Richard Sinnott\n# COMP90055 COMPUTING PROJECT\n# Project Title : Big Data Platform for Twitter-based Brand Analytics\n\n# Caculate which brand is the most popular one and label this area with the brand to the suburb_boundary database\n\nimport sys \nimport json\nimport couchdb\n\ncouch = couchdb.Server('http://115.146.89.7:5984/')\ncdb = couch['softdrinks']\ncdb_t = couch['suburb_boundaries']\n\ntemp_key = ''\ntemp_brand = ''\npre_senti = -1\ntemp_count = 0\ncounter = 0\n\nfor doc in cdb.view('postcode/suburb_mostpop', group_level=2):\n\tif doc.key[0] != temp_key:\n\t\tif temp_key == None:\n\n\t\t\ttemp_key = doc.key[0]\n\t\t\ttemp_brand = doc.key[1]\n\t\t\tpre_senti = doc.value[0]\n\n\t\tif temp_key != None:\n\t\t\tcounter +=1\n\t\t\tprint(temp_key, temp_brand, pre_senti,temp_count)\n\t\t\ttry:\n\t\t\t\tdbData = cdb_t[temp_key]\n\t\t\t\ttop_softdrink = {}\n\t\t\t\ttop_softdrink['brand'] = temp_brand\n\t\t\t\ttop_softdrink['sentiment_score'] = pre_senti\n\t\t\t\ttop_softdrink['count'] = temp_count\n\t\t\t\tdbData['top_softdrink'] = top_softdrink\n\t\t\t\tprint(top_softdrink)\n\t\t\t\tcdb_t.save(dbData)\n\t\t\t\tprint(dbData['top_softdrink'])\n\t\t\texcept Exception as e:\n\t\t\t\tprint(\"Index error\")\n\t\t\ttemp_key = doc.key[0]\n\t\t\ttemp_brand = doc.key[1]\n\t\t\tpre_senti = doc.value[0]\n\t\t\ttemp_count = doc.value[1]\n\n# Find most popular brand based on sentiment score\n\tif doc.key[0] == temp_key:\n\t\tkey = doc.key[0]\n\t\tbrand = doc.key[1]\n\t\tsentiment_score = doc.value[0]\n\t\tcount = doc.value[1]\n\t\tif sentiment_score > pre_senti:\n\t\t\ttemp_key = key\n\t\t\ttemp_brand = brand\n\t\t\tpre_senti = sentiment_score\n\t\t\ttemp_count = count\n\t\n# Find most popular brand based on count\t\t\n\t# if doc.key[0] == temp_key:\n\t# \tkey = doc.key[0]\n\t# \tbrand = doc.key[1]\n\t# \tsentiment_score = doc.value[0]\n\t# \tcount = doc.value[1]\n\t# \tif count > temp_count:\n\t# \t\ttemp_key = key\n\t# \t\ttemp_brand = brand\n\t# \t\tpre_senti = sentiment_score\n\t# \t\ttemp_count = count\t\n\nprint('Finished and count is: ', counter)\n\n\n\n\n\n","sub_path":"Data_analytics/suburb_mostpop_brand.py","file_name":"suburb_mostpop_brand.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"501550746","text":"\"\"\"\nQSlider class object presents the users with a groove over which a handle can\nbe moved. It is a classic widget to control a bounded value. Position of the handle\non the grovve is equivalent to an integer between the lower and the upper bounds of\nthe control.\n\"\"\"\nimport sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nclass sliderdemo(QWidget):\n def __init__(self, parent=None):\n super(sliderdemo, self).__init__(parent)\n\n layout = QVBoxLayout()\n\n self.l1 = QLabel(\"Try slide it!\")\n self.l1.setAlignment(Qt.AlignCenter)\n layout.addWidget(self.l1)\n\n self.s1 = QSlider(Qt.Horizontal)\n self.s1.setMinimum(10)\n self.s1.setMaximum(30)\n self.s1.setValue(20)\n self.s1.setTickPosition(QSlider.TicksBelow)\n self.s1.setTickInterval(5)\n self.s1.valueChanged.connect(self.valuechange)\n layout.addWidget(self.s1)\n\n self.setLayout(layout)\n self.setWindowTitle(\"SpinBox demo\")\n\n def valuechange(self):\n size = self.s1.value()\n self.l1.setFont(QFont(\"Arial\", size))\n self.l1.setText(\"Value: \" + str(size))\n\ndef main():\n app = QApplication(sys.argv)\n ex = sliderdemo()\n ex.show()\n sys.exit(app.exec_())\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"4-basic_widgets/slider.py","file_name":"slider.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"300998383","text":"import numpy as np\nimport pylab\nimport matplotlib as mpl\nfrom matplotlib import rc\nrc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\nrc('text', usetex=True)\n\nlistarr = open(\"photoz_list.txt\")\n\n# obj_no spec_z phot_z age_old age_new f_old_V old_modifier EBV norm chi\n# obj_no spec_z phot_z age_old age_new f_old_V EBV norm chi SFR stellar_mass\n### Find the number of data points, catastrophic outliers and sigma_dz, sigma_dz_NMAD and sigma_dz_clipped\n\nfor i in range(20):\n name = listarr.readline().strip()\n data = np.loadtxt(name)\n no = len(data) \n\n cat = 0.\n dz = (data[:,1] - data[:,2])/(1+data[:,1])\n sig_dz = np.std(dz)\n MAD = np.median(np.abs(dz - np.median(dz)))\n\n gooddata = []\n\n for i in range(len(data)):\n if np.abs(dz[i]) > 0.15:\n cat = cat+1.\n else:\n gooddata.append(i)\n\n data_nocat = np.zeros(len(gooddata)*11) ####11\n data_nocat.shape = (len(gooddata), 11) ####11\n\n for i in range(len(gooddata)):\n data_nocat[i, :] = data[gooddata[i], :]\n\n sigma_dz_clipped = np.std((data_nocat[:,1] - data_nocat[:,2])/(1+data_nocat[:,1]))\n\n \"\"\"\n ### Calculate star formation rates and stellar masses for the full sample and for the well fit sample\n SFR = data[:,9]\n mass = data[:,10]\n good_SFR = data_nocat[:,9]\n good_mass = data_nocat[:,10]\n \"\"\"\n ### Various plotting codes\n\n # obj_no spec_z phot_z age_old age_new f_old_V EBV norm chi SFR stellar_mass\n\n #Plots spec_z vs phot_z with a colorbar of stellar pop age\n maxxy = np.max([np.max(data[:,1]), np.max(data[:,2])]) + 0.05\n pylab.figure()#figsize=(16,12))\n pylab.scatter(data[:,1], data[:,2], c = data[:,5])#, norm=mpl.colors.LogNorm()) #3\n pylab.plot([0., 7], [0., 7], color=\"black\", lw=2)\n pylab.plot([0., 7], [0. - 0.15, 0.85*7 -0.15], color=\"grey\")\n pylab.plot([0., 7], [0. + 0.15, 1.15*7 + 0.15], color=\"grey\")\n pylab.xlim(0, 7)\n pylab.ylim(0, 7)\n pylab.ylabel(\"$z_{phot}$\", size=18)\n pylab.xlabel(\"$z_{spec}$\", size=18)\n cbar = pylab.colorbar()\n cbar.set_label(\"Fraction burst at 5000A.\", size=16)#Age of Stellar Pop. (yrs)\n \n #pylab.annotate(name, xy=(0.2, 6.7))\n pylab.annotate(\"$\\mathrm{N_{outliers}}$ = \" + str(cat), xy=(4.5,0.85))\n pylab.annotate(\"$\\mathrm{\\sigma_{dz}}$ = \" + str(round(sig_dz, 4)), xy=(4.5,0.6))\n pylab.annotate(\"$\\mathrm{\\sigma_{dz\\_NMAD}}$ = \" + str(round(MAD*1.483, 4)), xy=(4.5,0.35))\n pylab.annotate(\"$\\mathrm{\\sigma_{dz\\_clipped}}$ = \" + str(round(sigma_dz_clipped, 4)), xy=(4.5, 0.1))\n pylab.savefig(\"photoz/plots/\" + name[6:-4])\n\n\n\"\"\"\n#Plots age of stellar population vs extinction EBV value\npylab.figure()\npylab.scatter(data[:, 3]*10**-9, data[:,6], color=\"red\")\npylab.scatter(data_nocat[:, 3]*10**-9, data_nocat[:,6], color=\"blue\")\npylab.xlabel(\"Age of Stellar Pop. (Gyr)\", size=\"16\")\npylab.xlim(5*10**-3, 15)\npylab.xscale(\"log\")\npylab.ylabel(\"E(B - V) (mag)\", size=\"16\")\npylab.show()\n\n\n#Plots stellar mass vs star formation rate\npylab.figure()\npylab.scatter(mass, SFR, color=\"red\")\npylab.scatter(good_mass, good_SFR, color=\"blue\")\npylab.xlabel(\"Stellar Mass (Solar Masses)\", size=\"16\")\npylab.yscale(\"log\")\npylab.xscale(\"log\")\npylab.ylabel(\"SFR (Solar Masses per year)\", size=\"16\")\npylab.ylim(10**-5, 5*10**3)\npylab.xlim(10**5, 5*10**12)\npylab.show()\n\"\"\"\n","sub_path":"2comp/plot_photoz_2comp.py","file_name":"plot_photoz_2comp.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"147695703","text":"\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport os\n\"\"\" \nPlotting a diagonal correlation matrix\n======================================\n\n\"\"\"\n\n# import the dataframe\n\ndf = pd.read_csv(\"/home/edogerde/Bureau/ROI.csv\")\n\n# seaborn\nsns.set(style=\"white\")\n\n# Generate a large random dataset\nd = df[[\"label\", \"Patients\",\"mean\" ]]\ndt= d.pivot(columns=\"label\", index = \"Patients\" , values= \"mean\")\n\n# Compute the correlation matrix\ncorr = dt.corr()\n\n### Create the matrix figure with seaborn\n# Generate a mask for the upper triangle\nmask = np.zeros_like(corr, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\n\n# Set up the matplotlib figure\nf, ax = plt.subplots(figsize=(20, 30))\n\n# Generate a custom diverging colormap\ncmap = sns.diverging_palette(220, 10, as_cmap=True)\n\n# Draw the heatmap with the mask and correct aspect ratio\nsns.heatmap(corr, mask=mask, cmap=cmap, vmax=.7,\n square=True, xticklabels=5, yticklabels=5,\n linewidths=.8, cbar_kws={\"shrink\": .5}, ax=ax)\nplt.show()\n\n### Create the matrix figure with mathplot\nplt.imshow(corr, cmap=plt.cm.hot)\nplt.colorbar()\nplt.show()\n\n### Pattern amount subject\nsns.set(style=\"whitegrid\")\nsns.barplot(y=\"mean\", x=\"Patients\", hue = \"label\" , data= d,) \nplt.show()","sub_path":"analysis/analysis_roi/1_Dosimetry_corr_matrix.py","file_name":"1_Dosimetry_corr_matrix.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"366415242","text":"from numpy import *\nimport csv\n\n#\ndef classifyDescriptors(model, name_number_file, index_file, output_file):\n descriptor_numbers_pool = []\n model = model.translate({ord(c): None for c in '[_]'})\n current_set = [int(s) for s in model.split() if s.isdigit()]\n for d in current_set:\n if d not in descriptor_numbers_pool:\n descriptor_numbers_pool.append(d)\n descriptor_numbers_pool.sort()\n\n #\n with open(name_number_file, mode='r') as csvfile:\n datareader = csv.reader(csvfile, delimiter=',', quotechar=' ')\n desc_name_nums = array([row for row in datareader if row != []], order='C')\n\n descriptor_names_pool = []\n for d in descriptor_numbers_pool:\n temp_index = 0\n for nn in desc_name_nums:\n if d == temp_index:\n descriptor_names_pool.append([nn[0], temp_index])\n temp_index = temp_index + 1\n\n print(descriptor_numbers_pool)\n print(descriptor_names_pool)\n\n #\n with open(index_file, mode='r') as csvfile:\n datareader = csv.reader(csvfile, delimiter=',')\n desc_index = array([row for row in datareader if row != []], order='C')\n\n for d in descriptor_names_pool:\n for di in desc_index:\n if di[1] in d:\n d.append(di[0])\n d.append(di[2])\n d.append(di[3])\n d.append(di[4])\n\n #\n fileOut = open(output_file, 'w', newline='')\n fileW = csv.writer(fileOut)\n fileW.writerow(['Descriptor Temp ID', 'Descriptor Actual ID', 'Descriptor Name', 'Descriptor Details', 'Block', 'Sub-Block'])\n for d in descriptor_names_pool:\n fileW.writerow([d[1], d[2], d[0], d[3], d[4], d[5]])\n\n\ndesc_name_number_file = 'UsedDesc_InhiLabels_275m.csv'\ndescriptor_index_file = 'Descriptor_List.csv'\noutput_file = 'Inhibitors_275m_Final_Descriptors.csv'\nmodel = '[1_ 2_ 36_ 52_ 61_ 89_ 158_ 203_ 435_ 539_ 584]'\nclassifyDescriptors(model, desc_name_number_file, descriptor_index_file, output_file)","sub_path":"Mining Program/AnalyzeResults2.py","file_name":"AnalyzeResults2.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"498179751","text":"#!/usr/bin/env conda-execute\n\n# conda execute\n# env:\n# - python>3.5\n# - pelican\n# - markdown\n# - ipython\n# - notebook\n# - tidy-html5\n# - pygments\n# channels:\n# - defaults\n# - conda-forge\n# - pelson\n# run_with: python\n\nimport os\nimport glob\nimport shutil\nimport subprocess\n\n\ndef html():\n cmd = ['pelican', 'content', '--output', 'output', '--settings', 'pelicanconf.py']\n subprocess.check_call(cmd)\n\n\ndef reload():\n cmd = ['pelican', 'content', '--autoreload', '--output', 'output',\n '--settings', 'pelicanconf.py']\n subprocess.check_call(cmd)\n\n\ndef publish():\n cmd = ['pelican', 'content', '--output', 'output',\n '--settings', 'publishconf.py']\n subprocess.check_call(cmd)\n # Remove all ordinary files (not .git/.nojekyl though)\n for fname in glob.glob('output_branch/*'):\n if os.path.isdir(fname):\n shutil.rmtree(fname)\n else:\n os.unlink(fname)\n if not os.path.exists('output_branch'):\n os.mkdir('output_branch')\n\n # Copy all files\n for root, dirs, files in os.walk('output'):\n new_root = os.path.join('output_branch',\n os.path.normpath(os.path.relpath(root, 'output')))\n for dir in dirs:\n if dir.startswith('.'):\n dirs.remove(dir)\n continue\n new = os.path.join(new_root, dir)\n os.mkdir(new)\n for fname in files:\n if fname.startswith('.'):\n continue\n old = os.path.join(root, fname)\n new = os.path.join(new_root, fname)\n if fname.endswith('.html'):\n print('\\nConverting {}:'.format(old))\n cmd = ['tidy5', '-config', 'tidy_config.txt', old]\n with open(new, 'w') as fh:\n try:\n code = subprocess.check_call(cmd, stdout=fh)\n except subprocess.CalledProcessError as err:\n if err.returncode != 1:\n raise\n else:\n shutil.copy(old, new)\n\n for fname in sorted(glob.glob('output/*')):\n continue\n if os.path.isdir(fname):\n shutil.copytree(fname, os.path.join('output_branch', os.path.basename(fname)))\n elif fname.endswith('.html'):\n cmd = ['tidy5', '-config', 'tidy_config.txt', fname]\n with open(os.path.join('output_branch', os.path.basename(fname)), 'w') as fh:\n subprocess.check_call(cmd, stdout=fh)\n else:\n shutil.copy(fname, os.path.join('output_branch', os.path.basename(fname)))\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser('Help')\n subparsers = parser.add_subparsers(dest='subcommand')\n subparsers.required = True\n\n parser_html = subparsers.add_parser('html', help=\"Make the html\")\n parser_html.set_defaults(func=html)\n\n parser_publish = subparsers.add_parser('publish', help=\"Make publishable html, and put it in the output_branch.\")\n parser_publish.set_defaults(func=publish)\n\n parser_reload = subparsers.add_parser('reload', help=\"Make the html, and watch the folder for any changes.\")\n parser_reload.set_defaults(func=reload)\n\n args = parser.parse_args()\n args.func()\n","sub_path":"make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"595791845","text":"import redis\n\nr = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)\n\npubsub = r.pubsub()\npubsub.subscribe('sinewave')\n\nfor item in pubsub.listen():\n if item['type'] == 'message':\n print(item['data'])\n","sub_path":"sinewave_listener.py","file_name":"sinewave_listener.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"361314527","text":"from EventManager.Models.RobotRunnerEvents import RobotRunnerEvents\nfrom EventManager.EventSubscriptionController import EventSubscriptionController\nfrom ConfigValidator.Config.Models.RunTableModel import RunTableModel\nfrom ConfigValidator.Config.Models.FactorModel import FactorModel\nfrom ConfigValidator.Config.Models.RobotRunnerContext import RobotRunnerContext\nfrom ConfigValidator.Config.Models.OperationType import OperationType\n\nimport time\nfrom typing import Dict, List\nfrom pathlib import Path\n\nclass RobotRunnerConfig:\n # =================================================USER SPECIFIC NECESSARY CONFIG=================================================\n # Name for this experiment\n name: str = \"mini_test\"\n # Required ROS version for this experiment to be ran with \n # NOTE: (e.g. ROS2 foxy or eloquent)\n # NOTE: version: 2\n # NOTE: distro: \"foxy\"\n required_ros_version: int = None\n required_ros_distro: str = None\n # Experiment operation types\n operation_type: OperationType = OperationType.AUTO\n # Run settings\n time_between_runs_in_ms: int = 1000\n # Path to store results at\n # NOTE: Path does not need to exist, will be appended with 'name' as specified in this config and created on runtime\n results_output_path: Path = Path(\"~/Documents/experiments\")\n # =================================================USER SPECIFIC UNNECESSARY CONFIG===============================================\n\n # Dynamic configurations can be one-time satisfied here before the program takes the config as-is\n # NOTE: Setting some variable based on some criteria\n def __init__(self):\n \"\"\"Executes immediately after program start, on config load\"\"\"\n\n EventSubscriptionController.subscribe_to_multiple_events([ \n (RobotRunnerEvents.BEFORE_EXPERIMENT, self.before_experiment), \n (RobotRunnerEvents.START_RUN, self.start_run),\n (RobotRunnerEvents.START_MEASUREMENT, self.start_measurement),\n (RobotRunnerEvents.LAUNCH_MISSION, self.launch_mission),\n (RobotRunnerEvents.STOP_MEASUREMENT, self.stop_measurement),\n (RobotRunnerEvents.STOP_RUN, self.stop_run),\n (RobotRunnerEvents.POPULATE_RUN_DATA, self.populate_run_data),\n (RobotRunnerEvents.AFTER_EXPERIMENT, self.after_experiment)\n ])\n \n print(\"Custom config loaded\")\n\n def create_run_table(self) -> List[Dict]:\n \"\"\"Create and return the run_table here. A run_table is a List (rows) of tuples (columns), \n representing each run robot-runner must perform\"\"\"\n run_table = RunTableModel(\n factors = [\n FactorModel(\"example_factor\", ['example_treatment1', 'example_treatment2'])\n ],\n exclude_variations = [\n {\"example_treatment1\"}, # all runs having treatment example_treatment1 will be excluded\n {\"example_treatment1\", \"example_treatment2\"} # all runs having the combination will be excluded\n ] \n )\n run_table.create_experiment_run_table()\n return run_table.get_experiment_run_table()\n\n def before_experiment(self) -> None:\n \"\"\"Perform any activity required before starting the experiment here\"\"\"\n\n print(\"Config.before_experiment() called!\")\n\n def start_run(self, context: RobotRunnerContext) -> None:\n \"\"\"Perform any activity required for starting the run here. \n Activities before and after starting the run should also be performed here.\"\"\"\n \n print(\"Config.start_run() called!\")\n\n def start_measurement(self, context: RobotRunnerContext) -> None:\n print(\"Config.start_measurement called!\")\n\n def launch_mission(self, context: RobotRunnerContext) -> None:\n \"\"\"Perform any activity interacting with the robotic\n system in question (simulated or real-life) here.\"\"\"\n time.sleep(5)\n print(\"Config.launch_mission() called!\")\n\n def stop_measurement(self, context: RobotRunnerContext) -> None:\n print(\"Config.stop_measurement called!\")\n\n def stop_run(self, context: RobotRunnerContext) -> None:\n \"\"\"Perform any activity required for stopping the run here.\n Activities before and after stopping the run should also be performed here.\"\"\"\n \n print(\"Config.stop_run() called!\")\n \n def populate_run_data(self, context: RobotRunnerContext) -> tuple:\n \"\"\"Return the run data as a row for the output manager represented as a tuple\"\"\"\n return None\n\n def after_experiment(self) -> None:\n \"\"\"Perform any activity required after stopping the experiment here\"\"\"\n\n print(\"Config.after_experiment() called!\")\n\n # ===============================================DO NOT ALTER BELOW THIS LINE=================================================\n # NOTE: Do not alter these values\n experiment_path: Path = None\n","sub_path":"experiments/mini_test/mini_test_config.py","file_name":"mini_test_config.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"245297396","text":"\"\"\"\nCopyright (c) 2019 Michael McCartney, Kevin McLoughlin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport queue\nimport logging\nimport fnmatch\nimport requests\nimport functools\nimport threading\n\n\n# -- For Queue Prio\nfrom dataclasses import dataclass, field\nfrom typing import Any\n\nimport asyncio\nfrom aiohttp import web\nimport jinja2\nimport aiohttp_jinja2\n\nfrom . import log\nfrom .base import _HivemindAbstractObject, _HandlerBase\nfrom hivemind.util import global_settings\n\nfrom hivemind.data.abstract.scafold import _DatabaseIntegration\n\n# -- Bsaeic tables required by the system\nfrom hivemind.data.tables import TableDefinition, RequiredTables, NodeRegister\n\n# -- Populate known database mappings\nfrom hivemind.data.contrib import interfaces\n\n\nclass RootServiceHandler(_HandlerBase):\n \"\"\"\n Web handler for the services in order to route the\n data through properly.\n\n # TODO: Move this away from here\n \"\"\"\n async def register_node(self, request):\n \"\"\" Register a _Node \"\"\"\n data = await request.json()\n port = self.controller._register_node(data)\n return web.json_response({ 'result' : port })\n\n\n async def register_service(self, request):\n \"\"\" Register a _Service \"\"\"\n data = await request.json()\n self.controller._register_service(data)\n return web.json_response({ 'result' : True })\n\n\n async def register_subscription(self, request):\n \"\"\" Register a _Subscription \"\"\"\n data = await request.json()\n self.controller._register_subscription(data)\n return web.json_response({ 'result' : True })\n\n\n async def register_task(self, request):\n \"\"\" Register a _Task \"\"\"\n data = await request.json()\n task_connect = self.controller._register_task(data)\n return web.json_response(task_connect)\n\n\n async def heartbeat(self, request):\n \"\"\" Basic alive test \"\"\"\n return web.json_response({'result' : True})\n\n\n async def service_dispatch(self, request):\n \"\"\" Dispatch service command \"\"\"\n path = request.match_info['tail']\n data = await request.json()\n passback = self.controller._delegate(path, data)\n return web.json_response(passback)\n\n\n async def task_data_dispatch(self, request):\n # TODO\n pass\n\n\n async def index_post(self, request):\n # FIXME: Why do we need this?\n return web.json_response({'result': True})\n\n\n @aiohttp_jinja2.template(\"hive_index.html\")\n async def index(self, request):\n return self.controller.base_context()\n\n\n@dataclass(order=True)\nclass PrioritizedDispatch:\n \"\"\"\n Item used to identify the prio of arbitrary payload\n data from our services. Ripped from py docs.\n \"\"\"\n priority: int\n name: Any=field(compare=False)\n node: Any=field(compare=False)\n payload: Any=field(compare=False)\n\n\nclass RootController(_HivemindAbstractObject):\n \"\"\"\n Basic impl of subscription service handler\n \"\"\"\n\n #\n # The node states that determine how we handle them.\n #\n NODE_PENDING = 'pending'\n NODE_ONLINE = 'online'\n NODE_TERM = 'terminate'\n\n class SubscriptionInfo(object):\n \"\"\"\n Subscription data held by the RootController\n \"\"\"\n def __init__(self, endpoint, port, proxy):\n self._endpoint = endpoint\n self._port = port\n self._proxy = proxy\n\n @property\n def port(self):\n return self._port\n\n\n @property\n def endpoint(self):\n return self._endpoint\n\n\n @property\n def proxy(self):\n return self._proxy\n \n\n def __init__(self, **kwargs):\n _HivemindAbstractObject.__init__(\n self,\n logger=kwargs.get('logger', None)\n )\n\n self._settings = kwargs\n\n self._port_count = 0\n\n # Known nodes out in the ecosystem\n # self._nodes = set()\n\n # Known services actively running\n self._services = {}\n\n # Requested subscriptions\n self._subscriptions = {}\n\n # Registered tasks\n self._tasks = {}\n\n # How we know to shut down our dispatch threads\n self._abort = False\n\n #\n # To avoid bogging down slow processing subscriptions,\n # we use a set of response threads to make sure things\n # stay nice and light as well as handle instances of\n # bugged nodes without halting the rest of the execution\n # state.\n #\n self._response_threads = []\n self._response_lock = threading.RLock()\n self._response_condition = threading.Condition(self._response_lock)\n self._response_queue = queue.PriorityQueue()\n\n #\n # Startup utilities\n #\n self._startup_condition = kwargs.get('startup_condition', None)\n\n # We don't start the database until we're within the run() command\n # to make sure all database interactions with this object happen\n # on the same node.\n self._database = None\n\n\n @classmethod\n def send_to_controller(cls, service, payload):\n \"\"\"\n Utility for shipping messages to our controller which\n will then route to the various subscribers (alternate\n thread)\n \"\"\"\n json_data = {\n 'service' : service.name,\n 'node' : service.node.name,\n 'payload' : payload,\n 'priority' : 1 # TODO\n }\n\n default_port = global_settings['default_port']\n result = requests.post(\n f'http://127.0.0.1:{default_port}/service/{service.name}',\n json=json_data\n )\n result.raise_for_status()\n return 0 # We'll need some kind of passback\n\n\n @classmethod\n def _register_post(cls, type_, json_data):\n \"\"\"\n Utility for running a POST at the controller service\n \"\"\"\n default_port = global_settings['default_port']\n result = requests.post(\n f'http://127.0.0.1:{default_port}/register/{type_}',\n json=json_data\n )\n result.raise_for_status()\n return result.json() # Should be the port\n\n # -- Registration Methods (Called from the _Node classes)\n\n @classmethod\n def register_node(cls, node):\n \"\"\"\n Add the node to our root (if not already there). If it is,\n we simply ignore the request.\n \"\"\"\n return cls._register_post('node', {\n 'name' : node.name,\n 'status': cls.NODE_PENDING\n })\n\n\n @classmethod\n def deregister_node(cls, node):\n \"\"\"\n Dismantel a node\n \"\"\"\n return cls._register_post('node', {\n 'name' : node.name,\n 'status': cls.NODE_TERM\n })\n\n\n @classmethod\n def enable_node(cls, node):\n \"\"\"\n Enable the node\n \"\"\"\n return cls._register_post('node', {\n 'name' : node.name,\n 'status': cls.NODE_ONLINE\n })\n\n\n @classmethod\n def register_service(cls, service) -> dict:\n \"\"\"\n Register a service. This is called from a _Node\n\n :param service: The _Service instance that contains\n the required info.\n :return: dict\n \"\"\"\n return cls._register_post('service', {\n 'node' : service.node.name,\n 'name' : service.name,\n })\n\n\n @classmethod\n def register_subscription(cls, subscription) -> dict:\n \"\"\"\n Register a subscription. This is called from a _Node\n\n :param subscription: The _Subscription instance that contains\n the required info.\n :return: dict\n \"\"\"\n return cls._register_post('subscription', {\n 'node' : subscription.node.name,\n 'filter' : subscription.filter,\n 'endpoint' : subscription.endpoint,\n 'port' : subscription.node.port\n })\n\n\n @classmethod\n def register_task(cls, task):\n \"\"\"\n Register a task. This is call from a _Node (specifically a TaskNode)\n\n :param task: _Task instance that we'll be using\n :return dict:\n \"\"\"\n return cls._register_post('task', {\n 'node' : task.node.name,\n 'name' : task.name,\n 'endpoint' : task.endpoint,\n 'port' : task.node.port\n })\n\n\n @classmethod\n def exec_(cls, logging=None):\n \"\"\"\n Generic call used by most entry scripts to start the root without\n having to create a custom local instance\n \"\"\"\n log.start(logging is not None)\n controller = cls()\n controller.run()\n return controller\n\n # -- Virtual Interface\n\n def additional_routes(self) -> list:\n \"\"\"\n Overload if required. Return a list of aiohttp routes that we\n add to the web server for consumption. The main endpoints are\n injected already so only user specific endpoints should live\n here. The default implementation fills in the Task endpoint.\n\n :return: list\n \"\"\"\n from hivemind.util.tasknode import TaskNode\n endpoint = functools.partial(TaskNode.tasks_endpoint, self)\n return [\n web.get('/tasks', endpoint)\n ]\n\n # -- Overloaded\n\n def run(self, loop=None):\n \"\"\"\n Our run operation is built to handle the various incoming\n requests and respond to the required items in time.\n \"\"\"\n self._app = None\n try:\n if not loop:\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n\n #\n # Data layer interface\n #\n self._init_database()\n\n self._handler_class = RootServiceHandler()\n self._handler_class.controller = self # Reverse pointer\n\n self._app = web.Application(loop=loop)\n\n # Setup the template engine\n aiohttp_jinja2.setup(\n self._app,\n loader=jinja2.FileSystemLoader(\n global_settings['hive_root'] + '/static/templates'\n )\n )\n\n self._app.add_routes([\n web.post('/register/node',\n self._handler_class.register_node),\n\n web.post('/register/service',\n self._handler_class.register_service),\n\n web.post('/register/subscription',\n self._handler_class.register_subscription),\n\n web.post('/register/task',\n self._handler_class.register_task),\n\n web.get('/heartbeat',\n self._handler_class.heartbeat),\n\n web.post('/heartbeat',\n self._handler_class.heartbeat),\n\n web.post('/service/{tail:.*}',\n self._handler_class.service_dispatch),\n\n web.post('/',\n self._handler_class.index_post),\n web.get('/',\n self._handler_class.index),\n\n # -- For development - need a \"collectstatic\" eq\n web.static('/static',\n global_settings['static_dirs'][0],\n follow_symlinks=True)\n ])\n\n self._app.add_routes(self.additional_routes())\n\n #\n # Before running our server, let's start our queue threads\n # that deal with linking back to other services.\n #\n for i in range(self._settings.get('response_threads', 2)):\n res_thread = threading.Thread(\n target=self._dispatch,\n name=f'response_thread_{i}'\n )\n res_thread.start()\n self._response_threads.append(res_thread)\n\n\n default_port = global_settings['default_port']\n self.log_info(f\"Serving on {default_port}...\")\n\n if self._startup_condition:\n # Alert waiting parties that we're ready\n with self._startup_condition:\n self._startup_condition.notify_all()\n\n # Just keep serving!\n web.run_app(\n self._app,\n port=default_port,\n handle_signals=False,\n access_log=self.logger\n )\n\n except Exception as e:\n if not isinstance(e, KeyboardInterrupt):\n import traceback\n self.log_critical(traceback.format_exc())\n print (traceback.format_exc())\n\n finally:\n asyncio.run(self._shutdown())\n\n if self._startup_condition:\n # Make sure we clean up if something went wrong too\n with self._startup_condition:\n self._startup_condition.notify_all()\n\n return\n\n def base_context(self):\n \"\"\"\n The initial context we use when rendering jinja2 templates\n for use in the hive webfront\n :return: dict\n \"\"\"\n return {\n '_hive_name' : global_settings['name']\n }\n\n # -- Private Interface (reserved for running instance)\n\n def _node_exists(self, name):\n \"\"\"\n Check the database for the node\n \"\"\"\n query = self._database.new_query(\n NodeRegister, NodeRegister.name.equals(name)\n )\n return (query.count() > 0)\n\n\n def _get_node(self, name: str) -> (None, NodeRegister):\n \"\"\"\n Aquire a node if it exists. Otherwise return None\n :param name: The name of the node to search for\n :return: NodeRegister|None\n \"\"\"\n return self._database.new_query(\n NodeRegister, name=name\n ).get_or_null()\n\n def _register_node(self, payload):\n \"\"\"\n Register a node with our setup\n \"\"\"\n assert \\\n isinstance(payload, dict), \\\n 'Registration payload must be a dict'\n assert \\\n all(k in payload for k in ('name', 'status')), \\\n 'Registration payload missing name or status'\n\n if payload['status'] != self.NODE_TERM:\n self.log_info(f\"Register Node: {payload['name']}\")\n else:\n self.log_info(f\"Deregister Node: {payload['name']}\")\n\n node = self._get_node(payload['name'])\n\n with self.lock:\n if not node:\n\n if payload['status'] == self.NODE_TERM:\n # We're removing the node. Shouldn't be\n # here\n return 0\n\n self._port_count += 1\n port = global_settings['default_port'] + self._port_count\n self._database.create(\n NodeRegister,\n name=payload['name'],\n status=payload['status'],\n port=port\n )\n return port\n\n else:\n destroy = None\n\n # We've seen this node before (at least - we should\n # have)\n if payload['status'] == self.NODE_TERM:\n # Clean up this node\n self._remove_node(node)\n return 0\n else:\n node.status = payload['status']\n self._database.save(node)\n return node.port\n\n\n def _remove_node(self, node_instance: NodeRegister) -> None:\n \"\"\"\n Terminate all connections with a node. Because we base everything\n off the proxy, this becomes doable without too much headache.\n \"\"\"\n with self.lock: # reentrant\n\n if node_instance in self._services:\n self._services.pop(node_instance)\n\n if node_instance in self._tasks:\n self._tasks.pop(node_instance)\n\n for filter_, subinfo in self._subscriptions.items():\n to_rem = []\n for d in subinfo:\n if d.proxy == node_instance:\n to_rem.append(d)\n for d in to_rem:\n subinfo.remove(d)\n\n self._database.delete(node_instance)\n\n\n def _register_service(self, payload):\n \"\"\"\n Register a service\n \"\"\"\n assert isinstance(payload, dict), \\\n 'Service Registration payload must be a dict'\n\n assert all(k in payload for k in ('node', 'name')), \\\n 'Service Registration payload missing \"node\" or \"name\"'\n\n self.log_info(f\"Register Service: {payload['name']} to {payload['node']}\")\n\n node = self._get_node(payload['node'])\n assert node, f'Node {payload[\"node\"]} not found'\n\n with self.lock:\n known_services = self._services.setdefault(node, {})\n\n assert \\\n payload['name'] not in known_services, \\\n f'The service {payload[\"name\"]} already exists for {payload[\"node\"]}'\n\n known_services[payload['name']] = payload\n\n return 0\n\n\n def _register_subscription(self, payload):\n \"\"\"\n Register a subscription\n \"\"\"\n assert \\\n isinstance(payload, dict), \\\n 'Subscription Registration payload must be a dict'\n assert \\\n all(k in payload for k in ('node', 'filter', 'endpoint', 'port')), \\\n 'Subscription Registration payload missing \"node\", ' \\\n ' \"filter\", \"port\" or \"endpoint\"'\n\n node = self._get_node(payload['node'])\n assert node, f'Node {payload[\"node\"]} not found'\n\n self.log_info(\n f\"Register Subscription: {payload['node']} to {payload['filter']}\"\n )\n\n with self.lock:\n\n known_subscriptions = self._subscriptions.setdefault(\n payload['filter'], []\n )\n known_subscriptions.append(\n self.SubscriptionInfo(\n payload['endpoint'],\n payload['port'],\n node\n )\n )\n\n return 0\n\n\n def _register_task(self, payload):\n \"\"\"\n Register a task\n \"\"\"\n assert \\\n isinstance(payload, dict), \\\n 'Task Registration payload must be a dict'\n assert \\\n all(k in payload for k in ('node', 'filter', 'endpoint', 'port')), \\\n 'Task Registration payload missing \"node\", ' \\\n ' \"filter\", \"port\" or \"endpoint\"'\n\n node = self._get_node(payload['node'])\n assert node, f'Node {payload[\"node\"]} not found'\n\n self.log_info(\n f\"Register Task: {payload['node']} to {payload['name']}\"\n )\n\n task_required_data = {}\n\n with self.lock:\n known_tasks = self._tasks.setdefault(proxy, {})\n\n assert \\\n payload['name'] not in known_tasks, \\\n f'The task {payload[\"name\"]} already exists for {payload[\"node\"]}'\n\n #\n # We have to do quite a few things here...\n # 1. Build an endpoint for the task\n # task_required_data['endpoint'] = \n # 2. Based on the task info and any parameter definitions, we hold\n # that until we request that action be taken\n # 3. Cron is obviously a little different but the idea is mostly the same\n #\n\n return task_required_data\n\n\n\n def _delegate(self, path, payload):\n \"\"\"\n Based on the path, we have to handle our work accordingly.\n \"\"\"\n service_name = path.split('/')[-1]\n self.log_debug(f\"Message from: {service_name}\")\n\n self._response_queue.put(PrioritizedDispatch(\n payload.get('priority', 1), # Prio (lower is higher prio!)\n service_name, # Name\n payload.get('node', None), # Node\n payload.get('payload', None) # Payload\n ))\n\n with self._response_condition:\n self._response_condition.notify()\n\n return { 'result' : True } # For now\n\n\n\n def _recieve_task_data(self, path, payload):\n \"\"\"\n Based on the task information coming in, we store the information for\n our user to digest via the web server.\n :param path: The url path that we've entered with\n :param payload: The payload that we're given\n \"\"\"\n return 0\n\n\n async def _shutdown(self):\n if self._app:\n await self._app.shutdown()\n with self._response_condition:\n self._abort = True\n self._response_condition.notify_all()\n self._database.disconnect()\n\n\n def _dispatch(self):\n \"\"\"\n Based on what's available from the queue, ship out messages\n to any listening subsribers \n \"\"\"\n while True:\n\n with self._response_condition:\n while (not self._abort) and self._response_queue.empty():\n self._response_condition.wait()\n\n dispatch_object = None\n with self._response_lock:\n if self._abort:\n break\n\n try:\n dispatch_object = self._response_queue.get_nowait()\n except queue.Empty:\n continue # We must have missed it\n\n if not dispatch_object:\n continue # How??\n\n # We have a dispatch - locate any matching subscriptions\n for filter_ in self._subscriptions:\n if fnmatch.fnmatch(dispatch_object.name, filter_):\n\n #\n # We have a match - now it's time to ship this\n # payload to the subscriptions undernearth\n #\n for si in self._subscriptions[filter_]:\n url = f'http://127.0.0.1:{si.port}{si.endpoint}'\n self._send_to_subscription(\n url, dispatch_object.payload\n )\n\n\n def _send_to_subscription(self, url, payload) -> None:\n result = requests.post(url, json=payload)\n try:\n result.raise_for_status()\n except Exception as e:\n print (\"Sending to sub failed!\") # FIXME\n\n\n def _init_database(self) -> None:\n \"\"\"\n Initialize the database and make sure we have all the right bits\n :return: None\n \"\"\"\n self._database = _DatabaseIntegration.start_database(\n global_settings['database']\n )\n\n active_tables = self._database.get_table_names()\n\n if TableDefinition.db_name() not in active_tables:\n #\n # The table definition is a rather vital table\n # We need to make sure it's available\n #\n self._database._create_table(TableDefinition)\n active_tables.append(TableDefinition.db_name())\n\n for name, table in RequiredTables:\n\n if name not in active_tables:\n self._database._create_table(table)\n TableDefinition.register_table(self._database, table)\n\n # else:\n # TableDefinition.validate_table(table)\n","sub_path":"hivemind/core/root.py","file_name":"root.py","file_ext":"py","file_size_in_byte":24194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"638481938","text":"#!/usr/bin/env python3\n\nfrom os.path import isfile,getmtime\nfrom glob import glob\nfrom time import sleep,time\nfrom os import system\nfrom subprocess import Popen,PIPE\nfrom lib.utils import configuration\n\nconfig = configuration('shape_params.yaml')\nparams=config.getParams()\n\nscripts_dir=params['paths']['scripts_dir']\n\nlocal_data=params['paths']['data_dir']\nscript='process_file.py'\nyaml_file = 'shape_params.yaml'\nstack='s3://mousebraindata-open/MD657'\nexec_dir=params['paths']['scripts_dir']\n\n\ndef runPipe(command):\n print('cmd=',command)\n p=Popen(command.split(),stdout=PIPE,stderr=PIPE)\n L=p.communicate()\n stdout=L[0].decode(\"utf-8\").split('\\n')\n stderr=L[1].decode(\"utf-8\").split('\\n')\n return stdout,stderr\n\ndef run(command,out):\n print('cmd=',command,'out=',out)\n outfile=open(out,'w')\n Popen(command.split(),stdout=outfile,stderr=outfile)\n\ndef Last_Modified(file_name):\n try:\n mtime = getmtime(file_name)\n except OSError:\n mtime = 0\n return(mtime)\n\nif __name__=='__main__':\n Recent=False\n for logfile in glob(exec_dir+'/Controller*.log'):\n gap=time() - Last_Modified(logfile)\n if gap <120: # allow 2 minute idle\n print(logfile,'gap is %6.1f'%gap)\n Recent=True\n break\n if(not Recent):\n # Check that another 'controller' is not running\n stdout,stderr = runPipe('ps aux')\n Other_controller=False\n for line in stdout:\n if 'Controller.py' in line:\n Other_controller=True\n break\n \n if Other_controller:\n print('Other Controller.py is running')\n else:\n command='{0}/Controller.py {1} {2}'\\\n .format(exec_dir,stack,yaml_file)\n output='{0}/Controller-{1}.log'.format(exec_dir,int(time()))\n run(command,output)\n\n # Controller.py [-h] scripts_dir script s3location local_data\n","sub_path":"scripts/watchdog.py","file_name":"watchdog.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"654532248","text":"#Created by Oranje Maan\r\n#12 October 2018\r\n#Prime Factorization Function\r\n\r\n\r\ndef primeFactorization(number):\r\n #List of variables\r\n beenUsed = False\r\n uncertainty = False\r\n continuation = True\r\n count = 0\r\n currentPrime = 0\r\n isNegative = False\r\n primeNumberList = []\r\n primesList = []\r\n useNumber = 0\r\n #Checking to see if input is an integer\r\n try:\r\n int(number)\r\n except:\r\n print(\"The input was not an integer.\")\r\n return\r\n #Assigning a to input\r\n number = int(number)\r\n a = number\r\n #Reading a file with prime numbers\r\n primeNumberList = open(\"listPrime.txt\",\"r\")\r\n #Checking to see if number is negative\r\n if(number < 0):\r\n number = -number\r\n isNegative = True\r\n a = number\r\n #Looking for special cases\r\n if(number == 1):\r\n print(\"1 is neither a prime nor a composite number. It's only factor is itself.\")\r\n elif(number == 0):\r\n print(\"0 is neither a prime nor composite number. It's only factor is itself.\")\r\n else:\r\n #Finding the amount of prime numbers in listPrime smaller than the inputed number\r\n while(continuation):\r\n try:\r\n currentPrime = int(primeNumberList.readline())\r\n except:\r\n continuation = False\r\n uncertainty = True\r\n if (number <= currentPrime):\r\n continuation = False\r\n else:\r\n count = count + 1\r\n primesList.append(currentPrime)\r\n #Checking to see number of times dividable by every prime in primesList\r\n for i in range(count):\r\n continuation = True\r\n useNumber = 0\r\n while (continuation):\r\n if (a % primesList[i] == 0):\r\n useNumber = useNumber + 1\r\n beenUsed = True\r\n a = a / primesList[i]\r\n else:\r\n continuation = False\r\n if(useNumber > 0):\r\n print(str(primesList[i]) + \" - \" + str(useNumber))\r\n #Checking to see if prime\r\n if (beenUsed == False and isNegative == False):\r\n print(str(a) + \" is a prime number. It's only factor is itself and one.\")\r\n #Checking to see if negative\r\n if (isNegative):\r\n print(\"As this is a negative number, one and only one of the factors has to be negative.\")\r\n #Checking if in bounds of certainty\r\n if (uncertainty):\r\n print(\"The number is larger than the largest prime in the list. The results may be innacurate.\")\r\n\r\n#Calling function in main() \r\ndef main():\r\n number = input(\"Give an integer please.\")\r\n primeFactorization(number)\r\n \r\nmain()\r\n","sub_path":"Prime Factorization(3.7).py","file_name":"Prime Factorization(3.7).py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"577118435","text":"\"\"\"\nUses DataAcquisition class to extract data...\n\"\"\"\n\n\nimport os\nimport zipfile\nimport shutil\nfrom functools import partial\nfrom multiprocessing import Pool\n\nimport wget\nimport numpy as np\nimport pandas as pd\nimport librosa\nimport soundfile as sf\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n\nfrom aircraft_detector.utils.utils import (\n print_verbose,\n retrieve_files,\n refresh_directory,\n)\nimport aircraft_detector.utils.plot_helper as ph\n\n\nclass DataAcquisition:\n \"\"\"\n\n\n\n \"\"\"\n\n def __init__(self, root_directory):\n self._dir_root = root_directory\n self._sample_rate = 44100\n self.verbose = True\n self.super_verbose = False\n\n def import_audio_esc50(self):\n \"\"\"Download and extract the ESC-50 dataset.\n \"\"\"\n # set destination\n dir_dest = os.path.join(self._dir_root, \"Raw\", \"Aircraft\")\n if not os.path.exists(dir_dest):\n os.makedirs(dir_dest)\n # download\n fp_dest = os.path.join(dir_dest, \"ESC-50-master.zip\")\n fp_unzipped = os.path.join(dir_dest, \"ESC-50-master\")\n if not os.path.exists(fp_unzipped):\n print_verbose(self.verbose, \"Downloading...\")\n url = \"https://github.com/karoldvl/ESC-50/archive/master.zip\"\n wget.download(url, dir_dest)\n print_verbose(self.verbose, \"Download finished.\")\n # unzip\n with zipfile.ZipFile(fp_dest, \"r\") as zip_ref:\n zip_ref.extractall(dir_dest)\n print_verbose(\n self.verbose, \"Extracted ESC-50 to %s\" % os.path.abspath(fp_dest)\n )\n else:\n print_verbose(\n self.verbose,\n \"ESC-50 has already been extracted to %s\" % os.path.abspath(fp_dest),\n )\n\n def extract_audio_from_esc50(self, categories, db_trim=30, overwrite=False):\n \"\"\"Export relevant categories from the ESC-50 dataset.\n\n Keyword arguments:\n categories -- iterable containing the categories from the ESC-50\n dataset that should be extracted,\n db_trim -- threshold for the trimming of silence (default: 30dB),\n overwrite -- whether to overwrite existing data (default: False),\n verbose -- whether to print each file export (default: False).\n \"\"\"\n # set directories\n dir_esc50 = os.path.join(self._dir_root, \"Raw\", \"Aircraft\", \"ESC-50-master\")\n fp_esc50_csv = os.path.join(dir_esc50, \"meta\", \"esc50.csv\")\n dir_input = os.path.join(dir_esc50, \"audio\")\n dir_output = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\", \"Full\"\n )\n # check if output directory exists\n if os.path.exists(dir_output):\n if overwrite:\n shutil.rmtree(dir_output)\n else:\n print_verbose(\"Output directory already exists.\")\n return\n os.makedirs(os.path.join(dir_output))\n # get dataframe with filenames, categories\n df = pd.read_csv(fp_esc50_csv)\n df.drop([\"fold\", \"target\", \"esc10\", \"src_file\", \"take\"], axis=1, inplace=True)\n df.replace(\"_\", \"-\", inplace=True, regex=True) # less tedious later\n # extract relevant categories\n df_binary = df.loc[df[\"category\"].isin(categories)]\n categories = df_binary[\"category\"].unique()\n\n # loop over categories\n for cat in categories:\n # load files belonging to category\n files_src = df_binary.loc[df_binary[\"category\"] == cat][\n \"filename\"\n ].to_list()\n # loop over files\n for i, file in enumerate(files_src):\n src = os.path.join(dir_input, file)\n # load audio\n y, sr = librosa.load(src, sr=self._sample_rate)\n # trim audio\n y_trim, _ = librosa.effects.trim(y, top_db=db_trim)\n # export audio\n fn_out = \"%s_%02d.wav\" % (cat, i + 1)\n dest = os.path.join(dir_output, fn_out)\n sf.write(dest, y_trim, samplerate=sr)\n # printing\n if self.super_verbose:\n # set trim message\n if len(y_trim) < len(y):\n trim_msg = \" (trimmed to %.3f sec.)\" % (len(y_trim) / sr)\n else:\n trim_msg = \"\"\n print(\"%s ---> %s%s\" % (file, dest, trim_msg))\n\n print_verbose(\n self.verbose,\n \"Finished exporting %d files (sr = %d Hz)\" % (len(df_binary), sr),\n )\n\n def generate_silence_category(self, n_instances, duration):\n \"\"\"Generates a 'silence' category consisting of white noise.\n\n Keyword arguments:\n n_instances -- number of instances (recordings) generated,\n duration -- duration of each recording in seconds,\n verbose -- whether to print the generation of each file\n (default: False)\n \"\"\"\n # generate silence\n np.random.seed(42)\n silence = np.random.uniform(\n low=-1.0, high=1.0, size=(n_instances, duration * self._sample_rate)\n )\n # loop over instances\n for i in range(n_instances):\n # export to file\n fn = \"silence_%02d.wav\" % (i + 1)\n fp = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\", \"Full\", fn\n )\n sf.write(fp, silence[i], samplerate=self._sample_rate)\n print_verbose(self.super_verbose, \"Generated file: '%s'\" % fp)\n\n print_verbose(\n self.verbose, \"Finished generating %d instances of silence.\" % n_instances\n )\n\n def split_dataset(self, train_test_ratio=0.8, train_val_ratio=0.8, overwrite=False):\n \"\"\"Split the dataset into a training, validation and test subset.\n\n Keyword arguments:\n train_test_ratio -- ratio of the training set over the complete,\n set, the remainder will be assigned to the test subset\n (default: 0.8),\n train_val_ratio -- ratio of the actual training set over the\n training set, the remainder will be assigned to the validation\n subset (default: 0.8),\n overwrite -- whether to overwrite existing data (default: False).\n \"\"\"\n # directories\n dir_input = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\", \"Full\"\n )\n dir_root_output = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\"\n )\n # check if data should be overwritten if it exists\n if os.path.exists(os.path.join(dir_root_output, \"Train\")) and not overwrite:\n print_verbose(\n self.verbose, \"Dataset already exists and should not be overwritten.\"\n )\n return\n # refresh the output directories\n subdirs = [\"Train\", \"Val\", \"Test\"]\n for subdir in subdirs:\n refresh_directory(os.path.join(dir_root_output, subdir))\n\n # read files into array for easy slicing\n files = np.array(retrieve_files(dir_input))\n # get categories\n file_categories = np.array([os.path.split(f)[-1].split(\"_\")[0] for f in files])\n categories = np.unique(file_categories)\n files_per_category = len(files) // len(categories)\n\n # get train, val, test indices per category\n train_idcs, test_idcs = train_test_split(\n np.arange(files_per_category), train_size=train_test_ratio, random_state=42\n )\n train_idcs, val_idcs = train_test_split(\n train_idcs, train_size=train_val_ratio, random_state=42\n )\n print_verbose(\n self.verbose,\n \"Split per category (Train, Val, Test): (%d, %d, %d)\"\n % (len(train_idcs), len(val_idcs), len(test_idcs)),\n )\n\n # extract train, val, test files using indices and export to subdirs\n indices = [train_idcs, val_idcs, test_idcs]\n for idcs, subdir in zip(indices, subdirs):\n files_set = [\n f\n for f in files\n if int(os.path.split(f)[-1].split(\"_\")[-1].split(\".\")[0]) - 1 in idcs\n ]\n for file in files_set:\n dest = os.path.join(dir_root_output, subdir, os.path.split(file)[-1])\n shutil.copyfile(file, dest)\n\n # remove the now redundant 'Full' input directory\n shutil.rmtree(dir_input)\n\n def augment_training_data(self, overwrite=False):\n \"\"\"Augment the training data.\n\n Keyword arguments:\n overwrite -- whether to overwrite existing data (default: False).\n Augmentations include:\n Pitch Shift at [-2, -1, 1, 2] octaves,\n Time Stretch with ratios of [0.70,0.85, 1.15, 1.30],\n Intra-category mixing with four random files belonging to the\n same category.\n The 'silence' category (if generated) is omitted from the augmentation.\n \"\"\"\n # set directories\n dir_input = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\", \"Train\"\n )\n dir_root_output = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\"\n )\n\n # get files, but ignore augmentation for 'silence' category\n files = [\n os.path.join(dir_input, f)\n for f in sorted(os.listdir(dir_input))\n if os.path.split(f)[-1].split(\"_\")[0] != \"silence\"\n ]\n\n # loop through augmentations\n augmentations = [\"Pitch Shift\", \"Time Stretch\", \"Class Mix\"]\n do_augmentations = []\n for aug in augmentations:\n # set output directory\n dir_output = os.path.join(dir_root_output, \"Train \" + aug)\n # check if it exists or should be overwritten\n if overwrite or not os.path.exists(dir_output):\n refresh_directory(dir_output)\n do_augmentations.append(aug)\n\n # do augmentations\n if len(do_augmentations) > 0:\n for aug in do_augmentations:\n dir_output = os.path.join(dir_root_output, \"Train \" + aug)\n if aug == \"Class Mix\":\n # generate a list of directory-specific 'seeds' from the given seed\n # to preserve reproducible randomness while multiprocessing\n np.random.seed(42)\n seeds = np.random.randint(0, 10 * len(files), len(files))\n\n part = partial(\n self._augment_class_mix, dir_out=dir_output, all_files=files\n )\n\n with Pool(processes=os.cpu_count() - 1) as pool:\n pool.starmap(part, list(zip(files, seeds)))\n\n elif aug == \"Pitch Shift\":\n part = partial(self._augment_pitch_shift, dir_out=dir_output)\n\n with Pool(processes=os.cpu_count() - 1) as pool:\n pool.map(part, files)\n\n elif aug == \"Time Stretch\":\n part = partial(self._augment_time_stretch, dir_out=dir_output)\n\n with Pool(processes=os.cpu_count() - 1) as pool:\n pool.map(part, files)\n\n print_verbose(\n self.verbose,\n \"Augmentation: %d --> %d files using %s augmentation\"\n % (\n len(files),\n len(do_augmentations) * 4 * len(files),\n do_augmentations,\n ),\n )\n else:\n print_verbose(self.verbose, \"Augmentation has already been done.\")\n\n def _augment_class_mix(self, file, seed, dir_out, all_files):\n\n # load file\n y, sr = librosa.load(file, sr=self._sample_rate)\n # mix the audio with another recording from the same category\n category = os.path.split(file)[-1].split(\"_\")[0]\n files_category = [\n f\n for f in all_files\n if ((os.path.split(f)[-1].split(\"_\")[0] == category) and (f != file))\n ]\n\n # set random, unique seed per process\n np.random.seed(seed)\n # get unique files to mix with\n n_mixes = 4\n files_to_mix = np.random.choice(files_category, size=n_mixes, replace=False)\n\n for i in range(n_mixes):\n # select random mix ratio and random sample offset (circular)\n mix_ratio = np.random.uniform(low=0.2, high=0.5)\n offset = int(np.random.uniform(low=0, high=5) * sr)\n # load file\n y_mix, _ = librosa.load(files_to_mix[i], sr=sr)\n\n # pad/truncate y_mix so that it has the same length as y\n if len(y) > len(y_mix):\n # pad with noise\n padding = np.random.uniform(\n low=-1.0, high=1.0, size=len(y) - len(y_mix)\n )\n y_mix = np.concatenate((y_mix, padding), axis=0)\n elif len(y) < len(y_mix):\n # start sampling at random starting index\n idx = np.random.randint(len(y_mix) - len(y))\n y_mix = y_mix[idx : idx + len(y)]\n\n # apply offset\n y_mix = np.roll(y_mix, offset)\n # mix audio\n y_aug = y + y_mix * mix_ratio\n\n # export to file\n dest = os.path.join(\n dir_out, \"%s-cm%d.wav\" % (os.path.split(file)[-1].split(\".\")[0], i + 1)\n )\n sf.write(dest, y_aug, samplerate=sr)\n\n def _augment_pitch_shift(self, file, dir_out):\n # load file\n y, sr = librosa.load(file, sr=self._sample_rate)\n\n # pitch shift the audio\n shifts = [-2, -1, 1, 2]\n for i, shift in enumerate(shifts):\n y_aug = librosa.effects.pitch_shift(y, sr, shift)\n # export to file\n dest = os.path.join(\n dir_out, \"%s-ps%d.wav\" % (os.path.split(file)[-1].split(\".\")[0], i + 1),\n )\n sf.write(dest, y_aug, samplerate=sr)\n\n def _augment_time_stretch(self, file, dir_out):\n # load file\n y, sr = librosa.load(file, sr=self._sample_rate)\n\n # time stretch the audio\n stretches = [0.7, 0.85, 1.15, 1.3]\n for i, stretch in enumerate(stretches):\n y_aug = librosa.effects.time_stretch(y, stretch)\n # export to file\n dest = os.path.join(\n dir_out, \"%s-ts%d.wav\" % (os.path.split(file)[-1].split(\".\")[0], i + 1),\n )\n sf.write(dest, y_aug, samplerate=sr)\n\n def plot_examples(self, set_name, categories=None, idx=None):\n \"\"\"Plot audio data belonging to a given dataset.\n\n Keyword arguments:\n set_name -- set to be plotted (e.g. 'Test')\n categories -- iterable containing the original categories\n (airplane, engine, etc.) to be plotted (default: all),\n idx -- index of the file selected for plotting (default: 0).\n \"\"\"\n # get directory and available files\n dir_audio = os.path.join(\n self._dir_root, \"Aircraft Classification\", \"Audio\", set_name\n )\n files_audio = [\n os.path.join(dir_audio, f) for f in sorted(os.listdir(dir_audio))\n ]\n # plot all categories if not given\n if categories is None:\n file_categories = [os.path.split(f)[-1].split(\"_\")[0] for f in files_audio]\n categories = sorted(list(set(file_categories)))\n # plot the first example if index not given\n if idx is None:\n idx = 0\n\n # setup figure, subfigures\n n_categories = len(categories)\n fig = plt.figure(figsize=(6 * n_categories, 2), constrained_layout=False)\n gs = fig.add_gridspec(1, n_categories)\n\n # loop through categories\n for i, cat in enumerate(categories):\n # load audio file\n file_audio = [\n f for f in files_audio if os.path.split(f)[-1].split(\"_\")[0] == cat\n ][idx]\n fn = os.path.split(file_audio)[-1]\n # plot audio\n ax = fig.add_subplot(gs[i])\n ph.plot_audio(file_audio, sr=self._sample_rate, waveplot=True)\n ax.set_title(\"'%s' (sr = %d)\" % (fn, self._sample_rate))\n","sub_path":"aircraft_detector/aircraft_classification/data_acquisition.py","file_name":"data_acquisition.py","file_ext":"py","file_size_in_byte":16427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"404617397","text":"def int_func(str):\n\t\n\treturn str.capitalize()\n\t\na = input(\"Введите слово из маленьких латинских букв \")\nresult = int_func(a)\nprint(result)\n\na = input(\"Введите строку из слов, разделенных пробелом \")\nlist = a.split()\nlist2 = []\nfor elem in list:\n\tlist2.append(int_func(elem))\nprint(\" \".join(list2))\n\t\n\n","sub_path":"lesson_3/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"201005078","text":"import turtle\r\n\r\npen=turtle.Turtle()\r\nwindow=turtle.Screen()\r\ndistance=10\r\n\r\npen.pensize(4)\r\npen.shape=(\"turtle\")\r\npen.hideturtle()\r\n\r\nfor count in range(10):\r\n if count % 2 ==0:\r\n pen.color(\"blue\")\r\n else:\r\n pen.color(\"red\")\r\n pen.circle(distance)\r\n pen.penup()\r\n pen.goto(pen.xcor(),pen.ycor()-10)\r\n pen.pendown()\r\n distance=distance+10\r\n\r\nwindow.mainloop()","sub_path":"2016/Cocentric circles (even and odds).py","file_name":"Cocentric circles (even and odds).py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"358473049","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom sentcorr import SentCorr\nimport unittest\n\nclass EqualSentences(unittest.TestCase):\n mycentcorr = SentCorr()\n synonym_table = mycentcorr.creat_synonym_table()\n\n def test_equal_sent(self):\n '''sentences with all-similar words should be equal to 1'''\n s1 = '今天 北京 的 气温 是 多少 摄氏度'\n s2 = '天津 明天 的 温度 是 几 度'\n self.assertEqual(self.mycentcorr.sentcorr(s1, s2, self.synonym_table), 1)\n\n def test_similar_sent(self):\n '''sentence with part-similar words should be larger than 0.5'''\n s1 = '周末 北京 有 小雪 吗'\n s2 = '广州 星期三 有 大雨 吗'\n assert self.mycentcorr.sentcorr(s1, s2, self.synonym_table) > 0.5\n\n def test_non_equal_sent(self):\n '''sentence with part-similar words should be equal to 0'''\n s1 = '明天 可以 穿 短袖 出门 吗'\n s2 = '晚上 去 吃 烤鸭 好不好'\n assert self.mycentcorr.sentcorr(s1, s2, self.synonym_table) == 0\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"centcorr_unittest/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"207568282","text":"\nfrom collections import defaultdict\nimport logging\nimport re\n\nFETCH_LIMIT_PLAQUES = 500\n\nfrom google.appengine.api import memcache\nfrom google.appengine.ext import ndb\nfrom google.appengine.api import search\nfrom google.appengine.datastore.datastore_query import Cursor\nfrom google.appengine.ext.db import BadValueError\n\nclass Comment(ndb.Model):\n \"\"\"\n A class to model a user comment about a particular plaque.\n\n Linked to a single Plaque object via the .plaque KeyProperty/FK.\n \"\"\"\n text = ndb.TextProperty()\n created_on = ndb.DateTimeProperty(auto_now_add=True)\n created_by = ndb.UserProperty()\n approved = ndb.BooleanProperty(default=False)\n\nclass Plaque(ndb.Model):\n \"\"\"\n A class to model a plaque with:\n * (Required) lat/lon location\n * (Required) Text description\n * Image of the plaque or area around the plaque:\n - the image's GCS filename\n - the image's serving URL (much faster to serve from this, so worth\n recording it at instance creation time)\n * Zero or more text tags\n * Approved flag (default False)\n * Created-on date\n * Created-by name\n\n User comments about the Plaque are located in the .comments attr, which is a\n KeyProperty/FK to Comment. Not sure if this is better than having a\n comment.plaque KeyProperty/FK in the other direction.\n \"\"\"\n TINY_SIZE_PX = 100\n THUMBNAIL_SIZE_PX = 300\n DISPLAY_SIZE_PX = 1024\n BIG_SIZE_PX = 4096\n ALLOWED_ROTATIONS = [90, 180, 270]\n\n title = ndb.StringProperty(required=True) # StringProperty: 1500 char limit\n title_url = ndb.StringProperty(required=True)\n description = ndb.TextProperty(required=True) # no limit on TextProperty\n location = ndb.GeoPtProperty(required=True)\n pic = ndb.StringProperty()\n img_url = ndb.StringProperty()\n img_rot = ndb.IntegerProperty(default=0)\n tags = ndb.StringProperty(repeated=True)\n comments = ndb.KeyProperty(repeated=True, kind=Comment)\n approved = ndb.BooleanProperty(default=False)\n created_on = ndb.DateTimeProperty(auto_now_add=True)\n created_by = ndb.UserProperty()\n updated_on = ndb.DateTimeProperty(auto_now_add=True)\n updated_by = ndb.UserProperty()\n old_site_id = ndb.IntegerProperty()\n\n @classmethod\n def num_approved(cls):\n count = Plaque.query().filter(Plaque.approved == True).count()\n return count\n\n @classmethod\n def page_plaques(cls, num, start_cursor_urlsafe=None):\n memcache_names = [\n 'page_plaques_%s_%s' % (num, start_cursor_urlsafe),\n 'page_start_cursor_urlsafe_%s_%s' % (num, start_cursor_urlsafe),\n 'page_more_%s_%s' % (num, start_cursor_urlsafe),\n ]\n\n memcache_out = memcache.get_multi(memcache_names)\n memcache_worked = len(memcache_out.keys()) == len(memcache_names)\n if memcache_worked:\n logging.debug(\"memcache.get_multi worked for Plaque.page_plaques()\")\n plaques = memcache_out[memcache_names[0]]\n next_cursor = memcache_out[memcache_names[1]]\n more = memcache_out[memcache_names[2]]\n else:\n query = Plaque.query(\n ).filter(Plaque.approved == True).order(-Plaque.created_on)\n\n # Protect agains bad values of start_cursor_urlsafe, like the old\n # type of request to /page/3.\n if start_cursor_urlsafe:\n try:\n start_cursor = Cursor(urlsafe=start_cursor_urlsafe)\n except BadValueError:\n start_cursor = None\n else:\n start_cursor = None\n\n if start_cursor:\n plaques, next_cursor, more = query.fetch_page(num, start_cursor=start_cursor)\n else:\n plaques, next_cursor, more = query.fetch_page(num)\n\n memcache_status = memcache.set_multi({\n memcache_names[0]: plaques,\n memcache_names[1]: start_cursor,\n memcache_names[2]: more,\n })\n if memcache_status:\n logging.debug(\"\"\"memcache.set in Plaque.plaque_pages() failed: \n %s were not set\"\"\" % memcache_status)\n\n logging.info(\"In Plaque.page_url: %s plaques %s %s\" % (len(plaques), next_cursor, more))\n return plaques, next_cursor, more\n\n# @classmethod\n# def approved_list(cls, offset=0, limit=FETCH_LIMIT_PLAQUES):\n# #if disable_memcache:\n# # plaques = Plaque.query().filter(Plaque.approved == True\n# # ).order(-Plaque.created_on\n# # ).fetch(offset=offset, limit=limit)\n# # return plaques\n#\n# memcache_name = 'approved %s %s' % (offset, limit)\n# plaques = memcache.get(memcache_name)\n# if plaques is None:\n# plaques = Plaque.query().filter(Plaque.approved == True\n# ).order(-Plaque.created_on\n# ).fetch(offset=offset, limit=limit)\n# memcache_status = memcache.set(memcache_name, plaques)\n# if not memcache_status:\n# logging.debug(\"memcaching for Plaque.approved() failed\")\n# else:\n# logging.debug(\"memcache.get worked for Plaque.approved()\")\n# return plaques\n\n @classmethod\n def num_pending(cls, num=20): # num is the max to return\n count = Plaque.query().filter(Plaque.approved != True).count(limit=num)\n return count\n\n @classmethod\n def pending_list(cls, num=20):\n \"\"\"A separate method from approved() so that it will\n never be memcached.\"\"\"\n plaques = Plaque.query().filter(Plaque.approved != True\n ).order(Plaque.approved\n ).order(-Plaque.created_on\n ).fetch(limit=num)\n return plaques\n\n # Turning off because this doesn't scale.\n # TODO: add table UniqueTags\n @classmethod\n def all_tags_sized(cls):\n \"\"\"\n Return a dict of the tags and their display-layer font sizes. Done\n here to speed rendering and to make the whole thing memcacheable.\n \"\"\"\n tag_counts = memcache.get('all_tags_sized')\n if tag_counts is None:\n tag_counts = defaultdict(int)\n\n plaques = Plaque.query().filter(Plaque.approved == True).fetch()\n for plaque in plaques:\n for t in plaque.tags:\n tag_counts[t] += 1\n\n tag_fontsize = {}\n for tag, count in tag_counts.items():\n if count < 5:\n tag_fontsize[tag] = 10\n elif count < 10:\n tag_fontsize[tag] = 13\n elif count < 20:\n tag_fontsize[tag] = 16\n elif count < 40:\n tag_fontsize[tag] = 19\n elif count < 120:\n tag_fontsize[tag] = 22\n else:\n tag_fontsize[tag] = 25\n memcache_status = memcache.set('all_tags_sized', tag_fontsize)\n if not memcache_status:\n logging.debug(\"memcaching for all_tags_sized failed\")\n else:\n logging.debug(\"memcache.get worked for all_tags_sized\")\n\n return tag_counts\n\n @property\n def img_url_tiny(self):\n \"\"\"A URL for a square, tiny image for infowindow popups.\"\"\"\n url = '%s=s%s-c' % (self.img_url, self.TINY_SIZE_PX)\n if self.img_rot in Plaque.ALLOWED_ROTATIONS:\n url = \"%s-r%s\" % (url, self.img_rot)\n return url\n\n @property\n def img_url_thumbnail(self):\n \"\"\"A URL for a square, THUMBNAIL_SIZE_PX wide image for thumbnails.\"\"\"\n url = '%s=s%s-c' % (self.img_url, self.THUMBNAIL_SIZE_PX)\n if self.img_rot in Plaque.ALLOWED_ROTATIONS:\n url = \"%s-r%s\" % (url, self.img_rot)\n return url\n\n @property\n def img_url_display(self):\n \"\"\"A URL for a display-size image for display.\"\"\"\n url = '%s=s%s' % (self.img_url, self.DISPLAY_SIZE_PX)\n if self.img_rot in Plaque.ALLOWED_ROTATIONS:\n url = \"%s-r%s\" % (url, self.img_rot)\n return url\n\n @property\n def img_url_big(self):\n \"\"\"A URL for a big rotated image.\"\"\"\n url = '%s=s%s' % (self.img_url, self.BIG_SIZE_PX)\n if self.img_rot in Plaque.ALLOWED_ROTATIONS:\n url = \"%s-r%s\" % (url, self.img_rot)\n return url\n\n @property\n def title_page_url(self):\n \"\"\"This plaque's key-based page URL.\"\"\"\n url = '/plaque/%s' % self.title_url\n return url\n\n def page_url(self):\n \"\"\"This plaque's key-based page URL.\"\"\"\n url = '/plaque/%s' % self.key.urlsafe()\n return url\n\n def set_title_url(self, ancestor_key, is_edit=False):\n \"\"\"\n Set the title_url. For new plaques, if the title_url already exists on\n another plaque, add a suffix to make it unique. Keep plaques which are \n being edited by an admin the same.\n \"\"\"\n if is_edit:\n return\n\n if self.title:\n title_url = re.sub('[^\\w]+', '-', self.title.strip()).lower()\n else:\n title_url = ''\n\n orig_title_url = title_url\n\n count = 1\n n_matches= Plaque.num_same_title_urls(title_url, ancestor_key)\n while n_matches > 0:\n count += 1\n title_url = \"%s%s\" % (orig_title_url, count)\n n_matches = Plaque.num_same_title_urls(title_url, ancestor_key)\n\n self.title_url = title_url\n\n @classmethod\n def num_same_title_urls(cls, title_url, ancestor_key):\n query = Plaque.query(ancestor=ancestor_key\n ).filter(Plaque.title_url == title_url)\n num_plaques = query.count()\n return num_plaques\n\n def to_search_document(self):\n doc = search.Document(\n doc_id = self.key.urlsafe(),\n fields=[\n search.TextField(name='tags', value=\" \".join(self.tags)),\n search.TextField(name='title', value=self.title),\n search.HtmlField(name='description', value=self.description),\n search.GeoField(name='location',\n value=search.GeoPoint(self.location.lat,\n self.location.lon)),\n ],\n )\n return doc\n\n def to_dict(self, summary=False):\n if summary:\n plaque_dict = {\n 'title': self.title,\n 'title_page_url': self.title_page_url,\n 'lat': str(self.location.lat),\n 'lng': str(self.location.lon), # N.B.: 'lng' --> 'lon'\n 'img_url_tiny': self.img_url_tiny,\n }\n else:\n plaque_dict = {\n 'plaque_key': self.key.urlsafe(),\n 'title': self.title,\n 'title_url': self.title_url,\n 'description': self.description,\n 'location': str(self.location),\n 'pic': self.pic,\n 'img_url': self.img_url,\n 'img_rot': self.img_rot,\n 'tags': self.tags,\n 'comments': self.comments,\n 'approved': self.approved,\n #'created_on': str(self.created_on),\n #'created_by': self.created_by,\n #'updated_on': str(self.updated_on),\n #'updated_by': self.updated_by,\n 'old_site_id': self.old_site_id,\n }\n return plaque_dict\n\nclass FeaturedPlaque(ndb.Model):\n created_on = ndb.DateTimeProperty(auto_now_add=True)\n plaque = ndb.KeyProperty(repeated=False, kind=Plaque)\n\n","sub_path":"Models.py","file_name":"Models.py","file_ext":"py","file_size_in_byte":11768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"344862852","text":"\"\"\"Functions for transforming 16-bit thermal images into 8-bits\"\"\"\n# Imports\nimport argparse\nimport datetime\nimport os\nimport sys\nimport numpy as np\nfrom PIL import Image\n\n\n# Functions\ndef lin_normalize_image(image_array, bottom=None, top=None):\n \"\"\"Linear normalization for an image array\n Inputs:\n image_array: np.ndarray, image data to be normalized\n bottom: float, value to map to 0 in the new array\n top: float, value to map to 1 in the new array\n Output:\n scaled_image: nd.ndarray, scaled image between 0 and 255\n \"\"\"\n if bottom is None:\n bottom = np.min(image_array)\n if top is None:\n top = np.max(image_array)\n\n scaled_image = (image_array - bottom) / (top - bottom)\n scaled_image[scaled_image < 0] = 0\n scaled_image[scaled_image > 1] = 1\n\n scaled_image = np.floor(scaled_image * 255).astype(np.uint8)\n\n return scaled_image\n\ndef parse_arguments(sys_args):\n \"\"\"Parses the input and output directories from the arguments\n Input:\n sys_args: list, the arguments to be parsed\n Output:\n input_directory: string, path to the input image directory\n output_directory: string, path to the output image directory\n \"\"\"\n # Set up parse\n parser = argparse.ArgumentParser(\n description='Command line interface for thermal image normalization')\n parser.add_argument('--indir', type=str,\n required=True, help='relative path to directory containing images')\n parser.add_argument('--outdir', type=str,\n default=None, help='relative path to the output directory')\n # Parse\n args = parser.parse_args(sys_args)\n\n # Store values\n input_directory = args.indir\n\n if args.outdir is None:\n output_directory = input_directory\n else:\n output_directory = args.outdir\n\n return input_directory, output_directory\n\ndef curate_files(input_directory, output_directory):\n \"\"\"Generates name lists for input and output images\n Inputs:\n input_directory: string, path to the input image directory\n output_directory: string, path to the output image directory\n Output:\n input_files: list, contains the file names of the incoming images\n output_files: list, contains the file names of the outgoing images\n \"\"\"\n all_files = os.listdir(input_directory)\n\n input_files = [x for x in all_files if x.find('16BIT.PNG') != -1]\n output_files = [x.replace('16BIT', '8BIT-N') for x in input_files]\n\n input_files = [os.path.join(input_directory, x) for x in input_files]\n output_files = [os.path.join(output_directory, x) for x in output_files]\n\n return input_files, output_files\n\ndef parse_filename(filename):\n \"\"\"Gets the camera position argument from filename\n Input:\n filename: string, name of the image file\n Output:\n camera_pos: string, capital letter position of the camera\n \"\"\"\n tokens = os.path.basename(filename).split('_')\n \n for token in tokens:\n if token == 'P' or token == 'C' or token == 'S':\n camera_pos = token\n break\n else:\n print('Warning: Bad filename format %s' % filename)\n\n return camera_pos\n \n\ndef get_scaling_values(filename, num_rows):\n \"\"\"Returns the bottom and top scaling parameters based on filename\n Inputs:\n filename: string, name of the file\n num_rows: int, number of rows in the image\n Outputs:\n bottom: int, number that maps to 0 in scaled image\n top: int, number that maps to 255 in scaled image\n \"\"\"\n camera_pos = parse_filename(filename) \n \n # camera_pos S and default\n bottom = 51000\n top = 57500\n\n if camera_pos == \"P\":\n if num_rows == 512:\n bottom = 53500\n top = 56500\n elif num_rows == 480:\n bottom = 50500\n top = 58500\n else:\n print('Unknown camera size for file %s' % filename)\n elif camera_pos == \"C\":\n bottom = 50500\n top = 58500\n\n return bottom, top\n\ndef main(sys_args):\n \"\"\"Function that is called by the command line\"\"\"\n # Parses the arguments\n input_directory, output_directory = parse_arguments(sys_args[1:])\n input_files, output_files = curate_files(input_directory, output_directory)\n print('Found {} files for processing'.format(len(input_files)))\n \n successful = 0\n prev_time = datetime.datetime.now()\n for index, in_file in enumerate(input_files):\n if index % 1000 == 0:\n cur_time = datetime.datetime.now()\n time_diff = cur_time - prev_time\n time_est = time_diff * (len(input_files) - index) / 1000\n print('%d of %d -- %.2f sec. Time remaining: %s' % \n (index, len(input_files), time_diff.total_seconds(), time_est))\n prev_time = cur_time\n\n try:\n cur_data = np.array(Image.open(in_file))\n bottom, top = get_scaling_values(in_file, cur_data.shape[0])\n normalized = lin_normalize_image(cur_data, bottom, top)\n\n save_im = Image.fromarray(normalized)\n save_im.save(output_files[index])\n successful += 1\n except:\n print('Unable to load {}'.format(output_files[index]))\n\n print('Completed converting {} files'.format(successful))\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\n","sub_path":"src/ir-normalization/normalizer.py","file_name":"normalizer.py","file_ext":"py","file_size_in_byte":5361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"356125776","text":"# -*- encoding: utf-8 -*-\n\n__author__ = 'Mohanson'\n\nimport getopt\nimport sys\n\nfrom saika.mkdown.modules.mkdown import mkdown\n\n\nusage = \"\"\"\nUsage:\n saika.mkdown [options] [dirs]\n\nOptions:\n -h, --help Show help.\n -s, --style ', unsafe_allow_html=True)\r\nst.markdown('Streamlit : build and share data apps',\r\n unsafe_allow_html=True)\r\n\r\nst.sidebar.title(\"Bonjour :racing_car: :car: :blue_car:\")\r\n\r\nchoice = st.sidebar.radio(\"\", ('Analyse descriptive', \"Analyse des corrélations\"))\r\n\r\n# Création Sidebar avec les différents choix\r\nliste_pays = df_cars['continent'].unique().tolist()\r\n#liste_pays.insert(0, 'Tous')\r\n\r\nst.title('')\r\nst.title('')\r\n\r\nchoix_pays = st.sidebar.multiselect('Select countries', liste_pays, default= liste_pays, format_func=lambda x: 'Select a country' if x == '' else x)\r\n#choix_pays = st.selectbox('Select a continent :', liste_pays)\r\n\r\nif choice == 'Analyse descriptive':\r\n\r\n if choix_pays :\r\n \r\n df_cars = df_cars[df_cars['continent'].isin(choix_pays)]\r\n\r\n else :\r\n \r\n st.sidebar.warning('No option is selected')\r\n\r\n\r\n st.subheader('')\r\n\r\n st.markdown(\"Quelques graphiques pour l'analyse descriptive :\",\r\n unsafe_allow_html=True)\r\n st.title('')\r\n\r\n \r\n\r\n\r\n fig4 = px.pie(df_cars, values='year', names='continent', color='continent',color_discrete_map={'US.':'lightcyan',\r\n 'Japan.':'cyan',\r\n 'Europe.':'royalblue'})\r\n fig4.update_layout(title_text=\"Répartition des modèles par continent\",\r\n title_x=0.5, title_font_family=\"Verdana\")\r\n st.write(fig4)\r\n st.markdown(\"Près de 2/3 des modèles du dataset proviennent des Etats-Unis.\",\r\n unsafe_allow_html=True)\r\n st.header('')\r\n\r\n fig3 = px.histogram(df_cars, x=\"year\", color=\"continent\", color_discrete_map={'US.':'lightcyan',\r\n 'Japan.':'cyan',\r\n 'Europe.':'royalblue'})\r\n fig3.update_layout(title_text=\"Répartition des modèles par années\",\r\n title_x=0.5, title_font_family=\"Verdana\")\r\n fig3.update_layout({'plot_bgcolor': 'rgba(0,0,0,0)',\r\n 'paper_bgcolor': 'rgba(0,0,0,0)'})\r\n fig3.update_xaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig3.update_yaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig3.update_xaxes(title_text=\"Années\")\r\n #fig8.update_yaxes(title_text=\"Distance par gallon\")\r\n st.write(fig3)\r\n\r\n fig1 = px.box(df_cars, x=\"weightlbs\", color=\"continent\", color_discrete_map={'US.':'lightcyan',\r\n 'Japan.':'cyan',\r\n 'Europe.':'royalblue'})\r\n fig1.update_layout(title_text=\"Répartition des modèles par poids\",\r\n title_x=0.5, title_font_family=\"Verdana\")\r\n fig1.update_layout({'plot_bgcolor': 'rgba(0,0,0,0)',\r\n 'paper_bgcolor': 'rgba(0,0,0,0)'})\r\n fig1.update_xaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig1.update_yaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig1.update_xaxes(title_text=\"Poids\")\r\n #fig8.update_yaxes(title_text=\"Distance par gallon\")\r\n st.write(fig1)\r\n\r\n st.title('')\r\n\r\n fig2 = px.box(df_cars, x=\"hp\", color=\"continent\", color_discrete_map={'US.':'lightcyan',\r\n 'Japan.':'cyan',\r\n 'Europe.':'royalblue'})\r\n fig2.update_layout(title_text=\"Répartition des modèles par puissance\",\r\n title_x=0.5, title_font_family=\"Verdana\")\r\n fig2.update_layout({'plot_bgcolor': 'rgba(0,0,0,0)',\r\n 'paper_bgcolor': 'rgba(0,0,0,0)'})\r\n fig2.update_xaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig2.update_yaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig2.update_xaxes(title_text=\"Puissance (cv)\")\r\n #fig8.update_yaxes(title_text=\"Distance par gallon\")\r\n st.write(fig2)\r\n\r\n\r\n st.markdown(\"Sans surprise, les modèles US sont dans une catégorie à part avec des poids et des puissances beaucoup plus importants que les modèles japonais ou européens.\",\r\n unsafe_allow_html=True)\r\n \r\n\r\nif choice == 'Analyse des corrélations':\r\n\r\n if choix_pays :\r\n \r\n df_cars = df_cars[df_cars['continent'].isin(choix_pays)]\r\n\r\n else :\r\n \r\n st.sidebar.warning('No option is selected')\r\n\r\n st.subheader('')\r\n st.markdown('Heatmap de corrélation :',\r\n unsafe_allow_html=True)\r\n st.header('')\r\n fig, axes = plt.subplots(figsize=(12, 5))\r\n sns.heatmap(df_cars.corr(), annot=True, cmap=\"YlGnBu\")\r\n sns.set(rc={'figure.facecolor': 'white'})\r\n st.write(fig)\r\n st.markdown(\"A la lecture de ce heatmap, 4 variables sont fortement corrélées (hp, weightlbs, cylinders, cubicinches). Nous allons nous intéresser à d'autres corrélations ici.\",\r\n unsafe_allow_html=True)\r\n st.title('')\r\n\r\n st.markdown(\"Quelques analyses de corrélation :\",\r\n unsafe_allow_html=True)\r\n st.title('')\r\n fig7 = px.scatter(df_cars, x=\"time-to-60\",\r\n y=\"hp\", trendline=\"ols\", color=\"continent\", color_discrete_map={'US.':'lightcyan',\r\n 'Japan.':'cyan',\r\n 'Europe.':'royalblue'})\r\n fig7.update_layout(title_text=\"Corrélation entre l'accélération et la puissance\",\r\n title_x=0.5, title_font_family=\"Verdana\")\r\n fig7.update_layout({'plot_bgcolor': 'rgba(0,0,0,0)',\r\n 'paper_bgcolor': 'rgba(0,0,0,0)'})\r\n fig7.update_xaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig7.update_yaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig7.update_xaxes(title_text=\"Temps (sec)\")\r\n fig7.update_yaxes(title_text=\"Puissance\")\r\n st.write(fig7)\r\n st.markdown(\"Plus le modèle est puissant, plus la durée pour atteindre les 60 miles/heure est faible.\",\r\n unsafe_allow_html=True)\r\n\r\n st.title('')\r\n fig8 = px.scatter(df_cars, x=\"year\",\r\n y=\"mpg\", trendline=\"ols\", color=\"continent\", color_discrete_map={'US.':'lightcyan',\r\n 'Japan.':'cyan',\r\n 'Europe.':'royalblue'})\r\n fig8.update_layout(title_text=\"Corrélation entre la consommation et l'année de fabrication\",\r\n title_x=0.5, title_font_family=\"Verdana\")\r\n fig8.update_layout({'plot_bgcolor': 'rgba(0,0,0,0)',\r\n 'paper_bgcolor': 'rgba(0,0,0,0)'})\r\n fig8.update_xaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig8.update_yaxes(showgrid=False, gridwidth=1,\r\n gridcolor='black', linecolor='rgba(0,0,0,0)')\r\n fig8.update_xaxes(title_text=\"Années\")\r\n fig8.update_yaxes(title_text=\"Distance par gallon\")\r\n st.write(fig8)\r\n st.markdown(\"La distance parcourue par gallon ne cesse d'augmenter au fil du temps soit une baisse de la consommation des véhicules.\",\r\n unsafe_allow_html=True)\r\n st.title('')\r\n\r\n","sub_path":"quete_streamlit.py","file_name":"quete_streamlit.py","file_ext":"py","file_size_in_byte":8202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"350848133","text":"def main():\n number = int(input(\"Enter a number: \"))\n #escribe tu código abajo de esta línea\n numberstr= str(number)\n if len(numberstr)>6:\n print('Too long')\n else:\n if number >0:\n reverso= numberstr[len(numberstr)::-1]\n print(reverso)\n else:\n negativo= numberstr[0]\n reverso= numberstr[len(numberstr):0:-1]\n reversaneg= negativo + reverso\n print(reversaneg)\n","sub_path":"assignments/22InversoDigitos/src/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"190277404","text":"from collections import defaultdict\n\ncallbacks = defaultdict(list)\n\ndef register_callback(event_type, callback):\n callbacks[event_type].append(callback)\n\nclass Event(object):\n \"\"\" Abstract event extension class for mkdocs \"\"\"\n\n def __init__(self):\n self.consumed = False\n\n def broadcast(self):\n for callback in callbacks[type(self)]:\n callback(self)\n if self.consumed:\n return\n\nclass BuildPage(Event):\n \"\"\" Called before a page is generated within the navigation system \"\"\"\n def __init__(self, page_title, path, url, url_context):\n super(BuildPage, self).__init__()\n\n # input arguments\n self.page_title = page_title\n self.path = path\n self.url = url\n self.url_context = url_context\n\n # output arguments\n self.pages = []\n\nclass CLI(Event):\n # define additional plugin commands\n commands = set()\n\n def __init__(self, config, cmd, args, options=None):\n super(CLI, self).__init__()\n\n # define the execution event\n self.config = config\n self.cmd = cmd\n self.args = args\n self.options = options\n\nclass GenerateContent(Event):\n def __init__(self, config, page):\n super(GenerateContent, self).__init__()\n\n # inpute arguments\n self.config = config\n self.page = page\n\n # output arguments\n self.table_of_contents = ''\n self.meta = {}\n self.html_content = ''\n\nclass PreBuild(Event):\n \"\"\" Called before a build event occurs \"\"\"\n def __init__(self, config):\n super(PreBuild, self).__init__()\n\n self.config = config\n\n","sub_path":"mkdocs/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"250941726","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jan 1 10:17:04 2019\r\n\r\n@author: vrush\r\n\"\"\"\r\n\r\nimport pandas\r\nfrom sklearn import neighbors,cluster,preprocessing,svm,decomposition,model_selection,metrics,ensemble,feature_extraction,naive_bayes,linear_model\r\nimport numpy\r\nimport collections\r\nimport operator\r\nimport matplotlib.pyplot as plt\r\nimport scipy\r\nimport seaborn\r\nimport xgboost\r\nimport scipy.stats\r\nseaborn.set(rc={'figure.figsize':(11.7,8.27)})\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport selenium\r\nfrom selenium import webdriver\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.preprocessing import scale\r\n\r\ndef parse_amenities(am_st):\r\n am_st=am_st.translate(am_st.maketrans('','','{}'))\r\n arr=am_st.split(',')\r\n am=[s.translate(s.maketrans('','','\"')).strip() for s in arr if s!='']\r\n return(am)\r\n\r\n'''removes/replaces the rows/values having targetColumn greater than 99th percentile for each\r\ncategory level in the column passed to function'''\r\ndef handleAbove99tileByCategory(df,columnName,targetColumn,replaceWithCutoff=False):\r\n unique_vals=df[columnName].dropna().unique()\r\n print('Working on Column: ',columnName,' Target Column: ',targetColumn)\r\n print('Category wise 99th percentile')\r\n for val in unique_vals:\r\n subset=df[df[columnName]==val]\r\n cutoffpercentile=numpy.nanpercentile(subset[targetColumn],q=[99])\r\n print(columnName.upper(),'-',val,':',numpy.ceil(cutoffpercentile[0]))\r\n if(replaceWithCutoff==False):\r\n df=df.drop(df[(df[columnName]==val) & (df[targetColumn]>cutoffpercentile[0])].index)\r\n else:\r\n df.loc[df[(df[columnName]==val) & (df[targetColumn]>cutoffpercentile[0])].index,targetColumn]=numpy.ceil(cutoffpercentile)\r\n \r\n return(df)\r\n \r\n \r\ndef updatePrice(df):\r\n '''update from scrapped data''' \r\n merged_scrape=pandas.read_csv('C:\\\\Users\\\\gudea\\\\Desktop\\\\Python\\\\airbnb\\\\scrapped_data\\\\combinedscrape_180119.csv')\r\n merged_scrape=merged_scrape.fillna(0)#the records having NaN are no longer listed on airbnb.so we will remove them\r\n for url,new_price in zip(merged_scrape.listing_url,merged_scrape.new_price): \r\n df.loc[df.listing_url==url,'price']=new_price\r\n \r\n #remove 0 price listings as they are no longer listed on airbnb and we are not sure of their price\r\n df=df[df.price>0].copy()\r\n return(df)\r\n\r\n\r\ndef removeUnwantedColumns(df):\r\n '''remove the unwanted columns.mostly those having free flowing text'''\r\n df=df.drop(['id','scrape_id','last_scraped','name','summary','space'\r\n ,'description','experiences_offered','access'\r\n ,'interaction','neighborhood_overview','notes','transit'\r\n ,'house_rules','thumbnail_url','medium_url','picture_url','xl_picture_url'\r\n ,'host_url','host_name','host_since','host_location'\r\n ,'host_about','host_picture_url','host_listings_count'\r\n ,'host_acceptance_rate','host_thumbnail_url'\r\n ,'neighbourhood_group_cleansed','market','country_code','country'\r\n ,'weekly_price','monthly_price','calendar_updated'\r\n ,'has_availability','availability_30','availability_60'\r\n ,'availability_365','calendar_last_scraped'\r\n ,'requires_license','license','jurisdiction_names'\r\n ,'is_business_travel_ready','require_guest_profile_picture'\r\n ,'require_guest_phone_verification','calculated_host_listings_count','host_verifications'\r\n ,'host_neighbourhood','is_location_exact'],axis=1)\r\n \r\n \r\n \r\n '''after EDA, delete some more columns'''\r\n '''majority are one value so delete host_has_profile_pic'''\r\n df=df.drop(['host_has_profile_pic',],axis=1)\r\n '''as we have the neighbourhood, we dont need the zipcode'''\r\n df=df.drop(['zipcode'],axis=1)\r\n '''remove square feet as majority values are blank'''\r\n df=df.drop(['square_feet'],axis=1)\r\n '''remove columns that leak future information like review.remove unwanted reviews columns. we will only keep the main one'''\r\n df=df.drop(['number_of_reviews','review_scores_value','first_review','last_review','review_scores_accuracy','review_scores_rating','review_scores_cleanliness','review_scores_checkin','review_scores_communication','review_scores_location','reviews_per_month'],axis=1)\r\n '''as we have london_borough we dont need the state'''\r\n df=df.drop(['state'],axis=1)\r\n '''now in cleaned data neighbourhood stands for actual neighbourhood whereas \r\n neighbourhood_cleansed stands for the borough where this neighbourhood is located'''\r\n '''to avoid confustion we'll rename it to london_borough'''\r\n df=df.rename(index=int,columns={'neighbourhood_cleansed':'london_borough'})\r\n '''remove street,smart_location,city as we have london_borough'''\r\n df=df.drop(['street','smart_location','city'],axis=1)\r\n '''as we are predicting only the rental price and not the cleaning fee or security deposit.so we can remove those columns'''\r\n df=df.drop(['security_deposit','cleaning_fee'],axis=1)\r\n '''since host_response_rate and host_response_time are missing together for 35% of the records and since they dont \r\n have a strong corelation with the DV, we can drop them for now.'''\r\n df=df.drop(['host_response_rate','host_response_time'],axis=1)\r\n '''as majority are real bed we will delete this column'''\r\n df=df.drop(['bed_type'],axis=1) \r\n return(df) \r\n\r\n\r\ndef cleanData(df):\r\n '''DATA CLEANING'''\r\n '''cleaning special characters from certain numerical columns'''\r\n df['price']=df['price'].str.replace('$','').str.replace(',','').astype('float')\r\n df['extra_people']=df['extra_people'].str.replace('$','').str.replace(',','').astype('float')\r\n \r\n '''convert binary variables to numerical'''\r\n df.host_is_superhost=df.host_is_superhost.map({'f':0,'t':1})\r\n df.host_identity_verified=df.host_identity_verified.map({'f':0,'t':1})\r\n df.instant_bookable=df.instant_bookable.map({'f':0,'t':1})\r\n \r\n '''delete the rows having 0 as price as they are noise'''\r\n df=df[df.price>0].copy() \r\n '''the bedrooms which are actually marked as 0 are actually studio apartments.\r\n so replace the number of bedrooms by 1'''\r\n df.loc[df.bedrooms==0,'bedrooms']=1\r\n '''many listings have misleading info they are giving one bedroom for rent but have mentioned the total number of rooms in the house'''\r\n df.loc[(df.bedrooms>1)&(df.room_type=='Private room'),'bedrooms' ]=1\r\n '''similar problem they have mentioned how many people the house can accommodate but the price mentioned is for 1 person'''\r\n df.loc[(df.bedrooms==1)&(df.room_type=='Shared room'),'accommodates']=1\r\n '''we are restricting the scope to 5 bedrooms'''\r\n df=df[df.bedrooms<=5].copy()\r\n '''the hostels have many shared bathrooms which can affect the model. so for hostels we will cap bathroom to 1'''\r\n df.loc[df.property_type=='Hostel','bathrooms']=1\r\n return(df)\r\n\r\n\r\ndef featureEngineeringOfAmenities(df):\r\n '''clean the amenities field and convert into list'''\r\n df['amenities']=df.apply(lambda x:parse_amenities(x.amenities),axis=1)\r\n '''OHE the data of ammenities'''\r\n '''we cannot use getdummies here as each row has a list of amenities.so we are using MultiLabelBinarizer '''\r\n mlb=preprocessing.MultiLabelBinarizer()\r\n amenities=pandas.DataFrame(mlb.fit_transform(df['amenities']),columns=mlb.classes_, index=df.index) \r\n amenities=amenities.drop(['translation missing: en.hosting_amenity_49','translation missing: en.hosting_amenity_50'],axis=1)\r\n \r\n '''check corelation between amenities'''\r\n cor_amn=pandas.DataFrame(amenities.corr())\r\n for col in cor_amn.columns:\r\n cor_amn.loc[col,col]=numpy.nan\r\n high_cor=cor_amn.where(cor_amn.abs().gt(.8))\r\n high_cor=high_cor.dropna(axis=1,how='all')\r\n high_cor=high_cor.dropna(axis=0,how='all')\r\n \r\n '''highly corelated with bathroom essentials. so remove them'''\r\n amenities=amenities.drop(['Bath towel','Bedroom comforts','Body soap','Toilet paper'],axis=1)\r\n '''highly corelated with cooking basics. so remove them'''\r\n amenities=amenities.drop(['Dishes and silverware','Oven','Refrigerator','Stove','Microwave'],axis=1)\r\n '''highly corelated with self check in.so remove them'''\r\n amenities=amenities.drop(['Lockbox'],axis=1)\r\n '''highly corelated to toilet so remove'''\r\n amenities=amenities.drop(['Wide clearance to shower'],axis=1)\r\n \r\n '''delete original amenities column'''\r\n df=df.drop(['amenities'],axis=1) \r\n '''merge amenities with original data'''\r\n df=pandas.DataFrame(pandas.concat([df,amenities],axis=1))\r\n \r\n '''remove amenities which are most common or most uncommon'''\r\n amenities_dist=dict()\r\n unbalanced_amenities=list()\r\n for i in amenities.columns:\r\n freq=df[i].sum().item()\r\n amenities_dist.update({i:freq})\r\n if(freq<1500 or freq>70000):\r\n unbalanced_amenities.append(i)\r\n '''sort by most common'''\r\n amenities_dist=dict(sorted(amenities_dist.items(),key=operator.itemgetter(1),reverse=True))\r\n '''get rid of amenities which have less than 3% of 0's or 1's in each column'''\r\n df=df.drop(unbalanced_amenities,axis=1)\r\n return(df)\r\n \r\ndef reducePropertyTypeLevels(df):\r\n Property_Type_Count=collections.Counter(df.property_type)\r\n '''Counting the number of properties which are below and equal to 200'''\r\n Property_Count_Below_100=list()\r\n Property_Count_Below_100=[key for key,value in Property_Type_Count.items() if value<=100]\r\n '''Replacing the value of properties with others where count is below or equal to 10''' \r\n df['property_type'].replace(Property_Count_Below_100,\"Other\",inplace=True)\r\n return(df)\r\n\r\ndef missingValueImpute(df):\r\n df.bathrooms=df.bathrooms.fillna(round(df.bathrooms.mean()))\r\n df.host_is_superhost=df.host_is_superhost.fillna(0)\r\n df.host_identity_verified=df.host_identity_verified.fillna(0)\r\n df.host_total_listings_count=df.host_total_listings_count.fillna(0)\r\n return(df)\r\n\r\n\r\n\r\n'''LOGIC STARTS''' \r\n#load the data\r\nlondon_data=pandas.DataFrame(pandas.read_csv('C:\\\\Users\\\\gudea\\\\Desktop\\\\Python\\\\airbnb\\\\london_listings.csv',low_memory=False,na_values=['',' ',numpy.NAN,numpy.NaN,'NA','N/A']))\r\n#remove unwanted columns\r\nlondon_data=removeUnwantedColumns(london_data)\r\n#clean data\r\nlondon_data=cleanData(london_data)\r\n#update the prices we have scraped for some records to check their authenticity\r\nlondon_data=updatePrice(london_data)\r\n\r\n'''CHECK CORRELATION'''\r\ncorr=round(london_data.corr(),2)\r\nseaborn.heatmap(corr,annot=True)\r\n#accomodates and beds has strong corelation.so drop beds\r\nlondon_data=london_data.drop(['beds'],axis=1) \r\n\r\n\r\n\r\n'''VISUALIZATION'''\r\nseaborn.pointplot(x=london_data.bedrooms,y=london_data.price)\r\nseaborn.barplot(y=london_data.london_borough,x=london_data.price)\r\nseaborn.barplot(y=london_data.property_type,x=london_data.price)\r\nseaborn.boxplot(x=london_data.bedrooms)\r\nseaborn.FacetGrid(london_data[['latitude','longitude','london_borough']],hue='london_borough').map(plt.scatter,'latitude','longitude').add_legend()\r\nseaborn.regplot(x=london_data.bedrooms,y=london_data.price)\r\nseaborn.distplot(london_data.price)\r\nseaborn.regplot(x=london_data.bedrooms,y=london_data.bathrooms)\r\n\r\n\r\n'''OUTLIER TREATMENT'''\r\n#extreme outliers removal based on the number of bedrooms\r\nlondon_data=handleAbove99tileByCategory(london_data,'bedrooms','price')\r\n#handle outliers in case of number of bathrooms for other properties\r\nlondon_data=handleAbove99tileByCategory(london_data,'bedrooms','bathrooms',True)\r\n\r\n\r\n'''FEATURE ENGINEERING'''\r\n#reset index the dataframe as we have deleted some rows\r\nlondon_data=london_data.reset_index(drop=True)\r\n#Feature Engineering of Amenities\r\nlondon_data=featureEngineeringOfAmenities(london_data)\r\n#Reduce levels in Property Type\r\nseaborn.barplot(y=london_data.property_type,x=london_data.price)\r\nlondon_data=reducePropertyTypeLevels(london_data)\r\n#remove the columns which were kept for debuging.remove neighbourhood as we will be doing clustering on lat,long\r\nlondon_data=london_data. drop(['host_id','neighbourhood','listing_url'],axis=1) \r\n#bin the price column\r\nbins=[0,58,110,210,2001]\r\nnames=[1,2,3,4]\r\nprice_bins=pandas.cut(london_data.price,bins=bins,labels=names).astype('int')\r\nlondon_data['price_bins']=price_bins\r\n#OHE the categorical columns\r\nlondon_data=pandas.get_dummies(london_data)\r\n\r\n'''SPLIT INTO TRAIN AND TEST'''\r\nX=london_data.drop(['price','price_bins'],axis=1).copy()\r\nY=london_data[['price','price_bins']].copy()\r\nx_train, x_test, y_train, y_test = model_selection.train_test_split(X, Y,random_state = 18,train_size=0.7)\r\n\r\n#reset index for train and test\r\nx_train=x_train.reset_index(drop=True)\r\ny_train=y_train.reset_index(drop=True)\r\nx_test=x_test.reset_index(drop=True)\r\ny_test=y_test.reset_index(drop=True)\r\n\r\n'''IMPUTE MISSING VALUES FOR TRAIN AND TEST SEPERATELY'''\r\nx_train=missingValueImpute(x_train)\r\nx_test=missingValueImpute(x_test)\r\n\r\n\r\n'''CLUSTERING'''\r\n#instead of using the neighbourhood categorical columns having many levels. we can create location\r\n#clusters as it will avoid the need of creating many OHE columns\r\n#run kmeans on train data\r\nkmeans=KMeans(n_clusters=100).fit(x_train[['latitude','longitude']])\r\nlabels_train=kmeans.labels_\r\nx_train['location_cluster']=pandas.Series(labels_train)\r\n\r\n#then use this to predict the test location clusters\r\nlabels_test=kmeans.predict(x_test[['latitude','longitude']])\r\nx_test['location_cluster']=pandas.Series(labels_test)\r\n\r\n#as we have cluster, we can drop latitude and longitude for both train and test\r\nx_train=x_train.drop(['latitude','longitude'],axis=1)\r\nx_test=x_test.drop(['latitude','longitude'],axis=1)\r\n\r\n\r\n\r\n'''CLASSIFICATION OF THE PRICE BINS'''\r\n#Most of the time people have an idea about the price range in which their rental will fail. \r\n#For such people we can skip the classification stage and go directly to the price bucket specific regression .\r\n#For users who have no idea about the price range, we can first classify in which price bucket their rental can fall in\r\n#and then do the bucket specific regression\r\n\r\n#RandomForest Classifier to predict the price bins\r\nrandomForestClassifier=ensemble.RandomForestClassifier(n_estimators=200,max_features=100,max_depth=15,min_samples_leaf=5)\r\nrandomForestClassifier.fit(x_train,y_train['price_bins'])\r\nprint(randomForestClassifier.score(x_train,y_train['price_bins']))\r\nprint(randomForestClassifier.score(x_test,y_test['price_bins']))\r\ny_pred=randomForestClassifier.predict(x_test)\r\nreport=metrics.classification_report(y_test['price_bins'],y_pred)\r\nprint(report)\r\n\r\n#Logistic Regression\r\nlogistic=linear_model.LogisticRegression().fit(scale(x_train),y_train['price_bins'])\r\nprint(logistic.score(scale(x_train),y_train['price_bins']))\r\nprint(logistic.score(scale(x_test),y_test['price_bins']))\r\ny_pred=logistic.predict(scale(x_test))\r\nreport=metrics.classification_report(y_test['price_bins'],y_pred)\r\nprint(report)\r\n\r\n\r\n'''REGRESSION'''\r\n\r\n#A regression model is built for each of the price bins. So total 4 regression models will be built.\r\n#Based on the output of the classification model, we will call the appropriate regression model\r\n\r\n#Model for Price Bin 1#\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"END\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#rf=ensemble.RandomForestRegressor(n_estimators=100,max_features=100,min_samples_leaf=20)\r\n#rf.fit(x_train,y_train)\r\n#numpy.sqrt(metrics.mean_squared_error(y_train,rf.predict(x_train)))\r\n#rf.score(x_train,y_train)\r\n#rf.score(x_test,y_test)\r\n#\r\n#y_predicted=rf.predict(x_test)\r\n#metrics.median_absolute_error(y_test,y_predicted)\r\n#numpy.sqrt(metrics.mean_squared_error(y_test,y_predicted))\r\n#\r\n#residuals=y_test-y_predicted\r\n#print(scipy.stats.skew(residuals))\r\n#seaborn.distplot(residuals)\r\n#'''Heteroskedasticity(non constant variance.error increases as price increases) can be seen from the plot (Funnel Shape)'''\r\n#seaborn.residplot(x=y_predicted,y=residuals)\r\n#\r\n#imps=dict()\r\n#for feature, importance in zip(x_train.columns, rf.feature_importances_):\r\n# imps[feature] = importance #add the name/value pair \r\n#imps=list(sorted(imps.items(),key=operator.itemgetter(1),reverse=True))\r\n#\r\n#rf_log_transformed.get_params\r\n#rf_log_transformed=ensemble.RandomForestRegressor(n_estimators=200)\r\n#rf_log_transformed.fit(x_train,scipy.special.boxcox(y_train,0))\r\n#print(rf_log_transformed.score(x_train,scipy.special.boxcox(y_train,0)))\r\n#print(rf_log_transformed.score(x_test,scipy.special.boxcox(y_test,0)))\r\n#y_predicted_logtransformed=rf_log_transformed.predict(x_test)\r\n#residuals_log=scipy.special.boxcox(y_test,0)-y_predicted_logtransformed\r\n#print(scipy.stats.skew(residuals_log))\r\n#sum(y_predicted_logtransformed)\r\n#seaborn.distplot(residuals_log)\r\n#seaborn.residplot(x=y_predicted_logtransformed,y=residuals_log).set(xlabel='Fitted',ylabel='Residuals')\r\n#seaborn.regplot(x=scipy.special.inv_boxcox(y_predicted_logtransformed,0),y=y_test).set(xlabel='Predicted Price',ylabel='Actual Price')\r\n#\r\n#\r\n#metrics.median_absolute_error(y_test,scipy.special.inv_boxcox(y_predicted_logtransformed,0))\r\n#numpy.sqrt(metrics.mean_squared_error(y_test,scipy.special.inv_boxcox(y_predicted_logtransformed,0)))\r\n#\r\n#imps_rf=dict()\r\n#for feature, importance in zip(x_train.columns, rf_log_transformed.feature_importances_):\r\n# imps_rf[feature] = importance #add the name/value pair \r\n#imps_rf=list(sorted(imps_rf.items(),key=operator.itemgetter(1),reverse=True))\r\n#\r\n#actual=y_test.reset_index(drop=True)\r\n#normal_predict=pandas.Series(y_predicted).reset_index(drop=True)\r\n#log_predict=pandas.Series(scipy.special.inv_boxcox(y_predicted_logtransformed,0)).reset_index(drop=True)\r\n#\r\n#compare=pandas.DataFrame(pandas.concat([actual,normal_predict,log_predict],axis=1))\r\n#compare.columns=['Actual','Predicted','PredictedLog']\r\n#\r\n#\r\n#\r\n#from sklearn.pipeline import make_pipeline\r\n#svr = make_pipeline(preprocessing.RobustScaler(), linear_model.Lasso())\r\n#\r\n#svr.fit(x_train,scipy.special.boxcox(y_train,0))\r\n#\r\n#print(svr.score(x_test,scipy.special.boxcox(y_test,0)))\r\n#y_predicted_ridge=svr.predict(x_test)\r\n#print(metrics.median_absolute_error(y_test,scipy.special.inv_boxcox(y_predicted_ridge,0)))\r\n#numpy.sqrt(metrics.mean_squared_error(y_test,scipy.special.inv_boxcox(y_predicted_ridge,0)))\r\n#seaborn.regplot(y=y_predicted_ridge,x=x_test)\r\n#\r\n#actual=y_test.reset_index(drop=True)\r\n#ridge_predict=pandas.Series(scipy.special.inv_boxcox(y_predicted_ridge,0)).reset_index(drop=True)\r\n#log_predict=pandas.Series(scipy.special.inv_boxcox(y_predicted_logtransformed,0)).reset_index(drop=True)\r\n#\r\n#compare=pandas.DataFrame(pandas.concat([actual,ridge_predict,log_predict],axis=1))\r\n#compare.columns=['Actual','Ridge','RFLog']\r\n#\r\n#\r\n#ridge=linear_model.BayesianRidge()\r\n#ridge.fit(x_train,scipy.special.boxcox(y_train,0))\r\n#print(ridge.score(x_train,scipy.special.boxcox(y_train,0)))\r\n#print(ridge.score(x_test,scipy.special.boxcox(y_test,0)))\r\n#\r\n#\r\n#seaborn.regplot(x=temp.bedrooms,y=temp.price)\r\n#xgb=xgboost.XGBRegressor(max_depth=10,eta=)\r\n#\r\n#xgb=xgb.fit(x_train,scipy.special.boxcox(y_train,0))\r\n#print(xgb.score(x_train,scipy.special.boxcox(y_train,0)))\r\n#print(xgb.score(x_test,scipy.special.boxcox(y_test,0)))\r\n#y_predicted_xgb=xgb.predict(x_test)\r\n#print(metrics.median_absolute_error(y_test,scipy.special.inv_boxcox(y_predicted_xgb,0)))\r\n#print(numpy.sqrt(metrics.mean_squared_error(y_test,scipy.special.inv_boxcox(y_predicted_xgb,0))))\r\n#\r\n#from xgboost import plot_tree,plot_importance,to_graphviz\r\n#cols=x_train.columns\r\n#to_graphviz=to_graphviz(xgb)\r\n#cols=[x.replace(' ','') for x in cols]\r\n#plot_tree(xgb,feature_names=cols)\r\n#plot_importance(xgb)\r\n#import numpy\r\n#import numpy.core.multiarray\r\n#import shap\r\n#numpy.version.version\r\n#\r\n#shap.initjs()\r\n#\r\n#explainer = shap.TreeExplainer(xgb)\r\n#import site; site.getsitepackages()\r\n#shap_values = explainer.shap_values(X)\r\n#\r\n## visualize the first prediction's explanation\r\n#shap.force_plot(explainer.expected_value, shap_values[0,:], X.iloc[0,:])\r\n#plt.savefig('C:\\\\Users\\\\gudea\\\\Desktop\\\\Python\\\\imp_weight.jpg')\r\n#d=plt.rcParams['figure.figsize']\r\n#d[0]=30\r\n#d[1]=30\r\n#plot_importance(xgb,importance_type='cover')\r\n#plt.savefig('C:\\\\Users\\\\gudea\\\\Desktop\\\\Python\\\\imp_cover.jpg')\r\n#import graphviz\r\n#from sklearn.tree import export_graphviz\r\n#export_graphviz(xgb,\r\n# feature_names=x_train.columns,\r\n# filled=True,\r\n# rounded=True)\r\n#\r\n#param_grid = {'xgbregressor__learning_rate': numpy.arange(0.05,0.2,0.05), \r\n# 'xgbregressor__max_depth': numpy.arange(5,9,1),\r\n# 'xgbregressor__n_estimators': [100, 300],\r\n# 'xgbregressor__min_child_weight ': numpy.arange(1,4,1),\r\n# 'xgbregressor__alpha ': [0.005,0.05]}\r\n#\r\n## Instantiate the grid search model\r\n#grid_search = model_selection.GridSearchCV(estimator = xgb,\r\n# param_grid = param_grid, \r\n# cv = 3, n_jobs = -1, verbose = 2, \r\n# scoring = 'neg_mean_squared_error')\r\n#grid_search.fit(x_train, scipy.special.boxcox(y_train,0))\r\n#grid_search.best_params_\r\n#\r\n#y_predicted_xgb=xgb.predict(x_test)\r\n#print(metrics.median_absolute_error(y_test,scipy.special.inv_boxcox(y_predicted_xgb,0)))\r\n#print(numpy.sqrt(metrics.mean_squared_error(y_test,scipy.special.inv_boxcox(y_predicted_xgb,0))))\r\n#print(numpy.sqrt(metrics.mean_squared_error(y_train,scipy.special.inv_boxcox(xgb.predict(x_train),0))))\r\n#xgb.get_params()\r\n#imps_xgb=dict()\r\n#for feature, importance in zip(x_train.columns, xgb.feature_importances_):\r\n# imps_xgb[feature] = importance #add the name/value pair \r\n#imps_xgb=list(sorted(imps_xgb.items(),key=operator.itemgetter(1),reverse=True))\r\n#\r\n#x=x_test.reset_index(drop=True)\r\n#actual=y_test.reset_index(drop=True)\r\n#predict=pandas.Series(scipy.special.inv_boxcox(y_predicted_xgb,0)).reset_index(drop=True)\r\n#diff=numpy.abs(actual-predict)\r\n#diffpercent=(diff/actual)*100\r\n#within5percent=diffpercent[diffpercent<=10]\r\n#\r\n#compare=pandas.DataFrame(pandas.concat([actual,predict,diff,x],axis=1))\r\n#ind=['Actual','Predicted','Difference']\r\n#ind.extend(x.columns)\r\n#compare.columns=ind\r\n#compare.to_csv('analyze_predictions.csv',index=False)\r\n#\r\n#\r\n#\r\n#\r\n#'''BEDROOM BASED MODELS'''\r\n#\r\n#X_1bhk=london_data_bkp[london_data_bkp.cluster==0].drop(['price','cluster'],axis=1)\r\n#X_1bhk=X_1bhk.drop(cols,axis=1)\r\n#Y_1bhk=london_data_bkp[london_data_bkp.cluster==0]['price']\r\n#x_train_1bhk, x_test_1bhk, y_train_1bhk, y_test_1bhk = model_selection.train_test_split(X_1bhk, Y_1bhk,random_state = 25,train_size=0.7)\r\n#xgb_1bhk=xgboost.XGBRegressor(max_depth=8,n_estimators=100,reg_lambda=,reg_alpha=0.05)\r\n#xgb_1bhk.fit(x_train_1bhk,scipy.special.boxcox(y_train_1bhk,0))\r\n#print(xgb_1bhk.score(x_train_1bhk,scipy.special.boxcox(y_train_1bhk,0)))\r\n#print(xgb_1bhk.score(x_test_1bhk,scipy.special.boxcox(y_test_1bhk,0)))\r\n#print(numpy.sqrt(metrics.mean_squared_error(y_test_1bhk,scipy.special.inv_boxcox(xgb_1bhk.predict(x_test_1bhk),0))))\r\n#print(metrics.median_absolute_error(y_test_1bhk,scipy.special.inv_boxcox(xgb_1bhk.predict(x_test_1bhk),0)))\r\n##rmse 25.9\r\n#\r\n#,reg_lambda =30,reg_alpha=0.6\r\n#\r\n\r\n'''clusters'''\r\nlondon_data_imputed.to_csv('C:\\\\Users\\\\gudea\\\\Desktop\\\\Python\\\\airbnb\\\\london_clean_4.csv',index=True)\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"scrape-code_webdriver.py","file_name":"scrape-code_webdriver.py","file_ext":"py","file_size_in_byte":23767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"299286062","text":"import subprocess\r\nfrom contextlib import contextmanager\r\nfrom winrt.windows.system import Launcher\r\nfrom winrt.windows.foundation import Uri\r\nimport pyautogui\r\nimport win32gui\r\nimport win32con \r\nimport time\r\nimport asyncio\r\n\r\n_cursor_position = 50\r\n\r\ndef _cursor_coordinates(pos):\r\n x_0, y_0 = 2245, 715\r\n slider_length = 1100\r\n target_x = x_0 + (pos/100.) * slider_length\r\n return target_x, y_0\r\n\r\n\r\ndef move_cursor(step):\r\n global _cursor_position\r\n _cursor_position = max(0, min(100, _cursor_position + step))\r\n pyautogui.click(_cursor_coordinates(_cursor_position))\r\n \r\n\r\nasync def launch_uri(uri):\r\n await Launcher.launch_uri_async(Uri(uri))\r\n\r\n\r\ndef open_night_light():\r\n asyncio.run(launch_uri('ms-settings:nightlight'))\r\n settings = win32gui.FindWindow(None, 'settings')\r\n assert settings, \"Unable to find settings window...\"\r\n try:\r\n win32gui.SetForegroundWindow(settings)\r\n except:\r\n while win32gui.GetWindowText(win32gui.GetForegroundWindow()).lower() != 'settings':\r\n pyautogui.hotkey('alt', 'shift', 'tab')\r\n placement = (0, 1, (-1, -1), (-1, -1), (2187, 0, 3857, 2136))#\r\n if win32gui.GetWindowPlacement(settings) != placement:\r\n win32gui.SetWindowPlacement(settings, placement)\r\n return settings\r\n\r\n\r\ndef close_night_light():\r\n pyautogui.click(3770, 35)\r\n\r\n\r\n@contextmanager\r\ndef settings_window(sleep_time=0.3):\r\n settings = open_night_light()\r\n try:\r\n if sleep_time:\r\n time.sleep(sleep_time)\r\n yield settings\r\n finally:\r\n close_night_light()\r\n #win32gui.PostMessage(settings,win32con.WM_DESTROY,0,0)\r\n #win32gui.CloseWindow(settings)","sub_path":"nightlight.py","file_name":"nightlight.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"48408369","text":"from math import log\nfrom collections import defaultdict\nimport os\nfrom collections import ChainMap\nfrom collections import OrderedDict\n\nk1 = 1.2\nk2 = 100\nb = 0.75\nR = 0.0\n\ndef main():\n text_files = [f for f in os.listdir('/Users/tejasparab/Desktop/Python/Assignment 4/Para') if f.endswith('.txt')]\n text_files.reverse()\n words = defaultdict(list)\n name_count = defaultdict(list)\n\n words, name_count = unigram(text_files)\n\n with open('queries.txt', 'r') as f:\n lines = ''.join(f.readlines())\n\n queries = read_query(lines)\n file_count = 1\n results = []\n for query in queries:\n results = []\n results.append(exec_query(words, query, name_count))\n print(results)\n score = {}\n score = dict(ChainMap(*results))\n sorted_score = OrderedDict(sorted(score.items(), key=lambda x: x[1], reverse=True)[:100])\n counter = 1\n f = open(str(file_count) + \".txt\",'a')\n f.write(\"query_id Q0 doc_id rank BM25_score system_name\" + '\\n')\n for k, v in sorted_score.items():\n print(str(int(queries.index(query))+1) + \" \" + \"Q0\" + \" \" + str(k) + \" \" + str(counter) + \" \" + str(v) + \" \" + \"UniBM25\")\n f.write(str(int(queries.index(query))+1) + \" \" + \"Q0\" + \" \" + str(k) + \" \" + str(counter) + \" \" + str(v) + \" \" + \"UniBM25\" + '\\n')\n counter = counter + 1\n f.flush()\n f.close()\n file_count = file_count + 1\n\n\ndef unigram(text_files):\n words = []\n dict_words = defaultdict(list)\n dict_count = defaultdict(list)\n for i in text_files: #opens and reads the contents of a single file and enters the key:value information\n #in the dict_words, does so for the entire corpus passed.\n with open(\"Para/\" + i, 'r') as f:\n val = f.readlines()\n print(f.name)\n text = ''.join(val)\n words.append(text.lower().split(\" \")) #cross checking whether all terms lower yet again\n #print(words)\n flat_words = combined_list(words)\n while '' in flat_words:\n flat_words.remove('')\n #print(flat_words)\n dict_count[os.path.splitext(f.name)[0].replace('Para/', '')] = len(flat_words)\n #print(dict_count)\n for entry in flat_words: #check if the docid, count pair already present for the key\n if [os.path.splitext(os.path.basename(f.name))[0], flat_words.count(entry)] in dict_words[entry]:\n continue\n else: #else append to the values\n dict_words[entry].append([os.path.splitext(os.path.basename(f.name))[0], flat_words.count(entry)])\n words.clear() #clearing the word_list for the next iteration with a new file\n #print(dict_words)\n return dict_words, dict_count\n\n\ndef read_query(lines):\n query_list = []\n\n for line in lines.split('\\n'):\n query = line.rstrip().split()\n query_list.append(query)\n\n return query_list\n\n\ndef calculate_BM25(n, f, qf, r, N, dl, avdl):\n K = k1 * ((1 - b) + b * (float(dl) / float(avdl)))\n fir = log(((r + 0.5) / (R - r + 0.5)) / ((n - r + 0.5) / (N - n - R + r + 0.5)))\n s = ((k1 + 1) * f) / (K + f)\n t = ((k2 + 1) * qf) / (k2 + qf)\n return fir * s * t\n\n\ndef exec_query(words,query,name_count):\n query_result = dict()\n qf = 1\n r = 0\n N = 1000\n for term in query: #hurricane #isabel individual\n if term in words: #whether the term is in inverted index\n value = words[term] #if yes, then all the documents the term occurs in\n for single_val, freq in value: #for single document of all the documents\n if single_val in name_count: #no. of words in that document\n n = len(value) #no. of documents indexed by this term\n f = freq #frequency of that word\n dl = name_count[single_val] #no. of words in the document\n avdl = sum(name_count.values()) / N #sum of all dl's / no. of documents\n score = calculate_BM25(n, f, qf, r, N, dl, avdl)\n if term in query_result:\n query_result[single_val] += score\n else:\n query_result[single_val] = score\n return query_result\n\n\ndef combined_list(list1):\n flat_list = []\n for sublist in list1:\n for item in sublist:\n flat_list.append(item)\n\n return flat_list\nmain()\n","sub_path":"Assignment 4/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"113209973","text":"#!/usr/bin/python\n\nimport math\n\ndef recipe_batches(recipe, inventory):\n # function takes in 2 dictionaries, one representing a recepie and the other how much ingrededients we have\n # compare recipe to ingredients\n # find how many batches of the recipe we can make given what the recipe calls and what we have\n\n # batch available for ONE ingredient: \n # needed (20) what we have (40), QUOTIENT = 40 / 20\n\n # FIND THE LARGEST QUOTIENT AND OUTPUT IT\n # If there are ANY quotients less than 1 then output 0\n \n # inputs:\n # 2 dictionaries each with POSSIBLE keys: \n # milk, butter, flour, cheese, sugar\n\n # RECIPE = { 'milk': 100, 'butter': 50, 'flour': 5 }\n # INVENTORY = { 'milk': 138, 'butter': 48, 'flour': 51 }\n\n ## ---------------------- FIND THE SMALLEST BATCH POSSIBLE\n\n ## loop through recipe dictionary get the quotient of inventory item divided \n ## by recipe amount, while also recording the smallest batch possible, which is what\n # will be returned. if there are any missing keys from the inventory dict recipe dict has, return 0.\n smallest_batch = 999999999999\n\n # first check if the length of the inventory equal or greater, if it's smaller\n # then we don't have all the ingredients\n if len(recipe) > len(inventory):\n return 0\n\n # loop through the recipie and check the inventory dict for matching key\n for ingredient_key in recipe:\n if ingredient_key in inventory:\n # found matching ingredient, calculate how many batches it can make\n batch_amount = inventory[ingredient_key] // recipe[ingredient_key]\n if batch_amount < 1: # not enough ingredients for one batch, recipe not possible\n return 0\n else:\n # at least one batch is possible, check if it's the smallest, if it is, save it\n if batch_amount < smallest_batch:\n smallest_batch = batch_amount\n \n # at the end of the loop we should have the smallest batch possible\n return smallest_batch\n\n# print(recipe_batches({ 'milk': 2 }, { 'milk': 200}))\n\nif __name__ == '__main__':\n # Change the entries of these dictionaries to test \n # your implementation with different inputs\n recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }\n ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }\n print(\"{batches} batches can be made from the available ingredients: {ingredients}.\".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))","sub_path":"recipe_batches/recipe_batches.py","file_name":"recipe_batches.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"105902823","text":"from buffer import Buffer\nfrom collections import deque\nimport random\n\nTABLE_SIZE = 10\nHOP_COUNT_LIMITATION = 2\n\n\nclass OpenflowSwitch(object):\n \"\"\"A SDN switch\"\"\"\n\n def __init__(self, name):\n self.name = name\n self.table_queue = deque([])\n self.buffer = Buffer(name)\n self.counter = 0\n\n def add_rule(self, rule):\n if len(self.table_queue) < TABLE_SIZE:\n self.table_queue.appendleft(rule)\n else:\n self.table_queue.pop()\n self.table_queue.appendleft(rule)\n\n @staticmethod\n def send_packet(packet, recipient):\n recipient.buffer.put(packet)\n\n def handle_packet(self, controller, net):\n \"\"\"Update the routing table, and forward the routing packet over the proper links, if necessary.\"\"\"\n\n if not self.buffer.is_empty():\n packet = self.buffer.get()\n\n flag = False\n\n for rule in self.table_queue:\n src = rule['match']['src']\n dst = rule['match']['dst']\n\n if packet['source'] == src and packet['destination'] == dst:\n OpenflowSwitch.send_packet(packet, rule['next_hop'])\n flag = True\n break\n\n # When we do not send packets to the controller\n if not flag:\n if packet['hop_count'] < HOP_COUNT_LIMITATION:\n packet['hop_count'] += 1\n random_next = random.choice(list(net.sopts[self.name].values()))\n next_hop_info = net.g.node.get(random_next[0])\n next_hop_obj = next_hop_info.get('obj')\n if next_hop_info.get('isSwitch') is True:\n OpenflowSwitch.send_packet(packet, next_hop_obj)\n\n elif packet['destination'] == next_hop_obj.ip:\n OpenflowSwitch.send_packet(packet, next_hop_obj)\n\n else:\n self.counter += 1\n controller.update_table(packet)\n\n else:\n self.counter += 1\n controller.update_table(packet)\n\n\n # if not flag:\n # self.counter += 1\n # controller.update_table(packet)\n\n\nclass Host(object):\n \"\"\"A SDN switch\"\"\"\n\n def __init__(self, name, ip):\n self.name = name\n self.ip = ip\n self.buffer = Buffer(name)\n","sub_path":"devices.py","file_name":"devices.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"643543159","text":"# Python has two built-in methods that you can use on tuples.\n# Returns the number of times a specified value occurs in a tuple\n\n# Return the number of times the value 5 appears in the tuple:\n\nthistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)\nx = thistuple.count(5)\nprint(x)\n\n# Return the number of times the \"BMW K 1300 R\" appears in the tuple\nthistuple = (\"Royal Enfield\" , \"Harley Davidson\" , \"BMW K 1300 R\" , \"Maserati Quattroporte\" , \"BMW\" , \"MG Hector\" , \"BMW K 1300 R\")\nx = thistuple.count(\"BMW K 1300 R\")\nprint(x)\n","sub_path":"Python_Tuples/TupleMethods/count().py","file_name":"count().py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"653418597","text":"from django.shortcuts import render\n\nfrom django.utils import timezone\nfrom django.views.generic import ListView\nfrom django.views.generic.detail import DetailView\n\nfrom .mixin import LoginRequiredMixin, StaffRequiredMixin\nfrom .models import Book\n\nclass BookDetailView(StaffRequiredMixin, DetailView):\n model = Book\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"now\"] = timezone.now()\n context[\"books\"] = Book.objects.all()\n return context\n\n\nclass BookListView(LoginRequiredMixin, ListView):\n model = Book\n\n def get(self, request):\n # use 0 for session till browser close\n self.request.session.set_expiry(3600) # log in for 1 hour\n s_id = self.request.session.get(\"your_id\")\n if s_id is None:\n self.request.session[\"your_id\"] = request.user.username\n context = {\n \"id\": s_id,\n \"object_list\": Book.objects.all(), # Now, explicitly defined\n }\n return render(request, \"app_books/book_list.html\", context)\n","sub_path":"src/app_books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"112847775","text":"#=======================================================================#\n# USER NAME: Thach Le \n# FILE NAME: 061-piling-up.py\n# FILE PATH: /E/thach-working/hackerrank/python-skill/061-piling-up.py\n#=======================================================================#\n# import library\nimport time \nfrom collections import deque\ndef main():\n\t# file data input \n\tline = line = open('061-piling-up-tc', 'r').read().replace('\\r\\n', '\\n').split('\\n')\n\n\t####################### #\n\t# 0.046s O(n*M)\n\t####################### #\n\t# implement with list\n\tfor i in range(1, int(line[0])*2+1, 2):\n\t\tlst_input = list(map(int, line[i+1].split()))\n\t\tmin_idex = lst_input.index(min(lst_input))\n\t\tleft = lst_input[:min_idex]\n\t\tright = lst_input[min_idex:]\n\t\tprint(\"Yes\" if left == sorted(left, reverse=True) and right == sorted(right) else \"No\")\n\t####################### #\n\n\t####################### #\n\t# 0.051s O(n)\n\t####################### #\n\t# implement with list\n\t# for i in range(1, int(line[0])*2+1, 2):\n\t# \tdeque_inp = deque()\n\t# \tdeque_inp.extend(map(int, line[i+1].split()))\n\t# \tresult = 'Yes'\n\t# \tfor cube in sorted(deque_inp, reverse=True):\n\t# \t\tif cube == deque_inp[0]: deque_inp.popleft()\n\t# \t\telif cube == deque_inp[-1]: deque_inp.pop()\n\t# \t\telse:\n\t# \t\t\tprint('No')\n\t# \t\t\tbreak\n\t# \telse: print('Yes')\n\t####################### #\n\n\t####################### #\n\t# TOO SLOW O(n^2*M)\n\t####################### #\n\t# implement with deque\n\t# for i in range(1, int(line[0])*2+1, 2):\n\t# \tdeque_inp = deque()\n\t# \tdeque_inp.extend(map(int, line[i+1].split()))\n\t# \tresult = 'Yes'\n\t# \twhile deque_inp != deque():\n\t# \t\tif max(deque_inp) == deque_inp[0] or max(deque_inp) == deque_inp[-1]:\n\t# \t\t\tdeque_inp.remove(max(deque_inp))\n\t# \t\telse:\n\t# \t\t\tresult = 'No'\n\t# \t\t\tbreak\n\t# \tprint(result)\n\t####################### #\n\n\nif __name__ == \"__main__\":\n\tstart_time = time.time()\n\tmain()\n\tprint('Eslapsed time {0:.5f}'.format(time.time()-start_time))","sub_path":"python-skill/061-piling-up.py","file_name":"061-piling-up.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"572249882","text":"from stackexchange import Site, StackOverflow\nimport json\nimport os\nso = Site(StackOverflow, 'COq7tST2*12CYE9j8BA)CQ((')\nquestions_list = []\nuser_id = []\nusers = {}\nrep_user_map = {}\nbadge_user_map = {}\nbadges = {'gold': 0, 'silver':0, 'bronze':0}\ncount = 0\nquestions = {}\ntags = []\nfor question in so.questions(tagged=['python', 'pandas'], pagesize=10):\n response = question.json\n if not response['title'] in questions:\n questions[response['title']] = {}\n questions[response['title']]['tags'] = response['tags']\n tags.append(response['tags'])\n questions[response['title']]['answered'] = response['answer_count']\n if 'user_id' in response['owner']:\n questions_list.append(response['title'])\n user_id.append(response['owner']['user_id'])\n user_obj = so.user(response['owner']['user_id'])\n if not response['owner']['user_id'] in users:\n users[response['owner']['user_id']] = {}\n badge_user_map[user_obj.badge_total] = user_obj\n users[response['owner']['user_id']]['badge'] = user_obj.badge_total\n users[response['owner']['user_id']]['reputaion'] = user_obj.reputation\n users[response['owner']['user_id']]['url'] = user_obj.json['link']\n users[response['owner']['user_id']]['user_name'] = user_obj.json['display_name']\n users[response['owner']['user_id']]['user_id'] = response['owner']['user_id']\n rep_user_map[user_obj.reputation] = users[response['owner']['user_id']]\n if 'badge_counts' in user_obj.json:\n for badge_type in badges.keys():\n if badge_type in user_obj.json['badge_counts']:\n badges[badge_type] = badges[badge_type] + 1\n tags_list= []\n for tag in user_obj.tags.fetch():\n tags_list.append(tag)\n users[response['owner']['user_id']]['tags'] = tags_list\n count+=1\n if count > 50:\n break\n\ntop_weight_user = badge_user_map.keys()\ntop_weight_user.sort()\ntop_weight_user = top_weight_user[-1]\ntop_weight_user_obj = badge_user_map[top_weight_user]\ntop_ques = []\nfor ques in top_weight_user_obj.top_questions_in_tag(['python','pandas']):\n top_ques.append(ques.title)\n\ntags = [item for sublist in tags for item in sublist]\ntags = list(set(tags))\n\nques4 = {}\nfor t in tags:\n obj = so.tag(t)\n ques4[t] = obj.count\n\n\n\nprint (\"questions_list\")\nprint (questions_list)\nprint (\"\\nuser ids\")\nprint (user_id)\nprint (\"top questions according to the weightage.\\n\")\nprint (top_ques)\n\n\n\nrep_user = rep_user_map.keys()\nrep_user.sort()\nfor item in ['pandas', 'python']:\n with open(\"/tmp/%s_topic.txt\"%item, 'w') as f:\n for user in rep_user:\n f.write(str(rep_user_map[user]['user_id'])+\",\")\n f.write(rep_user_map[user]['user_name']+\",\")\n f.write(rep_user_map[user]['url']+\"\\n\")\nprint (\"Successfully written the results to the following files /tmp/pandas.txt /tmp/python.txt\")\n\n\nfor key, value in badges.iteritems():\n print (\"%s : %s\"%(key,value))\n\n\n\nfor key, value in questions.iteritems():\n print (\"Question --->%s\"%key)\n print (\"Tags --->%s\"%str(value['tags']))\n\nfor key, value in questions.iteritems():\n print (\"Question --->%s\"%key)\n print (\"Number of answers --->%s\"%value['answered'])\n\n\nfor key, value in ques4.iteritems():\n print (\"Tag %s Number of Questions %s\"%(key, value))\n\n\n","sub_path":"stack_overflow_api.py","file_name":"stack_overflow_api.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"186721423","text":"import pygame\r\n\r\n\r\npygame.init()\r\n\r\nwin = pygame.display.set_mode(((1360, 640)))\r\npygame.display.set_caption((\"zme9 ebana9\"))\r\n\r\nx = 500\r\ny = 500\r\nwidht = 50\r\nheight = 60\r\nspeed = 15\r\nrun = True\r\nwhile run:\r\n pygame.time.delay(50)\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n run = False\r\n keys = pygame.key.get_pressed()\r\n if keys[pygame.K_LEFT]:\r\n x -= speed\r\n if keys[pygame.K_RIGHT]:\r\n x += speed\r\n if keys[pygame.K_DOWN]:\r\n y += speed\r\n if keys[pygame.K_UP]:\r\n y -= speed\r\n pygame.draw.circle(win, (255, 255, 255), (x, y), 10, 0)\r\n pygame.display.update()\r\npygame.quit()\r\n","sub_path":"Игра на Python/snakegame.py","file_name":"snakegame.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"653041438","text":"import shutil, os\n\n# This is a list of cities, follow this format: [cityName, stateName, stateAbbr]\ncities = [\n [\"San Diego\", \"California\", \"CA\"],\n [\"New York City\", \"New York\", \"NY\"],\n [\"Boston\", \"Massachusetts\", \"MA\"],\n [\"Washington DC\", \"District of Columbia\", \"DC\"],\n [\"Houston\", \"Texas\", \"TX\"],\n [\"Austin\", \"Texas\", \"TX\"],\n [\"San Antonio\", \"Texas\", \"TX\"],\n [\"Chicago\", \"Illinois\", \"IL\"],\n [\"East Lansing\", \"Michigan\", \"MI\"],\n [\"Ann Arbor\", \"Michigan\", \"MI\"],\n [\"Providence\", \"Rhode Island\", \"RI\"],\n [\"Pittsburgh\", \"Pennsylvania\", \"PA\"],\n [\"Philadelphia\", \"Pennsylvania\", \"PA\"],\n [\"Vancouver\", \"British Columbia\", \"BC\"],\n [\"Portland\", \"Oregon\", \"OR\"],\n [\"Phoenix\", \"Arizona\", \"AZ\"],\n [\"San Francisco\", \"California\", \"CA\"],\n [\"Oakland\", \"California\", \"CA\"],\n [\"Berkeley\", \"California\", \"CA\"],\n [\"Hayward\", \"California\", \"CA\"],\n [\"Fremont\", \"California\", \"CA\"],\n [\"San Jose\", \"California\", \"CA\"],\n [\"Sunnyvale\", \"California\", \"CA\"],\n [\"Palo Alto\", \"California\", \"CA\"],\n [\"Menlo Park\", \"California\", \"CA\"],\n [\"Milpitas\", \"California\", \"CA\"],\n [\"Mountain View\", \"California\", \"CA\"],\n [\"Stanford\", \"California\", \"CA\"],\n [\"Los Angeles\", \"California\", \"CA\"],\n# [\"Detroit\", \"Michigan\", \"MI\"],\n# [\"Atlanta\", \"Georgia\", \"GA\"],\n# [\"Raleigh\", \"North Carolina\", \"NC\"],\n# [\"Dallas\", \"Texas\", \"TX\"],\n# [\"Tacoma\", \"Washington\", \"WA\"],\n# [\"Seattle\", \"Washington\", \"WA\"]\n]\n\n# These keywords will be put into sentences, so\n# please end with conference so that the sentences make sense.\nconferenceKeywords = [\n \"AI conference\",\n \"Artificial Intelligence conference\",\n \"machine learning conference\",\n \"deep learning conference\",\n \"NLP conference\"\n]\n\ndef urlize(s):\n return s.lower().replace(' ', '-')\n\n# Clean up the previous versions of generated by this script\nfor city in cities:\n state = city[1]\n try:\n shutil.rmtree(\"./\" + urlize(state))\n except:\n pass\n\n# NOW LETS DO SOME MASS CREATION BABY!\ncounter = 0\nfor city in cities:\n city_name = city[0]\n state_name = city[1]\n state_abbr = city[2]\n\n for keyword in conferenceKeywords:\n directory = os.path.join(urlize(state_name), urlize(city_name), urlize(keyword))\n print(directory)\n if not os.path.exists(directory):\n os.makedirs(directory)\n with open(os.path.join(directory, 'index.md'), 'w') as outfile:\n content = (\"---\\n\"\n \"title: AI Frontiers Conference\\n\"\n \"layout: index\\n\"\n \"cityKeyword: '%s'\\n\"\n \"stateKeyword: '%s'\\n\"\n \"stateAbbrKeyword: '%s'\\n\"\n \"conferenceKeyword: '%s'\\n\"\n \"---\") % (city_name, state_name, state_abbr, keyword)\n outfile.write(content)\n counter += 1\n\nprint(\"phew! %d files generated.\" % counter)\n","sub_path":"mass_generator.py","file_name":"mass_generator.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"94733058","text":"# -*- coding: utf-8 -*-\nimport hashlib\nfrom jinja2 import Markup\n\ndef gravatar(value):\n return 'https://www.gravatar.com/avatar/' + hashlib.md5(value.email.strip().lower().encode()).hexdigest() + '?r=pg&d=mp'\n\ndef convert_to_tag(line):\n if line.startswith('#'):\n components = line.split()\n level = components[0].count('#')\n headline = ' '.join(components[1:])\n return Markup(''.format(level)) + Markup.escape(headline) + Markup(''.format(level))\n else:\n return Markup('

') + Markup.escape(line) + Markup('

')\n \ndef mdlike(value):\n return Markup(''.join([\n convert_to_tag(l)\n for l\n in map(lambda x: x.strip(), value.split('\\n'))\n ]))\n\n\ndef init_filters(app):\n app.jinja_env.filters['gravatar'] = gravatar\n app.jinja_env.filters['mdlike'] = mdlike\n","sub_path":"websecjp/snippet/build/challenge/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"589990015","text":"import time\nimport threading\nimport redis\n\nr = redis.Redis(host='127.0.0.1', port=6379, db=0)\n\ndef func():\n for i in range(30):\n print(r.keys())\n time.sleep(1)\n return \"done \"\n\n\nif __name__ == \"__main__\":\n task = []\n for i in range(5):\n t1 = threading.Thread(target=func)\n task.append(t1)\n for i in task:\n i.start()\n\n for i in task:\n i.join()\n","sub_path":"redis/redis-py/multiprocess/multithread.py","file_name":"multithread.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"508364240","text":"#!/usr/bin/env python3\n\n\nimport sys\n\n\ndef sum_to_k(lst, k):\n i = 0\n while i < len(lst):\n j = i + 1\n while j < len(lst):\n if lst[i] + lst[j] == k:\n (lst[i], lst[j])\n j += 1\n i += 1\n# Solution like in the hint. Brute-force made correct.\n\n\ndef main():\n # k = int(sys.argv[1])\n # lst = [int(e) for e in sys.argv[2:]]\n # sum_to_k(lst, k)\n\n n = int(sys.argv[1])\n lst = [1, 6, 7, 8, 9, 10, 2, 3, 4, 5]\n k = 13\n lst *= n\n sum_to_k(lst, k)\n\n\nif __name__ == '__main__':\n main()\n\n\n# Complexity\n# O(n^2) - loop twice / look at items twice (asymptotically speaking)","sub_path":"year2_1819/computer_programming_3_algorithms_data_structures/labs/w1/ca117-revision/numbers.py","file_name":"numbers.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"606952078","text":"# -*- coding: utf-8 -*-\n# Copyright 2014 Objectif Libre\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n# @author: Stéphane Albert\n#\nimport datetime\nimport json\nimport os.path\nimport zipfile\n\nimport cloudkitty.utils as utils\n\n\nclass OSRTFBackend(object):\n \"\"\"Native backend for transient report storage.\n\n Used to store data from the output of the billing pipeline.\n \"\"\"\n\n def __init__(self):\n self._osrtf = None\n\n def open(self, filename):\n # FIXME(sheeprine): ZipFile is working well with filename\n # but not backend\n self._osrtf = zipfile.ZipFile(filename, 'a')\n\n def _gen_filename(self, timeframe):\n filename = '{}-{:02d}-{:02d}-{}-{}.json'.format(timeframe.year,\n timeframe.month,\n timeframe.day,\n timeframe.hour,\n timeframe.minute)\n return filename\n\n def _file_exists(self, filename):\n for file_info in self._osrtf.infolist():\n if file_info.filename == filename:\n return True\n return False\n\n def add(self, timeframe, data):\n \"\"\"Add the data to the OpenStack Report Transient Format.\"\"\"\n filename = self._gen_filename(timeframe)\n # We can only check for the existence of a file not rewrite or delete\n # it\n if not self._file_exists(filename):\n self._osrtf.writestr(filename, json.dumps(data))\n\n def get(self, timeframe):\n try:\n filename = self._gen_filename(timeframe)\n data = json.loads(self._osrtf.read(filename))\n return data\n except Exception:\n pass\n\n def close(self):\n self._osrtf.close()\n\n\nclass WriteOrchestrator(object):\n \"\"\"Write Orchestrator:\n\n Handle incoming data from the global orchestrator, and store them in an\n intermediary data format before final transformation.\n \"\"\"\n def __init__(self,\n backend,\n user_id,\n state_manager,\n basepath=None,\n period=3600):\n self._backend = backend\n self._uid = user_id\n self._period = period\n self._sm = state_manager\n self._basepath = basepath\n self._osrtf = None\n self._write_pipeline = []\n\n # State vars\n self.usage_start = None\n self.usage_start_dt = None\n self.usage_end = None\n self.usage_end_dt = None\n\n # Current total\n self.total = 0\n\n # Current usage period lines\n self._usage_data = {}\n\n def add_writer(self, writer_class):\n writer = writer_class(self,\n self._uid,\n self._backend,\n self._basepath)\n self._write_pipeline.append(writer)\n\n def _gen_osrtf_filename(self, timeframe):\n if not isinstance(timeframe, datetime.datetime):\n raise TypeError('timeframe should be of type datetime.')\n date = '{}-{:02d}'.format(timeframe.year, timeframe.month)\n filename = '{}-osrtf-{}.zip'.format(self._uid, date)\n return filename\n\n def _update_state_manager(self):\n self._sm.set_state(self.usage_end)\n metadata = {'total': self.total}\n self._sm.set_metadata(metadata)\n\n def _get_state_manager_timeframe(self):\n timeframe = self._sm.get_state()\n self.usage_start = datetime.datetime.fromtimestamp(timeframe)\n end_frame = timeframe + self._period\n self.usage_end = datetime.datetime.fromtimestamp(end_frame)\n metadata = self._sm.get_metadata()\n self.total = metadata.get('total', 0)\n\n def _filter_period(self, json_data):\n \"\"\"Detect the best usage period to extract.\n\n Removes the usage from the json data and returns it.\n \"\"\"\n candidate_ts = None\n candidate_idx = 0\n\n for idx, usage in enumerate(json_data):\n usage_ts = usage['period']['begin']\n if candidate_ts is None or usage_ts < candidate_ts:\n candidate_ts = usage_ts\n candidate_idx = idx\n\n if candidate_ts:\n return candidate_ts, json_data.pop(candidate_idx)['usage']\n\n def _format_data(self, timeframe, data):\n beg = utils.dt2ts(timeframe)\n end = beg + self._period\n final_data = {'period': {'begin': beg, 'end': end}}\n final_data['usage'] = data\n return [final_data]\n\n def _open_osrtf(self):\n if self._osrtf is None:\n self._osrtf = OSRTFBackend()\n filename = self._gen_osrtf_filename(self.usage_start_dt)\n if self._basepath:\n self._osrtf_filename = os.path.join(self._basepath, filename)\n self._osrtf.open(self._osrtf_filename)\n\n def _pre_commit(self):\n self._open_osrtf()\n\n def _commit(self):\n self._pre_commit()\n\n self._osrtf.add(self.usage_start_dt, self._usage_data)\n\n # Dispatch data to writing pipeline\n for backend in self._write_pipeline:\n backend.append(self._usage_data, self.usage_start, self.usage_end)\n\n self._update_state_manager()\n\n self._usage_data = {}\n\n self._post_commit()\n\n def _post_commit(self):\n self._osrtf.close()\n\n def _dispatch(self, data):\n for service in data:\n if service in self._usage_data:\n self._usage_data[service].extend(data[service])\n else:\n self._usage_data[service] = data[service]\n # Update totals\n for entry in data[service]:\n self.total += entry['billing']['price']\n\n def get_timeframe(self, timeframe):\n self._open_osrtf()\n data = self._osrtf.get(timeframe)\n self._osrtf.close()\n return self._format_data(timeframe, data)\n\n def append(self, raw_data):\n while raw_data:\n usage_start, data = self._filter_period(raw_data)\n if self.usage_end is not None and usage_start >= self.usage_end:\n self._commit()\n self.usage_start = None\n\n if self.usage_start is None:\n self.usage_start = usage_start\n self.usage_end = usage_start + self._period\n self.usage_start_dt = (\n datetime.datetime.fromtimestamp(self.usage_start))\n self.usage_end_dt = (\n datetime.datetime.fromtimestamp(self.usage_end))\n\n self._dispatch(data)\n\n def commit(self):\n self._commit()\n\n def close(self):\n for writer in self._write_pipeline:\n writer.close()\n if self._osrtf is not None:\n self._osrtf.close()\n","sub_path":"cloudkitty/write_orchestrator.py","file_name":"write_orchestrator.py","file_ext":"py","file_size_in_byte":7385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"315925985","text":"from flask import Flask\nfrom flask_bcrypt import Bcrypt\nfrom flask_mail import Mail\nfrom flask_login import LoginManager\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_restful import Api\nfrom flask_jwt import JWT\n\nfrom KYC_WalletApp.config import Config\n\ndb = SQLAlchemy()\nflask_bcrypt = Bcrypt()\nlogin_manager = LoginManager()\nlogin_manager.login_view = 'users.login'\nlogin_manager.login_message_category = 'warning'\nmail = Mail()\n\n\ndef create_app(config_class=Config):\n app = Flask(\n __name__,\n template_folder='./templates',\n static_folder='./static'\n )\n app.config.from_object(Config)\n api = Api(app)\n\n db.init_app(app)\n flask_bcrypt.init_app(app)\n login_manager.init_app(app)\n mail.init_app(app)\n\n @app.before_first_request\n def create_tables():\n db.create_all()\n\n from KYC_WalletApp.main.routes import main\n from KYC_WalletApp.users.routes import users\n from KYC_WalletApp.wallets.routes import wallets\n\n app.register_blueprint(main)\n app.register_blueprint(users)\n app.register_blueprint(wallets)\n\n from KYC_WalletAPI.resources.walletFactory import (DeployedWallets, WalletFactory,\n WalletRequest, ManageWallet, ApproveRequest,\n CreateNewWallet, ManageRequests, WalletData)\n\n api.add_resource(DeployedWallets, '/api/deployed_wallets')\n api.add_resource(WalletFactory, '/api/wallet_factory')\n api.add_resource(WalletRequest, '/api/wallet_request/')\n api.add_resource(ManageWallet, '/api/manage_wallet/')\n api.add_resource(ApproveRequest, '/api/approve_request/')\n api.add_resource(CreateNewWallet, '/api/wallet_factory/create_wallet')\n api.add_resource(ManageRequests, '/api/requests_made_activity')\n api.add_resource(WalletData, '/api/retrieve_wallet_data/')\n\n return app\n","sub_path":"KYC_WalletApp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"89994359","text":"import os\n\nimport telebot\nfrom flask import Flask, request\nfrom modules.bank_info import get_rates\n\nTOKEN = '637911219:AAFn5svpVGTk64IaZdbVu036JyTsGwDoCTk'\nbot = telebot.TeleBot(TOKEN)\napp = Flask(__name__)\n\n\n@bot.message_handler(commands=['get_rates'])\ndef send_rates(message):\n bot.send_message(message.chat.id, get_rates())\n\n\n@bot.message_handler(commands=['start'])\ndef start(message):\n bot.reply_to(message, 'Hello, ' + message.from_user.first_name)\n\n\n@bot.message_handler(func=lambda message: True, content_types=['text'])\ndef echo_message(message):\n bot.reply_to(message, message.text)\n\n\n@app.route('/' + 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\n\n@app.route(\"/\")\ndef webhook():\n bot.remove_webhook()\n bot.set_webhook(url='https://littleenginethatcould-flaskapp.herokuapp.com/' + TOKEN)\n return \"!\", 200\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=int(os.environ.get('PORT', 5000)), debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"135286815","text":"# 1. Поработайте с переменными, создайте несколько, выведите на экран,\n# запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.\n\nname = input(\"Введите ваше имя: \")\nage = int(input(\"Введите ваш возраст: \"))\ncode = int(input(\"Введите код доступа (либо 1276, либо 9738) \"))\nif code == 1276:\n print(\"Ваше имя\", name, \"Ваш возраст\", age, \"Предоставлен полный доступ\", sep=\"\\n\")\nelif code == 9738:\n print(\"Ваше имя\", name, \"Ваш возраст\", age, \"Предоставлен ограниченный доступ\", sep=\"\\n\")\nelse:\n print(\"Неверный код доступа\")\n\n# 2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды\n# и выведите в формате чч:мм:сс. Используйте форматирование строк.\n\ntime = int(input(\"Введите время в секундах: \"))\ntime_format = int(input(\"Введите 24 (если 24-ёх часовой формат) или 12 (если 12-ти часовой формат): \"))\nif 0 <= time <= 86399 and time_format == 24 or time_format == 12:\n if time_format == 24:\n print(f\"{time // 3600:02d}:{time % 3600 // 60:02d}:{time % 60:02d}\")\n elif time_format == 12:\n if time <= 43199:\n print(f\"{time // 3600:02d}:{time % 3600 // 60:02d}:{time % 60:02d} a.m.\")\n else:\n time_0 = time - 43200\n print(f\"{time_0 // 3600:02d}:{time_0 % 3600 // 60:02d}:{time_0 % 60:02d} p.m.\")\nelse:\n print(\"Недопустипое значение времени (от 0 до 86399) либо формата (12 или 24)\")\n\n# 3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.\n# Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369.\n\nnumber = int(input(\"Введите число: \"))\nprint(\"Сумма чисел равна: \", number + number * 10 + number * 2 ** 10)\n\n# 4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.\n# Для решения используйте цикл while и арифметические операции.\n\nnumber, maximum = int(input(\"Введите число: \")), 0\nwhile number > 0:\n total = number % 10\n if total > maximum:\n maximum = total\n number //= 10\nprint(maximum)\n\n# 5. Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом\n# работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки).\n# Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность\n# выручки (соотношение прибыли к выручке).\n# Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.\n\nx = int(input(\"Введите выручку фирмы: \"))\ny = int(input(\"Введите издержки фирмы: \"))\nif x > y:\n print(\"Фирма работает в прибыль\")\n print(\"Рентабельность выручки:\", int(round((x - y) / x, 2) * 100), \"%\")\n z = int(input(\"Введите количество сотрудников фирмы: \"))\n print(f\"Прибыль фирмы в расчете на одного сотрудника:, {(x - y) / z:.2f}\")\nelif x == y:\n print(\"Фирма работает в ноль\")\nelse:\n print(\"Фирма работает в убыток\")\n\n# 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.\n# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня,\n# на который общий результат спортсмена составит не менее b километров.\n# Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня.\n\na, b, c, total = int(input(\"Введите первое число: \")), int(input(\"Введите второе число: \")), 0, 1\nwhile b > c:\n total += 1\n c = 1.1 * a\n a = c\nprint(total)\n","sub_path":"Lesson01/Lesson01.py","file_name":"Lesson01.py","file_ext":"py","file_size_in_byte":5187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"221125317","text":"import numpy as np\nfrom keras.optimizers import RMSprop\n\nfrom molecules.ml.unsupervised import VAE\nfrom molecules.ml.unsupervised import EncoderConvolution2D\nfrom molecules.ml.unsupervised import DecoderConvolution2D\nfrom molecules.ml.unsupervised import HyperparamsEncoder\nfrom molecules.ml.unsupervised import HyperparamsDecoder\n\n\ndef objective(hparams):\n kernel1 = int(hparams[0])\n kernel2 = int(hparams[1])\n kernel3 = int(hparams[2])\n\n kernels = [kernel1, kernel2, kernel3]\n\n hparams_enc = HyperparamsEncoder()\n hparams_dec = HyperparamsDecoder()\n\n hparams_enc.kernels = kernels\n hparams_dec.kernels = kernels\n\n optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\n\n encoder = EncoderConvolution2D(\n input_shape=input_shape,\n hyperparameters=hparams_enc\n )\n\n encoder._get_final_conv_params()\n num_conv_params = encoder.total_conv_params\n encode_conv_shape = encoder.final_conv_shape\n\n decoder = DecoderConvolution2D(\n output_shape=input_shape,\n enc_conv_params=num_conv_params,\n enc_conv_shape=encode_conv_shape,\n hyperparameters=hparams_dec\n )\n\n cvae = VAE(\n input_shape=input_shape,\n latent_dim=3,\n encoder=encoder,\n decoder=decoder,\n optimizer=optimizer\n )\n\n history = cvae.train(x_train, validation_data=x_val, batch_size=512, epochs=100, callbacks=[])\n return np.mean(history.val_loss)\n","sub_path":"molexperiments/cvae/fspeptide/hyperparameter_optimization/objective.py","file_name":"objective.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"604050443","text":"#!/usr/local/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"pygame helper.\"\"\"\n\nfrom colors import Colors\n\nimport gflags\nimport pygame\nimport Queue\nimport sys\nimport threading\n\nfrom pygame.locals import *\n\nfrom memoized import *\nimport world_rules\n\nFLAGS = gflags.FLAGS\n\nBACKGROUND = Colors.white()\n\n\nclass Error(Exception):\n \"\"\"General error.\"\"\"\n\n\nclass NoNeighbor(Error):\n \"\"\"Raised if square has no neighbor in the indicated direction.\"\"\"\n\n\nclass OutsideWorld(Error):\n \"\"\"Raised if neighbor would be outside the known world.\"\"\"\n\n\nclass World(object):\n \"\"\"The world (grid). (0,0) is top left. Should be square.\"\"\"\n\n def __init__(self, width, height, square_width, rules, squares,\n black_white=False, random_events=False, workers=10):\n \"\"\"Init.\n\n Args:\n width: (int) width of the world in pixels.\n height: (int) height of the world in pixels.\n square_width: (int) width/height of citizen squares\n rules: (world_rules.WorldRules) world rules, function pointer\n squares: (dict) dict of Square objects. Current state.\n \"\"\"\n pygame.init()\n self.width = width\n self.height = height\n self.square_width = square_width\n self.msg_width = 100\n self.black_white = black_white\n self.rules = rules()\n self.squares = squares\n self.random_events = random_events\n # worker queue\n #self.q = Queue.Queue()\n #self.q = multiprocessing.JoinableQueue()\n #self._StartWorkers(workers)\n\n def Initialize(self):\n self.fps_clock = pygame.time.Clock()\n self.surface = pygame.display.set_mode((self.width + self.msg_width, self.height))\n self.fontObj = pygame.font.Font('freesansbold.ttf', 14)\n\n # set background\n self.Clear()\n\n # queue worker for processing next_gen data\n def Worker(self):\n while True:\n func, args = self.q.get()\n func(*args)\n self.q.task_done()\n\n def NextGeneration(self):\n \"\"\"Moves world to next generation.\"\"\"\n# for square_index, square in self.squares.iteritems():\n# # Put each next_gen square in a worker thread\n# self.q.put((self.NextGenSquare, [square_index]))\n#\n# # wait for all threads to finish work\n# self.q.join()\n\n for square_index in self.squares.iterkeys():\n self.NextGenSquare(square_index)\n\n # reset memoized cache\n #Memoized.reset()\n\n def NextGenSquare(self, square_index):\n \"\"\"Sets the square's nextgen state.\n\n Args:\n square_index: (int) square index in world\n \"\"\"\n square = self.squares[square_index]\n neighbors = self._NeighborCount(square)\n self.rules.NextGen(square, self.random_events, neighbors)\n\n\n def SetMessage(self, msg=\"Game\"):\n self.msgSurfaceObj = self.fontObj.render(msg, False, Colors.blue())\n self.msgRectobj = self.msgSurfaceObj.get_rect()\n self.msgRectobj.topleft = (self.width + 4, 0)\n\n # Clear previous msg\n self.surface.fill(Colors.white(), self.msgRectobj)\n\n self.surface.blit(self.msgSurfaceObj, self.msgRectobj)\n\n def DrawSquare(self, top, left, color, tint=None):\n # Draw inside grid.\n square_color = color() + tint\n pygame.draw.rect(\n self.surface, square_color, (top+1, left+1, self.square_width - 1,\n self.square_width - 1))\n\n def DrawGrid(self, color=Colors.green()):\n \"\"\"Draws grid.\"\"\"\n self._DrawVerticalGrid(color=color)\n self._DrawHorizontalGrid(color=color)\n\n def Clear(self):\n \"\"\"Clears surface.\"\"\"\n self.surface.fill(BACKGROUND)\n self.DrawGrid()\n self.Update()\n\n def Update(self):\n \"\"\"Redraws surface.\"\"\"\n pygame.display.update()\n\n def InWorld(self, position):\n \"\"\"Returns True if given position is in the World.\n\n Args:\n position: (tuple) (top, left) pixel.\n \"\"\"\n top, left = position[0], position[1]\n if (top < 0 or\n left < 0 or\n top + self.square_width > self.height or\n left + self.square_width > self.width):\n return False\n else:\n return True\n\n #@Memoized\n def _NeighborColor(self, square, position):\n \"\"\"Returns the color of the neighbor in position.\n\n Args:\n square: (Square) Object\n position: (string) Valid position from Square class (RIGHT, LEFT, etc)\n\n Returns:\n color, team: (Square.COLOR, teams.Team) color and team of neighbor.\n\n Raises:\n NoNeighbor: If there is no neighbor\n OutsideWorld: If neighbor would be outside the known world.\n \"\"\"\n neighbor_position = getattr(square, position)\n\n if neighbor_position in self.squares:\n return (self.squares[neighbor_position].color,\n self.squares[neighbor_position].team)\n else:\n raise NoNeighbor(\"No neighbor at %s\" % (neighbor_position,))\n\n def _NeighborCount(self, square):\n \"\"\"Returns the count and color of a square's neighbors.\n\n Args:\n square: (Square) Object\n\n Returns:\n neighbors: (dict) {\n Color.white: N, # total\n \"friends\": H,\n \"enemies\": J,\n \"total_neighbors\": L, # non-white neighbors\n \"influence\": Team # the team with the most influence\n # simply with the most squares\n # surrounding this one\n }\n \"\"\"\n neighbors = {\"total_neighbors\": 0, \"friends\": 0, \"enemies\": 0}\n\n\n if square.position == (46, 14):\n pass\n # initialize all colors to 0\n for color in Colors.all():\n neighbors[color] = 0\n\n neighbor_team_count = {}\n\n for pos in (world_rules.POSITIONS):\n try:\n neighbor_color, neighbor_team = self._NeighborColor(square, pos)\n except (OutsideWorld, NoNeighbor):\n continue\n\n neighbors[neighbor_color] += 1\n if neighbor_color != Colors.white:\n neighbors[\"total_neighbors\"] += 1\n\n neighbor_team_count.setdefault(neighbor_team, 0)\n neighbor_team_count[neighbor_team] += 1\n\n if neighbor_team == square.team:\n neighbors[\"friends\"] += 1\n else:\n neighbors[\"enemies\"] += 1\n\n influence = None\n max = 0\n for team, count in neighbor_team_count.iteritems():\n if count > max:\n max = count\n influence = team\n\n\n neighbors[\"influence\"] = influence\n\n return neighbors\n\n def _DrawVerticalGrid(self, color):\n \"\"\"Draws vertical grid.\"\"\"\n for x in xrange(0, self.width + self.square_width, self.square_width):\n pygame.draw.line(self.surface, color, (x, 0),\n (x, self.height), 1)\n\n def _DrawHorizontalGrid(self, color):\n \"\"\"Draws horizontal grid.\"\"\"\n for y in xrange(0, self.height + self.square_width, self.square_width):\n pygame.draw.line(self.surface, color, (0, y),\n (self.width, y), 1)\n\n def _StartWorkers(self, num_worker_threads):\n \"\"\"Starts queue workers.\"\"\"\n for i in range(num_worker_threads):\n t = threading.Thread(target=self.Worker)\n #t = multiprocessing.Process(target=self.Worker)\n t.daemon = True\n t.start()\n","sub_path":"src/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":7040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"185002435","text":"from bipbop.client import WebService\n\n\ndef query_arguments(query, params):\n data = []\n for key, value in params.items():\n data.append(\"'%s' = '%s'\" % (key, value))\n query += ' ' if query.upper().find('WHERE') != -1 else ' WHERE '\n query += ' AND '.join(data)\n return query\n\n\nws = WebService()\nresponse = ws.post(\"SELECT FROM 'JURISTEK'.'DATALAKE'\", {\n \"data\": query_arguments(\"SELECT FROM 'DATALAKE'.'NOME'\", {\n 'nome': 'HOSPITAL SANTA JOANA',\n 'inicio': '2019/08/10',\n 'fim': '2020/08/10',\n 'filter': 'andamento',\n 'limit': 100,\n 'skip': 1\n })\n})\n\n\ndef get_text(item, query):\n field = item.find(query)\n if field is None:\n return None\n return field.text\n\n\nfor item in response.findall('./body/advogado/processos/processo'):\n print({\n \"nome_parte\": get_text(item, './nome_parte'),\n \"tribunal_nome\": get_text(item, './tribunal_nome'),\n \"tribunal_consulta\": get_text(item, './tribunal_consulta'),\n \"parte\": get_text(item, './parte'),\n \"polo\": get_text(item, './polo'),\n \"numero_processo\": get_text(item, './numero_processo'),\n \"primeiro_andamento\": get_text(item, './primeiro_andamento'),\n })\n","sub_path":"test_juristek.py","file_name":"test_juristek.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"167643377","text":"# coding=utf-8\n\nfrom bs4 import BeautifulSoup\nimport re\nimport urlparse\n\n\nclass Parser(object):\n def parse(self, page_url, content):\n if page_url is None or content is None:\n return None\n soup = BeautifulSoup(content, 'html.parser', from_encoding='utf8')\n new_urls = self._get_new_urls(page_url, soup)\n new_data = self._get_new_data(page_url, soup)\n return new_urls, new_data\n\n def _get_new_urls(self, page_url, soup):\n links = soup.find_all('a', href=re.compile(r'/item/[\\s\\S]+?'))\n new_urls = set()\n\n for link in links:\n new_url = link['href']\n full_url = urlparse.urljoin('http://baike.baidu.com', '%s') % new_url[1:]\n new_urls.add(full_url)\n\n return new_urls\n\n def _get_new_data(self, page_url, soup):\n res_data = dict()\n\n res_data['url'] = page_url\n\n title_node = soup.find('dd', class_='lemmaWgt-lemmaTitle-title').find('h1')\n res_data['title'] = title_node.get_text()\n\n summary_node = soup.find('div', class_='lemma-summary')\n res_data['summary'] = summary_node.get_text()\n\n return res_data\n","sub_path":"crawer/html_parser.py","file_name":"html_parser.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"169261738","text":"import requests, json, numpy as np\ndef get_test_point():\n return [np.random.randint(255) for _ in range(785)]\n# time.sleep(5)\n\napp_name = \"mxnet-test1\"\nmodel_name = \"mxnet-model1\"\n\n\nprint( get_test_point())\nurl = \"http://127.0.0.1:1337/\"+ app_name + \"/predict\"\nprint(url)\nheaders = {\"Content-type\": \"application/json\"}\nout = requests.post(url, headers=headers, data=json.dumps({\"input\": get_test_point()})).json()\nprint(out)\n","sub_path":"mxnet_test.py","file_name":"mxnet_test.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"495812510","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n\nimport os\nimport pickle\n\nimport cv2 as cv\nimport numpy as np\n\n\nclass Extractor():\n def __init__(self, cls_root, save_dir, video2path):\n super().__init__()\n self.cls_root = cls_root\n self.save_dir = save_dir\n self.video2path = video2path\n if not os.path.exists(self.save_dir):\n os.makedirs(self.save_dir)\n\n self.record = open('./{}.txt'.format(os.path.basename(__file__).split('.')[0]), 'w+')\n\n def run(self):\n for split in os.listdir(self.cls_root):\n if split == 'test' or split == 'val':\n continue\n if not os.path.exists(os.path.join(self.save_dir, split)):\n os.mkdir(os.path.join(self.save_dir, split))\n\n for cls_txt in os.listdir(os.path.join(self.cls_root, split)):\n cls = cls_txt.split('.')[0]\n print('processing split-{}, cls-{}'.format(split, cls))\n if not os.path.join(self.save_dir, split, cls):\n os.mkdir(os.path.join(save_dir, split, cls))\n\n for idx, line in enumerate(open(os.path.join(cls_root, split, cls_txt), 'r+').readlines()):\n print(idx)\n vdo_name = line.split(' ')[0]\n if not os.path.exists(os.path.join(self.save_dir, split, cls)):\n os.mkdir(os.path.join(self.save_dir, split, cls))\n try:\n self.rgb_flow_gen(vdo_name, os.path.join(self.save_dir, split, cls))\n except Exception as e:\n print(e)\n with open('./{}.txt'.format(os.path.basename(__file__).split('.')[0], 'a+')) as record:\n record.write('[Error] {}\\n'.format(str(e)))\n\n def rgb_flow_gen(self, video, save_dir):\n # usage :\n # rgb_flow_gen('928296508.mp4', '/home/datasets/mayilong/PycharmProjects/p55/two_stream/v1/data/video_tmp')\n vdo_name = video.split('.')[0]\n vdo_path = video2path[video]\n cap = cv.VideoCapture(vdo_path)\n all_frames = int(cap.get(cv.CAP_PROP_FRAME_COUNT))\n img_height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))\n img_width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))\n fps = int(cap.get(cv.CAP_PROP_FPS))\n\n idx = 0\n interval = np.random.randint(0, 60)\n suffix = 0\n start_pos = np.random.randint(10, 60)\n prev_gray = None\n cur_gray = None\n already_save_rgb = False\n rgb_buf = []\n need_break = False\n while idx < all_frames:\n ret, frame = cap.read()\n if ret is False:\n rgb_buf.clear()\n cap.release()\n\n if idx < start_pos:\n idx += 1\n continue\n\n if need_break:\n for i in range(interval):\n ret, frame = cap.read()\n if ret is False:\n cap.release()\n break\n need_break = False\n interval = np.random.randint(0, 60)\n\n if (idx - start_pos) % 4 == 0:\n rgb_buf.append(frame)\n if len(rgb_buf) == 11:\n rgb_of_folder = os.path.join(os.path.join(save_dir, vdo_name + '_' + str(suffix)))\n if not os.path.exists(rgb_of_folder):\n os.mkdir(rgb_of_folder)\n suffix += 1\n self.handle_rgb_buf(rgb_buf, rgb_of_folder)\n rgb_buf.clear()\n need_break = True\n if suffix >= 4:\n cap.release()\n break\n\n idx += 1\n\n def handle_rgb_buf(self, rgb_buf, save_dir):\n # usage rgb_buf (list contain 11 rgb frame) save_dir (path/to/video_name)\n if len(rgb_buf) == 0 or len(rgb_buf) != 11:\n raise RuntimeError('rgb_buf is empty')\n rgb_file = rgb_buf[5]\n cv.imwrite(os.path.join(save_dir, 'rgb.jpeg'), rgb_file)\n prev_gray = cv.cvtColor(rgb_buf[0], cv.COLOR_RGB2GRAY)\n for i in range(1, len(rgb_buf)):\n cur_gray = cv.cvtColor(rgb_buf[i], cv.COLOR_RGB2GRAY)\n flow = cv.calcOpticalFlowFarneback(prev_gray, cur_gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)\n flow_x = flow[..., 0]\n flow_y = flow[..., 1]\n\n cv.imwrite(os.path.join(save_dir, 'flowx_{:02d}.jpeg'.format(i - 1)), flow_x)\n cv.imwrite(os.path.join(save_dir, 'flowy_{:02d}.jpeg'.format(i - 1)), flow_y)\n prev_gray = cur_gray\n cur_gray = None\n\n\nif __name__ == '__main__':\n # rgb_flow_gen('928296508.mp4', '/home/datasets/mayilong/PycharmProjects/p55/two_stream/v1/data/video_tmp')\n cls_root = '/home/datasets/mayilong/PycharmProjects/p55/two_stream/v1/data/split_data'\n save_dir = '/home/datasets/mayilong/PycharmProjects/p55/two_stream/v1/data/datasets'\n video2path = pickle.load(\n open('/home/datasets/mayilong/PycharmProjects/p55/resource/train_val_video2path.pkl', 'rb'))\n extractor = Extractor(cls_root, save_dir, video2path)\n extractor.run()\n","sub_path":"two_stream/datasets/dataset3/extract_rgb_flow.py","file_name":"extract_rgb_flow.py","file_ext":"py","file_size_in_byte":5225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"112098665","text":"import argparse\nimport sys\nimport pandas as pd\nimport re\nimport yaml\nimport os\nimport os.path as osp\n\nfrom multiprocessing import Pool\n\nsys.path.append(\"/home/viselol/simplot\")\nimport simplot as sp\n\n\ndef main():\n parser = argparse.ArgumentParser(description = 'Aggregates total stats for different runs of the same workload.')\n parser.add_argument('-w', '--workloads', required=True, help='YAML file with the workloads to process.')\n parser.add_argument('-i', '--input-dirs', nargs='+', required=True, help='Input data dirs.')\n parser.add_argument('-n', '--names', nargs='+', default=[], help='Names for the input data dirs.')\n parser.add_argument('-o', '--output-dir', default='plottot', help='Output dir.')\n parser.add_argument('-t', '--threads', type=int, default=1, help='Number of threads to use.')\n parser.add_argument('-c', '--columns', type=yaml.load, default=dict(), help='Dictionary with the coluluns to plot and the opperation to perform on them.')\n args = parser.parse_args()\n\n # Read the file with the list of workloads\n with open(args.workloads, 'r') as f:\n workloads = yaml.load(f)\n\n # Create output dir\n os.makedirs(osp.abspath(args.output_dir), exist_ok=True)\n\n # Read names\n if not args.names:\n for idir in args.input_dirs:\n with open(\"{}/name\".format(idir)) as f:\n args.names.append(f.readline().strip())\n assert len(args.input_dirs) == len(args.names)\n\n # Prepare arguments\n arguments = list()\n for metric, agg in args.columns.items():\n arguments.append((workloads, metric, agg, args.names, args.input_dirs, args.output_dir))\n\n # Parallellize\n assert len(arguments), colored(\"Nothing to read\", \"red\")\n print(\".\" * len(arguments), end=\"\")\n print(\"\\b\" * len(arguments), end=\"\")\n if args.threads > 1:\n with Pool(args.threads) as pool:\n pool.starmap(plot_metric, arguments)\n else:\n for data in arguments:\n plot_metric(*data)\n print()\n\n\n\ndef plot_metric(workloads, metric, agg, names, input_dirs, output_dir):\n a = sp.default_args()\n # a.equal_yaxes = [list(range(num_metrics))]\n # a.equal_xaxes = [list(range(num_metrics))]\n a.equal_yaxes = [[]]\n a.equal_xaxes = [[]]\n index = 0\n\n filename = \"{}/{}_wls.csv\".format(output_dir, metric.replace('/','.'))\n dfs_metric = []\n for wl_id, wl in enumerate(workloads):\n wl_name = \"-\".join(wl)\n dfs_exp = []\n for exp_id, (exp_name, input_dir) in enumerate(zip(names, input_dirs)):\n wl_dir = \"{}/{}\".format(input_dir, wl_name)\n wl_fin = \"{}/{}_fin.csv\".format(input_dir, wl_name)\n\n # Test if file exists\n if not os.path.exists(wl_fin):\n print(\"The workload {} has no 'fin' file\".format(wl_name))\n continue\n\n usecols = [\"app\", metric + \":mean\", metric + \":std\"]\n df = pd.read_table(wl_fin, sep=\",\", usecols=usecols)\n df.set_index(\"app\", inplace=True)\n df.columns = [\"{}:{}\".format(exp_name, metric), \"{}:{}:std\".format(exp_name, metric)]\n dfs_exp.append(df)\n df = pd.concat(dfs_exp, axis=1) # For this workload we have the data from all the experiments\n\n if agg == \"sum\":\n df = pd.DataFrame(df.sum()).T\n elif agg == \"max\":\n df = pd.DataFrame(df.max()).T\n else:\n assert(1==2)\n\n dfs_metric.append(df)\n df = pd.concat(dfs_metric, axis=0).reset_index(drop=True) # We have data for all the workloads\n df.to_csv(filename)\n\n plot = dict()\n plot[\"kind\"] = \"l\"\n plot[\"datafile\"] = filename\n plot[\"index\"] = 0\n plot[\"cols\"] = [df.columns.get_loc(\"{}:{}\".format(n, metric)) + 1 for n in names]\n plot[\"ecols\"] = [df.columns.get_loc(\"{}:{}:std\".format(n, metric)) + 1 for n in names]\n plot[\"labels\"] = names\n plot[\"xlabel\"] = \"Workloads\"\n plot[\"ylabel\"] = metric\n plot[\"yminorlocator\"] = [\"AutoMinorLocator\", {\"n\": 5}]\n plot[\"xminorlocator\"] = [\"IndexLocator\", {\"base\": 1, \"offset\": 0}]\n plot[\"ymin\"] = 0\n hlines = []\n for n, name in enumerate(names):\n column = \"{}:{}\".format(name, metric)\n # LUCIA = change median by mean\n hlines += [[df[column].mean(), {\"linestyle\": '-.', \"color\": \"D{}\".format(n)}]]\n #hlines += [[df[column].median(), {\"linestyle\": '-.', \"color\": \"D{}\".format(n)}]]\n hlines += [[df[column].quantile(0.25), {\"linestyle\": ':', \"color\": \"D{}\".format(n)}]]\n hlines += [[df[column].quantile(0.75), {\"linestyle\": ':', \"color\": \"D{}\".format(n)}]]\n print(hlines)\n plot[\"hl\"] = hlines\n a.plot.append(plot)\n\n grid = [[1,1]]\n figs, axes = sp.create_figures(grid, a.size, a.dpi)\n sp.plot_data(figs, axes, a.plot, a.title, a.equal_xaxes, a.equal_yaxes, a.rect)\n metric = re.sub('/$', '', metric).replace(\"/\", \".\")\n sp.write_output(figs, \"{}/{}_{}.pdf\".format(output_dir, metric, agg), a.rect)\n print(\"x\", end=\"\", flush=True)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/plot_tot_wl.py","file_name":"plot_tot_wl.py","file_ext":"py","file_size_in_byte":5034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"556950175","text":"import unittest\n\nfrom scapy.layers.inet import IP, UDP\nfrom scapy.layers.ntp import NTP\n\nfrom cp3_interceptor import CP3Interceptor\n\n\nclass CP3InterceptorTests(unittest.TestCase):\n\n def test_check_pck_pck_is_No_NTP_False_Returned(self):\n # Arrange\n interceptor = CP3Interceptor('','')\n\n # Act\n result = interceptor.check_pck(IP())\n\n # Assert\n self.assertFalse(result)\n\n def test_check_pck_has_no_matching_ip_False_Returned(self):\n # Arrange\n interceptor = CP3Interceptor('3.3.3.3', '4.4.4.4')\n pck = IP(dst='1.1.1.1',src='2.2.2.2') / UDP() / NTP()\n\n # Act\n result = interceptor.check_pck(pck)\n\n # Assert\n self.assertFalse(result)\n\n def test_check_pck_has_matching_ip_True_Returned(self):\n # Arrange\n interceptor = CP3Interceptor('3.3.3.3', '4.4.4.4')\n pck = IP(dst='1.1.1.1', src='3.3.3.3') / UDP() / NTP()\n\n # Act\n result = interceptor.check_pck(pck)\n\n # Assert\n self.assertTrue(result)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"python/cp3_code/tests_cp3_interceptor.py","file_name":"tests_cp3_interceptor.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"344893408","text":"import json\nimport re\nimport requests\nimport sys\nfrom datetime import datetime\nfrom account import username,password\n\nclass InstagramLogin():\n link = \"https://www.instagram.com/accounts/login/\"\n login_url = \"https://www.instagram.com/accounts/login/ajax/\"\n time = int(datetime.now().timestamp())\n csrf = \"\"\n with requests.Session() as req:\n x = req.get(url=link, headers={\"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36\"})\n csrf = re.findall(r\"csrf_token\\\":\\\"(.*?)\\\"\", x.text)[0]\n payload = {\n \"username\": username,\n \"enc_password\": f\"#PWD_INSTAGRAM_BROWSER:0:{time}:\"+password,\n \"queryParams\": {},\n \"optIntoOneTap\": \"false\"\n }\n login_header = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"Referer\": \"https://www.instagram.com/accounts/login/\",\n \"x-csrftoken\": csrf\n }\n def Login(self):\n req = requests.Session()\n s = req.post(url=self.login_url, data=self.payload, headers=self.login_header)\n response = json.loads(s.text)\n if \"authenticated\" in response:\n if response[\"authenticated\"]:\n print(\"\\n\"+\"-\"*25+\"\\n|| Login Successful!\"+\"\\n\"+\"-\"*25+\"\\n\")\n return req\n else:\n print(\"\\n\"+response+\"\\n\")\n sys.exit()\n else:\n print(\"\\n\"+response+\"\\n\")\n sys.exit()","sub_path":"InstagramAccountCrawl/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"381344565","text":"from blogs.models import Category, Blog, Tag\nfrom blogs.serializers import CategorySerializer, BlogSerializer, TagSerializer\n\nfrom rest_framework import viewsets\nfrom rest_framework.routers import DefaultRouter\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly\n\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\n\nclass CategoryViewSet(viewsets.ModelViewSet):\n permission_classes = (IsAuthenticatedOrReadOnly, )\n authentication_classes = (JSONWebTokenAuthentication, )\n\n queryset = Category.objects.all()\n serializer_class = CategorySerializer\n\nclass BlogViewSet(viewsets.ModelViewSet):\n permission_classes = (IsAuthenticatedOrReadOnly, )\n authentication_classes =(JSONWebTokenAuthentication, )\n\n queryset = Blog.objects.all()\n serializer_class = BlogSerializer\n\nclass TagViewSet(viewsets.ModelViewSet):\n permission_classes = (IsAuthenticatedOrReadOnly, )\n authentication_classes = (JSONWebTokenAuthentication, )\n\t\n queryset = Tag.objects.all()\n serializer_class = TagSerializer\n\ndef get_router():\n router = DefaultRouter()\n router.register(r'api/categories', CategoryViewSet)\n router.register(r'api/blogs', BlogViewSet)\n router.register(r'api/tags', TagViewSet)\n return router","sub_path":"blogs/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"325927753","text":"try:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nconfig = {\n 'description': 'Tabl_homework',\n 'author': 'Issa Beekun',\n 'author_email': 'Issa.Beekun@gmail.com',\n 'version': '1.0',\n 'test_suite':'nose.collector',\n 'test_requires': ['nose'],\n 'install_requires': ['nose', 're'],\n 'packages': ['BinarySearch', 'WordReversal'],\n 'scripts': [],\n 'name': 'Tabl-homework'\n}\n\nsetup(**config)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"4811168","text":"#!/usr/bin/env python\nimport sys\nimport pymysql\n\n\nclass Contsql:\n @staticmethod\n def connect(_host, _port, _user, _pwd, _dbName):\n return pymysql.connect(host=_host, port=_port, user=_user, password=_pwd, db=_dbName)\n\n @staticmethod\n def sqldelete(connect, sql_dele):\n cursor = connect.cursor()\n try:\n # sql = \"DELETE FROM trade WHERE account = '%s' LIMIT %d\"\n # data = ('13512345678', 1)\n cursor.execute(sql_dele)\n connect.commit() # 事务提交\n except Exception as e:\n connect.rollback() # 事务回滚\n raise e\n\n @staticmethod\n def sqlupdate(connect, sql_update):\n cursor = connect.cursor()\n try:\n # sql = \"UPDATE trade SET saving = %.2f WHERE account = '%s' \"\n # data = (8888, '13512345678')\n cursor.execute(sql_update)\n connect.commit() # 事务提交\n except Exception as e:\n connect.rollback() # 事务回滚\n raise e\n\n @staticmethod\n def sqlinsert(connect, sql_insert):\n cursor = connect.cursor()\n try:\n # sql = \"INSERT INTO trade (name, account, saving) VALUES ( '%s', '%s', %.2f )\"\n # data = ('雷军', '13512345678', 10000)\n # cursor.execute(sql % data)\n cursor.execute(sql_insert)\n connect.commit() # 事务提交\n except Exception as e:\n connect.rollback() # 事务回滚\n raise e\n\n @staticmethod\n def sqlquery(connect, sqlstr):\n cursor = connect.cursor()\n sql = sqlstr\n results = ()\n try:\n cursor.execute(sql)\n results = cursor.fetchall()\n connect.commit() # 事务提交\n # print('result=',len(results),'\\n')\n # for row in results:\n # id = row[0]\n # uid = row[1]\n # mid = row[2]\n # game_id = row[3]\n # username = row[4]\n # order_no = row[5]\n # role = row[6]\n # pay_mode = row[7]\n # money = row[8]\n # currency = row[9]\n # zone_id = row[10]\n # channel_id = row[11]\n # bank_code = row[12]\n # card_type = row[13]\n # card_no = row[14]\n # card_pwd = row[15]\n # pay_product_id = row[16]\n # pay_merchant_id = row[17]\n # status = row[18]\n # remark = row[19]\n # pay_order_no = row[20]\n # third_trade_no = row[21]\n # coupon_order_no = row[22]\n # coupon_no = row[23]\n # ctime = row[24]\n # mtime = row[25]\n # print('id = %s,uid = %s mid = %s game_id = %s username = %s order_no = %s role = %s pay_mode = %s money = %s ctime = %s mtime = %s ' %(id,uid,mid,game_id,username,order_no,role,pay_mode,money,ctime,mtime))\n except Exception as e:\n connect.rollback() # 事务回滚\n raise e\n finally:\n return results\n\n @staticmethod\n def dbClose(cursor, connect):\n cursor.close()\n connect.close()\n","sub_path":"sqlt/Contsql.py","file_name":"Contsql.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"258915039","text":"from sklearn import svm\nimport matplotlib.pyplot as plt\nimport json\nimport numpy as np\n\ntraining_length = 0.60\n\nwith open(\"../Output-files/features.json\", \"r\") as features_file:\n data = json.load( features_file )\n\nX = []\nY = []\n\nindex_feat = data[\"Index Features\"]\n\nfeatures_key = [\n \"Moving Average\", \n \"Price Momentum Oscillator\", \n \"Relative Strength Index\", \n \"On Balance Volume\", \n \"Stochastic Oscillator\",\n \"Sentiment Strength\"\n ]\n\nfor i in range( 0, len( index_feat ) ):\n temp_arr = []\n \n for j in range( 0, len( features_key ) ):\n temp_arr.append( index_feat[i][ features_key[j] ] )\n \n X.append( temp_arr )\n Y.append( index_feat[i][\"Target\"] )\n \nX = np.array( X )\nY = np.array( Y ) \nX_train = X[ : int( training_length*len( X ) ) ]\nY_train = Y[ : int( training_length*len( Y ) ) ]\nX_test = X[ int( training_length*len( X ) ) : ]\nY_test = Y[ int( training_length*len( Y ) ) : ]\n\nclf = svm.SVC( kernel='rbf' )\nclf.fit( X_train, Y_train )\nY_pred = clf.predict( X_test ) \n\ncnt = 0\npred_file = open(\"../Output-files/Predictions.txt\", \"w\")\npred_file.write(\"Actual Predicted\\n\")\nfor i in range( 0, len( Y_pred ) ):\n pred_file.write( (' '+str(Y_test[i]))[-2:] + \" \" + (' '+str(Y_pred[i]))[-2:] + \"\\n\" )\n if( Y_pred[i] != Y_test[i] ):\n cnt+=1\nprint( \"Prediction done with accuracy : \" + str( ( len( Y_pred ) - cnt )/( len( Y_pred ) ) ) + \" and predictions saved to Output-files/Predictions.txt\")\n","sub_path":"Python-PHP-Codes/svm_classifier.py","file_name":"svm_classifier.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"239165580","text":"#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport signal\nimport sys, time\nfrom mindwave import Headset, get_headset_dongles\n\ngamefig = plt.figure()\ngameplot = gamefig.add_subplot(1, 1, 1)\nANI = None\nheadsets = []\nball_location = [330, 190]\nBACKGROUND = plt.imread(\"field.jpg\")\nINTERVAL = 30\nBALL_RADIUS = 10\npause = False\n\nGOALS = [\n [[25, 125], [110, 270]],\n [[530, 630], [110, 270]],\n]\n\n\ndef check_win():\n if (\n ball_location[0] > GOALS[0][0][0]\n and ball_location[0] < GOALS[0][0][1]\n and ball_location[1] > GOALS[0][1][0]\n and ball_location[1] < GOALS[0][1][1]\n ):\n return 2\n if (\n ball_location[0] > GOALS[1][0][0]\n and ball_location[0] < GOALS[1][0][1]\n and ball_location[1] > GOALS[1][1][0]\n and ball_location[1] < GOALS[1][1][1]\n ):\n return 1\n return 0\n\n\ndef show_state(i):\n global pause\n global ball_location\n if not pause:\n winner = check_win()\n if winner:\n pause = True\n print(f\"Player {winner} wins!\")\n\n p1 = headsets[0].attention + headsets[0].meditation\n p2 = headsets[1].attention + headsets[1].meditation\n gameplot.clear()\n\n plt.xticks(rotation=45, ha=\"right\")\n plt.subplots_adjust(bottom=0.30)\n plt.title(\"MINDBALL\")\n\n ball_location[0] += int((p1 - p2) / 100 * INTERVAL)\n\n ball_location = [\n min(max(ball_location[0], 10), 650),\n min(max(ball_location[1], 10), 390),\n ]\n\n gameplot.add_patch(plt.Circle(ball_location, BALL_RADIUS, color=\"blue\"))\n gameplot.imshow(BACKGROUND)\n\n\ndef onClick(event):\n global ball_location\n global pause\n ball_location = [330, 190]\n pause = False\n pass\n\n\nif __name__ == \"__main__\":\n # connect headsets\n ports = get_headset_dongles()\n if not ports:\n print(\n \"ERROR: Could not find MindWave RF adapter. Please make sure your adapter is plugged in and a red or blue light is on.\"\n )\n headsets.append(Headset(ports[0]))\n headsets.append(Headset(ports[1]))\n\n time.sleep(1)\n if headsets[0].status == \"connected\":\n headsets[0].disconnect()\n time.sleep(1)\n if headsets[1].status == \"connected\":\n headsets[1].disconnect()\n time.sleep(1)\n\n print(\"Player 1, connect your headset.\")\n headsets[0].connect()\n state = \"x\"\n while headsets[0].status != \"connected\":\n time.sleep(5)\n curr_state = headsets[0].status\n if not curr_state == state:\n state = curr_state\n if state == \"standby\" or state is None:\n headsets[0].connect()\n print(\"Player 1 connected! Player 2, connect your headset.\")\n headsets[1].connect()\n state = \"x\"\n while headsets[1].status != \"connected\":\n time.sleep(5)\n curr_state = headsets[1].status\n if not curr_state == state:\n state = curr_state\n if state == \"standby\" or state is None:\n headsets[1].connect()\n\n print(\"Player 2 connected!\")\n gamefig.canvas.mpl_connect(\"button_press_event\", onClick)\n signal.signal(signal.SIGINT, signal.default_int_handler)\n try:\n ANI = animation.FuncAnimation(\n gamefig,\n show_state,\n interval=500,\n )\n plt.show()\n except KeyboardInterrupt:\n pass\n\n print(\"\\ndisconnecting...\")\n headsets[0].disconnect()\n headsets[1].disconnect()\n print(\"done\")\n sys.exit(0)\n","sub_path":"source/mindball_2d2p_easy.py","file_name":"mindball_2d2p_easy.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"485345313","text":"# Copyright (C) 2018 HE Yaowen \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nfrom . import get_default_client\nfrom . import DNSPodObject\nfrom .record import Record\n\n\nclass Domain(DNSPodObject):\n\n def get_records(self, params={}):\n records = []\n params['domain_id'] = self.id\n rds = self.dnspod_client.api_request('/Record.List', params)['records']\n\n for rd in rds:\n record = Record(rd)\n record.domain = self\n records.append(record)\n\n self.records = records\n\n return records\n\n def add_record(self, sub_domain, record_type, value, record_line_id=0, mx=5, ttl=600, status='enable'):\n params = {}\n\n params['domain_id'] = self.id\n params['sub_domain'] = sub_domain\n params['record_type'] = record_type\n params['value'] = value\n params['record_line_id'] = record_line_id\n params['mx'] = mx\n params['ttl'] = ttl\n params['status'] = status\n\n self.dnspod_client.api_request('/Record.Create', params)\n\n\ndef get_domains(**kwargs):\n domains = []\n client = get_default_client()\n\n rds = client.api_request('/Domain.List', kwargs)['domains']\n for rd in rds:\n domain = Domain(rd)\n domain.records = None\n domains.append(domain)\n\n\n return domains\n","sub_path":"dnspod/domain.py","file_name":"domain.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"27693319","text":"#\n# Copyright (c) 2020-2021 Arm Limited and Contributors. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n\"\"\"Defines a device detector for Windows.\"\"\"\nfrom pathlib import Path\nfrom typing import List\n\nfrom mbed_tools.devices._internal.base_detector import DeviceDetector\nfrom mbed_tools.devices._internal.candidate_device import CandidateDevice\nfrom mbed_tools.devices._internal.windows.system_data_loader import SystemDataLoader\nfrom mbed_tools.devices._internal.windows.usb_data_aggregation import SystemUsbData, AggregatedUsbData\n\n\nclass WindowsDeviceDetector(DeviceDetector):\n \"\"\"Windows specific implementation of device detection.\"\"\"\n\n def __init__(self) -> None:\n \"\"\"Initialiser.\"\"\"\n self._data_loader = SystemDataLoader()\n\n def find_candidates(self) -> List[CandidateDevice]:\n \"\"\"Return a generator of Candidates.\"\"\"\n return [\n WindowsDeviceDetector.map_to_candidate(usb)\n for usb in SystemUsbData(data_loader=self._data_loader).all()\n if WindowsDeviceDetector.is_valid_candidate(usb)\n ]\n\n @staticmethod\n def map_to_candidate(usb_data: AggregatedUsbData) -> CandidateDevice:\n \"\"\"Maps a USB device to a candidate.\"\"\"\n serial_port = next(iter(usb_data.get(\"serial_port\")), None)\n uid = usb_data.uid\n return CandidateDevice(\n product_id=uid.product_id,\n vendor_id=uid.vendor_id,\n mount_points=tuple(Path(disk.component_id) for disk in usb_data.get(\"disks\")),\n serial_number=uid.uid.presumed_serial_number,\n serial_port=serial_port.port_name if serial_port else None,\n )\n\n @staticmethod\n def is_valid_candidate(usb_data: AggregatedUsbData) -> bool:\n \"\"\"States whether the usb device is a valid candidate or not.\"\"\"\n return usb_data.is_composite and usb_data.is_associated_with_disk\n","sub_path":"src/mbed_tools/devices/_internal/windows/device_detector.py","file_name":"device_detector.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"249958880","text":"import os\nimport sys\n\nfrom pathlib import Path\n\n# User packages\nPKGS_PATH = \"site/wwwroot/.python_packages\"\nVENV_PKGS_PATH = \"site/wwwroot/worker_venv\"\n\nPKGS_36 = \"lib/python3.6/site-packages\"\nPKGS = \"lib/site-packages\"\n\n# Azure environment variables\nAZURE_WEBSITE_INSTANCE_ID = \"WEBSITE_INSTANCE_ID\"\nAZURE_CONTAINER_NAME = \"CONTAINER_NAME\"\n\n\ndef is_azure_environment():\n return (AZURE_CONTAINER_NAME in os.environ\n or AZURE_WEBSITE_INSTANCE_ID in os.environ)\n\n\ndef determine_user_pkg_paths():\n minor_version = sys.version_info[1]\n\n home = Path.home()\n pkgs_path = os.path.join(home, PKGS_PATH)\n venv_pkgs_path = os.path.join(home, VENV_PKGS_PATH)\n\n user_pkg_paths = []\n if minor_version == 6:\n user_pkg_paths.append(os.path.join(venv_pkgs_path, PKGS_36))\n user_pkg_paths.append(os.path.join(pkgs_path, PKGS_36))\n user_pkg_paths.append(os.path.join(pkgs_path, PKGS))\n elif minor_version in (7, 8):\n user_pkg_paths.append(os.path.join(pkgs_path, PKGS))\n else:\n raise RuntimeError(f'Unsupported Python version: 3.{minor_version}')\n\n return user_pkg_paths\n\n\nif __name__ == '__main__':\n # worker.py lives in the same directory as azure_functions_worker\n func_worker_dir = str(Path(__file__).absolute().parent)\n env = os.environ\n\n if is_azure_environment():\n user_pkg_paths = determine_user_pkg_paths()\n\n joined_pkg_paths = os.pathsep.join(user_pkg_paths)\n env['PYTHONPATH'] = f'{joined_pkg_paths}:{func_worker_dir}'\n os.execve(sys.executable,\n [sys.executable, '-m', 'azure_functions_worker']\n + sys.argv[1:],\n env)\n else:\n sys.path.insert(1, func_worker_dir)\n from azure_functions_worker import main\n\n main.main()\n","sub_path":"python/prodV3/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"445477469","text":"#!/usr/bin/env python\nfrom init import Initializer\nfrom lib.general import General \nfrom lib.regr.regression import Regression\nfrom lib.ml.machine_learning import MachineLearning \n\n\nclass Miner:\n \"\"\"Miner is essentially a class to start the analysis process\"\"\"\n\n def __init__(self, conf, db_type = \"mysql\"):\n \"\"\"\n Args:\n conf (str): path to custom configuration file\n db_type (str): database type\n \"\"\"\n # fields\n self.conf = conf\n self.db_type = db_type\n self.table = \"\"\n\n def prep(self, table_name):\n \"\"\"Prepares everything for execution\"\"\"\n self.init = Initializer(self.conf, table_name, self.db_type)\n self.init.init_external_frameworks() \n self.table = self.init.table\n\n self.general = General(self.init)\n\n self.regression = Regression(self.init)\n self.ml = MachineLearning(self.init)\n","sub_path":"miner.py","file_name":"miner.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"207425101","text":"\"\"\"ilab_molecular URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.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 path, re_path, include\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nimport result.views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n re_path(r'^$', result.views.index, name = 'index'),\n re_path(r'logout', result.views.logout, name = 'logout'), \n path('login', result.views.user_login, name = 'login'),\n #B URLS\n re_path(r'^b_new', result.views.hbv_sample_input, name = 'b_new'),\n re_path(r'^b_sample_list', result.views.hbv_sample_list, name = 'b_sample_list'),\n re_path(r'^b_run_file', result.views.hbv_take_info_from_run, name = 'b_run_file'), \n re_path(r'b_detail/(\\d+)', result.views.hbv_sample_detail, name = 'b_detail'),\n re_path(r'b_image/(\\d+)', result.views.hbv_create_img, name = 'b_image'),\n #C URL\n re_path(r'^c_new', result.views.hcv_sample_input, name = 'c_new'),\n re_path(r'^c_sample_list', result.views.hcv_sample_list, name = 'c_sample_list'),\n re_path(r'^c_run_file', result.views.hcv_take_info_from_run, name = 'c_run_file'), \n re_path(r'c_detail/(\\d+)', result.views.hcv_sample_detail, name = 'c_detail'),\n re_path(r'c_image/(\\d+)', result.views.hcv_create_img, name = 'c_image'),\n #Cgeno URL\n re_path(r'^cg_new', result.views.hcvg_sample_input, name = 'cg_new'),\n re_path(r'^cg_sample_list', result.views.hcvg_sample_list, name = 'cg_sample_list'),\n re_path(r'^cg_run_file/(\\d+)', result.views.hcvg_take_info_from_run, name = 'cg_run_file'), \n re_path(r'cg_detail/(\\d+)', result.views.hcvg_sample_detail, name = 'cg_detail'),\n re_path(r'cg_image/(\\d+)', result.views.hcvg_create_img, name = 'cg_image'),\n \n #CTNG_URL\n re_path(r'^ctng_new', result.views.ctng_sample_input, name = 'ctng_new'),\n re_path(r'^ctng_sample_list', result.views.ctng_sample_list, name = 'ctng_sample_list'),\n re_path(r'^ctng_run_file', result.views.ctng_take_info_from_run, name = 'ctng_run_file'), \n re_path(r'ctng_detail/(\\d+)', result.views.ctng_sample_detail, name = 'ctng_detail'),\n re_path(r'ctng_image/(\\d+)', result.views.ctng_create_img, name = 'ctng_image'),\n #HPV_URL\n re_path(r'^hpv_new', result.views.hpv_sample_input, name = 'hpv_new'),\n re_path(r'^hpv_sample_list', result.views.hpv_sample_list, name = 'hpv_sample_list'),\n re_path(r'^hpv_run_file', result.views.hpv_take_info_from_run, name = 'hpv_run_file'), \n re_path(r'hpv_detail/(\\d+)', result.views.hpv_sample_detail, name = 'hpv_detail'),\n re_path(r'hpv_image/(\\d+)', result.views.hpv_create_img, name = 'hpv_image'),\n re_path(r'hpv_populate/(\\d+)', result.views.hpv_populate, name= 'hpv_populate')\n\n\n] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)\n","sub_path":"ilab_molecular/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"495991243","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.forms.forms import BoundField\nfrom django.utils.encoding import force_unicode\nfrom django.utils.html import conditional_escape\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext as _\n\nfrom xendor.structure import Structure\nfrom xendor.models import Page\nfrom xendor.utils import cyr2lat\n\n\n# ##===Страницы(Page)===###\napp_choises = Structure().apps\nchoice_list = [['', ' - Модули не ассоциированы - ']]\n\nfor item in app_choises:\n choice_list.append([item, app_choises[item]['app_name']])\n\n\ndef get_children(node):\n list = []\n for item in node.get_children():\n list.append([item.id, (item.level + 1) * '--' + ' ' + item.title])\n list += get_children(item)\n\n return list\n\n\ndef get_pages():\n list = [[None, ' - Корень - '], ]\n for item in Page.objects.filter(level=0):\n list.append([item.id, (item.level + 1) * '--' + ' ' + item.title])\n list += get_children(item)\n\n return list\n\n\nclass PageAdminForm(forms.ModelForm):\n app_extension = forms.CharField(\n label='Ассоциированый модуль',\n required=False,\n widget=forms.Select(choices=choice_list),\n )\n\n parent = forms.ChoiceField(label=u'Родительский элемент', required=False)\n\n def __init__(self, *args, **kwargs):\n self.declared_fields['parent'].choices = get_pages()\n\n super(PageAdminForm, self).__init__(*args, **kwargs)\n\n\n # def clean_slug(self):\n # slug = self.cleaned_data.get('slug', None)\n #\n # if slug.lower() != cyr2lat(slug).lower().replace(' ', '_'):\n # raise forms.ValidationError(u'Неправильный формат синонима страницы (нельзя использовать дефис)')\n #\n # return slug\n\n def clean_parent(self):\n parent = self.cleaned_data.get('parent', None)\n\n try:\n parent = Page.objects.get(pk=parent)\n except:\n parent = None\n\n if parent and self.instance.id:\n children = [[self.instance.id,\n (self.instance.level + 1) * '—' + ' ' + self.instance.title], ] + get_children(self.instance)\n\n if [parent.id, (parent.level + 1) * '——' + ' ' + parent.title] in children:\n raise forms.ValidationError(u'Страница не может быть дочерней к себе или своим потомкам')\n\n return parent\n\n class Meta:\n model = Page\n\n exclude = (\n )\n","sub_path":"xendor/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"510191527","text":"\n# coding: utf-8\n\n# In[3]:\n\nimport numpy as np\n\n# >Реализуйте алгоритм аппроксимации одномерной последовательности\n# >полиномом N степени через метод наименьших квадратов.\n\n# >Рекомендуется ограничиться: matplotlib, numpy\n# >Примечание 1: Не используйте возможности scipy по построению регрессий\n\n# Буду писать в предположении, что np.linalg.solve нельзя.\n# под Питон3\n\n# разложение матрицы в произведение\n# нижнетреугольной с 1 на главной диагонали и верхнетреугольной\ndef LUdecomp(A):\n n = A.shape[0]\n LU = np.empty_like(A)\n for i in range(n):\n LU[i, i] = A[i, i]-(LU[i, :i] * LU[:i, i]).sum()\n for j in range(i + 1, n):\n LU[i, j] = A[i, j]-(LU[i, :i] * LU[:i, j]).sum()\n LU[j, i] = (A[j, i]-(LU[j, :i] * LU[:i, i]).sum()) / LU[i,i]\n return LU\n\na = np.random.random((3,3))+2\nprint (a)\nb=LUdecomp(a)\nprint (b)\n\n\n# In[4]:\n\n# решение СЛАУ этим разложением(компактная схема Гаусса)\ndef Lsolve(L, b):\n y = np.empty_like(b)\n n = b.size\n for i in range(n):\n y[i] = b[i] - (L[i, :i] * y[:i]).sum()\n return y\n\ndef Usolve(U, b):\n y = np.empty_like(b)\n n = b.size\n for i in range(n):\n j = n-i-1\n y[j] = (b[j] - (U[j, j+1:n] * y[j+1:n]).sum())/U[j, j]\n return y\n\ndef SLEsolve(A, b):\n LU = LUdecomp(A)\n y = Lsolve(LU, b)\n x = Usolve(LU, y)\n return x\n\na = np.random.random((3,3))+2\nprint (a)\nx0 = np.random.random(3)+2\nprint (x0)\nb = a.dot(x0)\nprint (b)\nx = SLEsolve(a,b)\nprint(x)\n\n\n# In[5]:\n\n# решение МНК\ndef regrkoef(x, y, m):\n A = np.fromfunction(lambda i, j: x[i]**j,(x.size, m), dtype=int )\n #print (A)\n #print (A.T)\n #print (np.dot(A.T, A))\n #print (np.dot(A.T, y))\n return SLEsolve(np.dot(A.T, A), np.dot(A.T, y))\n\n# потом доделать для нормального принятия массива на входе\ndef regrpol(x, y, m):\n k = regrkoef(x, y, m)\n def pol(u):\n return np.fromiter((k[i]*(u**i) for i in range(m)), dtype=int).sum()\n return pol\n\ndef regrpol1(x, y, m):\n k = regrkoef(x, y, m)\n def pol(u):\n return np.fromfunction(lambda i, j: k[j]*(u[i]**j), (u.size, m), dtype=int).sum(axis=1)\n return k, pol\n\n\na=np.arange(5)+2\nprint(a)\nb=np.fromfunction(lambda i, j: a[i]**j, (5,3), dtype=int )\nprint (b)\nx=1\nc=np.fromiter((a[i]*(x**i) for i in range(5)), dtype=int).sum()\nprint (c)\n\n\n# In[6]:\n\n# для сравнения скопирую пример с пар\n# красные графики - пара, синие - этот метод\nget_ipython().magic('matplotlib inline')\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\n\ndef func(x, a, b, c):\n return a * x**2 + b * x + c\n\nxdata = np.linspace(0, 4, 50)\ny = func(xdata, 2.5, 1.3, 0.5)\nydata = y + 0.5 * np.random.normal(size=len(xdata))\n\npopt, pcov = curve_fit(func, xdata, ydata)\n\nprint (popt)\n\nfunc(xdata, *popt)\n\nplt.scatter(xdata, ydata)\nplt.plot(xdata, func(xdata, *popt), color='red')\nplt.show()\n\n\nprint (\"--------------------------------------------------\")\n\nk, p=regrpol1(xdata, ydata, 3)\n\nprint (k)\n\nplt.scatter(xdata, ydata)\nplt.plot(xdata, p(xdata), color='blue')\nplt.show()\n\n\nprint (\"--------------------------------------------------\")\n\n\ndef func(x, a, b, c):\n return a * np.exp(-b * x) + c\n\nxdata = np.linspace(0, 4, 50)\ny = func(xdata, 2.5, 1.3, 0.5)\nydata = y + 0.5 * np.random.normal(size=len(xdata))\n\npopt, pcov = curve_fit(func, xdata, ydata)\n\nprint (popt)\n\nfunc(xdata, *popt)\n\nplt.scatter(xdata, ydata)\nplt.plot(xdata, func(xdata, *popt), color='red')\nplt.show()\n\n\nprint (\"--------------------------------------------------\")\n\nk, p=regrpol1(xdata, ydata, 3)\n\nprint (k)\n\nplt.scatter(xdata, ydata)\nplt.plot(xdata, p(xdata), color='blue')\nplt.show()\n\n\nprint (\"--------------------------------------------------\")\n\n\ndef func(x, a, b, c):\n return a * np.sin(-b * x) + c\n\nxdata = np.linspace(0, 4, 50)\ny = func(xdata, 2.5, 1.3, 0.5)\nydata = y + 0.5 * np.random.normal(size=len(xdata))\n\npopt, pcov = curve_fit(func, xdata, ydata)\n\nprint (popt)\n\nfunc(xdata, *popt)\n\nplt.scatter(xdata, ydata)\nplt.plot(xdata, func(xdata, *popt), color='red')\nplt.show()\n\nprint (\"--------------------------------------------------\")\n\nk, p=regrpol1(xdata, ydata, 4)\n\nprint (k)\n\nplt.scatter(xdata, ydata)\nplt.plot(xdata, p(xdata), color='blue')\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n","sub_path":"Regr.py","file_name":"Regr.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"505788749","text":"#!/usr/bin/env python\nimport sys\nimport os\nimport rospy\nimport time\nimport rospkg\nimport unittest\n\nrospack = rospkg.RosPack()\nmission_control_path = rospack.get_path('mission_control')\n\nsys.path.append(\"%s/src\" % mission_control_path)\n\nfrom mission_control_utils_constants import Constants\nimport mission_control_utils\nfrom std_msgs.msg import Bool\nfrom std_msgs.msg import Int32\n\nrospy.init_node('test_watchdog_fail_safe', anonymous=True)\n\nclass TestWatchdogFailSafe(unittest.TestCase):\n\n fail_safe_started = False\n fail_safe_finished = False\n test_counter6_foo = None\n test_counter6_bar = None\n\n def fail_safe_started_callback(self, data):\n self.fail_safe_started = data.data\n\n def fail_safe_finished_callback(self, data):\n self.fail_safe_finished = data.data\n\n def fail_safe_foo_callback(self, data):\n self.test_counter6_foo = data.data\n\n def fail_safe_bar_callback(self, data):\n self.test_counter6_bar = data.data\n\n def test_fail_safe_run_and_variables(self):\n rospy.Subscriber(\"/mission_control/test/fail_safe/started\", Bool, self.fail_safe_started_callback)\n rospy.Subscriber(\"/mission_control/test/fail_safe/finished\", Bool, self.fail_safe_finished_callback)\n rospy.Subscriber(\"/mission_control/test/fail_safe/test_counter6_foo\", Int32, self.fail_safe_foo_callback)\n rospy.Subscriber(\"/mission_control/test/fail_safe/test_counter6_bar\", Int32, self.fail_safe_bar_callback)\n\n mission_control_utils.subscribe_to_topics()\n\n bar = None\n foo = None\n\n timeout_t = time.time() + 60.0\n while not rospy.is_shutdown() and not self.fail_safe_finished and time.time() < timeout_t:\n if self.fail_safe_started:\n foo = int(mission_control_utils.get_var(\"test_counter6_foo\", -1)) #Getting data from fail safe node\n bar = int(mission_control_utils.get_var(\"test_counter6_bar\", -1)) #Getting data from fail safe node\n time.sleep(0.1)\n\n self.assertTrue(self.fail_safe_finished)\n self.assertTrue(self.test_counter6_foo == 10)\n self.assertTrue(self.test_counter6_bar == 100)\n self.assertTrue(foo == 10)\n self.assertTrue(bar == 100)\n\nif __name__ == '__main__':\n import rostest\n rostest.rosrun('mission_control', 'test_watchdog_fail_safe', TestWatchdogFailSafe)\n","sub_path":"test/test_watchdog_fail_safe.py","file_name":"test_watchdog_fail_safe.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"538158825","text":"import scrapy\nfrom ..items import PortoHousingItem\n\nclass PortoHousingSpider(scrapy.Spider):\n name = 'imovirtual'\n start_urls = [\n 'https://www.imovirtual.com/comprar/predio/porto/?search%5Bregion_id%5D=13&search%5Bsubregion_id%5D=190'\n ]\n def parse(self, response):\n\n items = PortoHousingItem()\n\n offer_items = response.css(\"div.offer-item-details\")\n\n for offer in offer_items:\n\n title = offer.css('span.offer-item-title::text').extract()[0]\n price = offer.css('li.offer-item-price::text').extract()[0].replace(' ','')\n\n format = offer.css('.offer-item-rooms::text').extract()\n area = offer.css('.offer-item-area::text').extract()[0]\n #params = response.css('.hidden-xs li::text').extract()\n #type = response.css('span.hidden-xs::text').extract()\n #local = response.css('p.text-nowrap::text').extract()\n\n items['price'] = price\n items['area'] = area\n items['format'] = format\n items['title'] = title\n\n yield items\n\n\n next_page = response.css('li.pager-next a::attr(href)').get()\n\n if next_page is not None:\n yield response.follow(next_page, callback= self.parse)\n","sub_path":"porto_housing/porto_housing/spiders/imovirtual_spider - teste.py","file_name":"imovirtual_spider - teste.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"241087187","text":"import MySQLdb\nfrom time import localtime,strftime\nimport pprint\n\n\ndef Database(device,data):\n print(\"Attempting database\")\n db=MySQLdb.connect(\"localhost\",\"raspberry\",\"helloworld\",\"raspberry\")\n pprint.pprint(data)\n curs=db.cursor()\n\n #Data Variables\n query =\"\"\n temprature = \"\"\n humidity =\"\"\n light_status=\"\"\n date_time = strftime((\"%Y-%m-%d %H:%M:%S\"),localtime())\n if(device == \"1\"):\n #Save the temprature & Humidity\n tableName = \"temprature\"\n temprature=data[0]\n humidity = data[1]\n\n query =\"insert into %s (device,temprature,humidity,date) values('%s','%s','%s','%s')\"%(tableName,device,temprature,humidity,date_time)\n try:\n curs.execute(query)\n db.commit()\n except:\n print(\"Error\")\n db.rollback()\n\n if(device==\"2\"):\n tableName = \"corridor\"\n light_status = \"on\" if(data[1]) else \"off\"\n door_status = \"opened\" if(data[2]) else \"closed\"\n secure = \"secure\" if(data[3]) else \"unsecure\"\n query =\"insert into %s (device,light,door,homesecuriety,date) values('%s','%s','%s','%s','%s')\"%(tableName,device,light_status,door_status,secure,date_time)\n print(query)\n try:\n curs.execute(query)\n db.commit()\n except:\n print(\"Error\")\n db.rollback()\n\n if(device==\"3\"):\n tableName = \"livingroom\"\n light_status = \"on\" if(data[0]) else \"off\"\n tv_status = \"on\" if(data[1]) else \"off\"\n query = \"insert into %s (device,light,tv,date) values('%s','%s','%s','%s')\"%(tableName,device,light_status,tv_status,date_time)\n try:\n curs.execute(query)\n db.commit()\n except:\n print(\"Error\")\n db.rollback()\n\n if(device==\"4\"):\n if(data[0]):\n pprint.pprint(data)\n \n tableName = \"room\"\n light_status = \"on\" if(data[1]) else \"off\"\n window_status = \"opened\" if(data[2]) else \"closed\"\n rainy = \"rainy\" if(data[3]) else \"none\"\n query = \"insert into %s (device,light,window,rainy,date) values('%s','%s','%s','%s','%s')\"%(tableName,device,light_status,window_status,rainy,date_time)\n try:\n curs.execute(query)\n db.commit()\n except:\n print(\"Error\")\n db.rollback()\n print(query)\n","sub_path":"Listening Mode Home Pi/Listening Mode/Devices/Database.py","file_name":"Database.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"553327122","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nThis script includes the remote computations for single-shot ridge\nregression with decentralized statistic calculation\n\"\"\"\nimport argparse\nimport json\nimport sys\nimport scipy as sp\nimport numpy as np\nimport regression as reg\n\n\ndef remote_1(args, computation_phase):\n \"\"\"\n Args:\n args (dictionary): {\n 'output': {\n 'beta_vector_local': ,\n 'r_2_local': ,\n 'ts_local': ,\n 'ps_local': ,\n 'mean_y_local': ,\n 'count_local': ,\n 'computation_phase':\n },\n 'cache': {\n 'covariates': ,\n 'dependents': ,\n 'lambda':\n }\n }\n\n computation_phase (string): field specifying which part (local/remote)\n of the decentralized computation has been\n performed last\n In this case, it has to be empty\n\n Returns:\n computation_output (json) : {\n 'cache': {\n 'avg_beta_vector': ,\n 'mean_y_global': ,\n 'dof_global': ,\n 'dof_local': ,\n 'beta_vector_local': ,\n 'r_2_local': ,\n 'ts_local': ,\n 'ps_local':\n },\n 'output': {\n 'avg_beta_vector': ,\n 'mean_y_global': ,\n 'computation_phase':\n }\n }\n\n Comments:\n Step 1: Calculate the averaged beta vector, mean_y_global & dof_global\n Step 2: Retrieve the local fit statistics and save them in the cache\n \"\"\"\n input_list = args['input']\n\n # Step 1\n avg_beta_vector = np.mean(\n [site['beta_vector_local'] for site in input_list])\n\n mean_y_local = [site['mean_y_local'] for site in input_list]\n count_y_local = [site['count_local'] for site in input_list]\n mean_y_global = np.average(mean_y_local, weights=count_y_local)\n\n dof_global = np.sum(count_y_local) - len(avg_beta_vector)\n\n # Step 2\n beta_vector_local = [site['beta_vector_local'] for site in input_list]\n dof_local = [\n site['count_local'] - len(avg_beta_vector) for site in input_list\n ]\n r_2_local = [site['r_2_local'] for site in input_list]\n ts_local = [site['ts_local'] for site in input_list]\n ps_local = [site['ps_local'] for site in input_list]\n\n computation_output_dict = {\n 'cache': {\n 'avg_beta_vector': avg_beta_vector.tolist(),\n 'mean_y_global': mean_y_global,\n 'dof_global': dof_global,\n 'dof_local': dof_local,\n 'beta_vector_local': beta_vector_local,\n 'r_2_local': r_2_local,\n 'ts_local': ts_local,\n 'ps_local': ps_local\n },\n 'output': {\n 'avg_beta_vector': avg_beta_vector.tolist(),\n 'mean_y_global': mean_y_global,\n 'computation_phase': computation_phase\n }\n }\n\n return json.dumps(\n computation_output_dict,\n sort_keys=True,\n indent=4,\n separators=(',', ': '))\n\n\ndef remote_2(args, computation_phase):\n \"\"\"\n # calculate the global model fit statistics, r_2_global, ts_global,\n # ps_global\n Args:\n args (dictionary): {\n 'output': {\n 'SSE_local': ,\n 'SST_local': ,\n 'varX_matrix_local': ,\n 'computation_phase':\n }\n }\n\n computation_phase (String): field specifying which part (local/remote)\n of the decentralized computation has been\n performed last\n In this case, it has to be empty\n Returns:\n computation_output (json) : {\n 'output': {\n 'avg_beta_vector': ,\n 'beta_vector_local': ,\n 'r_2_global': ,\n 'ts_global': ,\n 'ps_global': ,\n 'r_2_local': ,\n 'ts_local': ,\n 'ps_local': ,\n 'dof_global': ,\n 'dof_local': ,\n 'complete':\n }\n }\n \"\"\"\n cache_list = args['cache']\n input_list = args['input']\n avg_beta_vector = cache_list['avg_beta_vector']\n dof_global = cache_list['dof_global']\n\n SSE_global = np.sum([site['SSE_Local'] for site in input_list])\n SST_global = np.sum([site['SST_Local'] for site in input_list])\n varX_matrix_global = np.sum(\n [site['varX_matrix_Local'] for site in input_list])\n\n r_squared_global = 1 - (SSE_global / SST_global)\n MSE = SSE_global / dof_global\n var_covar_beta_global = MSE * sp.linalg.inv(varX_matrix_global)\n se_beta_global = np.sqrt(var_covar_beta_global.diagonal())\n ts_global = avg_beta_vector / se_beta_global\n ps_global = reg.t_to_p(ts_global, dof_global)\n\n computation_output_dict = {\n 'output': {\n 'avg_beta_vector': cache_list['avg_beta_vector'],\n 'beta_vector_local': cache_list['beta_vector_local'],\n 'r_2_global': r_squared_global,\n 'ts_global': ts_global,\n 'ps_global': ps_global,\n 'r_2_local': cache_list['r_2_local'],\n 'ts_local': cache_list['ts_local'],\n 'ps_local': cache_list['ps_local'],\n 'dof_global': cache_list['dof_global'],\n 'dof_local': cache_list['dof_local'],\n 'complete': True\n }\n }\n\n return json.dumps(\n computation_output_dict,\n sort_keys=True,\n indent=4,\n separators=(',', ': '))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='help read in coinstac \\\n input from local node')\n parser.add_argument('--run', type=json.loads, help='grab coinstac args')\n args = parser.parse_args()\n parsed_args = args.run\n\n # *******block 1*********\n if input_list[0]['computation_phase'] == 'local_1':\n computation_phase = 'remote_1'\n computation_output = remote_1(parsed_args, computation_phase)\n sys.stdout.write(computation_output)\n\n # *******block 2********#\n elif input_list[0]['computation_phase'] == 'local_2':\n computation_phase = 'remote_2'\n # step 1 calculate the global model fit statistics,\n # r_2_global, t_global, p_global\n computation_output = remote_2(parsed_args, computation_phase)\n sys.stdout.write(computation_output)\n else:\n raise ValueError(\"Errors occurred\")\n","sub_path":"remote.py","file_name":"remote.py","file_ext":"py","file_size_in_byte":7883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"510053592","text":"import random\nimport numpy as np\nfrom collections import deque\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nfrom keras import backend as K\nfrom keras.layers import Input\nfrom keras.models import Model\nimport tensorflow as tf\nfrom keras.models import Sequential\nfrom keras.layers import Conv1D\nfrom keras.layers import Conv2D\nfrom keras.layers import Reshape\nfrom keras.layers import Flatten\n\nBIT_RATE = [500.0,850.0,1200.0,1850.0]\n\nclass DQNAgent:\n def __init__(self, state_size, action_size):\n self.state_size = state_size\n self.action_size = action_size\n self.memory = deque(maxlen=200000)\n self.gamma = 0.95 # discount rate\n self.epsilon = 0.0 # exploration rate\n self.epsilon_min = 0.0\n self.epsilon_decay = 0.0\n self.learning_rate = 0.0001\n self.model = self._build_model()\n self.target_model = self._build_model()\n self.update_target_model()\n\n def _huber_loss(self, y_true, y_pred, clip_delta=1.0):\n error = y_true - y_pred\n cond = K.abs(error) <= clip_delta\n\n squared_loss = 0.5 * K.square(error)\n quadratic_loss = 0.5 * K.square(clip_delta) + clip_delta * (K.abs(error) - clip_delta)\n\n return K.mean(tf.where(cond, squared_loss, quadratic_loss))\n\n def _build_model(self):\n # Neural Net for Deep-Q learning Model\n model = Sequential()\n # model.add(Dense(128,input_dim=self.state_size, activation='relu'))\n model.add(Reshape((50,5),input_shape=(self.state_size,)))\n model.add(Conv1D(5,kernel_size=4, activation='relu'))\n model.add(Flatten())\n model.add(Dense(128, activation='relu'))\n model.add(Dense(128, activation='relu'))\n model.add(Dense(self.action_size, activation='relu'))\n model.compile(loss=self._huber_loss,\n optimizer=Adam(lr=self.learning_rate))\n return model\n\n def update_target_model(self):\n # copy weights from model to target_model\n self.target_model.set_weights(self.model.get_weights())\n\n def remember(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done))\n\n def act(self, state):\n if np.random.rand() <= self.epsilon:\n return random.randrange(self.action_size)\n act_values = self.model.predict(state)\n return np.argmax(act_values[0]) # returns action\n\n def replay(self, batch_size):\n minibatch = random.sample(self.memory, batch_size)\n for state, action, reward, next_state, done in minibatch:\n target = self.model.predict(state)\n if done:\n target[0][action] = reward\n else:\n a = self.model.predict(next_state)[0]\n t = self.target_model.predict(next_state)[0]\n # target[0][action] = reward + self.gamma * np.amax(t)\n target[0][action] = reward + self.gamma * t[np.argmax(a)]\n self.model.fit(state, target, epochs=1, verbose=0)\n if self.epsilon > self.epsilon_min:\n self.epsilon -= self.epsilon_decay\n\n def load(self, name):\n self.model.load_weights(name)\n\n def save(self, name):\n self.model.save_weights(name)\n\n\nclass Algorithm:\n def __init__(self):\n # fill your init vars\n self.state_size = 250\n self.action_size = 64\n self.history_len = 50\n self.BITRATE = [0, 1, 2, 3]\n self.TARGET_BUFFER = [0, 1, 2, 3]\n self.LATENCY_LIMIT = [1, 2, 3, 4]\n self.ACTION_SAPCE = []\n self.agent = DQNAgent(self.state_size, self.action_size)\n\n # Intial\n def Initial(self,model_name):\n # name = \"save/16.h5\"\n name = str(model_name+\"100.h5\")\n self.agent.load(name)\n\n for i in self.BITRATE:\n for j in self.TARGET_BUFFER:\n for k in self.LATENCY_LIMIT:\n action_apace = []\n action_apace.append(i)\n action_apace.append(j)\n action_apace.append(k)\n self.ACTION_SAPCE.append(action_apace)\n\n #Define your al\n def run(self, time, S_time_interval, S_send_data_size, S_chunk_len, S_rebuf, S_buffer_size, S_play_time_len,\n S_end_delay, S_decision_flag, S_buffer_flag, S_cdn_flag, S_skip_time, end_of_video, cdn_newest_id,\n download_id, cdn_has_frame, IntialVars, start_avgbw):\n\n target_buffer = 1\n latency_limit = 4\n\n state = []\n length = len(S_time_interval)\n history_len = self.history_len\n for i in S_buffer_size[length-history_len:]:\n state.append(i*0.1)\n for i in S_send_data_size[length-history_len:]:\n state.append(i*0.00001)\n for i in S_time_interval[length-history_len:]:\n state.append(i*10)\n for i in S_end_delay[length-history_len:]:\n state.append(i*0.1)\n for i in S_rebuf[length-history_len:]:\n state.append(i)\n\n state = np.reshape(state, [1, self.state_size])\n # print(state)\n action = self.agent.act(state)\n bit_rate = self.ACTION_SAPCE[action][0]\n target_buffer = self.ACTION_SAPCE[action][1]\n latency_limit = self.ACTION_SAPCE[action][2]\n\n return bit_rate, target_buffer,latency_limit\n","sub_path":"PDDQN_.py","file_name":"PDDQN_.py","file_ext":"py","file_size_in_byte":5352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"302721933","text":"# -*- coding: utf-8 -*-\r\n\r\nimport random\r\nimport collections\r\n\r\nfrom pytz import utc\r\n\r\nfrom pymongo import MongoClient\r\nfrom apscheduler.schedulers.blocking import *\r\nfrom apscheduler.jobstores.mongodb import MongoDBJobStore\r\nfrom apscheduler.jobstores.memory import MemoryJobStore\r\nfrom apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor\r\nfrom apscheduler.events import *\r\n\r\nimport threading\r\n\r\nlock = threading.Lock()\r\n\r\n\r\nhost = '127.0.0.1'\r\nport = 27017\r\nclient = MongoClient(host, port)\r\n\r\njobstores = {\r\n 'mongo': MongoDBJobStore(collection='job', database='game', client=client),\r\n 'default': MemoryJobStore()\r\n}\r\nexecutors = {\r\n 'default': ThreadPoolExecutor(10),\r\n 'processpool': ProcessPoolExecutor(3)\r\n}\r\njob_defaults = {\r\n 'coalesce': False,\r\n 'max_instances': 3\r\n}\r\n\r\n\r\nclass Unit:\r\n def __init__(self,name):\r\n self.name = name\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n def after_dead(self):\r\n pass\r\n\r\n def when_init(self):\r\n pass\r\n\r\n\r\nclass Hero(Unit):\r\n '''Hero: a role of the game\r\n name: the name of the hero\r\n life: the life of the hero\r\n damage: damage per second\r\n shield: the life of shield\r\n '''\r\n def __init__(self, name, life, damage, shield, speed):\r\n self.name = name\r\n self.life0 = self.life = life\r\n self.damage = damage\r\n self.shield0 = self.shield = shield\r\n self.speed = speed\r\n self._army = None\r\n\r\n @staticmethod\r\n def fromStr(s):\r\n # str -> Hero\r\n name, life, damage, shield, speed = s.split()\r\n return Hero(name, int(life), int(damage), int(shield), float(speed))\r\n \r\n def hit(self, other):\r\n assert isinstance(other, Army)\r\n with lock:\r\n if other:\r\n hero = other.random()\r\n else:\r\n raise ValueError('there is no hero left in the army %s'%other)\r\n print('%s 攻击 %s'%(self, hero))\r\n if not hero.shieldbreak():\r\n hero.shield -= self.damage\r\n if hero.shieldbreak():\r\n print('%s 护盾破裂'%hero)\r\n else:\r\n hero.life -= self.damage\r\n if hero.isdead():\r\n other -= hero\r\n return hero, other\r\n\r\n def shieldbreak(self):\r\n return self.shield <= 0\r\n\r\n def isdead(self):\r\n return self.life <= 0\r\n \r\n def reset(self):\r\n self.life = self.life0\r\n self.shield = self.shield0\r\n\r\n\r\nclass Army(Unit, collections.UserList):\r\n def __init__(self, name, heros):\r\n self.name = name\r\n self.data = heros\r\n\r\n def copy(self):\r\n import copy\r\n return copy.deepcopy(self)\r\n\r\n def random(self):\r\n return random.choice(self)\r\n\r\n @staticmethod\r\n def fromStr(name, s):\r\n # str -> Army\r\n heros = s.split(';')\r\n return Army(name, [Hero.fromStr(h) for h in heros])\r\n\r\n def __iadd__(self, other):\r\n if isinstance(other, Hero):\r\n self.append(other)\r\n else:\r\n self.extend(other)\r\n return self\r\n\r\n def __add__(self, other):\r\n cpy = self.copy()\r\n cpy += other\r\n return cpy\r\n\r\n def __isub__(self, other):\r\n if isinstance(other, Hero):\r\n self.remove(other)\r\n else:\r\n for h in other:\r\n self.remove(h)\r\n return self\r\n\r\n def __sub__(self, other):\r\n cpy = self.copy()\r\n cpy -= other\r\n return cpy\r\n\r\n @property\r\n def damage(self):\r\n return sum(hero.damage for hero in self)\r\n \r\n def isdead(self):\r\n return len(self) == 0\r\n\r\n\r\n\r\nclass Game(object):\r\n '''Game has 3 (principal) propteries\r\n title: title\r\n army1: army1\r\n army2: army2'''\r\n def __init__(self, title, army1=None, army2=None):\r\n self.title = title\r\n self.army1 = army1\r\n self.army2 = army2\r\n self._scheduler = None\r\n\r\n def init(self):\r\n scheduler = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)\r\n\r\n for h in self.army1:\r\n scheduler.add_job(h.hit, 'interval', args=(self.army2,), seconds=h.speed, id=str(h))\r\n for h in self.army2:\r\n scheduler.add_job(h.hit, 'interval', args=(self.army1,), seconds=h.speed, id=str(h))\r\n\r\n # def check(army1, army2):\r\n # if army1.isdead() or army2.isdead():\r\n # scheduler.shutdown()\r\n # scheduler.add_job(check, 'interval', args=(army1, army2), seconds=5, id='check')\r\n\r\n def rmjob(evt):\r\n # remove a job\r\n hero, army = evt.retval\r\n if hero:\r\n if hero.isdead():\r\n scheduler.remove_job(str(hero))\r\n print('%s 阵亡'%hero)\r\n else:\r\n print('%s 还剩余生命值 %d'%(hero, hero.life))\r\n if army.isdead():\r\n try:\r\n scheduler.shutdown()\r\n except RuntimeError:\r\n print('%s 全军覆没'%army)\r\n\r\n scheduler.add_listener(rmjob, EVENT_JOB_EXECUTED)\r\n self._scheduler = scheduler\r\n\r\n\r\n def start(self):\r\n try:\r\n self._scheduler.start()\r\n except ValueError as v:\r\n print(v)\r\n finally:\r\n client.close()\r\n\r\n\r\nif __name__ ==\"__main__\":\r\n\r\n army1 = Army.fromStr('袁军', '袁绍 500 10 100 1;颜良 200 30 30 1;文丑 200 30 30 2')\r\n army2 = Army.fromStr('曹军', '曹操 800 30 200 2;荀彧 100 20 600 3;许褚 100 20 10 1')\r\n\r\n threeKingdoms = Game('官渡之战:东汉末年三大战役之一', army1=army1, army2=army2)\r\n threeKingdoms.init()\r\n threeKingdoms.start()\r\n \r\n\r\n\r\n","sub_path":"tinygame.py","file_name":"tinygame.py","file_ext":"py","file_size_in_byte":5832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"303333002","text":"def solve(N):\r\n if N == 0: return \"INSOMNIA\"\r\n x = N\r\n missing = set(range(10))\r\n while missing:\r\n y = x\r\n while missing and y > 0:\r\n d = y % 10\r\n y //= 10\r\n missing.discard(d)\r\n x += N\r\n return x - N\r\n\r\nif __name__ == \"__main__\":\r\n T = int(input())\r\n for t in range(1, T+1):\r\n N = int(input())\r\n print (\"Case #%d: %s\" % (t, solve(N)))\r\n","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_wysek_counting.py","file_name":"16_0_1_wysek_counting.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"148394942","text":"\"\"\"Common get info functions for configuration\"\"\"\r\n\r\n# Python\r\nimport logging\r\n\r\n# Genie\r\nfrom genie.utils.timeout import Timeout\r\nfrom genie.metaparser.util.exceptions import SchemaEmptyParserError\r\n\r\nlog = logging.getLogger(__name__)\r\n\r\ndef get_configuration_mpls_label_switched_path_name(device, path):\r\n \"\"\" Get path name from show configuration protocols mpls label-switched-path {path}\r\n\r\n Args:\r\n device (obj): Device object\r\n path (str): File to check\r\n\r\n Returns:\r\n str or None: Configured primary name\r\n \"\"\"\r\n\r\n # Example dict\r\n # \"configuration\": {\r\n # \"protocols\": {\r\n # \"mpls\": {\r\n # \"label-switched-path\": {\r\n # \"primary\": {\r\n # \"name\": str,\r\n # }\r\n # }\r\n # }\r\n # }\r\n # }\r\n\r\n try:\r\n out = device.parse('show configuration protocols mpls label-switched-path {path}'.format(\r\n path=path\r\n ))\r\n except SchemaEmptyParserError:\r\n return None\r\n\r\n return out.q.get_values('name', 0) or None\r\n\r\n\r\ndef get_configuration_mpls_paths(device, path):\r\n \"\"\" Get all paths from show configuration protocols mpls path {path}\r\n\r\n Args:\r\n device (obj): Device object\r\n path (str): Path to check\r\n\r\n Returns:\r\n List or None: All path addresses\r\n \"\"\"\r\n\r\n # Example dict\r\n # \"configuration\": {\r\n # \"protocols\": {\r\n # \"mpls\": {\r\n # \"path\": {\r\n # \"path-list\": [{\r\n # 'name': str,\r\n # }]\r\n # }\r\n # }\r\n # }\r\n # }\r\n\r\n try:\r\n out = device.parse('show configuration protocols mpls path {path}'.format(\r\n path=path\r\n ))\r\n except SchemaEmptyParserError:\r\n return None\r\n\r\n return out.q.get_values('name') or None","sub_path":"pkgs/sdk-pkg/src/genie/libs/sdk/apis/junos/configuration/get.py","file_name":"get.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"2275838","text":"import os\nimport pandas as pd\nfrom scipy.ndimage import imread\n\n\ndef df_for_scatter(path_to_dataset):\n categories = os.listdir(path_to_dataset)\n names_list = []\n categories_list = []\n height_list = []\n width_list = []\n for category in categories:\n temp_path = os.path.join(path_to_dataset, category)\n for name in os.listdir(temp_path):\n names_list.append(name)\n categories_list.append(category)\n temp_size = imread(os.path.join(temp_path, name)).shape\n height_list.append(temp_size[0])\n width_list.append(temp_size[1])\n\n df = pd.DataFrame({'name': names_list,\n 'category': categories_list,\n 'height (px)': height_list,\n 'width (px)': width_list})\n return df\n\n\ndef count_of_categories(path_to_dataset):\n categories = os.listdir(path_to_dataset)\n result_df = {}\n for category in categories:\n result_df[category] = len(os.listdir(os.path.join(path_to_dataset, category)))\n return result_df\n\n","sub_path":"src/visualization/scatter_size.py","file_name":"scatter_size.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"404788195","text":"from random import random, uniform\nfrom vector import *\nfrom math import cos, sin, pi\n\nclass Spike:\n\n\tdef __init__(self, pos, vel, rCircle, phase):\n\t\tself.pos = pos\n\t\tself.vel = vel\n\t\tself.size = 9\n\t\tself.r = 150\n\t\tself.circle = rCircle\n\t\tself.spike = 1\n\t\tself.phase = phase\n\t\tself.count = 2 * pi * 1 / (self.vel.magnitude()/self.r) # count = 2pi/omega\n\t\tself.t = 0\n\n\tdef step(self):\n\t\tomega = self.vel.magnitude()/self.r\n\t\t#print omega\n\t\t#print self.count\n\n\t\tdx = self.r * omega * -sin(omega*self.t + self.phase * pi/2)\n\t\tdy = self.r * omega * cos(omega*self.t + self.phase * pi/2)\n\t\tif self.t >= self.count:\n\t\t\tself.t = 0\n\t\telse:\n\t\t\tself.vel.x = dx\n\t\t\tself.vel.y = dy\n\t\t\tself.pos.add(Vector(dx, dy, 0))\n\t\t\tself.t = self.t + 1\n","sub_path":"simulation/spike.py","file_name":"spike.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"182818835","text":"import argparse\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('number')\n number_value = parser.parse_args().number\n return number_value\n\n\ndef format_price(price):\n price_string = try_to_float_else_throw_exception(price)\n formatted_price_string = []\n left_side_string, right_side_string = price_string.split('.')[0], price_string.split('.')[1]\n left_side = make_left_side(left_side_string)\n formatted_price_string.append(left_side)\n if bool(int(right_side_string)) is not False:\n formatted_price_string.append(right_side_string)\n return '.'.join(formatted_price_string)\n\n\ndef try_to_float_else_throw_exception(price):\n try:\n if price.count(\",\") is 1:\n formatted_price = price.replace(\",\", \".\")\n price_string = str(float(formatted_price))\n return price_string\n price_string = str(float(price))\n return price_string\n except ValueError:\n print(\" '{}' не является допустимым значением.\".format(price))\n quit()\n\n\ndef make_left_side(left_side_string):\n formatted_price = separate_by_3_signs_from_right(left_side_string)\n return formatted_price\n\n\ndef separate_by_3_signs_from_right(string):\n \"\"\"\n Функция форматирует строку, ставя разделитель в виде пробела после\n каждого 3-го числа. Так как отсчет для разделения начинаем слева, делаем\n реверс строки и разделяем ее, после чего делаем реверс обратно. \n \"\"\"\n signs_in_1000 = 3\n reversed_left_side = string[::-1]\n reversed_list_of_separated_elements = []\n for elem_index in range(0, len(reversed_left_side), signs_in_1000):\n reversed_three_sign_list = reversed_left_side[elem_index: elem_index+signs_in_1000]\n three_sign_string = ''.join(list(reversed(reversed_three_sign_list)))\n reversed_list_of_separated_elements.append(three_sign_string)\n formatted_string = ' '.join(list(reversed(reversed_list_of_separated_elements)))\n return formatted_string\n\n\ndef output_value(value):\n print(\"Отформатированное значение - {}\".format(value))\n\n\nif __name__ == '__main__':\n number_value = parse_arguments()\n formatted_value = format_price(number_value)\n output_value(formatted_value)\n","sub_path":"format_price.py","file_name":"format_price.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"43889150","text":"import calendar\nfrom datetime import date\nimport random\n\nfrom slackbot.bot import respond_to\nfrom slackbot import settings\nimport slacker\nimport git\n\nfrom ..botmessage import botsend, botreply, botwebapi\n\n\n@respond_to('^help$')\ndef help(message):\n \"\"\"\n helpページのURLを返す\n \"\"\"\n botsend(message, 'ヘルプはこちら→ https://github.com/pyconjp/pyconjpbot#commands')\n\n\n@respond_to('^shuffle\\s+(.*)')\ndef shuffle(message, words):\n \"\"\"\n 指定したキーワードをシャッフルして返す\n \"\"\"\n words = words.split()\n if len(words) == 1:\n botsend(message, 'キーワードを複数指定してください\\n`$shuffle word1 word2...`')\n else:\n random.shuffle(words)\n botsend(message, ' '.join(words))\n\n\n@respond_to('^choice\\s+(.*)')\ndef choice(message, words):\n \"\"\"\n 指定したキーワードから一つを選んで返す\n \"\"\"\n words = words.split()\n if len(words) == 1:\n botsend(message, 'キーワードを複数指定してください\\n`$choice word1 word2...`')\n else:\n botsend(message, random.choice(words))\n\n\n@respond_to('^ping$')\ndef ping(message):\n \"\"\"\n pingに対してpongで応答する\n \"\"\"\n botreply(message, 'pong')\n\n\n@respond_to('^version$')\ndef version(message):\n \"\"\"\n バージョン情報を返す\n \"\"\"\n obj = git.Repo('').head.object\n url = \"https://github.com/pyconjp/pyconjpbot/commit/{}\".format(obj.hexsha)\n text = \"<{}|{}> {} - {}({})\".format(\n url, obj.hexsha[:6], obj.summary,\n obj.committer.name, obj.committed_datetime)\n attachments = [{\n 'pretext': text,\n }]\n botwebapi(message, attachments)\n\n\n@respond_to('^random$')\n@respond_to('^random\\s+(active|help)$')\ndef random_command(message, subcommand=None):\n \"\"\"\n チャンネルにいるメンバーからランダムに一人を選んで返す\n\n - https://github.com/os/slacker\n - https://api.slack.com/methods/channels.info\n - https://api.slack.com/methods/users.getPresence\n - https://api.slack.com/methods/users.info\n \"\"\"\n\n if subcommand == 'help':\n botsend(message, '''- `$random`: チャンネルにいるメンバーからランダムに一人を選ぶ\n- `$random active`: チャンネルにいるactiveなメンバーからランダムに一人を選ぶ\n''')\n return\n\n # チャンネルのメンバー一覧を取得\n channel = message.body['channel']\n webapi = slacker.Slacker(settings.API_TOKEN)\n cinfo = webapi.channels.info(channel)\n members = cinfo.body['channel']['members']\n\n # bot の id は除く\n bot_id = message._client.login_data['self']['id']\n members.remove(bot_id)\n\n member_id = None\n while not member_id:\n # メンバー一覧からランダムに選んで返す\n member_id = random.choice(members)\n if subcommand == 'active':\n # active が指定されている場合は presence を確認する\n presence = webapi.users.get_presence(member_id)\n if presence.body['presence'] == 'away':\n members.remove(member_id)\n member_id = None\n\n user_info = webapi.users.info(member_id)\n name = user_info.body['user']['name']\n botsend(message, '{} さん、君に決めた!'.format(name))\n\n\n@respond_to('^cal$')\n@respond_to('^cal\\s+(\\d+)$')\n@respond_to('^cal\\s+(\\d+)\\s+(\\d+)$')\ndef cal_command(message, month=None, year=None):\n \"\"\"\n 一ヶ月のカレンダーを返す\n \"\"\"\n today = date.today()\n month = int(month) if month else today.month\n year = int(year) if year else today.year\n\n cal = calendar.TextCalendar(firstweekday=calendar.SUNDAY)\n try:\n botsend(message, '```{}```'.format(cal.formatmonth(year, month)))\n except IndexError:\n # 数字が範囲外の場合は無視する\n pass\n\n\n@respond_to('^cal\\s+help$')\ndef cal_help(message):\n \"\"\"\n cal コマンドのヘルプを返す\n \"\"\"\n botsend(message, '''- `$cal`: 今月のカレンダーを返す\n- `$cal 9`: 今年の指定された月のカレンダーを返す\n- `$cal 9 2016`: 指定された年月のカレンダーを返す\n''')\n","sub_path":"pyconjpbot/plugins/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":4168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"480124510","text":"import base64\n\nimport web3\nfrom sdk.payment_channel import PaymentChannel\n\nfrom snet_cli.utils import get_contract_object, get_contract_deployment_block\n\n\nBLOCKS_PER_BATCH = 20000\n\n\nclass MPEContract:\n def __init__(self, w3):\n self.web3 = w3\n self.contract = get_contract_object(self.web3, \"MultiPartyEscrow.json\")\n self.event_topics = \\\n [self.web3.sha3(\n text=\"ChannelOpen(uint256,uint256,address,address,address,bytes32,uint256,uint256)\").hex()]\n self.deployment_block = get_contract_deployment_block(\n self.web3, \"MultiPartyEscrow.json\")\n\n def get_past_open_channels(self, account, service, starting_block_number=0, to_block_number=None):\n if to_block_number is None:\n to_block_number = self.web3.eth.getBlock(\"latest\")[\"number\"]\n\n if starting_block_number == 0:\n starting_block_number = self.deployment_block\n\n logs = []\n from_block = starting_block_number\n while from_block <= to_block_number:\n to_block = min(from_block + BLOCKS_PER_BATCH, to_block_number)\n logs = logs + self.web3.eth.getLogs({\"fromBlock\": from_block, \"toBlock\": to_block,\n \"address\": self.contract.address, \"topics\": self.event_topics})\n from_block = to_block + 1\n\n event_abi = self.contract._find_matching_event_abi(\n event_name=\"ChannelOpen\")\n group = service.metadata.get_group_id(service.group['group_name'])\n channels_opened = list(filter(\n lambda channel: channel.sender == account.address and channel.signer == account.signer_address and channel.recipient == service.group[\n \"payment_address\"] and channel.groupId == group,\n [web3.utils.events.get_event_data(\n event_abi, l)[\"args\"] for l in logs]\n ))\n return list(map(lambda channel: PaymentChannel(channel[\"channelId\"], self.web3, account, service, self), channels_opened))\n\n def balance(self, address):\n return self.contract.functions.balances(address).call()\n\n def deposit(self, account, amount_in_cogs):\n return account.send_transaction(self.contract.functions.deposit, amount_in_cogs)\n\n def open_channel(self, account, service, amount, expiration):\n return account.send_transaction(self.contract.functions.openChannel, account.signer_address, service.group[\"payment_address\"], base64.b64decode(str(service.group[\"group_id\"])), amount, expiration)\n\n def deposit_and_open_channel(self, account, service, amount, expiration):\n already_approved_amount = account.allowance()\n if amount > already_approved_amount:\n account.approve_transfer(amount)\n return account.send_transaction(self.contract.functions.depositAndOpenChannel, account.signer_address, service.group[\"payment_address\"], base64.b64decode(str(service.group[\"group_id\"])), amount, expiration)\n\n def channel_add_funds(self, account, channel_id, amount):\n self._fund_escrow_account(account, amount)\n return account.send_transaction(self.contract.functions.channelAddFunds, channel_id, amount)\n\n def channel_extend(self, account, channel_id, expiration):\n return account.send_transaction(self.contract.functions.channelExtend, channel_id, expiration)\n\n def channel_extend_and_add_funds(self, account, channel_id, expiration, amount):\n self._fund_escrow_account(account, amount)\n return account.send_transaction(self.contract.functions.channelExtendAndAddFunds, channel_id, expiration, amount)\n\n def _fund_escrow_account(self, account, amount):\n current_escrow_balance = self.balance(account.address)\n if amount > current_escrow_balance:\n account.deposit_to_escrow_account(amount - current_escrow_balance)\n","sub_path":"signer/sdk/mpe_contract.py","file_name":"mpe_contract.py","file_ext":"py","file_size_in_byte":3842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"34749728","text":"from itertools import chain\nimport abnormal.read_data\n\na=[1,2,3,4,5]\nb=('a','b','c')\nc={'a':1,'d':10}\nd=[(1,2)]\n\nfor i in chain(a,b,c.items(),d):\n print(i)","sub_path":"base_knowledge/迭代器/不同集合上元素的迭代.py","file_name":"不同集合上元素的迭代.py","file_ext":"py","file_size_in_byte":158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"625402966","text":"import os\n\n\nclass WordEmbeddingConfig:\n def __init__(self, data_root):\n self.glove_dictionary_file = os.path.join(data_root, 'word_embedding', 'glove_dictionary.json')\n self.glove_word_matrix_file = os.path.join(data_root, 'word_embedding', 'glove6b_init_300d.npy')\n self.fasttext_dictionary_file = os.path.join(data_root, 'word_embedding', 'fasttext_dictionary.json')\n self.fasttext_word_matrix_file = os.path.join(data_root, 'word_embedding', 'fasttext_init_300d.npy')\n\n\nclass Config:\n def __init__(self, args):\n self.tiers = args.tiers\n self.data_root = args.data_root\n self.save_dir = args.save_dir\n self.word_emb_config: WordEmbeddingConfig = WordEmbeddingConfig(self.data_root)\n\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"510249392","text":"#!/usr/bin/env python\r\n\r\n\r\nimport sys\r\nfrom subprocess import *\r\nimport json\r\n\r\n#=============================================Functions\r\n\r\n#read in source code from file and store it as a string\r\ndef readSourceCode(inputFileName):\r\n sourceCode = \"\"\r\n with open(inputFileName, \"r\") as input:\r\n for line in input:\r\n sourceCode = sourceCode + line\r\n return sourceCode\r\n\r\ndef getFunctionName(str, returnType):\r\n \r\n splitWithReturnType = str.split(returnType)[1]\r\n \r\n functionName = splitWithReturnType.lstrip()\r\n\r\n return functionName.split(\"(\")[0]\r\n\r\ndef getParameterList(str):\r\n splitLeftParen = str.split(\"(\")[1]\r\n functionParameters = splitLeftParen.split(\")\")[0]\r\n\r\n return functionParameters \r\n\r\ndef getParameterDictonary(str):\r\n splitLeftParen = str.split(\"(\")[1]\r\n functionParameters = splitLeftParen.split(\")\")[0]\r\n\r\n splitCommaToParametersList = getParameterList(str).split(\",\")\r\n \r\n parametersDictionary = {}\r\n \r\n for params in splitCommaToParametersList:\r\n keyValueArray = params.lstrip().split(\" \")\r\n key = keyValueArray[1]\r\n value = keyValueArray[0] \r\n parametersDictionary[key] = value\r\n \r\n return parametersDictionary \r\n \r\n \r\ndef getMethodBody(str):\r\n leftCurlyIndex = str.find(\"{\")\r\n leftCurlyRemoved = str[leftCurlyIndex+1:]\r\n\r\n reversedStr = reverseString(leftCurlyRemoved)\r\n\r\n rightCurlyIndex = reversedStr.find(\"}\")\r\n rightCurlyRemoved = reversedStr[rightCurlyIndex+1:]\r\n\r\n return reverseString(rightCurlyRemoved)\r\n\r\ndef reverseString(str):\r\n return str[::-1]\r\n\r\n \r\ndef generateJavaSourceCode(params, body, returnType, input):\r\n staticMethod = \"public static \" + returnType + \" run(\" + params + \") {\" + body + \"}\"\r\n\r\n mainSource = \"public class Main { public static void main(String[] args) { System.out.print(run(\" + input + \")); }\" + staticMethod + \"}\"\r\n\r\n return mainSource\r\n \r\ndef compileJava():\r\n call(\"ls\", \"-l\")\r\n\r\ndef Main():\r\n\r\n\r\n args = sys.argv\r\n source = readSourceCode(args[1])\r\n\r\n returnType = args[2]\r\n\r\n inputValue = args[3]\r\n\r\n functionName = getFunctionName(source, \"void\")\r\n\r\n paramDict = getParameterDictonary(source)\r\n\r\n paramterList = str(getParameterList(source))\r\n\r\n methodBody = getMethodBody(source)\r\n\r\n mainSource = generateJavaSourceCode(paramterList, methodBody, returnType, inputValue)\r\n\r\n\r\n\r\n with open(\"Main.java\", \"w\") as output:\r\n output.write(mainSource)\r\n\r\n call([\"javac\", \"Main.java\"])\r\n\r\n\r\n\r\n #returnResult = str(check_output([\"java\", \"Main\"]))[2:-3]\r\n\r\n cmd = \"java Main\"\r\n p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)\r\n returnResult = p.stdout.read() \r\n\r\n jsonList = [];\r\n paramDict[\"functionName\"] = functionName\r\n paramDict[\"input\"] = inputValue\r\n paramDict[\"output\"] = returnResult\r\n jsonList.append(paramDict)\r\n #for key in paramDict.keys():\r\n # json.append({key:paramDict[key]})\r\n\r\n\r\n\r\n print(json.dumps(jsonList));\r\n \r\n #print(str(json))\r\n\r\n#=============================================Main\r\n\r\n\r\nstr1 = \"public static void addTwo(int a, int b){return a+b;}\"\r\n\r\nprint(getMethodBody(str1))\r\n\r\n\r\n\r\n","sub_path":"front/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"142638893","text":"from pymongo import mongo_client\nfrom csv import DictWriter\n\n\nclass Mongo2Csv():\n def __init__(self, path='./policy.csv', host='127.0.0.1', port=27017, db_name='szkj', doc_name='policy'):\n self.to_path = path\n self.conn = mongo_client.MongoClient(host=host, port=port)\n self.db = self.conn[db_name]\n self.doc = self.db[doc_name]\n if not self.conn:\n raise Exception('Connection failure')\n\n def migrate(self):\n cursor = self.doc.find()\n filed_names = cursor[0].keys()\n with open(self.to_path, 'w') as f:\n csv_writer = DictWriter(f, filed_names)\n csv_writer.writeheader()\n for item in cursor:\n csv_writer.writerow(item)\n\n\nclient = Mongo2Csv()\nclient.migrate()\n","sub_path":"scrapycode/szkj/szkj/spiders/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"383076116","text":"# Write a method to replace all spaces in a string with '%20'.\n# You may assume that the string has sufficient space at the end to hold the additional characters,\n# and that you are given the \"true\" length of the string.\n\ninpstr = \"Mr John Smith\"\nlength = len(inpstr)\n\ndef urlify(mystr, length):\n spaces = 0\n for i in range(0 , length):\n if(mystr[i] == ' '):\n spaces += 1\n l = [''] * (length + spaces * 2)\n j = 0\n for i in range (0, 13):\n if(mystr[i] == ' '):\n l[j] = '%'\n j += 1\n l[j] = '2'\n j += 1\n l[j] = '0'\n else:\n l[j] = mystr[i]\n j += 1\n return l\n\nprint(urlify(inpstr, length))\n\n#Shorter Code:\ndef urlifyN(mystr):\n mylist = mystr.split(' ')\n #len() * 2 - 1 because after inserting '%20' we will have that many elements in the new list. Skipping two steps because after inserting\n # the element incerementing by one will insert element right after it resulting in duplicate '%20%20'\n for i in range(1, len(mylist) * 2 - 1, 2):\n mylist.insert(i,'%20')\n return ''.join(mylist)\n\nprint(urlifyN(inpstr))\n","sub_path":"Chapter1/1.3_URLify.py","file_name":"1.3_URLify.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"196653712","text":"# Strongly connected components\n\nfrom dfs import DFS\nfrom collections import deque, defaultdict\n\n\nclass SCC(DFS):\n\n def scc(self):\n \"\"\"Find strongly connected components in the graph\"\"\"\n q = deque()\n # topological sort gives us the order of vertices\n self.dfs(on_finished=lambda x: q.appendleft(x))\n return self._transposed_scc_dfs(q)\n\n def _transposed_scc_dfs(self, queue):\n \"\"\"Consider the vertices in order of decreasing finish time\"\"\"\n transposed = SCC.transpose(self)\n\n for v in transposed.vertices():\n v.color = \"white\"\n\n time = 1\n tree = 0\n for v in queue:\n vertex = transposed.vertex(v.vertex)\n if vertex.color == \"white\":\n tree += 1\n time = transposed._dfs(vertex, time, tree, None, None)\n\n components = defaultdict(deque)\n for vertex in transposed.vertices():\n components[vertex.tree].appendleft(self.vertex(vertex.vertex))\n\n return components\n\n\nif __name__ == \"__main__\":\n edges = [\n (\"a\", \"b\"),\n (\"b\", \"e\"),\n (\"b\", \"c\"),\n (\"b\", \"f\"),\n (\"c\", \"d\"),\n (\"c\", \"g\"),\n (\"d\", \"c\"),\n (\"d\", \"h\"),\n (\"e\", \"a\"),\n (\"e\", \"f\"),\n (\"f\", \"g\"),\n (\"g\", \"f\"),\n (\"g\", \"h\"),\n (\"h\", \"h\"),\n ]\n\n def print_scc(scc):\n for ix, components in scc.items():\n print(\"[{0}]:\".format(ix))\n for vertex in components:\n print(\" {0}\".format(vertex))\n print(\"\")\n\n g = SCC(edges, directed=True)\n print(\"-- Directed Graph: -- \")\n print(g)\n\n print(\"Transposed: \")\n print(SCC.transpose(g))\n\n print(\"Strongly connected components: \")\n print_scc(g.scc())","sub_path":"graphs/strongly-connected-components.py","file_name":"strongly-connected-components.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"308312973","text":"# Copyright 2017 AT&T Intellectual Property. All other rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport yaml\n\nfrom deckhand import factories\nfrom deckhand.tests import test_utils\nfrom deckhand.tests.unit.db import base\nfrom deckhand import types\n\nARMADA_VALIDATION_POLICY = \"\"\"\n---\nstatus: success\nvalidator:\n name: armada\n version: 1.1.3\n\"\"\"\n\nPROMENADE_VALIDATION_POLICY = \"\"\"\n---\nstatus: failure\nerrors:\n - documents:\n - schema: promenade/Node/v1\n name: node-document-name\n - schema: promenade/Masters/v1\n name: kubernetes-masters\n message: Node has master role, but not included in cluster masters list.\nvalidator:\n name: promenade\n version: 1.1.2\n\"\"\"\n\n\nclass TestValidations(base.TestDbBase):\n\n def _create_revision_with_validation_policy(self):\n vp_factory = factories.ValidationPolicyFactory()\n validation_policy = vp_factory.gen(types.DECKHAND_SCHEMA_VALIDATION,\n 'success')\n bucket_name = test_utils.rand_name('bucket')\n documents = self.create_documents(bucket_name, [validation_policy])\n revision_id = documents[0]['revision_id']\n return revision_id\n\n def test_create_validation(self):\n revision_id = self._create_revision_with_validation_policy()\n validation_name = test_utils.rand_name('validation')\n\n payload = yaml.safe_load(PROMENADE_VALIDATION_POLICY)\n created_validation = self.create_validation(\n revision_id, validation_name, payload)\n\n self.assertIsInstance(created_validation, dict)\n self.assertEqual(validation_name, created_validation['name'])\n self.assertEqual(payload['status'], created_validation['status'])\n self.assertEqual(payload['validator'], created_validation['validator'])\n\n def test_create_multiple_validations(self):\n revision_id = self._create_revision_with_validation_policy()\n\n for val_policy in (ARMADA_VALIDATION_POLICY,\n PROMENADE_VALIDATION_POLICY):\n validation_name = test_utils.rand_name('validation')\n\n payload = yaml.safe_load(val_policy)\n created_validation = self.create_validation(\n revision_id, validation_name, payload)\n\n payload.update({'name': validation_name})\n self.assertIsInstance(created_validation, dict)\n self.assertEqual(validation_name, created_validation['name'])\n self.assertEqual(payload['status'], created_validation['status'])\n self.assertEqual(payload['validator'],\n created_validation['validator'])\n","sub_path":"deckhand/tests/unit/db/test_validations.py","file_name":"test_validations.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"308634469","text":"import os\nimport sys\nimport json\nimport datetime\nimport numpy as np\nimport skimage.draw\n\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval\nfrom pycocotools import mask as maskUtils\n\nimport cv2\n\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../../\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn.config import Config\nfrom mrcnn import model as modellib, utils\n\n# Path to trained weights file\nCOCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\n\n# Directory to save logs and model checkpoints, if not provided\n# through the command line argument --logs\nDEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, \"logs\")\n\n\n\nclass DeskConfig(Config):\n \"\"\"Configuration for training on the toy dataset.\n Derives from the base Config class and overrides some values.\n \"\"\"\n # Give the configuration a recognizable name\n NAME = \"desks\"\n\n # Train on 1 GPU and 8 images per GPU. We can put multiple images on each\n # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).\n GPU_COUNT = 1\n IMAGES_PER_GPU = 4\n\n # Number of classes (including background)\n NUM_CLASSES = 1 + 1 # background + 3 shapes\n\n # Use small images for faster training. Set the limits of the small side\n # the large side, and that determines the image shape.\n IMAGE_MIN_DIM = 256\n IMAGE_MAX_DIM = 256\n\n LEARNING_RATE = 0.001\n LEARNING_MOMENTUM = 0.9\n\n # Use smaller anchors because our image and objects are small\n RPN_ANCHOR_SCALES = (16, 32, 64, 128, 256) # anchor side in pixels\n\n # Reduce training ROIs per image because the images are small and have\n # few objects. Aim to allow ROI sampling to pick 33% positive ROIs.\n TRAIN_ROIS_PER_IMAGE = 32\n\n # Use a small epoch since the data is simple\n STEPS_PER_EPOCH = 100\n\n # use small validation steps since the epoch is small\n VALIDATION_STEPS = 5\n\nclass DeskDataset(utils.Dataset):\n\n def load_desk(self,coco_root = \"./coco\",subset='train'):\n\n ann_path = os.path.join(coco_root,subset,'annotations.json')\n print(f'the annotation file is here:{ann_path}')\n\n coco = COCO(ann_path)\n\n class_ids = sorted(coco.getCatIds())\n image_ids = sorted(coco.getImgIds())\n if class_ids:\n for i in class_ids:\n self.add_class(\"desks\",i,coco.loadCats(i)[0][\"name\"])\n\n for i in image_ids:\n self.add_image(\"desks\",i,\n os.path.join(coco_root,subset,coco.imgs[i]['file_name']),\n width=coco.imgs[i][\"width\"],\n height = coco.imgs[i][\"height\"],\n annotations = coco.loadAnns(coco.getAnnIds(imgIds=[i]))\n )\n else:\n print(\"no category found!\")\n\n def load_mask(self,image_id):\n\n image_info = self.image_info[image_id]\n\n instance_masks = []\n class_ids = []\n annotations = self.image_info[image_id][\"annotations\"]\n # Build mask of shape [height, width, instance_count] and list\n # of class IDs that correspond to each channel of the mask.\n for annotation in annotations:\n class_id = self.map_source_class_id(\n \"desks.{}\".format(annotation['category_id']))\n if class_id:\n m = self.annToMask(annotation, image_info[\"height\"],\n image_info[\"width\"])\n # Some objects are so small that they're less than 1 pixel area\n # and end up rounded out. Skip those objects.\n if m.max() < 1:\n continue\n # Is it a crowd? If so, use a negative class ID.\n if annotation['iscrowd']:\n # Use negative class ID for crowds\n class_id *= -1\n # For crowd masks, annToMask() sometimes returns a mask\n # smaller than the given dimensions. If so, resize it.\n if m.shape[0] != image_info[\"height\"] or m.shape[1] != image_info[\"width\"]:\n m = np.ones([image_info[\"height\"], image_info[\"width\"]], dtype=bool)\n instance_masks.append(m)\n class_ids.append(class_id)\n\n # Pack instance masks into an array\n if class_ids:\n mask = np.stack(instance_masks, axis=2).astype(np.bool)\n class_ids = np.array(class_ids, dtype=np.int32)\n return mask, class_ids\n \n def image_reference(self,image_id):\n info = self.image_info[image_id]\n return info[\"path\"]\n\n # The following two functions are from pycocotools with a few changes.\n\n def annToRLE(self, ann, height, width):\n \"\"\"\n Convert annotation which can be polygons, uncompressed RLE to RLE.\n :return: binary mask (numpy 2D array)\n \"\"\"\n segm = ann['segmentation']\n if isinstance(segm, list):\n # polygon -- a single object might consist of multiple parts\n # we merge all parts into one mask rle code\n rles = maskUtils.frPyObjects(segm, height, width)\n rle = maskUtils.merge(rles)\n elif isinstance(segm['counts'], list):\n # uncompressed RLE\n rle = maskUtils.frPyObjects(segm, height, width)\n else:\n # rle\n rle = ann['segmentation']\n return rle\n\n def annToMask(self, ann, height, width):\n \"\"\"\n Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask.\n :return: binary mask (numpy 2D array)\n \"\"\"\n rle = self.annToRLE(ann, height, width)\n m = maskUtils.decode(rle)\n return m\n","sub_path":"samples/my/desk.py","file_name":"desk.py","file_ext":"py","file_size_in_byte":5798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"473001768","text":"#!/usr/bin/python\nimport math\nimport sys\nfrom vec2 import vec2\n\nTIKZ_DOC_BEGIN_OLD = r\"\"\"\n\\documentclass{article}\n\\usepackage{tikz}\n\\begin{document}\n\"\"\"\nTIKZ_DOC_BEGIN = r\"\"\"\n\\documentclass{book}\n\\usepackage{lipsum}% http://ctan.org/pkg/lipsum\n\\usepackage[margin=1cm,landscape,a3paper]{geometry}% http://ctan.org/pkg/geometry\n\\pagestyle{empty}% Set page style to empty\n\\makeatletter\n\\let\\ps@plain\\ps@empty% Make plain page style equivalent to empty page style\n\\makeatletter\n\\usepackage{tikz}\n\\begin{document}\n\"\"\"\nTIKZ_DOC_END = r\"\\end{document}\"\n\nROOT_COLOR = \"thick, black\"\nLEFT_COLOR = \"thick, blue\"\nRIGHT_COLOR = \"thick, red\"\n\nSCALE = 0.45\nNODE_RADIUS = SCALE * 4\nSPACING_VERT = SCALE * .707\nSPACING_HOR = SCALE * 1\nCELL_HEIGHT = SCALE * 4\nCELL_WIDTH = SCALE * 8\n\ndef largest_smaller_root(n, k=2):\n n_length = n.bit_length()\n root_length_lower_bound = n_length // k - 1\n root_length_upper_bound = root_length_lower_bound + 2\n lower_bound = 2 ** root_length_lower_bound\n upper_bound = 2 ** root_length_upper_bound\n estimate = 0\n found = False\n while not found:\n estimate = (lower_bound + upper_bound) // 2\n #print(lower_bound, estimate, upper_bound)\n check = estimate ** k\n if check == n:\n found = True\n elif check > n:\n upper_bound = estimate\n elif check < n:\n lower_bound = estimate\n if lower_bound == estimate and estimate + 1 == upper_bound:\n found = True\n return estimate\n\ndef inverse_gamma_2(r):\n #math.sqrt casts its input value to a float with too little precision to be used for very large numbers\n #x = math.floor((math.sqrt(8 * r - 7) - 1) / 2)\n x = (largest_smaller_root(8 * r - 7) - 1) // 2\n y = r - (x * x + x) // 2 - 1\n return (x, y)\n\nclass binary_tree:\n def __init__(self, root_label, rootcol = None, lcol = None, rcol = None):\n self.root_label = root_label\n self.root_pos = None\n self.bb_tl = None\n self.bb_br = None\n self.left_tree = None\n self.right_tree = None\n self.rootcol = rootcol if rootcol else \"black\"\n self.lcol = lcol if lcol else \"black\"\n self.rcol = rcol if rcol else \"black\"\n\n def build(self):\n if self.root_label == 0:\n self.bb_tl = vec2(0, 0)\n self.bb_br = vec2(0, 0)\n if self.root_label == 1:\n self.root_pos = vec2(0, 0)\n self.bb_tl = vec2(0, 0)\n self.bb_br = vec2(0, 0)\n else:\n x, y = inverse_gamma_2(self.root_label)\n if x > 0:\n self.left_tree = binary_tree(x, self.lcol, self.lcol, self.lcol)\n self.left_tree.build()\n if y > 0:\n self.right_tree = binary_tree(y, self.rcol, self.rcol, self.rcol)\n self.right_tree.build()\n\n if y > 0:\n left_width = self.left_tree.bb_br.x - self.left_tree.bb_tl.x\n right_width = self.right_tree.bb_br.x - self.right_tree.bb_tl.x\n height = self.left_tree.bb_tl.y\n offset_x = left_width + 0.5 * right_width + SPACING_HOR\n offset = vec2(offset_x, height) - self.right_tree.root_pos\n self.right_tree.transform(offset)\n center = 0.5 * (self.left_tree.root_pos + self.right_tree.root_pos)\n self.root_pos = vec2(center.x, height + SPACING_VERT)\n\n self.bb_tl = vec2(0 , height + SPACING_VERT)\n self.bb_br = vec2(self.right_tree.bb_br.x, 0)\n else:\n self.root_pos = self.left_tree.root_pos + vec2(0, SPACING_VERT)\n self.bb_tl = self.left_tree.bb_tl + vec2(0, SPACING_VERT)\n self.bb_br = self.left_tree.bb_br + vec2(0, 0) #Making a copy instead of referencing\n\n def transform(self, vec):\n self.root_pos = self.root_pos + vec \n self.bb_tl = self.bb_tl + vec \n self.bb_br = self.bb_br + vec \n if self.left_tree:\n self.left_tree.transform(vec)\n if self.right_tree:\n self.right_tree.transform(vec)\n\n def countNodes(self):\n n1 = 0\n n2 = 0\n if self.left_tree:\n n1 = self.left_tree.countNodes()\n if self.right_tree:\n n2 = self.right_tree.countNodes()\n return n1 + n2 + 1\n\n def countLeaves(self):\n if not self.left_tree and not self.right_tree:\n return 1\n n = 0\n if self.left_tree:\n n += self.left_tree.countLeaves()\n if self.right_tree:\n n += self.right_tree.countLeaves()\n return n\n\n\n def draw(self):\n if self.root_pos:\n s = r\"\\filldraw[{0}] {1} circle ({2}pt);\".format(self.rootcol, str(self.root_pos), NODE_RADIUS)\n print(s)\n else:\n return\n if self.left_tree:\n s = r\"\\draw[{0}] {1} -- {2};\".format(self.rootcol, self.left_tree.root_pos, self.root_pos)\n print(s)\n self.left_tree.draw()\n if self.right_tree:\n s = r\"\\draw[{0}] {1} -- {2};\".format(self.rootcol, self.root_pos, self.right_tree.root_pos)\n print(s)\n self.right_tree.draw()\n\ndef draw_tree(r):\n t = binary_tree(r, ROOT_COLOR, LEFT_COLOR, RIGHT_COLOR)\n t.build()\n t.draw()\n\ndef tree_figure(r, caption = None):\n print(\"%%%Tree \" + str(r) + \" auto-generated%%%\")\n print(r\"\\begin{figure}\\centering\\begin{tikzpicture}\")\n draw_tree(r)\n if not caption:\n if int(r) == 0:\n caption = r\"Tree ${0}$\".format(r)\n else:\n x, y = inverse_gamma_2(r)\n caption = r\"Tree ${0} = \\gamma({1},{2})$\".format(r,x,y)\n print(r\"\\end{tikzpicture}\\caption{\" + caption + r\"}\\end{figure}\")\n\ndef draw_tree_box(r):\n x, y = inverse_gamma_2(r)\n t = binary_tree(r, ROOT_COLOR, LEFT_COLOR, RIGHT_COLOR)\n t.build()\n root_offset = vec2(0.5 * CELL_WIDTH, - 0.1 * CELL_HEIGHT)\n t.transform(root_offset - t.root_pos)\n t.draw()\n text1 = r\"{$\" + str(r) + r\"$}\"\n text2 = r\"{$\" + str(t.countLeaves()) + r\"$}\"\n text3 = r\"{$\\gamma(\" + str(x) + \",\" + str(y) + r\")$}\"\n text4 = r\"{$\" + str(t.countNodes()) + r\"$}\"\n s = r\"\"\"\\draw ({0},{1}) node[rounded corners, outer sep=2pt,draw, align=left, below right]{4} \n -- ({0},{2}) node[align=left, above right, inner sep=0pt, outer sep=2pt]{6} \n -- ({3},{2}) node[align=right, above left, inner sep=0pt, outer sep=4.5pt]{5}\n -- ({3},{1}) node[align=right, below left, inner sep=0pt, outer sep=4.5pt]{7} -- ({0},{1});\"\"\"\n s = s.format(0, 0, -CELL_HEIGHT, CELL_WIDTH, text1, text2, text3, text4)\n print(s)\n\ndef draw_tree_box_legend(r):\n draw_tree_box(r)\n print(r\"\\draw(-0.5, -0.3) node[align=right, left]{tree id} -- (0.2, -0.3);\")\n print(r\"\\draw(-0.5, -1.0) node[align=right, left]{id of left and right subtree} -- (0.8, -1.0) -- (0.8, -1.3);\")\n print(r\"\\draw(0.5, -1.0) -- (0.5, -1.3);\")\n print(r\"\\draw(4.2, -0.3) node[align=left, right]{number of nodes} -- (3.5, -0.3);\")\n print(r\"\\draw(4.2, -1.5) node[align=left, right]{number of leaves} -- (3.5, -1.5);\")\n\ndef draw_table():\n print(r\"\\begin{tikzpicture}\")\n #print(r\"\\draw (0,0) circle (3pt);\")\n for r in range(1,67):\n x, y = inverse_gamma_2(r)\n left = CELL_WIDTH * y\n top = - CELL_HEIGHT * x\n print(r\"\\begin{scope}[shift={(\" + str(left) + \",\" + str(top) + \")}]\")\n draw_tree_box(r)\n print(r\"\\end{scope}\")\n\n print(r\"\\begin{scope}[shift={(\" + str(8 * CELL_WIDTH) + \",\" + str(-2 * CELL_HEIGHT) + \")}]\")\n draw_tree_box_legend(31)\n print(r\"\\end{scope}\")\n print(r\"\\end{tikzpicture}\")\n\ndef pi(digits):\n f = open(\"pi\", \"r\")\n s = f.readline()\n i = int(s[:digits+1])\n return i\n \n\n\nif __name__ == \"__main__\":\n print(TIKZ_DOC_BEGIN)\n #for r in range(0,300):\n # digits = r\n # tree_figure(pi(digits), \"Tree $\\pi\\cdot 10^{\" + str(digits) + \"}$\")\n # print(\"\\clearpage\")\n #for r in range(1,500):\n # sys.stderr.write(\"tree \" + str(r) + \"\\n\")\n # tree_figure(r)\n # if r % 20 == 0:\n # print(\"\\clearpage\")\n #draw_table()\n print(TIKZ_DOC_END)\n pass\n","sub_path":"draw-tree/draw-tree.py","file_name":"draw-tree.py","file_ext":"py","file_size_in_byte":8182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"621249077","text":"from __future__ import print_function\n\nimport os\n\nimport pool\nimport rcExceptions as ex\nfrom rcUtilities import lazy, justcall\nfrom rcGlobalEnv import rcEnv\nfrom converters import convert_size\n\nclass Pool(pool.Pool):\n type = \"shm\"\n capabilities = [\"rox\", \"rwx\", \"roo\", \"rwo\", \"blk\"]\n\n @lazy\n def path(self):\n return \"/dev/shm\"\n\n def translate_blk(self, name=None, size=None, shared=False):\n data = [\n {\n \"rtype\": \"disk\",\n \"type\": \"loop\",\n \"file\": os.path.join(self.path, \"%s.img\" % name),\n \"size\": size,\n }\n ]\n return data\n\n def translate(self, name=None, size=None, fmt=True, shared=False):\n if not fmt:\n return self.translate_blk(name=name, size=size, shared=shared)\n data = []\n path = os.path.join(self.path, name)\n size_opt = \"size=%dm\" % convert_size(size, _to=\"m\")\n if self.mnt_opt:\n mnt_opt = \",\".join((self.mnt_opt, size_opt))\n else:\n mnt_opt = size_opt\n data.append({\n \"rtype\": \"fs\",\n \"type\": \"tmpfs\",\n \"dev\": \"shmfs\",\n \"mnt\": self.mount_point(name),\n \"mnt_opt\": mnt_opt,\n })\n return data\n\n def pool_status(self):\n from converters import convert_size\n if not os.path.exists(self.path):\n os.makedirs(self.path)\n data = {\n \"type\": self.type,\n \"name\": self.name,\n \"capabilities\": self.capabilities,\n }\n cmd = [\"df\", \"-P\", self.path]\n out, err, ret = justcall(cmd)\n if ret != 0:\n return data\n l = out.splitlines()[-1].split()\n data[\"free\"] = int(l[3])\n data[\"used\"] = int(l[2])\n data[\"size\"] = int(l[1])\n data[\"head\"] = self.path\n return data\n\n","sub_path":"lib/poolShm.py","file_name":"poolShm.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"39310186","text":"\"\"\"\nImplementation of the MP3Engine interface using mutagen and pydub\n\"\"\"\n\nfrom typing import Optional\n\nfrom pydub import AudioSegment, playback, utils # type: ignore\n\ntry:\n import pyaudio # type: ignore\n USE_PYAUDIO = True\nexcept ImportError:\n USE_PYAUDIO = False\n\nfrom musicbingo.mp3.editor import MP3Editor, MP3File, MP3FileWriter\nfrom musicbingo.progress import Progress\nfrom musicbingo.song import Song\n\nclass PydubEditor(MP3Editor):\n \"\"\"MP3Editor implementation using pydub\"\"\"\n def _generate(self, destination: MP3FileWriter,\n progress: Progress) -> None:\n \"\"\"generate output file, combining all input files\"\"\"\n output: Optional[AudioSegment] = None\n num_files = float(len(destination._files))\n for index, mp3file in enumerate(destination._files, 1):\n progress.pct = 50.0 * index / num_files\n progress.text = f'Adding {mp3file.filename.name}'\n if progress.abort:\n return\n seg = AudioSegment.from_mp3(str(mp3file.filename))\n if mp3file.start is not None:\n if mp3file.end is not None:\n seg = seg[mp3file.start:mp3file.end]\n else:\n seg = seg[mp3file.start:]\n elif mp3file.end is not None:\n seg = seg[:mp3file.end]\n if mp3file.headroom is not None:\n seg = seg.normalize(mp3file.headroom)\n if output is None:\n output = seg\n else:\n output += seg\n tags = None\n if destination._metadata is not None:\n tags = {\n \"artist\": Song.clean(destination._metadata.artist),\n \"title\": Song.clean(destination._metadata.title)\n }\n if destination._metadata.album:\n tags[\"album\"] = Song.clean(destination._metadata.album)\n assert output is not None\n progress.text = f'Encoding MP3 file \"{destination.filename.name}\"'\n progress.pct = 50.0\n if progress.abort:\n return\n dest_dir = destination.filename.parent\n if not dest_dir.exists():\n dest_dir.mkdir(parents=True)\n output.export(str(destination.filename), format=\"mp3\",\n bitrate=destination.bitrate, tags=tags)\n progress.pct = 100.0\n\n def play(self, mp3file: MP3File, progress: Progress) -> None:\n \"\"\"play the specified mp3 file\"\"\"\n global USE_PYAUDIO # pylint: disable=global-statement\n\n seg = AudioSegment.from_mp3(str(mp3file.filename))\n if mp3file.start is not None:\n if mp3file.end is not None:\n seg = seg[mp3file.start:mp3file.end]\n else:\n seg = seg[mp3file.start:]\n elif mp3file.end is not None:\n seg = seg[:mp3file.end]\n if mp3file.headroom is not None:\n seg = seg.normalize(mp3file.headroom)\n if USE_PYAUDIO:\n self.play_with_pyaudio(seg, progress)\n else:\n # pydub has multiple playback fallbacks, but does not\n # provide an easy way to abort playback\n playback.play(seg)\n\n @staticmethod\n def play_with_pyaudio(seg: AudioSegment, progress: Progress) -> None:\n \"\"\"use pyaudio library to play audio segment\"\"\"\n pya = pyaudio.PyAudio()\n stream = pya.open(format=pya.get_format_from_width(seg.sample_width),\n channels=seg.channels,\n rate=seg.frame_rate,\n output=True)\n\n try:\n chunks = utils.make_chunks(seg, 500)\n scale: float = 1.0\n if chunks:\n scale = 100.0 / float(len(chunks))\n for index, chunk in enumerate(chunks):\n if progress.abort:\n break\n progress.pct = index * scale\n stream.write(chunk._data)\n finally:\n stream.stop_stream()\n stream.close()\n pya.terminate()\n","sub_path":"musicbingo/mp3/pydubeditor.py","file_name":"pydubeditor.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"631657479","text":"import pygame\n\nfrom Colors import Colors\n\n\nclass TilePane(object):\n \n def __init__(self, topleftTuple, sizeTuple, imageFileName=None):\n \n self.rect = pygame.Rect(topleftTuple, sizeTuple)\n if imageFileName is None:\n self.image = pygame.Surface(sizeTuple).convert_alpha()\n self.dirty = False\n\n self.solidity = None\n self.material = None\n \n self.groupId = \"\"\n\n self.images = {\n \"solidity\": None,\n \"material\": None\n }\n \n def getImage(self):\n \n self.image.fill(Colors.AlphaInvisible)\n \n if self.images[\"material\"] is not None:\n self.image.blit(self.images[\"material\"], (0, 0))\n if self.images[\"solidity\"] is not None:\n self.image.blit(self.images[\"solidity\"], (0, 0))\n\n return self.image\n\n def clear(self):\n\n self.material = None\n self.solidity = None\n self.images[\"material\"] = None\n self.images[\"solidity\"] = None\n self.dirty = True\n self.groupId = \"\"\n \n def __eq__(self, otherTile):\n \n solidityMatches = self.solidity == otherTile.solidity\n materialMatches = self.material == otherTile.material\n \n return solidityMatches and materialMatches\n \n def __ne__(self, otherTile):\n \n return not(self.__eq__(otherTile))\n","sub_path":"App/TilePane.py","file_name":"TilePane.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"325096786","text":"import RPi.GPIO as GPIO\nimport time, datetime\nimport os\nimport sys\nimport telepot\nimport telepot.helper\nfrom telepot.loop import MessageLoop\nfrom telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, KeyboardButton\nfrom telepot.delegate import (\n per_chat_id, create_open, pave_event_space, include_callback_query_chat_id)\n\n#t = time.localtime()\n'''\nsetTime1 = '2:12'\nstat1 = 0\nsetTime2 = '2:12'\nstat2 = 0\nsetTime3 = '2:12'\nstat3 = 0\n'''\n\nGPIO.setwarnings(False)\n\n# Inisialisasi Pin\nDIR_MTR1 = 14\nDIR_MTR2 = 15\nSTEP_MTR1 = 12\nSTEP_MTR2 = 13\nDRIVER = 18\nRELAY = 23\n\n# Perintah untuk menggunakan pin board GPIO Raspberry Pi\nGPIO.setmode(GPIO.BCM)\n\n# Pengaturan GPIO \nGPIO.setup(DIR_MTR1, GPIO.OUT)\nGPIO.setup(DIR_MTR2, GPIO.OUT)\nGPIO.setup(STEP_MTR1, GPIO.OUT)\nGPIO.setup(STEP_MTR2, GPIO.OUT)\nGPIO.setup(DRIVER, GPIO.OUT)\nGPIO.setup(RELAY, GPIO.OUT)\n\nGPIO.output(RELAY, 1) #Off initially\n\npropose_records = telepot.helper.SafeDict() # thread-safe dict\n\n#SetTelegram\nTOKEN = '1202817061:AAHLFAFoftMnaOenIt59XG_IzGIp8a7yM2M'\nCHATID = 1137202289\n\n#set schedul/jadwal pencitraan\nschedule = 0\n\njadwal_1 = 0\njadwal_2 = 0\njadwal_3 = 0\ntakar_1 = 0\ntakar_2 = 0\ntakar_3 = 0\nstatus_1 = False\nstatus_2 = False\nstatus_3 = False\n\nclass Lover(telepot.helper.ChatHandler):\n keyboard = ReplyKeyboardMarkup(keyboard=[[ #<-- Menu awal\n KeyboardButton(text='Beri Pakan'),\n KeyboardButton(text='Pengaturan')], [\n KeyboardButton(text='UMmm ...'),\n KeyboardButton(text='Keluar')\n ]], one_time_keyboard=True)\n keyboard1 = ReplyKeyboardMarkup(keyboard=[[ #<-- Terusan Pengaturan dari Menu Awal\n KeyboardButton(text='Set Penjadwalan Pemberian Pakan')], [\n KeyboardButton(text='Set Dosis Pemberian Pakan')\n ]], one_time_keyboard=True)\n keyboard2 = ReplyKeyboardMarkup(keyboard=[[ #-- Terusan Pengaturan-Takaran dari Menu Awal\n KeyboardButton(text='Jadwal Kolam 1'),\n KeyboardButton(text='Jadwal Kolam 2')], [\n KeyboardButton(text='Jadwal Kolam 3'),\n KeyboardButton(text='Jadwal Semua Kolam')], [\n KeyboardButton(text='Kembali')\n ]], one_time_keyboard=True)\n keyboard3 = ReplyKeyboardMarkup(keyboard=[[ #<-- Terusan Pengaturan-Waktu dari Menu Awal\n KeyboardButton(text='Dosis Kolam 1'),\n KeyboardButton(text='Dosis Kolam 2')], [\n KeyboardButton(text='Dosis Kolam 3'),\n KeyboardButton(text='Dosis Semua Kolam')], [\n KeyboardButton(text='Kembali')\n ]], one_time_keyboard=True)\n keyboard4 = InlineKeyboardMarkup(inline_keyboard=[[ #-- Terusan Pengaturan-Takaran dari Menu Awal\n InlineKeyboardButton(text='00:00', callback_data='0'),\n InlineKeyboardButton(text='01:00', callback_data='1'), \n InlineKeyboardButton(text='02:00', callback_data='2'),\n InlineKeyboardButton(text='03:00', callback_data='3')],[\n InlineKeyboardButton(text='04:00', callback_data='4'),\n InlineKeyboardButton(text='05:00', callback_data='5'), \n InlineKeyboardButton(text='06:00', callback_data='6'),\n InlineKeyboardButton(text='07:00', callback_data='7')],[\n InlineKeyboardButton(text='08:00', callback_data='8'),\n InlineKeyboardButton(text='09:00', callback_data='9'), \n InlineKeyboardButton(text='10:00', callback_data='10'),\n InlineKeyboardButton(text='11:00', callback_data='11')],[\n InlineKeyboardButton(text='12:00', callback_data='12'),\n InlineKeyboardButton(text='13:00', callback_data='13'), \n InlineKeyboardButton(text='14:00', callback_data='14'),\n InlineKeyboardButton(text='15:00', callback_data='15')],[\n InlineKeyboardButton(text='16:00', callback_data='16'),\n InlineKeyboardButton(text='17:00', callback_data='17'), \n InlineKeyboardButton(text='18:00', callback_data='18'),\n InlineKeyboardButton(text='19:00', callback_data='19')],[\n InlineKeyboardButton(text='20:00', callback_data='20'),\n InlineKeyboardButton(text='21:00', callback_data='21'), \n InlineKeyboardButton(text='22:00', callback_data='22'),\n InlineKeyboardButton(text='23:00', callback_data='23')],[\n InlineKeyboardButton(text='Kembali', callback_data='kembali')\n ]], resize_keyboard=True, one_time_keyboard=True)\n keyboard5 = ReplyKeyboardMarkup(keyboard=[[ \n KeyboardButton(text='Pakan Kolam 1'),\n KeyboardButton(text='Pakan Kolam 2')], [\n KeyboardButton(text='Pakan Kolam 3'),\n KeyboardButton(text='Pakan Semua Kolam')], [\n KeyboardButton(text='Kembali')\n ]], one_time_keyboard=True)\n\n def __init__(self, *args, **kwargs):\n super(Lover, self).__init__(*args, **kwargs)\n\n # Retrieve from database\n global propose_records\n if self.id in propose_records:\n self._edit_msg_ident = propose_records[self.id]\n self._editor = telepot.helper.Editor(self.bot, self._edit_msg_ident) if self._edit_msg_ident else None\n else:\n self._edit_msg_ident = None\n self._editor = None\n\n def _propose(self):\n sent = self.sender.sendMessage('Apa yang perlu saya lakukan ?', reply_markup=self.keyboard)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n \n \"\"\"\n def _propose_time(self):\n current_time = time.strftime(\"%H:%M\", t)\n (h, m) = current_time.split(':')\n result = int(h) * 3600 + int(m) * 60\n \n (h, m) = setTime1.split(':')\n timeklm1 = int(h) * 3600 + int(m) * 60\n \n (h, m) = setTime2.split(':')\n timeklm2 = int(h) * 3600 + int(m) * 60\n \n (h, m) = setTime3.split(':')\n timeklm3 = int(h) * 3600 + int(m) * 60\n \"\"\"\n\n def _cancel_last(self):\n if self._editor:\n self._editor.editMessageReplyMarkup(reply_markup=None)\n self._editor = None\n self._edit_msg_ident = None\n\n def on_chat_message(self, msg):\n global jadwal_1\n global jadwal_2\n global jadwal_3\n global takar_1\n global takar_2\n global takar_3\n global status_1\n global status_2\n global status_3\n\n chat_id = msg['chat']['id']\n if msg['from']['id'] != CHATID:\n bot.sendMessage(chat_id, \"Maaf ini adalah bot pribadi. Akses ditolak!\")\n self.close()\n \n command = msg['text']\n if (command == 'Keluar'):\n sent = self.sender.sendMessage(\"Terima kasih! \\nBye..\")\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n self.close()\n #== bagian pengaturan ==\n elif (command == 'Pengaturan'):\n sent = self.sender.sendMessage('Apa yang ingin Anda atur?', reply_markup=self.keyboard1)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n elif (command == 'Set Penjadwalan Pemberian Pakan'):\n sent = self.sender.sendMessage('Kolam mana yang ingi Anda atur Penjadwalan Pakannya ?', parse_mode='html', reply_markup=self.keyboard2)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n elif (command == 'Set Dosis Pemberian Pakan'):\n sent = self.sender.sendMessage('Kolam mana yang ingi Anda atur Dosis Pakannya ?', parse_mode='html', reply_markup=self.keyboard3)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n elif (command == 'Jadwal Kolam 1'):\n status_1 = True\n status_2 = False\n status_3 = False\n sent = self.sender.sendMessage('Silahkan pilih waktu penjadwalan pakan..', reply_markup=self.keyboard4 )\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n elif (command == 'Jadwal Kolam 2'):\n status_1 = False\n status_2 = True\n status_3 = False\n sent = self.sender.sendMessage('Silahkan pilih waktu penjadwalan pakan..', reply_markup=self.keyboard4 )\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n elif (command == 'Jadwal Kolam 3'):\n status_1 = False\n status_2 = False\n status_3 = True\n sent = self.sender.sendMessage('Silahkan pilih waktu penjadwalan pakan..', reply_markup=self.keyboard4 )\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n elif (command == 'Jadwal Semua Kolam'):\n status_1 = True\n status_2 = True\n status_3 = True\n sent = self.sender.sendMessage('Silahkan pilih waktu penjadwalan pakan..', reply_markup=self.keyboard4 )\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n #== end pengaturan ==\n else :\n self._propose()\n \n #self._cancel_last() \n\n def on_callback_query(self, msg):\n global jadwal_1\n global jadwal_2\n global jadwal_3\n global takar_1\n global takar_2\n global takar_3\n global status_1\n global status_2\n global status_3\n \n query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')\n \n # == Setting Penjadwalan == \n if query_data == '1':\n self.bot.answerCallbackQuery(query_id, text='Ok. Penjadwalan tersimpan..')\n self._cancel_last()\n text = 'Penjadwalan pemberian Pakan pada kolam '\n if (status_1):\n text += '1, '\n jadwal_1 = 1\n status_1 = False\n if (status_2):\n text += '2, '\n jadwal_2 = 1\n status_2 = False\n if (status_3):\n text += '3, '\n jadwal_3 = 1\n status_3 = False\n text += 'telah diset ke jam 01:00'\n sent = self.sender.sendMessage(text)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n self.close()\n \n elif query_data == 'dosis':\n self.bot.answerCallbackQuery(query_id, text='Ok. Pertanyaan berikutnya...')\n self._cancel_last()\n sent = self.sender.sendMessage('Kolam mana yang ingin anda atur dosis pakannya?', reply_markup=self.keyboard4)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n \n # ==pemberian pakan== \n elif query_data == 'pakan':\n self.bot.answerCallbackQuery(query_id, text='Ok. Pertanyaan berikutnya...')\n self._cancel_last()\n sent = self.sender.sendMessage('Kolam mana yang ingin anda beri pakan?', reply_markup=self.keyboard2)\n self._editor = telepot.helper.Editor(self.bot, sent)\n self._edit_msg_ident = telepot.message_identifier(sent)\n \n elif query_data == 'pknk1':\n if setTime1 == 'null' :\n self.bot.answerCallbackQuery(query_id, text='Ok. Pemberian pakan pada kolam 1 akan dilakukan...')\n self._cancel_last()\n #!! kasi pakan, kamera jalan,\n stat1 = 1\n self.sender.sendMessage('Pemberian pakan pada kolam 1 telah selesai \\nketikkan perintah /dokumentasi untuk mendapat rekaman video..')\n self.close()\n else :\n if stat1 == 0 :\n self.bot.answerCallbackQuery(query_id, text='Peringatan !!!')\n self._cancel_last()\n self.sender.sendMessage('Pemberian pakan pada kolam 1 Telah dijadwlkan pada pukul' + setTime1 + '\\nketikkan perintah /force1 untuk memberikan pakan sekarang juga..')\n self.close()\n \n else:\n self.bot.answerCallbackQuery(query_id, text='Ok. Tapi aku akan terus bertanya.')\n self._cancel_last()\n self._propose()\n \n def on__idle(self, event):\n global status_1\n global status_2\n global status_3\n if status_1 or status_2 or status_3 :\n self.sender.sendMessage('Saya tahu Anda mungkin perlu sedikit waktu. Aku akan selalu di sini untukmu.')\n self._cancel_last()\n self.close()\n \n def on_close(self, ex):\n # Save to database\n global propose_records\n propose_records[self.id] = (self._edit_msg_ident)\n\n\nbot = telepot.DelegatorBot(TOKEN, [\n include_callback_query_chat_id(\n pave_event_space())(\n per_chat_id(types=['private']), create_open, Lover, timeout=30),\n])\nMessageLoop(bot).run_as_thread()\nprint('Listening ...')\n\n#while 1: <--sama dengan true\nwhile True:\n now = datetime.datetime.now()\n print(now.hour,\":\",now.minute)\n print(jadwal_1,\":\",jadwal_2,\":\",jadwal_3,\":\",takar_1,\":\",takar_2,\":\",takar_3)\n if (now.hour == schedule):\n schedule = schedule + 1\n if (schedule == 24):\n schedule = 0\n from colorDetection import deteksi\n if (deteksi):\n print(\"terdeteksi\")\n #bot.sendMessage(CHATID, 'PERINGATAN !! SISTEM MENDETEKSI TERDAPAT IKAN MATI PADA KOLAM, SEGERA PERIKSA KONDISI KOLAM ANDA')\n bot.sendPhoto(CHATID, open('citra.jpg', 'rb'), caption = 'PERINGATAN !! SISTEM MENDETEKSI TERDAPAT IKAN MATI PADA KOLAM, SEGERA PERIKSA KONDISI KOLAM ANDA')\n else :\n print(\"tidak Terdeteksi\")\n time.sleep(60)\n","sub_path":"aFiFa5.py","file_name":"aFiFa5.py","file_ext":"py","file_size_in_byte":14600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"446201888","text":"# Facility Load Flexibilty Calculations for Ice Storage\n# by Karl Heine, Mines, 9/2019\n\n# Description: This python script loads an eso and performs calculations at each timestep for the potential of the\n# facility to reduce its max kW and total kWh over specified \"future\" time horizons. The results are then reported\n# in .csv/.txt output and plotted as .html interactive graphics.\n\n# Online Reference for Plotly: https://plot.ly/python/line-and-scatter/\n\nimport os\nimport sys\nimport calendar\nimport esoreader\nimport pandas as pd\nimport numpy as np\nimport plotly\nimport plotly.graph_objs as go\nfrom plotly import subplots\n\n# External Functions\nfrom performance import ice_performance\n\n# Program Control\nexp = False\t\t#Export Results\nf1 = False\t\t#Plot Results for Flex\nadd = True\t\t#Perform Load Add Calcs\n\n#-----------------------------------------------------------------------------------------------------------------------\n## Model and Analysis Parameter Definitions\n\n# Define Filepath\nfilepath = os.getcwd() + '/esos/'\n\n# Define Model Parameters\nfilename = 'SS47L15.eso'\t#Secondary School, CZ 2A, ice meets up to 30% of design load, chiller downsize applied\nice_cap = 2000\t\t\t\t\t#ton-hours\nchiller_cap = 347\t\t\t\t#tons\nchiller_COP = 2.80\t\t\t\t#nominal chiller COP\nmin_cap = 0.15 * chiller_cap\t#min PLR * nominal chiller capacity\ndescriptor = 'Secondary School in CZ 2A'\n\n# Load File\nprint('Loading File: ' + filename)\ndd, data = esoreader.read(filepath + filename)\n\n# Define Chiller/Ice Tank Names for ESO Data Directory Inspection\nice_name = 'THERMAL STORAGE ICE DETAILED 1'\nchill_name = '90.1-2010 AIRCOOLED WITHCONDENSER CHILLER 0 456TONS 1.3KW/TON'\n\n# Define Run Period\nrun_start = pd.datetime(2006,1,1,0)\t\t\t\t#Hour 0 on Jan 1\nrun_end = pd.datetime(2006,12,31,23,59)\t\t\t#Hour 23:59 on Dec 31\nts_per_hr = 4\t\t\t\t\t\t\t\t\t#15 minute simulation timestep !!!! Adjust date_range objects too!\nx_ts = pd.date_range(start = run_start, end = run_end, freq = '15min')\t\t#Vector of timestamps for simulation run pd\n\n# Define Analysis Peirod\nan_start = pd.datetime(2006,1,1,0)\t\t\t\t#Analysis Start Hour\nan_end = pd.datetime(2006,12,31,17)\t\t\t#Analysis Finish Hour\nan_pd = []\t\t\t\t\t\t\t\t\t\t#Index range of analysis period - empty\nidx = 0\nfor x in x_ts:\n\tif x == an_start:\n\t\tan_pd.append(idx)\n\tif x == an_end:\n\t\tan_pd.append(idx)\n\tidx += 1\n\nx_an = pd.date_range(start = x_ts[an_pd[0]], end = x_ts[an_pd[1]], freq = '15min')\t#Timestamp vector - for plotting\nprint(x_an[0])\n\n# Define Occupied Hours and Days\nocc_flag = 0\nocc_hrs = [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\t\t#Occupied from 08:00 through 20:00 (Pandas Hours Range from 0-23)\nocc_days = [0, 1, 2, 3, 4]\t\t#Excludes Sat and Sun\n\n# Define Flex Windows - number of future hours over which flexibilty is required\nwindow = [0.5, 1, 2, 3, 4, 5, 6]\n\n# Define Variables and Arrays for Load Shed Calcs\nkw_tr = [[None for i in range(len(x_an))] for j in range(len(window))]\nkw_future_tr = [[None for i in range(len(x_an))] for j in range(len(window))]\nkwh_tr = [[None for i in range(len(x_an))] for j in range(len(window))]\npost_flex_soc_tr = [[None for i in range(len(x_an))] for j in range(len(window))]\nno_flex_soc_tr = [[None for i in range(len(x_an))] for j in range(len(window))]\nocc_counter = 0\nno_rate_counter = [0 for j in range(len(window))]\nno_soc_counter =[0 for j in range(len(window))]\ntotal_counter = [0 for j in range(len(window))]\nflex_counter = [0 for j in range(len(window))]\nflex_future_counter = [0 for j in range(len(window))]\nocc_flex_counter = [0 for j in range(len(window))]\navg_flex = [0 for j in range(len(window))]\navg_flex_future = [0 for j in range(len(window))]\navg_occ_flex = [0 for j in range(len(window))]\navg_kwh_flex = [0 for j in range(len(window))]\n\n#Define Variables and Arrays for Load Add Clacs\nadd = [[None for i in range(len(x_an))] for j in range(len(window))]\nadd_occ = [[None for i in range(len(x_an))] for j in range(len(window))]\nadd_counter = [0 for j in range(len(window))]\nadd_occ_counter = [0 for j in range(len(window))]\navg_add = [0 for j in range(len(window))]\navg_add_occ = [0 for j in range(len(window))]\n\n#-----------------------------------------------------------------------------------------------------------------------\n## Load Required Variables\n\n#facility electric energy [J -> kW]\nkey = dd.index['TimeStep', None, 'Electricity:Facility']\npwr_facil = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#HVAC electric energy [J -> kWh]\nkey = dd.index['TimeStep', None, 'Electricity:HVAC']\npwr_hvac = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#cooling electric energy [J -> kW]\nkey = dd.index['TimeStep', None, 'Cooling:Electricity']\npwr_cool = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#pump electric energy [J -> kW]\nkey = dd.index['TimeStep', None, 'Pumps:Electricity']\npwr_pump = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#fan electric energy [J -> kW]\nkey = dd.index['TimeStep', None, 'Fans:Electricity']\npwr_fan = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#chiller electric energy [J -> kW] - incl condenser unit\nkey = dd.index['TimeStep', chill_name, 'Chiller Electric Energy']\npwr_chill = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#plant total electric energy [J -> kW] - all Plants!\nkey = dd.index['TimeStep', None, 'Electricity:Plant']\npwr_plant = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#ice tank ancillary electric energy [J -> kW]\nkey = dd.index['TimeStep', ice_name, 'Ice Thermal Storage Ancillary Electric Energy']\npwr_ice = [j * 2.77778e-7 * ts_per_hr for j in data[key]]\n\n#chiller cooling rate [W -> tons]\nkey = dd.index['TimeStep', chill_name, 'Chiller Evaporator Cooling Rate']\nrate_chill = [w * 0.0002843451 for w in data[key]]\n\n#ice tank cooling rate [W -> tons]\nkey = dd.index['TimeStep', ice_name, 'Ice Thermal Storage Cooling Discharge Rate']\nrate_dchg = [w * 0.0002843451 for w in data[key]]\n\n#ice tank charging rate [W -> tons]\nkey = dd.index['TimeStep', ice_name, 'Ice Thermal Storage Cooling Charge Rate']\nrate_chg = [w * 0.0002843451 for w in data[key]]\n\n#ice state of charge [-]\nkey = dd.index['TimeStep', ice_name, 'Ice Thermal Storage End Fraction']\nsoc = data[key]\n\n#drybulb temperature [C]\nkey = dd.index['TimeStep', 'Environment', 'Site Outdoor Air Drybulb Temperature']\ntdb = data[key]\n\n#wetbulb temperature [C]\nkey = dd.index['TimeStep', 'Environment', 'Site Outdoor Air Wetbulb Temperature']\ntwb = data[key]\n\n#return water temperature [C]\nkey = dd.index['TimeStep', 'CHILLED WATER LOOP SUPPLY INLET NODE', 'System Node Temperature']\nreturn_temp = data[key]\n\n#supply water temperature [C]\nkey = dd.index['TimeStep', 'CHILLED WATER LOOP SETPOINT SCHEDULE (NEW)', 'Schedule Value']\nsupply_temp = data[key]\n\n#facility electric power w/o chiller [kW]\npwr_facil_wo_chill = [pwr_facil[i] - pwr_chill[i] for i in range(len(pwr_facil))]\n\n#total cooling rate - chiller and ice [tons]\nrate_cool = [0] * len(rate_chill)\nfor i in range(len(rate_chill)):\n\tif rate_chg[i] == 0:\n\t\trate_cool[i] = rate_chill[i] + rate_dchg[i]\n\telse:\n\t\trate_cool[i] = rate_chill[i] - rate_chg[i]\n\nprint(' Data Successfully Loaded.\\n')\n\n#-----------------------------------------------------------------------------------------------------------------------\n## Calculations\nprint('Performing Calculations')\n\n# Iterate Over Every Timestep in Analysis Period\nfor t in range(an_pd[0], an_pd[1]):\n\n\t# Determine if t is in occupied hour\n\tif x_ts[t].dayofweek in occ_days and x_ts[t].hour in occ_hrs:\n\t\tocc_flag = 1\n\t\tocc_counter += 1\n\telse:\n\t\tocc_flag = 0\n\n\t# Iterate Analysis over Every Flex Window\n\tfor w in window:\n\n\t\te_flag = 0\t\t\t# Sufficient energy in ice tank flag\n\t\tp_flag = 0\t\t\t# Sufficient discharge capacity (power) flag\n\t\tflag = [0, 0, 0]\t# Charge/discharge indicator flag (start, peak, end)\n\n\t\t# Determine Number of Timesteps in Analysis Period\n\t\tsteps = int(w * ts_per_hr)\n\n\t\t# Integrate and Find Max Cooling and Electric Loads\n\t\tc = 0\n\t\tload_cool_to_pk = 0\n\t\te = 0\n\t\te_no_chill = 0\n\t\tload_e_no_chill = 0\n\t\tload_cool = 0\t\t# Total cooling energy required over analysis period [ton-hours]\n\t\tpk_cool = 0\t\t\t# Peak cooling rate required over analysis period [tons]\n\t\tpk_c_ts = 0\t\t\t# Timestep index of peak cooling rate [-]\n\t\tload_elec = 0\t\t# Total facility energy required over analysis period [kWh]\n\t\tpk_elec = 0\t\t\t# Peak facility power required over analysis period [kW]\n\t\tpk_e_ts = 0\t\t\t# Timestep index of peak facility power [-]\n\n\t\t#(Chiller Cooling Rate + Ice Cooling Rate) * ts [ton-hours]\n\t\tc = rate_cool[t:t+steps]\t\t\t\t\t\t# Subsection of total cooling load (provided) profile [tons]\n\t\tload_cool = sum(c) / ts_per_hr\t\t\t\t\t# Convert tons into ton-hours of cooling\n\t\tpk_cool = max(c)\t\t\t\t\t\t\t\t# Max tons of cooling in analysis period\n\t\tpk_c_ts = t + c.index(pk_cool) + 1\t\t\t\t# Timestep of max cooling\n\t\tload_cool_to_pk = sum(rate_cool[t:pk_c_ts])\t\t# Cooling load up to peak cooling timestep\n\n\t\t#Facility Power * ts [kWh]\n\t\te = pwr_facil[t:t+steps]\t\t\t\t\t\t# Subsection of facility power curve [kW]\n\t\te_no_chill = pwr_facil_wo_chill[t:t+steps]\t\t# Subsection of facility power w/o chiller curve [kW]\n\t\tload_elec = sum(e) / ts_per_hr\t\t\t\t\t# Convert kW into kWh values using timesteps/hour\n\t\tload_e_no_chill = sum(e_no_chill) / ts_per_hr\t# Convert kW into kWh values\n\t\tpk_elec = max(e)\t\t\t\t\t\t\t\t# Max kW for facility in analysis period\n\t\tpk_e_ts = t + e.index(pk_elec) + 1\t\t\t\t# Timestep of max kW\n\n\t\t# Check Cooling Energy Capacity Remaining\n\t\tavail_cap = ice_cap * soc[t]\n\t\tif avail_cap > load_cool:\n\t\t\tsoc_at_end = (avail_cap - load_cool) / ice_cap\n\t\t\te_flag = 1\n\t\telse:\n\t\t\tno_soc_counter[window.index(w)] += 1\n\n\t\t# Set Charge/Discharge Flag\n\t\tidx = 0\n\t\tfor i in [t, pk_c_ts, t+steps]:\n\t\t\tif rate_chg[i] > 0:\n\t\t\t\tflag[idx] = 1\n\t\t\telif rate_dchg[i] > 0:\n\t\t\t\tflag[idx] = 0\n\t\t\telse:\n\t\t\t\tflag[idx] = -1\n\n\t\t# Check Cooling Rate Ice Can Provide\n\t\tsoc_at_peak = (avail_cap - load_cool_to_pk) / ice_cap\n\t\tmax_dchg = [0, 0, 0]\t\t# @ start, peak, and end\n\t\tmax_dchg[0] = ice_performance(soc[t], return_temp[t], supply_temp[t], ice_cap, 0)\n\t\tmax_dchg[1] = ice_performance(soc_at_peak, return_temp[pk_c_ts], supply_temp[pk_c_ts], ice_cap, 0)\n\t\tmax_dchg[2] = ice_performance(soc_at_end, return_temp[t+steps], supply_temp[t+steps], ice_cap, 0)\n\n\t\t# If cooling rates can meet start, max, and average, then there is no cooling rate restriction on the DR shed\n\t\t# All units in tons\n\t\tif (max_dchg[0] + max_dchg[2]) / 2 * w >= load_cool \\\n\t\tand max_dchg[1] > pk_cool and max_dchg[2] > c[-1]:\n\t\t\tp_flag = 1\n\t\telse:\n\t\t\tno_rate_counter[window.index(w)] += 1\n\n\t\t# If ice can meet both energy and rate requirements, remove chiller power from load to calculate flex potential\n\t\tif e_flag and p_flag:\n\n\t\t\t#Total flex possible counter\n\t\t\ttotal_counter[window.index(w)] += 1\n\n\t\t\t# Calculate the projected kWh shaved over analysis window\n\t\t\tkwh_flex = load_elec - load_e_no_chill\n\n\t\t\t# Calc kW reduction relative to current timestep and to analysis window\n\t\t\tnew_max_kw = max(pwr_facil_wo_chill[t:t+steps])\n\t\t\tkw_flex = pwr_facil[t] - new_max_kw\n\t\t\tkw_flex_future = pk_elec - new_max_kw\n\n\t\t\t# Do not include periods when no kW reduction is provided (relative to pk_elec)\n\t\t\tif kw_flex_future <= 0:\n\t\t\t\tkw_flex_future = 0\n\t\t\telse:\n\t\t\t\tflex_future_counter[window.index(w)] += 1\n\t\t\t\tavg_flex_future[window.index(w)] += kw_flex_future\n\n\t\t\t\t# Calculate shed flex during occupied hours only\n\t\t\t\tif occ_flag == 1:\n\t\t\t\t\tocc_flex_counter[window.index(w)] += 1\n\t\t\t\t\tavg_occ_flex[window.index(w)] += kw_flex_future\n\t\t\t\t\tavg_kwh_flex[window.index(w)] += kwh_flex\n\n\t\t\t# Calculate flexibility relative to current timestep power as well\n\t\t\tif kw_flex <= 0:\n\t\t\t\tkw_flex = 0\n\t\t\telse:\n\t\t\t\tflex_counter[window.index(w)] += 1\n\t\t\t\tavg_flex[window.index(w)] += kw_flex\n\n\t\telse:\t# No flexiblity assumed if ITS cannot meet rate or energy requirements\n\t\t\tkw_flex = 0\n\t\t\tkw_flex_future = 0\n\t\t\tkwh_flex = 0\n\n\t\t# Update trace variables for shed plots\n\t\tkw_tr[window.index(w)][(t-an_pd[0])] = -kw_flex\n\t\tkw_future_tr[window.index(w)][(t-an_pd[0])] = kw_flex_future\n\t\tkwh_tr[window.index(w)][(t-an_pd[0])] = kwh_flex\n\t\tpost_flex_soc_tr[window.index(w)][(t-an_pd[0])] = soc_at_end\n\t\tno_flex_soc_tr[window.index(w)][(t-an_pd[0])] = soc[t+steps]\n\n\t\tif add:\n\t\t\t# Average cooling required over analysis period\n\t\t\tc_bar = sum(c) / steps\t\t\t# average tons\n\n\t\t\t# Average cooling provided by chiller over analysis period (excluding charging!)\n\t\t\tc_chill = []\n\t\t\tfor z in range(t,t+steps):\n\t\t\t\tc_chill.append(rate_chill[z] - rate_chg[z])\n\t\t\tc_bar_chill = sum(c_chill) / steps\t\t# average tons\n\n\t\t\t# If chiller capacity is nominally sufficient, add load based on nominal COP (convert tons to kW)\n\t\t\tif c > c_chill:\n\t\t\t\tadd_counter[window.index(w)] += 1\n\t\t\t\tif c_bar_chill <= chiller_cap:\n\t\t\t\t\tadd[window.index(w)][(t-an_pd[0])] = (c_bar - c_bar_chill) / 0.2843451 / chiller_COP\n\t\t\t\telif c_bar_chill > chiller_cap:\n\t\t\t\t\tadd[window.index(w)][(t-an_pd[0])] = (chiller_cap - c_bar_chill) / 0.2843451 / chiller_COP\n\n\t\t\t\tif occ_flag:\n\t\t\t\t\tadd_occ_counter[window.index(w)] += 1\n\t\t\t\t\tif c_bar_chill <= chiller_cap:\n\t\t\t\t\t\tadd_occ[window.index(w)][(t-an_pd[0])] = (c_bar - c_bar_chill) / 0.2843451 / chiller_COP\n\t\t\t\t\telif c_bar_chill > chiller_cap:\n\t\t\t\t\t\tadd_occ[window.index(w)][(t-an_pd[0])] = (chiller_cap - c_bar_chill) / 0.2843451 / chiller_COP\n\t\t\t\telse:\n\t\t\t\t\tadd_occ[window.index(w)][(t-an_pd[0])] = 0\n\n\t\t\t\t# Calc the average add terms\n\t\t\t\tavg_add[window.index(w)] += add[window.index(w)][(t-an_pd[0])]\n\t\t\t\tavg_add_occ[window.index(w)] += add_occ[window.index(w)][(t-an_pd[0])]\n\n\t\t\telif c <= c_chill:\n\t\t\t\tadd[window.index(w)][(t-an_pd[0])] = 0\n\n# Calculate the Average Flexibility Provided by ITS\nfor i in range(len(window)):\n\tif flex_counter[i] != 0:\n\t\tavg_flex[i] = avg_flex[i] / flex_counter[i]\n\t\tavg_flex_future[i] = avg_flex_future[i] / flex_future_counter[i]\n\t\tavg_kwh_flex[i] = avg_kwh_flex[i] / occ_flex_counter[i]\n\n\tif occ_flex_counter[i] != 0:\n\t\tavg_occ_flex[i] = avg_occ_flex[i] / occ_flex_counter[i]\n\n\tif add_counter[i] != 0:\n\t\tavg_add[i] = avg_add[i] / add_counter[i]\n\n\tif add_occ_counter[i] != 0:\n\t\tavg_add_occ[i] = avg_add_occ[i] / add_occ_counter[i]\n\n\n# Print Desired Outputs\nprint('Flex Counter:', [(i / ts_per_hr) for i in flex_counter])\nprint('Average Flex:', avg_flex)\nprint('Average Flex (Future):', avg_flex_future)\nprint('Total Hours:', len(x_an) / 4)\nprint('Occupied Flex Counter:', [(i / ts_per_hr) for i in occ_flex_counter])\nprint('Average Occupied Flex:', avg_occ_flex)\nprint('Occupied Hours:', occ_counter / 4)\nprint('Total Yes Flex Count:', [(i / ts_per_hr) for i in total_counter])\nprint('No Rate Count:', [(i / ts_per_hr) for i in no_rate_counter])\nprint('No SOC Count:', [(i / ts_per_hr) for i in no_soc_counter])\nprint('Average kWh Flex:', avg_kwh_flex)\nprint('Average Add kW:', avg_add)\nprint('Average Occ Add kW:', avg_add_occ)\nprint('Add Hours:', add_counter)\nprint('Add Occupied Hours:', add_occ_counter)\n\n\nprint(' Calculations Complete.\\n')\n\n#-----------------------------------------------------------------------------------------------------------------------\n## Create Figures\nprint('Creating Figures')\n\nstandard_template = go.layout.Template(\n\tlayout = go.Layout(\n\t\theight = 650, width = 1400,\n\t\ttitle_font = dict(family = 'Rockwell', size = 28),\n\t\txaxis = dict(\n\t\t\ttitle_font = dict(family = 'Rockwell', size = 24),\n\t\t\ttickfont = dict(family = 'Rockwell', size = 20),\n\t\t\tshowgrid = True,\n\t\t\tgridcolor = 'rgb(203,203,203)'\n\t\t\t),\n\t\tyaxis = dict(\n\t\t\ttitle_font = dict(family = 'Rockwell', size = 24),\n\t\t\ttickfont = dict(family = 'Rockwell', size = 20),\n\t\t\tshowgrid = True,\n\t\t\tgridcolor = 'rgb(203,203,203)'\n\t\t\t),\n\t\tpaper_bgcolor = 'rgba(0,0,0,0)', plot_bgcolor = 'rgba(0,0,0,0)',\n\t\t#legend = dict(x = 0.5, y = 1.1, font = dict(family = 'Rockwell', size = 18)),\n\t\thovermode = 'closest'\n\t)\n)\n\nkw_trace = []\nfor i in range(len(kw_tr)):\n\tkw_trace.append(go.Scatter(x = x_an, y = kw_tr[i], name = f'{window[i]} Hr kW Flex', legendgroup = i))\n\nkw_future_trace = []\nfor i in range(len(kw_future_tr)):\n kw_future_trace.append(go.Scatter(x = x_an, y = kw_future_tr[i],\n\t\t\t\t\t\t\t\t\tname = f'{window[i]} Hr kW Flex (Future)', legendgroup = i))\n\nkwh_trace = []\nfor i in range(len(kwh_tr)):\n\tkwh_trace.append(go.Scatter(x = x_an, y = kwh_tr[i], name = f'{window[i]} Hr kWh Flex', legendgroup = i))\n\nno_flex_soc_trace = []\nfor i in range(len(no_flex_soc_tr)):\n\tno_flex_soc_trace.append(go.Scatter(x = x_an, y = no_flex_soc_tr[i], name = f'{window[i]} Hr SOC No Flex',\n\t\t\t\t\t\t\t\t\t\tlegendgroup = i))\n\npost_flex_soc_trace = []\nfor i in range(len(post_flex_soc_tr)):\n\tpost_flex_soc_trace.append(go.Scatter(x = x_an, y = post_flex_soc_tr[i], name = f'{window[i]} Hr SOC Post Flex',\n\t\t\t\t\t\t\t\t\t\tlegendgroup = i))\n\nadd_trace = []\nfor i in range(len(add)):\n\tadd_trace.append(go.Scatter(x = x_an, y = add[i], name = f'{window[i]} Hr Add',\n\t\t\t\t\t\t\t\t\t\tlegendgroup = i))\n\npwr_trace = go.Scatter(x = x_an, y = pwr_facil[an_pd[0]:an_pd[1]], name = 'Facil Pwr [kW]')\n\nchill_trace = go.Scatter(x = x_an, y = pwr_chill[an_pd[0]:an_pd[1]], name = 'Chiller Pwr [kW]')\n\n# Fig 1\nif f1:\n\tfig = subplots.make_subplots(rows = 5, cols = 1, shared_xaxes = True,\n\t \t\tsubplot_titles = ('Facility Electric Load [kW]','kW Flex (Current)',\n\t\t\t\t\t\t\t\t \t\t\t\t'kW Flex (Future)', 'kWh Flex', 'Post SOC'))\n\n\tfig.append_trace(pwr_trace,1,1)\n\tfig.append_trace(chill_trace,1,1)\n\n\tfor i in range(len(kw_trace)):\n\t\tfig.append_trace(kw_trace[i],2,1)\n\n\tfor i in range(len(kw_future_trace)):\n\t\tfig.append_trace(kw_future_trace[i],3,1)\n\n\tfor i in range(len(kwh_trace)):\n\t\tfig.append_trace(kwh_trace[i],4,1)\n\n\tfor i in range(len(no_flex_soc_trace)):\n\t\tfig.append_trace(no_flex_soc_trace[i],5,1)\n\n\tfor i in range(len(post_flex_soc_trace)):\n\t\tfig.append_trace(post_flex_soc_trace[i],5,1)\n\n\t#fig['layout'].update(template = standard_template, showlegend = False)\n\tplotly.offline.plot(fig, filename = 'flex.html')\n\n# Add Plot\nfig = subplots.make_subplots(rows = 1, cols = 1, shared_xaxes = True)\n\nfig.append_trace(pwr_trace,1,1)\nfor i in range(len(add_trace)):\n\tfig.append_trace(add_trace[i],1,1)\n\nplotly.offline.plot(fig, filename = 'addflex.html')\n\n# Add and Shed Plot - Bounding!\nfig = subplots.make_subplots(rows = 1, cols = 1, shared_xaxes = True)\n\nfig.append_trace(add_trace[1],1,1)\nfig.append_trace(kw_trace[1],1,1)\n\nplotly.offline.plot(fig, filename = 'flexbound.html')\n\n\nprint(' Figures Complete.\\n')\nprint('Script Finished.')\n","sub_path":"add_ice_storage_to_plant_loop_for_load_flexiblity/analysis/flex.py","file_name":"flex.py","file_ext":"py","file_size_in_byte":18285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"109561176","text":" # -*- coding: utf-8 -*-\n\nfrom re import sub\n\nimport ply.lex as lex\n\nkeywords = {\n\t'smaller' : 'SMALLER',\n\t'larger' : 'LARGER',\n\t'first' : 'FIRST',\n\t'second' : 'SECOND',\n\t\n\t'not': 'NOT',\n\t'or': 'OR',\n\t'and': 'AND',\n\n\t'set': 'SET',\n\t'add': 'ADD',\n\t'sub': 'SUB',\n\n\t'int': 'INT',\n\t'short': 'SHORT',\n\t'bool': 'BOOL',\n\t'false': 'FALSE',\n\t'true': 'TRUE',\n\t'undefined': 'UNDEFINED',\n\n\t'vector': 'VECTOR',\n\t'of': 'OF',\n\n\t'function': 'FUNCTION',\n\t'return': 'RETURN',\n\t'if': 'IF',\n\t'then': 'THEN',\n\t'else': 'ELSE',\n\t'while': 'WHILE',\n\t'do': 'DO',\n\t'begin': 'BEGIN',\n\t'end': 'END',\n\n\t'lms': 'LMS',\n\t'move': 'MOVE',\n\t'right': 'RIGHT',\n\t'left': 'LEFT',\n\t'sizeof': 'SIZEOF',\n\t'print' : 'PRINT'\n}\n\ntokens = tuple(keywords.values()) + (\n\t'ID', 'ICONST', 'SCONST',\n\t'LPAREN', 'RPAREN', 'LBRACKET', 'RBRACKET', 'LBRACE', 'RBRACE', 'COMMA',\n\t'ENDS', 'NEWLINE'\n)\n\nt_COMMA = r'\\,'\nt_LPAREN = r'\\('\nt_RPAREN = r'\\)'\nt_LBRACKET = r'\\['\nt_RBRACKET = r'\\]'\nt_LBRACE = r'\\{'\nt_RBRACE = r'\\}'\nt_ENDS = r';'\nt_ANY_ignore = ' \\t'\n\n\ndef t_error(t):\n\tprint(\"Illegal character '%s' at line '%s'\" % (t.value[0], t.lexer.lineno))\n\n\n\ndef t_ICONST(t):\n\t'((\\-)?[1-9][0-9]*)|[0]'\n\tt.value = int(t.value)\n\treturn t;\n\n\ndef t_SCONST(t):\n\tr'((\\-)?(?i)[S][1-9][0-9]*)|((?i)[S][0])'\n\tt.value = sub(r'(?i)[S]', '', t.value)\n\tt.value = int(t.value)\n\treturn t;\n\n\ndef t_ID(t):\n\tr'[_A-Za-z][_A-Za-z0-9]*'\n\tt.value = t.value.lower()\n\tif t.value in keywords:\n\t\tt.type = keywords[t.value]\n\treturn t\n\n\ndef t_NEWLINE(t):\n\tr'\\n+'\n\tt.lexer.lineno += len(t.value)\n\n\nlexer = lex.lex()\n\nif __name__ == '__main__':\n\n\tdef test(lexer, data):\n\t\tlexer.input(data)\n\t\twhile True:\n\t\t\ttok = lexer.token()\n\t\t\tif not tok:\n\t\t\t\tbreak\n\t\t\tprint(tok)\n\t\t\tif tok.type == 'ENDS':\n\t\t\t\tprint()\n\n\tprint()\n\tfilename = 'simple_test.i2'\n\tdata = open(filename).read()\n\ttest(lexer, data)\n","sub_path":"i2_lexer.py","file_name":"i2_lexer.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"151302113","text":"#\n# See https://github.com/dials/dials/wiki/pytest for documentation on how to\n# write and run pytest tests, and an overview of the available features.\n#\n\nfrom __future__ import absolute_import, division, print_function\n\nimport os\n\nimport pytest\n\ndef pytest_addoption(parser):\n '''Add a '--runslow' option to py.test.'''\n try:\n parser.addoption(\"--regression\", action=\"store_true\", default=False,\n help=\"run regression tests\")\n except ValueError:\n pass # Thrown in case the command line option is already defined\n parser.addoption(\"--runslow\", action=\"store_true\", default=False,\n help=\"run slow tests\")\n\ndef pytest_collection_modifyitems(config, items):\n '''Tests marked as slow will not be run unless slow tests are enabled with\n the '--runslow' parameter or the test is selected specifically. The\n latter allows running slow tests via the libtbx compatibility layer.'''\n if not config.getoption(\"--runslow\") and len(items) > 1:\n skip_slow = pytest.mark.skip(reason=\"need --runslow option to run\")\n for item in items:\n if \"slow\" in item.keywords:\n item.add_marker(skip_slow)\n\n@pytest.fixture(scope=\"session\")\ndef dials_regression():\n '''Return the absolute path to the dials_regression module as a string.\n Skip the test if dials_regression is not installed.'''\n try:\n import dials_regression as dr\n except ImportError:\n pytest.skip(\"dials_regression required for this test\")\n return os.path.dirname(dr.__file__)\n\n@pytest.fixture(scope=\"session\")\ndef regression_data(request):\n '''Return the location of a regression data set as py.path object.\n Skip the test if the data are not present.\n '''\n if not request.config.getoption(\"--regression\"):\n pytest.skip(\"Test requires --regression option to run.\")\n\n import dials.util.regression_data\n df = dials.util.regression_data.DataFetcher()\n def skip_test_if_lookup_failed(result):\n if not result:\n pytest.skip('Regression data is required to run this test. Run dials.fetch_test_data')\n return result\n setattr(df, 'result_filter', skip_test_if_lookup_failed)\n return df\n\n@pytest.fixture\ndef run_in_tmpdir(tmpdir):\n '''Shortcut to create a temporary directory and then run the test inside\n this directory.'''\n tmpdir.chdir()\n return tmpdir\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"552095724","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/taurus/core/epics/test/test_epicsattribute.py\n# Compiled at: 2019-08-19 15:09:29\n\"\"\"Test for epicsattributes...\"\"\"\nimport os, sys, numpy, subprocess, unittest\nfrom taurus.core.units import Quantity\nimport taurus\nfrom taurus.test import insertTest, getResourcePath\nfrom taurus.core.taurusbasetypes import DataType, AttrQuality, DataFormat\nfrom taurus.core.taurusbasetypes import TaurusAttrValue\n\n@insertTest(helper_name='write_read_attr', attrname='ca:test:a', setvalue=Quantity('1000mm'), expected=dict(rvalue=Quantity('1m'), type=DataType.Float, writable=True, data_format=DataFormat._0D, range=[\n Quantity('-10m'), Quantity('10m')], alarms=[\n None, None], warnings=[\n None, None]), expected_attrv=dict(rvalue=Quantity('1m'), wvalue=Quantity('1m'), quality=AttrQuality.ATTR_VALID, error=None))\n@unittest.skipIf(('epics' in sys.modules) is False, 'epics module is not available')\nclass AttributeTestCase(unittest.TestCase):\n \"\"\"TestCase for the taurus.Attribute helper\"\"\"\n _process = None\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Run the epics_test softIoc\"\"\"\n db_name = getResourcePath('taurus.core.epics.test.res', 'epics_test.db')\n args = ['softIoc', '-m', 'INST=test', '-d', db_name]\n dev_null = open(os.devnull, 'wb')\n cls._process = subprocess.Popen(args, stdout=dev_null, stderr=dev_null)\n\n @classmethod\n def tearDownClass(cls):\n \"\"\"Terminate the epics_test softIoc process\"\"\"\n if cls._process:\n cls._process.terminate()\n else:\n taurus.warning('Process not started, cannot terminate it.')\n\n def write_read_attr(self, attrname=None, setvalue=None, expected=None, expected_attrv=None, expectedshape=None):\n \"\"\"check creation and correct write-and-read of an attribute\"\"\"\n if expected is None:\n expected = {}\n if expected_attrv is None:\n expected_attrv = {}\n a = taurus.Attribute(attrname)\n if setvalue is None:\n read_value = a.read(cache=False)\n else:\n read_value = a.write(setvalue, with_read=True)\n msg = 'read() for \"%s\" did not return a TaurusAttrValue (got a %s)' % (\n attrname, read_value.__class__.__name__)\n self.assertTrue(isinstance(read_value, TaurusAttrValue), msg)\n for k, exp in expected.items():\n try:\n got = getattr(a, k)\n except AttributeError:\n msg = 'The attribute, \"%s\" does not provide info on %s' % (\n attrname, k)\n self.fail(msg)\n\n msg = '%s for \"%s\" should be %r (got %r)' % (\n k, attrname, exp, got)\n self.__assertValidValue(exp, got, msg)\n\n for k, exp in expected_attrv.items():\n try:\n got = getattr(read_value, k)\n except AttributeError:\n msg = 'The read value for \"%s\" does not provide info on %s' % (\n attrname, k)\n self.fail(msg)\n\n msg = '%s for the value of %s should be %r (got %r)' % (\n k, attrname, exp, got)\n self.__assertValidValue(exp, got, msg)\n\n if expectedshape is not None:\n msg = 'rvalue.shape for %s should be %r (got %r)' % (\n attrname, expectedshape, read_value.rvalue.shape)\n self.assertEqual(read_value.rvalue.shape, expectedshape, msg)\n return\n\n def __assertValidValue(self, exp, got, msg):\n if isinstance(got, Quantity):\n got = got.to(Quantity(exp).units).magnitude\n if isinstance(exp, Quantity):\n exp = exp.magnitude\n try:\n chk = numpy.allclose(got, exp)\n except:\n if isinstance(got, numpy.ndarray):\n chk = got.tolist() == exp.tolist()\n else:\n chk = bool(got == exp)\n\n self.assertTrue(chk, msg)","sub_path":"pycfiles/taurus-4.6.1-py2.7/test_epicsattribute.py","file_name":"test_epicsattribute.py","file_ext":"py","file_size_in_byte":4063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"144085966","text":"from random import randint\nfrom Semaphore import Semaphore\nimport threading\n\nclass SemaphoreExampleThread(threading.Thread):\n\n intList = []\n listSize = 100000\n semaphore = Semaphore(1)\n\n def __init__(self):\n super(SemaphoreExampleThread, self).__init__()\n\n @staticmethod\n def fillList():\n for i in range(0, SemaphoreExampleThread.listSize):\n SemaphoreExampleThread.intList.append(i)\n\n def flipCoin(self):\n return randint(0,1)\n\n def run(self):\n for i in range(0,4):\n # Determine if this thread is heads or tails\n coin = self.flipCoin()\n if coin == 0:\n self.print_(\"Thread \" + self.getName() + \" is ready to read the shared location\")\n self.read()\n self.print_(\"Thread \" + self.getName() + \" is now done reading shared location\")\n else:\n self.print_(\"Thread \" + self.getName() + \" is read to write the shared location\")\n self.write()\n self.print_(\"Thread \" + self.getName() + \" is now donw writing shared location\")\n\n def print_(self, msg):\n \"\"\"\n Print threads indented for easier viewing\n :param msg:\n :return:\n \"\"\"\n if self.getName() == \"one\":\n print(\"\\t\"),\n elif self.getName() == \"two\":\n print(\"\\t\\t\"),\n elif self.getName() == \"three\":\n print(\"\\t\\t\\t\"),\n else:\n print(\"\\t\\t\\t\\t\"),\n print(msg)\n\n def read(self):\n for i in range(0,self.listSize -1):\n self.intList[i]\n\n def write(self):\n \"\"\"\n Update list\n :return:\n \"\"\"\n SemaphoreExampleThread.semaphore.acquire()\n for i in range(0, self.listSize-1):\n self.intList[i] = i\n SemaphoreExampleThread.semaphore.release()\n\n\n\n\n","sub_path":"ConcurrentFun/SemaphoreExampleThread.py","file_name":"SemaphoreExampleThread.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"537262364","text":"\"\"\"Wrap access to GA in a high level client with a \"fetch\" endpoint.\n\n\"\"\"\n\nfrom apiclient.errors import HttpError\nfrom dashboard.dirs import CACHE_DIR\nfrom dashboard.fetch.ga_auth import perform_auth\nfrom dashboard.fetch.ga_profile import get_profile\nfrom datetime import datetime, timedelta\nfrom oauth2client.client import AccessTokenRefreshError\nimport hashlib\nimport json\nimport logging\nimport os\nimport time\n\n\nlogger = logging.getLogger(__name__)\n\n\n\nclass GAError(Exception):\n pass\n\n\ndef cached_iterator(fn):\n cache_dir = os.path.join(CACHE_DIR, 'gacache')\n if not os.path.isdir(cache_dir):\n logger.info(\"Making cache dir %s\", cache_dir)\n os.makedirs(cache_dir)\n\n def wrapped(self, *args, **kwargs):\n assert isinstance(self, GAClient)\n h = hashlib.sha1(repr([args, kwargs])).hexdigest()\n path = os.path.join(cache_dir, h)\n if os.path.exists(path):\n logger.info(\"Serving GA request from cache\")\n with open(path) as fobj:\n for row in fobj:\n yield json.loads(row)\n return\n logger.info(\"Performing GA request %s\", path)\n sampled = False\n try:\n with open(path + '.tmp', 'wb') as fobj:\n for result in fn(self, *args, **kwargs):\n if result.get('sampled') is not None:\n sampled = True\n fobj.write(json.dumps(result, separators=(',', ':')) + '\\n')\n yield result\n except:\n os.unlink(path + '.tmp')\n raise\n if sampled:\n # Don't cache sampled results\n os.unlink(path + '.tmp')\n else:\n os.rename(path + '.tmp', path)\n\n return wrapped\n\n\nclass GAClient(object):\n def __init__(self):\n self._last_request = None\n\n # Worst sampling rate that we've seen. None if none seen.\n # Callers of the client may reset this to None, and read it.\n self.worst_sample_rate = None\n\n # Time until we can trust that GA has processed the data.\n self.ga_latency = timedelta(hours=4)\n\n def _ensure_init_ga(self):\n \"\"\"Initialise GA connection if not already done.\n\n Looks up profile ids, etc.\n\n \"\"\"\n if self._last_request is not None:\n return\n try:\n self.service = perform_auth()\n self.profiles = {\n 'search': get_profile(\n self.service, 'www.gov.uk', 'UA-26179049-1',\n 'Q. Site search (entire site with query strings)'),\n }\n except AccessTokenRefreshError:\n logger.exception(\n \"Credentials error initialising GA access\",\n )\n raise GAError(\"Credentials error initialising GA access\")\n except HttpError as error:\n logger.exception(\n \"HTTP error initialising GA access: %s: %s\",\n error.resp.status, error._get_reason(),\n )\n raise GAError(\"HTTP error initialising GA access\")\n self._last_request = time.time()\n\n def build_ga_params(self, profile_name, ga_date, kwargs):\n profile = self.profiles[profile_name]\n params = dict(\n ids='ga:' + profile['profile_id'],\n start_date=ga_date,\n end_date=ga_date,\n samplingLevel=\"HIGHER_PRECISION\",\n max_results=10000,\n )\n params.update(kwargs)\n return params\n\n @cached_iterator\n def _fetch_from_ga(self, profile_name, date, name_map, kwargs):\n \"\"\"Call GA with the given profile, date and args.\n\n Yield an iterator of the result.\n\n \"\"\"\n self._ensure_init_ga()\n\n # Rate limit by simplest possible means.\n since = time.time() - self._last_request\n if since < 1:\n time.sleep(1.0 - since)\n self._last_request = time.time()\n\n ga_date = date.strftime(\"%Y-%m-%d\")\n\n now = datetime.now()\n latest_hour = None\n if date + timedelta(days=1) + self.ga_latency > now:\n # Some data for the selected date is not yet reliably available.\n if \"ga:hour\" in kwargs.get('dimensions', ''):\n # Grouping by hour, so can rely on some of the old hours.\n latest_hour = ((now - self.ga_latency).hour + 23) % 24\n if latest_hour < 0:\n return\n else:\n # We're not grouping by hour, so can't rely on any of the data.\n return\n\n try:\n params = self.build_ga_params(profile_name, ga_date, kwargs)\n\n start_index = 1\n while True:\n resp = self.service.query.get_raw_response(\n start_index=start_index,\n **params\n )\n if resp.get('containsSampledData'):\n sample_size = int(resp.get('sampleSize', 0))\n sample_space = int(resp.get('sampleSpace', 1))\n sample_rate = sample_size * 100.0 / sample_space\n logger.warning(\n \"GA query in %r profile used sampled data (%.2f%%: %s of %s): params %r\",\n profile_name,\n sample_rate, sample_size, sample_space,\n params)\n else:\n sample_rate = None\n total_results = resp['totalResults']\n headers = [\n name_map.get(header['name'][3:], header['name'][3:])\n for header in resp['columnHeaders']\n ]\n header_types = [\n {\n 'STRING': unicode,\n 'INTEGER': int,\n 'PERCENT': float,\n }[header['dataType']]\n for header in resp['columnHeaders']\n ]\n\n def makerow(row):\n ret = dict(zip(\n headers,\n (header_type(value)\n for (header_type, value) in zip(header_types, row))))\n if 'hour' in ret:\n hour = int(ret['hour'])\n ret['hour'] = hour\n if latest_hour is not None and hour > latest_hour:\n return None\n if sample_rate:\n ret['sampled'] = sample_rate\n\n return ret\n\n rows = resp.get('rows', ())\n for row in rows:\n start_index += 1\n row = makerow(row)\n if row is not None:\n yield row\n logger.info(\n \"Fetched %d of %d rows\", start_index - 1, total_results\n )\n\n if start_index > total_results:\n return\n except AccessTokenRefreshError:\n logger.exception(\n \"Credentials error fetching data from GA\",\n )\n raise GAError(\"Credentials error fetching data from GA\")\n except HttpError as error:\n logger.exception(\n \"HTTP error fetching data from GA: %s: %s\",\n error.resp.status, error._get_reason(),\n )\n raise GAError(\"HTTP error fetching data from GA\")\n\n\n def fetch(self, profile_name, date, name_map=None, **kwargs):\n \"\"\"Fetch some metrics.\n\n :param profile_name: The textual name of the GA profile to use.\n :param date: The date to fetch data for.\n :param name_map: A mapping from google column name to a name to return.\n\n Any other arguments are passed to the call to GA.\n\n Yields a sequence of rows. In each row, values are mapped to the\n appropriate string, integer or float datatype.\n\n Date fields are added automatically:\n - a 'date' column holding an ISO format date string\n - a 'year' column holding the year number\n - a 'week' column holding the week number in the year\n - a 'week_day' column holding the ISO week-day number (1==mon, 7==sun)\n\n Data which is more recent than ga_latency will not be returned.\n\n \"\"\"\n if name_map is None:\n name_map = {}\n\n # Remove time components from date, if it has any.\n date = datetime(year=date.year, month=date.month, day=date.day)\n\n for row in self._fetch_from_ga(profile_name, date, name_map, kwargs):\n sample_rate = row.get('sampled')\n if (\n self.worst_sample_rate is None or\n self.worst_sample_rate > sample_rate\n ):\n self.worst_sample_rate = sample_rate\n yield row\n","sub_path":"dashboard/fetch/ga_client.py","file_name":"ga_client.py","file_ext":"py","file_size_in_byte":8835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"573323408","text":"HISTORY_SIZE = 3\nHISTORY_FILE = 'history.json'\n\ncode_sites = {\n 'pastebin.com' : r\".*?\\[(.*?)\\].*?.*?\",\n 'codepad.org' : r\".*?(.*?) .*?.*?\",\n 'gist.github.com': r'
1:\n raise TypeError\n if i <= 0:\n raise TypeError\n if range_num[0] >= range_num[1]:\n raise AttributeError\n orig_list = [randint(range_num[0], range_num[1]) for el in range(amount_num)]\n print(orig_list)\nexcept ValueError:\n print('Need numbers. Try again.')\nexcept TypeError:\n print('Need only two numbers. And they should be > 0. Really sorry, '\n 'but we can not build a range starting from negative number or 0 '\n 'as well as range for 3 numbers is impossible.')\nexcept AttributeError:\n print('Number 1 should be < than number 2. Please, try again.')\ntry:\n new_list = [el for el in orig_list if el > orig_list[(orig_list.index(el) - 1)] and orig_list.index(el) > 0]\n print(new_list)\nexcept NameError:\n pass\n\n\n","sub_path":"task_4.2.py","file_name":"task_4.2.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"474545192","text":"# Minimax AI for Connect 4 with alpha-beta pruning\n# @author Everett Harding\n\nfrom minimax import *\nimport time\nclass AlphaBeta(Minimax):\n \"\"\" alphabeta object that takes a current connect four\"\"\"\n timeLimit = 0\n\n def __init__(self, board):\n #copy the board\n super(AlphaBeta, self).__init__(board)\n\n def bestMove(self, depth, state, curr_player, timeLimit):\n \"\"\" Returns the best move (as a column number) and the associated alpha\n Calls search()\n \"\"\"\n # determine opponent's color\n if curr_player == self.colors[0]:\n opp_player = self.colors[1]\n else:\n opp_player = self.colors[0]\n\n # enumerate all legal moves\n legal_moves = {} # will map legal move states to their alpha values\n # for col in range(7):\n # # if column i is a legal move...\n # if self.isLegalMove(col, state):\n # # make the move in column 'col' for curr_player\n # temp = self.makeMove(state, col, curr_player)\n # start = time.clock()\n # legal_moves[col] = self.search(depth-1, temp, opp_player, -1000000, 1000000, curr_player, start, self.timeLimit/7)\n\n legal_moves , maxDepth= self.iterativeDeep(depth, timeLimit, state, curr_player, opp_player)\n #print(\"Depth reached: \", maxDepth)\n best_alpha = -99999999\n best_move = None\n moves = legal_moves.items()\n random.shuffle(list(moves))\n for move, alpha in moves:\n # print(\"Compare\", alpha,move, \"to\", best_alpha,best_move)\n if alpha >= best_alpha:\n best_alpha = alpha\n best_move = move\n\n return best_move, best_alpha, maxDepth\n\n # iterative deepening wrapper for alphabeta search\n def iterativeDeep(self, depth, timeLimit, state, curr_player, opp_player):\n d = 0\n startTime = time.clock()\n legal_moves = {}\n alpha = -100000\n beta = 100000\n while d <= depth and time.clock() - startTime <= timeLimit:\n for col in range(7):\n if self.isLegalMove(col, state):\n # make the move in column 'col' for curr_player\n temp = self.makeMove(state, col, curr_player)\n substart = time.clock()\n legal_moves[col] = self.search(d, temp, opp_player, alpha, beta, curr_player, substart, timeLimit/7)\n d += 1\n return legal_moves, d-1\n\n # based on pseudocode from wikipedia\n def search(self, depth, state, curr_player, alpha, beta, me, startTime, limit):\n \"\"\" minimax search with alpha-beta pruning\"\"\"\n children = []\n\n for col in range (7):\n if self.isLegalMove(col, state):\n temp = self.makeMove(state, col, curr_player)\n children.append(temp)\n children = sorted(children, key = lambda x: -self.value(x, me))\n # determine opponent's color\n if curr_player == self.colors[0]:\n opp_player = self.colors[1]\n else:\n opp_player = self.colors[0]\n\n if len(children) == 0 or time.clock() - startTime >= limit or depth == 0 :\n #print(\"Max Depth heuristic : \", self.value(state, curr_player))\n # for row in temp:\n # print(row)\n # print(\"\\n\")\n # print(\"Value:\", self.value(state, me))\n # input(\"continue?\\n\")\n return self.value(state, me)\n if self.gameIsOver(state):\n return self.value(state, me)\n\n if curr_player is me:\n #do max search\n val = -10000000\n for child in children:\n val = max(val, self.search(depth - 1, child, opp_player, alpha, beta, me, startTime, limit))\n alpha = max(alpha, val)\n if(beta <= alpha):\n return alpha\n if time.clock() - startTime >= limit:\n return val\n return val\n else :\n #do min search\n val = 10000000\n for child in children:\n val = min(val, self.search(depth - 1, child, opp_player, alpha, beta, me, startTime, limit))\n beta = min(beta, val)\n if (beta <= alpha):\n return beta\n if time.clock() - startTime >= limit:\n return val\n return val\n\n # def value(self, state, color):\n # \"\"\" Simple heuristic to evaluate board configurations\n # Heuristic is (num of 4-in-a-rows)*99999 + (num of 3-in-a-rows)*100 +\n # (num of 2-in-a-rows)*10 - (num of opponent 4-in-a-rows)*99999 - (num of opponent\n # 3-in-a-rows)*100 - (num of opponent 2-in-a-rows)*10\n # \"\"\"\n # if color == self.colors[0]:\n # o_color = self.colors[1]\n # else:\n # o_color = self.colors[0]\n #\n # my_fours = self.checkForStreak(state, color, 4)\n # my_threes = self.checkForStreak(state, color, 3)\n # my_twos = self.checkForStreak(state, color, 2)\n # opp_fours = self.checkForStreak(state, o_color, 4)\n # opp_threes = self.checkForStreak(state, o_color, 3)\n # opp_twos = self.checkForStreak(state, o_color, 2)\n # if opp_fours > 0:\n # return -10000000\n # else:\n # return my_fours * 100000 + my_threes * 100 + my_twos - (opp_threes *150 + opp_twos)\n","sub_path":"AI-master/FinalAssignment/alphabeta.py","file_name":"alphabeta.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"209602876","text":"import socket\nimport http.client\nimport spider.tencent\nimport spider.tencent.store\nimport spider.tencent.fetcher\nimport spider.tencent.parser\nfrom spider.tencent.error import *\n\n__all__ = [\"crawlHomePage\", \"crawlPostDetail\"]\n\nclass HomePageCrawler:\n\tdef __init__(self, loggingQueue):\n\t\tself.__store = spider.tencent.store.Storage()\n\t\tself.__fetcher = spider.tencent.fetcher.HttpClientFetcher()\n\t\tself.__loggingQueue = loggingQueue\n\n\tdef startCrawling(self, groupSize, crawlerId):\n\t\tfor (userId, home) in \\\n\t\t\t\tself.__store.getHomePageFetchQueue(groupSize, crawlerId):\n\t\t\tself.__crawlSinglePage(userId, home)\n\n\tdef __crawlSinglePage(self, userId, home):\n\t\tmessage = \"/\" + home + \"\\t\"\n\t\ttry:\n\t\t\tcontent = self.__fetcher.fetchPath(\"/\" + home)\n\t\t\tresult = spider.tencent.parser.HomePage(content).parse()\n\t\t\tself.__storeHomePage(userId, result)\n\t\t\tmessage += result[0]\n\t\texcept (socket.timeout, http.client.IncompleteRead, socket.error):\n\t\t\tmessage += \"@NETWORK-ERROR@\"\n\t\texcept (UnknownTemplate, UnicodeDecodeError, HttpError):\n\t\t\tself.__store.removeUserStub(userId)\n\t\t\tmessage += \"@BAD-PAGE@\"\n\t\tfinally:\n\t\t\tself.__loggingQueue.put(message)\n\n\tdef __storeHomePage(self, userId, result):\n\t\tname, postList, userList = result\n\t\tself.__store.fillUserStub(userId, name)\n\t\tfor u in set(userList):\n\t\t\tself.__store.addUserStub(u)\n\t\tfor p in postList:\n\t\t\tif len(p) == 2:\n\t\t\t\tself.__store.addCompletePost(userId, p[0], p[1])\n\t\t\telse:\n\t\t\t\tself.__store.addPostStub(p[0])\n\nclass PostDetailCrawler:\n\tdef __init__(self, loggingQueue):\n\t\tself.__loggingQueue = loggingQueue;\n\t\tself.__fetcher = spider.tencent.fetcher.HttpClientFetcher()\n\t\tself.__store = spider.tencent.store.Storage()\n\t\n\tdef startCrawling(self, groupSize, crawlerId):\n\t\tfor postId in \\\n\t\t\t\tself.__store.getPostDetailFetchQueue(groupSize, crawlerId):\n\t\t\tself.__crawlSinglePost(postId)\n\n\tdef __handlePostPage(self, postId, url, retrieveContent):\n\t\thtmlText = self.__fetcher.fetchUrl(url)\n\t\tinfo = spider.tencent.parser.PostDetail(htmlText, postId)\n\t\tresult = info.parse(retrieveContent)\n\t\tif len(result) == 4:\n\t\t\tself.__store.addUserStub(result[3])\n\t\t\tuid = self.__store.getUserId(result[3])\n\t\t\tself.__store.fillPostStub(postId, uid, result[2])\n\t\tfor u in set(result[0]):\n\t\t\tself.__store.addUserStub(u)\n\t\treturn result[1]\n\n\tdef __crawlSinglePost(self, postId):\n\t\turl = spider.tencent.POST_DETAIL_URL + str(postId)\n\t\tmessage = \"/p/t/\" + str(postId) + \"\\t\"\n\t\ttry:\n\t\t\turl = self.__handlePostPage(postId, url, True)\n\t\t\ttry:\n\t\t\t\twhile url != None:\n\t\t\t\t\turl = self.__handlePostPage(postId, url, False)\n\t\t\t\tmessage += \"@DONE@\"\n\t\t\texcept Exception as e:\n\t\t\t\tmessage += \"@PARTIAL@\"\n\t\t\t\traise e\n\t\texcept (socket.timeout, http.client.IncompleteRead, socket.error):\n\t\t\tmessage += \"@NETWORK-ERROR@\"\n\t\texcept (UnicodeDecodeError, HttpError):\n\t\t\tself.__store.removePostStub(postId)\n\t\t\tmessage += \"@BAD-PAGE@\"\n\t\tfinally:\n\t\t\tself.__loggingQueue.put(message)\n\ndef crawlHomePage(groupSize, crawlerId, loggingQueue):\n\tcrawler = HomePageCrawler(loggingQueue)\n\tcrawler.startCrawling(groupSize, crawlerId)\n\ndef crawlPostDetail(groupSize, crawlerId, loggingQueue):\n\tcrawler = PostDetailCrawler(loggingQueue)\n\tcrawler.startCrawling(groupSize, crawlerId)","sub_path":"extras/weibo-spider/spider/tencent/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"621506768","text":"import os\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\nfrom time import sleep\r\nimport matplotlib.pyplot as plt\r\nimport traj_process.basic_process as traj_process\r\n\r\n\r\ndef map_match(network, interval=3, figures_folder=None, node_list=None):\r\n \"\"\"\r\n\r\n :param network:\r\n :param interval:\r\n :param figures_folder:\r\n :param node_list:\r\n :return:\r\n \"\"\"\r\n\r\n # process the trajectory data of each node\r\n for node_id in network.nodes.keys():\r\n if node_list is not None:\r\n if not (node_id in node_list):\r\n continue\r\n # prepare the movements\r\n movements = network.nodes[node_id].movements\r\n\r\n # get the raw trajectories\r\n raw_trajectories = network.nodes[node_id].raw_trajectories\r\n\r\n # if there is no trajs of this node!\r\n if raw_trajectories is None:\r\n continue\r\n\r\n total_trips_num = len(raw_trajectories[\"time_stamp\"])\r\n\r\n trips_maximum_prob = []\r\n\r\n print(\"Map-matching node\", node_id, \"...\")\r\n sleep(0.005)\r\n for idx in tqdm(range(total_trips_num)):\r\n local_time_stamp = raw_trajectories[\"time_stamp\"][idx]\r\n local_latitudes = raw_trajectories[\"latitudes\"][idx]\r\n local_longitudes = raw_trajectories[\"longitudes\"][idx]\r\n trip_id = raw_trajectories[\"trip_id\"][idx]\r\n\r\n # continue if the num of the points less than a threshold\r\n if len(local_time_stamp) < 10:\r\n continue\r\n\r\n # generate the table of the minimum links to the traj points\r\n # change the interval of the trajectory points\r\n trajs_lats = local_latitudes[::interval]\r\n trajs_lons = local_longitudes[::interval]\r\n\r\n # save the probability that the trajs belong to a movement\r\n probability_dict = {}\r\n\r\n for movement_id in movements.keys():\r\n movement_landmarks = movements[movement_id].get_landmarks(network)\r\n\r\n link_latitudes = movement_landmarks[\"latitudes\"]\r\n link_longitudes = movement_landmarks[\"longitudes\"]\r\n\r\n last_idx = None\r\n for traj_idx in range(len(trajs_lats)):\r\n traj_lat = trajs_lats[traj_idx]\r\n traj_lon = trajs_lons[traj_idx]\r\n\r\n min_distance, min_point, point_idx = \\\r\n traj_process.get_min_distance_to_link(traj_lat, traj_lon,\r\n link_latitudes, link_longitudes)\r\n\r\n # this code is to ensure the direction of the trajectory\r\n local_idx = point_idx\r\n if last_idx is None:\r\n last_idx = local_idx\r\n else:\r\n if local_idx < last_idx:\r\n probability_dict[movement_id] *= 0.1\r\n\r\n if not (movement_id in probability_dict.keys()):\r\n probability_dict[movement_id] = 1\r\n\r\n probability_dict[movement_id] *= get_state_possibility(min_distance)\r\n\r\n points_num = len(trajs_lats)\r\n\r\n # Normalize the probability\r\n probability_dict[movement_id] = pow(probability_dict[movement_id], 1 / points_num)\r\n\r\n # get the maximum probability\r\n maximum_prob = 0\r\n best_movement_id = None\r\n for movement_id in probability_dict.keys():\r\n local_prob = probability_dict[movement_id]\r\n if local_prob > maximum_prob:\r\n best_movement_id = movement_id\r\n maximum_prob = local_prob\r\n\r\n # all the probability is zero\r\n if best_movement_id is None:\r\n continue\r\n\r\n # save the trajectory to the movement\r\n if maximum_prob > 0.4:\r\n if network.nodes[node_id].movements[best_movement_id].raw_trajectory is None:\r\n network.nodes[node_id].movements[best_movement_id].raw_trajectory = {\"time_stamp\": [],\r\n \"latitudes\": [],\r\n \"longitudes\": [],\r\n \"trip_id\": []}\r\n else:\r\n print(network.nodes[node_id].movements[best_movement_id].raw_trajectory.keys())\r\n network.nodes[node_id].movements[best_movement_id].raw_trajectory[\"time_stamp\"].append(local_time_stamp)\r\n network.nodes[node_id].movements[best_movement_id].raw_trajectory[\"latitudes\"].append(local_latitudes)\r\n network.nodes[node_id].movements[best_movement_id].raw_trajectory[\"longitudes\"].append(local_longitudes)\r\n network.nodes[node_id].movements[best_movement_id].raw_trajectory[\"trip_id\"].append(trip_id)\r\n\r\n if network.nodes[node_id].movements[best_movement_id].matched_trajectory is None:\r\n network.nodes[node_id].movements[best_movement_id].matched_trajectory = {\"time_stamp\": [],\r\n \"latitudes\": [],\r\n \"longitudes\": [],\r\n \"trip_id\": []}\r\n network.nodes[node_id].movements[best_movement_id].matched_trajectory[\"time_stamp\"].append(local_time_stamp)\r\n network.nodes[node_id].movements[best_movement_id].matched_trajectory[\"latitudes\"].append(local_latitudes)\r\n network.nodes[node_id].movements[best_movement_id].matched_trajectory[\"longitudes\"].append(local_longitudes)\r\n network.nodes[node_id].movements[best_movement_id].matched_trajectory[\"trip_id\"].append(trip_id)\r\n\r\n trips_maximum_prob.append(maximum_prob)\r\n\r\n if figures_folder is not None:\r\n plt.figure(dpi=150)\r\n plt.hist(trips_maximum_prob)\r\n valid_prop = np.sum([val > 0.4 for val in trips_maximum_prob]) / len(trips_maximum_prob)\r\n valid_prop = np.round(valid_prop * 100, 2)\r\n plt.title(str(node_id) + \" \" + str(valid_prop) + \"%\")\r\n\r\n save_file_name = os.path.join(figures_folder, str(node_id) + \"-hist.png\")\r\n plt.savefig(save_file_name)\r\n plt.close()\r\n\r\n movements = network.nodes[node_id].movements\r\n plt.figure(dpi=200, figsize=[15, 8])\r\n for movement_id in movements.keys():\r\n phase_id = movements[movement_id].phase_id\r\n plt.subplot(2, 4, phase_id)\r\n raw_trajectories = movements[movement_id].raw_trajectory\r\n\r\n for temp_id in movements.keys():\r\n movement_landmarks = movements[temp_id].get_landmarks(network)\r\n plt.plot(movement_landmarks[\"longitudes\"], movement_landmarks[\"latitudes\"], \"b.-\", alpha=0.3)\r\n\r\n if raw_trajectories is not None:\r\n trips_latitudes = raw_trajectories[\"latitudes\"]\r\n trips_longitudes = raw_trajectories[\"longitudes\"]\r\n for trip_idx in range(len(trips_latitudes)):\r\n plt.plot(trips_longitudes[trip_idx],\r\n trips_latitudes[trip_idx], \"r\", alpha=0.5)\r\n\r\n if raw_trajectories is None:\r\n plt.title(\"Phase \" + str(phase_id) + \" \" + \"0\")\r\n else:\r\n plt.title(\"Phase \" + str(phase_id) + \" \" + str(len(raw_trajectories[\"latitudes\"])))\r\n plt.xlabel(\"Longitude\")\r\n plt.ylabel(\"Latitude\")\r\n plt.xticks([])\r\n plt.yticks([])\r\n\r\n plt.tight_layout()\r\n plt.savefig(os.path.join(figures_folder, str(node_id) + \".png\"))\r\n plt.close()\r\n return network\r\n\r\n\r\ndef get_state_possibility(distance, sigma_z=8):\r\n \"\"\"\r\n\r\n :param distance:\r\n :param sigma_z:\r\n :return:\r\n \"\"\"\r\n prop = 1 / np.sqrt(2 * np.pi) / sigma_z * np.exp(-0.5 * pow(distance / sigma_z, 2))\r\n\r\n standard_value = 1 / np.sqrt(2 * np.pi) / sigma_z * np.exp(-0.5 * pow(0 / sigma_z, 2))\r\n prop /= standard_value\r\n return prop\r\n\r\n","sub_path":"traj_process/map_match.py","file_name":"map_match.py","file_ext":"py","file_size_in_byte":8518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"374292876","text":"import requests\nfrom scrapy.selector import Selector\nimport MySQLdb\nimport time\n\nconn=MySQLdb.connect(host=\"127.0.0.1\",user=\"root\",passwd=\"123456\",db=\"article_spider\",charset=\"utf8\")\ncursor=conn.cursor()\n\ndef crawl_ips():\n '''爬取西刺的免费ip代理'''\n headers={\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36\"}\n for i in range(1,3400):\n print(\"第:\",str(i),\"页\")\n time.sleep(1)\n re=requests.get(\"http://www.xicidaili.com/nn/{0}\".format(i),headers=headers)\n selector=Selector(text=re.text)\n all_trs=selector.css(\"#ip_list tr\")[1:]\n # print(all_trs)\n\n ip_list=[]\n for tr in all_trs:\n speed_str=tr.css(\".bar::attr(title)\").extract()[0]\n if speed_str:\n speed=float(speed_str.split(\"秒\")[0]) #速度\n # print(speed)\n all_texts=tr.css(\"td::text\").extract()\n # print(all_texts)\n ip=all_texts[0]\n port=all_texts[1]\n proxy_type=all_texts[5] if all_texts[2]=='\\n ' else all_texts[4]\n ip_list.append((ip,port,proxy_type,speed))\n\n for ip_info in ip_list: #注意这里用单引��\n insert_sql = \"insert into proxy_ip(`ip`,`port`,`speed`,`proxy_type`) VALUES ('{0}','{1}',{2},'{3}');\".format(ip_info[0],ip_info[1],ip_info[3],ip_info[2])\n print(insert_sql)\n cursor.execute(insert_sql)\n conn.commit()\n\nclass GetIP(object):\n def delete_ip(self,ip):\n #从数据库中删除无效的ip\n delete_sql = \"delete from proxy_ip where ip='{0}'\".format(ip)\n cursor.execute(delete_sql)\n conn.commit()\n return True\n def judge_ip(self,ip,port):\n '''判断ip是否可用'''\n http_url=\"https://www.baidu.com\" #坑!这里必须用https://www.baidu.com\n proxy_url=\"https://{0}:{1}\".format(ip,port)\n try:\n proxy_dict={\n \"http\":proxy_url,\n }\n response=requests.get(http_url,proxies=proxy_dict)\n except Exception as e:\n print(\"invalid ip and port\")\n self.delete_ip(ip)\n return False\n else: #如果except不会执行else\n code=response.status_code\n if code>=200 and code<300:\n print(\"effective ip\")\n return True\n else:\n print(\"invalid ip and port\")\n self.delete_ip(ip)\n return False\n def get_random_ip(self):\n '''从数据库中随机获取一个可用的ip'''\n random_sql=\"SELECT ip,port FROM proxy_ip ORDER BY RAND() LIMIT 1;\"\n result=cursor.execute(random_sql)\n for ip_info in cursor.fetchall():\n ip=ip_info[0]\n port=ip_info[1]\n print(\"随机获取了一个ip地址:\",ip,port)\n judge_re=self.judge_ip(ip,port)\n if judge_re:\n return \"https://{0}:{1}\".format(ip,port)\n else:\n return self.get_random_ip()\n\nif __name__ == '__main__':\n #爬ip\n # crawl_ips()\n\n g=GetIP();\n # 随机返回一个代理ip地址,例:https://121.231.68.71:33835\n print(g.get_random_ip())","sub_path":"tools/crawl_xici_ip.py","file_name":"crawl_xici_ip.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"627579761","text":"from math import acos, pi, sqrt\n\nimport numpy as np\nfrom qiskit import BasicAer\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\nfrom qiskit.aqua import QuantumInstance\nfrom qiskit.aqua.algorithms import VQC\nfrom qiskit.aqua.components.feature_maps import FeatureMap\nfrom qiskit.aqua.components.optimizers import SPSA\nfrom qiskit.circuit.library import TwoLocal\nfrom qiskit import IBMQ\nfrom qiskit.providers.ibmq import least_busy\nIBMQ.load_account()\nfrom read_data import *\n\nclass QracFeatureMap(FeatureMap):\n \"\"\"Mapping data with a custom feature map.\"\"\"\n\n def __init__(self, feature_dimension, depth=2):\n \"\"\"\n Args:\n feature_dimension (int): number of features\n depth (int): the number of repeated circuits\n \"\"\"\n self._support_parameterized_circuit = False\n self._feature_dimension = feature_dimension\n self._num_qubits = self._feature_dimension = feature_dimension\n self._depth = depth\n\n def construct_circuit(self, feature_string, qr, inverse=False):\n \"\"\"Construct the feature map circuit.\n\n Args:\n feature_string (string): 3n bit string encoding the case.\n qr (QauntumRegister): the QuantumRegister object for the circuit.\n inverse (bool): whether or not to invert the circuit.\n\n Returns:\n QuantumCircuit: a quantum circuit transforming data x.\n \"\"\"\n n_qubit = self._feature_dimension\n qc = QuantumCircuit(qr)\n theta = acos(sqrt(0.5 + sqrt(3.0) / 6.0))\n rotationParams = {\"000\": (2 * theta, pi / 4, -pi / 4), \"010\": (2 * theta, 3 * pi / 4, -3 * pi / 4),\n \"100\": (pi - 2 * theta, pi / 4, -pi / 4), \"110\": (pi - 2 * theta, 3 * pi / 4, -3 * pi / 4),\n \"001\": (2 * theta, -pi / 4, pi / 4), \"011\": (2 * theta, -3 * pi / 4, 3 * pi / 4),\n \"101\": (pi - 2 * theta, -pi / 4, pi / 4), \"111\": (pi - 2 * theta, -3 * pi / 4, 3 * pi / 4)}\n bits_list = [feature_string[i:i + 3] for i in range(0, 3*n_qubit, 3)]\n for i, bit in enumerate(bits_list):\n qc.u(*rotationParams[bit], i)\n qc.barrier()\n return qc\n\nclass TrainingMonitor:\n def __init__(self, iters, logging = True):\n self.batch_num = []\n self.params = []\n self.loss_hist = []\n self.index = []\n self.it = iters\n self.is_logging = logging\n def callback_monitor(self,a,b,c,d):\n if a%self.it==0:\n self.batch_num.append(a)\n self.params.append(b)\n self.loss_hist.append(c)\n self.index.append(d)\n if self.is_logging:\n print('Loss: %.3f'%c)\n'''\nDummy input\ntraining_input = {'A':['000','001','010','011','100'],'B':['101','110','111']}\ntest_input = {'A':['000','001','010','011','100'],'B':['101','110','111']}\n'''\n\nif __name__ == \"__main__\":\n training_input, test_input, pre_input = data2feature(read_cancer_data())\n random_seed = 333\n\n\n provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='qc2021s')\n backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and\n not x.configuration().simulator and x.status().operational==True))\n print(\"least busy backend: \", backend)\n\n optimizer = SPSA(max_trials=100, c0=4.0, skip_calibration=True)\n optimizer.set_options(save_steps=1)\n feature_map = QracFeatureMap(feature_dimension=3, depth=1)\n var_form = TwoLocal(3, ['ry','rz'], 'cz', reps=2)\n monitor = TrainingMonitor(5, logging=True)\n vqc = VQC(optimizer, feature_map, var_form, training_input, test_input, callback=monitor.callback_monitor)\n quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=random_seed, seed_transpiler=random_seed)\n result = vqc.run(quantum_instance)\n\n result_set_A = []\n result_set_B = []\n for i in range(10):\n pre_result_A = vqc.predict(pre_input['A'][i], quantum_instance)\n pre_result_B = vqc.predict(pre_input['B'][i], quantum_instance)\n success_ratio_A = list(pre_result_A[1]).count(0)/len(pre_result_A[1])\n success_ratio_B = list(pre_result_B[1]).count(1)/len(pre_result_B[1])\n print(f'Predict success ratio for negative cases of {i+1}th valid set: {success_ratio_A:.3f}')\n print(f'Predict success ratio for postive cases of {i+1}th valid set: {success_ratio_B:.3f}\\n')\n result_set_A.append(success_ratio_A)\n result_set_B.append(success_ratio_B)\n \n average_ratio_A = sum(result_set_A) / len(result_set_A)\n average_ratio_B = sum(result_set_B) / len(result_set_B)\n print(f\"success negative cases: {average_ratio_A:.3f}\\n success positive cases: {average_ratio_B:.3f}\")\n\n # Calculate f1 score\n p = list(pre_result_B[1]).count(1)/(list(pre_result_B[1]).count(1)+list(pre_result_A[1]).count(1))\n r = list(pre_result_B[1]).count(1)/len(pre_result_B[1])\n f1 = 2*p*r/(p+r)\n \n overall = (list(pre_result_A[1]).count(0)+list(pre_result_B[1]).count(1))/(len(pre_result_A[1])+len(pre_result_B[1]))\n print(f'Overall success ratio: {overall:.3f}')\n print(f'F1 value: {f1:.3f}')","sub_path":"qrac-qvc-real-backends.py","file_name":"qrac-qvc-real-backends.py","file_ext":"py","file_size_in_byte":5221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"394393549","text":"#!/usr/bin/env python3\n\nfrom collections import Counter\n\nfrom lengths import *\nfrom scan import *\n\ndefault_ld = LengthDictionary()\ndefault_ld.load(\".default_length_dictionary.pickle\")\n\nclass Test():\n \"\"\"Class for testing Semetrika with and without using\n length dictionary.\"\"\"\n\n def __init__(self, lines):\n # skip short lines\n self.lines = [line for line in lines\n if len(line) > 10]\n self.verse_count = len(self.lines)\n # without length dictionary\n self.verses_without_lengths = [Verse(line, length_dictionary=None)\n for line in self.lines]\n # with\n self.verses_with_lengths = [Verse(line, length_dictionary=\n default_ld.dictionary)\n for line in self.lines]\n # verses which cannot be scanned\n self.verses_with_no_scansion = [verse for verse\n in self.verses_without_lengths\n if verse.scansion_count == 0]\n # verses which are scanned differently with and without\n # the dictionary\n self.verses_with_different_scansions = [(wo, w) for wo, w\n in zip(self.verses_without_lengths,\n self.verses_with_lengths)\n if wo.scansion_count != w.scansion_count ]\n self.statistics = None\n self.count_statistics()\n\n # number of verses scanned in zero to six ways with and\n # without the length dictionary\n def count_statistics(self):\n statistics = {\"without\": Counter(), \"with\": Counter()}\n for verse in self.verses_without_lengths:\n statistics[\"without\"][verse.scansion_count] += 1\n for verse in self.verses_with_lengths:\n statistics[\"with\"][verse.scansion_count] += 1\n self.statistics = statistics\n return\n \n def print_statistics(self):\n \"\"\"Prints number of verses scanned in zero to six ways\n without and with the length dictionary.\"\"\"\n print(f\"NUMBER OF VERSES: {self.verse_count}\\n\")\n print(\"\\t| W/O\\tWITH\\t| W/O\\tWITH\")\n # there cannot be more than six scansions\n for scansion_count in range(7):\n wo_count = self.statistics[\"without\"][scansion_count]\n wo_pct = wo_count*100 // self.verse_count\n w_count = self.statistics[\"with\"][scansion_count]\n w_pct = w_count*100 // self.verse_count\n if not wo_count == w_count == 0:\n print(f\"{scansion_count}\\t| {wo_count}\\t{w_count}\"\n + f\"\\t| {wo_pct} %\\t{w_pct} %\")\n return\n \n def print_differences(self):\n \"\"\"Prints verses which cannot be scanned and those which\n are scanned differently without and with length dictionary.\"\"\"\n for verse_wo, verse_with in zip(self.verses_without_lengths,\n self.verses_with_lengths):\n if verse_wo.scansion_count == 0:\n print(\"NO SCANSION FOUND:\")\n verse_wo.print_scansions()\n print(f\"\\n{'='*30}\\n\")\n elif verse_wo.scansion_count != verse_with.scansion_count:\n print(\"DIFFERENT NUMEBR OF SCANSIONS:\")\n print(\"WITHOUT LENGTH DICTIONARY:\")\n verse_wo.print_scansions()\n print(\"WITH LENGTH DICTIONARY:\", end=\" \")\n verse_with.print_verse()\n verse_with.print_scansions()\n print(f\"\\n{'='*30}\\n\")\n return\n","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"319896734","text":"import logging\n\n_logger = logging.getLogger(__name__)\n\n\nclass Plugin:\n\n def install_package(self, server, package):\n \"\"\"\n Use common package managers to install the given package.\n\n :param server: SSHServer to install the package on\n :param package: name of the package to install\n \"\"\"\n command = \"sudo yum install %s -y\" % package\n _logger.debug(\"[PLUGIN:%s] Install package [%s] if needed (using yum)\" % (self.__class__.__name__, package))\n _logger.debug(command)\n _logger.debug(server.execute(command))\n command = \"sudo apt-get install %s -y\" % package\n _logger.debug(\"[PLUGIN:%s] Install package [%s] if needed (using apt-get)\" % (self.__class__.__name__, package))\n _logger.debug(command)\n _logger.debug(server.execute(command))\n _logger.debug(\"[PLUGIN:%s] Installing package [%s] done\" % (self.__class__.__name__, package))\n\n def install(self, server):\n \"\"\"\n Install the plugin on the given server.\n\n :param server: the SSHServer to install the software on\n \"\"\"\n raise Exception(\"[PLUGIN:%s] Method 'install' is not implemented\" % self.__class__.__name__)\n\n def collect(self, server):\n \"\"\"\n Collect results using the plugin and give back a list of dictionaries where all dictionaries have the same keys.\n\n :param: server SSHServer object which is used to execute commands on\n :return: list of dictionaries\n \"\"\"\n _logger.warn(\"[PLUGIN:%s] Method 'collect' is not implemented\" % self.__class__.__name__)\n","sub_path":"isa/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"118063675","text":"\"\"\"drfdemo URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/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.views.generic import TemplateView\nfrom django.urls import path, include\nfrom rest_framework.schemas import get_schema_view\nimport debug_toolbar\n\nurlpatterns = [\n path(\"horloge/\", include(\"horloge.urls\")),\n path(\"memcache/\", include(\"memcache.urls\")),\n path(\"files/\", include(\"file.urls\")),\n path(\"uptime/\", include(\"uptime.urls\")),\n path(\"admin/\", admin.site.urls),\n path(\"__debug__/\", include(debug_toolbar.urls)),\n path(\n \"openapi\",\n get_schema_view(\n title=\"Demo 1\", description=\"API for all things …\", version=\"1.0.0\"\n ),\n name=\"openapi-schema\",\n ),\n path(\n \"swagger-ui/\",\n TemplateView.as_view(\n template_name=\"swagger-ui.html\",\n extra_context={\"schema_url\": \"openapi-schema\"},\n ),\n ),\n]\n","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"19065681","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPipeline-GUI for Analysis with MNE-Python\n@author: Martin Schulz\n@email: dev@earthman-music.de\n@github: https://github.com/marsipu/mne_pipeline_hd\nLicense: BSD (3-clause)\nWritten on top of MNE-Python\nCopyright © 2011-2020, authors of MNE-Python (https://doi.org/10.3389/fnins.2013.00267)\ninspired by Andersen, L. M. (2018) (https://doi.org/10.3389/fnins.2018.00006)\n\"\"\"\nfrom importlib import resources\nfrom os import listdir\nfrom os.path import isdir, join\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QFont, QPixmap\nfrom PyQt5.QtWidgets import (QComboBox, QFileDialog, QGroupBox, QHBoxLayout, QInputDialog,\n QLabel, QMessageBox, QPushButton, QVBoxLayout, QWidget)\n\nfrom mne_pipeline_hd import QS\nfrom mne_pipeline_hd.gui.base_widgets import SimpleList\nfrom mne_pipeline_hd.gui.gui_utils import ErrorDialog, center, WorkerDialog\nfrom mne_pipeline_hd.gui.main_window import MainWindow\nfrom mne_pipeline_hd.pipeline_functions.controller import Controller\n\n\nclass WelcomeWindow(QWidget):\n def __init__(self):\n super().__init__()\n\n self.ct = Controller()\n self.main_window = None\n self.education_programs = list()\n self.education_on = QS().value('education', defaultValue=0)\n\n self.init_ui()\n self.check_controller()\n\n self.show()\n center(self)\n\n def init_ui(self):\n layout = QVBoxLayout()\n title_label = QLabel('Welcome to MNE-Pipeline!')\n title_label.setFont(QFont(QS().value('app_font'), 20))\n layout.addWidget(title_label)\n\n image_label = QLabel()\n with resources.path('mne_pipeline_hd.pipeline_resources',\n 'mne_pipeline_logo_evee_smaller.jpg') as img_path:\n image_label.setPixmap(QPixmap(str(img_path)))\n layout.addWidget(image_label)\n\n home_layout = QHBoxLayout()\n self.home_path_label = QLabel()\n home_layout.addWidget(self.home_path_label, stretch=4)\n home_path_bt = QPushButton('Set Home-Folder')\n home_path_bt.clicked.connect(self.set_home_path)\n home_layout.addWidget(home_path_bt, alignment=Qt.AlignRight)\n layout.addLayout(home_layout)\n\n project_layout = QHBoxLayout()\n self.project_label = QLabel()\n project_layout.addWidget(self.project_label)\n self.project_cmbx = QComboBox()\n self.project_cmbx.activated.connect(self.project_changed)\n project_layout.addWidget(self.project_cmbx)\n self.add_pr_bt = QPushButton('Add Project')\n self.add_pr_bt.clicked.connect(self.add_project)\n project_layout.addWidget(self.add_pr_bt, alignment=Qt.AlignRight)\n layout.addLayout(project_layout)\n\n self.edu_groupbox = QGroupBox('Education')\n self.edu_groupbox.setCheckable(True)\n if self.education_on == 'true':\n self.edu_groupbox.setChecked(True)\n else:\n self.edu_groupbox.setChecked(False)\n edu_layout = QVBoxLayout()\n self.edu_selection = SimpleList(self.education_programs, title='Education')\n edu_layout.addWidget(self.edu_selection)\n self.edu_groupbox.setLayout(edu_layout)\n layout.addWidget(self.edu_groupbox)\n\n bt_layout = QHBoxLayout()\n self.start_bt = QPushButton('Start')\n self.start_bt.setFont(QFont(QS().value('app_font'), 20))\n self.start_bt.setEnabled(False)\n self.start_bt.clicked.connect(self.init_main_window)\n bt_layout.addWidget(self.start_bt)\n\n close_bt = QPushButton('Close')\n close_bt.clicked.connect(self.close)\n close_bt.setFont(QFont(QS().value('app_font'), 20))\n bt_layout.addWidget(close_bt)\n\n layout.addLayout(bt_layout)\n self.setLayout(layout)\n\n def check_controller(self):\n self.start_bt.setEnabled(False)\n self.project_cmbx.setEnabled(False)\n self.add_pr_bt.setEnabled(False)\n\n # Check for Home-Path-Problems\n if 'home_path' in self.ct.errors:\n ht = f'{self.ct.errors[\"home_path\"]}\\n' \\\n f'Select a folder as Home-Path!'\n self.home_path_label.setText(ht)\n else:\n self.home_path_label.setText(f'{self.ct.home_path} selected.')\n self.project_cmbx.setEnabled(True)\n self.update_project_cmbx()\n self.add_pr_bt.setEnabled(True)\n\n # Add education-programs if there are any\n self.education_programs.clear()\n edu_path = join(self.ct.home_path, 'edu_programs')\n if isdir(edu_path):\n for file in [f for f in listdir(edu_path) if f[-9:] == '-edu.json']:\n self.education_programs.append(file)\n\n self.edu_selection.content_changed()\n\n # Check for Project-Problems\n if 'project' in self.ct.errors:\n pt = f'{self.ct.errors[\"project\"]}\\n' \\\n f'Select or add a project!'\n self.project_label.setText(pt)\n else:\n self.project_label.setText(f'{self.ct.pr.name} selected.')\n self.start_bt.setEnabled(True)\n\n # Check for Problems with Custom-Modules\n if 'custom_modules' in self.ct.errors:\n for name in self.ct.errors['custom_modules']:\n error_msg = self.ct.errors['custom_modules'][name]\n if isinstance(error_msg, tuple):\n ErrorDialog(error_msg, self,\n title=f'Error in import of custom-module: {name}')\n elif isinstance(error_msg, str):\n QMessageBox.warning(self, 'Import-Problem', error_msg)\n\n def set_home_path(self):\n loaded_home_path = QFileDialog.getExistingDirectory(self, f'{self.ct.home_path}'\n f'Select a folder as Home-Path')\n if loaded_home_path != '':\n self.ct = Controller(str(loaded_home_path))\n self.check_controller()\n\n def project_changed(self, project_idx):\n project = self.project_cmbx.itemText(project_idx)\n self.ct.change_project(project)\n self.update_project_cmbx()\n self.start_bt.setEnabled(True)\n\n def update_project_cmbx(self):\n if hasattr(self.ct, 'projects'):\n self.project_cmbx.clear()\n self.project_cmbx.addItems(self.ct.projects)\n if self.ct.pr is not None:\n self.project_label.setText(f'{self.ct.pr.name} selected.')\n self.project_cmbx.setCurrentText(self.ct.pr.name)\n\n def add_project(self):\n new_project, ok = QInputDialog.getText(self, 'Add Project',\n 'Please enter the name of a project!')\n if ok and new_project != '':\n self.ct.change_project(new_project)\n self.update_project_cmbx()\n self.start_bt.setEnabled(True)\n\n def init_main_window(self):\n if self.edu_groupbox.isChecked():\n self.ct.edu_program_name = self.edu_selection.get_current()\n self.ct.load_edu()\n\n # Check if MNE-Python is installed\n try:\n import mne\n except ModuleNotFoundError:\n QMessageBox.critical(self, 'MNE-Python not found!', 'MNE-Python was not found,'\n ' please install it before using MNE-Pipeline!')\n else:\n self.main_window = MainWindow(self.ct, self)\n if self.edu_groupbox.isChecked():\n self.main_window.start_edu()\n self.hide()\n\n def closeEvent(self, event):\n WorkerDialog(self, self.ct.save, blocking=True, title='Saving Project!')\n if self.edu_groupbox.isChecked():\n QS().setValue('education', 1)\n else:\n QS().setValue('education', 0)\n event.accept()\n","sub_path":"mne_pipeline_hd/gui/welcome_window.py","file_name":"welcome_window.py","file_ext":"py","file_size_in_byte":7961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"615190039","text":"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\nimport os\r\n\r\ndir = \"C://Users//Administrator//netlearn//SIFT_BFmatcher//SRAD2018_TRAIN_001//RAD_206482464212530//\"\r\n\r\nsift = cv2.xfeatures2d.SIFT_create()\r\n\r\ndef draw_radar_sift(dir):\r\n\tfile_list = os.listdir(dir)\r\n\tprint(file_list)\r\n\tfor filename in file_list:\r\n\t\tpath = ''\r\n\t\tpath = dir+filename\r\n\t\tgray = cv2.imread(path,0) #读取灰度图\r\n\t\t#gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) #灰度处理图像\r\n\t\tkp, des = sift.detectAndCompute(gray,None) #des是描述子\r\n\t\timg2 = cv2.drawKeypoints(gray,kp,gray,color=(255,0,255)) #画出特征点,并显示为红色圆圈\r\n\t\t#cv2.imshow(\"point\", img2)\r\n\t\tcv2.imwrite(path, img2)\r\n\t\tprint (\"%s has been draw sift!\"%filename)\r\n\t\tcv2.waitKey(0)\t\t\r\n \r\n\r\nif __name__ == '__main__':\r\n draw_radar_sift(dir)\r\n\r\n'''\r\nimport numpy as np\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\n\r\nimgname1 = 'RAD_206482464212530_038.png'\r\nimgname2 = 'RAD_206482464212530_054.png'\r\n\r\nsift = cv2.xfeatures2d.SIFT_create()\r\n\r\nimg1 = cv2.imread(imgname1,0)\r\n#gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) #灰度处理图像\r\nkp1, des1 = sift.detectAndCompute(img1,None) #des是描述子\r\n\r\nimg2 = cv2.imread(imgname2,0)\r\n#gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)#灰度处理图像\r\nkp2, des2 = sift.detectAndCompute(img2,None) #des是描述子\r\n\r\nhmerge = np.hstack((img1, img2)) #水平拼接\r\ncv2.imshow(\"gray\", hmerge) #拼接显示为gray\r\n#cv2.imwrite(\"gray\", hmerge)\r\ncv2.waitKey(0)\r\n\r\nimg3 = cv2.drawKeypoints(img1,kp1,img1,color=(255,0,255)) #画出特征点,并显示为红色圆圈\r\nimg4 = cv2.drawKeypoints(img2,kp2,img2,color=(255,0,255)) #画出特征点,并显示为红色圆圈\r\nhmerge = np.hstack((img3, img4)) #水平拼接\r\ncv2.imshow(\"point\", hmerge) #拼接显示为gray\r\n#cv2.imwrite(\"point\", hmerge)\r\ncv2.waitKey(0)\r\n# BFMatcher解决匹配\r\nbf = cv2.BFMatcher()\r\nmatches = bf.knnMatch(des1,des2, k=2)\r\n# 调整ratio\r\ngood = []\r\nfor m,n in matches:\r\n if m.distance < 0.75*n.distance:\r\n good.append([m])\r\n\r\n#img5 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,matches,None,flags=2)\r\nimg5 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good[:10],None,flags=2)\r\ncv2.imshow(\"BFmatch\", img5)\r\n#cv2.imwrite(\"BFmatch\", img5)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n'''\r\n","sub_path":"019 Opencv绘制sift关键点批量读取保存图像/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"160763753","text":"from .base_page import BasePage\nfrom .locators import BasketPageLocators\n\n\nclass BasketPage(BasePage):\n def should_not_be_items_in_basket(self):\n assert self.is_not_element_present(*BasketPageLocators.ITEMS_IN_BASKET), \\\n \"Items are presented, but should not be\"\n\n def should_be_empty_basket_message(self):\n a = self.browser.find_element(*BasketPageLocators.EMPTY_BASKET_MESSAGE).text\n assert a is \"Ваша корзина пуста\" or \"Your basket is empty.\", \\\n \"Wrong message; basket is not empty\"\n","sub_path":"Pages/basket_page.py","file_name":"basket_page.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"240093370","text":"import argparse\nimport json\nimport os\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom PIL import Image\nfrom torch.utils.data import DataLoader\nimport torch.distributions as tdist\nfrom torch.optim.lr_scheduler import MultiStepLR\nfrom unet_model_ori import UNet\nfrom unet_attention_decouple import AttenUnet_style\nfrom data_utils import autoTrainSetRaw2jpgProcessed \nfrom exposure_module import ExposureNet\nfrom isp import isp\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"7\"\n\ndef load_checkpoint(checkpoint_path, model, optimizer):\n assert os.path.isfile(checkpoint_path)\n checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')\n iteration = checkpoint_dict['iteration']\n optimizer.load_state_dict(checkpoint_dict['optimizer'])\n model_for_loading = checkpoint_dict['model']\n model.load_state_dict(model_for_loading.state_dict())\n print(\"Loaded checkpoint '{}' (iteration {})\" .format(\n checkpoint_path, iteration))\n return model, optimizer, iteration\n\ndef save_checkpoint(model, net_type, optimizer, learning_rate, iteration, filepath, parallel):\n print(\"Saving model and optimizer state at iteration {} to {}\".format(\n iteration, filepath))\n if net_type == \"exposure\":\n model_for_saving = ExposureNet().cuda()\n if net_type == \"u_net\":\n model_for_saving = UNet(**network_config).cuda()\n if net_type == \"unet_att_style\":\n model_for_saving = AttenUnet_style(**network_config2).cuda()\n if parallel:\n model_for_saving = nn.DataParallel(model_for_saving)\n model_for_saving.load_state_dict(model.state_dict())\n torch.save({'model': model_for_saving,\n 'iteration': iteration,\n 'optimizer': optimizer.state_dict(),\n 'learning_rate': learning_rate}, filepath)\n\n\ndef save_training_images_raw(img_list, image_path, img_name, alpha):\n print(\"Saving output images\")\n b,c,h,w = img_list[0].shape\n batch_list = []\n for img in img_list:\n clip(img)\n tmp_batch = isp(img[0,:,:,:], img_name[0], data_config[\"file_list\"], alpha[0])\n for i in range(b-1): \n tmp_batch = np.concatenate((tmp_batch, isp(img[i+1,:,:,:], img_name[i+1], data_config[\"file_list\"], alpha[i+1])), axis=1)\n batch_list.append(tmp_batch)\n new_img_array = np.concatenate(batch_list, axis=2) * 255\n new_img = Image.fromarray(np.transpose(new_img_array, [1,2,0]).astype('uint8'), 'RGB')\n new_img.save(image_path, quality=95)\n\ndef clip(img):\n img[img>1] = 1\n img[img<0] = 0\n\ndef get_variance_map(input_raw, shot_noise, read_noise, mul=None):\n if not type(mul) == type(None):\n shot_noise = shot_noise * mul\n read_noise = read_noise * mul * mul\n b, c, h, w = input_raw.size()\n read_noise = torch.unsqueeze(read_noise, 2) \n read_noise = torch.unsqueeze(read_noise, 3) \n read_noise = read_noise.repeat(1,1,h,w)\n shot_noise = torch.unsqueeze(shot_noise, 2) \n shot_noise = torch.unsqueeze(shot_noise, 3) \n shot_noise = shot_noise.repeat(1,1,h,w)\n \n variance = torch.add(input_raw * shot_noise, read_noise)\n n = tdist.Normal(loc=torch.zeros_like(variance), scale=torch.sqrt(variance))\n noise = n.sample()\n var_map = input_raw + noise\n return var_map\n\ndef train(output_directory, epochs, learning_rate1, learning_rate2, learning_rate3, aperture,\n iters_per_checkpoint, batch_size, epoch_size, loss_type1, loss_type2, loss_type3,\n net_type, net_type_ap, seed, checkpoint_path1, checkpoint_path2, checkpoint_path3, residual_learning1,\n residual_learning2, parallel, variance_map, isp_save, multi_stage=None, multi_stage2=None):\n # set manual seed\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n\n # build exposure module\n model_exposure = ExposureNet().cuda()\n\n # build noise model\n if net_type == \"u_net\":\n model_noise = UNet(**network_config).cuda()\n else:\n print(\"unsupported network type\")\n return 0\n # build aperture model\n if aperture:\n if net_type_ap == \"unet_att_style\":\n model_aperture = AttenUnet_style(**network_config2).cuda()\n else:\n print(\"unsupported network type\")\n return 0\n\n\n if parallel:\n model_exposure = nn.DataParallel(model_exposure)\n model_noise = nn.DataParallel(model_noise)\n if aperture:\n model_aperture = nn.DataParallel(model_aperture)\n optimizer_1 = torch.optim.Adam(model_exposure.parameters(), lr=learning_rate1)\n optimizer_2 = torch.optim.Adam(model_noise.parameters(), lr=learning_rate2)\n scheduler_2 = MultiStepLR(optimizer_2, milestones=[20, 40], gamma=0.1)\n if aperture:\n optimizer_3 = torch.optim.Adam(model_aperture.parameters(), lr=learning_rate3)\n scheduler_3 = MultiStepLR(optimizer_3, milestones=[20, 40], gamma=0.1)\n\n # Load checkpoint if one exists\n iteration = 0\n\n if checkpoint_path1 != \"\":\n model_exposure, optimizer_1, iteration = load_checkpoint(checkpoint_path1, model_exposure, optimizer_1)\n if checkpoint_path2 != \"\":\n model_noise, optimizer_2, iteration = load_checkpoint(checkpoint_path2, model_noise,\n optimizer_2)\n if checkpoint_path3 !=\"\":\n model_aperture, optimizer_3, iteration = load_checkpoint(checkpoint_path3, model_aperture,\n optimizer_3)\n iteration += 1\n\n # build dataset\n trainset = autoTrainSetRaw2jpgProcessed(**data_config)\n epoch_size = min(len(trainset), epoch_size)\n train_sampler = torch.utils.data.RandomSampler(trainset, True, epoch_size) \n train_loader = DataLoader(trainset, num_workers=5, shuffle=False,\n sampler=train_sampler,\n batch_size=batch_size,\n pin_memory=False,\n drop_last=True)\n\n # Get shared output_directory ready\n if not os.path.isdir(output_directory):\n os.makedirs(output_directory)\n os.chmod(output_directory, 0o775)\n \n print(\"output directory\", output_directory)\n\n model_noise.train()\n model_exposure.train()\n if aperture:\n model_aperture.train()\n epoch_offset = max(0, int(iteration / len(train_loader)))\n\n # ================ MAIN TRAINNIG LOOP! ===================\n for epoch in range(epoch_offset, epochs):\n print(\"Epoch: {}\".format(epoch))\n for i, batch in enumerate(train_loader):\n model_exposure.zero_grad()\n model_noise.zero_grad()\n if aperture:\n model_aperture.zero_grad()\n\n exp_params, ap_params, noise_params, input_raw, input_jpg, output_raw, mask, \\\n input_shot_noise, input_read_noise, output_shot_noise, output_read_noise, \\\n img_name = batch\n if aperture:\n ap_params = torch.autograd.Variable(ap_params.cuda())\n exp_params = torch.autograd.Variable(exp_params.cuda())\n noise_params = torch.autograd.Variable(noise_params.cuda())\n input_shot_noise = torch.autograd.Variable(input_shot_noise.cuda())\n input_read_noise = torch.autograd.Variable(input_read_noise.cuda())\n output_shot_noise = torch.autograd.Variable(output_shot_noise.cuda())\n output_read_noise = torch.autograd.Variable(output_read_noise.cuda())\n mask = mask.cuda()\n\n \n input_raw = torch.autograd.Variable(input_raw.cuda())\n output_raw = torch.autograd.Variable(output_raw.cuda())\n\n # simple exposure correction\n output_exp, exp_params_m = model_exposure([exp_params, input_raw])\n # noise correction\n # Estimate variance map\n if variance_map:\n # input variance map\n variance_input = get_variance_map(output_exp, input_shot_noise, input_read_noise, exp_params_m)\n # output variance map (As long as the output iso is known, it can be estimated)\n input_cat = torch.cat([output_exp, variance_input], 1)\n if net_type == \"u_net\":\n output_ns = model_noise(input_cat)\n else:\n if net_type == \"u_net\":\n output_ns = model_noise(output_exp)\n \n\n #aperture module \n if aperture:\n output_ap = model_aperture([ap_params, output_ns+output_exp])\n\n # define exposure loss\n if loss_type1 == \"l1\":\n loss_f1 = torch.nn.L1Loss()\n elif loss_type1 == \"l2\":\n loss_f1 = torch.nn.MSELoss()\n\n loss1 = loss_f1(output_exp*mask, output_raw*mask)\n\n # define noise loss\n if loss_type2 == \"l1\":\n loss_f2 = torch.nn.L1Loss()\n elif loss_type2 == \"l2\":\n loss_f2 = torch.nn.MSELoss()\n\n if residual_learning1:\n loss2 = loss_f2(output_ns*mask, (output_raw-output_exp)*mask)\n else:\n loss2 = loss_f2(output_ns*mask, output_raw*mask)\n\n \n if aperture:\n if loss_type3 == \"l1\":\n loss_f3 = torch.nn.L1Loss()\n elif loss_type3 == \"l2\":\n loss_f3 = torch.nn.MSELoss()\n if residual_learning2:\n loss3 = loss_f3((output_exp+output_ns+output_ap)*mask, output_raw*mask)\n else:\n loss3 = loss_f3(output_ap*mask, output_raw*mask)\n\n if not multi_stage:\n loss1.backward(retain_graph=True)\n optimizer_1.step()\n loss2.backward(retain_graph=True)\n optimizer_2.step()\n if aperture:\n loss3.backward(retain_graph=True)\n optimizer_3.step()\n\n else:\n if not aperture:\n if epoch < multi_stage:\n loss1.backward(retain_graph=True)\n optimizer_1.step()\n else:\n loss2.backward(retain_graph=True)\n optimizer_2.step()\n else:\n if epoch < multi_stage:\n loss1.backward(retain_graph=True)\n optimizer_1.step()\n elif epoch >= multi_stage and epoch < multi_stage2:\n loss2.backward(retain_graph=True)\n optimizer_2.step()\n else:\n loss3.backward(retain_graph=True)\n optimizer_3.step()\n\n\n if aperture:\n print(\"epochs{} iters{}:\\t{:.9f}\\t{:.9f}\\t{:.9f}\".format(epoch, iteration, loss1, loss2, loss3))\n else:\n print(\"epochs{} iters{}:\\t{:.9f}\\t{:.9f}\".format(epoch, iteration, loss1, loss2))\n\n if (iteration % iters_per_checkpoint == 0):\n checkpoint_path1 = \"{}/exp_{}\".format(\n output_directory, iteration)\n checkpoint_path2 = \"{}/unet_{}\".format(\n output_directory, iteration)\n checkpoint_path3 = \"{}/unet_att_{}\".format(\n output_directory, iteration)\n image_path = \"{}/img_{}.jpg\".format(\n output_directory, iteration)\n # save checkpoints\n save_checkpoint(model_exposure, \"exposure\", optimizer_1, learning_rate1, iteration,\n checkpoint_path1, parallel)\n save_checkpoint(model_noise, net_type, optimizer_2, learning_rate2, iteration,\n checkpoint_path2, parallel)\n save_checkpoint(model_aperture, net_type_ap, optimizer_3, learning_rate3, iteration,\n checkpoint_path3, parallel)\n # save testing images\n if residual_learning1:\n if isp_save:\n if aperture:\n if residual_learning2:\n save_training_images_raw([input_raw.cpu().data.numpy(),\n output_exp.cpu().data.numpy(),\n (output_ns+output_exp).cpu().data.numpy(),\n (output_ap+output_ns+output_exp).cpu().data.numpy(),\n output_raw.cpu().data.numpy()], image_path, img_name, exp_params_m.cpu().data.numpy())\n else:\n save_training_images_raw([input_raw.cpu().data.numpy(),\n output_exp.cpu().data.numpy(),\n (output_ns+output_exp).cpu().data.numpy(),\n output_ap.cpu().data.numpy(),\n output_raw.cpu().data.numpy()], image_path, img_name, exp_params_m.cpu().data.numpy())\n else:\n save_training_images_raw([input_raw.cpu().data.numpy(),\n output_exp.cpu().data.numpy(),\n (output_ns+output_exp).cpu().data.numpy(), \n output_raw.cpu().data.numpy()], image_path, img_name, exp_params_m.cpu().data.numpy())\n \n iteration += 1\n if epoch > multi_stage2:\n scheduler_3.step()\n elif epoch > multi_stage:\n scheduler_2.step()\n \n \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--config', type=str,\n help='JSON file for configuration')\n args = parser.parse_args()\n global config_path \n config_path = args.config\n\n with open(config_path) as f:\n data = f.read()\n config = json.loads(data)\n train_config = config[\"train_config\"]\n global data_config\n data_config = config[\"data_config\"]\n global network_config\n network_config = config[\"network_config\"]\n global network_config2\n network_config2 = config[\"network_config2\"]\n\n torch.backends.cudnn.enabled = True\n torch.backends.cudnn.benchmark = False\n train(**train_config)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":14507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"466039178","text":"MAXNBITS = 10\nsumluck = 0\nsols = []\nMOD = 10e8 + 7\nfor nbits1 in xrange(1, MAXNBITS):\n base = 1 << nbits1\n add = 1\n for pos in xrange(nbits1):\n num = base + add\n \n add <<= 1 \n sumluck = (sumluck + num) % MOD\n sols.append((num, sumluck))\n \ndef solve(n):\n res = 0\n for k, v in sols:\n if k > n:\n return res\n res = v\n return -1\n \nfor i in xrange(input()) :\n print(solve(input()))\n \n \n","sub_path":"HackerEarth/maxnbits.py","file_name":"maxnbits.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"63983589","text":"import time\nimport calendar\nfrom datetime import datetime as dt\n\n# store hosts path in variable\nhosts_temp = \"/Users/chipcarnes/Projects/python-mega-course/website-blocker/hosts\"\nhosts_path = \"/etc/hosts\"\n\n# redirection\nredirect_path = \"127.0.0.1\"\n\nblocked_websites = [\n \"www.facebook.com\",\n \"facebook.com\",\n \"www.twitter.com\",\n \"twitter.com\",\n \"gmail.com\",\n \"www.gmail.com\",\n ]\n\n\nstart_time = dt(dt.now().year, dt.now().month, dt.now().day, 8)\nend_time = dt(dt.now().year, dt.now().month, dt.now().day, 16)\nday_name = calendar.day_name[dt.now().weekday()]\n\nwhile True:\n if start_time < dt.now() < end_time and day_name != \"Saturday\":\n print(\"Working hours...\")\n # access etc/hosts file\n with open(hosts_temp, 'r+') as file:\n content = file.read()\n for site in blocked_websites:\n #skip the line/file if the websites are already listed in the file.\n if site in content:\n pass\n else:\n # write to file if between 9am-5pm\n file.write(redirect_path + \" \" + site + \"\\n\")\n # check time every few seconds\n time.sleep(5)\n else:\n # This section erases the added blocked websites from the file.\n with open(hosts_temp, 'r+') as file:\n # store file lines into an array\n content = file.readlines()\n # return pointer to beginning of file\n file.seek(0)\n for line in content:\n # search each line for the text of the website\n if not any(website in line for website in blocked_websites):\n # if it doesn't find a website in the line, append the line from the array of lines\n # this appends a copy of the file, excluding all the websites, to the top of the file\n # pushing the lines containing the websites, furthern down in lines.\n file.write(line)\n # pointer is at end of the copied lines, but before the sections containing the websites\n # and truncate/delete everything after the pointer.\n file.truncate()\n print(\"Not business time!\")\n time.sleep(5)\n","sub_path":"blocker.py","file_name":"blocker.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"492671834","text":"\"\"\"REST API index.\"\"\"\nimport flask\nimport cv_whiteboarding\nfrom flask import Flask, request, render_template\n\nclass InvalidUsage(Exception):\n \"\"\"Invalid Usage Class.\"\"\"\n status_code = 400\n\n def __init__(self, message, status_code=None, payload=None):\n \"\"\"Init invalid usage.\"\"\"\n Exception.__init__(self)\n self.message = message\n if status_code is not None:\n self.status_code = status_code\n self.payload = payload\n\n def to_dict(self):\n \"\"\"Convert message to dict.\"\"\"\n r_v = dict(self.payload or ())\n r_v['message'] = self.message\n return r_v\n\n\n@cv_whiteboarding.app.errorhandler(InvalidUsage)\ndef handle_invalid_usage(error):\n \"\"\"Handle invalid usage.\"\"\"\n response = flask.jsonify(error.to_dict())\n response.status_code = error.status_code\n return response\n\n@cv_whiteboarding.app.route('/testapi/', methods=[\"GET\"])\ndef testapi():\n \"\"\"A handler for testing.\"\"\"\n # check_login()\n context = {\n \"test\": \"convo_starter_backend is running!\",\n }\n return flask.jsonify(**context)\n\n@cv_whiteboarding.app.route('/', methods=[\"GET\"])\ndef home():\n context = {}\n return render_template(\"index.html\")\n","sub_path":"cv_whiteboarding/backend/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"396415294","text":"import xml.etree.ElementTree as ET\nimport sqlite3\n\n# \"get\" will only get attribute name's text\n# \"find\" will find the text inside the tag that \"find\" is look for\n\n\nxmlFile = \"full database.xml\"\nstoreFile = \"store_file.txt\"\ntree = ET.parse(xmlFile)\nroot = tree.getroot()\nns = '{http://www.drugbank.ca}'\n\ndatabaseFile = \"test_drugbank.db\"\nconn = sqlite3.connect(databaseFile)\ncursor = conn.cursor()\n\ncursor.execute(\"drop table if exists drugbank_drug;\")\ncursor.execute(\"drop table if exists drugbank_transport;\")\ncursor.execute(\"drop table if exists drugbank_carrier\")\ncursor.execute(\"drop view if exists combine_;\")\ncursor.execute(\"drop view if exists transporter_carrier;\")\ncursor.execute(\"create table drugbank_drug (drug_id char(20), drug_type char(20), drug_name char(20),\\\n drug_state char(20), drug_group char(20), drug_smiles text, drug_InChIKey text, drug_IUPAC_Name text, \\\n ChEMBL_ID text,primary key (drug_id));\")\ncursor.execute(\"create table drugbank_transport (drug_id char(20), drug_transport_id char(20), drug_transport_name char(20),\\\n actions char(20), foreign key (drug_id) references drugbank_drug(drug_id));\")\ncursor.execute(\"create table drugbank_carrier (drug_id char(20), drug_carrier_id char(20), drug_carrier_name \\\n char(20), target_type char(20), foreign key (drug_id) references drugbank_drug(drug_id));\")\ncursor.execute(\"create table drugbank_enzyme (drug_id char(20), drug_enzyme_id char(20), drug_enzyme_name \\\n char(20), target_type char(20), foreign key (drug_id) references drugbank_drug(drug_id));\")\n\n\n\n\n# for child in root:\n# print(child.tag, child.attrib)\n# output: {http://www.drugbank.ca}drug {'type': 'small molecule', 'updated': '2017-12-20', 'created': '2017-12-18'}\n# for child in root.findall(ns+\"drug\"):\n# drug_type = child.get(\"type\")\n# drug_ID = child.find(ns+\"drugbank-id\").text\n# print(drug_type,drug_ID)\n# output: small molecule DB09229 (success)\n\nfor child in root.findall(ns+\"drug\"):\n \n drug_type = child.get(\"type\")\n drug_ID = child.find(ns+\"drugbank-id\").text\n drug_name = child.find(ns+\"name\").text\n \n drug_state = None\n if child.find(ns+\"state\") is not None:\n drug_state = child.find(ns+\"state\").text\n \n #get drug group\n drug_group2 = None\n if child.findall(ns+\"groups\") is not None:\n drug_group = child.findall(ns+\"groups\")\n for i in drug_group:\n if i.find(ns+\"group\").text == \"approved\":\n drug_group2 = i.find(ns+\"group\").text\n else:\n drug_group2 = \"unapproved\"\n else:\n drug_group2 = None\n\n #get the properties of smiles and InChIkey\n drug_smiles = None\n drug_InChIKey = None\n drug_IUPAC_Name = None \n ChEMBL_id = None\n if child.findall(ns+\"calculated-properties\") is not None:\n \n drug_calculated_properties = child.findall(ns+\"calculated-properties\")\n for properties in drug_calculated_properties:\n drug_properties = properties.findall(ns+\"property\")\n for single_property in drug_properties:\n if single_property.find(ns+\"kind\") is not None and single_property.find(ns+\"kind\").text == \"SMILES\":\n drug_smiles = single_property.find(ns+\"value\").text\n #print(drug_smiles)\n if single_property.find(ns+\"kind\") is not None and single_property.find(ns+\"kind\").text == \"InChIKey\":\n drug_InChIKey = single_property.find(ns+\"value\").text\n\n if single_property.find(ns+\"kind\") is not None and single_property.find(ns+\"kind\").text == \"IUPAC Name\":\n drug_IUPAC_Name = single_property.find(ns+\"value\").text\n drug_external_id = child.findall(ns+\"external-identifiers\")\n for external_id in drug_external_id:\n external_identifiers = external_id.findall(ns+\"external-identifier\")\n for target_identifiers in external_identifiers:\n if target_identifiers.find(ns+\"resource\") is not None and target_identifiers.find(ns+\"resource\").text == \"ChEMBL\":\n ChEMBL_id = target_identifiers.find(ns+\"identifier\").text\n\n else:\n drug_smiles = None\n drug_InChIKey = None\n drug_IUPAC_Name = None \n ChEMBL_id = None\n #print(drug_ID, drug_type, drug_name, drug_state,drug_group2,drug_smiles, drug_InChIKey)\n temp_tuple = (drug_ID,drug_type,drug_name,drug_state,drug_group2,drug_smiles,drug_InChIKey,drug_IUPAC_Name,ChEMBL_id)\n cursor.execute(\"insert into drugbank_drug values (?,?,?,?,?,?,?,?,?)\",temp_tuple)\n # print(temp_tuple)\n\n\n trasnport_id = None\n transport_name = None\n\n for transport in child.findall(ns+\"transporters\"):\n #transportNum = transport.get(\"position\").text\n \n for i in transport.findall(ns+\"transporter\"):\n transport_id = i.find(ns+\"id\").text\n transport_name = i.find(ns+\"name\").text\n #print(drug_ID,transport_id,transport_name)\n transport_actions = \"\"\n for j in i.findall(ns+\"actions\"):\n for k in j.findall(ns+\"action\"):\n transport_actions += \"|\"+str(k.text)\n transport_actions += \"|\"\n\n temp_tuple = (drug_ID, transport_id,transport_name, transport_actions)\n # print(temp_tuple)\n\n cursor.execute(\"insert into drugbank_transport values (?,?,?,?)\",temp_tuple)\n \n # create enzyme table \n\n for enzymes in child.findall(ns+\"enzymes\"):\n #transportNum = transport.get(\"position\").text\n \n for i in enzymes.findall(ns+\"enzyme\"):\n enzymes_id = i.find(ns+\"id\").text\n enzymes_name = i.find(ns+\"name\").text\n #print(drug_ID,transport_id,transport_name)\n enzymes_actions = \"\"\n for j in i.findall(ns+\"actions\"):\n for k in j.findall(ns+\"action\"):\n enzymes_actions += \"|\"+str(k.text)\n enzymes_actions += \"|\"\n\n temp_tuple = (drug_ID,enzymes_id,enzymes_name,enzymes_actions)\n # print(temp_tuple)\n\n cursor.execute(\"insert into drugbank_enzyme values (?,?,?,?)\",temp_tuple)\n\n # UniprotKB_ID = None\n # for external_identifiers in child.findall(ns+\"external-identifiers\"):\n # # print(external_identifiers.tag)\n # for i in external_identifiers.findall(ns+\"external-identifier\"):\n \n # if i.find(ns+\"resource\") is not None and i.find(ns+\"resource\").text == \"UniProtKB\":\n # UniprotKB_ID = i.find(ns+\"identifier\").text\n\n # print(drug_ID,transport_id,UniprotKB_ID, transport_name )\n\n # cursor.execute(\"insert into drugbank_transport values (?,?,?,?)\",temp_tuple)\n # for carriers in child.findall(ns+\"carriers\"):\n # for i in carriers.findall(ns+\"carrier\"):\n # carrier_id = i.find(ns+\"id\").text\n # carrier_name = i.find(ns+\"name\").text\n \n # temp_tuple = (drug_ID, carrier_id, carrier_name, \"carrier\")\n\n # cursor.execute(\"insert into drugbank_carrier values (?,?,?,?)\", temp_tuple)\n\n# # get combined dataset\n# cursor.execute(\"create view combine_ as select drug.drug_id, drug.drug_type,drug.drug_name,drug.drug_state,drug.drug_group,\\\n# transport.drug_transport_id,transport.drug_transport_name from drugbank_drug drug \\\n# left outer join drugbank_transport transport on drug.drug_id = transport.drug_id;\")\n# # cursor.execute(\"create view transporter_carrier as select drug_id as drug_id, drug_carrier_id as drug_target_id, \\\n# # drug_carrier_name as drug_target_name, target_type as target_type \\\n# # from drugbank_carrier union select * from drugbank_transport;\")\nconn.commit()\nconn.close()\n","sub_path":"Create_dataset_from_DB/drugbank_parse/drugbank_full_database_parse.py","file_name":"drugbank_full_database_parse.py","file_ext":"py","file_size_in_byte":7823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"620276472","text":"from typing import List\n# Definition for a binary tree node.\nclass 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 isSymmetric(self, root: TreeNode) -> bool:\n if not root:\n return True\n if not root.left and not root.right:\n return True\n \n def isMirror(t1: TreeNode, t2: TreeNode) -> bool:\n if not t1 and not t2:\n return True\n if not t1 or not t2:\n return False\n return (t1.val == t2.val) and isMirror(t1.right, t2.left) and isMirror(t1.left, t2.right)\n \n return isMirror(root, root)\n \ndef convert2TreeNode(nums: List[int]) -> TreeNode:\n nodes = []\n for num in nums:\n if str(num) == 'null' or num == None:\n nodes.append(None)\n else:\n node = TreeNode(num)\n nodes.append(node)\n if not nodes or len(nodes) == 0:\n return None\n curr = 0\n level = 0\n next_child = 2 ** level\n while next_child < len(nodes):\n for i in range(curr, curr + 2 ** level):\n if nodes[i]:\n nodes[i].left = nodes[next_child] if next_child < len(nodes) else None\n nodes[i].right = nodes[next_child + 1] if next_child + 1 < len(nodes) else None\n next_child += 2\n curr = i + 1\n level += 1\n return nodes[0]\n\nif __name__== '__main__':\n solution = Solution()\n\n nums = [1,2,2,3,4,4,3]\n ans = solution.isSymmetric(convert2TreeNode(nums))\n print(ans)","sub_path":"101. Symmetric Tree/solution3.py","file_name":"solution3.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"411493225","text":"import torch\nimport torchvision\nfrom torch.nn import Sigmoid\nimport numpy as np\n\nclass FastRCNN:\n\n def __init__(self):\n\n self.device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\n self.model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True).to(self.device)\n self.model.eval()\n\n\n def person_boxes(self, img):\n image_tensor = torch.from_numpy(img).to(self.device)\n image_tensor = torch.transpose(image_tensor, 0,2)\n image_tensor = torch.transpose(image_tensor, 1,2)\n image_tensor = image_tensor/255\n output = self.model([image_tensor])\n boxes = output[0]['boxes']\n labels = output[0]['labels']\n scores = output[0]['scores']\n person_boxes = []\n box_labels = []\n for i in range(labels.shape[0]):\n if scores[i] > 0.8 and labels[i] == 1:\n person_boxes.append(boxes[i])\n box_labels.append(\"Person: {}%\".format(round(float(scores[i])*100, 2)))\n return person_boxes, box_labels\n","sub_path":"src/boxes/fast_rcnn.py","file_name":"fast_rcnn.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"78489748","text":"import math\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nclass Statistics():\n def __init__(self,listOfVals):\n self.listOfVals = listOfVals\n\n def getList(self):\n return self.listOfVals\n\n def setListOfVals(self,newList):\n self.listOfVals = newList\n\n def plotData(self,yaxisLabel = \"Y-Axis\"):\n plt.plot(self.getList())\n plt.ylabel(yaxisLabel)\n plt.show()\n\n def plotDataMean(self,yaxisLabel = \"Y-Axis\"):\n meanList = []\n for i in range(0, len(self.getList())):\n meanList.append(self.arithmeticMean())\n plt.plot(self.getList(),self.getList(),'r--',self.getList(),meanList,'r--')\n plt.ylabel(yaxisLabel)\n plt.show()\n\n def rangeList(self):\n if(len(self.getList()) >0):\n maxVal = max(self.listOfVals)\n minVal = min(self.listOfVals)\n return maxVal-minVal\n else:\n return None\n\n def mode(self):\n statDict = {}\n modeValue = None\n if len(self.getList()) != 0:\n for index in self.getList():\n if index in statDict:\n currentCount = statDict.get(index)\n statDict[index] = currentCount+1\n else:\n statDict[index] = 1\n statList = sorted(statDict.items(), key= lambda kv:(kv[1],kv[0]))\n modeValue = statList[len(statDict)-1][0]\n return modeValue\n\n def median(self):\n length = len(self.getList())\n if(length != 0):\n if(length%2 == 0):\n middleIndex = int((length/2)-1)\n indexMed = self.getList()[middleIndex]\n indexMed2 = self.getList()[middleIndex+1]\n return (indexMed+indexMed2)/2\n else:\n position = math.ceil(length/2)-1\n return self.getList()[position]\n else:\n return None\n\n def arithmeticMean(self):\n if (len(self.listOfVals) > 0):\n total = 0\n for elements in self.listOfVals:\n total += elements\n length = len(self.listOfVals)\n return total/length\n else:\n return 0\n\n def geometricMean(self):\n length = len(self.listOfVals)\n if(length >0):\n total = 1\n for index in self.listOfVals:\n total *= index\n return total**(1/length)\n else:\n return 0\n\n def harmonicMean(self):\n if(0 in self.listOfVals or len(self.listOfVals) == 0):\n return None\n else:\n length = len(self.listOfVals)\n total = 0\n for index in self.listOfVals:\n total += (1/index)\n return length/total\n\n def meanAbsoluteDeviation(self):\n if(len(self.getList())!= 0):\n mean = self.arithmeticMean()\n total = 0\n for index in self.getList():\n total += abs(mean-index)\n return total/len(self.getList())\n else:\n None\n\n def variance(self,population=True):\n size = len(self.getList())\n if(size != 0):\n mean = self.arithmeticMean()\n total = 0\n for index in self.getList():\n total+=(mean-index)**2\n if(population):\n return total/size\n else:\n return total/(size-1)\n else:\n return None\n\n def standardDeviation(self,population=True):\n if(len(self.getList()) != 0):\n if(population):\n return self.variance()**(0.5)\n else:\n return self.variance(population=False)**(0.5)\n else:\n return None\n\n def chebyshevInequality(self):\n if(len(self.getList()) != 0):\n std = self.standardDeviation()\n if(std < 1):\n return None\n else:\n return 1- (1.0/std**2)\n else:\n return None\n\n def zscore(self):\n zdict = {}\n if len(self.getList()) != 0 and len(self.getList()) != 1:\n if(self.standardDeviation() != 0):\n for i in self.getList():\n zdict[i]= (i - self.arithmeticMean()) / self.standardDeviation()\n return zdict\n else:\n return None\n elif len(self.getList()) == 1:\n return {self.getList()[0]:0}\n else:\n return None\n\n def correlationCoefficient(self):\n length = len(self.getList())\n if(length>1):\n xlist = []\n for i in range(1,length+1):\n xlist.append(i)\n defaultX = Statistics(xlist)\n if(self.zscore() != None):\n zscoreX = list(defaultX.zscore().values())\n zscoreY = []\n for value in self.getList():\n zscoreY.append(self.zscore().get(value))\n #zscoreY = list(self.zscore().values())\n sum = 0\n for i in range(0,len(zscoreX)):\n sum+= zscoreX[i]*zscoreY[i]\n return sum/(length)\n else:\n return 0\n elif(length ==1):\n return 0\n else:\n return None\n\n","sub_path":"com/project/src/PythonCrashCourse/DataScience/Statistics.py","file_name":"Statistics.py","file_ext":"py","file_size_in_byte":5307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"618823616","text":"import json\nimport os\n\nfrom flask import Blueprint, render_template, flash, request, url_for, g, make_response\nfrom flask_api.status import HTTP_200_OK, HTTP_404_NOT_FOUND, HTTP_403_FORBIDDEN, HTTP_401_UNAUTHORIZED\nfrom flask_wtf import FlaskForm\nfrom werkzeug.utils import redirect\nfrom wtforms import SubmitField, IntegerField\nfrom wtforms.validators import DataRequired\n\nfrom config import Config\nfrom gui.gui_utils import (find_animal_helper, like_animal_helper, list_animal_helper, update_access_token,\n set_response_cookie)\n\nbp = Blueprint('animals', __name__)\n\n\nclass FindAnimalForm(FlaskForm):\n animal_id = IntegerField('Идентификатор животного:',\n validators=[DataRequired(\"Пожалуйста, введите корректный идентификатор\")])\n submit = SubmitField('Найти')\n\n\nclass LikeAnimalForm(FlaskForm):\n submit = SubmitField('Мне нравится')\n\n\n@bp.route('/animals', methods=['GET', 'POST'])\ndef animals_all():\n if request.method == 'POST':\n size = request.form[\"size\"]\n return redirect(url_for('animals.animals_all', page=1, size=size))\n\n page = request.args.get('page', type=int, default=1)\n size = request.args.get('size', type=int, default=5)\n\n if page <= 0 or size <= 0:\n page = 1\n size = 5\n\n response = list_animal_helper(page, size)\n\n if response.status_code == HTTP_200_OK:\n animals = json.loads(response.content)\n prev_url = None\n next_url = None\n if animals is not None:\n if page > 1:\n prev_response = list_animal_helper(page - 1, size)\n if prev_response.status_code == HTTP_200_OK:\n prev_url = url_for('animals.animals_all', page=page - 1, size=size)\n\n next_response = list_animal_helper(page + 1, size)\n if next_response.status_code == HTTP_200_OK:\n next_url = url_for('animals.animals_all', page=page + 1, size=size)\n\n return render_template('animals/animals_all.html',\n animals=animals['animals'],\n prev_url=prev_url,\n next_url=next_url)\n else:\n flash('Неизвестная ошибка', 'danger')\n return render_template('animals/animals_all.html')\n else:\n if response.status_code == HTTP_404_NOT_FOUND:\n flash('База данных животных пуста', 'danger')\n return render_template('animals/animals_all.html')\n try:\n flash(json.loads(response.data), 'danger')\n except:\n flash('Неизвестная ошибка', 'danger')\n return render_template('animals/animals_all.html')\n\n\n@bp.route('/animals/find', methods=['GET', 'POST'])\ndef animal_find():\n find_animal_form = FindAnimalForm()\n if request.method == 'GET':\n return render_template('animals/animal_find.html',\n form=find_animal_form,\n found=False)\n\n if request.method == 'POST':\n if not find_animal_form.validate_on_submit():\n return render_template('animals/animal_find.html',\n form=find_animal_form,\n found=False)\n\n animal_id = request.form[\"animal_id\"]\n response = find_animal_helper(animal_id)\n\n if response.status_code == HTTP_200_OK:\n return redirect(url_for('animals.animal_info', animal_id=str(animal_id)))\n if response.status_code == HTTP_404_NOT_FOUND:\n flash('Животное не найдено', 'danger')\n return redirect(url_for('animals.animal_find'))\n else:\n try:\n flash(json.loads(response.data), 'danger')\n except:\n flash('Неизвестная ошибка', 'danger')\n return redirect(url_for('animals.animal_find'))\n\n\n@bp.route('/animals/', methods=['GET', 'POST'])\ndef animal_info(animal_id):\n like_animal_btn = LikeAnimalForm()\n\n if request.method == 'GET':\n response = find_animal_helper(animal_id)\n if response.status_code == HTTP_200_OK:\n animal = json.loads(response.content)\n\n if os.path.isfile(Config.GUI_IMAGES_PATH + 'animal_' + str(animal['id']) + '.jpg'):\n image_path = 'images/animal_' + str(animal['id']) + '.jpg'\n else:\n image_path = 'images/no_image.jpg'\n\n return render_template('animals/animal_info.html',\n title='Подробная информация о животном',\n animal=animal,\n image_path=image_path,\n button=like_animal_btn)\n if response.status_code == HTTP_404_NOT_FOUND:\n flash('Животное с указанным идентификатором не существует', 'danger')\n return redirect(url_for('animals.animal_find'))\n else:\n try:\n flash(json.loads(response.data), 'danger')\n except:\n flash('Неизвестная ошибка', 'danger')\n return redirect(url_for('animals.animal_find'))\n\n if request.method == 'POST':\n if not g.is_authorized:\n flash('Нужно авторизоваться, чтобы продолжить', 'info')\n return redirect(url_for('users.auth'))\n\n response = like_animal_helper(g.login, animal_id)\n\n access_token = None\n if response.status_code == HTTP_403_FORBIDDEN:\n access_token = update_access_token()\n if access_token:\n response = like_animal_helper(g.login, animal_id, access_token)\n\n if response.status_code == HTTP_200_OK:\n flash('Популярность животного успешно увеличена', 'success')\n response = make_response(redirect(url_for('animals.animal_info', animal_id=str(animal_id))))\n return set_response_cookie(response, access_token)\n else:\n if response.status_code in [HTTP_403_FORBIDDEN, HTTP_401_UNAUTHORIZED]:\n flash('Нужно авторизоваться, чтобы продолжить', 'info')\n response = make_response(redirect(url_for('users.logout')))\n return response\n try:\n flash(json.loads(response.data), 'danger')\n except:\n flash('Неизвестная ошибка', 'danger')\n response = make_response(redirect(url_for('animals.animal_info', animal_id=str(animal_id))))\n return set_response_cookie(response, access_token)\n","sub_path":"gui/routes/animals_routes.py","file_name":"animals_routes.py","file_ext":"py","file_size_in_byte":6912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"167545132","text":"from masonite.request import Request\nfrom masonite.auth.Sign import Sign\nfrom cryptography.fernet import Fernet\n\nwsgi_request = {\n 'wsgi.version': (1, 0),\n 'wsgi.multithread': False,\n 'wsgi.multiprocess': True,\n 'wsgi.run_once': False,\n 'SERVER_SOFTWARE': 'gunicorn/19.7.1',\n 'REQUEST_METHOD': 'GET',\n 'QUERY_STRING': 'application=Masonite',\n 'RAW_URI': '/',\n 'SERVER_PROTOCOL': 'HTTP/1.1',\n 'HTTP_HOST': '127.0.0.1:8000',\n 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'HTTP_UPGRADE_INSECURE_REQUESTS': '1',\n 'HTTP_COOKIE': '',\n 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7',\n 'HTTP_ACCEPT_LANGUAGE': 'en-us',\n 'HTTP_ACCEPT_ENCODING': 'gzip, deflate',\n 'HTTP_CONNECTION': 'keep-alive',\n 'wsgi.url_scheme': 'http',\n 'REMOTE_ADDR': '127.0.0.1',\n 'REMOTE_PORT': '62241',\n 'SERVER_NAME': '127.0.0.1',\n 'SERVER_PORT': '8000',\n 'PATH_INFO': '/',\n 'SCRIPT_NAME': ''\n}\n\nSECRET_KEY = 'pK1tLuZA8-upZGz-NiSCP_UVt-fxpxd796TaG6-dp8Y='\nREQUEST = Request(wsgi_request).key(SECRET_KEY)\n\n\ndef test_set_and_get_cookie():\n REQUEST.cookie('test', 'testvalue')\n assert REQUEST.get_cookie('test') == 'testvalue'\n\n\ndef test_set_and_get_multiple_cookies():\n REQUEST.cookie('cookie1', 'cookie1value')\n REQUEST.cookie('cookie2', 'cookie2value')\n\n assert REQUEST.get_cookie('cookie1') == 'cookie1value'\n assert REQUEST.get_cookie('cookie2') == 'cookie2value'\n\n\ndef test_set_cookie_without_encryption():\n REQUEST.cookie('notencrypted', 'value', False)\n\n assert REQUEST.get_cookie('notencrypted', False) == 'value'\n\n\ndef test_set_and_get_cookie_with_no_existing_cookies():\n REQUEST.environ['HTTP_COOKIE'] = ''\n REQUEST.cookie('test', 'testvalue')\n assert REQUEST.get_cookie('test') == 'testvalue'\n\n\ndef test_set_and_get_cookie_with_existing_cookie():\n REQUEST.environ['HTTP_COOKIE'] = 'cookie=true'\n REQUEST.cookie('test', 'testvalue')\n assert REQUEST.get_cookie('test') == 'testvalue'\n","sub_path":"tests/test_cookie_signing.py","file_name":"test_cookie_signing.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"576862231","text":"# Copyright 2016, ChinaNetCenter Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport logging\n\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import string_concat # noqa\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom horizon import exceptions\nfrom horizon import forms\nfrom horizon import tables\n\nfrom neutronclient.common.exceptions import Conflict\n\nfrom openstack_dashboard import api\nfrom openstack_dashboard.usage import quotas\n\nLOG = logging.getLogger(__name__)\n\n\nclass LaunchLink(tables.LinkAction):\n name = \"launch\"\n verbose_name = _(\"Launch Load Balancer\")\n url = \"horizon:network:loadbalancersv2:launch\"\n classes = (\"btn-launch\", \"ajax-modal\")\n policy_rules = ((\"network\", \"create_loadbalancer\"),)\n\n def allowed(self, request, datum):\n usages = quotas.tenant_quota_loadbalancer_usages(request)\n if usages['loadbalancer']['available'] <= 0:\n if \"disabled\" not in self.classes:\n self.classes = [c for c in self.classes] + ['disabled']\n self.verbose_name = string_concat(self.verbose_name, ' ',\n _(\"(Load balancer\"\n \" quota exceeded)\"))\n else:\n self.verbose_name = _(\"Launch Load Balancer\")\n classes = [c for c in self.classes if c != \"disabled\"]\n self.classes = classes\n\n return True\n\n\nclass TerminateLoadBalancer(tables.BatchAction):\n name = \"terminate\"\n action_present = _(\"Terminate\")\n action_past = _(\"Terminated\")\n data_type_singular = _(\"Load Balancer\")\n data_type_plural = _(\"Load Balancers\")\n classes = ('btn-danger', 'btn-terminate')\n policy_rules = ((\"network\", \"delete_loadbalancer\"),)\n redirect_url = 'horizon:network:loadbalancersv2:index'\n\n def allowed(self, request, loadbalancer=None):\n return True\n\n def action(self, request, obj_id):\n try:\n api.lbaasv2.loadbalancer_delete(request, obj_id)\n except Conflict:\n msg = _('There have been some listeners using this loadbalancer.')\n redirect = reverse(self.redirect_url)\n exceptions.handle(request, msg, redirect=redirect)\n except Exception as e:\n LOG.error('Failed to delete loadbalancer: %s' % e.message)\n msg = _('Failed to delete loadbalancer.')\n redirect = reverse(self.redirect_url)\n exceptions.handle(request, msg, redirect=redirect)\n\n\nclass AssociateFloatingIP(tables.LinkAction):\n name = \"associate_fip\"\n verbose_name = _(\"Associate Floating IP\")\n url = \"horizon:network:loadbalancersv2:associate\"\n classes = (\"ajax-modal\", \"btn-edit\")\n policy_rules = ((\"network\", \"associate_floating_ip\"),)\n\n def allowed(self, request, datum=None):\n if not datum or \\\n not datum.provisioning_status == \"ACTIVE\":\n return False\n\n admin_state = getattr(datum, 'admin_state_up', True)\n if not admin_state:\n return False\n\n if datum.public_ip:\n return False\n\n return True\n\n\nclass DisassociateFloatingIP(tables.BatchAction):\n name = \"disassociate_fip\"\n verbose_name = _(\"Disassociate Floating IP\")\n classes = ('btn-danger',)\n action_present = _(\"Disassociate\")\n action_past = _(\"Disassociated\")\n data_type_singular = _(\"Floating IP\")\n policy_rules = ((\"network\", \"disassociate_floating_ip\"),)\n failure_url = 'horizon:network:loadbalancersv2:index'\n success_url = 'horizon:network:loadbalancersv2:index'\n\n def action(self, request, obj_id):\n obj = self.table.get_object_by_id(obj_id)\n try:\n floatingips = api.neutron.FloatingIpManager(request).\\\n list(floating_ip_address=obj.public_ip)\n api.neutron.FloatingIpManager(request).\\\n disassociate(floatingips[0]['id'], None)\n except Exception as e:\n msg = _('Failed to disassociate floating IP.')\n LOG.error('Failed to disassociate floating ip: %s' % e.message)\n redirect = reverse(self.failure_url)\n exceptions.handle(request, msg, redirect=redirect)\n\n def get_success_url(self, request):\n return reverse(self.success_url)\n\n def allowed(self, request, datum=None):\n if datum.public_ip:\n return True\n\n return False\n\n\nclass UpdateRow(tables.Row):\n ajax = True\n\n def get_data(self, request, lb_id):\n try:\n loadbalancer = api.lbaasv2.loadbalancer_get(request, lb_id)\n except Exception as e:\n msg = _('Unable to get load balancer.')\n LOG.error('Unable to get load balancer: %s' % e.message)\n exceptions.handle(request, msg, ignore=True)\n\n return loadbalancer\n\n\nSTATUS_CHOICES = (\n (_(\"active\"), True),\n (_(\"fault\"), False),\n)\n\n\nSTATUS_DISPLAY_CHOICES = (\n (\"PENDING_CREATE\", _(\"pending create\")),\n (\"PENDING_UPDATE\", _(\"pending update\")),\n (\"PENDING_DELETE\", _(\"pending delete\")),\n (\"ACTIVE\", _(\"active\")),\n (\"ERROR\", _(\"fault\")),\n)\n\n\nNET_TYPE_DISPLAY_CHOICES = (\n (\"0\", _(\"private net\")),\n (\"1\", _(\"shared net\")),\n)\n\n\nclass LoadBalancerFilterAction(tables.FilterAction):\n\n def filter(self, table, loadbalancers, filter_string):\n \"\"\"Naive case-insensitive search.\"\"\"\n q = filter_string.lower()\n return [loadbalancer for loadbalancer in loadbalancers\n if q in loadbalancer.name.lower()]\n\n\nclass UpdateCell(tables.UpdateAction):\n policy_rules = ((\"network\", \"update_lb_name\"),)\n\n def allowd_action(self, request, loadbalancer, cell):\n status = getattr(loadbalancer, \"provisioning_status\", None)\n if status == 'PENDING_DELETE':\n return False\n return True\n\n def update_cell(self, request, datum, loadbalancer_id,\n cell_name, new_cell_value):\n try:\n api.lbaasv2.loadbalancer_update(\n request, loadbalancer_id, name=new_cell_value\n )\n except Exception:\n exceptions.handle(request, ignore=True)\n return False\n return True\n\n\nclass LoadBalancersTable(tables.DataTable):\n lb_id = tables.Column(\"id\",\n link=(\"horizon:network:loadbalancersv2:detail\"),\n verbose_name=_(\"ID\"))\n\n msg = _(\"Name must consist of number, letter or underscore.\")\n name = tables.Column(\"name\", verbose_name=_(\"Name\"),\n form_field=forms.RegexField(\n max_length=30, regex=r\"^[a-zA-Z0-9_-]+$\",\n help_text=msg,\n error_messages={\"invalid\": msg},\n required=True),\n update_action=UpdateCell)\n\n status = tables.Column(\"provisioning_status\",\n status=True,\n status_choices=STATUS_CHOICES,\n display_choices=STATUS_DISPLAY_CHOICES,\n verbose_name=_(\"Provisioning Status\"))\n\n net_type = tables.Column(\"net_type\",\n display_choices=NET_TYPE_DISPLAY_CHOICES,\n verbose_name=_(\"Network Type\"))\n\n vip = tables.Column(\"vip_address\",\n verbose_name=_(\"VIP\"))\n\n public_ip = tables.Column(\"public_ip\",\n verbose_name=_(\"Pubic IP\"))\n\n class Meta(object):\n name = \"loadbalancersv2\"\n verbose_name = _(\"Load Balancers\")\n status_columns = [\"status\"]\n row_class = UpdateRow\n table_actions = (LaunchLink, LoadBalancerFilterAction)\n row_actions = (AssociateFloatingIP, DisassociateFloatingIP,\n TerminateLoadBalancer)\n","sub_path":"horizon/openstack_dashboard/dashboards/network/loadbalancersv2/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":8363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"132478347","text":"#!/usr/bin/python\nimport json\nimport socket\nimport os\nimport sys\n\ndef nodesInsert(idx,ipaddr):\n print(idx,ipaddr)\n arr_nodes='{\"node\":{\"hostnames\":{},\"zone\":1},\"devices\":[{\"name\":\"/dev/sdb\",\"destroydata\": false},{\"name\":\"/dev/sdc\",\"destroydata\": false}]}'\n dict_nodes=json.loads(arr_nodes)\n dict_cluster[\"clusters\"][0][\"nodes\"].append(dict_nodes)\n arr_hostnames='{\"manage\": [\"'+ipaddr[0]+'\"], \"storage\": [\"'+ipaddr[2][0]+'\"]}'\n dict_hostnames=json.loads(arr_hostnames)\n dict_cluster[\"clusters\"][0][\"nodes\"][idx][\"node\"][\"hostnames\"]=dict_hostnames\n\nfnTopology = \"/tmp/aaa.json\"\nif os.path.isfile(fnTopology):\n with open(fnTopology) as json_file: \n dict_cluster = json.load(json_file)\nelse:\n arr_cluster='{\"clusters\": [{\"nodes\": []}]}'\n dict_cluster=json.loads(arr_cluster)\n\nidx=len(dict_cluster['clusters'][0]['nodes'])\nipaddr = socket.gethostbyname_ex(sys.argv[1])\narr_nodes='{\"node\":{\"hostnames\":{},\"zone\":1},\"devices\":[{\"name\":\"/dev/sdb\",\"destroydata\": false},{\"name\":\"/dev/sdc\",\"destroydata\": false}]}'\ndict_nodes=json.loads(arr_nodes)\ndict_cluster[\"clusters\"][0][\"nodes\"].append(dict_nodes)\narr_hostnames='{\"manage\": [\"'+ipaddr[0]+'\"], \"storage\": [\"'+ipaddr[2][0]+'\"]}'\ndict_hostnames=json.loads(arr_hostnames)\ndict_cluster[\"clusters\"][0][\"nodes\"][idx][\"node\"][\"hostnames\"]=dict_hostnames\n\n#print(json.dumps(dict_cluster, indent = 4, sort_keys=True))\n\n#pp.pprint(dict_cluster)\nwith open(fnTopology , 'w') as outfile:\n json.dump(dict_cluster, outfile, indent=2)\n\n","sub_path":"util/cwk01.py","file_name":"cwk01.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"359019304","text":"import numpy as np\r\nimport sys\r\nimport cv2\r\nimport PIL\r\nfrom PIL import ImageGrab, ImageQt, ImageFilter, ImageEnhance\r\n# from PIL.ImageQt import ImageQt\r\n\r\nfrom PyQt5 import QtWidgets, QtCore, QtGui\r\n# from PyQt5.QtCore import Qt\r\nfrom screeninfo import get_monitors\r\nimport main \r\n\r\nclass MainWindow(QtWidgets.QMainWindow):\r\n def __init__(self, parent=None, monitor_number=None, screen_width=None, screen_height=None, shot=None):\r\n # TODO Change monitor variables to *args, maybe\r\n super().__init__(parent)\r\n # QtWidgets.QMainWindow.__init__(self, parent) probably not needed\r\n\r\n self.monitor_number = int(monitor_number) - 1 #Qt is starting reading screen number from 0\r\n self.screen_width = int(screen_width)\r\n self.screen_height = int(screen_height)\r\n self.shot = shot\r\n # no idea why it is here\r\n # self.screenshot_tool_widget = Screenshot_tool(parent=self)\r\n # self.setCentralWidget(self.screenshot_tool_widget)\r\n\r\n self.starter()\r\n\r\n def starter(self):\r\n self.setGeometry(0, 0, self.screen_width, self.screen_height)\r\n # self.setWindowTitle(' ')\r\n self.begin = QtCore.QPoint()\r\n self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)\r\n self.setWindowFlags(QtCore.Qt.FramelessWindowHint) #no title bar\r\n # self.setWindowOpacity(0.3) window transparency\r\n self.monitor = QtWidgets.QDesktopWidget().screenGeometry(self.monitor_number)\r\n self.move(self.monitor.left(), self.monitor.top())\r\n # self.shot = self.shot.point(lambda p: p * 0.9)\r\n # # ImageFilter.GaussianBlur(radius=2) \r\n # self.shot = self.shot.filter(ImageFilter.GaussianBlur(radius=1))\r\n # enhancer = ImageEnhance.Contrast(self.shot)\r\n # self.shot = enhancer.enhance(4.0)\r\n\r\n self.qimage = ImageQt.ImageQt(self.shot)\r\n\r\n label = QtWidgets.QLabel(self)\r\n pixmap = QtGui.QPixmap.fromImage(self.qimage)\r\n label.setPixmap(pixmap)\r\n self.setCentralWidget(label)\r\n\r\n QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.CrossCursor))\r\n\r\n self.show()\r\n\r\n def keyPressEvent(self, event): #q for exit\r\n if event.key() == QtCore.Qt.Key_Q:\r\n # print('Quit')\r\n self.close()\r\n event.accept()\r\n\r\n def mousePressEvent(self, event):\r\n self.start = event.pos()\r\n # print(main.widget.INSTANCES)\r\n print(self.start)\r\n # self.end = self.start\r\n self.update()\r\n\r\n def mouseMoveEvent(self, event):\r\n self.end = event.pos()\r\n print(self.end)\r\n self.update()\r\n\r\n\r\n\r\n\r\n\r\n# class Screenshot_tool(QtWidgets.QWidget):\r\n# def __init__(self, parent=None):\r\n# super().__init__(parent)\r\n# QtWidgets.QWidget.__init__(self, parent)\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n monitors_resolution = []\r\n def monitors_info():\r\n for i, monitor_data in enumerate(get_monitors()):\r\n splited = str(monitor_data).split(',')\r\n monitor = [str(splited[-1].split('DISPLAY')[-1].split(\"'\")[0]),\r\n str(splited[-3].split('=')[-1]),\r\n str(splited[-2].split('=')[-1])]\r\n \r\n monitors_resolution.append(monitor)\r\n\r\n monitors_info()\r\n print(monitors_resolution)\r\n\r\n app = QtWidgets.QApplication(sys.argv)\r\n\r\n instance = MainWindow(monitor_number=monitors_resolution[0][0], #ScreenshotWidget\r\n screen_width=monitors_resolution[0][1], \r\n screen_height=monitors_resolution[0][2])\r\n\r\n # instance.show()\r\n sys.exit(app.exec_()) \r\n","sub_path":"make_screenshot.py","file_name":"make_screenshot.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"116722501","text":"#!/usr/bin/python\n\nimport math\n\ndef recipe_batches(recipe, ingredients):\n missing = [ingredient for ingredient in recipe.keys() if ingredient not in ingredients.keys()]\n\n if len(missing) > 0:\n return 0\n\n whole_amounts = []\n for i in recipe:\n whole_amounts.append(math.floor(ingredients[i]/recipe[i]))\n\n return min(whole_amounts)\n\n\nif __name__ == '__main__':\n # Change the entries of these dictionaries to test \n # your implementation with different inputs\n recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }\n ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }\n print(\"{batches} batches can be made from the available ingredients: {ingredients}.\".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))","sub_path":"recipe_batches/recipe_batches.py","file_name":"recipe_batches.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"428455693","text":"import tensorflow as tf \nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# classification 分类器\n\nmnist = input_data.read_data_sets('MNIST_data', one_hot=True)\n\ndef add_layer(inputs, in_size, out_size, activation_function=None):\n Weights = tf.Variable(tf.random_normal([in_size, out_size]))\n biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)\n Wx_plus_b = tf.matmul(inputs, Weights) + biases\n if activation_function is None:\n outputs = Wx_plus_b\n else:\n outputs = activation_function(Wx_plus_b)\n return outputs\n\ndef compute_accuracy(v_xs, v_ys):\n global prediction\n # 预测y的值\n y_pre = sess.run(prediction, feed_dict={xs: v_xs})\n # 预测的y值和真是值之间的差别\n correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))\n # 计算这组数据中多少是对的,多少时错的\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n # 返回百分比\n result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})\n return result\n\n\n# 每张图片的分辨率是28×28,���以我们的训练网络输入应该是28×28=784个像素数据。\nxs = tf.placeholder(tf.float32, [None, 784]) # 28x28\n\n# 每张图片都表示一个数字,所以我们的输出是数字0到9,共10类。\nys = tf.placeholder(tf.float32, [None, 10])\n\n# 添加输出层 输入为xs, 输入数据784个特征, 输出数据10个特征,激励函数为softmax \nprediction = add_layer(xs, 784, 10, activation_function=tf.nn.softmax)\n\n# 预测值和真实值间的误差\n# loss函数(即最优化目标函数)选用交叉熵函数。\n# 交叉熵用来衡量预测值和真实值的相似程度,如果完全相同,它们的交叉熵等于零。\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1])) # loss\n\n# train方法(最优化算法)采用梯度下降法。\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\n\n# 进行训练\nfor i in range(1000):\n # 每次选取100张图片进行训练\n batch_xs, batch_ys = mnist.train.next_batch(100)\n sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})\n\n # 每50次输出训练精度\n if i%50 == 0:\n print(compute_accuracy(mnist.test.images, mnist.test.labels))\n","sub_path":"09_classification.py","file_name":"09_classification.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"582231011","text":"from classes import *\n\n\ncircle = Circle(1, 2, 8)\nsquare = Square(4, 4)\ntriangle = Triangle(5, 5, 5)\nb = [circle, square, triangle]\ns = []\nfor i in b:\n s.append(i.area())\nprint(s)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"440495975","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# (C) 2013 Pengkui Luo \n# Created 06/19/2013, updated 08/19/2013\n#\n\"\"\" List of DNSBL services or DNS based antivirus services.\n\"\"\"\n__all__ = [\n 'is_dnsbl_service',\n 'is_dnsav_service',\n 'is_dnsblav_service',\n]\nprint('Executing %s' % __file__)\n\nimport os, sys, time\ntry: import cPickle as pickle\nexcept: import pickle\n\nfrom netutils import publicsuffix\n\nPATH = os.path.join(os.path.dirname(__file__), '@data')\n\ndnsav_suffixset = set(w.strip() for w in\n open(os.path.join(PATH, 'dnsav_suffixes.@r.txt')) if not w.startswith('#'))\n\ndnsbl_suffixset = set(w.strip() for w in\n open(os.path.join(PATH, 'dnsbl_suffixes.@r.txt')) if not w.startswith('#'))\n\n\ndef is_dnsav_service (domain):\n for suffix in dnsav_suffixset:\n if domain.endswith(suffix):\n return True\n return False\n\ndef is_dnsbl_service (domainstruct):\n assert isinstance(domainstruct, publicsuffix.DomainStruct)\n if not domainstruct.isFQDN:\n return False\n #if t2ld in dnsbl_suffixset or t3ld in dnsbl_suffixset:\n for eT23LD in domainstruct.eTkLD[1:3]:\n if eT23LD in dnsbl_suffixset:\n return True\n return False\n\ndef is_dnsblav_service (domainstruct):\n assert isinstance(domainstruct, publicsuffix.DomainStruct)\n if (is_dnsav_service(domainstruct.domain)\n or is_dnsbl_service(domainstruct)\n ): return True\n else: return False\n\n\nif __name__ == '__main__':\n t0 = time.time()\n print('Done. Time elapsed: %.2f.' % (time.time() - t0))\n","sub_path":"services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"152507455","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nThis experiment was created using PsychoPy2 Experiment Builder (v1.79.01), Tue Dec 19 17:23:10 2017\nIf you publish work using this script please cite the relevant PsychoPy publications\n Peirce, JW (2007) PsychoPy - Psychophysics software in Python. Journal of Neuroscience Methods, 162(1-2), 8-13.\n Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy. Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008\n\"\"\"\n\nfrom __future__ import division # so that 1/3=0.333 instead of 1/3=0\nfrom psychopy import locale_setup, visual, core, data, event, logging, sound, gui\nfrom psychopy.constants import * # things like STARTED, FINISHED\nimport numpy as np # whole numpy lib is available, prepend 'np.'\nfrom numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray\nfrom numpy.random import random, randint, normal, shuffle\nimport os # handy system and path functions\nimport sys # to get file system encoding\n\n# Ensure that relative paths start from the same directory as this script\n_thisDir = os.path.dirname(os.path.abspath(__file__)).decode(sys.getfilesystemencoding())\nos.chdir(_thisDir)\n\n# Store info about the experiment session\nexpName = u'PlanetPractice_StripedGo' # from the Builder filename that created this script\nexpInfo = {u'session': u'prac', u'participant': u'PP'}\ndlg = gui.DlgFromDict(dictionary=expInfo, title=expName)\nif dlg.OK == False: core.quit() # user pressed cancel\nexpInfo['date'] = data.getDateStr() # add a simple timestamp\nexpInfo['expName'] = expName\n\n# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc\nfilename = _thisDir + os.sep + u'data' + os.sep + '%s_%s' %(expInfo['participant'], expInfo['date'])\n\n# An ExperimentHandler isn't essential but helps with data saving\nthisExp = data.ExperimentHandler(name=expName, version='',\n extraInfo=expInfo, runtimeInfo=None,\n originPath=u'/Users/Katie/Dropbox/Planets/ForGithub/PracticeTask/PlanetPractice_StripedGo.psyexp',\n savePickle=True, saveWideText=True,\n dataFileName=filename)\n#save a log file for detail verbose info\nlogFile = logging.LogFile(filename+'.log', level=logging.EXP)\nlogging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file\n\nendExpNow = False # flag for 'escape' or other condition => quit the exp\n\n# Start Code - component code to be run before the window creation\n\n# Setup the Window\nwin = visual.Window(size=(1280, 800), fullscr=True, screen=0, allowGUI=False, allowStencil=False,\n monitor='testMonitor', color=[-1,-1,-1], colorSpace='rgb',\n blendMode='avg', useFBO=True,\n units='deg')\n# store frame rate of monitor if we can measure it successfully\nexpInfo['frameRate']=win.getActualFrameRate()\nif expInfo['frameRate']!=None:\n frameDur = 1.0/round(expInfo['frameRate'])\nelse:\n frameDur = 1.0/60.0 # couldn't get a reliable measure so guess\n\n# Initialize components for Routine \"directions1\"\ndirections1Clock = core.Clock()\ntext_8 = visual.TextStim(win=win, ori=0, name='text_8',\n text='You will be traveling through different galaxies. In one galaxy, you can win low amounts of money, but in the other you can win high amounts.\\r\\n\\r\\nIf you see a circle with 1 star, that means you can win or lose a low amount.\\r\\n\\r\\nIf you see a circle with 2 stars, that means you can win or lose a high amount. \\r\\n\\r\\nClick space to continue.', font='Arial',\n pos=[-10, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-1.0)\nhighCueImage = visual.ImageStim(win=win, name='highCueImage',\n image='images/high.png', mask=None,\n ori=0, pos=[10, -5], size=[9, 9],\n color=[1,1,1], colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=128, interpolate=True, depth=-2.0)\nlowCueImage = visual.ImageStim(win=win, name='lowCueImage',\n image='images/low.png', mask=None,\n ori=0, pos=[10, 6], size=[9, 9],\n color=[1,1,1], colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=128, interpolate=True, depth=-3.0)\nlowLabel = visual.TextStim(win=win, ori=0, name='lowLabel',\n text='Low', font='Arial',\n pos=[13.5, 10], height=.8, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-4.0)\nhighLabel = visual.TextStim(win=win, ori=0, name='highLabel',\n text='High', font='Arial',\n pos=[13.5, -.5], height=.8, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-5.0)\npolygon = visual.Rect(win=win, name='polygon',\n width=[10, 10][0], height=[10, 10][1],\n ori=0, pos=[10, 6],\n lineWidth=1, lineColor=[1,1,1], lineColorSpace='rgb',\n fillColor=None, fillColorSpace='rgb',\n opacity=1,depth=-6.0, \ninterpolate=True)\npolygon_2 = visual.Rect(win=win, name='polygon_2',\n width=[10, 10][0], height=[10, 10][1],\n ori=0, pos=[10, -5],\n lineWidth=1, lineColor=[1,1,1], lineColorSpace='rgb',\n fillColor=None, fillColorSpace='rgb',\n opacity=1,depth=-7.0, \ninterpolate=True)\npolygon_3 = visual.Rect(win=win, name='polygon_3',\n width=[10.5, 10.5][0], height=[10.5, 10.5][1],\n ori=0, pos=[10, -5],\n lineWidth=1, lineColor=[1,1,1], lineColorSpace='rgb',\n fillColor=None, fillColorSpace='rgb',\n opacity=1,depth=-8.0, \ninterpolate=True)\n\n# Initialize components for Routine \"Directions_images\"\nDirections_imagesClock = core.Clock()\ntext_5 = visual.TextStim(win=win, ori=0, name='text_5',\n text=u'In this game, you will see planets and asteroids. Planets have stripes, and asteroids have craters. Only click for the planets! If it is a planet, click space as quickly as possible. If it is an asteroid, do not press anything.\\r\\n\\r\\n', font=u'Arial',\n pos=[0, 5], height=1, wrapWidth=None,\n color=u'white', colorSpace='rgb', opacity=1,\n depth=0.0)\nimage_2 = visual.ImageStim(win=win, name='image_2',\n image=u'images/striped_planet.png', mask=None,\n ori=0, pos=[-10, -3], size=[10, 10],\n color=[1,1,1], colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=128, interpolate=True, depth=-1.0)\nimage_3 = visual.ImageStim(win=win, name='image_3',\n image=u'images/crater_planet.png', mask=None,\n ori=0, pos=[10, -3], size=[10, 10],\n color=[1,1,1], colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=128, interpolate=True, depth=-2.0)\ntext_6 = visual.TextStim(win=win, ori=0, name='text_6',\n text='Planet', font='Arial',\n pos=[-10, -9], height=1.5, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-4.0)\ntext_7 = visual.TextStim(win=win, ori=0, name='text_7',\n text='Asteroid', font='Arial',\n pos=[10, -9], height=1.5, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-5.0)\n\n# Initialize components for Routine \"directions2\"\ndirections2Clock = core.Clock()\ntext_4 = visual.TextStim(win=win, ori=0, name='text_4',\n text='First you will see a cue that will tell you how much you can earn.\\r\\n\\r\\nNext you will see a planet or an asteroid. \\r\\n\\r\\nThen you will see how you did. If you did well, you will get a reward, but if you did not do well you will get punished. \\r\\n\\r\\nPress space to start the practice!', font='Arial',\n pos=[0, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-1.0)\n\n# Initialize components for Routine \"trial\"\ntrialClock = core.Clock()\n# set border color\nborderColor='black'\n\n# Assumes \"first key\" or \"last key\" was chosen for store.\n# List conversion (to single key) happens immediately\n# when component finishes.\ndef check_correct(keys,correct):\n if len(keys): # At least 1 response\n if keys == correct:\n return True\n else:\n return False\n else: # No response\n if correct == None:\n return True\n else:\n return False\n\ntrialFrame = visual.Rect(win=win, name='trialFrame',\n width=[18, 18][0], height=[18, 18][1],\n ori=0, pos=[0, 0],\n lineWidth=2, lineColor=[1,1,1], lineColorSpace='rgb',\n fillColor=None, fillColorSpace='rgb',\n opacity=1,depth=-1.0, \ninterpolate=True)\ntrialFrame2 = visual.Rect(win=win, name='trialFrame2',\n width=[19, 19][0], height=[19, 19][1],\n ori=0, pos=[0, 0],\n lineWidth=2, lineColor='black', lineColorSpace='rgb',\n fillColor=None, fillColorSpace='rgb',\n opacity=1,depth=-2.0, \ninterpolate=True)\nCue_1 = visual.ImageStim(win=win, name='Cue_1',\n image='sin', mask=None,\n ori=0, pos=[0, 0], size=[15, 15],\n color=[1,1,1], colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=128, interpolate=True, depth=-3.0)\nISI_1 = visual.TextStim(win=win, ori=0, name='ISI_1',\n text='+', font='Arial',\n pos=[0, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-4.0)\nTarget = visual.ImageStim(win=win, name='Target',\n image='sin', mask=None,\n ori=0, pos=[0, 0], size=[15, 15],\n color=1.0, colorSpace='rgb', opacity=1,\n flipHoriz=False, flipVert=False,\n texRes=256, interpolate=True, depth=-5.0)\nISI_2 = visual.TextStim(win=win, ori=0, name='ISI_2',\n text='+', font='Arial',\n pos=[0, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-7.0)\nReward_text = visual.TextStim(win=win, ori=0, name='Reward_text',\n text=None, font='Arial',\n pos=[0, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-8.0)\nITI = visual.TextStim(win=win, ori=0, name='ITI',\n text='+', font='Arial',\n pos=[0, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=-9.0)\n\n# Initialize components for Routine \"End\"\nEndClock = core.Clock()\ntext_2 = visual.TextStim(win=win, ori=0, name='text_2',\n text='You finished the practice!\\r\\n\\r\\nIn the real game, you will only see the cue when the block starts, and you will only get feedback when you finish the block. Remember to go as fast as you can!\\r\\n\\r\\nIf you forget whether you are playing for low or high amounts, look at the boxes. One box means low, and two boxes mean high.\\r\\n\\r\\nDo you have any questions?', font='Arial',\n pos=[0, 0], height=1, wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=0.0)\n\n# Create some handy timers\nglobalClock = core.Clock() # to track the time since experiment started\nroutineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine \n\n#------Prepare to start Routine \"directions1\"-------\nt = 0\ndirections1Clock.reset() # clock \nframeN = -1\n# update component parameters for each repeat\nkey_resp_7 = event.BuilderKeyResponse() # create an object of type KeyResponse\nkey_resp_7.status = NOT_STARTED\n# keep track of which components have finished\ndirections1Components = []\ndirections1Components.append(key_resp_7)\ndirections1Components.append(text_8)\ndirections1Components.append(highCueImage)\ndirections1Components.append(lowCueImage)\ndirections1Components.append(lowLabel)\ndirections1Components.append(highLabel)\ndirections1Components.append(polygon)\ndirections1Components.append(polygon_2)\ndirections1Components.append(polygon_3)\nfor thisComponent in directions1Components:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"directions1\"-------\ncontinueRoutine = True\nwhile continueRoutine:\n # get current time\n t = directions1Clock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *key_resp_7* updates\n if t >= 0.0 and key_resp_7.status == NOT_STARTED:\n # keep track of start time/frame for later\n key_resp_7.tStart = t # underestimates by a little under one frame\n key_resp_7.frameNStart = frameN # exact frame index\n key_resp_7.status = STARTED\n # keyboard checking is just starting\n win.callOnFlip(key_resp_7.clock.reset) # t=0 on next screen flip\n event.clearEvents(eventType='keyboard')\n if key_resp_7.status == STARTED:\n theseKeys = event.getKeys(keyList=['space'])\n \n # check for quit:\n if \"escape\" in theseKeys:\n endExpNow = True\n if len(theseKeys) > 0: # at least one key was pressed\n key_resp_7.keys = theseKeys[-1] # just the last key pressed\n key_resp_7.rt = key_resp_7.clock.getTime()\n # a response ends the routine\n continueRoutine = False\n \n # *text_8* updates\n if t >= 0.0 and text_8.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_8.tStart = t # underestimates by a little under one frame\n text_8.frameNStart = frameN # exact frame index\n text_8.setAutoDraw(True)\n \n # *highCueImage* updates\n if t >= 0.0 and highCueImage.status == NOT_STARTED:\n # keep track of start time/frame for later\n highCueImage.tStart = t # underestimates by a little under one frame\n highCueImage.frameNStart = frameN # exact frame index\n highCueImage.setAutoDraw(True)\n \n # *lowCueImage* updates\n if t >= 0.0 and lowCueImage.status == NOT_STARTED:\n # keep track of start time/frame for later\n lowCueImage.tStart = t # underestimates by a little under one frame\n lowCueImage.frameNStart = frameN # exact frame index\n lowCueImage.setAutoDraw(True)\n \n # *lowLabel* updates\n if t >= 0.0 and lowLabel.status == NOT_STARTED:\n # keep track of start time/frame for later\n lowLabel.tStart = t # underestimates by a little under one frame\n lowLabel.frameNStart = frameN # exact frame index\n lowLabel.setAutoDraw(True)\n \n # *highLabel* updates\n if t >= 0.0 and highLabel.status == NOT_STARTED:\n # keep track of start time/frame for later\n highLabel.tStart = t # underestimates by a little under one frame\n highLabel.frameNStart = frameN # exact frame index\n highLabel.setAutoDraw(True)\n \n # *polygon* updates\n if t >= 0.0 and polygon.status == NOT_STARTED:\n # keep track of start time/frame for later\n polygon.tStart = t # underestimates by a little under one frame\n polygon.frameNStart = frameN # exact frame index\n polygon.setAutoDraw(True)\n \n # *polygon_2* updates\n if t >= 0.0 and polygon_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n polygon_2.tStart = t # underestimates by a little under one frame\n polygon_2.frameNStart = frameN # exact frame index\n polygon_2.setAutoDraw(True)\n \n # *polygon_3* updates\n if t >= 0.0 and polygon_3.status == NOT_STARTED:\n # keep track of start time/frame for later\n polygon_3.tStart = t # underestimates by a little under one frame\n polygon_3.frameNStart = frameN # exact frame index\n polygon_3.setAutoDraw(True)\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in directions1Components:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n\n#-------Ending Routine \"directions1\"-------\nfor thisComponent in directions1Components:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n# check responses\nif key_resp_7.keys in ['', [], None]: # No response was made\n key_resp_7.keys=None\n# store data for thisExp (ExperimentHandler)\nthisExp.addData('key_resp_7.keys',key_resp_7.keys)\nif key_resp_7.keys != None: # we had a response\n thisExp.addData('key_resp_7.rt', key_resp_7.rt)\nthisExp.nextEntry()\n# the Routine \"directions1\" was not non-slip safe, so reset the non-slip timer\nroutineTimer.reset()\n\n#------Prepare to start Routine \"Directions_images\"-------\nt = 0\nDirections_imagesClock.reset() # clock \nframeN = -1\n# update component parameters for each repeat\nkey_resp_6 = event.BuilderKeyResponse() # create an object of type KeyResponse\nkey_resp_6.status = NOT_STARTED\n# keep track of which components have finished\nDirections_imagesComponents = []\nDirections_imagesComponents.append(text_5)\nDirections_imagesComponents.append(image_2)\nDirections_imagesComponents.append(image_3)\nDirections_imagesComponents.append(key_resp_6)\nDirections_imagesComponents.append(text_6)\nDirections_imagesComponents.append(text_7)\nfor thisComponent in Directions_imagesComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"Directions_images\"-------\ncontinueRoutine = True\nwhile continueRoutine:\n # get current time\n t = Directions_imagesClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *text_5* updates\n if t >= 0.0 and text_5.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_5.tStart = t # underestimates by a little under one frame\n text_5.frameNStart = frameN # exact frame index\n text_5.setAutoDraw(True)\n \n # *image_2* updates\n if t >= 0.0 and image_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n image_2.tStart = t # underestimates by a little under one frame\n image_2.frameNStart = frameN # exact frame index\n image_2.setAutoDraw(True)\n \n # *image_3* updates\n if t >= 0.0 and image_3.status == NOT_STARTED:\n # keep track of start time/frame for later\n image_3.tStart = t # underestimates by a little under one frame\n image_3.frameNStart = frameN # exact frame index\n image_3.setAutoDraw(True)\n \n # *key_resp_6* updates\n if t >= 0.0 and key_resp_6.status == NOT_STARTED:\n # keep track of start time/frame for later\n key_resp_6.tStart = t # underestimates by a little under one frame\n key_resp_6.frameNStart = frameN # exact frame index\n key_resp_6.status = STARTED\n # keyboard checking is just starting\n win.callOnFlip(key_resp_6.clock.reset) # t=0 on next screen flip\n event.clearEvents(eventType='keyboard')\n if key_resp_6.status == STARTED:\n theseKeys = event.getKeys(keyList=['space'])\n \n # check for quit:\n if \"escape\" in theseKeys:\n endExpNow = True\n if len(theseKeys) > 0: # at least one key was pressed\n key_resp_6.keys = theseKeys[-1] # just the last key pressed\n key_resp_6.rt = key_resp_6.clock.getTime()\n # a response ends the routine\n continueRoutine = False\n \n # *text_6* updates\n if t >= 0.0 and text_6.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_6.tStart = t # underestimates by a little under one frame\n text_6.frameNStart = frameN # exact frame index\n text_6.setAutoDraw(True)\n \n # *text_7* updates\n if t >= 0.0 and text_7.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_7.tStart = t # underestimates by a little under one frame\n text_7.frameNStart = frameN # exact frame index\n text_7.setAutoDraw(True)\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in Directions_imagesComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n\n#-------Ending Routine \"Directions_images\"-------\nfor thisComponent in Directions_imagesComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n# check responses\nif key_resp_6.keys in ['', [], None]: # No response was made\n key_resp_6.keys=None\n# store data for thisExp (ExperimentHandler)\nthisExp.addData('key_resp_6.keys',key_resp_6.keys)\nif key_resp_6.keys != None: # we had a response\n thisExp.addData('key_resp_6.rt', key_resp_6.rt)\nthisExp.nextEntry()\n# the Routine \"Directions_images\" was not non-slip safe, so reset the non-slip timer\nroutineTimer.reset()\n\n#------Prepare to start Routine \"directions2\"-------\nt = 0\ndirections2Clock.reset() # clock \nframeN = -1\n# update component parameters for each repeat\nkey_resp_3 = event.BuilderKeyResponse() # create an object of type KeyResponse\nkey_resp_3.status = NOT_STARTED\n# keep track of which components have finished\ndirections2Components = []\ndirections2Components.append(key_resp_3)\ndirections2Components.append(text_4)\nfor thisComponent in directions2Components:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"directions2\"-------\ncontinueRoutine = True\nwhile continueRoutine:\n # get current time\n t = directions2Clock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *key_resp_3* updates\n if t >= 0.0 and key_resp_3.status == NOT_STARTED:\n # keep track of start time/frame for later\n key_resp_3.tStart = t # underestimates by a little under one frame\n key_resp_3.frameNStart = frameN # exact frame index\n key_resp_3.status = STARTED\n # keyboard checking is just starting\n win.callOnFlip(key_resp_3.clock.reset) # t=0 on next screen flip\n event.clearEvents(eventType='keyboard')\n if key_resp_3.status == STARTED:\n theseKeys = event.getKeys(keyList=['space'])\n \n # check for quit:\n if \"escape\" in theseKeys:\n endExpNow = True\n if len(theseKeys) > 0: # at least one key was pressed\n key_resp_3.keys = theseKeys[-1] # just the last key pressed\n key_resp_3.rt = key_resp_3.clock.getTime()\n # a response ends the routine\n continueRoutine = False\n \n # *text_4* updates\n if t >= 0.0 and text_4.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_4.tStart = t # underestimates by a little under one frame\n text_4.frameNStart = frameN # exact frame index\n text_4.setAutoDraw(True)\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in directions2Components:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n\n#-------Ending Routine \"directions2\"-------\nfor thisComponent in directions2Components:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n# check responses\nif key_resp_3.keys in ['', [], None]: # No response was made\n key_resp_3.keys=None\n# store data for thisExp (ExperimentHandler)\nthisExp.addData('key_resp_3.keys',key_resp_3.keys)\nif key_resp_3.keys != None: # we had a response\n thisExp.addData('key_resp_3.rt', key_resp_3.rt)\nthisExp.nextEntry()\n# the Routine \"directions2\" was not non-slip safe, so reset the non-slip timer\nroutineTimer.reset()\n\n# set up handler to look after randomisation of conditions etc\ntrials = data.TrialHandler(nReps=1, method='random', \n extraInfo=expInfo, originPath=-1,\n trialList=data.importConditions('conditions/practice.xlsx'),\n seed=0, name='trials')\nthisExp.addLoop(trials) # add the loop to the experiment\nthisTrial = trials.trialList[0] # so we can initialise stimuli with some values\n# abbreviate parameter names if possible (e.g. rgb=thisTrial.rgb)\nif thisTrial != None:\n for paramName in thisTrial.keys():\n exec(paramName + '= thisTrial.' + paramName)\n\nfor thisTrial in trials:\n currentLoop = trials\n # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)\n if thisTrial != None:\n for paramName in thisTrial.keys():\n exec(paramName + '= thisTrial.' + paramName)\n \n #------Prepare to start Routine \"trial\"-------\n t = 0\n trialClock.reset() # clock \n frameN = -1\n # update component parameters for each repeat\n \n \n \n # Set Cue image on Reward Value Condition\n if valueCondition == 'low':\n cueImage = 'low.png'\n else:\n cueImage = 'high.png'\n \n # Set Target Image on Go/Nogo Condition\n if targetType == 'go':\n targetImage = 'striped_planet.png'\n correct = 'space'\n else:\n targetImage = 'crater_planet.png'\n correct = None\n \n \n \n # set border width of 2nd border frame\n if valueCondition == 'low':\n borderColor='black'\n else:\n borderColor='white'\n trialFrame2.setLineColor(borderColor)\n \n # set outcome text\n outcomeText=None\n outcomeColor='white'\n Cue_1.setImage(os.path.join('images',cueImage))\n Target.setColor([1,1,1], colorSpace='rgb')\n Target.setImage(os.path.join('images',targetImage))\n key_resp_1 = event.BuilderKeyResponse() # create an object of type KeyResponse\n key_resp_1.status = NOT_STARTED\n # keep track of which components have finished\n trialComponents = []\n trialComponents.append(trialFrame)\n trialComponents.append(trialFrame2)\n trialComponents.append(Cue_1)\n trialComponents.append(ISI_1)\n trialComponents.append(Target)\n trialComponents.append(key_resp_1)\n trialComponents.append(ISI_2)\n trialComponents.append(Reward_text)\n trialComponents.append(ITI)\n for thisComponent in trialComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n \n #-------Start Routine \"trial\"-------\n continueRoutine = True\n while continueRoutine:\n # get current time\n t = trialClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n # write outcome text\n if key_resp_1.status == STOPPED and outcomeText == None:\n if check_correct(key_resp_1.keys,correct):\n if valueCondition == 'low':\n outcomeText = 'Correct! + $0.20'\n outcomeColor = 'green'\n else: # valueCondition == 'high'\n outcomeText = 'Correct! + $1.00'\n outcomeColor='green'\n else:\n if valueCondition == 'low':\n outcomeText = 'Incorrect! - $0.10'\n outcomeColor='red'\n else: # valueCondition == 'high'\n outcomeText = 'Incorrect! - $0.50'\n outcomeColor='red'\n Reward_text.setText(outcomeText)\n Reward_text.setColor(outcomeColor)\n trials.addData('outcomeText',outcomeText)\n trials.addData('cueImage', cueImage)\n trials.addData('targetImage', targetImage)\n \n # *trialFrame* updates\n if t >= 0 and trialFrame.status == NOT_STARTED:\n # keep track of start time/frame for later\n trialFrame.tStart = t # underestimates by a little under one frame\n trialFrame.frameNStart = frameN # exact frame index\n trialFrame.setAutoDraw(True)\n if trialFrame.status == STARTED and (Reward_text.status==FINISHED):\n trialFrame.setAutoDraw(False)\n \n # *trialFrame2* updates\n if t >= 0 and trialFrame2.status == NOT_STARTED:\n # keep track of start time/frame for later\n trialFrame2.tStart = t # underestimates by a little under one frame\n trialFrame2.frameNStart = frameN # exact frame index\n trialFrame2.setAutoDraw(True)\n if trialFrame2.status == STARTED and (Reward_text.status==FINISHED):\n trialFrame2.setAutoDraw(False)\n \n # *Cue_1* updates\n if t >= 0 and Cue_1.status == NOT_STARTED:\n # keep track of start time/frame for later\n Cue_1.tStart = t # underestimates by a little under one frame\n Cue_1.frameNStart = frameN # exact frame index\n Cue_1.setAutoDraw(True)\n if Cue_1.status == STARTED and t >= (0 + (0.5-win.monitorFramePeriod*0.75)): #most of one frame period left\n Cue_1.setAutoDraw(False)\n \n # *ISI_1* updates\n if (Cue_1.status==FINISHED) and ISI_1.status == NOT_STARTED:\n # keep track of start time/frame for later\n ISI_1.tStart = t # underestimates by a little under one frame\n ISI_1.frameNStart = frameN # exact frame index\n ISI_1.setAutoDraw(True)\n if ISI_1.status == STARTED and t >= (ISI_1.tStart + ISI1):\n ISI_1.setAutoDraw(False)\n \n # *Target* updates\n if (ISI_1.status==FINISHED) and Target.status == NOT_STARTED:\n # keep track of start time/frame for later\n Target.tStart = t # underestimates by a little under one frame\n Target.frameNStart = frameN # exact frame index\n Target.setAutoDraw(True)\n if Target.status == STARTED and t >= (Target.tStart + 0.5):\n Target.setAutoDraw(False)\n \n # *key_resp_1* updates\n if (ISI_1.status==FINISHED) and key_resp_1.status == NOT_STARTED:\n # keep track of start time/frame for later\n key_resp_1.tStart = t # underestimates by a little under one frame\n key_resp_1.frameNStart = frameN # exact frame index\n key_resp_1.status = STARTED\n # keyboard checking is just starting\n win.callOnFlip(key_resp_1.clock.reset) # t=0 on next screen flip\n event.clearEvents(eventType='keyboard')\n if key_resp_1.status == STARTED and t >= (key_resp_1.tStart + 1.5):\n key_resp_1.status = STOPPED\n if key_resp_1.status == STARTED:\n theseKeys = event.getKeys(keyList=['space'])\n \n # check for quit:\n if \"escape\" in theseKeys:\n endExpNow = True\n if len(theseKeys) > 0: # at least one key was pressed\n if key_resp_1.keys == []: # then this was the first keypress\n key_resp_1.keys = theseKeys[0] # just the first key pressed\n key_resp_1.rt = key_resp_1.clock.getTime()\n # was this 'correct'?\n if (key_resp_1.keys == str(correct)) or (key_resp_1.keys == correct):\n key_resp_1.corr = 1\n else:\n key_resp_1.corr = 0\n \n # *ISI_2* updates\n if (Target.status==FINISHED) and ISI_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n ISI_2.tStart = t # underestimates by a little under one frame\n ISI_2.frameNStart = frameN # exact frame index\n ISI_2.setAutoDraw(True)\n if ISI_2.status == STARTED and t >= (ISI_2.tStart + 2):\n ISI_2.setAutoDraw(False)\n \n # *Reward_text* updates\n if (ISI_2.status==FINISHED) and Reward_text.status == NOT_STARTED:\n # keep track of start time/frame for later\n Reward_text.tStart = t # underestimates by a little under one frame\n Reward_text.frameNStart = frameN # exact frame index\n Reward_text.setAutoDraw(True)\n if Reward_text.status == STARTED and t >= (Reward_text.tStart + 2):\n Reward_text.setAutoDraw(False)\n \n # *ITI* updates\n if (Reward_text.status==FINISHED) and ITI.status == NOT_STARTED:\n # keep track of start time/frame for later\n ITI.tStart = t # underestimates by a little under one frame\n ITI.frameNStart = frameN # exact frame index\n ITI.setAutoDraw(True)\n if ITI.status == STARTED and t >= (ITI.tStart + 2):\n ITI.setAutoDraw(False)\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in trialComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n \n #-------Ending Routine \"trial\"-------\n for thisComponent in trialComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n \n # check responses\n if key_resp_1.keys in ['', [], None]: # No response was made\n key_resp_1.keys=None\n # was no response the correct answer?!\n if str(correct).lower() == 'none': key_resp_1.corr = 1 # correct non-response\n else: key_resp_1.corr = 0 # failed to respond (incorrectly)\n # store data for trials (TrialHandler)\n trials.addData('key_resp_1.keys',key_resp_1.keys)\n trials.addData('key_resp_1.corr', key_resp_1.corr)\n if key_resp_1.keys != None: # we had a response\n trials.addData('key_resp_1.rt', key_resp_1.rt)\n # the Routine \"trial\" was not non-slip safe, so reset the non-slip timer\n routineTimer.reset()\n thisExp.nextEntry()\n \n# completed 1 repeats of 'trials'\n\n\n#------Prepare to start Routine \"End\"-------\nt = 0\nEndClock.reset() # clock \nframeN = -1\n# update component parameters for each repeat\nkey_resp_5 = event.BuilderKeyResponse() # create an object of type KeyResponse\nkey_resp_5.status = NOT_STARTED\n# keep track of which components have finished\nEndComponents = []\nEndComponents.append(text_2)\nEndComponents.append(key_resp_5)\nfor thisComponent in EndComponents:\n if hasattr(thisComponent, 'status'):\n thisComponent.status = NOT_STARTED\n\n#-------Start Routine \"End\"-------\ncontinueRoutine = True\nwhile continueRoutine:\n # get current time\n t = EndClock.getTime()\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\n # update/draw components on each frame\n \n # *text_2* updates\n if t >= 0.0 and text_2.status == NOT_STARTED:\n # keep track of start time/frame for later\n text_2.tStart = t # underestimates by a little under one frame\n text_2.frameNStart = frameN # exact frame index\n text_2.setAutoDraw(True)\n \n # *key_resp_5* updates\n if t >= 0.0 and key_resp_5.status == NOT_STARTED:\n # keep track of start time/frame for later\n key_resp_5.tStart = t # underestimates by a little under one frame\n key_resp_5.frameNStart = frameN # exact frame index\n key_resp_5.status = STARTED\n # keyboard checking is just starting\n win.callOnFlip(key_resp_5.clock.reset) # t=0 on next screen flip\n event.clearEvents(eventType='keyboard')\n if key_resp_5.status == STARTED:\n theseKeys = event.getKeys(keyList=['y', 'n', 'left', 'right', 'space'])\n \n # check for quit:\n if \"escape\" in theseKeys:\n endExpNow = True\n if len(theseKeys) > 0: # at least one key was pressed\n key_resp_5.keys = theseKeys[-1] # just the last key pressed\n key_resp_5.rt = key_resp_5.clock.getTime()\n # a response ends the routine\n continueRoutine = False\n \n # check if all components have finished\n if not continueRoutine: # a component has requested a forced-end of Routine\n break\n continueRoutine = False # will revert to True if at least one component still running\n for thisComponent in EndComponents:\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\n continueRoutine = True\n break # at least one component has not yet finished\n \n # check for quit (the Esc key)\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\n core.quit()\n \n # refresh the screen\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\n win.flip()\n\n#-------Ending Routine \"End\"-------\nfor thisComponent in EndComponents:\n if hasattr(thisComponent, \"setAutoDraw\"):\n thisComponent.setAutoDraw(False)\n# check responses\nif key_resp_5.keys in ['', [], None]: # No response was made\n key_resp_5.keys=None\n# store data for thisExp (ExperimentHandler)\nthisExp.addData('key_resp_5.keys',key_resp_5.keys)\nif key_resp_5.keys != None: # we had a response\n thisExp.addData('key_resp_5.rt', key_resp_5.rt)\nthisExp.nextEntry()\n# the Routine \"End\" was not non-slip safe, so reset the non-slip timer\nroutineTimer.reset()\n\n# these shouldn't be strictly necessary (should auto-save)\nthisExp.saveAsWideText(filename+'.csv')\nthisExp.saveAsPickle(filename)\nlogging.flush()\n# make sure everything is closed down\nthisExp.abort() # or data files will save again on exit\nwin.close()\ncore.quit()\n","sub_path":"PracticeTask/PlanetPractice_StripedGo_lastrun.py","file_name":"PlanetPractice_StripedGo_lastrun.py","file_ext":"py","file_size_in_byte":38386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"600193572","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n \nfrom scipy import special\nfrom refnx.dataset import ReflectDataset\nfrom refnx.analysis import CurveFitter, Objective, Transform, parameter, possibly_create_parameter, Parameters\nfrom refnx.reflect import ReflectModel, SLD, Erf, Component\nfrom refnx.reflect import structure\n\n# | . o . |\n# air-pro, phi-pho, center, mirror (i-o), pro-wat \n# a-w\n# (x/a)^2 + (y/b)^2 = 1 <-ellipse\n# air-pro to cetre = a, b is from area taken up\n\nclass param():\n def __init__(real=0, image=0, name='unknown', thickness=0):\n self.real = real\n pass\n \n\nclass eggs(Component):#\n def __init__(self, air, hydropho, hydrophil, water, tilt):\n super(eggs)\n names = ['air', 'hydropho', 'hydrophil', 'water']\n more = ['tilt']\n pass\n\nclass bsla_thesis(Component): #as in thesis\n def __init__(self, i_as=11.1, sig_as=0.1, i_ap=24.1, th_p= 25.1, i_ps=24.1, n_w=500.1, d_sld=2.01, a=13, b=16.5, c=27.5):\n #interface air solvent, interface width air solvent, interface air protien, interface protien solvent, number of water molecules, sld of deuterated protein \n super(bsla_thesis).__init__()\n name='bsla'\n self.name = name\n self.interface_air_protein = possibly_create_parameter(0.0,\n name='%s - interface_air_protein' % name)\n self.interface_protein_solvent = possibly_create_parameter(11.1,\n name='%s - interface_protein_solvent' % name)\n self.protein_length = possibly_create_parameter(25.1,\n name='%s - protein_length' % name)\n self.number_of_water_molecules = possibly_create_parameter(500.1,\n name='%s - number_of_water_molecules' % name)\n self.interface_width_air_solvent = possibly_create_parameter(15,\n name='%s - interface_width_air_solvent' % name)\n #self.interface_width_protein_solvent = possibly_create_parameter(0.1,\n # name='%s - interface_width_protein_solvent' % name)\n self.sld_of_protein = possibly_create_parameter(3.23, #*(10**(-6))\n name='%s - sld_of_protein' % name)\n self.d2o_to_h2o_ratio = possibly_create_parameter(1.0,\n name='%s - d2o_h2o_ratio' % name)\n# self.semi_axis_a = possibly_create_parameter(a,\n# name='%s - semi_axis_a' % name)\n# self.semi_axis_b = possibly_create_parameter(b,\n# name='%s - semi_axis_b' % name)\n# self.semi_axis_c = possibly_create_parameter(c,\n# name='%s - semi_axis_c' % name)\n self.a = 13\n self.b = 16.5\n self.c = 27.5\n self.volume_of_water_molecule = 30\n self.major_axis_length = 55\n self.d = (self.c - self.a)/self.volume_of_water_molecule\n #print([self.interface_air_protein,\n # self.interface_protein_solvent,\n # self.protein_length,\n # self.number_of_water_molecules,\n # self.interface_width_air_solvent,\n # #self.interface_width_protein_solvent,\n # self.sld_of_protein,\n # self.d2o_to_h2o_ratio])\n \n# b_o=0.5843*10**-4\n# b_d=0.6671*10**-4\n# b_h=-0.3739*10**-4\n# b_d2o = b_o + 2*b_d\n# b_d2o = 1.9185*10**-4\n# b_h2o = -0.1635*10**-4\n \n# self.sld_d2o = b_d2o/self.volume_of_water_molecule\n\n def __call__(self, z, structure=None):\n self.calculations()\n area_prot = self.area_protein(z)\n area_wat = self.area_water(z)\n #print(area_wat)\n #print('cough')\n #print(area_prot)\n area_total = area_wat+area_prot\n sld_prot = self.sld_protein(area_prot,area_total)\n sld_wat = self.sld_water(area_wat, area_total)\n #print(\"last\",len(sld_prot),len(sld_wat))\n return sld_prot+sld_wat\n\n @property\n def parameters(self):\n p = Parameters(name=self.name)\n p.extend([self.interface_air_protein,\n self.interface_protein_solvent,\n self.protein_length,\n self.number_of_water_molecules,\n self.interface_width_air_solvent,\n #self.interface_width_protein_solvent,\n self.sld_of_protein,\n self.d2o_to_h2o_ratio])\n return p\n\n def logp(self):\n #full = np.arange(150)\n #a_p = np.array(list(map(self.area_protein, full)))\n #a_w = np.array(list(map(self.area_water, full)))\n #max_w = max(a_w)\n #max_p = max(a_p)\n #max_a = max_w if max_w > max_p else max_p\n return 0\n\n def calculations(self):\n# a = 13\n# b = 16.5\n# c = 27.5\n# volume_of_water_molecule = 30\n self.e = self.major_axis_length - self.protein_length.value\n self.delta_a = self.a + (self.d*self.e)\n self.delta_c = self.c - (self.d*self.e)\n\n def area_protein(self, z):\n identity = np.ones(len(z))\n first_bit = np.pi*self.delta_a*self.b/(self.delta_c**2)\n second_bit = z - identity*self.interface_air_protein.value\n final_bit = identity*2*self.delta_c - second_bit\n# print('f',np.pi, self.delta_a,self.b, self.delta_c, first_bit)\n# print(second_bit)\n# print(final_bit)\n #print(\"pro lengths\",len(second_bit), len(final_bit))\n return first_bit*np.multiply(second_bit,final_bit)\n\n def sld_protein(self, area_p, area_total):\n ratio_area = area_p/area_total\n #print(\"pro sl lengths\",len(area_p),len(ratio_area))\n return ratio_area * self.sld_of_protein.value\n\n def area_water(self, zs):\n water_length = (self.interface_air_protein.value\n + self.protein_length.value\n - self.interface_protein_solvent.value)\n z_s = self.interface_protein_solvent.value+0.5*water_length # calc\n first_bit = (self.number_of_water_molecules.value\n *self.volume_of_water_molecule/(2*water_length))\n #print(self.interface_width_air_solvent.value, type(self.interface_width_air_solvent.value))\n #print(z,'\\n')\n #print(z, z_s ,0.5,self.d, self.interface_width_air_solvent.value,\n # special.erf((z - z_s + 0.5*self.d)\n # /self.interface_width_air_solvent.value))\n second_bits= np.copy(zs)\n #print(z_s, water_length, self.interface_width_air_solvent.value)\n for i in range(len(zs)):\n second_bits[i] = ( special.erf( (zs[i] - z_s + 0.5*water_length)\n / (self.interface_width_air_solvent.value*np.sqrt(2)) )\n - special.erf( (zs[i] - z_s - 0.5*water_length)\n / (self.interface_width_air_solvent.value*np.sqrt(2)) ) )\n #print(\"wat lengths\",len(second_bits))\n return first_bit*second_bits\n# print('helo',\n# second_bits[i], \n# zs[i],\n# zs[i] - z_s + 0.5*water_length, \n# zs[i] - z_s - 0.5*water_length,\n# special.erf((zs[i] - z_s + 0.5*water_length)\n# /self.interface_width_air_solvent.value),\n# special.erf((zs[i] - z_s - 0.5*self.d)\n# /self.interface_width_air_solvent.value))\n\n def sld_water(self, area_w, area_total):\n b_d2o = 1.9185#*10**-4\n b_h2o = -0.1635#*10**-4\n sld_d2o = 100*b_d2o/self.volume_of_water_molecule\n sld_h2o = 100*b_h2o/self.volume_of_water_molecule\n sld_solvent = (self.d2o_to_h2o_ratio.value*sld_d2o +\n (1-self.d2o_to_h2o_ratio.value)*sld_h2o)\n ratio_area = area_w/area_total\n return ratio_area * sld_solvent\n \n def slabs(self,structure=None):\n #in style of https://refnx.readthedocs.io/en/latest/_modules/refnx/reflect/spline.html#Spline\n length = (self.interface_air_protein.value\n + self.protein_length.value)\n no_slabs = length/1.\n thickness_slabs = length/no_slabs\n slabs = np.zeros((int(no_slabs), 5))\n slabs[:,0] = thickness_slabs\n slabs[-1,3] = 0.5\n distance = np.cumsum(slabs[..., 0]) - 0.5 * thickness_slabs\n slabs[:,1] = self(distance,structure)\n #print(\"slabs\",slabs)\n #slabs = structure.__profile_slicer(distance,slabs)\n return slabs\n\n#\n#air = SLD(value=0+0j, name='air')\n#----------\n#or \n#re =Parameter(0)\n#im=Parameter(0)\n#air = SLD([re,im])\n#---------\n#polymer = SLD(1,'polymer')\n#silicon = SLD(2,'silicon')\n#structure = air(thick=0,rough=0) | polymer(200,4) | silicon(0,3)\n# air-polymer roughness of 4, polymer size of 200\n# #Erf() <-error function\n# structure[1].interfaces = Erf() # air-polymer interface\n# structure[2].interfaces = Erf()\n#need lnprob\n#sort vol fractions \n#add areas etc.\n#possibly using possibly` creat parameter and parameter p.extend(\n#tilt and other values not used either\n\n\nclass bsla_non(Component): #not as in thesis\n def __init__(self, area_per_molecule=1, angle=1, length_of_molecule=1):\n #area per molecule, \n super(bsla).__init__()\n name='bsla'\n pass\n\n \n #for calculating unphysical thing\n def volume_fraction_protien(self, z):\n pass\n \n def volume_fraction_air(self, z):\n pass\n \n def volume_fraction_water(self, z):\n pass\n \n \nclass bsla_equation(Component): # equation based\n def __init__(self, extent, vs, dz,name='bsla', microslab_max_thickness=1):\n pass\n \n def __call__(self, z):\n pass\n \ndef test_run():\n print(\"\\n\\n\\n\")\n from refnx.dataset import Data1D\n from refnx.dataset import ReflectDataset\n import refnx\n import data_in\n data = data_in.data_in('d2o/29553_54.dat')\n # dataset = data # ...\n data = Data1D(data) \n from make_egg import bsla_thesis\n# air = SLD(0)\n# air = air(0,0)\n bt = bsla_thesis()\n bt.interface_protein_solvent.setp(vary=True, bounds=(11, 40))\n bt.protein_length.setp(vary=True, bounds=(25, 55))\n bt.number_of_water_molecules.setp(vary=True, bounds=(1, 10000))\n bt.interface_width_air_solvent.setp(vary=True, bounds=(0.001, 30))\n #bt.interface_width_protein_solvent.setp(vary=True, bounds=(0, 5))\n bt.sld_of_protein.setp(vary=True, bounds=(1.92, 6.21)) # *(10**(-6))\n bt.d2o_to_h2o_ratio.setp(vary=True, bounds=(0, 1))\n# if isinstance(bt, Component):\n# print(\"it is comp\")\n# if isinstance(bt, Structure):\n# print(\"it is\")\n #print(bt.parameters)\n# d2o = 1.9185/0.3\n# h2o = -0.1635/0.3\n# solvent = SLD((bt.d2o_to_h2o_ratio.value*d2o + (1-bt.d2o_to_h2o_ratio.value)*h2o))\n# solvent = solvent(0,0)\n# from refnx.reflect import Structure\n# structure = air|bt|solvent\n# structure.name = \"bsla\"\n from refnx.reflect import ReflectModel\n model = ReflectModel(bt)#structure)\n from refnx.analysis import Transform, CurveFitter, Objective\n objective = Objective(model,data)\n fitter = CurveFitter(objective)\n fitter.fit('differential_evolution');\n import matplotlib.pyplot as plt\n #%matplotlib notebook\n# plt.plot(*bt.sld_profile())\n objective.plot()\n plt.yscale('log')\n plt.xscale('log')\n plt.xlabel('Q')\n plt.ylabel('Reflectivity')\n plt.legend()\n print(bt)\n plt.show()\n \nif __name__ == '__main__':\n test_run()","sub_path":"make_egg.py","file_name":"make_egg.py","file_ext":"py","file_size_in_byte":11517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"312014618","text":"from django.shortcuts import render\nfrom .models import volunteer\nfrom django.http import HttpResponse\n# Create your views here.\ndef p2(request):\n return render(request,\"p2.html\")\n\n\ndef vl(request):\n if request.method == \"POST\":\n fn = request.POST[\"fname\"]\n ln = request.POST[\"lname\"]\n gender = request.POST[\"gender\"]\n avl = request.POST[\"availability\"]\n email = request.POST[\"email\"]\n ph = request.POST[\"phone\"]\n role = request.POST[\"role\"]\n adr = request.POST[\"address\"]\n msg = request.POST[\"message\"]\n volunteer_data=volunteer(fname=fn,lname=ln,gender=gender,availability=avl,email=email,phone=ph,role=role,address=adr,message=msg)\n volunteer_data.save()\n return HttpResponse(\"

data succesgully saved

\")\n return render(request,\"volregistration.html\")\n\ndef ragava(request):\n return render(request,\"p3.html\")","sub_path":"volunteer/volunteer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"478969043","text":"#!/usr/bin/python3\n\"\"\"14. Pascal's Triangle\"\"\"\n\n\ndef pascal_triangle(n):\n \"\"\"returns a list of lists of integers\n representing the Pascal’s triangle of n\n\n Args:\n n (int): size of the Pascal’s triangle\n\n Returns:\n list of lists: of integers\n \"\"\"\n\n if n <= 0:\n return list([])\n\n li = [[1]]\n\n for y in range(1, n):\n li.append([])\n for x in range(0, y + 1):\n n1 = 0\n n2 = 0\n if len(li[y - 1]) > x:\n n1 = li[y - 1][x]\n if x - 1 >= 0:\n n2 = li[y - 1][x - 1]\n li[y].append(n1 + n2)\n\n return li\n","sub_path":"0x0B-python-input_output/14-pascal_triangle.py","file_name":"14-pascal_triangle.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"416321948","text":"import os\nimport pandas as pd\nimport torch\n\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nfrom typing import Any, Dict, Optional\n\n\nclass FlowersDataset(Dataset):\n \"\"\"Flowers Recognition Dataset\n 今回のデータセットは,torchvision.datasets.ImageFolder でも実装可能だが,\n csv を作る練習をかねて,データセットクラスを自作している.\n \"\"\"\n\n def __init__(\n self, csv_file: str, transform: Optional[transforms.Compose] = None\n ) -> None:\n super().__init__()\n assert os.path.exists(csv_file)\n\n csv_path = os.path.join(csv_file)\n\n self.df = pd.read_csv(csv_path)\n self.transform = transform\n\n def __len__(self) -> int:\n return len(self.df)\n\n def __getitem__(self, idx: int) -> Dict[str, Any]:\n img_path = self.df.iloc[idx][\"image_path\"]\n img = Image.open(img_path)\n\n if self.transform is not None:\n img = self.transform(img)\n\n cls_id = self.df.iloc[idx][\"class_id\"]\n cls_id = torch.tensor(cls_id).long()\n\n label = self.df.iloc[idx][\"label\"]\n\n sample = {\"img\": img, \"class_id\": cls_id, \"label\": label, \"img_path\": img_path}\n\n return sample\n","sub_path":"libs/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"102907058","text":"from django.contrib import admin\r\nfrom django.conf.urls import url,include\r\nfrom django.urls import path\r\nfrom blog_admin.views import login,blog,uploads\r\nfrom blog_admin.views import user\r\n\r\nurlpatterns = [\r\n url(r'^$',login.login,name='login' ),\r\n url(r'^dologin$',login.dologin,name='dologin' ),\r\n url(r'^loginout$',login.loginout,name='loginout' ),\r\n\r\n url(r'^blog_index$',blog.blog_index,name='blog_index' ),\r\n url(r'^add_blog$',blog.add_blog,name='add_blog'),\r\n url(r'^insert_blog$',blog.insert_blog,name='insert_blog'),\r\n url(r'^update_blog/(?P[0-9]+)$',blog.update_blog,name='update_blog'),\r\n url(r'^edit_blog/(?P[0-9]+)$',blog.edit_blog,name='edit_blog'),\r\n url(r'^delete_blog/(?P[0-9]+)$',blog.delete_blog,name='delete_blog'),\r\n\r\n url(r'^upload/(?P[^/]+)$', uploads.upload_image, name='upload_image'),\r\n\r\n url(r'^userlist$',user.userlist,name='userlist' ),\r\n url(r'^adduser$',user.adduser,name='adduser' ),\r\n url(r'^insertuser$',user.insertuser,name='insertuser' ),\r\n url(r'^updateuser/(?P[0-9]+)$',user.updateuser,name='updateuser' ),\r\n url(r'^edituser/(?P[0-9]+)$',user.edituser,name='edituser' ),\r\n url(r'^deleteuser/(?P[0-9]+)$',user.deleteuser,name='deleteuser' ),\r\n\r\n\r\n]\r\n","sub_path":"blog_admin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"329836286","text":"''' Construct programm using random function '''\r\n\r\n\r\n\r\nimport random\r\n\r\nfirst_names = ['POOJA', 'KAJAL', 'PRADIP', 'AKSHAY', 'CHETAN', 'KUNJAN', 'SHUBHAM', 'SOJWAL', 'GAJANAN', 'RIZWAN', 'SUDESH', 'GAURI', 'NAMRATA', 'KIRTI', 'ARCHANA', 'MINAXI', 'PRAVIN', 'PRADIP', 'POOJA', 'ABHIJIT', 'PRIYANKA']\r\n\r\nlast_names = ['MORE', 'BHINGARE', 'KHAN', 'CHOPADE', 'BHARAMBE', 'RANE', 'CHAUDHARI', 'SARODE', 'PATIL', 'BHOLE', 'MARATHE', 'SHAIKH', 'GHOGARE', 'KOLHE', 'NHAVI', 'ZOPE', 'TANWAR', 'INGALE', 'GHULE', 'BARI', 'BHOI', 'PETHE', 'DESHMUKH', 'WANI', 'MAHAJAN', 'JAIN', 'SONAR']\r\n\r\nstreet_names = ['Main', 'High', 'Pearl', 'Maple', 'Park', 'Oak', 'Pine', 'Cedar', 'Elm', 'Shengola', 'Lake', 'Hill']\r\n\r\nfake_cities = ['Jamner', 'Jalgaon', \"Bhusawal\", 'Pachora', 'Shengola', 'Mumbai', 'Nashik', 'Chennai', 'Ahemdabad', 'Kolkata', 'New Delhi', 'Jipur', 'Luknow', 'Prayagraj', 'Wadodra', 'Madurai', 'Ranchi', 'Faketown', 'Westworld', 'Thundera', 'Vice City', 'Gaziabad', 'Oldtown', 'Valyria', 'Winterfell', 'Braavos‎', 'Lakeview']\r\n\r\nstates = ['MH', 'MP', 'UP', 'AR', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']\r\n\r\nfor num in range(100):\r\n first = random.choice(first_names)\r\n last = random.choice(last_names)\r\n\r\n phone = f'+91-{random.randint(100, 999)}-555-{random.randint(1000,9999)}'\r\n\r\n street_num = random.randint(100, 999)\r\n street = random.choice(street_names)\r\n city = random.choice(fake_cities)\r\n state = random.choice(states)\r\n zip_code = random.randint(400000, 499999)\r\n address = f'{street_num} {street} St., {city} {state} {zip_code}'\r\n\r\n email = first.lower() + last.lower() + '@bogusemail.com'\r\n\r\n print(f'{first} {last}\\n{phone}\\n{address}\\n{email}\\n')","sub_path":"random_mod.py","file_name":"random_mod.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"157412","text":"# -*- encoding: utf-8 -*-\nfrom guillotina import app_settings\nfrom guillotina import configure\nfrom guillotina.component import getMultiAdapter\nfrom guillotina.interfaces import ICloudFileField\nfrom guillotina.interfaces import IFile\nfrom guillotina.interfaces import IFileManager\nfrom guillotina.interfaces import IRequest\nfrom guillotina.interfaces import IResource\nfrom guillotina.interfaces import IStorage\nfrom guillotina.interfaces import NotStorable\nfrom guillotina.schema import Object\nfrom guillotina.utils import import_class\nfrom zope.interface import alsoProvides\nfrom zope.interface import implementer\n\nimport io\nimport mimetypes\nimport os\n\n\ndef get_contenttype(\n file=None,\n filename=None,\n default='application/octet-stream'):\n \"\"\"Get the MIME content type of the given file and/or filename.\n \"\"\"\n\n file_type = getattr(file, 'content_type', None)\n if file_type:\n return file_type\n\n filename = getattr(file, 'filename', filename)\n if filename:\n extension = os.path.splitext(filename)[1].lower()\n return mimetypes.types_map.get(extension, 'application/octet-stream')\n\n return default\n\n\n@implementer(ICloudFileField)\nclass CloudFileField(Object):\n \"\"\"\n A cloud file hosted file.\n\n Its configured on config.json with :\n\n \"cloud_storage\": \"pserver.s3storage.interfaces.IS3FileField\"\n\n or\n\n \"cloud_storage\": \"pserver.gcloudstorage.interfaces.IGCloudFileField\"\n\n \"\"\"\n\n schema = IFile\n\n def __init__(self, **kw):\n super(CloudFileField, self).__init__(schema=self.schema, **kw)\n\n\n@configure.adapter(\n for_=(IResource, IRequest, ICloudFileField),\n provides=IFileManager)\nclass CloudFileManager(object):\n\n def __init__(self, context, request, field):\n iface = import_class(app_settings['cloud_storage'])\n alsoProvides(field, iface)\n self.real_file_manager = getMultiAdapter(\n (context, request, field), IFileManager)\n\n async def download(self, *args, **kwargs):\n return await self.real_file_manager.download(*args, **kwargs)\n\n async def tus_options(self, *args, **kwargs):\n return await self.real_file_manager.tus_options(*args, **kwargs)\n\n async def tus_head(self, *args, **kwargs):\n return await self.real_file_manager.tus_head(*args, **kwargs)\n\n async def tus_patch(self, *args, **kwargs):\n return await self.real_file_manager.tus_patch(*args, **kwargs)\n\n async def tus_create(self, *args, **kwargs):\n return await self.real_file_manager.tus_create(*args, **kwargs)\n\n async def upload(self, *args, **kwargs):\n return await self.real_file_manager.upload(*args, **kwargs)\n\n async def iter_data(self, *args, **kwargs):\n async for chunk in self.real_file_manager.iter_data(*args, **kwargs):\n yield chunk\n\n async def save_file(self, generator, *args, **kwargs):\n await self.real_file_manager.save_file(generator, *args, **kwargs)\n\n# This file was borrowed from z3c.blobfile and is licensed under the terms of\n# the ZPL.\n\n\nMAXCHUNKSIZE = 1 << 16\n\n\n@implementer(IStorage)\n@configure.utility(provides=IStorage, name=\"builtins.str\")\nclass StringStorable(object):\n\n def store(self, data, blob):\n if not isinstance(data, str):\n raise NotStorable('Could not store data (not of \"str\" type).')\n\n with blob.open('w') as fp:\n fp.write(bytes(data, encoding='utf-8'))\n\n\n@implementer(IStorage)\n@configure.utility(provides=IStorage, name=\"builtin.bytes\")\nclass BytesStorable(StringStorable):\n\n def store(self, data, blob):\n if not isinstance(data, str):\n raise NotStorable('Could not store data (not of \"unicode\" type).')\n\n StringStorable.store(self, data, blob)\n\n\n@implementer(IStorage)\n@configure.utility(provides=IStorage, name=\"builtin.file\")\nclass FileDescriptorStorable(object):\n\n def store(self, data, blob):\n if not isinstance(data, io.IOBase):\n raise NotStorable('Could not store data (not of \"file\").')\n\n filename = getattr(data, 'name', None)\n if filename is not None:\n blob.consumeFile(filename)\n return\n","sub_path":"guillotina/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"474764490","text":"# coding=utf-8\nfrom __future__ import absolute_import, unicode_literals, division\nfrom moarcofy import config\n\nfrom jinja2 import Markup\nfrom flask import g\n\n\ndef javascript(filename=None):\n \"\"\"Ensures that the page will load 'filename' as a javascript (do not use\n an extension). This takes care of media versioning, prevents duplicates and\n handles compilation if needed.\"\"\"\n if not hasattr(g, \"scripts\"):\n g.scripts = set()\n\n name = \"/static/{0}/js/{1}.js\".format(config[\"version\"][\"media\"], filename)\n if name in g.scripts:\n return \"\"\n g.scripts.add(name)\n return Markup(\"\".format(name))\n\n\ndef stylesheet(filename=None):\n \"\"\"Ensures that the page will load 'filename' as a stylesheet (do not use\n an extension). This takes care of media versioning, prevents duplicates and\n handles compilation if needed.\"\"\"\n if not hasattr(g, \"stylesheets\"):\n g.stylesheets = set()\n\n name = \"/static/{0}/css/{1}.css\".format(config[\"version\"][\"media\"],\n filename)\n if name in g.stylesheets:\n return \"\"\n g.stylesheets.add(name)\n return Markup(\"\".format(name))\n\n\ndef resource(filename):\n \"\"\"Returns the URL a static resource, including versioning.\"\"\"\n return \"/static/{0}/{1}\".format(config[\"version\"][\"media\"], filename)\n","sub_path":"moarcofy/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"565960424","text":"from Utilities.file_utils import dir_to_subdir_list, create_dir, delete_dir\nfrom CursorRL.Study import Study, Action\nfrom CursorRL.configuration import *\nfrom CursorRL.actions import *\nfrom random import shuffle\nimport os\n\n\nclass Environment(object):\n def __init__(self, studies_dir, stats_dir, list_of_dirs=False):\n self.WRITE_STATS_STEPS = 100\n if list_of_dirs:\n studies = []\n for dir in studies_dir:\n studies += dir_to_subdir_list(dir)\n self.studies = studies\n else:\n self.studies = dir_to_subdir_list(studies_dir)\n self.current_study_index = 0\n self.current_study = None\n self.rewards_counter = 0\n self.completed_paths_counter = 0\n\n delete_dir(stats_dir)\n create_dir(stats_dir)\n self.steps_counter = 0\n self.rewards = []\n self.path_len = []\n self.path_completed = []\n self.rewards_file = os.path.join(stats_dir, \"rewards.txt\")\n self.path_len_file = os.path.join(stats_dir, \"path_len.txt\")\n self.path_completed_file = os.path.join(stats_dir, \"path_completed.txt\")\n\n def reset(self):\n if self.steps_counter == self.WRITE_STATS_STEPS:\n self.steps_counter = 0\n Environment.write_list_to_file(self.rewards, self.rewards_file)\n Environment.write_list_to_file(self.path_len, self.path_len_file)\n Environment.write_list_to_file(self.path_completed, self.path_completed_file)\n self.rewards = []\n self.path_len = []\n self.path_completed = []\n\n if self.current_study is not None:\n self.rewards.append(self.rewards_counter)\n self.path_len.append(self.current_study.image_index - warm_frames_num)\n self.path_completed.append(self.completed_paths_counter)\n\n self.current_study = Study(self.studies[self.current_study_index])\n self.current_study_index += 1\n if self.current_study_index == len(self.studies):\n self.current_study_index = 0\n shuffle(self.studies)\n self.steps_counter += 1\n return self.current_study.get_warm_frames()\n\n def step(self, action_index, step_size=None):\n self.current_study.actions.append(action_index)\n if action_index == none_action:\n s, r, d = self.current_study.step(Action(None, None, None))\n elif action_index == click_action:\n s, r, d = self.current_study.step(Action(None, None, True))\n else:\n if step_size is None:\n step_size = self.current_study.get_GT_step_size()\n s, r, d = self.current_study.step(Action(directions[action_index - 2], step_size, None))\n self.current_study.rewards.append(r)\n self.rewards_counter += r\n if d:\n if self.current_study.finished_successfully:\n self.completed_paths_counter += 1\n\n return s, r, d\n\n def start(self):\n if self.current_study is not None:\n return self.current_study.get_image()\n\n def write_stats(self):\n Environment.write_list_to_file(self.rewards, self.rewards_file)\n Environment.write_list_to_file(self.path_len, self.path_len_file)\n Environment.write_list_to_file(self.path_completed, self.path_completed_file)\n\n @classmethod\n def write_list_to_file(cls, data_list, file_path):\n with open(file_path, \"a\") as file:\n for item in data_list:\n file.write(str(item) + \"\\n\")\n","sub_path":"TrackingByReinforcementLearning/CursorRL/Environment.py","file_name":"Environment.py","file_ext":"py","file_size_in_byte":3522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"179578268","text":"'''\n===================================================================\nProject Name : Differential Evolution\nFile Name : main.py\nEncoding : UTF-8\nCreation Date : 2021/10/19\n===================================================================\n'''\n\nimport numpy as np\nimport configuration as cf\nimport function as fc\nimport optimizer as op\nimport logger as lg\n\ndef run(opt, cnf, fnc, log):\n\topt.initialize_solutions() # 初期化\n\tlog.logging(opt.pop, fnc.total_evals) # 初期個体群ログ\n\twhile fnc.total_evals < cnf.max_evals: # 評価回数上限まで実行\n\t\topt.get_next_population() # 次世代個体群生成\n\t\tlog.logging(opt.pop, fnc.total_evals) # 次世代個体群ログ\n\tlog.outLog(opt.pop, fnc.total_evals) # ログ出力(trial'n'.csv)\n\ndef main():\n\tcnf = cf.Configuration() # configurationインスタンス生成\n\tfor i in range(len(cnf.prob_name)): # 関数の個数だけ探索\n\t\tlog = lg.Logger(cnf, cnf.prob_name[i]) # loggerインスタンス生成\n\t\tfnc = fc.Function(cnf.prob_name[i], cnf.prob_dim) # 探索する関数のインスタンス生成\n\t\tfor j in range(cnf.max_trial): # 試行回数まで実行\n\t\t\tfnc.resetTotalEvals() # 総評価回数(functionクラス内変数)リセット\n\t\t\tcnf.setRandomSeed(seed = j + 1) # ランダムシード値設定\n\t\t\topt = op.DifferentialEvolution(cnf, fnc) # optimizerインスタンス生成\n\t\t\trun(opt, cnf, fnc, log) # 探索実行\n\t\tsts = lg.Statistics(cnf, fnc, log.path_out, log.path_trial) # 関数ごとの統計を作成\n\t\tsts.outStatistics() # 統計出力(all_trials.csv, statistics.csv)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"348846221","text":"# -*- coding: utf-8 -*-\n# @Author: Puffrora\n# @Date: 2019-09-27 23:11:58\n# @Last Modified by: Puffrora\n# @Last Modified time: 2019-09-27 23:28:55\n\n\nclass Solution:\n\tdef readBinaryWatch(self, num):\n\n\t\tdef count1(n):\n\t\t\tres = 0\n\t\t\twhile n != 0:\n\t\t\t\tn &= n - 1\n\t\t\t\tres += 1\n\t\t\treturn res\n\n\t\tres = []\n\n\t\tfor i in range(0, 12):\n\t\t\tfor j in range(0, 60):\n\t\t\t\tif count1(i) + count1(j) == num:\n\t\t\t\t\tres.append(str(i) + ':' + str(j) if j >= 10 else str(i) + ':' + '0' + str(j))\n\n\t\treturn res\n\n\t\t","sub_path":"Leetcode/leetcode401 二进制手表.py","file_name":"leetcode401 二进制手表.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"65710590","text":"import uuid\nimport json #, msgpack, snappy\n\nclass _Request_jsonrpc_v20: # (Event):\n \"\"\" A rpc call is represented by sending a Request object to a Server.\n \"\"\"\n \n JSON_RPC_VERSION = '2.0'\n JSON_RPC_DUMMY_ID = object()\n\n def __init__ (self, clientSession, payloadData):\n \n # Identity of the client session\n self.session = clientSession\n\n # NB: notification is not support by now \n if \"id\" not in payloadData:\n payloadData['id'] = uuid.uuid4().__str__() #.bytes\n\n # Original message data from rpc call\n self.data = payloadData\n\n # Enforce to specify the version of the JSON-RPC protocol.\n if \"jsonrpc\" not in payloadData:\n self.data[\"jsonrpc\"] = _Request_jsonrpc_v20.JSON_RPC_VERSION\n\n # A String containing the name of the method to be invoked. \n # Method names that begin with the word rpc followed by a period character (U+002E or ASCII 46) \n # are reserved for rpc-internal methods and extensions and MUST NOT be used for anything else. \n self.method = payloadData.get ('method')\n \n # A Structured value that holds the parameter values to be used during the invocation\n # of the method. This member MAY be omitted.\n self.params = payloadData.get ('params')\n\n # The Identifier that established by the Client that MUST contain a `String`, `Number`, or `NULL` \n # if included. If it is not included it is assumed to be a notification. The value SHOULD normally\n # not be Null [1] and Numbers SHOULD NOT contain fractional parts [2].\n #\n # [1] The use of Null as a value for the id member in a Request object \n # is discouraged, because this specification uses a value of Null for Responses \n # with an unknown id. Also, because JSON-RPC 1.0 uses an id value of Null\n # for Notifications this could cause confusion in handling.\n #\n # [2] Fractional parts may be problematic, since many decimal fractions\n # cannot be represented exactly as binary fractions.\n self.identity = payloadData.get ('id')\n\n\nclass _Response_jsonrpc_v20:\n \"\"\" When a rpc call is made, the Server MUST reply with a Response, except that \n in the case of Notifications. The Response is expressed as a single JSON Object.\n \"\"\"\n\n JSON_RPC_VERSION = '2.0'\n JSON_RPC_NO_ERROR = [0, '']\n \n def __init__(self, sessionRequest, resultData, errorData):\n \n # Client session of rpc call.\n self.session = sessionRequest.session\n\n # Message data payload of reply of a rpc call.\n self.data = dict()\n\n # A String specifying the version of the JSON-RPC protocol. MUST be exactly \"2.0\".\n self.data['jsonrpc'] = _Response_jsonrpc_v20.JSON_RPC_VERSION\n\n # `id` is REQUIRED. It MUST be the same as the value of the id member \n # in the Request Object. If there was an error in detecting the id in \n # the Request object (e.g. Parse error/Invalid Request), it MUST be Null.\n self.data['id'] = sessionRequest.identity\n\n # Either the result member or error member MUST be included, but both \n # members MUST NOT be included.\n #\n if resultData is not None:\n # The `result` field is REQUIRED on success. It MUST NOT exist \n # if there was an error invoking the method. The value of this \n # field is determined by the method invoked on the Server.\n self.data['result'] = resultData\n if errorData:\n # The `error` field is REQUIRED on error. It MUST NOT exist if \n # there was no error triggered during invocation. The value for \n # this field MUST be an Object.\n # NB: JAQS, this field maybe exist on success, with empty payload,\n # that is NOT consist with JSON-RPC specification.\n self.data['error'] = { \n \"code\" : errorData[0], \n 'message' : errorData[1] \n }\n\nclass _Respond_jsonrpc_v20:\n\n def __init__( self, clientSession, returnData):\n # @copydoc: _Response_jsonrpc_v20.client\n self.session = clientSession\n # @copydoc: _Response_jsonrpc_v20.data\n self.data = returnData\n # @copydoc: _Response_jsonrpc_v20.data[\"id\"]\n self.identity = returnData.get(\"id\")\n # @copydoc: _Response_jsonrpc_v20.data[\"result\"]\n self.result = returnData.get(\"result\")\n # @copydoc: _Response_jsonrpc_v20.data[\"error\"]\n self.error = returnData.get(\"error\")\n","sub_path":"rqalpha/mod/rqalpha_mod_sys_stock_realtime/jsonrpc/jsonrpc_protocol.py","file_name":"jsonrpc_protocol.py","file_ext":"py","file_size_in_byte":4612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"551791350","text":"import json\nimport os\n\nimport downloader\n\n\ndef return_local_db():\n os.chdir(os.environ['HOMEPATH'])\n os.chdir('./desktop')\n\n local_dic = dict()\n with open('db_template.json', 'r', encoding='UTF-8') as f:\n temp = json.loads(f.read())\n local_dic.update(temp)\n return local_dic\n\ndef return_compare_dic():\n local_db = return_local_db()\n data = downloader.update() #최신 DB를 받아옴.\n added_dic = dict()\n \n for x in local_db: #추가된 것만 골라서 받아옴\n if x in data:\n continue\n \n else:\n added_dic[x] = local_db[x]\n return added_dic\n\n\nif __name__ == '__main__':\n return_compare_dic()\n","sub_path":"Old/localdb.py","file_name":"localdb.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"502004433","text":"import os\nimport csv\n\nfile = os.path.join(\"Resources\",\"election_data.csv\")\n\ntotal_votes = 0\n\n#setting candidate and number of volutes as key and values in dictionary\nvote_counter = {}\n\n#reading csv file\nwith open(file) as data:\n csvreader = csv.reader(data,delimiter = \",\")\n header = next(csvreader)\n # Loop through all candidate names and add a new name each time one appears\n for row in csvreader:\n candidate = row[2]\n if candidate in vote_counter.keys():\n vote_counter[candidate] += 1\n else:\n vote_counter[candidate] = 1\n \n total_votes += 1\n\n#print(vote_counter) \nwinner = max(vote_counter, key = vote_counter.get)\n\nResults = f\"\"\"\nElection Reults\n-------------------------\nTotal Votes: {total_votes}\n-------------------------\"\"\"\n\nfor k, v in vote_counter.items():\n percentage = v / total_votes\n Results += k + ': ' + '{:.3%}'.format(percentage) + ', (' + str(v) +')\\n'\n\nResults += f\"\"\"-------------------------\nWinner: {winner}\n-------------------------\"\"\"\nprint(Results)\n\noutput_file = \"output_file.txt\"\nwith open(output_file, \"w\") as doc:\n doc.write(Results)\n","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"455766028","text":"\"\"\" Grid size test\n\n.. note:: An example config would be::\n\n name:\n example\n\n Tests::\n\n tests:\n 1:\n signals:\n data/klz/v1.0.0/Xe136_0n2b_n1_fig2.hdf5:\n fit_config:\n \"{spectral_fit_parameters: {rate: {logscale: false,\n logscale_deviation: True, high: 136.201323346,\n prior: 45.40044111532344, low: 0.0, sigma: None\n bins: 501}}}\"\n backgrounds:\n data/klz/v1.0.0/Xe136_2n2b_fig2.hdf5:\n fit_config:\n \"{spectral_fit_parameters: {rate: {\n logscale_deviation: False,\n high: 59328.506876615706, prior: 51322.23778253954\n low: 43315.96868846337, sigma: None, bins: 501}}}\"\n\n Followed by other tests with config altered. E.g. same signal\n config but background config has a smaller range::\n\n 2:\n signals:\n data/klz/v1.0.0/Xe136_0n2b_n1_fig2.hdf5:\n fit_config:\n \"{spectral_fit_parameters: {rate: {logscale: false,\n logscale_deviation: True, high: 136.201323346,\n prior: 45.40044111532344, low: 0.0, sigma: None\n bins: 501}}}\"\n backgrounds:\n data/klz/v1.0.0/Xe136_2n2b_fig2.hdf5:\n fit_config:\n \"{spectral_fit_parameters: {rate: {\n logscale_deviation: False,\n **high: 53990.9941472**, prior: 51322.23778253954,\n **low: 48653.48141787908**, sigma: None,\n bins: 501}}}\"\n\n\nCreated on Wed Mar 9 14:03:00 2016\n\n@author: ashley\n\"\"\"\nimport echidna.utilities as utilities\nimport echidna.output.store as store\nfrom echidna_analysis.ops.update_spectrum import update_spectrum\nimport echidna.scripts.klz_majoron_limits as klz_majoron_limits\n\nimport yaml\n\n\ndef main(args):\n \"\"\" Main script\n \"\"\"\n logger = utilities.start_logging(short_name=True)\n\n # Load tests from file\n if args.update_from is not None:\n with open(args.update_from, \"r\") as stream:\n logger.info(\"Loading tests from %s\" % args.update_from)\n update_from = yaml.load(stream)\n else:\n logger.warning(\"No option update_from, no tests have been loaded\")\n update_from = {}\n\n name = update_from[\"name\"]\n\n # Loop through tests\n tests = update_from[\"tests\"]\n logger.info(\"Loaded %d tests\" % len(tests))\n for test, test_dict in tests.iteritems():\n logger.info(\"Setting up test %d\" % test)\n\n # loop through signals\n signals = []\n for signal_file, signal_dict in test_dict[\"signals\"].iteritems():\n # Load spectrum\n signal = store.load(signal_file)\n\n # Update spectrum\n update_spectrum(signal, **signal_dict)\n signals.append(signal)\n\n # loop through backgrounds\n floating_backgrounds = []\n for background_file, background_dict in\\\n test_dict[\"backgrounds\"].iteritems():\n # load background\n background = store.load(background_file)\n\n # Update spectrum\n update_spectrum(background, **background_dict)\n floating_backgrounds.append(background)\n\n # Run limit script for test\n klz_majoron_limits.main(args, name=name, signals=signals,\n floating_backgrounds=floating_backgrounds)\n\n\nif __name__ == \"__main__\":\n from echidna.scripts.klz_majoron_limits import ReadableDir\n import echidna.output as output\n\n import argparse\n\n parser = argparse.ArgumentParser(\n description=\"KamLAND-Zen (plot-grab) Majoron limits script\")\n parser.add_argument(\"--from_file\", action=ReadableDir,\n help=\"Path to config file containing arg values\")\n parser.add_argument(\"--update_from\", action=ReadableDir,\n help=\"Path to config for updating spectra\")\n parser.add_argument(\"-s\", \"--save_path\", action=ReadableDir,\n help=\"Path to save all ouput files to. \"\n \"Overrides default from output module.\")\n parser.add_argument(\"--floating\", nargs=\"*\", help=\"Parse floating \"\n \"background spectra directly\")\n parser.add_argument(\"--signals\", nargs=\"*\", help=\"Parse signal spectra \"\n \"directly\")\n parser.add_argument(\"--sensitivity\", action=\"store_true\",\n help=\"Use expected background as data. Note a blank \"\n \"'data' spectrum must still be supplied, which will \"\n \"then be filled with the appropriate expected \"\n \"background spectrum.\")\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\"--lower_bound\", action=\"store_true\",\n help=\"Estimate lower bound on limit \"\n \"due to plot-grab errors\")\n group.add_argument(\"--upper_bound\", action=\"store_true\",\n help=\"Estimate upper bound on limit \"\n \"due plot-grab errors\")\n args = parser.parse_args()\n\n if args.save_path is not None:\n output.__default_save_path__ = args.save_path\n\n main(args)\n","sub_path":"jobs/grid_size_test.py","file_name":"grid_size_test.py","file_ext":"py","file_size_in_byte":5573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"67452383","text":"import tkinter as tk\nfrom pytube import YouTube\n\ndef clickUrl():\n labelMsg.config(text=\"\")\n if(url.get()==\"\"):\n labelMsg.config(text=\"請輸入網址\")\n else:\n try:\n yt=YouTube()\n yt.url=url.get()\n video=yt.get(\"mp4\",\"360p\")\n video.download('.')\n labelMsg.config(text=\"下載完成\")\n except:\n labelMsg.config(text=\"出現了一些錯誤\")\n\nwin = tk.Tk()\nwin.geometry(\"450x320\")\nwin.title('下載Youtube影片')\nurl = tk.StringVar()\nframe1= tk.Frame(win,width=450)\nframe1.pack()\nlabel1=tk.Label(frame1,text=\"Youtube 網址:\")\nentryUrl = tk.Entry(frame1,textvariable=url)\nentryUrl.config(width=40)\nbtnUrl=tk.Button(frame1,text=\"確定下載\",command=clickUrl)\nlabel1.grid(row=0,column=0,sticky=\"e\")\nentryUrl.grid(row=0,column=1)\nbtnUrl.grid(row=0,column=2)\nlabelMsg =tk.Label(win,text=\"\",fg=\"red\")\nlabelMsg.pack()\n\nwin.mainloop()\n\n","sub_path":"6.youtube/youtube_tinker.py","file_name":"youtube_tinker.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"15568401","text":"import numpy as np\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn import linear_model\r\n\r\ndef cost(x):\r\n\tm = A.shape[0]\r\n\treturn 0.5/m * np.linalg.norm(A.dot(x)-b,2)**2\r\ndef grad(x):\r\n\tm = A.shape[0]\r\n\treturn 1/m * A.T.dot(A.dot(x)-b)\r\ndef check_grad(x):\r\n\teps = 1e-4 \r\n\tg = np.zeros_like(x)\r\n\tfor i in range(len(x)):\r\n\t\tX1 = x.copy()\r\n\t\tx2 = x.copy()\r\n\t\tx1[i] +=eps\r\n\t\tx2[i] -=eps\r\n\t\tg[i] = (cost(x1) - cost(x2))/(2*eps)\r\n\r\n\tg_grad = grad(x)\r\n\tif np.linalg.norm(g-g_grad) > 1e-5:\r\n\t\tprint(\"WARNING: CHECK GRADIENT FUNCTION! \")\r\n\r\n \t\r\ndef gradient_descent(x_init,learning_rate,iteration):\r\n\tx_list = [x_init]\r\n\tm = A.shape[0]\r\n\tfor i in range(iteration):\r\n\t\tx_new = x_list[-1] - learning_rate*grad(x_list[-1])\r\n\t\tif np.linalg.norm(grad(x_new))/len(x_new) < 0.5:\r\n\t\t\tbreak\r\n\t\tx_list.append(x_new) \r\n\r\n\treturn x_list\r\n\r\n\r\n\r\n# Random data\r\nA = np.array([[2,5,7,9,11,16,19,23,22,29,29,35,37,40,46]]).T\r\nb = np.array([[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]]).T\r\n\r\n# Create model\r\nfig1 = plt.figure(\"GD for LinearRegression\")\r\nax = plt.axes(xlim=(-10,60),ylim=(-1,20))\r\n\r\nplt.plot(A,b,'ro')\r\nlr = linear_model.LinearRegression()\r\nlr.fit(A,b)\r\nx0_gd = np.linspace(1,46,2)\r\ny0_sklearn = lr.intercept_[0] + lr.coef_[0][0]*x0_gd\r\nplt.plot(x0_gd,y0_sklearn,color=\"green\")\r\n\r\nones = np.ones((A.shape[0],1),dtype=np.int8)\r\nA = np.concatenate((ones,A),axis=1)\r\n# Random initial line\r\nx_init = np.array([[1.],[2.]])\r\ny0_init = x_init[0][0] + x_init[1][0]*x0_gd\r\nplt.plot(x0_gd,y0_init,color=\"black\")\r\n\r\niteration = 60\r\nlearning_rate = 0.0001\r\nx_list = gradient_descent(x_init,learning_rate,iteration)\r\nfor i in range(len(x_list)):\r\n\ty0_x_list = x_list[i][0] + x_list[i][1]*x0_gd\r\n\tplt.plot(x0_gd,y0_x_list,color=\"black\")\r\nplt.show()\r\ncost_list = []\r\niter_list = []\r\nfor i in range(len(x_list)):\r\n\titer_list.append(i)\r\n\tcost_list.append(cost(x_list[i]))\r\nplt.plot(iter_list,cost_list)\r\nplt.xlabel('Iteration')\r\nplt.ylabel('Cost value')\r\nplt.show()","sub_path":"AI/LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"511186840","text":"#10/15/14\r\n#This program will ask the user to enter a series of postivie numbers.\r\n#Then the program will ask for a negative number to end the series.\r\n#The program will add all of the positive numbers and display the sum\r\n\r\n#x is the user input number\r\n\r\nsum=0\r\nprint(\"Please enter a negative number when you wish to stop entering numbers.\")\r\nx=int(input(\"Please enter your number: \"))\r\nwhile x>=0:\r\n sum=sum+x\r\n x=int(input(\"Please enter your number: \"))\r\n \r\nprint(\"The sum of your numbers is: \",sum)\r\n \r\n","sub_path":"Week 7 Py Labs/postivie series adder.py","file_name":"postivie series adder.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"627622555","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 14 12:38:31 2016\n\n@author: rex\n\"\"\"\nimport pandas as pd\nfrom Lib.Option import *\nimport matplotlib.pyplot as plt\nfrom os import getcwd\nfrom math import exp\n\n\ndef hedge_criteria(Yt_1, delta_t, lower_gamma, e, upper_gamma, St, r, T, t):\n\t'''return how much to buy/sell or to do nothing. \n\tWhich is worthy of noticing is that the upper_gamma is a\n\tquantity-weighted gamma of a portfolio'''\n\tBt = ((3 * e * St * exp(-r*(T-t)) * upper_gamma**2) \\\n\t\t / (2*lower_gamma))**(1/3)\n\tlower = delta_t - Bt\n\tupper = delta_t + Bt\n\tif lower <= Yt_1 <= upper: return (0, upper, lower)\n\telif Yt_1 > upper: return (upper - Yt_1, upper, lower)\n\telse: return (lower - Yt_1, upper, lower)\n\ndate_lst = pd.read_csv(getcwd()+\"/Lib/Data/a\", encoding=\"gbk\").loc[1808:1964, \"日期\"].values.tolist()\nprice_lst = pd.read_csv(getcwd()+\"/Lib/Data/a\", encoding=\"gbk\").loc[1808:1964, \"收盘价\"].values.tolist()\n\noption = EuropeanOptionPut(K=4800, T=(1964 - 1808) / 252, r=0.05, q=0.01, target=\"\")\n_sigmma = 20\nposition = 0\n\ncost_lst = []\nbuy_or_sell_lst = []\nrange_upper_lst = []\nrange_lower_lst = []\ndelta_lst = []\ndelta_before_lst = []\n_t = 0\n\nfor i in price_lst: \n option.update_info(t=_t, St=i, sigmma=_sigmma)\n delta = option.get_delta() * 1e4 + position * 1\n delta_before_lst.append(delta)\n gamma = option.get_gamma() * 1e4 \n \n change, upper, lower = hedge_criteria(Yt_1=position, delta_t=delta,\n lower_gamma=1, e=0.15, \n upper_gamma=gamma, St=i, r=0.05, \n T=(1964 - 1808) / 252, t=_t)\n change = round(change)\n position += change\n \n delta_lst.append(position * 1 + option.get_delta() * 1e4) \n cost_lst.append(change * i * 1.15)\n buy_or_sell_lst.append(change)\n range_upper_lst.append(upper)\n range_lower_lst.append(lower)\n _t += 1 / 252\n \n\n#plt.plot(price_lst)\n#plt.plot(cost_lst)\n#plt.plot(buy_or_sell_lst)\n#plt.plot(range_upper_lst)\n#plt.plot(range_lower_lst)\nplt.plot(delta_lst)\n#plt.plot(delta_before_lst)\n\nplt.show()\n\n","sub_path":"easy.py","file_name":"easy.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"392969298","text":"from typing import List, Optional\n\n\ndef get_example_scope(\n method: str,\n path: str,\n extra_headers=None,\n query: Optional[bytes] = b\"\",\n scheme: str = \"http\",\n server: Optional[List] = None,\n):\n \"\"\"Returns mocked ASGI scope\"\"\"\n\n if \"?\" in path:\n raise ValueError(\"The path in ASGI messages does not contain query string\")\n if query.startswith(b\"\"):\n query = query.lstrip(b\"\")\n if server is None:\n server = [\"127.0.0.1\", 8000]\n return {\n \"type\": scheme,\n \"http_version\": \"1.1\",\n \"server\": server,\n \"client\": [\"127.0.0.1\", 51492],\n \"scheme\": scheme,\n \"method\": method,\n \"root_path\": \"\",\n \"path\": path,\n \"raw_path\": path.encode(),\n \"query_string\": query,\n \"headers\": [\n (b\"host\", b\"127.0.0.1:8000\"),\n (\n b\"user-agent\",\n (\n b\"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; \"\n b\"rv:63.0) Gecko/20100101 Firefox/63.0\"\n ),\n ),\n (\n b\"accept\",\n (\n b\"text/html,application/xhtml+xml,\"\n b\"application/xml;q=0.9,*/*;q=0.8\"\n ),\n ),\n (b\"accept-language\", b\"en-US,en;q=0.9,it-IT;q=0.8,it;q=0.7\"),\n (b\"accept-encoding\", b\"gzip, deflate\"),\n (b\"connection\", b\"keep-alive\"),\n (b\"upgrade-insecure-requests\", b\"1\"),\n ]\n + ([tuple(header) for header in extra_headers] if extra_headers else []),\n }\n","sub_path":"blacksheep/testing/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"620174722","text":"__author__ = 'Marth'\n\nimport csv\n# from pprint import pprint\n\npokemoves = set()\nmovemethods = {}\n\nwith open('dex/pokemon_move_method_prose.csv', 'r') as csvfile:\n movereader = csv.reader(csvfile)\n movereader.next()\n\n for row in movereader:\n if row[1] == '9':\n movemethods[int(row[0])] = row[2]\n\nwith open('dex/pokemon_moves.csv', 'r') as csvfile:\n movereader = csv.reader(csvfile)\n movereader.next()\n\n for row in movereader:\n if row[1] == '15':\n temp = (int(row[0]), int(row[2]), int(row[3]))\n pokemoves.add(temp)\n\n# pprint(pokemoves)\n\n# write everything to file\nwith open('out/poke_moves.csv', 'w') as csvfile:\n header = 'poke_id,move_id,move_method_id\\n'\n csvfile.write(header)\n for move in pokemoves:\n csvfile.write(','.join(map(str, move)) + '\\n')\n\nwith open('out/poke_move_methods.csv', 'w') as csvfile:\n header = 'move_method_id,move_method_text\\n'\n csvfile.write(header)\n for move in movemethods:\n csvfile.write(str(move) + ',' + movemethods[move] + '\\n')","sub_path":"GenPokeMoves.py","file_name":"GenPokeMoves.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"170219673","text":"class Player:\n\n def __init__(self,ArmorVal,level,dam,swrd):\n self.name = \"Max\"\n self.hp = 20 + (2 * (level / 1.5) + ArmorVal)\n self.dmg = dam + (1 + (level + swrd))\n self.inventory = [\"Fists\",\"Legs\",\"Ripped Clothing\",\"Glass Vial\"]\n\n def display(self):\n self.hp = round(self.hp)\n print(\"Name: \" + str(self.name))\n print(\"HP: \" + str(self.hp))\n print(\"Inventory:\")\n print('\\n'.join(self.inventory))\n\n def addItem(self,x):\n if x in room:\n self.inventory.append(x)\n room.remove(x)\n else:\n print(\"No item exists in room!\")\n\n def removeItem(self,x):\n if x in room:\n self.inventory.remove(x)\n room.append(x)\n else:\n print(\"No item exists in inventory!\")\n\n","sub_path":"Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"487435061","text":"from django import forms\n\nfrom django.core.exceptions import ValidationError\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext as _\nfrom phonenumber_field.formfields import PhoneNumberField\n\nfrom country.models import Country\n\nFUNDING_TYPE_CHOICES = [\n ('', '---'),\n ('BBSRC funded', 'BBSRC funded'),\n ('Non-commercial', 'Other non-commercial (Academic/Charity)'),\n ('Industry', 'Industry'),\n ('Internal UoB', 'Internal, University of Birmingham')\n]\n\nREFERRAL_TYPE_CHOICES = [\n ('', '---'),\n ('SGM 2016', 'SGM Conference 2016'),\n ('Internal UoB', 'Internal UoB'),\n ('Word of mouth', 'Word of mouth'),\n ('Google', 'Google'),\n ('Twitter', 'Twitter'),\n ('Publication', 'Publication'),\n ('Other conference', 'Other conference')\n]\n\nBATCH_TYPE_CHOICES = [\n ('all together', 'Sending all samples together'),\n ('batches', 'Sending in multiple batches')\n]\n\nNAME_TITLE_CHOICES = [\n ('', ''),\n ('Dr', 'Dr'),\n ('Prof', 'Prof'),\n ('Mr', 'Mr'),\n ('Miss', 'Miss'),\n ('Ms', 'Ms'),\n ('Mrs', 'Mrs'),\n ('Mx', 'Mx'),\n ('Sir', 'Sir'),\n ('Lord', 'Lord')\n]\n\n\nclass QuoteRequestForm(forms.Form):\n name_title = forms.ChoiceField(\n choices=NAME_TITLE_CHOICES,\n label=_(\"Title\"),\n required=False)\n name_first = forms.CharField(max_length=50, label=_(\"First name\"))\n name_last = forms.CharField(max_length=50, label=_(\"Last name\"))\n email = forms.EmailField(label=_(\"Email address\"))\n phone = PhoneNumberField(\n label=_(\"Phone number\"),\n help_text=_(\"International customers: please enter a country code \"\n \"e.g. +1-541-754-3010 for a US number.\"))\n primary_contact_is_pi = forms.BooleanField(\n label=\"Same as primary contact\",\n required=False)\n pi_name_title = forms.ChoiceField(\n choices=NAME_TITLE_CHOICES,\n label=_(\"Title\"),\n required=False)\n pi_name_first = forms.CharField(\n label=_(\"First name\"),\n max_length=50,\n required=False)\n pi_name_last = forms.CharField(\n label=_(\"Last name\"),\n max_length=50,\n required=False)\n pi_email = forms.EmailField(label=_(\"Email address\"), required=False)\n organisation = forms.CharField(\n max_length=50,\n label=_(\"Institution / Company\"))\n department = forms.CharField(max_length=50, required=False)\n street_line_1 = forms.CharField(\n max_length=50,\n label=_(\"Address lines\"),\n widget=forms.TextInput(\n attrs={'placeholder': \"e.g. Room W126, Biosciences building.\"}))\n street_line_2 = forms.CharField(\n max_length=50,\n label=_(\"Address line 2\"),\n required=False)\n street_line_3 = forms.CharField(\n max_length=50,\n label=_(\"Address line 3\"),\n required=False)\n city = forms.CharField(max_length=50)\n region = forms.CharField(\n max_length=50,\n label=_(\"Region / State\"),\n required=False)\n postcode = forms.CharField(\n max_length=10,\n label=_(\"Postcode / Zip\"),\n required=False)\n country = forms.ModelChoiceField(\n queryset=Country.objects.all(),\n to_field_name='name',\n widget=forms.TextInput(),\n error_messages={\n 'required': \"Sample collection country is required.\",\n 'invalid_choice': \"Please select a valid country from the list.\"\n })\n funding_type = forms.ChoiceField(choices=FUNDING_TYPE_CHOICES)\n bbsrc_code = forms.CharField(required=False, label=_(\"BBSRC grant code\"))\n is_confidential = forms.BooleanField(required=False)\n num_dna_samples = forms.IntegerField(\n min_value=0,\n initial=0,\n required=False,\n label=_(\"No. of DNA samples\"))\n num_strain_samples = forms.IntegerField(\n min_value=0,\n initial=0,\n required=False,\n label=_(\"No. of strain samples\"))\n num_enhanced_strain_samples = forms.IntegerField(\n min_value=0,\n initial=0,\n required=False,\n label=_(\"No. strains for enhanced sequencing\"))\n confirm_strain_bsl2 = forms.BooleanField(\n required=False,\n label=_(mark_safe(\"Confirm that your strains comply with the strain submission criteria\")))\n confirm_enhanced_strain_bsl2 = forms.BooleanField(\n required=False,\n label=_(mark_safe(\"Confirm that your enhanced strains comply with the strain submission criteria\")))\n batch_type = forms.ChoiceField(\n choices=BATCH_TYPE_CHOICES,\n initial='all together')\n referral_type = forms.ChoiceField(\n choices=REFERRAL_TYPE_CHOICES,\n label=_(\"Where did you hear about us?\"))\n comments = forms.CharField(required=False, widget=forms.Textarea())\n\n def clean(self):\n cleaned_data = super(QuoteRequestForm, self).clean()\n non_field_errors = []\n\n funding_type = cleaned_data.get('funding_type')\n bbsrc_code = cleaned_data.get('bbsrc_code')\n num_dna_samples = cleaned_data.get('num_dna_samples')\n num_strain_samples = cleaned_data.get('num_strain_samples')\n num_enhanced_strain_samples = cleaned_data.get(\"num_enhanced_strain_samples\")\n confirm_strain_bsl2 = cleaned_data.get('confirm_strain_bsl2')\n confirm_enhanced_strain_bsl2 = cleaned_data.get('confirm_enhanced_strain_bsl2')\n primary_contact_is_pi = cleaned_data.get('primary_contact_is_pi')\n pi_name_title = cleaned_data.get('pi_name_title')\n pi_name_first = cleaned_data.get('pi_name_first')\n pi_name_last = cleaned_data.get('pi_name_last')\n pi_email = cleaned_data.get('pi_email')\n comments = cleaned_data.get('comments')\n\n if num_strain_samples is None:\n num_strain_samples = 0\n if num_dna_samples is None:\n num_dna_samples = 0\n if num_enhanced_strain_samples is None:\n num_enhanced_strain_samples = 0\n\n if primary_contact_is_pi:\n cleaned_data['pi_name_title'] = ''\n cleaned_data['pi_name_first'] = ''\n cleaned_data['pi_name_last'] = ''\n cleaned_data['pi_email'] = ''\n else:\n if not pi_name_first:\n self.add_error(\n 'pi_name_first',\n ValidationError(_(\"Principal investigator first name is required.\"),\n code='required'))\n if not pi_name_last:\n self.add_error(\n 'pi_name_last',\n ValidationError(_(\"Principal investigator last name is required.\"),\n code='required'))\n if not pi_email:\n self.add_error(\n 'pi_email',\n ValidationError(_(\"Principal investigator email is required.\"),\n code='required'))\n\n if (funding_type == 'BBSRC funded' and not bbsrc_code):\n bbsrc_error = ValidationError(_(\"BBSRC code is required.\"))\n self.add_error('bbsrc_code', bbsrc_error)\n non_field_errors.append(bbsrc_error)\n\n if (num_strain_samples > 0 and not confirm_strain_bsl2):\n bsl2_error = ValidationError(\n _(\"You must confirm that your strains comply with the strain submission criteria.\"))\n self.add_error('confirm_strain_bsl2', bsl2_error)\n non_field_errors.append(bsl2_error)\n\n if (num_enhanced_strain_samples > 0 and not confirm_enhanced_strain_bsl2):\n enhanced_bsl2_error = ValidationError(\n _(\"You must confirm that your enhanced strains comply with the strain submission criteria.\"))\n self.add_error('confirm_enhanced_strain_bsl2', enhanced_bsl2_error)\n non_field_errors.append(enhanced_bsl2_error)\n\n if not (num_strain_samples or num_dna_samples or num_enhanced_strain_samples):\n non_field_errors.append(\n ValidationError(\n _(\"A total sample quantity of at least one (strain or DNA)\"\n \" is required.\"))\n )\n\n if non_field_errors:\n raise ValidationError(non_field_errors)\n\n\n # If there were no validation errors\n # Prepend <=BSL2 & non-GMM confirmation(s) to comments field for displaying in the LIMS\n\n criteria_confirmations = []\n\n if num_strain_samples > 0 and confirm_strain_bsl2:\n criteria_confirmations.append('Confirmed that strains comply with strain submission criteria')\n if num_enhanced_strain_samples > 0 and confirm_enhanced_strain_bsl2:\n criteria_confirmations.append('Confirmed that enhanced strains comply with strain submission criteria')\n\n # If there are confirmations to add, add them with CRLF line endings as given by the HTML textarea\n if len(criteria_confirmations) > 0:\n criteria_confirmations_str = '\\r\\n'.join(criteria_confirmations)\n if not comments:\n cleaned_data['comments'] = criteria_confirmations_str\n else:\n cleaned_data['comments'] = '{}\\r\\n\\r\\n{}'.format(criteria_confirmations_str, comments)\n\n return cleaned_data\n","sub_path":"source/quote/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":9242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"301598138","text":"import numpy as np\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torch.optim as optim\n\ntransform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\ntrain_set = torchvision.datasets.CIFAR10(root='/home/welcome/Downloads/ml_ai_dl', train=True, download=True, transform=transform)\ntest_set = torchvision.datasets.CIFAR10(root='/home/welcome/Downloads/ml_ai_dl', train=False, download=True, transform=transform)\n\ndef get_train_loader(batchsize):\n\ttrain_loader = torch.utils.data.DataLoader(train_set, batch_size=batchsize, shuffle=True, num_workers=2)\n\treturn train_loader\n\n\nclasses = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\nclass CNNModel(torch.nn.Module):\n\t\n\t# shape of input x is (batchsize, 3, 32, 32)\n\t\n\tdef __init__(self):\n\t\tsuper(CNNModel, self).__init__()\n\t\t\n\t\t#Input channels = 3, output channels = 6\n\t\tself.conv1 = torch.nn.Conv2d(3, 6, kernel_size=5, stride=1)\n\t\tself.pool = torch.nn.MaxPool2d(kernel_size=2, stride=2)\n\t\t\n\t\tself.conv2 = torch.nn.Conv2d(6, 16, kernel_size=5, stride=1)\n\t\t#400 input features, 120 output features (see sizing flow below)\n\t\tself.drop = torch.nn.Dropout(p=0.3)\n\t\tself.fc1 = torch.nn.Linear(16*5*5, 120)\n\t\tself.fc2 = torch.nn.Linear(120, 84)\n\t\t#64 input features, 10 output features for our 10 defined classes\n\t\tself.fc3 = torch.nn.Linear(84, 10)\n\t\t\n\tdef forward(self, x):\n\t\t#Size changes from (batchsize, 3, 32, 32) to (batchsize, 6, 28, 28)\n\t\tx = self.conv1(x)\n\t\tx = F.relu(x)\n\t\t#Size changes from (batchsize, 6, 28, 28) to (batchsize, 6, 14, 14)\n\t\tx = self.pool(x)\n\t\t#Size changes from (batchsize, 6, 28, 28) to (batchsize, 16, 10, 10)\n\t\tx = self.conv2(x)\n\t\tx = F.relu(x)\n\t\t#Size changes from (batchsize, 16, 10, 10) to (batchsize, 16, 10, 10)\n\t\tx = self.pool(x)\n\t\t#flattening the input from (batchsize, 16, 5, 5) to (batchsize, *)\n\t\tx = x.view(x.shape[0], -1)\n\t\t#Size changes from (batchsize, 400) to (batchsize, 120)\n\t\t#x = self.drop(x)\n\t\tx = F.relu(self.fc1(x))\n\t\t#Size changes from (batchsize, 120) to (batchsize, 84)\n\t\t#x = self.drop(x)\n\t\tx = F.relu(self.fc2(x))\n\t\t#size changes from (batchsize, 84) to (batchsize, 10)\n\t\t#x = self.drop(x)\n\t\tx = self.fc3(x)\n\t\treturn(x)\n\ndef createLossAndOptimizer(net, learning_rate=0.001):\n\t\n\t#Loss function\n\tloss = torch.nn.CrossEntropyLoss()\n\t\n\t#Optimizer\n\toptimizer = optim.Adam(net.parameters(), lr=learning_rate)\n\t\n\treturn(loss, optimizer)\n\n\ndef trainNet(model, batch_size, n_epochs, learning_rate):\n\t#Get training data\n\ttrain_loader = get_train_loader(batch_size)\n\tn_batches = len(train_loader)\n\t\n\t#Create our loss and optimizer functions\n\tloss, optimizer = createLossAndOptimizer(model, learning_rate)\n\t\n\t#Loop for n_epochs\n\tfor epoch in range(n_epochs):\n\t\t\n\t\tfor i, data in enumerate(train_loader, 0):\n\t\t\t\n\t\t\t#Get inputs\n\t\t\timages, labels = data\n\t\t\t\n\t\t\t#Wrap them in a Variable object\n\t\t\timages, labels = Variable(images), Variable(labels)\n\t\t\t\n\t\t\t#Set the parameter gradients to zero\n\t\t\toptimizer.zero_grad()\n\n\t\t\t#Forward propagation \n\t\t\toutputs = model(images) \n\t\t\t\n\t\t\t#Calculating loss with softmax to obtain cross entropy loss\n\t\t\tloss_size = loss(outputs, labels)\n\t\t\n\t\t\t#Backward propation\n\t\t\tloss_size.backward()\n\t\t\n\t\t\t#Updating gradients\n\t\t\toptimizer.step() \n\t\t\t\n\t\t\t#Total number of labels\n\t\t\ttotal = labels.size(0)\n\t\t\n\t\t\t#Obtaining predictions from max value\n\t\t\t_, predicted = torch.max(outputs.data, 1)\n\t\t\n\t\t\t#Calculate the number of correct answers\n\t\t\tcorrect = (predicted == labels).sum().item()\n\t\t\n\t\t\tif (i + 1) % 100 == 0:\n\t\t\t\tprint('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}, Accuracy: {:.2f}%'\n\t\t\t\t \t\t.format(epoch + 1, n_epochs, i + 1, len(train_loader), loss_size.item(),\n\t\t\t\t\t\t \t\t(correct / total) * 100))\n\t\t\n\tprint(\"Training finished\")\n\n\ttorch.save(model.state_dict(), '/home/welcome/python_files/project/cifarmodel.ckpt')\n\n\nCNN = CNNModel()\ntrainNet(CNN, batch_size=32, n_epochs=20, learning_rate=0.001) \n\n\ndef testing(batchsize):\n\ttest_loader = torch.utils.data.DataLoader(test_set, batch_size=batchsize, shuffle=False, num_workers=2)\n\n\ttesting_model = CNNModel()\n\ttesting_model.load_state_dict(torch.load('/home/welcome/python_files/project/cifarmodel.ckpt'))\n\n\twith torch.no_grad():\n\t\tcorrect = 0\n\t\ttotal = 0\n\t\tfor images, labels in test_loader:\n\t\t\timages, labels = Variable(images), Variable(labels)\n\t\t\toutputs = testing_model(images)\n\t\t\ttotal += labels.size(0)\n\t\t\t_, predicted = torch.max(outputs.data, 1)\n\t\t\tcorrect += (predicted == labels).sum().item()\n\t\tprint(' Accuracy: {:.2f}%'.format((correct / total) * 100))\t\n\ntesting(50)\n","sub_path":"image_classification_cifar10.py","file_name":"image_classification_cifar10.py","file_ext":"py","file_size_in_byte":4654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"42817513","text":"import snowflake.connector\nimport pandas as pd\nfrom collections import defaultdict\nfrom snowflake.sqlalchemy import URL\nfrom sqlalchemy import create_engine\n\n#query: placeholder/description of what the arguement needs to be/ takes the query as an arguement\ndef querySnowflake(query, returnType):\n \n #con = variable short for connection/ 9-14: arguements used to establish a connection. \n con = snowflake.connector.connect(\n user = 'EpocratesComData',\n password = 'Epocrates123!',\n account = 'athenahealth',\n database = 'EPOCRATES_PROD',\n warehouse = 'EPOCRATES_ANALYTICS_PROD')\n\n #con.cursor().execute: how you execute a cursor/cursor: simulates user experience \n con.cursor().execute('USE ROLE EPOC_ANALYTICS_R')\n # con.cursor().execute('USE DATABASE EPOCRATES_PROD')\n con.cursor().execute('USE WAREHOUSE EPOCRATES_ANALYTICS_PROD')\n con.cursor().execute('USE SCHEMA EPOC_ANALYTICS')\n cur = con.cursor()\n\n # use pandas to read SQL Cursor to pandas DF\n resultsDF = pd.read_sql_query(query, con)\n # pandas DF to Dictionary\n resultsDFDict = pd.read_sql_query(query, con).to_dict('records')\n\n #returns a both the Dictionary and dataframe results as Tuple so we can use both if needed\n # print(resultsDFDict)\n if returnType == 'dataFrame':\n return resultsDF\n elif returnType == 'dict':\n return resultsDFDict\n else:\n return resultsDFDict, resultsDF\n\n\ndef writeSnowflake(inputDataFrame,tableName):\n # Fill in your SFlake details here\n engine = create_engine(URL(\n account = 'athenahealth',\n user = 'EpocratesComData',\n password = 'Epocrates123!',\n database = 'EPOCRATES_PROD',\n schema = 'EPOC_ANALYTICS',\n warehouse = 'EPOCRATES_ANALYTICS_PROD',\n role='EPOC_ANALYTICS_RW'\n ))\n # ), echo=True) \n # ^the echo=True function tells us which query is being run on snowflake; needed to share with Raj via JIRA ticket\n # Echo=true: to retrieve creation query \"if_exists=\" (below) should be set to replace. Otherwise, the funciton returns insert queries (not relevant)\n \n print('Engine Created\\n')\n \n connection = engine.connect()\n trans = connection.begin()\n print('Connected to Engine\\n')\n\n\n # THIS LETS US RUN SQL FORMATED QUERIES DIRECTLY TO SNOWFLAKE\n # engine.execute(\"\"\"\n # UPDATE DLA_DASH\n # SET ONE = 54321\n # WHERE ONE = 10\n # \"\"\")\n # trans.commit()\n\n\n\n # THIS WILL TAKE A PANDAS DATA FRAME AND APPEND THE DATA TO AN EXISTING TABLE ON SNOWFLAKE\n inputDataFrame.to_sql('{}'.format(tableName), con=engine, index=False, if_exists='append') #make sure index is False, Snowflake doesnt accept indexes\n #df = data frame; to_sql: takes the argument of a dataframe; when pushing SF data, index ALWAYS false; \n # if_exists= if table exists (options are 'append' or 'replace')\n # possibility to create duplicate rows\n print('Data Pushed To Snowflake')\n \n connection.close()\n engine.dispose()\n\ndef main():\n #\"\"\" allows for formatted queries that have line breaks\n querySnowflake(query)\n writeSnowflake(inputDataFrame,tableName)\n\n#'==' check the string/value of the variable only run query if name \nif __name__ == \"__main__\":\n main()\n\n","sub_path":"Snowflake/query_snowflake.py","file_name":"query_snowflake.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"461864387","text":"\n# Behavioral log values\n#\n\nKEY_L1_ACTIVITY = 'activity_l1'\nKEY_L2_ACTIVITY = 'activity_l2'\n\n# -------------------------\n# \"type\" values\n# -------------------------\nENTRY_TYPE_TA23API = 'TA23API' #'TA23API'\nENTRY_TYPE_DATAMART = 'DATAMART'\nENTRY_TYPE_SYSTEM = 'SYSTEM'\nENTRY_TYPE_UNKNOWN = 'UNKNOWN'\n\nENTRY_TYPES = (ENTRY_TYPE_TA23API,\n ENTRY_TYPE_DATAMART,\n ENTRY_TYPE_SYSTEM)\n\nENTRY_TYPE_CHOICES = ((x, x) for x in ENTRY_TYPES)\n\n# -------------------------\n# \"activity_l1\" values\n# -------------------------\nL1_SYSTEM_ACTIVITY = 'SYSTEM_ACTIVITY'\n\n# -----------------------------------\n# DATA_PREPARATION: L1 & L2\n# -----------------------------------\nL1_DATA_PREPARATION = 'DATA_PREPARATION'\n\nL2_APP_LAUNCH = 'APP_LAUNCH'\nL2_DATA_OPEN = 'DATA_OPEN'\nL2_DATA_EXPLORE = 'DATA_EXPLORE'\nL2_DATA_AUGMENT = 'DATA_AUGMENT'\nL2_DATA_TRANSFORM = 'DATA_TRANSFORM'\n\n\n# -----------------------------------\n# PROBLEM_DEFINITION: L1 & L2\n# -----------------------------------\nL1_PROBLEM_DEFINITION = 'PROBLEM_DEFINITION'\n\nL2_PROBLEM_SPECIFICATION = 'PROBLEM_SPECIFICATION'\n\n# -----------------------------------\n# MODEL_SELECTION: L1 & L2\n# -----------------------------------\nL1_MODEL_SELECTION = 'MODEL_SELECTION'\n\nL2_MODEL_SUMMARIZATION = 'MODEL_SUMMARIZATION'\nL2_MODEL_COMPARISON = 'MODEL_COMPARISON'\nL2_MODEL_EXPLANATION = 'MODEL_EXPLANATION'\nL2_MODEL_EXPORT = 'MODEL_EXPORT'\n\n\nL1_ACTIVITIES = (L1_SYSTEM_ACTIVITY,\n L1_DATA_PREPARATION,\n L1_PROBLEM_DEFINITION,\n L1_MODEL_SELECTION)\n\nL1_ACTIVITY_CHOICES = ((x, x) for x in L1_ACTIVITIES)\n\n# -------------------------\n# \"activity_l2\" values\n# -------------------------\nL2_ACTIVITY_BLANK = '(blank)'\n\nL2_DATA_SEARCH = 'DATA_SEARCH'\nL2_DATA_DOWNLOAD = 'DATA_DOWNLOAD'\n\n\nL2_MODEL_SEARCH = 'MODEL_SEARCH'\n\nL2_PROBLEM_SEARCH_SELECTION = 'PROBLEM_SEARCH_SELECTION'\n\n# -------------------------\n# \"feature_id\" values\n# -------------------------\n# These are no custom: not necessarily in this file\n# and don't conform to other D3M systesm\nFID_START_RAVENS_PEBBLES_PAGE = 'START_RAVENS_PEBBLES_PAGE'\n","sub_path":"tworaven_apps/behavioral_logs/static_vals.py","file_name":"static_vals.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"173671898","text":"#You must change the value of all the following variables, depending on your setup\r\n\r\n#identification keys to use with the AerisWeather API\r\n#string variables\r\n#you can retrieve these information on your member page on Aerisweather: https://www.aerisweather.com/account/member\r\nCLIENT_ID = \"384924U4HIRHSF9ZSFD27398364872646\"\r\nCLIENT_SECRET = \"98U94U294KD93UJOIEZFN9283927398178\"\r\n\r\n#name of your dataset\r\n#string variable\r\n#example for a dataset named \"processed_data.csv\": DATAFILE = \"processed_data.csv\"\r\n#for each participant, the dataset must contain the following information: participant identifier (no specific format), time at which the participant took the study (format must be \"DD/MM/YYYY HH:MM\"), exact location of the participant (format must be \"latitude,longitude\")\r\nDATAFILE = \"processed_data.csv\"\r\n\r\n#in your dataset, name of the column in which is referenced the participant ID of a given participant\r\n#string variable\r\n#example for a dataset in which the participant ID is referenced in the \"participant_id\" column: EXACT_LOCATION_COLUMN = \"participant_id\"\r\nPARTICIPANT_ID_COLUMN = \"participant_id\"\r\n\r\n#in your dataset, name of the column in which is referenced the timestamp of a given participant (time at which the participant took the study, with the following format: \"DD/MM/YYYY HH:MM\")\r\n#string variable\r\n#example for a dataset in which the timestamp is referenced in the \"timestamp\" column: EXACT_LOCATION_COLUMN = \"timestamp\"\r\nTIMESTAMP_COLUMN = \"timestamp\"\r\n\r\n#in your dataset, name of the column in which is referenced the exact location of a given participant, with the following format: \"latitude,longitude\"\r\n#string variable\r\n#example for a dataset in which the exact location is referenced in the \"exact_location\" column: EXACT_LOCATION_COLUMN = \"exact_location\"\r\nEXACT_LOCATION_COLUMN = \"exact_location\"\r\n\r\n\r\n#timezone of the time displayed on your computer\r\n#numerical variable\r\n#example for a computer in Paris: UTC_TIMEZONE = 2\r\n#example for a computer in New-York: UTC_TIMEZONE = -4\r\n#You are capped to a certain number of accesses to the API per day. If you happen to reach the daily limit, the script will be paused until midnight UTC.\r\nUTC_TIMEZONE = 2\r\n\r\n\r\n#year for which you want to collect yearly averages of the climate variables (leave unchanged if you don't want to collect yearly averages)\r\n#string variable\r\n#example: YEAR = \"2020\"\r\nYEAR = \"2020\"\r\n\r\n\r\n#variables of interest for the \"yearly_averages\" mode \r\n#all possible climate variables are displayed here:\r\n#https://www.aerisweather.com/support/docs/api/reference/endpoints/observations-summary/\r\n#if you want to collect climate variables different than those documented below, add/change the values in the following python list accordingly\r\n#note that you must keep the default values if you want to run the \"aerisweather_statscomputing.py\" script.\r\nSUMMARY_FOI = [\"periods.summary.dateTimeISO\",\r\n \"periods.summary.range.maxDateTimeISO\",\r\n \"periods.summary.range.minDateTimeISO\",\r\n \"periods.summary.temp.avgC\",\r\n \"periods.summary.temp.count\",\r\n \"periods.summary.dewpt.avgC\",\r\n \"periods.summary.dewpt.count\",\r\n \"periods.summary.rh.avg\",\r\n \"periods.summary.rh.count\",\r\n \"periods.summary.altimeter.avgMB\",\r\n \"periods.summary.altimeter.count\",\r\n \"periods.summary.pressure.avgMB\",\r\n \"periods.summary.pressure.count\",\r\n \"periods.summary.visibility.avgKM\",\r\n \"periods.summary.visibility.count\",\r\n \"periods.summary.wind.avgKPH\",\r\n \"periods.summary.wind.count\",\r\n \"periods.summary.sky.avg\",\r\n \"periods.summary.sky.count\",\r\n \"profile.elevM\"]\r\n\r\n\r\n#variables of interest for the \"specified_date\" mode\r\n#if you want to collect other climate variables, check this link:\r\n#https://www.aerisweather.com/support/docs/api/reference/endpoints/observations-archive/\r\n#if you want to collect climate variables different than those documented below, add/change the values in the following python list accordingly\r\n#note that you must keep the default values if you want to run the \"aerisweather_statscomputing.py\" script.\r\nARCHIVE_FOI = [\"periods.ob.dateTimeISO\",\r\n \"periods.ob.recDateTimeISO\",\r\n \"periods.ob.tempC\",\r\n \"periods.ob.dewpointC\",\r\n \"periods.ob.humidity\",\r\n \"periods.ob.pressureMB\",\r\n \"periods.ob.altimeterMB\",\r\n \"periods.ob.windSpeedKPH\",\r\n \"periods.ob.visibilityKM\",\r\n \"periods.ob.sky\",\r\n \"periods.profile.elevM\"]","sub_path":"aerisweather_keys.py","file_name":"aerisweather_keys.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"466369445","text":"# woqlClient.py\nfrom .dispatchRequest import DispatchRequest\n\n#from .errorMessage import *\nfrom .connectionConfig import ConnectionConfig\nfrom .connectionCapabilities import ConnectionCapabilities\n\nfrom .const import Const as const\nfrom .errorMessage import ErrorMessage\n#from .errors import (InvalidURIError)\nfrom .errors import *\n\nfrom .documentTemplate import DocumentTemplate\n\nfrom .idParser import IDParser\nimport json\n\n# WOQL client object\n# license Apache Version 2\n# summary Python module for accessing the Terminus DB API\n\n\nclass WOQLClient:\n\n \"\"\"\n The WOQLClient constructor\n\n :param **kwargs Connection arguments used to configure the Client. (db=terminusDBName | server=terminusServerURL | doc=docName | key=apiKey)\n\n \"\"\"\n\n def __init__(self, **kwargs):\n # current conCapabilities context variables\n key = kwargs.get('key')\n self.conConfig = ConnectionConfig(**kwargs)\n self.conCapabilities = ConnectionCapabilities(self.conConfig, key)\n\n\n\n def connect(self, serverURL=None, key=None):\n \"\"\"\n Connect to a Terminus server at the given URI with an API key\n Stores the terminus:ServerCapability document returned\n in the conCapabilities register which stores, the url, key, capabilities,\n and database meta-data for the connected server\n\n If the serverURL argument is omitted,\n self.conConfig.serverURL will be used if present\n or an error will be raise.\n\n Parameters\n ----------\n serverURL : str\n Terminus server URI\n key : str\n API key\n\n Returns\n -------\n dict or raise an InvalidURIError\n\n Examples\n -------\n >>> woql.WOQLClient().connect(serverUrl, key)\n dict\n \"\"\"\n if serverURL:\n self.conConfig.setServer(serverURL)\n\n if key:\n self.conCapabilities.setClientKey(key)\n\n jsonObj = self.dispatch(self.conConfig.serverURL, const.CONNECT, key)\n self.conCapabilities.addConnection(jsonObj)\n return jsonObj\n\n @staticmethod\n def directConnect(serverURL, key):\n \"\"\"\n connect directly without creating a new class instance\n\n Parameters\n ----------\n serverURL : str\n Terminus server URI\n key : str\n API key\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseServerURL(serverURL)\n return DispatchRequest.sendRequestByAction(idParser.serverURL, const.CONNECT, key)\n\n def createDatabase(self, dbID, label, key=None, **kwargs):\n \"\"\"\n Create a Terminus Database by posting\n a terminus:Database document to the Terminus Server\n\n Parameters\n ----------\n dbID : str\n ID of the specific database to create\n label : str\n Terminus label\n key : str, optional\n you can omit the key if you have set it before\n kwargs\n Optional arguments that ``createDatabase`` takes\n\n Returns\n -------\n dict\n\n Examples\n --------\n WOQLClient(server=\"http://localhost:6363\").createDatabase(\"someDB\", \"Database Label\", \"password\")\n \"\"\"\n self.conConfig.setDB(dbID)\n createDBTemplate = DocumentTemplate.createDBTemplate(\n self.conConfig.serverURL, self.conConfig.dbID, label, **kwargs)\n #after create db the server could send back the capabilities of the new db, we can add the new capability at the\n #capabilities list\n return self.dispatch(self.conConfig.dbURL(), const.CREATE_DATABASE, key, createDBTemplate)\n\n @staticmethod\n def directCreateDatabase(dbURL, label, key, **kwargs):\n \"\"\"Create Terminus Database with settings\n\n Parameters\n ----------\n dbURL : str\n TerminusDB full URL like http://localhost:6363/myDB\n label : str\n the terminus db title\n key : str\n the server API key\n kwargs\n Optional arguments that ``createDatabase`` takes\n\n Returns\n -------\n dict\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n createDBTemplate = DocumentTemplate.createDBTemplate(\n idParser.serverURL, idParser.dbID, label, **kwargs)\n DispatchRequest.sendRequestByAction(\n idParser.dbURL(), const.CREATE_DATABASE, key, createDBTemplate)\n\n def deleteDatabase(self, dbID, key=None):\n \"\"\"Delete a TerminusDB database\n\n Parameters\n ----------\n dbID : str\n ID of the database to delete\n key : str, optional\n you need the key if you didn't set before\n\n Returns\n -------\n dict\n\n Examples\n -------\n >>> WOQLClient(server=\"http://localhost:6363\").deleteDatabase(\"someDBToDelete\", \"password\")\n \"\"\"\n self.conConfig.setDB(dbID)\n jsonResponse = self.dispatch(\n self.conConfig.dbURL(), const.DELETE_DATABASE, key)\n self.conCapabilities.removeDB()\n return jsonResponse\n\n @staticmethod\n def directDeleteDatabase(dbURL, key):\n \"\"\"Delete a TerminusDB with settings\n\n Parameters\n ----------\n dbURL : str\n TerminusDB full URL like http://localhost:6363/myDB\n key : str\n the server API key\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n return DispatchRequest.sendRequestByAction(\n idParser.dbURL(), const.DELETE_DATABASE, key)\n\n def getSchema(self, dbID=None, key=None, options={\"terminus:encoding\": \"terminus:turtle\"}):\n \"\"\"Retrieves the schema of the specified database\n\n opts.format defines which format is requested, default is turtle(*json / turtle)\n\n Parameters\n ----------\n dbId : str\n TerminusDB Id or omitted (get last select database)\n key : str\n the server API key\n options : dict\n options object\n\n Returns\n -------\n str or dict\n \"\"\"\n if (dbID):\n self.conConfig.setDB(dbID)\n\n return self.dispatch(self.conConfig.schemaURL(), const.GET_SCHEMA, key, options)\n\n @staticmethod\n def directGetSchema(dbURL, key, options={\"terminus:encoding\": \"terminus:turtle\"}):\n \"\"\"Retrieves the schema of the specified database with settings\n\n opts.format defines which format is requested, default is turtle(*json / turtle)\n\n Parameters\n ----------\n dbId : str\n TerminusDB Id or omitted (get last select database)\n key : str\n the server API key\n options : dict\n options object\n\n Returns\n -------\n str or dict\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n return DispatchRequest.sendRequestByAction(\n idParser.schemaURL(), const.GET_SCHEMA, key, options)\n\n def updateSchema(self, docObj, dbID=None, key=None, opts={\"terminus:encoding\": \"terminus:turtle\"}):\n \"\"\"Updates the Schema of the specified database\n\n opts.format is used to specify which format is being used (*json / turtle)\n\n Parameters\n ----------\n docObj : dict\n valid owl ontology in json-ld or turtle format\n dbid : str\n TerminusDB Id or omitted\n key : str\n API key\n opts : dict\n options object\n\n Returns\n -------\n dict\n \"\"\"\n if (dbID):\n self.conConfig.setDB(dbID)\n docObj = DocumentTemplate.formatDocument(\n docObj, False, opts)\n return self.dispatch(self.conConfig.schemaURL(), const.UPDATE_SCHEMA, key, docObj)\n\n @staticmethod\n def directUpdateSchema(dbURL, docObj, key, opt={\"terminus:encoding\": \"terminus:turtle\"}):\n \"\"\"Updates the Schema of the specified database with settings\n\n opts.format is used to specify which format is being used (*json / turtle)\n\n Parameters\n ----------\n dbURL : str\n a valid TerminusDB full URL\n docObj : dict\n valid owl ontology in json-ld or turtle format\n key : str\n API key\n opts : dict\n options object\n\n Returns\n -------\n dict\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n docObj = DocumentTemplate.formatDocument(\n docObj, False, opts)\n return DispatchRequest.sendRequestByAction(\n idParser.schemaURL(), const.UPDATE_SCHEMA, key, docObj)\n\n def createDocument(self, docObj, documentID, dbID=None, key=None):\n \"\"\"Creates a new document in the specified database\n\n Parameters\n ----------\n docObj : dict\n a valid document in json-ld\n documentID : str\n a valid Terminus document id\n dbId : str\n a valid TerminusDB id\n key : str, optional\n API key\n Returns\n -------\n dict\n \"\"\"\n if(dbID):\n self.conConfig.setDB(dbID)\n self.conConfig.setDocument(documentID)\n docObj = DocumentTemplate.formatDocument(\n doc, None, None, self.conConfig.docURL())\n return self.dispatch(self.conConfig.docURL(), const.CREATE_DOCUMENT, key, docObj)\n\n @staticmethod\n def directCreateDocument(docObj, documentID, dbURL, key):\n \"\"\"Creates a new document in the specified database\n\n Parameters\n ----------\n docObj : dict\n a valid document in json-ld\n documentID : str\n a valid Terminus document id\n dbURL : str\n a valid TerminusDB full URL\n key : str, optional\n API key\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n idParser.parseDocumentID(documentID)\n\n docObj = DocumentTemplate.formatDocument(doc, None, None, idParser.docURL())\n return DispatchRequest.sendRequestByAction(idParser.docURL(), const.CREATE_DOCUMENT, key, docObj)\n\n def getDocument(self, documentID, dbID=None, key=None, opts={\"terminus:encoding\": \"terminus:frame\"}):\n \"\"\"Retrieves a document from the specified database\n\n Parameters\n ----------\n documentID : str\n a valid Terminus document id\n dbId : str\n a valid TerminusDB id\n key : str, optional\n API key\n opts : dict\n options object\n\n Returns\n -------\n dict\n \"\"\"\n if(dbID):\n self.conConfig.setDB(dbID)\n\n self.conConfig.setDocument(documentID)\n return self.dispatch(self.conConfig.docURL(), const.GET_DOCUMENT, key, opts)\n\n @staticmethod\n def directGetDocument(documentID, dbURL, key, opts={\"terminus:encoding\": \"terminus:frame\"}):\n \"\"\"Retrieves a document from the specified database with URL\n\n Parameters\n ----------\n documentID : str\n a valid Terminus document id\n dbURL : str\n a valid TerminusDB full URL\n key : str, optional\n API key\n opts : dict\n options object\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n idParser.parseDocumentID(documentID)\n return DispatchRequest.sendRequestByAction(idParser.docURL(), const.GET_DOCUMENT, key, opts)\n\n def updateDocument(self, documentID, docObj, dbID=None, key=None):\n \"\"\"\n Updates a document in the specified database with a new version\n\n Parameters\n ----------\n documentID : str\n a valid Terminus document id\n docObj : dict\n a valid document in json-ld\n dbId : str\n a valid TerminusDB id\n key : str, optional\n API key\n\n Returns\n -------\n dict\n \"\"\"\n if(dbID):\n self.conConfig.setDB(dbID)\n\n self.conConfig.setDocument(documentID)\n docObj = DocumentTemplate.formatDocument(\n docObj, None, None, self.conConfig.docURL())\n return self.dispatch(self.conConfig.docURL(), const.UPDATE_DOCUMENT, key, docObj)\n\n @staticmethod\n def directUpdateDocument(documentID, dbURL, key, docObj):\n \"\"\"\n Updates a document in the specified database with URL\n\n Parameters\n ----------\n documentID : str\n a valid Terminus document id\n dbURL : str\n a valid TerminusDB full URL\n key : str, optional\n API key\n docObj : dict\n a valid document in json-ld\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n idParser.parseDocumentID(documentID)\n docObj = DocumentTemplate.formatDocument(\n docObj, None, None, idParser.docURL())\n return DispatchRequest.sendRequestByAction(idParser.docURL(), const.GET_DOCUMENT, key, docObj)\n\n def deleteDocument(self, documentID, dbID=None, key=None):\n \"\"\"\n Deletes a document from the specified database\n\n Parameters\n ----------\n documentID : str\n a valid Terminus document id\n dbId : str\n a valid TerminusDB id\n key : str, optional\n API key\n\n Returns\n -------\n dict\n \"\"\"\n if(dbID):\n self.conConfig.setDB(dbID)\n\n self.conConfig.setDocument(documentID)\n\n return self.dispatch(self.conConfig.docURL(), const.DELETE_DOCUMENT, key)\n\n @staticmethod\n def directDeleteDocument(self, documentID, dbURL, key):\n \"\"\"\n Deletes a document from the specified database with URL\n\n Parameters\n ----------\n documentID : str\n a valid Terminus document id\n dbURL : str\n a valid TerminusDB full URL\n key : str, optional\n API key\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n idParser.parseDocumentID(documentID)\n\n return DispatchRequest.sendRequestByAction(idParser.docURL(), const.DELETE_DOCUMENT, key)\n\n def select(self, woqlQuery, dbID=None, key=None,fileList=None):\n \"\"\"\n Executes a read-only WOQL query on the specified database and returns the results\n\n Parameters\n ----------\n woqlQuery : WOQLQuery object\n woql query select statement\n dbId : str\n a valid TerminusDB id\n key : str, optional\n API key\n fileList : list, optional\n List of files that are needed for the query\n\n Returns\n -------\n dict\n \"\"\"\n if(dbID):\n self.conConfig.setDB(dbID)\n\n payload = {'terminus:query': json.dumps(woqlQuery)}\n if type(fileList) == dict:\n payload.update(fileList);\n\n return self.dispatch(self.conConfig.queryURL(), const.WOQL_SELECT, key, payload)\n\n @staticmethod\n def directSelect(woqlQuery, dbURL, key, fileList=None):\n \"\"\"\n Static function that executes a read-only WOQL query on the specified database\n and returns the results\n\n Parameters\n ----------\n woqlQuery : WOQLQuery object\n woql query select statement\n dbId : str\n a valid full TerminusDB database URL\n key : str, optional\n API key\n fileList : list, optional\n List of files that are needed for the query\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n\n payload = {'terminus:query': json.dumps(woqlQuery)}\n if type(fileList) == dict:\n payload.update(fileList);\n return DispatchRequest.sendRequestByAction(idParser.queryURL(), const.WOQL_SELECT, key, payload)\n\n def update(self, woqlQuery, dbID=None, key=None ,fileList=None):\n \"\"\"\n Executes a WOQL query on the specified database which updates the state and returns the results\n\n Parameters\n ----------\n woqlQuery : WOQLQuery object\n woql query select statement\n dbId : str\n a valid TerminusDB database ID\n key : str, optional\n API key\n fileList : list, optional\n List of files that are needed for the query\n\n Returns\n -------\n dict\n \"\"\"\n if(dbID):\n self.conConfig.setDB(dbID)\n # raise InvalidURIError(ErrorMessage.getInvalidURIMessage(docurl, \"Update\"))\n if type(fileList) == dict:\n file_dict = {}\n for name in fileList:\n path = fileList[name]\n stream = open(path, 'rb')\n print(name)\n file_dict[name] = (name,stream,'text/plain')\n file_dict['terminus:query'] = (None,json.dumps(woqlQuery),'application/json')\n payload = None\n else:\n file_dict = None\n payload = {'terminus:query': json.dumps(woqlQuery)}\n\n return self.dispatch(self.conConfig.queryURL(), const.WOQL_UPDATE, key, payload, file_dict)\n\n @staticmethod\n def directUpdate(woqlQuery, dbURL, key,fileList=None):\n \"\"\"\n Static function that executes a WOQL query on the specified database which\n updates the state and returns the results\n\n Parameters\n ----------\n woqlQuery : WOQLQuery object\n woql query select statement\n dbURL : str\n a valid full TerminusDB database URL\n key : str, optional\n API key\n fileList : list, optional\n List of files that are needed for the query\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n idParser = IDParser()\n idParser.parseDBURL(dbURL)\n\n if type(fileList) == dict:\n file_dict = {}\n for name in fileList:\n path = fileList[name]\n stream = open(path, 'rb')\n print(name)\n file_dict[name] = (name,stream,'text/plain')\n file_dict['terminus:query'] = (None,json.dumps(woqlQuery),'application/json')\n payload = None\n else:\n file_dict = None\n payload = {'terminus:query': json.dumps(woqlQuery)}\n\n return DispatchRequest.sendRequestByAction(idParser.queryURL(), const.WOQL_UPDATE, key, payload, file_dict)\n\n def dispatch(self, url, action, connectionKey, payload={}, file_dict = None):\n \"\"\"\n Directly dispatch to a Terminus database.\n\n Parameters\n ----------\n url : str\n The server URL to point the action at\n connectionKey : str\n API key to the document\n payload : dict\n Payload to send to the server\n file_dict : list, optional\n List of files that are needed for the query\n\n\n Returns\n -------\n dict or raise an InvalidURIError\n \"\"\"\n if connectionKey is None:\n # if the api key is not setted the method raise an APIerror\n connectionKey = self.conCapabilities.getClientKey()\n\n #if (action != const.CONNECT and self.conConfig.connectedMode and self.conCapabilities.serverConnected() is False):\n\n #key = payload.key if isinstance(payload,dict) and key in payload else False\n #self.connect(self.conConfig.serverURL, connectionKey)\n #print(\"CONNCT BEFORE ACTION\", action)\n\n #check if we can perform this action or raise an AccessDeniedError error\n #review the access control\n #self.conCapabilities.capabilitiesPermit(action)\n return DispatchRequest.sendRequestByAction(url, action, connectionKey, payload, file_dict)\n","sub_path":"woqlclient/woqlClient.py","file_name":"woqlClient.py","file_ext":"py","file_size_in_byte":20224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"261798505","text":"#! /usr/bin/env python\n\"\"\"Basic Model Interface implementation for Parker's FallVelocity.\"\"\"\n\nimport types\n\nimport numpy as np\nimport yaml\nfrom basic_modeling_interface import Bmi\n\nfrom STR_scripts.s_FallVelocity import FallVelocity_solver\n\n\nclass FallVelocity(Bmi):\n\n\n _name = 'STR_FallVelocity'\n \n # Standard Names of variables it could potentially get from another model\n _input_var_names = (\n 'particle__diameter',\n 'fluid__kinematic_viscosity',\n 'gravitational_acceleration',\n 'fluid__density',\n 'particle__density',)\n \n # Standard Names of variables it could pass to another model\n _output_var_names = (\n 'particle__settling_velocity',\n 'particle__Reynolds_number',\n 'particle__dimensionless_fall_velocity',)\n\n def __init__(self):\n \"\"\"Create a model that is ready for initialization.\"\"\"\n self._FV = None\n self._time = 0.\n self._values = {}\n self._var_units = {}\n\n\n\n def initialize(self, filename='../input_files/FallVelocity.yaml'):\n \"\"\"Initialize the FallVelocity model.\n\n Parameters\n ----------\n filename : str, optional\n Path to name of input file.\n \"\"\"\n \n with open(filename, 'r') as file_obj:\n params = yaml.load(file_obj)\n \n default_params = {'particle__diameter': 0.1,\n 'fluid__kinematic_viscosity': 1e-6,\n 'gravitational_acceleration': 9.81,\n 'fluid__density': 1000.,\n 'particle__density': 2650.,\n 'output_filename': 'output/FallVelocity_output.json'}\n \n \n # sets missing parameters to default values\n for key,value in default_params.items():\n params[key] = params.get(key, default_params[key])\n\n for key,value in params.items():\n if (value is None) or (value == 'None'):\n params[key] = default_params[key]\n \n \n \n self._FV = FallVelocity_solver(params)\n\n\n self._values = {'particle__diameter': self._FV.grain_size,\n 'fluid__kinematic_viscosity': self._FV.kinematic_viscosity,\n 'gravitational_acceleration': self._FV.gravitational_acceleration,\n 'fluid__density': self._FV.density_of_fluid,\n 'particle__density': self._FV.density_of_particle,\n 'particle__settling_velocity': self._FV.settling_velocity,\n 'particle__Reynolds_number': self._FV.Reynolds_number,\n 'particle__dimensionless_fall_velocity': self._FV.dimensionless_fall_velocity}\n \n \n self._var_units = {\n 'particle__diameter': 'mm',\n 'fluid__kinematic_viscosity': 'm2 s-1',\n 'gravitational_acceleration': 'm s-2',\n 'fluid__density': 'Kg m-3',\n 'particle__density': 'Kg m-3',\n 'particle__settling_velocity': 'm s-1',\n 'particle__Reynolds_number': '-',\n 'particle__dimensionless_fall_velocity': '-'}\n \n\n\n # keep these methods so it can couple with other BMIed models\n def update(self):\n \"\"\"Advance model by one time step.\n Since this script does not evolve in time,\n update() just runs the script once\"\"\"\n \n self._FV.run()\n \n\n def update_frac(self, time_frac):\n \"\"\"Update model by a fraction of a time step.\n\n Parameters\n ----------\n time_frac : float\n Fraction fo a time step.\n \n Since this script does not evolve in time,\n update() just runs the script once\"\"\"\n \n self.update()\n\n\n def update_until(self, then):\n \"\"\"Update model until a particular time.\n\n Parameters\n ----------\n then : float\n Time to run model until.\n \n Since this script does not evolve in time,\n update() just runs the script once\"\"\"\n \n self.update()\n\n def finalize(self):\n \"\"\"Finalize model.\"\"\"\n self._FV.finalize()\n \n \n \n\n\n\n def get_var_type(self, var_name):\n \"\"\"Data type of variable.\n\n Parameters\n ----------\n var_name : str\n Name of variable as CSDMS Standard Name.\n\n Returns\n -------\n str\n Data type.\n \"\"\"\n return str(self.get_value_ref(var_name).dtype)\n\n def get_var_units(self, var_name):\n \"\"\"Get units of variable.\n\n Parameters\n ----------\n var_name : str\n Name of variable as CSDMS Standard Name.\n\n Returns\n -------\n str\n Variable units.\n \"\"\"\n return self._var_units[var_name]\n\n def get_var_nbytes(self, var_name):\n \"\"\"Get units of variable.\n\n Parameters\n ----------\n var_name : str\n Name of variable as CSDMS Standard Name.\n\n Returns\n -------\n int\n Size of data array in bytes.\n \"\"\"\n return self.get_value_ref(var_name).nbytes\n\n\n\n def get_value_ref(self, var_name):\n \"\"\"Reference to values.\n\n Parameters\n ----------\n var_name : str\n Name of variable as CSDMS Standard Name.\n\n Returns\n -------\n array_like\n Value array.\n \"\"\"\n return self._values[var_name]\n\n def get_value(self, var_name):\n \"\"\"Copy of values.\n\n Parameters\n ----------\n var_name : str\n Name of variable as CSDMS Standard Name.\n\n Returns\n -------\n array_like\n Copy of values.\n \"\"\"\n return self.get_value_ref(var_name).copy()\n\n\n def set_value(self, var_name, src):\n \"\"\"Set model values.\n\n Parameters\n ----------\n var_name : str\n Name of variable as CSDMS Standard Name.\n src : int or float\n New value\n \"\"\"\n val = self.get_value_ref(var_name)\n val[:] = src\n\n\n def get_component_name(self):\n \"\"\"Name of the component.\"\"\"\n return self._name\n\n def get_input_var_names(self):\n \"\"\"Get names of input variables.\"\"\"\n return self._input_var_names\n\n def get_output_var_names(self):\n \"\"\"Get names of output variables.\"\"\"\n return self._output_var_names\n \n","sub_path":"STR/FallVelocity.py","file_name":"FallVelocity.py","file_ext":"py","file_size_in_byte":6544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"29861502","text":"import random\nclass Solution(object):\n def __init__(self, nums):\n \"\"\"\n :type nums: List[int]\n \"\"\"\n self.original = nums\n\n def reset(self):\n \"\"\"\n Resets the array to its original configuration and return it.\n :rtype: List[int]\n \"\"\"\n return self.original\n\n def shuffle(self):\n \"\"\"\n Returns a random shuffling of the array.\n :rtype: List[int]\n \"\"\"\n res = []\n marked = [False, ]*len(self.original)\n for i in range(len(self.original)):\n randIndex = random.randint(0, len(self.original) - 1 - i)\n restElement = list(filter(lambda x: not marked[x], range(len(self.original))))\n marked[restElement[randIndex]] = True\n res.append(self.original[restElement[randIndex]])\n\n return res\n\n # Your Solution object will be instantiated and called as such:\n # obj = Solution(nums)\n # param_1 = obj.reset()\n # param_2 = obj.shuffle()\n\nif __name__ == \"__main__\":\n arr = [1, 2, 3, 4, 5, 6, 7]\n s = Solution(arr)\n for i in range(10):\n r0 = s.shuffle()\n print(r0)\n","sub_path":"exercise/leetcode/python_src/by2017_Sep/Leet384.py","file_name":"Leet384.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"354799441","text":"#!/usr/bin/python\n# Copyright (c) 2021 Philip Company\n# Author: Philip Chen\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport speech_recognition as sr\nimport time\nimport sys\nimport smbus\n\nbus = smbus.SMBus(1)\n\n# this device has two I2C addresses\nDISPLAY_RGB_ADDR = 0x62\nDISPLAY_TEXT_ADDR = 0x3e\n\n# I2C LCD\n# set backlight to (R,G,B) (values from 0..255 for each)\ndef setRGB(r,g,b):\n bus.write_byte_data(DISPLAY_RGB_ADDR,0,0)\n bus.write_byte_data(DISPLAY_RGB_ADDR,1,0)\n bus.write_byte_data(DISPLAY_RGB_ADDR,0x08,0xaa)\n bus.write_byte_data(DISPLAY_RGB_ADDR,4,r)\n bus.write_byte_data(DISPLAY_RGB_ADDR,3,g)\n bus.write_byte_data(DISPLAY_RGB_ADDR,2,b)\n\n# send command to display (no need for external use)\ndef textCommand(cmd):\n bus.write_byte_data(DISPLAY_TEXT_ADDR,0x80,cmd)\n\n# set display text \\n for second line(or auto wrap)\ndef setText(text):\n textCommand(0x01) # clear display\n time.sleep(.05)\n textCommand(0x08 | 0x04) # display on, no cursor\n textCommand(0x28) # 2 lines\n time.sleep(.05)\n count = 0\n row = 0\n for c in text:\n if c == '\\n' or count >= 16:\n count = 0\n row += 1\n if row >= 2:\n break\n textCommand(0xc0)\n if c == '\\n':\n continue\n count += 1\n bus.write_byte_data(DISPLAY_TEXT_ADDR,0x40,ord(c))\n\ndef i2c_lcd_test():\n textCommand(0x01) # clear display\n time.sleep(.05)\n textCommand(0x08 | 0x04) # display on, no cursor\n textCommand(0x28) # 2 lines\n time.sleep(.05)\n\n for i in range(0,5):\n setRGB( 255, 0, 0 )\n time.sleep(1)\n setRGB( 255, 255, 0 )\n time.sleep(1)\n setRGB( 0, 255, 0 )\n time.sleep(1)\n setRGB( 0, 255, 255 )\n time.sleep(1)\n setRGB( 0, 0, 255 )\n time.sleep(1)\n setRGB( 255, 0, 255 )\n time.sleep(1)\n\n setRGB( 128, 255, 0 )\n setText( \"Hello world !\\nIt works !\\n\" )\n\ndef i2c_lcd_init():\n textCommand(0x01) # clear display\n time.sleep(.05)\n textCommand(0x08 | 0x04) # display on, no cursor\n textCommand(0x28) # 2 lines\n time.sleep(.05)\n\ni2c_lcd_init()\nr = sr.Recognizer()\n\nwhile True:\n with sr.Microphone() as source:\n r.adjust_for_ambient_noise(source)\n print('say one of follows :\\n\"red carpet\"\\n\"green grass\"\\n\"navy blue\"\\n\"yellow river\"\\n\"blue sky\"\\n\"pink panther\"\\n\"snow white\"\\n')\n print('say \"stop\" to exit')\n audio = r.record(source, duration = 3)\n \n try:\n voice_data = r.recognize_google(audio, language='en-US')\n print(voice_data)\n if voice_data.lower() == 'red carpet':\n setRGB( 255, 0, 0 )\n elif voice_data.lower() == 'green grass':\n setRGB( 0, 255, 0 )\n elif voice_data.lower() == 'navy blue':\n setRGB( 0, 0, 255 )\n elif voice_data.lower() == 'yellow river':\n setRGB( 255, 255, 0 )\n elif voice_data.lower() == 'blue sky':\n setRGB( 0, 255, 255 )\n elif voice_data.lower() == 'pink panther':\n setRGB( 255, 0, 255 )\n elif voice_data.lower() == 'snow white':\n setRGB( 255, 255, 255 )\n elif voice_data.lower() == 'stop':\n setRGB( 0, 0, 0 )\n break\n except Exception as e:\n print (e)\n \n","sub_path":"i2s_lcd.py","file_name":"i2s_lcd.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"362390309","text":"\nfrom imap_module_wrapper import IMAPConnection\nfrom slackapi import SlackPoster\nimport requests\nimport configparser\nimport os.path\nimport sys\n\n\n# = 設定ファイル ロード ========================================================\nenvConfig = configparser.ConfigParser()\nenvConfig.read('../slacknotify_envsettings.ini')\naddressList = configparser.ConfigParser()\naddressList.read('slacknotify_addresslist.ini')\nporicyList = configparser.ConfigParser()\nporicyList.read('slacknotify_domainlist.ini')\n\n# = 新規メールのチェック・Slack転送 =============================================\n## 核心的処理\ndef mailCheckAndProcess(session, mailBoxName):\n ## Flagがついてないメールの番号を取得\n session.selectBox(mailBoxName)\n mails=session.getNoFlaggedMail()\n ## 各メールについて処理\n \n for i in mails[0].split():\n ## メールを取得\n mail=session.getMailDetail(i)\n mailaddressInfo = addressList.items(section=section)\n ## メールアドレスと紐づいた全ての受付チャンネルについて処理\n ProceedCnt = 0\n FinishedResponces = []\n for p in mailaddressInfo:\n if('imap_notify' in p[0]):\n ## 受信チャンネルへメール転送\n ProceedCnt = ProceedCnt + 1\n try:\n slackpt=SlackPoster()\n responce=slackpt.IMAPMailPost(\n channelId = p[1],\n uid = mail['UID'],\n succeedState = mail['Succeed'],\n mailBoxName = mailBoxName,\n mailFromAdd = mail['From_Address'],\n mailFromName = mail['From_Name'],\n mailToAdd = mail['To_Address'],\n mailToName = mail['To_Name'],\n mailsub = mail['Subject'],\n mailbody = mail['Body']\n )\n session.addFlagToMail(i,'Slack_'+responce['ts'])\n FinishedResponces.append(responce)\n except Exception as Err_inst:\n print(Err_inst)\n continue\n if ProceedCnt == len(FinishedResponces):\n print('Transfar Mail Completed of mail '+str(i))\n session.addFlagToMail(i,'POSTED_SLACK_COMPLETED')\n if len(FinishedResponces) != 0:\n print('Transfar Mail of '+str(i))\n print(' - RequirePost:'+str(ProceedCnt))\n print(' - CompletedPost:'+str(len(FinishedResponces)))\n session.addFlagToMail(i,'POSTED_SLACK')\n session.commitFrags()\n print('commited flag')\n session.closeBox()\n \n\n## めんどい色々\nfor sections in addressList.items():\n # [ここから] メールアドレス毎に実行\n section = sections[0]\n if section == \"DEFAULT\":\n continue\n # IMAPサーバURL/Port ロード\n poricyName = addressList[section]['poricy']\n IMAPserverUrl = poricyList[poricyName]['imap_address']\n IMAPServerPort = poricyList[poricyName]['imap_port']\n # IMAPサーバ接続\n session = IMAPConnection(IMAPserverUrl,IMAPServerPort) # Sock Session作成\n session.login(addressList[section]['imap_user'],addressList[section]['imap_pass']) # Login\n ## 全メールのチェック・転送・マーク処理\n mailCheckAndProcess(session,'INBOX')\n mailCheckAndProcess(session,'INBOX.Sent')\n ## 後始末\n session.logout()\n # [ここまで] メールアドレス毎に実行\n\n\n","sub_path":"imap_root.py","file_name":"imap_root.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"38586390","text":"import logging\nimport sys\nimport threading\nimport time\nimport traceback\nimport xml.etree.ElementTree as ET\n\n\nclass _TextRecorder(object):\n \"\"\"Record test result to stdout.\"\"\"\n\n def __init__(self, opts, logger):\n self._opts = opts\n self._logger = logger\n\n def start(self, case):\n if case == 1:\n self._logger.info(\"TEST START\")\n self._logger.debug(\"CASE %2d: START\" % case)\n\n def success(self, case, rc, out):\n if self._opts.is_verbose:\n self._logger.info(\n \"CASE %2d: SUCCESS (rc %s)\\n%s\" % (case, rc, out)\n )\n else:\n self._logger.info(\"CASE %2d: SUCCESS\" % case)\n\n def failure(self, case, rc, out):\n self._logger.info(\"CASE %2d: FAILURE (rc %s)\\n%s\" % (case, rc, out))\n\n def skip(self, case):\n self._logger.info(\"CASE %2d: SKIP\" % case)\n\n def timeout(self, case, pid):\n self._logger.info(\n \"CASE %2d: TIMEOUT \"\n \"(after %ds, pid: %d)\" % (case, self._opts.timeout, pid)\n )\n\n def flush(self):\n pass\n\n\nclass _JunitRecorder(object):\n \"\"\"Record test results to Junit xml.\"\"\"\n\n def __init__(self, opts):\n self._opts = opts\n # test results format:\n # { 1: {'start': , 'end': , 'rc': ,\n # 'out': } }\n self._results = {}\n self._skipped = []\n self._timedout = []\n self._start_times = {}\n self._lock = threading.Lock()\n\n def start(self, case):\n with self._lock:\n # Note that some test cases that do not exist are started due to\n # the nature of threaded test case runs. These extra cases are\n # ignored.\n self._start_times[case] = time.time()\n\n def success(self, case, rc, out):\n with self._lock:\n self._results[case] = {\n \"start\": self._start_times[case],\n \"end\": time.time(),\n \"rc\": rc,\n \"out\": out,\n }\n\n def failure(self, case, rc, out):\n with self._lock:\n self._results[case] = {\n \"start\": self._start_times[case],\n \"end\": time.time(),\n \"rc\": rc,\n \"out\": out,\n }\n\n def timeout(self, case, pid):\n with self._lock:\n self._timedout.append(case)\n\n def skip(self, case):\n with self._lock:\n self._skipped.append(case)\n\n def _write_out_xml(self):\n # Some helpful information on the Junit format:\n # http://stackoverflow.com/questions/4922867/\n # junit-xml-format-specification-that-hudson-supports\n suite = ET.Element(\"testsuite\")\n ET.SubElement(suite, \"properties\")\n suite.set(\"name\", self._opts.component_name)\n\n properties = suite.find(\"properties\")\n verbosityProperty = ET.SubElement(properties, \"property\")\n verbosityProperty.set(\"name\", \"verbosity\")\n verbosityProperty.set(\"value\", \"%d\" % self._opts.verbosity)\n\n timeoutProperty = ET.SubElement(properties, \"property\")\n timeoutProperty.set(\"name\", \"timeout\")\n timeoutProperty.set(\"value\", \"%d\" % self._opts.timeout)\n\n cases = sorted(self._skipped + list(self._results.keys()))\n\n for case in cases:\n testcase = ET.SubElement(suite, \"testcase\")\n testcase.set(\"name\", \"%d\" % case)\n if case in self._results:\n case_result = self._results[case]\n delta = case_result[\"end\"] - case_result[\"start\"]\n testcase.set(\"time\", \"%.6f\" % delta)\n systemout = ET.SubElement(testcase, \"system-out\")\n systemout.text = case_result[\"out\"]\n if case_result[\"rc\"] == 0:\n testcase.set(\"status\", \"passed\")\n else:\n testcase.set(\"status\", \"failed\")\n failure = ET.SubElement(testcase, \"failure\")\n if case in self._timedout:\n failure.set(\"type\", \"timeout\")\n else:\n failure.set(\"type\", \"test failure\")\n failure.set(\"message\", \"rc: %d\" % case_result[\"rc\"])\n else:\n ET.SubElement(testcase, \"skipped\")\n\n tree = ET.ElementTree(suite)\n tree.write(self._opts.junit_file_path)\n\n def flush(self):\n with self._lock:\n self._write_out_xml()\n\n\nclass Log(object):\n \"\"\"This class represents a mechanism to record the status of the test run.\n\n An object of this type can be used to record when a test case started,\n succeeded, or failed. If the options passed into the initializer has the\n ``junit_file_path`` attribute set, the object records the status to the\n junit xml file pointed to by that attribute; otherwise, the object writes\n the status messages directly to stdout.\n\n \"\"\"\n\n def __init__(self, opts):\n \"\"\"Initialize the object with specified options.\n\n Args:\n opts (Options): Test runner options.\n \"\"\"\n self._opts = opts\n self._configure_logger()\n if self._opts.junit_file_path:\n self._recorder = _JunitRecorder(self._opts)\n else:\n self._recorder = _TextRecorder(self._opts, self._logger)\n\n def _configure_logger(self):\n self._logger = logging.getLogger()\n datefmt = \"%H:%M:%S\"\n if self._opts.is_debug:\n level = logging.DEBUG\n format_ = \"[%(asctime)s] [%(threadName)s] %(message)s\"\n else:\n level = logging.INFO\n format_ = \"[%(asctime)s] %(message)s\"\n\n handler = logging.StreamHandler(sys.stdout)\n formatter = logging.Formatter(format_, datefmt)\n handler.setFormatter(formatter)\n self._logger.addHandler(handler)\n self._logger.setLevel(level)\n\n def record_start(self, case):\n self._recorder.start(case)\n\n def record_skip(self, case):\n self._recorder.skip(case)\n\n def record_timeout(self, case, pid):\n self._recorder.timeout(case, pid)\n\n def record_success(self, case, rc, out):\n self._recorder.success(case, rc, out)\n\n def record_failure(self, case, rc, out):\n self._recorder.failure(case, rc, out)\n\n def record_exception(self, case, e):\n self._logger.info(\"CASE %2d: PYTHON EXCEPTION (%s)\" % (case, str(e)))\n self._logger.info(\"Traceback:\")\n for line in traceback.format_exception(*sys.exc_info()):\n self._logger.info(line.rstrip())\n\n def info(self, msg):\n self._logger.info(msg)\n\n def info_case(self, case, msg):\n self._logger.info(\"CASE %2d: %s\" % (case, msg))\n\n def debug(self, msg):\n self._logger.debug(msg)\n\n def debug_case(self, case, msg):\n self._logger.debug(\"CASE %2d: %s\" % (case, msg))\n\n def flush(self):\n self._recorder.flush()\n\n\n# -----------------------------------------------------------------------------\n# Copyright 2015 Bloomberg Finance L.P.\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# ----------------------------- END-OF-FILE -----------------------------------\n","sub_path":"BdeBuildSystem/scripts/runtest/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":7694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"599501409","text":"print('APP_Predicate')\npath = '/home/students/stalknia/Papka/apps/'\nimport nn\nimport preprocessing\nfrom dictionary import *\nfrom predicate_nn import bag_of_words\n\nDICT_FILE = '{}predicate/dats/dict_predicate.dat'.format(path)\nWEIGHTS_FILE = '{}predicate/dats/weights_predicate.dat'.format(path)\n\nd = DictionaryC()\nd.load(DICT_FILE)\n\nnetwork = nn.Net()\nnetwork.load(WEIGHTS_FILE)\n\npredicate = lambda text, res : 'http://dbpedia.org/ontology/{}'.format(vec_to_class(network.net(bag_of_words(preprocessing.full(text), d.dictionary)), d.classes))\n\nimport sys\nsys.path.insert(0, path)\nimport app_template\nimport return_template\n\nconfigfile = \"{}predicate/predicate.conf\".format(path)\naboutendpoint = \"/about\"\nhealthendpoint = \"/health\"\n\ndata_type = 'predicate'\nasks = []\n\nblueprint = return_template.service(predicate, asks, data_type, configfile).relation_clf\napp_template.app(configfile, aboutendpoint, healthendpoint, blueprint)\n","sub_path":"apps/predicate/app_predicate.py","file_name":"app_predicate.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"388612589","text":"# Birthday Months Counter\nimport json\nimport datetime\nfrom collections import Counter\n\nwith open(\"resources/Exercise34.json\", \"r\") as f:\n birthdays = json.load(f)\n\ndates = birthdays.values()\nparsedDates = []\n\nfor i in dates:\n my_date = datetime.datetime.strptime(i, \"%m/%d/%Y\")\n parsedDates.append(my_date.strftime(\"%B\"))\n\nc = Counter(parsedDates)\n\nwith open(\"resources/Exercise35.json\", \"w\") as f:\n json.dump(c, f, sort_keys=True, indent=4)\n","sub_path":"Exercise35.py","file_name":"Exercise35.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"343841883","text":"#!/usr/bin/python\n\nimport rospy, tf_conversions, rospkg\nfrom james_ur_kinematics.srv import *\nfrom geometry_msgs.msg import Pose, Point, Quaternion\nfrom natnet_msgs.msg import MarkerList\n\nimport numpy as np\nfrom time import sleep\n\npkg_dir = rospkg.RosPack().get_path('motive_ur_calib') + '/'\nmotive_samples_fp = pkg_dir + 'calib_data_motive.npy'\n\n### UR5 control\n\npx_r = [ 0.6, 0.7 ]; py_r = [ -0.2, 0.1 ]; pz_r = [ 0.1, 0.2 ]\nrr_r = [ -np.pi/2, np.pi/2 ]; rp_r = [ 0.0, np.pi/8 ]; ry_r = [ -np.pi/6, np.pi/6 ]\nur_move_time = 5.0\n\npose_ranges_ = [ px_r, py_r, pz_r, rr_r, rp_r, ry_r ]\npose_mindiff_ = [ [ np.min(pose_ranges_[i]), np.ptp(pose_ranges_[i]) ] for i in range(6) ]\nquaternion_from_euler = tf_conversions.transformations.quaternion_from_euler\n\ndef gen_random_pose(ik_svc):\n while True:\n r_ = np.random.random_sample(6)\n pose6_ = [ pose_mindiff_[i][0] + r_[i]*pose_mindiff_[i][1] for i in range(6) ]\n ql_ = list(quaternion_from_euler(*pose6_[3:]))\n ik_req_ = IKRequest(ee_pose=Pose(\n position=Point(*pose6_[:3]), orientation=Quaternion(*ql_)))\n jangs_ = ik_svc(ik_req_).joint_angles\n if len(jangs_) > 0: return list(jangs_[:6]), pose6_[:3]+ql_\n \ndef move_to_random_pose(ik_svc, m2j_svc):\n j6_,p7_ = gen_random_pose(ik_svc)\n m2j_svc(MoveToRequest(ur_state=j6_+[ur_move_time], gripper_state=True))\n \n return j6_, p7_\n\n### user input with typecast\n\ndef cast_input(datatype, s=''):\n while True:\n try:\n return datatype(raw_input(s))\n except:\n print(' Invalid input, please try again ...')\n\nif __name__ == '__main__':\n\n ### ROS stuff\n\n rospy.init_node('ur5_motive_calib_rec_script', anonymous=True)\n\n ik_topic_ = 'ur5_kin/IK'\n rospy.wait_for_service(ik_topic_)\n ik_svc_ = rospy.ServiceProxy(ik_topic_, IK)\n\n m2j_topic_ = 'ur5/command/moveToJoints'\n rospy.wait_for_service(m2j_topic_)\n m2j_svc_ = rospy.ServiceProxy(m2j_topic_, MoveTo)\n\n ### marker data handling\n\n def get_loose_markers_msg():\n while True:\n msg_ = rospy.wait_for_message(\n '/natnet_client/markers/leftovers', MarkerList)\n if len(msg_.ids) != 0: return msg_\n else: sleep(0.1)\n \n def get_marker_xyz(mID):\n while True:\n motive_msg_ = get_loose_markers_msg()\n if not (mID in motive_msg_.ids):\n print(motive_msg_.ids)\n mID = cast_input(int, ' Please enter a marker ID: ')\n else: \n i_ = motive_msg_.ids.index(mID)\n xyz_ = [ motive_msg_.positions[i_].x,\n motive_msg_.positions[i_].y, motive_msg_.positions[i_].z ]\n return xyz_, mID\n\n mID_ = None\n\n ### actual data gettin'\n \n n_samples_ = 10\n marker_readings_per_sample_ = 10\n \n motive_samps_all_ = np.empty([n_samples_,10])\n for i in range(n_samples_):\n # move robot\n j6_,p7_ = move_to_random_pose(ik_svc_, m2j_svc_)\n # marker positions\n motive_samps_ = np.empty([marker_readings_per_sample_,3])\n for j in range(marker_readings_per_sample_):\n motive_samps_[j,:],mID_ = get_marker_xyz(mID_)\n motive_samps_mean_ = np.mean(motive_samps_, axis=0)\n # append\n motive_samps_all_[i,:7] = p7_\n motive_samps_all_[i,7:] = motive_samps_mean_\n print('Recorded %d/%d' % (i+1,n_samples_))\n\n np.save(motive_samples_fp, motive_samps_all_)\n","sub_path":"src/record_data.py","file_name":"record_data.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"568349516","text":"#######################################################\n#Made by: Joren Vrancken\n#Description: sudoku solver with algorithme X \n#Last edit: 02-05-2013: added tutorial\n#######################################################\n#How to:\n#Put your sudoku in the var named 'sudoku'.\n#any known numbers as ints and unknown numbers as \"x\" with quotes\n#######################################################\nsudoku =[\n[\"x\",\"x\",\"x\",8,4,\"x\",\"x\",\"x\",9], \n[\"x\",\"x\",1,\"x\",\"x\",\"x\",\"x\",\"x\",5], \n[8,\"x\",\"x\",\"x\",2,1,4,6,\"x\"], \n[7,\"x\",8,\"x\",\"x\",\"x\",\"x\",9,\"x\"], \n[\"x\",\"x\",\"x\",\"x\",\"x\",\"x\",\"x\",\"x\",\"x\"], \n[\"x\",5,\"x\",\"x\",\"x\",\"x\",3,\"x\",1], \n[\"x\",2,4,9,1,\"x\",\"x\",\"x\",7], \n[9,\"x\",\"x\",\"x\",\"x\",\"x\",5,\"x\",\"x\"],\n[3,\"x\",\"x\",\"x\",8,4,\"x\",\"x\",\"x\"]]\n#######################################################\n#Don't edit anything beyond this line\n#######################################################\nimport time \nstart_time = time.time()\nprint(\"starting the sudoku solver\")\nprint(\"------sudoku to solve------\")\nfor row in sudoku:\n string = \"\"\n for n in row:\n string+=str(n)+\" \"\n print(string)\nprint(\"-\"*27)\nprint(\"Solutions\")\nprint(\"-\"*27)\n\n\ndef block(c):\n\tx=[0,0,c[2]]\n\tfor i in range(2):\n\t\tif c[i] < 3:\n\t\t\tx[i] = 1\n\t\tif c[i] >= 3 and c[i] < 6:\n\t\t\tx[i] = 2\n\t\tif c[i] >= 6:\n\t\t\tx[i] = 3\n\treturn (\"b\",x[0],x[1],x[2])\n\ndef dictcopy(dic):\n\tkeys = list(dic.keys())\n\tvalues = list(dic.values())\n\tvalues = [list(i) for i in values]\n\treturn dict(zip(keys,values))\n\ndef sudotoset(x):\n\td = {}\n\tfor i in range(len(x)):\n\t\tfor j in range(len(x[i])):\n\t\t\tif x[i][j] == \"x\":\n\t\t\t\tfor r in range(1,10):\n\t\t\t\t\td[(i,j,r)] = []\n\t\t\telse:\n\t\t\t\td[(i,j,x[i][j])]=[]\n\tfor i in d.keys():\n\t\td[i].append((\"k\",i[0],i[2]))\n\t\td[i].append((\"r\",i[1],i[2]))\n\t\td[i].append(block(i))\n\t\td[i].append((\"v\",i[0],i[1]))\n\treturn d\n\nSet = sudotoset(sudoku)\nvalues = []\nmatrix= {}\nkeys = sorted(list(Set.keys()))\nfor i in keys:\n\tfor j in Set[i]:\n\t\tif j not in values:\n\t\t\tvalues.append(j)\n\nfor i in range(len(keys)):\n\tkey = keys[i]\n\tmatrix[key]=[]\n\tfor j in values:\n\t\tif j in Set[key]:\n\t\t\tmatrix[key].append(1)\n\t\telse:\n\t\t\tmatrix[key].append(0)\ndel values,keys,Set,sudoku\n\nsets = [[[],matrix,[]]]\t\t\t\ndeleted= []\nsolution = []\nstep5=[]\nsolutioncount = 0\nsolved = False\nwhile solved == False:\n if sets == []:\n solved = True\n for mx in sets:\n matrix = mx[1]\n if matrix == {}:\n solutioncount+=1\n print(\"Solution\",solutioncount)\n print(\"-\"*27)\n s = [[0]*9 for number in range(9)]\n for solrow in sorted(mx[2]):\n s[solrow[0]][solrow[1]]=solrow[2]\n for solrow in s:\n sudostring=\"\"\n for solel in solrow:\n sudostring+=str(solel)+\" \"\n print(sudostring)\n print(\"-\"*27)\n continue\n allcolumncount = []\n for i in range(len(list(matrix.values())[0])):\n columncount = 0\n rows = []\n for j in sorted(matrix.keys()):\n if matrix[j][i] == 1:\n columncount+=1\n rows.append(j)\n allcolumncount.append([columncount,rows])\n columncountmin=[i[0] for i in allcolumncount]\n if min(columncountmin) == 0:\n continue\n rows = allcolumncount[columncountmin.index(min(columncountmin))][1]\n step5.append([rows,matrix,mx[2]])\n sets = []\n\n for s in step5:\n for row in s[0]:\n matrix=dictcopy(s[1])\n delete=[]\n for key in sorted(matrix.keys()):\n for c in range(len(matrix[row])):\n if matrix[row][c] == 1 and matrix[key][c] == 1:\n delete.append(key)\n break\n for key in delete:\n del matrix[key]\n\t\t\n delete = sorted([i for i in range(len(s[1][row])) if s[1][row][i] == 1],reverse=True)\n for key in matrix.keys():\n for d in delete:\n del matrix[key][d]\n sets.append([[],matrix,s[2]+[row]])\n step5=[]\nruntime = str(time.time()- start_time)\nprint(\"Solutions: \"+str(solutioncount))\nprint(\"Runtime: \"+runtime+\" seconds.\")\n","sub_path":"Algx older versions (Sudoku Solver)/algXv.3/algorithmxv3.6.py","file_name":"algorithmxv3.6.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"333596948","text":"#\n# matrix.py\n#\n# Copyright © 2007, 2011-2012, 2016 Monotype Imaging Inc. All Rights Reserved.\n#\n\n\"\"\"\nUtilities for manipulating transformation matrices.\n\"\"\"\n\n# System imports\nimport math\n\n# Other imports\nfrom fontio3.fontdata import seqmeta\nfrom fontio3.fontmath import matrix_row\n\n# -----------------------------------------------------------------------------\n\n#\n# Classes\n#\n\nclass Matrix(list, metaclass=seqmeta.FontDataMetaclass):\n \"\"\"\n Objects representing 3x3 matrices. These are lists of three lists of\n numeric values.\n \n >>> m = Matrix()\n >>> print(m)\n No changes\n \n >>> m = Matrix.forShift(25, -50)\n >>> m.pprint()\n Shift X by 25.0 and Y by -50.0\n \"\"\"\n \n #\n # Class definition variables\n #\n \n seqSpec = dict(\n item_deepconverterfunc = matrix_row.Matrix_row,\n item_followsprotocol = True,\n seq_fixedlength = 3,\n seq_pprintfunc = (lambda p,x,**k: p.simple(str(x), **k)))\n \n #\n # Methods\n #\n \n def __init__(self, *args, **kwArgs):\n \"\"\"\n Initializes the Matrix as specified, unless there are no parameters, in\n which case the identity matrix will be used.\n \n >>> m = Matrix([[1, 0, 0]])\n Traceback (most recent call last):\n ...\n ValueError: Matrix must have 3 rows.\n \"\"\"\n\n if args:\n v = [matrix_row.Matrix_row(x) for x in args[0]]\n \n else:\n v = identityMatrix.__deepcopy__()\n \n if len(v) != 3:\n raise ValueError(\"Matrix must have 3 rows.\")\n\n self[:] = v\n \n def __str__(self):\n \"\"\"\n Returns a string representation of the Matrix object that is relatively\n simple and easy for non-mathematicians to understand.\n \n >>> mScale = Matrix.forScale(1.75, -0.5)\n >>> mShift = Matrix.forShift(80, 300)\n >>> print(Matrix())\n No changes\n \n >>> print(mScale)\n Scale X by 1.75 and Y by -0.5\n \n >>> print(mShift)\n Shift X by 80.0 and Y by 300.0\n \n >>> print(mShift.multiply(mScale))\n Shift X by 80.0 and Y by 300.0, and then scale X by 1.75 and Y by -0.5\n \n >>> obj = mScale.multiply(mShift)\n >>> obj.kwArgs = {'shiftBeforeScale': False}\n >>> print(obj)\n Scale X by 1.75 and Y by -0.5, and then shift X by 80 and Y by 300\n \n >>> print(Matrix.forRotation(90))\n [[0.0, 1.0, 0], [-1.0, 0.0, 0], [0, 0, 1]]\n \"\"\"\n \n if self == identityMatrix:\n return \"No changes\"\n \n if any([self[0][1], self[0][2], self[1][0], self[1][2]]):\n return str([list(self[0]), list(self[1]), list(self[2])])\n \n sbs = getattr(self, 'kwArgs', {}).get('shiftBeforeScale', True)\n shift, scale = self.toShiftAndScale(sbs)\n hasXShift = bool(shift[2][0])\n hasYShift = bool(shift[2][1])\n hasShift = hasXShift or hasYShift\n hasXScale = scale[0][0] != 1.0\n hasYScale = scale[1][1] != 1.0\n hasScale = hasXScale or hasYScale\n sv = []\n \n if hasShift and hasScale:\n if sbs:\n sv.append(\n self._nicePiece(\n \"Shift\",\n hasXShift,\n hasYShift,\n shift[2][0],\n shift[2][1]))\n \n sv.append(\n self._nicePiece(\n \"scale\",\n hasXScale,\n hasYScale,\n scale[0][0],\n scale[1][1]))\n \n else:\n sv.append(\n self._nicePiece(\n \"Scale\",\n hasXScale,\n hasYScale,\n scale[0][0],\n scale[1][1]))\n \n sv.append(\n self._nicePiece(\n \"shift\",\n hasXShift,\n hasYShift,\n shift[2][0],\n shift[2][1]))\n \n elif hasShift:\n sv.append(\n self._nicePiece(\n \"Shift\",\n hasXShift,\n hasYShift,\n shift[2][0],\n shift[2][1]))\n \n else:\n sv.append(\n self._nicePiece(\n \"Scale\",\n hasXScale,\n hasYScale,\n scale[0][0],\n scale[1][1]))\n \n return \", and then \".join(sv)\n \n @staticmethod\n def _nicePiece(kind, doX, doY, x, y):\n if doX and doY:\n s = \"%s X by %s and Y by %s\" % (kind, x, y)\n elif doX:\n s = \"%s X by %s\" % (kind, x)\n else:\n s = \"%s Y by %s\" % (kind, y)\n \n return s\n \n def determinant(self):\n \"\"\"\n Returns the determinant of self. This will always be a floating-point\n number, even if the matrix is made up of integers.\n \n >>> m = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n >>> m.determinant()\n 0.0\n \"\"\"\n \n m1 = self[0][0] * (self[1][1] * self[2][2] - self[1][2] * self[2][1])\n m2 = self[0][1] * (self[1][0] * self[2][2] - self[1][2] * self[2][0])\n m3 = self[0][2] * (self[1][0] * self[2][1] - self[1][1] * self[2][0])\n return float(m1 + m3 - m2)\n \n @classmethod\n def forRotation(cls, angleInDegrees):\n \"\"\"\n Returns a Matrix object representing a transformation involving just a\n rotation by the specified angle in a counter-clockwise direction.\n \n >>> print(Matrix.forRotation(360))\n No changes\n \n >>> print(Matrix.forRotation(90))\n [[0.0, 1.0, 0], [-1.0, 0.0, 0], [0, 0, 1]]\n \n >>> print(Matrix.forRotation(180))\n Scale X by -1.0 and Y by -1.0\n \n >>> print(Matrix.forRotation(270))\n [[0.0, -1.0, 0], [1.0, 0.0, 0], [0, 0, 1]]\n \n >>> m = Matrix.forRotation(45)\n >>> for v in m:\n ... for n in v:\n ... print(round(n, 8))\n 0.70710678\n 0.70710678\n 0\n -0.70710678\n 0.70710678\n 0\n 0\n 0\n 1\n \"\"\"\n \n angleInDegrees %= 360\n \n if angleInDegrees == 0:\n s, c = 0.0, 1.0\n elif angleInDegrees == 90:\n s, c = 1.0, 0.0\n elif angleInDegrees == 180:\n s, c = 0.0, -1.0\n elif angleInDegrees == 270:\n s, c = -1.0, 0.0\n else:\n angleInRadians = angleInDegrees * math.pi / 180\n s, c = math.sin(angleInRadians), math.cos(angleInRadians)\n \n return cls([[c, s, 0], [-s, c, 0], [0, 0, 1]])\n \n @classmethod\n def forScale(cls, xScale, yScale):\n \"\"\"\n Returns a Matrix object representing a transformation involving just\n the two specified scale factors.\n \n >>> print(Matrix.forScale(1, 2))\n Scale Y by 2\n \"\"\"\n \n return cls([[xScale, 0, 0], [0, yScale, 0], [0, 0, 1]])\n \n @classmethod\n def forShift(cls, xMove, yMove):\n \"\"\"\n Returns a Matrix object representing a transformation involving just\n the two specified shift amounts.\n \n >>> print(Matrix.forShift(1, 2))\n Shift X by 1.0 and Y by 2.0\n \"\"\"\n \n return cls([[1, 0, 0], [0, 1, 0], [xMove, yMove, 1]])\n \n def inverse(self):\n \"\"\"\n Returns a new Matrix representing the inverse of self, or None if the\n matrix cannot be inverted.\n \n >>> m = Matrix([[2, 0, 0], [0, 1, 0], [10, 5, 1]])\n >>> print(list(m.inverse()))\n [Matrix_row([0.5, 0.0, 0.0]), Matrix_row([0.0, 1.0, 0.0]), Matrix_row([-5.0, -5.0, 1.0])]\n >>> print(m.inverse())\n Shift X by -10.0 and Y by -5.0, and then scale X by 0.5\n >>> m = Matrix([[0.0000005, 0, 0], [0, 0.0000005, 0], [0, 0, 1.0]])\n >>> m.inverse()\n \"\"\"\n \n det = self.determinant()\n \n if abs(det) < 1.0e-6:\n return None\n \n m = self.minor()\n m[0][1] = -m[0][1]\n m[1][0] = -m[1][0]\n m[1][2] = -m[1][2]\n m[2][1] = -m[2][1]\n t = m.transpose()\n return Matrix([[t[r][c] / det for c in range(3)] for r in range(3)])\n \n inverted = inverse\n \n def is2by2Equivalent(self):\n \"\"\"\n Returns a boolean indicating whether our matrix is equivalent to a 2x2,\n e.g.: [[a, b, 0],\n [d, e, 0],\n [0, 0, 1]]\n \n >>> Matrix([[3, 1, 0], [-2, -2, 0], [0, 0, 1]]).is2by2Equivalent()\n True\n >>> Matrix([[3, 1, 0.5], [-2, -2, 0], [0, 0, 1]]).is2by2Equivalent()\n False\n >>> Matrix([[3, 1, 0], [-2, -2, 0.5], [0, 0, 1]]).is2by2Equivalent()\n False\n \"\"\"\n \n if self[0][2]:\n return False\n \n if self[1][2]:\n return False\n \n return self[2] == [0, 0, 1]\n \n def mapPoint(self, p):\n \"\"\"\n Given a point-like object (a sequence of two values), applies the\n matrix to the point and returns the resulting point as a list of two\n values.\n \n >>> m = Matrix([[2, 0, 0], [0, 1, 0], [10, 5, 1]])\n >>> print(m.mapPoint([-10, 20]))\n [-10, 25]\n \"\"\"\n \n x, y = p[0], p[1]\n xNew = x * self[0][0] + y * self[1][0] + self[2][0]\n yNew = x * self[0][1] + y * self[1][1] + self[2][1]\n return [xNew, yNew]\n \n def minor(self):\n \"\"\"\n Returns a new Matrix representing the minor of self.\n \n >>> m = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n >>> print(m.minor())\n [[-3, -6, -3], [-6, -12, -6], [-3, -6, -3]]\n \"\"\"\n \n m00 = self[1][1] * self[2][2] - self[1][2] * self[2][1]\n m01 = self[1][0] * self[2][2] - self[1][2] * self[2][0]\n m02 = self[1][0] * self[2][1] - self[1][1] * self[2][0]\n m10 = self[0][1] * self[2][2] - self[0][2] * self[2][1]\n m11 = self[0][0] * self[2][2] - self[0][2] * self[2][0]\n m12 = self[0][0] * self[2][1] - self[0][1] * self[2][0]\n m20 = self[0][1] * self[1][2] - self[0][2] * self[1][1]\n m21 = self[0][0] * self[1][2] - self[0][2] * self[1][0]\n m22 = self[0][0] * self[1][1] - self[0][1] * self[1][0]\n return Matrix([[m00, m01, m02], [m10, m11, m12], [m20, m21, m22]])\n \n def multiplied(self, other):\n \"\"\"\n Returns a new Matrix representing self times other (in that order).\n \n >>> m1 = Matrix([[0.5, 0, 0], [0, 1, 0], [-5, -5, 1]])\n >>> m2 = Matrix([[3, 0, 0], [0, 3, 0], [0, 30, 1]])\n >>> print(list(m1.multiplied(m2)))\n [Matrix_row([1.5, 0.0, 0.0]), Matrix_row([0, 3, 0]), Matrix_row([-15, 15, 1])]\n >>> print(m1.multiplied(m2))\n Shift X by -10.0 and Y by 5.0, and then scale X by 1.5 and Y by 3\n \"\"\"\n \n m = []\n \n for row in range(3):\n for col in range(3):\n sum = 0\n \n for n in range(3):\n sum += self[row][n] * other[n][col]\n \n m.append(sum)\n \n return Matrix([m[0:3], m[3:6], m[6:9]])\n \n multiply = multiplied\n \n def toShiftAndScale(self, shiftBeforeScale=True):\n \"\"\"\n Decomposes self into two separate Matrix objects, one for shift and one\n for scale. If shiftBeforeScale is True, self is decomposed such that\n the shift matrix is multiplied by the scale to yield self; otherwise,\n self is decomposed such that the scale matrix is multiplied by the\n shift to yield self.\n\n Returns a pair (shift, scale) in that order, irrespective of the state\n of the shiftBeforeScale boolean.\n \n >>> m = Matrix([[3, 0, 0], [0, 2, 0], [30, 40, 1]])\n >>> ss = m.toShiftAndScale(False)\n >>> print(ss[0]) # always the shift\n Shift X by 30.0 and Y by 40.0\n >>> print(ss[1]) # always the scale\n Scale X by 3 and Y by 2\n \n >>> ss = m.toShiftAndScale(True)\n >>> print(ss[0]) # always the shift\n Shift X by 10.0 and Y by 20.0\n >>> print(ss[1]) # always the scale\n Scale X by 3 and Y by 2\n \n >>> mx = Matrix([[3, 0.5, 0.5], [0.5, 3, 0], [0, 0, 1]])\n >>> sx = mx.toShiftAndScale()\n >>> sx[0][0]\n Matrix_row([1, 0, 0])\n \"\"\"\n \n a, b, c, d = self[0][0], self[0][1], self[1][0], self[1][1]\n mScale = Matrix([[a, b, 0], [c, d, 0], [0, 0, 1]])\n \n if shiftBeforeScale:\n if b == 0 and c == 0: # the most common case by far\n dx = self[2][0] / a\n dy = self[2][1] / d\n \n else:\n disc = a * d - b * c\n dx = (d * self[2][0] - c * self[2][1]) / disc\n dy = (self[2][0] - a * dx) / c\n \n mShift = Matrix.forShift(dx, dy)\n \n else:\n mShift = Matrix.forShift(self[2][0], self[2][1])\n \n return mShift, mScale\n \n def transpose(self):\n \"\"\"\n Returns a new Matrix representing the transposition of self.\n \n >>> m = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n >>> print(m.transpose())\n [[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n \"\"\"\n \n return Matrix([[self[c][r] for c in range(3)] for r in range(3)])\n \n transposed = transpose\n\n# -----------------------------------------------------------------------------\n\n#\n# Constants\n#\n\nidentityMatrix = Matrix([\n matrix_row.Matrix_row([1.0, 0.0, 0.0]),\n matrix_row.Matrix_row([0.0, 1.0, 0.0]),\n matrix_row.Matrix_row([0.0, 0.0, 1.0])])\n\n# -----------------------------------------------------------------------------\n\n#\n# Test code\n#\n\nif 0:\n def __________________(): pass\n\ndef _test():\n import doctest\n doctest.testmod()\n\nif __name__ == \"__main__\":\n _test()\n","sub_path":"fontio3/fontio3/fontmath/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":14234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"373856109","text":"class Node:\n def __init__(self, parent = None, left = None, right = None):\n self.parent = parent\n self.left = left\n self.right = right\n\n\ndef insert(T, root, z):\n if root == z:\n T[z] = Node()\n else:\n T[z] = Node()\n x = root\n while x is not None:\n next_parent = x\n if z < x:\n x = T[x].left\n else:\n x = T[x].right\n T[z].parent = next_parent\n\n if z < next_parent:\n T[next_parent].left = z\n else:\n T[next_parent].right = z\n\n\ndef inParse(T, u, inOrder):\n if u is None:\n return\n inParse(T, T[u].left, inOrder)\n inOrder.append(u)\n inParse(T, T[u].right, inOrder)\n\n\ndef preParse(T, u, preOrder):\n if u is None:\n return\n preOrder.append(u)\n preParse(T, T[u].left, preOrder)\n preParse(T, T[u].right, preOrder)\n\n\nn = int(input())\nT = {}\n\nfor i in range(n):\n command = list(input().split())\n if command[0] == 'insert':\n z = int(command[1])\n if i == 0:\n root = z\n insert(T, root, z)\n else:\n preOrder, inOrder = [], []\n inParse(T, root, inOrder)\n preParse(T, root, preOrder)\n print(\"\", *inOrder)\n print(\"\", *preOrder)\n","sub_path":"ALDS1_8_A.py","file_name":"ALDS1_8_A.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"506786937","text":"'''\nHelper funations to be used.\n'''\n\nimport math, copy, csv\n\n\ndef print_helper(properties, prop_text, units):\n '''\n Used to print out the properties\n '''\n dummy_i = 0\n print(' \\n ')\n for prop_i in prop_text:\n print(str(prop_i) + ' ' + str(properties[dummy_i]) + ' ' + str(units[dummy_i]) )\n dummy_i += 1\n\ndef dist(p, q):\n return math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)\n\ndef get_num(x):\n try:\n return int(''.join(ele for ele in x if ele.isdigit() or ele == '.'))\n except ValueError:\n return x\n\ndef list_2_string(list):\n new_string = ''\n for item in list[0:-1]:\n new_string += str(item)\n new_string += ' , '\n new_string += str(list[-1])\n return new_string\n\ndef one_load_combination(line_name_obj, coord, defined_loads, load_condition,\n defined_tanks, comb_name, acc, load_factors_all):\n '''\n Creating load combination.\n Inserted into self.line_to_struc index = 4\n \"dnva\", \"line12\", \"static_ballast_10m\"\n #load combination dictionary (comb,line,load) : [stat - DoubleVar(), dyn - DoubleVar], on/off - IntVar()]\n :return:\n '''\n\n if load_condition not in ['tanktest','manual', 'slamming']:\n return helper_dnva_dnvb(line_name_obj, coord, defined_loads, load_condition,\n defined_tanks, comb_name, acc, load_factors_all)\n elif load_condition == 'tanktest' and comb_name == 'tanktest':\n return helper_tank_test(line_name_obj, coord, defined_loads, load_condition,\n defined_tanks, comb_name, acc, load_factors_all)\n elif load_condition == 'manual':\n return helper_manual(line_name_obj, comb_name,load_factors_all)\n elif load_condition == 'slamming':\n return helper_slamming(defined_loads)\n else:\n return None\n\ndef helper_dnva_dnvb(line_name_obj, coord, defined_loads, load_condition,\n defined_tanks, comb_name, acc, load_factors_all):\n\n # calculate the defined loads\n calc_load = []\n line_name = line_name_obj[0]\n structure_type = line_name_obj[1].get_structure_type()\n #print('---STRUCTURE TYPE---', structure_type)\n static_pressure,dynamic_pressure = 0,0\n #print('-----HELPER START FOR', comb_name, load_condition, line_name,'-----')\n if len(defined_loads) != 0:\n for load in defined_loads :\n if load != None:\n #print('LOAD NAME: ',comb_name, line_name, load.get_name())\n load_factors = load_factors_all[(comb_name, line_name, load.get_name())]\n # USE GET() (static,dyn, on/off)\n if load_condition == load.get_load_condition():\n static_pressure = (load_factors[2].get())*(load_factors[0].get())\\\n *load.get_calculated_pressure(coord, acc[0],structure_type)\n dynamic_pressure = (load_factors[2].get())*(load_factors[1].get())\\\n *load.get_calculated_pressure(coord, acc[1],structure_type)\n # print('load (NON-TANK) calculation for load condition:' , load_condition, ' - Load is: ', load.get_name(), ' - Type is: ')\n # print('static with acc:', acc[0], ' is: ',str(load_factors[2].get()),'*',str(load_factors[0].get()),'*',\n # str(load.get_calculated_pressure(coord, acc[0],structure_type)), ' = ', static_pressure)\n # print('dynamic with acc:', acc[1],' is: ',str(load_factors[2].get()),'*',str(load_factors[1].get()),'*',\n # str(load.get_calculated_pressure(coord, acc[1],structure_type)), ' = ', dynamic_pressure)\n calc_load.append(static_pressure+dynamic_pressure)\n\n # calculate the tank loads\n\n if len(defined_tanks) != 0:\n temp_tank = {}\n\n for tank_name_obj in defined_tanks:\n temp_tank[tank_name_obj[0]] = 0\n\n load_factors = load_factors_all[(comb_name, line_name, tank_name_obj[0])]\n overpress_lf = [1.3,0]# if load_factors[0].get()==1.2 else [1,1.3]\n\n if load_condition == tank_name_obj[1].get_condition():\n # USE GET() (static,dyn, on/off)\n static_pressure = load_factors[2].get()*(load_factors[0].get())\\\n *tank_name_obj[1].get_calculated_pressure(coord,acc[0])\\\n +tank_name_obj[1].get_overpressure()*overpress_lf[0]\n dynamic_pressure = load_factors[2].get()*load_factors[1].get()\\\n *tank_name_obj[1].get_calculated_pressure(coord,acc[1])\\\n +tank_name_obj[1].get_overpressure()*overpress_lf[1]\n\n temp_tank[tank_name_obj[0]] = static_pressure + dynamic_pressure# .append((static_pressure + dynamic_pressure))\n # if line_name_obj[0] == 'line46':\n # print('load (TANK) calculation for load condition:', load_condition, ' - Tank is: ', tank_name_obj[0])\n # print('load factors : ', load_factors[0].get(),load_factors[1].get(),load_factors[2].get())\n # print('static: ', str(load_factors[2].get()), '*', str(load_factors[0].get()) , '*',\n # str(tank_name_obj[1].get_calculated_pressure(coord,acc[0])),' + ',\n # str(tank_name_obj[1].get_overpressure()), '*',str(overpress_lf[0]), ' = ', static_pressure)\n # print('dynamic: ',str(load_factors[2].get()), '*', str(load_factors[1].get()), '*'\n # ,str(tank_name_obj[1].get_calculated_pressure(coord, acc[1])),' + ',\n # str(tank_name_obj[1].get_overpressure()), '*',str(overpress_lf[1]),' = ', dynamic_pressure)\n # choosing the tank with the highest pressures\n\n if len(defined_loads) == 0:\n line_tank_pressure_calc = max([pressure for pressure in temp_tank.values()])\n highest_dnv_tank_pressure = tank_name_obj[1].get_tank_dnv_minimum_pressure(load_factors[0].get(),\n load_factors[1].get())\n line_dnv_tank_pressure = tank_name_obj[1].get_line_pressure_from_max_pressure(highest_dnv_tank_pressure,\n coord)\n\n # print('Tank load to append is max( ',highest_tank_pressure_calc,highest_dnv_tank_pressure,')')\n highest_tank_pressure = max(line_tank_pressure_calc,line_dnv_tank_pressure)\n calc_load.append(-highest_tank_pressure if highest_tank_pressure else 0)\n else:\n pass\n # print('-----HELPER END, RESULT IS: ', calc_load,'-----')\n\n return int(abs(sum(calc_load)))\n\ndef helper_slamming(defined_loads):\n\n # calculate the defined loads\n\n if len(defined_loads) != 0:\n for load in defined_loads:\n if load != None and load.get_load_condition() == 'slamming':\n return load.get_calculated_pressure(0, 0, 'slamming')\n\n\ndef helper_tank_test(line_name_obj, coord, defined_loads, load_condition,\n defined_tanks, comb_name, acc, load_factors_all):\n # calculate the defined loads\n calc_load = []\n static_pressure, dynamic_pressure = 0, 0\n line_name = line_name_obj[0]\n structure_type = line_name_obj[1].get_structure_type()\n\n if len(defined_loads) != 0:\n for load in defined_loads:\n if load != None:\n load_factors = load_factors_all[(comb_name, line_name, load.get_name())]\n # USE GET() (static,dyn, on/off)\n if load_condition == load.get_load_condition():\n static_pressure = (load_factors[2].get()) * (load_factors[0].get()) \\\n * load.get_calculated_pressure(coord, acc[0], structure_type)\n dynamic_pressure = (load_factors[2].get()) * (load_factors[1].get()) \\\n * load.get_calculated_pressure(coord, acc[1], structure_type)\n calc_load.append(static_pressure + dynamic_pressure)\n\n # calculate the tank loads\n temp_tank={}\n if len(defined_tanks) != 0:\n\n for tank_name_obj in defined_tanks:\n temp_tank[tank_name_obj[0]] = []\n\n for tank_name_obj in defined_tanks:\n load_factors = load_factors_all[(comb_name, line_name, tank_name_obj[0])]\n # print('tank test LF: ', load_factors[0],load_factors[1],load_factors[2])\n # USE GET() (static,dyn, on/off)\n overpress_lf = [1.3, 0] if load_factors[0].get() == 1.2 else [1, 0]\n static_pressure = (load_factors[2].get()) * (load_factors[0].get())\\\n * tank_name_obj[1].get_calculated_pressure(coord, acc[0])\\\n +tank_name_obj[1].get_overpressure()*overpress_lf[0]\n dynamic_pressure = (load_factors[2].get()) * (load_factors[1].get())\\\n * tank_name_obj[1].get_calculated_pressure(coord, acc[1])\\\n +tank_name_obj[1].get_overpressure()*overpress_lf[1]\n\n temp_tank[tank_name_obj[0]].append((static_pressure + dynamic_pressure))\n # choosing the tank with the highest pressures\n if len(defined_tanks) != 0:\n highest_tank_pressure = max([temp_tank[tank[0]] for tank in defined_tanks])\n calc_load.append(-highest_tank_pressure[0] if len(highest_tank_pressure) > 0 else 0)\n else:\n pass\n return int(abs(sum(calc_load)))\n\ndef helper_manual(line_name, comb_name,load_factors_all):\n\n load_factors = load_factors_all[(comb_name, line_name[0], 'manual')]\n\n return load_factors[0].get() * load_factors[1].get() * load_factors[2].get()\n\ndef helper_read_section_file(files, obj = None, to_json = False, to_csv = False):\n ''' Read a xml file. '''\n import json\n from xml.dom import minidom\n to_return_final, to_return, return_csv = list(), dict(), list()\n if type(files) != list:\n files = [files,]\n for file in files:\n if file.endswith('xml'):\n xmldoc = minidom.parse(file)\n sectionlist = xmldoc.getElementsByTagName('section')\n sec_types = ('unsymmetrical_i_section', 'l_section', 'bar_section')\n\n for idx, sec_type in enumerate(sec_types):\n sec_type_get = xmldoc.getElementsByTagName(sec_type)\n if sec_types == []:\n continue\n for item, itemdata in zip(sectionlist, sec_type_get):\n if sec_type == sec_types[0]:\n stf_web_h, stf_web_thk = 'h', 'tw'\n stf_flange_width, stf_flange_thk = 'bfbot', 'tfbot'\n stiffener_type = 'T'\n mult = 1/1000\n elif sec_type == sec_types[1]:\n stf_web_h, stf_web_thk = 'h', 'tw'\n stf_flange_width, stf_flange_thk = 'b', 'tf'\n stiffener_type = 'L'\n mult = 1/1000\n elif sec_type == sec_types[2]:\n stf_web_h, stf_web_thk = 'h', 'b'\n stf_flange_width, stf_flange_thk = None, None\n stiffener_type = 'FB'\n mult = 1 / 1000\n section_name = item.getAttribute('name')\n to_return[section_name] = {'stf_web_height': [float(itemdata.getAttribute(stf_web_h)) *mult, 'm'],\n 'stf_web_thk': [float(itemdata.getAttribute(stf_web_thk)) *mult,'m'],\n 'stf_flange_width': [0 if stf_flange_width is None else\n float(itemdata.getAttribute(stf_flange_width)) *mult,'m'],\n 'stf_flange_thk': [0 if stf_flange_thk is None else\n float(itemdata.getAttribute(stf_flange_thk)) *mult, 'm'],\n 'stf_type': [stiffener_type, '']}\n\n return_csv.append([to_return[section_name][var][0] for var in ['stf_web_height', 'stf_web_thk',\n 'stf_flange_width', 'stf_flange_thk',\n 'stf_type']])\n if to_json:\n with open('sections.json', 'w') as file:\n json.dump(to_return, file)\n if to_csv:\n with open('sections.csv', 'w', newline='') as file:\n section_writer = csv.writer(file)\n for line in return_csv:\n section_writer.writerow(line)\n\n elif file.endswith('json'):\n with open(file, 'r') as json_file:\n to_return = json.load(json_file)\n\n elif file.endswith('csv'):\n with open(file, 'r') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for idx, section in enumerate(csv_reader):\n\n\n to_return[str(idx)] = {'stf_web_height': [float(section[0]), 'm'],\n 'stf_web_thk': [float(section[1]),'m'],\n 'stf_flange_width': [float(section[2]),'m'],\n 'stf_flange_thk': [float(section[3]), 'm'],\n 'stf_type': [section[4], '']}\n\n if to_json:\n with open('sections.json', 'w') as file:\n json.dump(to_return, file)\n\n if to_csv:\n with open('sections.csv', 'w', newline = '') as file:\n section_writer = csv.writer(file)\n for line in return_csv:\n section_writer.writerow(line)\n if obj is not None: # This will return a modified object.\n if type(obj) is not list:\n obj = [obj, ]\n append_list = [[],]\n else:\n append_list = [list() for dummy in obj]\n else:\n append_list = list()\n\n for key, value in to_return.items():\n if obj is not None: # This will return a modified object.\n for idx, iter_obj in enumerate(obj):\n new_obj = copy.deepcopy(iter_obj)\n new_obj_prop = new_obj.get_structure_prop()\n for prop_name, prop_val in value.items():\n new_obj_prop[prop_name] = prop_val\n new_obj.set_main_properties(new_obj_prop)\n append_list[idx].append(new_obj)\n else:\n to_return_final.append(value)\n if len(append_list) == 1:\n to_return_final = append_list[0]\n elif len(append_list) == 0:\n pass\n elif len(append_list) > 1:\n to_return_final = append_list\n\n return to_return_final\n\ndef open_example_file(root_path = None):\n import os\n\n if os.path.isfile('sections.csv'):\n os.startfile('sections.csv')\n else:\n os.startfile(root_path + '/' + 'sections.csv')\n\ndef add_new_section(section_list, new_section):\n ''' Checking if a section is already in the list. '''\n existing_section = False\n\n for section in section_list:\n\n if section.__str__() == new_section.__str__():\n existing_section = True\n\n if existing_section == False:\n section_list.append(new_section)\n\n return section_list\n\n\nif __name__ == '__main__':\n import ANYstructure.example_data as ex\n from pathlib import Path\n file = Path('C:/Users/nmm000756/Documents/GitHub/ANYstructure/ANYstructure/sections.json')\n all_returned = helper_read_section_file(file.name)\n\n import random\n print(random.choice(all_returned))\n","sub_path":"ANYstructure/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":15942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"485720607","text":"from collections import OrderedDict\n\nfrom crawlfrontier.exceptions import NotConfigured\nfrom crawlfrontier.utils.misc import load_object\nfrom crawlfrontier.settings import Settings\nfrom crawlfrontier.core.components import Backend, Middleware\nfrom crawlfrontier.logger import FrontierLogger\nfrom models import Page, Link\n\n\nclass FrontierManager(object):\n\n def __init__(self, page_model, link_model, backend, logger, event_log_manager,\n frontier_middlewares=None, test_mode=False,\n max_pages=0, max_next_pages=0, auto_start=True, settings=None):\n\n # Settings\n self._settings = settings or Settings()\n\n # Logger\n self._logger = load_object(logger)(self._settings)\n assert isinstance(self._logger, FrontierLogger), \"logger '%s' must subclass FrontierLogger\" % \\\n self._logger.__class__.__name__\n\n # Log frontier manager starting\n self.logger.manager.debug('-'*80)\n self.logger.manager.debug('Starting Frontier Manager...')\n\n # Test mode\n self._test_mode = test_mode\n self.logger.manager.debug('Test mode %s' % (\"ENABLED\" if self.test_mode else \"DISABLED\"))\n\n # Load page model\n self._page_model = load_object(page_model)\n assert issubclass(self._page_model, Page), \"Page model '%s' must subclass Page\" % \\\n self._page_model.__name__\n\n # Load link model\n self._link_model = load_object(link_model)\n assert issubclass(self._link_model, Link), \"Page model '%s' must subclass Link\" % \\\n self._link_model.__name__\n\n # Load middlewares\n self._frontier_middlewares = self._load_middlewares(frontier_middlewares)\n\n # Load backend\n self.logger.manager.debug(\"Loading backend '%s'\" % backend)\n self._backend = self._load_object(backend)\n assert isinstance(self.backend, Backend), \"backend '%s' must subclass Backend\" % \\\n self.backend.__class__.__name__\n\n # Init frontier components pipeline\n self._components_pipeline = [\n ('Middleware', self.frontier_middlewares),\n ('Backend', self.backend),\n ]\n\n # Page counters\n self._max_pages = max_pages\n self._max_next_pages = max_next_pages\n self._n_pages = 0\n\n # Iteration counter\n self._iteration = 0\n\n # Manager finished flag\n self._finished = False\n\n # Load Event log manager\n self.logger.manager.debug(\"Loading event log manager '%s'\" % event_log_manager)\n self._event_log_manager = self._load_object(event_log_manager)\n\n # Log frontier manager start\n self.logger.manager.debug('Frontier Manager Started!')\n self.logger.manager.debug('-'*80)\n\n # start/stop\n self._started = False\n self._stopped = False\n self._auto_start = auto_start\n if self.auto_start:\n self.start()\n\n\n @classmethod\n def from_settings(cls, settings=None):\n manager_settings = Settings(settings)\n return FrontierManager(page_model=manager_settings.PAGE_MODEL,\n link_model=manager_settings.LINK_MODEL,\n backend=manager_settings.BACKEND,\n logger=manager_settings.LOGGER,\n event_log_manager=manager_settings.EVENT_LOG_MANAGER,\n frontier_middlewares=manager_settings.MIDDLEWARES,\n test_mode=manager_settings.TEST_MODE,\n max_pages=manager_settings.MAX_PAGES,\n max_next_pages=manager_settings.MAX_NEXT_PAGES,\n auto_start=manager_settings.AUTO_START,\n settings=manager_settings)\n @property\n def settings(self):\n return self._settings\n\n @property\n def logger(self):\n return self._logger\n\n @property\n def test_mode(self):\n return self._test_mode\n\n @property\n def page_model(self):\n return self._page_model\n\n @property\n def link_model(self):\n return self._link_model\n\n @property\n def frontier_middlewares(self):\n return self._frontier_middlewares\n\n @property\n def backend(self):\n return self._backend\n\n @property\n def auto_start(self):\n return self._auto_start\n\n @property\n def event_log_manager(self):\n return self._event_log_manager\n\n @property\n def iteration(self):\n return self._iteration\n\n @property\n def max_pages(self):\n return self._max_pages\n\n @property\n def max_next_pages(self):\n return self._max_next_pages\n\n @property\n def n_pages(self):\n return self._n_pages\n\n def start(self):\n assert not self._started, 'Frontier already started!'\n self.event_log_manager.frontier_start()\n self.logger.manager.debug(self._msg('START'))\n self._process_components(method_name='frontier_start')\n self._started = True\n\n def stop(self):\n self._check_startstop()\n self.logger.manager.debug(self._msg('STOP'))\n self._process_components(method_name='frontier_stop')\n self._stopped = True\n self.event_log_manager.frontier_stop()\n\n def add_seeds(self, urls):\n self._check_startstop()\n links = [self._link_model(url=url) for url in urls]\n self.event_log_manager.add_seeds(links)\n self.logger.manager.debug(self._msg('ADD_SEEDS urls_length=%s' % len(urls)))\n return self._process_components(method_name='add_seeds',\n obj=links,\n return_classes=(list,))\n\n def page_crawled(self, page, links=None):\n self._check_startstop()\n self.logger.manager.debug(self._msg('PAGE_CRAWLED url=%s status=%s links=%s'\n % (page.url, page.status, len(links) if links else 0)))\n processed_page = self._process_components(method_name='page_crawled',\n obj=page,\n return_classes=Page,\n links=[self._link_model(url=url) for url in links] if links else [])\n self.event_log_manager.page_crawled(processed_page, links)\n return processed_page\n\n def page_crawled_error(self, page, error):\n self._check_startstop()\n self.logger.manager.debug(self._msg('PAGE_CRAWLED_ERROR url=%s' % page.url))\n processed_page = self._process_components(method_name='page_crawled_error',\n obj=page,\n return_classes=Page,\n error=error)\n self.event_log_manager.page_crawled_error(processed_page, error)\n return processed_page\n\n def get_next_pages(self, max_next_pages=0):\n self._check_startstop()\n\n # End condition check\n if self.max_pages and self.n_pages >= self.max_pages:\n self.logger.manager.warning(self._msg('MAX PAGES REACHED! (%s/%s)' % (self.n_pages, self.max_pages)))\n self._finished = True\n return []\n\n # Calculate number of pages to request\n max_next_pages = max_next_pages or self.max_next_pages\n if self.max_pages:\n if not max_next_pages:\n max_next_pages = self.max_pages - self.n_pages\n else:\n if self.n_pages+max_next_pages > self.max_pages:\n max_next_pages = self.max_pages - self.n_pages\n\n # log (in)\n self.logger.manager.debug(self._msg('GET_NEXT_PAGES(in) max_next_pages=%s n_pages=%s/%s' %\n (max_next_pages, self.n_pages, self.max_pages or '-')))\n\n # Request next pages\n next_pages = self.backend.get_next_pages(max_next_pages)\n\n # Increment page counter\n self._n_pages += len(next_pages)\n\n # Increment Iteration and log event\n if next_pages:\n self._iteration += 1\n self.event_log_manager.get_next_pages(max_next_pages, next_pages)\n\n # log (out)\n self.logger.manager.debug(self._msg('GET_NEXT_PAGES(out) returned_pages=%s n_pages=%s/%s' %\n (len(next_pages), self.n_pages, self.max_pages or '-')))\n\n # Return next pages\n return next_pages\n\n def get_page(self, url):\n self._check_startstop()\n self.logger.manager.debug(self._msg('GET_PAGE url=%s' % url))\n return self._process_components(method_name='get_page',\n obj=self._link_model(url=url),\n return_classes=Page)\n\n def _msg(self, msg):\n return '(%s) %s' % (self.iteration, msg)\n\n def _load_object(self, obj_class_name, silent=False):\n obj_class = load_object(obj_class_name)\n try:\n return self._load_frontier_object(obj_class)\n except NotConfigured:\n if not silent:\n raise NotConfigured\n\n def _load_frontier_object(self, obj_class):\n if hasattr(obj_class, 'from_manager'):\n return obj_class.from_manager(self)\n else:\n return obj_class()\n\n def _load_middlewares(self, middleware_names):\n # TO-DO: Use dict for middleware ordering\n mws = []\n for mw_name in middleware_names or []:\n self.logger.manager.debug(\"Loading middleware '%s'\" % mw_name)\n mw = self._load_object(mw_name, silent=True)\n assert isinstance(mw, Middleware), \"middleware '%s' must subclass Middleware\" % \\\n mw.__class__.__name__\n if mw:\n mws.append(mw)\n return mws\n\n def _process_components(self, method_name, obj=None, return_classes=None, **kwargs):\n return_obj = obj\n for component_category, component in self._components_pipeline:\n components = component if isinstance(component, list) else [component]\n for component in components:\n return_obj = self._process_component(component=component, method_name=method_name,\n component_category=component_category, obj=return_obj,\n return_classes=return_classes,\n **kwargs)\n if obj and not return_obj:\n self.logger.manager.warning(\"Object '%s' filtered in '%s' by '%s'\" % (\n obj.__class__.__name__, method_name, component.__class__.__name__\n ))\n return\n return return_obj\n\n def _process_component(self, component, method_name, component_category, obj, return_classes, **kwargs):\n debug_msg = \"processing '%s' '%s.%s' %s\" % (method_name, component_category, component.__class__.__name__, obj)\n self.logger.debugging.debug(debug_msg)\n return_obj = getattr(component, method_name)(*([obj] if obj else []), **kwargs)\n assert return_obj is None or isinstance(return_obj, return_classes), \\\n \"%s '%s.%s' must return None or %s, Got '%s'\" % \\\n (component_category, obj.__class__.__name__, method_name,\n ' or '.join(c.__name__ for c in return_classes)\n if isinstance(return_classes, tuple) else\n return_classes.__name__,\n return_obj.__class__.__name__)\n return return_obj\n\n def _check_startstop(self):\n assert self._started, \"Frontier not started!\"\n assert not self._stopped, \"Call to stopped frontier!\"\n\n def _log_event(self, event, params=None):\n event_params = OrderedDict()\n event_params['job_id'] = self.job_id\n event_params['iteration'] = self.iteration\n if params:\n event_params.update(params)\n self.logger.events.event(event=event, params=event_params)\n","sub_path":"crawlfrontier/core/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":12324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"569677222","text":"from shock_prep.utils import trees, dataframe_utils as df_utils\n\n\ndef _get_highest_priority_locations(df, use_osm=True):\n if not use_osm and df['map_type'].nunique() > 1:\n df = df.loc[df['map_type'] != \"open_street_maps\", :]\n\n best_map_type = df['map_type'].min()\n best_idxs = df['map_type'] == best_map_type\n best_locs = df.loc[best_idxs, 'location_id']\n if best_map_type == \"collaborator\" or best_map_type == \"manual\":\n return set(best_locs)\n\n kept = set(best_locs)\n for _, group in df.groupby('map_type', sort=True):\n # optimization\n if group.empty:\n continue\n new_locs = trees.filter_locs_for_ancestors_present(group.location_id, kept)\n kept = trees.keep_only_detailed_locs(kept | new_locs)\n return kept\n\n\ndef _locations_are_most_detailed(df, within):\n return (\n df\n .groupby(within, as_index=False)\n .agg({'location_id': lambda l: trees.keep_only_detailed_locs(set(l))})\n .pipe(df_utils.unnest, 'location_id')\n )\n\n\ndef _detailed_locations_within_map_type(d, use_col='source_col'):\n return _locations_are_most_detailed(d, within=['source_event_id', use_col, 'map_type'])\n\n\ndef _non_duplicated_over_map_types(d, use_col='source_col'):\n return (d\n .sort_values('map_type')\n .drop_duplicates(['source_event_id', use_col, 'location_id'],\n keep='first'))\n\n\ndef _has_multiple_unique_locations(d, use_col='source_col'):\n return (d\n .groupby(['source_event_id', use_col],\n as_index=False)\n .agg({'location_id': 'count'})\n .query('location_id > 1')\n .loc[:, ['source_event_id', use_col]]\n )\n\n\ndef _highest_priority_locations(df, use_osm=True, use_col='source_col'):\n\n if df.empty:\n return df[['source_event_id', use_col, 'location_id']]\n return (\n df\n .groupby(['source_event_id', use_col])\n .apply(lambda g: _get_highest_priority_locations(g, use_osm))\n .to_frame(name='location_id')\n .reset_index()\n .pipe(df_utils.unnest, 'location_id')\n )\n\n\ndef apply_mapping_hierarchy(df):\n out = df_utils.cascade(\n df,\n dict(property_map=_detailed_locations_within_map_type,\n keep_label='detailed_locations_within_map_type',\n add_keep_label=True),\n dict(property_map=_non_duplicated_over_map_types,\n keep_label='non_duplicated_over_map_types',\n add_keep_label=True),\n dict(property_map=_has_multiple_unique_locations,\n keep_label='has_multiple_unique_locations',\n add_keep_label=True),\n dict(property_map=_highest_priority_locations,\n keep_label='highest_priority_locations',\n add_keep_label=True),\n )\n\n return out.assign(\n map_type_hierarchy_kept=lambda d:\n d['detailed_locations_within_map_type'].fillna(False) &\n d['non_duplicated_over_map_types'].fillna(False) &\n (\n ~d['has_multiple_unique_locations'].fillna(False) |\n d['highest_priority_locations'].fillna(False)\n )\n )\n","sub_path":"gbd_2019/cod_code/fataldiscontinuities/location_mapping/apply_map_hierarchy.py","file_name":"apply_map_hierarchy.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"147615094","text":"#!/usr/bin/env python3\n\n\"\"\"Parse the hunt events CSV from the hunt website to see who won by various metrics\n\nADV = team advanced to that level\nREQ = team requested a hint\n\nEdit the values of the constants at the top of this file for your purposes, e.g.\nSTART_TIME, TEAM_NAMES, etc.\n\"\"\"\nimport csv\nfrom collections import defaultdict\nfrom datetime import datetime, timezone\nfrom pathlib import Path\nfrom typing import TypeAlias\n\n# Start time\nSTART_TIME = datetime.strptime(\"2000-01-01 00:00:00+0000\", \"%Y-%m-%d %H:%M:%S%z\")\n# 2.0 hours per hint\n# N.B. assumes all hints _requested_ take a penalty,\n# script will need editing if you want to only account for hints _used_\nPENALTY_PER_HINT_IN_HOURS = 2.0\n# \"Final\" level, the advance to which encodes that the team finished\nFINAL_LEVEL = \"51\"\n# List of team names as strings\nTEAM_NAMES: list[\"TeamName\"] = []\n# Path to hunt event csv taken from the website\nCSV_FILE_PATH = r\"C:\\Users\\username\\Downloads\\hunt.huntevent.csv\"\n\nTeamName: TypeAlias = str\n\n\ndef parse_timestamp(timestamp: str) -> datetime:\n return datetime.strptime(timestamp, \"%Y-%m-%d %H:%M:%S\").replace(\n tzinfo=timezone.utc\n )\n\n\ndef main(csv_file: str) -> None:\n teams = TEAM_NAMES\n team_raw_times: dict[TeamName, float] = defaultdict(float)\n team_running_totals: dict[TeamName, float] = defaultdict(float)\n team_hints_requested: dict[TeamName, int] = defaultdict(int)\n team_levels: dict[TeamName, int] = defaultdict(int)\n\n with Path(csv_file).open(encoding=\"utf-8\") as f:\n csv_reader = csv.DictReader(f)\n\n for line in csv_reader:\n team = line[\"user\"]\n assert team in teams\n # penalty of x hours per hint\n if line[\"type\"] == \"REQ\":\n team_running_totals[team] += PENALTY_PER_HINT_IN_HOURS\n team_hints_requested[team] += 1\n elif line[\"type\"] == \"ADV\":\n team_levels[team] += 1\n # Final level\n if line[\"level\"] == FINAL_LEVEL:\n timestamp = line[\"time\"].split(\".\")[0]\n finish_time = parse_timestamp(timestamp)\n time_taken = (finish_time - START_TIME).total_seconds() / 60 / 60\n print(time_taken)\n team_running_totals[team] += time_taken\n team_raw_times[team] = time_taken\n\n print(\"Raw times\", team_raw_times)\n print(\"Running totals\", team_running_totals)\n print(\"Hints requested\", team_hints_requested)\n print(\"Team levels completed\", team_levels)\n\n\nif __name__ == \"__main__\":\n main(CSV_FILE_PATH)\n","sub_path":"admin_scripts/calculate_winners.py","file_name":"calculate_winners.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"178945910","text":"\"\"\"This Python script counts words in a Markdown / LaTeX document(s).\n\nUsage:\n\tpython3 count_words.py \n\nIt will ignore ATX headers, LaTeX & Markdown comments, and LaTeX markup tags.\n\nTODO: inline HTML, Markdown images & tables\nTODO: LaTeX comments\n\"\"\"\n\n\ndef get_filename() -> str:\n\t\"\"\"\n\tGet the filename from the command line.\n\n\tReturns:\n\t\tthe first positional argument (the filename)\n\n\t\"\"\"\n\tfrom sys import argv\n\ttry:\n\t\t# try to get the filename\n\t\tfilename = argv[1]\n\texcept IndexError:\n\t\t# pass the exception along to the next level\n\t\traise ValueError('no filename position argument!')\n\treturn filename\n\n\ntry:\n\t# get the filename from the command line\n\tfilename = get_filename()\nexcept ValueError:\n\t# print the usage information and exit\n\tprint(__doc__)\n\tfrom sys import exit\n\texit(1)\n\n\n# specific Markdown files to ignore like READMEs and build artifacts\nIGNORED_MD_FILENAMES = ['README.md', 'build.md']\n\n# specific extensions to recognized as Markdown\nMARKDOWN_EXTENSIONS = ['.md', 'markdown', '.tex']\n\n\ndef is_md(filename: str) -> bool:\n\t\"\"\"\n\tReturn a boolean determining if the filename is a markdown file.\n\n\tArgs:\n\t filename: the filename to validate\n\n\tReturns:\n\t\ttrue if the filename is a markdown file, false otherwise\n\n\t\"\"\"\n # iterate over the ignored filenames to ensure the file is valid\n\tfor ignored_file_name in IGNORED_MD_FILENAMES:\n\t\tif filename == ignored_file_name:\n\t\t\treturn False\n # iterate over the extensions in the accepted extensions\n\tfor markdown_extension in MARKDOWN_EXTENSIONS:\n\t\tif markdown_extension == filename[-len(markdown_extension):]:\n\t\t\treturn True\n\t# the filename doesn't have a valid extension, return False\n\treturn False\n\n\ndef markdown_filenames(directory: str) -> list:\n\t\"\"\"\n\tReturn a list of the filenames in the input directory.\n\n\tArgs:\n\t\tdirectory: the input directory\n\n\tReturns:\n\t\ta list of the markdown files in the input directory.\n\n\t\"\"\"\n\tfrom os import listdir\n\ttry:\n\t\t# return a sorted list of the files in the given directory if they\n\t\t# are legal markdown files\n\t\treturn sorted([file for file in listdir(directory) if is_md(file)])\n\texcept FileNotFoundError:\n\t\t# catch a file not found error if the directory doesn't exist\n\t\tprint('{} does not exist!'.format(directory))\n\t\texit(1)\n\n\n# the sentinel value for LaTeX comment lines\nLATEX_COMMENT = '%'\n\n# the sentinel value for Markdown header lines\nMARKDOWN_HEADER = '#'\n\n\ndef clean_line(line: str) -> str:\n\t\"\"\"\n\tClean a single line and return it.\n\n\tArgs:\n\t\tline: the line of Markdown / LaTeX to clean\n\n\tReturns:\n\t\ta cleaned line of text\n\n\t\"\"\"\n\tif LATEX_COMMENT in line[:1] or MARKDOWN_HEADER in line[:1]:\n\t\t# ignore LaTeX comment lines and Markdown header lines\n\t\treturn ''\n\t# strip the line of all whitespace and new lines and append a single space\n\treturn line.rstrip() + ' '\n\n\n# A regular expression for removing Markdown comments\nMARKDOWN_COMMENT_REGEX = r''\n\n# a regular expression for removing LaTeX markup the group in () is the\n# optional [] parameters following a markup call.\nLATEX_MARKUP_REGEX = r'\\\\.+?{.+?}(\\[.+?\\])?'\n\n\ndef clean_contents(contents: str) -> str:\n\t\"\"\"\n\tClean and return the contents of a LaTeX / Markdown file.\n\n\tArgs:\n\t\tcontents: the contents of the file to clean\n\n\tReturns:\n\t\ta file with all markup nonsense removed\n\n\t\"\"\"\n\tclean_contents = contents\n\tfrom re import sub\n\t# remove the markdown comments from the text\n\tclean_contents = sub(MARKDOWN_COMMENT_REGEX, '', clean_contents)\n\t# remove the LaTeX markup\n\tclean_contents = sub(LATEX_MARKUP_REGEX, '', clean_contents)\n\t# return the clean text\n\treturn clean_contents\n\n\ndef read_file(filename: str) -> str:\n\t\"\"\"\n\tRead the contents of a single file.\n\n\tArgs:\n\t\tfilename: the name of the file to read\n\n\tReturns:\n\t\tthe string contents of the file\n\n\t\"\"\"\n\tif not is_md(filename):\n\t\traise ValueError('filename must have a valid markdown extension')\n\t# initialize the contents to store from the file\n\tcontents = ''\n\t# open the file into the contents one line at a time\n\twith open(filename) as md_file:\n\t\t# iterate over each line in the file and write it to the output\n\t\tfor line in md_file:\n\t\t\tcontents += clean_line(line)\n\treturn clean_contents(contents)\n\n\ndef read_dir(directory: str) -> str:\n\t\"\"\"\n\tRead the contents of every Markdown / LaTeX file in a directory.\n\n\tArgs:\n\t\tdirectory: the name of the directory to read files from\n\n\tReturns:\n\t\tthe concatenated contents of the files in the directory\n\n\t\"\"\"\n\t# initialize the contents to store from the files\n\tcontents = ''\n\t# iterate over the files and collect their contents\n\tfor filename in markdown_filenames(directory):\n\t\tcontents += read_file('{}/{}'.format(directory, filename))\n\treturn contents\n\n\ndef read_contents(filename: str) -> str:\n\t\"\"\"\n\tRead the contents of a file or directory.\n\n\tArgs:\n\t\tfilename: the filename or directory to read\n\n\tReturns:\n\t\tthe concatenated text from the file(s)\n\n\t\"\"\"\n\tfrom os.path import isdir\n\tif isdir(filename):\n\t\treturn read_dir(filename)\n\telse:\n\t\treturn read_file(filename)\n\n\ndef words(contents: str) -> int:\n\t\"\"\"\n\tReturn the number of words in a file's contents.\n\n\tArgs:\n\t\tcontents: the text to count the words in\n\n\tReturns:\n\t\tthe number of words in the contents\n\n\t\"\"\"\n\tfrom re import findall\n\treturn findall(r'\\w+', contents)\n\n\n# read the contents of the file\ncontents = read_contents(filename)\n# split the contents into words\nwords = words(contents)\n# count the words in the list\nword_count = len(words)\n# print the word count to the console\nprint('{} words in {}'.format(word_count, filename))\n","sub_path":"Backup-grid-cost-forecasting/paper/src/python/count_words.py","file_name":"count_words.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"250111911","text":"#Name: Muhammad Shoaib\n#Reg: L1f16bscs0162\n#Subject: PBD\n#Section: C\n#Assignment: 1\n\n\n\n\n\n\n#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# Question: 1\nimport math\n\ndef rotation(n):\n rotations = list()\n for i in range( len( str(n) ) ):\n m = int( str(n)[i:] + str(n)[:i] )\n rotations.append(m)\n return rotations\n\ndef primeCheck(num):\n # If given number is greater than 1 \n if num > 1:\n for i in range(2, num):\n if (num % i) == 0:\n return False\n break\n return True\n else:\n return False\n\n\ndef checkManyPrime(List):\n allDone = False\n length = len(List)\n for x in range(length):\n check = primeCheck(List[x])\n if check == True:\n allDone = True\n else:\n return False\n return True\n\nList = list()\n\nfor i in range(0, 10000):\n List.append(i+1)\n\nAllPrimeList = list()\nList2Count = 0\nfor x in range(0, 10000):\n check = primeCheck(List[x])\n if check == True:\n AllPrimeList.append(List[x])\n\n\ncircular_prime = list()\ncircular_prime_check = int(0)\nfor x in range(0, 100000):\n rotaion_list = rotation(x)\n check = checkManyPrime(rotaion_list)\n if check == True:\n circular_prime.append(x)\n circular_prime_check += 1\n\nprint(\"there are \",circular_prime_check,\" circular primes\")\nprint(circular_prime) \n\n\n# In[ ]:\n\n\ndef SieveOfEratosthenes(n): \n \n # Create a boolean array \"prime[0..n]\" and initialize \n # all entries it as true. A value in prime[i] will \n # finally be false if i is Not a prime, else true. \n prime = [True for i in range(n+1)] \n p = 2\n while (p * p <= n): \n \n # If prime[p] is not changed, then it is a prime \n if (prime[p] == True): \n \n # Update all multiples of p \n for i in range(p * p, n+1, p): \n prime[i] = False\n p += 1\n \n # Print all prime numbers\n count = int(0)\n List_prime = list()\n for p in range(2, n+1): \n if prime[p]:\n List_prime.append(p)\n return List_prime\n \ndef rotation(n):\n rotations = list()\n for i in range( len( str(n) ) ):\n m = int( str(n)[i:] + str(n)[:i] )\n rotations.append(m)\n return rotations\n\ndef primeCheck(num):\n # If given number is greater than 1 \n if num > 1:\n for i in range(2, num):\n if (num % i) == 0:\n return False\n break\n return True\n else:\n return False\n \ndef checkManyPrime(List):\n allDone = False\n length = len(List)\n for x in range(length):\n check = primeCheck(List[x])\n if check == True:\n allDone = True\n else:\n return False\n return True \n \n\n \n \nn = 1000000\nprint(\"Following are the prime numbers smaller\",) \nprint(\"than or equal to\", n)\nList_of_prime = SieveOfEratosthenes(n)\nprint(List_of_prime)\n\nlength_Prime = len(List_of_prime)\ncircular_prime = list()\ncircular_prime_check = int(0)\nfor x in range(length_Prime):\n rotaion_list = rotation(List_of_prime[x])\n print(rotaion_list)\n check = checkManyPrime(rotaion_list)\n if check == True:\n circular_prime.append(List_of_prime[x])\n circular_prime_check += 1\n \nprint(\"there are \",circular_prime_check,\" circular primes\")\nprint(circular_prime)\n\nlength_of_cir_prime = len(circular_prime)\nprint(\"the lenght is: \",length_of_cir_prime)\n\n\n# In[ ]:\n\n\n# Question 2\n\n\n# In[ ]:\n\n\ndef sieve(n):\n is_prime = [True]*n\n is_prime[0] = False\n is_prime[1] = False\n is_prime[2] = True\n for i in range(3, int(n**0.5+1), 2):\n index = i*2\n while index < n:\n is_prime[index] = False\n index = index+i\n prime = [2]\n for i in range(3, n, 2):\n if is_prime[i]:\n prime.append(i)\n return prime\n\nprimes = sieve(1000000)\n\n\nlength = 0\n\n\nlargest = 0\n\n\nlastj = len(primes)\n\nfor i in range(len(primes)):\n for j in range(i+length, lastj):\n sol = sum(primes[i:j])\n if sol < 1000000:\n if sol in primes:\n length = j-i\n largest = sol\n else:\n lastj = j+1\n break\n\nprint(largest)\n\n\n# In[4]:\n\n\n# Question 3\n\n\n# In[5]:\n\n\nrm_prime = list()\n\ndef sieve(n):\n is_prime = [True]*n\n is_prime[0] = False\n is_prime[1] = False\n is_prime[2] = True\n # even numbers except 2 have been eliminated\n for i in range(3, int(n**0.5+1), 2):\n index = i*2\n while index < n:\n is_prime[index] = False\n index = index+i\n prime = [2]\n for i in range(3, n, 2):\n if is_prime[i]:\n prime.append(i)\n return prime\n\ndef leftCheck(num):\n length = len(str(abs(num)))\n length2 = length -1\n power = 10**length2\n flag = True\n num2 = num\n for x in range(length2):\n if num2 in rm_prime:\n flag = True\n print(\"true\")\n else: \n flag = False\n \n num2 = num2 % power\n power = power / 10\n print(num2, \",\", power)\n return flag\n \n \n\nPrime_number = sieve(1000000)\n\nrm_prime = Prime_number[4:]\n\nrm_prime_len = len(rm_prime)\n\nprint(leftCheck(23))\n\n# for prime in rm_prime:\n# flag = True\n# leftCheck(prime)\n \n \n# leftCheck()\n# print(rm_prime)\n\n\n# In[6]:\n\n\n# Question 4\n\n\n# In[11]:\n\n\ndef is_lychrel(n):\n \n for i in range(50):\n number = n + int(str(n)[::-1])\n if str(number) == str(number)[::-1]:\n return False\n n = number\n return True\n\ncounter = 0\n\nfor i in range(10001):\n if is_lychrel(i):\n counter += 1\n\nprint(counter)\n\n\n# In[12]:\n\n\n# Question 5\n\n\n# In[13]:\n\n\nclass CircularQueue(): \n \n def __init__(self, size): \n self.size = size \n \n self.queue = [None for i in range(size)] \n self.front = self.rear = -1\n \n def enqueue(self, data): \n \n if ((self.rear + 1) % self.size == self.front): \n print(\" Queue is Full\\n\") \n \n elif (self.front == -1): \n self.front = 0\n self.rear = 0\n self.queue[self.rear] = data \n else: \n \n self.rear = (self.rear + 1) % self.size \n self.queue[self.rear] = data \n \n def dequeue(self): \n if (self.front == -1): \n print (\"Queue is Empty\\n\") \n \n elif (self.front == self.rear): \n temp=self.queue[self.front] \n self.front = -1\n self.rear = -1\n return temp \n else: \n temp = self.queue[self.front] \n self.front = (self.front + 1) % self.size \n return temp \n \n def display(self): \n \n if(self.front == -1): \n print (\"Queue is Empty\") \n \n elif (self.rear >= self.front): \n print(\"Elements in the circular queue are:\", \n end = \" \") \n for i in range(self.front, self.rear + 1): \n print(self.queue[i], end = \" \") \n print () \n \n else: \n print (\"Elements in Circular Queue are:\", \n end = \" \") \n for i in range(self.front, self.size): \n print(self.queue[i], end = \" \") \n for i in range(0, self.rear + 1): \n print(self.queue[i], end = \" \") \n print () \n \n if ((self.rear + 1) % self.size == self.front): \n print(\"Queue is Full\") \n \n# Driver Code \nob = CircularQueue(5) \nob.enqueue(14) \nob.enqueue(22) \nob.enqueue(13) \nob.enqueue(-6) \nob.display() \nprint (\"Deleted value = \", ob.dequeue()) \nprint (\"Deleted value = \", ob.dequeue()) \nob.display() \nob.enqueue(9) \nob.enqueue(20) \nob.enqueue(5) \nob.display() \n\n\n# In[14]:\n\n\n# Question 6\n\n\n# In[15]:\n\n\nfrom queue import Queue \n \nclass Stack: \n \n def __init__(self): \n \n self.q1 = Queue() \n self.q2 = Queue() \n \n self.curr_size = 0\n \n def push(self, x): \n self.curr_size += 1\n \n self.q2.put(x) \n \n \n while (not self.q1.empty()): \n self.q2.put(self.q1.queue[0]) \n self.q1.get() \n \n self.q = self.q1 \n self.q1 = self.q2 \n self.q2 = self.q \n \n def pop(self): \n \n if (self.q1.empty()): \n return\n self.q1.get() \n self.curr_size -= 1\n \n def top(self): \n if (self.q1.empty()): \n return -1\n return self.q1.queue[0] \n \n def size(self): \n return self.curr_size \n \n# Driver Code \nif __name__ == '__main__': \n s = Stack() \n s.push(1) \n s.push(2) \n s.push(3) \n \n print(\"current size: \", s.size()) \n print(s.top()) \n s.pop() \n print(s.top()) \n s.pop() \n print(s.top()) \n \n print(\"current size: \", s.size()) \n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Assignment 1.py","file_name":"Assignment 1.py","file_ext":"py","file_size_in_byte":8917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"27536502","text":"#analyze the chains from narrow and wide priored harmonic model. plot histograms and chains\n\nimport pystan, os,pickle,sys,numpy\nfrom pystan import *\nimport matplotlib.pyplot as plt\nfrom glob import glob\nfrom os.path import *\nfrom numpy import *\nimport pandas as pd\nfrom scipy.io import loadmat\nfrom scipy.stats import norm\nfrom ipdb import set_trace\n\ndef findSubjects(path):\n return [x.split(os.sep)[-1] for x in glob(join(path,'sub*'))]\n\ndef analPlot(sub,phase,model):\n '''\n analPlot is of course short for analyse and plot\n What else?\n '''\n print('ANALyzing {}'.format(sub)) \n #load fit, extract chains, rearrange for easier plotting\n path = join(sub,'phase{:02d}'.format(phase),'quadruplet','fit_long_warmup{}.pic'.format(model))\n try:\n fit = pickle.load(open(path,'rb'))\n except:\n fit = pickle.load(open(path.replace('.pic',''),'rb'))\n \n chains = fit.extract(['konstante','allWeights','sigma'])\n chains = {x: expand_dims(chains[x],axis = len(chains[x].shape)) for x in chains.keys()}\n chains = concatenate([chains['sigma'],chains['konstante'],*[chains['allWeights'][:,:,x] for x in range(chains['allWeights'].shape[-1]) ] ],axis = 1)\n chainNames = ['sigma','konstante',*['cosWeight{}'.format(x) for x in range(3)],*['sinWeight{}'.format(x) for x in range(3)]]\n chains = pd.DataFrame(chains,columns = chainNames)\n \n #figure\n# fig,ax = plt.subplots(nrows=len(chainNames),ncols=2,sharex=False,sharey=False,figsize=(15,20))\n# for x,name in enumerate(chainNames):\n# ax[x,0].hist(chains.loc[:,name],bins = 30)\n# ax[x,0].set_title(name)\n# ax[x,1].plot(chains.loc[:,name])\n# ax[x,0].set_title(name,fontdict = {'fontsize':20})\n# ax[x,0].tick_params(axis='both', which='both', labelsize=15)\n# ax[x,1].tick_params(axis='both', which='both', labelsize=15)\n# for y in range(2): \n# for tick in ax[x,y].get_xticklabels():\n# tick.set_visible(True)\n# plt.subplots_adjust(hspace=0.6)\n# fig.savefig(join(sub,'phase{:02d}'.format(phase),'quadruplet','plotChain_longWarmup_{}.png'.format(model)))\n plt.close() \n #get mode based solution and pickle it\n solution = getSolution(fit,style='mean')\n with open(join(sub,'phase{:02d}'.format(phase),'quadruplet','meanSolution_longWarmup_{}.pic'.format(model)),'wb') as f:\n pickle.dump(solution,f,-1)\n #load stimlist and responses for likelihood computation\n matDat = loadmat(join(sub,'phase{:02d}'.format(phase),'quadruplet','data.mat'))['out'][0][0]\n negLL = computeNegLL(solution,matDat)\n with open(join(sub,'phase{:02d}'.format(phase),'quadruplet','negLL_bayes_longWarmup_{}_mean.pic'.format(model)),'wb') as f:\n pickle.dump(negLL,f,-1)\n return fit\n\ndef getSolution(fit, style = 'mode'):\n solution = {'radii': None, 'sigma': None}\n if style == 'mode':\n chains = fit.extract(['sigma','radii'])\n for param in solution.keys():\n solution[param] = mode(chains[param])[0]\n elif style == 'mean':\n f = fit.summary()\n fit = pd.DataFrame(f['summary'],columns = f['summary_colnames'], index = f['summary_rownames'])\n solution['radii'] = fit.loc[fit.index.str.contains('radii'),'mean']\n solution['sigma'] = fit.loc['sigma','mean']\n else:\n print('No valid measure of central tendency. Try again with \"mean\" or \"mode\"')\n return\n return solution\n\ndef computeNegLL(solution,mat):\n radii = solution['radii']\n sigma = solution['sigma']\n #set_trace()\n angles = array(range(radii.size)) / 4 * pi\n #get stimlst and responses\n stimlist = mat[0]-1\n responses = mat[1].squeeze()\n #radii and angles as per stimlist\n trRadii = radii[stimlist]\n trAngles = angles[stimlist]\n #difference in angles\n dRho = concatenate([diff(trAngles[:,:2]),diff(trAngles[:,2:])],axis=1)\n #difference in distances\n dist = zeros(dRho.shape)\n dist[:,0] = sqrt((trRadii[:,:2]**2).sum(axis=1) -2 * trRadii[:,:2].prod(axis=1) * cos(dRho[:,0]))\n dist[:,1] = sqrt((trRadii[:,2:]**2).sum(axis=1) -2 * trRadii[:,2:].prod(axis=1) * cos(dRho[:,1]))\n d_dist = dist[:,1] -dist[:,0]\n #probability of choices as given by estimated parameters\n p = norm.cdf(d_dist,0,sigma)**(1-responses) * (1-norm.cdf(d_dist,0,sigma))**(responses)\n #combined to negative log likelihood\n negLL = - sum(log(p))\n return negLL\n\ndef mode(ndarray, axis=0):\n # Check inputs\n ndarray = numpy.asarray(ndarray)\n ndim = ndarray.ndim\n if ndarray.size == 1:\n return (ndarray[0], 1)\n elif ndarray.size == 0:\n raise Exception('Cannot compute mode on empty array')\n try:\n axis = range(ndarray.ndim)[axis]\n except:\n raise Exception('Axis \"{}\" incompatible with the {}-dimension array'.format(axis, ndim))\n\n # If array is 1-D and numpy version is > 1.9 numpy.unique will suffice\n if all([ndim == 1,\n int(numpy.__version__.split('.')[0]) >= 1,\n int(numpy.__version__.split('.')[1]) >= 9]):\n modals, counts = numpy.unique(ndarray, return_counts=True)\n index = numpy.argmax(counts)\n return modals[index], counts[index]\n\n # Sort array\n sort = numpy.sort(ndarray, axis=axis)\n # Create array to transpose along the axis and get padding shape\n transpose = numpy.roll(numpy.arange(ndim)[::-1], axis)\n shape = list(sort.shape)\n shape[axis] = 1\n # Create a boolean array along strides of unique values\n strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'),\n numpy.diff(sort, axis=axis) == 0,\n numpy.zeros(shape=shape, dtype='bool')],\n axis=axis).transpose(transpose).ravel()\n # Count the stride lengths\n counts = numpy.cumsum(strides)\n counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])])\n counts[strides] = 0\n # Get shape of padded counts and slice to return to the original shape\n shape = numpy.array(sort.shape)\n shape[axis] += 1\n shape = shape[transpose]\n slices = [slice(None)] * ndim\n slices[axis] = slice(1, None)\n # Reshape and compute final counts\n counts = counts.reshape(shape).transpose(transpose)[slices] + 1\n\n # Find maximum counts and return modals/counts\n slices = [slice(None, i) for i in sort.shape]\n del slices[axis]\n index = numpy.ogrid[slices]\n index.insert(axis, numpy.argmax(counts, axis=axis))\n return sort[index], counts[index]\n\n\nif __name__ == '__main__':\n global model#necessary for fit to be unpickled. global bc lazy \n global base\n base = r'C:\\Users\\neugebauer\\Documents\\Experiments\\MAPDS\\testData'\n os.chdir(base)\n os.chdir('..') \n model = [pickle.load(open(join(os.getcwd(),'stanModels','harmonic_model_{}.pic'.format(x)),'rb')) for x in ['wide','narrow']]\n os.chdir('testData')\n subjects = findSubjects(base)\n os.chdir(base)#from now on everything is relative\n [analPlot(s,p,m) for s in subjects for p in [2,4] for m in ['narrow']]\n","sub_path":"functions/harmonicAnalyzeChains_mean.py","file_name":"harmonicAnalyzeChains_mean.py","file_ext":"py","file_size_in_byte":7071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"646793830","text":"\"\"\"\nCMSSW job type plug-in\n\"\"\"\n\nimport os\nimport tempfile\n\nfrom WMCore.DataStructs.LumiList import LumiList\n\nimport PandaServerInterface as PandaInterface\n\nfrom CRABClient.JobType.BasicJobType import BasicJobType\nfrom CRABClient.JobType.CMSSWConfig import CMSSWConfig\nfrom CRABClient.JobType.LumiMask import getLumiMask\nfrom CRABClient.JobType.UserTarball import UserTarball\nfrom CRABClient.JobType.ScramEnvironment import ScramEnvironment\nfrom CRABClient.client_exceptions import EnvironmentException\n\nclass Analysis(BasicJobType):\n \"\"\"\n CMSSW job type plug-in\n \"\"\"\n\n\n def run(self, requestConfig):\n \"\"\"\n Override run() for JobType\n \"\"\"\n configArguments = {'addoutputfiles' : [],\n 'adduserfiles' : [],\n 'tfileoutfiles' : [],\n 'edmoutfiles' : [],\n }\n\n # Get SCRAM environment\n scram = ScramEnvironment(logger=self.logger)\n\n configArguments.update({'jobarch' : scram.scramArch,\n 'jobsw' : scram.cmsswVersion, })\n\n # Build tarball\n if self.workdir:\n tarUUID = PandaInterface.wrappedUuidGen()\n self.logger.debug('UNIQUE NAME: tarUUID %s ' % tarUUID)\n if len(tarUUID):\n tarFilename = os.path.join(self.workdir, tarUUID +'default.tgz')\n cfgOutputName = os.path.join(self.workdir, 'CMSSW_cfg.py')\n else:\n raise EnvironmentException('Problem with uuidgen while preparing for Sandbox upload.')\n else:\n _dummy, tarFilename = tempfile.mkstemp(suffix='.tgz')\n _dummy, cfgOutputName = tempfile.mkstemp(suffix='_cfg.py')\n\n #configArguments['userisburl'] = 'https://'+ self.config.General.ufccacheUrl + '/crabcache/file?hashkey=' + uploadResults['hashkey']#XXX hardcoded\n #configArguments['userisburl'] = 'INSERTuserisburl'#XXX hardcoded\n if getattr(self.config.Data, 'inputDataset', None):\n configArguments['inputdata'] = self.config.Data.inputDataset\n# configArguments['ProcessingVersion'] = getattr(self.config.Data, 'processingVersion', None)\n\n # Create CMSSW config\n self.logger.debug(\"self.config: %s\" % self.config)\n self.logger.debug(\"self.config.JobType.psetName: %s\" % self.config.JobType.psetName)\n cmsswCfg = CMSSWConfig(config=self.config, logger=self.logger,\n userConfig=self.config.JobType.psetName)\n\n # Interogate CMSSW config and user config for output file names, for now no use for edmFiles or TFiles here.\n analysisFiles, edmFiles = cmsswCfg.outputFiles()\n self.logger.debug(\"TFiles %s and EDM Files %s will be collected\" % (analysisFiles, edmFiles))\n configArguments['tfileoutfiles'] = analysisFiles\n configArguments['edmoutfiles'] = edmFiles\n\n outputFiles = getattr(self.config.JobType, 'outputFiles', [])\n self.logger.debug(\"User files %s will be collected\" % outputFiles)\n configArguments['addoutputfiles'].extend(outputFiles)\n\n # Write out CMSSW config\n cmsswCfg.writeFile(cfgOutputName)\n\n with UserTarball(name=tarFilename, logger=self.logger, config=self.config) as tb:\n inputFiles = getattr(self.config.JobType, 'inputFiles', [])\n tb.addFiles(userFiles=inputFiles, cfgOutputName=cfgOutputName)\n configArguments['adduserfiles'] = [os.path.basename(f) for f in inputFiles]\n uploadResults = tb.upload()\n\n self.logger.debug(\"Result uploading input files: %s \" % str(uploadResults))\n configArguments['cachefilename'] = uploadResults[1]\n configArguments['cacheurl'] = uploadResults[0]\n isbchecksum = uploadResults[2]\n\n # Upload list of user-defined input files to process as the primary input\n userFileName = getattr(self.config.Data, 'userInputFile', None)\n if userFileName:\n self.logger.debug(\"Attaching a list of user-specified primary input files from %s.\" % userFileName)\n fnames = []\n for fname in open(userFileName).readlines():\n fnames.append(fname.strip())\n configArguments['userfiles'] = fnames\n\n primDS = getattr(self.config.Data, 'primaryDataset', None)\n if primDS:\n # Normalizes \"foo/bar\" and \"/foo/bar\" to \"/foo/bar\"\n primDS = \"/\" + os.path.join(*primDS.split(\"/\"))\n if not re.match(\"/%(primDS)s.*\" % WMCore.Lexicon.lfnParts, primDS):\n self.logger.warning(\"Invalid primary dataset name %s for private MC; publishing may fail\" % primDS)\n configArguments['inputdata'] = primDS\n elif getattr(self.config.Data, 'inputDataset', None):\n configArguments['inputdata'] = self.config.Data.inputDataset\n else:\n configArguments['inputdata'] = \"/CRAB_UserFiles\"\n\n # Upload lumi mask if it exists\n lumiMaskName = getattr(self.config.Data, 'lumiMask', None)\n if lumiMaskName:\n self.logger.debug(\"Attaching lumi mask %s to the request\" % lumiMaskName)\n lumiDict = getLumiMask(config=self.config, logger=self.logger)\n configArguments['runs'] = lumiDict.keys()\n #for each run we'll encode the lumis as a string representing a list of integers\n #[[1,2],[5,5]] ==> '1,2,5,5'\n configArguments['lumis'] = [ str(reduce(lambda x,y: x+y, \\\n lumiDict[run]))[1:-1].replace(' ','') \\\n for run in configArguments['runs'] ]\n\n configArguments['jobtype'] = 'Analysis'\n\n return tarFilename, configArguments, isbchecksum\n\n\n def validateConfig(self, config):\n \"\"\"\n Validate the CMSSW portion of the config file making sure\n required values are there and optional values don't conflict\n \"\"\"\n\n valid, reason = self.validateBasicConfig(config)\n if not valid:\n return (valid, reason)\n\n if not getattr(config.Data, 'inputDataset', None) and not getattr(config.Data, 'userInputFile', None):\n valid = False\n reason += 'Crab configuration problem: missing or null input dataset name. '\n\n if self.splitAlgo == 'EventBased': \n valid = False\n reason += 'Analysis JobType does not support EventBased Splitting.'\n\n return (valid, reason)\n\n def validateBasicConfig(self, config):\n \"\"\"\n Validate the common portion of the config for data and MC making sure\n required values are there and optional values don't conflict\n \"\"\"\n\n valid = True\n reason = ''\n\n if not getattr(config, 'Data', None):\n valid = False\n reason += 'Crab configuration problem: missing Data section. '\n\n self.splitAlgo = getattr(config.Data, 'splitting', None)\n if not self.splitAlgo:\n valid = False\n reason += 'Crab configuration problem: missing or null splitting algorithm. '\n\n if not getattr(config.JobType, 'psetName', None):\n valid = False\n reason += 'Crab configuration problem: missing or null CMSSW config file name. '\n\n return (valid, reason)\n","sub_path":"src/python/CRABClient/JobType/Analysis.py","file_name":"Analysis.py","file_ext":"py","file_size_in_byte":7413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"573318983","text":"import smtplib\nimport json\nfrom email.message import EmailMessage\nfrom twilio.rest import Client\nimport os\n\n\n# with open('bot_alert.json') as f:\n# \t\tdata = json.load(f)\n\ndef email_alerts(subject, body, to):\n# print('alerting..')\n\n msg = EmailMessage()\n msg['Subject'] = subject\n msg['To'] = to\n msg['From'] = 'Task Master Alerts'\n msg.set_content(body)\n\n user = os.environ['USERNAME']\n passwd = os.environ['APP_PASS']\n\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.starttls()\n server.login(user, passwd)\n server.send_message(msg)\n server.quit()\n\ndef phone_carrier(number):\n sid = os.environ['TWIL_SID']\n tok = os.environ['TWIL_TOK']\n client = Client(sid, tok)\n phone = client.lookups \\\n .phone_numbers(number)\\\n .fetch(type=['carrier'])\n \n return phone.carrier['name']\n\ndef phone_alerts(number, subject,body):\n c = str(phone_carrier(number)).lower()\n\n avail={\n \"t-mobile\" : \"@tmomail.net\",\n 'at&t': '@txt.att.net',\n 'boost': '@sms.myboostmobile.com',\n 'cricket': '@mms.cricketwireless.net',\n 'sprint': '@messaging.sprintpcs.com',\n 'verizon': '@vtext.com'\n }\n # print(c)\n temp = ''\n for key in avail:\n if key in c:\n temp = avail[key]\n return email_alerts(subject, body, f'{number}{temp}')\n\n\n\nif __name__ == '__main__':\n email_alerts('asd','asd','junhyxf@gmail.com')\n\n\n\n\n","sub_path":"alert_program.py","file_name":"alert_program.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"378482467","text":"# -*- coding: utf-8 -*-\r\n# @Author: LiLing\r\n# @Date: 2018-09-11 10:53:24\r\n# @Last Modified by: Liling\r\n# @Last Modified time: 2018-09-11 12:48:54\r\n\"\"\"\r\n给定一个无向图graph,当这个图为二分图时返回true。\r\n如果我们能将一个图的节点集合分割成两个独立的子集A和B,并使图中的每一条边的两个节点一个来自A集合,一个来自B集合,我们就将这个图称为二分图。\r\ngraph将会以邻接表方式给出,graph[i]表示图中与节点i相连的所有节点。每个节点都是一个在0到graph.length-1之间的整数。这图中没有自环和平行边: \r\ngraph[i] 中不存在i,并且graph[i]中没有重复的值。\r\n\r\n\r\n示例 1:\r\n输入: [[1,3], [0,2], [1,3], [0,2]]\r\n输出: true\r\n解释: \r\n无向图如下:\r\n0----1\r\n| |\r\n| |\r\n3----2\r\n我们可以将节点分成两组: {0, 2} 和 {1, 3}。\r\n\r\n示例 2:\r\n输入: [[1,2,3], [0,2], [0,1,3], [0,2]]\r\n输出: false\r\n解释: \r\n无向图如下:\r\n0----1\r\n| \\ |\r\n| \\ |\r\n3----2\r\n我们不能将节点分割成两个独立的子集。\r\n注意:\r\n\r\ngraph 的长度范围为 [1, 100]。\r\ngraph[i] 中的元素的范围为 [0, graph.length - 1]。\r\ngraph[i] 不会包含 i 或者有重复的值。\r\n图是无向的: 如果j 在 graph[i]里边, 那么 i 也会在 graph[j]里边。\r\n\"\"\"\r\nclass Solution:\r\n def isBipartite(self, graph):\r\n \"\"\"\r\n :type graph: List[List[int]]\r\n :rtype: bool\r\n \"\"\"\r\n def validColor(graph, colors, color, node):\r\n if colors[node] != -1:\r\n return colors[node] == color\r\n colors[node] =color\r\n for j in graph[node]:\r\n if not validColor(graph, colors, 1 - color, j):\r\n return False\r\n return True\r\n \r\n n = len(graph)\r\n colors = [-1]*n\r\n for i in range(n):\r\n if colors[i]==-1 and not validColor(graph, colors, 0, i):\r\n return False\r\n\r\n return True\r\n\r\nclass Solution:\r\n def isBipartite(self, graph):\r\n \"\"\"\r\n :type graph: List[List[int]]\r\n :rtype: bool\r\n \"\"\"\r\n WHITE, BLACK = range(2)\r\n\r\n if not graph:\r\n return True\r\n\r\n def dfs(node, color=WHITE):\r\n if node in colormap:\r\n return colormap[node] == color\r\n # assign color to node\r\n colormap[node] = color\r\n # toggle color\r\n color = BLACK if color == WHITE else WHITE\r\n # check following nodes\r\n return all(dfs(neighbor, color) for neighbor in graph[node])\r\n\r\n colormap = {}\r\n # check graph nodes\r\n return all(dfs(node) for node in range(len(graph)) if node not in colormap)\r\n\r\ns=Solution()\r\nprint(s.isBipartite([[1],[0,3],[3],[1,2]]))","sub_path":"LeetCode/785.IsGraphBipartite判断二分图(递归).py","file_name":"785.IsGraphBipartite判断二分图(递归).py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"237271814","text":"import sys\n\ndef handleForceExit(ClassName):\n object = ClassName()\n try:\n object.execute()\n except KeyboardInterrupt:\n object.closeConnection()\n sys.exit(1)\n\ndef parseInt(stringToParse):\n try:\n if not stringToParse: return None\n return int(stringToParse)\n except:\n print('Cannot convert string to integer')\n return None","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"153679835","text":"# 방금 그곡 - 구현 - 17683\n'''\n라디오를 자주 듣는 네오는 라디오에서 방금 나왔던 음악이 무슨 음악인지 궁금해질 때가 많다. \n그럴 때 네오는 다음 포털의 '방금그곡' 서비스를 이용하곤 한다. \n방금그곡에서는 TV, 라디오 등에서 나온 음악에 관해 제목 등의 정보를 제공하는 서비스이다.\n\n네오는 기억한 멜로디를 재생 시간과 제공된 악보를 직접 보면서 비교하려고 한다. 다음과 같은 가정을 할 때 네오가 찾으려는 음악의 제목을 구하여라.\n\n\n방금그곡 서비스에서는 음악 제목, 재생이 시작되고 끝난 시각, 악보를 제공한다.\n네오가 기억한 멜로디와 악보에 사용되는 음은 C, C#, D, D#, E, F, F#, G, G#, A, A#, B 12개이다.\n각 음은 1분에 1개씩 재생된다. 음악은 반드시 처음부터 재생되며 음악 길이보다 재생된 시간이 길 때는 음악이 끊김 없이 처음부터 반복해서 재생된다. 음악 길이보다 재생된 시간이 짧을 때는 처음부터 재생 시간만큼만 재생된다.\n음악이 00:00를 넘겨서까지 재생되는 일은 없다.\n조건이 일치하는 음악이 ���러 개일 때에는 라디오에서 재생된 시간이 제일 긴 음악 제목을 반환한다. 재생된 시간도 같을 경우 먼저 입력된 음악 제목을 반환한다.\n조건이 일치하는 음악이 없을 때에는 “(None)”을 반환한다.\n'''\nimport datetime\n\n\ndef solution(m, musicinfos):\n # musicinfos에서 재생시간을 구한다......\n times = [(datetime.datetime.strptime(i.split(\n ',')[1], '%H:%M') - datetime.datetime.strptime(i.split(',')[0], '%H:%M')).seconds//60 for i in musicinfos]\n\n # print(times)\n\n # melody를 재생시간만큼 반복시켜 구한다..\n melodys = []\n for i, musicinfo in enumerate(musicinfos):\n music = musicinfo.split(',')[-1]\n # print(shop_count)\n music *= (times[i]) # 범위 실수 했었음\n # print(music)\n shop_count = music[:times[i]+1].count('#')\n # print(shop_count)\n melody = ''\n for j in range(times[i]+shop_count):\n melody += music[j]\n melodys.append(melody)\n # print(melodys)\n\n # C# 같은애들 소문자로 치환..\n new_melodys = []\n for melody in melodys:\n if 'C#' in melody:\n melody = melody.replace('C#', 'c')\n new_melodys.append(melody)\n elif 'D#' in melody:\n melody = melody.replace('D#', 'd')\n new_melodys.append(melody)\n elif 'F#' in melody:\n melody = melody.replace('F#', 'f')\n new_melodys.append(melody)\n elif 'G#' in melody:\n melody = melody.replace('G#', 'g')\n new_melodys.append(melody)\n elif 'A#' in melody:\n melody = melody.replace('A#', 'a')\n new_melodys.append(melody)\n else:\n new_melodys.append(melody)\n # print(new_melodys)\n\n if 'C#' in m:\n m = m.replace('C#', 'c')\n elif 'D#' in m:\n m = m.replace('D#', 'd')\n elif 'F#' in m:\n m = m.replace('F#', 'f')\n elif 'G#' in m:\n m = m.replace('G#', 'g')\n elif 'A#' in m:\n m = m.replace('A#', 'a')\n\n # print(new_melodys)\n # print(m)\n\n temp = []\n for i in range(len(new_melodys)):\n # 주어진 음이 멜로디들 안에 포함되어 있으면 인덱스를 저장인데\n if m in new_melodys[i]:\n temp.append(i)\n if temp == []:\n return \"(None)\"\n\n # 같은 멜로디가 포함된 노래가 있을경우 - 재생시간이 긴 것을 출력하라고 했다. 그래서 위에서 인덱스 저장\n max_len_music = 0 # 재생시간이 제일 긴 노래\n for t in temp:\n if max_len_music <= times[t]:\n max_len_music = times[t]\n\n # 그노래의 인덱스\n idx = times.index(max_len_music)\n # 답안 도출\n\n return musicinfos[idx].split(',')[2]\n\n\n# print(\n# solution('ABCDEFG', [\"12:00,12:14,HELLO,CDEFGAB\", \"13:00,13:05,WORLD,ABCDEF\"]))\n# print(solution('CC#BCC#BCC#BCC#B', [\n# \"03:00,03:30,FOO,CC#B\", \"04:00,04:08,BAR,CC#BCC#BCC#B\"]))\nprint(\n solution('ABC#', [\"12:00,12:14,HELLO,C#DEFGAB\", \"13:00,13:05,WORLD,ABCDEF\"]))\n# print(\n# solution('ABC#', [\"12:15,12:14,HELLO,C#DEFGAB\", \"13:00,13:05,WORLD,ABCDEF\"]))\n","sub_path":"python/programmers/구현/[17683_구현_방금그곡]홍종완.py","file_name":"[17683_구현_방금그곡]홍종완.py","file_ext":"py","file_size_in_byte":4381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"439468396","text":"from abc import ABCMeta, abstractmethod\n\n#추상 클래스\nclass Character(metaclass=ABCMeta):\n def __init__(self, name, hp, power):\n self.name=name\n self.hp=hp\n self.power=power\n\n @abstractmethod\n def attack(self, other, attack_kind):\n pass\n\n @abstractmethod\n def get_damage(self, power, attack_kind):\n pass\n\n def __str__(self):\n return '{} : {}'.format(self.name, self.hp)\n\nclass Player(Character):\n def __init__(self, name='player', hp=100, power=10, *attack_kinds):\n super().__init__(name, hp, power)\n\n self.skills=[]\n for attack_kind in attack_kinds:\n self.skills.append(attack_kind)\n\n def attack(self, other, attack_kind):\n if attack_kind in self.skills:\n other.get_damage(self.power, attack_kind)\n\n def get_damage(self, power, attack_kind):\n \"\"\"\n attack_kind가 self.skills에 있으면 피해가 반감\n \"\"\"\n if attack_kind in self.skills:\n self.hp-= (power//2)\n else:\n self.hp-=power\n\n#공통된 부분은 부모 클래스로 만들어 둔다.\nclass Monster(Character):\n def __init__(self, name, hp, power):\n super().__init__(name, hp, power)\n self.attack_kind=None\n\n def attack(self, other, attack_kind):\n if self.attack_kind==attack_kind:\n other.get_damage(self.power, attack_kind)\n\n #공격 받을 때 \n #불 몬스터의 경우 불 공격을 받으�� 오히려 체력이 증가!!\n #얼음 공격을 받으면 체력이 깎인다.\n def get_damage(self, power, attack_kind):\n \"\"\"\n 몬스터는 같은 속성의 공격을 받으면 체력이 증가!!\n \"\"\"\n if self.attack_kind==attack_kind:\n self.hp+=power\n else:\n self.hp-=power\n\n def get_attack_kind(self):\n return self.attack_kind\n\nclass IceMonster(Monster):\n def __init__(self, name='Ice monster', hp=50, power=10):\n super().__init__(name, hp, power)\n self.attack_kind='ICE'\n\nclass FireMosnter(Monster):\n def __init__(self, name='Fire monster', hp=50, power=20):\n super().__init__(name, hp, power)\n self.attack_kind='FIRE'\n\nif __name__==\"__main__\":\n player=Player('sword master', 100, 30, 'ICE')\n monsters=[]\n monsters.append(IceMonster())\n monsters.append(FireMosnter())\n\n for monster in monsters:\n print(monster)\n\n for monster in monsters:\n player.attack(monster, 'ICE')\n\n print('after the player attacked')\n for monster in monsters:\n print(monster)\n print()\n\n print(player)\n\n for monster in monsters:\n #플레이어가 ICE 공격 가짐\n #아이스 몬스터 공격시 5만 깎임\n #파이어 몬스터 공격시 20이 깎임\n monster.attack(player, monster.get_attack_kind())\n \n print('after monsters attacked')\n print(player)\n","sub_path":"class/character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"432949569","text":"from django.db import models\r\nfrom django.contrib.auth.models import AbstractUser\r\nimport json\r\n# Create your models here.\r\n#用户\r\nclass User(AbstractUser):\r\n qq = models.CharField(max_length=20, blank=True, null=True, verbose_name='QQ号码')\r\n mobile = models.CharField(max_length=11, blank=True, null=True, unique=True, verbose_name='手机号码')\r\n\r\n class Meta:\r\n verbose_name = '用户'\r\n verbose_name_plural = verbose_name\r\n ordering = ['-id']\r\n\r\n def __str__(self):\r\n return self.username\r\n\r\nclass behaviours(models.Model):\r\n user = models.ForeignKey(User, verbose_name='用户',on_delete=models.CASCADE,)\r\n imgId = models.CharField(max_length=100, verbose_name='图片ID')\r\n # startTime = models.CharField(max_length=300, verbose_name='开始时间')\r\n # endTime = models.CharField(max_length=300, verbose_name='结束时间')\r\n startTime = models.CharField(max_length=300, verbose_name='开始时间')\r\n endTime = models.CharField(max_length=300, verbose_name='结束时间')\r\n clickCounter = models.IntegerField(default=0, verbose_name='鼠标选中次数')\r\n Interval = models.FloatField(default=0.0, verbose_name='持续时间(s)')\r\n humanBehavior = models.CharField(max_length=2000, verbose_name='用户行为')\r\n machineBehavior = models.CharField(max_length=2000, verbose_name='机器行为')\r\n inputLogs = models.CharField(max_length=3000, verbose_name='文本框日志')\r\n annotation = models.CharField(max_length=2000, verbose_name='标注结果')\r\n imageUrl= models.CharField(max_length=1000,verbose_name='图片路径')\r\n # imageFile= models.ImageField(upload_to='clothing/%Y/%m', default= 'clothing/default.jpg', verbose_name='图片路径')\r\n\r\n class Meta:\r\n verbose_name = '行为'\r\n verbose_name_plural = verbose_name \r\n ordering = ['id']\r\n\r\n # def __str__(self):\r\n # return self.user.username + \"--\" + self.imgId+ \"--\" +self.annotation\r\n\r\nclass picturesTab(models.Model):\r\n imgId= models.CharField(max_length=100,verbose_name='图片ID')\r\n imageUrl= models.CharField(max_length=100,verbose_name='图片路径')\r\n aiRecommenddations= models.CharField(max_length=200,verbose_name='机器推荐描述')\r\n class Meta:\r\n verbose_name = '图片库'\r\n verbose_name_plural = verbose_name\r\n ordering = ['id']\r\n\r\nclass workStack(models.Model):\r\n user = models.ForeignKey(User, verbose_name='用户',on_delete=models.CASCADE,)\r\n imgId= models.CharField(max_length=100,verbose_name='图片ID')\r\n serialNumber= models.IntegerField(default=0, verbose_name='标注序列号')\r\n class Meta:\r\n verbose_name = '工作栈'\r\n verbose_name_plural = verbose_name\r\n ordering = ['id']\r\n\r\nimport csv\r\nfrom django.http import HttpResponse\r\nfrom django.utils.http import urlquote\r\ndef export_as_csv_action(description='Export selected objects as csv file',\r\n fields=None,exclude=None,header=True):\r\n def export_as_csv(modeladmin,request,queryset):\r\n opts=modeladmin.model._meta\r\n if not fields:\r\n field_names=[field for field in opts]\r\n else:\r\n field_names=fields\r\n response = HttpResponse( content_type = 'text/csv')\r\n response['Content-Disposition']='attachment;filename={}.csv'.format(urlquote(opts.verbose_name))\r\n writer = csv.writer(response)\r\n if header:\r\n writer.writerow(field_names)\r\n for obj in queryset:\r\n \r\n # 正常的这样处理就行了\r\n row = [getattr(obj,field)()if callable(getattr(obj,field))else getattr(obj,field) for field in field_names]\r\n\r\n # 如果新添处理功能比如处理下时间的显示格式\r\n # row=[]\r\n # forfieldinfield_names:\r\n # value=getattr(obj,field)\r\n # ifisinstance(value,datetime.datetime):\r\n # value=value.'WW^sY')\r\n # row.append(value)\r\n\r\n writer.writerow(row)\r\n return response\r\n export_as_csv.short_description = description\r\n return export_as_csv\r\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"383135864","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def levelOrder(self, root: 'TreeNode') -> 'List[List[int]]':\n if not root: return []\n queue = [root]\n ans = []\n while queue:\n i, length = 0, len(queue)\n cur = []\n while i < length: # Fix length, store & pop value in same level\n n = queue.pop(0)\n cur.append(n.val)\n if n and n.left: queue.append(n.left)\n if n and n.right: queue.append(n.right)\n i += 1\n ans.append(cur[:])\n return ans \n","sub_path":"src/102-binary-tree-level-order-traversal.py","file_name":"102-binary-tree-level-order-traversal.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"583868842","text":"\"\"\"\nRxPY example running a Tornado server doing search queries against\nWikipedia to populate the autocomplete dropdown in the web UI. Start\nusing `python autocomplete.py` and navigate your web browser to\nhttp://localhost:8080\nUses the RxPY AsyncIOScheduler (Python 3.4 is required)\n\"\"\"\n\nimport os\nimport rx\nasyncio = rx.config['asyncio']\n\nfrom rx.subjects import Subject\nfrom rx.concurrency import AsyncIOScheduler\nfrom time import sleep\n\n\nscheduler = AsyncIOScheduler()\n\n\ndef search_wikipedia(term):\n \"\"\"Search Wikipedia for a given term\"\"\"\n url = 'http://en.wikipedia.org/w/api.php'\n\n params = {\n \"action\": 'opensearch',\n \"search\": term,\n \"format\": 'json'\n }\n # Must set a user agent for non-browser requests to Wikipedia\n user_agent = \"RxPY/1.0 (https://github.com/dbrattli/RxPY; dag@brattli.net) Tornado/4.0.1\"\n\n url = url_concat(url, params)\n\n http_client = AsyncHTTPClient()\n return http_client.fetch(url, method='GET', user_agent=user_agent)\n\n\nclass WSHandler():\n def open(self):\n print(\"WebSocket opened\")\n\n # A Subject is both an observable and observer, so we can both subscribe\n # to it and also feed (send) it with new values\n self.subject = Subject()\n\n # Get all distinct key up events from the input and only fire if long enough and distinct\n searcher = (self.subject\n .map(lambda x: x[\"term\"])\n # Only if the text is longer than 2 characters\n .filter(lambda text: len(text) > 2)\n .debounce(750) # Pause for 750ms\n .distinct_until_changed() # Only if the value has changed\n .flat_map_latest(search_wikipedia)\n )\n\n def handle_response(x):\n print(x.body)\n\n def on_error(ex):\n print(ex)\n\n searcher.subscribe(handle_response, on_error, scheduler=scheduler)\n\n def on_message(self, message):\n obj = json_decode(message)\n self.subject.on_next(obj)\n\n\ndef main():\n AsyncIOMainLoop().install()\n asyncio.get_event_loop().run_forever()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"async_autocomplete.py","file_name":"async_autocomplete.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"652493430","text":"\nfrom django.urls import path,include\nfrom django.contrib import admin\n\n# from .views import (\n# FoodsListView,\n# FoodsDetailView,\n# RestaurantsListView,\n# RestaurantsDetailView\n# # ArticleCreateView,\n# # ArticleUpdateView,\n# # ArticleDeleteVie w\n# )\nfrom .views import (\n # FoodsListView,\n # FoodsDetailView,\n RestaurantsListView,\n RestaurantsDetailView,\n RestaurantsCreateView,\n RestaurantsUpdateView,\n RestaurantsDeleteView,\n TrendingListView\n # ArticleCreateView,\n # ArticleUpdateView,\n # ArticleDeleteView\n)\n\nurlpatterns = [\n # path('Foods', FoodsListView.as_view()),\n # path('', RestaurantsListView.as_view()),\n # path('Foods', FoodsListView.as_view()),\n path('Restaurants', RestaurantsListView.as_view()),\n path('Trending/', TrendingListView.as_view()),\n # path('login', LoginView.as_view()),\n path('Restaurants/create/', RestaurantsCreateView.as_view()),\n # path('creat e/', ArticleCreateView.as_view()),\n # path('', FoodsDetailView.as_view()),\n path('Restaurants/', RestaurantsDetailView.as_view()),\n path('Restaurants//update/', RestaurantsUpdateView.as_view()),\n path('Restaurants//delete/', RestaurantsDeleteView.as_view()),\n # path('admin/', admin.site.urls),\n # path('create/', ArticleCreateView.as_view()),\n # path('', FoodsDetailView.as_view()),\n # path('/update/', ArticleUpdateView.as_view()),\n # path('/delete/', ArticleDeleteView.as_view())\n]\n","sub_path":"restaurant/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"316355729","text":"import numpy as np\nimport pylab\nimport matplotlib.pyplot as plt\nfrom astropy.io import ascii\n\ndebug0 = True\t\t# See the raw signal\ndebug = False\t\t# Set to true to plot graphs\ndebug1 = True\t\t# Set to true to plot graphs\ndebug2 = False\t\t# Good and bad examples\ndebug3 = True\t\t# deltas heatmap\n\n\nstep1 = True\nstep2 = True\n\n\ndef compare_signal(signal, samples_per_symbol, packet_size, samples_between_packets):\n\n\t#signal = signal[50000:-1]\n\tprint(\"samples:\t\t\t\t\t\" + str(len(signal)))\n\tprint(\"samples_per_symbol:\t\t\" + str(samples_per_symbol))\n\tprint(\"samples_between_packets:\t\" + str(samples_between_packets))\n\n\tdiff_signal = np.gradient(signal)\n\tdiff_signal1 = [x * 10 for x in diff_signal]\n\n\tsignal_ceil = max(signal)\n\tsignal_floor = min(signal)\n\t#print(\"\\n\\namplitude\" + str(signal_ceil - signal_floor) + \"\\n\\n\")\n\n\tratio = 0.27\n\n\tthreshold = ((signal_ceil - signal_floor)*ratio) + signal_floor\n\n\t#pylab.plot(signal)\n\n\tsignal_zero_centered = [(x - threshold) for x in signal]\n\n\n\t#determine the PBZ points\n\tzero_crossings = np.where(np.diff(np.signbit(signal_zero_centered)))[0]\n\tzero_crossings = zero_crossings.tolist()\n\t#zero_crossings.append(len(signal_zero_centered))\n\n\t#determine the diff PBZ points\n\n\tzero_crossings_diff = np.where(np.diff(np.signbit(diff_signal)))[0]\n\tzero_crossings_diff = zero_crossings_diff.tolist()\n\t#zero_crossings_diff.append(len(diff_signal))\n\n\tzcc = []\n\tfor x in zero_crossings:\n\t\tif signal_zero_centered[x+1] > 0:\n\t\t\tpassed = (y for y in zero_crossings_diff if y < x)\n\t\t\tzcc.append(int(max(passed)))\n\t\t\t#zcc.append(int((max(passed)+x)/2))\n\t\tif signal_zero_centered[x+1] < 0:\n\t\t\tpassed = (y for y in zero_crossings_diff if y > x)\n\t\t\tzcc.append(int(min(passed)))\n\t\t\t#zcc.append(int((min(passed)+x)/2))\n\n\t#zcc = zero_crossings\n\tprint(\"zero_crossings:\t\t\t\" + str(len(zcc)))\n\n\n\n\tif debug0 == True:\n\t\tplt.plot(signal)\n\t\tplt.axhline(y=threshold, color='k', linestyle='-')\n\t\tthreshold_scatter = [threshold] * len(zcc)\n\t\tplt.scatter(zcc, threshold_scatter, color= 'red')\n\t\tplt.title('Raw Signal')\n\t\tplt.ylabel('Quantization')\n\t\tplt.xlabel('Sample Index')\n\t\tplt.show()\n\n\t##################\t##################\t##################\t##################\t##################\t##################\n\t##Ensinar a distinção aqui STEP 1 BEGINS\n\t##################\t##################\t##################\t##################\t##################\t##################\n\n\n\tcorrect_point = input(\"Correct Transition:\")\t\t\t#HALF TRANSITION\n\twrong_point = input(\"Wrong Transition:\")\n\n\t#correct_point = 99492\t\t\t#HALF TRANSITION\n\t#wrong_point = 67004\n\n\t#correct_point = 133584\t\t\t#HALF TRANSITION\n\t#wrong_point = 66930\n\n\tcorrect_index = zcc.index(correct_point)\n\twrong_index = zcc.index(wrong_point)\n\n\n\tif(step1 == True or step2 == True):\n\n\t\tpacket_fade = 0\n\n\t\tA = samples_per_symbol\t\t\t\t\t\t\t\t\t\t\t\t\t#number of samples expected in a symbol\n\t\tB = samples_per_symbol * packet_size + samples_between_packets\t \t#number of samples expected between equivalent points in consecutive packets\n\n\t\tmh = range((packet_size-1)*2+1)\n\t\tmatrix_height = [x-packet_size+1 for x in mh]\n\n\t\tml = range(packet_fade*2+1)\n\t\tmatrix_length = [x-packet_fade for x in ml]\n\n\n\t\t#criar a matriz de diferenças\n\n\t\t# The x travels in bit distance, the y travels in packet distance\n\t\tkey = [[ int((x*B) + (y*A)) for y in matrix_height] for x in matrix_length]\n\n\t\theatmap = [[[ 0 for y in mh] for x in ml] for z in range(len(zcc))]\n\t\theatmap_total = [[ 0 for y in mh] for x in ml]\n\t\tdata = ascii.write(key, format = 'fixed_width_no_header', delimiter = '||')\n\n\t##################\t##################\t##################\t##################\t##################\t##################\n\t# STEP 1 BEGINS\n\t##################\t##################\t##################\t##################\t##################\t##################\n\n\n\tif step1 == True:\n\n\t\tsurveil_range= 5\n\t\tcutoff = surveil_range * B + (A*packet_size)\n\t\tresolution = 128\n\t\tmargin = int(cutoff/(resolution*2)*4)\n\t\tprint('margin = ' + str(margin))\n\t\tnumber_of_bins = surveil_range * resolution\n\t\tall_bins = np.linspace(-cutoff, cutoff, number_of_bins)\n\n\t\tall_differences = []\n\t\tcorrect_point_differences = []\n\t\twrong_point_differences = []\n\t\tfor x in zcc:\n\t\t\tfor y in zcc:\n\t\t\t\tif abs(x-y) < cutoff:\n\t\t\t\t\tall_differences.append(y-x)\n\t\t\tdelta_correct = abs(zcc[correct_index]-x)\n\t\t\tdelta_wrong = abs(zcc[wrong_index]-x)\n\t\t\tif delta_correct < cutoff:\n\t\t\t\tcorrect_point_differences.append(zcc[correct_index]-x)\n\t\t\tif delta_wrong < cutoff:\n\t\t\t\twrong_point_differences.append(zcc[wrong_index]-x)\n\n\n\n\t\tp = np.digitize(all_differences, all_bins)\n\t\tall_binned = [0 for x in range(number_of_bins)]\n\t\tfor w in range(len(p)):\n\t\t\tall_binned[p[w]] +=1\n\n\n\t\tcount = 0\n\t\tv_lines = []\n\n\t\tlocal_maxima_index = (np.diff(np.sign(np.diff(all_binned))) < 0).nonzero()[0] + 1 # local max\n\n\t\ttopN = [all_binned[w] for w in local_maxima_index] \t#\t[VALUE OF LOCAL MAX, INDEX OF LOCAL MAX]\n\t\ttopN_index = [w for w in local_maxima_index]\t\t# has to be done this way to convert nparray to list\n\n\t\t#print(topN)\n\n\t\twhile len(topN)>surveil_range*2+1:\n\t\t\tminimum = topN.index((min(topN)))\n\t\t\ttopN.pop(minimum)\n\t\t\ttopN_index.pop(minimum)\n\n\n\t\tpeaks = [all_bins[w] for w in topN_index]\n\t\tpeaks_nz = peaks\n\t\tpeaks_nz.pop(int(len(peaks_nz)/2)) # same as peaks but without the indice that corresponds to the zero\n\n\t\ttrust = [0 for x in zcc]\n\t\tfor x in range(len(zcc)):\n\t\t\tfor y in peaks_nz:\n\t\t\t\ttemp = zcc[x] + y\n\t\t\t\tfor z in zcc:\n\t\t\t\t\tif abs(z-temp) < margin:\n\t\t\t\t\t\ttrust[x] += 1\n\n\t\tcompensation_range = packet_size*surveil_range\n\t\tfor x in range(len(trust[0:packet_size*surveil_range])):\n\t\t\ttrust[x] = int( trust[x] / min(1, ((compensation_range+x)/(compensation_range))))\n\n\n\t\tzcc2 = [x for x in zcc]\n\t\ttrust2 = [x for x in trust]\n\t\ttrust3 = [n/max(trust)*max(signal) for n in trust]\n\t\tcount = len(trust2) -1\n\t\tmaximum = max(trust2)\n\t\tcutoff_ratio = 0.25\n\t\tcutoff_line = maximum * cutoff_ratio\n\t\twhile count > 0:\n\t\t\tif trust2[count] < cutoff_line:\n\t\t\t\ttrust2.pop(count)\n\t\t\t\tzcc2.pop(count)\n\t\t\tcount -= 1\n\n\n\n\t\tif debug3 == True:\n\n\n\t\t\tall_differences= [i for i in all_differences if i != 0]\n\t\t\tz_all_differences = np.hstack(all_differences).tolist()\n\t\t\tz_correct_point_differences = np.hstack(correct_point_differences).tolist()\n\t\t\tz_wrong_point_differences = np.hstack(wrong_point_differences).tolist()\n\n\n\t\t\tplt.subplot(311)\n\t\t\tplt.hist(z_all_differences, bins=all_bins) \t\t\t\t \t# arguments are passed to np.histogram\n\t\t\tfor w in peaks:\n\t\t\t\tcenter = (w - int(cutoff/number_of_bins))\n\t\t\t\tplt.axvline(x=center, color='k', linestyle='-')\n\t\t\tplt.title('Histogram of all deltas of all points')\n\t\t\tplt.subplot(312)\n\t\t\tplt.title('All deltas of a correct transition')\n\t\t\tplt.ylim([0, 1])\n\t\t\tplt.hist(z_correct_point_differences, bins=all_bins) \t \t# arguments are passed to np.histogram\n\t\t\tfor w in peaks:\n\t\t\t\tcenter = (w - int(cutoff/number_of_bins))\n\t\t\t\tplt.axvspan(center-margin, center+margin, color='red', alpha=0.5)\n\t\t\tplt.subplot(313)\n\t\t\tplt.title('All deltas of a wrong transition')\n\t\t\tplt.ylim([0, 1])\n\t\t\tplt.hist(z_wrong_point_differences, bins=all_bins)\t\t \t# arguments are passed to np.histogram\n\t\t\tfor w in peaks:\n\t\t\t\tcenter = (w - int(cutoff/number_of_bins))\n\t\t\t\tplt.axvspan(center-margin, center+margin, color='red', alpha=0.5)\n\n\t\t\tplt.show()\n\n\tprint('\\n\\n\\n\\n\\n')\n\n\n\t##################\t##################\t##################\t##################\t##################\t##################\n\t# STEP 1 ENDS\n\t# STEP 2 BEGINS\n\t##################\t##################\t##################\t##################\t##################\t##################\n\n\tif step2 == True:\n\n\t\tallmargins = []\n\t\terror_margin = 5\n\t\taux = range(error_margin*2+1)\n\t\tpossible_errors = [x-error_margin for x in aux]\n\t\t#print(possible_errors)\n\n\t\tfor x in range(len(zcc2)):\n\t\t\t#print(x)\n\t\t\tc1 = 0\n\t\t\tc2 = len(zcc2)-1\n\t\t\twhile (zcc2[c1] < zcc2[x] + key[0][0]):\n\t\t\t\tc1 += 1\n\t\t\twhile (zcc2[c2] > zcc2[x] + key[-1][-1]):\n\t\t\t\tc2 -= 1\n\n\t\t\tpassed = zcc2[c1:c2]\n\t\t\t#passed = (y for y in zcc if (abs(y - zcc[x] < key[-1][-1]+error_margin)))\n\t\t\t#print(passed)\n\t\t\tfor a in ml:\n\t\t\t\tfor b in mh:\n\t\t\t\t\t#print(delta)\n\t\t\t\t\tsum = zcc2[x] + key[a][b]\n\t\t\t\t\tfor h in possible_errors:\n\t\t\t\t\t\tif sum+h in passed:\n\t\t\t\t\t\t\theatmap[x][a][b] = 1\n\n\t\t\theatmap[x][packet_fade][(packet_size-1)] = 'X'\n\n\t\t\thitsum2 = [0 for x in range(len(zcc2))]\n\t\t\tfor z in range(len(zcc2)):\n\t\t\t\theatmap_buffer = [[ heatmap[z][x][y] for y in mh] for x in ml]\n\t\t\t\tfor a in ml:\n\t\t\t\t\tfor b in mh:\n\t\t\t\t\t\tif type(heatmap_buffer[a][b]) == int :\n\t\t\t\t\t\t\theatmap_total[a][b] += heatmap_buffer[a][b]\n\t\t\t\t\t\t\thitsum2[z] += heatmap_buffer[a][b]\n\n\t\thitsum = [(u/max(hitsum2))*max(signal) for u in hitsum2]\n\n\t##################\t##################\t##################\t##################\t##################\t##################\n\n\tallindexes = []\n\tchosen_samples = []\n\tfor a in range(len(zcc2)-1):\n\t\tindex = int(zcc2[a] + round(samples_per_symbol*0.45))\n\t\twhile(index < (zcc2[a+1] - (samples_per_symbol*0.1))):\n\t\t\tallindexes.append(index)\n\t\t\tchosen_samples.append(signal_zero_centered[index])\n\t\t\tindex += round(samples_per_symbol)\n\n\t##################\t##################\t##################\t##################\t##################\t##################\n\n\n\tif debug1 == True:\n\t\tsignal_samples = []\n\t\tfor x in range(len(allindexes)):\n\t\t\tsignal_samples.append(signal[allindexes[x]])\n\t\t#pylab.subplot(211)\n\n\t\t#plt.scatter(zcc2, hitsum , color='red')\n\t\t#plt.scatter(zcc, trust3 , color='red')\n\t\t#plt.plot(signal)\n\t\t#plt.title('Trust levels of transitions')\n\n\t\t#for x in range(len(zcc)):\n\t\t\t#line = zcc[x] + 7790\n\t\t#plt.axvline(x=105797, color='red', linestyle='-')\n\n\n\t\t#pylab.plot(diff_signal1)\t\t\t\t\t\t\t\t\t\t\t# signal'\n\n\t\t#plt.axhline(y=threshold, color='k', linestyle='-')\n\t\t#plt.axhline(y=0, color='k', linestyle='-')\n\t\t#plt.scatter(allindexes, signal_samples, color='orange')\t\t\t# AMOSTRAS COLHIDAS\n\t\t#threshold_scatter = [threshold] * len(zcc2)\n\t\t#threshold_scatter_diff = [threshold] * len(zero_crossings_diff)\n\t\t#plt.scatter(zero_crossings_diff, threshold_scatter_diff , color='black')\n\n\n\t\t#plt.subplot(212)\n\t\tthreshold_scatter = [threshold] * len(zcc2)\n\t\tplt.scatter(zcc2, hitsum, color='red')\n\t\tplt.plot(signal)\n\t\tplt.title('Transition pattern search')\n\t\tfor y in matrix_height:\n\t\t\tfor x in matrix_length:\n\t\t\t\tplt.axvline(x=correct_point, color='red', linestyle='-')\n\t\t\t\tplt.axvline(x=key[x][y]+correct_point+error_margin, color='green', linestyle='--')\n\t\t\t\tplt.axvline(x=key[x][y]+correct_point-error_margin, color='green', linestyle='--')\n\t\t#plt.ylim([0, 100])\n\n\t\t#ax = plt.gca()\n\t\t#ax.yaxis.grid(True)\n\t\t#fft_signal = np.fft(signal)\n\t\t#pylab.plot(fft_signal)\n\n\t\t#plt.subplot(313)\n\t\t#plt.scatter(zcc2, hitsum)\n\t\t#ax = plt.gca()\n\t\t#ax.yaxis.grid(True)\n\n\t\tpylab.show()\n\n\n\tresult = np.where(np.asarray(chosen_samples) > 0, 1, 0)\n\n\treturn result\n","sub_path":"PBZS_comparator.py","file_name":"PBZS_comparator.py","file_ext":"py","file_size_in_byte":10671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"607083687","text":"# 题目:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。\n# 如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。\n# 思路:根据后序遍历,尾元素一定是根节点\n# 再根据二叉搜索树的性质:左子节点的元素一定小于根节点,右子节点的元素一定大于根节点\n# 递归比较左右子树书否符合此特性\n\n\nclass TreeNode(object):\n def __init__(self, data):\n self.val = data\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def VerifySquenceOfBST(self, sequence):\n if not sequence:\n return False\n\n root = sequence[-1]\n\n if min(sequence) > root or max(sequence) < root:\n return False\n\n index = 0\n\n for i in range(len(sequence) - 1):\n index = i\n if sequence[i] > root:\n break\n\n for j in range(index + 1, len(sequence) - 1):\n if sequence[j] < root:\n return False\n\n # 递归检查左子树是否是二叉搜索树\n left = True\n if index > 0:\n left = self.VerifySquenceOfBST(sequence[:index])\n\n # 递归检查右子树是否是二叉搜索树\n right = True\n if index < len(sequence) - 1:\n right = self.VerifySquenceOfBST(sequence[index: len(sequence) - 1])\n return left and right\n\n\narray = [5, 7, 6, 9, 11, 10, 8]\narray2 = [4, 6, 7, 5]\narray3 = [1, 2, 3, 4, 5]\nS = Solution()\nprint(S.VerifySquenceOfBST(array))\nprint(S.VerifySquenceOfBST(array2))\nprint(S.VerifySquenceOfBST(array3))\n","sub_path":"33_01二叉搜索树的后序遍历序列.py","file_name":"33_01二叉搜索树的后序遍历序列.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"27243988","text":"# S = 1/1 + 3/2 + 5/4 ... 99/50\npar = 1\nimpar = 0\nfor c in range(1, 100):\n if c % 2 == 0:\n par += c\n else:\n impar += c\ntotal = impar / par\nprint(f'A valor de S é igual a {total}')","sub_path":"Aula 6/31 calcular o valor de s.py","file_name":"31 calcular o valor de s.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"164097032","text":"from paraview.simple import *\nparaview.simple._DisableFirstRenderCameraReset()\n\nAges003_vtk = LegacyVTKReader( FileNames=['/home/imalkov/DropboxUni2015/M.s/Research/DATA/SESSION_TREE/NODE02/Session1B/VTK/Ages003.vtk'] )\n\nRenderView1 = GetRenderView()\na1_ExhumationRate_PVLookupTable = GetLookupTableForArray( \"ExhumationRate\", 1 )\n\nDataRepresentation2 = Show()\nDataRepresentation2.EdgeColor = [0.0, 0.0, 0.5000076295109483]\nDataRepresentation2.SelectionPointFieldDataArrayName = 'ExhumationRate'\nDataRepresentation2.ScalarOpacityFunction = []\nDataRepresentation2.ColorArrayName = ('POINT_DATA', 'ExhumationRate')\nDataRepresentation2.ScalarOpacityUnitDistance = 1.495838960900772\nDataRepresentation2.LookupTable = a1_ExhumationRate_PVLookupTable\nDataRepresentation2.ScaleFactor = 6.000162124633789\n\nPlotOnIntersectionCurves1 = PlotOnIntersectionCurves( SliceType=\"Plane\" )\n\nRenderView1.CameraClippingRange = [123.5457148353541, 138.47412023773984]\n\nPlotOnIntersectionCurves1.SliceType.Origin = [15.01878547668457, 30.000810623168945, 32.597999572753906]\n\nactive_objects.source.SMProxy.InvokeEvent('UserEvent', 'ShowWidget')\n\n\nXYChartView1 = CreateXYPlotView()\n\nactive_objects.source.SMProxy.InvokeEvent('UserEvent', 'HideWidget')\n\n\nAnimationScene1 = GetAnimationScene()\nDataRepresentation3 = Show()\nDataRepresentation3.XArrayName = 'arc_length'\nDataRepresentation3.SeriesVisibility = ['Points (0)', '0', 'Points (1)', '0', 'Points (2)', '0', 'Points (Magnitude)', '0', 'arc_length', '0', 'vtkOriginalIndices', '0']\nDataRepresentation3.UseIndexForXAxis = 0\n\nXYChartView1.BottomAxisRange = [0.0, 80.0]\nXYChartView1.TopAxisRange = [0.0, 6.66]\nXYChartView1.ViewTime = 0.0\nXYChartView1.LeftAxisRange = [-5.0, 65.0]\nXYChartView1.RightAxisRange = [0.0, 6.66]\n\nAnimationScene1.ViewModules = [ RenderView1, XYChartView1 ]\n\nDelete(XYChartView1)\nDelete(DataRepresentation3)\nAnimationScene1.ViewModules = RenderView1\n\nactive_objects.source.SMProxy.InvokeEvent('UserEvent', 'ShowWidget')\n\n\nSetActiveView(RenderView1)\nDataRepresentation4 = Show()\nDataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483]\nDataRepresentation4.SelectionPointFieldDataArrayName = 'ApatiteFTAge'\nDataRepresentation4.ColorArrayName = ('POINT_DATA', 'ExhumationRate')\nDataRepresentation4.LookupTable = a1_ExhumationRate_PVLookupTable\nDataRepresentation4.ScaleFactor = 6.000162124633789\n\nRenderView1.CameraClippingRange = [122.17747501296641, 140.19645443192317]\n\nRender()\n","sub_path":"examples/paraviewexamples/example02.py","file_name":"example02.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"101407639","text":"# encoding: utf-8\nimport pyxel\npyxel.init(160, 120, caption=\"Pong\")\n\n\n# ---- labda -----\n\nlabdax = 30\nlabday = 40\n# sebessége\nsebx = 1\nseby = 1\n\ndef labda_update():\n global labdax, labday, sebx, seby\n # ütközés\n if labdax > 160 - 6: sebx = -sebx\n if labday > 120 - 6: seby = -seby\n if labdax < 6:\n # ***** itt hívjuk meg a függvényt *****\n if uton_van(labday):\n sebx = -sebx\n if labday < 6: seby = -seby\n\n # labda mozgatása\n labdax = labdax + sebx\n labday = labday + seby\n\ndef labda_draw():\n pyxel.circ(labdax, labday, 4, 8)\n\n\n# ----- ütő -----\nutoy = 60\ndef uto_update():\n global utoy\n if pyxel.btn(pyxel.KEY_W):\n utoy = utoy - 1\n if pyxel.btn(pyxel.KEY_S):\n utoy = utoy + 1\ndef uto_draw():\n pyxel.rect(0, utoy - 20/2, 3, 20, 9)\n\n# ***** itt van az új függvényünk *****\ndef uton_van(y):\n return utoy-20/2 < y < utoy+20/2\n\n\n\ndef update():\n labda_update()\n uto_update()\n\ndef draw():\n pyxel.cls(0)\n labda_draw()\n uto_draw()\n\n\npyxel.run(update, draw)\n","sub_path":"22_utkozes_megoldas.py","file_name":"22_utkozes_megoldas.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"83382097","text":"#!/usr/bin/env python \nimport rospy\n\n#from client.srv import motorCommand\n#from client.msg import sensorValue\nfrom hci.msg import sensorValue\nfrom hci.srv import motorCommand\n\n\nnode_name = 'robotInterface'\nmotorCommandTopic = 'motorCommand'\nsensorValueTopic = 'sensorValue'\n\nmotorCommandPub = None\n\nsensorValueMap = {\n\t(0,0),\n\t(1,0),\n\t(2,0),\n\t(3,0),\n\t(4,0),\n\t(5,0),\n\t(6,0),\n\t(7,0),\n\t(8,0),\n\t(9,0),\n\t(10,0),\n\t(11,0),\n\t(12,0),\n\t(13,0),\n\t(14,0),\n\t(15,0),\n\t(16,0),\n\t(17,0),\n\t(18,0),\n\t(19,0),\n\t(20,0),\n\t(21,0),\n\t(22,0),\n\t(23,0),\n\t(24,0),\n\t(25,0),\n\t(26,0),\n\t(27,0),\n\t(28,0),\n\t(29,0),\n\t(30,0),\n\t(31,0),\n\t(32,0)\n}\n\n\ndef sendMotorCommand(motorID, value):\n\ttry:\n\t\tresp = motorCommandPub(motorID,value)\n\texcept rospy.ServiceException as exc:\n\t\tprint(\"motor command service didn't process request: \" + str(exc))\n\treturn resp.success\n\ndef sensorValueCallback(data):\n\trospy.loginfo(\"Sensor %u has value %f\", data.sensorID, data.value)\n\tsensorValueMap[data.sensorID] = data.value;\n\ndef getSensorValue(sensorID):\n\treturn sensorValueMap(sensorID);\n\ndef initializeRobotInterface():\n\trospy.init_node(node_name,disable_signals=True)\n\n\trospy.wait_for_service(motorCommandTopic)\n\tmotorCommandPub = rospy.ServiceProxy(motorCommandTopic, motorCommand, persistent=True)\n\n\trospy.Subscriber(sensorValueTopic,sensorValue,sensorValueCallback)\n\trospy.spin()\n","sub_path":"client/scripts/robotInterface.py","file_name":"robotInterface.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"638540497","text":"# MIT License\n#\n# Copyright (c) 2017 Tom Runia\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to conditions.\n#\n# Author: Deep Learning Course | Fall 2018\n# Date Created: 2018-09-04\n################################################################################\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.distributions as dist\n\n\nclass TextGenerationModel(nn.Module):\n\n def __init__(self, batch_size, seq_length, vocabulary_size,\n lstm_num_hidden=256, lstm_num_layers=2, device='cuda:0',\n dropout_keep_prob=1):\n super(TextGenerationModel, self).__init__()\n # Initialization here...\n self.device = device\n self.vocabulary_size = vocabulary_size\n self.batch_size = batch_size\n self.seq_length = seq_length\n\n self.lstm = nn.LSTM(vocabulary_size, lstm_num_hidden, lstm_num_layers,\n dropout=dropout_keep_prob)\n\n self.linear = nn.Linear(lstm_num_hidden, vocabulary_size)\n\n def forward(self, x):\n # Implementation here...\n out, _ = self.lstm(x)\n\n out = self.linear(out)\n\n return out\n\n def sample(self, random=False, temperature=0.5):\n \"\"\"\n Generate a sample.\n \"\"\"\n self.eval()\n\n indices = torch.LongTensor(self.batch_size,1).random_(\n 0, self.vocabulary_size).to(self.device)\n\n x = torch.zeros(self.batch_size, self.vocabulary_size).to(self.device)\n x.scatter_(1, indices, 1)\n x = x.unsqueeze(0)\n\n output = [x]\n\n x, (h, c) = self.lstm(x)\n x = self.linear(x)\n\n output.append(x)\n\n for i in range(self.seq_length - 2):\n x, (h, c) = self.lstm(x, (h, c))\n x = self.linear(x)\n\n if random:\n # Apply temperature.\n x = x / temperature\n\n x = F.softmax(x, -1) \n\n distribution = dist.Categorical(x)\n indices = distribution.sample().t()\n else:\n indices = x.argmax(-1).t()\n\n # Reshape into one-hot vectors.\n x.zero_().squeeze_()\n x.scatter_(1, indices, 1).unsqueeze_(0)\n output.append(x)\n\n out = torch.stack(output).squeeze()\n\n self.train()\n\n return out\n","sub_path":"assignment_2/part2/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"64010920","text":"from experiments import utils\nfrom keras.layers import Conv1D, MaxPool1D, Dense, Flatten, Activation, Dropout, BatchNormalization, Lambda, AveragePooling1D, UpSampling1D\nimport numpy as np\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom keras.models import Sequential, Model\nfrom keras.optimizers import sgd, nadam, adam, rmsprop, adadelta, adagrad\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nfrom preprocessing import processing_util as util\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt\nfrom keras.utils.vis_utils import plot_model\nimport os\nos.environ[\"PATH\"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin'\n\n\ndef mlp(x_train, y_train):\n y_train = utils.to_categorical(y_train)\n nb_features = x_train.shape[1]\n nb_classes = y_train.shape[1]\n para = {\n 'model_name': 'mlp_basic_',\n 'size_of_batch': 1000,\n 'nb_epoch': 1000,\n 'drop_rate': 0.\n }\n # model\n early_stop = EarlyStopping(monitor='val_loss', min_delta=0, patience=100, verbose=1, mode='auto')\n callbacks_list = [early_stop]\n\n model = Sequential(name=para['model_name'])\n model.add(Dense(50, input_dim=nb_features, activation='relu'))\n model.add(Dense(25, activation='relu'))\n # model.add(Dropout(para['drop_rate']))\n model.add(Dense(units=nb_classes))\n model.add(Activation('softmax'))\n # print(model.summary())\n\n model.compile(loss='categorical_crossentropy',\n optimizer=sgd(),\n metrics=['categorical_accuracy'])\n\n history = model.fit(x_train, y_train,\n batch_size=para['size_of_batch'],\n epochs=para['nb_epoch'],\n shuffle=True,\n validation_split=0.33,\n callbacks=callbacks_list)\n\n return history, model\n\n\nif __name__ == '__main__':\n seed = 8\n np.random.seed(seed)\n # load data\n fn = 'wholeset_Jim_nomissing_withIDs.csv'\n read_file_path = util.get_file_path(fn)\n df = pd.read_csv(read_file_path, encoding='utf8')\n # make y data\n y_data = df['MRS_3']\n # make x data\n df = df.drop(['MRS_3'], axis=1)\n x_data = df\n # make train and test\n x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3, shuffle=True)\n train_IDs = x_train[['ICASE_ID', 'IDCASE_ID']]\n x_train = x_train.drop(['ICASE_ID', 'IDCASE_ID'], axis=1)\n test_IDs = x_test[['ICASE_ID', 'IDCASE_ID']]\n x_test = x_test.drop(['ICASE_ID', 'IDCASE_ID'], axis=1)\n # model\n history, model = mlp(utils.scale(x_train), y_train)\n # plot_model(model, to_file='mlp.png', show_shapes=True, show_layer_names=True)\n\n utils.plot_acc_loss_for_multi(history)\n # Testing\n test_IDs['label'] = y_test\n y_test = utils.to_categorical(y_test)\n loss, acc = model.evaluate(utils.scale(x_test), y_test, verbose=0)\n y_predict = model.predict(utils.scale(x_test))\n y_pred = np.argmax(y_predict, axis=1).astype('str')\n test_IDs['predict'] = y_pred\n print('Test loss:', loss)\n print('Test accuracy:', acc)\n np.savetxt('mlp_predic.csv', test_IDs, delimiter=',', fmt='%s')\n\n\n\n # for inx, val in y_test.iteritems():\n # print(inx)\n # print(val)\n aa = str(y_test)\n bb = str(y_pred)\n C = confusion_matrix(np.argmax(y_test, axis=1).astype('str'),\n np.argmax(y_predict, axis=1).astype('str')\n )\n print(C)\n plt.figure()\n utils.plot_confusion_matrix(C, classes=['0', '1', '2', '3', '4', '5', '6'])\n utils.performance_cal(C)","sub_path":"three_month/preprocessing/mlp_kara.py","file_name":"mlp_kara.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"567858176","text":"''' File: hw3_part3.py \n Author: Skye Ortiz \n Date: 09/27/2016 \n Section: 26 \n E-mail: sortiz1@umbc.edu \n Description: This program tells the user what the state of\n water is at a certain temperature on the temperature scale.\n Collaboration: I did not collaborate with anyone on this assignment.\n'''\ndef main():\n temperature = float(input(\"Please enter the temperature\"))\n degrees = input(\"Please enter \\\"C\\\" for Celcius or \\\"K\\\" for Kelvin.\")\n\n if degrees == \"C\":\n if temperature <= 0:\n print(\"Water is a solid at that temperature.\")\n elif temperature >= 100:\n print(\"Water is a gas at that temperature.\")\n else:\n print(\"Water is liquid at that temperature.\")\n else:\n if temperature <= 273.2:\n print(\"Water is a solid at that temperature.\")\n elif temperature >= 373.2:\n print(\"Water is a gas at that temperature.\")\n else:\n print(\"Water is liquid at that temperature.\")\n\nmain() \n","sub_path":"data/HW3/hw3_431.py","file_name":"hw3_431.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"216875894","text":"#coding: utf8\nimport numpy as np\nimport math\nclass Axe: # un axe avec des ticks et des valeurs définies en ces ticks\n def __init__(self,nom,unit,mini,maxi,nb,valeurs):\n self.nom=nom # nom de l'axe\n self.unit=unit # unité\n self.mini=mini # tick gauche de l'axe (valtick[0])\n self.maxi=maxi # tick droite de l'axe (vlatick[nb-1]\n self.nb=nb # nombre de ticks sur l'axe\n if self.nb<2:\n raise Exception(\"Axe: le nombre de ticks de l'axe %s doit être supérieur ou égal à 2\" % self.nb)\n self.valtick=np.linspace(mini,maxi,nb, float) # liste des nb ticks de l'axe numérotés de 0 à nb-1\n self.valeurs=valeurs # liste des nb valeurs attachées à chaque ticks de l'axe\n if (len(self.valeurs)!=nb):\n raise Exception (\"Axe: le nombre de valeurs attachées à l'axe : %s est déférent du nombre de ticks de l' axe : %s\" %(len(self.valeurs),self.nb))\n def isInside (self,x): # test si \"x\" est dans les limites de l'axe\n return ((self.mini<=x<=self.maxi) or (-self.mini<=-x<=-self.maxi))\n def interval(self,x): # retourne le premier ticks de l'axes inférieur à la valeur \"x\"\n if self.isInside(x):\n if x==self.maxi:\n n=self.nb-2\n else:\n n=int((x-self.mini)/(self.maxi-self.mini)*(self.nb-1))\n return (n,(x-self.valtick[n])/(self.valtick[n+1]-self.valtick[n]))\n else:\n raise Exception(\"Axe.interval(x) : La valeur x=%s n'est pas dans les limites de l'axe qui sont : [ %s , %s ]\" %(x, self.mini, self.maxi))\n def val (self,x): # renvoie la valeur attachée à la position \"x\" sur l'axe, par interpollation linéaire des valeurs des deux ticks encadrant x\n (ninf,prop)=self.interval(x)\n return (self.valeurs[ninf]+(prop*(self.valeurs[ninf+1]-self.valeurs[ninf])))\n\"\"\" \nnb=2801\nvaleurs=np.arange(nb)\n#valeurs=np.sin(np.arange(nb)/float(nb-1)*math.pi/2.)\naxe=Axe(\"longi\",\"degrés\",-12,16.,nb,valeurs)\nprint axe.valtick\nprint axe.valeurs\nprint axe.isInside(5.)\nprint axe.interval(5.1)\nprint axe.interval(4.59)\nprint axe.interval(2.2342)\nprint axe.interval(0.0)\nprint axe.interval(10.0)\nprint axe.interval(9.99)\nprint axe.val(9.99)\nprint axe.val(12.4555959)\nprint axe.val(9.999999999999999)\nprint axe.val(-12)\nprint axe.val(2)\nprint axe.val(16)\n\n\"\"\"","sub_path":"Axe.py","file_name":"Axe.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"410425617","text":"from clients import GoogleAdminClient, GoogleDriveClient\nfrom external import csv_utils\nfrom datetime import datetime\nimport logging\nimport sys\nimport json\nimport time\nfrom logging import Handler\n\nlogger = logging.getLogger(__name__)\n\ndef _dt_fmt(dt):\n if not isinstance(dt, datetime):\n return dt\n return dt.strftime(\"%Y-%m-%d\")\n\n\ndef enable_stdout_logging():\n \"\"\"\n Invoke this prior to starting report to enable stdout logging.\n \"\"\"\n root = logging.getLogger()\n root.setLevel(logging.DEBUG)\n\n handler = logging.StreamHandler(sys.stdout)\n handler.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n root.addHandler(handler)\n\n\nclass GoogleDriveAuditReport(object):\n \"\"\"\n Reporting utility that generates a local spreadsheet of GDrive files and permissions.\n Usage is simple but the utility can take a while to run, see example usage below:\n \"\"\"\n\n def __init__(self, credentials, admin_user, audit_users=True, audit_team_drives=False):\n self.should_audit_users = audit_users\n self.should_audit_drives = audit_team_drives\n\n if not isinstance(credentials, basestring):\n raise ValueError(\"'credentials' must be a json formatted credential string, \"\n \"or a filename pointing to a json formatted credential string.\")\n\n try:\n credentials = json.loads(credentials)\n except:\n # This is probably a filename and not a json formatted string.\n # Error will be raised if it is not a valid file path.\n f = open(credentials, \"rb\")\n credentials = f.read().decode('utf-8')\n f.close()\n\n if not admin_user:\n raise ValueError('admin_user must be supplied (Google email address of user with administrative rights.')\n\n self.credentials = credentials\n self.user_files = dict()\n self.team_drive_files = dict()\n self.admin_user = admin_user\n\n # By default .git folders are ignored.\n # To add exclusion folders, set this property before starting the report.\n self.exclude_folders_named = [\".git\"]\n\n def start(self, output_file_name=None):\n \"\"\"\n Start generating the report.\n :return:\n \"\"\"\n self.audit_users()\n self.audit_team_drives()\n\n if self.should_audit_users:\n self.export_user_drive_report(output_file_name)\n\n if self.should_audit_drives:\n self.export_team_drive_report()\n\n def audit_team_drives(self):\n \"\"\"\n Audit all files found within team drives.\n Team drives audit is untested - we don't have an team drive enabled account to test on.\n :return:\n \"\"\"\n if not self.should_audit_drives:\n logger.info(\"Skipping audit of team drives.\")\n return\n\n logger.info(\"Beginning google drive audit of team drives.\")\n drive_client = GoogleDriveClient(self.credentials)\n folders = drive_client.team_drives()\n for folder in folders:\n files = None\n try:\n files = drive_client.walk_tree(folder_id=folder.id,\n path=folder.name,\n max_depth=30,\n my_folders_only=False,\n exclude_folders_named=self.exclude_folders_named)\n if not files:\n logger.info(\"No files found in team drive %s.\", folder.name)\n\n self.team_drive_files[folder.name] = files\n logger.info(\"Completed audit of team drive %s. %i files found.\", folder.name, len(files))\n except:\n logger.exception(\"Error occurred querying drive files for team drive %s.\", folder.name)\n\n drive_client.close()\n\n def audit_users(self):\n \"\"\"\n Audit all files found in user drives.\n :return:\n \"\"\"\n if not self.should_audit_users:\n logger.info(\"Skipping audit of user drives.\")\n return\n\n logger.info(\"Beginning google drive audit of user drives.\")\n users = self.get_users()\n\n if not users:\n return\n\n for user in users:\n if not user.primaryEmail:\n continue\n files = self.list_user_drive(user)\n if not files:\n logger.info(\"No files found in user drive %s.\", user.primaryEmail)\n continue\n\n logger.info(\"Completed audit of user drive %s. %i files found.\", user.primaryEmail, len(files))\n self.user_files[user.primaryEmail] = files\n\n def list_user_drive(self, user):\n \"\"\"\n Connect as the specified user and get report on all files.\n \"\"\"\n drive_client = None\n files = None\n try:\n drive_client = GoogleDriveClient(self.credentials,\n connect_as=user.primaryEmail)\n files = drive_client.walk_tree(exclude_folders_named=self.exclude_folders_named)\n\n except:\n logger.exception(\"Error occurred querying drive files for user %s.\", user.primaryEmail)\n\n finally:\n if drive_client:\n drive_client.close()\n return files\n\n def get_users(self):\n \"\"\"\n Call the admin api and get a list of all user objects.\n :return:\n \"\"\"\n admin_client = None\n users = None\n try:\n admin_client = GoogleAdminClient(self.credentials, connect_as=self.admin_user)\n users = admin_client.all_users()\n except:\n logger.exception(\"Error occurred querying google users.\")\n finally:\n if admin_client:\n admin_client.close()\n return users\n\n def export_user_drive_report(self, output_file_name=None):\n \"\"\"\n Export a csv file of the user drive permission report.\n :return:\n \"\"\"\n if not self.user_files:\n return None\n\n rows = []\n for email, file_data in self.user_files.iteritems():\n for path, f in file_data:\n row = {\"User Drive\": email, \"path\": path, \"name\": f.name, \"mimeType\": f.mimeType,\n \"trashed\": f.trashed, \"webViewLink\": f.webViewLink,\n \"createdTime\": _dt_fmt(f.createdTime), \"modifiedTime\": _dt_fmt(f.modifiedTime),\n \"owners\": self.file_owners(f),\n \"lastModifyingUser\": self.file_last_modified_by(f), \"shared\": f.shared,\n \"viewersCanCopy\": f.viewersCanCopyContent,\n \"usersAndGroups\": self.user_permission_string(f.permissions),\n \"domains\": self.domain_permission_string(f.permissions),\n \"anyone\": self.anyone_permission_string(f.permissions)\n }\n rows.append(row)\n\n out = csv_utils.records_to_string(rows)\n if not output_file_name:\n timestamp = time.mktime(datetime.now().timetuple())\n output_file_name = \"user_permission_report_%i.csv\" % timestamp\n\n logger.info(\"Writing user drive permissions report to '%s.'\" % output_file_name)\n f = open(output_file_name, \"wb\")\n f.write(out.encode('utf-8'))\n f.close()\n logger.info(\"Finished.\")\n\n @staticmethod\n def file_owners(file_obj):\n if not file_obj.owners:\n return \"\"\n owner_emails = [o.emailAddress for o in file_obj.owners if isinstance(o.emailAddress, basestring)]\n return \",\".join(owner_emails)\n\n @staticmethod\n def file_last_modified_by(file_obj):\n if not file_obj.lastModifyingUser:\n return None\n return file_obj.lastModifyingUser.emailAddress\n\n @staticmethod\n def user_permission_string(permissions):\n if not permissions:\n return \"\"\n user_permissions = (p for p in permissions if p.type in {'user', 'group'} and not p.deleted)\n return \",\".join(\"{}:{}:{}\".format(p.type, p.emailAddress, p.role)\n for p in user_permissions)\n\n @staticmethod\n def domain_permission_string(permissions):\n if not permissions:\n return \"\"\n domain_permissions = (p for p in permissions if p.type == 'domain' and not p.deleted)\n return \",\".join(\"{}:{}:D({})\".format(p.domain, p.role, p.allowFileDiscovery)\n for p in domain_permissions)\n\n @staticmethod\n def anyone_permission_string(permissions):\n if not permissions:\n return \"\"\n public_permissions = (p for p in permissions if p.type == 'anyone' and not p.deleted)\n return \",\".join(\"{}:D({})\".format(p.role, p.allowFileDiscovery)\n for p in public_permissions)\n\n def export_team_drive_report(self):\n \"\"\"\n Not yet implemented.\n \"\"\"\n logger.error(\"The team drive audit export has not yet been implemented.\")\n","sub_path":"audit.py","file_name":"audit.py","file_ext":"py","file_size_in_byte":9143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"91812768","text":"from django.urls import path\nfrom django.shortcuts import render\nfrom Employer import views\nurlpatterns=[\n path(\"home\",views.EmployerTotalJobApply.as_view(),name=\"Ehome\"),\n path(\"profile/create\",views.EmployerCreateProfileView.as_view(),name=\"EProfileCreate\"),\n path(\"profile/view\",views.EmployerProfileDetailView.as_view(),name=\"EProfileDetail\"),\n path(\"profile/change/\",views.EmployerProfileEditView.as_view(),name=\"EProfileEdit\"),\n path(\"jobpost/create\",views.EmployerJobPostView.as_view(),name=\"EJobPostCreate\"),\n path(\"jobpost/list\",views.EmployerJobDetailView.as_view(),name=\"EJobPostList\")\n]","sub_path":"JobPortal/Employer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"122605903","text":"__author__ = 'jblowe'\n\nimport os\nimport re\nimport time\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, render_to_response\n\nfrom search.utils import doSearch, setConstants, loginfo\nfrom common import cspace # we use the config file reading function\nfrom cspace_django_site import settings\nfrom os import path\n\nconfig = cspace.getConfig(path.join(settings.BASE_PARENT_DIR, 'config'), 'imaginator')\n\nMAXMARKERS = int(config.get('imaginator', 'MAXMARKERS'))\nMAXRESULTS = int(config.get('imaginator', 'MAXRESULTS'))\nMAXLONGRESULTS = int(config.get('imaginator', 'MAXLONGRESULTS'))\nIMAGESERVER = config.get('imaginator', 'IMAGESERVER')\nCSPACESERVER = config.get('imaginator', 'CSPACESERVER')\nSOLRSERVER = config.get('imaginator', 'SOLRSERVER')\nSOLRCORE = config.get('imaginator', 'SOLRCORE')\nTITLE = config.get('imaginator', 'TITLE')\nINSTITUTION = config.get('imaginator', 'INSTITUTION')\nSUGGESTIONS = config.get('imaginator', 'SUGGESTIONS')\nLAYOUT = config.get('imaginator', 'LAYOUT')\n\n\n#@login_required()\ndef index(request):\n\n context = setConstants({})\n\n # http://blog.mobileesp.com/\n # the middleware must be installed for the following to work...\n if request.is_phone:\n context['device'] = 'phone'\n elif request.is_tablet:\n context['device'] = 'tablet'\n else:\n context['device'] = 'other'\n\n if request.method == 'GET' and request.GET != {}:\n context['searchValues'] = request.GET\n\n if 'text' in request.GET:\n context['text'] = request.GET['text']\n if 'musno' in request.GET:\n context['musno'] = request.GET['musno']\n context['maxresults'] = 1\n if 'submit' in request.GET:\n context['maxresults'] = MAXRESULTS\n if \"Metadata\" in request.GET['submit']:\n context['resultType'] = 'metadata'\n context['displayType'] = 'full'\n elif \"Images\" in request.GET['submit']:\n context['resultType'] = 'images'\n context['pixonly'] = 'true'\n context['displayType'] = 'grid'\n elif \"Lucky\" in request.GET['submit']:\n context['resultType'] = 'metadata'\n context['maxresults'] = 1\n else:\n context['resultType'] = 'metadata'\n context['title'] = TITLE\n\n # do search\n loginfo('start search', context, request)\n context = doSearch(context)\n\n return render(request, 'imagineImages.html', context)\n\n else:\n \n return render(request, 'imagineImages.html', context)\n","sub_path":"imaginator/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"591399248","text":"import pickle\nimport os\nimport argparse\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom print_confidence_accuracy import estimator_name\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('name', type=str)\nparser.add_argument('--acquisition', '-a', type=str, default='bald')\nargs = parser.parse_args()\nargs.repeats = {'mnist': 3, 'cifar': 3, 'imagenet': 1}[args.name]\n\n\ndef process_file(file_name, count_conf, args, methods):\n\n with open(file_name, 'rb') as f:\n record = pickle.load(f)\n\n if args.acquisition == 'bald':\n process_file_bald(record, count_conf, args, methods)\n return\n\n bins = np.concatenate((np.arange(0, 1, 0.1), [0.98, 0.99, 0.999]))\n for estimator in methods:\n if estimator not in record['uncertainties'].keys():\n continue\n ue = record['uncertainties'][estimator]\n\n print(estimator)\n print(min(ue), max(ue))\n if args.acquisition == 'bald':\n ue = ue / max(ue)\n\n for confidence_level in bins:\n point_confidences = 1 - ue\n level_count = np.sum(point_confidences > confidence_level)\n count_conf.append((confidence_level, level_count, estimator_name(estimator)))\n\n\ndef process_file_bald(record, count_conf, args, methods):\n # bins = np.concatenate((np.arange(0, 1, 0.1), [0.98, 0.99, 0.999]))\n\n max_ue = {\n 'mnist': 1.4, 'cifar': 1, 'imagenet': 1.1\n }[args.name]\n\n bins = np.concatenate(([0, 0.02, 0.04, 0.06], np.arange(0.1, max_ue, 0.02)))\n\n for estimator in methods:\n if estimator not in record['uncertainties'].keys():\n continue\n ue = record['uncertainties'][estimator]\n\n print(estimator)\n if args.acquisition == 'bald':\n ue = ue / max(ue)\n\n for ue_level in bins:\n level_count = np.sum(ue < ue_level)\n count_conf.append((ue_level, level_count, estimator_name(estimator)))\n\n\ncount_conf = []\n\nfor i in range(args.repeats):\n file_name = f'logs/classification/{args.name}_{i}/ue_ood_{args.acquisition}.pickle'\n if args.acquisition == 'max_prob':\n methods = ['mc_dropout', 'ht_dpp', 'cov_k_dpp', 'cov_dpp', 'ht_k_dpp', 'max_prob']\n else:\n methods = ['mc_dropout', 'ht_dpp', 'cov_k_dpp', 'cov_dpp', 'ht_k_dpp']\n\n\n process_file(file_name, count_conf, args, methods)\n\n if args.acquisition == 'max_prob':\n ensemble_method = f\"ensemble_{args.acquisition}\"\n file_name = f'logs/classification/{args.name}_{i}/ue_ensemble_ood.pickle'\n if os.path.exists(file_name):\n process_file(file_name, count_conf, args, [ensemble_method])\n\n\n\nif args.acquisition == 'bald':\n metric = 'UE'\nelse:\n metric = 'Confidence'\n\nplt.rcParams.update({'font.size': 13})\nplt.rc('grid', linestyle=\"--\")\nplt.figure(figsize=(7, 5))\nplt.title(f\"{metric}-count for OOD {args.name} {args.acquisition}\")\ndf = pd.DataFrame(count_conf, columns=[f'{metric} level', 'Count', 'Estimator'])\nsns.lineplot(f'{metric} level', 'Count', data=df, hue='Estimator')\nplt.subplots_adjust(left=0.15)\n# plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\nsign = '<' if args.acquisition == 'bald' else '>'\nplt.ylabel(rf\"Number of samples, {metric} {sign} $\\tau$\")\nplt.xlabel(rf\"$\\tau$\")\nplt.grid()\nplt.savefig(f\"data/conf_ood_{args.name}_{args.acquisition}\", dpi=150)\nplt.show()\n\n","sub_path":"experiments/print_ood.py","file_name":"print_ood.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"28417652","text":"from sqlalchemy import (\n Column,\n Index,\n Integer,\n Text,\n )\n\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom sqlalchemy.orm import (\n scoped_session,\n sessionmaker,\n )\n\nfrom zope.sqlalchemy import ZopeTransactionExtension\n\nDBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))\nBase = declarative_base()\n\n\nclass MyModel(Base):\n \"\"\"\n >>> import transaction\n >>> from sqlalchemy import create_engine\n >>> engine = create_engine('sqlite://')\n >>> from simple.models import (\n ... DBSession,\n ... Base,\n ... MyModel,\n ... )\n >>> DBSession.configure(bind=engine)\n >>> Base.metadata.create_all(engine)\n >>> with transaction.manager:\n ... model = MyModel(name='one', value=1234)\n ... DBSession.add(model)\n >>>\n \"\"\"\n __tablename__ = 'MyModel'\n id = Column(Integer, primary_key=True)\n name = Column(Text)\n value = Column(Integer)\n\nIndex('my_index', MyModel.name, unique=True, mysql_length=255)\n","sub_path":"pyramid/doctesting/simple/simple/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"330121276","text":"import numpy as np\r\nimport cv2\r\nimport imutils\r\nimport seaborn as sns\r\n\r\nimg = cv2.imread('3.jpg')\r\ncv2.imshow('image',img)\r\n#k = cv2.waitKey(0)\r\n#if k == 27: # wait for ESC key to exit\r\n# cv2.destroyAllWindows()\r\n#elif k == ord('s'): # wait for 's' key to save and exit\r\n# cv2.imwrite('messigray.png',img)\r\n# cv2.destroyAllWindows()\r\n \r\n#pre-processing for the image\r\nicol = (0,114,23,255,255,66) # Pipes\r\n\r\nframeBGR = cv2.GaussianBlur(img, (7, 7), 0)\r\n#frameBGR = cv2.medianBlur(img, 7)\r\n#frameBGR = cv2.bilateralFilter(frameBGR, 15 ,75, 75)\r\n#kernal = np.ones((15, 15), np.uint8)\r\n#frameBGR = cv2.filter2D(frameBGR, -1, kernal)\"\"\"\r\n\t\r\n# Show blurred image.\r\ncv2.imshow('blurred', frameBGR)\r\n\t\r\n# HSV (Hue, Saturation, Value).\r\n# Convert the frame to HSV colour model.\r\nhsv = cv2.cvtColor(frameBGR, cv2.COLOR_BGR2HSV)\r\n\r\n# HSV values to define a colour range.\r\ncolorLow = np.array([0,114,23])\r\ncolorHigh = np.array([255,255,66])\r\nmask = cv2.inRange(hsv, colorLow, colorHigh)\r\n# Show the first mask\r\ncv2.imshow('mask-plain', mask)\r\n \r\n#kernel = np.ones((5,5),np.uint8)\r\n#mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)\r\n\r\n#kernal = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))\r\n#mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernal,iterations=1)\r\n#mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernal,iterations=1)\r\n \r\n# Show morphological transformation mask\r\n#cv2.imshow('mask', mask)\r\n\r\n# Put mask over top of the original image.\r\nresult = cv2.bitwise_and(img, img, mask = mask)\r\ncv2.imshow('result',result)\r\n\r\n# find contours in the thresholded image\r\ncnts = cv2.findContours(mask, cv2.RETR_EXTERNAL,\r\n\tcv2.CHAIN_APPROX_SIMPLE)\r\ncnts = imutils.grab_contours(cnts)\r\nprint(\"[INFO] {} unique contours found\".format(len(cnts)))\r\n \r\n# loop over the contours\r\nk = 0\r\na = []\r\n\r\nfor (i, c) in enumerate(cnts):\r\n\t# draw the contour\r\n\t#print(\"The value for each c\",c)\r\n\t((x, y), _) = cv2.minEnclosingCircle(c)\r\n\ta.append(cv2.contourArea(c))\r\n\tif(cv2.contourArea(c) > 500 and cv2.contourArea(c)<2500):\r\n\t\tcv2.putText(img, \"#{}\".format(k + 1), (int(x) - 10, int(y)),\r\n \t\tcv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)\r\n\t\tk = k + 1\r\n\t\tprint(\"The value for K\",k) \r\n \t#print(\"Area of rectangle\",cv2.contourArea(c))\r\n\r\n\t\tcv2.drawContours(img, [c], -1, (0, 255, 0), 2)\r\n\r\nprint(\"Total number of pipes\",k-1)\r\n# show the output image\r\ncv2.imshow(\"Image\", img)\r\ncv2.waitKey(0)\r\n\r\n#Plot to see the average contours area distribution\r\na1 = sns.distplot(a,hist=True,kde=True,rug=True)\r\n","sub_path":"counter_1.py","file_name":"counter_1.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"125943605","text":"from __future__ import print_function, absolute_import\nimport os.path as osp\nimport os\nimport numpy as np\nfrom collections import defaultdict\n\nfrom ..utils.data import Dataset\nfrom ..utils.osutils import mkdir_if_missing\nfrom ..utils.serialization import read_json\nfrom ..utils.serialization import write_json\n\n\n\ndef _pluck(datasetname, identities, indices, id_offset=None, cam_offset=None):\n \"\"\"Extract im names of given pids.\n Args:\n identities: containing im names\n indices: pids\n relabel: whether to transform pids to classification labels\n \"\"\"\n ret = []\n for index, pid in enumerate(indices):\n pid_images = identities[pid]\n for camid, cam_images in enumerate(pid_images):\n for fname in cam_images:\n name = osp.splitext(fname)[0]\n x, y, _ = map(int, name.split('_'))\n assert pid == x and camid == y\n if (id_offset and cam_offset):\n ret.append((osp.join(datasetname, 'images', fname),\n id_offset+index, cam_offset+camid))\n else:\n ret.append((osp.join(datasetname, 'images', fname),\n index, camid))\n return ret\nclass Merged_Dataset(Dataset):\n \"\"\"\n merge the selected dataset for training\n args:\n datasets: a list of dataset name e.g.['market1501','cuhk03']\n\n \"\"\"\n def __init__(self, root, datasets, split_id=0, num_val=100, download=True):\n for dataset in datasets:\n assert dataset in os.listdir(root)\n super(Merged_Dataset, self).__init__(root, split_id=split_id)\n self.datasets = datasets\n\n for dataset in datasets:\n if not self._check_integrity(dataset):\n raise RuntimeError( dataset + \" not found or corrupted. \"\n \"You should download it first.\")\n\n self.load(num_val)\n\n def _check_integrity(self,dataset):\n return osp.isdir(osp.join(self.root, dataset, 'images')) and \\\n osp.isfile(osp.join(self.root, dataset, 'meta.json')) and \\\n osp.isfile(osp.join(self.root, dataset, 'splits.json'))\n\n @property\n def images_dir(self):\n return osp.join(self.root)\n\n def load(self, num_val=0.3, verbose=True, labelset=True):\n cam_offset = 0\n self.query = defaultdict()\n self.gallery = defaultdict()\n for dataset in self.datasets:\n splits = read_json(osp.join(self.root, dataset, 'splits.json'))\n if self.split_id >= len(splits):\n raise ValueError(\"split_id exceeds total splits {}\"\n .format(len(splits)))\n self.split = splits[self.split_id]\n trainval_pids = np.asarray(self.split['trainval'])\n np.random.shuffle(trainval_pids)\n num = len(trainval_pids)\n if isinstance(num_val, float):\n num_val = int(round(num * num_val))\n if num_val >= num or num_val < 0:\n raise ValueError(\"num_val exceeds total identities {}\"\n .format(num))\n train_pids = sorted(trainval_pids[:-num_val])\n val_pids = sorted(trainval_pids[-num_val:])\n\n self.meta = read_json(osp.join(self.root, dataset, 'meta.json'))\n identities = self.meta['identities']\n\n self.train.extend(_pluck(dataset, identities, train_pids, len(self.train), cam_offset))\n self.val.extend(_pluck(dataset, identities, val_pids, len(self.val), cam_offset))\n self.trainval.extend(_pluck(dataset, identities, trainval_pids, len(self.trainval), cam_offset))\n self.num_trainval_ids += len(trainval_pids)\n self.num_train_ids += len(train_pids)\n self.num_val_ids += len(val_pids)\n\n cam_offset += self.meta['num_cameras']\n\n if 'query_fnames'in self.meta.keys():\n query_fnames = self.meta['query_fnames']\n gallery_fnames = self.meta['gallery_fnames']\n self.query[dataset] = []\n for fname in query_fnames:\n name = osp.splitext(fname)[0]\n pid, cam, _ = map(int, name.split('_'))\n fname = os.path.join(dataset, 'images', fname)\n self.query[dataset].append((fname, pid, cam))\n self.gallery[dataset] = []\n for fname in gallery_fnames:\n name = osp.splitext(fname)[0]\n pid, cam, _ = map(int, name.split('_'))\n fname = os.path.join(dataset, 'images', fname)\n self.gallery[dataset].append((fname, pid, cam))\n elif 'labeled_query' in self.meta.keys():\n if labelset:\n query_fnames = self.meta['labeled_query']\n gallery_fnames = self.meta['labeled_gallery']\n else:\n query_fnames = self.meta['detected_query']\n gallery_fnames = self.meta['detected_gallery']\n self.query[dataset] = []\n for fname in query_fnames:\n name = osp.splitext(fname)[0]\n pid, cam, _ = map(int, name.split('_'))\n fname = os.path.join(dataset, 'images', fname)\n self.query[dataset].append((fname, pid, cam))\n self.gallery[dataset] = []\n for fname in gallery_fnames:\n name = osp.splitext(fname)[0]\n pid, cam, _ = map(int, name.split('_'))\n fname = os.path.join(dataset, 'images', fname)\n self.gallery[dataset].append((fname, pid, cam))\n else:\n self.query[dataset] = _pluck(dataset, identities, self.split['query'])\n self.gallery[dataset] = _pluck(dataset, identities, self.split['gallery'])\n print(\" {}_query | {:5d} | {:8d}\"\n .format(dataset, len(self.split['query']), len(self.query[dataset])))\n print(\" {}_gallery | {:5d} | {:8d}\"\n .format(dataset, len(self.split['gallery']), len(self.gallery[dataset])))\n if verbose:\n print(self.__class__.__name__, \"dataset loaded\")\n print(\" subset | # ids | # images\")\n print(\" ---------------------------\")\n print(\" train | {:5d} | {:8d}\"\n .format(self.num_train_ids, len(self.train)))\n print(\" val | {:5d} | {:8d}\"\n .format(self.num_val_ids, len(self.val)))\n print(\" trainval | {:5d} | {:8d}\"\n .format(self.num_trainval_ids, len(self.trainval)))\n\n\n","sub_path":"reid/datasets/merged_dataset.py","file_name":"merged_dataset.py","file_ext":"py","file_size_in_byte":6750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"639444277","text":"# -*- coding: utf-8 -*-\nfrom __future__ import (absolute_import, division, print_function, unicode_literals)\n\nfrom gensim.corpora.dictionary import Dictionary\nfrom multiprocessing import cpu_count\nfrom multiprocessing import Pool\nfrom simple_arxiv_engine.utils.util_tasks import DictionaryFetcher\nfrom simple_arxiv_engine.utils.utils import Chunkizer\n\nimport gzip\nimport json\nimport logging\nimport luigi\nimport nltk\nimport os\nimport uuid\n\n\n__author__ = 'Karl Ritchie '\n__copyrights__ = 'Copyright 2017 Karl Ritchie'\n\n\nlogger_name = 'simple.arxiv.engine'\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(logger_name)\n\nDATA = os.environ['SAE_DATA_FOLDER']\nDB = 'simple_arxiv_engine'\nCOLL = 'raw'\n\n\nclass OfflineDictionaryBuilder(luigi.Task):\n \"\"\" Builds a dictionary with paper summaries receive from ArXiv API\n\n \"\"\"\n\n def requires(self):\n return DictionaryFetcher(self.output().path)\n\n def output(self):\n return luigi.LocalTarget(path='{folder}/models/dictionary.model'.format(folder=DATA))\n\n @staticmethod\n def process_dictionaries(files):\n \"\"\" Method for processing a list of files and creating a dictionary based on the summary of papers.\n\n It will place the result into a staging dictionary that will be merged with the main dictionary in the run\n method of this class\n \"\"\"\n filename = '{folder}/models/dictionary.model.{id}'.format(folder=DATA, id=uuid.uuid4())\n dictionary = Dictionary()\n\n # Process each raw files\n for infile in files:\n\n with gzip.open(infile) as f_in:\n\n documents = []\n\n for line in f_in:\n\n if isinstance(line, bytes):\n line = line.decode('utf-8')\n\n tokens = nltk.word_tokenize(json.loads(line)['summary'])\n documents.append(tokens)\n\n dictionary.add_documents(documents)\n\n dictionary.save(filename)\n return filename\n\n def run(self):\n \"\"\" Loop through files to build dictionary\n\n \"\"\"\n\n files = ('{0}/raw/{1}'.format(str(DATA), str(file)) for file in os.listdir('{0}/raw'.format(DATA)))\n file_chunks = Chunkizer.chunkize_into_list(files, 100)\n\n dictionary = Dictionary.load(self.input().path)\n dictionaries = set()\n\n pool = Pool(processes=cpu_count())\n\n for i, output in enumerate(pool.imap_unordered(OfflineDictionaryBuilder.process_dictionaries,\n (chunk for chunk in file_chunks), chunksize=1), 1):\n dictionaries.add(output)\n\n for dictio in dictionaries:\n\n dictionary.merge_with(Dictionary.load(dictio))\n\n # Clean the staging files after\n os.remove(dictio)\n\n dictionary.save(self.input().path)\n return\n\nif __name__ == '__main__':\n luigi.run(main_task_cls=OfflineDictionaryBuilder, local_scheduler=True,\n cmdline_args=[])\n","sub_path":"simple_arxiv_engine/data_processing/offline_dictionary_builder.py","file_name":"offline_dictionary_builder.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"647811840","text":"\"\"\"\nGive a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.\n\nSubstrings that occur multiple times are counted the number of times they occur.\n\nExample 1:\n\nInput: \"00110011\"\nOutput: 6\nExplanation: There are 6 substrings that have equal number of consecutive 1's and 0's: \"0011\", \"01\", \"1100\", \"10\", \"0011\", and \"01\".\n\nNotice that some of these substrings repeat and are counted the number of times they occur.\n\nAlso, \"00110011\" is not a valid substring because all the 0's (and 1's) are not grouped together.\n\nExample 2:\n\nInput: \"10101\"\nOutput: 4\nExplanation: There are 4 substrings: \"10\", \"01\", \"10\", \"01\" that have equal number of consecutive 1's and 0's.\n\nNote:\ns.length will be between 1 and 50,000.\ns will only consist of \"0\" or \"1\" characters.\n\"\"\"\n\nclass Solution:\n def countBinarySubstrings(self, s):\n \"\"\"\n 计数二进制子串\n :param s: str\n :return: int\n \"\"\"\n pre, cur, result = 0, 1, 0\n for i in range(len(s) - 1):\n if s[i] == s[i + 1]:\n cur += 1\n else:\n pre = cur\n cur = 1\n if pre >= cur:\n result += 1\n return result\n\nif __name__ == '__main__':\n solu = Solution()\n print(solu.countBinarySubstrings(\"00110011\"))","sub_path":"696_Count Binary Substrings.py","file_name":"696_Count Binary Substrings.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"633749297","text":"#!/usr/bin/env python\n#\n# Created by: Shawn Chen \n#\n# LICENSE\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the Free\n# Software Foundation; either version 2 of the License, or(at your option)\n# any later version.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n# more details at http://www.gnu.org/copyleft/gpl.html\n#\n# Brief\n# Solves LeetCode Problem 8: String to Integer\n\n\nclass Solution(object):\n def myAtoi(self, str):\n \"\"\"\n :type str: str\n :rtype: int\n \"\"\"\n if len(str) <= 0:\n return 0\n num = 0\n # remove leading whitespace\n str = str.lstrip()\n if str[0] == '-':\n sign = -1\n else:\n sign = 1\n if str[0] in ['-', '+']:\n str = str[1:]\n for i in str:\n if i.isdigit():\n num = 10 * num + int(i)\n else:\n break\n if num > 2147483647:\n if sign == 1:\n num = 2147483647\n elif sign == -1:\n num = 2147483648\n else:\n num = 0\n return num * sign\n","sub_path":"Problem8/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"12156913","text":"try:\n from urlparse import urljoin\n from urllib2 import build_opener\nexcept ImportError:\n from urllib.parse import urljoin\n from urllib.request import build_opener\nimport json\nclass APIClient(object):\n \"\"\"WHM API client class\"\"\"\n def __init__(self,\n host_uri='https://127.0.0.1:2087',\n api_user='root',\n api_type='json-api',\n api_version=1,\n api_acc_hash=None):\n super(APIClient, self).__init__()\n self.host_uri = host_uri\n self.api_user = api_user\n self.api_type = api_type\n self.api_version = api_version\n self.api_acc_hash = api_acc_hash or self.__read_accesshash()\n self.opener = self._get_opener()\n\n def __read_accesshash(self, acc_hash_path='/root/.accesshash'):\n \"\"\"\n Read accesshash file from root directory(if not specified another).\n \"\"\"\n with open(acc_hash_path) as f:\n access_hash = f.read()\n hash_string = ''.join(\n [hl.rstrip('\\n') for hl in access_hash.splitlines()]\n )\n return hash_string\n\n def get_url_for(self, function, req_params={}):\n \"\"\" URL constructor for API calls.\n @function: function name to vbe called from WHMApi list.\n @params: request params.\n \"\"\"\n params = '&'.join(['{pn}={pv}'.format(pn=pn, pv=pv)\n for (pn, pv) in req_params.items()])\n url_path = '{at}/{fc}?api.version={av}&{pm}'.format(\n at=self.api_type,\n fc=function,\n av=self.api_version,\n pm=params)\n constrcuted = urljoin(self.host_uri, url_path)\n # Dirty hack to prevent few if's\n # This allows us to ignore case when paramse were empty.\n return constrcuted.rstrip('&')\n\n def _auth_headers(self):\n headers = [\n ('Authorization', 'WHM {us}:{ah}'.format(\n us=self.api_user,\n ah=self.api_acc_hash))\n ]\n return headers\n\n def _get_opener(self):\n \"\"\"Retrieve URLOpenerDirector object with required headers\"\"\"\n opener = build_opener()\n opener.addheaders = self._auth_headers()\n return opener\n\n def call(self, function, req_params={}):\n \"\"\" Generate API call with specified params for specified function \"\"\"\n uri = self.get_url_for(function, req_params)\n result = self.opener.open(uri)\n return json.loads(result.read().decode('utf-8'))\n","sub_path":"whmapi/APIClient.py","file_name":"APIClient.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"40337703","text":"import math\nimport skimage.feature as ft\nfrom skimage.feature import blob_doh\nfrom skimage.filters import roberts, sobel, canny, threshold_otsu\nfrom skimage.morphology import reconstruction, closing, square\nfrom skimage.measure import regionprops, label\nfrom skimage.segmentation import clear_border\nfrom skimage.color import label2rgb\nfrom sklearn.decomposition import RandomizedPCA\nimport numpy as np\n\nclass RPCA(object):\n def analyse(image):\n pca = RandomizedPCA(n_components=5)\n pca.fit(image)\n return pca.explained_variance_ratio_\n\nclass Blobs(object):\n def detect(image, verbose=False):\n \"\"\"Blob detection by computation of the \n Laplacian of Gaussian and Difference of Gaussian.\n\n Params:\n image -- numpy array of luminance (RGB / 255)\n\n Returns:\n (num_small_blobs, num_large_blobs)\n \"\"\"\n small_blobs = Blobs._detect_small_masses(image)\n large_blobs = Blobs._detect_large_masses(image)\n return (small_blobs, large_blobs)\n\n def _detect_small_masses(image):\n \"\"\" Uses the Laplacian of Gaussian blob detection method.\"\"\"\n blobs = blob_doh(image, max_sigma=20, threshold=.01)\n if len(blobs) == 0:\n return 0\n blobs[:,2] = blobs[:,2] * math.sqrt(2)\n filtered = []\n for blob in blobs:\n if blob[2] > 1.5 and blob[2] < 15:\n filtered.append(blob)\n if len(filtered) == 0:\n return 0\n else:\n return len(filtered)\n\n def _detect_large_masses(image):\n \"\"\" Uses the difference of gaussian blob detection method,\n which is much less accurate than LoG. With a higher threshold,\n larger and more obvious masses are more readily calculated.\n \"\"\"\n blobs = blob_doh(image, max_sigma=30, threshold=2)\n if len(blobs) == 0:\n return 0\n blobs[:,2] = blobs[:,2] * math.sqrt(2)\n filtered = []\n for blob in blobs:\n if blob[2] > 15:\n filtered.append(blob)\n if len(filtered) == 0:\n return 0\n else:\n return len(filtered)\n\n\nclass Edges(object):\n def __init__(self):\n self.lim = None\n\n def detect(image, verbose=True):\n \"\"\"Roberts and Sobel edge detection.\n\n Params:\n image -- numpy array of luminance (RGB / 255)\n\n Returns:\n roberts_limited -- array of x,y coordinates\n \"\"\"\n roberts_edge, sobel_edge = Edges.calculate_edges(image)\n roberts_limited = Edges.limit(roberts_edge)\n # sobel_limited = self.limit(sobel)\n return roberts_limited\n\n\n\n def calculate_edges(image):\n \"\"\"Calculates Roberts and Sobel edge detection.\n\n Parameters\n ----------\n image -- numpy array of luminance (RGB / 255)\n\n Returns\n -------\n Tuple: (\n edge_roberts -- Array of Roberts edge detection result\n edge_sobel -- Array of Sobel edge detection result\n )\n \"\"\"\n edge_roberts = roberts(image)\n edge_sobel = sobel(image)\n return (edge_roberts, edge_sobel)\n\n def limit(edges):\n \"\"\" \"\"\"\n maximum = max(edges.flatten())\n lim = maximum * 0.65\n Edges.lim = lim\n new_coords = []\n for row in edges:\n new_row = []\n for pixel in row:\n if pixel > lim:\n new_pixel = pixel\n else:\n new_pixel = 0.0\n new_row.append(new_pixel)\n new_coords.append(new_row)\n\n lim_coords = []\n for row in new_coords:\n for pixel in row:\n if pixel > lim:\n lim_coords.append([row.index(pixel), new_coords.index(row)])\n\n lim_coords_np = np.array(lim_coords)\n interim = np.ascontiguousarray(lim_coords_np).view(np.dtype((np.void, lim_coords_np.dtype.itemsize * lim_coords_np.shape[1])))\n _, idx = np.unique(interim, return_index=True)\n lim_coords = lim_coords_np[idx] \n return lim_coords\n \n\n\nclass Peaks(object):\n def detect(image, verbose=True):\n \"\"\" Detects luminance peaks in image.\n\n Parameters\n ----------\n image -- numpy array of luminance (RGB / 255)\n \n Returns\n -------\n coords -- array of peak x,y coordinates\n max_lum_int -- maximum luminance in image, rounded integer\n \"\"\"\n return Peaks.make_peaks(image)\n\n def make_peaks(image):\n mask = image\n seed = np.copy(image)\n seed[1:-1, 1:-1] = image.min()\n rec = reconstruction(seed, mask, method='dilation')\n res = image - rec\n result = np.array(res)\n maximum_luminance = max(result.flatten())\n mean_luminance = np.mean(result.flatten())\n mean_lum_int = math.floor(mean_luminance*255)\n max_lum_int = math.floor(maximum_luminance*255)\n lum_diff = max_lum_int - mean_lum_int\n lim = maximum_luminance * .8\n coords = []\n for row in result:\n new_row = []\n for pixel in row:\n if pixel > lim:\n new_pixel = pixel\n else:\n new_pixel = 0.0\n new_row.append(new_pixel)\n coords.append(new_row)\n lim_coords = []\n for row in coords:\n for pixel in row:\n if pixel > lim:\n lim_coords.append([row.index(pixel), coords.index(row)])\n\n lim_coords_np = np.array(lim_coords)\n interim = np.ascontiguousarray(lim_coords_np).view(np.dtype((np.void, lim_coords_np.dtype.itemsize * lim_coords_np.shape[1])))\n _, idx = np.unique(interim, return_index=True)\n lim_coords = lim_coords_np[idx] \n return lim_coords, max_lum_int, lum_diff\n \n \nclass Regions(object):\n def detect(image):\n edge_canny = ft.canny(image, sigma=0.5)\n thresh = threshold_otsu(edge_canny)\n bw = closing(edge_canny > thresh, square(3))\n cleared = bw.copy()\n clear_border(cleared)\n label_image = label(cleared)\n image_label_overlay = label2rgb(label_image, image=edge_canny)\n regions = []\n for region in regionprops(label_image):\n if region.area > 300:\n regions.append(region.area)\n \n if len(regions) > 0:\n \tlargest_region = max(regions)\n else:\n \tlargest_region = 0\n regions = len(regions)\n return (largest_region, regions)","sub_path":"kpimage/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":6615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"37521079","text":"#main.py\n\n# import external modules\nimport pygame, random, sys\nimport numpy as np\n# import local scripts\n\n# initialize pygame\npygame.init()\n\n# Window title\nTITLE = \"Program's title\"\npygame.display.set_caption(TITLE)\n\n# screen\nWIDTH = 640\nHEIGHT = 320\nscreen = pygame.display.set_mode((WIDTH,HEIGHT))\n\n# Key controls\npressed_key = []\n\n# quitting msg\nquitting_message = 'User is quitting the app'\n\n# Clock obj -> to keep track of FPS\nframerate = 24\nclock = pygame.time.Clock()\n\n\n# GLOBAL VARS\n# drawing vars\nellipse_fill = (255, 255, 255)\nalpha_white = (255, 255, 255, 120)\n\n\n\n# SETUP\n# starting background\nbackground = (0,0,0)\n#screen.fill(background)\n# custom objs\n\n# functions\ndef draw():\n\n\t# GET X\n\n\t# v.1: mean 0, sd 1 and normalize for custom mean and sd\n\t# --------------------------------------------------------\n\t# get a normal distribution:\n\tmean, sd, population = 0, 1, WIDTH # mean, standard deviation, pop size\n\tgaussian = np.random.normal(mean, sd, population) # make dataset\n\t# get random num from distribution\n\tindex = int(random.randrange(population))\n\tnum = gaussian[index]\n\t# normalized num to mean 320 and std 60:\n\tmean, sd = 320, 60\n\tx = sd * num + mean\n\n\t# v.2: custom mean and sd \n\t# --------------------------------------------------------\n\t\t# -> x tilts to the right\n\t\t# -> don't know why\n\t#mean, sd, population = 360, 60, WIDTH # mean, standard deviation, pop size\n\t#gaussian = np.random.normal(mean, sd, population) # make dataset\n\t#index = int(random.randrange(population))\n\t#num = gaussian[index]\n\t#x = num\n\n\t# TRANSPARENT ELLIPSE\n\t# 1. make alpha surface (able to hold multiple alpha objs)\n\talpha_surf = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)\n\t# 2. draw alpha-colored shape\n\tellipse_rect = pygame.Rect(x, 180, 16, 16)\n\tpygame.draw.ellipse(alpha_surf, alpha_white, ellipse_rect)\n\t# 3. blit alpha surf\n\talpha_rect = alpha_surf.get_rect()\n\tscreen.blit(alpha_surf, alpha_rect) # surf obj, rect obj\n\n\n# MAIN LOOP\n\nrunning = True\n\nwhile running:\n\t\n\t# MOUSE\n\tmouseX, mouseY = pygame.mouse.get_pos()\n\n\t# EVENTS - cannot be placed in a function to be called here\n\tfor event in pygame.event.get(): #all events in pygame\n\t\tif event.type == pygame.QUIT: # clicking QUIT button (X)\n\t\t\trunning = False # stop running\n\t\t\tprint(quitting_message)\n\t\t\tpygame.quit()\n\t\t\tsys.exit()\n\t\tif event.type == pygame.KEYDOWN:\n\t\t\tpressed_key.append(pygame.key.name(event.key)) # pressed_key must be a list for the following to work\n\t\t\tif event.key == pygame.K_LALT or event.key == pygame.K_F4:\n\t\t\t\trunning = False # stop running\n\t\t\t\tprint(quitting_message)\n\t\t\t\tpygame.quit()\n\t\t\t\tsys.exit()\n\t\n\n\t# DRAW\n\tdraw()\n\n\n\t# Set FPS\n\tclock.tick(framerate)\n\t# Update screen: last line of loop. Fires animation\n\tpygame.display.update()","sub_path":"00 - Introduction/gaussian_distribution_v05.py","file_name":"gaussian_distribution_v05.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"417230163","text":"from django import http\n\n\nclass SimpleMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n # One-time configuration and initialization.\n\n def __call__(self, request):\n # Code to be executed for each request before\n # the view (and later middleware) are called.\n\n response = self.get_response(request)\n\n if (request.method == \"OPTIONS\"):\n response = http.HttpResponse()\n response[\"Content-Length\"] = \"0\"\n response[\"Access-Control-Max-Age\"] = 86400\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"DELETE, GET, OPTIONS, PATCH, POST, PUT, HEAD\"\n response[\"Access-Control-Allow-Headers\"] = \"accept, accept-encoding, authorization, content-type, referer, sec-ch-ua, sec-ch-ua-mobile, dnt, origin, user-agent, x-csrftoken, x-requested-with\"\n return response\n","sub_path":"scribbli/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"30191135","text":"#!/usr/bin/python\n# -*- coding:utf8 -*-\nimport numpy as np\nimport math\nimport os\nimport json\n\nimport torch\nfrom torch import nn\nfrom common import softplus, inverse_softplus, cov2logsigma, logsigma2cov, split_first_dim, merge_first_two_dims\nfrom model.func import weighted_linear, normal_differential_sample, multivariate_normal_kl_loss\nfrom model.dynamic.combinational_linears import CombinationalLinears\nfrom model.common import DBlock, PreProcess\n\n\n\nclass VAEAKFCombinedLinear(nn.Module):\n def __init__(self, input_size, state_size, observations_size, net_type='lstm', k=16, num_layers=1, L=1, R=1,\n num_linears=8,random_overshooting=True,\n D=30):\n\n \"\"\"\n\n :param input_size: The size of external input\n :param state_size:\n :param observations_size:\n :param net_type: the type of VAE\n :param k: size of hidden state\n :param num_layers:\n :param L: The times for sampling auxiliary distribution.\n \"\"\"\n super(VAEAKFCombinedLinear, self).__init__()\n self.k = k\n self.observations_size = observations_size\n self.state_size = state_size\n self.input_size = input_size\n self.L = L\n self.R = R\n self.D = D\n self.random_overshooting = random_overshooting\n self.num_layers = num_layers\n\n assert D >= 1 and L >= 1 and R >= 1\n # region Define parameters for training\n self.process_x = PreProcess(input_size + observations_size, k)\n self.net_type = net_type\n self.rnn = nn.LSTM(k, k, num_layers=num_layers)\n self.posterior_hidden_state0 = torch.nn.Parameter(torch.zeros(k))\n self.gauss_decoder = DBlock(k, k*2, state_size)\n\n # In combinated linears, learnable linear matrix are weighted upon a softmax output.\n self.dynamic = CombinationalLinears(\n input_size,\n state_size,\n num_layers=num_layers,\n num_linears=num_linears,\n hidden_size=k\n )\n\n self.estimate_logdelta = torch.nn.parameter.Parameter(torch.randn(observations_size)) # noise in observation\n self.estimate_H = torch.nn.parameter.Parameter(torch.zeros((observations_size, state_size)))\n self.estimate_bias = torch.nn.parameter.Parameter(torch.randn(observations_size)) # bias in observation\n\n # endregion\n\n self.state_mu = None\n self.state_logsigma = None\n self.external_input_seq = None\n self.observations_seq = None\n self.initial_prior_mu, self.initial_prior_logsigma = None, None\n self.sampled_state = None\n self.weight_initial_hidden_state = None\n\n def forward_posterior(self, external_input_seq, observations_seq, posterior_lstm_state=None, weight_initial_hidden_state=None):\n\n self.external_input_seq = external_input_seq\n self.observations_seq = observations_seq\n\n l, batch_size, _ = external_input_seq.size()\n\n posterior_lstm_state = self.generate_lstm_initial_state(\n self.posterior_hidden_state0, batch_size, self.num_layers) if posterior_lstm_state is None else posterior_lstm_state\n\n self.initial_prior_mu, self.initial_prior_logsigma = self.gauss_decoder(\n posterior_lstm_state[0][-1]\n )\n\n all_seq = torch.cat([external_input_seq, observations_seq], dim=2)\n all_seq = self.process_x(all_seq)\n z_seq, new_posterior_lstm_state = self.rnn(all_seq, posterior_lstm_state)\n self.state_mu, self.state_logsigma = self.gauss_decoder(z_seq)\n\n self.weight_initial_hidden_state = weight_initial_hidden_state\n # region 估计每个位置的weight_hidden_state\n sampled_state = normal_differential_sample(\n torch.distributions.MultivariateNormal(self.state_mu, logsigma2cov(self.state_logsigma))\n )\n # weight_initial_hidden_state 是上一轮次forward时lstm的隐状态(hn, cn)\n\n weight_hidden_state = self.generate_lstm_initial_state(\n self.dynamic.weight_hidden_state0, batch_size, self.num_layers\n ) if weight_initial_hidden_state is None else weight_initial_hidden_state\n\n _, weight_hidden_state = self.dynamic.linears_weight_lstm(\n sampled_state, weight_hidden_state\n )\n new_weight_initial_hidden_state = weight_hidden_state\n # endregion\n\n return self.state_mu, self.state_logsigma, new_posterior_lstm_state, new_weight_initial_hidden_state\n\n def forward_prediction(self, external_input_seq, posterior_lstm_state=None, weight_initial_hidden_state=None,\n max_prob=False, return_weight_map=False):\n\n l, batch_size, _ = external_input_seq.size()\n\n # 生成-1时刻的隐变量分布\n posterior_lstm_state = self.generate_lstm_initial_state(\n self.posterior_hidden_state0, batch_size, self.num_layers) if posterior_lstm_state is None else posterior_lstm_state\n\n weight_hidden_state = self.generate_lstm_initial_state(\n self.dynamic.weight_hidden_state0, batch_size, self.num_layers) if weight_initial_hidden_state is None else weight_initial_hidden_state\n\n state_sampled_list = []\n weight_map_list = []\n\n self.initial_prior_mu, self.initial_prior_logsigma = self.gauss_decoder(\n posterior_lstm_state[0][-1]\n )\n\n # 预测过程通过ancestral sampling方法采样l个时刻的隐状态\n\n # 此处采样-1时刻的隐状态\n state = normal_differential_sample(\n torch.distributions.MultivariateNormal(self.initial_prior_mu, logsigma2cov(self.initial_prior_logsigma))\n )\n\n for i in range(l):\n\n # 根据weight_hidden_state计算i-1位置隐状态对应的linears weight, lstm为多层时,取h的最后一层状态\n next_state_dist, state, (weight_hidden_state, weight_map) = self.dynamic(\n state, external_input_seq[i], (weight_hidden_state, ))\n state_sampled_list.append(state)\n weight_map_list.append(weight_map)\n\n\n sampled_state = torch.stack(state_sampled_list)\n weight_map = torch.stack(weight_map_list)\n\n # 利用隐状态计算观测数据分布\n observations_dist = self.decode(state=sampled_state, mode='dist')\n\n # 对观测分布采样并更新后验lstm隐状态\n if max_prob:\n observations_sample = observations_dist.loc\n else:\n observations_sample = normal_differential_sample(observations_dist)\n _, posterior_lstm_state = self.rnn(\n self.process_x(torch.cat([external_input_seq, observations_sample], dim=-1)), posterior_lstm_state\n )\n\n if return_weight_map:\n return observations_dist, observations_sample, posterior_lstm_state, weight_hidden_state, weight_map\n else:\n return observations_dist, observations_sample, posterior_lstm_state, weight_hidden_state\n\n\n @staticmethod\n def generate_lstm_initial_state(state0, batch_size, num_layers):\n \"\"\"\n\n Args:\n state0: 可学习的初始隐状态 hn\n state0:\n batch_size:\n\n Returns:\n 扩展hn为多层,并产生全零cn\n 如果posterior_lstm_state 为 None 根据模型内部参数重构posterior_lstm_state,并解码先验分布\n 否则直接对posterior_lstm_state解码\n \"\"\"\n initial_hidden_state = torch.cat([\n torch.zeros_like(state0).repeat(num_layers-1, batch_size, 1),\n state0.repeat(batch_size, 1).unsqueeze(dim=0)\n ], dim=0)\n lstm_state = (initial_hidden_state, torch.zeros_like(initial_hidden_state))\n\n return lstm_state\n\n\n def call_loss(self):\n \"\"\"\n\n Returns: 调用call_loss前需要调用forward_posterior,以获得输入数据及隐状态的后验分布。\n 该算法采用 stochastic overshooting 方法来估计隐变量后验分布与先验分布的kl散度。具体过程如下:\n 对于任意位置i,其后验分布为q(i), 利用后验分布采样q(i-d),其中d为[1,D)的随机值。利用祖先采样从分布p(i-1|i-d, a[i-d:i-1])采样。\n 然后根据采样出来的h(i-1)计算i时刻隐变量的先验分布p(i|i-1),并计算与q(i)的kl散度。\n\n \"\"\"\n\n l, bs, _ = self.observations_seq.shape\n\n # system dynamic: p(s(t+1) | s(t), a(t+1))\n # o(t) o(t+1)\n # ^ ^\n # | |\n # | |\n # s(t) -----> s(t+1)\n # ^\n # |\n # |\n # a(t+1)\n\n # region calculating kl divergence :\n\n # 把系统-1时刻的先验分布加到后验分布中\n q_mu = torch.cat([self.initial_prior_mu.unsqueeze(dim=0), self.state_mu], dim=0)\n q_cov = torch.cat([logsigma2cov(self.initial_prior_logsigma).unsqueeze(dim=0), logsigma2cov(self.state_logsigma)])\n\n # 先从后验分布中采样,长度为 l + 1\n sampled_state = normal_differential_sample(\n torch.distributions.MultivariateNormal(q_mu, q_cov)\n )\n\n # 取forward_posterior时存储的weight_initial_hidden_state构建lstm的初始隐状态(hn,cn),如果为None,从动态模型dynamic内置参数构建\n weight_hidden_state = self.generate_lstm_initial_state(\n self.dynamic.weight_hidden_state0, bs, self.num_layers\n ) if self.weight_initial_hidden_state is None else self.weight_initial_hidden_state\n\n # region 计算各个位置的weight lstm 隐状态\n weight_h_c_list = [weight_hidden_state]\n for i in range(1, l+1):\n _, weight_hidden_state = self.dynamic.linears_weight_lstm(\n sampled_state[i:i+1], weight_hidden_state\n )\n weight_h_c_list.append(weight_hidden_state)\n\n # weight_hidden_state_memory : A tuple (l, bs, num_layers, h_size), (l,bs, num_layers, c_size)\n weight_hidden_state_memory = tuple([torch.stack(state).contiguous().transpose(2, 1) for state in zip(\n *weight_h_c_list\n )])\n\n # region 魔法开始! random overshooting\n\n \"\"\"\n 定义名词:\n 训练位置 : i, 指计算KL[q(i)||p(i|i-1)]的位置\n 起始位置: i-t ,指over shooting 中做长序列预测的起始位置p(i-1|i-t),其中t对于不同batch中的不同训练数据、不同序列位置i都是随机的\n 单步预测位置: i-1\n \"\"\"\n def kl_sample():\n\n\n for overshooting_length in (range(self.D, self.D+1) if self.random_overshooting else range(1, self.D+1)):\n # 不对完整的序列计算kl散度,因为需要往前最多look back D步,所以只考虑序列最后 l + 1 - D个位置,\n # trained_positions存储被训练位置的下标,以后要用下标来做gather操作\n\n trained_positions = torch.arange(overshooting_length, q_mu.size()[0], device=sampled_state.device).reshape(-1, 1).repeat(1, bs)\n trained_length = trained_positions.size()[0]\n if self.random_overshooting:\n # 对每个待训练的位置,随机look back一定距离,随机范围是[1,D]\n sampled_d = torch.randint(1, self.D+1, trained_positions.size(), device=sampled_state.device)\n else:\n sampled_d = torch.randint(overshooting_length, overshooting_length + 1,\n trained_positions.size(), device=sampled_state.device)\n\n # 根据随机出来的距离,计算后验分布做采样的位置\n positions_minus_d = trained_positions - sampled_d\n\n def seq_gather(input, index):\n \"\"\"\n 根据index存储的下标,取input序列指定位置的张量\n Args:\n input: shape(length, bs, a, b, c, ...)\n index: (l, bs)\n\n Returns: tensor with shape (l, bs, a, b, c, ...)\n\n \"\"\"\n l, bs = index.size()[0], index.size()[1]\n\n assert (index >= 0).all() and (index < input.size()[0]).all()\n\n return torch.gather(\n input, dim=0, index=index.reshape(\n l, bs, *([1]*(len(input.shape)-2))\n ).repeat(1, 1, *input.size()[2:])\n )\n\n assert (positions_minus_d >= 0).all()\n # 从sampled_state中取出起始位置对应的采样的状态\n predicted_state_sampled = seq_gather(sampled_state, positions_minus_d)\n # 取出起始位置对应的weight lstm 隐状态:用weight_hidden_state_memory内的状态作为初始状态,之后的状态边采样,边用lstm计算\n weight_hidden_state = tuple([seq_gather(weight_hidden_state_memory[_], positions_minus_d) for _ in [0, 1]])\n current_sampled_positions = positions_minus_d\n\n # 从起始位置开始,不停地做单步预测,直到预测到单步预测位置为止\n while (current_sampled_positions < trained_positions - 1).any():\n\n # 找到那些还没到单步预测位置的positions\n updated_positions = (current_sampled_positions < trained_positions - 1)\n # 取出这些位置的采样状态\n changed_state = predicted_state_sampled[updated_positions]\n # 取出这些位置的weight lstm隐状态\n changed_weight_hidden_state = tuple([weight_hidden_state[_][updated_positions] for _ in range(2)])\n hn, cn = changed_weight_hidden_state\n hn = hn.contiguous().transpose(1, 0)\n cn = cn.contiguous().transpose(1, 0)\n\n \"\"\"\n 对于外部输入项下标为什么是current_sampled_positions的解释:\n 因为考虑了-1位置的先验分布,因此sampled_state,即完整后验隐状态采样的长度为l+1,对应下���位[0,l],而外部输入序列\n external_input_seq的长度为l,对应下标[0,l-1],对应系统变换为 func(state[0] , input[0]) -> state[1],因此,\n current_sampled_positions存储的是当前正在向前滚动的隐状态下标,与其产生作用的外部输入序列下标应同为current_sampled_positions\n \"\"\"\n external_input_need = seq_gather(self.external_input_seq, current_sampled_positions)[updated_positions]\n\n # 利用动态系统模拟状态变化,返回下一时刻的分布及采样\n next_state_dist, next_state_sample, ((new_hn, new_cn), weight_map) = self.dynamic(\n changed_state, external_input_need, ((hn, cn),)\n )\n # 更新 状态、lstm隐状态\n weight_hidden_state[0][updated_positions] = hn.contiguous().transpose(1, 0)\n weight_hidden_state[1][updated_positions] = cn.contiguous().transpose(1, 0)\n predicted_state_sampled[updated_positions] = next_state_sample\n\n # 没到单步预测位置的位置增1\n current_sampled_positions[updated_positions] += 1\n assert (current_sampled_positions + 1 == trained_positions).all()\n\n # 以单步预测位置作为起点,再做一次单步预测\n\n # dynamic 的输入tensor要求为(bs, xxx),需要把张量前两维合并\n weight_hidden_state = tuple([merge_first_two_dims(weight_hidden_state[_]) for _ in range(2)])\n\n # 取其中单步预测分布, 其他返回值没用\n hn, cn = weight_hidden_state\n hn = hn.contiguous().transpose(1, 0)\n cn = cn.contiguous().transpose(1, 0)\n one_step_predicted_dist, _, _ = self.dynamic(merge_first_two_dims(predicted_state_sampled),\n merge_first_two_dims(seq_gather(self.external_input_seq, current_sampled_positions)),\n ((hn, cn),))\n # 计算训练位置i,后验分布q(i)与先验分布p(i|i-1)的kl散度\n kl = multivariate_normal_kl_loss(self.state_mu[-trained_length:],\n logsigma2cov(self.state_logsigma[-trained_length:]),\n split_first_dim(one_step_predicted_dist.loc, (trained_length, bs)),\n split_first_dim(one_step_predicted_dist.covariance_matrix, (trained_length, bs))\n )\n return kl\n kl = sum([kl_sample() for _ in range(self.R)])/self.R\n # endregion\n\n # region calculation generative probability p(x|z)\n generative_likelihood = self.estimate_generative_logprobability()\n # endregion\n\n # maximun -kl + generative_likelihood\n return (kl - generative_likelihood)/bs, kl/bs, -generative_likelihood/bs\n\n def estimate_generative_logprobability(self):\n\n def estimate_generative_logprobability_from_sample():\n state = self.sample_state(max_prob=False)\n observations_mu = torch.nn.functional.linear(state, self.estimate_H) + self.estimate_bias\n observations_cov = logsigma2cov(self.estimate_logdelta)\n observations_normal_dist = torch.distributions.MultivariateNormal(observations_mu, observations_cov)\n return torch.sum(observations_normal_dist.log_prob(self.observations_seq))\n\n generative_likelihood = sum([estimate_generative_logprobability_from_sample() for _ in range(self.L)])/self.L\n return generative_likelihood\n\n def decode(self, state, mode='sample'):\n \"\"\"\n\n Args:\n state: with shape (len, batch_size, state_size)\n mode: dist or sample\n\n Returns:\n\n \"\"\"\n observations_mu = torch.nn.functional.linear(state, self.estimate_H) + self.estimate_bias\n observations_cov = logsigma2cov(self.estimate_logdelta)\n observations_normal_dist = torch.distributions.MultivariateNormal(observations_mu, observations_cov)\n if mode == 'dist':\n return observations_normal_dist\n elif mode == 'sample':\n return observations_normal_dist.sample()\n\n def sample_state(self, max_prob=True):\n \"\"\"\n :param max_prob: If True, return the sequence which has the biggest probability. Otherwise, a randomly sampled\n sequence will be returned.\n :return:(l, bs, state_size)\n \"\"\"\n if self.state_mu is None:\n raise AssertionError('You have to call forward method before sampling state')\n if max_prob:\n return self.state_mu\n noise = torch.randn_like(self.state_mu)\n state = noise*softplus(self.state_logsigma) + self.state_mu\n return state\n\n def sigma_interval(self, e):\n return self.state_mu - e * softplus(self.state_logsigma), \\\n self.state_mu + e * softplus(self.state_logsigma)\n\n","sub_path":"model/vaeakf_combinational_linears_random.py","file_name":"vaeakf_combinational_linears_random.py","file_ext":"py","file_size_in_byte":19449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"56536331","text":"from Entity.Piece.piece import Piece as PieceEntity\nfrom Enum.enum import *\nfrom Util.position import *\nfrom Util.action import *\n\nclass King(PieceEntity):\n\n def __init__(self, field, team, position):\n PieceEntity.__init__(self, field, team, position, Piece.KING)\n\n def GetRules(self):\n allowedPositions = [\n self.position + Position(0, 1),\n self.position + Position(1, 1),\n self.position + Position(1, 0),\n self.position + Position(1, -1),\n self.position + Position(0, -1),\n self.position + Position(-1, -1),\n self.position + Position(-1, 0),\n self.position + Position(-1, 1)\n ]\n\n allowedActions = []\n for position in allowedPositions:\n target = self.field.CheckCase(position)\n if target:\n if target.team != self.team:\n allowedActions.append(Action(self, position, target))\n else:\n allowedActions.append(Action(self, position))\n\n #Castling\n if self.moveNumber == 0 and self.field.inCheck != self.team:\n for rook in self.field.GetPieces(self.team, Piece.ROOK):\n if rook.moveNumber == 0:\n sub = rook.position - self.position\n direction = 1\n if sub.x < 0:\n direction = -1\n nothingBetween = True\n for i in range(1, sub.x*direction):\n x = self.position.x + i*direction\n if self.field.CheckCase(Position(x, self.position.y)):\n nothingBetween = False\n break\n if nothingBetween:\n movePosition = self.position + Position(2*direction, 0)\n action = Action(self, movePosition)\n rookPosition = movePosition + Position(-direction, 0)\n if not(self.field.CheckAfterAction(action)) and not(self.field.CheckAfterAction(Action(self, rookPosition))):\n action.AttachCallback(Action(rook, rookPosition))\n allowedActions.append(action)\n\n\n\n return allowedActions","sub_path":"Entity/Piece/king.py","file_name":"king.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"89124012","text":"import types\nimport operations\nimport math\n\n#class to bundle problem parameters\nclass Problem:\n def __init__(self, alg, startnum, targetnum, time, ops):\n NumberTypes = (int, float)\n assert isinstance(alg, str), \"alg is not an string: %r\" % alg\n assert isinstance(startnum, NumberTypes), \"startnum is not a number: %r\" % startnum\n assert isinstance(targetnum, NumberTypes), \"targetnum is not a number: %r\" % targetnum\n assert isinstance(time, NumberTypes), \"time is not a number: %r\" % time\n for op in ops:\n assert isinstance(op[0], str), \"operator is not a string: %r\" % op[0]\n try:\n assert isinstance(op[1], NumberTypes), \"operand is not a number: %r\" % op[1]\n except:\n print(\"operand is not a number: %r\" % op[1])\n\n self.alg = alg\n self.startnum = startnum\n self.targetnum = targetnum\n self.time = time\n self.ops = ops\n self.increasing = operations.categorize_problem(self.ops)\n self.sub_targets = operations.calculate_subtargets(self.targetnum, self.ops)\n\n def __str__(self):\n return \"\"\n # prints the problem details\n def printProblem(self):\n print (self.alg, self.startnum, self.targetnum, self.time, self.ops)\n\n # evaluates the operation on a given number\n # @param number - the number to be evaluated\n # @param op - the operation to be executed\n def evalOp(self, number, op):\n return math.floor(operations.eval_operation(number, op[0], op[1]))\n\n # determines if this branch should be cutoff\n # @param {number} current - the current value of the state\n # @return {boolean}\n def cut_off(self, current):\n if self.increasing == None:\n return False\n if current > self.targetnum:\n print(current)\n if self.increasing:\n return True\n elif current < self.targetnum:\n if not self.increasing:\n return True\n return False\n","sub_path":"assig1/problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"342004175","text":"#!python\n# -*- coding:utf-8 -*-\nfrom __future__ import print_function\nfrom setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\", encoding='utf-8') as fh:\n long_description = fh.read()\n\nsetup(\n name=\"hicmsd\",\n version=\"0.0.1\",\n author=\"Biao Zhang\",\n author_email=\"littlebiao@outlook.com\",\n description=\"Code of HiCMSD\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n license=\"MIT\",\n url=\"https://github.com/Codsir/HiCMSD\",\n packages=find_packages(),\n install_requires=[\n \"scikit-image >= 0.13.0\",\n \"visdom >= 0.1.8.5\",\n \"torch >= 0.4.1\",\n \"torchvision >= 0.2.1\",\n \"scikit-learn >= 0.20.0\",\n \"numpy >= 1.15.4\",\n \"scipy >= 1.1.0\",\n ],\n classifiers=[\n \"Topic :: Scientific/Engineering :: Bio-Informatics\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Intended Audience :: Science/Research\",\n ],\n python_requires='>=3.5',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"249981187","text":"import gym\nfrom space_wrappers.transform import discretize, flatten, rescale\nfrom gym.spaces import *\nimport numpy as np\nimport itertools\n\ndef check_convert(trafo, target, original):\n assert (trafo.convert_from(target) == original).all()\n assert (trafo.convert_to(original) == target).all()\n# discretize\n\ndef test_discretize_1d_box():\n cont = Box(np.array([0.0]), np.array([1.0]))\n trafo = discretize(cont, 10)\n\n assert trafo.target == Discrete(10)\n assert trafo.convert_from(0) == 0.0\n assert trafo.convert_from(9) == 1.0\n assert trafo.convert_to(0.0) == 0\n assert trafo.convert_to(1.0) == 9\n\ndef test_discretize_discrete():\n start = Discrete(5)\n trafo = discretize(start, 10)\n assert trafo.target == start\n\ndef test_discretize_nd_box():\n cont = Box(np.array([0.0, 1.0]), np.array([1.0, 2.0]))\n trafo = discretize(cont, 10)\n\n assert trafo.target == MultiDiscrete([(0, 9), (0, 9)])\n check_convert(trafo, (0, 0), [0.0, 1.0])\n check_convert(trafo, (9, 9), [1.0, 2.0])\n\n trafo = discretize(cont, (5, 10))\n\n assert trafo.target == MultiDiscrete([(0, 4), (0, 9)])\n check_convert(trafo, (0, 0), [0.0, 1.0])\n check_convert(trafo, (4, 9), [1.0, 2.0])\n\n# flatten\ndef test_flatten_single():\n start = Discrete(5)\n trafo = flatten(start)\n assert trafo.target == start\n\n start = Box(np.array([0.0]), np.array([1.0]))\n trafo = flatten(start)\n assert trafo.target == start\n\ndef test_flatten_discrete():\n md = MultiDiscrete([(0, 2), (0, 3)])\n trafo = flatten(md)\n\n assert trafo.target == Discrete(12)\n # check that we get all actions exactly once\n actions = []\n for (i, j) in itertools.product([0, 1, 2], [0, 1, 2, 3]):\n actions += [(i, j)]\n for i in range(0, 12):\n a = trafo.convert_from(i)\n assert a in actions, (a, actions)\n assert trafo.convert_to(a) == i\n actions = list(filter(lambda x: x != a, list(actions)))\n assert len(actions) == 0\n\n # same test for binary\n md = MultiBinary(3)\n trafo = flatten(md)\n\n assert trafo.target == Discrete(2**3)\n # check that we get all actions exactly once\n actions = []\n for (i, j, k) in itertools.product([0, 1], [0, 1], [0, 1]):\n actions += [(i, j, k)]\n for i in range(0, 8):\n a = trafo.convert_from(i)\n assert trafo.convert_to(a) == i\n assert a in actions, (a, actions)\n actions = list(filter(lambda x: x != a, actions))\n assert len(actions) == 0\n\ndef test_flatten_continuous():\n ct = Box(np.zeros((2,2)), np.ones((2, 2)))\n trafo = flatten(ct)\n\n assert trafo.target == Box(np.zeros(4), np.ones(4))\n check_convert(trafo, [1, 2, 3, 4], [[1, 2], [3, 4]])\n\n# rescale\ndef test_rescale_discrete():\n for s in [Discrete(10), MultiDiscrete([(0, 2), (0, 3)]), MultiBinary(5)]:\n try:\n rescale(s, 1.0)\n assert False \n except TypeError: pass\n\ndef test_rescale_box():\n s = Box(np.array([0.0, 1.0]), np.array([1.0, 2.0]))\n trafo = rescale(s, np.array([1.0, 0.0]), np.array([2.0, 1.0]))\n\n assert trafo.target == Box(np.array([1.0, 0.0]), np.array([2.0, 1.0]))\n check_convert(trafo, [1.0, 0.0], [0.0, 1.0])\n check_convert(trafo, [2.0, 1.0], [1.0, 2.0])\n\n # scalar rescale\n s = Box(np.array([0.0, 1.0]), np.array([1.0, 2.0]))\n trafo = rescale(s, 0.0, 1.0)\n\n assert trafo.target == Box(np.array([0.0, 0.0]), np.array([1.0, 1.0]))\n\n\nif __name__ == '__main__':\n test_discretize_1d_box()\n test_discretize_discrete()\n test_discretize_nd_box()\n\n test_flatten_single()\n test_flatten_discrete()\n test_flatten_continuous()\n\n test_rescale_discrete()\n test_rescale_box()\n\n","sub_path":"space_wrappers/tests/test_transform.py","file_name":"test_transform.py","file_ext":"py","file_size_in_byte":3674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"96656037","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pymongo,os,sys\n\nsys.path.append(os.path.dirname(os.path.split(os.path.realpath(__file__))[0]))\n\nfrom conf.settings import DB_MUSICMAGV2\n\nclass ChannelBriefInfos(object):\n '''\n channel_brief_infos\n '''\n def __init__(self, json):\n self.channel_brief_info_id = ''\n self.channel_brief_info_content = ''\n self.channel_brief_info_title = ''\n self.channel_brief_info_type = '' ##\n self.channel_brief_info_date = ''\n self.special = 'False'\n self.resources_ids = []\n self.source_url = ''\n self.content_from = ''\n self.author = ''\n self.ymd = ''\n self.resourcetype = '' ##\n\n self.generate_fields(json)\n\n def find_channel_brief_info_type_from_resources_ids(self, resources_ids):\n type = 'text'\n for resources in resources_ids:\n if resources.get('resource_info_type','') != 1:#不是文字\n type = 'img'\n break\n return type\n\n def find_channel_brief_info_type(self, json):\n channel_brief_info_type = 1\n resources_ids = json.get('resources_ids','')\n if resources_ids:\n for resources in resources_ids:\n if resources.get('resource_info_type','') != 1:#不是文字\n channel_brief_info_type = 2\n break\n return channel_brief_info_type\n\n def find_resourcetype(self,json):\n '''\n not sure\n '''\n resource_type = 'text'\n resources_ids = json.get('resources_ids','')\n for resources in resources_ids:\n if resources.get('resource_info_type','') != 1:#不是文字\n resource_type = 'img'\n break\n return resource_type\n\n def find_channel_brief_info_content(self, resources_ids):\n channel_brief_info_content = ''\n for resource in resources_ids: #设置channel_brief_info_content\n resourcetype = resource.get('resource_info_type','')\n if int(resourcetype) == 5 and resource.get('resource_info_content',''):\n channel_brief_info_content = resource.get('resource_info_content','')\n break\n return channel_brief_info_content\n\n def generate_fields(self, json):\n self.channel_brief_info_id = json.get('channel_brief_info_id','')\n resources_ids = []\n for resource in json.get('resources_ids',''): #清除空的内容\n if resource:\n resources_ids.append(resource)\n self.channel_brief_info_content = self.find_channel_brief_info_content(resources_ids)\n self.channel_brief_info_title = json.get('channel_brief_info_title','')\n self.channel_brief_info_type = self.find_channel_brief_info_type(json)\n self.channel_brief_info_date = json.get('channel_brief_info_date','')\n self.special = False\n #resources_ids = ResourcesIds(resources_ids)\n # for i in resources_ids:\n # i = ResourcesIds.field_completion(i)\n # i = ResourcesIds.delete_not_pic_field(i)\n self.resources_ids = ResourcesIds.generate_resources_ids_for_data_newbrief_collection_format(resources_ids)\n #self.resources_ids = resources_ids #经过处理后的resources_ids\n self.source_url = json.get('source_url','')\n self.content_from = json.get('content_from','')\n self.author = json.get('author','')\n self.ymd = self.generate_ymd(json.get('channel_brief_info_date'))\n #self.resourcetype = self.find_resourcetype(json)\n self.resourcetype = '' #设为空\n\n def data(self):\n data = {\n 'channel_brief_info_id':self.channel_brief_info_id,\n 'channel_brief_info_content':self.channel_brief_info_content,\n 'channel_brief_info_title':self.channel_brief_info_title,\n 'channel_brief_info_type':self.channel_brief_info_type,\n 'channel_brief_info_date':self.channel_brief_info_date,\n 'special':self.special,\n 'resources_ids':self.resources_ids,\n 'source_url':self.source_url,\n 'content_from':self.content_from,\n 'author':self.author,\n 'ymd':self.ymd,\n 'resourcetype':self.resourcetype\n }\n return data\n\n def generate_ymd(self, date_str):\n res = ''\n try:\n res = date_str.strip().split(' ')[0]\n except Exception as e:\n print (\"ERROR!! %s\"%str(e))\n return res\n\n\n\nclass ResourcesIds(object):\n '''\n resources_ids\n '''\n resource_field_ = ['resource_info_thumbnails_url',\n 'resource_info_ios_url',\n 'resource_info_normal_url',\n 'resource_info_android_url',\n 'resource_info_id',\n 'resource_info_content',\n 'resource_info_original_url',\n 'resource_info_url',\n 'resource_info_type'\n ]\n def __init__(self, json):\n self.resource_info_thumbnails_url = ''\n self.resource_info_ios_url = ''\n self.resource_info_normal_url = ''\n self.resource_info_android_url = ''\n self.resource_info_id = ''\n self.resource_info_content = ''\n self.resource_info_original_url = ''\n self.resource_info_url = ''\n self.resource_info_type = ''\n\n @staticmethod\n def field_completion(resource):\n for i in ResourcesIds.resource_field_:\n if i not in resource.keys():\n resource[i] = ''\n return resource\n\n @staticmethod\n def delete_not_pic_field(resources_ids): #去掉里面一层非图片的字段\n for i in resources_ids.keys():\n if i not in ['resource_info_type','resource_info_original_url','resource_info_id']:\n resources_ids[i] = ''\n return resources_ids\n\n @staticmethod\n def generate_resources_ids_for_data_newbrief_collection_format(resources_ids):\n '''\n 1 最多resources_ids只有9个\n 2 只有resource_info_type=1的情况存在\n '''\n res = []\n for resource in resources_ids:\n resource = ResourcesIds.field_completion(resource)\n if 'resource_info_type' in resource.keys() and int(resource['resource_info_type']) == 1:\n res.append(resource)\n res = res[:9]\n return res\n\nif __name__ == '__main__':\n a = {'resource_info_ios_url':'','resource_info_type':1}\n a = ResourcesIds.field_completion(a)\n a = ResourcesIds.field_completion(a)\n print (a)","sub_path":"model/jsons.py","file_name":"jsons.py","file_ext":"py","file_size_in_byte":6765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"65772506","text":"#! /usr/bin/env python3\n\nimport logging\nimport time\nimport zipfile\n\nimport requests\nimport us\n\n\nlogger = logging.getLogger(__file__)\nlogger.addHandler(logging.StreamHandler())\nlogger.setLevel(logging.INFO)\n\n# The Census download URLs are case-sensitive\nURL = 'https://www2.census.gov/geo/tiger/TIGER2018/SLD{chamber_uppercase}/tl_2018_{fips}_sld{chamber}.zip'\nMAX_ATTEMPTS = 3\nSECONDS_BEFORE_RETRY = 5\n\nfor state in us.STATES + [us.states.PR]:\n logger.info(\"Fetching shapefiles for {}\".format(state.name))\n\n for chamber in ['l', 'u']:\n fips = state.fips\n download_url = URL.format(fips=fips, chamber=chamber, chamber_uppercase=chamber.upper())\n\n attempts = 0\n while attempts < MAX_ATTEMPTS:\n response = requests.get(download_url)\n if response.status_code not in [500, 503]:\n break\n else:\n attempts += 1\n time.sleep(SECONDS_BEFORE_RETRY)\n\n if response.status_code == 200:\n filename = './data/tl_2018_{fips}_sld{chamber}.zip'.format(fips=fips, chamber=chamber)\n # This _could_ all be done with a single file operation,\n # by using a `BytesIO` file-like object to temporarily hold the\n # HTTP response. However, that's less readable and maintainable,\n # and a bit of delay isn't a problem given the slowness\n # of the Census downloads in the first place.\n with open(filename, 'wb') as f:\n f.write(response.content)\n with zipfile.ZipFile(filename, 'r') as f:\n f.extractall('./data')\n elif (response.status_code == 404 and state.abbr == 'DC' and chamber == 'l') or \\\n (response.status_code == 404 and state.abbr == 'NE' and chamber == 'l'):\n # These chambers are non-existant, and a `404` is expected\n pass\n else:\n response.raise_for_status()\n","sub_path":"get-all-sld-shapefiles.py","file_name":"get-all-sld-shapefiles.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"27815438","text":"# pylint: disable=unused-import, wrong-import-position\n# -*- coding: utf-8 -*-\n#\n# ramstk.views.gtk3.requirement.__init__.py is part of The RAMSTK Project\n#\n# All rights reserved.\n# Copyright 2020 Doyle Rowland doyle.rowland reliaqual com\n\"\"\"The RAMSTK GTK3 revision package.\"\"\"\n\nATTRIBUTE_KEYS = {\n 2: ['derived', 'integer'],\n 3: ['description', 'string'],\n 4: ['figure_number', 'string'],\n 5: ['owner', 'integer'],\n 6: ['page_number', 'string'],\n 8: ['priority', 'integer'],\n 10: ['specification', 'string'],\n 11: ['requirement_type', 'integer'],\n 12: ['validated', 'integer'],\n 13: ['validated_date', 'string'],\n}\n\n# RAMSTK Local Imports\nfrom .moduleview import ModuleView as mvwRequirement\nfrom .workview import GeneralData as wvwRequirementGD\nfrom .workview import RequirementAnalysis as wvwRequirementAnalysis\n","sub_path":"src/ramstk/views/gtk3/requirement/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"527421929","text":"import os, time, random\nimport queue\n\nclass filededuplication :\n # 사용할 소수 ( 소수 크기가 크면 클 수록 정확도 상승 )\n prime_number = 1048583\n # 윈도우 크기\n window_size = 1 << 8\n # 확률(p = 1 / 2 ** 2 )\n last_mask = (1 << 8) - 1\n # 수가 커지는 것을 방지하기 위한 상수\n end_subset = (1 << 32) - 1\n # 소수를 저장( 계산을 빠르게 하기 위한 작업 )\n save_prime = (prime_number ** (window_size - 1)) & end_subset\n # 샘플링 확률\n r = 1.0\n\n def __init__(self) :\n while True :\n self.target_dir = os.path.normpath(input(\"Directory path : \"))\n if not os.path.exists(self.target_dir) :\n print(\"The path does not exist. Please check the path and re-enter.\")\n elif not os.path.isdir(self.target_dir) :\n print(\"It is not a directory. Please enter the correct directory path.\")\n else :\n break\n def run(self) :\n start_time = time.time()\n self.file_dic = {}\n for path, dir, files in os.walk(self.target_dir):\n for file_name in files :\n self.set_fingerprint(path + \"\\\\\" + file_name)\n\n for from_file_name, from_file_finger_print in sorted(self.file_dic.items()):\n for to_file_name, to_file_finger_print in sorted(self.file_dic.items()):\n # 이미 검사한 파일인 경우\n if from_file_name >= to_file_name:\n continue\n intersection_size = len(from_file_finger_print & to_file_finger_print)\n #jaccard_similarity = (sampled_intersection_size / self.r) / (len(from_file_finger_print) + len(to_file_finger_print) - (sampled_intersection_size / r))\n jaccard_similarity = len(from_file_finger_print & to_file_finger_print) / len(from_file_finger_print | to_file_finger_print)\n print(\"Chunk Count : %d %d\" % (len(from_file_finger_print), len(to_file_finger_print)))\n print(\"%s 과 %s 는 %.2f %% 유사합니다.\" % (from_file_name, to_file_name, jaccard_similarity * 100))\n end_time = time.time()\n print(\"걸린시간 : %d\" % (end_time - start_time))\n def set_fingerprint(self, file_path ):\n fingerprint_set = set()\n file_size = os.path.getsize(file_path)\n #count_of_signature = int((file_size - self.window_size) * self.p * self.r)\n q = queue.Queue()\n q.put((0, file_size - self.window_size));\n f = open(file_path, 'rb')\n while not q.empty() :\n p = q.get()\n if p[1] - p[0] < self.window_size :\n continue\n m = random.randint(p[0], p[1])\n e = self.insert_fingerprint(f, m, p[1], fingerprint_set)\n q.put((p[0], max(m - self.window_size, e - self.window_size)))\n q.put((e +self.window_size, p[1]))\n self.file_dic[file_path] = fingerprint_set\n\n def insert_fingerprint(self, f, start, end, fingerprint_set) :\n f.seek(start)\n file_point = start\n slicing_window = bytearray(f.read(self.window_size))\n current_chunk = 0\n previous_chunk = 0\n for each_byte in slicing_window:\n current_chunk *= self.prime_number\n current_chunk += each_byte\n current_chunk &= self.end_subset\n while(file_point < end) :\n if current_chunk & self.last_mask == 0 :\n fingerprint_set.add(current_chunk)\n break\n buf = f.read(1)\n file_point += 1\n previous_chunk = current_chunk\n current_chunk = (previous_chunk - slicing_window[0] * self.save_prime) * self.prime_number + buf[0]\n if current_chunk < 0 :\n current_chunk += self.end_subset + 1\n current_chunk &= self.end_subset\n slicing_window.pop(0)\n slicing_window.append(buf[0])\n return file_point\n\n","sub_path":"File Deduplication/filededuplication.py","file_name":"filededuplication.py","file_ext":"py","file_size_in_byte":3973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"397284598","text":"from dataclasses import dataclass\nfrom sys import float_info\nfrom typing import Optional, Union\n\nimport bpy\nfrom bpy.app.translations import pgettext\n\nfrom ..common.logging import get_logger\n\nlogger = get_logger(__name__)\n\nMESH_CONVERTIBLE_OBJECT_TYPES = [\n \"CURVE\",\n \"FONT\",\n \"MESH\",\n # \"META\", # Disable until the glTF 2.0 add-on supports it\n \"SURFACE\",\n]\n\n\ndef export_materials(objects: list[bpy.types.Object]) -> list[bpy.types.Material]:\n result = []\n for obj in objects:\n if obj.type not in MESH_CONVERTIBLE_OBJECT_TYPES:\n continue\n\n mesh_convertible = obj.data\n if isinstance(mesh_convertible, (bpy.types.Curve, bpy.types.Mesh)):\n for material_ref in mesh_convertible.materials:\n if not isinstance(material_ref, bpy.types.Material):\n continue\n material = bpy.data.materials.get(material_ref.name)\n if not isinstance(material, bpy.types.Material):\n continue\n if material not in result:\n result.append(material)\n else:\n logger.error(\n f\"Unexpected mesh convertible object type: {type(mesh_convertible)}\"\n )\n\n for material_slot in obj.material_slots:\n if not material_slot:\n continue\n material_ref = material_slot.material\n if not material_ref:\n continue\n material = bpy.data.materials.get(material_ref.name)\n if not isinstance(material, bpy.types.Material):\n continue\n if material not in result:\n result.append(material)\n\n return result\n\n\ndef vrm_shader_node(material: bpy.types.Material) -> Optional[bpy.types.Node]:\n if not material.node_tree or not material.node_tree.nodes:\n return None\n for node in material.node_tree.nodes:\n if (\n node.type == \"OUTPUT_MATERIAL\"\n and node.inputs[\"Surface\"].links\n and node.inputs[\"Surface\"].links[0].from_node.type == \"GROUP\"\n and node.inputs[\"Surface\"].links[0].from_node.node_tree.get(\"SHADER\")\n is not None\n ):\n return node.inputs[\"Surface\"].links[0].from_node\n return None\n\n\ndef shader_nodes_and_materials(\n materials: list[bpy.types.Material],\n) -> list[tuple[bpy.types.Node, bpy.types.Material]]:\n result = []\n for material in materials:\n node = vrm_shader_node(material)\n if node:\n result.append((node, material))\n return result\n\n\ndef object_distance(\n left: bpy.types.Object,\n right: bpy.types.Object,\n collection_child_to_parent: dict[\n bpy.types.Collection, Optional[bpy.types.Collection]\n ],\n) -> tuple[int, int, int, int]:\n left_collection_path: list[bpy.types.Collection] = []\n left_collections = [\n collection\n for collection in left.users_collection\n if collection in collection_child_to_parent\n ]\n if left_collections:\n left_collection = left_collections[0]\n while left_collection:\n left_collection_path.insert(0, left_collection)\n left_collection = collection_child_to_parent.get(left_collection)\n\n right_collection_path: list[bpy.types.Collection] = []\n right_collections = [\n collection\n for collection in right.users_collection\n if collection in collection_child_to_parent\n ]\n if right_collections:\n right_collection = right_collections[0]\n while right_collection:\n right_collection_path.insert(0, right_collection)\n right_collection = collection_child_to_parent.get(right_collection)\n\n while (\n left_collection_path\n and right_collection_path\n and left_collection_path[0] == right_collection_path[0]\n ):\n left_collection_path.pop(0)\n right_collection_path.pop(0)\n\n left_parent_path: list[bpy.types.Object] = []\n while left:\n left_parent_path.insert(0, left)\n left = left.parent\n\n right_parent_path: list[bpy.types.Object] = []\n while right:\n right_parent_path.insert(0, right)\n right = right.parent\n\n while (\n left_parent_path\n and right_parent_path\n and left_parent_path[0] == right_parent_path[0]\n ):\n left_parent_path.pop(0)\n right_parent_path.pop(0)\n\n return (\n len(left_parent_path),\n len(right_parent_path),\n len(left_collection_path),\n len(right_collection_path),\n )\n\n\ndef armature_exists(context: bpy.types.Object) -> bool:\n return any(armature.users for armature in bpy.data.armatures) and any(\n obj.type == \"ARMATURE\" for obj in context.blend_data.objects\n )\n\n\ndef current_armature_is_vrm0(context: bpy.types.Context) -> bool:\n live_armature_datum = [\n armature_data for armature_data in bpy.data.armatures if armature_data.users\n ]\n if not live_armature_datum:\n return False\n if all(\n hasattr(armature_data, \"vrm_addon_extension\")\n and armature_data.vrm_addon_extension.is_vrm0()\n for armature_data in live_armature_datum\n ) and any(obj.type == \"ARMATURE\" for obj in context.blend_data.objects):\n return True\n armature = current_armature(context)\n if armature is None:\n return False\n return bool(armature.data.vrm_addon_extension.is_vrm0())\n\n\ndef current_armature_is_vrm1(context: bpy.types.Context) -> bool:\n live_armature_datum = [\n armature_data for armature_data in bpy.data.armatures if armature_data.users\n ]\n if not live_armature_datum:\n return False\n if all(\n hasattr(armature_data, \"vrm_addon_extension\")\n and armature_data.vrm_addon_extension.is_vrm1()\n for armature_data in live_armature_datum\n ) and any(obj.type == \"ARMATURE\" for obj in context.blend_data.objects):\n return True\n armature = current_armature(context)\n if armature is None:\n return False\n return bool(armature.data.vrm_addon_extension.is_vrm1())\n\n\ndef multiple_armatures_exist(context: bpy.types.Object) -> bool:\n first_data_exists = False\n for data in bpy.data.armatures:\n if not data.users:\n continue\n if not first_data_exists:\n first_data_exists = True\n continue\n\n first_obj_exists = False\n for obj in context.blend_data.objects:\n if obj.type == \"ARMATURE\":\n if first_obj_exists:\n return True\n first_obj_exists = True\n break\n return False\n\n\ndef current_armature(context: bpy.types.Context) -> Optional[bpy.types.Object]:\n objects = [obj for obj in context.blend_data.objects if obj.type == \"ARMATURE\"]\n if not objects:\n return None\n\n if len(objects) == 1:\n return objects[0]\n\n active_object = context.active_object\n if not active_object:\n active_object = context.view_layer.objects.active\n if not active_object:\n return objects[0]\n\n collection_child_to_parent: dict[\n bpy.types.Collection, Optional[bpy.types.Collection]\n ] = {context.scene.collection: None}\n\n collections = [context.scene.collection]\n while collections:\n parent = collections.pop()\n for child in parent.children:\n collections.append(child)\n collection_child_to_parent[child] = parent\n\n min_distance: Optional[tuple[int, int, int, int]] = None\n nearest_object: Optional[bpy.types.Object] = None\n for obj in objects:\n distance = object_distance(active_object, obj, collection_child_to_parent)\n if min_distance is None or min_distance > distance:\n min_distance = distance\n nearest_object = obj\n\n return objects[0] if nearest_object is None else nearest_object\n\n\ndef export_objects(\n context: bpy.types.Context,\n export_invisibles: bool,\n export_only_selections: bool,\n armature_object_name: Optional[str],\n) -> list[bpy.types.Object]:\n selected_objects = []\n if export_only_selections:\n selected_objects = list(context.selected_objects)\n elif export_invisibles:\n selected_objects = list(context.blend_data.objects)\n else:\n selected_objects = list(context.selectable_objects)\n\n objects = []\n\n armature_object = None\n if armature_object_name:\n armature_object = context.blend_data.objects.get(armature_object_name)\n if armature_object and armature_object.name in context.view_layer.objects:\n objects.append(armature_object)\n else:\n armature_object = None\n if not armature_object:\n objects.extend(\n obj\n for obj in context.blend_data.objects\n if obj.type == \"ARMATURE\" and obj.name in context.view_layer.objects\n )\n\n for obj in selected_objects:\n if obj.type in [\"ARMATURE\", \"LIGHT\", \"CAMERA\"]:\n continue\n if obj.name not in context.view_layer.objects:\n continue\n if not export_invisibles and not obj.visible_get():\n continue\n objects.append(obj)\n\n return objects\n\n\n@dataclass(frozen=True)\nclass ExportConstraint:\n roll_constraints: dict[str, bpy.types.CopyRotationConstraint]\n aim_constraints: dict[str, bpy.types.DampedTrackConstraint]\n rotation_constraints: dict[str, bpy.types.CopyRotationConstraint]\n\n\ndef is_roll_constraint(\n constraint: bpy.types.Constraint,\n objs: list[bpy.types.Object],\n armature: bpy.types.Object,\n) -> bool:\n return (\n isinstance(constraint, bpy.types.CopyRotationConstraint)\n and constraint.is_valid\n and not constraint.mute\n and constraint.target\n and constraint.target in objs\n and constraint.mix_mode == \"ADD\"\n and (int(constraint.use_x) + int(constraint.use_y) + int(constraint.use_z)) == 1\n and constraint.owner_space == \"LOCAL\"\n and constraint.target_space == \"LOCAL\"\n and (\n constraint.target.type != \"ARMATURE\"\n or (\n constraint.target == armature\n and constraint.subtarget in constraint.target.data.bones\n )\n )\n )\n\n\ndef is_aim_constraint(\n constraint: bpy.types.Constraint,\n objs: list[bpy.types.Object],\n armature: bpy.types.Object,\n) -> bool:\n return (\n isinstance(constraint, bpy.types.DampedTrackConstraint)\n and constraint.is_valid\n and not constraint.mute\n and constraint.target\n and constraint.target in objs\n and (\n constraint.target.type != \"ARMATURE\"\n or (\n constraint.target == armature\n and constraint.subtarget in constraint.target.data.bones\n and abs(constraint.head_tail) < float_info.epsilon\n )\n )\n )\n\n\ndef is_rotation_constraint(\n constraint: bpy.types.Constraint,\n objs: list[bpy.types.Object],\n armature: bpy.types.Object,\n) -> bool:\n return (\n isinstance(constraint, bpy.types.CopyRotationConstraint)\n and constraint.is_valid\n and not constraint.mute\n and constraint.target\n and constraint.target in objs\n and not constraint.invert_x\n and not constraint.invert_y\n and not constraint.invert_z\n and constraint.mix_mode == \"ADD\"\n and constraint.use_x\n and constraint.use_y\n and constraint.use_z\n and constraint.owner_space == \"LOCAL\"\n and constraint.target_space == \"LOCAL\"\n and (\n constraint.target.type != \"ARMATURE\"\n or (\n constraint.target == armature\n and constraint.subtarget in constraint.target.data.bones\n )\n )\n )\n\n\ndef export_object_constraints(\n objs: list[bpy.types.Object],\n armature: bpy.types.Object,\n) -> ExportConstraint:\n roll_constraints: dict[str, bpy.types.CopyRotationConstraint] = {}\n aim_constraints: dict[str, bpy.types.DampedTrackConstraint] = {}\n rotation_constraints: dict[str, bpy.types.CopyRotationConstraint] = {}\n\n for obj in objs:\n for constraint in obj.constraints:\n if is_roll_constraint(constraint, objs, armature):\n roll_constraints[obj.name] = constraint\n break\n if is_aim_constraint(constraint, objs, armature):\n aim_constraints[obj.name] = constraint\n break\n if is_rotation_constraint(constraint, objs, armature):\n rotation_constraints[obj.name] = constraint\n break\n\n return ExportConstraint(\n roll_constraints=roll_constraints,\n aim_constraints=aim_constraints,\n rotation_constraints=rotation_constraints,\n )\n\n\ndef export_bone_constraints(\n objs: list[bpy.types.Object],\n armature: bpy.types.Object,\n) -> ExportConstraint:\n roll_constraints: dict[str, bpy.types.CopyRotationConstraint] = {}\n aim_constraints: dict[str, bpy.types.DampedTrackConstraint] = {}\n rotation_constraints: dict[str, bpy.types.CopyRotationConstraint] = {}\n\n for bone in armature.pose.bones:\n for constraint in bone.constraints:\n if is_roll_constraint(constraint, objs, armature):\n roll_constraints[bone.name] = constraint\n break\n if is_aim_constraint(constraint, objs, armature):\n aim_constraints[bone.name] = constraint\n break\n if is_rotation_constraint(constraint, objs, armature):\n rotation_constraints[bone.name] = constraint\n break\n\n return ExportConstraint(\n roll_constraints=roll_constraints,\n aim_constraints=aim_constraints,\n rotation_constraints=rotation_constraints,\n )\n\n\ndef export_constraints(\n objs: list[bpy.types.Object],\n armature: bpy.types.Object,\n) -> tuple[ExportConstraint, ExportConstraint, list[str]]:\n messages: list[str] = []\n object_constraints = export_object_constraints(objs, armature)\n bone_constraints = export_bone_constraints(objs, armature)\n\n all_roll_constraints = list(object_constraints.roll_constraints.values()) + list(\n bone_constraints.roll_constraints.values()\n )\n all_rotation_constraints = list(\n object_constraints.rotation_constraints.values()\n ) + list(bone_constraints.rotation_constraints.values())\n all_constraints: list[bpy.types.CopyRotationConstraint] = (\n all_roll_constraints\n + all_rotation_constraints\n # TODO: Aim Constraint's circular dependency detection\n # + list(object_constraints.aim_constraints.values())\n # + list(bone_constraints.aim_constraints.values())\n )\n\n excluded_constraints: list[\n Union[\n bpy.types.CopyRotationConstraint,\n bpy.types.DampedTrackConstraint,\n bpy.types.CopyRotationConstraint,\n ]\n ] = []\n\n for search_constraint in all_constraints:\n current_constraints = [\n (\n search_constraint,\n (\n search_constraint.use_x,\n search_constraint.use_y,\n search_constraint.use_z,\n ),\n )\n ]\n iterated_constraints = set()\n while current_constraints:\n current_constraint, current_axis = current_constraints.pop()\n\n if current_constraint in iterated_constraints:\n break\n iterated_constraints.add(current_constraint)\n\n found = False\n\n if current_constraint.target.type == \"ARMATURE\":\n bone = current_constraint.target.pose.bones[\n current_constraint.subtarget\n ]\n owner_name = bone.name\n target_constraints = bone.constraints\n else:\n owner_name = current_constraint.target.name\n target_constraints = current_constraint.target.constraints\n\n for target_constraint in target_constraints:\n if target_constraint not in all_constraints:\n continue\n\n next_target_axis = (\n current_axis[0] and target_constraint.use_x,\n current_axis[1] and target_constraint.use_y,\n current_axis[2] and target_constraint.use_z,\n )\n if next_target_axis == (False, False, False):\n continue\n\n if target_constraint != search_constraint:\n current_constraints.append((target_constraint, next_target_axis))\n continue\n\n excluded_constraints.append(search_constraint)\n messages.append(\n pgettext(\n 'Node Constraint \"{owner_name} / {constraint_name}\" has a circular dependency'\n ).format(\n owner_name=owner_name,\n constraint_name=search_constraint.name,\n )\n )\n found = True\n break\n\n if found:\n break\n\n return (\n ExportConstraint(\n roll_constraints={\n k: v\n for k, v in object_constraints.roll_constraints.items()\n if v not in excluded_constraints\n },\n aim_constraints={\n k: v\n for k, v in object_constraints.aim_constraints.items()\n if v not in excluded_constraints\n },\n rotation_constraints={\n k: v\n for k, v in object_constraints.rotation_constraints.items()\n if v not in excluded_constraints\n },\n ),\n ExportConstraint(\n roll_constraints={\n k: v\n for k, v in bone_constraints.roll_constraints.items()\n if v not in excluded_constraints\n },\n aim_constraints={\n k: v\n for k, v in bone_constraints.aim_constraints.items()\n if v not in excluded_constraints\n },\n rotation_constraints={\n k: v\n for k, v in bone_constraints.rotation_constraints.items()\n if v not in excluded_constraints\n },\n ),\n messages,\n )\n","sub_path":"addons/VRM_Addon_for_Blender-2_17_7/editor/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":18406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"277579188","text":"# import libraries\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport mdtraj as md\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom msmbuilder import dataset\n\nimport seaborn as sns\nsns.set_style(\"whitegrid\")\nsns.set_context(\"poster\")\n\n# load trajectories\nSrc_trajectories = dataset.MDTrajDataset(\"/cbio/jclab/projects/fah/fah-data/munged/no-solvent/10471/*.h5\")\n\n# import 2SRC structure to compare to\nSRC2 = md.load(\"SRC_2SRC_A.pdb\")\n\n# Define hydrogen bond coordinates (0-indexed)\nKER_src = [[28,43],[43,142]]\n\n# Define Activation loop (resid)\nAloop_src = [138,158]\n\ndef shukla_coords(trajectories,KER,Aloop,SRC2):\n\n difference = []\n rmsd = []\n\n for traj in trajectories:\n\n # append difference\n k295e310 = md.compute_contacts(traj, [KER[0]])\n e310r409 = md.compute_contacts(traj, [KER[1]])\n difference.append(10*(e310r409[0] - k295e310[0])) # 10x because mdtraj is naturally in nm\n\n # append rmsd\n Activation_Loop_SRC2 = SRC2.top.select(\"backbone and (resid %s to %s)\" %(138,158))\n Activation_Loop_kinase = traj.top.select(\"backbone and (resid %s to %s)\" %(Aloop[0],Aloop[1]))\n\n SRC2_cut = SRC2.atom_slice(Activation_Loop_SRC2)\n traj_cut = traj.atom_slice(Activation_Loop_kinase)\n\n rmsd.append(10*(md.rmsd(traj_cut,SRC2_cut,frame=0))) # 10x because mdtraj is naturaly in nm\n\n # flatten list of arrays\n flattened_difference = np.asarray([val for sublist in difference for val in sublist])\n flattened_rmsd = np.asarray([val for sublist in rmsd for val in sublist])\n\n return [flattened_rmsd, flattened_difference]\n\n# generate data\n[rmsd_src,difference_src] = shukla_coords(Src_trajectories,KER_src,Aloop_src,SRC2)\n\n#save rmsd and difference data\nnp.save('rmsd_src.npy',rmsd_src)\nnp.save('difference_src.npy',difference_src)\n\n#plot\nsns.kdeplot(rmsd_src,difference_src[:,0],shade=True,log=True,cmap=\"Reds\",shade_lowest=False)\n\nplt.xlabel('RMSD Activation Loop ($\\AA$)')\nplt.ylabel('d(E310-R409) - d(K295-E310) ($\\AA$)')\nplt.ylim(-20,20)\nplt.xlim(0,10)\nplt.title('Src sims - 10471')\n\nplt.savefig('plotting_Shukla_fig2_Src_10471.png',dpi=1000)\n","sub_path":"other-reaction-coords/Shukla-Fig2/plotting_Shukla_fig2_Src_10471.py","file_name":"plotting_Shukla_fig2_Src_10471.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"254672799","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Oct 20 17:29:30 2018\r\n\r\n@author: Ivana-ETF\r\n\"\"\"\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport argparse\r\nimport requests\r\nfrom HTMLTable import * \r\nimport sys\r\n\r\n \r\n\r\ndef get_table(url, sport, element, iid, index, clas):\r\n \r\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)'\r\n ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95'\r\n ' Safari/537.36'}\r\n res = requests.get(url, headers=headers)\r\n plain_text = res.text \r\n soup = BeautifulSoup(plain_text, 'html.parser')\r\n table = soup.find_all('table')\r\n \r\n # Check if there are tables on the page\r\n if len(table):\r\n # Check which html element is selected\r\n if element == \"table\":\r\n if iid or clas :\r\n attr = 'id' if iid else 'class'\r\n val = iid if iid else clas\r\n b = 0\r\n for i in range(len(table)):\r\n try:\r\n pom = table[i][attr]\r\n except:\r\n print('There is no element {}'.format(val))\r\n exit()\r\n else:\r\n if isinstance(pom, list):\r\n pom=','.join(pom)\r\n if pom == val:\r\n b += 1\r\n parse(table[i], sport, element, iid, index, clas)\r\n\r\n if not b:\r\n print('There is no attribute {} with value {}'\r\n .format(attr, val)) \r\n else:\r\n if int(index) in range(len(table)):\r\n parse(table[int(index)], sport, element, iid, index, clas)\r\n else:\r\n print('There is no table with index {}'\r\n .format(str(index))) \r\n \r\n else:\r\n parse(table[0], sport, element, iid, index, clas)\r\n else:\r\n b = 0\r\n for s in soup.find_all(\"div\"):\r\n if s.find('iframe'):\r\n b += 1\r\n iframe_url = s.find('iframe')['src']\r\n get_table(iframe_url, sport, element, iid, index, clas)\r\n if not b:\r\n print('There is no table and iframe on the page')\r\n \r\ndef parse_args(args):\r\n \r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"url\", help=\"choose the Staff Directory page URL to \"\r\n \"be scraped\")\r\n parser.add_argument(\"sport\", help=\"choose sport to be filtered\")\r\n parser.add_argument(\"--html_elem\", help=\"choose html element\",\\\r\n choices=['table','tr','td'])\r\n group = parser.add_mutually_exclusive_group()\r\n group.add_argument('--element_id')\r\n group.add_argument('--element_index')\r\n group.add_argument('--element_class')\r\n \r\n return parser.parse_args(args) \r\n \r\ndef Main():\r\n\r\n parser = parse_args(sys.argv[1:])\r\n if (parser.html_elem and parser.element_id is None \r\n and parser.element_index is None and parser.element_class is None):\r\n print('--html_elem requires --element_id or --element_index ' \r\n 'or --element_class')\r\n exit()\r\n \r\n get_table(parser.url, parser.sport, parser.html_elem, parser.element_id, \r\n parser.element_index, parser.element_class)\r\n \r\n\r\nif __name__=='__main__':\r\n Main()\r\n \r\n \r\n\r\n\r\n","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"73648089","text":"import pickle\nimport numpy as np\nfrom pathlib import Path\nfrom V_ProcessAudioFile import processSong\nfrom C_1 import Samples_to_Peaks\nfrom e_peaksToDict import peaks_to_fp\n\ndef make_dict(pathName):\n '''\n Creates a dictionary of nearest neighbor values.\n\n This function takes in a path to a folder and\n creates a pickle file containing a dictionary\n of neighbors. It also returns the dictionary.\n\n Parameters:\n -----------\n pathName: Valid string representing a path to a folder\n The folder which the songs will be taken out of (in MP3 format)\n \n Returns:\n --------\n Dictionary{Tuple[int, int, int], List[Tuple[int, int]]}\n A dictionary containing all of the nearest neighbor pairs.\n '''\n res = {}\n res2 = {}\n pathList = Path(pathName).glob('*.mp3')\n cnt = 0\n for fileName in pathList:\n fileStr = str(fileName)\n digSamp = processSong(fileStr)\n peaks = Samples_to_Peaks(digSamp)\n res = peaks_to_fp(peaks, cnt, res)\n res2[cnt] = fileName.stem\n cnt = cnt+1\n\n pickle_out = open(\"database.pickle\", \"wb\")\n pickle.dump(res, pickle_out)\n pickle_out.close()\n pickle_out2 = open(\"codeToSong.pickle\", \"wb\")\n pickle.dump(res2, pickle_out2)\n pickle_out2.close()\n\n return res, res2","sub_path":"e_makeDict.py","file_name":"e_makeDict.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"444875727","text":"# coding = utf-8\n\"\"\"\n@Author: Idiot\n@Time: 2019/7/23 20:21\n@Software: PyCharm\n@File: lesson65.py\n@Version: V1.0\n@Desc: HTTP头部信息模拟\n\"\"\"\n\"\"\"\n有时候,我们在向网站发出请求时,会受到回应,请求被拒绝。\n因为网站为了防止用户的恶意获取数据,增加了一个验证,这里的验证主要是发送请求的工具是否为标准的浏览器\n使用urllib请求,和使用浏览器进行请求,是有一些差别的。\n差别在HTTP协议中叫做:HTTP头部信息\n\"\"\"\n\"\"\"\n先看下post请求的信息:\n{\n \"args\": {}, \n \"data\": \"\", \n \"files\": {}, \n \"form\": {\n \"word\": \"hello\"\n }, \n \"headers\": {\n \"Accept-Encoding\": \"identity\", \n \"Content-Length\": \"10\", \n \"Content-Type\": \"application/x-www-form-urlencoded\", \n \"Host\": \"httpbin.org\", \n \"User-Agent\": \"Python-urllib/3.7\" 此处就是说明请求的工具是Python\n }, \n \"json\": null, \n \"origin\": \"113.140.23.177, 113.140.23.177\", \n \"url\": \"https://httpbin.org/post\"\n}\n\"\"\"\n\"\"\"\n而使用浏览器请求的数据:\n{\n \"args\": {\n \"a\": \"123\", \n \"b\": \"456\"\n }, \n \"headers\": {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\", \n \"Accept-Encoding\": \"gzip, deflate\", \n \"Accept-Language\": \"zh-CN,zh;q=0.9,en;q=0.8\", \n \"Host\": \"httpbin.org\", \n \"Upgrade-Insecure-Requests\": \"1\", \n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36\"\n }, # 从这里就能看出,这是使用浏览器来请求的\n \"origin\": \"113.140.23.177, 113.140.23.177\", \n \"url\": \"https://httpbin.org/get?a=123&b=456\"\n}\n\"\"\"\n# 那么,如何更换User-Agent,来绕开服务器的检测\n# 这些信息怎么通过urllib传给服务器\n\nfrom urllib import request, parse\n\n# 请求仍为POST方式\nurl = 'http://httpbin.org/post'\nheaders = {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9,en;q=0.8\",\n \"Host\": \"httpbin.org\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36\"\n}\n# 如何将上面的header通过urllib传输给服务器?\ndict = {\n 'name': 'value'\n}\ndata = bytes(parse.urlencode(dict), encoding='utf8')\n# 在Request中加上一个headers,把字典进行重新编码,而且把字符集编排为utf-8\n# 最后将数据变成网页的字节型\nreq = request.Request(url=url, data=data, headers=headers, method='POST')\nresponse = request.urlopen(req)\nprint(response.read().decode('utf-8'))\n# 这里存在问题,无法正常运行\n","sub_path":"Section11/lesson65/lesson65.py","file_name":"lesson65.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"228029649","text":"from tkinter import Tk, Label, Frame, Button, LEFT, Y\nfrom PIL import Image, ImageTk\nfrom os import path\nfrom random import randint\n\n\nclass FieldTile:\n def __init__(self, name, size):\n resources_folder = path.realpath(path.dirname(__file__) + '/resources')\n self._image_path = resources_folder + f'/{name}.png'\n self.normal\n self.size = size\n\n self.taken = [None for _ in range(10)]\n\n @property\n def rgba(self):\n self.image = Image.open(self._image_path).convert('RGBA')\n return self\n\n @property\n def normal(self):\n self.image = Image.open(self._image_path)\n return self\n\n def take_img(self, i):\n if not self.taken[i]:\n taken_img = self.cut(i)\n taken_photo = ImageTk.PhotoImage(taken_img)\n self.taken[i] = taken_photo\n return taken_photo\n\n else:\n return self.taken[i]\n\n def cut(self, i):\n step = self.size\n xs = 1\n xe = self.size\n ys = (i - 1) * step\n ye = i * step\n taken = self.image.crop((xs, ys, xe, ye))\n\n return taken\n\n\nclass ViewFieldTiles:\n def __init__(self):\n self.aqua_ball = FieldTile('ball-aqua', 60)\n self.blue_ball = FieldTile('ball-blue', 60)\n self.green_ball = FieldTile('ball-green', 60)\n self.pink_ball = FieldTile('ball-pink', 60)\n self.red_ball = FieldTile('ball-red', 60)\n self.violet_ball = FieldTile('ball-violet', 60)\n self.yellow_ball = FieldTile('ball-yellow', 60)\n\n self.cell = FieldTile('cell-bgr', 69)\n self.page = FieldTile('page-bgr', 128)\n\n\ntiles = None\n\n\nclass Position:\n def __init__(self, x: int, y: int):\n self.x = x\n self.y = y\n\n\ndef differ(pos1, pos2):\n return Position(pos1.x - pos2.x, pos1.y - pos2.y)\n\n\nclass ViewFieldCell(Label):\n def __init__(self, master, row, col, field):\n self.ball_tile = None\n self.backed = None\n self.field: list[list[ViewFieldCell]] = field\n\n super().__init__(master, image=tiles.cell.take_img(1), borderwidth=0)\n self.grid(row=row, column=col)\n self.bind('', self.on_click)\n self.click_handler = None\n self.pos = Position(col, row)\n self.is_prev = False\n\n def put_ball(self, ball_tile: FieldTile):\n self.to_blend_bg_ball(1, ball_tile, 1)\n\n def select_ball(self):\n self.to_blend_bg_ball(2, self.ball_tile, 1)\n\n def unselect_ball(self):\n self.to_blend_bg_ball(1, self.ball_tile, 1)\n\n def to_blend_bg_ball(self, bg_tile_num, ball_tile, ball_tile_num):\n bg = tiles.cell.rgba.cut(bg_tile_num)\n ball = ball_tile.rgba.cut(ball_tile_num)\n new_ball = Image.new('RGBA', bg.size)\n new_ball.paste(ball, (7, 6))\n backed = Image.alpha_composite(bg, new_ball)\n backed_photo = ImageTk.PhotoImage(backed)\n self.backed = backed_photo\n self.ball_tile = ball_tile\n self.config(image=backed_photo)\n\n def clear(self):\n self.backed = None\n self.config(image=tiles.cell.take_img(1))\n\n def on_click(self, event):\n if self.click_handler:\n self.click_handler(self, event)\n\n @property\n def free(self):\n return not self.backed\n\n def sibling_in(self, direction: Position):\n rev_dir = Position(-direction.x, -direction.y)\n new_pos = differ(self.pos, rev_dir)\n if (new_pos.x < 0 or new_pos.y < 0 or\n new_pos.y > len(self.field) - 1 or new_pos.x > len(self.field[0]) - 1):\n return None\n return self.field[new_pos.y][new_pos.x]\n\n\nclass ViewGameInfo:\n def __init__(self, master):\n self.lines = Label(master, font=(\"Google Sans\", 20), bg='#454545', fg='#ffffff')\n self.lines.grid(row=1, column=1, columnspan=3, pady=10)\n self.score = Label(master, font=(\"Google Sans\", 20), bg='#454545', fg='#ffffff')\n self.score.grid(row=2, column=1, columnspan=3)\n self.update_lines(0)\n self.update_score(0)\n\n def update_lines(self, value):\n self.lines.config(text=f'Линии {value}')\n\n def update_score(self, value):\n self.score.config(text=f'Счёт: {value}')\n\n\nclass GameControls:\n def __init__(self, master):\n Label(master, height=1, bg='#454545').grid(row=3, column=1, columnspan=3)\n self.step = Button(master, text=\"Сделать ход\", font=(\"Google Sans\", 15), bg='#515156', fg='white', padx=2,\n pady=1, relief='raised')\n self.step.grid(row=6, column=1, columnspan=3, pady=10)\n self.new_game = Button(master, text=\"Новая игра\", font=(\"Google Sans\", 15), bg='#515156', fg='white', padx=2,\n pady=1, relief='raised')\n self.new_game.grid(row=10, column=1, columnspan=3, pady=10)\n\n\nclass GameHint(list):\n def __init__(self, master):\n super().__init__()\n Label(master, height=2, bg='#454545').grid(row=7, column=1, columnspan=3)\n Label(master, text='Подсказка:', font=(\"Google Sans\", 15), bg='#454545', fg='white').grid(row=7, column=1,\n columnspan=3, pady=4)\n self.model = []\n for i in range(3):\n self.append(Label(master, bg='#454545'))\n self.model.append(None)\n self[i].grid(row=9, column=1 + i)\n\n def update(self: list, three_balls: list):\n i = 0\n for ball in three_balls:\n self[i].config(image=ball.take_img(5))\n self.model[i] = ball\n i += 1\n\n\nclass GameInfo:\n def __init__(self, master):\n master.config(bg='#454545')\n self.controls = GameControls(master)\n self.hint = GameHint(master)\n self.info = ViewGameInfo(master)\n\n\nclass Interface:\n def __init__(self):\n global tiles\n\n self.root = Tk()\n self.root.title('Линии')\n width = 880\n height = 690\n screen_width = self.root.winfo_screenwidth()\n screen_height = self.root.winfo_screenheight()\n\n x_coordinate = int((screen_width / 2) - (width / 2))\n y_coordinate = int((screen_height / 2) - (height / 2))\n self.size = Position(width, height)\n self.root.geometry(\"{}x{}+{}+{}\".format(width, height, x_coordinate, y_coordinate))\n\n tiles = ViewFieldTiles()\n self.tiles = tiles\n\n self.root.config(bg='#454545')\n\n self.field_frame = Frame(self.root)\n self.field_frame.pack(side=LEFT)\n\n self.info_frame = Frame(self.root)\n self.info_frame.pack(side=LEFT, fill=Y)\n self.info = GameInfo(self.info_frame)\n\n self.field = []\n for row in range(10):\n self.field.append([])\n for col in range(10):\n cell = ViewFieldCell(self.field_frame, row, col, self.field)\n self.field[row].append(cell)\n\n self.game_over = Label(self.info_frame, fg='white', bg='#454545', text=\"Игра окончена\",\n font=(\"Google Sans\", 19), padx=2, pady=1)\n\n @property\n def game_over_visibility(self):\n pass\n\n @game_over_visibility.setter\n def game_over_visibility(self, visible: bool):\n if visible:\n self.game_over.grid(row=11, column=1, columnspan=3)\n else:\n self.game_over.grid_forget()\n\n def render(self):\n self.root.mainloop()\n\n\nclass ModelField(list):\n def __init__(self, field: list):\n super().__init__()\n self.field = field\n\n size = len(field)\n\n def get_square_dialog(square_shift_x, square_shift_y, square_size, reverse=False):\n nonlocal field\n\n dialog = []\n for j in range(square_size):\n if not reverse:\n zx = j\n zy = j\n else:\n zx = square_size - 1 - j\n zy = j\n dialog.append(field[square_shift_y + zy][square_shift_x + zx])\n\n return dialog\n\n rows = field\n\n cols = [[] for cell in field[0]]\n for row in field:\n i = 0\n for cell in row:\n cols[i].append(cell)\n i += 1\n\n main_dialogs = [get_square_dialog(0, 0, size)]\n for i in range(5, size):\n k = size - i\n main_dialogs.append(get_square_dialog(k, 0, i))\n main_dialogs.append(get_square_dialog(0, k, i))\n\n sub_dialogs = [get_square_dialog(0, 0, size, True)]\n for i in range(5, size):\n k = size - i\n sub_dialogs.append(get_square_dialog(k, k, i, True))\n sub_dialogs.append(get_square_dialog(0, 0, i, True))\n\n self.rows = rows\n self.cols = cols\n self.main_dialogs = main_dialogs\n self.sub_dialogs = sub_dialogs\n\n\nclass Model:\n def __init__(self, view_field: Interface):\n self.view = view_field\n self.state = 'ball not selected'\n self.selected = None\n self.score = 0\n self.lines = 0\n self.field = ModelField(view_field.field)\n\n self.restart()\n\n view_field.info.controls.new_game.bind('', self.restart)\n view_field.info.controls.step.bind('', self.step)\n\n for row in self.view.field:\n for cell in row:\n cell.click_handler = self._cell_click_handler\n\n def restart(self, event=None):\n self.view.game_over_visibility = False\n self._clear_field()\n self.gen_hint()\n self.step()\n self.view.info.info.update_score(0)\n self.view.info.info.update_lines(0)\n self.state = 'ball not selected'\n\n def step(self, event=None):\n self.use_hint()\n self.gen_hint()\n\n def gen_hint(self):\n balls = []\n for i in range(3):\n balls.append(self._random_ball())\n self.view.info.hint.update(balls)\n\n def use_hint(self):\n hint = self.view.info.hint\n\n free = self._field_free_cells()\n\n for i in range(2, -1, -1):\n if len(free) - i <= 1:\n self.game_over()\n return\n else:\n cell = self._random_from(free)\n cell.put_ball(hint.model[i])\n free.pop()\n\n def game_over(self):\n\n self.view.game_over_visibility = True\n\n @staticmethod\n def _random_from(list_of):\n return list_of[randint(0, len(list_of) - 1)]\n\n def _random_ball(self):\n field_tiles = self.view.tiles\n balls = [\n field_tiles.aqua_ball,\n field_tiles.blue_ball,\n field_tiles.green_ball,\n field_tiles.pink_ball,\n field_tiles.red_ball,\n field_tiles.violet_ball,\n field_tiles.yellow_ball\n ]\n\n return self._random_from(balls)\n\n def _field_free_cells(self):\n free = []\n field = self.view.field\n for row in field:\n for cell in row:\n if cell.free:\n free.append(cell)\n return free\n\n def _clear_field(self):\n field = self.view.field\n\n for row in field:\n for cell in row:\n cell.clear()\n\n def _cell_click_handler(self, cell: ViewFieldCell, event):\n\n if cell.free:\n if self.state == 'ball not selected':\n pass\n elif self.state == 'ball selected':\n line_is_maked = self._cells_reachable(self.selected, cell)\n\n if line_is_maked:\n cell.put_ball(self.selected.ball_tile)\n\n self.selected.unselect_ball()\n self.selected.clear()\n self.selected = None\n\n self.state = 'ball moved'\n\n lines = self._check_all_lines()\n\n for line in lines:\n self.lines += 1\n self.view.info.info.update_lines(self.lines)\n\n for cell in line:\n cell.unselect_ball()\n cell.clear()\n\n self.score += 10\n self.view.info.info.update_score(self.score)\n\n self.state = 'ball not selected'\n\n if len(lines) == 0:\n self.step()\n\n else:\n pass\n else:\n if self.state == 'ball not selected':\n self.state = 'ball selected'\n self.selected = cell\n cell.select_ball()\n elif self.state == 'ball selected':\n self.selected.unselect_ball()\n self.selected = cell\n cell.select_ball()\n\n\n def _check_all_lines(self):\n\n def check_field_lines(field_lines):\n sequences = []\n\n for line in field_lines:\n sequence = []\n prev_color = None\n\n def reset_sequence(color, field_cell=None):\n nonlocal sequence, prev_color\n\n if len(sequence) == 5:\n sequences.append(sequence)\n\n prev_color = color\n sequence = [field_cell] if field_cell else []\n\n for cell in line:\n if cell.free:\n reset_sequence(None)\n continue\n\n else:\n curr_color = cell.ball_tile\n\n if prev_color is None:\n reset_sequence(curr_color, cell)\n\n elif curr_color == prev_color:\n sequence.append(cell)\n\n else:\n reset_sequence(curr_color, cell)\n\n reset_sequence(None)\n\n return sequences\n\n field_lines = []\n field_lines += check_field_lines(self.field.rows)\n field_lines += check_field_lines(self.field.cols)\n field_lines += check_field_lines(self.field.main_dialogs)\n field_lines += check_field_lines(self.field.sub_dialogs)\n\n return field_lines\n\n\n def _cells_reachable(self, a: ViewFieldCell, b: ViewFieldCell, print_check_way=False):\n\n def reset_cells_prev():\n field = self.view.field\n for row in field:\n for cell in row:\n cell.is_prev = False\n\n def step_all_directions(from_cell: ViewFieldCell, target: ViewFieldCell):\n player_steps = []\n\n left = Position(1, 0)\n right = Position(-1, 0)\n up = Position(0, 1)\n down = Position(0, -1)\n for direction in [up, down, left, right]:\n sibling = from_cell.sibling_in(direction)\n\n if not sibling:\n continue\n\n if sibling == target:\n return True\n else:\n if sibling.free and not sibling.is_prev:\n sibling.is_prev = True\n if print_check_way:\n sibling.to_blend_bg_ball(1, self.view.tiles.yellow_ball, 6)\n player_steps.append(sibling)\n\n elif sibling.free and sibling.is_prev:\n if print_check_way:\n sibling.to_blend_bg_ball(1, self.view.tiles.green_ball, 6)\n\n return player_steps\n\n steps = [a]\n\n while True:\n new_steps_storage = []\n\n for step in steps:\n new_steps = step_all_directions(step, b)\n\n if new_steps is True:\n reset_cells_prev()\n return True\n else:\n new_steps_storage += new_steps\n\n if len(new_steps_storage) == 0:\n reset_cells_prev\n return False\n steps = new_steps_storage\n\n\nui = Interface()\ngameModel = Model(ui)\n\nui.render()\n","sub_path":"Lab/03/lines.py","file_name":"lines.py","file_ext":"py","file_size_in_byte":16080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"312094418","text":"from google.appengine.api import urlfetch\nfrom google.appengine.ext import db\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.template.context import RequestContext\nfrom django.utils import simplejson\nimport re \n\n\n\nfrom xml.dom import minidom \n\nfrom models import Song, Playlist\nfrom forms import PlaylistForm, SongForm\n\n\ndef getText(nodelist):\n rc = \"\"\n for node in nodelist:\n if node.nodeType == node.TEXT_NODE:\n rc = rc + node.data\n return rc\n\ndef index(request):\n\treturn render_to_response('index.html')\n\ndef create(request):\n\tif request.method == 'POST':\n\t\turl = request.POST.get('playlist_location', '')\n\t\t#\n\t\t#regexp here!!!!!!!!!\n\t\t#\n\t\tresult = urlfetch.fetch(url + \"code/xspf.php\")\n\n\t\tif result.status_code == 200:\n#\t\t\txml = minidom.parseString(unicode(result.content, \"utf-8\" ))\n\t\t\ttry:\n\t\t\t\txml = minidom.parseString(result.content.replace(\"&\", \"&\"))\n\t\t\texcept:\n\t\t\t\treturn render_to_response('create.html', {'flash' : \"Ops. Something went wrong!!!...\"})\n\t\t\t\n\t\t\ttracks = xml.getElementsByTagName('track')\n\t\t\tplaylist = Playlist(title=\"lorem ipsum dolor\", location=url)\n\t\t\tplaylist.save()\n\n\t\t\tfor song in tracks:\n\t\t\t\tloc = song.getElementsByTagName('location')[0]\n\t\t\t\tme = song.getElementsByTagName('meta')[0]\n\t\t\t\tti = song.getElementsByTagName('title')[0]\n\t\t\t\tfo = song.getElementsByTagName('info')[0]\n\n\t\t\t\ts = SongForm({\n\t\t\t\t\t'location': getText(loc.childNodes),\n\t\t\t\t\t'meta': getText(me.childNodes),\n\t\t\t\t\t'title': getText(ti.childNodes),\n\t\t\t\t\t'info': getText(fo.childNodes),\n\t\t\t\t})\n\t\t\t\tif s.is_valid():\n\t\t\t\t\ts.playlist = playlist\n\t\t\t\t\ts.save()\n\n\t\t\treturn render_to_response('create.html', {'flash' : \"Playlist added! Go back to home page.\"})\n\n\treturn render_to_response('create.html')\n\ndef search(request, keyword=\"\"):\n\treturn render_to_response('search.html', { 'keyword': keyword })\n\n#########\n#\n# API\n#\n#########\n\ndef query(request):\n\tkey = request.GET.get('song', '')\n\tquery = Song.all().search(key).fetch(limit=10)\n\tsongs = []\n\tfor s in query:\n\t\tsongs.append({\n\t\t\t'title' : s.title,\n\t\t\t'location' : s.location,\n\t\t\t'info' : s.info\n\t\t})\n\n\tenc = simplejson.JSONEncoder()\n\tdata = enc.encode(songs)\n\treturn HttpResponse(data)\n\ndef ping(request):\n\treturn HttpResponse(\"\")\n","sub_path":"opentapes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"524675381","text":"import logging\r\nimport os.path\r\nimport json\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\nuri = \"/isam/ssl_certificates\"\r\n\r\n\r\n\r\ndef get_all_certificates (isamAppliance, check_mode=False, force=False):\r\n\t\"\"\"\r\n\tGet information about all certificates on the appliance\t\r\n\t\"\"\"\r\n\timport time\r\n\tepoch_time = int(time.time())\r\n\t\r\n\tcerts=[]\r\n\tdbs_obj = isamAppliance.invoke_get(\"Retrieve all certificate databases\", uri)\r\n\tdbs=dbs_obj['data']\r\n\tfor db in dbs:\r\n\t\tpcert_obj=isamAppliance.invoke_get(\"Retrieve personal certificates\", \"{0}/{1}/personal_cert\".format(uri,db['id']))\r\n\t\tlogger.info(\"Got object {0}\".format(pcert_obj))\r\n\t\tpcerts=pcert_obj['data']\r\n\t\tfor pcert in pcerts:\r\n\t\t\tcert_epoch = int(pcert['notafter_epoch'])\r\n\t\t\tcerts.append({\r\n\t\t\t\t\t\t\"db_id\":db['id'],\r\n\t\t\t\t\t\t\"cert_id\":pcert['id'],\r\n\t\t\t\t\t\t\"issuer\":pcert['issuer'],\r\n\t\t\t\t\t\t\"subject\":pcert['subject'],\t\t\t\t\t\t\r\n\t\t\t\t\t\t\"type\":\"personal\",\r\n\t\t\t\t\t\t\"exp_epoch\":pcert['notafter_epoch'],\r\n\t\t\t\t\t\t\"exp_date\":pcert['notafter'],\r\n\t\t\t\t\t\t\"expired\":cert_epoch < epoch_time\r\n\t\t\t\t\t\t})\r\n\r\n\t\tscert_obj=isamAppliance.invoke_get(\"Retrieve signer certificates\", \"{0}/{1}/signer_cert\".format(uri,db['id']))\r\n\t\tscerts=scert_obj['data']\r\n\t\tfor scert in scerts:\r\n\t\t\tcert_epoch = int(scert['notafter_epoch'])\r\n\t\t\tcerts.append({\r\n\t\t\t\t\t\t\"db_id\":db['id'],\r\n\t\t\t\t\t\t\"cert_id\":scert['id'],\r\n\t\t\t\t\t\t\"issuer\":scert['issuer'],\t\t\t\t\t\t\r\n\t\t\t\t\t\t\"subject\":scert['subject'],\r\n\t\t\t\t\t\t\"type\":\"signer\",\r\n\t\t\t\t\t\t\"exp_epoch\":scert['notafter_epoch'],\r\n\t\t\t\t\t\t\"exp_date\":scert['notafter'],\r\n\t\t\t\t\t\t\"expired\":cert_epoch < epoch_time})\r\n\r\n\t\t\r\n\treturn_obj = isamAppliance.create_return_object()\r\n\treturn_obj['data'] = certs\r\n\t\r\n\treturn return_obj","sub_path":"ibmsecurity/isam/base/ssl_certificates/all_certificates.py","file_name":"all_certificates.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"342811664","text":" # -*- coding: utf-8 -*-\nfrom odoo.exceptions import UserError\nimport datetime\n\ndef gen_model_dict_categ_and_location_partner():\n user_model_dict = {\n \n u'location partner': {\n 'title_rows' : [0], \n 'begin_data_row_offset_with_title_row' :1,\n 'sheet_names': [u'Location Partner'],\n 'model':'stock.location',\n 'fields' : [\n ('name',{'func':None,'xl_title':u'Name','key':True,'required':True}),\n ('usage',{'set_val':'supplier'}),\n ('is_kho_cha',{'set_val':True}),\n ('department_id',{'set_val':False}),\n ('cho_phep_am',{'set_val':True}),\n ('cho_phep_khac_tram_chon',{'set_val':True}),\n ('not_show_in_bb',{'func':lambda v,n: True if v else False,'xl_title':u'not_show_in_bb','for_excel_readonly':True}),\n ('partner_id_of_stock_for_report',{\n 'fields':[('name',{'func': lambda v,n:not n['vof_dict']['not_show_in_bb']['val'] and n['vof_dict']['name']['val'], 'key':True,'required':True}),\n ]\n }\n ),\n ]\n },#location partner\n \n u'categ': {\n 'title_rows' : [0], \n 'begin_data_row_offset_with_title_row' :1,\n 'sheet_names': [u'categ'],\n 'model':'product.category',\n 'fields' : [\n ('name',{'func':None,'xl_title':u'Name','key':True,'required':True}),\n ('stt_for_report',{'func':None,'xl_title':u'stt_for_report','required':True,'type_allow':[float]}),\n# ('usage',{'set_val':'supplier'}),\n# ('is_kho_cha',{'set_val':True}),\n# ('cho_phep_khac_tram_chon',{'set_val':True}),\n# ('partner_id_of_stock_for_report',{'fields':[('name',{'func': lambda v,n:n['vof_dict']['name']['val'], 'key':True,'required':True}),\n# ]\n# }\n# ),\n ]\n },#location partner\n \n \n \n \n }\n \n return user_model_dict\n \n\n ","sub_path":"tonkho/models/import_excel_model_dict_folder/model_dict_categ_and_location_partner.py","file_name":"model_dict_categ_and_location_partner.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"183723250","text":"n = int(input(\"Nhập n đề liệt kê các sos nguyên tố trước nó : \"))\ndef soNT(i):\n count = 0\n for s in range(1, i + 1):\n if (n % s == 0):\n count += 1\n if count == 2:\n print(s)\nfor n in range(2, n + 1):\n if n == 1:\n print(1)\n soNT(n)","sub_path":"Python_Lab_01/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"611220068","text":"# -*- coding: utf-8 -*-\n\n# Scrapy settings for Demo project\n#\n# For simplicity, this file contains only the most important settings by\n# default. All the other settings are documented here:\n#\n# http://doc.scrapy.org/en/latest/topics/settings.html\n#\n\nBOT_NAME = 'demo'\n\nDOWNLOAD_DELAY = 0.25\nCOOKIES_ENABLES = False\n\nSPIDER_MODULES = ['demo.spiders']\nNEWSPIDER_MODULE = 'demo.spiders'\n\nDOWNLOAD_MIDDLEWARES = {\n 'scrapy.contrib.downloadermiddleware.useragent.UserAgentMiddleware' :None,\n 'CSDNBlogCrawlSpider.spiders.rotate_useragent.RotateUserAgentMiddleware' :400\n}\n\nITEM_PIPELINES = {\n\t'demo.pipelines.PCbabyPipeline': 2,\n\t'scrapy.contrib.pipeline.images.ImagesPipeline': 1\n}\n\nIMAGES_STORE = './images'\nIMAGES_THUMBS = {\n\t'small': (100,100),\n\t'big': (300,300),\n}\n\n# Crawl responsibly by identifying yourself (and your website) on the user-agent\n#USER_AGENT = 'Demo (+http://www.yourdomain.com)'\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"544368223","text":"try:\n import sim\nexcept:\n print ('--------------------------------------------------------------')\n print ('\"sim.py\" could not be imported. This means very probably that')\n print ('either \"sim.py\" or the remoteApi library could not be found.')\n print ('Make sure both are in the same folder as this file,')\n print ('or appropriately adjust the file \"sim.py\"')\n print ('--------------------------------------------------------------')\n print ('')\n\nimport time\n\nprint ('Program started')\nsim.simxFinish(-1) # just in case, close all opened connections\nclientID=sim.simxStart('127.0.0.1',19997,True,True,5000,5) # Connect to CoppeliaSim\n\nif clientID!=-1:\n print ('Connected to remote API server')\n\n\n res,UR5_joint1 =sim.simxGetObjectHandle( clientID, 'UR5_joint1', sim.simx_opmode_blocking)\n res,UR5_joint2 =sim.simxGetObjectHandle( clientID, 'UR5_joint2', sim.simx_opmode_blocking)\n res,UR5_joint3 =sim.simxGetObjectHandle( clientID, 'UR5_joint3', sim.simx_opmode_blocking)\n\n UR5 = [UR5_joint1, UR5_joint2, UR5_joint3]\n \n from math import pi\n print(pi)\n \n UR5_q = []\n for joint in UR5:\n res, value = sim.simxGetJointPosition(clientID, joint, sim.simx_opmode_oneshot)\n print('La posición de: ', joint, ' es ', value)\n UR5_q.append(value)\n \n steps = 100\n \n for t in range(steps):\n for joint in UR5:\n sim.simxSetJointTargetPosition(clientID, joint, t*(pi/2)/steps, sim.simx_opmode_streaming)\n time.sleep(2/steps)\n \n time.sleep(1)\n for t in range(steps,0,-1):\n for joint in UR5:\n sim.simxSetJointTargetPosition(clientID, joint, t*(pi/2)/steps, sim.simx_opmode_streaming)\n time.sleep(2/steps)\n\n \n time.sleep(2)\n\n # Now send some data to CoppeliaSim in a non-blocking fashion:\n sim.simxAddStatusbarMessage(clientID,'Hello CoppeliaSim!\\nWe are running Python 3 code.',sim.simx_opmode_oneshot)\n\n # Before closing the connection to CoppeliaSim, make sure that the last command sent out had time to arrive. You can guarantee this with (for example):\n sim.simxGetPingTime(clientID)\n\n # Now close the connection to CoppeliaSim:\n sim.simxFinish(clientID)\n \n \nelse:\n print ('Failed connecting to remote API server')\nprint ('Program ended')\n","sub_path":"CONDA/Coppelia/DEP/move_ur5_copsim.py","file_name":"move_ur5_copsim.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"326453357","text":"\n# Input number\n\nnum = int(input('Enter a number: '))\n\nif num % 2:\n matrix = [[0 for x in range(num)] for i in range(num)]\n step = 1\n i, j = 0, (num // 2)\n matrix[i][j] = step\n while step < num * num:\n if (i == 0) and (j == (num -1)):\n i += 1\n elif i == 0:\n i = num - 1\n j += 1\n elif j == (num -1):\n i -= 1\n j = 0\n else:\n if matrix[i - 1][j + 1] != 0:\n i += 1\n else:\n i -= 1\n j += 1\n step += 1\n matrix[i][j] = step\n\n for i in range(num) :\n for j in range(num) :\n print(repr(matrix[i][j]).rjust(4), end=' ')\n print('\\n')\nelse:\n print('Khong hop le.') ","sub_path":"MaPhuong.py","file_name":"MaPhuong.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"159266089","text":"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nimport numpy as np\n\nfrom . import group_accuracy_score, group_balanced_root_mean_squared_error\nfrom . import group_fallout_rate, group_max_error\nfrom . import group_mean_absolute_error, group_mean_overprediction\nfrom . import group_mean_squared_error, group_mean_squared_log_error\nfrom . import group_mean_underprediction, group_median_absolute_error\nfrom . import group_mean_prediction\nfrom . import group_miss_rate, group_precision_score, group_r2_score\nfrom . import group_recall_score, group_roc_auc_score, group_root_mean_squared_error\nfrom . import group_selection_rate, group_specificity_score, group_zero_one_loss\n\n_GROUP_NAMES_MSG = \"The sensitive_feature_names property must be a list of strings\"\n_METRICS_KEYS_MSG = \"Keys for metrics dictionary must be strings\"\n_METRICS_VALUES_MSG = \"Values for metrics dictionary must be of type GroupMetricResult\"\n\n_ARRAYS_NOT_SAME_LENGTH = \"Lengths of y_true, y_pred and sensitive_features must match\"\n\n_Y_TRUE = 'trueY'\n_Y_PRED = 'predictedY'\n_PRECOMPUTED_METRICS = 'precomputedMetrics'\n_GLOBAL = 'global'\n_BINS = 'bins'\n_PRECOMPUTED_BINS = 'precomputedFeatureBins'\n_BIN_VECTOR = 'binVector'\n_BIN_LABELS = 'binLabels'\n_FEATURE_BIN_NAME = 'featureBinName'\n_PREDICTION_TYPE = 'predictionType'\n_PREDICTION_BINARY_CLASSIFICATION = 'binaryClassification'\n_MODEL_NAMES = 'modelNames'\n_SCHEMA = 'schemaType'\n_GROUP_METRIC_SET = 'groupMetricSet'\n_VERSION = 'schemaVersion'\n\n_UNSUPPORTED_MODEL_TYPE = \"The specified model_type of '{0}' is not supported\"\n_DICT_TOO_MANY_Y_PRED = 'Too many y_pred values in dictionary'\n\nBINARY_CLASSIFICATION = 'binary_classification'\nREGRESSION = 'regression'\n_allowed_model_types = frozenset([BINARY_CLASSIFICATION, REGRESSION])\n\n# The following keys need to match those of _metric_methods in\n# _fairlearn_dashboard.py\n# Issue 269 is about unifying the two sets\nGROUP_ACCURACY_SCORE = \"accuracy_score\"\nGROUP_BALANCED_ROOT_MEAN_SQUARED_ERROR = \"balanced_root_mean_squared_error\"\nGROUP_FALLOUT_RATE = \"fallout_rate\"\nGROUP_MAX_ERROR = \"max_error\"\nGROUP_MEAN_ABSOLUTE_ERROR = \"mean_absolute_error\"\nGROUP_MEAN_OVERPREDICTION = \"overprediction\"\nGROUP_MEAN_PREDICTION = \"average\"\nGROUP_MEAN_SQUARED_ERROR = \"mean_squared_error\"\nGROUP_MEAN_SQUARED_LOG_ERROR = \"6d106114-4433-40a2-b091-8983ab540a53\"\nGROUP_MEAN_UNDERPREDICTION = \"underprediction\"\nGROUP_MEDIAN_ABSOLUTE_ERROR = \"median_absolute_error\"\nGROUP_MISS_RATE = \"miss_rate\"\nGROUP_PRECISION_SCORE = \"precision_score\"\nGROUP_R2_SCORE = \"r2_score\"\nGROUP_RECALL_SCORE = \"recall_score\"\nGROUP_ROC_AUC_SCORE = \"balanced_accuracy_score\"\nGROUP_ROOT_MEAN_SQUARED_ERROR = \"root_mean_squared_error\"\nGROUP_SELECTION_RATE = \"selection_rate\"\nGROUP_SPECIFICITY_SCORE = \"specificity_score\"\nGROUP_ZERO_ONE_LOSS = \"zero_one_loss\"\n\nBINARY_CLASSIFICATION_METRICS = {}\nBINARY_CLASSIFICATION_METRICS[GROUP_ACCURACY_SCORE] = group_accuracy_score\nBINARY_CLASSIFICATION_METRICS[GROUP_FALLOUT_RATE] = group_fallout_rate\nBINARY_CLASSIFICATION_METRICS[GROUP_MEAN_OVERPREDICTION] = group_mean_overprediction\nBINARY_CLASSIFICATION_METRICS[GROUP_MEAN_UNDERPREDICTION] = group_mean_underprediction\nBINARY_CLASSIFICATION_METRICS[GROUP_MISS_RATE] = group_miss_rate\nBINARY_CLASSIFICATION_METRICS[GROUP_PRECISION_SCORE] = group_precision_score\nBINARY_CLASSIFICATION_METRICS[GROUP_RECALL_SCORE] = group_recall_score\nBINARY_CLASSIFICATION_METRICS[GROUP_ROC_AUC_SCORE] = group_roc_auc_score\nBINARY_CLASSIFICATION_METRICS[GROUP_SELECTION_RATE] = group_selection_rate\nBINARY_CLASSIFICATION_METRICS[GROUP_SPECIFICITY_SCORE] = group_specificity_score\n\nREGRESSION_METRICS = {}\nREGRESSION_METRICS[GROUP_BALANCED_ROOT_MEAN_SQUARED_ERROR] = group_balanced_root_mean_squared_error # noqa:E501\nREGRESSION_METRICS[GROUP_MAX_ERROR] = group_max_error\nREGRESSION_METRICS[GROUP_MEAN_ABSOLUTE_ERROR] = group_mean_absolute_error\nREGRESSION_METRICS[GROUP_MEAN_OVERPREDICTION] = group_mean_overprediction\nREGRESSION_METRICS[GROUP_MEAN_PREDICTION] = group_mean_prediction\nREGRESSION_METRICS[GROUP_MEAN_SQUARED_ERROR] = group_mean_squared_error\nREGRESSION_METRICS[GROUP_MEAN_SQUARED_LOG_ERROR] = group_mean_squared_log_error\nREGRESSION_METRICS[GROUP_MEAN_UNDERPREDICTION] = group_mean_underprediction\nREGRESSION_METRICS[GROUP_MEDIAN_ABSOLUTE_ERROR] = group_median_absolute_error\nREGRESSION_METRICS[GROUP_R2_SCORE] = group_r2_score\nREGRESSION_METRICS[GROUP_ROOT_MEAN_SQUARED_ERROR] = group_root_mean_squared_error\nREGRESSION_METRICS[GROUP_ZERO_ONE_LOSS] = group_zero_one_loss\n\n\ndef create_group_metric_set(model_type,\n y_true,\n y_preds,\n sensitive_features,\n model_titles=None,\n sensitive_feature_names=None,\n extra_metrics=None):\n \"\"\"Create a dictionary matching the Dashboard's cache.\"\"\"\n if extra_metrics is not None:\n raise NotImplementedError(\"No support for extra_metrics yet\")\n\n # We could consider checking that the length of y_preds matches model_titles\n # and that the length of sensitive_features matches sensitive_feature_names\n\n result = dict()\n result[_SCHEMA] = _GROUP_METRIC_SET\n result[_VERSION] = 0\n\n if model_type not in _allowed_model_types:\n msg_format = \"model_type '{0}' not in {1}\"\n msg = msg_format.format(model_type, sorted(\n list(_allowed_model_types)))\n raise ValueError(msg)\n\n function_dict = None\n if model_type == BINARY_CLASSIFICATION:\n result[_PREDICTION_TYPE] = _PREDICTION_BINARY_CLASSIFICATION\n function_dict = BINARY_CLASSIFICATION_METRICS\n else:\n raise NotImplementedError(\"No support yet for regression\")\n\n _yt = np.asarray(y_true)\n result[_Y_TRUE] = _yt.tolist()\n\n result[_Y_PRED] = []\n result[_PRECOMPUTED_METRICS] = []\n result[_PRECOMPUTED_BINS] = []\n result[_MODEL_NAMES] = []\n for g, group_membership in enumerate(sensitive_features):\n _gm = np.asarray(group_membership).tolist()\n _unique_groups = sorted(list(np.unique(_gm)))\n group_names = [str(x) for x in _unique_groups]\n groups = [_unique_groups.index(x) for x in _gm]\n bin_dict = {_BIN_VECTOR: groups, _BIN_LABELS: group_names}\n if sensitive_feature_names is not None:\n bin_dict[_FEATURE_BIN_NAME] = sensitive_feature_names[g]\n result[_PRECOMPUTED_BINS].append(bin_dict)\n\n model_list = []\n for m, model_pred in enumerate(y_preds):\n _yp = np.asarray(model_pred).tolist()\n\n # Only record each y_pred and model name once\n if g == 0:\n result[_Y_PRED].append(_yp)\n if model_titles is not None:\n result[_MODEL_NAMES].append(model_titles[m])\n\n metric_dict = dict()\n for metric_key, metric_func in function_dict.items():\n gmr = metric_func(_yt, _yp, groups)\n curr_dict = dict()\n curr_dict[_GLOBAL] = gmr.overall\n curr_dict[_BINS] = list(gmr.by_group.values())\n metric_dict[metric_key] = curr_dict\n model_list.append(metric_dict)\n result[_PRECOMPUTED_METRICS].append(model_list)\n\n return result\n","sub_path":"fairlearn/metrics/_group_metric_set.py","file_name":"_group_metric_set.py","file_ext":"py","file_size_in_byte":7290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"57726144","text":"'''\n분류 : 그리디 알고리즘\n문제 : 보석도둑 (백준 1202번)\n작성일자 : 2021.03.07\n'''\n\n# 보석은 가격과 무게 정보를 갖고 있고, 가방에 담을 수 있는 최대 무게가 존재\n# 가방에는 1개의 보석만 넣을 수 있다\n## 목적 : 훔칠 수 있는 보석 가격의 합의 최댓값을 출력\n## 접근 : 가장 가볍고 가장 비싼 보석부터 처리한다 \n## 최대 무게가 가장 가벼운 가방에 비싼 보석을 넣는 것을 우선으로 생각\n## 이중 반복문을 통한 O(N^2)을 피하도록 구현 \n\n# 가방을 오름차순으로 정렬한다 (정렬하지 않으면 밑의 while조건문에서 문제 발생)\n## 기준이 되는 가방보다 작거나 같은 보석이 다 들어가야하는데, 못들어가는 경우 생김\n# 보석을 무게를 기준으로 오름차순 정렬한다 \n# 반복문(가방기준)을 돌며 현재 가방무게보다 작거나 같은 보석을 최대힙에 넣는다 \n## 최대힙에는 보석의 가격을 넣는다 \n## 중요한 점은 특정 가방의 무게보다 작거나 같아서 들어간 보석은 어차피 추후에 다른 가방에도\n## 들어가지므로, 최대힙으로 큰 값들만 빼주면 된다\nimport sys\nimport heapq\n\nN, K = map(int, input().split())\njew = []\nbag = []\nfor _ in range(N) : \n jew.append(list(map(int, sys.stdin.readline().rstrip().split())))\njew.sort(key= lambda x: x[0])\nfor _ in range(K) : \n bag.append(int(sys.stdin.readline().rstrip()))\nbag.sort()\n\nmyQue = []\nindex = 0\nresult = 0\n### 기준을 남긴채로 반복문 돌리는 기법 (단순 이중 for문과의 차이)\nfor i in range(len(bag)) : \n # 기준이 되는 가방보다 무게가 작은 보석들을 집어넣기\n # while 반복문의 탈출조건\n ## 파이썬은 인터프리터 언어이므로 로직상으로 맞아도 순서에 따라 틀려질 수 있음\n ## index= jew[index][0]: \n # 최대힙으로 대입\n heapq.heappush(myQue, -jew[index][1]) \n index += 1 \n \n # 기준에 충족하는 보석을 다 채웠으면, 가장 큰 값 비우기\n if len(myQue) : \n result += heapq.heappop(myQue)\nprint(-result)\n\n\n","sub_path":"greedy/R_greedy_28.py","file_name":"R_greedy_28.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"609729924","text":"import json\nimport random\nimport string\nimport time\n\nimport tornado\nimport tornado.web\nfrom sqlalchemy import or_\n\nfrom _base import ShareitBaseHandler\nfrom model.base import Base\nfrom model.const import Const\nfrom model.dim_ads_thirdparty_adunit import ThirdPartAdpostionInfo\nfrom model.operation_log import OperationLog\nfrom model.shareit_adpostion_info import ShareitAdpostionInfo\nfrom model.shareit_android_ver import ShareitAndroidVer\nfrom model.user import User\nfrom utils.util import convert_date\n\n\nclass AdminLogindHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def post(self):\n data = json.loads(self.request.body.decode())\n account = data[\"account\"]\n password = data[\"password\"]\n user_obj = User.query.filter_by(account=account, password=password, status=0).first()\n if not user_obj:\n self.finish({\"code\": 500, \"flag\": True})\n else:\n salt = ''.join(random.sample(string.ascii_letters + string.digits, 32)) + \"|\" + account\n token = {\"token\": salt}\n user_obj.update(**token)\n self.finish({\"code\": 200, \"flag\": True, \"token\": salt})\n\n\nclass LogoutHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n account = self.request.headers[\"Thrdate-Token\"].split(\"|\")[1]\n user_obj = User.query.filter_by(account=account, status=0).first()\n if user_obj is not None:\n update_info = {\"token\": \"\"}\n user_obj.update(**update_info)\n Base.db_session.commit()\n self.finish({\"code\": 200, \"flag\": True})\n else:\n self.finish({\"code\": 400, \"flag\": True})\n\n\nclass ShareitAdposHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self):\n page = int(self.get_argument(\"page\", 1))\n pagesize = int(self.get_argument(\"pagesize\", 10))\n adpage = self.get_argument(\"adpage\", \"\")\n adformat = self.get_argument(\"adformat\", \"\")\n adtype = self.get_argument(\"adtype\", \"\")\n filter = self.get_argument(\"filter\", \"\")\n arg_dict = {\"adpage\": adpage, \"adformat\": adformat, \"adtype\": adtype}\n filter_dict = dict()\n for k, v in arg_dict.items():\n if v != \"\":\n filter_dict[k] = v\n filter_dict[\"status\"] = 0\n\n adpos_list = ShareitAdpostionInfo.query.filter_by(**filter_dict) \\\n .filter(or_(ShareitAdpostionInfo.adpos_name.like(\"%\" + filter + \"%\"),\n ShareitAdpostionInfo.id.like(\"%\" + filter + \"%\"))) \\\n .order_by(ShareitAdpostionInfo.id.desc()) \\\n .offset((page - 1) * pagesize) \\\n .limit(pagesize) \\\n .all()\n\n total = ShareitAdpostionInfo.query.filter_by(**filter_dict) \\\n .filter(or_(ShareitAdpostionInfo.adpos_name.like(\"%\" + filter + \"%\"),\n ShareitAdpostionInfo.id.like(\"%\" + filter + \"%\"))) \\\n .count()\n\n res = self.assemble_data(data=self.list_json(adpos_list), code=200, total=total)\n self.finish(res)\n\n\nclass ShareitAdposModifyHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def post(self):\n data = json.loads(self.request.body.decode())\n pos_data = data[\"item\"]\n action = data[\"action\"]\n pos_data[\"modify_time\"] = int(time.time() * 1000)\n\n try:\n if action == \"add\":\n pos_data[\"create_time\"] = int(time.time() * 1000)\n pos_data[\"status\"] = 0\n ShareitAdpostionInfo.create(**pos_data)\n else:\n ShareitAdpostionInfo.update_or_create(id=pos_data[\"id\"], defaults=pos_data)\n except Exception as e:\n print(\"update ShareitAdpostionInfo error, error is: %s; data is: %s\" % (e, pos_data))\n self.finish(self.assemble_data(flag=True, code=400))\n else:\n self.log()\n self.finish(self.assemble_data(flag=True, code=200))\n\n\nclass ThrPartPlacementHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n adpos = self.get_argument(\"adpos\", \"\")\n shareit_adpos = self.get_argument(\"shareit_adpos\", \"\") # 茄子广告位信息,ssssss-id\n tag = self.get_argument(\"tag\", \"\")\n priority = self.get_argument(\"priority\", \"\")\n platform = self.get_argument(\"platform\", \"\")\n page = int(self.get_argument(\"page\", 1))\n pagesize = int(self.get_argument(\"pagesize\", 10))\n\n adpos_list = ThirdPartAdpostionInfo.query \\\n .join(ShareitAdpostionInfo, ThirdPartAdpostionInfo.shareit_adpos == ShareitAdpostionInfo.id) \\\n .filter(ThirdPartAdpostionInfo.platform==platform, ThirdPartAdpostionInfo.status==0) \\\n .filter(or_(ThirdPartAdpostionInfo.adpos_name.like(\"%\" + adpos + \"%\"),\n ThirdPartAdpostionInfo.adpos_id.like(\"%\" + adpos + \"%\"))) \\\n .filter(or_(ThirdPartAdpostionInfo.shareit_adpos.like(\"%\" + shareit_adpos + \"%\"),\n ShareitAdpostionInfo.adpos_name.like(\"%\" + shareit_adpos + \"%\"))) \\\n .filter(ThirdPartAdpostionInfo.tag_info.like(\"%\" + tag + \"%\")) \\\n .filter(ThirdPartAdpostionInfo.priority_info.like(\"%\" + priority + \"%\")) \\\n .order_by(ThirdPartAdpostionInfo.id.desc()) \\\n .offset((page - 1) * pagesize) \\\n .limit(pagesize) \\\n .all()\n\n total = ThirdPartAdpostionInfo.query \\\n .join(ShareitAdpostionInfo, ThirdPartAdpostionInfo.shareit_adpos == ShareitAdpostionInfo.id) \\\n .filter(ThirdPartAdpostionInfo.platform==platform, ThirdPartAdpostionInfo.status==0) \\\n .filter(or_(ThirdPartAdpostionInfo.adpos_name.like(\"%\" + adpos + \"%\"),\n ThirdPartAdpostionInfo.adpos_id.like(\"%\" + adpos + \"%\"))) \\\n .filter(or_(ThirdPartAdpostionInfo.shareit_adpos.like(\"%\" + shareit_adpos + \"%\"),\n ShareitAdpostionInfo.adpos_name.like(\"%\" + shareit_adpos + \"%\"))) \\\n .filter(ThirdPartAdpostionInfo.tag_info.like(\"%\" + tag + \"%\")) \\\n .filter(ThirdPartAdpostionInfo.priority_info.like(\"%\" + priority + \"%\")) \\\n .count()\n\n res = self.assemble_data(data=self.list_json(adpos_list), code=200, total=total)\n for item in res[\"data\"]:\n item[\"tag_info\"] = json.loads(item[\"tag_info\"])\n item[\"priority_info\"] = json.loads(item[\"priority_info\"])\n self.finish(res)\n\n @tornado.gen.coroutine\n def delete(self, *args, **kwargs):\n id = int(self.get_argument(\"id\", 0))\n del_info = {\n \"status\": -1,\n \"modify_time\": int(time.time() * 1000)\n }\n try:\n ThirdPartAdpostionInfo.get(id).update(**del_info)\n except Exception as e:\n print(\"delete ThirdPartAdpostionInfo error; error is: %s, ID:%s\" % (e, id))\n self.finish(self.assemble_data(flag=True, code=400))\n else:\n self.log()\n self.finish(self.assemble_data(flag=True, code=200))\n\n\nclass ThrPartPlacementModifyHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def post(self, *args, **kwargs):\n data = json.loads(self.request.body.decode())\n current_time = int(time.time() * 1000)\n pos_data = data[\"item\"]\n action = data[\"action\"]\n pos_data[\"modify_time\"] = current_time\n pos_data[\"tag_info\"] = json.dumps(pos_data[\"tag_info\"])\n pos_data[\"priority_info\"] = json.dumps(pos_data.get(\"priority_info\", []))\n try:\n if action == \"add\":\n pos_data[\"create_time\"] = current_time\n if pos_data[\"platform\"] != \"facebook\":\n pos_data[\"start_date\"] = \"\"\n pos_data[\"status\"] = 0\n ThirdPartAdpostionInfo.create(**pos_data)\n else:\n ThirdPartAdpostionInfo.update_or_create(id=pos_data[\"id\"], defaults=pos_data)\n except Exception as e:\n print(\"ThirdPartAdpostionInfo update error, error is: \", e)\n self.finish(self.assemble_data(flag=True, code=400))\n else:\n self.log()\n self.finish(self.assemble_data(flag=True, code=200))\n\n\nclass AndroidVersionHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n version = self.get_argument(\"version\", \"\")\n version_tag = self.get_argument(\"version_tag\", \"\")\n page = int(self.get_argument(\"page\", 1))\n pagesize = int(self.get_argument(\"pagesize\", 10))\n\n verstion_list = ShareitAndroidVer.query \\\n .filter_by(status=0) \\\n .filter(ShareitAndroidVer.version.like(\"%\" + version + \"%\")) \\\n .filter(ShareitAndroidVer.version_tag.like(\"%\" + version_tag + \"%\")) \\\n .order_by(ShareitAndroidVer.id.desc()) \\\n .offset((page - 1) * pagesize) \\\n .limit(pagesize) \\\n .all()\n\n total = ShareitAndroidVer.query \\\n .filter_by(status=0) \\\n .filter(ShareitAndroidVer.version.like(\"%\" + version + \"%\")) \\\n .filter(ShareitAndroidVer.version_tag.like(\"%\" + version_tag + \"%\")) \\\n .count()\n\n res = self.assemble_data(data=self.list_json(verstion_list), code=200, total=total)\n self.finish(res)\n\n @tornado.gen.coroutine\n def delete(self, *args, **kwargs):\n id = int(self.get_argument(\"id\", 0))\n del_info = {\n \"status\": -1,\n \"modify_time\": int(time.time() * 1000)\n }\n try:\n ShareitAndroidVer.get(id).update(**del_info)\n except Exception as e:\n print(\"update android version error, error is: %s; id is %s\" % (e, id))\n self.finish(self.assemble_data(flag=True, code=400))\n else:\n self.log()\n self.finish(self.assemble_data(flag=True, code=200))\n\n\nclass AndroidVersionModifyHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def post(self, *args, **kwargs):\n data = json.loads(self.request.body.decode())\n pos_data = data[\"item\"]\n action = data[\"action\"]\n current_time = int(time.time() * 1000)\n pos_data[\"modify_time\"] = current_time\n\n try:\n if action == \"add\":\n pos_data[\"create_time\"] = current_time\n pos_data[\"status\"] = 0\n ShareitAndroidVer.create(**pos_data)\n else:\n ShareitAndroidVer.update_or_create(id=pos_data[\"id\"], defaults=pos_data)\n except Exception as e:\n print(\"update android version error, error is: %s, data is: %s\" % (e, pos_data))\n self.finish(self.assemble_data(flag=True, code=400))\n else:\n self.log()\n self.finish(self.assemble_data(flag=True, code=200))\n\n\nclass ConstHandler(ShareitBaseHandler):\n def update_thrplace(self, id):\n const = Const.get(ident=id)\n content = const.content\n type = const.type\n current_time = int(time.time() * 1000)\n if type == \"tag\":\n # 三方广告位更新\n placement_list = ThirdPartAdpostionInfo.query.filter_by(status=0).all()\n for p in placement_list:\n tag_info = eval(p.tag_info)\n new_tag_info = []\n flag = False # 判定是否要更新广告位表\n for tag in tag_info:\n if tag.get(\"tag\", \"\") != content:\n new_tag_info.append(tag)\n if tag.get(\"tag\", \"\") == content:\n flag = True\n if flag is True:\n update_data = {\"tag_info\": json.dumps(new_tag_info), \"modify_time\": current_time}\n p.update(**update_data)\n\n # 安卓版本号删除\n version_list = ShareitAndroidVer.query.filter_by(status=0).all()\n for version in version_list:\n tag = version.version_tag\n tag_list = tag.split(\",\")\n new_tag_list = []\n flag = False\n for t in tag_list:\n if t != content:\n new_tag_list.append(t)\n if t == content:\n flag = True\n if flag is True:\n update_version_data = {\"version_tag\": \",\".join(new_tag_list), \"modify_time\": current_time}\n version.update(**update_version_data)\n\n if type == \"priority\":\n placement_list = ThirdPartAdpostionInfo.query.filter_by(status=0).all()\n for p in placement_list:\n priority_info = eval(p.priority_info)\n new_priority_info = []\n flag = False # 判定是否要更新广告位表\n for priority in priority_info:\n if priority.get(\"priority\", \"\") != content:\n new_priority_info.append(priority)\n if priority.get(\"priority\", \"\") == content:\n flag = True\n if flag is True:\n update_data = {\"priority_info\": json.dumps(new_priority_info), \"modify_time\": current_time}\n p.update(**update_data)\n\n if type == \"adpage\":\n shareit_placements = ShareitAdpostionInfo.query.filter_by(status=0, adpage=content).all()\n for p in shareit_placements:\n update_data = {\"adpage\": \"\", \"modify_time\": current_time}\n p.update(**update_data)\n\n if type == \"adtype\":\n shareit_placements = ShareitAdpostionInfo.query.filter_by(status=0, adtype=content).all()\n for p in shareit_placements:\n update_data = {\"adtype\": \"\", \"modify_time\": current_time}\n p.update(**update_data)\n\n if type == \"adformat\":\n shareit_placements = ShareitAdpostionInfo.query.filter_by(status=0, adformat=content).all()\n for p in shareit_placements:\n update_data = {\"adformat\": \"\", \"modify_time\": current_time}\n p.update(**update_data)\n\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n type = self.get_argument(\"type\", \"\")\n page = int(self.get_argument(\"page\", 1))\n pagesize = int(self.get_argument(\"pagesize\", 10))\n const_list = Const.query \\\n .filter_by(status=0, type=type) \\\n .order_by(Const.id.desc()) \\\n .offset((page - 1) * pagesize) \\\n .limit(pagesize) \\\n .all()\n total = Const.query \\\n .filter_by(status=0, type=type) \\\n .count()\n\n res = self.assemble_data(data=self.list_json(const_list), code=200, total=total)\n self.finish(res)\n\n @tornado.gen.coroutine\n def delete(self, *args, **kwargs):\n id = int(self.get_argument(\"id\", 0))\n del_info = {\n \"status\": -1,\n \"modify_time\": int(time.time() * 1000)\n }\n\n try:\n Const.get(id).update(**del_info)\n self.update_thrplace(id)\n except Exception as e:\n print(\"delete const failted, error is: %s; id is: %s\" % (e, id))\n self.finish(self.assemble_data(code=400, flag=True))\n else:\n self.log()\n self.finish(self.assemble_data(code=200, flag=True))\n\n\nclass ConstModifyHandler(ShareitBaseHandler):\n def update_thrplace(self, id, new_content):\n \"\"\"需要在Const表修改之前,修改相应的表,需要传入修改之前的值和修改之后的值\"\"\"\n const = Const.get(ident=id)\n content = const.content\n type = const.type\n current_time = int(time.time() * 1000)\n if type == \"tag\":\n placement_list = ThirdPartAdpostionInfo.query.filter_by(status=0).all()\n for p in placement_list:\n tag_info = eval(p.tag_info)\n for tag in tag_info:\n if tag.get(\"tag\", \"\") == content:\n tag[\"tag\"] = new_content\n update_data = {\"tag_info\": json.dumps(tag_info), \"modify_time\": current_time}\n p.update(**update_data)\n\n # 更新安卓版本号\n version_list = ShareitAndroidVer.query.filter_by(status=0).all()\n for version in version_list:\n tag = version.version_tag\n tag_list = tag.split(\",\")\n flag = False\n for k, v in enumerate(tag_list):\n if v == content:\n tag_list[k] = new_content\n flag = True\n if flag is True:\n update_version_data = {\"version_tag\": \",\".join(tag_list), \"modify_time\": current_time}\n version.update(**update_version_data)\n\n if type == \"priority\":\n placement_list = ThirdPartAdpostionInfo.query.filter_by(status=0).all()\n for p in placement_list:\n priority_info = eval(p.priority_info)\n for priority in priority_info:\n if priority.get(\"priority\", \"\") == content:\n priority[\"priority\"] = new_content\n update_data = {\"priority_info\": json.dumps(priority_info), \"modify_time\": current_time}\n p.update(**update_data)\n\n if type == \"adpage\":\n shareit_placements = ShareitAdpostionInfo.query.filter_by(status=0, adpage=content).all()\n for p in shareit_placements:\n update_data = {\"adpage\": new_content, \"modify_time\": current_time}\n p.update(**update_data)\n\n if type == \"adtype\":\n shareit_placements = ShareitAdpostionInfo.query.filter_by(status=0, adtype=content).all()\n for p in shareit_placements:\n update_data = {\"adtype\": new_content, \"modify_time\": current_time}\n p.update(**update_data)\n\n if type == \"adformat\":\n shareit_placements = ShareitAdpostionInfo.query.filter_by(status=0, adformat=content).all()\n for p in shareit_placements:\n update_data = {\"adformat\": new_content, \"modify_time\": current_time}\n p.update(**update_data)\n\n @tornado.gen.coroutine\n def post(self, *args, **kwargs):\n data = json.loads(self.request.body.decode())\n action = data[\"action\"]\n pos_data = data[\"item\"]\n current_time = int(time.time() * 1000)\n pos_data[\"modify_time\"] = current_time\n try:\n if action == \"add\":\n pos_data[\"create_time\"] = current_time\n pos_data[\"status\"] = 0\n Const.create(**pos_data)\n else:\n self.update_thrplace(id=pos_data[\"id\"], new_content=pos_data[\"content\"])\n Const.update_or_create(id=pos_data[\"id\"], defaults=pos_data)\n except Exception as e:\n print(\"update const failed, error is: %s; data is: %s\" % (e, pos_data))\n self.finish(self.assemble_data(flag=True, code=400))\n else:\n self.log()\n self.finish(self.assemble_data(flag=True, code=200))\n\n\nclass ExportHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n \"\"\"\n shareit_adpos:茄子广告位;third_part:第三方广告平台管理; version:茄子安卓版本\n 二级区分:只针对第三方平台管理,其他不传此参数; admob;altamob;faccebook;mopub\n \"\"\"\n\n place = self.get_argument(\"place\", \"\")\n exp_type = self.get_argument(\"type\", \"\")\n exp_data = []\n if place == \"shareit_adpos\":\n exp_data = ShareitAdpostionInfo.query.filter_by(status=0).all()\n\n if place == \"third_part\":\n exp_data = ThirdPartAdpostionInfo.query.filter_by(status=0, platform=exp_type).all()\n\n if place == \"version\":\n exp_data = ShareitAndroidVer.query.filter_by(status=0).all()\n\n res = self.assemble_data(data=self.list_json(exp_data), code=200, flag=True)\n\n if place == \"third_part\":\n for item in res[\"data\"]:\n item[\"tag_info\"] = json.loads(item[\"tag_info\"])\n item[\"priority_info\"] = json.loads(item[\"priority_info\"])\n self.finish(res)\n\n\nclass OptionHandler(ShareitBaseHandler):\n def extract_data_with_id(self, obj_list, option_name):\n option_list = []\n for item in obj_list:\n k_v = {}\n name = getattr(item, option_name)\n id = getattr(item, \"id\")\n key = name + \"/\" + str(id)\n k_v[\"key\"] = key\n k_v[\"value\"] = id\n option_list.append(k_v)\n\n return option_list\n\n def extract_data(self, obj_list, option_name):\n option_list = []\n for item in obj_list:\n k_v = {}\n item_name = getattr(item, option_name)\n k_v[\"key\"] = item_name\n k_v[\"value\"] = item_name\n option_list.append(k_v)\n\n return option_list\n\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n \"\"\"\n 按需传入:adpage:广告页;adtype:广告类型;adformat:广告样式;tag:标签;priority:优先级; shareit_adpostion:广告位信息; username:操作人\n\n \"\"\"\n option = self.get_argument(\"option\", \"\")\n option_list = []\n\n if option == \"tag\" or option == \"priority\" or option == \"adpage\" or option == \"adtype\" or option == \"adformat\":\n res = Const.db_session.execute(\n \"select distinct content from const where type='\" + option + \"' and status=0\").fetchall()\n option_list = self.extract_data(res, \"content\")\n\n if option == \"shareit_adpostion\":\n # name/ID\n res = ShareitAdpostionInfo.db_session.execute(\n \"select id, adpos_name from dim_ads_standard_adunit where status=0\")\n option_list = self.extract_data_with_id(res, \"adpos_name\")\n\n if option == \"username\":\n res = User.db_session.execute(\"select user_name from user where status=0\")\n option_list = self.extract_data(res, \"user_name\")\n\n self.finish(self.assemble_data(data=option_list, code=200, flag=True))\n\n\nclass CheckHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n \"\"\"\n data_type: shareitid:茄子广告位信息;adpage:常量配置adpage;adformat:常量配置adformat;adtype:常量配置adtype;Priority:常量配置Priority; Tag:常量配置Tag\n content: 待检测字段\n\n \"\"\"\n data_type = self.get_argument(\"type\", \"\")\n content = self.get_argument(\"content\", \"\")\n res = None\n\n if data_type == \"shareitid\":\n res = ShareitAdpostionInfo.query.filter_by(adpos_name=content, status=0).first()\n if data_type == \"adpage\":\n res = Const.query.filter_by(content=content, type=\"adpage\", status=0).first()\n if data_type == \"adformat\":\n res = Const.query.filter_by(content=content, type=\"adformat\", status=0).first()\n if data_type == \"adtype\":\n res = Const.query.filter_by(content=content, type=\"adtype\", status=0).first()\n if data_type == \"priority\":\n res = Const.query.filter_by(content=content, type=\"priority\", status=0).first()\n if data_type == \"tag\":\n res = Const.query.filter_by(content=content, type=\"tag\", status=0).first()\n if data_type == \"account\":\n res = User.query.filter_by(account=content, status=0).first()\n\n if res is None:\n self.finish({\"code\": 200, \"flag\": True, \"status\": \"notbe\"})\n else:\n self.finish({\"code\": 200, \"flag\": True, \"status\": \"be\"})\n\n\nclass UserHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n page = int(self.get_argument(\"page\", 1))\n pagesize = int(self.get_argument(\"pagesize\", 10))\n users = User.query.filter_by(status=0).order_by(User.id.desc()).offset((page - 1) * pagesize).limit(pagesize).all()\n total = User.query.filter_by(status=0).count()\n user_list = []\n for user in users:\n user_dict = dict()\n user_dict[\"id\"] = user.id\n user_dict[\"user_name\"] = user.user_name\n user_dict[\"account\"] = user.account\n user_dict[\"role\"] = user.role\n user_list.append(user_dict)\n\n self.finish(self.assemble_data(data=user_list, total=total, code=200))\n\n @tornado.gen.coroutine\n def delete(self, *args, **kwargs):\n user_id = self.get_argument(\"id\", 0)\n del_info = {\"status\": -1, \"modify_time\": int(time.time() * 1000)}\n try:\n User.get(ident=user_id).update(**del_info)\n except Exception as e:\n print(\"delete user failed, error is: %s; id is: %s\" % (e, user_id))\n self.finish({\"flag\": True, \"code\": 400})\n else:\n self.log()\n self.finish({\"flag\": True, \"code\": 200})\n\n\nclass UserModifyHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def post(self, *args, **kwargs):\n data = json.loads(self.request.body.decode())\n current_time = int(time.time() * 1000)\n action = data[\"action\"]\n pos_data = data[\"item\"]\n pos_data[\"modify_time\"] = current_time\n try:\n if action == \"add\":\n pos_data[\"status\"] = 0\n pos_data[\"create_time\"] = current_time\n pos_data[\"tel\"] = None\n pos_data[\"token\"] = None\n User.create(**pos_data)\n else:\n User.update_or_create(id=pos_data[\"id\"], defaults=pos_data)\n except Exception as e:\n print(\"update user failed error is: %s; data is %s\" % (e, pos_data))\n self.finish({\"flag\": True, \"code\": 400})\n else:\n self.log()\n self.finish({\"flag\": True, \"code\": 200})\n\n\nclass LogHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self, *args, **kwargs):\n page = int(self.get_argument(\"page\", 1))\n pagesize = int(self.get_argument(\"pagesize\", 10))\n start_time = int(self.get_argument(\"start_time\")) if self.get_argument(\"start_time\", \"\") != \"\" else 0\n end_time = int(self.get_argument(\"end_time\")) if self.get_argument(\"end_time\", \"\") != \"\" else 10000000000000\n user_name = self.get_argument(\"user_name\", \"\")\n operate_type = int(self.get_argument(\"operate_type\")) if self.get_argument(\"operate_type\",\n \"\") != \"\" else -1 # -1表示未知\n now = self.get_argument(\"now\", \"\")\n operate_object = self.get_argument(\"operate_object\", \"\")\n log_list = OperationLog.query \\\n .filter(OperationLog.operate_time >= start_time, OperationLog.operate_time <= end_time) \\\n .filter(OperationLog.user_name.like(\"%\" + user_name + \"%\")) \\\n .filter(OperationLog.operate_object.like(\"%\" + operate_object + \"%\")) \\\n .filter(OperationLog.now.like(\"%\" + now + \"%\"))\n if operate_type != -1:\n log_list = log_list.filter_by(operate_type=operate_type)\n\n total = log_list.count()\n return_data = log_list.order_by(OperationLog.id.desc()).offset((page - 1) * pagesize).limit(pagesize).all()\n for log in return_data:\n log.operate_time = convert_date(time_stamp=log.operate_time, seconds=True, ms=True, format=\"/\")\n\n res = self.assemble_data(data=self.list_json(return_data), code=200, total=total)\n self.finish(res)\n\n\nclass UserInfoHandler(ShareitBaseHandler):\n @tornado.gen.coroutine\n def get(self):\n token = self.get_argument(\"token\", \"\")\n roles = []\n user_obj = User.query.filter_by(status=0, token=token).first()\n data = {\n \"user_name\": \"\",\n \"account\": \"\",\n \"roles\": [],\n }\n if user_obj is not None:\n user_name = user_obj.user_name\n account = user_obj.account\n roles.append(user_obj.role)\n data = {\n \"user_name\": user_name,\n \"account\": account,\n \"roles\": roles,\n }\n\n res = self.assemble_data(code=200, data=data)\n self.finish(res)\n\n# 晓科:priority返回空字符串,这样的话每条数据后面都要加个空字符串的\n","sub_path":"ssp/views/AdminHandler.py","file_name":"AdminHandler.py","file_ext":"py","file_size_in_byte":28522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"572893595","text":"\"\"\"\nMichael S. Emanuel\nWed May 2 12:52:58 2018\n\nSpecial subset sums: testing\nProblem 105\n\nLet S(A) represent the sum of elements in set A of size n.\nWe shall call it a special sum set if for any two non-empty disjoint subsets, B and C,\nthe following properties are true:\n S(B) ≠ S(C); that is, sums of subsets cannot be equal.\n If B contains more elements than C then S(B) > S(C).\n\nFor example, {81, 88, 75, 42, 87, 84, 86, 65} is not a special sum set because\n65 + 87 + 88 = 75 + 81 + 84, whereas {157, 150, 164, 119, 79, 159, 161, 139, 158}\nsatisfies both rules for all possible subset pair combinations and S(A) = 1286.\n\nUsing sets.txt (right click and \"Save Link/Target As...\"), a 4K text file with one-hundred sets\ncontaining seven to twelve elements (the two examples given above are the first two sets in the\nfile), identify all the special sum sets, A1, A2, ..., Ak, and find the value of\nS(A1) + S(A2) + ... + S(Ak).\nNOTE: This problem is related to Problem 103 and Problem 106.\n\"\"\"\n\n# from Euler.SpecialSubsetSums import isSpecialSumSet\nfrom Euler.SpecialSubsetSums import isSpecialSumSet_BF\nfrom typing import List, Tuple\n\n\ndef loadData() -> List[Tuple[int, ...]]:\n fileName: str = 'DataFiles/p105_sets.txt'\n with open(fileName) as fh:\n lines: List[str] = fh.readlines()\n rows: List[List[str]] = [line.strip().split(',') for line in lines]\n return [tuple([int(x) for x in row]) for row in rows]\n\n\ndef main() -> int:\n # Load the data\n testSets: List[Tuple[int, ...]] = loadData()\n # Accumulator for sum of testSets that are special sum set\n sssTotal: int = 0\n sssCount: int = 0\n for testSet in testSets:\n if isSpecialSumSet_BF(testSet):\n sssCount += 1\n sssTotal += sum(testSet)\n print(f'Found {sssCount} Special Sum Sets.')\n print(f'Their sum (and the answer) is {sssTotal}.')\n return sssTotal\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Prob105_SpecialSubsetSums-Testing.py","file_name":"Prob105_SpecialSubsetSums-Testing.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"391306904","text":"import os\n\nfrom chalice import *\n\nfrom chalicelib.database.models import *\n\nDEFAULT_COGNITO_IDENTITY_ID = os.environ.get('DEFAULT_COGNITO_IDENTITY_ID')\n\ndef get_cognito_id(identity):\n cognitoIdentityId = identity.get('cognitoIdentityId', DEFAULT_COGNITO_IDENTITY_ID)\n if not cognitoIdentityId:\n cognitoIdentityId = DEFAULT_COGNITO_IDENTITY_ID\n return cognitoIdentityId\n\n\ndef authorize_user(identity):\n cognito_id = get_cognito_id(identity)\n try:\n user_profile = AuthProvider.get(AuthProvider.cognito_id == cognito_id).user\n if user_profile.status == UserProfile.STATUS_PENDING:\n raise UnauthorizedError('You are pending for activation.')\n elif user_profile.status == UserProfile.STATUS_SUSPENDED:\n raise UnauthorizedError('You are suspended.')\n elif user_profile.status != UserProfile.STATUS_ACTIVE:\n raise UnauthorizedError('You are invalid user.')\n return user_profile\n except AuthProvider.DoesNotExist:\n raise UnauthorizedError('Sign-in user is not found.')\n\n\ndef authorize_teacher(user_profile):\n if not (user_profile.is_teacher()\n and user_profile.teacher_info[0].is_teacher()):\n raise ForbiddenError()\n\n\ndef authorize_admin(user_profile):\n if not (user_profile.is_admin()):\n raise ForbiddenError()\n\n\ndef authorize_manager(user_profile):\n if not (user_profile.is_teacher()\n and user_profile.teacher_info[0].is_manager()):\n raise ForbiddenError()\n\n\ndef authorize_caregiver(user_profile):\n if not user_profile.is_caregiver():\n raise ForbiddenError()\n\n\ndef authorize_caregiver_of_student(user_profile, student_id):\n try:\n (Caregiver.select()\n .where(Caregiver.user == user_profile)\n .where((Caregiver.account_type == Caregiver.TYPE_CAREGIVER)\n | (Caregiver.account_type == Caregiver.TYPE_GUARDIAN))\n .where(Caregiver.student == student_id).get())\n except Caregiver.DoesNotExist:\n raise ForbiddenError()\n\n\ndef authorize_guardian_of_student(user_profile, student_id):\n try:\n (Caregiver.select()\n .where(Caregiver.user == user_profile)\n .where(Caregiver.account_type == Caregiver.TYPE_GUARDIAN)\n .where(Caregiver.student == student_id).get())\n except Caregiver.DoesNotExist:\n raise ForbiddenError()\n\n\ndef authorize_teacher_of_student(user_profile, student_id):\n try:\n (Student.select()\n .where(Student.id == student_id)\n .where(Student.centre == user_profile.teacher_info[0].centre).get())\n except Student.DoesNotExist:\n raise ForbiddenError()\n\n","sub_path":"server/chalicelib/helpers/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"473972873","text":"#!/usr/bin/python\n\n# Has dependency on the OpenCV Library\n# OpenCV: http://opencv.org/\nimport cv\n\nimport argparse\nimport json\nfrom PIL import Image \nfrom time import gmtime, strftime\n\n# Globals\n\nMIN_SIZE = (20, 20)\nIMAGE_SCALE = 1\nHAAR_SCALE = 1.2\nMIN_NEIGHBORS = 2\nHAAR_FLAGS = 0\nHAAR_TRAINER = \"haarcascade_frontalface_alt.xml\"\n\nclass Imag:\n def __init__(self,image_name,cascade):\n try:\n image = cv.LoadImage(image_name, 1)\n except IOError:\n return \n except:\n return\n else:\n self.faces = []\n #Allocate Space for grayscale image and tiny image\n #Dramatically reduces computation time in exchange for temporary space\n grayscale = cv.CreateImage((image.width,image.height),8,1)\n img = cv.CreateImage((cv.Round(image.width/IMAGE_SCALE),cv.Round(image.height/IMAGE_SCALE)),8,1)\n\n cv.CvtColor(image,grayscale,cv.CV_BGR2GRAY)\n cv.Resize(grayscale,img,cv.CV_INTER_LINEAR)\n cv.EqualizeHist(img,img)\n\n matches = cv.HaarDetectObjects(img,cascade,cv.CreateMemStorage(0),HAAR_SCALE,IMAGE_SCALE,HAAR_FLAGS,MIN_SIZE)\n for ((x,y,width,height),wat) in matches:\n self.faces.append({\"x\":x,\"y\":y,\"width\":width,\"height\":height})\n self.name=image_name\n\nclass batchImag:\n def __init__(self,images,trainer,owner):\n try:\n cascade = cv.Load(trainer)\n except TypeError:\n return \n except:\n return\n else: \n self.data = {}\n self.owner = str(owner)\n for image_name in images:\n image = Imag(image_name,cascade)\n self.data[image_name]=image.faces\n \n def printDataJSON(self):\n size = 200, 200\n data = [] \n for key in self.data.keys():\n im = Image.open(key)\n for crop in self.data[key]:\n time = strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n im.crop((crop['x'],crop['y'],crop['x']+crop['width'],crop['y']+crop['height'])).resize(size).save(key)\n data.append(key)\n print(json.dumps(data))\n\ndef main():\n parser = argparse.ArgumentParser(description='Facial detection program built on the OpenCV library.')\n parser.add_argument('files', nargs='*', help=' ...')\n parser.add_argument('--cascade', dest='cascade', default=HAAR_TRAINER, help='Haar cascade file trained facial detection')\n parser.add_argument('--owner', dest='owner', help='Haar cascade file trained facial detection')\n pargs = parser.parse_args()\n\n images = batchImag(pargs.files,pargs.cascade,pargs.owner)\n images.printDataJSON()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"lib/python2.7/face_crop/face_crop.py","file_name":"face_crop.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"288800016","text":"from pico2d import *\nimport game_framework\nimport game_state\n\ndef enter():\n global image, bgm, button, buttonwav, bt1state, bt2state, explain, explainstate, bt, bt1, bt2, bt3, bt4, start, startstate\n image = load_image('image/title.png')\n button = load_image('image/titlebutton.png')\n bgm=load_music('music/title_music.mp3')\n bgm.set_volume(70)\n bgm.repeat_play()\n buttonwav = load_wav('music/button.wav')\n buttonwav.set_volume(100)\n bt1state=0\n bt2state=0\n explain=[]\n explain.append(load_image('image/설명1.png'))\n explain.append(load_image('image/설명2.png'))\n explain.append(load_image('image/설명3.png'))\n explain.append(load_image('image/설명4.png'))\n explain.append(load_image('image/설명5.png'))\n explain.append(load_image('image/설명6.png'))\n explain.append(load_image('image/설명7.png'))\n explain.append(load_image('image/설명8.png'))\n explain.append(load_image('image/설명9.png'))\n explain.append(load_image('image/설명10.png'))\n explain.append(load_image('image/설명11.png'))\n explain.append(load_image('image/설명12.png'))\n explainstate=-1\n bt=[]\n bt.append(load_image('image/bt1.png'))\n bt.append(load_image('image/bt2.png'))\n bt.append(load_image('image/bt3.png'))\n bt.append(load_image('image/bt4.png'))\n start=[]\n start.append(load_image('image/시작1.png'))\n start.append(load_image('image/시작2.png'))\n startstate=-1\n bt1=False\n bt2=False\n bt3=False\n bt4=False\n\ndef exit():\n global image, bgm, button, buttonwav, explain, bt, start\n del(image)\n del(bgm)\n del(button)\n del(buttonwav)\n del(explain)\n del(bt)\n del(start)\n\ndef draw():\n clear_canvas()\n image.draw(400,300)\n button.clip_draw(bt1state*223,0,222,64,243,65)\n button.clip_draw(bt2state*223,64,222,64,563,65)\n if explainstate>-1 and explainstate<12:\n explain[explainstate].draw(400,300)\n if bt1==True:\n bt[0].draw(195,221)\n if bt2==True:\n bt[1].draw(632,221)\n if bt3==True and explainstate>0:\n bt[2].draw(432,254)\n if bt4==True and explainstate<11:\n bt[3].draw(483,254)\n if startstate >= 0:\n start[startstate].draw(400,300)\n if bt1 == True:\n bt[0].draw(195, 221)\n if bt2 == True:\n bt[1].draw(632, 221)\n if bt4 == True:\n bt[3].draw(483, 254)\n update_canvas()\n\ndef update():\n delay(0.03)\n \ndef handle_events():\n global bt1state, bt2state, explainstate, bt1, bt2, bt3, bt4, startstate\n events=get_events()\n for event in events:\n if event.type ==SDL_QUIT:\n game_framework.quit()\n elif event.type==SDL_KEYDOWN:\n if event.key == SDLK_SPACE and startstate>=0:\n if startstate == 0:\n game_state.mode = 'AI'\n elif startstate == 1:\n game_state.mode = 'PVP'\n game_framework.push_state(game_state)\n elif event.key == SDLK_UP:\n startstate = 0\n elif event.key ==SDLK_DOWN:\n startstate = 1\n elif event.key == SDLK_ESCAPE:\n game_framework.quit()\n elif event.type == SDL_MOUSEMOTION:\n tx, ty = event.x, 600 - event.y\n if tx>=131 and tx<=354 and ty>=32 and ty<=98 and bt1state==0:\n bt1state=1\n buttonwav.play()\n elif tx<131 or tx>354 or ty<32 or ty>98:\n bt1state=0\n if tx>=452 and tx<=674 and ty>=32 and ty<=98 and bt2state==0:\n bt2state=1\n buttonwav.play()\n elif tx<452 or tx>674 or ty<32 or ty>98:\n bt2state=0\n if (explainstate>=0 and explainstate<=11) or startstate>=0:\n if tx > 147 and tx < 243 and ty > 211 and ty < 231 and bt1==False:\n bt1=True\n buttonwav.play()\n elif tx<=147 or tx>=243 or ty<=211 or ty>=231:\n bt1=False\n if tx > 610 and tx < 654 and ty > 211 and ty < 231 and bt2==False:\n bt2=True\n buttonwav.play()\n elif tx<=610 or tx>=654 or ty<=211 or ty>=231:\n bt2=False\n if explainstate>0 and tx>411 and tx<455 and ty>244 and ty<264 and bt3==False:\n bt3=True\n buttonwav.play()\n elif tx<=411 or tx>=455 or ty<=244 or ty>=264:\n bt3=False\n if explainstate<11 and tx>461 and tx<505 and ty>244 and ty<264 and bt4==False:\n bt4=True\n buttonwav.play()\n elif tx<=461 or tx>=505 or ty<=244 or ty>=264:\n bt4=False\n if startstate>=0:\n if tx>177 and tx<273 and ty>290 and ty<310:\n startstate=1\n elif tx>177 and tx<273 and ty>310 and ty<330:\n startstate=0\n\n\n elif event.type == SDL_MOUSEBUTTONDOWN:\n tx, ty = event.x, 600 - event.y\n if event.button == SDL_BUTTON_LEFT:\n if tx >= 131 and tx <= 354 and ty >= 32 and ty <= 98:\n startstate=0\n if tx>=452 and tx<=674 and ty>=32 and ty<=98:\n explainstate=0\n if explainstate>=0 and explainstate<=11:\n if tx>147 and tx<243 and ty>211 and ty<231:\n explainstate=-1\n if tx>610 and tx<654 and ty>211 and ty<231:\n explainstate=-1\n if explainstate > 0 and tx > 411 and tx < 455 and ty > 244 and ty < 264:\n explainstate-=1\n if explainstate < 11 and tx > 461 and tx < 505 and ty > 244 and ty < 264:\n explainstate+=1\n if startstate>=0:\n if tx>147 and tx<243 and ty>211 and ty<231:\n startstate=-1\n if tx>610 and tx<654 and ty>211 and ty<231:\n if startstate==0:\n game_state.mode = 'AI'\n elif startstate==1:\n game_state.mode = 'PVP'\n game_framework.push_state(game_state)\n if explainstate < 11 and tx > 461 and tx < 505 and ty > 244 and ty < 264:\n if startstate==0:\n game_state.mode = 'AI'\n elif startstate==1:\n game_state.mode = 'PVP'\n game_framework.push_state(game_state)\n if tx > 177 and tx < 273 and ty > 290 and ty < 310:\n game_state.mode = 'PVP'\n game_framework.push_state(game_state)\n elif tx > 177 and tx < 273 and ty > 310 and ty < 330:\n game_state.mode = 'AI'\n game_framework.push_state(game_state)\n\ndef pause():\n pass\n\ndef resume():\n pass\n\nif __name__=='__main__':\n import sys\n current_module = sys.modules[__name__]\n open_canvas()\n game_framework.run(current_module)\n close_canvas()\n","sub_path":"Term/title_state.py","file_name":"title_state.py","file_ext":"py","file_size_in_byte":7278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"466453912","text":"__author__ = 'alexander'\n\nimport tensorflow as tf\n\nx = tf.Variable(3, name='x')\ny = tf.Variable(4, name='y')\nz = x + y\n\nwith tf.Session() as sess:\n sess.run(tf.initialize_all_variables())\n result = sess.run(z)\n print(result)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"366951642","text":"# -*- coding: utf-8 -*-\n\nimport queue\n\nimport pathfinding\n\ndef astar(depart,arrivee,murs):\n if depart == arrivee:\n return []\n \n frontiere = queue.PriorityQueue()\n frontiere.put((0, depart))\n \n precedent = {}\n precedent[depart] = None\n \n cout_courrant = {}\n cout_courrant[depart] = 0\n\n while not frontiere.empty():\n (optimal,courrant) = frontiere.get()\n\n if courrant == arrivee:\n break\n \n for suivant in pathfinding.neighbors(murs,courrant):\n cout = cout_courrant[courrant] + 1\n if suivant not in cout_courrant or cout < cout_courrant[suivant]:\n cout_courrant[suivant] = cout\n optimal = cout + pathfinding.manhattan_distance(arrivee, suivant)\n frontiere.put((optimal,suivant))\n precedent[suivant] = courrant \n \n courrant = arrivee\n chemin = []\n\n while courrant != depart:\n chemin.append(courrant)\n courrant = precedent[courrant] \n chemin.reverse()\n \n return chemin","sub_path":"kolkata-restaurant/astar.py","file_name":"astar.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"281451913","text":"from ftw.builder import Builder\nfrom ftw.builder import create\nfrom opengever.meeting.committee import get_group_vocabulary\nfrom opengever.meeting.committeeroles import CommitteeRoles\nfrom opengever.testing import FunctionalTestCase\nfrom opengever.testing import IntegrationTestCase\n\n\nclass TestCommitteeTabs(FunctionalTestCase):\n\n def setUp(self):\n super(TestCommitteeTabs, self).setUp()\n\n self.container = create(Builder('committee_container'))\n self.committee = create(Builder('committee')\n .within(self.container))\n\n def test_committee_roles_initialized(self):\n self.assertEqual(\n ('CommitteeResponsible', ),\n dict(self.committee.get_local_roles())['client1_users'])\n\n def test_update_roles_removes_old_role(self):\n CommitteeRoles(self.committee).update(\n 'foo', previous_principal='client1_users')\n\n local_roles = dict(self.committee.get_local_roles())\n self.assertNotIn('client1_users', local_roles)\n self.assertEqual(('CommitteeResponsible',),\n local_roles['foo'])\n\n def test_update_roles_preserves_unmanaged_roles(self):\n self.committee.manage_addLocalRoles('foo',\n ['Contributor', 'Administrator'])\n self.committee.manage_addLocalRoles(\n 'client1_users', ['Contributor'])\n\n CommitteeRoles(self.committee).update(\n 'foo', previous_principal='client1_users')\n local_roles = dict(self.committee.get_local_roles())\n self.assertItemsEqual(\n ['Administrator', 'CommitteeResponsible', 'Contributor'],\n local_roles['foo'])\n self.assertItemsEqual(\n ['Contributor'],\n local_roles['client1_users'])\n\n def test_principal_of_managed_roles_is_a_bytestring(self):\n for principal, roles in self.committee.get_local_roles():\n self.assertTrue(isinstance(principal, str), 'Not a byte string')\n\n\nclass TestCommitteeGroupsVocabulary(IntegrationTestCase):\n\n def test_return_all_groups(self):\n self.login(self.committee_responsible)\n\n self.assertItemsEqual(\n [u'fa_users',\n u'fa_inbox_users',\n u'projekt_a',\n u'projekt_b',\n u'committee_rpk_group',\n u'committee_ver_group'],\n [term.value for term in\n get_group_vocabulary(self.committee_container)])\n","sub_path":"opengever/meeting/tests/test_committee_roles.py","file_name":"test_committee_roles.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"54795526","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\nimport spiceypy as spice\r\nprint(\"Toolkit Version: \" + spice.tkvrsn(\"TOOLKIT\")) #prints version of toolkit\r\n\r\nspice.furnsh(\"./cassMetaK.txt\")\r\n\r\nstep = 4000\r\n\r\nutc = ['Jun 20, 2004', 'Dec 1, 2005'] #Get positions between these two dates\r\n\r\netOne = spice.str2et(utc[0]) #get et values one...\r\netTwo = spice.str2et(utc[1]) #...and two, we could vectorize str2et\r\nprint(\"ET One: {}, ET Two: {}\".format(etOne, etTwo))\r\n\r\ntimes = [x*(etTwo-etOne)/step + etOne for x in range(step)] # get times\r\n\r\n\r\nprint(times[0:3]) #prints the first few times:\r\n\r\n#Runs spkpos as a vectorized function\r\npositions, lightTimes = spice.spkpos('Cassini', times, 'J2000', 'NONE', 'SATURN BARYCENTER')\r\n\r\n# Positions is a 3xN vector of XYZ positions\r\nprint(\"Positions: \")\r\nprint(positions[0])\r\n\r\n# Light times is a N vector of time\r\nprint(\"Light Times: \")\r\nprint(lightTimes[0])\r\n\r\n#Graphs the stuff\r\nfig = plt.figure(figsize=(9, 9))\r\nax = fig.add_subplot(111, projection='3d')\r\nax.plot(positions.T[0], positions.T[1], positions.T[2])\r\nplt.title('SpiceyPy Cassini Position Example from Jun 20, 2004 to Dec 1, 2005')\r\nplt.show()\r\n","sub_path":"Cassini Example/cassiniExample.py","file_name":"cassiniExample.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"360593150","text":"# coding: utf8\n\"\"\"\nHelpers for Python and platform compatibility. To distinguish them from\nthe builtin functions, replacement functions are suffixed with an underscore,\ne.g. `unicode_`.\n\nDOCS: https://spacy.io/api/top-level#compat\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport os\nimport sys\nimport itertools\nimport ast\nimport types\n\nfrom thinc.neural.util import copy_array\n\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\ntry:\n import copy_reg\nexcept ImportError:\n import copyreg as copy_reg\n\ntry:\n from cupy.cuda.stream import Stream as CudaStream\nexcept ImportError:\n CudaStream = None\n\ntry:\n import cupy\nexcept ImportError:\n cupy = None\n\ntry:\n from thinc.neural.optimizers import Optimizer # noqa: F401\nexcept ImportError:\n from thinc.neural.optimizers import Adam as Optimizer # noqa: F401\n\npickle = pickle\ncopy_reg = copy_reg\nCudaStream = CudaStream\ncupy = cupy\ncopy_array = copy_array\nizip = getattr(itertools, \"izip\", zip)\n\nis_windows = sys.platform.startswith(\"win\")\nis_linux = sys.platform.startswith(\"linux\")\nis_osx = sys.platform == \"darwin\"\n\n# See: https://github.com/benjaminp/six/blob/master/six.py\nis_python2 = sys.version_info[0] == 2\nis_python3 = sys.version_info[0] == 3\nis_python_pre_3_5 = is_python2 or (is_python3 and sys.version_info[1] < 5)\n\nif is_python2:\n bytes_ = str\n unicode_ = unicode # noqa: F821\n basestring_ = basestring # noqa: F821\n input_ = raw_input # noqa: F821\n path2str = lambda path: str(path).decode(\"utf8\")\n class_types = (type, types.ClassType)\n\nelif is_python3:\n bytes_ = bytes\n unicode_ = str\n basestring_ = str\n input_ = input\n path2str = lambda path: str(path)\n class_types = (type, types.ClassType) if is_python_pre_3_5 else type\n\n\ndef b_to_str(b_str):\n \"\"\"Convert a bytes object to a string.\n\n b_str (bytes): The object to convert.\n RETURNS (unicode): The converted string.\n \"\"\"\n if is_python2:\n return b_str\n # Important: if no encoding is set, string becomes \"b'...'\"\n return str(b_str, encoding=\"utf8\")\n\n\ndef symlink_to(orig, dest):\n \"\"\"Create a symlink. Used for model shortcut links.\n\n orig (unicode / Path): The origin path.\n dest (unicode / Path): The destination path of the symlink.\n \"\"\"\n if is_windows:\n import subprocess\n\n subprocess.check_call(\n [\"mklink\", \"/d\", path2str(orig), path2str(dest)], shell=True\n )\n else:\n orig.symlink_to(dest)\n\n\ndef symlink_remove(link):\n \"\"\"Remove a symlink. Used for model shortcut links.\n\n link (unicode / Path): The path to the symlink.\n \"\"\"\n # https://stackoverflow.com/q/26554135/6400719\n if os.path.isdir(path2str(link)) and is_windows:\n # this should only be on Py2.7 and windows\n os.rmdir(path2str(link))\n else:\n os.unlink(path2str(link))\n\n\ndef is_config(python2=None, python3=None, windows=None, linux=None, osx=None):\n \"\"\"Check if a specific configuration of Python version and operating system\n matches the user's setup. Mostly used to display targeted error messages.\n\n python2 (bool): spaCy is executed with Python 2.x.\n python3 (bool): spaCy is executed with Python 3.x.\n windows (bool): spaCy is executed on Windows.\n linux (bool): spaCy is executed on Linux.\n osx (bool): spaCy is executed on OS X or macOS.\n RETURNS (bool): Whether the configuration matches the user's platform.\n\n DOCS: https://spacy.io/api/top-level#compat.is_config\n \"\"\"\n return (\n python2 in (None, is_python2)\n and python3 in (None, is_python3)\n and windows in (None, is_windows)\n and linux in (None, is_linux)\n and osx in (None, is_osx)\n )\n\n\ndef import_file(name, loc):\n \"\"\"Import module from a file. Used to load models from a directory.\n\n name (unicode): Name of module to load.\n loc (unicode / Path): Path to the file.\n RETURNS: The loaded module.\n \"\"\"\n loc = path2str(loc)\n if is_python_pre_3_5:\n import imp\n\n return imp.load_source(name, loc)\n else:\n import importlib.util\n\n spec = importlib.util.spec_from_file_location(name, str(loc))\n module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(module)\n return module\n\n\ndef unescape_unicode(string):\n \"\"\"Python2.7's re module chokes when compiling patterns that have ranges\n between escaped unicode codepoints if the two codepoints are unrecognised\n in the unicode database. For instance:\n\n re.compile('[\\\\uAA77-\\\\uAA79]').findall(\"hello\")\n\n Ends up matching every character (on Python 2). This problem doesn't occur\n if we're dealing with unicode literals.\n \"\"\"\n if string is None:\n return string\n # We only want to unescape the unicode, so we first must protect the other\n # backslashes.\n string = string.replace(\"\\\\\", \"\\\\\\\\\")\n # Now we remove that protection for the unicode.\n string = string.replace(\"\\\\\\\\u\", \"\\\\u\")\n string = string.replace(\"\\\\\\\\U\", \"\\\\U\")\n # Now we unescape by evaling the string with the AST. This can't execute\n # code -- it only does the representational level.\n return ast.literal_eval(\"u'''\" + string + \"'''\")\n","sub_path":"spacy/compat.py","file_name":"compat.py","file_ext":"py","file_size_in_byte":5215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"632015334","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.3 (3230)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/lsbardel/workspace/python-stdnet/extensions/setup.py\n# Compiled at: 2013-06-20 16:59:58\n# Size of source mod 2**32: 2527 bytes\nimport os, sys\nfrom distutils.core import setup\nfrom distutils.extension import Extension\nfrom distutils.errors import CCompilerError, DistutilsExecError, DistutilsPlatformError\nfrom Cython.Distutils import build_ext\nfrom Cython.Build import cythonize\ntry:\n import numpy\n include_dirs = [\n numpy.get_include()]\nexcept ImportError:\n include_dirs = []\n\next_errors = (\n CCompilerError, DistutilsExecError, DistutilsPlatformError)\nif sys.platform == 'win32':\n if sys.version_info > (2, 6):\n ext_errors += (IOError,)\n\nclass BuildFailed(Exception):\n\n def __init__(self, msg=None):\n if not msg:\n msg = str(sys.exc_info()[1])\n self.msg = msg\n\n\nclass tolerant_build_ext(build_ext):\n\n def run(self):\n try:\n build_ext.run(self)\n except DistutilsPlatformError:\n raise BuildFailed\n\n def build_extension(self, ext):\n try:\n build_ext.build_extension(self, ext)\n except ext_errors:\n raise BuildFailed\n except ValueError:\n if \"'path'\" in str(sys.exc_info()[1]):\n raise BuildFailed\n raise\n\n\nlib_path = os.path.dirname(__file__)\nextra_compile_args = []\nextension = Extension('stdnet.backends.redisb.cparser', [\n os.path.join(lib_path, 'src', 'cparser.pyx')], language='c++', include_dirs=include_dirs)\ninclude_dirs.append(os.path.join(lib_path, 'src'))\nlibparams = {'ext_modules': cythonize(extension), \n 'cmdclass': {'build_ext': tolerant_build_ext}, 'include_dirs': include_dirs}","sub_path":"pycfiles/python-stdnet-0.8.2.tar/setup.cpython-33.py","file_name":"setup.cpython-33.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"382576408","text":"import re\n\nnumbers = re.findall('\\d+', '5x + 2y = 5')\n\nprint(numbers[0])\n\nprint(numbers[1])\n\nprint(numbers[2])\n\n\ninput = 'x(4x(3x)) = (2y)'.replace(\" \", \"\")\nprint(input)\n\n# Step 1: Equal sign (=)\n\nequal = input.find('=')\n\nleftside = input[0:equal]\nrightside = input[equal+1:]\n\nprint(leftside)\nprint(rightside)\n\n\n# Step 2: Brackets ()\n# Procedure:\n\"\"\"\n1. Find first ( and first )\n2. delete from initial string and replace it with V1, V2 ... \n3. Store that string \n\n\nException: x(3x(5x)) so if in this bracket part, other brackets are present, continue with the inner part\n\"\"\"\n\nbracket1 = input.find('(')\nbracket2 = input.find(')')\n\nbrackets = input[bracket1+1:bracket2]\nprint(brackets)\n\n\n# Must be a for loop untill ???\n\nif '(' in brackets:\n tempbracket = brackets.find('(')\n print(tempbracket)\n newposbracket = tempbracket + bracket1\n\nelse:\n print(\"There are no other brackets\")\n\ntempinput = input\n\n# Next lines of code need to be fixed\n\ntempinput.replace(tempinput[newposbracket:bracket2], 'V1')\n\nprint(tempinput)","sub_path":"process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"517677293","text":"import torch \r\nimport torch.nn.functional as F\r\nimport torchvision.transforms as transforms\r\n\r\nimport numpy as np\r\nfrom PIL import Image\r\n\r\n\r\n\r\ndef DUF_downsample(x, scale=4):\r\n \"\"\"Downsamping with Gaussian kernel used in the DUF official code\r\n\r\n Args:\r\n x (Tensor, [B, T, C, H, W]): frames to be downsampled.\r\n scale (int): downsampling factor: 2 | 3 | 4.\r\n \"\"\"\r\n\r\n assert scale in [2, 3, 4], 'Scale [{}] is not supported'.format(scale)\r\n\r\n def gkern(kernlen=13, nsig=1.6):\r\n import scipy.ndimage.filters as fi\r\n inp = np.zeros((kernlen, kernlen))\r\n # set element at the middle to one, a dirac delta\r\n inp[kernlen // 2, kernlen // 2] = 1\r\n # gaussian-smooth the dirac, resulting in a gaussian filter mask\r\n return fi.gaussian_filter(inp, nsig)\r\n\r\n T = len(x)\r\n x = torch.stack(x, 1)\r\n \r\n B, T, C, H, W = x.size()\r\n x = x.view(-1, 1, H, W)\r\n pad_w, pad_h = 6 + scale * 2, 6 + scale * 2 # 6 is the pad of the gaussian filter\r\n r_h, r_w = 0, 0\r\n if scale == 3:\r\n r_h = 3 - (H % 3)\r\n r_w = 3 - (W % 3)\r\n x = F.pad(x, [pad_w, pad_w + r_w, pad_h, pad_h + r_h], 'reflect')\r\n\r\n gaussian_filter = torch.from_numpy(gkern(13, 0.4 * scale)).type_as(x).unsqueeze(0).unsqueeze(0)\r\n x = F.conv2d(x, gaussian_filter, stride=scale)\r\n x = x[:, :, 2:-2, 2:-2]\r\n x = x.view(B, T, C, x.size(2), x.size(3))\r\n\r\n outs = []\r\n\r\n for t in range(T):\r\n outs.append(x[:,t])\r\n\r\n return outs\r\n\r\n\r\ndef load_pretrained_weight(model, path):\r\n\r\n pretrained_dict = torch.load(path)\r\n model_dict = model.state_dict()\r\n pretrained_dict = {k:v for k,v in pretrained_dict.items() if k in model_dict}\r\n model_dict.update(pretrained_dict)\r\n model.load_state_dict(model_dict)\r\n\r\n return model\r\n\r\ndef pad_img(x, scale_factor=4):\r\n\r\n b,c,h,w = x.size()\r\n wt = (( w//(64*scale_factor)+1)*64*scale_factor -w)\r\n ht = (( h//(64*scale_factor)+1)*64*scale_factor -h)\r\n wp = np.int(wt/2)\r\n hp = np.int(ht/2)\r\n x = F.pad(x, pad=[wp,wp,hp,hp], mode='replicate')\r\n\r\n return x, wp, hp\r\n\r\ndef tensor_to_numpy(x, is_cuda = True):\r\n\r\n if is_cuda:\r\n x = x.cpu().data.numpy()\r\n x = np.transpose(x.astype('float32'), [0,2,3,1])\r\n x = np.clip((x+1.)/2., 0,1)\r\n \r\n return x\r\n\r\ndef numpy_to_tensor(x, is_cuda = True):\r\n \r\n transformations = transforms.Compose(\r\n [transforms.ToTensor(), \r\n transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))])\r\n \r\n x = transformations(x)\r\n x = x.unsqueeze(0)\r\n if is_cuda:\r\n x = x.float().cuda()\r\n else:\r\n x = x.float()\r\n \r\n return x\r\n\r\ndef num_to_filename(cnt = 1):\r\n\r\n MAX_LEN = 6\r\n str_cnt = str(cnt)\r\n \r\n file_str = '0'\r\n for c in range(MAX_LEN - len(str_cnt)):\r\n file_str += '0'\r\n\r\n file_str += str_cnt\r\n\r\n return file_str\r\n\r\ndef clip_and_numpy(x, wp, hp):\r\n\r\n if(wp !=0 and hp !=0):\r\n x = x[:,:,hp:-hp,wp:-wp]\r\n elif(wp==0 and hp!=0):\r\n x = x[:,:,hp:-hp,:]\r\n elif(wp!=0 and hp==0):\r\n x = x[:,:,:,wp:-wp]\r\n \r\n x = tensor_to_numpy(x)[0] \r\n\r\n return x\r\n\r\ndef save_img(img, save_path):\r\n canvas = np.asarray(img)*255\r\n canvas = canvas.astype(np.uint8)\r\n canvas = Image.fromarray(canvas)\r\n canvas.save(save_path)\r\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"457811649","text":"\"\"\"\nMichael S. Emanuel\nTue Apr 24 16:41:42 2018\n\nMonopoly odds\nProblem 84\nhttps://projecteuler.net/problem=84\n\nSee here for a picture of the board:\nhttps://images-na.ssl-images-amazon.com/images/I/51AnnChCJcL.jpg\n\nIn the game, Monopoly, the standard board is set up in the following way:\n\nGO\tA1\tCC1\tA2\tT1\tR1\tB1\tCH1\tB2\tB3\tJAIL\nH2 C1\nT2 U1\nH1 C2\nCH3 C3\nR4 R2\nG3 D1\nCC3 CC2\nG2 D2\nG1 D3\nG2J\tF3\tU2\tF2\tF1\tR3\tE3\tE2\tCH2\tE1\t FP\n\nA player starts on the GO square and adds the scores on two 6-sided dice to determine the number\nof squares they advance in a clockwise direction. Without any further rules we would expect to\nvisit each square with equal probability: 2.5%.\nHowever, landing on G2J (Go To Jail), CC (community chest), and CH (chance)\nchanges this distribution.\n\nIn addition to G2J, and one card from each of CC and CH, that orders the player to go directly to\njail, if a player rolls three consecutive doubles, they do not advance the result of their 3rd\nroll. Instead they proceed directly to jail.\n\nAt the beginning of the game, the CC and CH cards are shuffled.\nWhen a player lands on CC or CH they take a card from the top of the respective pile and, after\nfollowing the instructions, it is returned to the bottom of the pile.\nThere are sixteen cards in each pile, but for the purpose of this problem we are only concerned\nwith cards that order a movement; any instruction not concerned with movement will be ignored and\nthe player will remain on the CC/CH square.\n\nCommunity Chest (2/16 cards):\nAdvance to GO\nGo to JAIL\nChance (10/16 cards):\nAdvance to GO\nGo to JAIL\nGo to C1\nGo to E3\nGo to H2\nGo to R1\nGo to next R (railway company)\nGo to next R\nGo to next U (utility company)\nGo back 3 squares.\n\nThe heart of this problem concerns the likelihood of visiting a particular square.\nThat is, the probability of finishing at that square after a roll.\nFor this reason it should be clear that, with the exception of G2J for which the probability of\nfinishing on it is zero, the CH squares will have the lowest probabilities, as 5/8 request a\nmovement to another square, and it is the final square that the player finishes at on each roll\nthat we are interested in. We shall make no distinction between \"Just Visiting\" and being sent to\nJAIL, and we shall also ignore the rule about requiring a double to \"get out of jail\", assuming\nthat they pay to get out on their next turn.\n\nBy starting at GO and numbering the squares sequentially from 00 to 39 we can concatenate these\ntwo-digit numbers to produce strings that correspond with sets of squares.\n\nStatistically it can be shown that the three most popular squares, in order, are\nJAIL (6.24%) = Square 10, E3 (3.18%) = Square 24, and GO (3.09%) = Square 00.\nSo these three most popular squares can be listed with the six-digit modal string: 102400.\n\nIf, instead of using two 6-sided dice, two 4-sided dice are used, find the six-digit modal string.\n\"\"\"\n\nimport numpy as np\nfrom Euler.Utility import range_inc\nfrom typing import List, Tuple, Dict, Callable\n\n# Type aliases\nmsqReturnType = Tuple[Tuple[str, ...], Tuple[int, ...], Dict[int, str], Dict[str, int]]\nmsqtReturnType = Tuple[Tuple[str, ...], Dict[str, str]]\nmdReturnType = msqReturnType\nmstReturnType = msqReturnType\n\n\ndef makeSquares() -> msqReturnType:\n # List of square names\n squareNames: Tuple[str, ...] = (\n 'GO', 'A1', 'CC1', 'A2', 'T1', 'R1', 'B1', 'CH1', 'B2', 'B3', 'JAIL',\n 'C1', 'U1', 'C2', 'C3', 'R2', 'D1', 'CC2', 'D2', 'D3', 'FP',\n 'E1', 'CH2', 'E2', 'E3', 'R3', 'F1', 'F2', 'U2', 'F3', 'G2J',\n 'G1', 'G2', 'CC3', 'G3', 'R4', 'CH3', 'H1', 'T2', 'H2')\n # Number of squares\n N: int = len(squareNames)\n # List of squareIDs; integers from 0 to 39\n squareIDs: Tuple[int, ...] = tuple([n for n in range(N)])\n # Map between square name and number (both ways)\n squareIDtoName: Dict[int, str] = dict([(n, squareNames[n]) for n in squareIDs])\n squareNameToID: Dict[str, int] = dict([(squareNames[n], n) for n in squareIDs])\n # Return these objects\n return (squareNames, squareIDs, squareIDtoName, squareNameToID)\n\n\ndef makeSquareTypes() -> msqtReturnType:\n # Types of squares\n squareTypes: Tuple[str, ...] = ('LAND', 'RR', 'UTIL', 'TAX', 'CH', 'CC', 'G2J', 'JAIL', 'FREE')\n # Map square name to type\n sqNamesByType: Dict[str, Tuple[str, ...]] = dict()\n sqNamesByType['LAND'] = (\n 'A1', 'A2', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3', 'D1', 'D2', 'D3',\n 'E1', 'E2', 'E3', 'F1', 'F2', 'F3', 'G1', 'G2', 'G3', 'H1', 'H2') # 22\n sqNamesByType['RR'] = ('R1', 'R2', 'R3', 'R4') # 4\n sqNamesByType['UTIL'] = ('U1', 'U2') # 2\n sqNamesByType['TAX'] = ('T1', 'T2') # 2\n sqNamesByType['CH'] = ('CH1', 'CH2', 'CH3') # 3\n sqNamesByType['CC'] = ('CC1', 'CC2', 'CC3') # 3\n sqNamesByType['FREE'] = ('GO', 'FP',) # 2\n sqNamesByType['JAIL'] = ('JAIL',) # 1\n sqNamesByType['G2J'] = ('G2J',) # 1\n # Assemble names by type into a a single dictionary mapping names to types\n squareNameToType: Dict['str', 'str'] = \\\n dict([(snm, styp) for (styp, snms) in sqNamesByType.items() for snm in snms])\n # Return sqNameToType map\n return (squareTypes, squareNameToType)\n\n\ndef makeDoubles() -> mdReturnType:\n # The number of consecutive doubles that have been rolled\n doubleNames: Tuple[str, str, str] = ('0', '1', '2')\n doubleIDs: Tuple[int, int, int] = (0, 1, 2)\n doubleIDtoName: Dict[int, str] = dict([(n, doubleNames[n]) for n in doubleIDs])\n doubleNameToID: Dict[str, int] = dict([(doubleNames[n], n) for n in doubleIDs])\n # Return\n return (doubleNames, doubleIDs, doubleIDtoName, doubleNameToID)\n\n\ndef makeDiceRolls(diceSides: int = 6) -> Dict[Tuple[int, bool], float]:\n # Roll of one die\n dieRoll: Tuple[int, ...] = tuple([n for n in range_inc(diceSides)])\n # Dice roll is the number of spaces and a bool indicating whether the roll was a double\n diceRolls: Dict[Tuple[int, bool], float] = dict()\n rollEvents: int = diceSides * diceSides\n for d1 in dieRoll:\n for d2 in dieRoll:\n offset: int = (d1 + d2)\n isDouble: bool = (d1 == d2)\n prob: float = 1.0 / rollEvents\n entry: Tuple[int, bool] = (offset, isDouble)\n diceRolls[entry] = diceRolls.get(entry, 0.0) + prob\n return diceRolls\n\n\ndef makeStates(squareNames: Tuple[str, ...], doubleNames: Tuple[str, ...]) -> mstReturnType:\n # The game state for this exercise is the Cartesian product of the square and the number\n # of consecutive doubles that have been rolled\n stateNames: Tuple[str, ...] = \\\n tuple([squareName + '.' + n for n in doubleNames for squareName in squareNames])\n stateIDs: Tuple[int, ...] = tuple([n for n in range(len(stateNames))])\n stateIDtoName: Dict[int, str] = dict([(n, stateNames[n]) for n in stateIDs])\n stateNameToID: Dict[str, int] = dict([(stateNames[n], n) for n in stateIDs])\n # Return these objects\n return (stateNames, stateIDs, stateIDtoName, stateNameToID)\n\n\n# Main\n\n# Make monopoly squares\nsquareNames: Tuple[str, ...]\nsquareIDs: Tuple[int, ...]\nsquareIDtoName: Dict[int, str]\nsquareNameToID: Dict[str, int]\n(squareNames, squareIDs, squareIDtoName, squareNameToID) = makeSquares()\n\n# Monopoly square types\nsquareTypes: Tuple[str, ...]\nsquareNameToType: Dict[str, str]\n(squareTypes, squareNameToType) = makeSquareTypes()\n\n# Make doubles\ndoubleNames: Tuple[str, ...]\ndoubleIDs: Tuple[int, ...]\ndoubleIDtoName: Dict[int, str]\ndoubleNameToID: Dict[str, int]\n(doubleNames, doubleIDs, doubleIDtoName, doubleNameToID) = makeDoubles()\n# Maximum consecutive doubles (to to jail after 3 doubles)\nmaxConsDouble: int = len(doubleIDs)\n\n# Make dice rolls\ndiceSides: int = 6\ndiceRolls: Dict[Tuple[int, bool], float] = makeDiceRolls(diceSides)\n\n# Make game states\nstateNames: Tuple[str, ...]\nstateIDs: Tuple[int, ...]\nstateIDtoName: Dict[int, str]\nstateNameToID: Dict[str, int]\n(stateNames, stateIDs, stateIDtoName, stateNameToID) = makeStates(squareNames, doubleNames)\n\n# Number of game squares\nN: int = len(squareIDs)\n# Number of game states\nM: int = len(stateIDs)\n\n\ndef shiftedSquareID(squareID: int, offset: int) -> int:\n \"\"\"Shift squareID forward by offset, wrapping around past GO if necessary.\"\"\"\n return (squareID + offset) % N\n\n\ndef stateID_fromParts(squareID: int, doubleID: int) -> int:\n \"\"\"Return a StateID given a SquareID and a DoubleID\"\"\"\n return doubleID * N + squareID\n\n\ndef stateID_toParts(stateID: int) -> Tuple[int, int]:\n \"\"\"Extract the SquareID and DoubleID corresponding to a StateID\"\"\"\n squareID: int = stateID % N\n doubleID: int = stateID // N\n return(squareID, doubleID)\n\n\ndef isBasicSquare(squareID: int) -> bool:\n # Get the type of this square\n squareName: str = squareIDtoName[squareID]\n squareTypeName: str = squareNameToType[squareName]\n # List of basic square types:\n basicSquareTypes = ('LAND', 'RR', 'UTIL', 'TAX', 'JAIL', 'FREE')\n # specialSquareTypes = ('CH', 'CC', 'G2J')\n # Check that the input square has a basic type\n return (squareTypeName in basicSquareTypes)\n\n\ndef squareProbType(squareID: int) -> str:\n \"\"\"Four types of transition probability: BASIC, CC, CH, G2J.\"\"\"\n # Get the type of this square\n squareName: str = squareIDtoName[squareID]\n squareTypeName: str = squareNameToType[squareName]\n # If squareType is not basic, the probType is the same as the squareType\n return 'BASIC' if isBasicSquare(squareID) else squareTypeName\n\n\ndef makeTransProb_Basic(stateID: int) -> np.ndarray:\n \"\"\"Make a transition probability vector for squares with basic type\"\"\"\n # Extract the squareID and doubleID from the stateID\n squareID: int\n doubleID: int\n (squareID, doubleID) = stateID_toParts(stateID)\n\n # Initialize transition probability to zero\n tp: np.ndarray = np.zeros((M, 1))\n # The offset and isDouble flag from dice rolls\n offset: int\n isDouble: bool\n prob: float\n # Square corresponding to jail and go to jail\n squareID_JAIL: int = squareNameToID['JAIL']\n squareID_G2J: int = squareNameToID['G2J']\n\n # Iterate through possible dice rolls\n for (offset, isDouble), prob in diceRolls.items():\n # Did this new roll send you to jail on consecutive doubles?\n # isJail: bool = (doubleID == 2 and isDouble)\n isNormalRoll: bool = not (doubleID == 2 and isDouble)\n # The new squareID and doubleID\n squareID_New: int = shiftedSquareID(squareID, offset) if isNormalRoll else squareID_JAIL\n doubleID_New: int = 0 if not isDouble else ((doubleID + 1) % maxConsDouble)\n # Combine these to get the new stateID\n stateID_New = stateID_fromParts(squareID_New, doubleID_New)\n # Add the probability of this dice roll to entry for stateID_New\n tp[stateID_New] += prob\n\n # Apply go to jail if applicable\n for doubleID in doubleIDs:\n stateID_JAIL = stateID_fromParts(squareID_JAIL, doubleID)\n stateID_G2J = stateID_fromParts(squareID_G2J, doubleID)\n tp[stateID_JAIL] += tp[stateID_G2J]\n tp[stateID_G2J] = 0.0\n\n # Return the assembled transition probability vector\n return tp\n\n\ndef makeTransProb_G2J(stateID: int) -> np.ndarray:\n tp: np.ndarray = np.zeros((M, 1))\n # StateID for jail\n squareID_JAIL: int = squareNameToID['JAIL']\n doubleID: int = 0\n stateID_JAIL: int = stateID_fromParts(squareID_JAIL, doubleID)\n # Set transition probability for jail\n tp[stateID_JAIL] += 1.0\n return tp\n\n\ndef makeTransProb_CC(stateID: int) -> np.ndarray:\n \"\"\"Make special transition probability vector for Community Chest squares.\"\"\"\n # Extract the squareID and doubleID from the stateID\n squareID: int\n doubleID: int\n (squareID, doubleID) = stateID_toParts(stateID)\n # The number of that are basic or special\n cardsBasic: int = 14\n cardsSpecial: int = 2\n # Total number of cards\n cardsTotal: int = cardsBasic + cardsSpecial\n\n assert (cardsTotal == 16), 'Error in Community Chest card total!'\n # First calculate the basic transition probabilities.\n # These will apply if the card picked does not send you to GO or JAIL\n tpBasic: np.ndarray = makeTransProb_Basic(stateID)\n\n # Below calculate the transition probability arising from special cards.\n # 1 / 16 chance Advance to GO\n # 1 / 16 chance Go to JAIL\n tpSpecial: np.ndarray = np.zeros((M, 1))\n # SquareID for JAIL and GO\n squareID_GO: int = squareNameToID['GO']\n squareID_JAIL: int = squareNameToID['JAIL']\n # StateIDs for these squares; when you get sent to jail, double resets to 0\n stateID_GO: int = stateID_fromParts(squareID_GO, doubleID)\n stateID_JAIL: int = stateID_fromParts(squareID_JAIL, doubleID=0)\n # Transition probabilities to these special destination squares\n tpSpecial[stateID_GO] += 1 / cardsSpecial\n tpSpecial[stateID_JAIL] += 1 / cardsSpecial\n # The probability of a special event\n specialProb = cardsSpecial / cardsTotal\n\n # Return the basic and special probabilities\n return (tpBasic, tpSpecial, specialProb)\n\n\n# Reusable table: on one of the three Chance squares, what is the next railroad?\nnextRail: Dict[int, int] = {\n squareNameToID['CH1']: squareNameToID['R2'], # Red Chance -> Pennsylvania RR\n squareNameToID['CH2']: squareNameToID['R3'], # Blue Chance --> B & O RR\n squareNameToID['CH3']: squareNameToID['R1'], # Yellow Chance --> Reading RR\n }\n\n\n# Reusable table: on one of the three Chance squares, what is the next utility?\nnextUtil: Dict[int, int] = {\n squareNameToID['CH1']: squareNameToID['U1'], # Red Chance -> Electric Co.\n squareNameToID['CH2']: squareNameToID['U2'], # Blue Chance --> Water Co.\n squareNameToID['CH3']: squareNameToID['U1'], # Yellow Chance --> Electric Co.\n }\n\n\ndef makeTransProb_CH(stateID: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"Make transition probability vector for Chance squares.\"\"\"\n # Extract the squareID and doubleID from the stateID\n squareID: int\n doubleID: int\n (squareID, doubleID) = stateID_toParts(stateID)\n # The number of that are basic or special\n cardsBasic: int = 6\n cardsSpecial: int = 10\n # Total number of cards\n cardsTotal: int = cardsBasic + cardsSpecial\n assert (cardsTotal == 16), 'Error in Community Chest card total!'\n\n # First calculate the basic transition probabilities.\n # These will apply if the card picked does not send you to GO or JAIL\n tpBasic: np.ndarray = makeTransProb_Basic(stateID)\n\n # Below calculate the transition probability arising from special cards.\n tpSpecial: np.ndarray = np.zeros((M, 1))\n # SquareID for special destination squares\n # Advance to GO\n squareID_GO: int = squareNameToID['GO']\n # Go to JAIL\n squareID_JAIL: int = squareNameToID['JAIL']\n # Go to C1\n squareID_C1: int = squareNameToID['C1']\n # Go to E3\n squareID_E3: int = squareNameToID['E3']\n # Go to H2\n squareID_H2: int = squareNameToID['H2']\n # Go to R1\n squareID_R1: int = squareNameToID['R1']\n # Go to next R; this appears twice\n squareID_NextR: int = nextRail[squareID]\n # Go to next U (utility company)\n squareID_NextU: int = nextUtil[squareID]\n # Go back 3 squares.\n squareID_Back3: int = shiftedSquareID(squareID, -3)\n # Assemble the above into a tuple of 10 squareIDs (duplicate next railroad)\n squareIDs = (squareID_GO, squareID_JAIL, squareID_C1, squareID_E3, squareID_H2,\n squareID_R1, squareID_NextR, squareID_NextR, squareID_NextU, squareID_Back3)\n # doubleIDs for the next state; usually the same as now ...\n doubleIDs: List[int] = cardsSpecial * [doubleID]\n # ... but when you get sent to jail, doubles counter resets to 0 (?)\n doubleIDs[1] = 0\n # doubleIDs: List[int] = cardsSpecial * [0]\n\n # Tuple of 10 StateIDs\n # stateIDs = [stateID_fromParts(squareID, doubleID) for squareID in squareIDs]\n stateIDs = [stateID_fromParts(squareIDs[i], doubleIDs[i]) for i in range(cardsSpecial)]\n # Transition probabilities to these special destination squares\n for stateID_New in stateIDs:\n tpSpecial[stateID_New] += 1 / cardsSpecial\n\n # The probability of a special event\n specialProb = cardsSpecial / cardsTotal\n\n # Return the basic and special probabilities\n return (tpBasic, tpSpecial, specialProb)\n\n\ndef makeTransProb(stateID: int) -> np.ndarray:\n \"\"\"Make transition probability vector for any square by dispatching to suitable worker.\"\"\"\n # Extract the squareID and doubleID from the stateID\n squareID: int\n doubleID: int\n (squareID, doubleID) = stateID_toParts(stateID)\n # Get the probability type for this square: BASIC, CC, CH, or G2J\n probType: str = squareProbType(squareID)\n\n def sanityCheck() -> None:\n \"\"\" Sanity check: probabilities sum to 1\"\"\"\n msg: str = f'Transition probility does not sum to 1 for stateID={stateID}.'\n assert np.isclose(np.sum(tp), 1.0), msg\n # Initialize transition probability to zero vector\n tp1: np.ndarray = np.zeros((M, 1))\n tp: np.ndarray\n # Dispatch calls to suitable helper functions\n if probType == 'BASIC':\n tp1 = makeTransProb_Basic(stateID)\n if probType == 'G2J':\n tp = makeTransProb_G2J(stateID)\n sanityCheck()\n return tp.flatten()\n if probType == 'CC':\n (tpBasic, tpSpecial, specialProb) = makeTransProb_CC(stateID)\n if probType == 'CH':\n (tpBasic, tpSpecial, specialProb) = makeTransProb_CH(stateID)\n if probType in ('CC', 'CH'):\n basicProb = 1.0 - specialProb\n tp = basicProb * tpBasic + specialProb * tpSpecial\n sanityCheck()\n return tp.flatten()\n\n # If the starting type was basic, perform a second pass where special transfers are applied\n # for go to jail, community chest and chance\n prob: float\n tp = np.zeros((M, 1))\n for newStateID in stateIDs:\n newSquareID, newDoublesID = stateID_toParts(newStateID)\n newProbType = squareProbType(newSquareID)\n # Save probability of this state into prob for adjustments below\n newStateProb = tp1[newStateID]\n # Allocate probability prob based on its type\n if newProbType == 'BASIC':\n tp[newStateID] += newStateProb\n if newProbType == 'G2J':\n # All of this probability flows to the Jail state with 0 doubles\n tp[stateNameToID['JAIL.0']] += newStateProb\n if newProbType == 'CC':\n # 2 out of 16 cards apply a special probability shift out of CC\n (_, tpSpecial, specialProb) = makeTransProb_CC(newStateID)\n if newProbType == 'CH':\n # 10 out of 16 cards apply a special probability shift out of Chance\n (_, tpSpecial, specialProb) = makeTransProb_CH(newStateID)\n if newProbType in ('CC', 'CH'):\n basicProb = 1.0 - specialProb\n tp[newStateID] += basicProb * newStateProb\n tp += specialProb * newStateProb * tpSpecial\n\n sanityCheck()\n # Flatten the transition probability so it can overwrite one column\n return tp.flatten()\n\n\n# Type alias for tisplayTransitionProb type\ndtpType = List[Tuple[str, int, int]]\n\n\ndef displayTransProbVec(tp: np.ndarray) -> dtpType:\n idx = np.nonzero(tp)\n i: int\n dispStateIDs: List[int] = [i for i in idx[0]]\n probs: List[float] = [np.asscalar(tp[i]) for i in dispStateIDs]\n dispStateNames: List[str] = [stateNames[i] for i in dispStateIDs]\n parts: List[Tuple[int, int]] = [stateID_toParts(stateID) for stateID in dispStateIDs]\n dispSquareIDs = [p[0] for p in parts]\n stateCount: int = len(dispStateIDs)\n dtp: List[Tuple[str, int, int]] = \\\n [(dispStateNames[i], dispSquareIDs[i], int(probs[i]*10000)) for i in range(stateCount)]\n dtp.sort(key=lambda x: x[1])\n return dtp\n\n\ndef displayTransProbFrom(stateID: int) -> dtpType:\n tp = tpMat[:, stateID]\n dtp = displayTransProbVec(tp)\n return dtp\n\n\ndef displayTransProbTo(stateID: int) -> dtpType:\n tp = tpMat[stateID, :]\n dtp = displayTransProbVec(tp)\n return dtp\n\n\n# Transition probability for each state\n# tp: np.ndarray\n# tpTbl: Dict[int, np.ndarray] = dict()\n# Transition Probability Matrix\ntpMat: np.ndarray = np.zeros((M, M))\nfor stateID in stateIDs:\n tpMat[:, stateID] = makeTransProb(stateID)\n pass\n\n# The initial state is on the GO square with zero doubles\nprob: np.ndarray = np.zeros((M, 1))\nsquareID_GO = squareNameToID['GO']\nstateID_Start = stateID_fromParts(squareID_GO, 0)\n# The initial probability distribution has a weight of 1.0 on the starting state\nprob[stateID_Start] = 1.0\n\n# Continue iterating the transition\n# prob = tpMat * prob\n# Until prob is close to its previous value\n# Cap the number of iterations to avoid slow running time\nmaxIters: int = 100\niterNum: int = 0\nprobPrev: np.ndarray = np.zeros((M, 1))\nwhile not np.allclose(prob, probPrev):\n probPrev = prob\n prob = tpMat @ prob\n iterNum += 1\n if iterNum > maxIters:\n break\nprint(f'Converged after {iterNum} iterations.')\n\n# Run 10 more iterations to polish the results\ni: int\nfor i in range(10):\n prob = tpMat @ prob\n\n# Now compress the states to probabilities of landing on each square\n# Left multiply state probabilities by the N X M matrix stateToSquare\nidMat: np.ndarray = np.identity(N)\nstateToSquare: np.ndarray = np.hstack(3*(idMat,))\n# The resulting square probabilities\nsquareProb: np.ndarray = stateToSquare @ prob\nnameProb = [(squareNames[n], squareIDs[n], np.asscalar(squareProb[n])*100) for n in range(N)]\nnameProb.sort(key=lambda x: x[2], reverse=True)\nmodalString: str = f'{nameProb[0][1]:02}{nameProb[1][1]:02}{nameProb[2][1]:02}'\nprint(f'Modal String = {modalString}.')\n\n# Display version of transition probability; in terms of squares not states\ntpDisp = stateToSquare @ tpMat\ntdp = displayTransProbFrom(0)\n\n\n# TODO: this is still not quite right. With normal dice, getting a probabilities\n# JAIL = 5.89% vs. 6.25%\n# E3 = 3.01% vs. 3.18%\n# D3 = 2.93% vs. 3.09%","sub_path":"Prob084_MonopolyOdds.py","file_name":"Prob084_MonopolyOdds.py","file_ext":"py","file_size_in_byte":22341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"377321827","text":"\n# -*- coding: utf-8 -*-\n\"\"\"WSGI Application and Routes\"\"\"\n\nimport os\nimport sys\nimport webapp2\nimport handlers\n\napp = webapp2.WSGIApplication(debug=True)\n\nsecure_scheme = 'https'\n\n_routes = [\n webapp2.Route('/', handlers.IndexHandler, methods=['GET','POST']),\n]\n\ndef add_routes(app, routes=_routes):\n if app.debug:\n secure_scheme = 'http'\n for r in routes:\n app.router.add(r)\n\nadd_routes(app,_routes)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"194169809","text":"def modify(name):\n\t\"\"\"\n return the name with the last name first, followed by a comma,\n followed by the first name (if any), followed by the first letter of\n each remaining name with a period after each letter. \n name has at least one word. \n \"\"\"\n\tnamelist = name.split();\n\n\tif len(namelist) == 1:\n\t\treturn name\n\telif len(namelist) == 2:\n\t\treturn namelist[-1] + \", \" + namelist[0]\n\telse:\n\t\tmiddlenames = list()\n\t\tfor i in range(1,len(namelist)-1):\n\t\t\tif len(namelist[i]) > 1:\n\t\t\t\tmiddlenames.append(namelist[i][0] + \".\")\n\t\t\telse:\n\t\t\t\tmiddlenames.append(namelist[i])\n\t\treturn namelist[-1] + \", \" + namelist[0] + \" \" + ' '.join(middlenames)\n\n\n\n","sub_path":"LastNameFirst.py","file_name":"LastNameFirst.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"216497838","text":"from django_countries.fields import CountryField\nfrom django.db import models\n\nfrom autoslug import AutoSlugField\nfrom model_utils.models import TimeStampedModel\n\n\nclass Cheese(TimeStampedModel):\n\n FIRMNESS_UNSPECIFIED = 'unspecified'\n FIRMNESS_SOFT = 'soft'\n FIRMNESS_SEMI_SOFT = 'semi-soft'\n FIRMNESS_SEMI_HARD = 'semi-hard'\n FIRMNESS_HARD = 'hard'\n FIRMNESS_CHOICES = (\n (FIRMNESS_UNSPECIFIED, 'Unspecified'),\n (FIRMNESS_SOFT, 'Soft'),\n (FIRMNESS_SEMI_SOFT, 'Semi-Soft'),\n (FIRMNESS_SEMI_HARD, 'Semi-Hard'),\n (FIRMNESS_HARD, 'Hard'),\n )\n\n name = models.CharField('Name of Cheese', max_length=255)\n slug = AutoSlugField('Cheese Address', unique=True, always_update=False,\n populate_from='name')\n description = models.TextField('Description', blank=True)\n firmness = models.CharField('Firmness', choices=FIRMNESS_CHOICES,\n default=FIRMNESS_UNSPECIFIED, max_length=15)\n country_of_origin = CountryField('Country of Origin', blank=True)\n\n def __str__(self):\n return self.name\n","sub_path":"everycheese/cheeses/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"195710326","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n# datetime_bin.py\n\"\"\"This module provides functions on binning and averaging data\"\"\"\n\nimport os, sys\n#import re\nfrom datetime import datetime, timedelta\nimport numpy as np\n#import scipy as sp\n#import matplotlib.pyplot as plt\n#from mpl_toolkits.basemap import Basemap\n#from matplotlib import mlab\nfrom .parser import *\n\n__all__ = ['datetime_bin', 'datetime_period', 'datetime_group', 'datetime_neighbor'] \ndef datetime_bin(datetimes, tdelta, starttime=None, endtime=None, return_bin_info=False):\n \"\"\"This function partition a serie of datetime objects into equal timedelta bin. \n Returns a list of np.where style tuples. If return_bin_info is True, also returns a list of (bin_start, bin_end) tuples.\n Parameters:\n datetimes is a seq of datetime objects, \n tdelta is a timedelta object,\n starttime is a datetime object or None. When it's None, use the first datetime in the input sequence as starttime\n endtime is a datetime object or None. When it's None, use the last datetime in the input sequence as endtime\n \"\"\"\n if len(datetimes) == 0:\n if return_bin_info:\n return [], []\n else:\n return []\n datetimes = parse_datetime(datetimes)\n if starttime is None:\n starttime = datetimes[0]\n else:\n starttime = parse_datetime(starttime)\n if endtime is None:\n endtime = datetimes[-1] # + tdelta / 2\n else:\n endtime = parse_datetime(endtime)\n if tdelta is None:\n tdelta = endtime - starttime\n else:\n tdelta = parse_timedelta(tdelta)\n\n tmpbin_start = starttime\n result = []\n bin_info = []\n tmpbin = []\n tmpbin_end = tmpbin_start + tdelta\n i = 0\n while tmpbin_start < endtime:\n if i == len(datetimes) or datetimes[i] >= tmpbin_end:\n bin_info.append((tmpbin_start, tmpbin_end))\n result.append((np.array(tmpbin, dtype='i8'), ))\n tmpbin = []\n tmpbin_start, tmpbin_end = tmpbin_end, tmpbin_end + tdelta\n elif datetimes[i] < tmpbin_start:\n i += 1\n else:\n tmpbin.append(i)\n i += 1\n \n if return_bin_info is True:\n return result, bin_info\n else:\n return result\n\ndef datetime_period(datetimes, splitpoints, starttime=None, endtime=None, return_bin_info=False, include_period_before_first_splitpoint=False):\n \"\"\"This function partition a serie of datetime objects into periods according to splitpoints. \n Returns a list of np.where style tuples. If return_bin_info is True, also returns a list of (bin_start, bin_end) tuples.\n Parameters:\n datetimes is a seq of datetime objects, \n splitpoints is a seq of datetime objects as splitpoints,\n starttime is a datetime object or None. When it's None, use the first datetime in the input sequence as starttime\n endtime is a datetime object or None. When it's None, use the last datetime in the input sequence as endtime\n return_bin_info: default False\n include_period_before_first_splitpoint: default False\n \"\"\"\n if len(datetimes) == 0:\n if return_bin_info:\n return [], []\n else:\n return []\n datetimes = parse_datetime(datetimes)\n min_dts = np.min(datetimes)\n max_dts = np.max(datetimes)\n if starttime is None:\n starttime = min_dts\n else:\n starttime = parse_datetime(starttime)\n if endtime is None:\n endtime = max_dts\n else:\n endtime = parse_datetime(endtime)\n if starttime > max_dts or endtime < min_dts:\n if return_bin_info:\n return [], []\n else:\n return []\n \n if not include_period_before_first_splitpoint:\n begs = list(splitpoints)\n ends = list(splitpoints)[1:] + [datetime.max]\n else:\n begs = [datetime.min] + list(splitpoints)\n ends = list(splitpoints) + [datetime.max]\n \n# start_i = np.argmax(splitpoints >= starttime)\n# end_i = np.argmin(splitpoints >= endtime)\n# TODO: add actual starttime and endtime support\n bes = zip(begs, ends)\n periods = []\n for b, e in bes:\n periods.append( np.where((datetimes >= b) & (datetimes < e)) )\n\n if return_bin_info:\n return periods, bes\n else:\n return periods\n\n\ndef datetime_group(datetimes, tdelta_threshold, starttime=None, endtime=None, return_bin_info=False):\n \"\"\"This function partition a serie of datetime objects into groups (clusters) according to a tdelta_threshold. \n Returns a list of np.where style tuples. If return_bin_info is True, also returns a list of (bin_start, bin_end) tuples.\n Parameters:\n datetimes is a seq of datetime objects, which should be sorted.\n tdelta_threshold: a timedelta object.\n starttime is a datetime object or None. When it's None, use the first datetime in the input sequence as starttime. Not Implemented\n endtime is a datetime object or None. When it's None, use the last datetime in the input sequence as endtime. NOt Implemented\n return_bin_info: default False\n \"\"\"\n if len(datetimes) == 0:\n if return_bin_info:\n return [], []\n else:\n return []\n datetimes = parse_datetime(datetimes)\n min_dts = np.min(datetimes)\n max_dts = np.max(datetimes)\n if starttime is None:\n starttime = min_dts\n else:\n starttime = parse_datetime(starttime)\n if endtime is None:\n endtime = max_dts\n else:\n endtime = parse_datetime(endtime)\n if starttime > max_dts or endtime < min_dts:\n if return_bin_info:\n return [], []\n else:\n return []\n \n basket = [0]\n pool = []\n for i in range (1, len(datetimes)):\n if datetimes[i] - datetimes[i-1] < tdelta_threshole:\n basket.append(i)\n else:\n pool.append(basket)\n basket = [i]\n pool.append(basket)\n result = [(b, ) for b in pool]\n if return_bin_info:\n return result, [(datetimes[b[0]], datetimes[b[-1]]) for b in pool] \n else:\n return result\n\ndef datetime_neighbor(datetimes, target_datetimes, tdelta_threshold, starttime=None, endtime=None, return_bin_info=False):\n \"\"\"This function finds proper datetimes which are near each target datetime point, within tdelta_threshold, from a serie of datetimes . \n Returns a list of np.where style tuples. If return_bin_info is True, also returns a list of (bin_start, bin_end) tuples.\n Parameters:\n datetimes is a seq of datetime objects, to be choosen from.\n target_datetimes: for each one in this, find its neighborhood.\n tdelta_threshold: a timedelta object.\n starttime is a datetime object or None. When it's None, use the first datetime in the input sequence as starttime. Not Implemented\n endtime is a datetime object or None. When it's None, use the last datetime in the input sequence as endtime. NOt Implemented\n return_bin_info: default False\n \"\"\"\n if len(datetimes) == 0:\n if return_bin_info:\n return [], []\n else:\n return []\n datetimes = parse_datetime(datetimes)\n min_dts = np.min(datetimes)\n max_dts = np.max(datetimes)\n if starttime is None:\n starttime = min_dts\n else:\n starttime = parse_datetime(starttime)\n if endtime is None:\n endtime = max_dts\n else:\n endtime = parse_datetime(endtime)\n if starttime > max_dts or endtime < min_dts:\n if return_bin_info:\n return [], []\n else:\n return []\n \n result = []\n bes = []\n for target in target_datetimes:\n b = target - tdelta_threshold\n e = target + tdelta_threshold\n w = np.where((datetimes>=b) & (datetimes<=e))\n result.append(w)\n bes.append((b,e))\n\n if return_bin_info:\n return result, bes\n else:\n return result\n\nif __name__ == '__main__':\n pass\n","sub_path":"metlib/datetime/datetime_bin.py","file_name":"datetime_bin.py","file_ext":"py","file_size_in_byte":7903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"245014652","text":"'''\nDana Solitaire\nSection 17\n11/24/2018\n\nThis class will track individuals moving along the universe and log their \nawards and total points. Most of the needed functions are in this class because \nit's easier to understand.\n'''\nimport math as m\n\nclass Person(object):\n #Initalizes person object with attributes\n #(str, float, str, float, float, float, float, str, list, bool)\n def __init__(self, name, radius, home_universe, x, y, dx, dy,\\\n current_universe, rewards):\n self.name = name\n self.radius = radius\n self.home_universe = home_universe\n self.x = float(x)\n self.y = float(y)\n self.dx = float(dx)\n self.dy = float(dy)\n self.current_universe = current_universe\n self.points = 0\n # [x, y, points, name, index]\n self.rewards = rewards\n #Stores dx and dy when stopped\n self.dx_stop = dx\n self.dy_stop = dy\n #Bool to check if person has stopped\n self.stop = False\n #Str that can contain name of other person collided with\n self.crashed_with = ''\n \n def __str__(self):\n #This function prints out person info\n print('{} of {} in universe {}'.format(self.name, self.home_universe,\\\n self.current_universe))\n print(4 * ' ' +\\\n 'at ({:.1f},{:.1f}) speed ({:.1f},{:.1f}) with {} rewards and {} points'.\\\n format(self.x, self.y, self.dx_stop, self.dy_stop,\\\n len(self.rewards), self.points))\n return ''\n #Simple function adds speed to position\n def move(self):\n self.x += self.dx\n self.y += self.dy\n\n #This checks if the center if the person is at or pass the borders\n def check_edges(self, step):\n if self.dx == 0 and self.dy == 0:\n return 0\n elif self.x >= 1000 or self.x <= 0 or\\\n self.y <= 0 or self.y >= 1000:\n print('{} stopped at simulation step {} at location ({:.1f},{:.1f})\\n'\\\n .format(self.name, step + 1, self.x, self.y))\n self.stop = True\n #Storing dx and dy\n self.dx_stop = self.dx\n self.dy_stop = self.dy\n #This ensures that move can be called and this person will not move\n self.dx = 0\n self.dy = 0\n \n #(object, int)\n #Checks if abs of dx and dy are less than 10, if so it stores the values,\n #sets stop bool to True, and sets dx and dy to zero\n def check_speed(self, step):\n if self.dx == 0 or self.dy ==0:\n return\n elif abs(self.dx) < 10 or abs(self.dy) < 10:\n print('{} stopped at simulation step {} at location ({:.1f},{:.1f})\\n'\\\n .format(self.name, step, self.x, self.y))\n self.stop = True\n self.dx_stop = self.dx\n self.dy_stop = self.dy\n self.dx = 0\n self.dy = 0\n \n #(object, int, list of list)\n #This function checks if reward is within person radius\n def near_reward(self, step, rewards):\n for reward in rewards.copy():\n distance = m.sqrt((self.x - reward[0]) ** 2\\\n + (self.y - reward[1]) ** 2)\n if distance <= self.radius:\n print('{} picked up \"{}\" at simulation step {}'\\\n .format(self.name, reward[3], step))\n #This adds rewards to the list of rewards person has\n self.rewards.append(reward)\n self.points += reward[2]\n #Removes the reward from the overall reward list for that universe\n rewards.remove(reward)\n n = len(self.rewards)\n #Reassigns dx and dy\n self.dx = self.dx - (n % 2) * (n / 6) * self.dx\n self.dy = self.dy - ((n + 1) % 2) * (n / 6) * self.dy\n #Prints output\n print('{} of {} in universe {}'.format(self.name, \\\n self.home_universe, self.current_universe))\n print(4 * ' ' +\\\n 'at ({:.1f},{:.1f}) speed ({:.1f},{:.1f}) with {} rewards and {} points\\n'.\\\n format(self.x, self.y, self.dx, self.dy,\\\n len(self.rewards), self.points))\n \n #(self, int, list)\n '''This function takes the step number and portals list from universe'''\n def near_portal(self, step, portals):\n for portal in portals:\n #Calculates the distance\n distance = m.sqrt((self.x - portal[0]) ** 2\\\n + (self.y - portal[1]) ** 2)\n if distance <= self.radius:\n print('{} passed through a portal at simulation step {}'\\\n .format(self.name, portal[3], step))\n self.current_universe = portal[3]\n self.x = portal[3]\n self.y = portal[4]\n #print('{} of {} in universe {})\n \n #This function checks if person is colliding with other people in universe\n def check_crash(self, people_list, rewards, step):\n for second_person in people_list:\n #Calculates distance\n distance = m.sqrt((self.x - second_person.x) ** 2\\\n + (self.y - second_person.y) ** 2)\n #This if statement skips thefunction if person is\n #colliding with itself\n if distance == 0:\n pass\n #This line checks if the person is within range of another person\n #and that it hasn't already crashed with the same person\n elif distance <= self.radius and self.crashed_with != second_person.name: \n print('{} and {} crashed at simulation step {} in universe {}'\\\n .format(self.name, second_person.name,\\\n step,self.current_universe))\n #Assigns crashed_with to other person's name\n self.crashed_with = second_person.name\n second_person.crashed_with = self.name\n if len(self.rewards) != 0:\n self_temp = self.rewards[0]\n print('{} dropped \"{}\", reward returned to {} at ({},{})'\\\n .format(self.name, self_temp[3], \\\n self.current_universe, self_temp[0], \\\n self_temp[1]))\n rewards.insert(self_temp[4], self_temp)\n self.rewards.pop(0)\n self.points -= self_temp[2]\n n = len(self.rewards) \n #Changes the speed only if reward is dropped\n self.dx = -(self.dx + (n % 2) * (n/6) * self.dx)\n self.dy = -(self.dy + ((n + 1) % 2) * (n/6)* self.dy)\n self.move() \n if len(second_person.rewards) != 0:\n temp_reward = second_person.rewards[0]\n print('{} dropped \"{}\", reward returned to {} at ({},{})'\\\n .format(second_person.name, temp_reward[3], \\\n second_person.current_universe, \\\n temp_reward[0], temp_reward[1]))\n rewards.insert(temp_reward[4],temp_reward)\n second_person.rewards.pop(0)\n second_person.points -= temp_reward[2]\n n = len(second_person.rewards)\n second_person.dx = -(second_person.dx + \\\n (n%2)* (n/6)*second_person.dx)\n second_person.dy = -(second_person.dy + \\\n ((n+ 1) % 2)* (n/ 6)\\\n * second_person.dy)\n second_person.move()\n #Printing output\n print('{} of {} in universe {}'.format(self.name, \\\n self.home_universe, self.current_universe))\n print(4 * ' ' +\\\n 'at ({:.1f},{:.1f}) speed ({:.1f},{:.1f}) with {} rewards and {} points\\n'.\\\n format(self.x, self.y, self.dx, self.dy,\\\n len(self.rewards), self.points)) \n print('{} of {} in universe {}'.format(second_person.name, \\\n second_person.home_universe, \\\n second_person.current_universe))\n print(4 * ' ' +\\\n 'at ({:.1f},{:.1f}) speed ({:.1f},{:.1f}) with {} rewards and {} points\\n'.\\\n format(second_person.x, second_person.y, second_person.dx, \\\n second_person.dy, len(second_person.rewards), \\\n second_person.points))\n \n #Overriding the less than function to compare persons based on points \n def __lt__(self, other):\n return self.points < other.points\n \n \n ","sub_path":"Homework/hw8/Person.py","file_name":"Person.py","file_ext":"py","file_size_in_byte":9019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"210955901","text":"#!/usr/bin/env python\n\nr\"\"\"\nDefine variable manipulation functions.\n\"\"\"\n\nimport os\nimport re\n\ntry:\n from robot.utils import DotDict\nexcept ImportError:\n pass\n\nimport collections\n\nimport gen_print as gp\nimport gen_misc as gm\n\n\ndef create_var_dict(*args):\n r\"\"\"\n Create a dictionary whose keys/values are the arg names/arg values passed\n to it and return it to the caller.\n\n Note: The resulting dictionary will be ordered.\n\n Description of argument(s):\n *args An unlimited number of arguments to be processed.\n\n Example use:\n\n first_name = 'Steve'\n last_name = 'Smith'\n var_dict = create_var_dict(first_name, last_name)\n\n gp.print_var(var_dict)\n\n The print-out of the resulting var dictionary is:\n var_dict:\n var_dict[first_name]: Steve\n var_dict[last_name]: Smith\n \"\"\"\n\n try:\n result_dict = collections.OrderedDict()\n except AttributeError:\n result_dict = DotDict()\n\n arg_num = 1\n for arg in args:\n arg_name = gp.get_arg_name(None, arg_num, stack_frame_ix=2)\n result_dict[arg_name] = arg\n arg_num += 1\n\n return result_dict\n\n\ndefault_record_delim = ':'\ndefault_key_val_delim = '.'\n\n\ndef join_dict(dict,\n record_delim=default_record_delim,\n key_val_delim=default_key_val_delim):\n r\"\"\"\n Join a dictionary's keys and values into a string and return the string.\n\n Description of argument(s):\n dict The dictionary whose keys and values are\n to be joined.\n record_delim The delimiter to be used to separate\n dictionary pairs in the resulting string.\n key_val_delim The delimiter to be used to separate keys\n from values in the resulting string.\n\n Example use:\n\n gp.print_var(var_dict)\n str1 = join_dict(var_dict)\n gp.pvar(str1)\n\n Program output.\n var_dict:\n var_dict[first_name]: Steve\n var_dict[last_name]: Smith\n str1:\n first_name.Steve:last_name.Smith\n \"\"\"\n\n format_str = '%s' + key_val_delim + '%s'\n return record_delim.join([format_str % (key, value) for (key, value) in\n dict.items()])\n\n\ndef split_to_dict(string,\n record_delim=default_record_delim,\n key_val_delim=default_key_val_delim):\n r\"\"\"\n Split a string into a dictionary and return it.\n\n This function is the complement to join_dict.\n\n Description of argument(s):\n string The string to be split into a dictionary.\n The string must have the proper delimiters\n in it. A string created by join_dict\n would qualify.\n record_delim The delimiter to be used to separate\n dictionary pairs in the input string.\n key_val_delim The delimiter to be used to separate\n keys/values in the input string.\n\n Example use:\n\n gp.print_var(str1)\n new_dict = split_to_dict(str1)\n gp.print_var(new_dict)\n\n\n Program output.\n str1:\n first_name.Steve:last_name.Smith\n new_dict:\n new_dict[first_name]: Steve\n new_dict[last_name]: Smith\n \"\"\"\n\n try:\n result_dict = collections.OrderedDict()\n except AttributeError:\n result_dict = DotDict()\n\n raw_keys_values = string.split(record_delim)\n for key_value in raw_keys_values:\n key_value_list = key_value.split(key_val_delim)\n try:\n result_dict[key_value_list[0]] = key_value_list[1]\n except IndexError:\n result_dict[key_value_list[0]] = \"\"\n\n return result_dict\n\n\ndef create_file_path(file_name_dict,\n dir_path=\"/tmp/\",\n file_suffix=\"\"):\n r\"\"\"\n Create a file path using the given parameters and return it.\n\n Description of argument(s):\n file_name_dict A dictionary with keys/values which are to\n appear as part of the file name.\n dir_path The dir_path that is to appear as part of\n the file name.\n file_suffix A suffix to be included as part of the\n file name.\n \"\"\"\n\n dir_path = gm.add_trailing_slash(dir_path)\n return dir_path + join_dict(file_name_dict) + file_suffix\n\n\ndef parse_file_path(file_path):\n r\"\"\"\n Parse a file path created by create_file_path and return the result as a\n dictionary.\n\n This function is the complement to create_file_path.\n\n Description of argument(s):\n file_path The file_path.\n\n Example use:\n gp.pvar(boot_results_file_path)\n file_path_data = parse_file_path(boot_results_file_path)\n gp.pvar(file_path_data)\n\n Program output.\n\n boot_results_file_path:\n /tmp/pgm_name.obmc_boot_test:openbmc_nickname.beye6:master_pid.2039:boot_re\n sults\n file_path_data:\n file_path_data[dir_path]: /tmp/\n file_path_data[pgm_name]: obmc_boot_test\n file_path_data[openbmc_nickname]: beye6\n file_path_data[master_pid]: 2039\n file_path_data[boot_results]:\n \"\"\"\n\n try:\n result_dict = collections.OrderedDict()\n except AttributeError:\n result_dict = DotDict()\n\n dir_path = os.path.dirname(file_path) + os.sep\n file_path = os.path.basename(file_path)\n\n result_dict['dir_path'] = dir_path\n\n result_dict.update(split_to_dict(file_path))\n\n return result_dict\n\n\ndef parse_key_value(string,\n delim=\":\",\n strip=\" \",\n to_lower=1,\n underscores=1):\n r\"\"\"\n Parse a key/value string and return as a key/value tuple.\n\n This function is useful for parsing a line of program output or data that\n is in the following form:\n \n\n An example of a key/value string would be as follows:\n\n Current Limit State: No Active Power Limit\n\n In the example shown, the delimiter is \":\". The resulting key would be as\n follows:\n Current Limit State\n\n Note: If one were to take the default values of to_lower=1 and\n underscores=1, the resulting key would be as follows:\n current_limit_state\n\n The to_lower and underscores arguments are provided for those who wish to\n have their key names have the look and feel of python variable names.\n\n The resulting value for the example above would be as follows:\n No Active Power Limit\n\n Another example:\n name=Mike\n\n In this case, the delim would be \"=\", the key is \"name\" and the value is\n \"Mike\".\n\n Description of argument(s):\n string The string to be parsed.\n delim The delimiter which separates the key from\n the value.\n strip The characters (if any) to strip from the\n beginning and end of both the key and the\n value.\n to_lower Change the key name to lower case.\n underscores Change any blanks found in the key name to\n underscores.\n \"\"\"\n\n pair = string.split(delim)\n\n key = pair[0].strip(strip)\n if len(pair) == 0:\n value = \"\"\n else:\n value = delim.join(pair[1:]).strip(strip)\n\n if to_lower:\n key = key.lower()\n if underscores:\n key = re.sub(r\" \", \"_\", key)\n\n return key, value\n\n\ndef key_value_list_to_dict(list,\n process_indent=0,\n **args):\n r\"\"\"\n Convert a list containing key/value strings to a dictionary and return it.\n\n See docstring of parse_key_value function for details on key/value strings.\n\n Example usage:\n\n For the following value of list:\n\n list:\n list[0]: Current Limit State: No Active Power Limit\n list[1]: Exception actions: Hard Power Off & Log Event to SEL\n list[2]: Power Limit: 0 Watts\n list[3]: Correction time: 0 milliseconds\n list[4]: Sampling period: 0 seconds\n\n And the following call in python:\n\n power_limit = key_value_outbuf_to_dict(list)\n\n The resulting power_limit directory would look like this:\n\n power_limit:\n [current_limit_state]: No Active Power Limit\n [exception_actions]: Hard Power Off & Log Event to SEL\n [power_limit]: 0 Watts\n [correction_time]: 0 milliseconds\n [sampling_period]: 0 seconds\n\n Another example containing a sub-list (see process_indent description\n below):\n\n Provides Device SDRs : yes\n Additional Device Support :\n Sensor Device\n SEL Device\n FRU Inventory Device\n Chassis Device\n\n Note that the 2 qualifications for containing a sub-list are met: 1)\n 'Additional Device Support' has no value and 2) The entries below it are\n indented. In this case those entries contain no delimiters (\":\") so they\n will be processed as a list rather than as a dictionary. The result would\n be as follows:\n\n mc_info:\n mc_info[provides_device_sdrs]: yes\n mc_info[additional_device_support]:\n mc_info[additional_device_support][0]: Sensor Device\n mc_info[additional_device_support][1]: SEL Device\n mc_info[additional_device_support][2]: FRU Inventory Device\n mc_info[additional_device_support][3]: Chassis Device\n\n Description of argument(s):\n list A list of key/value strings. (See\n docstring of parse_key_value function for\n details).\n process_indent This indicates that indented\n sub-dictionaries and sub-lists are to be\n processed as such. An entry may have a\n sub-dict or sub-list if 1) It has no value\n other than blank 2) There are entries\n below it that are indented.\n **args Arguments to be interpreted by\n parse_key_value. (See docstring of\n parse_key_value function for details).\n \"\"\"\n\n try:\n result_dict = collections.OrderedDict()\n except AttributeError:\n result_dict = DotDict()\n\n if not process_indent:\n for entry in list:\n key, value = parse_key_value(entry, **args)\n result_dict[key] = value\n return result_dict\n\n # Process list while paying heed to indentation.\n delim = args.get(\"delim\", \":\")\n # Initialize \"parent_\" indentation level variables.\n parent_indent = len(list[0]) - len(list[0].lstrip())\n sub_list = []\n for entry in list:\n key, value = parse_key_value(entry, **args)\n\n indent = len(entry) - len(entry.lstrip())\n\n if indent > parent_indent and parent_value == \"\":\n # This line is indented compared to the parent entry and the\n # parent entry has no value.\n # Append the entry to sub_list for later processing.\n sub_list.append(str(entry))\n continue\n\n # Process any outstanding sub_list and add it to\n # result_dict[parent_key].\n if len(sub_list) > 0:\n if any(delim in word for word in sub_list):\n # If delim is found anywhere in the sub_list, we'll process\n # as a sub-dictionary.\n result_dict[parent_key] = key_value_list_to_dict(sub_list,\n **args)\n else:\n result_dict[parent_key] = map(str.strip, sub_list)\n del sub_list[:]\n\n result_dict[key] = value\n\n parent_key = key\n parent_value = value\n parent_indent = indent\n\n # Any outstanding sub_list to be processed?\n if len(sub_list) > 0:\n if any(delim in word for word in sub_list):\n # If delim is found anywhere in the sub_list, we'll process as a\n # sub-dictionary.\n result_dict[parent_key] = key_value_list_to_dict(sub_list, **args)\n else:\n result_dict[parent_key] = map(str.strip, sub_list)\n\n return result_dict\n\n\ndef key_value_outbuf_to_dict(out_buf,\n **args):\n r\"\"\"\n Convert a buffer with a key/value string on each line to a dictionary and\n return it.\n\n Each line in the out_buf should end with a \\n.\n\n See docstring of parse_key_value function for details on key/value strings.\n\n Example usage:\n\n For the following value of out_buf:\n\n Current Limit State: No Active Power Limit\n Exception actions: Hard Power Off & Log Event to SEL\n Power Limit: 0 Watts\n Correction time: 0 milliseconds\n Sampling period: 0 seconds\n\n And the following call in python:\n\n power_limit = key_value_outbuf_to_dict(out_buf)\n\n The resulting power_limit directory would look like this:\n\n power_limit:\n [current_limit_state]: No Active Power Limit\n [exception_actions]: Hard Power Off & Log Event to SEL\n [power_limit]: 0 Watts\n [correction_time]: 0 milliseconds\n [sampling_period]: 0 seconds\n\n Description of argument(s):\n out_buf A buffer with a key/value string on each\n line. (See docstring of parse_key_value\n function for details).\n **args Arguments to be interpreted by\n parse_key_value. (See docstring of\n parse_key_value function for details).\n \"\"\"\n\n # Create key_var_list and remove null entries.\n key_var_list = list(filter(None, out_buf.split(\"\\n\")))\n return key_value_list_to_dict(key_var_list, **args)\n\n\ndef list_to_report(report_list,\n to_lower=1):\n r\"\"\"\n Convert a list containing report text lines to a report \"object\" and\n return it.\n\n The first entry in report_list must be a header line consisting of column\n names delimited by white space. No column name may contain white space.\n The remaining report_list entries should contain tabular data which\n corresponds to the column names.\n\n A report object is a list where each entry is a dictionary whose keys are\n the field names from the first entry in report_list.\n\n Example:\n Given the following report_list as input:\n\n rl:\n rl[0]: Filesystem 1K-blocks Used Available Use% Mounted on\n rl[1]: dev 247120 0 247120 0% /dev\n rl[2]: tmpfs 248408 79792 168616 32% /run\n\n This function will return a list of dictionaries as shown below:\n\n df_report:\n df_report[0]:\n [filesystem]: dev\n [1k-blocks]: 247120\n [used]: 0\n [available]: 247120\n [use%]: 0%\n [mounted]: /dev\n df_report[1]:\n [filesystem]: dev\n [1k-blocks]: 247120\n [used]: 0\n [available]: 247120\n [use%]: 0%\n [mounted]: /dev\n\n Notice that because \"Mounted on\" contains a space, \"on\" would be\n considered the 7th field. In this case, there is never any data in field\n 7 so things work out nicely. A caller could do some pre-processing if\n desired (e.g. change \"Mounted on\" to \"Mounted_on\").\n\n Description of argument(s):\n report_list A list where each entry is one line of\n output from a report. The first entry\n must be a header line which contains\n column names. Column names may not\n contain spaces.\n to_lower Change the resulting key names to lower\n case.\n \"\"\"\n\n # Process header line.\n header_line = report_list[0]\n if to_lower:\n header_line = header_line.lower()\n columns = header_line.split()\n\n report_obj = []\n for report_line in report_list[1:]:\n line = report_list[1].split()\n try:\n line_dict = collections.OrderedDict(zip(columns, line))\n except AttributeError:\n line_dict = DotDict(zip(columns, line))\n report_obj.append(line_dict)\n\n return report_obj\n\n\ndef outbuf_to_report(out_buf,\n **args):\n r\"\"\"\n Convert a text buffer containing report lines to a report \"object\" and\n return it.\n\n Refer to list_to_report (above) for more details.\n\n Example:\n\n Given the following out_buf:\n\n Filesystem 1K-blocks Used Available Use% Mounted on\n dev 247120 0 247120 0% /dev\n tmpfs 248408 79792 168616 32% /run\n\n This function will return a list of dictionaries as shown below:\n\n df_report:\n df_report[0]:\n [filesystem]: dev\n [1k-blocks]: 247120\n [used]: 0\n [available]: 247120\n [use%]: 0%\n [mounted]: /dev\n df_report[1]:\n [filesystem]: dev\n [1k-blocks]: 247120\n [used]: 0\n [available]: 247120\n [use%]: 0%\n [mounted]: /dev\n\n Other possible uses:\n - Process the output of a ps command.\n - Process the output of an ls command (the caller would need to supply\n column names)\n\n Description of argument(s):\n out_buf A text report The first line must be a\n header line which contains column names.\n Column names may not contain spaces.\n **args Arguments to be interpreted by\n list_to_report. (See docstring of\n list_to_report function for details).\n \"\"\"\n\n report_list = filter(None, out_buf.split(\"\\n\"))\n return list_to_report(report_list, **args)\n","sub_path":"lib/var_funcs.py","file_name":"var_funcs.py","file_ext":"py","file_size_in_byte":19225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"653245378","text":"from collections import Counter\nimport re\nimport csv\nimport argparse\n\n\n\ndef read_log(filename):\n \"\"\"Accepts log file and returns list of ips\"\"\"\n\n regexp = r\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\"\n\n with open(filename) as f:\n log = f.read()\n ip_list = re.findall(regexp, log)\n\n return ip_list\n\n\ndef ip_counter(list_of_ips):\n \"\"\"Counts ips in an input list. Returns a dictionary - ip: frequency \"\"\"\n return Counter(list_of_ips)\n \n\ndef write_to_csv(ip_dict, output_file=\"parsed.csv\"):\n \"\"\"Writes an input dictionary to a csv file\"\"\"\n\n with open(output_file, 'w') as csvfile:\n writer = csv.writer(csvfile)\n\n header = ['IP', 'Frequency']\n writer.writerow(header)\n\n for ip in ip_dict:\n writer.writerow((ip, ip_dict[ip]))\n\ndef main():\n parser = argparse.ArgumentParser(description='Extracting IP-addresses data from Apache logs.')\n parser.add_argument('log', help='Log filename. I.e. sample_log.txt or sample.log etc.')\n args = parser.parse_args()\n\n write_to_csv(ip_counter(read_log(args.log)))\n\n \n\n\nif __name__ == \"__main__\":\n #write_to_csv(ip_counter(read_log(\"optimist_2016_02_04.log\")))\n main()\n\n\n\n\n\n\n","sub_path":"ala.py","file_name":"ala.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"444537741","text":"# -*- coding: utf-8 -*-\n# ----------------------------------------------------------------------\n# Base testing classes\n# ----------------------------------------------------------------------\n# Copyright (C) 2007-2018 The NOC Project\n# See LICENSE for details\n# ----------------------------------------------------------------------\n\n# Third-party modules\nfrom django.db import connection\nimport pytest\n\n\n@pytest.mark.usefixtures(\"database\")\nclass BaseModelTest(object):\n model = None # Must be overriden\n\n def get_cursor(self):\n return connection.cursor()\n\n def test_database_table(self):\n \"\"\"\n Check database table is created during migration\n :return:\n \"\"\"\n assert self.model._meta.db_table\n c = self.get_cursor()\n c.execute(\n \"SELECT COUNT(*) FROM pg_class WHERE relname=%s\",\n [self.model._meta.db_table]\n )\n return c.fetchall()[0][0] == 1\n\n def test_uncode(self):\n for o in self.model.objects.all():\n assert unicode(o)\n\n\n@pytest.mark.usefixtures(\"database\")\nclass BaseDocumentTest(object):\n model = None # Must be overriden\n\n def get_collection(self):\n return self.model._get_collection()\n\n def test_uncode(self):\n for o in self.model.objects.all():\n assert unicode(o)\n","sub_path":"tests/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"396336918","text":"'''\nFast Exponentiation:\n\nAsk the user to enter 2 integers a and b and output a^b (i.e. pow(a,b)) in O(lg n) time complexity.\n'''\n\n\ndef nr_power(a, b):\n if b == 0:\n return 1\n temp = pow(a, b // 2)\n if b%2 == 0:\n return temp * temp\n else:\n return a * temp * temp\n\n\ndef get_nr():\n while True:\n try:\n nr = int(input('Enter a number: '))\n except:\n print('Number incorrect!')\n else:\n return nr\n\n\nprint('Enter base')\nbase = get_nr()\nprint('Enter power')\npwr = get_nr()\nprint('a^b = {}'.format(nr_power(base, pwr)))\n","sub_path":"___basic/bootcamp/capstone/01numbers/22fast_exponentiation.py","file_name":"22fast_exponentiation.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"121334623","text":"\"\"\"platzigram views \"\"\"\n\n# Django\nfrom django.http import HttpResponse\nimport json\n\n#Utilities\nfrom datetime import datetime\n\ndef hello_world(request):\n \"\"\"return a greeting\"\"\"\n return HttpResponse('Oh, hi! Currente server time is {}'.format(\n datetime.now().strftime('%b %dth, %Y - %H:%M hrs')\n ))\n #return HttpResponse('Oh, hi! Currente server time is {}'.format( \n # now = datetime.now().strftime('%b %dth, %Y - %H:%M hrs')\n # ))\n\ndef sorted_numbers(request):\n \"\"\"Hi\"\"\" \n #print(request)\n #import pdb;pdb.set_trace() # para poder debugear en la consola\n numbers = request.GET['numbers'].split(',')\n numbers_int = sorted([int(number) for number in numbers])\n data = {\n 'status' : 'ok',\n 'numbers': numbers_int,\n 'message': 'Integers sorted succefully.'\n }\n #response = JsonResponse([numbers_int], safe=False)\n response = HttpResponse(\n json.dumps(data, indent=4),\n content_type='application/json'\n )\n\n #return HttpResponse(JsonResponse(str(numbers).split(',')))\n return response\n\n\ndef say_hi(request,name,age):\n \"\"\"return a greatting\"\"\"\n if age < 12:\n messague = 'Sorry {} you are not allowed here'.format(name)\n else:\n messague = 'Hi {} welcome to Platzigram '.format(name)\n\n return HttpResponse(messague)","sub_path":"platzigram/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"596013070","text":"from openpyxl import load_workbook\nfrom bibtexparser.bwriter import BibTexWriter\nfrom bibtexparser.bibdatabase import BibDatabase\nimport time\nimport sys\nfrom lxml import html\nimport requests\n\n\n# @Techreport{3gpp.36.331,\n# author = \"3GPP\",\n# title = \"{Evolved Universal Terrestrial Radio Access (E-UTRA); Radio Resource Control (RRC); Protocol specification}\",\n# type = \"TS\",\n# institution = \"{3rd Generation Partnership Project (3GPP)}\",\n# number = \"{36.331}\",\n# days = 11,\n# month = jul,\n# year = 2016,\n# url = \"http://www.3gpp.org/dynareport/36331.htm\",\n# }\n\ndb = BibDatabase()\ndb.entries = []\n\nwb2 = load_workbook(sys.argv[1])\nsheetnames = wb2.get_sheet_names()\nws = wb2[sheetnames[0]]\n\n# Iterate over the rows in the Excel-sheet but skip the header.\nfor row in ws.iter_rows(row_offset=1):\n\n number = row[0].value\n title = row[2].value\n type = row[1].value\n\n if number is None:\n continue\n\n entry = {\n 'ID': \"3gpp.{}\".format(number),\n 'ENTRYTYPE': \"techreport\",\n 'title': \"{{{}}}\".format(title),\n 'type': type,\n 'author': \"3GPP\",\n 'institution': \"{3rd Generation Partnership Project (3GPP)}\",\n 'number': number,\n 'url': \"http://www.3gpp.org/\\-DynaReport/\\-{}.htm\"\n .format(number.replace(\".\", \"\"))\n }\n\n if row[0].hyperlink is not None:\n # entry['url'] = row[0].hyperlink.target\n\n page = requests.get(row[0].hyperlink.target)\n tree = html.fromstring(page.content)\n\n for release in range(2):\n\n row = tree.xpath(\n '//tr[@id=\"SpecificationReleaseControl1_rpbReleases_i{}_ctl00_specificationsVersionGrid_ctl00__0\"]/td/div/a'\n .format(release))\n\n if len(row) > 0:\n daterow = tree.xpath(\n '//tr[@id=\"SpecificationReleaseControl1_rpbReleases_i{}_ctl00_specificationsVersionGrid_ctl00__0\"]/td'\n .format(release))\n\n entry['note'] = \"Version {}\".format(row[1].text.strip())\n\n if daterow[2].text.strip() is not \"\":\n date = daterow[2].text.split('-')\n entry['day'] = date[2].strip()\n entry['year'] = date[0].strip()\n entry['month'] = date[1].strip()\n break\n\n print(entry)\n db.entries.append(entry)\n\nwriter = BibTexWriter()\nwith open(sys.argv[2], 'w') as bibfile:\n bibfile.write(writer.write(db))\n","sub_path":"3gpp-citations.py","file_name":"3gpp-citations.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"310461378","text":"import psycopg2\nfrom datetime import date\n\n\ndef create_movies_table(table):\n try:\n conn = psycopg2.connect(database='djangotraining', user='djangouser', password='secret')\n try:\n cur = conn.cursor()\n cur.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS %s (\n title\t\t\tvarchar(64) NOT NULL UNIQUE,\n episode_nb\t\tinteger,\n opening_crawl\ttext,\n director\t\tvarchar(32) NOT NULL,\n producer\t\tvarchar(128) NOT NULL,\n release_date\tdate NOT NULL,\n PRIMARY KEY\t\t(episode_nb)\n );\n \"\"\" % (table, ))\n except Exception as e:\n return (\" cannot create table: \" + str(e))\n else:\n conn.commit()\t\t# What is commit?\n conn.close()\n cur.close()\n return (\"OK\")\n\n except Exception as e:\n return (' connection to postgreSQL failed: ' + str(e))\n\n\ndef insert_into_table(epi_nb: int, title: str, director: str, producer: str, rel_date: date, opening: str ='',):\n try:\n conn = psycopg2.connect(database='djangotraining', user='djangouser', password='secret')\n try:\n cur = conn.cursor()\t\t# how to set %s for table_name\n cur.execute(\"\"\"\n INSERT INTO ex04_movies (episode_nb, title, opening_crawl, director, producer, release_date)\n VALUES (%(epi_nb)s, %(title)s, %(opening)s, %(director)s, %(producer)s, %(rel_date)s)\n ON CONFLICT (episode_nb) DO NOTHING;\n \"\"\",\n {'epi_nb': epi_nb, 'title': title, 'opening' : opening, 'director' : director, 'producer': producer, 'rel_date': rel_date}\n )\n except Exception as e:\n return (\" cannot insert into table: \" + str(e))\n else:\n conn.commit()\n conn.close()\n cur.close()\n return (\"OK\")\n\n except Exception as e:\n return (' connection to postgreSQL failed: ' + str(e))\n\n\ndef select_all_from_table(table):\n try:\n conn = psycopg2.connect(database='djangotraining', user='djangouser', password='secret')\n try:\n cur = conn.cursor()\n cur.execute(\"\"\"\n SELECT episode_nb, title, opening_crawl, director, producer, release_date FROM %s;\n \"\"\" % (table, )\n )\n ret = cur.fetchall()\n except Exception as e:\n return (\" cannot select from table: \" + str(e))\n else:\n conn.commit()\n conn.close()\n cur.close()\n if len(ret) == 0:\n return (\"No data available.\")\n return (ret)\n\n except Exception as e:\n return (' connection to postgreSQL failed: ' + str(e))\n\ndef delete_movie_from_table(table, col_name, val):\n try:\n conn = psycopg2.connect(database='djangotraining', user='djangouser', password='secret')\n try:\n cur = conn.cursor()\n print(\"\"\"\n DELETE FROM %s\n WHERE %s = '%s';\n \"\"\" % (table, col_name, val,))\n cur.execute(\"\"\"\n DELETE FROM %s\n WHERE %s = '%s';\n \"\"\" % (table, col_name, val,)\n )\n\n except Exception as e:\n return (\" cannot select from table: \" + str(e))\n else:\n conn.commit()\n conn.close()\n cur.close()\n\n except Exception as e:\n return (' connection to postgreSQL failed: ' + str(e))\n\n","sub_path":"Day05_ve/Day05_root/ex04/psy.py","file_name":"psy.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"206467773","text":"#!/usr/bin/python\n#normalization\n\nimport pandas as pd\nimport numpy as np\nimport scipy as sp\n\ndata=pd.ExcelFile('fame_practice.xls')\n\ndata.sheet_names\n\nclean_data=data.parse('FAME_nut_comb_1_2_14_cleaned.tx', index_col=0)\n\ndata_new=clean_data.reset_index()\n\npre_cols=data_new.groupby(['ID']).mean()\n\nb=pre_cols.ix[:,[\"SAT\"]]\n\nc=np.log10(b)\n\npre_cols['log_SAT']= c\n\npre_cols.to_excel('logtestx.xls',sheet_name='Sheet1')\n","sub_path":"log_normal_test.py","file_name":"log_normal_test.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"379585706","text":"import cv2\nfrom matplotlib import pyplot as plt\n\nimg = cv2.imread(\"opencv-logo.png\")\nprint(type(img)) # \nprint(img.shape) # (222, 180, 3)\n\nbegin_point = (0, 80)\ncolor = \"yellow\"\ntext = \"Example\"\nplt.imshow(img)\n\nplt.axhline(begin_point[1], color=color, linestyle=\"--\", linewidth=1)\nplt.text(*begin_point, text, color=color)\nplt.show()\n","sub_path":"Python/Starting/chapxx/opencv/ch1/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"184078012","text":"# Adapted from\n# https://github.com/alan-turing-institute/sktime/blob/v0.11.0/sktime/utils/validation/_dependencies.py\n\nfrom importlib import import_module\nfrom typing import Optional\n\nfrom pycaret.internal.logging import get_logger\n\nlogger = get_logger()\n\n\ndef _check_soft_dependencies(\n package: str,\n severity: str = \"error\",\n extra: Optional[str] = \"all_extras\",\n install_name: Optional[str] = None,\n) -> bool:\n \"\"\"Check if all soft dependencies are installed and raise appropriate error message\n when not.\n\n Parameters\n ----------\n package : str\n Package to check\n severity : str, optional\n Whether to raise an error (\"error\") or just a warning message (\"warning\"),\n by default \"error\"\n extra : Optional[str], optional\n The 'extras' that will install this package, by default \"all_extras\".\n If None, it means that the dependency is not available in optional\n requirements file and must be installed by the user on their own.\n install_name : Optional[str], optional\n The package name to install, by default None\n If none, the name in `package` argument is used\n\n Returns\n -------\n bool\n If error is set to \"warning\", returns True if package can be imported or False\n if it can not be imported\n\n Raises\n ------\n ModuleNotFoundError\n User friendly error with suggested action to install all required soft\n dependencies\n RuntimeError\n Is the severity argument is not one of the allowed values\n \"\"\"\n install_name = install_name or package\n try:\n import_module(package)\n package_available = True\n except ModuleNotFoundError as e:\n msg = (\n f\"\\n{e}.\"\n f\"\\n'{package}' is a soft dependency and not included in the \"\n f\"pycaret installation. Please run: `pip install {install_name}` to install.\"\n )\n if extra is not None:\n msg = (\n msg\n + f\"\\nAlternately, you can install this by running `pip install pycaret[{extra}]`\"\n )\n\n if severity == \"error\":\n raise ModuleNotFoundError(msg)\n elif severity == \"warning\":\n logger.warning(f\"{msg}\")\n package_available = False\n else:\n raise RuntimeError(\n \"Error in calling _check_soft_dependencies, severity \"\n f'argument must be \"error\" or \"warning\", found \"{severity}\".'\n )\n\n return package_available\n","sub_path":"pycaret/utils/_dependencies.py","file_name":"_dependencies.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"391979485","text":"\"\"\"\nThis module provides helper functions that will add common information of\n Testplan execution to test report.\nThey could be used directly in testcases or provided to\n pre/pose_start/stop hooks.\nAlso provided is a predefined testsuite that can be included in user's\n Multitest directly.\n\"\"\"\n\n__all__ = [\n \"log_pwd\",\n \"log_hardware\",\n \"log_cmd\",\n \"log_environment\",\n \"attach_log\",\n \"attach_driver_logs_if_failed\",\n \"extract_driver_metadata\",\n \"clean_runpath_if_passed\",\n \"TestplanExecutionInfo\",\n]\n\nimport logging\nimport os\nimport psutil\nimport shutil\nimport socket\nimport sys\n\nfrom testplan.common.entity import Environment\nfrom testplan.common.utils.logger import TESTPLAN_LOGGER\nfrom testplan.common.utils.path import pwd\nfrom testplan.testing.multitest import testsuite, testcase\nfrom testplan.testing.multitest.result import Result\n\n\ndef log_hardware(result: Result) -> None:\n \"\"\"\n Saves host hardware information to the report.\n\n :param result: testcase result\n \"\"\"\n result.log(socket.getfqdn(), description=\"Current Host\")\n hardware = {\n \"CPU count\": psutil.cpu_count(),\n \"CPU frequence\": str(psutil.cpu_freq()),\n \"CPU percent\": psutil.cpu_percent(interval=1, percpu=True),\n \"Memory\": str(psutil.virtual_memory()),\n \"Swap\": str(psutil.swap_memory()),\n \"Disk usage\": str(psutil.disk_usage(os.getcwd())),\n \"Net interface addresses\": psutil.net_if_addrs(),\n \"PID\": os.getpid(),\n }\n result.dict.log(hardware, description=\"Hardware info\")\n\n\ndef log_environment(result: Result) -> None:\n \"\"\"\n Saves host environment variable to the report.\n\n :param result: testcase result\n \"\"\"\n result.dict.log(\n dict(os.environ), description=\"Current environment variable\"\n )\n\n\ndef log_pwd(result: Result) -> None:\n \"\"\"\n Saves current path to the report.\n\n :param result: testcase result\n \"\"\"\n result.log(pwd(), description=\"PWD environment\")\n result.log(os.getcwd(), description=\"Current real path\")\n\n\ndef log_cmd(result: Result) -> None:\n \"\"\"\n Saves command line arguments to the report.\n\n :param result: testcase result\n \"\"\"\n result.log(sys.argv, description=\"Command\")\n result.log(\n os.path.abspath(os.path.realpath(sys.argv[0])),\n description=\"Resolved path\",\n )\n\n\ndef extract_driver_metadata(env: Environment, result: Result) -> None:\n \"\"\"\n Saves metadata of each driver to the report.\n\n :param env: environment\n :param result: testcase result\n \"\"\"\n data = {rss.name: rss.extract_driver_metadata().to_dict() for rss in env}\n result.dict.log(data, description=\"Environment metadata\")\n\n\ndef attach_log(result: Result) -> None:\n \"\"\"\n Attaches top-level testplan.log file to the report.\n\n :param result: testcase result\n \"\"\"\n log_handlers = TESTPLAN_LOGGER.handlers\n for handler in log_handlers:\n if isinstance(handler, logging.FileHandler):\n result.attach(handler.baseFilename, description=\"Testplan log\")\n return\n\n\ndef attach_driver_logs_if_failed(\n env: Environment,\n result: Result,\n) -> None:\n \"\"\"\n Attaches stdout and stderr files to the report for each driver.\n\n :param env: environment\n :param result: testcase result\n \"\"\"\n if not env.parent.report.passed:\n for driver in env:\n std = getattr(driver, \"std\")\n if std:\n result.attach(\n std.out_path,\n description=\"Driver: {} stdout\".format(driver.name),\n )\n result.attach(\n std.err_path,\n description=\"Driver: {} stderr\".format(driver.name),\n )\n\n\ndef clean_runpath_if_passed(\n env: Environment,\n result: Result,\n) -> None:\n \"\"\"\n Deletes multitest-level runpath if the multitest passed.\n\n :param env: environment\n :param result: result object\n \"\"\"\n multitest = env.parent\n if multitest.report.passed:\n shutil.rmtree(multitest.runpath, ignore_errors=True)\n\n\n@testsuite\nclass TestplanExecutionInfo:\n \"\"\"\n Utility testsuite to log generic information of Testplan execution.\n \"\"\"\n\n @testcase\n def environment(self, env, result):\n \"\"\"\n Environment\n \"\"\"\n log_environment(result)\n\n @testcase\n def path(self, env, result):\n \"\"\"\n Execution path\n \"\"\"\n log_pwd(result)\n log_cmd(result)\n\n @testcase\n def hardware(self, env, result):\n \"\"\"\n Host hardware\n \"\"\"\n log_hardware(result)\n\n @testcase\n def logging(self, env, result):\n \"\"\"\n Testplan log\n \"\"\"\n attach_log(result)\n","sub_path":"testplan/common/utils/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"433245466","text":"#! /usr/bin/env python\n# --------------------------------------------------------\n# DIAMOND RATE SCANS\n# created on June 24th 2016 by M. Reichmann\n# --------------------------------------------------------\n\nfrom __future__ import print_function\nfrom analysis import *\nfrom collections import Counter\nfrom json import load, dump\n\nfrom ROOT import TMultiGraph, TH2F, TH1F, TGraph2DErrors\nfrom re import split as splitname\n\nfrom pad_collection import AnalysisCollection, PadCollection\nfrom run import Run\nfrom run_selection import RunSelection\nfrom selector import collection_selector\nfrom functools import partial\nfrom binning import Bins\n\n\nclass DiaScans(Analysis):\n def __init__(self, selection_name=None, verbose=False):\n Analysis.__init__(self, verbose=verbose)\n\n self.print_start(run=selection_name, tc=False, prnt=verbose)\n\n # Main\n self.Name = selection_name\n self.Selections = self.load_selections()\n self.Selection = self.load_selection(selection_name)\n\n # Config\n self.DUTParser = load_parser(join(self.Dir, 'Configuration', 'DiamondAliases.ini'))\n\n # Info\n self.RS = RunSelection() # dummy for information\n self.DUTName = self.load_dut_name()\n self.RunPlans = self.load_runplans()\n self.TestCampaigns = self.load_test_campaigns()\n self.RunSelections = self.load_run_selections()\n self.RunInfos = self.load_run_infos()\n self.Info = self.load_selection_info()\n self.NPlans = len(self.Info) if self.Info else None\n\n self.Colors = get_color_gradient(self.NPlans) if self.Info else None\n\n self.set_results_dir(join('Results', 'selections', '' if self.Name is None else self.Name))\n\n self.print_finished(prnt=verbose)\n\n # ----------------------------------------\n # region INIT\n def load_selections(self):\n with open(join(self.Dir, self.MainConfig.get('MISC', 'runplan selection file'))) as f:\n return load(f, object_pairs_hook=OrderedDict)\n\n def load_selection(self, name):\n if name is None:\n return\n if name not in self.Selections.keys():\n warning('\"{} does not exist in:\\n{} '.format(name, sorted(self.Selections.iterkeys())))\n self.Name = None\n return\n return self.Selections[name]\n\n def load_dut_name(self, name=None):\n name = self.Name if name is None else name\n if name is None:\n return\n if any([word in name.lower() for word in ['all', 'test']]):\n return name.title()\n dut = name.lower()\n if dut not in self.DUTParser.options('ALIASES'):\n dut = splitname('[-_]', name)[0]\n if dut.lower() not in self.DUTParser.options('ALIASES'):\n dut = '-'.join(splitname('[-_]', name)[:2])\n if dut.lower() not in self.DUTParser.options('ALIASES'):\n warning('No diamond name found in \"{}\". Please choose one from \\n{}'.format(name, ', '.join(self.DUTParser.options('ALIASES'))))\n return self.DUTParser.get('ALIASES', dut)\n\n def load_runplans(self):\n with open(self.RS.RunPlanPath) as f:\n return load(f, object_pairs_hook=OrderedDict)\n\n def load_test_campaigns(self):\n return sorted(self.RunPlans.iterkeys() if self.Name is None else list(set(self.Selection.iterkeys())))\n\n def load_run_selections(self):\n return OrderedDict((tc, RunSelection(tc)) for tc in self.TestCampaigns)\n\n def load_run_infos(self):\n return OrderedDict((tc, rs.RunInfos) for tc, rs in self.RunSelections.iteritems())\n\n def load_selection_info(self):\n selections = []\n if self.Selection is None:\n return\n for tc, rps in self.Selection.iteritems():\n for rp, dut_nrs in rps.iteritems():\n for dut_nr in array([dut_nrs]).flatten():\n selections.append(SelectionInfo(self.RunSelections[tc].select_runs_from_runplan(rp, dut_nr, unselect=True)))\n return selections\n # endregion INIT\n # ----------------------------------------\n\n # ----------------------------------------\n # region GET\n def get_rp_diamonds(self, tc, rp):\n sel = self.RunSelections[tc].select_runs_from_runplan(rp, unselect=True)\n return sel.get_dut_names()\n\n def get_first_run(self, tc, rp):\n return self.get_runs(rp, tc)[0]\n\n def get_runs(self, rp, tc):\n return self.RunPlans[tc][rp]['runs']\n\n def get_dut_names(self):\n return [sel.DUTName for sel in self.Info]\n\n def get_run_types(self):\n return [sel.Type.lower() for sel in self.Info]\n\n def get_irradiations(self, string=True):\n return [make_irr_string(sel.Irradiation) if string else float(sel.Irradiation) for sel in self.Info]\n\n def get_bias_voltages(self):\n return [sel.Bias for sel in self.Info]\n\n def get_rp_values(self, sel, f, pickle_info=None, redo=False, load_tree=True, *args, **kwargs):\n pickle_path = self.make_pickle_path(pickle_info.SubDir, pickle_info.Name, sel.RunPlan, sel.DUTNr, pickle_info.Suffix, sel.TCString) if pickle_info else ''\n if file_exists(pickle_path) and not redo:\n with open(pickle_path) as f:\n return pickle.load(f)\n self.info('Did not find {}'.format(pickle_path), prnt=pickle_path)\n ana = collection_selector(sel.RunPlan, sel.DUTNr, sel.TCString, load_tree)\n try:\n pf = partial(f, ana, redo=redo, *args, **kwargs)\n return do_pickle(pickle_path, pf, redo=redo) if pickle_info else pf()\n except TypeError:\n pf = partial(f, ana, *args, **kwargs)\n return do_pickle(pickle_path, pf, redo=redo) if pickle_info else pf()\n\n def get_values(self, f, pickle_info=None, redo=False, load_tree=True, *args, **kwargs):\n return [self.get_rp_values(sel, f, pickle_info, redo, load_tree, *args, **kwargs) for sel in self.Info]\n\n def get_pulse_heights(self, avrg=False, redo=False):\n return self.get_values(AnalysisCollection.get_pulse_heights, PickleInfo('Ph_fit', 'PhVals', '{}'.format(int(avrg))), redo=redo, avrg=avrg)\n\n def get_rate_dependcies(self, redo=False):\n return self.get_values(AnalysisCollection.get_rate_dependence, PickleInfo('Ph_fit', 'RD'), redo=redo)\n\n def print_rate_dependencies(self):\n for i, (s1, s2) in zip(self.Info, self.get_rate_dependcies()):\n print(i)\n print(' Rel STD: {:2.1f}'.format(s1.n * 100))\n print(' Rel Spread: {:2.1f} \\\\pm {:0.1f}'.format(s2.n * 100, s2.s * 100))\n\n def get_rp_pulse_heights(self, sel, corr=True, redo=False):\n return self.get_rp_values(sel, AnalysisCollection.get_pulse_heights, PickleInfo('Ph_fit', 'PhVals', '10000_{}'.format(corr)), redo=redo, corr=corr)\n\n def get_pedestals(self, redo=False):\n return self.get_values(PadCollection.get_pedestals, PickleInfo('Pedestal', 'Values'), redo=redo)\n\n def get_rel_errors(self, flux=105, redo=False):\n return self.get_values(AnalysisCollection.get_repr_error, PickleInfo('Errors', 'Repr', flux), redo=redo, flux=flux)\n\n def get_mean_uniformities(self, redo=False, low=False, high=False):\n return self.get_values(AnalysisCollection.get_mean_uniformity, PickleInfo('Uniformity', '', '{}{}'.format(int(low), int(high))), redo=redo, high_flux=high, low_flux=low)\n\n def get_uniformities(self, redo=False, low=False, high=False):\n return self.get_values(AnalysisCollection.get_uniformities, PickleInfo('Uniformity', 'SMSTD', '{}{}'.format(int(low), int(high))), redo=redo, high_flux=high, low_flux=low)\n\n def get_currents(self):\n return self.get_values(AnalysisCollection.get_currents, PickleInfo('Currents', 'Vals'))\n\n def get_fluxes(self, avrg=False):\n return self.get_values(AnalysisCollection.get_fluxes, PickleInfo('Flux', 'Vals', suf='{}'.format(int(avrg)) if avrg else ''), avrg=avrg)\n\n def get_all_infos(self):\n return [sel for tc in self.RunPlans.iterkeys() for sel in self.get_tc_infos(tc)]\n\n def get_dia_infos(self, dut_name):\n dut_name = self.RS.Run.translate_dia(dut_name)\n return [sel for tc in self.RunPlans.iterkeys() for sel in self.get_tc_infos(tc) if dut_name == sel.DUTName]\n\n def get_tc_infos(self, tc):\n rs = self.RunSelections[tc] if tc in self.RunSelections else RunSelection(tc)\n return [SelectionInfo(rs.select_runs_from_runplan(rp, dut + 1, unselect=True)) for rp in sorted(self.RunPlans[tc]) for dut in xrange(rs.get_n_duts(run_plan=rp))]\n\n def get_bias_str(self):\n return ' at {bias} V'.format(bias=self.Info[0].Bias) if len(set(self.get_bias_voltages())) == 1 else ''\n\n def get_all_ana_strings(self, dut=None, tc=None, redo=False):\n selections = self.get_all_infos() if dut is None and tc is None else self.get_dia_infos(dut) if tc is None else self.get_tc_infos(tc)\n selections = [sel for sel in selections if self.RS.Run.translate_dia(dut) == sel.DUTName] if dut is not None else selections\n redo = ' -rd' if redo else ''\n return '_'.join(['analyse {} {} -c -tc {} -d{}'.format(sel.RunPlan, sel.DUTNr, sel.TCString, redo) for sel in selections])\n # endregion GET\n # ----------------------------------------\n\n # ----------------------------------------\n # region SHOW\n def show_selections(self):\n header = ['Name', 'Diamond', 'Campaigns']\n rows = []\n old_sel = deepcopy(self.Name)\n for name in self.Selections.iterkeys():\n self.set_selection_name(name)\n row = [name, self.load_dut_name(), ', '.join(str(tc) for tc in self.load_test_campaigns())]\n rows.append(row)\n self.set_selection_name(old_sel)\n print_table(rows, header)\n\n def show_selection(self):\n \"\"\" Gives detailed information about the chosen selection \"\"\"\n print_table(rows=[sel() for sel in self.Info], header=['TC', 'RunPlan', 'DUT', 'Nr', 'Runs', 'Bias', 'Type', 'Irrad']) if self.Info else warning('Selection is empty!')\n\n def show_all_runplans(self):\n old_sel = deepcopy(self.Name)\n self.set_selection(None)\n for tc, runplans in sorted(self.RunPlans.iteritems()):\n if runplans:\n print_small_banner(tc, color='yellow')\n header = ['Runplan', 'Runs', 'Diamonds']\n rows = []\n for rp, dic in sorted(runplans.iteritems()):\n runs = dic['runs']\n rows.append([rp, '{:03d}-{:03d}'.format(runs[0], runs[-1]), ', '.join(self.get_rp_diamonds(tc, rp))])\n print_table(rows, header)\n self.set_selection_name(old_sel)\n\n def show_pulse_heights(self):\n rows = [[sel.TCString, sel.RunPlan] + ['{:2.2f}'.format(i) for i in mean_sigma([dic['ph'] for dic in phs.itervalues()])] for phs, sel in zip(self.get_pulse_heights(), self.Info)]\n print_table(rows, header=['Test Campaign', 'Run Plan', 'PH [mv]', 'STD [mV]'])\n # endregion SHOW\n # ----------------------------------------\n\n # ----------------------------------------\n # region SELECTION\n def set_selection(self, name):\n self.info('Set Selection {0}'.format(name))\n self.Name = name\n self.DUTName = self.load_dut_name()\n self.Selection = self.load_selection(name)\n self.TestCampaigns = self.load_test_campaigns()\n self.RunSelections = self.load_run_selections()\n self.RunInfos = [rs.RunInfos for rs in self.RunSelections.itervalues()]\n self.Info = self.load_selection_info()\n self.set_results_dir(join('Results', 'selections', self.Name)) if name else do_nothing()\n\n def set_selection_name(self, name):\n self.Name = name\n self.Selection = self.load_selection(name)\n\n def clear_selection(self):\n self.Selection = {}\n\n def select_runplan(self, runplan, dut=1, testcampaign=None):\n rp = make_runplan_string(runplan)\n tc = str(testcampaign) if testcampaign is not None else self.TestCampaigns[-1]\n if rp in self.RunPlans[tc]:\n if tc not in self.Selection:\n self.Selection[tc] = {}\n self.Selection[tc][rp] = dut\n else:\n log_warning('The runplan {0} does not exist in {1}!'.format(rp, tc))\n\n def unselect_runplan(self, runplan, testcampaign=None):\n rp = make_runplan_string(runplan)\n tc = str(testcampaign) if testcampaign is not None else self.TestCampaigns[-1]\n try:\n self.Selection[tc].pop(rp)\n except KeyError:\n log_warning('The runplan {0} does not exist in {1}!'.format(rp, tc))\n\n def add_selection(self):\n name = raw_input('Enter the name of the selection: ')\n self.clear_selection()\n self.Selections[name] = {} if name not in self.Selections else self.Selections[name]\n run_plan = raw_input('Enter test campaign, run plan number, channel: ')\n while run_plan:\n tc, rp, ch = [string.strip(' ') for string in run_plan.split(',')]\n self.select_runplan(rp, int(ch), tc)\n run_plan = raw_input('Enter test campaign, run plan number, channel (leave blank to finish): ')\n self.save_selection(name)\n\n def save_selection(self, name=None):\n name = raw_input('Enter the name of the selection: ') if name is None else name\n if not self.Selection:\n warning('Selection is empty!')\n return\n with open(join(self.Dir, self.MainConfig.get('MISC', 'runplan selection file')), 'w') as f:\n if name in self.Selections:\n query = raw_input('{} does already exist. Do you want to overwrite it? (y/n) '.format(name))\n if query.lower().strip() in ['no', 'n']:\n return\n self.Selections[name] = self.Selection\n dump(self.Selection, f, indent=2, sort_keys=True)\n self.info('Saved {} to selections'.format(name))\n # endregion SELECTION\n # ----------------------------------------\n\n # ----------------------------------------\n # region DRAWING\n def draw_collimator_settings(self, show=True):\n h = TH2F('h_cs', 'Collimator Settings', 125, 50, 300, 75, 0, 150)\n for tc in self.TestCampaigns:\n for run, data in self.RunInfos[tc].iteritems():\n try:\n h.Fill(data['fs11'], data['fs13'])\n except KeyError:\n pass\n format_histo(h, x_tit='fs11', y_tit='fsh13', y_off=1.3, stats=0, z_off=1.1, z_tit='Number of Entries', z_range=[0, 80])\n self.save_histo(h, 'CollimatorSettings', show, draw_opt='colz', lm=.12, rm=.16)\n\n def draw_flux_vs_collimators(self, show=True):\n gr = TGraph2DErrors()\n gr.SetNameTitle('gr_fc', 'Flux Vs. Collimators')\n col_settings = Counter([(data['fs11'], data['fs13']) for tc in self.TestCampaigns for data in self.RunInfos[tc].itervalues() if 'fs11' in data and data['fs11'] > 0])\n i = 0\n for col, nr in col_settings.iteritems():\n if nr > 10:\n flux_fit = self.draw_flux_distribution(col[0], col[1], show=False)\n if flux_fit is not None:\n gr.SetPoint(i, col[0], col[1], flux_fit.Parameter(1))\n gr.SetPointError(i, 0, 0, flux_fit.Parameter(2))\n i += 1\n self.draw_histo(gr, 'FluxVsCollimators', show, draw_opt='surf1', lm=.15, phi=17, theta=35)\n format_histo(gr, x_tit='fs11', x_off=1.3, y_tit='fsh13', y_off=1.9, stats=0, z_off=1.9, z_tit='Flux kHz/cm^{2}', markersize=2, y_range=[0, 130])\n self.save_plots('FluxVsCollimators', show=show, prnt=False)\n h = gr.Clone()\n h.Draw('samep')\n self.Objects.append(h)\n self.save_plots('FluxVsCollimators', show=show)\n\n def draw_flux_variations(self, show=True, rel_sigma=False):\n gr = self.make_tgrapherrors('gr_fd', 'Flux Deviations')\n col_settings = Counter([(data['fs11'], data['fs13']) for tc in self.TestCampaigns for data in self.RunInfos[tc].itervalues() if 'fs11' in data and data['fs11'] > 0])\n i = 0\n for col, nr in sorted(col_settings.iteritems()):\n if nr > 30:\n flux_fit = self.draw_flux_distribution(col[0], col[1], show=False)\n if flux_fit is not None:\n gr.SetPoint(i, flux_fit.Parameter(1), flux_fit.Parameter(2) if not rel_sigma else flux_fit.Parameter(2) / flux_fit.Parameter(1))\n yerr = flux_fit.ParError(2) + .5 * flux_fit.Parameter(2)\n if rel_sigma:\n yerr = flux_fit.Parameter(2) / flux_fit.Parameter(1) * sqrt(sum([((flux_fit.ParError(j) + .5 * flux_fit.Parameter(2) if rel_sigma else 0) / flux_fit.Parameter(j)) ** 2\n for j in xrange(1, 3)]))\n gr.SetPointError(i, flux_fit.ParError(1), yerr)\n l1 = self.draw_tlatex(gr.GetX()[i] * 1.05, gr.GetY()[i], '{0}/{1}'.format(make_col_str(col[0]), make_col_str(col[1])), color=1, align=10, size=.03)\n gr.GetListOfFunctions().Add(l1)\n i += 1\n format_histo(gr, x_tit='Mean Flux [au]', y_tit='{0}Sigma [au]'.format('Relative ' if rel_sigma else ''), y_off=1.3)\n self.draw_histo(gr, 'FluxVariations', show, draw_opt='alp', logx=True, logy=not rel_sigma, lm=.12)\n gr.GetXaxis().SetLimits(gr.GetX()[0] / 2, gr.GetX()[gr.GetN() - 1] * 4)\n self.save_plots('FluxVariations{0}'.format('Rel' if rel_sigma else ''), show=show)\n\n def draw_flux_distribution(self, fs11, fsh13, tc=None, do_fit=True, show=True, run_thr=None):\n values = []\n for tc in self.TestCampaigns if tc is None else [tc]:\n for run, data in sorted(self.RunInfos[tc].iteritems()):\n info_run = Run(run_number=run, test_campaign=tc, tree=False)\n if run_thr is not None:\n if run_thr > 0 and int(run) < run_thr:\n continue\n elif run_thr < 0 and int(run) > abs(run_thr):\n continue\n try:\n if data['fs11'] == fs11 and data['fs13'] == fsh13:\n flux = info_run.Flux\n # print tc, run, flux\n values.append(flux) if flux > 1 else do_nothing()\n except KeyError:\n pass\n if not values:\n return\n spread = max(values) - min(values)\n set_root_output(False)\n h = TH1F('h_fd', 'Flux Distribution for {0}/{1}'.format(fs11, fsh13), int(sqrt(len(values))) + 5, min(values) - .2 * spread, max(values) + .2 * spread)\n for val in values:\n h.Fill(val)\n self.format_statbox(only_fit=True, w=.25) if do_fit else do_nothing()\n format_histo(h, x_tit='Flux in kHz/cm^{2}', y_tit='Number of Entries', y_off=1.3, stats=0 if not do_fit else 1)\n self.draw_histo(h, '', show)\n fit = None\n if do_fit:\n h.SetName('Fit Results')\n set_root_output(show)\n fit = h.Fit('gaus', 'qs')\n self.save_plots('FluxDistribution{0}_{1}'.format(int(fs11), int(fsh13)), show=show)\n return fit\n\n def draw_dia_rate_scans(self, redo=False, irr=True, corr=True):\n mg = TMultiGraph('mg_ph', '{dia} Rate Scans{b};Flux [kHz/cm^{{2}}]; Pulse Height [mV]'.format(dia=self.DUTName, b=self.get_bias_str()))\n mgs = self.get_values(AnalysisCollection.draw_pulse_heights, PickleInfo('Ph_fit', 'MG', '10000_{}'.format(corr)), redo=redo, show=False, prnt=False)\n for i, (mgi, sel) in enumerate(zip(mgs, self.Info)):\n for g in mgi.GetListOfGraphs():\n format_histo(g, color=self.Colors[i], markersize=1.5, lw=2)\n if g.GetName() == 'gFirst':\n format_histo(g, color=1, marker=26, markersize=2)\n elif g.GetName() == 'gLast':\n format_histo(g, color=1, marker=23, markersize=2)\n mg.Add(mgi)\n legend = self.make_full_legend([mgi.GetListOfGraphs()[0] for mgi in mgs], irr)\n y = concatenate([get_graph_y(g) for g in mg.GetListOfGraphs()])\n format_histo(mg, draw_first=True, y_tit='Pulse Height [au]', y_range=[0, y.max().n * 1.1], tit_size=.05, lab_size=.05, y_off=.91, x_off=1.2, x_range=Bins().FluxRange)\n self.save_histo(mg, 'DiaScans{dia}'.format(dia=make_dia_str(self.DUTName)), draw_opt='a', logx=True, leg=legend, x=1.6, lm=.092, bm=.12, gridy=True)\n\n def draw_pedestals(self, rel=False, redo=False, show=True, irr=True):\n mg = TMultiGraph('mg_ph', '{dia} Pedestals{b};Flux [kHz/cm^{{2}}]; Pulse Height [mV]'.format(dia=self.DUTName, b=self.get_bias_str()))\n for i, (values, sel, fluxes) in enumerate(zip(self.get_pedestals(redo), self.Info, self.get_fluxes())):\n pedestals = array([make_ufloat(*tup) for tup in array(values).T])\n if rel:\n pedestals /= array([dic['ph'] for dic in self.get_rp_pulse_heights(sel, redo).itervalues()]) * .01\n g = self.make_tgrapherrors('gp{}'.format(i), '', x=fluxes.values(), y=pedestals, color=self.Colors[i])\n mg.Add(g, 'pl')\n legend = self.make_full_legend(mg.GetListOfGraphs(), irr)\n format_histo(mg, draw_first=True, y_tit='Pulse Height [au]', tit_size=.05, lab_size=.05, y_off=.91, x_off=1.2, x_range=Bins().FluxRange)\n self.save_histo(mg, '{}Pedestals'.format(self.Name), draw_opt='a', logx=True, leg=legend, x=1.6, lm=.092, bm=.12, gridy=True, show=show)\n\n def make_full_legend(self, graphs, irr=True):\n same_bias = len(set(self.get_bias_voltages())) == 1\n cols = 1 + (not same_bias) + irr\n legend = self.make_legend(.75, .4, w=.2 * cols, nentries=4, clean=True, cols=cols)\n for i, (g, sel) in enumerate(zip(graphs, self.Info)):\n legend.AddEntry(g, '{} - {}'.format(sel.RunPlan, make_tc_str(sel.TCString)), 'lp')\n legend.AddEntry(0, make_irr_string(sel.Irradiation), '') if irr else do_nothing()\n legend.AddEntry(0, get_bias_root_string(sel.Bias), '') if not same_bias else do_nothing()\n return legend\n\n def draw_title_pad(self, h, x0, lm, c_height):\n if self.Title:\n biases = list(set(self.get_bias_voltages()))\n bias_str = ' at {b}'.format(b=make_bias_str(biases[0])) if len(biases) == 1 else ''\n self.draw_tpad('p0', 'p0', pos=[x0, 1 - h / c_height, 1, 1], margins=[0, 0, 0, 0], transparent=True)\n self.draw_tpavetext('{dia} Rate Scans{b}'.format(dia=self.DUTName, b=bias_str), lm, 1, 0, 1, font=62, align=13, size=.5, margin=0)\n get_last_canvas().cd()\n\n def draw_scaled_rate_scans(self, irr=False, y_range=.07, pad_height=.18, scale=1, avrg=False):\n data = zip(self.get_pulse_heights(avrg=avrg), self.get_fluxes(avrg=avrg), get_color_gradient(self.NPlans))\n title_height = pad_height / 2 if self.Title else .03 # half of a pad for title\n c_height = (self.NPlans + .5) * pad_height + title_height # half of a pad for the x-axis\n c_width = 1.3 * pad_height / .2 # keep aspect ratio for standard pad_height\n c = self.make_canvas(name='csrc', x=c_width, y=c_height, transp=True, logx=True, gridy=True)\n lm, rm, x0, size = .07, .02, .08, .22\n\n self.draw_title_pad(title_height, x0, lm, c_height)\n self.draw_tpad('p1', 'p1', pos=[0, 0, x0, 1], margins=[0, 0, 0, 0], transparent=True) # info pad\n self.draw_tpavetext('Scaled Pulse Height', 0, 1, 0, 1, align=22, size=.5, angle=90, margin=0) # y-axis title\n c.cd()\n\n for i, (ph, flux, color) in enumerate(data):\n c.cd()\n y0, y1 = [(c_height - title_height - pad_height * (i + j)) / c_height for j in [1, 0]]\n p = self.draw_tpad('p{i}'.format(i=i + 3), '', pos=[x0, y0, 1, y1], margins=[lm, rm, 0, 0], logx=True, gridy=True, gridx=True)\n g = self.make_tgrapherrors('gsph{}'.format(i), '', x=flux, y=ph)\n scale_graph(g, val=scale) if scale else do_nothing()\n format_histo(g, title=' ', color=color, x_range=Bins().FluxRange, y_range=[1 - y_range, 1 + y_range], marker=markers(i), lab_size=size, ndivy=505, markersize=1.5, x_ticks=.15)\n self.draw_histo(g, draw_opt='ap', canvas=p)\n self.draw_legend(i, g, irr, rm)\n c.cd()\n\n self.draw_tpad('p2', pos=[x0, 0, 1, pad_height / 2 / c_height], margins=[lm, rm, 0, 0], transparent=True) # x-axis pad\n self.draw_x_axis(1, lm, 1 - rm, 'Flux [kHz/cm^{2}]', Bins().FluxRange, opt='', log=True, tick_size=0, lab_size=size * 2, tit_size=size * 2, off=1.1)\n self.save_plots('ScaledDiaScans{dia}'.format(dia=make_dia_str(self.DUTName)))\n\n def draw_scaled_distribution(self, excluded=None):\n values = concatenate(([vals / mean_sigma(vals)[0] for i, vals in enumerate(self.get_pulse_heights()) if i not in [excluded]]))\n h = TH1F('hsd', 'Scaled Pulse Height Distribution', 40, .9, 1.1)\n h.FillN(values.size, array([v.n for v in values], 'd'), full(values.size, 1, 'd'))\n self.format_statbox(all_stat=1)\n format_histo(h, x_tit='Scaled Pulse Height', y_tit='Number of Entries', y_off=1.2, fill_color=self.FillColor)\n self.draw_histo(h, lm=.12)\n return values\n\n def make_plots(self, name, f, irr_pad=None, canvas=None, **kwargs):\n for sel in self.Info:\n self.info('Creating {} Plots for {}'.format(name, sel.TCString))\n self.get_rp_values(sel, f, **kwargs)\n self.draw_irradiation(make_irr_string(sel.Irradiation), irr_pad, left=False) if irr_pad is not None else do_nothing()\n self.save_plots('{}{}_{}_{}'.format(name, sel.TCString, sel.RunPlan, sel.DUTNr), canvas=get_object(canvas))\n\n def make_pulse_height_plots(self, y_range=None):\n self.make_plots('PH', AnalysisCollection.draw_pulse_heights, show=False, y_range=y_range, irr_pad=get_object('p1'))\n\n def make_current_plots(self, c_range=None):\n self.make_plots('Currents', AnalysisCollection.draw_currents, show=False, c_range=c_range, draw_opt='al')\n\n def make_current_flux_plots(self, c_range=None):\n self.make_plots('CF', AnalysisCollection.draw_currents, show=False, c_range=c_range, draw_opt='al', with_flux=True, canvas='cc')\n\n def draw_currents(self, align=False, show=True):\n mg = TMultiGraph('mgc', 'Leakage Current vs. Flux')\n legend = self.make_legend(nentries=len(self.RunSelections), w=.4, x2=.52)\n currents = [c.values() for c in self.get_currents()]\n fluxes = [f.values() for f in self.get_fluxes()]\n for i, (x, y) in enumerate(zip(fluxes, currents)):\n g = self.make_tgrapherrors('gf', 'gf', x=x, y=y)\n if align:\n fit = g.Fit('pol1', 'qs0')\n g = self.make_tgrapherrors('gc{}'.format(i), '', y=array(currents[i]) - fit.Parameter(0) + .1, x=fluxes[i])\n format_histo(g, color=self.get_color())\n legend.AddEntry(g, '{tc} - {hv}'.format(tc=self.Info[i].TCString, hv=self.get_rp_values(self.Info[i], AnalysisCollection.get_hv_name, load_tree=False)), 'pl')\n mg.Add(g, 'p')\n format_histo(mg, draw_first=True, y_tit='Current [nA]', x_tit='Flux [kHz/cm^{2}]', y_range=[.1, array(currents).max().n * 2], x_range=Bins().FluxRange)\n self.save_histo(mg, 'CurrentFlux{}'.format(self.Name), draw_opt='a', logx=True, logy=True, leg=legend, bm=.17, show=show)\n\n def get_titles(self, irr=False):\n if len(set(self.get_dut_names())) > 1:\n return self.get_dut_names()\n tits = self.get_irradiations() if irr else [make_tc_str(tc) for tc in self.TestCampaigns]\n if any(['rand' in word for word in self.get_run_types()]):\n for i, sel in enumerate(self.Info):\n tits[i] += ' (random)' if 'rand' in sel.Type.lower() else ' '\n return tits\n\n def draw_legend(self, ind, gr, irr, rm):\n add_bias = len(set(self.get_bias_voltages())) > 1\n tits = self.get_titles(irr)\n biases = [make_bias_str(bias) for bias in self.get_bias_voltages()] if add_bias else [''] * len(tits)\n x1 = 1 - max([(12 if irr else len(tit)) + len(bias) for tit, bias in zip(tits, biases)]) * .022\n legend = self.make_legend(x1, 1, x2=1 - rm, nentries=1.2, scale=5)\n legend.AddEntry(gr, tits[ind], 'pe')\n if add_bias:\n legend.SetNColumns(2)\n legend.AddEntry('', biases[ind], '')\n legend.Draw()\n\n def set_bin_labels(self, h):\n for i, sel in enumerate(self.Info):\n h.GetXaxis().SetBinLabel(h.GetXaxis().FindBin(i), '{} - {}'.format(make_tc_str(sel.TCString, 0), sel.RunPlan))\n\n def draw_mean_pedestals(self, redo=False, show=True):\n y = array([make_ufloat(mean(tc_values, axis=1)) for tc_values in self.get_pedestals(redo)])\n g = self.make_tgrapherrors('gmp', 'Mean Pedestals', x=arange(y.size), y=y)\n format_histo(g, x_tit='Run Plan', y_tit='Pulse Height [mV]', y_off=1.2, x_range=increased_range([0, y.size - 1], .3, .3), x_off=2.5)\n self.set_bin_labels(g)\n self.save_histo(g, 'PedestalMeans{}'.format(self.Name.title().replace('-', '').replace('_', '')), show, draw_opt='ap', bm=.2, x=1.5, y=.75, gridy=True)\n\n def draw_means(self, y_range=None, show=True):\n y = array([make_ufloat(mean_sigma([dic['ph'] for dic in ph.itervalues()])) for ph in self.get_pulse_heights()])\n g = self.make_tgrapherrors('gms', 'Pulse Height Evolution', x=arange(y.size), y=y)\n format_histo(g, x_tit='Run Plan', y_tit='Mean Pulse Height [mV]', y_off=1.2, x_range=increased_range([0, y.size - 1], .3, .3), x_off=2.5, y_range=y_range)\n self.set_bin_labels(g)\n self.save_histo(g, 'Means{}'.format(self.Name.title().replace('-', '').replace('_', '')), show, draw_opt='ap', bm=.2, x=1.5, y=.75, gridy=True)\n\n def draw_sigmas(self, y_range=None, show=True):\n mean_sigmas = [mean_sigma([dic['ph'] for dic in ph.itervalues()]) for ph in self.get_pulse_heights()]\n y = array([make_ufloat((0, 100 * s / m)) for m, s in mean_sigmas])\n g = self.make_tgrapherrors('gms', 'Pulse Height STD Evolution', x=arange(y.size), y=y)\n format_histo(g, x_tit='Run Plan', y_tit='Pulse Height Standard Deviation [%]', y_off=1.2, x_range=increased_range([0, y.size - 1], .3, .3), x_off=2.5, y_range=y_range)\n self.set_bin_labels(g)\n self.save_histo(g, 'Means{}'.format(self.Name.title().replace('-', '').replace('_', '')), show, draw_opt='ap', bm=.2, x=1.5, y=.75, gridy=True)\n\n def draw_uniformity(self, arg=2, redo=False, low=False, high=False):\n y_values = [v[arg] for v in self.get_mean_uniformities(redo=redo, low=low, high=high)]\n x_values = [make_ufloat((v, v * .2)) for v in self.get_irradiations(string=False)]\n g = self.make_tgrapherrors('gu', 'Uniformity', x=x_values, y=y_values)\n format_histo(g, x_tit='Irradiation [n/cm^{2}]', y_tit='FWHM/MPV', y_off=1.3)\n self.draw_histo(g, draw_opt='ap')\n\n def draw_peak_flux(self, show=True):\n leg = self.make_legend(x2=.45, w=.3)\n mg = TMultiGraph('mgph', 'Peak Flux vs. FAST-OR Flux')\n values_list = self.get_values(AnalysisCollection.get_peak_flux, PickleInfo('Peaks', 'Flux'))\n flux_list = self.get_fluxes()\n for sel, values, fluxes in zip(self.Info, values_list, flux_list):\n g = self.make_tgrapherrors('g{}'.format(sel.RunPlan), '', x=fluxes, y=values)\n format_histo(g, color=self.get_color())\n leg.AddEntry(g, '{} @ {:+1.0f}V'.format(sel.DUTName, sel.Bias), 'pl')\n mg.Add(g, 'p')\n x, y = concatenate(flux_list), concatenate(values_list)\n x_range, y_range = [.5 * min(x).n, 1.2 * max(x).n], [.5 * min(y).n, 1.2 * max(y).n]\n format_histo(mg, draw_first=True, y_tit='Peak Flux [kHz/cm^{2}] ', x_tit='FAST-OR Flux [kHz/cm^{2}]', x_range=x_range, y_off=1.8, y_range=y_range)\n self.save_histo(mg, 'PeakFluxes{}'.format(self.Name), draw_opt='a', leg=leg, show=show, lm=.13)\n # endregion DRAWING\n # ----------------------------------------\n\n\nclass SelectionInfo:\n def __init__(self, sel):\n self.TCString = sel.TCString\n self.RunPlan = sel.SelectedRunplan\n self.DUT = sel.SelectedDUT\n self.DUTName = self.DUT.Name\n self.DUTNr = self.DUT.Number\n self.Verbose = sel.Run.Verbose\n self.Bias = self.DUT.Bias\n self.Irradiation = self.DUT.get_irradiation(self.TCString)\n self.Type = sel.SelectedType.lower()\n self.Runs = sel.get_selected_runs()\n\n def __str__(self):\n return 'Selection instance: {} {} {}'.format(self.TCString, self.RunPlan, self.DUTName)\n\n def __repr__(self):\n return self.__str__()\n\n def __call__(self):\n return [self.TCString, self.RunPlan, self.DUTName, self.DUTNr, '{:03d}-{:03d}'.format(self.Runs[0], self.Runs[-1]), '{:+4.0f}V'.format(self.Bias), self.Type, self.Irradiation]\n\n\nclass PickleInfo:\n def __init__(self, sub_dir, name, suf=None):\n self.SubDir = sub_dir\n self.Name = name\n self.Suffix = '' if suf is None else str(suf)\n\n\nif __name__ == '__main__':\n\n aparser = ArgumentParser()\n aparser.add_argument('sel', nargs='?', default=None, help='name of the selection')\n aparser.add_argument('-d', nargs='?', default=None, help='dut')\n aparser.add_argument('-tc', nargs='?', default=None, help='test campaign')\n aparser.add_argument('-v', '--verbose', action='store_false')\n aparser.add_argument('-p', action='store_true', help='print analysis strings')\n aparser.add_argument('-r', action='store_true', help='redo')\n aparser.add_argument('-s', action='store_true', help='activate show single selection')\n aparser.add_argument('-sa', action='store_true', help='active show all selections')\n pargs = aparser.parse_args()\n\n z = DiaScans(pargs.sel, pargs.verbose)\n if pargs.p:\n print(z.get_all_ana_strings(pargs.d, pargs.tc, pargs.r))\n if pargs.s:\n z.show_selection()\n if pargs.sa:\n z.show_selections()\n","sub_path":"src/runplan_selection.py","file_name":"runplan_selection.py","file_ext":"py","file_size_in_byte":34274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"638273235","text":"# SPDX-License-Identifier: BSD-3-Clause\n# Copyright(c) 2019 Nippon Telegraph and Telephone Corporation\nimport copy\n\n\nclass BaseComplPatternItem(object):\n \"\"\"Base class for completion of pattern items.\n\n Each pattern item inherits from this class.\n Provides base functionality and command completion.\n \"\"\"\n\n # Token after DATA_FIELDS\n MATCHING_PATTERN = [\"is\", \"spec\", \"last\", \"mask\", \"prefix\"]\n\n def __init__(self, data=None):\n if data is not None:\n self.data = data\n\n def compl_item(self, tokens, index):\n \"\"\"Completion for pattern item commands.\n\n Complement using the information defined in the inherited class.\n \"\"\"\n candidates = []\n\n while index < len(tokens):\n if tokens[index - 1] == \"/\":\n # Completion processing end when \"/\" is specified\n candidates = []\n break\n\n elif tokens[index - 1] in self.DATA_FIELDS:\n candidates = self.MATCHING_PATTERN\n\n elif tokens[index - 1] in self.MATCHING_PATTERN:\n if tokens[index - 1] == \"prefix\":\n candidates = [\"Prefix\"]\n\n else:\n tmp_token = self.DATA_FIELDS_VALUES.get(tokens[index - 2])\n if tmp_token is not None:\n candidates = [tmp_token]\n else:\n candidates = []\n\n else:\n # Data fields candidate and end token\n candidates = copy.deepcopy(self.DATA_FIELDS)\n candidates.append(\"/\")\n\n index += 1\n\n return (candidates, index)\n\n\nclass ComplEth(BaseComplPatternItem):\n \"\"\"Complete pattern item `eth`.\"\"\"\n\n # Eth data fields\n DATA_FIELDS = [\"dst\", \"src\", \"type\"]\n\n # DATA_FIELDS value candidates\n DATA_FIELDS_VALUES = {\n \"dst\": \"MAC_ADDRESS\",\n \"src\": \"MAC_ADDRESS\",\n \"type\": \"UNSIGNED_INT\"\n }\n\n\nclass ComplVlan(BaseComplPatternItem):\n \"\"\"Complete pattern item `vlan`.\"\"\"\n\n # Vlan data fields\n DATA_FIELDS = [\"tci\", \"pcp\", \"dei\", \"vid\", \"inner_type\"]\n\n # DATA_FIELDS value candidates\n DATA_FIELDS_VALUES = {\n \"tci\": \"UNSIGNED_INT\",\n \"pcp\": \"UNSIGNED_INT\",\n \"dei\": \"UNSIGNED_INT\",\n \"vid\": \"UNSIGNED_INT\",\n \"inner_type\": \"UNSIGNED_INT\"\n }\n","sub_path":"src/cli/commands/pri_flow_compl_pattern.py","file_name":"pri_flow_compl_pattern.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"533835000","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 30 17:37:18 2016\n\n@author: zozo\n\"\"\"\n\nfname = 'A-large.in'\nf = open(fname,'r')\n\nnlines = f.readline().replace('\\n','') #\ninputs = []\nfor l in range(int(nlines)):\n inputs.append(f.readline().replace('\\n',''))\n\nf.close()\n\nnum = [\"ZERO\", \"TWO\", \"SIX\",\"EIGHT\", \"THREE\",\"FOUR\", \"FIVE\", \"SEVEN\", \"NINE\",\"ONE\",]\ndigits = [0,2,6,8,3,4,5,7,9,1]\n\noutstr = ''\n\nfor i in range(len(inputs)):\n outlist = []\n for k in range(len(num)):\n stop = 0\n while stop < 1:\n numpresent = 0\n for c in num[k]:\n if c in inputs[i] :\n numpresent += 1\n else:\n stop = stop + 1\n \n \n if len(num[k])==numpresent:\n outlist.append(digits[k])\n for kk in range(len(num[k])):\n inputs[i] = inputs[i].replace(num[k][kk],'',1)\n else:\n stop = stop + 1\n \n outlist.sort()\n outstr += 'Case #' + str(i+1) + ': ' \n for e in outlist: \n outstr+=str(e)\n outstr+='\\n' \n\n\n\nfout = open(fname + '.sub','w')\nfout.writelines(outstr)\nfout.close()","sub_path":"codes/CodeJamCrawler/16_2_1/Guf/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"498088838","text":"from Caracteristique import Caracteristique, ListeVide\nimport sys\n\n\ndef main():\n caract = Caracteristique()\n try:\n caract.afficher_caracteristiques()\n except ListeVide:\n sys.exit(\"La structure du fichier caractéristique n'est pas valide !\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"552876155","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 21 13:57:06 2019\n\n@author: ragnoletto\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport helper as hlp\nimport math as ma\n\n# Loading data\ndata = np.load('data100D.npy')\n#data = np.load('data2D.npy')\n[num_pts, dim] = np.shape(data)\nis_valid = True\n# For Validation set\nif is_valid:\n valid_batch = int(num_pts / 3.0)\n np.random.seed(45689)\n rnd_idx = np.arange(num_pts)\n np.random.shuffle(rnd_idx)\n val_data = data[rnd_idx[:valid_batch]]\n data = data[rnd_idx[valid_batch:]]\n\n# Distance function for GMM\ndef distanceFunc(X, MU):\n # Inputs\n # X: is an NxD matrix (N observations and D dimensions)\n # MU: is an KxD matrix (K means and D dimensions)\n # Outputs\n # pair_dist: is the pairwise distance matrix (NxK)\n # TODO\n X2 = tf.multiply(X,X)\n X2 = tf.reduce_sum(X2,axis = 1,keepdims = True)\n MU2 = tf.multiply(tf.transpose(MU), tf.transpose(MU))\n MU2 = tf.reduce_sum(MU2,axis=0,keepdims = True)\n pair_dist = X2 + MU2 - tf.multiply(2.0,tf.matmul(X,tf.transpose(MU)))\n return pair_dist\n\ndef log_GaussPDF(X, mu, sigma):\n # Inputs\n # X: N X D\n # mu: K X D\n # sigma: K X 1\n # log_pi: K X 1\n\n # Outputs:\n # log Gaussian PDF N X K\n\n # TODO\n dist_matrix = distanceFunc(X,mu)\n sigmaT = tf.reshape(sigma,[-1, K]) \n log_PDF = -1/2*tf.divide(dist_matrix,sigmaT) - tf.math.log(tf.sqrt(2.0*ma.pi*sigmaT))\n return log_PDF\n\ndef log_posterior(log_PDF, log_pi):\n # Input\n # log_PDF: log Gaussian PDF N X K\n # log_pi: K X 1\n\n # Outputs\n # log_post: N X K\n\n # TODO\n log_post = log_PDF + tf.transpose(log_pi)\n return log_post\n \ndef MoG():\n X = tf.placeholder(tf.float32,[None, D], name=\"X\")\n MU = tf.get_variable('mean',dtype = tf.float32,shape = [K,D], initializer = tf.initializers.random_normal())\n Psi = tf.get_variable('variance',dtype = tf.float32,shape = [K,1], initializer = tf.initializers.random_normal())\n Pi = tf.get_variable('posterior',dtype = tf.float32,shape = [K,1], initializer = tf.initializers.random_normal())\n \n log_Pi = hlp.logsoftmax(Pi)\n Sigma2 = tf.exp(Psi)\n \n Gauss_PDF = log_GaussPDF(X,MU,Sigma2)\n \n Log_Post = log_posterior(Gauss_PDF,log_Pi)\n Belong = tf.arg_max(Log_Post,dimension = 1)\n lossfunc = -tf.reduce_sum(hlp.reduce_logsumexp(Log_Post))\n optimizer = tf.train.AdamOptimizer(learning_rate = 0.01, beta1 = 0.9, beta2 = 0.99, epsilon = 1e-5)\n train = optimizer.minimize(loss=lossfunc)\n return X,MU,Psi, Pi,lossfunc,Belong,train\n \nD = data.shape[1]\nK = 5\ntf.reset_default_graph() \nX,mu,psi, pi, error,belongs,train = MoG()\ninit = tf.global_variables_initializer()\nsess = tf.InteractiveSession()\nsess.run(init)\nepochs = 500\n\n\nfor step in range(0, epochs):\n _,current_mu,curr_psi, curr_pi ,current_error = sess.run([train,mu,psi,pi,error],feed_dict = {X:data})\n if step % 10 == 0:\n print(current_error)\n \n \nfinal_belong = sess.run([belongs],feed_dict = {X:data})\nvalidloss = sess.run([error], feed_dict = {X:val_data})\nfinal_belong = final_belong[0]\nclassdiv = np.zeros(K)\nfor i in range(0,K):\n classdiv[i] = np.mean(final_belong==i)\n\n \n#RUN TO PLOT THE CLASSES, TAKES LONG TIME DUE TO ITERATION\ndef plotclasses(data,final_belong,current_mu):\n colors = ['red','green','blue','purple', 'orange']\n for i in range(current_mu.shape[0]):\n idx = np.where(final_belong==i)\n current_class = np.take(data,idx[0],axis=0)\n #print(idx,data.shape,current_class.shape)\n plt.scatter(current_class[:,0],current_class[:,1], color = colors[i])\n\n plt.grid(True)\n #plt.scatter(mu_x,mu_y, color = 'black')\n for i in range(current_mu.shape[0]):\n plt.scatter(current_mu[i][0],current_mu[i][1], color = 'black')\n plt.annotate(i, (current_mu[i][0],current_mu[i][1]))\n plt.show()\n \n \nplotclasses(data,final_belong,current_mu)\n\nsess.close()","sub_path":"a3/gmm_david.py","file_name":"gmm_david.py","file_ext":"py","file_size_in_byte":3985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"50830493","text":"# Author: Fernando Zuher\n# Place: Brazil\n# Date: 12/04/2020\n# Book: Python Crash Course, 2nd Edition. Author: ERIC MATTHES.\n# About: Exercise, Chapter 7 - User Input and while Loops\n\n# 7-9. No Pastrami: Using the list sandwich_orders from Exercise 7-8, make sure\n# the sandwich 'pastrami' appears in the list at least three times. Add code\n# near the beginning of your program to print a message saying the deli has\n# run out of pastrami, and then use a while loop to remove all occurrences of\n# 'pastrami' from sandwich_orders . Make sure no pastrami sandwiches end up\n# in finished_sandwiches.\n\nsandwich_orders = ['pastrami', 'misto quente', 'pastrami', 'hamburguer', 'big mac', 'pastrami']\nfinished_sandwiches = []\n\nprint(\"The deli has run out of pastrami.\")\nwhile \"pastrami\" in sandwich_orders:\n\tsandwich_orders.remove('pastrami')\n\nfor sandwich in sandwich_orders:\n\tprint(f\"I made your {sandwich} sandwich.\")\n\tfinished_sandwiches.append(sandwich);\n\nprint(\"The sandwiches made were:\")\nfor sandwich in finished_sandwiches:\n\tprint(f\"\\t {sandwich}\")\n\n\n\n","sub_path":"Python/Chapters/Part I - Basics/Chapter 7 - User Input and while Loops/7_9_no_pastrami.py","file_name":"7_9_no_pastrami.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"517004404","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*- \n\n\nimport tensorflow as tf\nimport numpy as np\nimport datetime as dt\n\nx_in = tf.Variable(tf.random_uniform(shape=[20, 1], minval=0.0, maxval=1.0), dtype=tf.float32, trainable=False)\ny_in = tf.Variable(tf.random_uniform(shape=[20, 1], minval=0.0, maxval=1.0), dtype=tf.float32, trainable=False)\n\nhidden = 500\nlearning_rate = 1e-4\n# global_step=tf.Variable(0, trainable=False)\n# learning_rate = tf.train.exponential_decay(1e-2, global_step, 2e4, 0.96, staircase=False)\n\nw0x = tf.Variable(tf.random_normal(shape=[1, hidden], stddev=1), dtype=tf.float32)\nw0y = tf.Variable(tf.random_normal(shape=[1, hidden], stddev=1), dtype=tf.float32)\nb0x = tf.Variable(tf.random_normal(shape=[1, hidden], stddev=1), dtype=tf.float32)\nb0y = tf.Variable(tf.random_normal(shape=[1, hidden], stddev=1), dtype=tf.float32)\nw1 = tf.Variable(tf.random_normal(shape=[hidden, 1], stddev=1), dtype=tf.float32)\nb1 = tf.Variable(tf.random_normal(shape=[1, 1], stddev=1), dtype=tf.float32)\n\na = tf.sigmoid(tf.matmul(x_in, w0x) + b0x) + tf.sigmoid(tf.matmul(y_in, w0y) + b0y)\nnet_out = tf.matmul(a, w1) + b1\n\ndsigmoidh = tf.sigmoid(a) * (1 - tf.sigmoid(a))\npd_x = w0x * (tf.transpose(w1) * dsigmoidh)\npd_y = w0y * (tf.transpose(w1) * dsigmoidh)\ndsigmoidh2 = tf.sigmoid(a) + dsigmoidh - 2 * tf.sigmoid(a) * dsigmoidh\npd_x2 = (w0x * w0x) * (tf.transpose(w1) * dsigmoidh2)\npd_y2 = (w0y * w0y) * (tf.transpose(w1) * dsigmoidh2)\n\n\ntral = tf.abs(x_in * (1 - x_in) * (y_in * (1 - y_in) * pd_y2 + (2 - 4 * y_in) * pd_y - 2 * net_out) + y_in *\n (1 - y_in) * (x_in * (1 - x_in) * pd_x2 + (2 - 4 * x_in) * pd_x - 2 * net_out) - (np.pi ** 2) *\n y_in * tf.sin(np.pi * x_in))\nloss = tf.reduce_mean(tral)\n\noptimizer = tf.train.GradientDescentOptimizer(learning_rate)\n# optimizer = tf.train.AdamOptimizer(learning_rate)\ntrain = optimizer.minimize((loss))\n\ninit = tf.global_variables_initializer()\n\nsess = tf.Session()\nsess.run(init)\n\nstep = 0\n\nwhile 1:\n step = step + 1\n sess.run(train)\n if step % 2000 == 0:\n time = dt.datetime.now().isoformat()\n print(time, 'step:', step, 'loss:', sess.run(loss))\n if sess.run(loss) < 0.1:\n print(time, 'step:', step, 'loss:', sess.run(loss))\n break\n\nsess.close()\n\n'''\nx = np.linspace(0, 1, 100)\ny = np.linspace(0, 1, 100)\n'''","sub_path":"PDE/PDE2.py","file_name":"PDE2.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"275378410","text":"import os\nimport getpathInfo# 自己定义的内部类,该类返回项目的绝对路径\n#调用读Excel的第三方库xlrd\nimport xlrd\nimport xlwt\n\n# 拿到该项目所在的绝对路径\npath = getpathInfo.get_Path()\n\nclass ReadExcel():\n def get_xls(self,xls_name,sheet_name):\n\n\n #xls路径 = path + filename\n xlsPath = os.path.join(path,'testFile','case',xls_name)\n #打开用例\n rb = xlrd.open_workbook(xlsPath)\n #获取sheet\n sheet1 = rb.sheet_by_name(sheet_name)\n\n # wb = xlrd.open_workbook(xlsPath)\n print(xlsPath)\n print(wb.sheet_names())\n\n ncols = sheet1.ncols\n nrows = sheet1.nrows\n\n for row in range(1, nrows):\n print('----------------------------------当前执行--------第',row,'行----------------------------------')\n res = None\n url = url0+sheet1.row_values(row, 0, 1)[0]\n method = sheet1.row_values(row, 1, 2)[0]\n params = sheet1.row_values(row, 2, 3)[0]\n\n\nif __name__ == '__main__':#我们执行该文件测试一下是否可以正确获取Excel中的值\n print(ReadExcel().get_xls('userCase.xlsx', 'login'))\n print(ReadExcel().get_xls('userCase.xlsx', 'login')[0][1])","sub_path":"MyFrame_API/common/my_readExcel.py","file_name":"my_readExcel.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"491812999","text":"# See LICENSE for details\n\nimport os\nimport sys\nimport pluggy\nimport shutil\nimport yaml\nimport random\nimport re\nimport datetime\nimport pytest\nimport filecmp\nimport glob\n\nfrom river_core.log import logger\nfrom river_core.utils import *\n\n\ndef compile_cmd_list(make_file, work_dir, key_list):\n\n run_commands = []\n\n # Hmm here the key_list becomes a string need to do some magic to get into proper list\n # RE Magic here\n replacements = {\"[\": \"\", \"]\": \"\", \"'\": \"\", \" \": \"\"}\n replacements = dict((re.escape(k), v) for k, v in replacements.items())\n pattern = re.compile(\"|\".join(replacements.keys()))\n str_key_list = pattern.sub(lambda m: replacements[re.escape(m.group(0))],\n key_list)\n key_list = str_key_list.split(\",\")\n\n for file_name in key_list:\n logger.debug(\n \"Creating Makefile command for {0} to build ASM files\".format(\n file_name))\n run_commands.append('make -f {0} {1}'.format(\n make_file, file_name))\n return run_commands\n\n\ndef idfnc(val):\n return val\n\n\ndef pytest_generate_tests(metafunc):\n\n if 'test_input' in metafunc.fixturenames:\n logger.debug('Generating commands from pytest_framework')\n test_list = compile_cmd_list(\n # metafunc.config.getoption(\"output_dir\"),\n metafunc.config.getoption(\"make_file\"),\n metafunc.config.getoption(\"work_dir\"),\n metafunc.config.getoption(\"key_list\"))\n metafunc.parametrize('test_input', test_list, ids=idfnc, indirect=True)\n\n\n@pytest.fixture\ndef test_input(request):\n # compile tests\n logger.debug('Generating commands from test_input fixture')\n program = request.param\n stage = program.split()[-1]\n (ret, out, err) = sys_command(program, timeout=5000)\n return ret, err, stage\n\ndef test_eval(test_input):\n assert test_input[\n 0] == 0, \"Tests failed because of {0} at {1} stage\".format(\n test_input[1], test_input[2])\n\n","sub_path":"dut_plugins/chromite_questa_plugin/gen_framework.py","file_name":"gen_framework.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"171742414","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom sqlalchemy import create_engine, Table, MetaData\nfrom sqlalchemy.sql import select\n\neng = create_engine(\"mysql+pymysql://root:123456@localhost/test0\")\n\n\ndef to_sql(stm):\n return ''.join(str(stm.compile(compile_kwargs={\"literal_binds\": True})).split('\\n'))\n\n\nwith eng.connect() as con:\n meta = MetaData(eng)\n cars = Table('Cars', meta, autoload=True)\n\n stm = select([cars.c.Name, cars.c.Price]).limit(3)\n print('----')\n print(to_sql(stm))\n print('----')\n rs = con.execute(stm)\n\n print(rs.fetchall())\n","sub_path":"sqlalchemy/exp_select_limit.py","file_name":"exp_select_limit.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"630759210","text":"\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport time\nimport IPython.display as display\nimport sys\nimport numpy as np\nimport torch.nn as nn\nimport collections\nimport torch.nn.init as init\n\n'''画图'''\ndef use_svg_display():\n '''用矢量图显示'''\n display.set_matplotlib_formats('svg')\n\n\ndef set_figsize(figsize=(3.5, 2.5)):\n '''设置图的尺寸'''\n # 用矢量图显示\n use_svg_display()\n # 设置尺寸\n plt.rcParams['figure.figsize'] = figsize\n\n\ndef semilogy(x_vals, y_vals, x_label, y_label, x2_vals=None, y2_vals=None, legend=None, figsize=(3.5, 2.5)):\n '''作图函数'''\n set_figsize(figsize)\n plt.xlabel(x_label)\n plt.ylabel(y_label)\n plt.semilogy(x_vals, y_vals)\n if x2_vals and y2_vals:\n plt.semilogy(x2_vals, y2_vals, linestyle=':')\n plt.legend(legend)\n plt.show()\n\n'''1.生成数据集'''\n# 训练集数量,测试集\nn_train, n_test, num_inputs = 20, 100, 200\n# 真实权重,偏置 \ntrue_w, true_b = torch.ones(num_inputs, 1) * 0.01, 0.05\n# 特征向量\nfeatures = torch.randn((n_train + n_test, num_inputs))\n# 标签\nlabels = torch.matmul(features, true_w) + true_b\n# 带噪声的标签\nlabels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)\n# 训练集,测试集特征向量\ntrain_features, test_features = features[:n_train, :], features[n_train:, :]\n# 训练集,测试集标签\ntrain_labels, test_labels = labels[:n_train], labels[n_train:]\n\n'''2.定义损失函数(均方误差损失)'''\ndef squared_loss(y_hat, y):\n return (y_hat - y.view(y_hat.shape)) ** 2 / 2\n\n'''3.定义训练和测试'''\n# 批大小,训练轮数,学习率\nbatch_size, num_epochs, lr = 1, 100, 0.003\n# 数据集\ndataset = torch.utils.data.TensorDataset(train_features, train_labels)\n# 训练集迭代器\ntrain_iter = torch.utils.data.DataLoader(dataset, batch_size, shuffle=True)\n# 损失函数\nloss = squared_loss\n\ndef fit_and_plot_pytorch(wd):\n # 对权重参数衰减。权重名称一般是以weight结尾\n # 网络结构\n net = nn.Linear(num_inputs, 1)\n # 参数初始化\n nn.init.normal_(net.weight, mean=0, std=1)\n nn.init.normal_(net.bias, mean=0, std=1)\n # 权重参数优化算法(weight_decay权重衰减)\n optimizer_w = torch.optim.SGD(params=[net.weight], lr=lr, weight_decay=wd)\n # 偏置优化算法(不对偏置衰减)\n optimizer_b = torch.optim.SGD(params=[net.bias], lr=lr) \n\n # 训练集损失,测试集损失\n train_ls, test_ls = [], []\n for epoch in range(num_epochs):\n for X, y in train_iter:\n # bacth内的平均损失\n l = loss(net(X), y).mean()\n # 参数的梯度清零\n optimizer_w.zero_grad()\n optimizer_b.zero_grad()\n # 反向传播计算梯度\n l.backward()\n # 梯度下降更新参数对两个optimizer实例分别调用step函数,从而分别更新权重和偏差\n optimizer_w.step()\n optimizer_b.step()\n # 训练集平均损失\n train_ls.append(loss(net(train_features), train_labels).mean().item())\n # 测试集平均损失\n test_ls.append(loss(net(test_features), test_labels).mean().item())\n # 画图\n semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'loss',\n range(1, num_epochs + 1), test_ls, ['train', 'test'])\n print('L2 norm of w:', net.weight.data.norm().item())\n\n# 过拟合\nfit_and_plot_pytorch(0)\n# 权重衰减防止过拟合\nfit_and_plot_pytorch(3)","sub_path":"深度学习/动手学深度学习/3.深度学习基础/3.12_2.py","file_name":"3.12_2.py","file_ext":"py","file_size_in_byte":3585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"588083201","text":"import numpy as np\nimport cv2\nimport imutils\n\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\n\ndef invert_img(img):\n img = (255-img)\n return img\n\ndef canny(imgray):\n imgray = cv2.GaussianBlur(imgray, (5,5), 200)\n canny_low = 5\n canny_high = 150\n\n thresh = cv2.Canny(imgray,canny_low,canny_high)\n return thresh\n\ndef filtering(imgray):\n thresh = canny(imgray)\n\n minLineLength = 1\n maxLineGap = 1\n\n\n lines = cv2.HoughLines(thresh,1,np.pi/180,0)\n #lines = cv2.HoughLinesP(thresh,2,np.pi/180,100,minLineLength,maxLineGap)\n # print lines.shape\n\n # Code for HoughLinesP\n '''\n for i in range(0,lines.shape[0]):\n for x1,y1,x2,y2 in lines[i]:\n cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)\n '''\n\n # Code for HoughLines\n\n for i in range(0,5):\n for rho,theta in lines[i]:\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a*rho\n y0 = b*rho\n x1 = int(x0 + 1000*(-b))\n y1 = int(y0 + 1000*(a))\n x2 = int(x0 - 1000*(-b))\n y2 = int(y0 - 1000*(a))\n\n cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)\n\n\n return thresh\n\n\nimg = cv2.imread('screenshots/01.png')\n\n\nimgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nimg = imutils.resize(img, height = 500)\nimgray = imutils.resize(imgray, height = 500)\n\nthresh = filtering(imgray)\n\ncv2.imshow('original', img)\ncv2.imshow('result', thresh)\ncv2.waitKey(0)","sub_path":"experiments/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"165550622","text":"import numpy as np\nimport pyroomacoustics as pa\nimport wave\nimport scipy.signal as sp\nimport matplotlib.pyplot as plt\n\ndef calculate_steering_vector(mic_alignments,source_locations,freqs,sound_speed=340,is_use_far=False):\n #マイク数を取得\n n_channels=np.shape(mic_alignments)[1]\n\n #音源数を取得\n n_source=np.shape(source_locations)[1]\n\n if is_use_far==True:\n #音源位置を正規化\n norm_source_locations=source_locations/np.linalg.norm(source_locations,2,axis=0,keepdims=True)\n\n #位相を求める\n steering_phase=np.einsum('k,ism,ism->ksm',2.j*np.pi/sound_speed*freqs,norm_source_locations[...,None],mic_alignments[:,None,:])\n\n #ステアリングベクトルを算出\n steering_vector=1./np.sqrt(n_channels)*np.exp(steering_phase)\n\n return(steering_vector)\n\n else:\n\n #音源とマイクの距離を求める\n #distance: Ns x Nm\n distance=np.sqrt(np.sum(np.square(source_locations[...,None]-mic_alignments[:,None,:]),axis=0))\n\n #遅延時間(delay) [sec]\n delay=distance/sound_speed\n\n #ステアリングベクトルの位相を求める\n steering_phase=np.einsum('k,sm->ksm',-2.j*np.pi*freqs,delay)\n \n #音量の減衰\n steering_decay_ratio=1./distance\n\n #ステアリングベクトルを求める\n steering_vector=steering_decay_ratio[None,...]*np.exp(steering_phase)\n\n #大きさを1で正規化する\n steering_vector=steering_vector/np.linalg.norm(steering_vector,2,axis=2,keepdims=True)\n\n return(steering_vector)\n\ndef write_file_from_time_signal(signal,file_name,sample_rate):\n #2バイトのデータに変換\n signal=signal.astype(np.int16)\n\n #waveファイルに書き込む\n wave_out = wave.open(file_name, 'w')\n\n #モノラル:1、ステレオ:2\n wave_out.setnchannels(1)\n\n #サンプルサイズ2byte\n wave_out.setsampwidth(2)\n\n #サンプリング周波数\n wave_out.setframerate(sample_rate)\n\n #データを書き込み\n wave_out.writeframes(signal)\n\n #ファイルを閉じる\n wave_out.close()\n\n# np.random.seed(0)\n# # clean_wave_files = [\"../CMU_ARCTIC/cmu_us_aew_arctic/wav/arctic_a0001.wav\"]\n# clean_wave_files = [\"../CMU_ARCTIC/cmu_us_aew_arctic/wav/arctic_a0001.wav\", \"../CMU_ARCTIC/cmu_us_axb_arctic/wav/arctic_a0002.wav\"]\n# n_sources = len(clean_wave_files)\n# n_samples = 0\n# for clean_wave_file in clean_wave_files:\n# wav = wave.open(clean_wave_file)\n# if n_samples < wav.getnframes():\n# n_samples = wav.getnframes()\n# wav.close()\n# clean_data = np.zeros([n_sources, n_samples])\n# s = 0\n# for clean_wave_file in clean_wave_files:\n# wav = wave.open(clean_wave_file)\n# data = wav.readframes(wav.getnframes())\n# data = np.frombuffer(data, dtype=np.int16)\n# data = data / np.iinfo(np.int16).max\n# clean_data[s, :wav.getnframes()] = data\n# wav.close()\n# s = s + 1\n# sample_rate = 16000\n# N = 1024\n# Nk = N / 2 + 1\n# freqs = np.arange(0, Nk, 1) * sample_rate / N\n# # SNR = 20.\n# SNR = 90.\n# room_dim = np.r_[10.0, 10.0, 10.0]\n# mic_array_loc = room_dim / 2 + np.random.randn(3) * 0.1\n# # mic_alignments = np.array(\n# # [[-0.01, 0.0, 0.0],\n# # [ 0.01, 0.0, 0.0]]\n# # )\n# mic_alignments = np.array(\n# [[x, 0.0, 0.0] for x in np.arange(-0.31, 0.32, 0.02)]\n# )\n# n_channels = np.shape(mic_alignments)[0]\n# R = mic_alignments.T + mic_array_loc[:, None]\n# room = pa.ShoeBox(room_dim, fs=sample_rate, max_order=0)\n# room.add_microphone_array(pa.MicrophoneArray(R, fs=room.fs))\n# # doas = np.array([[np.pi / 2., 0.]])\n# doas = np.array([[np.pi / 2., 0.],\n# [np.pi / 2., np.pi / 2.]])\n# distance = 1.\n# source_locations = np.zeros((3, doas.shape[0]), dtype=doas.dtype)\n# source_locations[0, :] = np.cos(doas[:, 1]) * np.sin(doas[:, 0])\n# source_locations[1, :] = np.sin(doas[:, 1]) * np.sin(doas[:, 0])\n# source_locations[2, :] = np.cos(doas[:, 0])\n# source_locations *= distance\n# source_locations += mic_array_loc[:, None]\n# print(np.shape(clean_data))\n# for s in range(n_sources):\n# clean_data[s] /= np.std(clean_data[s])\n# room.add_source(source_locations[:, s], signal=clean_data[s])\n# room.simulate(snr=SNR)\n# multi_conv_data = room.mic_array.signals\n# write_file_from_time_signal(multi_conv_data[0] * np.iinfo(np.int16).max / 20.,\n# \"./results/mix_in_2spk.wav\", sample_rate)\n# # near_steering_vectors = calculate_steering_vector(R, source_locations, freqs, is_use_far=False)\n# near_steering_vectors = calculate_steering_vector(R, source_locations[:,:1], freqs, is_use_far=False)\n# f, t, stft_data = sp.stft(multi_conv_data, fs=sample_rate, window=\"hann\", nperseg=N)\n# s_hat = np.einsum(\"ksm,mkt->skt\", np.conjugate(near_steering_vectors), stft_data)\n# c_hat = np.einsum(\"skt,ksm->mskt\", s_hat, near_steering_vectors)\n# t, ds_out = sp.istft(c_hat[0], fs=sample_rate, window=\"hann\", nperseg=N)\n# ds_out = ds_out * np.iinfo(np.int16).max / 20.\n# write_file_from_time_signal(ds_out, \"./results/ds_out_2spk.wav\", sample_rate)\n\nsample_rate = 16000\nN = 1024\nNk = N / 2 + 1\nfreqs = np.arange(0, Nk, 1) * sample_rate / N\n# mic_alignments = np.array([[x, 0.0, 0.0] for x in np.arange(-0.01, 0.02, 0.02)])\nmic_alignments = np.array([[x, 0.0, 0.0] for x in np.arange(-0.31, 0.32, 0.02)])\nn_channels = np.shape(mic_alignments)[0]\ndoas = np.array([[np.pi / 2., theta] for theta in np.arange(-np.pi, np.pi, 1. / 180. * np.pi)])\ndistance = 1.\nsource_locations = np.zeros((3, doas.shape[0]), dtype=doas.dtype)\nsource_locations[0, :] = np.cos(doas[:, 1]) * np.sin(doas[:, 0])\nsource_locations[1, :] = np.sin(doas[:, 1]) * np.sin(doas[:, 0])\nsource_locations[2, :] = np.cos(doas[:, 0])\nsource_locations *= distance\nnear_steering_vectors = calculate_steering_vector(mic_alignments.T, source_locations, freqs, is_use_far=False)\ndesired_index = np.argmin(np.abs(doas[:,1]), axis=0)\ndesired_steering_vector = near_steering_vectors[:, desired_index, :]\ndirectivity_pattern = np.square(np.abs(np.einsum(\"km,ksm->ks\", np.conjugate(desired_steering_vector), near_steering_vectors)))\nplt.style.use(\"grayscale\")\nfig = plt.figure(figsize=(7,7))\nax = plt.subplot(111, projection=\"polar\")\nax.set_theta_zero_location('N')\nax.set_theta_direction(\"clockwise\")\nax.grid(True, linestyle=\"--\")\nax.yaxis.labelpad = -250\nylabel = plt.ylabel(\"Responce [dB]\")\nylabel.set_position((0, 0.6))\nylabel.set_rotation(0)\nplt.yticks([-20, -10, 0])\nplt.ylim([-30, 0])\nplt.xlabel(\"Azimuth [degrees]\")\ndraw_freqs = np.array([1000, 2000, 3000, 4000])\ndraw_freq_list = np.argmin(np.abs(freqs[:, None] - draw_freqs[None, :]), axis=0)\nfor draw_freq_index in draw_freq_list:\n plt.plot(doas[:,1], 10. * np.log10(directivity_pattern[draw_freq_index, :]), lw=3, label=f\"{freqs[draw_freq_index]} [Hz]\")\nplt.legend(loc=(0.2, 0.6))\nplt.show()","sub_path":"section6/subsec4.py","file_name":"subsec4.py","file_ext":"py","file_size_in_byte":6835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"189321674","text":"from MountainRed.dbsm import DataBasesWriter, logger\n\n\nclass Writer(DataBasesWriter):\n\n def is_options_legal(self) -> bool:\n \"\"\"\n sqlite 必须的字段有:\n engine, name\n \"\"\"\n KEYS = {\"ENGINE\", \"NAME\"}\n keys = self.options.keys()\n diff = KEYS.difference(set(keys))\n if diff:\n logger.warn(\"%s 下缺少关键配置! %s\" % (self.name, str(diff)))\n return False\n else:\n diff = set(keys).difference(KEYS)\n if diff:\n logger.warn(\"%s 下发现无效的多余参数! %s\" % (self.name, str(diff)))\n return True\n","sub_path":"MountainRed/dbsm/writers/sqlite.py","file_name":"sqlite.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"633394877","text":"# > INITIALIZATION\n\nimport re\nimport gc\nimport numpy as np\nimport pandas as pd\nimport pickle\n\nfrom sklearn.metrics import f1_score\nfrom sklearn.model_selection import train_test_split\nfrom pandas import read_csv\nfrom gensim.models import KeyedVectors\n\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D\nfrom keras.layers import Bidirectional, GlobalMaxPool1D, GlobalMaxPooling1D, GlobalAveragePooling1D\nfrom keras.layers import Input, Embedding, Dense, Conv2D, MaxPool2D, concatenate\nfrom keras.layers import Reshape, Flatten, Concatenate, Dropout, SpatialDropout1D\nfrom keras.optimizers import Adam\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.engine.topology import Layer\nfrom keras import initializers, regularizers, constraints, optimizers, layers\n\n# >> constant values to change\n\nMAX_FEATURES = 50000\nMAX_SENTENCE_LEN = 150\n\n# >> imports\n\n\n# >> constant values NOT to change\n\nEMBEDDING_FILE_GLOVE = '../input/embeddings/glove.840B.300d/glove.840B.300d.txt'\nEMBEDDING_FILE_GOOGLE = '../input/embeddings/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin'\nEMBEDDING_FILE_PARAGRAM = '../input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'\nEMBEDDING_FILE_WIKI = '../input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec'\nTOKEN_FILTERS = '!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~'\nEMBED_SIZE = 300\n\nMISSPELLED_WORDS = {'colour': 'color',\n 'centre': 'center',\n 'favourite': 'favorite',\n 'travelling': 'traveling',\n 'counselling': 'counseling',\n 'theatre': 'theater',\n 'cancelled': 'canceled',\n 'labour': 'labor',\n 'organisation': 'organization',\n 'wwii': 'world war 2',\n 'citicise': 'criticize',\n 'youtu': 'youtube',\n 'youtubebe': 'youtube',\n 'Qoura': 'Quora',\n 'sallary': 'salary',\n 'Whta': 'What',\n 'narcisist': 'narcissist',\n 'howdo': 'how do',\n 'whatare': 'what are',\n 'howcan': 'how can',\n 'howmuch': 'how much',\n 'howmany': 'how many',\n 'whydo': 'why do',\n 'doI': 'do I',\n 'theBest': 'the best',\n 'howdoes': 'how does',\n 'mastrubation': 'masturbation',\n 'mastrubate': 'masturbate',\n \"mastrubating\": 'masturbating',\n 'pennis': 'penis',\n 'Etherium': 'Ethereum',\n 'narcissit': 'narcissist',\n 'bigdata': 'big data',\n '2k17': '2017', '2k18': '2018',\n 'qouta': 'quota',\n 'exboyfriend': 'ex boyfriend',\n 'airhostess': 'air hostess',\n \"whst\": 'what',\n 'watsapp': 'whatsapp',\n 'demonitisation': 'demonetization',\n 'demonitization': 'demonetization',\n 'Demonetization': 'demonetization',\n 'demonetisation': 'demonetization',\n 'Quorans': 'users',\n 'quorans': 'users',\n 'Pokémon': 'Pokemon',\n 'pokémon': 'pokemon'}\n\nPUNCT = \"/-'?!.,#$%\\'()*+-/:;<=>@[\\\\]^_`{|}~\" + '\"\"“”’' + '∞θ÷α•à−β∅³π‘₹´°£€\\×™√²—–&'\nPUNCT_MAPPING = {\"‘\": \"'\", \"₹\": \"e\", \"´\": \"'\", \"°\": \"\",\n \"€\": \"e\", \"™\": \"tm\", \"√\": \" sqrt \",\n \"×\": \"x\", \"²\": \"2\", \"—\": \"-\", \"–\": \"-\",\n \"’\": \"'\", \"_\": \"-\", \"`\": \"'\", '“': '\"',\n '”': '\"', '“': '\"', \"£\": \"e\", '∞': 'infinity',\n 'θ': 'theta', '÷': '/',\n 'α': 'alpha', '•': '.', 'à': 'a',\n '−': '-', 'β': 'beta', '∅': '', '³': '3', 'π': 'pi'}\n\n\n# >> FUNCTION DEFINITION\n\ndef clean_numbers(sentence):\n return (re.sub(r\"\\d{2,}(\\.[0-9]+)*\",\n lambda x: len(x.group()) * \"#\",\n sentence))\n\n\ndef correct_spelling(text, dic):\n for word in dic.keys():\n text = text.replace(word, dic[word])\n\n return text\n\n\ndef clean_special_chars(text, punct, mapping):\n for p in mapping:\n text = text.replace(p, mapping[p])\n\n for p in punct:\n text = text.replace(p, f' {p} ')\n\n specials = {'\\u200b': ' ', '…': ' ... ',\n '\\ufeff': '', 'करना': '', 'है': ''}\n for s in specials:\n text = text.replace(s, specials[s])\n\n return text\n\n\ndef clean_corpus(corpus, to_lower=True):\n corpus = [correct_spelling(sentence, MISSPELLED_WORDS) for sentence in corpus]\n\n corpus = [clean_special_chars(sentence, PUNCT, PUNCT_MAPPING) for sentence in corpus]\n\n corpus = [clean_numbers(sentence) for sentence in corpus]\n\n if (to_lower):\n corpus = [sentence.lower() for sentence in corpus]\n\n return (corpus)\n\n\ndef fit_tokenizer(corpus, max_features=None, add_filters=None):\n # set tokenizer filters\n filtersForTokenizer = TOKEN_FILTERS\n if add_filters is not None:\n filtersForTokenizer = filtersForTokenizer + add_filters\n\n # tokenize the sentences\n if max_features is not None:\n tokenizer = Tokenizer(num_words=max_features,\n filters=filtersForTokenizer)\n else:\n tokenizer = Tokenizer(filters=filtersForTokenizer)\n\n tokenizer.fit_on_texts(corpus)\n\n return (tokenizer)\n\n\ndef create_word_matrix(tokenizer, corpus, maxlen):\n tokenizedCorpus = pad_sequences(tokenizer.texts_to_sequences(corpus),\n maxlen=maxlen)\n return (tokenizedCorpus)\n\n\ndef load_glove(tokenizer, embedding_file):\n # load whole embedding file\n\n def get_coefs(word, *arr):\n return word, np.asarray(arr, dtype='float32')\n\n embeddingsIndex = dict(get_coefs(*o.split(\" \")) for o in open(embedding_file))\n\n wholeEmbedding = np.stack(list(embeddingsIndex.values()))\n embeddingMean, embeddingStd = wholeEmbedding.mean(), wholeEmbedding.std()\n embeddingSize = wholeEmbedding.shape[1]\n\n # create embedding matrix where oov words are\n # initialized to a random normal vector\n\n wordIndex = tokenizer.word_index\n numberOfWords = min(tokenizer.num_words, len(wordIndex))\n embeddingMatrix = np.random.normal(embeddingMean, embeddingStd,\n (numberOfWords, embeddingSize))\n for word, i in wordIndex.items():\n if i >= numberOfWords: continue\n embeddingVector = embeddingsIndex.get(word)\n if embeddingVector is not None:\n embeddingMatrix[i] = embeddingVector\n\n # finally get out-of-vocabulary words\n\n oov = {word: n for word, n in tokenizer.word_counts.items() if word not in embeddingsIndex.keys()}\n\n oovPercentSingleWord = len(oov) / len(wordIndex)\n oovPercentAll = sum(oov.values()) / sum(tokenizer.word_counts.values())\n\n oovToPrint = pd.DataFrame(sorted(oov.items(), key=lambda kv: kv[1],\n reverse=True)[0:14],\n columns=['Word', 'N'])\n\n printTemplate = \"\"\"\n \n GLOVE - Percentage of words not in embedding: {0:.2%} ({2:.2%} of vocabulary).\n {1}\n \n Shape of final embedding matrix: {3}\n \"\"\"\n print(printTemplate.format(oovPercentAll, oovToPrint,\n oovPercentSingleWord, embeddingMatrix.shape))\n\n return embeddingMatrix\n\n\ndef load_wiki(tokenizer, embedding_file):\n # load whole embedding file\n\n def get_coefs(word, *arr):\n return word, np.asarray(arr, dtype='float32')\n\n embeddingsIndex = dict(get_coefs(*o.split(\" \")) for o in open(embedding_file, encoding='latin')\n if len(o) > 100)\n\n wholeEmbedding = np.stack(list(embeddingsIndex.values()))\n embeddingMean, embeddingStd = wholeEmbedding.mean(), wholeEmbedding.std()\n embeddingSize = wholeEmbedding.shape[1]\n\n # create embedding matrix where oov words are\n # initialized to a random normal vector\n\n wordIndex = tokenizer.word_index\n numberOfWords = min(tokenizer.num_words, len(wordIndex))\n embeddingMatrix = np.random.normal(embeddingMean, embeddingStd,\n (numberOfWords, embeddingSize))\n\n for word, i in wordIndex.items():\n if i >= numberOfWords: continue\n embeddingVector = embeddingsIndex.get(word)\n if embeddingVector is not None:\n embeddingMatrix[i] = embeddingVector\n\n # finally get out-of-vocabulary words\n\n oov = {word: n for word, n in tokenizer.word_counts.items() if word not in embeddingsIndex.keys()}\n\n oovPercentSingleWord = len(oov) / len(wordIndex)\n oovPercentAll = sum(oov.values()) / sum(tokenizer.word_counts.values())\n\n oovToPrint = pd.DataFrame(sorted(oov.items(), key=lambda kv: kv[1],\n reverse=True)[0:14],\n columns=['Word', 'N'])\n\n printTemplate = \"\"\"\n \n WIKI - Percentage of words not in embedding: {0:.2%} ({2:.2%} of vocabulary).\n {1}\n \n Shape of final embedding matrix: {3}\n \"\"\"\n print(printTemplate.format(oovPercentAll, oovToPrint,\n oovPercentSingleWord, embeddingMatrix.shape))\n\n return embeddingMatrix\n\n\ndef load_paragram(tokenizer, embedding_file):\n # load whole embedding file\n\n def get_coefs(word, *arr):\n return word, np.asarray(arr, dtype='float32')\n\n embeddingsIndex = dict(get_coefs(*o.split(\" \")) for o in open(embedding_file, encoding='latin'))\n\n wholeEmbedding = np.stack(list(embeddingsIndex.values()))\n embeddingMean, embeddingStd = wholeEmbedding.mean(), wholeEmbedding.std()\n embeddingSize = wholeEmbedding.shape[1]\n\n # create embedding matrix where oov words are\n # initialized to a random normal vector\n\n wordIndex = tokenizer.word_index\n numberOfWords = min(tokenizer.num_words, len(wordIndex))\n embeddingMatrix = np.random.normal(embeddingMean, embeddingStd,\n (numberOfWords, embeddingSize))\n for word, i in wordIndex.items():\n if i >= numberOfWords: continue\n embeddingVector = embeddingsIndex.get(word)\n if embeddingVector is not None:\n embeddingMatrix[i] = embeddingVector\n\n # finally get out-of-vocabulary words\n\n oov = {word: n for word, n in tokenizer.word_counts.items() if word not in embeddingsIndex.keys()}\n\n oovPercentSingleWord = len(oov) / len(wordIndex)\n oovPercentAll = sum(oov.values()) / sum(tokenizer.word_counts.values())\n\n oovToPrint = pd.DataFrame(sorted(oov.items(), key=lambda kv: kv[1],\n reverse=True)[0:14],\n columns=['Word', 'N'])\n\n printTemplate = \"\"\"\n \n PARAGRAM - Percentage of words not in embedding: {0:.2%} ({2:.2%} of vocabulary).\n {1}\n \n Shape of final embedding matrix: {3}\n \"\"\"\n print(printTemplate.format(oovPercentAll, oovToPrint,\n oovPercentSingleWord, embeddingMatrix.shape))\n\n return embeddingMatrix\n\n\ndef load_google(tokenizer, embedding_file):\n # load whole embedding file\n\n embeddingsKVector = KeyedVectors.load_word2vec_format(embedding_file, binary=True)\n\n wholeEmbedding = embeddingsKVector.vectors\n embeddingMean, embeddingStd = wholeEmbedding.mean(), wholeEmbedding.std()\n embeddingSize = wholeEmbedding.shape[1]\n wholeEmbedding = None\n\n # create embedding matrix where oov words are\n # initialized to a random normal vector\n\n wordIndex = tokenizer.word_index\n numberOfWords = min(tokenizer.num_words, len(wordIndex))\n embeddingMatrix = np.random.normal(embeddingMean, embeddingStd,\n (numberOfWords, embeddingSize))\n embeddingWords = embeddingsKVector.vocab.keys()\n\n for word, i in wordIndex.items():\n if i >= numberOfWords: continue\n if word in embeddingWords:\n embeddingVector = embeddingsKVector.get_vector(word)\n else:\n embeddinVector = None\n if embeddingVector is not None:\n embeddingMatrix[i] = embeddingVector\n\n # finally get out-of-vocabulary words\n\n oov = {word: n for word, n in tokenizer.word_counts.items() if word not in embeddingWords}\n\n oovPercentSingleWord = len(oov) / len(wordIndex)\n oovPercentAll = sum(oov.values()) / sum(tokenizer.word_counts.values())\n\n oovToPrint = pd.DataFrame(sorted(oov.items(), key=lambda kv: kv[1],\n reverse=True)[0:14],\n columns=['Word', 'N'])\n\n printTemplate = \"\"\"\n \n GOOGLE - Percentage of words not in embedding: {0:.2%} ({2:.2%} of vocabulary).\n {1}\n \n Shape of final embedding matrix: {3}\n \"\"\"\n print(printTemplate.format(oovPercentAll, oovToPrint,\n oovPercentSingleWord, embeddingMatrix.shape))\n\n # clean RAM memory, just in case\n embeddingsKVector = None\n\n return embeddingMatrix\n\n\n# borrowed from:\n# https://www.kaggle.com/suicaokhoailang/lstm-attention-baseline-0-652-lb\nclass Attention(Layer):\n def __init__(self, step_dim,\n W_regularizer=None, b_regularizer=None,\n W_constraint=None, b_constraint=None,\n bias=True, **kwargs):\n self.supports_masking = True\n self.init = initializers.get('glorot_uniform')\n\n self.W_regularizer = regularizers.get(W_regularizer)\n self.b_regularizer = regularizers.get(b_regularizer)\n\n self.W_constraint = constraints.get(W_constraint)\n self.b_constraint = constraints.get(b_constraint)\n\n self.bias = bias\n self.step_dim = step_dim\n self.features_dim = 0\n super(Attention, self).__init__(**kwargs)\n\n def build(self, input_shape):\n assert len(input_shape) == 3\n\n self.W = self.add_weight((input_shape[-1],),\n initializer=self.init,\n name='{}_W'.format(self.name),\n regularizer=self.W_regularizer,\n constraint=self.W_constraint)\n self.features_dim = input_shape[-1]\n\n if self.bias:\n self.b = self.add_weight((input_shape[1],),\n initializer='zero',\n name='{}_b'.format(self.name),\n regularizer=self.b_regularizer,\n constraint=self.b_constraint)\n else:\n self.b = None\n\n self.built = True\n\n def compute_mask(self, input, input_mask=None):\n return None\n\n def call(self, x, mask=None):\n features_dim = self.features_dim\n step_dim = self.step_dim\n\n eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)),\n K.reshape(self.W, (features_dim, 1))), (-1, step_dim))\n\n if self.bias:\n eij += self.b\n\n eij = K.tanh(eij)\n\n a = K.exp(eij)\n\n if mask is not None:\n a *= K.cast(mask, K.floatx())\n\n a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())\n\n a = K.expand_dims(a)\n weighted_input = x * a\n return K.sum(weighted_input, axis=1)\n\n def compute_output_shape(self, input_shape):\n return input_shape[0], self.features_dim\n\n\ndef best_threshold(y_hat, y):\n # borrowed from: \n # www.kaggle.com/jannen/reaching-0-7-fork-from-bilstm-attention-kfold\n tmp = [0, 0, 0] # idx, cur, max\n delta = 0\n for tmp[0] in np.arange(0.1, 0.501, 0.01):\n tmp[1] = f1_score(y, (y_hat > tmp[0]).astype(int))\n if tmp[1] > tmp[2]:\n delta = tmp[0]\n tmp[2] = tmp[1]\n print('Best threshold is {:.4f} with F1 score: {:.4f}'.format(delta, tmp[2]))\n return delta, tmp[2]\n\n\ndef nn_fit_test(model, batch_size=512, epochs=2, cl_weight=None,\n datasets=None):\n # recover data\n train_X = datasets['train_X']\n train_y = datasets['train_y']\n val_X = datasets['val_X']\n val_y = datasets['val_y']\n test_X = datasets['test_X']\n\n # model fitting\n if cl_weight is None:\n model.fit(train_X, train_y, batch_size=batch_size, epochs=epochs,\n validation_data=(val_X, val_y))\n else:\n model.fit(train_X, train_y, batch_size=batch_size, epochs=epochs,\n validation_data=(val_X, val_y), class_weight=cl_weight)\n\n # apply model to training, validation and test\n train_y_hat = model.predict([train_X], batch_size=batch_size, verbose=1)\n val_y_hat = model.predict([val_X], batch_size=batch_size, verbose=1)\n test_y_hat = model.predict([test_X], batch_size=batch_size, verbose=1)\n\n # F1 score on validation\n bt, f1 = best_threshold(val_y_hat, val_y)\n\n return train_y_hat, val_y_hat, test_y_hat, bt, f1\n\n\ndef add_features(df0):\n\n df = df0.copy()\n df['question_text'] = df['question_text'].apply(lambda x: str(x))\n df['total_length'] = df['question_text'].apply(len)\n df['capitals'] = df['question_text'].apply(lambda comment: sum(1 for c in comment if c.isupper()))\n df['caps_vs_length'] = df.apply(lambda row: float(row['capitals']) / float(row['total_length']),\n axis=1)\n df['num_words'] = df.question_text.str.count('\\S+')\n df['num_unique_words'] = df['question_text'].apply(lambda comment: len(set(w for w in comment.split())))\n df['words_vs_unique'] = df['num_unique_words'] / df['num_words']\n\n return df\n\n\n# > LOAD DATA\n\ntrain_df = pd.read_csv(\"../input/train.csv\")\ntest_df = pd.read_csv(\"../input/test.csv\")\n\n\n# > TV SPLIT + DATA CLEANING\n\n# >> training / validation split\n\ntrain_df, val_df = train_test_split(train_df, test_size=0.15,\n random_state=2019)\n\n# >> extract corpus\n\ntrain_corpus = train_df['question_text']\nval_corpus = val_df['question_text']\ntest_corpus = test_df['question_text']\n\n# >> clean corpus\n\ntrain_corpus = clean_corpus(train_corpus)\nval_corpus = clean_corpus(val_corpus)\ntest_corpus = clean_corpus(test_corpus)\n\n# > TOKENIZE\n\n# >> fit tokenizer\n\ntrain_tokenizer = fit_tokenizer(train_corpus, max_features=MAX_FEATURES,\n add_filters=\"'’\")\n\n\n# > LOAD EMBEDDINGS\n\nembedding_glove_filtered = load_glove(train_tokenizer, EMBEDDING_FILE_GLOVE)\ngc.collect() # probably useless\nembedding_paragram_filtered = load_paragram(train_tokenizer, EMBEDDING_FILE_PARAGRAM)\ngc.collect()\nembedding_wiki_filtered = load_wiki(train_tokenizer, EMBEDDING_FILE_WIKI)\ngc.collect()\n\n\n# > FINAL STEPS BEFORE NN\n\n# >> apply tokenizer and create matrices\n\ntrain_nn_x = create_word_matrix(train_tokenizer,\n train_corpus, MAX_SENTENCE_LEN)\nval_nn_x = create_word_matrix(train_tokenizer,\n val_corpus, MAX_SENTENCE_LEN)\ntest_nn_x = create_word_matrix(train_tokenizer,\n test_corpus, MAX_SENTENCE_LEN)\n\n# >> extract target array\n\ntrain_nn_y = train_df['target']\nval_nn_y = val_df['target']\n\n\n# DATA IN & OUT (run just once!)\n\n# >> input data\n\ndata_4_nn = {'train_X': train_nn_x,\n 'train_y': train_nn_y,\n 'val_X': val_nn_x,\n 'val_y': val_nn_y,\n 'test_X': test_nn_x}\n\n# >> initialize results\n\nnn_fit_results = dict()\n\n\n# > MODEL FUNCTIONS\n\ndef model_lstm_attention(embedding_matrix, sentences_maxlen=MAX_SENTENCE_LEN,\n max_features=MAX_FEATURES, embedding_size=EMBED_SIZE):\n if max_features != embedding_matrix.shape[0]:\n max_features = embedding_matrix.shape[0]\n inp = Input(shape=(sentences_maxlen,))\n x = Embedding(max_features, embedding_size,\n weights=[embedding_matrix], trainable=False)(inp)\n x = Bidirectional(CuDNNLSTM(128, return_sequences=True))(x)\n x = Dropout(0.10)(x)\n x = Bidirectional(CuDNNLSTM(64, return_sequences=True))(x)\n x = Attention(sentences_maxlen)(x)\n x = Dense(64, activation=\"relu\")(x)\n x = Dropout(0.15)(x)\n x = Dense(1, activation=\"sigmoid\")(x)\n model = Model(inputs=inp, outputs=x)\n model.compile(loss='binary_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n\n return model\n\n\ndef model_gru_pooling(embedding_matrix, sentences_maxlen=MAX_SENTENCE_LEN,\n max_features=MAX_FEATURES, embedding_size=EMBED_SIZE):\n if max_features != embedding_matrix.shape[0]:\n max_features = embedding_matrix.shape[0] \n inp = Input(shape=(sentences_maxlen,))\n x = Embedding(max_features, embedding_size,\n weights=[embedding_matrix], trainable=False)(inp)\n x = Bidirectional(CuDNNGRU(64, return_sequences=True, stateful=False))(x)\n avg_pool = GlobalAveragePooling1D()(x)\n max_pool = GlobalMaxPooling1D()(x)\n conc = concatenate([avg_pool, max_pool])\n x = Dense(64, activation=\"relu\")(conc)\n x = Dropout(0.2)(x)\n x = Dense(32, activation=\"relu\")(x)\n x = Dropout(0.1)(x)\n x = Dense(1, activation=\"sigmoid\")(x)\n model = Model(inputs=inp, outputs=x)\n model.compile(loss='binary_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n\n return model\n\n\n# > NN PT.1: LSTM W/ATTENTION (ONE EMBEDDING AT A TIME)\n\n# Based on:\n# https://www.kaggle.com/shujian/mix-of-nn-models-based-on-meta-embedding\n\n# >> Glove only\n\nmod_lstmA_glove = model_lstm_attention(embedding_glove_filtered)\nprint(mod_lstmA_glove.summary())\n\nnn_fit_results['lstm a glove only'] = nn_fit_test(mod_lstmA_glove, epochs=3, datasets=data_4_nn)\n\n# >> Wiki only\n\nmod_lstmA_wiki = model_lstm_attention(embedding_wiki_filtered)\nprint(mod_lstmA_wiki.summary())\n\nnn_fit_results['lstm a wiki only'] = nn_fit_test(mod_lstmA_wiki, epochs=3, datasets=data_4_nn)\n\n# >> Paragram only\n\nmod_lstmA_paragram = model_lstm_attention(embedding_paragram_filtered)\nprint(mod_lstmA_paragram.summary())\n\nnn_fit_results['lstm a paragram only'] = nn_fit_test(mod_lstmA_paragram, epochs=3, datasets=data_4_nn)\n\n\n# # > NN PT.2: GRU W/POOLING\n# \n# # >> Glove only\n# \n# mod_gruP_glove = model_gru_pooling(embedding_glove_filtered)\n# print(mod_gruP_glove.summary())\n# \n# nn_fit_results['gru pool glove only'] = nn_fit_test(mod_gruP_glove, epochs=3, datasets=data_4_nn)\n# \n# # >> Wiki only\n# \n# mod_gruP_wiki = model_gru_pooling(embedding_wiki_filtered)\n# print(mod_gruP_wiki.summary())\n# \n# nn_fit_results['gru pool wiki only'] = nn_fit_test(mod_gruP_wiki, epochs=3, datasets=data_4_nn)\n# \n# # >> Paragram only\n# \n# mod_gruP_paragram = model_gru_pooling(embedding_paragram_filtered)\n# print(mod_gruP_paragram.summary())\n# \n# nn_fit_results['gru pool paragram only'] = nn_fit_test(mod_gruP_paragram, epochs=3, datasets=data_4_nn)\n# \n\n# > FINAL PREDICTION\n\n# >> assign probability with embeddings\n\n# train\ntrain_df['pr_lstma_glove'] = nn_fit_results['lstm a glove only'][0]\ntrain_df['pr_lstma_wiki'] = nn_fit_results['lstm a wiki only'][0]\ntrain_df['pr_lstma_paragram'] = nn_fit_results['lstm a paragram only'][0]\n#train_df['pr_grup_glove'] = nn_fit_results['gru pool glove only'][0]\n#train_df['pr_grup_wiki'] = nn_fit_results['gru pool wiki only'][0]\n#train_df['pr_grup_paragram'] = nn_fit_results['gru pool paragram only'][0]\n\n# validation\nval_df['pr_lstma_glove'] = nn_fit_results['lstm a glove only'][1]\nval_df['pr_lstma_wiki'] = nn_fit_results['lstm a wiki only'][1]\nval_df['pr_lstma_paragram'] = nn_fit_results['lstm a paragram only'][1]\n# val_df['pr_grup_glove'] = nn_fit_results['gru pool glove only'][1]\n# val_df['pr_grup_wiki'] = nn_fit_results['gru pool wiki only'][1]\n# val_df['pr_grup_paragram'] = nn_fit_results['gru pool paragram only'][1]\n\n# test\ntest_df['pr_lstma_glove'] = nn_fit_results['lstm a glove only'][2]\ntest_df['pr_lstma_wiki'] = nn_fit_results['lstm a wiki only'][2]\ntest_df['pr_lstma_paragram'] = nn_fit_results['lstm a paragram only'][2]\n# test_df['pr_grup_glove'] = nn_fit_results['gru pool glove only'][2]\n# test_df['pr_grup_wiki'] = nn_fit_results['gru pool wiki only'][2]\n# test_df['pr_grup_paragram'] = nn_fit_results['gru pool paragram only'][2]\n\n# >> final probability and threshold\n\npr_mean_val = (val_df['pr_lstma_glove'] + val_df['pr_lstma_paragram'] + \\\n val_df['pr_lstma_wiki']) / 3\n\nbt, f1 = best_threshold(pr_mean_val, val_nn_y)\n\n\n# > SAVE SUBMISSION\n\npr_mean_test = (test_df['pr_lstma_glove'] + test_df['pr_lstma_paragram'] + \\\n test_df['pr_lstma_wiki']) / 3\n\npred_test_y = (pr_mean_test>bt).astype(int)\nout_df = pd.DataFrame({\"qid\":test_df[\"qid\"].values})\nout_df['prediction'] = pred_test_y\nout_df.to_csv(\"submission.csv\", index=False)","sub_path":"Quora/prog/08_QUORA_finale.py","file_name":"08_QUORA_finale.py","file_ext":"py","file_size_in_byte":24975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"185331766","text":"from src.config import config\nfrom .tracestore import TraceStore\nfrom src.model import get_all_entities, get_all_ports, REAL, \\\n get_influences, get_transitions, get_entities, get_updates, get_actions, \\\n get_inputs, get_outputs, get_sources, get_locals\nfrom .transitiontime import TransitionTimeCalculator\nfrom .conditiontimedchangecalculator import ConditionTimedChangeCalculator\nfrom .to_z3 import to_python, evaluate_to_bool\nimport random\n\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass BaseSimulator(object):\n\n def __init__(self, entity, timeunit=REAL, plotter=config.default_plotter, default_to_integer_real=config.use_integer_and_real, record_traces=config.record_traces):\n self.entity = entity\n self.timeunit = timeunit\n self.plotter = plotter\n self.global_time = 0\n self.default_to_integer_real = default_to_integer_real\n self.traces = TraceStore()\n self.record_traces = record_traces\n\n # go ahead and save the values right away\n # FIXME: disabled for now, if we do this, then we should also do after stabilise\n # if self.record_traces:\n # self.trace_store.save_entity(self.entity)\n\n def plot(self, entity=None, **kwargs):\n \"\"\"\n List of plotter options:\n updates = True\n update_labels = False\n transitions = True\n transition_labels = False\n influence_labels = False\n interface_only = False\n no_behaviour = False\n show_update_ports = False\n color_updates : False\n \"\"\"\n if not entity:\n entity = self.entity\n if self.plotter:\n title = \"(t = %s)\" % self.global_time\n return self.plotter.plot(entity, name=title, **kwargs)\n else:\n logger.error(\"No plotter defined!!!\")\n\n \"\"\" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \"\"\"\n \"\"\" set values \"\"\"\n\n def set_values(self, port_value_map):\n print(\"xxx\")\n self._value_change(port_value_map)\n self._stabilise_fp(self.entity)\n\n def _value_change(self, port_value_map):\n for port, value in port_value_map.items():\n port.value = value\n\n \"\"\" stabilise \"\"\"\n\n def stabilise(self, entity=None):\n \"\"\"This one looks nicer in the API\"\"\"\n return self._stabilise_fp(entity)\n\n def _stabilise_fp(self, entity=None):\n if entity is None:\n entity = self.entity\n\n logger.debug(f\"stabilise FP for entity {entity._name} ({entity.__class__.__name__})\")\n stabilise_changes = self._stabilise(entity)\n if stabilise_changes:\n self._stabilise_fp(entity)\n\n return stabilise_changes\n\n def _stabilise(self, entity):\n logger.debug(f\"stabilise entity {entity._name} ({entity.__class__.__name__})\")\n influence_changes = self.influence_fp(entity)\n transition_changes = self.transition(entity)\n update_changes = self.update(entity, 0)\n\n # return if there were changes\n logger.debug(\"stabilise: (influence_changes: %s), (transition_changes: %s), (update_changes: %s)\", influence_changes, transition_changes, update_changes)\n return influence_changes or transition_changes or update_changes\n\n \"\"\" influence \"\"\"\n\n def influence_fp(self, entity):\n logger.debug(\"influence fp in entity %s (%s)\", entity._name, entity.__class__.__name__)\n\n influence_changes = self.influence(entity)\n if influence_changes:\n self.influence_fp(entity)\n\n return influence_changes\n\n def influence(self, entity):\n logger.debug(f\"influence in entity {entity._name} ({entity.__class__.__name__})\")\n changes = self.propagate_influences(entity)\n subchanges = self.stabilize_children(entity)\n # return if something changed\n return changes or subchanges\n\n def propagate_influences(self, entity):\n logger.debug(f\"propagate_influences in entity {entity._name} ({entity.__class__.__name__})\")\n changes = {}\n for inf in get_influences(entity):\n inf_func_value = self._get_influence_function_value(inf)\n if not bool(inf_func_value == inf.target.value):\n changes[inf.target] = inf_func_value\n\n # this actually executes the change of values\n for port, new_value in changes.items():\n logger.debug(f\"influence change in entity {entity._name} ({entity.__class__.__name__}): new value for port <<{port._name}>> is {new_value} (from: {port.value})\")\n self._value_change(changes)\n return len(changes) > 0\n\n def stabilize_children(self, entity):\n logger.debug(f\"stabilize_children in entity {entity._name} ({entity.__class__.__name__})\")\n subchanges = []\n for subentity in get_entities(entity):\n sub_changed = self._stabilise_fp(subentity)\n subchanges.append(sub_changed)\n return any(subchanges)\n\n def _get_influence_function_value(self, influence):\n return influence.get_function_value()\n\n def transition(self, entity):\n logger.debug(\"transitions in entity %s (%s)\", entity._name, entity.__class__.__name__)\n transitions_from_current_state = [t for t in get_transitions(entity) if t.source == entity.current]\n enabled_transitions = [t for t in transitions_from_current_state if self._get_transition_guard_value(t)]\n\n transition = None\n if len(enabled_transitions) >= 1:\n transition = random.choice(enabled_transitions)\n entity.current = transition.target\n logger.info(f\"Time: {self.global_time} | Firing transition <<{transition._name}>> in {entity._name} ({entity.__class__.__name__}) : {transition.source._name} -> {transition.target._name} | current global time: {self.global_time}\")\n\n transition_updates = [up for up in get_updates(transition._parent) if up.state == transition] # FIXME: until we completely switched to only allowing actions...\n actions = [a for a in get_actions(transition._parent) if a.transition == transition]\n for act in actions + transition_updates:\n logger.debug(f\"Triggering action {act._name} in entity {entity._name} ({entity.__class__.__name__})\")\n newval = self._get_action_function_value(act)\n if newval != act.target.value:\n logger.info(f\"Port value changed: {act.target._name} ({act.target._parent._name}) {act.target.value} -> {newval}\")\n act.target.value = newval\n\n # return if a transition was fired\n return (transition is not None)\n\n def _get_transition_guard_value(self, transition):\n value = transition.guard(transition._parent)\n logger.debug(f\"Transition {transition._name} in entity {transition._parent._name} ({transition._parent.__class__.__name__}) is enabled? {value}\")\n return value\n\n \"\"\" UPDATES \"\"\"\n\n def update_system(self, entity, time):\n logger.info(f\"{entity._name} ({entity.__class__.__name__}) with dt of {time}\")\n original_port_values = {t: t.value for t in get_all_ports(entity)}\n original_states = {e: (e.current if hasattr(e, \"current\") else None) for e in get_all_entities(entity)}\n\n # backup subentity-inputs' and outputs' pre values\n for sub in get_entities(entity):\n for _in in get_inputs(sub):\n _in.pre = _in.value\n for _out in get_outputs(sub):\n _out.pre = _out.value\n # and local pre values\n for local in get_locals(entity):\n local.pre = local.value\n\n self._update_fp(entity, time, original_states, original_port_values, first=True)\n\n # we return whether the entity's outputs changed so we know whether the parent has to re-calculate the updates\n output_changed = [original_port_values[p] != p.value for p in get_outputs(entity)]\n logger.info(f\"finished {entity._name} ({entity.__class__.__name__}) with dt of {time}\")\n return any(output_changed)\n\n def _update_fp(self, entity, time, original_states, original_port_values, first=False):\n logger.debug(f\"entity <<{entity._name}>> ({entity.__class__.__name__})\")\n update_changes = self._update(entity, time, original_states, original_port_values, first)\n if update_changes:\n logger.debug(f\"entity <<{entity._name}>> ({entity.__class__.__name__}) recurse\")\n self._update_fp(entity, time, original_states, original_port_values, first=False)\n\n return update_changes # return whether there were changes means there were changes\n # TODO: improvement: we could test whether the iteration invalidated (reset) the previous changes to stop parent from iterating\n\n def _update(self, entity, time, original_states, original_port_values, first=False):\n logger.debug(f\"entity <<{entity._name}>> ({entity.__class__.__name__}) with dt of {time}\")\n\n # set pre's\n for port in get_sources(entity):\n port.pre = original_port_values[port]\n\n current_port_values = {t: t.value for t in get_all_ports(entity)}\n updates_from_current_state = [up for up in get_updates(entity) if up.state == entity.current]\n\n \"\"\" apply updates \"\"\"\n values_to_update = {}\n for update in updates_from_current_state:\n logger.debug(f\"Executing update <<{update._name}>> (target: {update.target._name}) in entity {entity._name} ({entity.__class__.__name__})\")\n update_func_value = self._calculate_update_value(entity, time, original_states, original_port_values, update)\n if not bool(current_port_values[update.target] == update_func_value): # this means something changed\n values_to_update[update.target] = update_func_value\n logger.debug(f\"Update <<{update._name}>> in entity {entity._name} ({entity.__class__.__name__}) TEMP changing value of port {update.target._name} (type: {update.target.resource.unit}) to {update_func_value} (from {current_port_values[update.target]}) | global time {self.global_time}\")\n self._value_change(values_to_update)\n self.propagate_influences(entity) # propagate through influences and to children\n\n logger.debug(f\"executing subentity updates\")\n subentity_changes = []\n for subentity in get_entities(entity):\n # only do it if the inputs values changed, otherwise we'll stay like this...\n # also do it if it's the first time we execute\n if first or any(i.value != current_port_values[i] for i in get_inputs(subentity)):\n logger.debug(f\"Applying update to subentity {subentity._name} ({subentity.__class__.__name__})\")\n self.reset_subentity(subentity, original_states, original_port_values) # resets all except inputs\n self.update_system(subentity, time)\n self.stabilise(subentity)\n sub_changes = [o.value != current_port_values[o] for o in get_outputs(subentity)]\n logger.debug(f\"Applying update to subentity {subentity._name} ({subentity.__class__.__name__}) changed values: {any(sub_changes)}\")\n subentity_changes.append(any(sub_changes))\n logger.debug(f\"Finished update of subentity {subentity._name} ({subentity.__class__.__name__})\")\n logger.debug(f\"finished executing subentity updates\")\n self.propagate_influences(entity) # forward all influences\n\n logger.debug(f\"finished entity <<{entity._name}>> ({entity.__class__.__name__}) with dt of {time}\")\n # either port values changed or subentity interfaces changed\n return len(values_to_update) > 0 or any(subentity_changes)\n\n def _calculate_update_value(self, entity, time, original_states, original_port_values, update):\n current_target_val = update.target.value\n update.target.value = original_port_values[update.target] # reset target value\n up_func_value = self._get_update_function_value(update, time) # calculate it again\n update.target.value = current_target_val\n # if not bool(up_func_value == current_target_val): # this means something changed !\n # # if we come here, then clearly the value changed through the second update, i.e. there is a dependency somewhere\n # logger.debug(f\"Update {update._name} entity {entity._name} ({entity.__class__.__name__}) SECONDARY changing value of port {update.target._name} (type: {update.target.resource.unit}) to {up_func_value} (from {current_target_val}) | global time {self.global_time}\")\n # return True # change!!\n #\n # return False # no change\n return up_func_value\n\n def update(self, entity, time):\n time = to_python(time) # assert it's a python number\n logger.info(f\"entity <<{entity._name}>> ({entity.__class__.__name__}) dt = {time}\")\n\n for _in in get_inputs(entity):\n _in.pre = _in.value\n for _out in get_outputs(entity):\n _out.pre = _out.value\n\n before = {port: port.value for port in get_all_ports(entity)}\n retval = self.update_system(entity, time)\n logger.info(f\"finished entity <<{entity._name}>> ({entity.__class__.__name__}) dt = {time}\")\n for port in get_all_ports(entity):\n if port.value != before[port]:\n logger.info(f\"The following port value changed: {port._name} ({port._parent._name}) {before[port]} -> {port.value}\")\n return retval\n\n # updates_from_current_state = [up for up in get_updates(entity) if up.state == entity.current]\n #\n # original_port_values = {t: t.value for t in get_all_ports(entity)}\n # original_states = {e: e.current for e in get_all_entities(entity)}\n #\n # values_after_update = {}\n # for update in updates_from_current_state:\n # update_func_value = self._get_update_function_value(update, time)\n # values_after_update[update.target] = update_func_value\n # if not bool(original_port_values[update.target] == update_func_value):\n # logger.debug(f\"Update <<{update._name}>> in entity {entity._name} ({entity.__class__.__name__}) TEMP changing value of port {update.target._name} (type: {update.target.resource.unit}) to {update_func_value} (from {original_target_values[update.target]}) | global time {self.global_time}\")\n # # changes = True\n # self._value_change(values_after_update)\n # self.influence_fp(entity) # propagate through influences and to children\n #\n # subentity_inputs_before_update = {}\n # for sub in get_entities(entity):\n # self.update(sub, time)\n #\n # secondary_changes = True\n # while secondary_changes:\n # \"\"\" Check if the update effects are final \"\"\"\n # secondary_changes = False # reset the repetition flag\n # secondary_changes_to_values_after_update = {}\n # for secondary_update in updates_from_current_state:\n # # reset value, to make sure those self-referencing counters are still possible and not giving infinite loops\n # secondary_update.target.value = original_port_values[secondary_update.target]\n # up_func_value = self._get_update_function_value(secondary_update, time)\n # secondary_update.target.value = values_after_update[secondary_update.target] # we did this reset only for the calculation\n # if not bool(up_func_value == values_after_update[secondary_update.target]):\n # # if we come here, then clearly the value changed through the second update, i.e. there is a dependency somewhere\n # logger.debug(f\"Update {secondary_update._name} entity {entity._name} ({entity.__class__.__name__}) SECONDARY changing value of port {secondary_update.target._name} (type: {secondary_update.target.resource.unit}) to {up_func_value} (from {values_after_update[secondary_update.target]}) | global time {self.global_time}\")\n # logger.debug(f\"up_func_value: {up_func_value} --- values_after_update: {values_after_update[secondary_update.target]}\")\n # secondary_changes = True\n # secondary_changes_to_values_after_update[secondary_update.target] = up_func_value\n # values_after_update[secondary_update.target] = up_func_value\n # self._value_change(secondary_changes_to_values_after_update)\n # self.influence_fp(entity)\n #\n # \"\"\" Check if the subentities need re-calculation \"\"\"\n # for subentity in get_entities(entity):\n # for input_port in get_inputs(subentity):\n # if not bool(input_port.value == values_after_update[update.target]):\n # # If one of the input values changed, we need to re-calculate\n # self.reset(subentity, original_states, original_port_values)\n # self.update(subentity, time) # retry update\n # break # we reset, that's enough for now\n #\n # \"\"\" Report if there were changes \"\"\"\n # changes = False\n # for port in get_all_ports(entity):\n # if not bool(port.value == original_port_values[port]):\n # logger.info(f\"Updates in entity {entity._name} ({entity.__class__.__name__}) changed value of port {port._name} (type: {port.resource.unit}) to {port.value} (from {original_port_values[port]}) | global time {self.global_time}\")\n # changes = True\n #\n # for ent in get_all_entities(entity):\n # if ent.current == original_states[ent]:\n # logger.info(f\"Updates in entity {entity._name} ({entity.__class__.__name__}) changed state of entity {ent._name} to {ent.current._name} (from {original_states[ent]._name}) | global time {self.global_time}\")\n # changes = True\n #\n # stabilisation_changes = self.stabilise(entity) # TODO: not sure if this is necessary, think about it\n #\n # return changes or stabilisation_changes\n\n def reset_subentity(self, entity, state_map, port_value_map):\n logger.debug(f\"Resetting entity {entity._name} ({entity.__class__.__name__})\")\n for ent in get_all_entities(entity):\n if ent in state_map and state_map[ent] is not None:\n ent.current = state_map[ent]\n\n for port in get_all_ports(entity):\n if port not in get_inputs(entity): # don't reset the input values\n port.value = port_value_map[port]\n # port.pre = port_value_map[port] # but reset all pre values, including inputs, because we really want that state before\n\n # def update_fp(self, entity, time):\n # logger.debug(\"update_fp in entity %s (%s)\", entity._name, entity.__class__.__name__)\n # updates_from_current = [up for up in get_updates(entity) if up.state == entity.current]\n #\n # # save values\n # original_target_values = {t: t.value for t in get_targets(entity)}\n #\n # values_after_update = {}\n # for update in updates_from_current:\n # update_func_value = self._get_update_function_value(update, time)\n # values_after_update[update.target] = update_func_value\n # if not bool(original_target_values[update.target] == update_func_value):\n # logger.debug(f\"Update <<{update._name}>> in entity {entity._name} ({entity.__class__.__name__}) TEMP changing value of port {update.target._name} (type: {update.target.resource.unit}) to {update_func_value} (from {original_target_values[update.target]}) | global time {self.global_time}\")\n # # changes = True\n # self._value_change(values_after_update)\n # self.influence_fp(entity) # propagate through influences and to children\n #\n # secondary_changes = True\n # while secondary_changes:\n # secondary_changes = False # reset the repetition flag\n # secondary_changes_to_values_after_update = {}\n # for secondary_update in updates_from_current:\n # # reset value, to make sure those self-referencing counters are still possible and not giving infinite loops\n # secondary_update.target.value = original_target_values[secondary_update.target]\n # up_func_value = self._get_update_function_value(secondary_update, time)\n # secondary_update.target.value = values_after_update[secondary_update.target] # we did this reset only for the calculation\n # if not bool(up_func_value == values_after_update[secondary_update.target]):\n # # if we come here, then clearly the value changed through the second update, i.e. there is a dependency somewhere\n # logger.debug(f\"Update {secondary_update._name} entity {entity._name} ({entity.__class__.__name__}) SECONDARY changing value of port {secondary_update.target._name} (type: {secondary_update.target.resource.unit}) to {up_func_value} (from {values_after_update[secondary_update.target]}) | global time {self.global_time}\")\n # logger.debug(f\"up_func_value: {up_func_value} --- values_after_update: {values_after_update[secondary_update.target]}\")\n # secondary_changes = True\n # secondary_changes_to_values_after_update[secondary_update.target] = up_func_value\n # values_after_update[secondary_update.target] = up_func_value\n # self._value_change(secondary_changes_to_values_after_update)\n # self.influence_fp(entity)\n #\n # changes = False\n # for target_port, value in original_target_values.items():\n # if not bool(target_port.value == value):\n # logger.info(f\"Updates in entity {entity._name} ({entity.__class__.__name__}) changed value of port {target_port._name} (type: {target_port.resource.unit}) to {target_port.value} (from {value}) | global time {self.global_time}\")\n # changes = True\n #\n # return changes\n #\n # # changes = {}\n # # # execute updates\n # # for update in updates_from_current:\n # # up_func_value = self._get_update_function_value(update, time)\n # # if not bool(up_func_value == original_target_values[update.target]):\n # # changes[update.target] = up_func_value\n # # logger.info(f\"Update {update._name} in entity {entity._name} ({entity.__class__.__name__}) changing value of port {update.target._name} (type: {update.target.resource.unit}) to {up_func_value} | global time {self.global_time}\")\n # #\n # # # this actually executes the change of values\n # # self._value_change(changes)\n # #\n # # # return if there were changes\n # # return (len(changes) > 0)\n\n def _get_update_function_value(self, update, time):\n return update.function(update._parent, time)\n\n def _get_action_function_value(self, action):\n return action.function(action._parent)\n\n class WarningDuplicateFilter(logging.Filter):\n\n def __init__(self):\n self.warning_logs = set()\n\n def filter(self, record):\n # add other fields if you need more granular comparison, depends on your app\n if record.levelno != logging.WARNING:\n return True\n\n msg = record.getMessage()\n if msg in self.warning_logs:\n return False\n else:\n self.warning_logs.add(msg)\n return True\n # import pdb; pdb.set_trace()\n #\n # current_log = (record.module, record.levelno, record.msg)\n # if current_log != getattr(self, \"last_log\", None):\n # self.last_log = current_log\n # return True\n # return False\n\n def advance(self, t, consider_behaviour_changes=config.consider_behaviour_changes):\n filter = self.WarningDuplicateFilter()\n for handler in logging.root.handlers:\n handler.addFilter(filter)\n\n self.advance_rec(t, consider_behaviour_changes)\n\n for handler in logging.root.handlers:\n handler.removeFilter(filter)\n\n \"\"\" advance \"\"\"\n def advance_rec(self, t, consider_behaviour_changes=config.consider_behaviour_changes):\n # save traces\n if self.record_traces:\n self.traces.save_entity(self.entity, self.global_time)\n\n logger.info(f\"Received instructions to advance {t} time steps. (Current global time: {self.global_time})\")\n logger.debug(\"starting advance of %s time units. (global time now: %s)\", t, self.global_time)\n if evaluate_to_bool(t <= 0):\n logger.warn(\"Advancing 0 is not allowed. Use stabilise_fp instead.\")\n return\n\n if consider_behaviour_changes:\n next_trans = self.next_behaviour_change_time()\n else:\n next_trans = self.next_transition_time()\n\n if next_trans is None:\n logger.info(f\"No next transition, just advance {t}\")\n self.global_time += t\n # execute all updates in all entities\n self.update(self.entity, t)\n logger.debug(\"Finished updates after advance\")\n\n # stabilise the system\n self._stabilise_fp(self.entity)\n\n # record those traces\n if self.record_traces:\n self.traces.save_entity(self.entity, self.global_time)\n return\n\n # ntt = next_trans[0]\n ntt = to_python(next_trans[0])\n if evaluate_to_bool(ntt >= t):\n logger.info(f\"Advancing {t}\")\n self.global_time += t\n # execute all updates in all entities\n self.update(self.entity, t)\n logger.debug(\"Finished updates after advance\")\n\n # stabilise the system\n self._stabilise_fp(self.entity)\n logger.info(f\"Finished Advancing {t}\")\n else:\n logger.info(f\"The next transition is in {ntt} time units. Advancing that first, then the rest of the {t}.\")\n self.advance_rec(ntt, consider_behaviour_changes)\n logger.info(f\"Now need to advance the rest of the {t}: {t - ntt}\")\n self.advance_rec(t - ntt, consider_behaviour_changes)\n logger.debug(f\"finished total advance of {t} (time is now {self.global_time})\")\n\n # record those traces\n if self.record_traces:\n self.traces.save_entity(self.entity, self.global_time)\n\n \"\"\" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \"\"\"\n\n def get_next_transition_time(self):\n \"\"\" this function is a convenience for debugging, so we don't have to create a TransitionTimeCalculator manually \"\"\"\n ntt = self.next_transition_time()\n if ntt:\n logger.info(f\"The next transition to fire is '{ntt[1]._name}' in ntt={to_python(ntt[0])} time steps\")\n return (ntt[1]._name, to_python(ntt[0]))\n else:\n logger.info(\"There is no transition reachable by time advance.\")\n return None\n\n def next_transition_time(self):\n \"\"\" this function is a convenience for debugging, so we don't have to create a TransitionTimeCalculator manually \"\"\"\n logger.info(self.timeunit)\n return TransitionTimeCalculator(self.entity, self.timeunit, use_integer_and_real=self.default_to_integer_real).get_next_transition_time()\n\n \"\"\" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \"\"\"\n\n # def advance_behaviour_change(self, t):\n # # save traces\n # if self.record_traces:\n # self.traces.save_entity(self.entity, self.global_time)\n #\n # logger.info(f\"Received instructions to advance {t} time steps. (Current global time: {self.global_time})\")\n # logger.debug(\"starting advance of %s time units. (global time now: %s)\", t, self.global_time)\n # if t <= 0:\n # logger.warn(\"Advancing 0 is not allowed. Use stabilise_fp instead.\")\n # return\n #\n # next_trans = self.next_behaviour_change_time()\n # if next_trans is None:\n # logger.info(f\"No next behaviour change, just advance {t}\")\n # # execute all updates in all entities\n # self.update(self.entity, t)\n # # for e in get_all_entities(self.entity):\n # # self.update(e, t)\n #\n # # stabilise the system\n # self._stabilise_fp(self.entity)\n # self.global_time += t\n #\n # # record those traces\n # if self.record_traces:\n # self.traces.save_entity(self.entity, self.global_time)\n # return\n #\n # ntt = to_python(next_trans[0])\n # if ntt >= t:\n # logger.info(\"Advancing %s\", t)\n # # execute all updates in all entities\n # self.update(self.entity, t)\n #\n # # stabilise the system\n # self._stabilise_fp(self.entity)\n # self.global_time += t\n # else:\n # logger.info(f\"The next behaviour change is in {ntt} time units. Advancing that first, then the rest of the {t}.\")\n # self.advance_behaviour_change(ntt)\n # logger.info(f\"Now need to advance the rest of the {t}: {t - ntt}\")\n # self.advance_behaviour_change(t - ntt)\n # logger.debug(f\"finished total advance of {t} (time is now {self.global_time})\")\n #\n # # record those traces\n # if self.record_traces:\n # self.traces.save_entity(self.entity, self.global_time)\n\n def next_behaviour_change_time(self):\n \"\"\" this function is a convenience for debugging, so we don't have to create a TransitionTimeCalculator manually \"\"\"\n nbct = ConditionTimedChangeCalculator(self.entity, self.timeunit, use_integer_and_real=self.default_to_integer_real).get_next_behaviour_change_time()\n if nbct is not None:\n logger.info(f\"The next behaviour change is {nbct[1]._name} in {to_python(nbct[0])} time steps\")\n else:\n logger.info(\"There is no behaviour change reachable by time advance.\")\n return nbct\n","sub_path":"src/simulator/basesimulator.py","file_name":"basesimulator.py","file_ext":"py","file_size_in_byte":30390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"282312828","text":"import cv2\nimport numpy as np\n\ncap = cv2.VideoCapture(0)\ncv2.namedWindow(\"Video\")\ncv2.namedWindow('hsv', cv2.WINDOW_NORMAL)\ncv2.namedWindow('tracking', cv2.WINDOW_NORMAL)\n\n\ndef get_hsv_val(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDOWN:\n stat2, img2 = cap.read()\n vals = img2[y][x]\n # set track bar to -10 + 10 of click\n adjust = 25\n cv2.setTrackbarPos('H Min', 'hsv', vals[0]-adjust)\n cv2.setTrackbarPos('H Max', 'hsv', vals[0]+adjust)\n cv2.setTrackbarPos('S Min', 'hsv', vals[1]-adjust)\n cv2.setTrackbarPos('S Max', 'hsv', vals[1]+adjust)\n cv2.setTrackbarPos('V Min', 'hsv', vals[2]-adjust)\n cv2.setTrackbarPos('V Max', 'hsv', vals[2]+adjust)\n\n\ncv2.setMouseCallback(\"hsv\", get_hsv_val)\n\ndef nothing(x):\n pass\n\ncv2.createTrackbar('H Min','hsv',0,255, nothing)\ncv2.createTrackbar('H Max','hsv',0,255, nothing)\ncv2.createTrackbar('S Min','hsv',0,255, nothing)\ncv2.createTrackbar('S Max','hsv',0,255, nothing)\ncv2.createTrackbar('V Min','hsv',0,255, nothing)\ncv2.createTrackbar('V Max','hsv',0,255, nothing)\n\nwhile True:\n status, img = cap.read()\n cv2.resizeWindow(\"Video\", 600,400)\n cv2.imshow(\"Video\", img)\n cv2.resizeWindow(\"hsv\", 600,400)\n cv2.resizeWindow(\"tracking\", 600,400)\n\n # get slider values\n h = cv2.getTrackbarPos('H Max','hsv')\n s = cv2.getTrackbarPos('S Max','hsv')\n v = cv2.getTrackbarPos('V Max','hsv')\n\n hsv_max = np.array([h, s, v])\n\n h = cv2.getTrackbarPos('H Min','hsv')\n s = cv2.getTrackbarPos('S Min','hsv')\n v = cv2.getTrackbarPos('V Min','hsv')\n\n hsv_min = np.array([h, s, v])\n\n # Convert to hsv\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n cv2.imshow('hsv', hsv)\n\n # Color tracking\n track = cv2.inRange(hsv, hsv_min, hsv_max)\n\n kernel = np.ones((2,2), np.uint8)\n\n img_erosion = cv2.erode(track, kernel, iterations=1)\n kernel = np.ones((6,6), np.uint8)\n img_dilation = cv2.dilate(img_erosion, kernel, iterations=1)\n\n cv2.imshow('Erosion', img_erosion)\n cv2.imshow('tracking', img_dilation)\n\n # unedited tracking image\n # cv2.imshow('tracking', track)\n\n k = cv2.waitKey(1)\n if k == 27:\n break\n\ncv2.destroyAllWindows()\n","sub_path":"old/track_object.py","file_name":"track_object.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"407068252","text":"def hold(a, b, c):\n\tif (a**2 + b**2 + c**2)/2 in [a**2, b**2, c**2] and max(a, b, c) < (a+b+c):\n\t\tprint('The lengths are: ',a, b, c)\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef sol(n):\n\tnum = 0\n\tfor i in range(1, n//3):\n\t\tfor j in range(i, (n-i)//2):\n\t\t\tk = n - i - j\n\t\t\tif hold(i,j,k):\n\t\t\t\tnum += 1\n\treturn num\n\nsolmax = 0\nfor p in range(3, 1001):\n\ttemp = sol(p)\n\tprint('number', p, 'has', temp, 'solutions')\n\tsolmax = max(solmax, temp)\n\nprint(solmax)","sub_path":"resource/code-samples/project-euler/0319P39.py","file_name":"0319P39.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"289470098","text":"# See LICENSE for licensing information.\n#\n# Copyright (c) 2016-2019 Regents of the University of California \n# All rights reserved.\n#\nfrom bitcell_base_array import bitcell_base_array\nfrom sram_factory import factory\nfrom globals import OPTS\n\n\nclass dummy_array(bitcell_base_array):\n \"\"\"\n Generate a dummy row/column for the replica array.\n \"\"\"\n def __init__(self, cols, rows, column_offset=0, mirror=0, name=\"\"):\n super().__init__(cols, rows, name, column_offset)\n self.mirror = mirror\n\n self.create_netlist()\n if not OPTS.netlist_only:\n self.create_layout()\n \n def create_netlist(self):\n \"\"\" Create and connect the netlist \"\"\"\n self.add_modules()\n self.add_pins()\n self.create_instances()\n\n def create_layout(self):\n\n self.place_array(\"dummy_r{0}_c{1}\", self.mirror)\n\n self.add_layout_pins()\n\n self.add_boundary()\n \n self.DRC_LVS()\n\n def add_modules(self):\n \"\"\" Add the modules used in this design \"\"\"\n self.dummy_cell = factory.create(module_type=\"dummy_{}\".format(OPTS.bitcell))\n self.add_mod(self.dummy_cell)\n\n self.cell = factory.create(module_type=\"bitcell\")\n \n def create_instances(self):\n \"\"\" Create the module instances used in this design \"\"\"\n self.cell_inst = {}\n for col in range(self.column_size):\n for row in range(self.row_size):\n name = \"bit_r{0}_c{1}\".format(row, col)\n self.cell_inst[row, col]=self.add_inst(name=name,\n mod=self.dummy_cell)\n self.connect_inst(self.get_bitcell_pins(col, row))\n\n def input_load(self):\n wl_wire = self.gen_wl_wire()\n return wl_wire.return_input_cap()\n\n def get_wordline_cin(self):\n \"\"\"Get the relative input capacitance from the wordline connections in all the bitcell\"\"\"\n # A single wordline is connected to all the bitcells in a single row meaning the capacitance depends on the # of columns\n bitcell_wl_cin = self.cell.get_wl_cin()\n total_cin = bitcell_wl_cin * self.column_size\n return total_cin\n","sub_path":"compiler/modules/dummy_array.py","file_name":"dummy_array.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"} +{"seq_id":"472842883","text":"n, x = map(int, input().split())\r\nif x == 1 or x == (2 * n - 1):\r\n print(\"No\")\r\n exit()\r\n\r\nprint(\"Yes\")\r\n\r\nr = [x - 1, x, x + 1]\r\ntmp = list(range(1, x - 1)) + list(range(x + 2, 2 * n))\r\n\r\nans = tmp[n - 2:] + r + tmp[:n - 2]\r\n\r\nfor i in ans:\r\n print(i)","sub_path":"Source Codes/AtCoder/agc006/B/4926379.py","file_name":"4926379.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}