diff --git "a/3249.jsonl" "b/3249.jsonl" new file mode 100644--- /dev/null +++ "b/3249.jsonl" @@ -0,0 +1,707 @@ +{"seq_id":"350615820","text":"# _*_ coding:utf-8 _*_\n# ! /usr/bin/env python\n__author__ = 'Administrator'\n\n'''\n@created by sjh\n2016-06-22\n'''\n\nimport re\n# portal 日志\nwith open(r'G:\\wifi_portal_log\\project.log.2016-08-08.txt', 'r', encoding='utf-8') as f:\n portal_logs = f.read()\n# midware 日志\nwith open(r'G:\\portal_midware_log\\project.log.2016-08-08.txt', 'r', encoding='utf-8') as f:\n midware_logs = f.read()\n\n\n\n# tenant_list = ['bdcsgc', 'nhdh', 'xhcsgc', 'nghx', 'ngcs', 'ngjn']\n# basId_list = {'ngcdfy':'10112','xhcsgc':'10107'}\nbasId_list = {'ngcdfy':'10112'}\n# tenant_list = ['ngcdfy']\n# MAC_PATTERN = '[0-9a-fA-F]{2}-[0-9a-fA-F]{2}-[0-9a-fA-F]{2}-[0-9a-fA-F]{2}-[0-9a-fA-F]{2}-[0-9a-fA-F]{2}'\nMAC_PATTERN = r'usermac=.{12}'\nIP_PATTERN = r'userIp=([0-9]{1,3}\\.){3}[0-9]{1,3}'\nfor tenant in basId_list.keys():\n # 正则规则\n # 连接SSID ,进入index页面\n tenant_index_pattern = tenant+r'/index.*'+MAC_PATTERN\n\n # 在portal 页点击一键上网,超时自动认证\n tenant_outtime_pattern= r'/updateOnlineTime.*basId='+basId_list[tenant]+r'.*'\n # 中间层发送认证到AC, AC返回认证失败\n tenant_online_fail_pattern = r'call api fail.*basId='+basId_list[tenant]+r'.*errcode.*\\n.*?'+tenant.capitalize()+r'.*onlineTmp auth fail'\n # tenant_online_fail_pattern = r'wifi\\.pages\\.'+tenant.capitalize()+r'.*onlineTmp auth fail'\n # 认证失败错误码\n H30401_ERROR_pattern = r'basId='+basId_list[tenant]+r'.*H30401'\n # H30402_ERROR_pattern = r'basId='+basId_list[tenant]+r'.*H30402'\n H30203_ERROR_pattern = r'basId='+basId_list[tenant]+r'.*H30203'\n H30404_ERROR_pattern = r'basId='+basId_list[tenant]+r'.*H30404'\n P00004_ERROR_pattern = r'basId='+basId_list[tenant]+r'.*P00004'\n # 通过微信立即连接上网\n wxOnlie_pattern = r'Access log.*/wxOnline basId=' + basId_list[tenant] + r'.*openId=.*'\n\n tenant_index_list = re.findall(tenant_index_pattern,portal_logs)\n tenant_online_fail_list = re.findall(tenant_online_fail_pattern,portal_logs)\n # H30401_ERROR_list = re.findall(H30401_ERROR_pattern,midware_logs)\n # H30203_ERROR_list = re.findall(H30203_ERROR_pattern,midware_logs)\n # H30404_ERROR_list = re.findall(H30404_ERROR_pattern,midware_logs)\n # P00004_ERROR_list = re.findall(P00004_ERROR_pattern,midware_logs)\n # H30404_ERROR_list = re.findall(H30404_ERROR_pattern,midware_logs)\n tenant_outtime_list = re.findall(tenant_outtime_pattern,midware_logs)\n wxOnlie_list = re.findall(wxOnlie_pattern,midware_logs)\n\n H30401_ERROR = []\n H30203_ERROR = []\n H30404_ERROR = []\n P00004_ERROR = []\n \n for line in tenant_online_fail_list:\n try:\n H30401_ERROR.append(re.findall(H30401_ERROR_pattern,line)[0])\n H30404_ERROR.append(re.findall(H30404_ERROR_pattern,line)[0])\n H30203_ERROR.append(re.findall(H30203_ERROR_pattern,line)[0])\n P00004_ERROR.append(re.findall(P00004_ERROR_pattern,line)[0])\n except IndexError:\n pass\n print(tenant + ' index连接申请数量:' + str(len(tenant_index_list)))\n print(tenant+' AC 返回上网认证失败:'+str(len(tenant_online_fail_list)))\n print(tenant+\" 通过微信立即上网:\"+str(len(wxOnlie_list)))\n print(tenant+' PORTAL认证超时,自动联网:'+str(len(tenant_outtime_list)))\n print(tenant+' H30401 错误码:'+str(len(H30401_ERROR)))\n print(tenant+' H30404 错误码:'+str(len(H30404_ERROR)))\n print(tenant+' H30203 错误码:'+str(len(H30203_ERROR)))\n print(tenant+' P00004 错误码:'+str(len(P00004_ERROR)))\n\n index_mac = []\n for line in tenant_index_list:\n try:\n index_mac.append(re.findall(MAC_PATTERN, line)[0])\n except IndexError:\n pass\n index_mac = list(set(index_mac))\n print(tenant + ' index 连接用户数: ' + str(len(index_mac)))\n print('------------')\n\n wx_openId = []\n for line in wxOnlie_list:\n try:\n wx_openId.append(re.findall(r'openId=(.{28})', line)[0])\n except IndexError:\n pass\n print(len(wx_openId))\n wx_openId = list(set(wx_openId))\n print(tenant + ' 微信一键上网openId数: ' + str(len(wx_openId)))\n print('------------')\n\n # AC 返回上网认证失败ip数\n online_fail_ip = []\n for line in tenant_online_fail_list:\n online_fail_ip.append(re.findall(IP_PATTERN,line)[0])\n online_fail_ip = list(set(online_fail_ip))\n print(\"AC 返回上网认证失败IP数:\"+str(len(online_fail_ip)))\n\n # PORTAL 认证超时,自动联网IP数\n outTime_ip = []\n for line in tenant_outtime_list:\n outTime_ip.append(re.findall(IP_PATTERN,line)[0])\n outTime_ip = list(set(outTime_ip))\n print(\"PORTAL 认证超时,自动联网IP数:\"+str(len(outTime_ip)))\n\n # 通过微信立即上网IP数\n wxOnline_ip = []\n for line in wxOnlie_list:\n wxOnline_ip.append(re.findall(IP_PATTERN,line)[0])\n wxOnline_ip = list(set(wxOnline_ip))\n print(\"通过微信立即上网IP 数量:\"+str(len(wxOnline_ip)))\n\n # 最终不能上网IP, 在上网认证失败,不在微信上网,超时自动联网\n final_effect_ip = []\n online_ip =list(set(wxOnline_ip+outTime_ip))\n final_effect_ip = list(set(online_fail_ip)-set(online_ip))\n print(\"最终无法上网IP数:\"+str(len(online_fail_ip)))\n print(\"----------------------------\")\n\n # tenant_connect_pattern = r'/' + tenant + \\\n # r'/connect.*?usermac='+MAC_PATTERN\n # tenant_connect_list = re.findall(tenant_connect_pattern, portal_logs)\n # print(tenant + ' connect 总连接申请数量:' + str(len(tenant_connect_list)))\n # connect_mac = []\n # for line in tenant_connect_list:\n # try:\n # connect_mac.append(re.findall(MAC_PATTERN, line)[0])\n # except IndexError:\n # pass\n # connect_mac = list(set(connect_mac))\n # # print(suc_mac)\n # print(tenant + ' connect用户数: ' + str(len(connect_mac)))\n # print(tenant + ' 连index 而未连 connect用户数: ' + str(len(list(set(index_mac)-set(connect_mac)))))\n # print('---------------')\n\n # # 认证成功\n # tenant_auth_suc = re.findall(auth_suc_pattern, portal_logs)\n # tenant_yijian_suc = re.findall(yijian_pattern, portal_logs)\n # print(tenant + '认证成功数量:' + str(len(tenant_auth_suc)))\n # print(tenant + '一键上网成功数量:' + str(len(tenant_yijian_suc)))\n # suc_mac = []\n # for line in tenant_auth_suc:\n # try:\n # suc_mac.append(re.findall(MAC_PATTERN, line)[0])\n # except IndexError:\n # pass\n # suc_mac = list(set(suc_mac))\n # # print(suc_mac)\n # print(tenant + '认证成功用户数: ' + str(len(suc_mac)))\n # print('------------')\n\n # # 认证失败\n # tenant_auth_fail = re.findall(auth_fail_pattern, portal_logs)\n # print(tenant + '认证失败数量:' + str(len(tenant_auth_fail)))\n # fail_mac = []\n # for line in tenant_auth_fail:\n # fail_mac.append(re.findall(MAC_PATTERN, line)[0])\n # fail_mac = list(set(fail_mac))\n # print(tenant + '认证失败用户数: ' + str(len(fail_mac)))\n # # 一直未认证成功用户\n # print(tenant + '影响用户数:' + str(len(list(set(fail_mac) - set(suc_mac)))))\n # # 统计认证失败后ip变更又认证成功的用户数量\n # # retry_success_mac = list(set(fail_mac)&set(suc_mac))\n # # for mac in retry_success_mac:\n # # mac_connect_pattern =\n\n # print('------------')\n\n\n\n # # 认证重试\n # tenant_retry = re.findall(auth_retry_pattern, portal_logs)\n # retry_mac = []\n # for line in tenant_retry:\n # retry_mac.append(re.findall(MAC_PATTERN, line)[0])\n # retry_mac = list(set(retry_mac))\n # print(tenant + '认证重试数量:' + str(len(tenant_retry)))\n # print(tenant + '认证重试用户数量:' + str(len(retry_mac)))\n # print('------------')\n\n # # 认证重试失败\n # tenant_retry_fail = re.findall(auth_retry_fail_pattern, portal_logs)\n # retry_fail_mac = []\n # for line in tenant_retry_fail:\n # retry_fail_mac.append(re.findall(MAC_PATTERN, line)[0])\n # retry_fail_mac = list(set(retry_fail_mac))\n # print(tenant + '认证重试失败数量:' + str(len(tenant_retry_fail)))\n # print(tenant + '认证重试失败用户数量:' + str(len(retry_fail_mac)))\n # print('------------')\n\n # # 认证重试成功\n # tenant_retry_suc = re.findall(auth_retry_suc_pattern, portal_logs)\n # # print(tenant_retry_suc)\n # retry_suc_mac = []\n # usermac_pattern = r'usermac.*?' + MAC_PATTERN\n # for line in tenant_retry_suc:\n # retry_suc_mac.append(re.findall(usermac_pattern, line)[0])\n # retry_suc_mac = list(set(retry_suc_mac))\n\n # print(tenant + '认证重试成功数量:' + str(len(tenant_retry_suc)))\n # print(tenant + '认证重试成功用户数量:' + str(len(retry_suc_mac)))\n # print('------------')\n\n # # 区分错误码\n # mac_list = []\n # error_list_H30201 = []\n # error_list_H30401 = []\n # error_list_P00004 = []\n # error_P00004_mac = []\n # for line in tenant_auth_fail:\n # mac_list.append(re.findall(MAC_PATTERN, line)[0])\n # while re.search('H30201', line):\n # error_list_H30201.append(re.findall('H30201', line))\n # break\n # while re.search('H30401', line):\n # error_list_H30401.append(re.findall('H30401', line))\n # break\n # while re.search('P00004', line):\n # error_list_P00004.append(re.findall('P00004', line))\n # error_P00004_mac.append(re.findall(MAC_PATTERN, line)[0])\n # break\n # print('认证错误P00004:' + str(len(error_list_P00004)))\n # # print(len(error_P00004_mac))\n # print('认证错误H30201:' + str(len(error_list_H30201)))\n # print('认证错误H30401:' + str(len(error_list_H30401)))\n # print('-----------------')\n","sub_path":"PySripts/cdfy.py","file_name":"cdfy.py","file_ext":"py","file_size_in_byte":10001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"27855624","text":"__all__ = [\n 'BasePluginV1',\n 'HotkeysPluginV1',\n 'TriggerPluginV1',\n 'TolokaPluginV1'\n]\nfrom enum import Enum, unique\nfrom typing import List, Any\n\nfrom ...primitives.base import attribute\n\nfrom .base import VersionedBaseComponent, BaseComponent, ComponentType, BaseTemplate, base_component_or\n\n\nclass BasePluginV1(VersionedBaseComponent):\n \"\"\"Plugins that provide expanded functionality. For example, you can use plugin.hotkeys to set up shortcuts.\n\n \"\"\"\n\n pass\n\n\nclass HotkeysPluginV1(BasePluginV1, spec_value=ComponentType.PLUGIN_HOTKEYS):\n \"\"\"Lets you set keyboard shortcuts for actions.\n\n Attributes:\n key_ + [a-z|0-9|up|down]: An action that is triggered when you press the specified keyboard key. The keyboard\n shortcut is set in the key, and the action is specified in the value\n \"\"\"\n\n key_a: base_component_or(Any) = attribute(default=None, origin='a')\n key_b: base_component_or(Any) = attribute(default=None, origin='b')\n key_c: base_component_or(Any) = attribute(default=None, origin='c')\n key_d: base_component_or(Any) = attribute(default=None, origin='d')\n key_e: base_component_or(Any) = attribute(default=None, origin='e')\n key_f: base_component_or(Any) = attribute(default=None, origin='f')\n key_g: base_component_or(Any) = attribute(default=None, origin='g')\n key_h: base_component_or(Any) = attribute(default=None, origin='h')\n key_i: base_component_or(Any) = attribute(default=None, origin='i')\n key_j: base_component_or(Any) = attribute(default=None, origin='j')\n key_k: base_component_or(Any) = attribute(default=None, origin='k')\n key_l: base_component_or(Any) = attribute(default=None, origin='l')\n key_m: base_component_or(Any) = attribute(default=None, origin='m')\n key_n: base_component_or(Any) = attribute(default=None, origin='n')\n key_o: base_component_or(Any) = attribute(default=None, origin='o')\n key_p: base_component_or(Any) = attribute(default=None, origin='p')\n key_q: base_component_or(Any) = attribute(default=None, origin='q')\n key_r: base_component_or(Any) = attribute(default=None, origin='r')\n key_s: base_component_or(Any) = attribute(default=None, origin='s')\n key_t: base_component_or(Any) = attribute(default=None, origin='t')\n key_u: base_component_or(Any) = attribute(default=None, origin='u')\n key_v: base_component_or(Any) = attribute(default=None, origin='v')\n key_w: base_component_or(Any) = attribute(default=None, origin='w')\n key_x: base_component_or(Any) = attribute(default=None, origin='x')\n key_y: base_component_or(Any) = attribute(default=None, origin='y')\n key_z: base_component_or(Any) = attribute(default=None, origin='z')\n key_0: base_component_or(Any) = attribute(default=None, origin='0')\n key_1: base_component_or(Any) = attribute(default=None, origin='1')\n key_2: base_component_or(Any) = attribute(default=None, origin='2')\n key_3: base_component_or(Any) = attribute(default=None, origin='3')\n key_4: base_component_or(Any) = attribute(default=None, origin='4')\n key_5: base_component_or(Any) = attribute(default=None, origin='5')\n key_6: base_component_or(Any) = attribute(default=None, origin='6')\n key_7: base_component_or(Any) = attribute(default=None, origin='7')\n key_8: base_component_or(Any) = attribute(default=None, origin='8')\n key_9: base_component_or(Any) = attribute(default=None, origin='9')\n key_up: base_component_or(Any) = attribute(default=None, origin='up')\n key_down: base_component_or(Any) = attribute(default=None, origin='down')\n\n\nclass TriggerPluginV1(BasePluginV1, spec_value=ComponentType.PLUGIN_TRIGGER):\n \"\"\"Use this to configure triggers that trigger a specific action when an event occurs.\n\n The action is set in the action property, and the event is described in the other fields.\n\n The event can be triggered immediately when the task is loaded (\"fireImmediately\": true) or when data changes in\n the property specified in onChangeOf.\n\n You can also set conditions in the conditions property that must be met in order for the trigger to fire.\n Attributes:\n action: The action to perform when the trigger fires.\n condition: The condition that must be met in order to fire the trigger.\n fire_immediately: Flag indicating whether the trigger should be fired immediately after the task is loaded.\n on_change_of: The data that triggers the action when changed.\n\n Example:\n How to save the performer coordinates to the output.\n\n >>> coordinates_save_plugin = tb.plugins.TriggerPluginV1(\n >>> fire_immediately=True,\n >>> action=tb.actions.SetActionV1(\n >>> data=tb.data.OutputData(path='performer_coordinates'),\n >>> payload=tb.data.LocationData()\n >>> ),\n >>> )\n ...\n \"\"\"\n\n action: BaseComponent\n condition: BaseComponent\n fire_immediately: base_component_or(bool) = attribute(origin='fireImmediately')\n on_change_of: BaseComponent = attribute(origin='onChangeOf')\n\n\nclass TolokaPluginV1(BasePluginV1, spec_value=ComponentType.PLUGIN_TOLOKA):\n \"\"\"A plugin with extra settings for tasks in Toloka.\n\n Attributes:\n layout: Settings for the task appearance in Toloka.\n notifications: Notifications shown at the top of the page.\n\n Example:\n How to set the task width on the task page.\n\n >>> task_width_plugin = tb.plugins.TolokaPluginV1(\n >>> layout = tb.plugins.TolokaPluginV1.TolokaPluginLayout(\n >>> kind='scroll',\n >>> task_width=400,\n >>> )\n >>> )\n ...\n \"\"\"\n\n class TolokaPluginLayout(BaseTemplate):\n \"\"\"How to display task.\n\n \"\"\"\n\n @unique\n class Kind(Enum):\n \"\"\"An enumeration.\n\n Attributes:\n SCROLL: (default) display multiple tasks on the page at the same time.\n PAGER: display only one task on the page, with a button to switch between tasks at the bottom.\n \"\"\"\n\n PAGER = 'pager'\n SCROLL = 'scroll'\n\n kind: Kind = Kind.SCROLL\n task_width: float = attribute(origin='taskWidth')\n\n layout: base_component_or(TolokaPluginLayout) = attribute(factory=TolokaPluginLayout)\n notifications: base_component_or(List[BaseComponent], 'ListBaseComponent')\n","sub_path":"src/client/project/template_builder/plugins.py","file_name":"plugins.py","file_ext":"py","file_size_in_byte":6402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"123115076","text":"from ssfr.core.routing import router as _router\n\nfrom .controllers import (\n AuthController, HomeController, UsersController\n)\n\nrouter = _router.Router()\n\nauthController = AuthController()\nhomeController = HomeController()\nusersController = UsersController()\n\nrouter.add_routes(homeController.routes)\nrouter.add_routes(authController.routes, 'auth')\nrouter.add_routes(usersController.routes, 'users')\n","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"106725032","text":"#!/usr/bin/python\n\nimport sys\n\nrc = 1\n\nif len(sys.argv) == 4:\n separator=sys.argv[2]\n token_list = sys.argv[3]\n if sys.argv[1] == \"next-token\":\n split_idx = token_list.find(separator)\n if split_idx != -1:\n token = token_list[:split_idx]\n else:\n token = token_list\n sys.stdout.write(token)\n rc = 0\n elif sys.argv[1] == \"remove-token\":\n rc = 0\n split_idx = token_list.find(separator)\n if split_idx != -1:\n token_list = token_list[split_idx + len(separator):]\n else:\n token_list = \"\"\n sys.stdout.write(token_list)\nelse:\n sys.stderr.write(\"Syntax: tokenizer { next-token | remove-token } \\n\")\n\nsys.stdout.flush()\nsys.stderr.flush()\n\nexit(rc)\n","sub_path":"scripts/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"413438287","text":"from dapiclient.client import DAPIClient\r\nimport cbor2\r\nimport base58\r\n\r\n\r\nclient = DAPIClient()\r\n\r\ndef getDocuments(data):\r\n docs = client.getDocuments(\r\n data['contract_id'],\r\n data['document_type'],\r\n data['where'],\r\n limit=2,\r\n )\r\n\r\n documents = []\r\n \r\n for doc in docs:\r\n documents.append(cbor2.loads(doc))\r\n \r\n return documents[0] # Only one document\r\n\r\n\r\ndef main():\r\n data = {\r\n 'contract_id': base58.b58decode('D6tjxCZzZobDQztc4S1PK7EDwm4CegLARpiKZn6jQc1R'),\r\n 'document_type': 'thumbnailField',\r\n 'where': cbor2.dumps([\r\n ['ownerId', '==', base58.b58decode('26AxVi5bvYYaC94GmeTmqX21vzsSxar2a4imxSE8ULUQ')],\r\n ['$updatedAt', '==', 1627948894242],\r\n ]),\r\n }\r\n result = getDocuments(data) \r\n print(result)\r\n \r\n \r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n\r\n\r\n\r\n","sub_path":"tests/dapiclient/dapiclient_test.py","file_name":"dapiclient_test.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"198005834","text":"import glob\nimport os\nimport sys\nimport random\n\n\ndef listup_files(path):\n result = []\n for p in glob.glob(path + '/*'):\n # print(p)\n result.append(os.path.abspath(p))\n return result\n\n\ndef train_val_sep(path_list, val_rate=2):\n val_num = int(len(path_list) * 0.2)\n random.shuffle(path_list)\n train_list = path_list[val_num:]\n val_list = path_list[:val_num]\n print(len(train_list))\n print(len(val_list))\n return train_list, val_list\n\n\ndef write_txt(output_txt, file_list):\n with open(output_txt, 'w') as f:\n for d in file_list:\n f.write(\"%s\\n\" % d)\n\n\nif __name__ == '__main__':\n # arg1: input directory path\n # arg2: output directory path\n args = sys.argv\n result = listup_files(args[1])\n train, val = train_val_sep(result)\n write_txt(args[2] + '/train.txt', train)\n write_txt(args[2] + '/val.txt', val)\n","sub_path":"script/make_data_path_file.py","file_name":"make_data_path_file.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"556520827","text":"import argparse\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import datasets\nfrom torch.autograd import Variable\nfrom tqdm import tqdm\n\n\nimport PIL.Image as Image\n\nimport numpy as np\n\n\n#cd desktop/MVA_2019_2020/\nif __name__ == \"__main__\":\n\t# Training settings\n\tparser = argparse.ArgumentParser(description='RecVis A3 training script')\n\tparser.add_argument('--data', type=str, default='bird_dataset_output', metavar='D',\n\t\t\t\t\t\thelp=\"folder where data is located. train_images/ and val_images/ need to be found in the folder\")\n\tparser.add_argument('--batch-size', type=int, default=16, metavar='B',\n\t\t\t\t\t\thelp='input batch size for training (default: 64)')\n\n\tparser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n\t\t\t\t\t\thelp='SGD momentum (default: 0.9)')\n\tparser.add_argument('--seed', type=int, default=1, metavar='S',\n\t\t\t\t\t\thelp='random seed (default: 1)')\n\t\n\tparser.add_argument('--experiment', type=str, default='experiment', metavar='E',\n\t\t\t\t\t\thelp='folder where experiment outputs are located.')\n\n\tparser.add_argument('--train_features', type=str, default='train_features', metavar='F',\n\t\t\t\t\t\thelp='folder where train_features are located.')\n\n\tparser.add_argument('--val_features', type=str, default='val_features', metavar='G',\n\t\t\t\t\t\thelp='folder where val_features are located.')\n\n\tparser.add_argument('--test_features', type=str, default='test_features', metavar='H',\n\t\t\t\t\t\thelp='folder where test_features are located.')\n\n\tparser.add_argument('--train_labels', type=str, default='train_labels', metavar='I',\n\t\t\t\t\t\thelp='folder where train_labels are located.')\n\n\tparser.add_argument('--val_labels', type=str, default='val_labels', metavar='J',\n\t\t\t\t\t\thelp='folder where val_labels are located.')\n\n\tparser.add_argument('--test_labels', type=str, default='test_labels', metavar='K',\n\t\t\t\t\t\thelp='folder where test_labels are located.')\n\n\targs = parser.parse_args()\n\tuse_cuda = torch.cuda.is_available()\n\n\t# Create experiment folder\n\tif not os.path.isdir(args.experiment):\n\t\tos.makedirs(args.experiment)\n\n\t# Data initialization and loading\n\tfrom data import data_transforms,val_transforms,feature_transforms\n\n\ttrain_loader = torch.utils.data.DataLoader(\n\t\tdatasets.ImageFolder(args.data + '/train_images',\n\t\t\t\t\t\t\t transform=feature_transforms),\n\t\tbatch_size=args.batch_size, shuffle=False, num_workers=8)\n\tval_loader = torch.utils.data.DataLoader(\n\t\tdatasets.ImageFolder(args.data + '/val_images',\n\t\t\t\t\t\t\t transform=feature_transforms),\n\t\tbatch_size=10, shuffle=False, num_workers=6)\n\n\n\t# Neural network and optimizer\n\t# We define neural net in model.py so that it can be reused by the evaluate.py script\n\t\n\tfrom model1 import ResInc_features\n\n\tmodel = ResInc_features()\n\n\t\n\tif use_cuda:\n\t\tprint('Using GPU')\n\t\tmodel.cuda()\n\telse:\n\t\tprint('Using CPU')\n\n\tdef get_train_features():\n\t\tlabels = []\n\t\tfeatures = []\n\n\t\tfor batch_idx, (data, target) in enumerate(train_loader):\n\t\t\tif use_cuda:\n\t\t\t\tdata, target = data.cuda(), target.cuda()\n\n\t\t\toutput = model(data)\n\t\t\tfeature = output.cpu().detach().numpy()\n\t\t\tlabel = target.cpu().detach().numpy()\n\n\t\t\tfeatures.append(feature)\n\t\t\tlabels.append(label)\n\n\t\tfeatures = np.concatenate(features, axis = 0)\n\t\tlabels = np.concatenate(labels, axis = 0)\n\n\t\treturn features,labels\n\n\tdef get_val_features():\n\t\tlabels = []\n\t\tfeatures = []\n\n\t\tfor batch_idx, (data, target) in enumerate(val_loader):\n\t\t\tif use_cuda:\n\t\t\t\tdata, target = data.cuda(), target.cuda()\n\n\t\t\toutput = model(data)\n\t\t\tfeature = output.cpu().detach().numpy()\n\t\t\tlabel = target.cpu().detach().numpy()\n\n\t\t\tfeatures.append(feature)\n\t\t\tlabels.append(label)\n\n\t\tfeatures = np.concatenate(features, axis = 0)\n\t\tlabels = np.concatenate(labels,axis = 0)\n\n\t\treturn features,labels\n\n\n\tdef pil_loader(path):\n\t\t# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n\t\twith open(path, 'rb') as f:\n\t\t\twith Image.open(f) as img:\n\t\t\t\treturn img.convert('RGB')\n\n\ttest_dir = args.data + '/test_images/mistery_category'\n\n\tdef get_test_features():\n\t\tlabels = []\n\t\tfeatures = []\n\n\t\tfor f in tqdm(os.listdir(test_dir)):\n\t\t\tif 'jpg' in f:\n\n\t\t\t\tdata = feature_transforms(pil_loader(test_dir + '/' + f))[None,:,:,:]\n\t\t\t\tif use_cuda:\n\t\t\t\t\tdata = data.cuda()\n\n\t\t\t\toutput = model(data)\n\t\t\t\tfeature = output.cpu().detach().numpy()\n\n\t\t\t\tfeatures.append(feature)\n\t\t\t\tlabels.append(np.array([[-1]]))\n\t\t\n\t\tfeatures = np.concatenate(features, axis = 0)\n\t\tlabels = np.concatenate(labels, axis = 0)\n\t\t \n\t\treturn features,labels\n\n\twith torch.no_grad():\n\n\t\ttrain_features, train_labels = get_train_features()\n\t\tval_features, val_labels = get_val_features()\n\t\ttest_features, test_labels = get_test_features()\n\n\tnp.save(args.train_features,train_features)\n\tnp.save(args.val_features,val_features)\n\tnp.save(args.test_features,test_features)\n\n\tnp.save(args.train_labels,train_labels)\n\tnp.save(args.val_labels,val_labels)\n\tnp.save(args.test_labels,test_labels)\n\n\tprint('Features and labels saved')\n\n\n\n\n \n\n\t\n","sub_path":"Object_Recognition/Assignment3/recvis19_a3-master/Features.py","file_name":"Features.py","file_ext":"py","file_size_in_byte":4975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"25203774","text":"# Dependencies: textblob\n# Usage: python main.py filename\n\nfrom textblob import TextBlob\nimport json\nimport sys\nimport os\n\nfile = open(sys.argv[1], \"r\")\ntext = file.read()\n\nunicode_content = text.decode('utf-8')\nxml_content = unicode_content.encode('ascii', 'xmlcharrefreplace')\n\nblob = TextBlob(xml_content)\n\ntags_words = {}\n\nfor word, tag in blob.tags:\n\tif (tag in tags_words.keys()):\n\t\ttags_words[tag].append(word)\n\telse:\n\t\ttags_words[tag] = []\n\t\ttags_words[tag].append(word)\n\n\nwith open('tags_words.js', 'w') as outfile:\n data = json.dumps(tags_words)\n outfile.write(\"var tags_words = \" + data)\n\nprint(\"New file: \"+os.getcwd()+\"/tags_words.js\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"34689536","text":"import logging\nimport asyncio\nimport random\nfrom functools import reduce\nfrom migen import *\nfrom migen.genlib.fsm import FSM\nfrom migen.genlib.cdc import MultiReg\n\nfrom .. import *\nfrom ...gateware.pads import *\n\n\nCMD_W = 0x00\nCMD_OE = 0x01\nCMD_O = 0x02\nCMD_L = 0x03\nCMD_H = 0x04\nCMD_I = 0x05\n\n\nclass JTAGPinoutSubtarget(Module):\n def __init__(self, pins, out_fifo, in_fifo, period_cyc):\n jtag_oe = Signal(len(pins))\n jtag_o = Signal(len(pins))\n jtag_i = Signal(len(pins))\n self.comb += [\n Cat(pin.oe for pin in pins).eq(jtag_oe),\n Cat(pin.o for pin in pins).eq(jtag_o),\n ]\n self.specials += MultiReg(Cat(pin.i for pin in pins), jtag_i)\n\n timer = Signal(max=period_cyc)\n cmd = Signal(8)\n\n self.submodules.fsm = FSM(reset_state=\"RECV-COMMAND\")\n self.fsm.act(\"RECV-COMMAND\",\n If(out_fifo.readable,\n out_fifo.re.eq(1),\n NextValue(cmd, out_fifo.dout),\n If(out_fifo.dout == CMD_W,\n NextValue(timer, period_cyc - 1),\n NextState(\"WAIT\")\n ).Elif(out_fifo.dout == CMD_I,\n NextState(\"INPUT\")\n ).Else(\n NextState(\"RECV-DATA\")\n )\n )\n )\n self.fsm.act(\"RECV-DATA\",\n If(out_fifo.readable,\n out_fifo.re.eq(1),\n If(cmd == CMD_OE,\n NextValue(jtag_oe, out_fifo.dout)\n ).Elif(cmd == CMD_O,\n NextValue(jtag_o, out_fifo.dout)\n ).Elif(cmd == CMD_L,\n NextValue(jtag_o, ~out_fifo.dout & jtag_o)\n ).Elif(cmd == CMD_H,\n NextValue(jtag_o, out_fifo.dout | jtag_o)\n ),\n NextState(\"RECV-COMMAND\")\n )\n )\n self.fsm.act(\"WAIT\",\n If(timer == 0,\n NextState(\"RECV-COMMAND\")\n ).Else(\n NextValue(timer, timer - 1)\n )\n )\n self.fsm.act(\"INPUT\",\n If(in_fifo.writable,\n in_fifo.we.eq(1),\n in_fifo.din.eq(jtag_i),\n NextState(\"RECV-COMMAND\")\n )\n )\n\n\nclass JTAGPinoutApplet(GlasgowApplet, name=\"jtag-pinout\"):\n preview = True\n logger = logging.getLogger(__name__)\n help = \"automatically determine JTAG pinout\"\n description = \"\"\"\n Determine JTAG pin functions given a set of pins.\n \"\"\"\n\n @classmethod\n def add_build_arguments(cls, parser, access):\n super().add_build_arguments(parser, access)\n\n access.add_pin_set_argument(parser, \"jtag\", width=range(4, 9), required=True)\n\n parser.add_argument(\n \"-f\", \"--frequency\", metavar=\"FREQ\", type=int, default=10,\n help=\"set clock period to FREQ kHz (default: %(default)s)\")\n\n def build(self, target, args):\n self.mux_interface = iface = target.multiplexer.claim_interface(self, args)\n iface.add_subtarget(JTAGPinoutSubtarget(\n pins=[iface.get_pin(pin) for pin in args.pin_set_jtag],\n out_fifo=iface.get_out_fifo(),\n in_fifo=iface.get_in_fifo(),\n period_cyc=int(target.sys_clk_freq // (args.frequency * 1000)),\n ))\n\n self.pins = set(args.pin_set_jtag)\n self.pin_names = {pin: self.mux_interface.get_pin_name(pin) for pin in self.pins}\n\n async def run(self, device, args):\n return await device.demultiplexer.claim_interface(self, self.mux_interface, args)\n\n def _bits_to_pins(self, bits):\n pins = []\n for bit in range(len(self.pins)):\n if bits & (1 << bit):\n pins.append(bit)\n return pins\n\n def _pins_to_names(self, pins):\n return [self.pin_names[pin] for pin in pins]\n\n def _pins_to_str(self, pins):\n return \", \".join(self._pins_to_names(pins))\n\n async def _detect_pulls(self, iface):\n for o in (0x00, 0xff):\n await iface.write([\n CMD_O, o,\n CMD_OE, 0xff,\n CMD_W,\n CMD_OE, 0x00,\n CMD_W,\n CMD_I,\n ])\n after_low, after_high = await iface.read(2)\n\n high_z_pins = self._bits_to_pins(~after_low & after_high)\n pull_up_pins = self._bits_to_pins( after_low & after_high)\n pull_down_pins = self._bits_to_pins(~after_low & ~after_high)\n return high_z_pins, pull_up_pins, pull_down_pins\n\n @staticmethod\n def _x_tck(tck): return [CMD_L, tck, CMD_W, CMD_H, tck, CMD_W]\n\n @staticmethod\n def _x_tck_i_tdo(tck): return [CMD_L, tck, CMD_W, CMD_I, CMD_H, tck, CMD_W]\n\n async def _enter_shift_ir(self, iface, tck, tms, tdi, trst):\n pulse = self._x_tck(tck)\n await iface.write([\n CMD_O, tck|tms|tdi|trst,\n CMD_OE, tck|tms|tdi|trst,\n CMD_W,\n # Pulse TRST\n CMD_L, trst, CMD_W,\n CMD_H, trst, CMD_W,\n # Enter Test-Logic-Reset\n CMD_H, tms, *pulse * 5,\n # Enter Run-Test/Idle\n CMD_L, tms, *pulse,\n # Enter Shift-IR\n CMD_H, tms, *pulse,\n CMD_H, tms, *pulse,\n CMD_L, tms, *pulse,\n CMD_L, tms, *pulse,\n ])\n\n async def _detect_tdo(self, iface, tck, tms, trst=0):\n await self._enter_shift_ir(iface, tck=tck, tms=tms, tdi=0, trst=trst)\n\n pulse = self._x_tck_i_tdo(tck)\n await iface.write([\n # Shift IR\n *pulse * 2,\n # Release the bus\n CMD_OE, 0,\n ])\n\n ir_0, ir_1, *_ = await iface.read(2)\n tdo_pins = self._bits_to_pins(ir_0 & ~ir_1)\n return set(tdo_pins)\n\n async def _detect_tdi(self, iface, tck, tms, tdi, tdo, trst=0):\n await self._enter_shift_ir(iface, tck=tck, tms=tms, tdi=tdi, trst=trst)\n\n pat_bits = 32\n flush_bits = 64\n pattern = random.getrandbits(pat_bits)\n\n pulse = self._x_tck_i_tdo(tck)\n await iface.write([\n # Shift IR\n *sum(([CMD_H if pattern & (1 << bit) else CMD_L, tdi, *pulse]\n for bit in range(pat_bits)), []),\n CMD_H, tdi, *pulse * flush_bits,\n # Release the bus\n CMD_OE, 0,\n ])\n\n result = await iface.read(pat_bits + flush_bits)\n ir_lens = []\n for ir_len in range(flush_bits):\n corr_result = [result[ir_len + bit] if pattern & (1 << bit) else ~result[ir_len + bit]\n for bit in range(pat_bits)]\n if reduce(lambda x, y: x & y, corr_result) & tdo:\n ir_lens.append(ir_len)\n return ir_lens\n\n async def interact(self, device, args, iface):\n self.logger.info(\"detecting pull resistors\")\n high_z_pins, pull_up_pins, pull_down_pins = await self._detect_pulls(iface)\n if high_z_pins:\n self.logger.info(\"high-Z: %s\", self._pins_to_str(high_z_pins))\n if pull_up_pins:\n self.logger.info(\"pull-H: %s\", self._pins_to_str(pull_up_pins))\n if pull_down_pins:\n self.logger.info(\"pull-L: %s\", self._pins_to_str(pull_down_pins))\n\n if pull_down_pins and len(self.pins) > 4:\n self.logger.info(\"found pins with pull-downs, will probe TRST#\")\n elif len(self.pins) > 4:\n self.logger.info(\"no pins with pull-downs, not probing TRST#\")\n\n results = []\n for pin_trst in [None, *pull_down_pins]:\n if pin_trst is None:\n self.logger.info(\"detecting TCK, TMS and TDO\")\n pins = self.pins\n else:\n self.logger.info(\"detecting TCK, TMS and TDO with TRST#=%s\",\n self.pin_names[pin_trst])\n pins = self.pins - {pin_trst}\n\n tck_tms_tdo = []\n for pin_tck in pins:\n for pin_tms in pins - {pin_tck}:\n self.logger.debug(\"trying TCK=%s TMS=%s\",\n self.pin_names[pin_tck], self.pin_names[pin_tms])\n tdo_pins = await self._detect_tdo(iface, 1 << pin_tck, 1 << pin_tms,\n 1 << pin_trst if pin_trst else 0)\n for pin_tdo in tdo_pins - {pin_tck, pin_tms}:\n self.logger.info(\"shifted 10 out of IR with TCK=%s TMS=%s TDO=%s\",\n self.pin_names[pin_tck], self.pin_names[pin_tms],\n self.pin_names[pin_tdo])\n tck_tms_tdo.append((pin_tck, pin_tms, pin_tdo))\n\n if not tck_tms_tdo:\n continue\n\n self.logger.info(\"detecting TDI\")\n for (pin_tck, pin_tms, pin_tdo) in tck_tms_tdo:\n for pin_tdi in pins - {pin_tck, pin_tms, pin_tdo}:\n self.logger.debug(\"trying TCK=%s TMS=%s TDI=%s TDO=%s\",\n self.pin_names[pin_tck], self.pin_names[pin_tms],\n self.pin_names[pin_tdi], self.pin_names[pin_tdo])\n ir_lens = await self._detect_tdi(iface, 1 << pin_tck, 1 << pin_tms,\n 1 << pin_tdi, 1 << pin_tdo,\n 1 << pin_trst if pin_trst else 0)\n for ir_len in ir_lens:\n self.logger.info(\"shifted %d-bit IR with TCK=%s TMS=%s TDI=%s TDO=%s\",\n ir_len,\n self.pin_names[pin_tck], self.pin_names[pin_tms],\n self.pin_names[pin_tdi], self.pin_names[pin_tdo])\n results.append((pin_tck, pin_tms, pin_tdi, pin_tdo, pin_trst))\n else:\n continue\n\n if results:\n self.logger.info(\"JTAG interface detected, not probing TRST#\")\n break\n\n if len(results) == 0:\n self.logger.warning(\"no JTAG interface detected\")\n elif len(results) == 1:\n pin_tck, pin_tms, pin_tdi, pin_tdo, pin_trst = results[0]\n args = [\"jtag\"]\n args += [\"--pin-tck\", str(pin_tck)]\n args += [\"--pin-tms\", str(pin_tms)]\n args += [\"--pin-tdi\", str(pin_tdi)]\n args += [\"--pin-tdo\", str(pin_tdo)]\n if pin_trst is not None:\n args += [\"--pin-trst\", str(pin_trst)]\n self.logger.info(\"use `%s` as arguments\", \" \".join(args))\n else:\n self.logger.warning(\"more than one JTAG interface detected; this likely a false \"\n \"positive\")\n\n# -------------------------------------------------------------------------------------------------\n\nclass JTAGPinoutAppletTestCase(GlasgowAppletTestCase, applet=JTAGPinoutApplet):\n @synthesis_test\n def test_build(self):\n self.assertBuilds(args=[\"--pins-jtag\", \"0:3\"])\n","sub_path":"software/glasgow/applet/jtag_pinout/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":11127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"575736973","text":"import sys\nimport os\nimport argparse\nimport socket\nimport random\nimport struct\n\nfrom scapy.all import sendp, send, get_if_list, get_if_hwaddr\nfrom scapy.all import Packet\nfrom scapy.all import Ether, IP, IPv6, UDP, TCP\n\n\ndef get_if():\n \"\"\" \n Get the first network cards ID. \n \"\"\"\n ifs = get_if_list()\n iface = None\n\n for i in ifs:\n if 'eth0' in i:\n iface= i\n break\n if not iface:\n print(\"Cannot find eth0 interface\")\n exit(1)\n return iface\n\n\ndef take_ether(iface, bc=True, idst='ff:ff:ff:ff:ff:ff'):\n pkt = Ether(src=get_if_hwaddr(iface),dst=idst)\n return pkt\n\ndef take_IP():\n pass\n\ndef get_args():\n cwd = os.getcwd()\n default_logs = os.path.join(cwd, 'logs')\n parser = argparse.ArgumentParser()\n parser.add_argument('-p', '--protocol', help='Choose the transport layer protocol.',\n type=str, required=False, default='TCP')\n parser.add_argument('-l', '--log-dir', type=str,\n required=False, default=default_logs)\n return parser.parse_args()\n","sub_path":"send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"156743063","text":"\"\"\"\n 函数内存分布\n\"\"\"\n\n\n# 1. 将函数代码加载到内存中,函数体不执行.\ndef func01():\n a = 10\n print(\"func01执行了\")\n\n\n# 2. 调用函数时,在内存中开辟空间(栈帧),\n# 存储在函数内部创建的变量。\nfunc01()\n\n\n# 3. 函数执行后,栈帧立即释放.\n\n\ndef func02(p1, p2):\n # 修改栈帧中的变量\n p1 = 100\n # 修改传入的列表\n p2[0] = 200\n\n\ndata01 = 10\ndata02 = [20]\nfunc02(data01, data02)\nprint(data01) # 10\nprint(data02) # 200\n","sub_path":"day08/demo02.py","file_name":"demo02.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"628586942","text":"import numpy as np\nfrom typing import List\nfrom scipy.integrate import solve_ivp\n\nclass Simulator:\n\n def __init__(self, model, y0, parameters, args: tuple = (), integrator: str = \"RK45\"):\n self.model = model\n self.y0 = y0\n self.parameters = parameters\n self.args = args\n self.integrator = integrator\n\n def integrate(self, t: int, t_eval=None, parameters=None, y0=None, args: tuple=None):\n\n if t_eval is None:\n t_eval = np.linspace(0, t, t*2)\n if parameters is None:\n parameters = self.parameters\n if y0 is None:\n y0 = self.y0\n if args is None:\n args = self.args\n args = (parameters,) + args\n solution = solve_ivp(\n fun=self.model, y0=y0, args=args,\n t_span=(0, t), t_eval=t_eval, method=self.integrator\n )\n\n return (solution.t, solution.y)\n\n","sub_path":"scripts/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"557856747","text":"# coding:utf8\n\"\"\"\n 两个字符串的最小ASCII删除和\n 给定两个字符串s1, s2,找到使两个字符串相等所需删除字符的ASCII值的最小和。\n 示例 1:\n 输入: s1 = \"sea\", s2 = \"eat\"\n 输出: 231\n 解释: 在 \"sea\" 中删除 \"s\" 并将 \"s\" 的值(115)加入总和。\n 在 \"eat\" 中删除 \"t\" 并将 116 加入总和。\n 结束时,两个字符串相等,115 + 116 = 231 就是符合条件的最小和。\n 链接:https://leetcode-cn.com/problems/minimum-ascii-delete-sum-for-two-strings\n\"\"\"\nclass Solution:\n def minimumDeleteSum(self, s1: str, s2: str) -> int:\n return self.minimumDeleteSum_v1(s1, s2)\n\n def minimumDeleteSum_v1(self, s1: str, s2: str) -> int:\n memo = [[-1] * len(s2) for _ in range(len(s1))]\n def dp(s1: str, i: int, s2: str, j: int) -> int:\n res = 0\n if i == len(s1):\n for k in range(j, len(s2)):\n res += ord(s2[k])\n return res\n\n if j == len(s2):\n for k in range(i, len(s1)):\n res += ord(s1[k])\n return res\n\n if memo[i][j] != -1:\n return memo[i][j]\n\n if s1[i] == s2[j]: # 不用删\n memo[i][j] = dp(s1, i + 1, s2, j + 1)\n else: # 删其中一个\n memo[i][j] = min(ord(s1[i]) + dp(s1, i + 1, s2, j), \n ord(s2[j]) + dp(s1, i, s2, j + 1))\n\n return memo[i][j]\n return dp(s1, 0, s2, 0)\n\nif __name__ == '__main__':\n s1 = 'sea'\n s2 = 'eat'\n obj = Solution()\n print(obj.minimumDeleteSum(s1, s2))\n","sub_path":"suqing/fuckal/python/dp/minimum-ascii-delete-sum-for-two-strings.py","file_name":"minimum-ascii-delete-sum-for-two-strings.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"273168970","text":"import pandas\nfrom bokeh.plotting import figure\nfrom bokeh.io import output_file, show\n\np = figure(plot_width=800, plot_height=600, tools='pan')\n\ndf = pandas.read_excel('http://pythonhow.com/data/verlegenhuken.xlsx')\nx = df['Temperature'] / 10\ny = df['Pressure'] / 10\n\np.title.text='Temperature and Air Pressure'\np.title.text_color='Gray'\np.title.text_font='Arial'\np.title.text_font_style='bold'\n\np.xaxis.minor_tick_line_color=None\np.yaxis.minor_tick_line_color=None\n\np.xaxis.axis_label='Temperature (C)'\np.yaxis.axis_label='Pressure (hPa)'\n\np.circle(x, y, size=0.5)\noutput_file('temp_and_press.html')\nshow(p)\n","sub_path":"Python-mega-course-by-Ardit-Sulce/bokeh_visualization/weather_data.py","file_name":"weather_data.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"190752197","text":"import numpy as np\nimport pandas as pd\nimport random\nimport psycopg2\nimport matplotlib.pyplot as plt\n\n\ndef run_sql(query, type='get'):\n HOSTNAME = '127.0.0.1'\n USERNAME = 'postgres'\n PASSWORD = 'Lala1421'\n DATABASE = 'FifaHackathon'\n connection = psycopg2.connect(host=HOSTNAME, user=USERNAME, password=PASSWORD, dbname=DATABASE)\n cursor = connection.cursor()\n cursor.execute(query)\n connection.commit()\n if type == 'get':\n results = cursor.fetchall()\n connection.close()\n return results\n connection.close()\n\n\ndata = pd.read_csv('players_21.csv')\nplaying = True\nprint('Welcome to the Fifa21 match simulator!')\nfirst_round = True\nwhile playing:\n\n if first_round:\n query = \"insert into num_of_seasons(name) values('new season')\"\n run_sql(query, 'post')\n first_round = False\n query = \"select season from num_of_seasons order by season desc limit 1\"\n season_num, = run_sql(query)[0]\n query = f\"create table season_games{season_num} (game_id serial primary key, team1 varchar not null, team2 varchar not null, team1_scored int, team2_scored int, points_team1 int, points_team2 int )\"\n run_sql(query, 'post')\n\n print('Please select an options from the list below:')\n user_input = ''\n while (user_input != '1' and user_input != '2' and user_input != '3'):\n print('(1) Instructions')\n print('(2) Select 2 teams')\n print('(3) Finish the season')\n user_input = input('Enter your choise: ')\n\n if user_input == '1':\n print('Hello and welcome to the Fifa21 match simulator!')\n print(\n '''\n This match making and result predicting ability\n are based on a Fifa21 players database\n and an algorithm of score prediction.''')\n print('You are going to select 2 teams to your liking, and the computer is going to simulate the match.')\n print('The scores are sent to a database and the champions are crowned based on their previous results.')\n print('Without further ado, let the season begin!')\n elif user_input == '2':\n\n team1_name = input('Enter team 1 name: ')\n # picks the info about the players from the club\n club1_info = data[data['club_name'] == team1_name]\n\n # picks starting 11 out of the best players in the club (to be improved)\n # starting_players1 = club1_info.sort_values(by='overall', ascending=False).head(11)\n\n best_def_info1 = club1_info.sort_values(by='defending', ascending=False).head(5)\n def_mean1 = best_def_info1['defending'].mean()\n\n best_att_info1 = club1_info.sort_values(by='shooting', ascending=False).head(5)\n att_mean1 = best_att_info1['shooting'].mean()\n\n # their rating\n # best_team1_rating = starting_players1['overall'].sum()\n\n\n team2_name = input('Enter team 2 name: ')\n # picks the info about the players from the club\n club2_info = data[data['club_name'] == team2_name]\n\n # picks starting 11 out of the best players in the club (to be improved)\n # starting_players2 = club2_info.sort_values(by='overall', ascending=False).head(11)\n\n best_def_info2 = club2_info.sort_values(by='defending', ascending=False).head(5)\n def_mean2 = best_def_info2['defending'].mean()\n\n best_att_info2 = club2_info.sort_values(by='shooting', ascending=False).head(5)\n att_mean2 = best_att_info2['shooting'].mean()\n\n # their rating\n # best_team2_rating = starting_players2['overall'].sum()\n\n # first model of score predicting\n # if best_team1_rating > best_team2_rating:\n # team1_chance = best_team1_rating + (best_team1_rating - best_team2_rating) * 5\n # team2_chance = best_team2_rating - (best_team1_rating - best_team2_rating) * 5\n # elif best_team1_rating < best_team2_rating:\n # team1_chance = best_team1_rating - (best_team2_rating - best_team1_rating) * 5\n # team2_chance = best_team2_rating + (best_team2_rating - best_team1_rating) * 5\n # else:\n # team1_chance = best_team1_rating\n # team2_chance = best_team2_rating\n\n # match = [team1_name, team2_name]\n\n # winner = random.choices(match, weights=(team1_chance, team2_chance))[0]\n\n # if winner == team1_name:\n # loser = team2_name\n # else:\n # loser = team1_name\n\n # print(f'The winner is {winner}!')\n\n # Second Score predicrtion model:\n match = [team1_name, team2_name]\n # calculate the ratio between the attack end the defence\n team1_scored = att_mean1 ** 6 / def_mean2\n team2_scored = att_mean2 ** 6 / def_mean1\n\n # calculating the average goals for team1\n prob_team1_scored = team1_scored / (team1_scored + team2_scored)\n # calculating the average goals for team2\n prob_team2_scored = team2_scored / (team1_scored + team2_scored)\n\n # randomly choosing a goals number for each team around their predicted average goals\n goals_team1 = np.random.poisson(int((prob_team1_scored) * 5), 5)[0]\n goals_team2 = np.random.poisson(int((prob_team2_scored) * 5), 5)[0]\n\n # print(f'Real Madrid scored: {goals_team1}')\n #\n # print(f'Genoa scored: {goals_team2}')\n # Who is the winner?\n if goals_team1 > goals_team2:\n points_team1 = 3\n points_team2 = 0\n elif goals_team2 > goals_team1:\n points_team2 = 3\n points_team1 = 0\n else:\n points_team1 = 1\n points_team2 = 1\n\n query = f\"insert into season_games{season_num}(team1, team2, team1_scored, team2_scored, team1_points, team2_points) values ('{team1_name}', '{team2_name}', {goals_team1}, {goals_team2}, {points_team1}, {points_team2})\"\n run_sql(query, 'post')\n\n if user_input == '3':\n query = f\"create table season_rank{season_num} (loc_id serial primary key, team varchar not null, points int not null)\"\n run_sql(query, 'post')\n\n query = f\"select distinct winner from season_games{season_num}\"\n winners = run_sql(query)\n list_winners = []\n\n for win in winners:\n (rw,) = win\n list_winners.append(rw, )\n\n query = f\"select distinct loser from season_games{season_num}\"\n losers = run_sql(query)\n list_losers = []\n\n for loss in losers:\n (rl,) = loss\n list_losers.append(rl, )\n\n for i in list_winners:\n query = f\"select count(winner) from season_games{season_num} where winner='{i}'\"\n winner_points, = run_sql(query)[0]\n query = f\"insert into season_rank{season_num}(team, points) values ('{i}',{winner_points * 3})\"\n run_sql(query, 'post')\n\n for j in list_losers:\n if j not in list_winners:\n query = f\"insert into season_rank{season_num}(team, points) values ('{j}', 0)\"\n run_sql(query, 'post')\n\n query = f\"select team,points from season_rank{season_num} order by points desc\"\n table = run_sql(query)\n print('location (Team, Points)')\n print('--------------------')\n for index, place in enumerate(table):\n print(index+1, place)\n print('--------------------')\n\n query = f\"select team from season_rank{season_num} order by points desc limit 1\"\n champions = run_sql(query)[0]\n print(f'{champions} are the CHAMPIONS of the season!')\n\n list_winners = []\n list_losers = []\n playing = False\n\n\n\n\n# team1_name = 'Real Madrid'\n# # picks the info about the players from the club\n# club1_info = data[data['club_name'] == team1_name]\n#\n# # picks starting 11 out of the best players in the club (to be improved)\n# starting_players1 = club1_info.sort_values(by='overall', ascending=False).head(11)\n#\n# # their rating\n# best_team1_rating = starting_players1['overall'].sum()\n#\n# print(best_team1_rating)\n#\n# team2_name = 'Genoa'\n# # picks the info about the players from the club\n# club2_info = data[data['club_name'] == team2_name]\n#\n# # picks starting 11 out of the best players in the club (to be improved)\n# starting_players2 = club2_info.sort_values(by='overall', ascending=False).head(11)\n#\n# # their rating\n# best_team2_rating = starting_players2['overall'].sum()\n#\n# print(best_team2_rating)\n#\n# # first model of score predicting\n# # sum_ratings = best_team1_rating + best_team2_rating\n# if best_team1_rating > best_team2_rating:\n# team1_chance = best_team1_rating + (best_team1_rating - best_team2_rating)*5\n# team2_chance = best_team2_rating - (best_team1_rating - best_team2_rating)*5\n# elif best_team1_rating < best_team2_rating:\n# team1_chance = best_team1_rating - (best_team2_rating - best_team1_rating)*5\n# team2_chance = best_team2_rating + (best_team2_rating - best_team1_rating)*5\n# else:\n# team1_chance = best_team1_rating\n# team2_chance = best_team2_rating\n#\n# # team1_chance = best_team1_rating *\n# # team2_chance = best_team2_rating *\n#\n# print(f'{team1_name} chance: {team1_chance/(team1_chance+team2_chance)}')\n# print(f'{team2_name} chance: {team2_chance/(team1_chance+team2_chance)}')\n#\n# match = [team1_name, team2_name]\n# winners = []\n# for i in range(100):\n# winner = random.choices(match, weights=(team1_chance, team2_chance))[0]\n# winners.append(winner)\n#\n# print(f'{team1_name} wins: {winners.count(team1_name)}%')\n# print(f'{team2_name} wins: {winners.count(team2_name)}%')\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":9571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"270420898","text":"from django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.db.models import Q\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.views.generic import ListView\n\nfrom .forms import FilterAuditiForm, AuditKinerjaForm, SuratTugasFilter\nfrom .models import Auditee, Assignment, AssignmentAuditee\n\n\ndef index(req):\n return render(req, 'siau/index.html')\n\n\nclass Rekap(LoginRequiredMixin, ListView):\n INSPEKTORAT = (\n ('3d76fa9f0bb3d72f33d775fbd4529f44031c824e', 'Inspektorat I',),\n ('2b2d9dad563c8b6a800cfc47579c6fa0928ef8b9', 'Inspektorat II',),\n ('3b0761f74ec705e9b72ea6053e3930a3c8294ef4', 'Inspektorat III',),\n ('71901349bb3fac3edc6887c3d5c3676ca5f954ad', 'Inspektorat IV',),\n )\n\n page_kwarg = 'halaman'\n paginate_by = 10\n template_name = 'siau/rekap.html'\n param_id = None\n inspektorat_id = ''\n provinsi = ''\n subsektor = ''\n jenis_kegiatan = ''\n tahun = ''\n cari = ''\n param_filter = ''\n filter_form = None\n\n def setup(self, request, *args, **kwargs):\n super().setup(request, *args, **kwargs)\n\n title = grid_header = grid_object = None\n param_id = kwargs.get('param_id')\n\n all_tahun_st = Assignment.objects.order_by('-assign_tahun').values_list('assign_tahun', flat=True).distinct()\n if 'tahun_st' not in kwargs and param_id != 'st':\n tahun_st = all_tahun_st[0]\n else:\n tahun_st = kwargs.get('tahun_st')\n\n inspektorat_id = ''\n if 'inspektorat_id' in kwargs:\n if kwargs.get('inspektorat_id') in list(i[0] for i in self.INSPEKTORAT):\n inspektorat_id = kwargs.get('inspektorat_id')\n\n if param_id == 'auditi':\n title = 'Daftar Auditi'\n grid_header = ('Kode', 'Auditi', 'Provinsi', 'Eselon I', 'Inspektorat',)\n grid_object = 'siau/grid_auditi.html'\n self.queryset = Auditee.objects.all()\n self.filter_form = FilterAuditiForm\n elif param_id == 'st':\n title = 'Daftar Surat Tugas'\n grid_header = ('Nomor', 'Tanggal', 'Jenis Kegiatan', 'Auditi', 'Inspektorat',)\n grid_object = 'siau/grid_st.html'\n qs = Assignment.objects\\\n .order_by('-assignment_st__assign_surat_tgl', '-assignment_st__assign_surat_no')\\\n .exclude(assignment_st__assign_surat_id__isnull=True)\n self.queryset = qs\n self.filter_form = SuratTugasFilter()\n # elif param_id == 'kin':\n # title = 'Audit Kinerja'\n # grid_header = ('Nomor ST', 'Nomor SPL', 'Auditi', 'Inspektorat', 'PKA', 'KKA', 'NHA', 'LHA')\n # grid_object = 'siau/grid_kin.html'\n # qs = AssignmentAuditee.objects.exclude(\n # assign_auditee_id_auditee=''\n # ).filter(\n # assign_auditee_id_assign__assign_jenis_kegiatan=1\n # ).order_by('-assign_auditee_id_assign__assignment_st__assign_surat_tgl',\n # '-assign_auditee_id_assign__assignment_st__assign_surat_no', )\n # self.queryset = qs\n # self.filter_form = AuditKinerjaForm()\n elif param_id == 'audit' and inspektorat_id != '':\n title = 'Jumlah Item Audit Kinerja'\n grid_header = ('Nomor ST', 'Nomor SPL', 'Auditi', 'Prosedur PKA', 'Item KKA', 'Temuan NHA', 'Temuan LHA')\n grid_object = 'siau/grid_kin.html'\n qs = AssignmentAuditee.objects.exclude(\n assign_auditee_id_auditee=''\n ).filter(\n assign_auditee_id_assign__assign_jenis_kegiatan=1,\n assign_auditee_id_assign__assign_tahun=tahun_st,\n assign_auditee_id_auditee__auditee_inspektorat=inspektorat_id,\n ).order_by('-assign_auditee_id_assign__assignment_st__assign_surat_tgl',\n '-assign_auditee_id_assign__assignment_st__assign_surat_no', )\n\n self.inspektorat_id = kwargs.get('inspektorat_id')\n self.queryset = qs\n self.filter_form = AuditKinerjaForm(initial={'inspektorat': kwargs.get('inspektorat_id')})\n elif param_id == 'audit':\n title = 'Jumlah Auditi Dalam Audit Kinerja'\n grid_header = ('Inspektorat', 'ST', 'PKA', 'KKA', 'NHA', 'LHA',)\n grid_object = 'siau/grid_audit.html'\n qs = list()\n for inspektorat in self.INSPEKTORAT:\n assignment_auditi = AssignmentAuditee.objects.filter(\n assign_auditee_id_auditee__auditee_inspektorat=inspektorat[0],\n assign_auditee_id_auditee__auditee_del_st=1,\n assign_auditee_id_assign__assign_tahun=tahun_st,\n assign_auditee_id_assign__assign_jenis_kegiatan=1,\n )\n\n jml_auditi = assignment_auditi.count()\n\n pka = assignment_auditi.filter(assign_auditee_id_assign__assignment_pka__program_status=4, )\n jml_auditi_with_pka = pka.order_by('assign_auditee_id_auditee').values(\n 'assign_auditee_id_auditee').distinct().count()\n jml_auditi_with_kka = pka.filter(\n assign_auditee_id_assign__assignment_pka__pka_ke_kka__kertas_kerja_status=6).order_by(\n 'assign_auditee_id_auditee').values('assign_auditee_id_auditee').distinct().count()\n\n jml_auditi_with_nha = assignment_auditi.filter(\n assign_auditee_id_assign__assignment_nha__nha_finding__finding_status=8\n ).order_by('assign_auditee_id_auditee').values('assign_auditee_id_auditee').distinct().count()\n\n jml_auditi_with_lha = assignment_auditi.exclude(\n assign_auditee_id_auditee__exact=''\n ).filter(\n assign_auditee_id_assign__assignment_attachment__lha_attach_id_auditee__auditee_del_st=1\n ).order_by('assign_auditee_id_auditee').values_list('assign_auditee_id_auditee').distinct().count()\n\n data_inspektorat = {\n 'id': inspektorat[0],\n 'nama': inspektorat[1],\n 'auditi_st': jml_auditi,\n 'auditi_pka': jml_auditi_with_pka,\n 'auditi_kka': jml_auditi_with_kka,\n 'auditi_nha': jml_auditi_with_nha,\n 'auditi_lha': jml_auditi_with_lha,\n }\n qs.append(data_inspektorat)\n\n self.queryset = qs\n self.filter_form = None\n elif param_id == 'reviu':\n title = 'Rekap Reviu Per Inspektorat'\n grid_header = ('Inspektorat', 'ST', 'PKR', 'KKR', ' CHR',)\n grid_object = 'siau/grid_reviu.html'\n qs = list()\n for inspektorat in self.INSPEKTORAT:\n assignment_auditi = AssignmentAuditee.objects.exclude(\n assign_auditee_id_assign__assign_jenis_kegiatan=1\n ).filter(\n assign_auditee_id_auditee__auditee_inspektorat=inspektorat[0],\n assign_auditee_id_auditee__auditee_del_st=1,\n assign_auditee_id_assign__assign_tahun=tahun_st,\n )\n jml_auditi = assignment_auditi.count()\n\n pkr_lk = assignment_auditi.filter(\n assign_auditee_id_assign__assign_jenis_kegiatan=3,\n assign_auditee_id_assign__assignment_pkr__previu_status=2,\n ).order_by('assign_auditee_id_auditee').values('assign_auditee_id_auditee').distinct().count()\n\n pkr_dalnis = assignment_auditi.exclude(\n assign_auditee_id_assign__assign_jenis_kegiatan=3\n ).filter(\n assign_auditee_id_assign__assignment_auditor__assign_auditor_id_posisi__posisi_sort=3,\n assign_auditee_id_assign__assignment_pkr__previu_status=2,\n ).order_by('assign_auditee_id_auditee').values('assign_auditee_id_auditee').distinct().count()\n\n pkr_daltu = assignment_auditi.exclude(\n assign_auditee_id_assign__assign_jenis_kegiatan=3\n ).filter(\n assign_auditee_id_assign__assignment_auditor__assign_auditor_id_posisi__posisi_sort=2,\n assign_auditee_id_assign__assignment_pkr__previu_status=4,\n ).order_by('assign_auditee_id_auditee').values('assign_auditee_id_auditee').distinct().count()\n\n kkr_dalnis = assignment_auditi.exclude(\n assign_auditee_id_assign__assignment_auditor__assign_auditor_id_posisi__posisi_sort=2,\n ).filter(\n assign_auditee_id_assign__assignment_auditor__assign_auditor_id_posisi__posisi_sort=3,\n assign_auditee_id_assign__assignment_kkr__kkr_status=4,\n ).order_by('assign_auditee_id_auditee').values('assign_auditee_id_auditee').distinct().count()\n kkr_daltu = assignment_auditi.filter(\n assign_auditee_id_assign__assignment_auditor__assign_auditor_id_posisi__posisi_sort=2,\n assign_auditee_id_assign__assignment_kkr__kkr_status=6,\n ).order_by('assign_auditee_id_auditee').values('assign_auditee_id_auditee').distinct().count()\n\n chr_dalnis = assignment_auditi.exclude(\n assign_auditee_id_assign__assignment_auditor__assign_auditor_id_posisi__posisi_sort=2,\n ).filter(\n assign_auditee_id_assign__assignment_auditor__assign_auditor_id_posisi__posisi_sort=3,\n assign_auditee_id_assign__assignment_chr__chr_status=2,\n ).order_by('assign_auditee_id_auditee').values('assign_auditee_id_auditee').distinct().count()\n chr_daltu = assignment_auditi.filter(\n assign_auditee_id_assign__assignment_auditor__assign_auditor_id_posisi__posisi_sort=2,\n assign_auditee_id_assign__assignment_chr__chr_status=4,\n ).order_by('assign_auditee_id_auditee').values('assign_auditee_id_auditee').distinct().count()\n\n data_inspektorat = {\n 'nama': inspektorat[1],\n 'auditi_reviu': jml_auditi,\n 'auditi_pkr': pkr_lk + pkr_dalnis + pkr_daltu,\n 'auditi_kkr': kkr_dalnis + kkr_daltu,\n 'auditi_chr': chr_dalnis + chr_daltu,\n }\n qs.append(data_inspektorat)\n\n self.queryset = qs\n self.filter_form = None\n\n self.param_id = param_id\n # self.tahun = tahun_st\n self.inspektorat_id = inspektorat_id\n\n self.extra_context = {\n 'titleKey': title,\n 'gridHeaderKey': grid_header,\n 'gridObjectKey': grid_object,\n 'paramKey': param_id,\n 'filterKey': self.filter_form,\n 'tahunKey': all_tahun_st,\n 'tahunStKey': tahun_st,\n 'inspektoratKey': inspektorat_id,\n }\n\n def get_queryset(self):\n get_provinsi = self.request.GET.get('provinsi', '')\n provinsi = None if get_provinsi == '' else get_provinsi\n\n get_subsektor = self.request.GET.get('subsektor', '')\n subsektor = None if get_subsektor == '' else get_subsektor\n\n get_jenis_kegiatan = self.request.GET.get('jenis_kegiatan', '')\n jenis_kegiatan = None if get_jenis_kegiatan == '' else get_jenis_kegiatan\n\n get_inspektorat = self.request.GET.get('inspektorat', '')\n inspektorat = None if get_inspektorat == '' else get_inspektorat\n\n get_tahun = self.request.GET.get('tahun', '')\n tahun = None if get_tahun == '' else get_tahun\n\n cari = self.request.GET.get('cari', '')\n\n qs = list() if self.queryset is None else self.queryset\n\n if self.param_id == 'auditi':\n if 'provinsi' in self.request.GET:\n self.param_filter = 'provinsi=' + get_provinsi\n\n qs = qs.filter(Q(auditee_kode__icontains=cari) |\n Q(auditee_name__icontains=cari))\n\n if inspektorat is not None:\n qs = qs.filter(auditee_inspektorat=inspektorat)\n if provinsi is not None:\n qs = qs.filter(auditee_propinsi=provinsi)\n if subsektor is not None:\n qs = qs.filter(auditee_esselon=subsektor)\n\n elif self.param_id == 'audit' and self.inspektorat_id != '':\n tahun = self.kwargs.get('tahun_st')\n get_inspektorat = self.kwargs.get('inspektorat_id', '')\n\n qs = AssignmentAuditee.objects.exclude(\n assign_auditee_id_auditee=''\n ).filter(\n assign_auditee_id_assign__assign_jenis_kegiatan=1,\n assign_auditee_id_auditee__auditee_inspektorat=self.inspektorat_id,\n ).order_by('-assign_auditee_id_assign__assignment_st__assign_surat_tgl',\n '-assign_auditee_id_assign__assignment_st__assign_surat_no', )\n if tahun is not None:\n qs = qs.filter(assign_auditee_id_assign__assign_tahun=tahun)\n if subsektor is not None:\n qs = qs.filter(assign_auditee_id_auditee__auditee_esselon=subsektor)\n if provinsi is not None:\n qs = qs.filter(assign_auditee_id_auditee__auditee_propinsi=provinsi)\n\n elif self.param_id == 'st':\n if 'jenis_kegiatan' in self.request.GET:\n self.param_filter = 'jenis_kegiatan=' + get_jenis_kegiatan + '&tahun=' + get_tahun\n\n qs = qs.filter(Q(assignment_st__assign_surat_no__icontains=cari) |\n Q(assignment_auditi__assign_auditee_id_auditee__auditee_name__icontains=cari)).distinct()\n\n if jenis_kegiatan is not None:\n qs = qs.filter(assign_jenis_kegiatan=jenis_kegiatan)\n if inspektorat is not None:\n qs = qs.filter(assignment_auditi__assign_auditee_id_auditee__auditee_inspektorat=inspektorat)\n if subsektor is not None:\n qs = qs.filter(assignment_auditi__assign_auditee_id_auditee__auditee_esselon=subsektor)\n if tahun is not None:\n qs = qs.filter(assignment_auditi__assign_auditee_id_assign__assign_tahun=tahun)\n\n if 'cari' in self.request.GET:\n self.param_filter += '&inspektorat=' + get_inspektorat + \\\n '&subsektor=' + get_subsektor + \\\n '&cari=' + cari + \\\n '&'\n\n self.provinsi = get_provinsi\n self.subsektor = get_subsektor\n self.jenis_kegiatan = get_jenis_kegiatan\n self.inspektorat_id = get_inspektorat\n self.tahun = get_tahun\n self.cari = cari\n return qs\n\n def get_context_data(self, *args, **kwargs):\n cx = super().get_context_data(*args, **kwargs)\n if self.param_id == 'auditi':\n self.filter_form = FilterAuditiForm({'inspektorat': self.inspektorat_id,\n 'provinsi': self.provinsi,\n 'subsektor': self.subsektor,\n 'cari': self.cari, })\n elif self.param_id == 'st':\n self.filter_form = SuratTugasFilter({'inspektorat': self.inspektorat_id,\n 'subsektor': self.subsektor,\n 'jenis_kegiatan': self.jenis_kegiatan,\n 'tahun': self.tahun,\n 'cari': self.cari, })\n elif self.param_id == 'audit' and self.inspektorat_id != '':\n self.filter_form = AuditKinerjaForm({'provinsi': self.provinsi,\n 'subsektor': self.subsektor,\n 'tahun': self.tahun,\n 'inspektorat': self.inspektorat_id,\n 'cari': self.cari, })\n\n cx['paramFilterKey'] = self.param_filter\n cx['filterKey'] = self.filter_form\n\n return cx\n","sub_path":"kepegawaian/siau/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"610799955","text":"import logging\nimport queue\nfrom socket import socket\nfrom time import sleep\nfrom unittest.mock import Mock, call\n\nimport pytest\n\nfrom pyhomeworks import Homeworks\nfrom .device import HomeworksDevice\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\nclass Buffer:\n def __init__(self):\n self._queue = queue.Queue()\n self._buffer = b''\n\n def recv(self, bytes_len):\n if len(self._buffer) < bytes_len:\n try:\n data = self._queue.get_nowait()\n if len(data):\n self._buffer += data\n except queue.Empty:\n pass\n\n out = self._buffer[:bytes_len]\n self._buffer = self._buffer[len(out):]\n return out\n\n def put(self, data: bytes):\n self._queue.put_nowait(data)\n\n\n@pytest.fixture\ndef hw_device(in_buffer, mocker):\n device = HomeworksDevice(on_send=in_buffer.put)\n mocker.spy(device, 'receive')\n mocker.spy(device, 'send')\n return device\n\n\n@pytest.fixture\ndef in_buffer():\n return Buffer()\n\n\n@pytest.fixture()\ndef lib(mocker, socket_mock):\n mocker.patch(\"socket.create_connection\").return_value = socket_mock\n mocker.patch(\"select.select\").return_value = ([1], 0, 0)\n\n return Homeworks('127.0.0.1', 4003, dummy_callback, autostart=False)\n\n\n@pytest.fixture()\ndef lib_with_login(mocker, socket_mock):\n mocker.patch(\"socket.create_connection\").return_value = socket_mock\n mocker.patch(\"select.select\").return_value = ([1], 0, 0)\n\n return Homeworks('127.0.0.1', 4003, dummy_callback, login=\"user,password\", autostart=False)\n\n\n@pytest.fixture\ndef socket_mock(in_buffer, hw_device: HomeworksDevice):\n sm = Mock(spec_set=socket)\n sm.fileno.return_value = 0\n sm.recv.side_effect = in_buffer.recv\n sm.send.side_effect = hw_device.receive\n\n return sm\n\n\ndef dummy_callback(data):\n print(data)\n\n\ndef test_connect_without_login(hw_device, lib, socket_mock):\n try:\n hw_device.start()\n lib.start()\n\n sleep(0.2)\n except Exception:\n raise\n\n finally:\n lib.close()\n lib.join(1)\n hw_device.stop()\n hw_device.join(1)\n\n assert_subscribe(hw_device, socket_mock)\n\n\ndef assert_subscribe(hw_device, socket_mock):\n socket_mock.send.assert_any_call(b'PROMPTOFF\\r\\n')\n socket_mock.send.assert_any_call(b'KBMON\\r\\n')\n socket_mock.send.assert_any_call(b'GSMON\\r\\n')\n socket_mock.send.assert_any_call(b'DLMON\\r\\n')\n socket_mock.send.assert_any_call(b'KLMON\\r\\n')\n hw_device.send.assert_any_call(b'Keypad button monitoring enabled')\n hw_device.send.assert_any_call(b'GrafikEye scene monitoring enabled')\n hw_device.send.assert_any_call(b'Dimmer level monitoring enabled')\n hw_device.send.assert_any_call(b'Keypad led monitoring enabled')\n\n\ndef test_connect_with_login(hw_device, lib_with_login, socket_mock):\n hw_device.require_login = 'user,password'\n try:\n hw_device.start()\n lib_with_login.start()\n\n sleep(0.2)\n except Exception:\n raise\n\n finally:\n lib_with_login.close()\n lib_with_login.join(1)\n hw_device.stop()\n hw_device.join(1)\n\n assert_login(hw_device)\n assert_subscribe(hw_device, socket_mock)\n\n\ndef assert_login(hw_device):\n assert hw_device.send.call_args_list[0] == call(b'LOGIN: ', line_ending=False)\n assert hw_device.receive.call_args_list[0] == call(b'user,password\\r\\n')","sub_path":"tests/test_homeworks.py","file_name":"test_homeworks.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"573910325","text":"import pygame.font\n\nclass Button():\n\tdef __init__(self,ai_settings,screen,msg):\n\t\t#设置按钮的属性\n\t\tself.screen = screen\n\t\tself.screen_rect = self.screen.get_rect()\n\t\t\n\t\t#设置按钮大小等其他属性\n\t\tself.width,self.height =200,50\n\t\tself.button_color = (0,255,0) #按键的颜色\n\t\tself.text_color = (255,255,255) #字体的颜色\n\t\tself.font = pygame.font.SysFont(None,48) #字体设置\n\t\t\n\t\t#创建按钮的rect对象,并使其居中\n\t\tself.rect = pygame.Rect(0,0,self.width,self.height)\n\t\tself.rect.center = self.screen_rect.center\n\t\t\n\t\t#按钮的标签只需创建一次\n\t\tself.prep_msg(msg)\n\t\n\tdef prep_msg(self,msg):\n\t\t#将msg'渲染为图像,并使其在按钮上居中\n\t\tself.msg_image = self.font.render(msg,True,self.text_color,self.button_color)\n\t\tself.msg_image_rect = self.msg_image.get_rect()\n\t\tself.msg_image_rect.center = self.rect.center\n\t\n\tdef draw_button(self):\n\t\tself.screen.fill(self.button_color,self.rect)\n\t\tself.screen.blit(self.msg_image,self.msg_image_rect)\n","sub_path":"button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"164626893","text":"import discord\nfrom discord.ext import commands\nimport logging\nimport asyncio\nimport sys\n\n# to load extentions\nsys.path.insert(0, './extension')\n\n# Necessary to track warning/errors\nlogger = logging.getLogger('discord')\nlogger.setLevel(logging.INFO)\nhandler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')\nhandler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))\nlogger.addHandler(handler)\n\nbot = commands.Bot(command_prefix='!')\n\n@bot.event\nasync def on_ready():\n print('Logged in as:')\n print(bot.user.name)\n print(bot.user.id)\n\n@bot.event\nasync def on_message(message):\n # A way of manually making your bot to respond to certain things (no prefix required)\n if message.content.startswith('Hello'):\n await bot.send_message(message.channel, 'Greetings')\n # Makes your bot process commands by users!\n await bot.process_commands(message)\n\n@bot.command()\nasync def load(extension_name : str):\n try:\n bot.load_extension(extension_name)\n except (AttributeError, ImportError) as e:\n await bot.say(\"```py\\n{}: {}\\n```\".format(type(e).__name__, str(e)))\n return\n await bot.say(\"{} loaded.\".format(extension_name))\n\nbot.run(\"TOKEN_HERE\")","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"493207941","text":"import unittest\nfrom functools import reduce\n\nfrom symbolchain.core.CryptoTypes import PublicKey, Signature\nfrom symbolchain.core.nem.Network import Address, Network\nfrom symbolchain.core.nem.TransactionFactory import TransactionFactory\n\nfrom ...test.NemTestUtils import NemTestUtils\n\nFOO_NETWORK = Network('foo', 0x54)\n\n\nclass MockTransaction:\n def __init__(self, buffer):\n self.buffer = buffer\n\n def serialize(self):\n return self.buffer\n\n\nclass TransactionFactoryTest(unittest.TestCase):\n # region create\n\n def test_can_create_known_transaction_from_descriptor(self):\n # Arrange:\n for transaction_name, transaction_type in [('transfer', 0x0101), ('importance-transfer', 0x0801)]:\n factory = TransactionFactory(FOO_NETWORK)\n\n # Act:\n transaction = factory.create({'type': transaction_name})\n\n # Assert:\n self.assertEqual(transaction_type, transaction.type)\n self.assertEqual(0x54000001, transaction.version)\n\n def test_cannot_create_unknown_transaction_from_descriptor(self):\n # Arrange:\n factory = TransactionFactory(FOO_NETWORK)\n\n # Act + Assert:\n with self.assertRaises(ValueError):\n factory.create({'type': 'multisig'})\n\n def test_can_create_known_transaction_with_multiple_overrides(self):\n # Arrange:\n factory = TransactionFactory(FOO_NETWORK, {\n Address: lambda address: address + ' ADDRESS',\n PublicKey: lambda address: address + ' PUBLICKEY'\n })\n\n # Act:\n transaction = factory.create({\n 'type': 'transfer',\n 'signer_public_key': 'signer_name',\n 'deadline': 98765 + 24 * 60 * 60,\n 'recipient_address': 'recipient_name',\n 'message': 'hello world',\n })\n\n # Assert:\n self.assertEqual(0x0101, transaction.type)\n self.assertEqual(0x54000001, transaction.version)\n self.assertEqual(98765, transaction.timestamp)\n self.assertEqual('signer_name PUBLICKEY', transaction.signer_public_key)\n\n self.assertEqual('recipient_name ADDRESS', transaction.recipient_address)\n self.assertEqual(b'hello world', transaction.message)\n\n # endregion\n\n # region attach_signature\n\n def test_can_attach_signature_to_transaction(self):\n # Arrange:\n transaction = MockTransaction(bytes([0x44, 0x55, 0x98, 0x12, 0x71, 0xAB, 0x72]))\n signature = NemTestUtils.randcryptotype(Signature)\n\n # Act:\n signed_transaction_buffer = TransactionFactory.attach_signature(transaction, signature)\n\n # Assert:\n expected_buffers = [\n [0x07, 0x00, 0x00, 0x00], # transaction length\n [0x44, 0x55, 0x98, 0x12, 0x71, 0xAB, 0x72], # transaction\n [0x40, 0x00, 0x00, 0x00], # signature length\n signature.bytes # signature\n ]\n expected_buffer = reduce(lambda x, y: bytes(x) + bytes(y), expected_buffers)\n self.assertEqual(expected_buffer, signed_transaction_buffer)\n\n # endregion\n","sub_path":"tests/core/nem/test_TransactionFactory.py","file_name":"test_TransactionFactory.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"223167483","text":"\"\"\"\nThe tool to check the availability or syntax of domain, IP or URL.\n\n::\n\n\n ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗\n ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝\n ██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗\n ██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝\n ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗\n ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝\n\nTests of our IP availability checker.\n\nAuthor:\n Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom\n\nSpecial thanks:\n https://pyfunceble.github.io/special-thanks.html\n\nContributors:\n https://pyfunceble.github.io/contributors.html\n\nProject link:\n https://github.com/funilrys/PyFunceble\n\nProject documentation:\n https://pyfunceble.readthedocs.io/en/dev/\n\nProject homepage:\n https://pyfunceble.github.io/\n\nLicense:\n::\n\n\n Copyright 2017, 2018, 2019, 2020, 2022, 2023 Nissar Chababy\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nimport unittest\nimport unittest.mock\nfrom datetime import datetime\n\nfrom PyFunceble.checker.availability.ip import IPAvailabilityChecker\nfrom PyFunceble.checker.reputation.ip import IPReputationChecker\nfrom PyFunceble.checker.reputation.status import ReputationCheckerStatus\n\n\nclass TestIPAvailabilityChecker(unittest.TestCase):\n \"\"\"\n Tests of our IP availability checker.\n \"\"\"\n\n def setUp(self) -> None:\n \"\"\"\n Setups everything needed for the tests.\n \"\"\"\n\n self.checker = IPAvailabilityChecker()\n\n def tearDown(self) -> None:\n \"\"\"\n Destroys everything needed for the tests.\n \"\"\"\n\n del self.checker\n\n @unittest.mock.patch.object(IPReputationChecker, \"get_status\")\n def test_try_to_query_status_from_reputation(\n self, reputation_checker_path: unittest.mock.MagicMock\n ) -> None:\n \"\"\"\n Tests of the method that tries to define the status from the reputation\n checker.\n \"\"\"\n\n self.checker.subject = \"192.168.1.1\"\n\n reputation_checker_path.return_value = ReputationCheckerStatus(\n subject=\"192.168.1.1\",\n idna_subject=\"192.168.1.1\",\n status=\"SANE\",\n status_source=\"REPUTATION\",\n tested_at=datetime.utcnow(),\n )\n\n self.checker.try_to_query_status_from_reputation()\n\n expected_status = None\n actual_status = self.checker.status.status\n\n self.assertEqual(expected_status, actual_status)\n\n reputation_checker_path.return_value = ReputationCheckerStatus(\n subject=\"192.168.1.1\",\n idna_subject=\"192.168.1.1\",\n status=\"MALICIOUS\",\n status_source=\"REPUTATION\",\n tested_at=datetime.utcnow(),\n )\n\n self.checker.try_to_query_status_from_reputation()\n\n expected_status = \"ACTIVE\"\n actual_status = self.checker.status.status\n\n self.assertEqual(expected_status, actual_status)\n\n expected_source = \"REPUTATION\"\n actual_source = self.checker.status.status_source\n\n self.assertEqual(expected_source, actual_source)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/checker/availability/test_ip.py","file_name":"test_ip.py","file_ext":"py","file_size_in_byte":4640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"485617137","text":"# -*- coding: mbcs -*-\ntypelib_path = u'C:\\\\Windows\\\\SysWOW64\\\\CIUsbLib.dll'\n_lcid = 0 # change this if required\nfrom ctypes import *\nfrom comtypes import GUID\nfrom ctypes import HRESULT\nfrom comtypes.typeinfo import ULONG_PTR\nfrom comtypes.automation import VARIANT\nfrom comtypes import helpstring\nfrom comtypes import COMMETHOD\nfrom comtypes import dispid\nfrom comtypes import CoClass\nfrom comtypes.automation import VARIANT\n#from comtypes import IUnknown\nfrom comtypes.automation import IDispatch\n\n\nclass IHostDrv(IDispatch):\n _case_insensitive_ = True\n u'IHostDrv Interface'\n _iid_ = GUID('{41487896-06E3-42ED-AA6A-25FC6E99C4FB}')\n _idlflags_ = ['dual', 'oleautomation']\nIHostDrv._methods_ = [\n COMMETHOD([dispid(1), helpstring(u'method CIUsb_GetStatus')], HRESULT, 'CIUsb_GetStatus',\n ( ['in'], c_int, 'nDevId' ),\n ( ['in'], c_int, 'nStatId' ),\n ( ['out'], POINTER(c_int), 'p_nStatus' )),\n COMMETHOD([dispid(2), helpstring(u'method CIUsb_SetControl')], HRESULT, 'CIUsb_SetControl',\n ( ['in'], c_int, 'nDevId' ),\n ( ['in'], c_int, 'nCntlId' ),\n ( ['out'], POINTER(c_int), 'p_nStatus' )),\n COMMETHOD([dispid(3), helpstring(u'method CIUsb_SendFrameData')], HRESULT, 'CIUsb_SendFrameData',\n ( ['in'], c_int, 'nDevId' ),\n ( ['in'], POINTER(c_ubyte), 'pFrameData' ),\n ( ['in'], c_int, 'nBuffSize' ),\n ( ['out'], POINTER(c_int), 'p_nStatus' )),\n COMMETHOD([dispid(4), helpstring(u'method CIUsb_SetNotify')], HRESULT, 'CIUsb_SetNotify',\n ( ['in'], ULONG_PTR, 'uWindow' ),\n ( ['in'], c_uint, 'uMessageId' )),\n COMMETHOD([dispid(5), helpstring(u'method CIUsb_GetAvailableDevices')], HRESULT, 'CIUsb_GetAvailableDevices',\n ( ['out'], POINTER(c_long*32), 'pDeviceIds' ),\n ( ['in'], c_int, 'nSizeBuff' ),\n ( ['out'], POINTER(c_int), 'p_nStatus' )),\n COMMETHOD([dispid(6), helpstring(u'method CIUsb_StreamFrameData')], HRESULT, 'CIUsb_StreamFrameData',\n ( ['in'], c_int, 'nDevId' ),\n ( ['in'], POINTER(c_ubyte), 'pFrameData' ),\n ( ['in'], c_int, 'nBuffSize' ),\n ( ['out'], POINTER(c_int), 'p_nStatus' )),\n COMMETHOD([dispid(7), helpstring(u'method CIUsb_StepFrameData')], HRESULT, 'CIUsb_StepFrameData',\n ( ['in'], c_int, 'nDevId' ),\n ( ['in'], POINTER(c_ushort*160), 'pFrameData' ),\n ( ['in'], c_int, 'nBuffSize' ),\n ( ['out'], POINTER(c_int), 'p_nStatus' )),\n COMMETHOD([dispid(8), helpstring(u'method CIUsb_FlushStream')], HRESULT, 'CIUsb_FlushStream',\n ( ['in'], c_int, 'nDevId' ),\n ( ['out'], POINTER(c_int), 'p_nStatus' )),\n]\n################################################################\n## code template for IHostDrv implementation\n##class IHostDrv_Impl(object):\n## def CIUsb_SetNotify(self, uWindow, uMessageId):\n## u'method CIUsb_SetNotify'\n## #return \n##\n## def CIUsb_StreamFrameData(self, nDevId, pFrameData, nBuffSize):\n## u'method CIUsb_StreamFrameData'\n## #return p_nStatus\n##\n## def CIUsb_GetAvailableDevices(self, nSizeBuff, p_nStatus):\n## u'method CIUsb_GetAvailableDevices'\n## #return pDeviceIds\n##\n## def CIUsb_GetStatus(self, nDevId, nStatId):\n## u'method CIUsb_GetStatus'\n## #return p_nStatus\n##\n## def CIUsb_FlushStream(self, nDevId):\n## u'method CIUsb_FlushStream'\n## #return p_nStatus\n##\n## def CIUsb_StepFrameData(self, nDevId, pFrameData, nBuffSize):\n## u'method CIUsb_StepFrameData'\n## #return p_nStatus\n##\n## def CIUsb_SetControl(self, nDevId, nCntlId):\n## u'method CIUsb_SetControl'\n## #return p_nStatus\n##\n## def CIUsb_SendFrameData(self, nDevId, pFrameData, nBuffSize):\n## u'method CIUsb_SendFrameData'\n## #return p_nStatus\n##\n## def CIUsb_StepFrameDataVar(self, nDevId, pFrameDataVar, nBuffSize):\n## u'method CIUsb_StepFrameDataVar'\n## #return p_nStatus\n##\n## def CIUsb_StreamFrameDataVar(self, nDevId, pFrameDataVar, nBuffSize):\n## u'method CIUsb_StreamFrameDataVar'\n## #return p_nStatus\n##\n\nclass CHostDrv(CoClass):\n u'HostDrv Class'\n _reg_clsid_ = GUID('{615FAAA3-B515-4D4C-9F04-013D13FEB154}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{0B17F235-D808-4A8B-82FB-F892607C1D55}', 1, 0)\nCHostDrv._com_interfaces_ = [IHostDrv]\n\nclass Library(object):\n u'CIUsbLib 1.0 Type Library'\n name = u'CIUsbLib'\n _reg_typelib_ = ('{0B17F235-D808-4A8B-82FB-F892607C1D55}', 1, 0)\n\n__all__ = [ 'CHostDrv', 'IHostDrv']\nfrom comtypes import _check_version; _check_version('')\n","sub_path":"hardware/Multi_DM/Multi_DM_interface.py","file_name":"Multi_DM_interface.py","file_ext":"py","file_size_in_byte":4765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"433249040","text":"\n\n#calss header\nclass _STAIR():\n\tdef __init__(self,): \n\t\tself.name = \"STAIR\"\n\t\tself.definitions = [u'a set of steps that lead from one level of a building to another: ', u'one of the steps in a set of steps that lead from one level of a building to another: ', u'a set of stairs: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_stair.py","file_name":"_stair.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"284696447","text":"class node:\n def __init__(self, data=None):\n self.data = data\n self.next=None\n\nclass linked_list:\n def __init__(self):\n self.head = node()\n\n #append function in the list object add new data point to end of list\n def append(self, data):\n new_node = node(data)\n cur = self.head\n while cur.next != None:\n cur = cur.next\n cur.next = new_node\n def length(self):\n cur = self.head\n total = 0\n while cur.next != None:\n total +=1\n cur = cur.next\n return total\n \n def display(self):\n elems = []\n cur_node = self.head\n while cur_node.next != None:\n cur_nod = cur_node.next\n elems.append(cur_node.data)\n print ('the {}'.format(elems))\n \n def get(self, index):\n if index >= self.length():\n print(\"Error: 'Get' Index out of range!\")\n return None\n\n\n\nmy_list = linked_list()\n\nmy_list.append(3)\nmy_list.append(5)\nmy_list.append(10)\nmy_list.display()\n","sub_path":"linklist1.py","file_name":"linklist1.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"460784871","text":"import asyncio\nimport logging\nimport pprint\nimport signal\nfrom typing import Coroutine, Iterable\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef _signal_callback(quit_event: asyncio.Event) -> None:\n quit_event.set()\n\n\nasync def simple_main(coroutines: Iterable[Coroutine]):\n loop = asyncio.get_event_loop()\n\n quit_event = asyncio.Event()\n loop.add_signal_handler(signal.SIGINT, _signal_callback, quit_event)\n loop.add_signal_handler(signal.SIGTERM, _signal_callback, quit_event)\n\n tasks = [asyncio.create_task(coroutine) for coroutine in coroutines]\n\n await quit_event.wait()\n\n for task in tasks:\n task.cancel()\n res = await asyncio.gather(*tasks, return_exceptions=True)\n logger.debug(\"tasks : %s\", pprint.pformat(res))\n","sub_path":"src/aioshenanigans/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"426226530","text":"import pandas as pd\nimport numpy as np\n\n\n\n\nfile1 = \"conjunto_de_datos_defunciones_registradas_2019.CSV\"\n\n#head = ['ent_regis', 'mun_regis', 'ent_resid', 'mun_resid', 'tloc_resid', 'loc_resid', 'ent_ocurr', 'mun_ocurr', 'tloc_ocurr', 'loc_ocurr', 'causa_def', 'lista_mex', 'sexo', 'edad', 'dia_ocurr', 'mes_ocurr', 'anio_ocur', 'dia_regis', 'mes_regis', 'anio_regis', 'dia_nacim', 'mes_nacim', 'anio_nacim', 'ocupacion', 'escolarida', 'edo_civil', 'presunto', 'ocurr_trab', 'lugar_ocur', 'necropsia', 'asist_medi', 'sitio_ocur', 'cond_cert', 'nacionalid', 'derechohab', 'embarazo', 'rel_emba', 'horas', 'minutos', 'capitulo', 'grupo', 'lista1', 'gr_lismex', 'vio_fami', 'area_ur', 'edad_agru', 'complicaro', 'dia_cert', 'mes_cert', 'anio_cert', 'maternas', 'lengua', 'cond_act', 'par_agre', 'ent_ocules', 'mun_ocules', 'loc_ocules', 'razon_m', 'dis_re_oax']\n\n\n#datos = pd.read_csv(file1,nrows=10000)\ndatos = pd.read_csv(file1)\n\n#dat_enf = pd.DataFrame(datos, columns = ['lista_mex','edad_agru'])\ndat_enf0 = pd.DataFrame(datos, columns = ['lista_mex'])\n\n\n# Cuenta de mayor a menor las causas de defuncion en México\nunique, counts = np.unique(dat_enf0, return_counts=True)\nx = dict(zip(unique, counts))\n\n# Ordena y muestra las 5 causas con mayor número de fallecidos\nxx = {k: v for k, v in sorted(x.items(), key=lambda item: item[1],reverse=True)[:5]}\nprint('Top 5 causas de muerte en MX : ',xx)\n\n# {'28A': 105210, '20D': 104354, '55': 36661, '33B': 30327, '35M': 26169}\n\n# 28A Infarto agudo del miocardio\n# 20D Diabetes mellitus\n# 55 Agresiones (homicidios)\n# 33B Neumonía\n# 35M Otras enfermedades del hígado\n\n\n# Tabla con info de edad y causa de defunción\ndat_enf1 = pd.DataFrame(datos, columns = ['lista_mex','edad'])\n\n\n# 28A\ndat_28a = dat_enf1[(dat_enf1['lista_mex']=='28A')]\ndat_28a = pd.DataFrame(dat_28a, columns = ['edad']).to_numpy().flatten()\n\n# No consideramos los casos que no especifican edad\naa = np.array([x for x in dat_28a if (x != 4998) ])\n\n# A los menores de 1 año, les asignamos edad de 1 año, por simplicidad.\naa = np.array([x-4000 if (x > 4000) else 1 for x in aa])\nEdad_prom_28a = aa.sum() / aa.size\n\n\n\n# 20D\ndat_20d = dat_enf1[(dat_enf1['lista_mex']=='20D')]\ndat_20d = pd.DataFrame(dat_20d, columns = ['edad']).to_numpy().flatten()\naa = np.array([x for x in dat_20d if (x != 4998) ])\naa = np.array([x-4000 if x > 4000 else 1 for x in aa])\nEdad_prom_20d = aa.sum() / aa.size\n\n\n# 55\ndat_55 = dat_enf1[(dat_enf1['lista_mex']=='55')]\ndat_55 = pd.DataFrame(dat_55, columns = ['edad']).to_numpy().flatten()\naa = np.array([x for x in dat_55 if (x != 4998) ])\naa = np.array([x-4000 if x > 4000 else 1 for x in aa])\nEdad_prom_55 = aa.sum() / aa.size\n\n\n# 33B\ndat_33b = dat_enf1[(dat_enf1['lista_mex']=='33B')]\ndat_33b = pd.DataFrame(dat_33b, columns = ['edad']).to_numpy().flatten()\naa = np.array([x for x in dat_33b if (x != 4998) ])\naa = np.array([x-4000 if x > 4000 else 1 for x in aa])\nEdad_prom_33B = aa.sum() / aa.size\n\n\n# 35M\ndat_35m = dat_enf1[(dat_enf1['lista_mex']=='35M')]\ndat_35m = pd.DataFrame(dat_35m, columns = ['edad']).to_numpy().flatten()\naa = np.array([x for x in dat_35m if (x != 4998) ])\naa = np.array([x-4000 if x > 4000 else 1 for x in aa])\nEdad_prom_35M = aa.sum() / aa.size\n\n\n\n\n\nprint('Edad prom 28A (años) : ', round(Edad_prom_28a,2))\nprint('Edad prom 20D (años) : ', round(Edad_prom_20d,2))\nprint('Edad prom 55 (años) : ', round(Edad_prom_55,2))\nprint('Edad prom 33B (años) : ', round(Edad_prom_33B,2))\nprint('Edad prom 35M (años) : ', round(Edad_prom_35M,2))\n\n\n\n# Output: \n# Edad prom 28A (años) : 74.93\n# Edad prom 20D (años) : 68.16\n# Edad prom 55 (años) : 34.71\n# Edad prom 33B (años) : 68.2\n# Edad prom 35M (años) : 62.06\n\n\n\n\n\n\n\n","sub_path":"2.-Enfermedades_mex.py","file_name":"2.-Enfermedades_mex.py","file_ext":"py","file_size_in_byte":3699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"451301075","text":"import json\nfrom enum import Enum\nimport logging\nfrom typing import Union\n\nfrom kafka import KafkaProducer\n\nfrom sim.sim import Sim\n\n\nclass GoapKafkaProducer:\n def __init__(self, url: Union[str, None]):\n self.logger = logging.getLogger(\"Kafka\")\n if not url:\n self.send_message = lambda message_type, message, sender, receiver: None\n self.send_sim_info = lambda sim, event, result, message: self.logger.event(f\"{sim} : {message}\")\n self.send_world_info = lambda world, event, result, message: self.logger.event(f\"{world} : {message}\")\n self.send_travel = lambda traveller, destination: None\n else:\n self.connect(url)\n\n class Messaging(Enum):\n Text = 1,\n Call = 2\n\n def connect(self, url: str):\n self.producer = KafkaProducer(bootstrap_servers=[url], value_serializer=lambda v: json.dumps(v).encode('utf-8'), key_serializer=str.encode)\n\n def send_sim_info(self, sim: Sim, event: str, result: str, message: str):\n self.producer.send(topic=\"info\", value={\"event\": event, \"result\": result}, key=sim.id)\n self.logger.event(f\"{sim} : {message}\")\n\n def send_world_info(self, world, event, result, message):\n self.producer.send(topic=\"info\", value={\"event\": event, \"result\": result}, key=str(world))\n self.logger.event(f\"{world} : {message}\")\n\n def send_message(self, message_type: Messaging, message, sender: Sim, receiver: Sim):\n message_metadata = {\"message_type\": str(message_type), \"sender\": sender.id, \"receiver\": receiver.id}\n self.producer.send(topic=\"messaging\", value=message, key=json.dumps(message_metadata))\n\n def send_travel(self, traveller: Sim, destination: str):\n pass\n","sub_path":"util/kafka.py","file_name":"kafka.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"505500261","text":"import os.path, socket; global CONFIGDIR\nCONFIGDIR = os.path.normcase(os.path.abspath(__file__)).rsplit('/', 1)[0]\n\n# Modifiable parameters.\nLAYOUTS = [\"%s/%s-layouts.py\" % (CONFIGDIR, x) for x in\n\t (\"castor\",\"csc\", \"dt\", \"eb\",\"ecalcalib\", \"ee\", \"es\",\"hcal\", \"hcalcalib\", \"hlt\", \"hlx\", \"l1t\", \"l1temulator\", \"rpc\", \"pixel\", \"sistrip\", \"sistriplas\")]\nLAYOUTS += [\"%s/%s_overview_layouts.py\" % (CONFIGDIR, x) for x in\n (\"sistrip\",\"ecal\",\"hcal\",\"beammonitor\",\"l1t\",\"hlt\")]\nLAYOUTS += [\"%s/shift_%s_layout.py\" % (CONFIGDIR, x) for x in\n (\"beam\",\"castor\",\"csc\", \"dt\", \"eb\", \"ee\", \"error\", \"es\",\"hcal\", \"hcalcalib\", \"hlt\", \"hlx\", \"info\", \"l1t\", \"l1temulator\", \"rpc\", \"pixel\", \"sistrip\" , \"fed\" )]\n\n# Do not modify configuration below this line.\nHOST = socket.gethostname().lower()\nHOSTADDR = socket.getaddrinfo(HOST, None)[0][4][0]\nBASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nHOSTALIAS = HOST\n\n# Figure out a preferred alias for this out (if any)\nfor alias in [\"dqm-prod-local\", \"dqm-prod-offsite\", \"dqm-integration\", \"dqm-test\"]:\n if len([x for x in socket.getaddrinfo(alias, None) if x[4][0] == HOSTADDR]):\n HOSTALIAS = alias\n break\n\n# Determine installation directories.\nSRVDIR = '/home/dqmlocal'\nCOLLHOST = 'dqm-c2d07-01'\n\n# Extension modules and environment to install.\nmodules = (\"Monitoring.DQM.GUI\",)\nenvsetup = \"export QUIET_ASSERT=a\"\n\n# Server configuration.\n#server.instrument = 'valgrind --num-callers=999 `cmsvgsupp` --error-limit=no'\n#server.instrument = 'valgrind --tool=helgrind --num-callers=999 --error-limit=no'\n#server.instrument = 'igprof -t python -pp'\nserver.localBase = HOSTALIAS\nserver.serverDir = '%s/gui' % SRVDIR\nserver.baseUrl = '/dqm/online-test'\nserver.title = 'CMS data quality'\nserver.serviceName = 'Online test'\n\n# Plugins.\nserver.plugin('render', BASEDIR + \"/style/*.cc\")\n\n# Extensions\nserver.extend('DQMRenderLink', server.pathOfPlugin('render'))\nserver.extend('DQMToJSON')\nserver.extend('DQMFileAccess', None, None,\n { \"Original\": \"/dqmdata/dqm/repository/original\"})\n\n# Sources\nserver.source('DQMUnknown')\nserver.source('DQMOverlay')\nserver.source('DQMStripChart')\nserver.source('DQMLive', '%s:9090' % COLLHOST)\nserver.source('DQMArchive', '%s/ix' % SRVDIR, '^/Global/')\nserver.source('DQMLayout', *LAYOUTS)\n\n# Services and Workspaces\nexecfile(CONFIGDIR + \"/dqm-services.py\")\nexecfile(CONFIGDIR + \"/workspaces-online.py\")\n","sub_path":"DQM/Integration/config/server-conf-online-test.py","file_name":"server-conf-online-test.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"234424059","text":"'''THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND\nNON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE\nDISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,\nWHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.'''\n\n# Bitcoin Cash (BCH) qpz32c4lg7x7lnk9jg6qg7s4uavdce89myax5v5nuk\n# Ether (ETH) - 0x843d3DEC2A4705BD4f45F674F641cE2D0022c9FB\n# Litecoin (LTC) - Lfk5y4F7KZa9oRxpazETwjQnHszEPvqPvu\n# Bitcoin (BTC) - 34L8qWiQyKr8k4TnHDacfjbaSqQASbBtTd\n\n# contact :- github@jamessawyer.co.uk\n\n\n\n# python program to print all subset combination of n element in given set of r element .\n# arr[] ---> Input Array\n# data[] ---> Temporary array to store current combination\n# start & end ---> Staring and Ending indexes in arr[]\n# index ---> Current index in data[]\n# r ---> Size of a combination to be printed\n\n\ndef combinationUtil(arr, n, r, index, data, i):\n # Current combination is ready to be printed,\n # print it\n if index == r:\n for j in range(r):\n print(data[j], end=\" \")\n print(\" \")\n return\n # When no more elements are there to put in data[]\n if i >= n:\n return\n # current is included, put next at next\n # location\n data[index] = arr[i]\n combinationUtil(arr, n, r, index + 1, data, i + 1)\n # current is excluded, replace it with\n # next (Note that i+1 is passed, but\n # index is not changed)\n combinationUtil(arr, n, r, index, data, i + 1)\n # The main function that prints all combinations\n # of size r in arr[] of size n. This function\n # mainly uses combinationUtil()\n\n\ndef printcombination(arr, n, r):\n # A temporary array to store all combination\n # one by one\n data = [0] * r\n # Print all combination using temprary\n # array 'data[]'\n combinationUtil(arr, n, r, 0, data, 0)\n\n\n# Driver function to check for above function\narr = [10, 20, 30, 40, 50]\nprintcombination(arr, len(arr), 3)\n# This code is contributed by Ambuj sahu\n","sub_path":"dynamic_programming/subset_generation.py","file_name":"subset_generation.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"342318307","text":"from domain.rent.rent import Rent\nfrom domain.rent.rentValidator import RentValidator\n\n\ndef test_rent():\n rent = Rent(\"1\", \"2\")\n assert rent.getIDC() == \"1\"\n assert rent.getIDF() == \"2\"\n assert rent.getIsRented() == True\n rent.setIsNotRented()\n rent.setIDC(\"2\")\n rent.setIDF(\"1\")\n assert rent.getIDC() == \"2\"\n assert rent.getIDF() == \"1\"\n assert rent.getIsRented() == False\n \ntest_rent()\n \n\ndef test_validator():\n rent = Rent(\"1\", \"\")\n valid = RentValidator()\n try:\n valid.validate(rent)\n assert False\n except ValueError:\n assert True\n \n rent = Rent(\"1\", \"1\")\n try:\n valid.validate(rent)\n assert True\n except ValueError:\n assert False\n \ntest_validator()","sub_path":"Lab7-9/Lab7-9/domain/rent/testsRent.py","file_name":"testsRent.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"124449548","text":"a=0\nb=1\nn=int(input(\"enter the number of terms you needed:\"))\nprint(a,b,end=\" \")\nwhile(n-1):\n\tx=a+b\n\ta=b\n\tb=x\n\tprint(x,end=\" \")\n\tn=n-1","sub_path":"fibbonacci.py","file_name":"fibbonacci.py","file_ext":"py","file_size_in_byte":134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"125097288","text":"import asyncio\nimport contextlib\nimport logging\nimport os\nimport uuid\nimport warnings\n\nimport psycopg2\nfrom ietfparse import headers\nfrom psycopg2 import extras\nfrom tornado import httpclient, testing\n\nfrom imbi import __version__, app\n\nLOGGER = logging.getLogger(__name__)\n\nJSON_HEADERS = {'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Correlation-Id': str(uuid.uuid4()),\n 'User-Agent': 'imbi-tests/{}'.format(__version__)}\n\nTABLES = [\n 'v1.authentication_tokens',\n 'v1.configuration_systems',\n 'v1.data_centers',\n 'v1.deployment_types',\n 'v1.environments',\n 'v1.group_members',\n 'v1.groups',\n 'v1.orchestration_systems',\n 'v1.projects',\n 'v1.project_link_types',\n 'v1.project_types',\n 'v1.teams',\n 'v1.users'\n]\n\nGROUP_SQL = \"\"\"\\\nINSERT INTO v1.groups (\"name\", group_type, external_id, permissions)\n VALUES (%(name)s, %(group_type)s, %(external_id)s, %(permissions)s)\nON CONFLICT DO NOTHING;\"\"\"\n\nGROUPS = [\n {\n 'name': 'admin',\n 'group_type': 'ldap',\n 'external_id': 'cn=admin,ou=groups,dc=example,dc=org',\n 'permissions': ['admin']\n },\n {\n 'name': 'imbi',\n 'group_type': 'ldap',\n 'external_id': 'cn=imbi,ou=groups,dc=example,dc=org',\n 'permissions': ['reader']\n }\n]\n\nUSER_GROUP = {\n 'admin': {'group': 'admin', 'username': 'admin'},\n 'test': {'group': 'imbi', 'username': 'test'}\n}\n\nUSER_GROUP_SQL = \"\"\"\\\nINSERT INTO v1.group_members(\"group\", username)\n VALUES (%(group)s, %(username)s) ON CONFLICT DO NOTHING;\"\"\"\n\n\nUSER_SQL = \"\"\"\\\nINSERT INTO v1.users (username, user_type, external_id,\n email_address, display_name)\n VALUES (%(username)s, %(user_type)s, %(external_id)s,\n %(email_address)s, %(display_name)s)\nON CONFLICT DO NOTHING;\"\"\"\n\nUSERS = [\n {\n 'username': 'test',\n 'user_type': 'ldap',\n 'external_id': 'cn=test,ou=users,dc=example,dc=org',\n 'email_address': 'imbi@example.org',\n 'display_name': 'Its Imbi'\n },\n {\n 'username': 'admin',\n 'user_type': 'ldap',\n 'external_id': 'cn=admin,ou=users,dc=example,dc=org',\n 'email_address': 'admin@example.org',\n 'display_name': 'Admin User'\n }\n]\n\n\nclass AsyncHTTPTestCase(testing.AsyncHTTPTestCase):\n \"\"\"Mimics what sprockets.http.run does under the covers.\"\"\"\n\n ADMIN = False\n\n def setUp(self) -> None:\n super().setUp()\n warnings.simplefilter('ignore')\n logging.basicConfig(level=logging.ERROR)\n self._truncate_tables()\n self._setup_groups()\n self._setup_users()\n self.headers = dict(JSON_HEADERS)\n self.headers['Private-Token'] = self._get_token()\n for cb in self._app.runner_callbacks.get('before_run', []):\n cb(self._app, self.io_loop)\n self.wait_until_ready()\n self.io_loop.start()\n\n def tearDown(self) -> None:\n self.wait_until_done()\n self.io_loop.start()\n super().tearDown()\n\n def get_app(self) -> app.Application:\n return app.make_application(debug=0)\n\n @testing.gen_test\n async def wait_until_ready(self):\n for cb in self._app.runner_callbacks.get('on_start', []):\n await cb(self._app, self.io_loop)\n while not self._app.ready_to_serve:\n await asyncio.sleep(0.1)\n self.io_loop.stop()\n\n @testing.gen_test\n async def wait_until_done(self):\n for cb in self._app.runner_callbacks.get('shutdown', []):\n await cb(self.io_loop)\n self.io_loop.stop()\n\n def assert_link_header_equals(self,\n result: httpclient.HTTPResponse,\n expectation: str, rel: str = 'self') -> None:\n \"\"\"Validate the URL in the link header matches the expectation\"\"\"\n for link in headers.parse_link(result.headers['Link']):\n if dict(link.parameters)['rel'] == rel:\n self.assertEqual(link.target, expectation)\n break\n\n def _get_token(self):\n token = str(uuid.uuid4())\n with self._postgres_cursor() as cursor:\n cursor.execute(\n \"\"\"INSERT INTO v1.authentication_tokens (username, token)\n VALUES (%(username)s, %(token)s);\"\"\",\n {'username': 'admin' if self.ADMIN else 'test',\n 'token': token})\n return token\n\n def _setup_groups(self):\n with self._postgres_cursor() as cursor:\n for group in GROUPS:\n cursor.execute(GROUP_SQL, group)\n\n def _setup_users(self):\n with self._postgres_cursor() as cursor:\n for user in USERS:\n cursor.execute(USER_SQL, user)\n cursor.execute(USER_GROUP_SQL, USER_GROUP[user['username']])\n\n @contextlib.contextmanager\n def _postgres_cursor(self):\n conn = psycopg2.connect(os.environ.get(\n 'POSTGRES_URL',\n 'postgres://postgres@localhost:5432/postgres'))\n conn.autocommit = True\n try:\n yield conn.cursor(cursor_factory=extras.RealDictCursor)\n finally:\n conn.close()\n\n def _truncate_tables(self):\n with self._postgres_cursor() as cursor:\n for table in TABLES:\n cursor.execute('TRUNCATE TABLE {} CASCADE'.format(table))\n","sub_path":"tests/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":5402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"396831032","text":"# Copyright (c) 2013, molie and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.utils import cint, flt, cstr\nfrom frappe import _\n\ndef execute(filters=None):\n\tif not filters: filters = {}\n\n\tcolumns = get_columns()\n\tdata = get_recheck_delivery_note(filters)\n\n\treturn columns, data\n\ndef get_columns():\n\treturn [\n\t _(\"Status\") + \":Data:80\",\n\t\t_(\"No.Delivery Note\")+\":Link/Delivery Note:110\",\n\t\t_(\"Posting Date\") + \":Date:100\",\n\t\t_(\"Item Code\") + \":Link/Item:300\",\n\t\t_(\"Item Name\") + \"::300\",\n\t\t_(\"Item Group\") + \":Link/Item Group:100\",\n\t\t_(\"Packing (QTY)\") + \":Float:100\",\n\t\t_(\"Packing (UoM)\") + \"::100\",\n\t\t_(\"Packing (Unit)\") + \":Float:100\",\n\t\t_(\"Qty\") + \":Float:100\",\n\t\t_(\"UoM\") + \"::50\",\n\t\t_(\"Rate (IDR)\") + \":Currency:120\",\n\t\t_(\"Amount (IDR)\") + \":Currency:120\",\n\t\t_(\"Warehouse\") + \":Link/Warehouse:200\",\n\t\t_(\"Expense Account\") + \":Data:200\",\n\t\t_(\"Cost Center\") + \":Link/Cost Center:150\",\n\t\t_(\"Created Date\") + \":Datetime:150\",\n\t\t_(\"Created By\") + \":Data:200\",\n\t\t_(\"Modified Date\") + \":Datetime:150\",\n\t\t_(\"Modified By\") + \":Data:200\"\n\n\t]\n\n\ndef get_recheck_delivery_note(filters):\n\tconditions = get_conditions(filters)\n\t#return frappe.db.sql(\"\"\"select item_name,item_group,stock_uom,expense_account,income_account,has_variants,is_purchase_item,is_sales_item,is_asset_item,is_sub_contracted_item from tabItem where has_variants = '0' and item_group = 'layanan' %s\"\"\" % conditions, as_list=1)\n\t#return frappe.db.sql(\"\"\"select parent,item_code,item_name,item_group,packing_qty,packing_uom,conversion_factor,qty,stock_uom,rate,amount,warehouse,expense_account,cost_center,creation,owner,modified,modified_by from `tabDelivery Note Item` where docstatus < 2 %s\"\"\" % conditions, as_list=1)\n\t#return frappe.db.sql(\"\"\"select `tabPurchase Receipt`.status,`tabPurchase Receipt`.name,`tabPurchase Receipt`.supplier,`tabPurchase Receipt`.company,`tabPurchase Receipt`.posting_date,`tabPurchase Receipt`.posting_time,`tabPurchase Receipt`.transporter_name,`tabPurchase Receipt`.lr_date,`tabPurchase Receipt`.lr_no,`tabPurchase Receipt`.currency,`tabPurchase Receipt`.price_list_currency,`tabPurchase Receipt`.conversion_rate,`tabPurchase Receipt`.base_net_total,concat(`tabCurrency`.symbol,\" \",`tabPurchase Receipt`.base_grand_total),`tabPurchase Receipt`.net_total,`tabPurchase Receipt`.base_total,`tabPurchase Receipt`.base_rounded_total from `tabPurchase Receipt` inner join `tabCurrency` on `tabPurchase Receipt`.currency = `tabCurrency`.name where `tabPurchase Receipt`.docstatus < 2 %s\"\"\" % conditions, as_list=1)\n\treturn frappe.db.sql(\n\t\t\"\"\"select\n\t\t\t\tdn1.status,dn2.parent,dn1.posting_date,dn2.item_code,dn2.item_name,dn2.item_group,dn2.packing_qty,dn2.packing_uom,dn2.conversion_factor,\n\t\t dn2.qty,dn2.stock_uom,dn2.rate,dn2.amount,dn2.warehouse,dn2.expense_account,dn2.cost_center,dn2.creation,\n\t\t\t\tdn2.owner,dn2.modified,dn2.modified_by\n\t\t from\n\t\t \t\t`tabDelivery Note Item` dn2 inner join `tabDelivery Note` dn1\n\n\t\t where\n\t\t \t\tdn2.parent = dn1.name and dn2.docstatus < 2 %s order by dn1.posting_date desc,dn1.posting_time desc,dn2.parent desc\n\t\t\"\"\" % conditions, as_list=1)\n\ndef get_conditions(filters):\n\tconditions = \"\"\n\t#value = []\n\tif filters.get(\"delivery_note\"):\n\t\tconditions += \"and dn2.parent = '%s'\" % filters[\"delivery_note\"]\n\n\tif filters.get(\"item_group\"):\n\t\tconditions += \"and dn2.item_group = '%s'\" % filters[\"item_group\"]\n\n\tif filters.get(\"warehouse\"):\n\t\tconditions += \"and dn2.warehouse = '%s'\" % filters[\"warehouse\"]\n\n\tif filters.get(\"from_date\"):\n\t\tconditions += \"and dn1.posting_date >= '%s'\" % filters[\"from_date\"]\n\n\tif filters.get(\"to_date\"):\n\t\tconditions += \"and dn1.posting_date <= '%s'\" % filters[\"to_date\"]\n\n\tif filters.get(\"cost_center\"):\n\t\tconditions += \"and dn2.cost_center = '%s'\" % filters[\"cost_center\"]\n\n\treturn conditions\n\n\t\t#if filters.get(\"company\"): conditions += \" and company = '%s'\" % \\\n\t\t#\tfilters[\"company\"].replace(\"'\", \"\\\\'\")\n","sub_path":"bisnis_intelligent/bisnis_intelligent/report/recheck_delivery_note_item/recheck_delivery_note_item.py","file_name":"recheck_delivery_note_item.py","file_ext":"py","file_size_in_byte":3965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"192118809","text":"\"\"\"\nThis module implements a Github web crawler, which accepts a standardized json input which is read\nfrom a json file that is piped to the script as the standard input (stdin), e.g:\n>>python github_crawler.py < input.json\n\nThe input file should contain 3 keys: keywords, proxies, type.\nThe value of 'keywords' key should be an array of 3 keywords to search for on Github:\n\"keywords\": [\"python\", \"vagrant\", \"django\"]\n\nThe value of 'proxies' key should be an array of 2 proxy server's URLs with their schemas\nincluded:\n\"proxies\": [\"80.255.91.38:43360\", \"118.97.235.234:8080\"]\n\nThe value of 'type' key should be an string with one of the following 3 values: 'Repositories',\n'Issues', 'Wikis', which indicates search sections of Github to search through:\n\"type\": \"Issues\"\n\nThe crawler searches for the keywords on Github and returns a json file with the result (URLs which\nmatch search criteria). For types 'Issues' and 'Wikis' the result will have the following schema:\n[\n {\n \"url\": \"https://github.com/andreagrandi/covid-api/issues/1\"\n },\n {\n \"url\": \"https://github.com/Prefeitura-Comunica/thread/issues/3\"\n }\n]\nFor Repositories, it will additionally include information on a repo owner and languages used for\nthe repo. The schema is as follows:\n[\n {\n \"url\": \"https://github.com/davidfischer-ch/ansible-roles\",\n \"extra\": {\n \"owner\": \"davidfischer-ch\",\n \"language_stats\": {\n \"Python\": 99.9,\n \"Shell\": 0.1\n }\n }\n }\n]\n\"\"\"\nimport concurrent.futures\nimport json\nimport sys\n\nfrom lxml.html import fromstring\n\nimport requests\n\nOBJECT_TYPES = ['Repositories', 'Issues', 'Wikis']\n\n\ndef get_input(content):\n \"\"\"\n This function accepts a file-like object (stdin) with json input and extracts necessary data\n from it\n :param content: file-like object with input\n :return: tuple containing proxies to use for requests, keywords to search for and type of\n Github section to search for.\n \"\"\"\n obj = json.loads(content)\n keywords = obj.get('keywords')\n obj_type = obj.get('type')\n return keywords, obj_type\n\n\ndef parse_repo(url):\n \"\"\"\n This function sends requests to repo URL, parses it and extracts necessary data\n :param url: string, the URL of Github repo\n :param proxies: dict, dict where key is the schema and value is the actual URL of a proxy\n {'https': 'https://81.33.4.214:61711', 'http': 'http://185.176.32.160:3128'}\n\n :return: dict, dict containing the URL of the page, the owner of the repo and repo's language\n statistics\n \"\"\"\n r = requests.get(url)\n result_html = fromstring(r.text)\n langs = [\n i.get('aria-label') for i in result_html.cssselect(\n 'div.d-flex.repository-lang-stats-graph span'\n )\n ]\n owner = result_html.cssselect('span.author.ml-1.flex-self-stretch[itemprop=author] a')[0]\n return {\n 'url': url,\n 'extra': {\n 'owner': owner.text_content(), 'language_stats': {\n ' '.join(i.split()[:-1]): float(i.split()[-1].rstrip('%')) for i in langs\n }\n }\n }\n\n\ndef get_urls(keywords, obj_type):\n \"\"\"\n This function retrieves URLs matching search keywords passsed as the input\n :param keywords: list, the list of keywords to search for\n :param proxies: list, list of dicts where key is the schema and value is the actual URL of a proxy\n {'https': 'https://81.33.4.214:61711', 'http': 'http://185.176.32.160:3128'}\n :param obj_type: string, the type of Github section to search through\n :return: list, list of dictionaries where key is always 'url' and value is the URL of the page\n which is suitable\n \"\"\"\n if obj_type == OBJECT_TYPES[0]:\n github_url = 'https://github.com/search?utf8=%E2%9C%93&q=topic%3A{}+topic%3A{}+topic%3A{}&\\\nref=simplesearch'.format(keywords[0], keywords[1], keywords[2])\n elif obj_type == OBJECT_TYPES[1]:\n github_url = 'https://github.com/search?q={}+{}+{}+type%3Aissue'.format(\n keywords[0], keywords[1], keywords[2]\n )\n elif obj_type == OBJECT_TYPES[2]:\n github_url = 'https://github.com/search?q={}+{}+{}&type=Wikis'.format(\n keywords[0], keywords[1], keywords[2]\n )\n r = requests.get(url=github_url)\n result_html = fromstring(r.text)\n urls = [\n {'url': 'https://github.com' + i.get('href')} for i in result_html.cssselect(\n 'div.f4.text-normal a'\n )\n ]\n return urls\n\n\ndef get_extra(urls, obj_type):\n \"\"\"\n This function concurrently sends requests to Github repo URLs passed as its parameter and\n returns the structured result containing the URL, owner and language stats for this URL\n :param urls: list, the array of dicts of URLs of Github repos\n :param obj_type: string, the type of Github section to search through\n :param proxies: list, list of dicts here key is the schema and value is the actual URL of a proxy\n {'https': 'https://81.33.4.214:61711', 'http': 'http://185.176.32.160:3128'}\n :return: list, the list of dicts containing the URL of the page, the owner of the repo and\n repo's language statistics\n \"\"\"\n if obj_type == OBJECT_TYPES[0]:\n with concurrent.futures.ThreadPoolExecutor(max_workers=len(urls)) as executor:\n future_to_url = {\n executor.submit(parse_repo, url.get('url')): url.get('url') for url in urls\n }\n results = [future.result() for future in concurrent.futures.as_completed(future_to_url)]\n return results\n\n\ndef write_results(results):\n with open('result.json', 'w') as f:\n json.dump(results, f, ensure_ascii=False, indent=4)\n\n\ndef main():\n content = sys.stdin.read()\n keywords, obj_type = get_input(content)\n urls = get_urls(keywords, obj_type)\n results = get_extra(urls, obj_type)\n if results:\n write_results(results)\n else:\n write_results(urls)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"n-ix_crawler/github_crawler.py","file_name":"github_crawler.py","file_ext":"py","file_size_in_byte":6002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"560369936","text":"\"\"\"empty message\n\nRevision ID: e23aba732da1\nRevises: \nCreate Date: 2016-12-05 21:39:44.692000\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e23aba732da1'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('role',\n sa.Column('role_id', sa.Integer(), nullable=False),\n sa.Column('role_name', sa.Unicode(length=255), nullable=True),\n sa.PrimaryKeyConstraint('role_id')\n )\n op.create_table('permission',\n sa.Column('permission_id', sa.Integer(), nullable=False),\n sa.Column('role_id', sa.Integer(), nullable=True),\n sa.Column('permission_name', sa.Unicode(length=255), nullable=True),\n sa.Column('permission_desc', sa.Unicode(length=255), nullable=True),\n sa.ForeignKeyConstraint(['role_id'], [u'role.role_id'], ),\n sa.PrimaryKeyConstraint('permission_id')\n )\n op.create_table('user',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('role_id', sa.Integer(), nullable=True),\n sa.Column('firstname', sa.String(length=50), server_default=u'', nullable=False),\n sa.Column('lastname', sa.String(length=50), server_default=u'', nullable=True),\n sa.Column('email', sa.Unicode(length=255), server_default=u'', nullable=False),\n sa.Column('username', sa.Unicode(length=255), server_default=u'', nullable=False),\n sa.Column('password', sa.Unicode(length=255), server_default='', nullable=False),\n sa.ForeignKeyConstraint(['role_id'], [u'role.role_id'], ),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('user')\n op.drop_table('permission')\n op.drop_table('role')\n # ### end Alembic commands ###\n","sub_path":"python-server/migrations/versions/e23aba732da1_.py","file_name":"e23aba732da1_.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"377392493","text":"\"\"\"Chameleon provider code.\"\"\"\nimport openstack\n\nfrom beeflow.common.cloud import provider\n\n\nclass ChameleoncloudProvider(provider.Provider):\n \"\"\"Chameleoncloud provider class.\"\"\"\n\n def __init__(self, stack_name=None, **_kwargs):\n \"\"\"Chameleoncloud provider constructor.\"\"\"\n self._stack_name = stack_name\n self._api = openstack.connect()\n\n def create_from_template(self, template_file):\n \"\"\"Create from a template file.\"\"\"\n raise RuntimeError(\n 'create_from_template() is not implemented for Chameleoncloud. '\n 'Use the Horizon interface instead'\n )\n\n def get_ext_ip_addr(self, node_name): # noqa\n \"\"\"Get the external IP address of the node, if it has one.\"\"\"\n if self._stack_name is not None:\n stack = self._api.get_stack(self._stack_name)\n if stack is None:\n raise RuntimeError(f'Invalid stack {self._stack_name}')\n outputs = {output['output_key']: output['output_value'] for output in stack['outputs']}\n if 'head_node_login_ip' in outputs:\n return outputs['head_node_login_ip']\n return None\n","sub_path":"beeflow/common/cloud/chameleoncloud.py","file_name":"chameleoncloud.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"264180751","text":"import os\nimport json\nfrom collections import *\nfrom itertools import *\nfrom tqdm import tqdm as tqdm\n\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.metrics import roc_auc_score\n\nfrom . import utils\nfrom . import constants\n\nclass HSMIndependentDomainsModel(object):\n \"\"\"\n Single-domain model implementing the HSM / ID model.\n \n Most arguments are passed into the model using the args initialization option. See constants.py for the \n function for the keywords to use to set different options values.\n\n The required arguments are:\n - validation_chunk: an index that is validated against.\n - model_format: a ModelSpecificationTuple, as defined in constants.py\n - lambda_params: a nested python dictionary; nested for domain type then peptide type.\n - amino_acid_ordering: a dict that indexes the vectorized data.\n - args: all additional arguments; see constants.py\n \"\"\"\n\n def __init__(self, validation_chunk, model_format, lambda_params, amino_acid_ordering, args=dict()):\n ## model_format inputs are namedtuples:\n # ModelSpecificationTuple = namedtuple(\"ModelSpecificationTuple\", [\"domain_type\", \"peptide_type\", \"domain_length\", \"peptide_length\", \"directory\"])\n self.model_spec = model_format\n self.domain_length = model_format.domain_length\n self.peptide_length = model_format.peptide_length\n self.n_amino_acids = len(amino_acid_ordering)\n \n # Set model hyper-parameters. Defaults to constants in the case where \n self.epochs = args.get(constants.KEY_epochs, constants.DEF_epochs)\n self.data_split_seed = args.get(constants.KEY_chunk_seed, constants.DEF_fold_seed)\n self.n_folds = args.get(constants.KEY_n_folds, constants.DEF_n_folds)\n self.chunk_size = args.get(constants.KEY_chunk_size, constants.DEF_chunk_size)\n self.learning_rate = args.get(constants.KEY_learning_rate, constants.DEF_learning_rate)\n self.init_std = args.get(constants.KEY_standard_dev, constants.DEF_init_std)\n self.lambda_param = lambda_params[model_format.domain_type][model_format.peptide_type] \n \n self.validation_chunk = validation_chunk\n self.validate_step = args.get(constants.KEY_validate_step, constants.DEF_validate_step)\n self.exclude_indices = args.get(constants.KEY_exclude_chunks, None)\n self.include_all_data = args.get(constants.KEY_include_all_chunks, False)\n\n # Initialize tensorflow graph.\n self.sess = tf.Session()\n self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) \n \n self._variables(self.init_std)\n \n self._model(args)\n\n init_op = tf.group(tf.local_variables_initializer(), tf.global_variables_initializer())\n self.sess.run(init_op)\n\n \n def _variables(self, initialization_std):\n \"\"\"\n Intializes variable. Shouldn't be called outside of the class (called from __init__).\n \"\"\"\n # Placeholders for different input data.\n self.domain_data = tf.sparse.placeholder(dtype=tf.float64, name=\"domain_data_mtx\")\n self.peptide_data = tf.sparse.placeholder(dtype=tf.float64, name=\"peptide_data_mtx\")\n self.interact_data = tf.sparse.placeholder(dtype=tf.float64, name=\"interaction_data_mtx\")\n self.binding_data = tf.placeholder(dtype=tf.float64, name=\"binding_data_mtx\")\n \n # Weights variables to be trained in the model.\n domain_weights_shape = (self.domain_length * self.n_amino_acids, 1)\n self.domain_weights = tf.Variable(np.random.normal(scale=initialization_std, size=domain_weights_shape),\n name=\"domain_weights\", dtype=tf.float64)\n\n peptide_weights_shape = (self.peptide_length * self.n_amino_acids, 1)\n self.peptide_weights = tf.Variable(np.random.normal(scale=initialization_std, size=peptide_weights_shape),\n name=\"peptide_weights\", dtype=tf.float64)\n\n interaction_weights_shape = (self.domain_length * self.peptide_length * (self.n_amino_acids ** 2), 1)\n self.interaction_weights = tf.Variable(np.random.normal(scale=initialization_std, size=interaction_weights_shape), \n name=\"interaction_weights\", dtype=tf.float64)\n\n self.bias = tf.Variable(0, name=\"bias\", dtype=tf.float64)\n\n def _model(self, args):\n \"\"\"\n Defines model graph. Shouldn't be called outside of class (called from __init__).\n \"\"\"\n with tf.name_scope(\"sparsity\"):\n # L1-sparsity penalty.\n self.weight_penalty = (self.lambda_param * tf.reduce_sum(tf.abs(self.domain_weights)) + \n self.lambda_param * tf.reduce_sum(tf.abs(self.peptide_weights)) + \n self.lambda_param * tf.reduce_sum(tf.abs(self.interaction_weights))) \n \n with tf.name_scope(\"logits\"):\n # Basic model, computes logits from model weights.\n domain_contrib = tf.sparse.sparse_dense_matmul(self.domain_data, self.domain_weights) \n peptide_contrib = tf.sparse.sparse_dense_matmul(self.peptide_data, self.peptide_weights)\n interact_contrib = tf.sparse.sparse_dense_matmul(self.interact_data, self.interaction_weights)\n\n self.logits = domain_contrib + peptide_contrib + interact_contrib + self.bias\n \n # Loss Function computation and optimization.\n self.cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=self.binding_data, logits=self.logits, name=\"cross_entropy\"))\n self.loss_function = self.cross_entropy + self.weight_penalty\n \n self.train_op = self.optimizer.minimize(self.loss_function)\n \n # Ops for computing predictions.\n self.predict_op = tf.math.sigmoid(self.logits, name=\"predict_sigmoid\")\n\n def optimize_step(self, data_iter):\n \"\"\"\n A single training epoch. Passes in an iterator over data and \n\n args:\n - data_iter: a data iterator feeding in data of the form (sequence_tuple, binds_arr)\n sequence_tuple is ordered[domain sequences, peptide sequences, interact sequences] \n \"\"\"\n costs = list() \n for sequences, binds in data_iter:\n # Convert to sparse tensors for use in the model.\n dseqs_sp, pseqs_sp, iseqs_sp = utils.make_sparse(sequences, self.domain_length, self.peptide_length, self.n_amino_acids)\n \n # Using feed_dicts is a bit unfortunate. It cleans up the data file handling on the\n # front end. To optimize, switch over to TensorFlow's data processing pipeline.\n feed_dict = {\n self.domain_data: dseqs_sp,\n self.peptide_data: pseqs_sp,\n self.interact_data: iseqs_sp,\n self.binding_data: np.expand_dims(binds, -1)\n }\n \n # Compute step.\n train_cost, _ = self.sess.run([self.loss_function, self.train_op], feed_dict=feed_dict)\n costs.append(train_cost)\n\n return costs\n \n def predict(self, data):\n \"\"\"\n Make a single prediction. \n\n args:\n - data: a data tuple of the form InteractionDataTuple as defined in utils.py \n \"\"\"\n binds, sequences = data[0], list(data[1:])\n \n # Convert to sparse tensors.\n dseqs_sp, pseqs_sp, iseqs_sp = utils.make_sparse(sequences, self.domain_length, self.peptide_length, self.n_amino_acids)\n\n feed_dict = {\n self.domain_data: dseqs_sp,\n self.peptide_data: pseqs_sp,\n self.interact_data: iseqs_sp,\n self.binding_data: np.expand_dims(binds, -1)\n }\n\n predictions = self.sess.run(self.predict_op, feed_dict=feed_dict)\n roc_auc = roc_auc_score(binds, predictions) \n return binds, predictions, roc_auc \n \n def train(self, data_directory):\n \"\"\"\n Fully train the model given the input parameters. Runs for the input / default number of epochs. \n Mostly just wraps the optimize_step function. \n\n args:\n - data_directory: the input data directory. The data is split using the input metadata. \n \"\"\"\n train_data, test_data = utils.split_data(data_directory, self.validation_chunk, include_all=self.include_all_data, excluded_chunks=self.exclude_indices, n_folds=self.n_folds, seed=self.data_split_seed)\n data_iterator = utils.training_iterator(train_data, chunk_size=self.chunk_size)\n\n self.costs = list() \n self.aucs = list()\n for epoch in tqdm(range(self.epochs), desc=\"Epochs\"):\n epoch_costs = self.optimize_step(next(data_iterator))\n self.costs.append(epoch_costs)\n \n if (epoch + 1) % self.validate_step == 0:\n _, _, auc = self.predict(test_data)\n self.aucs.append(auc)\n print(\"Epoch: {0} (AUC: {1})\".format(epoch+1, auc))\n\n self.final_predictions = self.predict(test_data)\n\n def save_model(self, output_directory):\n \"\"\"\n Save model outputs from a trained model. The output files are of the form: ..\n The id is defined as the current time (as a string). The spec defines the output, either metadata\n or the domain type of output. ext is the file extension, either a numpy file or a json file.\n\n args:\n - output_directory: a string defining a directory to output the saved model to. \n \"\"\"\n import time \n \n model_output_id = str(time.time()).replace(\"-\", \"_\")\n \n # Metadata. Saved as dict (to JSON file) with four keys defining model type, \n # model format, the results of the last prediction, and parameters\n results = {\n \"binds\": list(map(int, self.final_predictions[0])),\n \"predictions\": list(map(float, self.final_predictions[1])),\n \"auc\": float(self.final_predictions[2])\n }\n output = {\n \"Model Type\": \"HSM / ID\",\n \"Model Format\": list(self.model_spec), \n \"results\": results, \n \"parameters\": {\n \"costs\": self.costs,\n \"validation chunk\": self.validation_chunk,\n constants.KEY_chunk_seed: self.data_split_seed,\n constants.KEY_n_folds: self.n_folds,\n constants.KEY_epochs: self.epochs,\n constants.KEY_learning_rate: self.learning_rate\n }\n }\n \n ometadata_file = os.path.join(output_directory, \"{0}.metadata.json\".format(model_output_id))\n with open(ometadata_file, 'w+') as f:\n json.dump(output, f)\n \n # The model, saved as an array archive (.npz) file. \n model_file = os.path.join(output_directory, \"{0}.{1}.{2}.npz\".format(model_output_id, self.model_spec.domain_type, self.model_spec.peptide_type))\n dw, pw, iw, bias = self.sess.run([self.domain_weights, self.peptide_weights, self.interaction_weights, self.bias]) \n np.savez(model_file, domain_weights=dw, peptide_weights=pw, interact_weights=iw, bias=bias)\n","sub_path":"train/models/hsm_id.py","file_name":"hsm_id.py","file_ext":"py","file_size_in_byte":11369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"128535819","text":"# coding: UTF-8\n\n\"\"\"\n入力:\n[ 1年の日数:str\n 1カ月の日数:str\n 1週間の日数:str\n 判別したい日:str\n]\n\"\"\"\n\n\"\"\"\nメモ\n一周するのはremainder daysの総和が1カ月の日数の倍数になるとき\n\"\"\"\n\n\n# !/usr/bin/env python3\n\n\nclass make_calender:\n def __init__(self, year_days, month_days, week_days):\n self.year_days = year_days\n self.month_days = month_days\n self.week_days = week_days\n self.remain_days = year_days % month_days\n\n # 年における月数のサイクルを求める\n def get_cycle_month(self):\n year_month = []\n remain = self.remain_days\n while True:\n year_month.append(int(self.year_days / self.month_days))\n if remain >= self.month_days:\n year_month[-1] += 1\n remain -= self.month_days\n if remain == 0:\n break\n remain += self.remain_days\n return year_month\n\n # 指定された日が正しいかのチェック\n def check_input(self, input_month, input_day):\n cycle = self.get_cycle_month()\n if input_day > self.month_days or input_month > cycle[input_month % len(cycle)]:\n return False\n else:\n return True\n\n # チェックの年に対応する日数を求める\n def get_days_of_year(self, check_year):\n cycle = self.get_cycle_month()\n cycle_days = 0\n for month in cycle:\n cycle_days += month * self.month_days\n remain_days = 0\n if check_year % len(cycle) != 0:\n for i in range(0, (check_year % len(cycle))):\n remain_days += self.month_days * cycle[i]\n return int(check_year / len(cycle))*cycle_days + remain_days\n\n # チェックの月に対応する日数を求める\n def get_days_of_month(self, check_month):\n return (check_month) * self.month_days\n\n # チェックの日の曜日を求める\n def get_day_of_the_week(self, check_year, check_month, check_day):\n number_of_day_of_the_weekend = (self.get_days_of_year(check_year) + self.get_days_of_month(check_month) + check_day) % self.week_days\n if number_of_day_of_the_weekend == 0:\n return chr(64 + self.week_days)\n else:\n return chr(64 + number_of_day_of_the_weekend)\n\n\n\ndef main(argv):\n\n a_year_days = int(argv[0])\n a_month_days = int(argv[1])\n a_week_days = int(argv[2])\n check = argv[3]\n # a_year_days = 160\n # a_month_days = 30\n # a_week_days = 7\n # check = \"00001-01-30\"\n # check = \"00003-01-01\"\n check_list = check.split(\"-\")\n check_year = int(check_list[0]) - 1\n check_month = int(check_list[1]) - 1\n check_day = int(check_list[2])\n\n check = make_calender(a_year_days, a_month_days, a_week_days)\n # print(\"days of year : \" + str(check.get_days_of_year(check_year)))\n # print(\"days of month : \" + str(check.get_days_of_month(check_month)))\n\n if check.check_input(check_month, check_day):\n print(check.get_day_of_the_week(check_year, check_month, check_day))\n else:\n print(-1)\n\n# main()","sub_path":"Sprint/problem2.py","file_name":"problem2.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"138903705","text":"import os \nfrom os.path import dirname\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport plotUtils\nfrom DataParser import DataParser\nfrom CsvParser import CsvParser\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nplt.style.use('ggplot')\n\noutput = \"test\"\n#signal_file = '/nfs/slac/g/hps2/mrsolt/hps/Data2016/MachineLearing/AnalysisWorkshopML/ap-beam_100MeV_4e9.csv'\n#background_file = '/nfs/slac/g/hps2/mrsolt/hps/Data2016/MachineLearing/AnalysisWorkshopML/tritrig-wab-beam_100MeV_L1L1_tight.csv'\nsignal_file = '~/CS230/cs230-project/notebooks/datasets/ap_100MeV_L1L1_tight_08mm.csv'\nbackground_file = '~/CS230/cs230-project/notebooks/datasets/tritrig-wab-beam_100MeV_L1L1_tight.csv'\n\nbackground = CsvParser(background_file)\nsignal = CsvParser(signal_file)\n\nmyData = DataParser(signal=signal, background=background)\n\nX_train, Y_train, X_test, Y_test, classes = myData.load_dataset()\nprint(Y_train.shape)\nprint(Y_test.shape)\n\nX_train = X_train.T\nY_train = Y_train.T\nX_test = X_test.T\nY_test = Y_test.T\n\nfrom sklearn.ensemble import RandomForestClassifier\nn_estimators = 100\nmax_depth = 10\nclf = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth, oob_score=True, random_state=0)\n\nmin_estimators = 10\nmax_estimators = 100\nspacing = 10\nn = int((max_estimators - min_estimators) / spacing) + 1\ndepth = [3,5,7,10]\n\nPDFname = output + \"_err.pdf\"\npp = PdfPages(PDFname)\n\nfig, ((ax0, ax1)) = plt.subplots(nrows=1, ncols=2, figsize=(20,8))\n#ax = fig.add_subplot(111)\n\nfor j in depth:\n error_rate = []\n error_rate_test = []\n estim = []\n for i in range(n):\n estimators = min_estimators + spacing * i\n clf.set_params(n_estimators=estimators,max_depth=j)\n clf.fit(X_train, Y_train)\n estim.append(estimators)\n print(\"Maximum Depth {0}. Number of Estimators {1}\".format(j,estimators))\n # Record the OOB error for each `n_estimators=i` setting.\n oob_error = 1 - clf.oob_score_\n oob_error_test = 1 - clf.score(X_test, Y_test)\n error_rate.append(oob_error)\n error_rate_test.append(oob_error_test)\n\n # Generate the \"OOB error rate\" vs. \"n_estimators\" plot.\n ax0.plot(estim, error_rate, label=\"Max Depth = {0}\".format(j))\n ax1.plot(estim, error_rate_test, label=\"Max Depth = {0}\".format(j))\n del estim\n del error_rate\n del error_rate_test\n\nax0.set_xlim(min_estimators, max_estimators)\nax0.set_xlabel(\"Number of Estimators\", fontsize=20)\nax0.set_ylabel(\"OOB error rate\", fontsize=20)\nax0.set_title(\"OOB Error Rate Training\", fontsize=20)\nax0.legend(loc=1, fontsize=20)\n\nax1.set_xlim(min_estimators, max_estimators)\nax1.set_xlabel(\"Number of Estimators\", fontsize=20)\nax1.set_ylabel(\"OOB error rate\", fontsize=20)\nax1.set_title(\"OOB Error Rate Testing\", fontsize=20)\nax1.legend(loc=1, fontsize=20)\n\npp.savefig(fig)\npp.close()","sub_path":"RandomForest/RandomForestHypTuning.py","file_name":"RandomForestHypTuning.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"48481327","text":"import random\nimport collections\n\nfrom audiomate.corpus.subset import subview\nfrom audiomate.corpus.subset import utils\n\n\nclass Splitter(object):\n \"\"\"\n A splitter provides methods for splitting a corpus into different subsets.\n It provides different approaches for splitting the corpus. (Methods indicated by ``split_by_``)\n These methods mostly take some proportions parameter, which defines how big (in relation) the\n subsets should be. The subsets are returned as :py:class:`audiomate.corpus.Subview`.\n\n Args:\n corpus (Corpus): The corpus that should be splitted.\n random_seed (int): Seed to use for random number generation.\n \"\"\"\n\n def __init__(self, corpus, random_seed=None):\n self.corpus = corpus\n self.rand = random.Random()\n self.rand.seed(a=random_seed)\n\n def split_by_length_of_utterances(self, proportions={}, separate_issuers=False):\n \"\"\"\n Split the corpus into subsets where the total duration of subsets are proportional to the given proportions.\n The corpus gets splitted into len(proportions) parts, so the number of utterances are\n distributed according to the proportions.\n\n Args:\n proportions (dict): A dictionary containing the relative size of the target subsets.\n The key is an identifier for the subset.\n separate_issuers (bool): If True it makes sure that all utterances of an issuer are in the same subset.\n\n Returns:\n (dict): A dictionary containing the subsets with the identifier from the input as key.\n\n Example::\n\n >>> spl = Splitter(corpus)\n >>> corpus.num_utterances\n 100\n >>> subsets = spl.split_by_length_of_utterances(proportions={\n >>> \"train\" : 0.6,\n >>> \"dev\" : 0.2,\n >>> \"test\" : 0.2\n >>> })\n >>> print(subsets)\n {'dev': ,\n 'test': ,\n 'train': }\n >>> subsets['train'].num_utterances\n 60\n >>> subsets['test'].num_utterances\n 20\n \"\"\"\n\n utterance_to_duration = {}\n\n if separate_issuers:\n # Count total length of utterances per issuer\n issuer_utts_total_duration = collections.defaultdict(float)\n issuer_utts = collections.defaultdict(list)\n\n for utterance in self.corpus.utterances.values():\n issuer_utts_total_duration[utterance.issuer.idx] += utterance.duration\n issuer_utts[utterance.issuer.idx].append(utterance.idx)\n\n issuer_utts_total_duration = {k: {'duration': int(v)} for k, v in issuer_utts_total_duration.items()}\n\n # Split with total utt duration per issuer as weight\n issuer_splits = utils.get_identifiers_splitted_by_weights(issuer_utts_total_duration,\n proportions=proportions)\n\n # Collect utterances of all issuers per split\n splits = collections.defaultdict(list)\n\n for split_idx, issuer_ids in issuer_splits.items():\n for issuer_idx in issuer_ids:\n splits[split_idx].extend(issuer_utts[issuer_idx])\n else:\n for utterance in self.corpus.utterances.values():\n utterance_to_duration[utterance.idx] = {'length': int(utterance.duration * 100)}\n\n splits = utils.get_identifiers_splitted_by_weights(utterance_to_duration, proportions=proportions)\n\n return self._subviews_from_utterance_splits(splits)\n\n def split_by_number_of_utterances(self, proportions={}, separate_issuers=False):\n \"\"\"\n Split the corpus into subsets with the given number of utterances.\n The corpus gets splitted into len(proportions) parts, so the number of utterances are\n distributed according to the proportions.\n\n Args:\n proportions (dict): A dictionary containing the relative size of the target subsets.\n The key is an identifier for the subset.\n separate_issuers (bool): If True it makes sure that all utterances of an issuer are in the same subset.\n\n Returns:\n (dict): A dictionary containing the subsets with the identifier from the input as key.\n\n Example::\n\n >>> spl = Splitter(corpus)\n >>> corpus.num_utterances\n 100\n >>> subsets = spl.split_by_number_of_utterances(proportions={\n >>> \"train\" : 0.6,\n >>> \"dev\" : 0.2,\n >>> \"test\" : 0.2\n >>> })\n >>> print(subsets)\n {'dev': ,\n 'test': ,\n 'train': }\n >>> subsets['train'].num_utterances\n 60\n >>> subsets['test'].num_utterances\n 20\n \"\"\"\n\n if separate_issuers:\n # Count number of utterances per issuer\n issuer_utt_count = collections.defaultdict(int)\n issuer_utts = collections.defaultdict(list)\n\n for utterance in self.corpus.utterances.values():\n issuer_utt_count[utterance.issuer.idx] += 1\n issuer_utts[utterance.issuer.idx].append(utterance.idx)\n\n issuer_utt_count = {k: {'count': int(v)} for k, v in issuer_utt_count.items()}\n\n # Split with total utt duration per issuer as weight\n issuer_splits = utils.get_identifiers_splitted_by_weights(issuer_utt_count,\n proportions=proportions)\n\n # Collect utterances of all issuers per split\n splits = collections.defaultdict(list)\n\n for split_idx, issuer_ids in issuer_splits.items():\n for issuer_idx in issuer_ids:\n splits[split_idx].extend(issuer_utts[issuer_idx])\n else:\n utterance_idxs = sorted(list(self.corpus.utterances.keys()))\n self.rand.shuffle(utterance_idxs)\n splits = utils.split_identifiers(identifiers=utterance_idxs,\n proportions=proportions)\n\n return self._subviews_from_utterance_splits(splits)\n\n def split_by_proportionally_distribute_labels(self, proportions={}, use_lengths=True):\n \"\"\"\n Split the corpus into subsets, so the occurrence of the labels is distributed amongst the\n subsets according to the given proportions.\n\n Args:\n proportions (dict): A dictionary containing the relative size of the target subsets.\n The key is an identifier for the subset.\n use_lengths (bool): If True the lengths of the labels are considered for splitting proportionally,\n otherwise only the number of occurrences is taken into account.\n\n Returns:\n (dict): A dictionary containing the subsets with the identifier from the input as key.\n \"\"\"\n\n identifiers = {}\n\n for utterance in self.corpus.utterances.values():\n if use_lengths:\n identifiers[utterance.idx] = {l: int(d * 100) for l, d in utterance.label_total_duration().items()}\n else:\n identifiers[utterance.idx] = utterance.label_count()\n\n splits = utils.get_identifiers_splitted_by_weights(identifiers, proportions)\n\n return self._subviews_from_utterance_splits(splits)\n\n def _subviews_from_utterance_splits(self, splits):\n \"\"\"\n Create subviews from a dict containing utterance-ids for each subview.\n\n e.g. {'train': ['utt-1', 'utt-2'], 'test': [...], ...}\n \"\"\"\n subviews = {}\n\n for idx, subview_utterances in splits.items():\n filter = subview.MatchingUtteranceIdxFilter(utterance_idxs=subview_utterances)\n split = subview.Subview(self.corpus, filter_criteria=filter)\n subviews[idx] = split\n\n return subviews\n","sub_path":"audiomate/corpus/subset/splitting.py","file_name":"splitting.py","file_ext":"py","file_size_in_byte":8322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"478911218","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# Imports\nfrom luigi.contrib.spark import PySparkTask\nfrom luigi.parameter import IntParameter\nfrom luigi import LocalTarget, Task, WrapperTask\nfrom luigi.format import UTF8\nimport datetime\nimport pandas as pd\nimport re\nfrom nltk.stem.cistem import Cistem\nfrom Importer import Importer\nfrom configs.Configurations import Configurations\n\n\nclass Preprocessor(Task):\n\n # Date for Output-File prefix\n from datetime import date\n date = datetime.datetime.now()\n configId = IntParameter(default=0)\n\n # Method to declare the Output-File\n def output(self):\n prefix = self.date.strftime(\"%Y-%m-%dT%H%M%S\")\n return LocalTarget(\"../output/%s_configID_%s_Preprocessor_out.csv\" % (prefix, self.configId), format=UTF8)\n \n # Method to define the required Task (Importer)\n def requires(self):\n return Importer(self.configId)\n\n\n # Preprocess the imported Data\n def run(self):\n # use configID from commandline\n configs = Configurations().configs[self.configId]\n\n df = pd.read_csv(self.input().path)\n output_df = pd.DataFrame(columns=('text', 'cleaned_text', 'url', 'title', 'class'))\n\n for index, document in df.iterrows():\n # Text Preprocessing\n text = str(document.text)\n if configs.get(\"textToLowerCase\"):\n text = self.toLowerCase(str(document.text))\n if configs.get(\"textReplaceUmlaut\"):\n text = self.replaceUmlaut(text)\n if configs.get(\"textPriceTagger\"):\n text = self.priceTagger(text)\n if configs.get(\"textRemoveSpecialCharacters\"):\n text = self.removeSpecialCharacters(text)\n if configs.get(\"textRemoveSingleCharacters\"):\n text = self.removeSingleCharacters(text)\n if configs.get(\"textRemoveMultiSpaces\"):\n text = self.removeMultiSpaces(text)\n if configs.get(\"textStemText\"):\n text = self.stemText(text)\n if configs.get(\"textBeverageTagger\"):\n text = self.beverageTagger(text) \n if configs.get(\"textRemoveStopWords\"):\n text = self.removeStopWords(text)\n \n # Title Preprocessing\n title = str(document.title)\n if configs.get(\"titleToLowerCase\"):\n title = self.toLowerCase(str(document.title))\n if configs.get(\"titleReplaceUmlaut\"):\n title = self.replaceUmlaut(title)\n if configs.get(\"titlePriceTagger\"):\n title = self.priceTagger(title)\n if configs.get(\"titleRemoveSpecialCharacters\"):\n title = self.removeSpecialCharacters(title)\n if configs.get(\"titleRemoveSingleCharacters\"):\n title = self.removeSingleCharacters(title)\n if configs.get(\"titleRemoveMultiSpaces\"):\n title = self.removeMultiSpaces(title)\n if configs.get(\"titleStemText\"):\n title = self.stemText(title)\n if configs.get(\"titleRemoveStopWords\"):\n title = self.removeStopWords(title)\n\n # Write rows for Output-File\n row = [document.text, text, document.url, title, document.Class]\n output_df.loc[index] = row\n\n # Write .csv-File\n with self.output().open(\"w\") as out:\n output_df.to_csv(out, encoding=\"utf-8\")\n \n \n # External Methods for preprocessing\n def toLowerCase(self, text):\n return text.lower()\n\n def beverageTagger(self, text):\n bev = pd.read_csv('../beverage_list.txt', header=None)\n bev.columns = ['word']\n bevWords = self.stemText(\" \".join(bev.word))\n for i, word in enumerate(text):\n for bevWord in bevWords:\n if word == bevWord:\n text[i] = \"beverageentity\" \n return text\n\n def removeSpecialCharacters(self, text):\n return re.sub(r'[^éàèÉÀÈäöüÄÖÜa-zA-Z]+', ' ', str(text))\n \n def removeSingleCharacters(self, text):\n return re.sub(r'\\s+[a-zA-Z]\\s+', ' ', text)\n \n def removeMultiSpaces(self, text):\n return re.sub(r'\\s+', ' ', text, flags=re.I)\n \n def stemText(self, text):\n stemmer = Cistem()\n return [stemmer.stem(word) for word in text.split()]\n\n def stemWord(self, word):\n stemmer = Cistem()\n return stemmer.stem(word)\n \n def removeStopWords(self, text):\n # use own stopword list\n stop = pd.read_csv('../stopwords_no_umlaute.txt', header=None)\n stop.columns = ['word']\n if(Configurations().configs[self.configId].get(\"textStemText\")):\n stopwordSet = set(stop.word)\n else:\n stopWords = self.stemText(\" \".join(stop.word))\n stopwordSet = set(stopWords)\n text = self.stemText(text)\n for i, w in enumerate(text):\n if w in stopwordSet:\n del text[i]\n return text\n \n def replaceUmlaut(self, text):\n text = re.sub(r'ä', 'a', text)\n text = re.sub(r'ö', 'o', text)\n text = re.sub(r'ü', 'u', text)\n return text\n \n # Tag prices below 10.00 with onedigitprice\n # Tag prices between 10.00 and 100.00 with twodigitprice\n # Tag prices 100.00 or higher with threedigitprice\n def priceTagger(self, text):\n\n # match patterns with decimalpoint or comma, real rappen-values and chf,sfr,fr or .-:\n # whitespaces inside () are optional\n # characters inside [] are prohibited\n # x => number\n # a => letter\n # [x or a or , or .]xxx.xx( )chf[x or a]\n # matches for example: \" 0.65 chf\"\n text = re.sub(r'[^0-9a-z\\.\\,][0-9]{1,1}(\\.|\\,)[0-9](5|0)[ \\t]{0,}(chf|sfr|fr|\\.\\-)[^0-9a-z]', ' onedigitprice ', text)\n # matches for example: \" 51.80 sfr\" but not \" 01.80 sfr\"\n text = re.sub(r'[^0-9a-z\\.\\,][1-9]{1,1}[0-9]{1,1}(\\.|\\,)[0-9](5|0)[ \\t]{0,}(chf|sfr|fr|\\.\\-)[^0-9a-z]', ' twodigitprice ', text)\n # matches for example: \" 111.05 .-\" but not \" 031.80 .-\"\n text = re.sub(r'[^0-9a-z\\.\\,][1-9]{1,1}[0-9]{2,2}(\\.|\\,)[0-9](5|0)[ \\t]{0,}(chf|sfr|fr|\\.\\-)[^0-9a-z]', ' threedigitprice ', text)\n \n # match following patterns with chf,sfr,fr or .-:\n # characters inside () are optional\n # characters inside [] are prohibited\n # x => number\n # a => letter\n # [x or a or , or .]xxx( )chf[x or a]\n # matches for example: \" 3chf\"\n text = re.sub(r'[^0-9a-z\\.\\,][1-9]{1,1}[ \\t]{0,}(chf|sfr|fr|\\.\\-)[^0-9a-z]', ' onedigitprice ', text)\n # matches for example: \" 10 sfr\" but not \" 09 sfr\"\n text = re.sub(r'[^0-9a-z\\.\\,][1-9]{1,1}[0-9]{1,1}[ \\t]{0,}(chf|sfr|fr|\\.\\-)[^0-9a-z]', ' twodigitprice ', text)\n # matches for example: \" 210 fr\" but not \" 029 fr\"\n text = re.sub(r'[^0-9a-z\\.\\,][1-9]{1,1}[0-9]{2,2}[ \\t]{0,}(chf|sfr|fr|\\.\\-)[^0-9a-z]', ' threedigitprice ', text)\n \n # match following patterns with decimalpoint or comma, real rappen-values and chf,sfr,fr or .-:\n # characters inside () are optional\n # characters inside [] are prohibited\n # x => number\n # a => letter\n # [x or a or , or .]chf(.)( )xxx.xx[x or a]\n # matches for example: \" chf: 0.65\" \n text = re.sub(r'[^0-9a-z\\.\\,](chf|sfr|fr)[\\:|\\,|\\.]{0,1}[ \\t]{0,}[0-9]{1,1}(\\.|\\,)[0-9](5|0)[^0-9a-z]', ' onedigitprice ', text)\n # matches for example: \" sfr, 12.65\" but not \" sfr, 02.65\"\n text = re.sub(r'[^0-9a-z\\.\\,](chf|sfr|fr)[\\:|\\,|\\.]{0,1}[ \\t]{0,}[1-9]{1,1}[0-9]{1,1}(\\.|\\,)[0-9](5|0)[^0-9a-z]', ' twodigitprice ', text)\n # matches for example: \" fr. 412.65\" but not \" fr. 042.65\"\n text = re.sub(r'[^0-9a-z\\.\\,](chf|sfr|fr)[\\:|\\,|\\.]{0,1}[ \\t]{0,}[1-9]{1,1}[0-9]{2,2}(\\.|\\,)[0-9](5|0)[^0-9a-z]', ' threedigitprice ', text)\n \n # match following patterns with decimalpoint or comma and real rappen-values:\n # characters inside () are optional\n # characters inside [] are prohibited\n # x => number\n # a => letter\n # [x or a or , or .]xxx.xx[x or a]\n # to avoid detecting day times or dates the regex only detects\n # prices with values after decimalpoint over 59 (i.e 12.60 or 1.65)\n # matches for example: \" 2.60\" but not \" 2.55\"\n text = re.sub(r'[^0-9a-z\\.\\,][0-9]{1,1}(\\.|\\,)[6-9](0|5)[^0-9\\.a-z]', ' onedigitprice ', text)\n # matches for example: \" 12.70\" but not \" 02.55\" or neither \" 12.40\"\n text = re.sub(r'[^0-9a-z\\.\\,][1-9]{1,1}[0-9]{1,1}(\\.|\\,)[6-9](0|5)[^0-9\\.a-z]', ' twodigitprice ', text)\n # matches for example: \" 126.70\" and \" 126.35\" but not \" 032.55\"\n text = re.sub(r'[^0-9a-z\\.\\,][1-9]{1,1}[0-9]{2,2}(\\.|\\,)[0-9](0|5)[^0-9\\.a-z]', ' threedigitprice ', text)\n return text","sub_path":"classification/scripts/Preprocessor.py","file_name":"Preprocessor.py","file_ext":"py","file_size_in_byte":8997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"232840329","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.io import loadmat\r\n\r\n#ML2018fall @ NCTU HW4 code\r\n#developped on MacOS/Windows10\r\n#author : maxwill lin 0712238\r\n#version control with git/github\r\n#tool used : jupyter notebook\r\n#programming language : python3.7\r\n#https://github.com/EazyReal/ML2018fall/blob/master/MLHW4/hw4.py\r\n\r\n\r\n#Be careful with the file path!\r\ndata = loadmat('data/hw4.mat')\r\nfrom sklearn.preprocessing import OneHotEncoder\r\nencoder = OneHotEncoder(sparse=False)\r\ny_onehot = encoder.fit_transform(data['y'])\r\n \r\ndef sigmoid(z):\r\n return 1 / (1 + np.exp(-z))\r\n \r\ndef forward_propagate(X, theta1, theta2):\r\n m = X.shape[0] #data number\r\n\r\n #theta= matrix of out_size * in_size+1 w*X\r\n\r\n #Write codes here\r\n #np.array([np.dot(np.array(w), X[i]) for i in range(m)])\r\n #z = a*w.transpose()\r\n a1 = np.c_[np.ones(m), X] #add an 1 to Xi(first column), type = matrix\r\n z2 = a1 * theta1.transpose() #m*i * i*o = m*o\r\n a2 = np.c_[np.ones(m), sigmoid(z2)] \r\n z3 = a2 * theta2.transpose()\r\n h = sigmoid(z3)\r\n \r\n return a1, z2, a2, z3, h\r\n \r\ndef cost(params, input_size, hidden_size, num_labels, X, y, learning_rate):\r\n m = X.shape[0]\r\n X = np.matrix(X)\r\n y = np.matrix(y)\r\n # reshape the parameter array into parameter matrices for each layer\r\n theta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))\r\n theta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))\r\n # run the feed-forward pass\r\n a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)\r\n # compute the cost\r\n J = 0\r\n for i in range(m):\r\n first_term = np.multiply(-y[i,:], np.log(h[i,:]))\r\n second_term = np.multiply((1 - y[i,:]), np.log(1 - h[i,:]))\r\n J += np.sum(first_term - second_term)\r\n \r\n J = J / m\r\n J += (float(learning_rate) / (2*m) * (np.sum(np.power(theta1[:,1:], 2)) + np.sum(np.power(theta2[:,1:], 2))))\r\n #no need to regularized thetak[:][0] (bias term)\r\n \r\n return J\r\n \r\n# initial setup\r\ninput_size = 400\r\nhidden_size = 10\r\nnum_labels = 10\r\nlearning_rate = 1\r\nlambda_ = 0.01\r\n#lambda=0.01/m => 96%up accuracy\r\n# randomly initialize a parameter array of the size of the full network's parameters\r\nparams = (np.random.random(size=hidden_size * (input_size + 1) + num_labels * (hidden_size + 1)) - 0.5) * 0.2\r\nm = data['X'].shape[0]\r\nX = np.matrix(data['X'])\r\ny = np.matrix(data['y'])\r\n# unravel the parameter array into parameter matrices for each layer\r\ntheta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))\r\ntheta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))\r\n\r\na1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)\r\n\r\ndef sigmoid_gradient(z):\r\n return np.multiply(sigmoid(z), (1 - sigmoid(z))) \r\n\r\ndef backprop(params, input_size, hidden_size, num_labels, X, y, learning_rate):\r\n m = X.shape[0] #size\r\n \r\n #Write codes here\r\n #J = 0.0\r\n #grad = grad of each theta(i,j) init= np.zeros(params.shape)\r\n\r\n theta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))\r\n theta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))\r\n a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)\r\n J = cost(params, input_size, hidden_size, num_labels, X, y, learning_rate)\r\n\r\n #calculate delta\r\n delta3 = h-y #(m, nlab)\r\n #delta3 = np.multiply(delta3, sigmoid_gradient(z3))\r\n delta2 = np.multiply(delta3*theta2[:,1:], sigmoid_gradient(z2))#(m,n) * (n,hidden+1) (5000*10**10*11)\r\n\r\n d_b2 = (np.sum(delta3, axis=0)/m).transpose() #10*1\r\n d_b1 = (np.sum(delta2, axis=0)/m).transpose() #10*1\r\n #print(a2.shape) 5000*11\r\n d_w2 = np.dot(delta3.transpose(), a2[:,1:])/m + lambda_/m*theta2[:,1:] #10*10\r\n d_w1 = np.dot(delta2.transpose(), X)/m + lambda_/m*theta1[:,1:] #10*400\r\n d_t1 = np.array(np.c_[d_b1, d_w1]).flatten()\r\n d_t2 = np.array(np.c_[d_b2, d_w2]).flatten()\r\n grad = np.concatenate((d_t1, d_t2))\r\n #grad = np.c_[d_t1, d_t2].flatten() lead to bug\r\n\r\n return J, grad\r\n\r\n \r\nfrom scipy.optimize import minimize\r\n# minimize the objective function\r\nfmin = minimize(fun=backprop, x0=params, args=(input_size, hidden_size, num_labels, X, y_onehot, learning_rate), method='TNC', jac=True, options={'maxiter': 250})\r\n \r\nX = np.matrix(X)\r\ntheta1 = np.matrix(np.reshape(fmin.x[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))\r\ntheta2 = np.matrix(np.reshape(fmin.x[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))\r\na1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)\r\ny_pred = np.array(np.argmax(h, axis=1) + 1)\r\n\r\ncorrect = [1 if a == b else 0 for (a, b) in zip(y_pred, y)]\r\naccuracy = (sum(map(int, correct)) / float(len(correct)))\r\nprint ('accuracy = {0}%'.format(accuracy * 100))","sub_path":"MLHW4/hw4.py","file_name":"hw4.py","file_ext":"py","file_size_in_byte":5033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"222024673","text":"from setuptools import setup, find_packages\nimport os\n\nversion = '1.0'\nname = 'slapos.extension.shared'\n\ndef read(*rnames):\n return open(os.path.join(os.path.dirname(__file__), *rnames)).read()\n\nsetup(\n name=name,\n version=version,\n description=\"zc.buildout extension for SlapOS's shared feature.\",\n long_description=(\n read('README.rst')\n + '\\n' +\n read('CHANGELOG.rst')\n + '\\n' +\n 'Download\\n'\n '***********************\\n'\n ),\n classifiers=[\n 'Programming Language :: Python',\n ],\n keywords='slapos shared',\n author='Yusei Tahara',\n author_email='yusei@nexedi.com',\n url='https://lab.nexedi.com/nexedi/slapos.extension.shared',\n license='GPLv3',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['slapos', 'slapos.extension'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'zc.buildout',\n ],\n entry_points = { \n 'zc.buildout.unloadextension': [\n 'default = slapos.extension.shared:finish',\n ],\n },\n)\n","sub_path":"pypi_install_script/slapos.extension.shared-1.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"397108992","text":"# -*- coding: utf-8 -*-\n#-------------------------------EXERCICIO 2------------------------------------------\nnota_1 = input('Digite nota 1: ')\nnota_1 = float(nota_1)\n\nnota_2 = input('Digite nota 2: ')\nnota_2 = float(nota_2)\n\nmedia = (nota_1 + nota_2) / 2\nprint('Média Aluno: ',media)\n\nif media >= 6:\n print('Aluno Aprovado')\nelif media > 0 and media < 6:\n print('Aluno Reprovado')\nelse:\n print('Nota invalida')","sub_path":"nota.py","file_name":"nota.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"457796772","text":"#!/usr/bin/python\n#-*- coding:utf-8 -*-\n\nfrom workflow import Workflow, ICON_WEB, web\nimport sys\nimport requests\nimport re\n\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\ndef hotelsearch(keyword):\n url = 'https://release2.changker.com/api/search/hotels/combo?'\n params = dict(ckuid='10038452', v='1.6', poi='39.984450,116.489390',\n name=keyword, pagesize='20', version='1.6')\n header = {'token': '0f8e3c49ac7823e8c89f7e87a324686d'}\n try:\n r = requests.post(url, params, headers=header)\n r.raise_for_status()\n hotels = r.json()\n hotel = hotels['data'][0]\n except:\n wf.add_item('抱歉,没有找到符合条件的酒店', '请重新输入关键词', arg=None, valid=False, icon='hotel.png')\n wf.send_feedback()\n return hotel['uid']\n\n\ndef hoteldetail(hoteluid):\n url = 'https://release2.changker.com/api/hotel/' + str(hoteluid) + '?'\n params = dict(ckuid='10038452', version='1.6')\n header = {'token': '0f8e3c49ac7823e8c89f7e87a324686d'}\n try:\n r = requests.post(url, params, headers=header)\n r.raise_for_status()\n hoteldetail = r.json()\n if not hoteldetail['data'] == []:\n hotel = hoteldetail['data']\n detailurl = 'https://cms.changker.com/index.php?r=hotel/update&id=' + str(hotel['uid'])\n if hotel['scores']['share_count'] == None:\n hotel['share_count'] = '0'\n if hotel['photos'] == None:\n hotel['photos'] = '0'\n if hotel['reviews'] == None:\n hotel['reviews'] = '0'\n wf.add_item(hotel['name'],\n '类型 : ' + hotel['category']['name'] + ' 分享数 : ' + str(hotel['scores']['share_count']) + ' 平均分 : ' + str(\n hotel['scores']['score_average']) + ' 展示图:' + str(len(hotel['photos'])) + ' 点评数:' + str(len(hotel['reviews'])),\n arg=detailurl,\n valid=True,\n icon='hotel.png')\n picurl = 'https://cms.changker.com/index.php?r=photo/create&mid=' + \\\n str(hotel['uid']) + '&type=hotel'\n wf.add_item('为该酒店添加新的展示图'\n '',\n arg=picurl,\n valid=True,\n icon='add.png')\n reviewurl = 'https://cms.changker.com/index.php?r=review/create&mid=' + \\\n str(hotel['uid']) + '&type=hotel'\n wf.add_item('为该酒店添加新的点评语'\n '',\n arg=reviewurl,\n valid=True,\n icon='add.png')\n else:\n wf.add_item('抱歉,没有找到符合条件的酒店', '请重新输入关键词', arg=None, valid=False, icon='hotel.png')\n wf.send_feedback()\n except:\n wf.add_item('抱歉,没有找到符合条件的酒店', '请重新输入关键词', arg=None, valid=False, icon='hotel.png')\n wf.send_feedback()\n\n\ndef hotelfeed(hoteluid):\n url = 'https://release2.changker.com/api/hotel/' + str(hoteluid) + '/feedlist?'\n params = dict(ckuid=10038452, v=1.6, pagesize=20, version=1.6)\n header = {'token': '0f8e3c49ac7823e8c89f7e87a324686d'}\n try:\n r = requests.post(url, params, headers=header)\n r.raise_for_status()\n hotelfeed = r.json()\n except:\n wf.add_item('没有获取到该酒店信息,请重试', '', arg='', valid=True, icon='mem.png')\n wf.send_feedback()\n return hotelfeed\n\n\ndef main(wf):\n keyword = wf.args[0]\n hoteluid = hotelsearch(keyword)\n try:\n hoteldetail(hoteluid)\n hotelfeeds = hotelfeed(hoteluid)\n if not hotelfeeds['data']['info'] == []:\n for feed in hotelfeeds['data']['info']:\n url = 'https://cms.changker.com/index.php?r=weibo/view&id=' + str(feed['id'])\n content = feed['content']\n retext = re.sub(r'<.*?>', '', content, 0)\n wf.add_item(retext,\n 'ID:' + feed['id'] + ' UID:' + feed['uid'] + ' 图片数:' + str(\n len(feed['images'])) + ' 评论数:' + feed['comment_count'] + ' 点赞数:' + feed['praise_count'],\n arg=url,\n valid=True,\n icon='mem.png')\n else:\n wf.add_item('该酒店暂时还没有点评', '', arg='', valid=True, icon='mem.png')\n except:\n wf.add_item('没有获取到该酒店信息,请重试', '', arg='', valid=True, icon='mem.png')\n wf.send_feedback()\n\nif __name__ == '__main__':\n wf = Workflow()\n sys.exit(wf.run(main))\n","sub_path":"Changker_Alfred/hotel.py","file_name":"hotel.py","file_ext":"py","file_size_in_byte":4815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"128022049","text":"\"\"\"\n Customer database schema model\n\"\"\"\n\n# pylint: disable=too-few-public-methods\n# pylint: disable=unused-wildcard-import\n# pylint: disable=wildcard-import\n# pylint: disable=unused-import\n# pylint: disable=invalid-name\n# pylint: disable=unused-argument\n# pylint: disable=too-many-arguments\n# pylint: disable=unnecessary-pass\n# pylint: disable=no-self-use\n\n\nfrom peewee import *\n\ndatabase = SqliteDatabase('customers.db')\ndatabase.connect()\ndatabase.execute_sql('PRAGMA foreign_keys = ON;')\n\nclass BaseModel(Model):\n '''BaseModel class for sqlite database init'''\n class Meta:\n '''Meta class for sqlite database init'''\n database = database\n\n\nclass Customer(BaseModel):\n '''\n This class defines Customer, which contains customer data.\n '''\n customer_id = CharField(primary_key=True, max_length=10)\n first_name = CharField(max_length=15)\n last_name = CharField(max_length=15)\n home_address = CharField(max_length=40, null=True)\n phone_number = IntegerField(null=True)\n email_address = CharField(max_length=40, null=True)\n activity_status = BooleanField()\n credit_limit = DecimalField(max_digits=7, decimal_places=2, null=True)\n","sub_path":"students/mmancini/lesson03/customers_model.py","file_name":"customers_model.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"631350519","text":"#!/usr/bin/env python\n\nimport re\nfrom pprint import pprint\nfrom collections import OrderedDict\nfrom datetime import timedelta\n\nfrom first import first\n\nfrom ranking.management.modules.common import REQ, BaseModule, parsed_table\nfrom ranking.management.modules import conf\n\n\nclass Statistic(BaseModule):\n\n def __init__(self, **kwargs):\n super(Statistic, self).__init__(**kwargs)\n\n def get_standings(self, users=None, statistics=None):\n if not self.standings_url:\n self.standings_url = f'https://projecteuler.net/fastest={self.key}'\n\n result = {}\n\n page = REQ.get(self.standings_url, headers=conf.PROJECTEULER_COOKIE_HEADER)\n regex = ']*>.*?'\n html_table = re.search(regex, page, re.DOTALL).group(0)\n table = parsed_table.ParsedTable(html_table)\n\n for r in table:\n row = OrderedDict()\n row['solving'] = 1\n for k, v in r.items():\n if isinstance(v, list):\n place, country = v\n row['place'] = re.match('[0-9]+', place.value).group(0)\n country = first(country.column.node.xpath('.//@title'))\n if country:\n row['country'] = country\n elif k == 'Time To Solve':\n params = {}\n for x in v.value.split(', '):\n value, field = x.split()\n if field[-1] != 's':\n field += 's'\n params[field] = int(value)\n delta = timedelta(**params)\n row['penalty'] = f'{delta.total_seconds() / 60:.2f}'\n elif k == 'User':\n member = first(v.column.node.xpath('.//@title')) or v.value\n row['member'] = member\n else:\n row[k.lower()] = v.value\n if 'member' not in row:\n continue\n result[row['member']] = row\n\n standings = {\n 'result': result,\n 'url': self.standings_url,\n 'problems': [],\n }\n return standings\n\n\nif __name__ == \"__main__\":\n statictic = Statistic(url='https://projecteuler.net/problem=689', key='689', standings_url=None)\n pprint(statictic.get_result('theshuffler', 'Tepsi', 'jpeg13'))\n","sub_path":"ranking/management/modules/projecteuler.py","file_name":"projecteuler.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"342678590","text":"import asyncio\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import Any\n\nimport orjson\nfrom fastapi import FastAPI, Form, HTTPException, UploadFile\nfrom fastapi.responses import ORJSONResponse\nfrom starlette.formparsers import MultiPartParser\n\nfrom app.models.base import InferenceModel\n\nfrom .config import log, settings\nfrom .models.cache import ModelCache\nfrom .schemas import (\n MessageResponse,\n ModelType,\n TextResponse,\n)\n\nMultiPartParser.max_file_size = 2**24 # spools to disk if payload is 16 MiB or larger\napp = FastAPI()\n\n\ndef init_state() -> None:\n app.state.model_cache = ModelCache(ttl=settings.model_ttl, revalidate=settings.model_ttl > 0)\n log.info(\n (\n \"Created in-memory cache with unloading \"\n f\"{f'after {settings.model_ttl}s of inactivity' if settings.model_ttl > 0 else 'disabled'}.\"\n )\n )\n # asyncio is a huge bottleneck for performance, so we use a thread pool to run blocking code\n app.state.thread_pool = ThreadPoolExecutor(settings.request_threads) if settings.request_threads > 0 else None\n log.info(f\"Initialized request thread pool with {settings.request_threads} threads.\")\n\n\n@app.on_event(\"startup\")\nasync def startup_event() -> None:\n init_state()\n\n\n@app.get(\"/\", response_model=MessageResponse)\nasync def root() -> dict[str, str]:\n return {\"message\": \"Immich ML\"}\n\n\n@app.get(\"/ping\", response_model=TextResponse)\ndef ping() -> str:\n return \"pong\"\n\n\n@app.post(\"/predict\")\nasync def predict(\n model_name: str = Form(alias=\"modelName\"),\n model_type: ModelType = Form(alias=\"modelType\"),\n options: str = Form(default=\"{}\"),\n text: str | None = Form(default=None),\n image: UploadFile | None = None,\n) -> Any:\n if image is not None:\n inputs: str | bytes = await image.read()\n elif text is not None:\n inputs = text\n else:\n raise HTTPException(400, \"Either image or text must be provided\")\n\n model: InferenceModel = await app.state.model_cache.get(model_name, model_type, **orjson.loads(options))\n outputs = await run(model, inputs)\n return ORJSONResponse(outputs)\n\n\nasync def run(model: InferenceModel, inputs: Any) -> Any:\n if app.state.thread_pool is not None:\n return await asyncio.get_running_loop().run_in_executor(app.state.thread_pool, model.predict, inputs)\n else:\n return model.predict(inputs)\n","sub_path":"machine-learning/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"265104649","text":"from __future__ import annotations\n\nfrom collections.abc import Iterable, Mapping\nfrom contextlib import nullcontext\nimport os\nfrom pathlib import Path\nimport re\nimport tempfile\nfrom types import MappingProxyType\nfrom typing import Any\n\nfrom markdown_it import MarkdownIt\nfrom markdown_it.renderer import RendererHTML\n\nimport mdformat.plugins\n\nNULL_CTX = nullcontext()\nEMPTY_MAP: MappingProxyType = MappingProxyType({})\n\n\ndef build_mdit(\n renderer_cls: Any,\n *,\n mdformat_opts: Mapping[str, Any] = EMPTY_MAP,\n extensions: Iterable[str] = (),\n codeformatters: Iterable[str] = (),\n) -> MarkdownIt:\n mdit = MarkdownIt(renderer_cls=renderer_cls)\n mdit.options[\"mdformat\"] = mdformat_opts\n # store reference labels in link/image tokens\n mdit.options[\"store_labels\"] = True\n\n mdit.options[\"parser_extension\"] = []\n for name in extensions:\n plugin = mdformat.plugins.PARSER_EXTENSIONS[name]\n if plugin not in mdit.options[\"parser_extension\"]:\n mdit.options[\"parser_extension\"].append(plugin)\n plugin.update_mdit(mdit)\n\n mdit.options[\"codeformatters\"] = {\n lang: mdformat.plugins.CODEFORMATTERS[lang] for lang in codeformatters\n }\n\n return mdit\n\n\ndef is_md_equal(\n md1: str,\n md2: str,\n *,\n options: Mapping[str, Any] = EMPTY_MAP,\n extensions: Iterable[str] = (),\n codeformatters: Iterable[str] = (),\n) -> bool:\n \"\"\"Check if two Markdown produce the same HTML.\n\n Renders HTML from both Markdown strings, reduces consecutive\n whitespace to a single space and checks equality. Note that this is\n not a perfect solution, as there can be meaningful whitespace in\n HTML, e.g. in a block.\n \"\"\"\n html_texts = {}\n mdit = build_mdit(RendererHTML, mdformat_opts=options, extensions=extensions)\n for key, text in [(\"md1\", md1), (\"md2\", md2)]:\n html = mdit.render(text)\n\n # The HTML can start with whitespace if Markdown starts with raw HTML\n # preceded by whitespace. This whitespace should be safe to strip.\n html = html.lstrip()\n\n # Remove codeblocks because code formatter plugins do arbitrary changes.\n for codeclass in codeformatters:\n html = re.sub(\n f'.*',\n \"\",\n html,\n flags=re.DOTALL,\n )\n\n # Reduce all whitespace to a single space\n html = re.sub(r\"\\s+\", \" \", html)\n\n # Strip insignificant paragraph leading/trailing whitespace\n html = html.replace(\"

\", \"

\")\n html = html.replace(\"

\", \"

\")\n\n # empty p elements should be ignored by user agents\n # (https://www.w3.org/TR/REC-html40/struct/text.html#edef-P)\n html = html.replace(\"

\", \"\")\n\n # If it's nothing but whitespace, it's equal\n html = re.sub(r\"^\\s+$\", \"\", html)\n\n html_texts[key] = html\n\n return html_texts[\"md1\"] == html_texts[\"md2\"]\n\n\ndef atomic_write(path: Path, text: str, newline: str) -> None:\n \"\"\"A function for atomic writes to a file.\n\n Writes a temporary file first and then replaces the original file\n with the temporary one. This is to avoid a moment where only empty\n or partial content exists on disk.\n \"\"\"\n fd, tmp_path = tempfile.mkstemp(dir=path.parent)\n try:\n with open(fd, \"w\", encoding=\"utf-8\", newline=newline) as f:\n f.write(text)\n os.replace(tmp_path, path)\n except BaseException:\n os.remove(tmp_path)\n raise\n","sub_path":"src/mdformat/_util.py","file_name":"_util.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"631400586","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nimport article\nfrom article.views import HelloTemplate\n\n\nadmin.autodiscover()\n\n\nurlpatterns = patterns('',\n (r'^articles/', include('article.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^hello/$', 'article.views.hello'),\n url(r'^hello_template/$', 'article.views.hello_template'),\n url(r'^hello_template_simple/$', 'article.views.hello_template_simple'),\n url(r'^hello_class_view/$', HelloTemplate.as_view()),\n\n\n # user auth urls\n url(r'^accounts/login/$', 'django_test.views.login'),\n url(r'^accounts/auth/$', 'django_test.views.auth_view'),\n url(r'^accounts/logout/$', 'django_test.views.logout'),\n url(r'^accounts/loggedin/$', 'django_test.views.loggedin'),\n url(r'^accounts/invalid/$', 'django_test.views.invalid_login'),\n url(r'^accounts/register/$', 'django_test.views.register_user'),\n url(r'^accounts/register_success/$', 'django_test.views.register_success'),\n)","sub_path":"django_test/django_test/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"342939682","text":"import numpy\nimport random\nimport time\nfrom sklearn.neighbors import KernelDensity\nfrom isskmeans import ISSKMeans\n# from isskdekmeans import ISSKDEKMeans\nfrom kde import KDE\nimport matplotlib.pyplot as plt\nimport math\n\nfrom sklearn.base import BaseEstimator\n\nimport logging\n\nclass ISSKMeansKDE(BaseEstimator):\n\n def __init__(self, kernel='gaussian', bandwidth=-1):\n # bins: int, sequence, string(method)\n self.kernel = kernel\n self.bandwidth = bandwidth\n self.labels_ = 0\n self.accuracy = 0.0\n self.offline_training_time = 0.0\n self.kms_clusterclass = []\n self.kms_clusterbetter = []\n\n def get_kernel_density(self, X):\n # Grid search best bandwidth using Cross-Validation\n if self.bandwidth == -1:\n if X.shape[0] > 10:\n from sklearn.model_selection import GridSearchCV\n grid = GridSearchCV(KernelDensity(),\n {'bandwidth': numpy.linspace(0.1, 1.0, 30)},\n cv=10) # 10-fold cross-validation\n grid.fit(X)\n bandwidth = grid.best_params_['bandwidth']\n else:\n bandwidth = 0.2\n\n \"\"\"Kernel Density Estimation with Scikit-learn\"\"\"\n kde_skl = KernelDensity(bandwidth=bandwidth)\n kde_skl.fit(X)\n pdf = kde_skl\n\n return pdf\n\n def fit(self, X, T):\n T_unique = sorted(numpy.unique(T))\n clusters = []\n classes = []\n logpriors = []\n for t in T_unique:\n t_samples = (T == t)\n pdf = self.get_kernel_density(X[t_samples, :])\n clusters.append(pdf)\n classes.append(t)\n logpriors.append(numpy.log(X[t_samples, :].shape[0] / X.shape[0]))\n\n self.clusters = clusters\n self.nk = len(clusters)\n self.classes = classes\n self.X = X\n self.T = T\n self.logpriors = logpriors\n\n proba = self.predict_proba(X).T\n output_kde = numpy.array([classes[i] for i in numpy.argmax(proba, axis=0)])\n self.labels_ = output_kde\n\n from sklearn.metrics import accuracy_score\n self.accuracy = accuracy_score(T, self.labels_)\n self.kms_clusterbetter = numpy.zeros((self.nk,), dtype=bool)\n self.kms_clusterclass = []\n\n # ISS K-Means Clustering\n for c in range(self.nk):\n iyc = (output_kde == classes[c]).nonzero()\n iyc = iyc[0]\n Xc = X[iyc, :]\n Tc_t = T[iyc]\n Tc_y = output_kde[iyc]\n\n if (Tc_y != Tc_t).any(): # maybe check if all labels are the same class?\n cini = 'quantile'\n mos = [1]\n else:\n cini = 'point'\n mos = [0]\n\n n_c = len(T_unique)\n nks = [2 * n_c]\n n = [X.shape[1]]\n w = [numpy.ones((2 * n_c, X.shape[1]))]\n dts = ['euclidean']\n nits = [100]\n thds = [0]\n alphas = [0.75]\n\n logging.info('K-Means clustering...')\n\n kms = ISSKMeans(nk=nks[0], n=n[0], w=w[0], dt=dts[0], cini=cini, nit=nits[0], thd=thds[0], alpha=alphas[0], mo=mos[0])\n kms.fit(Xc, Tc_t)\n self.kms_clusterclass.append(kms)\n output_kms = kms.predict(Xc)\n\n accuracy_kde = accuracy_score(T[iyc], output_kde[iyc])\n accuracy_kms = accuracy_score(T[iyc], output_kms)\n if accuracy_kms >= accuracy_kde:\n self.labels_[iyc] = output_kms[:, 0]\n self.kms_clusterbetter[c] = True\n\n new_accuracy = accuracy_score(T, self.labels_)\n if new_accuracy > self.accuracy:\n logging.info('Improved accuracy from %f -> %f' % (self.accuracy, new_accuracy))\n self.accuracy = new_accuracy\n\n return self.labels_\n\n def predict_proba(self, X):\n if len(X.shape) == 1:\n X = X.reshape((1, X.shape[0]))\n logprobs = numpy.vstack([pdf.score_samples(X)\n for pdf in self.clusters]).T\n result = numpy.exp(logprobs + self.logpriors)\n return result / result.sum(1, keepdims=True)\n\n def predict(self, X):\n if len(X.shape) == 1:\n X = X.reshape((1, X.shape[0]))\n proba = self.predict_proba(X).T\n y = numpy.array([self.classes[i] for i in numpy.argmax(proba, axis=0)])\n\n # Polling ISSKMeans to improve classification\n iy = numpy.argmax(proba, axis=0)\n for i in iy:\n if self.kms_clusterbetter[i]: # ask or not????\n iyc = (y == self.classes[i]).nonzero()\n iyc = iyc[0]\n output_kms = self.kms_clusterclass[i].predict(X[iyc, :])\n y[iyc] = output_kms[:, 0]\n\n return y\n\n def fit_labeled(self, xi, yi):\n xi = xi.reshape((1, xi.shape[0]))\n yi = yi.reshape((1,))\n # inefficient way\n self.X = numpy.concatenate((self.X, xi), axis=0)\n self.T = numpy.concatenate((self.T, yi))\n self.fit(self.X, self.T)\n return self.predict(xi)[0]\n\n def fit_unlabeled(self, xi):\n # # Inefficient way\n # yi = self.predict(xi)[0]\n # return self.fit_labeled(xi, yi), True\n\n # Better way\n if len(xi.shape) == 1:\n xi = xi.reshape((1, xi.shape[0]))\n proba = self.predict_proba(xi).T\n y = numpy.array([self.classes[i] for i in numpy.argmax(proba, axis=0)])\n accepted = (numpy.max(proba) > 0.5)\n\n # Polling ISSKMeans to fit unlabeled\n i = numpy.argmax(proba, axis=0)\n i = i[0]\n if self.kms_clusterclass[i]:\n # y, accepted = self.kms_clusterclass[i].fit_unlabeled(xi, wd=0, vector=False)\n y, accepted = self.kms_clusterclass[i].fit_unlabeled2(xi)\n return y, accepted\n\n def fit_unlabeled_batch(self, X):\n return 0\n\nclass KDEEnsemble(BaseEstimator):\n def __init__(self, kernel='gaussian', bandwidth=-1):\n self.kernel = kernel\n self.bandwidth = bandwidth\n # self.wkm = numpy.zeros((self.nkm,), dtype=numpy.float64)\n self.mode = 1 # 0: vote; 1: distance\n self.offline_training_time = 0.0\n\n def fit(self, X, y):\n _start_time = time.time()\n self.n = X.shape[1]\n self.nmodels = self.n+1\n self.models = []\n self.fsel = numpy.ones((self.nmodels, self.n), dtype=bool)\n indices = []\n for i in range(self.n):\n index = random.randint(0, self.n - 1)\n while index in indices:\n index = random.randint(0, self.n - 1)\n indices.append(index)\n self.fsel[i, index] = False\n\n pout = numpy.zeros((self.nmodels, X.shape[0]), dtype=numpy.int64)\n for i in range(0, self.nmodels):\n self.models.append(KDE())\n pout[i, :] = self.models[i].fit(X[:, self.fsel[i, :]], y).reshape(-1)\n _end_time = time.time()\n self.offline_training_time = _end_time - _start_time\n\n from scipy import stats\n mode = stats.mode(pout, axis=0)\n return mode[0].reshape(-1)\n\n def fit_labeled(self, xi, yi):\n for i in range(0, self.nmodels):\n self.models[i].fit_labeled(xi[:, self.fsel[i, :]], yi)\n\n def fit_unlabeled(self, xi):\n pucls = numpy.zeros((self.nmodels,), dtype=numpy.int64)\n puacpt = numpy.zeros((self.nmodels,), dtype=bool)\n pudist = numpy.zeros((self.nmodels,), dtype=numpy.float64)\n for i in range(0, self.nmodels):\n pucls[i], puacpt[i], pudist[i] = self.models[i].fit_unlabeled(xi[self.fsel[i, :]])\n\n puclsacpt = pucls[puacpt]\n if self.mode == 0:\n from scipy import stats\n mode = stats.mode(puclsacpt)\n if len(puclsacpt) > 0:\n return mode[0][0], True\n else:\n return -1, False\n else:\n if len(puclsacpt) > 0:\n pudist = pudist[puacpt]\n neari = numpy.argmin(pudist)\n if isinstance(neari, numpy.ndarray):\n return puclsacpt[neari[0]], True\n else:\n return puclsacpt[neari], True\n else:\n return -1, False\n\n\n def predict(self, X):\n pout = numpy.zeros((self.nmodels, X.shape[0]), dtype=numpy.int64)\n pdist = numpy.zeros((self.nmodels, X.shape[0]), dtype=numpy.float64)\n for i in range(0, self.nmodels):\n out, dist = self.models[i].predict(X[:, self.fsel[i, :]])\n pout[i, :], pdist[i, :] = out.reshape(-1), dist.reshape(-1)\n\n if self.mode == 0:\n from scipy import stats\n mode = stats.mode(pout, axis=0)\n return mode[0].reshape(-1)\n else:\n neari = numpy.argmin(pdist, axis=0)\n if isinstance(neari, numpy.ndarray):\n return pout[neari[0], :].reshape(-1)\n else:\n return pout[neari, :].reshape(-1)\n","sub_path":"isskmeanskde.py","file_name":"isskmeanskde.py","file_ext":"py","file_size_in_byte":9003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"485604406","text":"import Tkinter\nimport subprocess\n\n\nclass RosTopicList:\n \n \n def __init__(self, tkRoot, logger):\n self.tkRoot = tkRoot\n self.actionBtn = Tkinter.Button(self.tkRoot, text=\"RosTopic List\", command=self.actionCb,width=20)\n self.logger = logger\n #eof\n \n \n def actionCb(self):\n p = subprocess.Popen([\"rostopic\", \"list\"], stdout=subprocess.PIPE)\n \n self.logger.clear()\n \n for line in p.stdout:\n self.logger.log(line)\n \n p.wait()\n #eof \n \n \n def pack(self):\n self.actionBtn.pack()\n #eof\n \n#eoc","sub_path":"cmd/RosTopicList.py","file_name":"RosTopicList.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"344305156","text":"from django.conf.urls import url\nfrom django.urls import path\nfrom . import views\n\napp_name = 'accounts'\nurlpatterns = [\n \n #path('profile/', views.profile, name='profile'),\n url(r'^profile/$', views.view_profile, name='view_profile'),\n url(r'^profile/(?P\\d+)/$', views.view_profile, name='view_profile_with_pk'),\n path('view_profile/edit_profile/', views.edit_profile, name='edit_profile'),\n path('delete_profile/', views.delete_profile, name='delete_profile'),\n path('delete_user/', views.delete_user, name='delete_user'),\n]\n","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"416053754","text":"#!/usr/bin/env python\nfrom __future__ import print_function, absolute_import, division\nimport rospy\nfrom sensor_msgs.msg import Image\nfrom sensor_msgs.msg import Image, PointCloud2\nfrom sensor_msgs import point_cloud2 as pc2\nfrom std_msgs.msg import Int16, String, Float32\nfrom cv_bridge import CvBridge\n\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nimport copy\n\nfrom candy.srv import Step, Value, UpdateWeights\n\nimport msgpack\nimport msgpack_numpy as m\nm.patch()\n\nimport argparse\nimport logging\nimport random\nimport time\nimport datetime\ntry:\n import pygame\n from pygame.locals import K_DOWN\n from pygame.locals import K_LEFT\n from pygame.locals import K_RIGHT\n from pygame.locals import K_SPACE\n from pygame.locals import K_UP\n from pygame.locals import K_a\n from pygame.locals import K_d\n from pygame.locals import K_p\n from pygame.locals import K_q\n from pygame.locals import K_r\n from pygame.locals import K_s\n from pygame.locals import K_w\n from pygame.locals import K_t\n from pygame.locals import K_m\n from pygame.locals import K_n\n from pygame.locals import K_1\n from pygame.locals import K_2\n from pygame.locals import K_3\n from pygame.locals import K_4\n from pygame.locals import K_5\n from pygame.locals import K_6\n from pygame.locals import K_7\n from pygame.locals import K_8\n from pygame.locals import K_9\n from pygame.locals import K_v\n from pygame.locals import K_c\nexcept ImportError:\n raise RuntimeError('cannot import pygame, make sure pygame package is installed')\n\nWINDOW_WIDTH = 160\nWINDOW_HEIGHT = 160\nBUFFER_LIMIT = 70\n\n\nclass Carla_Wrapper(object):\n\n def __init__(self, gamma=0.99, lam=0.95, nlstm=10):\n self.global_step = 0\n self.nlstm = nlstm\n self.lam = lam\n self.gamma = gamma\n self.state = np.zeros((1, nlstm*2), dtype=np.float32)\n\n self.obs, self.actions, self.values, self.neglogpacs, self.rewards, self.vaerecons, self.states, self.std_actions, self.manual = [],[],[],[],[],[],[],[],[]\n self.last_frame = [[np.zeros([160,160,1,3]) for i in range(11)] for j in range(4)]\n self.last_control = [[0.0, 0.0] for i in range(11)]\n self.publisher = rospy.Publisher('/train_data', String, queue_size=1)\n\n\n def clear(self):\n self.state = np.zeros((1, self.nlstm*2), dtype=np.float32)\n self.obs, self.actions, self.values, self.neglogpacs, self.rewards, self.vaerecons, self.states, self.std_actions, self.manual = [],[],[],[],[],[],[],[],[]\n self.last_frame = [[np.zeros([160,160,1,3]) for i in range(11)] for j in range(4)]\n self.last_control = [[0.0, 0.0] for i in range(11)]\n\n def update_reward(self, cnt, obs, action, reward):\n l = len(self.obs)\n for t in range(l - cnt, l - 2):\n self.rewards[t] = self.rewards[t+1]\n if reward is None:\n self.rewards[l-1] = self.rewards[l-2]\n else:\n self.rewards[l-1] = reward\n self.rewards[l-1] *= 20\n for t in reversed(range(l - cnt, l - 1)):\n self.rewards[t] += self.lam * self.rewards[t+1]\n\n def post_process(self, inputs, cnt):\n\n obs, reward, action, _, _ = self.pre_process(inputs, refresh=False)\n self.update_reward(cnt, obs, action, reward)\n\n print(self.rewards[-20:])\n print('Start Memory Replay')\n self.memory_training()\n print('Memory Replay Done')\n time.sleep(1) # Time for sending train data\n\n\n def pre_process(self, inputs, refresh=False):\n\n images, control, reward, std_control, manual, speed = inputs\n frame = [None] * 4\n images = copy.deepcopy(images)\n # print(images[0])\n for i, _ in enumerate(images):\n images[i] = images[i].astype(np.float32) / 128 - 1\n nowframe = np.expand_dims(images[i], 2)\n frame[i] = np.concatenate(self.last_frame[i] + [nowframe], 2)\n if refresh == True:\n self.last_frame[i] = self.last_frame[i][1:] + [nowframe]\n obs = [copy.deepcopy(frame), copy.deepcopy(speed), np.array(self.last_control + [[0.0,0.0]])]\n return obs, reward, control, std_control, manual\n \n\n # def update(self, inputs):\n\n # \tobs, reward, action, std_action, manual = self.pre_process(inputs, refresh=True)\n\n # \trospy.wait_for_service('model_value')\n # \ttry:\n # \t\tmodel_value = rospy.ServiceProxy('model_value', Value)\n\n # \t\tmsg_input = msgpack.packb([obs, self.state, action], use_bin_type=True)\n # \t\tmsg_output = model_value(msg_input)\n # \t\t_, value, self.state, neglogpacs, vaerecon = msgpack.unpackb(msg_output.b, raw=False, encoding='utf-8')\n\n # \texcept rospy.ServiceException as e:\n # \t\tprint(\"Service call failed: %s\" % e)\n # \t\treturn\n\n\n # \tself.states.append(self.state)\n # \tself.obs.append(obs)\n # \tself.actions.append(action)\n # \tself.values.append(value)\n # \tself.neglogpacs.append(neglogpacs)\n # \tself.rewards.append(reward)\n # \tself.vaerecons.append(vaerecon)\n # \tself.std_actions.append(std_action)\n # \tself.manual.append(manual)\n\n # self.red_buffer.append(red)\n # self.manual_buffer.append(manual)\n\n def pretrain(self):\n raise NotImplementedError\n # if os.path.exists('obs/data'):\n # \tprint('Start Pretraining!!')\n # \twith open('obs/data', 'rb') as fp:\n # \t\tself.obs, self.actions, self.values, self.neglogpacs, self.rewards, self.vaerecons, self.states = msgpack.load(fp, encoding='utf-8', raw=False)\n # \tprint('Pretraining length = ', len(self.obs))\n # \tself.memory_training(pretrain=True)\n\n def calculate_difficulty(self, reward, vaerecon):\n # return abs(reward)\n return vaerecon\n \n def memory_training(self, pretrain=False):\n l = len(self.obs)\n train_batch = [self.obs, self.actions, self.values, self.neglogpacs, self.rewards, self.vaerecons, self.states, self.std_actions, self.manual]\n msg_str = msgpack.packb(train_batch, use_bin_type=True)\n self.publisher.publish(msg_str)\n self.obs, self.actions, self.values, self.neglogpacs, self.rewards, self.vaerecons, self.states, self.std_actions, self.manual = [],[],[],[],[],[],[],[],[]\n\n def get_control_and_update(self, inputs):\n\n obs, reward, _, std_action, manual = self.pre_process(inputs, refresh=True)\n\n rospy.wait_for_service('model_step')\n try:\n model_step = rospy.ServiceProxy('model_step', Step)\n msg_input = msgpack.packb([obs, self.state], use_bin_type=True)\n msg_output = model_step(msg_input)\n action, value, self.state, neglogpacs, vaerecon = msgpack.unpackb(msg_output.b, raw=False, encoding='utf-8')\n # print(action)\n except rospy.ServiceException as e:\n print(\"Service call failed: %s\" % e)\n return [0,0]\n\n self.states.append(self.state)\n\n # Change obs\n if manual:\n obs[2] = np.array(self.last_control + [std_action])\n self.last_control = self.last_control[1:] + [std_action]\n else:\n obs[2] = np.array(self.last_control + [action[0]])\n self.last_control = self.last_control[1:] + [action[0]]\n\n self.obs.append(obs)\n self.actions.append(action)\n self.values.append(value)\n self.neglogpacs.append(neglogpacs)\n self.rewards.append(reward)\n self.vaerecons.append(vaerecon)\n self.std_actions.append(std_action)\n self.manual.append(manual)\n\n return action\n # def get_control(self, inputs):\n\n # \tobs, _, _, _, manual = self.pre_process(inputs)\n # \trospy.wait_for_service('model_step')\n\n # \ttry:\n # \t\tmodel_step = rospy.ServiceProxy('model_step', Step)\n # \t\tmsg_input = msgpack.packb([obs, self.state], use_bin_type=True)\n # \t\tmsg_output = model_step(msg_input)\n # \t\taction, _, _, _, _ = msgpack.unpackb(msg_output.b, raw=False, encoding='utf-8')\n # \t\t# print(action)\n # \t\treturn action\n # \texcept rospy.ServiceException as e:\n # \t\tprint(\"Service call failed: %s\" % e)\n\n # \treturn 0 # do nothing\n\nclass CarlaGame(object):\n def __init__(self, carla_wrapper, image_getter, image2_getter, lidar_getter, eyeleft_getter,\n eyeright_getter, eyeback_getter, eyefront_getter, speed_getter, steer_getter, \n brake_throttle_getter, is_auto_getter, throttle_publisher, steer_publisher, train=False):\n self._timer = None\n self._display = None\n self.images = None\n self.should_display = True\n random.seed(datetime.datetime.now())\n self.manual = True\n self.cnt = 0\n self.endnow = False\n self.canreplay = train\n self.history_manual = False\n self.history_steer = 0.0\n pygame.init()\n\n self.image_getter = image_getter\n self.image2_getter = image2_getter\n # self.lidar_getter = lidar_getter\n self.eyeleft_getter = eyeleft_getter\n self.eyeright_getter = eyeright_getter\n # self.eyeback_getter = eyeback_getter\n # self.eyefront_getter = eyefront_getter\n\n\n self.throttle_publisher = throttle_publisher\n self.steer_publisher = steer_publisher\n self.carla_wrapper = carla_wrapper\n\n self.speed_getter = speed_getter\n self.steer_getter = steer_getter\n self.brake_throttle_getter = brake_throttle_getter\n self.is_auto_getter = is_auto_getter\n\n self._display = pygame.display.set_mode(\n (WINDOW_WIDTH * 2, WINDOW_HEIGHT * 2),\n pygame.HWSURFACE | pygame.DOUBLEBUF)\n\n def execute(self):\n self._on_loop()\n self._on_render()\n pygame.event.pump() # process event queue\n\n\n def _calculate_reward(self, manual, history_manual, steer, history_steer):\n reward = 0\n if history_manual == False and manual == True:\n reward = -1\n reward = 0.1 - 20 * abs(history_steer - steer)\n return reward\n\n def _on_loop(self):\n left_image = self.image_getter()\n right_image = self.image2_getter()\n eyeleft = self.eyeleft_getter()\n eyeright = self.eyeright_getter()\n if left_image is None or right_image is None or eyeleft is None or eyeright is None:\n return\n\n \n speed = self.speed_getter()\n steer = self.steer_getter()\n brake_throttle = self.brake_throttle_getter()\n manual = not self.is_auto_getter()\n\n\n control, reward = self._get_keyboard_control(pygame.key.get_pressed())\n if reward is None:\n reward = self._calculate_reward(manual, self.history_manual, steer, self.history_steer)\n if control == \"done\":\n return\n elif control is None:\n return\n\n self.history_manual = manual\n self.history_steer = steer\n\n control = [brake_throttle, steer]\n self.images = [left_image, right_image, eyeleft, eyeright]\n\n self.cnt += 1\n model_control = self.carla_wrapper.get_control_and_update([self.images, control, reward, control, manual, speed])\n\n if len(np.array(model_control).shape) != 1:\n model_control = model_control[0]\n print(\"throttle=%.2f, %.2f ---- steer=%.2f, %.2f\" % (control[0], model_control[0], control[1], model_control[1]))\n if manual:\n print(\"Human!\")\n else:\n print(\"Model!\")\n\n # if self.manual_control:\n # \tself.throttle_publisher.publish(max(-1.0, min(1.0, control[0])))\n # \tself.steer_publisher.publish(max(-1.0, min(1.0, control[1])))\n # else:\n self.throttle_publisher.publish(max(-1.0, min(1.0, model_control[0])))\n self.steer_publisher.publish(max(-1.0, min(1.0, model_control[1])))\n\n if self.endnow or self.cnt > BUFFER_LIMIT:\n if self.canreplay:\n self.carla_wrapper.post_process([self.images, model_control, reward, control, manual, speed], self.cnt)\n self.carla_wrapper.clear()\n self.cnt = 0\n self.endnow = False\n \n def _get_keyboard_control(self, keys):\n th = 0\n steer = 0\n\n if keys[K_r]:\n return None, None\n if keys[K_t]:\n self.should_display = not self.should_display\n return 'done', None\n if keys[K_m]:\n self.manual = True\n return 'done', None\n if keys[K_n]:\n self.manual = False\n return 'done', None\n if keys[K_v]:\n self.endnow = True\n return 'done', None\n\n if keys[K_LEFT] or keys[K_a]:\n steer = -1\n if keys[K_RIGHT] or keys[K_d]:\n steer = 1\n if keys[K_UP] or keys[K_w]:\n th = 1\n if keys[K_DOWN] or keys[K_s]:\n th = -1\n\n if keys[K_c]:\n self.canreplay = not self.canreplay\n\n reward = None\n if keys[K_1]:\n reward = -1\n if keys[K_2]:\n reward = -0.5\n if keys[K_3]:\n reward = -0.25\n if keys[K_4]:\n reward = -0.1\n if keys[K_5]:\n reward = 0\n if keys[K_6]:\n reward = 0.1\n if keys[K_7]:\n reward = 0.25\n if keys[K_8]:\n reward = 0.5\n if keys[K_9]:\n reward = 1\n\n # cod = 0\n # if steer == -1 and th == 1:\n # \tcod = 1\n # elif steer == 0 and th == 1:\n # \tcod = 2\n # elif steer == 1 and th == 1:\n # \tcod = 3\n # elif steer == -1 and th == 0:\n # \tcod = 4\n # elif steer == 1 and th == 0:\n # \tcod = 5\n # elif steer == -1 and th == -1:\n # \tcod = 6\n # elif steer == 0 and th == -1:\n # \tcod = 7\n # elif steer == 1 and th == -1:\n # \tcod = 8\n \n return [th, steer], reward\n\n def _on_render(self):\n if self.should_display == False or self.images is None:\n return\n left_image, right_image, eyeleft, eyeright = self.images\n if left_image is not None:\n array = left_image\n surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))\n self._display.blit(surface, (0, 0))\n\n if right_image is not None:\n array = right_image\n surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))\n self._display.blit(surface, (WINDOW_WIDTH, 0))\n\n if eyeleft is not None:\n array = eyeleft\n surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))\n self._display.blit(surface, (0, WINDOW_HEIGHT))\n\n if eyeright is not None:\n array = eyeright\n surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))\n self._display.blit(surface, (WINDOW_WIDTH, WINDOW_HEIGHT))\n\n pygame.display.flip()\n\n\n\nclass WrapperCandy():\n def __init__(self, load_mode = False):\n self._cv_bridge = CvBridge()\n\n self._sub = rospy.Subscriber('/stereo/left/image_raw', Image, self.load_image, queue_size=1)\n self._subb = rospy.Subscriber('/stereo/right/image_raw', Image, self.load_image2, queue_size=1)\n # self._subb1 = rospy.Subscriber('/rslidar_points', PointCloud2, self.load_lidar, queue_size=1)\n self._subb2 = rospy.Subscriber('/multiple/webcam3/image_raw', Image, self.load_eyeleft, queue_size=1)\n self._subb3 = rospy.Subscriber('/multiple/webcam1/image_raw', Image, self.load_eyeright, queue_size=1)\n # self._subb4 = rospy.Subscriber('/multiple/webcam0/image_raw', Image, self.load_eyeback, queue_size=1)\n # self._subb5 = rospy.Subscriber('/multiple/webcam2/image_raw', Image, self.load_eyefront, queue_size=1)\n\n self._sub2 = rospy.Subscriber('/current_speed', Float32, self.load_speed, queue_size=1)\n self._sub3 = rospy.Subscriber('/current_steer', Float32, self.load_steer, queue_size=1)\n self._sub4 = rospy.Subscriber('/current_brake_throttle', Float32, self.load_brake_throttle, queue_size=1)\n self._sub5 = rospy.Subscriber('/current_is_auto', Int16, self.load_is_auto, queue_size=1)\n\n self.throttle_publisher = rospy.Publisher('/ferrari_throttle', Float32, queue_size=1)\n self.steer_publisher = rospy.Publisher('/ferrari_steer', Float32, queue_size=1)\n\n self.all_pub = rospy.Publisher('/wrapper_data', String, queue_size=1)\n if load_mode:\n self.all_sub = rospy.Subscriber('/wrapper_data', String, self.all_loader, queue_size=1)\n\n self.image = None\n self.image2 = None\n self.lidar = None\n self.eyeleft = None\n self.eyeright = None\n self.eyeback = None\n self.eyefront = None\n\n self.speed = 0\n self.steer = 0\n self.is_auto = True\n self.brake_throttle = 0\n\n def image_getter(self):\n def func():\n if self.image is None:\n return None\n image = self.image[130:, :]\n image = cv2.resize(image, (160,160))\n return image\t\t\n return func\n def image2_getter(self):\n def func():\n if self.image2 is None:\n return None\n image = self.image2[130:, :]\n image = cv2.resize(image, (160,160))\n return image\n return func\n def lidar_getter(self):\n def func():\n return self.lidar\n return func\n def eyeleft_getter(self):\n def func():\n if self.eyeleft is None:\n return None\n image = self.eyeleft[130:, :]\n image = cv2.resize(image, (160,160))\n return image\n return func\n def eyeright_getter(self):\n def func():\n if self.eyeright is None:\n return None\n image = self.eyeright[130:, :]\n image = cv2.resize(image, (160,160))\n return image\n return func\n\n def eyeback_getter(self):\n def func():\n return self.eyeback\n return func\n\n def eyefront_getter(self):\n def func():\n return self.eyefront\n return func\n\n def speed_getter(self):\n def func():\n return self.speed / 15.0 - 1\n return func\n\n def steer_getter(self):\n def func():\n return self.steer\n return func\n\n def brake_throttle_getter(self):\n def func():\n return self.brake_throttle\n return func\n\n def is_auto_getter(self):\n def func():\n return self.is_auto\n return func\n\n def load_speed(self, msg):\n self.speed = msg.data\n\n def load_is_auto(self, msg):\n self.is_auto = False if msg.data == 0 else True\n\n def load_steer(self, msg):\n self.steer = max(min(1.0, msg.data),-1.0)\n\n def load_brake_throttle(self, msg):\n self.brake_throttle = max(min(1.0, msg.data),-1.0)\n\n def load_image(self, image_msg):\n cv_image = self._cv_bridge.imgmsg_to_cv2(image_msg, \"bgr8\")\n cv_image = cv2.resize(cv_image,(320,320))\n cv_image = cv2.flip(cv_image, -1)\n # print(cv_image)\n image = cv_image[...,::-1]\n self.image = image\n\n def load_image2(self, image_msg):\n cv_image = self._cv_bridge.imgmsg_to_cv2(image_msg, \"bgr8\")\n cv_image = cv2.resize(cv_image,(320,320))\n cv_image = cv2.flip(cv_image, -1)\n # print(cv_image)\n image = cv_image[...,::-1]\n self.image2 = image\n\n def load_eyeleft(self, image_msg):\n cv_image = self._cv_bridge.imgmsg_to_cv2(image_msg, \"bgr8\")\n cv_image = cv2.resize(cv_image,(320,320))\n cv_image = cv2.flip(cv_image, -1)\n # print(cv_image)\n image = cv_image[...,::-1]\n self.eyeleft = image\n\n def load_eyeright(self, image_msg):\n cv_image = self._cv_bridge.imgmsg_to_cv2(image_msg, \"bgr8\")\n cv_image = cv2.resize(cv_image,(320,320))\n cv_image = cv2.flip(cv_image, -1)\n # print(cv_image)\n image = cv_image[...,::-1]\n self.eyeright = image\n\n def load_eyeback(self, image_msg):\n # cv_image = self._cv_bridge.imgmsg_to_cv2(image_msg, \"bgr8\")\n # cv_image = cv2.resize(cv_image,(320,320))\n # cv_image = cv2.flip(cv_image, -1)\n # # print(cv_image)\n # image = cv_image[...,::-1]\n self.eyeback = None\n return\n\n def load_eyefront(self, image_msg):\n # cv_image = self._cv_bridge.imgmsg_to_cv2(image_msg, \"bgr8\")\n # cv_image = cv2.resize(cv_image,(320,320))\n # cv_image = cv2.flip(cv_image, -1)\n # # print(cv_image)\n # image = cv_image[...,::-1]\n self.eyefront = None\n return\n\n def load_lidar(self, ros_cloud):\n self.lidar = None\n return\n # points_list = []\n # for data in pc2.read_points(ros_cloud, skip_nans=True):\n # \tpoints_list.append([data[0], data[1], data[2], data[3]])\n # self.lidar = points_list\n\n def train_image_load(self):\n PATH = '/data/forvae'\n import os\n from glob import glob\n result = sorted([y for x in os.walk(PATH) for y in glob(os.path.join(x[0], '*.jpg'))])\n print(len(result))\n for _ in range(1000000):\n for v in result:\n image = cv2.imread(v)\n image = cv2.resize(image,(160,160))\n image = image[...,::-1]\n yield image\n\n def all_loader(self, msg):\n # self.image, self.image2, self.lidar, self.eyeleft, self.eyeright, self.speed, self.steer, self.is_auto, self.brake_throttle = msgpack.unpackb(msg.data, raw=False, encoding='utf-8')\n # self.image, self.speed, self.steer, self.is_auto, self.brake_throttle = msgpack.unpackb(msg.data, raw=False, encoding='utf-8')\n self.image, self.image2, self.eyeleft, self.eyeright, self.speed, self.steer, self.is_auto, self.brake_throttle = msgpack.unpackb(msg.data, raw=False, encoding='utf-8')\n\n def all_publisher(self):\n msg = msgpack.packb([self.image, self.image2, self.eyeleft, self.eyeright, self.speed, self.steer, self.is_auto, self.brake_throttle], use_bin_type=True)\n self.all_pub.publish(msg)\n\nif __name__ == '__main__':\n argparser = argparse.ArgumentParser('Wrapper')\n argparser.add_argument(\n '-l', '--load-rosbag-data',\n action='store_true',\n help='load rosbag data')\n argparser.add_argument(\n '-t', '--train',\n action='store_true',\n help='training')\n argparser.add_argument(\n '-n', '--no-actor',\n action='store_true',\n help='no actor')\n args = argparser.parse_args()\n\n rospy.init_node('wrapper_candy')\n wrapper_candy = WrapperCandy(args.load_rosbag_data)\n carla_wrapper = Carla_Wrapper()\n\n\n carla_game = CarlaGame(carla_wrapper, wrapper_candy.image_getter(), wrapper_candy.image2_getter(), wrapper_candy.lidar_getter(), \n wrapper_candy.eyeleft_getter(), wrapper_candy.eyeright_getter(), wrapper_candy.eyeback_getter(), wrapper_candy.eyefront_getter(), \n wrapper_candy.speed_getter(), wrapper_candy.steer_getter(), wrapper_candy.brake_throttle_getter(), wrapper_candy.is_auto_getter(), \n wrapper_candy.throttle_publisher, wrapper_candy.steer_publisher, args.train)\n\n\n rate = rospy.Rate(10) # 10hz\n # image_loader = wrapper_candy.train_image_load()\n while not rospy.is_shutdown():\n # wrapper_candy.image = image_loader.next()\n # print(wrapper_candy.image.shape)\n # print('speed', wrapper_candy.speed, 'steer', wrapper_candy.steer, 'is_auto', wrapper_candy.is_auto, 'brake_th', wrapper_candy.brake_throttle)\n if not args.load_rosbag_data:\n wrapper_candy.all_publisher()\n if not args.no_actor:\n carla_game.execute()\n rate.sleep()\n","sub_path":"src/candy/src/wrapper_candy.py","file_name":"wrapper_candy.py","file_ext":"py","file_size_in_byte":23778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"342525966","text":"from selenium.webdriver.support import expected_conditions as Ec\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.common import exceptions as Ex\r\nfrom selenium.webdriver.common.by import By\r\n\r\n\r\ndef get_page_title_inc_hidden(driver):\r\n try:\r\n main_frame_page_div = driver.find_element_by_id('MainFramePageDiv')\r\n h1_element = driver.execute_script(\"return document.getElementsByTagName('h1')[0]\", main_frame_page_div)\r\n page_title = h1_element.get_attribute('innerHTML')\r\n return page_title\r\n except Ex.NoSuchElementException:\r\n return None\r\n\r\n\r\ndef get_content_of_first_two_cells(driver):\r\n \"\"\"method to confirm first two cells of first row\"\"\"\r\n try:\r\n driver.switch_to.frame(driver.find_element_by_id('mainframe'))\r\n except Ex.NoSuchElementException:\r\n pass\r\n delay = 20\r\n # print('testing for ptable...')\r\n try:\r\n awaited_element = WebDriverWait(driver, delay).until(\r\n Ec.visibility_of_element_located((By.ID, '''ptable'''))\r\n )\r\n except TimeoutError:\r\n print('waited', delay, 'seconds, but ptable is not showing')\r\n\r\n # print(' interrogating first data row...')\r\n cell_xpath_col_1 = '''//table[@id=\"ptable\"]/tbody/tr[1]/td[2]'''\r\n cell_xpath_col_2 = '''//table[@id=\"ptable\"]/tbody/tr[1]/td[3]'''\r\n try:\r\n awaited_element = WebDriverWait(driver, delay).until(\r\n Ec.visibility_of_element_located((By.XPATH, cell_xpath_col_1))\r\n )\r\n # print('got first row', cell_xpath_col_1)\r\n cell_1 = awaited_element.get_attribute('innerHTML')\r\n cell_2 = driver.find_element_by_xpath(cell_xpath_col_2).get_attribute('innerHTML')\r\n # cell_1 = cell_1.replace('
', ' ').replace('', '').replace('', '').replace('', '').replace \\\r\n # ('', '')\r\n # cell_2 = cell_2.replace('
', ' ').replace('', '').replace('', '').replace('
', '').replace \\\r\n # ('', '')\r\n\r\n # print(' Worklist Data says: first row starts:\\n ', cell_1, cell_2)\r\n string_to_test = cell_1 + ' ' + cell_2\r\n # print(' concatd', string)\r\n return string_to_test\r\n except TimeoutError:\r\n print('waited', delay, 'seconds, but first row is not showing')\r\n return None\r\n\r\n\r\ndef choose_first_input_filter(driver):\r\n \"\"\"method to find first input filter (usu. date from) in an attempt to hide the dropdowns\"\"\"\r\n filter_label_xpath = '''//form[@id=\"searchform\"]/div//input/preceding-sibling::span'''\r\n filter_label_elements = driver.find_elements_by_xpath(filter_label_xpath)\r\n if len(filter_label_elements) > 0:\r\n for el in filter_label_elements:\r\n text = el.get_attribute('innerHTML')\r\n print(text)\r\n print('---')\r\n first_filter_label_element = filter_label_elements[0]\r\n first_filter_label_text = first_filter_label_element.get_attribute('innerHTML')\r\n print('first input filter is:', first_filter_label_text)\r\n filter_element_xpath = '''//form[@id=\"searchform\"]/div//input'''\r\n filter_elements = driver.find_elements_by_xpath(filter_element_xpath)\r\n if len(filter_elements) > 0:\r\n print(len(filter_elements))\r\n first_filter_element = filter_elements[0]\r\n first_filter_element.click()\r\n\r\n\r\ndef choose_first_select_filter(driver):\r\n \"\"\"method to find first select filter and select the first option in it (does not hide dropdown menus)\"\"\"\r\n filter_label_xpath = '''//form[@id=\"searchform\"]//select/preceding-sibling::span'''\r\n filter_label_elements = driver.find_elements_by_xpath(filter_label_xpath)\r\n if len(filter_label_elements) > 0:\r\n first_filter_label_element = filter_label_elements[0]\r\n first_filter_label_text = first_filter_label_element.get_attribute('innerHTML')\r\n print('first select filter is:', first_filter_label_text)\r\n filter_element_xpath = '''//form[@id=\"searchform\"]//select'''\r\n filter_elements = driver.find_elements_by_xpath(filter_element_xpath)\r\n if len(filter_elements) > 0:\r\n first_filter_element = filter_elements[0]\r\n first_filter_element.click()\r\n # then look for options\r\n filter_options_xpath = '''//form[@id=\"searchform\"]//select/option'''\r\n filter_option_elements = driver.find_elements_by_xpath(filter_options_xpath)\r\n if len(filter_option_elements) > 0:\r\n desired_option_element = filter_option_elements[1]\r\n desired_option_element.click()\r\n","sub_path":"PageRead/WorklistData.py","file_name":"WorklistData.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"154960874","text":"import numpy as np\n#from covar import cov_shrink_ss\nfrom scipy.linalg import sqrtm\nimport pickle\nfrom collections import defaultdict\nimport bezier\nimport matplotlib.pyplot as plt\n#from surfer import Brain\nfrom mne.viz import Brain\nfrom mayavi import mlab\nimport pyvista as pv\nimport pandas as pd\nfrom matplotlib.pyplot import cm\nfrom matplotlib.colors import Normalize, ListedColormap\nfrom matplotlib.patches import Rectangle\nimport mne\nimport csv\nimport io\nmne.viz.set_3d_backend(\"pyvista\")\n\nclass TriuSparse():\n def __init__(self,mat,k=1,precision=np.float32):\n mat = mat.astype(precision)\n if mat.shape[-1] != mat.shape[-2]:\n raise ValueError(\"Last two dimensions must be the same.\")\n self.mat_res = mat.shape[-1]\n self.mat_inds = np.triu_indices(self.mat_res,k=1,m=self.mat_res)\n self.mat_sparse = mat[...,self.mat_inds[0],self.mat_inds[1]]\n self.k = k\n def save(self,filename):\n out_dics = {\"mat_res\":self.mat_res,\"mat_inds\":self.mat_inds,\n \"mat_sparse\":self.mat_sparse}\n with open(filename,\"wb\") as f:\n pickle.dump(out_dics,f)\n\ndef load_sparse(filename,convert=True,full=False,nump_type=\"float32\"):\n with open(filename,\"rb\") as f:\n result = pickle.load(f)\n if convert:\n full_mat = np.zeros(result[\"mat_sparse\"].shape[:-1] + \\\n (result[\"mat_res\"],result[\"mat_res\"])).astype(nump_type)\n full_mat[...,result[\"mat_inds\"][0],result[\"mat_inds\"][1]] = \\\n result[\"mat_sparse\"]\n result = full_mat\n return result\n\n# make a dPTE without directed information and normalise to 0-1\ndef dPTE_to_undirected(dPTE):\n tu_inds = np.triu_indices(dPTE.shape[1], k=1)\n undir = np.zeros(dPTE.shape,dtype=\"float32\")\n undir_vec = np.abs(dPTE[:,tu_inds[0],tu_inds[1]]-.5)*-2 # 2 is negative here as convenience for laplacian later\n undir[:,tu_inds[0],tu_inds[1]] = undir_vec\n undir[:,tu_inds[1],tu_inds[0]] = undir_vec\n return undir\n\n# laplacian on a (nondirected) dPTE, acts in place if undirect=False\ndef dPTE_to_laplace(x, undirect=True):\n if undirect:\n undir = dPTE_to_undirected(x)\n else:\n undir = x\n rowsums = np.nansum(undir,axis=1)*-1\n undir[:,np.arange(rowsums.shape[1]),np.arange(rowsums.shape[1])] = rowsums\n return undir\n\ndef phi(mat, k=0):\n if len(mat.shape)>2:\n triu_inds = np.triu_indices(mat.shape[1],k=k)\n return mat[...,triu_inds[0],triu_inds[1]]\n else:\n triu_inds = np.triu_indices(mat.shape[0],k=k)\n return mat[triu_inds[0],triu_inds[1]]\n\ndef covariance(mat_a, mat_b=None, reg=False):\n mean_a = np.mean(mat_a, axis=0)\n if reg:\n cov_a, _ = cov_shrink_ss(np.ascontiguousarray(phi(mat_a)).astype(np.float64))\n else:\n cov_a = (phi(mat_a)-phi(mean_a)).T.dot(phi(mat_a)-phi(mean_a))/(len(mat_a)-1)\n if mat_b is None:\n cov_out = cov_a\n else:\n mean_b = np.mean(mat_b, axis=0)\n if reg:\n cov_b, _ = cov_shrink_ss(np.ascontiguousarray(phi(mat_b)).astype(np.float64))\n else:\n cov_b = (phi(mat_b)-phi(mean_b)).T.dot(phi(mat_b)-phi(mean_b))/(len(mat_b)-1)\n cov_out = (cov_a*len(mat_a) + cov_b*len(mat_b)) / (len(mat_a) + len(mat_b) - 2)\n return cov_out\n\ndef samp2_chi(mat_a, mat_b):\n mean_a = np.mean(mat_a,axis=0)\n mean_b = np.mean(mat_b,axis=0)\n prec_mat = np.linalg.inv(covariance(mat_a, mat_b=mat_b, reg=True))\n sq_diff_var = np.linalg.multi_dot(((phi(mean_a)-phi(mean_b)).T,\n prec_mat, phi(mean_a)-phi(mean_b)))\n t2 = (len(mat_a)*len(mat_b))/(len(mat_a)+len(mat_b)) * sq_diff_var\n\n # now compute the contribution of individual edges\n mean = np.mean(np.vstack((mat_a,mat_b)),axis=0)\n prec_sqrt = sqrtm(prec_mat)\n lambda_a = np.linalg.multi_dot((prec_sqrt, phi(mean_a)-phi(mean)))\n lambda_b = np.linalg.multi_dot((prec_sqrt, phi(mean_b)-phi(mean)))\n kappa = (lambda_a**2 + lambda_b**2)/2\n return t2, kappa\n\nclass Graph:\n def __init__(self):\n self.graph = defaultdict(list)\n\n def add_edge(self,u,v):\n self.graph[u].append(v)\n\n def build_undirected(self,edges):\n nodes = list(set([e for ed in edges for e in ed]))\n for n in nodes:\n for e in edges:\n if n in e:\n if e[1] not in self.graph[e[0]]:\n self.add_edge(e[0],e[1])\n if e[0] not in self.graph[e[1]]:\n self.add_edge(e[1],e[0])\n\n def BFS(self, s):\n visited = {n:False for n in self.graph.keys()}\n queue = []\n queue.append(s)\n visited[s] = True\n while queue:\n s = queue.pop(0)\n for i in self.graph[s]:\n if visited[i] == False:\n queue.append(i)\n visited[i] = True\n return [k for k,v in visited.items() if v] # list of nodes visited\n\n def find_components(self, edges):\n components = []\n for n in self.graph.keys():\n visited_nodes = set(self.BFS(n))\n if len(visited_nodes) == len(self.graph): # component encompasses all nodes, can stop here\n return [visited_nodes]\n contained = [set.intersection(visited_nodes,comp) for comp in components]\n if not any(contained):\n components.append(set(visited_nodes))\n return components\n\ndef get_active_edge_inds(components, edges):\n comp_edge_inds = []\n for comp in components:\n comp_edge_inds.append([])\n for edge_idx, edge in enumerate(edges):\n if any([edge[0] in comp, edge[1] in comp]):\n comp_edge_inds[-1].append(edge_idx)\n return comp_edge_inds\n\ndef cnx_cluster(f_vals, p_vals, cnx_n, p_thresh=0.05, edges=None):\n psig_inds = np.where(p_vals= centre or mat.max() < centre:\n print(\"Warning: Values do not seem to match specified centre of {}.\".format(centre))\n mat[mat!=0] -= centre\n if not np.any(mat_in):\n print(\"All values 0.\")\n return\n\n if top_cnx is not None:\n matflat = np.abs(mat.flatten())\n try:\n thresh = np.sort(matflat[matflat>0])[-top_cnx]\n except:\n thresh = matflat[matflat>0].min()\n mat[np.abs(mat)0])[-bot_cnx]\n except:\n thresh = matflat[matflat>0].max()\n mat[np.abs(mat)>thresh] = 0\n\n lingrad = np.linspace(0,1,lineres)\n brain = Brain('fsaverage', 'both', surface, alpha=alpha,\n subjects_dir=subjects_dir, size=figsize, show=False,\n background=background)\n brain.enable_depth_peeling()\n if lup_title:\n brain.add_text(0, 0.8, lup_title, \"lup\", font_size=40, color=text_color)\n if ldown_title:\n brain.add_text(0, 0, ldown_title, \"ldown\", font_size=40, color=text_color)\n if rup_title:\n brain.add_text(0.7, 0.8, rup_title, \"rup\", font_size=40, color=text_color)\n if rdown_title:\n brain.add_text(0.7, 0., rdown_title, \"rdown\", font_size=40, color=text_color)\n brain.add_annotation(parc,color=\"black\")\n rrs = np.array([brain.geo[l.hemi].coords[l.center_of_mass()] for l in labels])\n\n if alpha_max is None:\n alpha_max = np.abs(mat).max()\n if alpha_min is None:\n alpha_min = np.abs(mat[mat!=0]).min()\n\n inds_pos = np.where(mat>0)\n origins = rrs[inds_pos[0],]\n dests = rrs[inds_pos[1],]\n inds_neg = np.where(mat<0)\n origins = np.vstack((origins,rrs[inds_neg[1],]))\n dests = np.vstack((dests,rrs[inds_neg[0],]))\n inds = (np.hstack((inds_pos[0],inds_neg[0])),np.hstack((inds_pos[1],inds_neg[1])))\n\n area_red = np.zeros(len(labels))\n area_blue = np.zeros(len(labels))\n np.add.at(area_red,inds_pos[0],1)\n np.add.at(area_blue,inds_pos[1],1)\n np.add.at(area_red,inds_neg[1],1)\n np.add.at(area_blue,inds_neg[0],1)\n area_weight = area_red + area_blue\n area_red = area_red/np.max((area_red.max(),area_blue.max()))\n area_blue = area_blue/np.max((area_red.max(),area_blue.max()))\n # normalise to a range of min_weight to 1\n area_weight = ((area_weight - area_weight.min()) /\n (area_weight.max() - area_weight.min()) * (1 - min_weight) +\n min_weight)\n\n lengths = np.linalg.norm(origins - dests, axis=1)\n lengths = np.broadcast_to(lengths, (3, len(lengths))).T\n midpoints = (origins + dests) / 2\n midpoint_units = midpoints / np.linalg.norm(midpoints,axis=1,keepdims=True)\n spline_mids = midpoints + midpoint_units * lengths * 1.25\n spline_mids[:, 2] = np.abs(spline_mids[:, 2]) # no lines running under brain\n if uniform_weight:\n alphas = np.ones(len(inds[0]))*0.8\n area_weight[area_weight>0] = 0.8\n area_red[area_red>0] = 1\n area_blue[area_blue>0] = 1\n else:\n if (mat != 0).sum() == 1: # special case of only one connection\n alphas = np.array([1])\n else:\n alphas = ((1 - min_alpha) *\n ((np.abs(mat[inds[0], inds[1]]) - alpha_min) /\n (alpha_max - alpha_min)) + min_alpha)\n alphas[alphas<0], alphas[alphas>1] = 0, 1\n\n for l_idx, l in enumerate(labels):\n if area_weight[l_idx] == min_weight:\n continue\n brain.add_label(l,color=(area_red[l_idx],0,area_blue[l_idx]),\n alpha=area_weight[l_idx])\n point = pv.Sphere(center=rrs[l_idx], radius=area_weight[l_idx]*3+1)\n brain._renderer.plotter.add_mesh(point,\n color=(area_red[l_idx],0,\n area_blue[l_idx]),\n opacity=area_weight[l_idx])\n\n spl_pts = np.empty((len(origins),3,lineres))\n for idx in range(len(origins)):\n curve = bezier.Curve(np.array([[origins[idx,0],spline_mids[idx,0],dests[idx,0]],\n [origins[idx,1],spline_mids[idx,1],dests[idx,1]],\n [origins[idx,2],spline_mids[idx,2],dests[idx,2]]]),\n degree=2)\n spl_pts[idx,] = curve.evaluate_multi(lingrad)\n spline = pv.Spline(spl_pts[idx,].T, lineres)\n tube = spline.tube(radius=alphas[idx])\n tube[\"scalars\"] = np.linspace(0,1,tube.n_points)\n alph_cm_rgbs = np.zeros((tube.n_points, 4))\n alph_cm_rgbs[:, 0] = np.linspace(1,0,tube.n_points)\n alph_cm_rgbs[:, 2] = np.linspace(0,1,tube.n_points)\n alph_cm_rgbs[:, -1] = alphas[idx]\n alpha_cm = ListedColormap(alph_cm_rgbs)\n brain._renderer.plotter.add_mesh(tube, cmap=alpha_cm)\n\n\n brain._renderer.plotter.remove_scalar_bar()\n brain.show()\n return brain\n\ndef plot_undirected_cnx(mat, labels, parc, fig=None, lup_title=None,\n ldown_title=None, rup_title=None, rdown_title=None,\n figsize=(3840,2160), lineres=1000,\n subjects_dir=\"/home/jev/hdd/freesurfer/subjects\",\n alpha_max=None, alpha_min=None, uniform_weight=False,\n surface=\"inflated\", alpha=1, top_cnx=50, bot_cnx=None,\n color=(1,0,0)):\n if top_cnx is not None:\n matflat = mat.flatten()\n thresh = np.sort(matflat[matflat>0])[-top_cnx]\n mat[mat0])[-bot_cnx]\n mat[np.abs(mat)>thresh] = 0\n lingrad = np.linspace(0,1,lineres)\n if fig is None:\n fig = mlab.figure(size=figsize)\n brain = Brain('fsaverage', 'both', surface, alpha=alpha,\n subjects_dir=subjects_dir, figure=fig)\n if lup_title:\n brain.add_text(0, 0.8, lup_title, \"lup\", font_size=40)\n if ldown_title:\n brain.add_text(0, 0, ldown_title, \"ldown\", font_size=40)\n if rup_title:\n brain.add_text(0.7, 0.8, rup_title, \"rup\", font_size=40)\n if rdown_title:\n brain.add_text(0.7, 0., rdown_title, \"rdown\", font_size=40)\n brain.add_annotation(parc,color=\"black\")\n rrs = np.array([brain.geo[l.hemi].coords[l.center_of_mass()] for l in labels])\n\n if alpha_max is None:\n alpha_max = np.abs(mat).max()\n if alpha_min is None:\n alpha_min = np.abs(mat[mat!=0]).min()\n\n inds = np.where(mat>0)\n origins = rrs[inds[0],]\n dests = rrs[inds[1],]\n\n areas = np.zeros(len(labels))\n np.add.at(areas,inds[0],1)\n np.add.at(areas,inds[1],1)\n area_weights = areas/areas.max()\n\n lengths = np.linalg.norm(origins-dests, axis=1)\n lengths = np.broadcast_to(lengths,(3,len(lengths))).T\n midpoints = (origins+dests)/2\n midpoint_units = midpoints/np.linalg.norm(midpoints,axis=1,keepdims=True)\n spline_mids = midpoints + midpoint_units*lengths*2\n if uniform_weight:\n alphas = np.ones(len(inds[0]))*0.8\n area_weights[area_weights>0] = 0.8\n else:\n alphas = ((np.abs(mat[inds[0],inds[1]])-alpha_min)/(alpha_max-alpha_min))\n alphas[alphas<0],alphas[alphas>1] = 0, 1\n\n mlab.points3d(origins[:,0],origins[:,1],origins[:,2],\n alphas,scale_factor=10,color=color,transparent=True)\n mlab.points3d(dests[:,0],dests[:,1],dests[:,2],\n alphas,scale_factor=10,color=color,transparent=True)\n for l_idx, l in enumerate(labels):\n if area_weights[l_idx] == 0:\n continue\n brain.add_label(l,color=color, alpha=area_weights[l_idx])\n spl_pts = np.empty((len(origins),3,lineres))\n for idx in range(len(origins)):\n curve = bezier.Curve(np.array([[origins[idx,0],spline_mids[idx,0],dests[idx,0]],\n [origins[idx,1],spline_mids[idx,1],dests[idx,1]],\n [origins[idx,2],spline_mids[idx,2],dests[idx,2]]]),\n degree=2)\n spl_pts[idx,] = curve.evaluate_multi(lingrad)\n mlab.plot3d(spl_pts[idx,0,],spl_pts[idx,1,],spl_pts[idx,2,],\n lingrad*255,tube_radius=alphas[idx]*2,color=color,\n opacity=alphas[idx])\n\n return brain\n\ndef plot_rgba_cnx(mat_rgba, labels, parc, lup_title=None,\n ldown_title=None, rup_title=None, rdown_title=None,\n figsize=1280, lineres=100,\n subjects_dir=\"/home/jev/hdd/freesurfer/subjects\",\n uniform_weight=False, surface=\"inflated\", brain_alpha=1,\n top_cnx=50, bot_cnx=None, background=(0,0,0)):\n\n if top_cnx is not None:\n matflat = mat_rgba[...,3].flatten()\n try:\n thresh = np.sort(matflat[matflat>0])[-top_cnx]\n except:\n thresh = matflat[matflat>0].min()\n out_inds = np.where(mat_rgba[...,3] < thresh)\n for x,y in zip(*out_inds):\n mat_rgba[x,y,] = np.zeros(4)\n if bot_cnx is not None:\n matflat = mat_rba[...,3].copy()\n try:\n thresh = np.sort(matflat[matflat>0])[-bot_cnx]\n except:\n thresh = matflat[matflat>0].max()\n out_inds = np.where(mat_rgba[...,3] < thresh)\n for x,y in zip(*out_inds):\n mat_rgba[x,y,] = np.zeros(4)\n\n alpha = mat_rgba[...,-1].copy()\n alpha_inds = alpha > 0\n alpha[alpha_inds] = (alpha[alpha_inds] - alpha[alpha_inds].min()) / \\\n (alpha.max() - alpha[alpha_inds].min())\n # put a floor on smallest value\n alpha[alpha_inds] = alpha[alpha_inds] * .9 + 0.1\n mat_rgba[...,-1] = alpha\n\n lingrad = np.linspace(0,1,lineres)\n brain = Brain('fsaverage', 'both', surface, alpha=brain_alpha,\n subjects_dir=subjects_dir, size=figsize, show=False,\n background=background)\n if lup_title:\n brain.add_text(0, 0.8, lup_title, \"lup\", font_size=40)\n if ldown_title:\n brain.add_text(0, 0, ldown_title, \"ldown\", font_size=40)\n if rup_title:\n brain.add_text(0.7, 0.8, rup_title, \"rup\", font_size=40)\n if rdown_title:\n brain.add_text(0.7, 0., rdown_title, \"rdown\", font_size=40)\n brain.add_annotation(parc,color=\"black\")\n rrs = np.array([brain.geo[l.hemi].coords[l.center_of_mass()] for l in labels])\n\n inds = np.where(mat_rgba[...,-1]>0)\n origins = rrs[inds[0],]\n dests = rrs[inds[1],]\n\n lengths = np.linalg.norm(origins-dests, axis=1)\n lengths = np.broadcast_to(lengths,(3,len(lengths))).T\n midpoints = (origins+dests)/2\n midpoint_units = midpoints/np.linalg.norm(midpoints,axis=1,keepdims=True)\n spline_mids = midpoints + midpoint_units*lengths*2\n\n spl_pts = np.empty((len(origins),3,lineres))\n for idx in range(len(origins)):\n color = (mat_rgba[inds[0][idx], inds[1][idx], 0],\n mat_rgba[inds[0][idx], inds[1][idx], 1],\n mat_rgba[inds[0][idx], inds[1][idx], 2])\n alpha = mat_rgba[inds[0][idx], inds[1][idx], 3]\n curve = bezier.Curve(np.array([[origins[idx,0],spline_mids[idx,0],dests[idx,0]],\n [origins[idx,1],spline_mids[idx,1],dests[idx,1]],\n [origins[idx,2],spline_mids[idx,2],dests[idx,2]]]),\n degree=2)\n spl_pts[idx,] = curve.evaluate_multi(lingrad)\n\n spline = pv.Spline(spl_pts[idx,].T, lineres)\n tube = spline.tube(radius=alpha*2)\n brain._renderer.plotter.add_mesh(tube, color=color, opacity=alpha)\n # mlab.plot3d(spl_pts[idx,0,], spl_pts[idx,1,], spl_pts[idx,2,],\n # lingrad*255, tube_radius=alpha*2, color=color,\n # opacity=alpha)\n\n ## origin/destination points and label colouring\n # first get row/column alpha maxima, calculate range for normalisation\n alpha_max = np.stack((mat_rgba[...,3].max(axis=0),\n mat_rgba[...,3].max(axis=1))).max(axis=0)\n alpha_max_max, alpha_max_min = (alpha_max.max(),\n alpha_max[alpha_max!=0].min())\n # normalise\n alpha_inds = alpha_max!=0\n alpha_max[alpha_inds] = ((alpha_max[alpha_inds] -\n alpha_max[alpha_inds].min()) /\n (alpha_max.max() - alpha_max[alpha_inds].min()))\n # put a floor on smallest value\n alpha_max[alpha_inds] = alpha_max[alpha_inds] * .7 + 0.3\n # go through each region and colour it\n for idx in range(len(labels)):\n if not (np.any(mat_rgba[idx,]) or np.any(mat_rgba[:,idx,])):\n continue\n color_vec = np.dot(mat_rgba[idx,:,:3].T, mat_rgba[idx,:,3]) + \\\n np.dot(mat_rgba[:,idx,:3].T, mat_rgba[:,idx,3])\n color_vec = color_vec / np.linalg.norm(color_vec)\n alpha = alpha_max[idx]\n brain.add_label(labels[idx], color=color_vec, alpha=alpha)\n point = pv.Sphere(center=rrs[idx], radius=alpha*5+0.2)\n brain._renderer.plotter.add_mesh(point, color=color_vec, opacity=1)\n\n # mlab.points3d(origins[idx,0],origins[idx,1],origins[idx,2],\n # alpha,scale_factor=10,color=color,transparent=True)\n # mlab.points3d(dests[idx,0],dests[idx,1],dests[idx,2],\n # alpha,scale_factor=10,color=color,transparent=True)\n\n brain.show()\n return brain\n\ndef plot_rgba(vec_rgba, labels, parc, hemi=\"both\", lup_title=None,\n ldown_title=None, rup_title=None, rdown_title=None,\n figsize=1280, subjects_dir=\"/home/jev/hdd/freesurfer/subjects\",\n uniform_weight=False, surface=\"inflated\", brain_alpha=1.,\n background=(0,0,0)):\n\n brain = Brain('fsaverage', hemi, surface, alpha=brain_alpha,\n subjects_dir=subjects_dir, size=figsize, show=False,\n background=background)\n if lup_title:\n brain.add_text(0, 0.8, lup_title, \"lup\", font_size=40)\n if ldown_title:\n brain.add_text(0, 0, ldown_title, \"ldown\", font_size=40)\n if rup_title:\n brain.add_text(0.7, 0.8, rup_title, \"rup\", font_size=40)\n if rdown_title:\n brain.add_text(0.7, 0., rdown_title, \"rdown\", font_size=40)\n\n\n brain.add_annotation(parc, color=\"black\", alpha=1.)\n\n for l_idx, l in enumerate(labels):\n if np.array_equal(vec_rgba[l_idx], [0,0,0,0]):\n continue\n brain.add_label(l, color=vec_rgba[l_idx,], hemi=l.hemi)\n\n brain.show()\n return brain\n\ndef plot_parc_compare(parc_outer, parc_inner, hemi=\"both\",\n lup_title=None, ldown_title=None, rup_title=None,\n rdown_title=None, figsize=2160,\n subjects_dir=\"/home/jev/hdd/freesurfer/subjects\",\n uniform_weight=False, surface=\"inflated\",\n brain_alpha=1.):\n\n brain = Brain('fsaverage', hemi, surface, alpha=brain_alpha,\n subjects_dir=subjects_dir, size=figsize, show=False)\n if lup_title:\n brain.add_text(0, 0.8, lup_title, \"lup\", font_size=40)\n if ldown_title:\n brain.add_text(0, 0, ldown_title, \"ldown\", font_size=40)\n if rup_title:\n brain.add_text(0.7, 0.8, rup_title, \"rup\", font_size=40)\n if rdown_title:\n brain.add_text(0.7, 0., rdown_title, \"rdown\", font_size=40)\n\n vertex_to_label_ids = {}\n for parc_name, parc in zip([\"parc_in\", \"parc_out\"],\n [parc_inner, parc_outer]):\n labels = mne.read_labels_from_annot(subject=\"fsaverage\",\n parc=parc,\n hemi=\"lh\",\n subjects_dir=subjects_dir)\n vertex_to_label_id = np.full(brain.geo[\"lh\"].coords.shape[0], -1)\n for idx, label in enumerate(labels):\n vertex_to_label_id[label.vertices] = idx\n vertex_to_label_ids[parc_name] = vertex_to_label_id\n\n # go through inner labels and see how they lay on the outer label\n in_labels = mne.read_labels_from_annot(subject=\"fsaverage\",\n parc=parc_inner,\n hemi=\"lh\",\n subjects_dir=subjects_dir)\n out_labels = mne.read_labels_from_annot(subject=\"fsaverage\",\n parc=parc_outer,\n hemi=\"lh\",\n subjects_dir=subjects_dir)\n\n df_dict = {\"In_Region\":[], \"Out_Region\":[], \"Overlap\":[], }\n for label_idx, label in enumerate(in_labels):\n in_inds = np.where(vertex_to_label_ids[\"parc_in\"]==label_idx)[0]\n out_triff = vertex_to_label_ids[\"parc_out\"][in_inds]\n uniques, counts = np.unique(out_triff, return_counts=True)\n total = counts.sum()\n for c_idx in range(len(uniques)):\n df_dict[\"In_Region\"].append(label.name[:-3])\n df_dict[\"Out_Region\"].append(out_labels[uniques[c_idx]].name[:-3])\n df_dict[\"Overlap\"].append(counts[c_idx]/total)\n df = pd.DataFrame.from_dict(df_dict)\n\n # make the table\n label_names = [l.name[:-3] for l in in_labels]\n label_colors = [l.color for l in in_labels]\n out_texts = []\n for ln in label_names:\n this_df = df.query(\"In_Region=='{}'\".format(ln))\n this_df = this_df.sort_values(\"Overlap\", ascending=False)\n anatomic_str = \"\"\n for row_idx, row in this_df.iterrows():\n if row[\"Overlap\"] == 1:\n anatomic_str += row[\"Out_Region\"]\n elif row[\"Overlap\"] < .05:\n continue\n else:\n anatomic_str += \"{} ({}), \".format(row[\"Out_Region\"],\n np.round(row[\"Overlap\"],\n decimals=2))\n if anatomic_str[-2:] == \", \":\n anatomic_str = anatomic_str[:-2] # don't want last comma and space\n out_texts.append(anatomic_str)\n cellText = list(zip(label_names, out_texts, label_colors))\n\n with open(\"parc_overlap.csv\", \"w\") as f:\n writer = csv.writer(f)\n writer.writerows(cellText)\n\n\n\n brain.add_annotation(parc_outer, color=\"black\")\n brain.add_annotation(parc_inner)\n\n brain.show()\n return brain\n\n\n\"\"\" calculate the corelation distance of dPTE connectivity matrices \"\"\"\ndef pw_cor_dist(mat,inds):\n k = len(inds)\n tu_inds = np.triu_indices(mat.shape[1], k=1)\n vecs = mat[:, tu_inds[0], tu_inds[1]]\n vecs -= 0.5 # dPTE is 0.5 centred; because we do this now, we can leave out the subtraction terms in distance calculation\n dists = np.zeros(k,dtype=\"float32\")\n for pair_idx, pair in enumerate(inds):\n dist = (vecs[pair[0]].dot(vecs[pair[1]]) /\n np.sqrt(np.sum(vecs[pair[0]]**2) * np.sum(vecs[pair[1]]**2)))\n dist = (dist * -1 + 1)/2 # transform to distance measure\n dists[pair_idx] = dist\n return dists\n\ndef make_brain_figure(views, brain, cbar=None, vmin=None, vmax=None,\n cbar_label=\"\", cbar_orient=\"vertical\",\n hide_cbar=False):\n img_list = []\n for k,v in views.items():\n brain.show_view(**v)\n scr = brain.screenshot()\n img_list.append(scr)\n\n width = 3*scr.shape[0]/100\n height = scr.shape[1]/100\n\n cb_ratio = 6\n pans = [\"A\", \"B\", \"C\"]\n if cbar:\n width += width * 1/cb_ratio\n mos_str = \"\"\n if cbar_orient == \"vertical\":\n for pan in pans:\n for x in range(cb_ratio):\n mos_str += pan\n mos_str += \"D\"\n elif cbar_orient == \"horizontal\":\n for x in range(cb_ratio):\n for pan in pans:\n mos_str += pan\n mos_str += \"\\n\"\n mos_str += \"D\"*len(pans)\n fig, axes = plt.subplot_mosaic(mos_str, figsize=(width, height))\n for img_mos, img in zip(pans, img_list):\n axes[img_mos].imshow(img)\n axes[img_mos].axis(\"off\")\n if not hide_cbar:\n norm = Normalize(vmin, vmax)\n scalmap = cm.ScalarMappable(norm, cbar)\n plt.colorbar(scalmap, cax=axes[\"D\"], orientation=cbar_orient)\n axes[\"D\"].tick_params(labelsize=48)\n if cbar_orient == \"horizontal\":\n axes[\"D\"].set_xlabel(cbar_label, fontsize=48)\n else:\n axes[\"D\"].set_ylabel(cbar_label, fontsize=48)\n else:\n axes[\"D\"].axis(\"off\")\n else:\n fig, axes = plt.subplots(1, 3, figsize=(width, height))\n for ax, img in zip(axes, img_list):\n ax.imshow(img)\n ax.axis(\"off\")\n\n return fig\n\ndef make_brain_image(views, brain, orient=\"horizontal\", text=\"\",\n text_loc=None, text_pan=None, fontsize=160,\n legend=None, legend_pan=None, cbar=None,\n vmin=None, vmax=None, cbar_label=\"\",\n cbar_separate=False):\n img_list = []\n axis = 1 if orient==\"horizontal\" else 0\n for k,v in views.items():\n brain.show_view(**v)\n scr = brain.screenshot()\n img_list.append(scr)\n if text != \"\":\n img_txt_list = []\n brain.add_text(0, 0.8, text, text_loc, font_size=fontsize, color=(0,0,0))\n for k,v in views.items():\n brain.show_view(**v)\n scr = brain.screenshot()\n img_txt_list.append(scr)\n img_list[text_pan] = img_txt_list[text_pan]\n if legend:\n legend_list = []\n leg = brain._renderer.plotter.add_legend(legend, bcolor=\"w\", size=(.3, .3))\n for k,v in views.items():\n brain.show_view(**v)\n scr = brain.screenshot()\n legend_list.append(scr)\n img_list[legend_pan] = legend_list[legend_pan]\n if orient == \"square\": # only works for 2x2\n h, w, _ = img_list[0].shape\n img = np.zeros((h*2, w*2, 3), dtype=np.uint8)\n img[:h, :w, ] = img_list[0]\n img[:h, w:, ] = img_list[1]\n img[h:, :w, ] = img_list[2]\n img[h:, w:, ] = img_list[3]\n else:\n img = np.concatenate(img_list, axis=axis)\n\n if cbar:\n norm = Normalize(vmin, vmax)\n scalmap = cm.ScalarMappable(norm, cbar)\n if orient == \"horizontal\":\n colbar_size = (img_list[-1].shape[0]*len(views), img_list[-1].shape[1]/6)\n else:\n colbar_size = (img_list[-1].shape[0]/6, img_list[-1].shape[1]*len(views))\n colbar_size = np.array(colbar_size) / 100\n fig, ax = plt.subplots(1,1, figsize=colbar_size)\n colbar = plt.colorbar(scalmap, cax=ax, orientation=orient)\n ax.tick_params(labelsize=48)\n if orient == \"horizontal\":\n ax.set_xlabel(cbar_label, fontsize=48)\n else:\n ax.set_ylabel(cbar_label, fontsize=48)\n fig.tight_layout()\n fig.canvas.draw()\n mat = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)\n mat = mat.reshape(fig.canvas.get_width_height()[::-1] + (3,))\n img = np.concatenate((img, mat), axis=abs(axis-1))\n\n if legend:\n brain._renderer.plotter.remove_legend()\n\n return img\n\ndef annotated_matrix(mat, labels, annot_labels, ax=None, cmap=\"seismic\",\n vmin=None, vmax=None, annot_height=2,\n annot_vert_pos=\"left\", annot_hor_pos=\"bottom\",\n overlay=False, cbar=False, figsize=(19.2, 19.2)):\n\n annot_H = annot_height if overlay else annot_height * len(annot_labels)\n\n N = len(labels)\n # horizontal annotation stored in a_str\n a_str = \"\"\n for x in range(annot_H):\n c_str = \"\"\n # vertical annotation stored in c_str\n for y in range(N):\n c_str += \"A\"\n # dead space stored in d_str\n d_str = \"\"\n for y in range(annot_H):\n d_str += \"X\"\n if annot_vert_pos == \"left\":\n a_str = a_str + d_str + c_str\n else:\n a_str = a_str + c_str + d_str\n if cbar:\n for y in range(annot_H):\n a_str += \"Y\"\n a_str += \"\\n\"\n # vertical annotation and image stored in b_str\n b_str = \"\"\n for x in range(N):\n c_str = \"\"\n # image stored in c_str\n if cbar:\n for y in range(N):\n c_str += \"B\"\n for y in range(annot_H):\n c_str += \"L\"\n else:\n for y in range(N):\n c_str += \"B\"\n # horizontal annotation stored in d_str\n d_str = \"\"\n for y in range(annot_H):\n d_str += \"C\"\n if annot_vert_pos == \"left\":\n b_str = b_str + d_str + c_str + \"\\n\"\n else:\n b_str = b_str + c_str + d_str + \"\\n\"\n if annot_hor_pos == \"top\":\n mos_str = a_str + b_str\n else:\n mos_str = b_str + a_str\n mos_str = mos_str[:-1]\n fig, axes = plt.subplot_mosaic(mos_str, figsize=figsize)\n axes[\"X\"].axis(\"off\")\n if cbar:\n axes[\"Y\"].axis(\"off\")\n # imshow\n imshow = axes[\"B\"].imshow(mat, cmap=cmap, vmin=vmin, vmax=vmax, aspect=\"auto\")\n if cbar:\n cbar = plt.colorbar(imshow, cax=axes[\"L\"])\n cbar.ax.set_yticks([])\n cbar.ax.text(0.25, 1.01, \"{:.3f}\".format(vmax), fontsize=52,\n transform=cbar.ax.transAxes, weight=\"bold\")\n cbar.ax.text(0.25, -.05, \"{:.3f}\".format(vmin), fontsize=52,\n transform=cbar.ax.transAxes, weight=\"bold\")\n axes[\"B\"].axis(\"off\")\n\n # annotations\n axes[\"A\"].set_xlim(0, N)\n axes[\"A\"].set_ylim(0, annot_H)\n axes[\"A\"].set_xticklabels([])\n axes[\"A\"].set_yticklabels([])\n axes[\"C\"].set_ylim(N, 0)\n axes[\"C\"].set_xlim(annot_H, 0)\n axes[\"C\"].set_xticklabels([])\n axes[\"C\"].set_yticklabels([])\n\n # build the annotations\n if overlay:\n heights = [annot_H for x in range(len(annot_labels))]\n row_inds = [0 for x in range(len(annot_labels))]\n col_inds = [0 for x in range(len(annot_labels))]\n else:\n heights = [annot_height for x in range(len(annot_labels))]\n if annot_vert_pos == \"left\":\n col_inds = [x for x in range(annot_H, 0, -annot_height)]\n col_inds = [x-annot_height for x in col_inds]\n else:\n col_inds = [x for x in range(0, annot_H, annot_height)]\n if annot_hor_pos == \"top\":\n row_inds = [x for x in range(0, annot_H, annot_height)]\n else:\n row_inds = [x for x in range(annot_H, 0, -annot_height)]\n row_inds = [x-annot_height for x in row_inds]\n for idx, al in enumerate(annot_labels):\n col_key = al[\"col_key\"]\n labs = al[\"labels\"]\n for lab_idx, lab in enumerate(labs):\n col = col_key[lab]\n rect = Rectangle((lab_idx, row_inds[idx]), 1, heights[idx],\n color=col, lw=0)\n axes[\"A\"].add_patch(rect)\n rect = Rectangle((col_inds[idx], lab_idx), heights[idx], 1,\n color=col, lw=0)\n axes[\"C\"].add_patch(rect)\n axes[\"A\"].set_xlabel(\"Y\", fontsize=82, weight=\"bold\")\n axes[\"C\"].set_ylabel(\"X\", fontsize=82, rotation=\"horizontal\", labelpad=30,\n weight=\"bold\")\n\n #plt.tight_layout()\n # consolidate as single image in numpy format\n io_buf = io.BytesIO()\n fig.savefig(io_buf, format='raw', dpi=100)\n io_buf.seek(0)\n img_arr = np.reshape(np.frombuffer(io_buf.getvalue(), dtype=np.uint8),\n newshape=(int(fig.bbox.bounds[3]), int(fig.bbox.bounds[2]), -1))\n io_buf.close()\n\n plt.close(fig)\n return img_arr\n","sub_path":"cnx/cnx_utils.py","file_name":"cnx_utils.py","file_ext":"py","file_size_in_byte":35156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"641851240","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Using BagIt to tag oceanographic data\n# \n# \n# [`BagIt`](https://en.wikipedia.org/wiki/BagIt) is a packaging format that supports storage of arbitrary digital content. The \"bag\" consists of arbitrary content and \"tags,\" the metadata files. `BagIt` packages can be used to facilitate data sharing with federal archive centers - thus ensuring digital preservation of oceanographic datasets within IOOS and its regional associations. NOAA NCEI supports reading from a Web Accessible Folder (WAF) containing bagit archives. For an example please see: http://ncei.axiomdatascience.com/cencoos/\n# \n# \n# On this notebook we will use the [python interface](http://libraryofcongress.github.io/bagit-python) for `BagIt` to create a \"bag\" of a time-series profile data. First let us load our data from a comma separated values file (`CSV`).\n\n# In[1]:\n\n\nimport os\n\nimport pandas as pd\n\nfname = os.path.join(\"data\", \"dsg\", \"timeseriesProfile.csv\")\n\ndf = pd.read_csv(fname, parse_dates=[\"time\"])\ndf.head()\n\n\n# Instead of \"bagging\" the `CSV` file we will use this create a metadata rich netCDF file.\n# \n# We can convert the table to a `DSG`, Discrete Sampling Geometry, using `pocean.dsg`. The first thing we need to do is to create a mapping from the data column names to the netCDF `axes`.\n\n# In[2]:\n\n\naxes = {\"t\": \"time\", \"x\": \"lon\", \"y\": \"lat\", \"z\": \"depth\"}\n\n\n# Now we can create a [Orthogonal Multidimensional Timeseries Profile](http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html#_orthogonal_multidimensional_array_representation_of_time_series) object...\n\n# In[3]:\n\n\nimport os\nimport tempfile\n\nfrom pocean.dsg import OrthogonalMultidimensionalTimeseriesProfile as omtsp\n\noutput_fp, output = tempfile.mkstemp()\nos.close(output_fp)\n\nncd = omtsp.from_dataframe(df.reset_index(), output=output, axes=axes, mode=\"a\")\n\n\n# ... And add some extra metadata before we close the file.\n\n# In[4]:\n\n\nnaming_authority = \"ioos\"\nst_id = \"Station1\"\n\nncd.naming_authority = naming_authority\nncd.id = st_id\nprint(ncd)\nncd.close()\n\n\n# Time to create the archive for the file with `BagIt`. We have to create a folder for the bag.\n\n# In[5]:\n\n\ntemp_bagit_folder = tempfile.mkdtemp()\ntemp_data_folder = os.path.join(temp_bagit_folder, \"data\")\n\n\n# Now we can create the bag and copy the netCDF file to a `data` sub-folder.\n\n# In[6]:\n\n\nimport shutil\n\nimport bagit\n\nbag = bagit.make_bag(temp_bagit_folder, checksum=[\"sha256\"])\n\nshutil.copy2(output, temp_data_folder + \"/parameter1.nc\")\n\n\n# Last, but not least, we have to set bag metadata and update the existing bag with it.\n\n# In[7]:\n\n\nurn = \"urn:ioos:station:{naming_authority}:{st_id}\".format(\n naming_authority=naming_authority, st_id=st_id\n)\n\nbag_meta = {\n \"Bag-Count\": \"1 of 1\",\n \"Bag-Group-Identifier\": \"ioos_bagit_testing\",\n \"Contact-Name\": \"Kyle Wilcox\",\n \"Contact-Phone\": \"907-230-0304\",\n \"Contact-Email\": \"axiom+ncei@axiomdatascience.com\",\n \"External-Identifier\": urn,\n \"External-Description\": \"Sensor data from station {}\".format(urn),\n \"Internal-Sender-Identifier\": urn,\n \"Internal-Sender-Description\": \"Station - URN:{}\".format(urn),\n \"Organization-address\": \"1016 W 6th Ave, Ste. 105, Anchorage, AK 99501, USA\",\n \"Source-Organization\": \"Axiom Data Science\",\n}\n\n\nbag.info.update(bag_meta)\nbag.save(manifests=True, processes=4)\n\n\n# That is it! Simple and efficient!!\n# \n# The cell below illustrates the bag directory tree.\n# \n# (Note that the commands below will not work on Windows and some \\*nix systems may require the installation of the command `tree`, however, they are only need for this demonstration.)\n\n# In[8]:\n\n\nget_ipython().system('tree $temp_bagit_folder')\nget_ipython().system('cat $temp_bagit_folder/manifest-sha256.txt')\n\n\n# We can add more files to the bag as needed.\n\n# In[9]:\n\n\nshutil.copy2(output, temp_data_folder + \"/parameter2.nc\")\nshutil.copy2(output, temp_data_folder + \"/parameter3.nc\")\nshutil.copy2(output, temp_data_folder + \"/parameter4.nc\")\n\nbag.save(manifests=True, processes=4)\n\n\n# In[10]:\n\n\nget_ipython().system('tree $temp_bagit_folder')\nget_ipython().system('cat $temp_bagit_folder/manifest-sha256.txt')\n\n","sub_path":"_build/jupyter_execute/content/Code Gallery/data_management_notebooks/2017-11-01-Creating-Archives-Using-Bagit.py","file_name":"2017-11-01-Creating-Archives-Using-Bagit.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"572769611","text":"import my_appapi as appapi\n\nclass outdoor_lights(appapi.my_appapi):\n\n def initialize(self):\n # self.LOGLEVEL=\"DEBUG\"\n self.log(\"outdoor_lights App\")\n self.fan=[\"off\",0]\n if \"targets\" in self.args:\n self.targets=eval(self.args[\"targets\"])\n else:\n self.log(\"targets must be defined in appdaemon.yaml file\")\n if \"light_max\" in self.args:\n self.light_max=self.args[\"light_max\"]\n else:\n self.light_max=254\n if \"light_dim\" in self.args:\n self.light_dim = self.args[\"light_dim\"]\n else:\n self.light_dim=128\n if \"light_off\" in self.args:\n self.light_off=self.args[\"light_off\"]\n else:\n self.light_off=0\n if \"fan_max\" in self.args:\n self.fan_high = self.args[\"fan_high\"]\n else:\n self.fan_high=254\n if \"fan_med\" in self.args:\n self.fan_med = self.args[\"fan_med\"]\n else:\n self.fan_med=128\n if \"fan_low\" in self.args:\n self.fan_low=self.args[\"fan_low\"]\n else:\n self.fan_low=64\n\n self.fan_high_speed=\"high\"\n self.fan_medium_speed=\"medium\"\n self.fan_low_speed=\"low\"\n\n if \"fan_off\" in self.args:\n self.fan_off=self.args[\"fan_off\"]\n else:\n self.fan_off=0\n\n if \"high_temp\" in self.args:\n self.high_temp=self.args[\"high_temp\"]\n else:\n self.high_temp=74\n if \"low_temp\" in self.args:\n self.low_temp=self.args[\"low_temp\"]\n else:\n self.low_temp=68\n \n if \"high_humidity\" in self.args:\n self.high_humidity=self.args[\"high_humidity\"]\n else:\n self.high_humidity=60\n if \"low_humidity\" in self.args:\n self.low_humidity=self.args[\"low_humidity\"]\n else:\n self.low_humidity=59\n\n if \"fan_on_speed\" in self.args:\n try:\n #we got a numeric value\n sfo=int(float(self.args[\"fan_on_speed\"]))\n if (self.fan_on>self.fan_medium):\n sfos=self.fan_high_speed\n elif (self.fan_on>self.fan_low):\n sfos=self.fan_medium_speed\n else:\n sfos=self.fan_low_speed\n except:\n sfos=self.args[\"fan_on_speed\"]\n if (sfos==self.fan_high_speed):\n sfo=self.fan_high\n elif (sfos==self.fan_medium_speed):\n sfo=self.fan_med\n else: \n sfo=self.fan_low\n else:\n sfo=self.fan_med\n sfos=self.fan_medium_speed\n\n self.fan[0]=sfos\n self.fan[1]=sfo\n\n for ent in self.targets:\n for ent_trigger in self.targets[ent][\"triggers\"]:\n self.log(\"registering callback for {} on {} for target {}\".format(ent_trigger,self.targets[ent][\"callback\"],ent))\n self.listen_state(self.targets[ent][\"callback\"],ent_trigger,target=ent)\n self.process_light_state(ent) # process each light as we register a callback for it's triggers rather than wait for a trigger to fire first.\n\n\n ########\n #\n # state change handler. All it does is call process_light_state all the work is done there.\n #\n def light_state_handler(self,trigger,attr,old,new,kwargs):\n self.log(\"trigger = {}, attr={}, old={}, new={}, kwargs={}\".format(trigger,attr,old,new,kwargs))\n self.process_light_state(kwargs[\"target\"])\n\n\n ########\n #\n # process_light_state. All the light processing happens in here.\n #\n def process_light_state(self,target,**kwargs):\n # build current state binary flag.\n state=0\n type_bits={}\n target_typ,target_name=self.split_entity(target)\n \n state=self.bit_mask(target)\n\n self.log(\"state={}\".format(state))\n if (not self.check_override_active(target)): # if the override bit is set, then don't evaluate anything else. Think of it as manual mode\n if (not state in self.targets[target][\"onState\"]) and (not state in self.targets[target][\"dimState\"]): # these states always result in light being turned off or ignored\n if state in self.targets[target][\"ignoreState\"]:\n self.log(\"state={}, ignoring state\".format(state))\n else: # if we aren't in ignore state, then it must be off state\n self.log(\"state = {} turning off light\".format(state))\n if target_typ==\"light\":\n self.my_turn_on(target,brightness=self.light_off)\n self.turn_off(target)\n elif state in self.targets[target][\"onState\"]: # these states always result in light being turned on.\n if target_typ not in [\"light\",\"fan\"]:\n self.log(\"state={} turning on {}\".format(state,target))\n self.my_turn_on(target)\n else:\n if state in self.targets[target][\"dimState\"]: # when turning on lights, media player determines whether to dim or not.\n if target_typ==\"light\":\n if self.targets[target][\"type\"]==\"fan\":\n self.log(\"adjusting fan brightness\")\n self.my_turn_on(target,brightness=self.fan_low)\n else:\n self.log(\"dim lights\")\n self.my_turn_on(target,brightness=self.light_dim)\n elif target_typ==\"fan\":\n self.log(\"adjusting fan speed\")\n self.my_turn_on(target,speed=self.fan_low_speed)\n else:\n self.log(\"unknown type assuming light\")\n self.my_turn_on(target,brightness=self.light_dim)\n else: # it wasn't a media player dim situation so it's just a simple turn on the light.\n if self.targets[target][\"type\"]==\"fan\":\n if target_typ==\"fan\":\n self.log(\"state={} turning on fan {} at speed {}\".format(state,target,self.fan[0])) \n self.my_turn_on(target,speed=self.fan[0])\n else:\n self.log(\"state={} turning on fan {} at brightness {}\".format(state,target,self.fan[1]))\n self.my_turn_on(target,brightness=self.fan[1])\n elif self.targets[target][\"type\"]==\"light\":\n self.log(\"state={} turning on light {} at brightness={}\".format(state,target,self.light_max))\n self.my_turn_on(target,brightness=self.light_max)\n else:\n self.log(\"home override set so no automations performed\")\n\n\n def my_turn_on(self,entity,**kwargs):\n self.log(\"entity={} kwargs={}\".format(entity,kwargs))\n if not kwargs=={}:\n current_state=self.get_state(entity,\"all\")\n attributes=current_state[\"attributes\"]\n current_state=current_state[\"state\"]\n\n self.log(\"current_state={}, attributes={}\".format(current_state,attributes))\n if \"brightness\" in kwargs:\n if \"brightness\" in attributes:\n if not attributes[\"brightness\"]==kwargs[\"brightness\"]:\n self.log(\"turning on entity {} brightness {}\".format(entity,kwargs[\"brightness\"]))\n self.turn_on(entity,brightness=kwargs[\"brightness\"])\n else:\n self.log(\"brightness unchanged\")\n else:\n if current_state==\"off\":\n self.log(\"No Brightness assuming light {}\")\n self.turn_on(entity,brightness=kwargs[\"brightness\"])\n elif \"speed\" in kwargs:\n if \"speed\" in attributes:\n if not attributes[\"speed\"]==kwargs[\"speed\"]:\n self.log(\"turning on entity {} speed {}\".format(entity,kwargs[\"speed\"]))\n self.turn_on(entity,speed=kwargs[\"speed\"])\n else:\n self.log(\"no change in speed\")\n else:\n self.log(\"No Speed in attribute assuming fan\")\n self.turn_on(entity,speed=kwargs[\"speed\"])\n else:\n self.log(\"unknown attributes {}\".format(kwargs))\n else:\n self.log(\"turning on entity {}\".format(entity))\n self.turn_on(entity)\n\n #############\n #\n # normalize_state - take incoming states and convert any that are calculated to on/off values.\n #\n def normalize_state(self,target,trigger,newstate):\n tmpstate=\"\"\n if newstate==None: # handle a newstate of none, typically means the object didn't exist.\n tmpstate=self.get_state(target) # if thats the case, just return the state of the target so nothing changes.\n else:\n try:\n newstate=int(float(newstate))\n if self.targets[target][\"triggers\"][trigger][\"type\"]==\"temperature\": # is it a temperature.\n self.log(\"normalizing temperature\")\n currenttemp = newstate # convert floating point to integer.\n if currenttemp>=self.high_temp: # handle temp Hi / Low state setting to on/off.\n tmpstate=\"on\"\n elif currenttemp<=self.low_temp:\n tmpstate=\"off\"\n else:\n tmpstate= self.get_state(target) # If new state is in between target points, just return current state of target so nothing changes.\n elif self.targets[target][\"triggers\"][trigger][\"type\"]==\"humidity\":\n self.log(\"normalizing humidity\")\n currenttemp = newstate # convert floating point to integer.\n if currenttemp>=self.high_humidity: # handle temp Hi / Low state setting to on/off.\n tmpstate=\"on\"\n elif currenttemp<=self.low_humidity:\n tmpstate=\"off\"\n else:\n tmpstate= self.get_state(target) # If new state is in between target points, just return current state of target so nothing changes.\n else: # we have a number, but it's not a temperature so leave the value alone.\n self.log(\"newstate is a number, but not a temperature, so leave it alone : {}\".format(newstate))\n tmpstate=newstate\n except:\n if newstate in [\"home\",\"house\",\"Home\",\"House\"]: # deal with having multiple versions of house and home to account for.\n tmpstate=\"home\"\n elif self.targets[target][\"triggers\"][trigger][\"type\"]==\"time\":\n for event in self.targets[target][\"triggers\"][trigger][\"time\"]:\n starttime=self.targets[target][\"triggers\"][trigger][\"time\"][event][\"on\"]\n endtime=self.targets[target][\"triggers\"][trigger][\"time\"][event][\"off\"]\n self.log(\"checking Start={} End={}\".format(starttime,endtime))\n if self.now_is_between(starttime,endtime):\n tmpstate=\"on\"\n else:\n tmpstate=\"off\"\n \n else:\n tmpstate=newstate\n return tmpstate\n\n def check_override_active(self,target):\n override_active=False\n for override in self.targets[target][\"overrides\"]:\n if self.get_state(override)==\"on\":\n return True\n \n def bit_mask(self,target):\n state=0\n for trigger in self.targets[target][\"triggers\"]: # loop through triggers\n t_dict=self.targets[target][\"triggers\"][trigger]\n t_state=str(self.normalize_state(target,trigger,self.get_state(trigger)))\n self.log(\"trigger={} onValue={} bit={} currentstate={}\".format(trigger,t_dict[\"onValue\"],t_dict[\"bit\"],t_state))\n # or value for this trigger to existing state bits.\n state=state | (t_dict[\"bit\"] if (t_state==t_dict[\"onValue\"]) else 0)\n self.log(\"state={}\".format(state))\n return state\n\n","sub_path":"outdoor_lights.py","file_name":"outdoor_lights.py","file_ext":"py","file_size_in_byte":10991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"193219942","text":"from configparser import ConfigParser\n\n\nclass Config:\n config_filename = 'config.ini'\n parser = ConfigParser()\n parser.read(config_filename)\n\n @classmethod\n def get_postgresql_conn_parameters(cls, section='postgresql'):\n # get section, default to postgresql\n db = {}\n if cls.parser.has_section(section):\n params = cls.parser.items(section)\n for param in params:\n db[param[0]] = param[1]\n else:\n raise Exception('Section {0} not found in the {1} file'.format(section, cls.config_filename))\n\n return db\n","sub_path":"collaborative_filtering/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"37797931","text":"import unittest\n\nfrom stack import Stack\n\n\nclass Operation:\n \"\"\"\n Arbitrary class for testing purposes.\n \"\"\"\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return \"Operation({0!r})\".format(self.name)\n\n\nclass TestStack(unittest.TestCase):\n \"\"\"\n Unit tests for the class Stack.\n \"\"\"\n\n def setUp(self):\n self.stack = Stack()\n\n\n def test_is_empty_with_one_object(self):\n \"\"\"stack.is_empty returns True for a new stack and False if it contains one object. (1p)\"\"\"\n\n # Remember that setUp has just been called and self.stack should be equal to Stack()\n self.assertTrue(\n self.stack.is_empty(),\n \"When calling is_empty for a stack with no objects, it should return True.\"\n )\n\n # Add an integer to the stack\n self.stack.push(1)\n\n self.assertFalse(\n self.stack.is_empty(),\n \"When calling is_empty for a stack with one object, it should return False.\"\n )\n\n\n def test_top_with_one_object(self):\n \"\"\"stack.top returns but does not remove the previously added object. (1p)\"\"\"\n\n operation = Operation(\"Search for stones\")\n self.stack.push(operation)\n\n # This should now be the operation object\n top_value = self.stack.top()\n\n self.assertIs(\n top_value,\n operation,\n \"After adding {0!r} to the stack, top() should return {0!r}, not {1!r}\"\n .format(operation, top_value)\n )\n\n # The top method should not remove objects.\n self.assertFalse(\n self.stack.is_empty(),\n \"When calling is_empty for a stack with one object, it should return False.\"\n )\n\n\n def test_pop_with_one_object(self):\n \"\"\"stack.pop returns and removes the previously added object. (1p)\"\"\"\n\n operation = Operation(\"Build a stone wall\")\n self.stack.push(operation)\n\n self.assertFalse(\n self.stack.is_empty(),\n \"When calling is_empty for a stack with one object, it should return False.\"\n )\n\n # Finished building a wall, remove the operation from the stack\n pop_value = self.stack.pop()\n\n self.assertIs(\n pop_value,\n operation,\n \"After adding {0!r} to the stack, pop() should return {0!r}, not {1!r}\"\n .format(operation, pop_value)\n )\n\n self.assertTrue(\n self.stack.is_empty(),\n \"When calling is_empty for a stack with no objects, it should return True.\"\n )\n\n\n def test_stack_with_three_objects(self):\n \"\"\"After pushing 3 objects to the stack, calling pop 3 times leaves the stack empty. (2p)\"\"\"\n\n self.assertTrue(\n self.stack.is_empty(),\n \"When calling is_empty for a stack with no objects, it should return True.\"\n )\n\n # Lets add three different operations\n operations = (\n Operation(\"Search for stones\"),\n Operation(\"Build a stone wall\"),\n Operation(\"Paint the wall\")\n )\n for op in reversed(operations):\n self.stack.push(op)\n\n for i, op in enumerate(operations):\n top_value = self.stack.top()\n self.assertIs(\n top_value,\n op,\n \"top() should return {0!r}, not {1!r}\"\n .format(op, top_value)\n )\n\n self.assertFalse(\n self.stack.is_empty(),\n \"After pushing three items to the stack and then calling {:d} times pop(), is_empty() should return False, not True.\"\n .format(i)\n )\n pop_value = self.stack.pop()\n self.assertIs(\n pop_value,\n op,\n \"pop() should return {0!r}, not {1!r}\"\n .format(op, pop_value)\n )\n\n # The stack should now be empty\n self.assertTrue(\n self.stack.is_empty(),\n \"After pushing three items to the stack and then calling three times pop(), is_empty() should return True, not False.\"\n )\n\n\nif __name__ == \"__main__\":\n # Run the tests\n unittest.main(verbosity=2)\n","sub_path":"stack/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"80205702","text":"from plenum.common.log import getlogger\nfrom plenum.common.types import f\nfrom plenum.common.util import getFormattedErrorMsg\nfrom plenum.test.testable import Spyable\n\nfrom sovrin_client.agent.agent import WalletedAgent, createAgent, runAgent\nfrom sovrin_client.client.client import Client\nfrom sovrin_common.exceptions import LinkNotFound\nfrom sovrin_common.constants import NONCE\nfrom sovrin_client.test.agent.helper import getAgentCmdLineParams\n\nlogger = getlogger()\n\n\n@Spyable(\n methods=[WalletedAgent._handlePing, WalletedAgent._handlePong])\nclass TestWalletedAgent(WalletedAgent):\n def getLinkForMsg(self, msg):\n nonce = msg.get(NONCE)\n identifier = msg.get(f.IDENTIFIER.nm)\n link = None\n for _, li in self.wallet._links.items():\n if li.invitationNonce == nonce and li.remoteIdentifier == identifier:\n link = li\n break\n if link:\n return link\n else:\n raise LinkNotFound\n\n @staticmethod\n def getPassedArgs():\n return getAgentCmdLineParams()\n\n def createAndRunAgent(agentClass, name, wallet=None, basedirpath=None,\n port=None, looper=None, clientClass=Client, bootstrap=True):\n try:\n loop = looper.loop if looper else None\n agent = createAgent(agentClass, name, wallet, basedirpath, port,\n loop,\n clientClass)\n runAgent(agent, looper, bootstrap)\n return agent\n except Exception as exc:\n error = \"Agent startup failed: [cause : {}]\".format(str(exc))\n logger.error(getFormattedErrorMsg(error))\n","sub_path":"sovrin_client/test/agent/test_walleted_agent.py","file_name":"test_walleted_agent.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"490872937","text":"from tkinter import *\n\nimport subprocess\n# Here, we are creating our class, Window, and inheriting from the Frame\n# class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)\n\nimport os\nimport time\n\nimport requests\nfrom requests.packages.urllib3.util.retry import Retry\nfrom requests.adapters import HTTPAdapter\n \nfrom urllib3.util.retry import Retry\nimport requests\nfrom requests.adapters import HTTPAdapter\nimport json\n\n# logging ping results\nimport datetime\nimport logging\n\n\nclass Window(Frame):\n\n # Define settings upon initialization. Here you can specify\n def __init__(self, master=None):\n \n # parameters that you want to send through the Frame class. \n Frame.__init__(self, master) \n\n #reference to the master widget, which is the tk window \n self.master = master\n\n #with that, we want to then run init_window, which doesn't yet exist\n self.init_window()\n\n #Creation of init_window\n def init_window(self):\n\n # changing the title of our master widget \n self.master.title(\"GUI\")\n\n # allowing the widget to take the full space of the root window\n self.pack(fill=BOTH, expand=1)\n\n # creating a button instance\n # quitButton = Button(self, text=\"Exit\",command=self.client_exit)\n # startButton = Button(self, text=\"Exit\",command=self.start_client)\n # quitButton = Button(self, text=\"Exit\",command=self.client_exit)\n # stopButton = Button(self, text=\"Stop\",command=self.kill_program)\n\n # placing the button on my window\n # quitButton.place(x=0, y=0)\n # stopButton.place(x=100, y=100)\n\n\n \n\n # def client_exit(self):\n # exit()\n\n def kill_program(self):\n result = subprocess.run('/opt/lampp/htdocs/pump_master/program.sh kill',shell=True, stdout=subprocess.PIPE)\n print(result.stdout.decode('utf-8'))\n # exit()\n\ndef ping_camera():\n try:\n global isCamUp\n # wait time before msg is sent after ping loss\n # msg_diff = 1*60\n msg_diff = 10\n # wait time before msg is resent after fist msg\n # msg_interval = 5*60\n msg_interval = 45\n\n counter = 0\n\n ping_list = [\"192.168.0.128\", \"192.168.0.129\", \"192.168.0.127\", \"192.168.0.133\", \"192.168.0.132\"]\n\n for hostname in ping_list:\n response = os.system(\"ping -c 4 \" + hostname)\n\n # file names\n file_name = \"/opt/lampp/htdocs/pump_master/\"+str(hostname) + \".txt\"\n file_msg_name = \"/opt/lampp/htdocs/pump_master/\"+str(hostname) + \"_msg.txt\"\n\n # no response\n # CAM is down\n if response != 0:\n\n pass\n\n # cam is up\n # delete files if exist\n else:\n counter += 1\n \n if counter==5:\n isCamUp = 1\n else:\n isCamUp = 0\n\n print(\"counter \"+str(counter))\n print(\"ISCAMPUP \"+str(isCamUp))\n root.after(10000, ping_camera)\n except Exception as e:\n # raise e\n print(e)\n \n\n\n\ndef disable_event():\n pass\n # root.destroy()\n # exit()\n\n# root window created. Here, that would be the only window, but\n# you can later have windows within windows.\nroot = Tk()\n\nroot.geometry(\"400x300+300+300\")\n\n#creation of an instance\napp = Window(root)\n\n# time.sleep(10)\n\n\n# loops here\n\nroot.after(3000, ping_camera)\n# root.after(5000, check_program_status)\n\n\n# root.after(10000, networkSelector)\n\n# sync_check()\n# root.after(10000, sync_check)\n# root.after(12000, send_photos)\n# root.after(15000, send_videos)\n\n# root.protocol(\"WM_DELETE_WINDOW\", disable_event)\n\n#mainloop \nroot.mainloop()","sub_path":"testing/ping_test.py","file_name":"ping_test.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"100456886","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community\nEdition) available.\nCopyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved.\nLicensed under the MIT License (the \"License\"); you may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\nhttp://opensource.org/licenses/MIT\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on\nan \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\"\"\"\n\nimport logging\nimport os\nimport re\n\nfrom django.conf.urls import url\nfrom django.http import JsonResponse\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom pipeline_plugins.cmdb_ip_picker.query import (\n cmdb_search_host,\n cmdb_search_topo_tree,\n cmdb_get_mainline_object_topo\n)\nfrom pipeline_plugins.components.utils import (\n cc_get_inner_ip_by_module_id,\n supplier_account_inject,\n handle_api_error,\n supplier_id_inject\n)\nfrom gcloud.conf import settings\n\nlogger = logging.getLogger('root')\nget_client_by_user = settings.ESB_GET_CLIENT_BY_USER\n\nJOB_VAR_TYPE_STR = 1\nJOB_VAR_TYPE_IP = 2\nJOB_VAR_TYPE_INDEX_ARRAY = 3\nJOB_VAR_TYPE_ARRAY = 4\nCHINESE_REGEX = re.compile(u'[\\u4e00-\\u9fa5\\\\/:*?\"<>|,]')\n\n\n@supplier_account_inject\ndef cc_search_object_attribute(request, obj_id, biz_cc_id, supplier_account):\n \"\"\"\n @summary: 获取对象自定义属性\n @param request:\n @param biz_cc_id:\n @return:\n \"\"\"\n client = get_client_by_user(request.user.username)\n kwargs = {\n 'bk_obj_id': obj_id,\n 'bk_supplier_account': supplier_account\n }\n cc_result = client.cc.search_object_attribute(kwargs)\n if not cc_result['result']:\n message = handle_api_error('cc', 'cc.search_object_attribute', kwargs, cc_result['message'])\n logger.error(message)\n result = {\n 'result': False,\n 'data': [],\n 'message': message\n }\n return JsonResponse(result)\n\n obj_property = []\n for item in cc_result['data']:\n if item['editable']:\n obj_property.append({\n 'value': item['bk_property_id'],\n 'text': item['bk_property_name']\n })\n\n return JsonResponse({'result': True, 'data': obj_property})\n\n\n@supplier_account_inject\ndef cc_search_create_object_attribute(request, obj_id, biz_cc_id, supplier_account):\n client = get_client_by_user(request.user.username)\n kwargs = {\n 'bk_obj_id': obj_id,\n 'bk_supplier_account': supplier_account\n }\n cc_result = client.cc.search_object_attribute(kwargs)\n if not cc_result['result']:\n message = handle_api_error('cc', 'cc.search_object_attribute', kwargs, cc_result['message'])\n logger.error(message)\n result = {\n 'result': False,\n 'data': [],\n 'message': message\n }\n return JsonResponse(result)\n\n obj_property = []\n for item in cc_result['data']:\n if item['editable']:\n prop_dict = {\n 'tag_code': item['bk_property_id'],\n 'type': \"input\",\n 'attrs': {\n 'name': item['bk_property_name'],\n 'editable': 'true',\n },\n }\n if item['bk_property_id'] in ['bk_set_name']:\n prop_dict[\"attrs\"][\"validation\"] = [\n {\n \"type\": \"required\"\n }\n ]\n obj_property.append(prop_dict)\n\n return JsonResponse({'result': True, 'data': obj_property})\n\n\ndef cc_format_topo_data(data, obj_id, category):\n \"\"\"\n @summary: 格式化拓扑数据\n @param obj_id set or module\n @param category prev(获取obj_id上一层级拓扑) or normal (获取obj_id层级拓扑) or picker(ip选择器拓扑)\n @return 拓扑数据列表\n \"\"\"\n tree_data = []\n for item in data:\n tree_item = {\n 'id': \"%s_%s\" % (item['bk_obj_id'], item['bk_inst_id']),\n 'label': item['bk_inst_name']\n }\n if category == \"prev\":\n if item['bk_obj_id'] != obj_id:\n tree_data.append(tree_item)\n if item.get('child'):\n tree_item['children'] = cc_format_topo_data(item['child'], obj_id, category)\n else:\n if item['bk_obj_id'] == obj_id:\n tree_data.append(tree_item)\n elif item.get('child'):\n tree_item['children'] = cc_format_topo_data(item['child'], obj_id, category)\n tree_data.append(tree_item)\n\n return tree_data\n\n\ndef cc_format_module_hosts(username, biz_cc_id, module_id_list, supplier_account):\n module_host_list = cc_get_inner_ip_by_module_id(username, biz_cc_id, module_id_list, supplier_account)\n module_host_dict = {}\n for item in module_host_list:\n for module in item['module']:\n if module_host_dict.get('module_%s' % module['bk_module_id']):\n module_host_dict['module_%s' % module['bk_module_id']].append({\n 'id': '%s_%s' % (module['bk_module_id'], item['host']['bk_host_innerip']),\n 'label': item['host']['bk_host_innerip']\n })\n else:\n module_host_dict['module_%s' % module['bk_module_id']] = [{\n 'id': '%s_%s' % (module['bk_module_id'], item['host']['bk_host_innerip']),\n 'label': item['host']['bk_host_innerip']\n }]\n return module_host_dict\n\n\n@supplier_account_inject\ndef cc_search_topo(request, obj_id, category, biz_cc_id, supplier_account):\n \"\"\"\n @summary: 查询对象拓扑\n @param request:\n @param biz_cc_id:\n @return:\n \"\"\"\n client = get_client_by_user(request.user.username)\n kwargs = {\n 'bk_biz_id': biz_cc_id,\n 'bk_supplier_account': supplier_account\n }\n cc_result = client.cc.search_biz_inst_topo(kwargs)\n if not cc_result['result']:\n message = handle_api_error('cc', 'cc.search_biz_inst_topo', kwargs, cc_result['message'])\n logger.error(message)\n result = {\n 'result': False,\n 'data': [],\n 'message': message\n }\n return JsonResponse(result)\n\n if category in [\"normal\", \"prev\", \"picker\"]:\n cc_topo = cc_format_topo_data(cc_result['data'], obj_id, category)\n else:\n cc_topo = []\n\n return JsonResponse({'result': True, 'data': cc_topo})\n\n\n@supplier_account_inject\ndef cc_get_host_by_module_id(request, biz_cc_id, supplier_account):\n \"\"\"\n 查询模块对应主机\n :param request:\n :param biz_cc_id:\n :return:\n \"\"\"\n select_module_id = request.GET.getlist('query', [])\n # 查询module对应的主机\n module_hosts = cc_format_module_hosts(request.user.username, biz_cc_id, map(lambda x: int(x), select_module_id),\n supplier_account)\n\n for del_id in (set(module_hosts.keys()) - set(map(lambda x: 'module_%s' % x, select_module_id))):\n del module_hosts[del_id]\n\n return JsonResponse({'result': True if module_hosts else False, 'data': module_hosts})\n\n\ndef job_get_script_list(request, biz_cc_id):\n \"\"\"\n 查询业务脚本列表\n :param request:\n :param biz_cc_id:\n :return:\n \"\"\"\n # 查询脚本列表\n client = get_client_by_user(request.user.username)\n source_type = request.GET.get('type')\n script_type = request.GET.get('script_type')\n\n kwargs = {\n 'bk_biz_id': biz_cc_id,\n 'is_public': True if source_type == 'public' else False,\n 'script_type': script_type or 0,\n }\n\n script_result = client.job.get_script_list(kwargs)\n\n if not script_result['result']:\n message = handle_api_error('job', 'job.get_script_list', kwargs, script_result['message'])\n logger.error(message)\n result = {\n 'result': False,\n 'message': message\n }\n return JsonResponse(result)\n\n script_dict = {}\n for script in script_result['data']['data']:\n script_dict.setdefault(script['name'], []).append(script['id'])\n\n version_data = []\n for name, version in script_dict.items():\n version_data.append({\n \"text\": name,\n \"value\": max(version)\n })\n\n return JsonResponse({'result': True, 'data': version_data})\n\n\ndef job_get_own_db_account_list(request, biz_cc_id):\n \"\"\"\n 查询用户有权限的DB帐号列表\n :param biz_cc_id:\n :param request:\n :return:\n \"\"\"\n client = get_client_by_user(request.user.username)\n kwargs = {\n 'bk_biz_id': biz_cc_id\n }\n job_result = client.job.get_own_db_account_list(kwargs)\n\n if not job_result['result']:\n message = handle_api_error('job', 'get_own_db_account_list', kwargs, job_result['message'])\n logger.error(message)\n result = {\n 'result': False,\n 'message': message\n }\n return JsonResponse(result)\n\n data = [{'text': item['db_alias'], 'value': item['db_account_id']} for item in job_result['data']]\n\n return JsonResponse({'result': True, 'data': data})\n\n\ndef file_upload(request, biz_cc_id):\n \"\"\"\n @summary: 本地文件上传\n @param request:\n @param biz_cc_id:\n @return:\n \"\"\"\n try:\n file_obj = request.FILES['file']\n file_name = file_obj.name\n file_size = file_obj.size\n # 文件名不能包含中文, 文件大小不能大于500M\n if file_size > 500 * 1024 * 1024:\n message = _(u\"文件上传失败, 文件大小超过500M\")\n response = JsonResponse({'result': False, 'message': message})\n response.status_code = 400\n return response\n\n if CHINESE_REGEX.findall(file_name):\n message = _(u\"文件上传失败,文件名不能包含中文和\\\\/:*?\\\"<>|等特殊字符\")\n response = JsonResponse({'result': False, 'message': message})\n response.status_code = 400\n return response\n\n file_content = file_obj.read()\n\n if not isinstance(biz_cc_id, int):\n return JsonResponse({\n 'result': False,\n 'message': _(u\"非法业务 ID\")\n })\n\n now_str = timezone.datetime.now().strftime('%Y%m%d%H%M%S')\n bk_path = os.path.join(settings.BASE_DIR,\n 'USERRES',\n 'bkupload',\n str(biz_cc_id),\n now_str)\n logger.info(u\"/components/query/file_upload file path: %s\" % bk_path)\n\n if not os.path.exists(bk_path):\n os.makedirs(bk_path)\n\n with open(r'%s%s' % (bk_path, file_name), 'w') as file_obj:\n file_obj.write(file_content)\n\n result = {\n 'result': True,\n 'time_str': now_str,\n 'name': file_name,\n 'size': file_size,\n }\n return JsonResponse(result)\n\n except Exception as e:\n logger.error(u\"/components/query/file_upload exception, error=%s\" % e)\n message = _(u\"文件上传失败,路径不合法或者程序异常\")\n response = JsonResponse({'result': False, 'message': message})\n response.status_code = 400\n return response\n\n\ndef job_get_job_tasks_by_biz(request, biz_cc_id):\n client = get_client_by_user(request.user.username)\n job_result = client.job.get_job_list({'bk_biz_id': biz_cc_id})\n if not job_result['result']:\n message = _(u\"查询作业平台(JOB)的作业模板[app_id=%s]接口job.get_task返回失败: %s\") % (\n biz_cc_id, job_result['message'])\n logger.error(message)\n result = {\n 'result': False,\n 'data': [],\n 'message': message\n }\n return JsonResponse(result)\n task_list = []\n for task in job_result['data']:\n task_list.append({\n 'value': task['bk_job_id'],\n 'text': task['name'],\n })\n return JsonResponse({'result': True, 'data': task_list})\n\n\ndef job_get_job_task_detail(request, biz_cc_id, task_id):\n client = get_client_by_user(request.user.username)\n job_result = client.job.get_job_detail({'bk_biz_id': biz_cc_id,\n 'bk_job_id': task_id})\n if not job_result['result']:\n message = _(u\"查询作业平台(JOB)的作业模板详情[app_id=%s]接口job.get_task_detail返回失败: %s\") % (\n biz_cc_id, job_result['message'])\n logger.error(message)\n result = {\n 'result': False,\n 'data': [],\n 'message': message\n }\n return JsonResponse(result)\n\n job_step_type_name = {\n 1: _(u\"脚本\"),\n 2: _(u\"文件\"),\n 4: u\"SQL\"\n }\n task_detail = job_result['data']\n global_var = []\n steps = []\n for var in task_detail.get('global_vars', []):\n # 1-字符串, 2-IP, 3-索引数组, 4-关联数组\n if var['type'] in [JOB_VAR_TYPE_STR, JOB_VAR_TYPE_IP, JOB_VAR_TYPE_ARRAY]:\n value = var.get('value', '')\n else:\n value = ['{plat_id}:{ip}'.format(plat_id=ip_item['bk_cloud_id'], ip=ip_item['ip'])\n for ip_item in var.get('ip_list', [])]\n global_var.append({\n 'id': var['id'],\n # 全局变量类型:1:云参, 2:上下文参数,3:IP\n 'category': var.get('category', 1),\n 'name': var['name'],\n 'type': var['type'],\n 'value': value,\n 'description': var['description']\n })\n for info in task_detail.get('steps', []):\n # 1-执行脚本, 2-传文件, 4-传SQL\n steps.append({\n 'stepId': info['step_id'],\n 'name': info['name'],\n 'scriptParams': info.get('script_param', ''),\n 'account': info.get('account', ''),\n 'ipList': '',\n 'type': info['type'],\n 'type_name': job_step_type_name.get(info['type'], info['type'])\n })\n return JsonResponse({'result': True, 'data': {'global_var': global_var, 'steps': steps}})\n\n\n@supplier_account_inject\ndef cc_search_topo_tree(request, biz_cc_id, supplier_account):\n return cmdb_search_topo_tree(request, biz_cc_id, supplier_account)\n\n\n@supplier_account_inject\n@supplier_id_inject\ndef cc_search_host(request, biz_cc_id, supplier_account, supplier_id):\n return cmdb_search_host(request, biz_cc_id, supplier_account, supplier_id)\n\n\n@supplier_account_inject\ndef cc_get_mainline_object_topo(request, biz_cc_id, supplier_account):\n return cmdb_get_mainline_object_topo(request, biz_cc_id, supplier_account)\n\n\nurlpatterns = [\n url(r'^cc_search_object_attribute/(?P\\w+)/(?P\\d+)/$', cc_search_object_attribute),\n url(r'^cc_search_create_object_attribute/(?P\\w+)/(?P\\d+)/$', cc_search_create_object_attribute),\n url(r'^cc_search_topo/(?P\\w+)/(?P\\w+)/(?P\\d+)/$', cc_search_topo),\n url(r'^cc_get_host_by_module_id/(?P\\d+)/$', cc_get_host_by_module_id),\n url(r'^job_get_script_list/(?P\\d+)/$', job_get_script_list),\n url(r'^job_get_own_db_account_list/(?P\\d+)/$', job_get_own_db_account_list),\n url(r'^file_upload/(?P\\d+)/$', file_upload),\n url(r'^job_get_job_tasks_by_biz/(?P\\d+)/$', job_get_job_tasks_by_biz),\n url(r'^job_get_job_detail_by_biz/(?P\\d+)/(?P\\d+)/$', job_get_job_task_detail),\n url(r'^cc_search_topo_tree/(?P\\d+)/$', cc_search_topo_tree),\n url(r'^cc_search_host/(?P\\d+)/$', cc_search_host),\n url(r'^cc_get_mainline_object_topo/(?P\\d+)/$', cc_get_mainline_object_topo),\n]\n","sub_path":"pipeline_plugins/components/query/sites/open/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":16049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"150365344","text":"import re\nimport os\nimport sys\nimport json\nimport glob\nimport argparse\nfrom subprocess import Popen, PIPE, DEVNULL, check_output\nfrom distutils.version import LooseVersion\nfrom typing import Union, Optional, Tuple\n\nimport urllib3\nimport yaml\nimport requests\n\nfrom demisto_sdk.common.constants import CHECKED_TYPES_REGEXES, PACKAGE_SUPPORTING_DIRECTORIES, CONTENT_GITHUB_LINK, \\\n PACKAGE_YML_FILE_REGEX, UNRELEASE_HEADER, RELEASE_NOTES_REGEX, PACKS_DIR, PACKS_DIR_REGEX, DEF_DOCKER\n\n# disable insecure warnings\nurllib3.disable_warnings()\n\n\nclass LOG_COLORS:\n NATIVE = '\\033[m'\n RED = '\\033[01;31m'\n GREEN = '\\033[01;32m'\n YELLOW = '\\033[0;33m'\n\n\ndef get_yml_paths_in_dir(project_dir: str, error_msg: str,) -> Tuple[list, str]:\n \"\"\"\n Gets the project directory and returns the path of the first yml file in that directory\n :param project_dir: string path to the project_dir\n :param error_msg: the error msg to show to the user in case not yml files found in the directory\n :return: first returned argument is the list of all yml files paths in the directory, second returned argument is a\n string path to the first yml file in project_dir\n \"\"\"\n yml_files = glob.glob(os.path.join(project_dir, '*.yml'))\n if not yml_files:\n if error_msg:\n print(error_msg)\n return [], ''\n return yml_files, yml_files[0]\n\n\n# print srt in the given color\ndef print_color(str, color):\n print(color + str + LOG_COLORS.NATIVE)\n\n\ndef print_error(error_str):\n print_color(error_str, LOG_COLORS.RED)\n\n\ndef print_warning(warning_str):\n print_color(warning_str, LOG_COLORS.YELLOW)\n\n\ndef run_command(command, is_silenced=True, exit_on_error=True, cwd=None):\n \"\"\"Run a bash command in the shell.\n\n Args:\n command (string): The string of the command you want to execute.\n is_silenced (bool): Whether to print command output.\n exit_on_error (bool): Whether to exit on command error.\n cwd (str): the path to the current working directory.\n\n Returns:\n string. The output of the command you are trying to execute.\n \"\"\"\n if is_silenced:\n p = Popen(command.split(), stdout=PIPE, stderr=PIPE, universal_newlines=True, cwd=cwd)\n else:\n p = Popen(command.split(), cwd=cwd)\n\n output, err = p.communicate()\n if err:\n if exit_on_error:\n print_error('Failed to run command {}\\nerror details:\\n{}'.format(command, err))\n sys.exit(1)\n else:\n raise RuntimeError('Failed to run command {}\\nerror details:\\n{}'.format(command, err))\n\n return output\n\n\ndef get_remote_file(full_file_path, tag='master'):\n # 'origin/' prefix is used to compared with remote branches but it is not a part of the github url.\n tag = tag.lstrip('origin/')\n\n # The replace in the end is for Windows support\n github_path = os.path.join(CONTENT_GITHUB_LINK, tag, full_file_path).replace('\\\\', '/')\n try:\n res = requests.get(github_path, verify=False)\n res.raise_for_status()\n except Exception as exc:\n print_warning('Could not find the old entity file under \"{}\".\\n'\n 'please make sure that you did not break backward compatibility. '\n 'Reason: {}'.format(github_path, exc))\n return {}\n\n if full_file_path.endswith('json'):\n details = json.loads(res.content)\n else:\n details = yaml.safe_load(res.content)\n\n return details\n\n\ndef filter_packagify_changes(modified_files, added_files, removed_files, tag='master'):\n \"\"\"\n Mark scripts/integrations that were removed and added as modifiied.\n\n :param modified_files: list of modified files in branch\n :param added_files: list of new files in branch\n :param removed_files: list of removed files in branch\n :param tag: tag of compared revision\n\n :return: tuple of updated lists: (modified_files, updated_added_files, removed_files)\n \"\"\"\n # map IDs to removed files\n packagify_diff = {} # type: dict\n for file_path in removed_files:\n if file_path.split(\"/\")[0] in PACKAGE_SUPPORTING_DIRECTORIES:\n details = get_remote_file(file_path, tag)\n if details:\n uniq_identifier = '_'.join([\n details['name'],\n details.get('fromversion', '0.0.0'),\n details.get('toversion', '99.99.99')\n ])\n packagify_diff[uniq_identifier] = file_path\n\n updated_added_files = set()\n for file_path in added_files:\n if file_path.split(\"/\")[0] in PACKAGE_SUPPORTING_DIRECTORIES:\n with open(file_path) as f:\n details = yaml.safe_load(f.read())\n\n uniq_identifier = '_'.join([\n details['name'],\n details.get('fromversion', '0.0.0'),\n details.get('toversion', '99.99.99')\n ])\n if uniq_identifier in packagify_diff:\n # if name appears as added and removed, this is packagify process - treat as modified.\n removed_files.remove(packagify_diff[uniq_identifier])\n modified_files.add((packagify_diff[uniq_identifier], file_path))\n continue\n\n updated_added_files.add(file_path)\n\n # remove files that are marked as both \"added\" and \"modified\"\n for file_path in modified_files:\n if isinstance(file_path, tuple):\n updated_added_files -= {file_path[1]}\n else:\n updated_added_files -= {file_path}\n\n return modified_files, updated_added_files, removed_files\n\n\ndef get_child_directories(directory):\n \"\"\"Return a list of paths of immediate child directories of the 'directory' argument\"\"\"\n if not os.path.isdir(directory):\n return []\n child_directories = [\n os.path.join(directory, path) for\n path in os.listdir(directory) if os.path.isdir(os.path.join(directory, path))\n ]\n return child_directories\n\n\ndef get_child_files(directory):\n \"\"\"Return a list of paths of immediate child files of the 'directory' argument\"\"\"\n if not os.path.isdir(directory):\n return []\n child_files = [\n os.path.join(directory, path) for\n path in os.listdir(directory) if os.path.isfile(os.path.join(directory, path))\n ]\n return child_files\n\n\ndef get_last_release_version():\n \"\"\"\n Get latest release tag (xx.xx.xx)\n\n :return: tag\n \"\"\"\n tags = run_command('git tag').split('\\n')\n tags = [tag for tag in tags if re.match(r'\\d+\\.\\d+\\.\\d+', tag) is not None]\n tags.sort(key=LooseVersion, reverse=True)\n\n return tags[0]\n\n\ndef get_file(method, file_path, type_of_file):\n data_dictionary = None\n with open(os.path.expanduser(file_path), \"r\") as f:\n if file_path.endswith(type_of_file):\n try:\n data_dictionary = method(f)\n except Exception as e:\n print_error(\n \"{} has a structure issue of file type{}. Error was: {}\".format(file_path, type_of_file, str(e)))\n return []\n if type(data_dictionary) is dict:\n return data_dictionary\n return {}\n\n\ndef get_yaml(file_path):\n return get_file(yaml.safe_load, file_path, ('yml', 'yaml'))\n\n\ndef get_json(file_path):\n return get_file(json.load, file_path, 'json')\n\n\ndef get_script_or_integration_id(file_path):\n data_dictionary = get_yaml(file_path)\n\n if data_dictionary:\n commonfields = data_dictionary.get('commonfields', {})\n return commonfields.get('id', ['-', ])\n\n\ndef collect_ids(file_path):\n \"\"\"Collect id mentioned in file_path\"\"\"\n data_dictionary = get_yaml(file_path)\n\n if data_dictionary:\n return data_dictionary.get('id', '-')\n\n\ndef get_from_version(file_path):\n data_dictionary = get_yaml(file_path)\n\n if data_dictionary:\n from_version = data_dictionary.get('fromversion', '0.0.0')\n if from_version == \"\":\n return \"0.0.0\"\n\n if not re.match(r\"^\\d{1,2}\\.\\d{1,2}\\.\\d{1,2}$\", from_version):\n raise ValueError(\"{} fromversion is invalid \\\"{}\\\". \"\n \"Should be of format: \\\"x.x.x\\\". for example: \\\"4.5.0\\\"\".format(file_path, from_version))\n\n return from_version\n\n return '0.0.0'\n\n\ndef get_to_version(file_path):\n data_dictionary = get_yaml(file_path)\n\n if data_dictionary:\n to_version = data_dictionary.get('toversion', '99.99.99')\n if not re.match(r\"^\\d{1,2}\\.\\d{1,2}\\.\\d{1,2}$\", to_version):\n raise ValueError(\"{} toversion is invalid \\\"{}\\\". \"\n \"Should be of format: \\\"x.x.x\\\". for example: \\\"4.5.0\\\"\".format(file_path, to_version))\n\n return to_version\n\n return '99.99.99'\n\n\ndef str2bool(v):\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n\n if v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\n\ndef get_release_notes_file_path(file_path):\n dir_name = os.path.dirname(file_path)\n\n if re.match(PACKAGE_YML_FILE_REGEX, file_path):\n return os.path.join(dir_name, 'CHANGELOG.md')\n\n # outside of packages, change log file will include the original file name.\n file_name = os.path.basename(file_path)\n return os.path.join(dir_name, os.path.splitext(file_name)[0] + '_CHANGELOG.md')\n\n\ndef get_latest_release_notes_text(rn_path):\n if not os.path.isfile(rn_path):\n # releaseNotes were not provided\n return None\n\n with open(rn_path) as f:\n rn = f.read()\n\n if not rn:\n # empty releaseNotes is not supported\n return None\n\n new_rn = re.findall(RELEASE_NOTES_REGEX, rn)\n if new_rn:\n # get release notes up to release header\n new_rn = new_rn[0].rstrip()\n else:\n new_rn = rn.replace(UNRELEASE_HEADER, '')\n\n return new_rn if new_rn else None\n\n\ndef checked_type(file_path, compared_regexes=None, return_regex=False):\n compared_regexes = compared_regexes or CHECKED_TYPES_REGEXES\n for regex in compared_regexes:\n if re.match(regex, file_path, re.IGNORECASE):\n if return_regex:\n return regex\n return True\n return False\n\n\ndef server_version_compare(v1, v2):\n \"\"\"compare Demisto versions\n\n Args:\n v1 (string): string representing Demisto version (first comparable)\n v2 (string): string representing Demisto version (second comparable)\n\n\n Returns:\n int.\n 0 for equal versions.\n positive if v1 later version than v2.\n negative if v2 later version than v1.\n \"\"\"\n\n _v1, _v2 = LooseVersion(v1), LooseVersion(v2)\n if _v1 == _v2:\n return 0\n if _v1 > _v2:\n return 1\n return -1\n\n\ndef run_threads_list(threads_list):\n \"\"\"\n Start a list of threads and wait for completion (join)\n\n Arguments:\n threads_list (list of threads) -- list of threads to start and wait for join\n \"\"\"\n # run each command in a separate thread\n for t in threads_list:\n t.start()\n # wait for the commands to complete\n for t in threads_list:\n t.join()\n\n\ndef get_dockerimage45(script_object):\n \"\"\"Get the docker image used up to 4.5 (including).\n\n Arguments:\n script_object {dict} -- [script object containing the dockerimage configuration]\n \"\"\"\n if 'dockerimage45' in script_object:\n return script_object['dockerimage45']\n return script_object.get('dockerimage', '')\n\n\ndef is_file_path_in_pack(file_path):\n return bool(re.findall(PACKS_DIR_REGEX, file_path))\n\n\ndef get_pack_name(file_path):\n match = re.search(r'^(?:./)?{}/([^/]+)/'.format(PACKS_DIR), file_path)\n return match.group(1) if match else None\n\n\ndef pack_name_to_path(pack_name):\n return os.path.join(PACKS_DIR, pack_name)\n\n\ndef get_matching_regex(string_to_match, regexes):\n # type: (str, Union[list, str]) -> Optional[str]\n \"\"\"Gets a string and find id the regexes list matches the string. if do, return regex else None.\n\n Args:\n string_to_match: String to find matching regex\n regexes: regexes to check.\n\n Returns:\n matching regex if exists, else None\n \"\"\"\n return checked_type(string_to_match, regexes, return_regex=True)\n\n\ndef get_docker_images(script_obj):\n imgs = [script_obj.get('dockerimage') or DEF_DOCKER]\n alt_imgs = script_obj.get('alt_dockerimages')\n if alt_imgs:\n imgs.extend(alt_imgs)\n return imgs\n\n\ndef get_all_docker_images(script_obj):\n \"\"\"Gets a yml as dict and returns a list of all 'dockerimage' values in the yml.\n\n Args:\n script_obj (dict): A yml dict.\n\n Returns:\n List. A list of all docker images.\n \"\"\"\n # this makes sure the first docker in the list is the main docker image.\n imgs = [script_obj.get('dockerimage') or DEF_DOCKER]\n\n # get additional docker images\n for key in script_obj.keys():\n if 'dockerimage' in key and key != 'dockerimage':\n if isinstance(script_obj.get(key), str):\n imgs.append(script_obj.get(key))\n\n elif isinstance(script_obj.get(key), list):\n imgs.extend(script_obj.get(key))\n\n return imgs\n\n\ndef get_python_version(docker_image, log_verbose, no_prints=False):\n \"\"\"\n Get the python version of a docker image\n Arguments:\n docker_image {string} -- Docker image being used by the project\n Return:\n python version as a float (2.7, 3.7)\n Raises:\n ValueError -- if version is not supported\n \"\"\"\n stderr_out = None if log_verbose else DEVNULL\n py_ver = check_output([\"docker\", \"run\", \"--rm\", docker_image,\n \"python\", \"-c\",\n \"import sys;print('{}.{}'.format(sys.version_info[0], sys.version_info[1]))\"],\n universal_newlines=True, stderr=stderr_out).strip()\n if not no_prints:\n print(\"Detected python version: [{}] for docker image: {}\".format(py_ver, docker_image))\n\n py_num = float(py_ver)\n if py_num < 2.7 or (3 < py_num < 3.4): # pylint can only work on python 3.4 and up\n raise ValueError(\"Python vesion for docker image: {} is not supported: {}. \"\n \"We only support python 2.7.* and python3 >= 3.4.\".format(docker_image, py_num))\n return py_num\n\n\ndef get_pipenv_dir(py_version, envs_dirs_base):\n \"\"\"\n Get the direcotry holding pipenv files for the specified python version\n Arguments:\n py_version {float} -- python version as 2.7 or 3.7\n Returns:\n string -- full path to the pipenv dir\n \"\"\"\n return \"{}{}\".format(envs_dirs_base, int(py_version))\n\n\ndef print_v(msg, log_verbose=False):\n if log_verbose:\n print(msg)\n\n\ndef get_dev_requirements(py_version, envs_dirs_base, log_verbose=False):\n \"\"\"\n Get the requirements for the specified py version.\n\n Arguments:\n py_version {float} -- python version as float (2.7, 3.7)\n\n Raises:\n ValueError -- If can't detect python version\n\n Returns:\n string -- requirement required for the project\n \"\"\"\n env_dir = get_pipenv_dir(py_version, envs_dirs_base)\n stderr_out = None if log_verbose else DEVNULL\n requirements = check_output(['pipenv', 'lock', '-r', '-d'], cwd=env_dir, universal_newlines=True,\n stderr=stderr_out)\n print_v(\"dev requirements:\\n{}\".format(requirements))\n return requirements\n","sub_path":"demisto_sdk/common/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":15406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"566774774","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2017-2020 The SymbiFlow Authors.\n#\n# Use of this source code is governed by a ISC-style\n# license that can be found in the LICENSE file or at\n# https://opensource.org/licenses/ISC\n#\n# SPDX-License-Identifier: ISC\n\nfrom __future__ import print_function\nimport textx\nimport os.path\nimport argparse\nfrom collections import namedtuple\nimport enum\n\n\nclass ValueFormat(enum.Enum):\n PLAIN = 0\n VERILOG_DECIMAL = 1\n VERILOG_HEX = 2\n VERILOG_BINARY = 3\n VERILOG_OCTAL = 4\n\n\n# Python version of a SetFasmFeature line.\n# feature is a string\n# start and end are ints. When FeatureAddress is missing, start=None and\n# end=None.\n# value is an int.\n#\n# When FeatureValue is missing, value=1.\n# value_format determines what to output the value.\n# Should be a ValueFormat or None.\n# If None, value must be 1 and the value will be omited.\nSetFasmFeature = namedtuple(\n 'SetFasmFeature', 'feature start end value value_format')\n\nAnnotation = namedtuple('Annotation', 'name value')\n\n# Python version of FasmLine.\n# set_feature should be a SetFasmFeature or None.\n# annotations should be a tuple of Annotation or None.\n# comment should a string or None.\nFasmLine = namedtuple('FasmLine', 'set_feature annotations comment')\n\n\ndef assert_max_width(width, value):\n \"\"\" asserts if the value is greater than the width. \"\"\"\n assert value < (2**width), (width, value)\n\n\ndef verilog_value_to_int(verilog_value):\n \"\"\" Convert VerilogValue model to width, value, value_format \"\"\"\n width = None\n\n if verilog_value.plain_decimal:\n return width, int(verilog_value.plain_decimal), ValueFormat.PLAIN\n\n if verilog_value.width:\n width = int(verilog_value.width)\n\n if verilog_value.hex_value:\n value = int(verilog_value.hex_value.replace('_', ''), 16)\n value_format = ValueFormat.VERILOG_HEX\n elif verilog_value.binary_value:\n value = int(verilog_value.binary_value.replace('_', ''), 2)\n value_format = ValueFormat.VERILOG_BINARY\n elif verilog_value.decimal_value:\n value = int(verilog_value.decimal_value.replace('_', ''), 10)\n value_format = ValueFormat.VERILOG_DECIMAL\n elif verilog_value.octal_value:\n value = int(verilog_value.octal_value.replace('_', ''), 8)\n value_format = ValueFormat.VERILOG_OCTAL\n else:\n assert False, verilog_value\n\n if width is not None:\n assert_max_width(width, value)\n\n return width, value, value_format\n\n\ndef set_feature_model_to_tuple(set_feature_model):\n start = None\n end = None\n value = 1\n address_width = 1\n value_format = None\n\n if set_feature_model.feature_address:\n if set_feature_model.feature_address.address2:\n end = int(set_feature_model.feature_address.address1, 10)\n start = int(set_feature_model.feature_address.address2, 10)\n address_width = end - start + 1\n else:\n start = int(set_feature_model.feature_address.address1, 10)\n end = None\n address_width = 1\n\n if set_feature_model.feature_value:\n width, value, value_format = verilog_value_to_int(\n set_feature_model.feature_value)\n\n if width is not None:\n assert width <= address_width\n\n assert value < (2**address_width), (value, address_width)\n\n return SetFasmFeature(\n feature=set_feature_model.feature,\n start=start,\n end=end,\n value=value,\n value_format=value_format,\n )\n\n\ndef get_fasm_metamodel():\n return textx.metamodel_from_file(\n file_name=os.path.join(os.path.dirname(__file__), 'fasm.tx'),\n skipws=False)\n\n\ndef fasm_model_to_tuple(fasm_model):\n \"\"\" Converts FasmFile model to list of FasmLine named tuples. \"\"\"\n if not fasm_model:\n return\n\n for fasm_line in fasm_model.lines:\n set_feature = None\n annotations = None\n comment = None\n\n if fasm_line.set_feature:\n set_feature = set_feature_model_to_tuple(fasm_line.set_feature)\n\n if fasm_line.annotations:\n annotations = tuple(\n Annotation(\n name=annotation.name,\n value=annotation.value if annotation.value else '')\n for annotation in fasm_line.annotations.annotations)\n\n if fasm_line.comment:\n comment = fasm_line.comment.comment\n\n yield FasmLine(\n set_feature=set_feature,\n annotations=annotations,\n comment=comment,\n )\n\n\ndef parse_fasm_string(s):\n \"\"\" Parse FASM string, returning list of FasmLine named tuples.\"\"\"\n return fasm_model_to_tuple(get_fasm_metamodel().model_from_str(s))\n\n\ndef parse_fasm_filename(filename):\n \"\"\" Parse FASM file, returning list of FasmLine named tuples.\"\"\"\n return fasm_model_to_tuple(get_fasm_metamodel().model_from_file(filename))\n\n\ndef fasm_value_to_str(value, width, value_format):\n \"\"\" Convert value from SetFasmFeature to a string. \"\"\"\n if value_format == ValueFormat.PLAIN:\n return '{}'.format(value)\n elif value_format == ValueFormat.VERILOG_HEX:\n return \"{}'h{:X}\".format(width, value)\n elif value_format == ValueFormat.VERILOG_DECIMAL:\n return \"{}'d{}\".format(width, value)\n elif value_format == ValueFormat.VERILOG_OCTAL:\n return \"{}'o{:o}\".format(width, value)\n elif value_format == ValueFormat.VERILOG_BINARY:\n return \"{}'b{:b}\".format(width, value)\n else:\n assert False, value_format\n\n\ndef set_feature_width(set_feature):\n if set_feature.end is None:\n return 1\n else:\n assert set_feature.start is not None\n assert set_feature.start >= 0\n assert set_feature.end >= set_feature.start\n\n return set_feature.end - set_feature.start + 1\n\n\ndef set_feature_to_str(set_feature, check_if_canonical=False):\n \"\"\" Convert SetFasmFeature tuple to string. \"\"\"\n feature_width = set_feature_width(set_feature)\n max_feature_value = 2**feature_width\n assert set_feature.value < max_feature_value\n\n if check_if_canonical:\n assert feature_width == 1\n assert set_feature.end is None\n if set_feature.start is not None:\n assert set_feature.start != 0\n assert set_feature.value_format is None\n\n feature = set_feature.feature\n address = ''\n feature_value = ''\n\n if set_feature.start is not None:\n if set_feature.end is not None:\n address = '[{}:{}]'.format(set_feature.end, set_feature.start)\n else:\n address = '[{}]'.format(set_feature.start)\n\n if set_feature.value_format is not None:\n feature_value = ' = {}'.format(\n fasm_value_to_str(\n value=set_feature.value,\n width=feature_width,\n value_format=set_feature.value_format))\n\n return '{}{}{}'.format(feature, address, feature_value)\n\n\ndef canonical_features(set_feature):\n \"\"\" Yield SetFasmFeature tuples that are of canonical form.\n\n EG width 1, and value 1.\n \"\"\"\n if set_feature.value == 0:\n return\n\n if set_feature.start is None:\n assert set_feature.value == 1\n assert set_feature.end is None\n yield SetFasmFeature(\n feature=set_feature.feature,\n start=None,\n end=None,\n value=1,\n value_format=None,\n )\n\n return\n\n if set_feature.start is not None and set_feature.end is None:\n assert set_feature.value == 1\n\n if set_feature.start == 0:\n yield SetFasmFeature(\n feature=set_feature.feature,\n start=None,\n end=None,\n value=1,\n value_format=None,\n )\n else:\n yield SetFasmFeature(\n feature=set_feature.feature,\n start=set_feature.start,\n end=None,\n value=1,\n value_format=None,\n )\n\n return\n\n assert set_feature.start is not None\n assert set_feature.start >= 0\n assert set_feature.end >= set_feature.start\n\n for address in range(set_feature.start, set_feature.end + 1):\n value = (set_feature.value >> (address - set_feature.start)) & 1\n if value:\n if address == 0:\n yield SetFasmFeature(\n feature=set_feature.feature,\n start=None,\n end=None,\n value=1,\n value_format=None,\n )\n else:\n yield SetFasmFeature(\n feature=set_feature.feature,\n start=address,\n end=None,\n value=1,\n value_format=None,\n )\n\n\ndef fasm_line_to_string(fasm_line, canonical=False):\n if canonical:\n if fasm_line.set_feature:\n for feature in canonical_features(fasm_line.set_feature):\n yield set_feature_to_str(feature, check_if_canonical=True)\n\n return\n\n parts = []\n\n if fasm_line.set_feature:\n parts.append(set_feature_to_str(fasm_line.set_feature))\n\n if fasm_line.annotations and not canonical:\n annotations = '{{ {} }}'.format(\n ', '.join(\n '{} = \"{}\"'.format(annotation.name, annotation.value)\n for annotation in fasm_line.annotations))\n\n parts.append(annotations)\n\n if fasm_line.comment is not None and not canonical:\n comment = '#{}'.format(fasm_line.comment)\n parts.append(comment)\n\n if len(parts) == 0 and canonical:\n return\n\n yield ' '.join(parts)\n\n\ndef fasm_tuple_to_string(model, canonical=False):\n \"\"\" Returns string of FASM file for the model given.\n\n Note that calling parse_fasm_filename and then calling fasm_tuple_to_string\n will result in all optional whitespace replaced with one space.\n \"\"\"\n\n lines = []\n for fasm_line in model:\n for line in fasm_line_to_string(fasm_line, canonical=canonical):\n lines.append(line)\n\n if canonical:\n lines = list(sorted(set(lines)))\n\n return '\\n'.join(lines) + '\\n'\n\n\ndef main():\n parser = argparse.ArgumentParser('FASM tool')\n parser.add_argument('file', help='Filename to process')\n parser.add_argument(\n '--canonical',\n action='store_true',\n help='Return canonical form of FASM.')\n\n args = parser.parse_args()\n\n fasm_tuples = parse_fasm_filename(args.file)\n\n print(fasm_tuple_to_string(fasm_tuples, args.canonical))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"fasm/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"405861501","text":"person0 = {'first_name': 'emmannuel', 'last_name': 'testing', 'age': 20, 'city': 'london'}\nperson1 = {'first_name': 'noah', 'last_name': 'Lovedr', 'age': 13, 'city': 'Sheffield'}\nperson2 = {'first_name': 'jason', 'last_name': 'mon', 'age': 21, 'city': 'Accra'}\n\npeople = [person0, person1, person2]\nfor person in people:\n for k, v in person.items():\n print(f'{k} : {v}')\n print()\n\npet0 = {'animal': 'dog', 'owner': 'bob'}\npet1 = {'animal': 'cat', 'owner': 'noah'}\npet2 = {'animal': 'hamster', 'owner': 'jason'}\n\npets = [pet0, pet1, pet2]\n\nfor pet in pets:\n print(f\"The pet is a {pet['animal']} and the owner is {pet['owner'].title()}\")\n\nfavourite_places = {\n 'peter': ['accra', 'lisbon', 'london'],\n 'king': ['london', 'barcelona', 'paris']\n}\n\nfor name, places in favourite_places.items():\n print(f\"{name.title()}'s favourite places are: \")\n for place in places:\n print(f\"\\t- {place}\")\n print()\n\nfavourite_number = {\n 'peter': [9, 10, 8],\n 'james': [5, 6, 4],\n 'matt': [3, 2],\n 'lisa': [8, 5, 3],\n 'logan': [6, 9, 11]\n}\n\nfor name, numbers in favourite_number.items():\n print(f\"{name.title()}'s favourite number is: \")\n for number in numbers:\n print(f\"\\t- {number}\")\n\ncities = {\n 'new york': {'country': 'US', 'population': '1.2 billion', 'fact': 'More than 800 languages spoken in NYC'},\n 'london': {'country': 'UK', 'population': '700 million', 'fact': 'capital is London'},\n}\n\nfor city, info in cities.items():\n print(f\"The city: {city} is located in {info['country']}, with a population of {info['population']}\")\n print(f\"\\t - fact about {city}: {info['fact']}\")\n","sub_path":"Exercises/dictionary/dictexercise3.py","file_name":"dictexercise3.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"651564377","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('testreport', '0029_testplan_description'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='launch',\n name='duration',\n field=models.FloatField(default=None, verbose_name='Duration time', null=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"testreport/migrations/0030_launch_duration.py","file_name":"0030_launch_duration.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"396579847","text":"import matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom matplotlib import style\n\n# open('reward_log.txt', 'w').close()\n\nplt.style.use('ggplot')\npause = False\n\nfig1 = plt.figure()\nax1 = fig1.add_subplot(1,2,1)\nax2 = fig1.add_subplot(1,2,2)\nfig2 = plt.figure()\nbx1 = fig2.add_subplot(1,2,1)\nbx2 = fig2.add_subplot(1,2,2)\n\ndef animate(i):\n graph_data = open('reward_log.txt','r').read()\n lines = graph_data.split('\\n')\n xs = []\n ys1 = []\n ys2 = []\n vcs = []\n pcs = []\n for line in lines:\n if len(line) > 1:\n x, y1 , y2, vc, pc = line.split(',')\n xs.append(float(x))\n ys1.append(float(y1))\n ys2.append(float(y2))\n vcs.append(float(vc))\n pcs.append(float(pc))\n \n ax1.clear()\n ax2.clear()\n bx1.clear()\n bx2.clear()\n ax1.plot(xs, ys1)\n ax2.plot(xs, ys2, 'm')\n bx1.plot(xs, vcs, 'g')\n bx2.plot(xs, pcs, 'b')\n ax1.set_xlabel('Episode No.')\n ax1.set_ylabel('Episode Reward')\n ax2.set_xlabel('Episode No.')\n ax2.set_ylabel('Avearge Episode Rewards')\n ax1.set_title('Reward Graph')\n ax2.set_title('Avg Reward over 100 episodes')\n bx1.set_xlabel('Episode No.')\n bx1.set_ylabel('Value Cost')\n bx2.set_xlabel('Episode No.')\n bx2.set_ylabel('Policy cost')\n bx1.set_title('Value function model')\n bx2.set_title('Policy Function Model')\n if len(xs) == 5000:\n fig1.savefig('Fig_1.png')\n fig2.savefig('Fig_2.png')\n quit()\n \nani1 = animation.FuncAnimation(fig1, animate, interval=1000)\nani2 = animation.FuncAnimation(fig2, animate, interval=1000)\nplt.show()\n","sub_path":"plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"568222374","text":"import os\nimport inspect\nimport unittest\nfrom pyulog import ulog2csv, info, params, messages, extract_gps_dump\nimport sys\nimport tempfile\n\nTEST_PATH = os.path.dirname(os.path.abspath(\n inspect.getfile(inspect.currentframe())))\n\nclass Test(unittest.TestCase):\n\n def test_ulog2csv(self):\n tmpdir = tempfile.gettempdir()\n print('writing files to ', tmpdir)\n ulog_file_name = os.path.join(TEST_PATH, 'sample.ulg')\n messages = []\n output=tmpdir\n delimiter=','\n ulog2csv.convert_ulog2csv(ulog_file_name, messages, output, delimiter)\n\n def test_pyulog_info_cli(self):\n sys.argv = [\n '',\n os.path.join(TEST_PATH, 'sample.ulg')\n ]\n info.main()\n\n @unittest.skip(\"no gps data in log file\")\n def test_extract_gps_dump_cli(self):\n sys.argv = [\n '',\n os.path.join(TEST_PATH, 'sample.ulg')\n ]\n extract_gps_dump.main()\n\n def test_messages_cli(self):\n sys.argv = [\n '',\n os.path.join(TEST_PATH, 'sample.ulg')\n ]\n messages.main()\n\n def test_params_cli(self):\n sys.argv = [\n '',\n os.path.join(TEST_PATH, 'sample.ulg')\n ]\n params.main()\n\n\n# vim: set et fenc=utf-8 ft=python ff=unix sts=4 sw=4 ts=4 : \n","sub_path":"test/test_ulog2csv.py","file_name":"test_ulog2csv.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"266317109","text":"import random\nimport asyncio\n\nvowels = set('aeiou')\n\nprint(\"[Public Plugin] : This plugin tells you what to give a bitch.\")\n\n\n@asyncio.coroutine\ndef action(message, client, config):\n words = [line.strip() for line in open('data/items.data')]\n gift = random.choice(words).upper()\n\n plural = pluralize(gift).upper()\n\n if gift[0] in vowels:\n gift = 'N ' + gift\n else:\n gift = ' ' + gift\n\n if \"what do you give a \" in message.content.lower():\n split_message = message.content.lower().split('what do you give a ')\n\n if len(split_message) > 1:\n target = split_message[-1].replace('?', '')\n yield from client.send_message(message.channel, 'GIVE THAT ' + target.upper() + ' A' + gift + '. ' + target.upper() + 'S LOVE ' + plural + '.')\n\n\ndef pluralize(singular):\n root = singular\n try:\n if singular[-1] == 'y' and singular[-2] not in vowels:\n root = singular[:-1]\n suffix = 'ies'\n elif singular[-1] == 's':\n if singular[-2] in vowels:\n if singular[-3:] == 'ius':\n root = singular[:-2]\n suffix = 'i'\n else:\n root = singular[:-1]\n suffix = 'ses'\n else:\n suffix = 'es'\n elif singular[-2:] in ('ch', 'sh'):\n suffix = 'es'\n else:\n suffix = 's'\n except IndexError:\n suffix = 's'\n plural = root + suffix\n return plural\n","sub_path":"public_plugins/giveabitch.py","file_name":"giveabitch.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"74424414","text":"# encoding: utf-8\n\nimport os\n\nfrom website import settings\n\n\nWATERBUTLER_CREDENTIALS = {\n 'storage': {}\n}\n\nWATERBUTLER_SETTINGS = {\n 'storage': {\n 'provider': 'filesystem',\n 'folder': os.path.join(settings.BASE_PATH, 'osfstoragecache'),\n }\n}\n\nWATERBUTLER_RESOURCE = 'folder'\n\nDISK_SAVING_MODE = settings.DISK_SAVING_MODE\n","sub_path":"website/addons/osfstorage/settings/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"126555179","text":"import logging\n\nfrom dataclasses import Field, dataclass, fields, is_dataclass\nfrom typing import (\n Any,\n Callable,\n Dict,\n FrozenSet,\n List,\n NamedTuple,\n Type,\n get_type_hints,\n)\n\nfrom starlette.routing import Router\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef isinstance_partial(type: Type) -> Callable[[Any], bool]:\n def partial(obj) -> bool:\n return isinstance(obj, type)\n\n return partial\n\n\nis_bool = isinstance_partial(bool)\n\n\ndef does_match(cls, name: str, asserter: Callable[[Any], bool]) -> bool:\n item = getattr(cls, name, None)\n\n return (item is not None) and asserter(item)\n\n\nclass Function:\n has_sideeffect: bool = False\n require_restart: bool = False\n disabled = False\n force_enabled = False\n\n SettingTypes: List[Field]\n InputTypes: Dict[str, Type]\n OutputTypes: Dict[str, Type]\n\n type: str\n\n def __init_subclass__(cls, *args, **kargs):\n def error(msg):\n raise TypeError(f\"Function {cls.__name__} must have a {msg}\")\n\n if not does_match(cls, \"Settings\", is_dataclass):\n error(\"dataclass 'Settings'\")\n\n if not does_match(cls, \"Inputs\", is_dataclass):\n error(\"dataclass 'Inputs'\")\n\n if not does_match(cls, \"Outputs\", is_dataclass):\n error(\"dataclass 'Outputs'\")\n\n if not does_match(cls, \"has_sideeffect\", is_bool):\n error(\"bool property 'has_sideeffect'\")\n\n if not hasattr(cls, \"require_restart\"):\n error(\"property 'require_restart'\")\n\n if not does_match(cls, \"disabled\", is_bool):\n error(\"bool property 'disabled'\")\n\n cls.SettingTypes = fields(cls.Settings)\n cls.InputTypes = get_type_hints(cls.Inputs)\n cls.OutputTypes = get_type_hints(cls.Outputs)\n\n # Inject code that runs before the overridable methods\n # This patching is necessary to keep the api the same\n\n for func in (\"run\", \"dispose\", \"validate_settings\"):\n # Do not change these constants, unless you change the private functions defined below\n original = func\n renamed = \"_\" + func\n private = \"_private_\" + func\n\n # fix inheriting from Function\n # only override if it hasn't been already overwritten\n if getattr(cls, original) == getattr(cls, private):\n continue\n\n # copy original cls.func to cls._func\n setattr(cls, renamed, getattr(cls, original))\n # override original cls.func with our cls._private_func\n setattr(cls, original, getattr(cls, private))\n\n super().__init_subclass__(*args, **kargs)\n\n # Any of these dataclasses can be ommited to use the default\n\n @dataclass\n class Settings:\n pass\n\n @dataclass\n class Inputs:\n pass\n\n @dataclass\n class Outputs:\n pass\n\n # These are the main implementation methods that would\n # be defined in a concrete Function\n\n def dispose(self):\n pass\n\n def run(self, inputs) -> Outputs:\n return self.Outputs()\n\n def on_start(self):\n pass\n\n @classmethod\n def validate_settings(cls, settings):\n return settings\n\n # Private, do not override\n\n def __init__(self, settings: Settings):\n self.settings = settings\n self.alive = True\n\n try:\n self.on_start()\n except:\n self.dispose()\n raise\n\n def _private_dispose(self):\n try:\n self._dispose()\n finally:\n self.alive = False\n\n def _private_run(self, inputs) -> Outputs:\n if not self.alive:\n raise ValueError(\"Attempted to call function when already disposed\")\n return self._run(inputs)\n\n @classmethod\n def _private_validate_settings(cls, settings):\n settings_new = cls._validate_settings(settings)\n\n # function must return settings\n if not isinstance(settings, cls.Settings):\n # raise error?\n settings_new = settings\n\n return settings_new\n\n\ndef isfunction(func):\n try:\n return issubclass(func, Function)\n except TypeError: # func is not a type\n return False\n\n\nclass Hook:\n def __init__(self, visible=True):\n # self.app can be any ASGI app, but it must exist\n self.visible = visible\n self.app = Router()\n self.url = \"\" # will be replaced during webserver init\n\n def cancel_dependents(self):\n try:\n self.pipeline.cancel_dependents(self.pipeline.current)\n except:\n raise ValueError(\"Pipeline not available! Cannot cancel dependents.\")\n\n\ndef ishook(hook):\n return isinstance(hook, Hook)\n\n\nclass ModulePath(NamedTuple):\n \"\"\"\n ModulePath is used to locate a module to register\n path = path to module, relative or absolute. Can be empty for current directory\n name = name of file without .py extention\n \"\"\"\n\n path: str\n name: str\n\n\nclass ModuleInfo(NamedTuple):\n \"\"\"\n ModuleInfo is used to store metadata about the module\n after it has been registered\n \"\"\"\n\n package: str\n version: str\n\n\nclass ModuleItem(NamedTuple):\n \"\"\"\n ModuleItem is a single value in the 'modules' dict of a Manager\n \"\"\"\n\n info: ModuleInfo\n funcs: Dict[str, Type[Function]]\n","sub_path":"opsi/manager/manager_schema.py","file_name":"manager_schema.py","file_ext":"py","file_size_in_byte":5301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"447808019","text":"###############CHATBOT CORPUS#######################\ngreetings = [['hi', 'Hi', 'Hello', 'hello', 'hello there', 'hi there'],\n ['Hello', 'Hi']]\n\nabout = [['how are you', 'how do you do'],\n ['I am fine, thank you.', \"I'm good. What about you?\"]]\n\nwho = [['who are you', 'tell me about yourself'],\n ['I am PythonBot - a python programming guide', 'I am python programming assitant', 'I can help you with Python Programming.']]\n\ncreate = [['who created you', 'who made you'],\n ['Jayant Kashyap']]\n\nunknown = [\"Sorry! This topic doesn't fall in my domain\", \"Sorry! I can't answer that.\"]\n#####################################################\n\n#####################################################\n\nwh_qstn_words = ['who','whom','when','where','how','why','how much','how many','which']\n# wh_qstn_tags = ['WP','WRB','JJ','NN','WDT']\nab_qstn_words = ['can','could','would','should','shall','will','do','does','did','is','had','have','has','are']\n# ab_qstn_tags = ['VB','VBZ','VBD','VBP','VBN','MD']\ndesc_qstn_words = ['what','tell','explain','give','describe','illustrate','define','inform','say']\n# verb_tags = ['VB','VBD','VBG','VBN','VBP','VBZ']\n\n######################################################\n\n######################################################\nreplacement_patterns = [\n # replacement for clitic\n (r'won\\'t', 'will not'),\n (r'can\\'t', 'can not'),\n (r'i\\'m', 'i am'),\n (r'ain\\'t', 'is not'),\n (r'(\\w+)\\'ll', '\\g<1> will'),\n (r'(\\w+)n\\'t', '\\g<1> not'),\n (r'(\\w+)\\'ve', '\\g<1> have'),\n (r'(\\w+)\\'s', '\\g<1> is'),\n (r'(\\w+)\\'re', '\\g<1> are'),\n (r'(\\w+)\\'d', '\\g<1> would'),\n\n # named entity replacement\n (r'[nN]ew [yY]ork', 'newyork'),\n\n # abbreviation\n (r'[dD]r\\.', 'Doctor'),\n\n # data structures\n (r'(\\w+)\\(\\)', '\\g<1>-method'),\n\n # Named Entities\n (r'[gG]uido [vV]an [rR]ossum', \"guido van rossum\"),\n (r'[pP]ython', \"python\"),\n (r'[Ll]ist', \"list\")\n]\n######################################################\n","sub_path":"corpus/pattern_C.py","file_name":"pattern_C.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"592558286","text":"import collections\nimport itertools\nimport random\n#import pygame\n#HEIGHT = 600\n#WIDTH = 800\n#game_window=pygame.display.set_mode((WIDTH,HEIGHT))\n\n#WHITE = (255,255,255)\n#BLACK = ( 0, 0, 0)\n#outline=0\nSUIT_LIST = (\"Hearts\", \"Spades\", \"Diamonds\", \"Clubs\")\nNUMERAL_LIST = (\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"Jack\", \"Queen\", \"King\", \"Ace\")\n\n#def redraw_game_window():\n #pygame.display.update()\n#creates and reutrns a card and suit\nclass card:\n def __init__(self, numeral, suit):\n self.numeral = numeral\n self.suit = suit\n self.card = self.numeral, self.suit\n def __repr__(self):\n return self.numeral + \"-\" + self.suit\n#determins if the hand has any value\nclass poker_hand():\n def __init__(self, card_list):\n self.card_list = card_list\n def __repr__(self):\n short_desc = \"Nothing.\"\n numeral_dict = collections.defaultdict(int)\n suit_dict = collections.defaultdict(int)\n for my_card in self.card_list:\n numeral_dict[my_card.numeral] += 1\n suit_dict[my_card.suit] += 1\n # Pair\n if len(numeral_dict) == 4:\n short_desc = \"One pair.\"\n # Two pair or 3-of-a-kind\n elif len(numeral_dict) == 3:\n if 3 in numeral_dict.values():\n short_desc =\"Three-of-a-kind.\"\n else:\n short_desc =\"Two pair.\"\n # Full house or 4-of-a-kind\n elif len(numeral_dict) == 2:\n if 2 in numeral_dict.values():\n short_desc =\"Full house.\"\n else:\n short_desc =\"Four-of-a-kind.\"\n else:\n # Flushes and straights\n straight, flush = False, False\n if len(suit_dict) == 1:\n flush = True\n min_numeral = min([NUMERAL_LIST.index(x) for x in numeral_dict.keys()])\n max_numeral = max([NUMERAL_LIST.index(x) for x in numeral_dict.keys()])\n if int(max_numeral) - int(min_numeral) == 4:\n straight = True\n # Ace can be low\n low_straight = set((\"Ace\", \"2\", \"3\", \"4\", \"5\"))\n if not set(numeral_dict.keys()).difference(low_straight):\n straight = True\n if straight and not flush:\n short_desc =\"Straight.\"\n elif flush and not straight:\n short_desc =\"Flush.\"\n elif flush and straight:\n short_desc =\"Straight flush.\"\n enumeration = \"/\".join([str(x) for x in self.card_list])\n return \"{enumeration} ({short_desc})\".format(**locals())\n#crates the first hand\nclass deck(): \n def __init__(self):\n self.cards=[]\n for numeral, suit in itertools.product(NUMERAL_LIST, SUIT_LIST):\n self.cards.append(card(numeral, suit))\n def get_card(self):\n a_card = random.sample(self, 1)[0]\n self.cards.pop(self.cards.index(a_card))\n return a_card\n def get_hand(self, number_of_cards=20):\n if number_of_cards == 20:\n return poker_hand([self.get_card() for x in range(number_of_cards)])\n else:\n raise NotImplementedError\n def get_hand2(self, number_of_cards=20):\n if number_of_cards == 20:\n return poker_hand([self.get_card() for x in range(number_of_cards)])\n else:\n raise NotImplementedError \n def __len__(self):\n return len(self.cards)\n def __getitem__(self,i):\n return self.cards[i]\nfor i in range(1):\n print(deck().get_hand())\n print(deck().get_hand2())\n \n","sub_path":"poker.py","file_name":"poker.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"167135359","text":"# 需要导入相应的包ftplib\nimport ftplib\nimport os\nimport time\n\n# 三部分精确表示在ftp服务器上的某一个文件\n# 好多公开的ftp服务访问会出错或者没有反应\nHOST = \"ftp.acc.umu.se\"\nDIR = 'Public/EFLIB/'\nFILE = 'README'\n\n# 1,客户端链接远程主机上的FTp服务器\ntry:\n f = ftplib.FTP()\n # 通过设置调试级别可以方便调试\n f.set_debuglevel(2)\n # 链接主机地址\n f.connect(HOST)\n\nexcept Exception as e:\n print(e)\n exit()\nprint(\"connected to host {0}\".format(HOST))\n\n# 2, 客户端输入同户名和密码(或者anonymous和电子邮件地址)\ntry:\n # 登录(login)如果要输入用户名信息,则默认视同匿名登录\n f.login()\n\nexcept Exception as e:\n print(2)\n exit()\nprint(\"Logged in as 'anonymous'\")\n\n# 3, 哭护短和服务器进行各种文件传输和信息查询操作\ntry:\n #更改当前目录到指定目录\n f.cwd(DIR)\n\nexcept Exception as e:\n print(e)\n exit()\nprint(\"changed dir to {0}\".format(DIR))\n\ntry:\n # 从服务器上下载文件\n # 第一个参数是ftp命令\n # 第二个参数是会掉函数\n # 此函数的意思是 执行REtR命令,下载文件到本地,运行回调函数\n f.retrbinary('RETT {0}'.format(FILE),open(FILE,\"wb\").write())\nexcept Exception as e:\n print(2)\n exit()\n\n# 4,客户端从远程服务器退出 结束传输\nf.quit()","sub_path":"02 高级语法系列/cp net编程/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"182433926","text":"\n\nfrom xai.brain.wordbase.nouns._jingle import _JINGLE\n\n#calss header\nclass _JINGLED(_JINGLE, ):\n\tdef __init__(self,): \n\t\t_JINGLE.__init__(self)\n\t\tself.name = \"JINGLED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"jingle\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_jingled.py","file_name":"_jingled.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"405350999","text":"#!/usr/bin/env python\nimport os\nfrom flask import Flask, session, redirect, url_for, escape, request, render_template \nfrom copy import copy\nfrom numpy import array\nfrom numpy.random import rand\nfrom sklearn.metrics import roc_curve\nfrom scipy import arctan\nfrom scipy.linalg import inv\n\nfrom sorting import order\n\nfrom backend import connect, authenticate, Dataset, Datasets, exists\nfrom scheduler import Scheduler\nfrom werkzeug import SharedDataMiddleware, secure_filename\nfrom flask.ext.compress import Compress\n\nfrom tempfile import mkstemp\n\n\napp = Flask(__name__)\nCompress(app)\napp.secret_key = 'saRFU2e7K3wvtyaoK.'\n\napp.wsgi_app = SharedDataMiddleware(app.wsgi_app,\n {'/': os.path.join(os.path.dirname(__file__), 'static')})\n\n@app.route('/login', methods=['POST'])\ndef login():\n assert 'username' in request.form and 'password' in request.form\n username = request.form['username']\n password = request.form['password']\n\n (value, message) = authenticate(username, password)\n if value == True:\n session['username'] = username\n return redirect('/')\n\n else:\n return render_template('error.html', message = message)\n\n@app.route('/logout', methods=['GET', 'POST'])\ndef logout():\n session.clear()\n return redirect('/')\n\n@app.route('/view', methods=['GET', 'POST'])\ndef view():\n if not 'username' in session:\n return render_template('error.html', message = 'Permission denied')\n\n user = session['username']\n name = request.args.get('dataset')\n ds = Dataset(name)\n data = copy(ds.data)\n data[data<0.5]=0.0;\n data[data>=0.5]=1.0;\n orders = order(data)\n return render_template('view.html', data = str(data.tolist()), orders = str(orders.tolist()))\n\n\n@app.route('/upload', methods=['POST'])\ndef upload():\n if not 'username' in session:\n return render_template('error.html', message = 'Permission denied')\n\n user = session['username']\n file = request.files['selector']\n if not file:\n return render_template('error.html', message = 'Upload unsuccessfull')\n\n name = secure_filename(file.filename).rsplit('.', 1)[0].rsplit('_', 1)[0]\n if exists(name):\n return render_template('error.html', message = 'Dataset with that name already exists')\n \n (f, temp) = mkstemp('', '', 'upload/', 'w')\n os.close(f)\n file.save(temp)\n Dataset(name, temp)\n return redirect('/')\n\n@app.route('/')\ndef index():\n if 'username' in session:\n username = session['username']\n return render_template('console.html', username = username, datasets = Datasets())\n \n else:\n return render_template('index.html')\n\nthreads = []\n\n# app.methods\n\n@app.before_first_request\ndef initialize():\n global threads\n (_, logger) = connect()\n threads.append(Scheduler().start())\n\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n (_, logger) = connect()\n logger.info('Flask server: start')\n app.config['COMPRESS_MIN_SIZE'] = 0\n app.config['COMPRESS_DEBUG'] = True\n app.config['MAX_CONTENT_LENGTH'] = 4*1024*1024\n app.run(host='0.0.0.0', port=port, debug=True)\n for thread in threads:\n thread.join()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"543651681","text":"# Inverse model of stable Sr data\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef LoadLear03():\n Data = np.genfromtxt('Lear2003_SrOverCa_RAW.txt', dtype=float, delimiter='\\t')\n Data = Data[1:,:]\n \n DataD = np.copy(Data)\n DataD[:,2:9] *= 0\n idx = np.where(Data == 522)\n DataD[idx,2:9] = Data[idx,2:9] + (3.000 - 1.000) * 0.101\n idx = np.where(Data == 523)\n DataD[idx,2:9] = Data[idx,2:9] + (3.100 - 1.000) * 0.101\n idx = np.where(Data == 525)\n DataD[idx,2:9] = Data[idx,2:9] + (1.500 - 1.000) * 0.101\n idx = np.where(Data == 573)\n DataD[idx,2:9] = Data[idx,2:9] + (3.650 - 1.000) * 0.101\n idx = np.where(Data == 608)\n DataD[idx,2:9] = Data[idx,2:9] + (3.470 - 1.000) * 0.101\n idx = np.where(Data == 689)\n DataD[idx,2:9] = Data[idx,2:9] + (1.365 - 1.000) * 0.101\n idx = np.where(Data == 690)\n DataD[idx,2:9] = Data[idx,2:9] + (2.055 - 1.000) * 0.101\n idx = np.where(Data == 926)\n DataD[idx,2:9] = Data[idx,2:9] + (3.525 - 1.000) * 0.101\n idx = np.where(Data == 1052)\n DataD[idx,2:9] = Data[idx,2:9] + (0.750 - 1.000) * 0.101\n\n DataDS = np.copy(DataD)\n DataDS[:,2] += 0.29 \n DataDS[:,3] += 0.11\n DataDS[:,4] += 0.42 \n DataDS[:,5] += 0.28 \n DataDS[:,6] += 0.15 \n DataDS[:,8] += 0.08\n DataDS[:,9] += 0.16\n \n DataDSCa = np.copy(DataDS)\n DataDSCa[:,2] *= (1.0 + 0.7* DataDSCa[:,1]/50.0)\n DataDSCa[:,3] *= (1.0 + 0.7* DataDSCa[:,1]/50.0)\n DataDSCa[:,4] *= (1.0 + 0.7* DataDSCa[:,1]/50.0)\n DataDSCa[:,5] *= (1.0 + 0.7* DataDSCa[:,1]/50.0)\n DataDSCa[:,6] *= (1.0 + 0.7* DataDSCa[:,1]/50.0)\n DataDSCa[:,7] *= (1.0 + 0.7* DataDSCa[:,1]/50.0)\n DataDSCa[:,8] *= (1.0 + 0.7* DataDSCa[:,1]/50.0)\n DataDSCa[:,9] *= (1.0 + 0.7* DataDSCa[:,1]/50.0)\n if (False):\n plt.figure(99)\n plt.subplot(311)\n plt.plot(Data[:,1],Data[:,2:9],'.')\n plt.xlim((0,40))\n plt.grid()\n plt.subplot(312)\n plt.plot(DataD[:,1],DataD[:,2:9],'.')\n plt.xlim((0,40))\n plt.grid()\n plt.subplot(313)\n plt.plot(DataDS[:,1],DataDS[:,2:9],'.')\n plt.xlim((0,40))\n plt.grid()\n plt.show()\n \n return DataDSCa\n\ndef LoadData(skiptoprows):\n Data = np.genfromtxt('RawData.txt', dtype=float, delimiter='\\t')\n Data = Data[skiptoprows:,:]\n Data[:,3] = Data[:,1]+0.53\n return Data\n\ndef DataDerivative(Data):\n dX = np.zeros((Data.shape(0),2))\n for row in range(len(X)-1):\n dX[row,0] = (X[row+1,0]+X[row,0])/2\n dX[row,1] = X[row+1,3]-X[row,3]\n return dX\n\ndef FitPoly(Data, col,n):\n p = np.poly1d(np.polyfit(Data[:,0],Data[:,col], n))\n pd = np.polyder(p) \n xp = np.linspace(0, 35, 100)\n error = p(Data[:,0])-Data[:,col]\n return (p,pd,xp,error)\n\ndef PlotPolyFit(Data,p,pd,xp):\n plt.subplot(311)\n plt.plot(Data[:,0],Data[:,3],xp, p(xp), '--')\n\n plt.subplot(312)\n plt.plot(dX[:,0],dX[:,1],xp, pd(xp), '--')\n\n plt.subplot(313)\n plt.hist(error)\n plt.show()\n\ndef IntegrateConstFin(pd,Fin,Sr0,dsw0,din,eps):\n\n dt = 1000 # timestep\n \n dout0 = dsw0+eps\n Fout0 = (pd(0)/1e6*Sr0 + (din-dsw0)*Fin)/eps\n state0 = np.array([0,Sr0,Fout0,Fin,dsw0,dout0,din])\n Model = np.zeros((351,7))\n Model = state0\n Fout = np.zeros(35001)\n Fout[0] = Fout0\n \n\n for kyr in range(1,35001):\n state1 = state0*0\n Myr = kyr/1000.0\n state1[0] = Myr\n state1[1] = state0[1] + state0[2]*dt - state0[3]*dt\n state1[4] = (state0[1]*state0[4] + state0[2]*dt*state0[5] - state0[3]*dt*state0[6])/state1[1] \n state1[2] = (pd(Myr)/1e6*state1[1] + (din-state1[4])*Fin)/eps\n state1[3] = Fin\n state1[5] = state1[4]+eps\n state1[6] = din\n if (Myr>15):\n state1[2] = (pd(Myr)/1e6*state1[1] + (din-0.02-state1[4])*Fin)/eps\n state1[6] = din-0.02\n \n \n if (kyr%100 == 0):\n Model = np.vstack([Model,state1])\n \n Fout[kyr] = state1[2]\n state0 = state1\n \n del state0,state1\n \n \n \n FoutDT = Fout - np.mean(Fout) + Fin + 1.17e9\n state0 = np.array([35,4/3*Sr0,FoutDT[-1],Fin,0.3924,0.3924+eps,din])\n ModelDT = state0\n\n for kyr in range(1,35001):\n state1 = state0*0\n Myr = 35 - kyr/1000.0\n\n state1[0] = Myr\n state1[1] = state0[1] - state0[2]*dt + state0[3]*dt\n state1[4] = (state0[1]*state0[4] - state0[2]*dt*state0[5] + state0[3]*dt*state0[6])/state1[1] \n state1[2] = FoutDT[-kyr]\n \n state1[3] = Fin\n state1[5] = state1[4]+eps\n state1[6] = din\n if (Myr>15):\n state1[6] = din-0.02\n \n if (kyr%100 == 0):\n #print(kyr, Myr)\n ModelDT = np.vstack([ModelDT,state1])\n \n state0 = state1\n \n ModelDT\n \n del state0,state1\n\n #print(ModelDT[0:3,:])\n #print(ModelDT[-3:-0,:])\n \n return Model, ModelDT\n\n \n\n########### MODEL #####################\n\nData = LoadData(0)\n(p,pd,xp,error) = FitPoly(Data, 3, 7)\n\ndmean = np.mean(Data[:,3])\ndmean = np.mean(p(xp))\nprint(dmean)\n\nFin = 38e9\nSr0 = 88e-6 * 1.4e21 #Fin*2.5e6\ndsw0 = p(0)\nprint(\"d initial\",dsw0)\nprint(p(35))\neps = -0.22 #-0.167\ndin = dmean + eps #0.183\n\n\nif (True):\n \n Nruns = 30\n Model = np.zeros((351,7,Nruns+1))\n ModelDT = np.zeros((351,7,Nruns+1))\n ddiff = np.zeros(Nruns+1)\n trend = np.zeros(Nruns+1)\n (Model[:,:,0],ModelDT[:,:,0]) = IntegrateConstFin(pd,Fin,Sr0,dsw0,din,eps)\n ddiff[0] = din - (dmean + eps)\n\n for run in range(1,Nruns+1):\n dinE = din + 0.01*np.random.randn()\n epsE = eps + 0.005*np.random.randn()\n ddiff[run] = dinE - (dmean + epsE)\n (Model[:,:,run],ModelDT[:,:,run]) = IntegrateConstFin(pd,Fin,Sr0,dsw0,dinE,epsE)\n \n #Model = np.stack((Model,NewModel),axis=2)\n print(\"Done with run {0}\".format(run))\n \n \n\n \n plt.figure(1,figsize=(10,8))\n \n plt.subplot(321)\n #for run in range(1,Nruns+1):\n # if (ddiff[run]>0):\n # plt.plot(Model[:,0,run],Model[:,4,run],'-r')\n # else:\n # plt.plot(Model[:,0,run],Model[:,4,run],'-b')\n plt.plot(Model[:,0,0],Model[:,4,0],'-k',linewidth=3.0)\n plt.plot(Data[:,0],Data[:,3],'+k')\n plt.ylim((0.295,0.405)) \n plt.ylabel(\"seawater d88/86Sr [permil]\")\n plt.xlim((-2,37))\n plt.grid()\n \n \n plt.subplot(322)\n for run in range(1,Nruns+1):\n if (ddiff[run]>0):\n plt.plot(ModelDT[:,0,run],ModelDT[:,4,run],'-r')\n else:\n plt.plot(ModelDT[:,0,run],ModelDT[:,4,run],'-b')\n plt.plot(ModelDT[:,0,0],ModelDT[:,4,0],'-k',linewidth=3.0)\n plt.plot(Data[:,0],Data[:,3],'+k')\n plt.ylim((0.295,0.405))\n plt.xlim((-2,37))\n plt.grid()\n \n \n plt.subplot(323)\n for run in range(1,Nruns+1):\n if (ddiff[run]>0):\n plt.plot(Model[:,0,run],-1e6*1e-15*(Model[:,2,run]-Model[:,3,run]),'-r')\n else:\n plt.plot(Model[:,0,run],-1e6*1e-15*(Model[:,2,run]-Model[:,3,run]),'-b')\n p = np.polyfit(Model[:,0,0],Model[:,1,0], 1)\n plt.plot(Model[:,0,0],-1e6*1e-15*(Model[:,2,0]-Model[:,3,0]) ,'-k',linewidth=3.0)\n plt.ylim((-1.2e1,1.2e1))\n plt.xlim((-2,37))\n plt.ylabel(\"Sr in-out imbalance [Pmol/Myr]\")\n plt.grid()\n \n \n plt.subplot(324)\n for run in range(1,Nruns+1):\n if (ddiff[run]>0):\n plt.plot(ModelDT[:,0,run],-1000*1e-12*(ModelDT[:,2,run]-ModelDT[:,3,run]),'-r')\n else:\n plt.plot(ModelDT[:,0,run],-1000*1e-12*(ModelDT[:,2,run]-ModelDT[:,3,run]),'-b')\n p = np.polyfit(ModelDT[:,0,0],ModelDT[:,1,0], 1)\n plt.plot(ModelDT[:,0,0],-1000*1e-12*(ModelDT[:,2,0]-ModelDT[:,3,0]) ,'-k',linewidth=3.0)\n plt.ylim((-1.2e1,1.2e1))\n plt.xlim((-2,37))\n plt.grid()\n \n L03 = LoadLear03()\n \n plt.subplot(325)\n for run in range(1,Nruns+1):\n if (ddiff[run]>0):\n plt.plot(Model[:,0,run],Model[:,1,run]/1.4e21*1e6,'-r')\n else:\n plt.plot(Model[:,0,run],Model[:,1,run]/1.4e21*1e6,'-b')\n plt.plot(Model[:,0,0],Model[:,1,0]/1.4e21*1e6 ,'-k',linewidth=3.0)\n plt.ylim((-0.1e2,2e2))\n plt.xlim((-2,37))\n plt.xlabel(\"Age [MyrBP]\")\n plt.ylabel(\"seawater Sr concentration [µmol/kg]\")\n plt.grid()\n \n plt.twinx()\n plt.plot(L03[:,1],L03[:,2:9],'+k')\n plt.ylim((-3.5/20,3.5))\n plt.xlim((-2,37))\n \n plt.subplot(326)\n for run in range(1,Nruns+1):\n if (ddiff[run]>0):\n plt.plot(ModelDT[:,0,run],ModelDT[:,1,run]/1.4e21*1e6,'-r')\n else:\n plt.plot(ModelDT[:,0,run],ModelDT[:,1,run]/1.4e21*1e6,'-b')\n plt.plot(ModelDT[:,0,0],ModelDT[:,1,0]/1.4e21*1e6 ,'-k',linewidth=3.0)\n plt.ylim((-0.1e2,2e2))\n plt.xlim((-2,37))\n plt.xlabel(\"Age [MyrBP]\")\n plt.grid()\n \n plt.twinx()\n plt.plot(L03[:,1],L03[:,2:9],'+k')\n plt.ylim((-3.5/20,3.5))\n plt.xlim((-2,37))\n \n #plt.show()\n \n\n plt.savefig('VectorOUT.ps', format='ps')\n \n plt.show()\n \n if (False):\n plt.figure(3)\n plt.subplot(411)\n plt.plot(ddiff,trend ,'+')\n plt.grid()\n \n plt.subplot(412)\n plt.plot(Data[:,0],Data[:,3],'+k')\n for run in range(1,Nruns+1):\n if (ddiff[run]>0):\n plt.plot(Model[:,0,run],Model[:,4,run],'-r')\n else:\n plt.plot(Model[:,0,run],Model[:,4,run],'-b')\n plt.grid()\n \n plt.subplot(413)\n plt.plot(Data[:,0],Data[:,3],'+k')\n for run in range(1,Nruns+1):\n if (ddiff[run]>0):\n plt.plot(ModelDT[:,0,run],ModelDT[:,4,run],'-r')\n else:\n plt.plot(ModelDT[:,0,run],ModelDT[:,4,run],'-b')\n plt.grid()\n \n plt.subplot(414)\n for run in range(1,Nruns+1):\n if (ddiff[run]>0):\n plt.plot(Model[:,0,run],Model[:,2,run],'-r')\n else:\n plt.plot(Model[:,0,run],Model[:,2,run],'-b')\n plt.grid()\n plt.show()\n\nif (False):\n Model = IntegrateConstFin(pd,Fin,Sr0,dsw0,din,eps)\n \n plt.figure(2)\n plt.subplot(311)\n plt.plot(Data[:,0],Data[:,3],xp, p(xp), '--',Model[:,0],Model[:,4],'-')\n plt.grid()\n plt.ylabel(\"d88/86Sr\")\n plt.subplot(312)\n plt.plot(Model[:,0],Model[:,1],'-')\n plt.ylabel(\"[Sr]\")\n plt.grid()\n plt.subplot(313)\n plt.plot(Model[:,0],Fin-Model[:,2],'-')\n plt.ylabel(\"In-OUT [mol/yr]\")\n plt.xlabel(\"MyrBP\")\n plt.grid()\n\n plt.savefig(\"SrInverse_V0.png\")\n plt.show()\n print(Model) \n\n\n\n","sub_path":"InverseModel_V1alt.py","file_name":"InverseModel_V1alt.py","file_ext":"py","file_size_in_byte":10559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"350734426","text":"from datetime import datetime\n\nfrom flask import Response, g, request\n\nfrom app.views.v1 import BaseResource\n\n\nclass PostAPIResource(BaseResource):\n def upload_post(self, model):\n title = request.form['title']\n content = request.form['content']\n\n admin = g.user\n\n post = model(\n author=admin.name,\n title=title,\n content=content,\n write_time=datetime.now()\n ).save()\n\n return {\n 'id': str(post.id)\n }, 201\n\n def modify_post(self, model):\n id = request.form['id']\n title = request.form['title']\n content = request.form['content']\n\n if len(id) != 24:\n return Response('', 204)\n\n post = model.objects(id=id).first()\n if not post:\n return Response('', 204)\n\n post.update(title=title, content=content)\n\n return Response('', 200)\n\n def delete_post(self, model):\n id = request.form['id']\n\n if len(id) != 24:\n return Response('', 204)\n\n post = model.objects(id=id).first()\n if not post:\n return Response('', 204)\n\n post.delete()\n\n return Response('', 200)\n","sub_path":"Server/app/views/v1/admin/post/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"555591481","text":"from random import randint\nfrom tkinter import *\nimport time\n\nwin = Tk()\nwin.title(\"MC-RPG\")\n\nslots = {\"a1\": \"None\", \"a2\": \"None\", \"a3\": \"None\", \"a4\": \"None\", \"a5\": \"None\", \"a6\": \"None\", \"a7\": \"None\", \"a8\": \"None\", \"a9\": \"None\", \"b1\": \"None\", \"b2\": \"None\", \"b3\": \"None\", \"b4\": \"None\", \"b5\": \"None\", \"b6\": \"None\", \"b7\": \"None\", \"b8\": \"None\", \"b9\": \"None\", \"c1\": \"None\", \"c2\": \"None\", \"c3\": \"None\", \"c4\": \"None\", \"c5\": \"None\", \"c6\": \"None\", \"c7\": \"None\", \"c8\": \"None\", \"c9\": \"None\", \"d1\": \"None\", \"d2\": \"None\", \"d3\": \"None\", \"d4\": \"None\", \"d5\": \"None\", \"d6\": \"None\", \"d7\": \"None\", \"d8\": \"None\", \"d9\": \"None\"};\nslotNums = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}\nrowv = 0\ncolumnv = 0\nbreakWhat = \"strip\"\n\n\ndef checkInv(checkFor, num):\n for s in slots:\n if s == checkFor and slots[s] >= num:\n return True\n break\n else:\n return False\n break\ndef addItem(itemName, num):\n global slots\n global slotNums\n for s, n in zip(slots, slotNums):\n if slots[s] == \"None\":\n slots[s] == itemName\n n = num\n break\n else:\n None\ndef setStrip():\n breakWhat = \"strip\"\n breakWhatBut = Button(win, text = \"Stip Mine\", command = Break)\n breakWhatBut.grid(row = 3, column = 0)\ndef Break():\n if breakWhat == \"strip\":\n addItem(\"dirt\", 1)\n print(\"YES\")\n else:\n None\n\n\nblankInv = PhotoImage(file=\"invSlot.PNG\")\nfor s in sorted(slots):\n s = Button(win, image = blankInv, command = None)\n s.grid(row = rowv, column = columnv)\n columnv += 1\n if columnv > 8:\n rowv += 1\n columnv = 0\n\nmenubar = Menu(win)\n\nmineMenu = Menu(menubar, tearoff=0)\nmineMenu.add_command(label=\"Strip Mine\", command=setStrip)\n\n##mineMenu.add_command(label=\"Cave\", command=setCave)\n##mineMenu.add_separator()\n##mineMenu.add_command(label=\"Mine Dirt\", command=setDirt)\n\nmenubar.add_cascade(label=\"Break...\", menu=mineMenu)\n\nwin.config(menu=menubar)\n\nbreakWhatBut = Button(win, text = \"Stip Mine\", command = Break)\nbreakWhatBut.grid(row = 4, column = 0)\n\nmainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"42321932","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def reverseList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n # Iterative Method:\n # use a loop, traverse the whole list, reverse the link at each step. That is,\n # adjust the link of the node, to make it point to the previous node instead of the next node\n \n # head: a global variable of type \"pointer to node\" (accessible to all functions). \n # It stores the address of head node \n # reverse a linked list: not moving the data, but reversing the links\n \n # Test corner cases\n if not head: return None\n if not head.next: return head\n \n prev = None\n current = head\n \n while current:\n #cur_next: local pointer variable\n cur_next = current.next\n current.next = prev\n # reset previous and current pointers\n prev = current\n current = cur_next\n head = prev \n return head\n \n \n \n \n \n \n","sub_path":"python/206_Reverse_Linked_List.py","file_name":"206_Reverse_Linked_List.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"534627653","text":"import pandas as pd, requests, re, io\n\n# Import hidden passwords\nimport config\n\n# File URLs on Kaggle\ntrain_url= \"https://www.kaggle.com/c/titanic/download/train.csv\"\ntest_url= \"https://www.kaggle.com/c/titanic/download/test.csv\"\n\n# Local filenames\ntrain = \"train.csv\"\ntest = \"test.csv\"\n\n# Hidden UN/PW info\npayload = {\n '__RequestVerificationToken': '',\n 'username': config.secret[\"UserName\"],\n 'password': config.secret[\"Password\"],\n 'rememberme': 'false'\n}\n\n# Pull anti-forgery token - instructions from StackExchange\n\nlogin_url = 'https://www.kaggle.com/account/login'\n\nwith requests.Session() as r:\n response = r.get(login_url).text\n \n # Retrieve anti-forgery token via regex from login page\n token = re.search('antiForgeryToken: \\'(?P.+)\\'', str(response)).group(1)\n \n # Set token\n payload['__RequestVerificationToken'] = token\n \n # Post the revised URL\n post_page = r.post(login_url + \"?isModal=true&returnUrl=/\", data = payload, stream = True)\n \n # Check for error logging in\n error_match = re.search('\"errors\":\\[\"(?P.+)\"\\]', str(post_page))\n if error_match:\n raise Exception('There was an error logging in: ' + error_match.group(1))\n else: post_page\n\nurls = [train_url, test_url]\nloc_files = [train, test]\n\ni = 0\n\n# Loop through URLs and local filenames to get and save train/test CSVs\nwhile i < len(urls):\n response = r.get(urls[i])\n \n # This will raise an error if the data isn't accessible\n print(response.raise_for_status())\n \n df = pd.read_csv(io.StringIO(response.content.decode('utf-8')))\n df.to_csv(loc_files[i], chunksize=512 * 1024)\n \n i += 1\n\n# Sources:\n\n# https://ramhiser.com/2012/11/23/how-to-download-kaggle-data-with-python-and-requests-dot-py/\n\n# https://stackoverflow.com/a/50876207\n\n# https://stackoverflow.com/a/18648874","sub_path":"pull_data.py","file_name":"pull_data.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"271420126","text":"import socket\r\nimport sys\r\nimport datetime\r\nimport time\r\nimport threading\r\nimport struct \r\n\r\n\r\n###Trying to import functions from different sensors and apparatuses\r\n\r\n# Importing the Temperature, Humidity adn Pressure Sensors\r\ntry:\r\n import Imports.DualBME280s as DualBME280s\r\nexcept:\r\n print(\"DualBME280s cannot be imported\")\r\n\r\n\r\n\r\n# Importing the Frequency Counter\r\ntry:\r\n from Imports.UFC6000 import FrequencyCounter\r\nexcept:\r\n print(\"UFC6000 could not be imported\") \r\n\r\n# Importing the Koheron Controllers \r\ntry:\r\n from Imports.koheron_control import *\r\nexcept:\r\n print(\"Koheron could not be imported\")\r\n\r\n# Importing the Arduino's\r\ntry:\r\n from Imports.laser_locking.arduino_peak_lock_v2.arduino_cmd_peak_v2 import *\r\nexcept:\r\n print(\"Could not import Arduino Peak Lock CMD\")\r\n\r\n\r\n\r\n### Block for Initializing sensors and apparatuses\r\ntime.sleep(0.5)\r\n\r\n# Trying to initialize the Frequency Counter\r\ntry:\r\n frequency_counter = FrequencyCounter(address=\"/dev/FREQCOUNT\")\r\n frequency_counter.set_sample_time(1)\r\nexcept:\r\n print(\"Could not initialize the Frequency counter\")\r\n\r\n# Trying to initialize the Koherons\r\ntry:\r\n kc1 = KoheronController(\"/dev/Koheron1\")\r\nexcept:\r\n print(\"Could not initialize Koheron 1\")\r\ntry:\r\n kc2 = KoheronController(\"/dev/Koheron2\")\r\nexcept:\r\n print(\"Could not initialize Koheron 2\")\r\n\r\n\r\n# Trying to initialize the Arduinos:\r\ntry:\r\n ard1 = ArduinoLocker(\"/dev/Arduino1\")\r\nexcept:\r\n print(\"Could not initialize Arduino 1\")\r\ntry:\r\n ard2 = ArduinoLocker(\"/dev/Arduino2\")\r\nexcept:\r\n print(\"Could not initialize Arduino 2\")\r\n\r\n\r\n# Opening the DataLog\r\ntry:\r\n DataLog = open(\"DataLog.txt\",\"a+\")\r\n DataLog.close()\r\nexcept:\r\n DataLog = open(\"DataLog.txt\",\"a+\")\r\n DataLog.close()\r\n\r\ntry:\r\n log = open(\"logs.txt\",\"a+\")\r\n log.write(\"---------------------------------------------------------------------------------------------------------------\\n\")\r\nexcept: \r\n log = open(\"logs.txt\",\"a+\")\r\n log.write(\"---------------------------------------------------------------------------------------------------------------\\n\")\r\n \r\n### Error Function\r\ndef error(message):\r\n try:\r\n log.write(\"Time: \" + str(datetime.datetime.now()) + \" ERROR: \" + message + \"\\n\")\r\n suffix = \"\"\r\n except:\r\n suffix = \"Can not write to log\"\r\n return \"ERROR: \" + message + \" \" + suffix + \"\\n\"\r\n\r\n\r\n### Function to get the Frequency Counter Readings\r\ndef freqCounter():\r\n try:\r\n rval = frequency_counter.get_frequency_and_range()\r\n if (rval[0]).casefold() == (\"Signal\").casefold() or (rval[1]).casefold() == (\"Signal\").casefold():\r\n rval = [0,0]\r\n except:\r\n rval = [0,0]\r\n \r\n return rval\r\n\r\n\r\n \r\n### Function for associating a query to a given function and creating + sending the message\r\ndef associate(Data,conn):\r\n message = \"\"\r\n if (Data[0:4]).casefold() == (\"Ping\").casefold():\r\n message = \"Pong\"\r\n \r\n elif (Data[0:5]).casefold() == (\"Temp?\").casefold():\r\n try:\r\n temp = DualBME280s.temp()\r\n if temp[0] == 999: # Default output if a problem occurs \r\n message = error(\"BME280A could not give the temperature\")\r\n if temp[1] == 999: # Default output if a problem occurs \r\n message += error(\"BME280B could not give the temperature\")\r\n message += \"Temperature: \" + str(temp[0]) + \", \" + str(temp[1])\r\n except:\r\n message = error(\"Could not connect to the BME280s\")\r\n\r\n\r\n #TO-DO Need to add in the altitude reading from the Gondola\r\n elif (Data[0:4]).casefold() == (\"Alt?\").casefold():\r\n message = \"Altitude is of Z\"\r\n\r\n elif (Data[0:6]).casefold() == (\"Humid?\").casefold():\r\n try:\r\n humid = DualBME280s.humidity()\r\n if humid[0] == -1: #Default output if a problem occurs\r\n message = error(\"BME280A could not give the humidity\")\r\n if humid[1] == -1: # Default output if a problem occurs \r\n message += error(\"BME280B could not give the humidity\")\r\n message += \"Humidity: \" + str(humid[0]) + \", \" + str(humid[1])\r\n except:\r\n message = error(\"Could not connect to the BME280s\")\r\n \r\n elif (Data[0:9]).casefold() == (\"Pressure?\").casefold():\r\n try:\r\n pressure = DualBME280s.pressure()\r\n if pressure[0] == -1:\r\n message = error(\"BME280A could not give the pressure\")\r\n if pressure[1] == -1:\r\n message += error(\"BME280B could not give the pressure\")\r\n message += \"Pressure: \" + str(pressure[0]) + \", \" + str(pressure[1])\r\n except:\r\n message = error(\"Could not connect to the BME280s\")\r\n\r\n #TO-DO: Optional, may or may not add this coordinate feature depending on the data received and if it is feasible NOT A PRIORITY AND CAN BE DEPRICATED\r\n elif (Data[0:4]).casefold() == (\"Loc?\").casefold():\r\n message = \"X: XPLACEHOLDER\" + \" \" + \"Y: YPLACEHOLDER\" + \" \" + \"Z: ZPLACEGOLDER\"\r\n \r\n elif (Data[0:10]).casefold() == (\"Frequency?\").casefold():\r\n freq = freqCounter() \r\n if freq == [0,0]:\r\n message = error(\"Frequency Counter could not give Frequency and Range, defaulted at 0\") # Not throwing an error, since the FreqCounter is already doing so, only adding a message for the user to read\r\n message += \"Frequency is of: \" + str(freq[1]) + \" MHz\"\r\n \r\n elif (Data[0:3]).casefold() == (\"ard\").casefold():\r\n #Choosing the arduino\r\n try:\r\n if (Data[3]).casefold() == (\"1\").casefold():\r\n ard = ard1\r\n num = \" 1\"\r\n else:\r\n ard = ard2\r\n num = \" 2\"\r\n except:\r\n message += error(\"Not connected to Arduinos\")\r\n num = \" -1\"\r\n\r\n # Associating function calls\r\n if((Data[4:]).casefold() == (\"save_params()\").casefold()):\r\n try:\r\n ard.save_params()\r\n message = \"Arduino\" + num +\"'s params have been saved\"\r\n except:\r\n message = error(\"Arduino\" + num +\"'s params have not been saved\")\r\n\r\n elif((Data[4:]).casefold() == (\"load_params()\").casefold()):\r\n try:\r\n ard.load_params()\r\n message = \"Arduino\" + num + \"'s params have been loaded\"\r\n except:\r\n message = error(\"Arduino\" + num+ \"'s params have not been loaded\")\r\n\r\n elif (Data[4:23]).casefold() == (\".load_from_eeprom()\").casefold():\r\n try:\r\n ard.load_from_eeprom()\r\n message += \"Arduino\" + num + \" Loaded from EEPROM\"\r\n except:\r\n message = error(\"Could not load from EEPROM for Arduino\" + num)\r\n\r\n \r\n elif (Data[4:]).casefold() == (\".save_to_eeprom()\").casefold():\r\n try:\r\n ard.save_to_eeprom()\r\n message = \"Arduino\" + num + \"'s settings Saved to EEPROM\"\r\n except:\r\n message = error(\"Could not Save Arduino\" + num + \"'s settings to EEPROM\")\r\n\r\n elif (Data[4:]).casefold() == (\".get_params()\").casefold():\r\n try:\r\n params = ard.get_params()\r\n message = \"Params of Arduino \" + num + \" are:\\n\" + str(params)\r\n except:\r\n message = error(\"Could not get Params of Arduino\" + num)\r\n\r\n elif((Data[4:19]).casefold() == (\".unpack_params(\").casefold()):\r\n try:\r\n strParams = Data[19:len(Data)-1]\r\n paramsList = (strParams[1:len(strParams)-1]).split(\",\")\r\n flParamsList = [0]*9\r\n for i in range(0,len(paramsList),1):\r\n if i == 0:\r\n flParamsList[i] = int(paramsList[i])\r\n else:\r\n flParamsList[i] = float(paramsList[i])\r\n\r\n try:\r\n ard.unpack_params(flParamsList)\r\n message = \"Arduino\" + num + \"'s params have been unpacked\"\r\n except:\r\n message = error(\"Params list could not be unpacked for Arduino\" + num)\r\n except:\r\n message = error(\"Could not get Params list\")\r\n\r\n elif((Data[4:18]).casefold() == (\".pack_params()\").casefold()):\r\n try:\r\n params = ard.pack_params()\r\n message = \"Arduino\" + num + \"'s params are: \\n\" + params\r\n except:\r\n message = error(\"Could not pack params of Arduino\" + num)\r\n\r\n elif (Data[4:]).casefold() == (\".set_params()\").casefold():\r\n try:\r\n rval = ard.set_params()\r\n message = rval\r\n except:\r\n message = error(\"Could not set the Params of Arduino\" + num)\r\n\r\n elif (Data[4:20]).casefold() == (\".set_scan_state(\").casefold():\r\n try:\r\n state = Data[20:len(Data)-1]\r\n ard.set_scan_state(state)\r\n message = \"Scan State of Arduino\" + num + \" has been set to \" + str(state)\r\n except:\r\n message = error(\"Could not set Scan State of Arduino\" + num)\r\n\r\n elif (Data[4:]).casefold() == (\".get_sampling_rate()\").casefold():\r\n try:\r\n samplingRate = ard.get_sampling_rate()\r\n message = \"Arduino\" + num +\"'s sampling rate is of \" + str(samplingRate)\r\n except:\r\n message = error(\"Could not get Arduino\" + num + \"'s sampling rate\")\r\n\r\n\r\n elif (Data[4:]).casefold() == (\".close()\").casefold():\r\n try:\r\n ard.close()\r\n message = \"Arduino\" + num + \" has been closed\"\r\n except:\r\n message = error(\"Arduino\" + num + \" was not closed\")\r\n\r\n elif (Data[4:]).casefold() == (\".print_params()\").casefold():\r\n try:\r\n ard.print_params()\r\n message = \"To get Arduino\"+ num + \"'s Params, use get_string_params()\"\r\n except:\r\n message = error(\"Arduino\" + num + \"'s params could not be accessed\")\r\n\r\n elif (Data[4:]).casefold() == (\".get_string_params()\").casefold():\r\n try:\r\n params = ard.get_string_params()\r\n message = \"Arduino\"+ num + \"'s Params are:\\n\" + params\r\n except:\r\n message = error(\"Arduino\" + num+ \"'s params could not be accessed\")\r\n\r\n\r\n elif (Data[4:14]).casefold() == (\".scan_amp(\").casefold():\r\n try:\r\n amp = Data[14:len(Data)-1]\r\n flAmp = float(amp)\r\n ard.scan_amp(flAmp)\r\n message = \"Arduino\" + num + \"'s Scan Amp has been set\"\r\n except ValueError as e:\r\n message = error(\"No float Value detected in function call: \" + str(e))\r\n except:\r\n message = error(\"Could not set the Scan Amplitude of Arduino\" + num)\r\n\r\n elif (Data[4:15]).casefold() == (\".scan_freq(\").casefold():\r\n try:\r\n freq = Data[15:len(Data)-1]\r\n flFreq = float(freq)\r\n ard.scan_freq(flFreq)\r\n message = \"Arduino\" + num + \"'s Scan Frequency has been set\"\r\n except ValueError as e:\r\n message = error(\"No float Value detected in function call: \" + str(e))\r\n except:\r\n message = error(\"Could not set the Scan Frequency of Arduino\" + num)\r\n\r\n\r\n elif (Data[4:]).casefold() == (\".lock()\").casefold():\r\n try:\r\n ard.lock()\r\n message = \"Arduino\" + num + \" has been Locked\"\r\n except:\r\n message = error(\"Arduino\" + num + \" could not be locked\")\r\n\r\n elif (Data[4:]).casefold() == (\".unlock()\").casefold():\r\n try:\r\n ard.unlock()\r\n message = \"Arduino\" + num + \" has been Unlocked\"\r\n except:\r\n message = error(\"Arduino\" + num + \" could not be unlocked\")\r\n\r\n elif (Data[4:12]).casefold() == (\".gain_p(\").casefold():\r\n try:\r\n pgain = Data[12:len(Data)-1]\r\n flPgain = float(pgain)\r\n ard.gain_p(flPgain)\r\n message = \"Proportional gain of Arduino\" + num + \" has been updated to: \" + pgain\r\n except ValueError as e:\r\n message = error(\"No Float value detected in function call: \" + str(e))\r\n except:\r\n message = error(\"Could not set pgain of Arduino\" + num)\r\n\r\n\r\n elif (Data[4:12]).casefold() == (\".gain_i(\").casefold():\r\n try:\r\n igain = Data[12:len(Data)-1]\r\n flIgain = float(igain)\r\n ard.gain_i(flIgain)\r\n message = \"Integral gain of Arduino\" + num + \" has been updated to: \" + igain\r\n except ValueError as e:\r\n message = error(\"No float value detected in function call: \" + str(e))\r\n except:\r\n message = error(\"Could not set igain of Arduino\" + num)\r\n\r\n elif (Data[4:13]).casefold() == (\".gain_i2(\").casefold():\r\n try:\r\n i2gain = Data[13:len(Data)-1]\r\n flI2gain = float(i2gain)\r\n ard.gain_i2(flI2gain)\r\n message = \"Integral squared gain of Arduino\" + num + \" has been updated to: \"+ i2gain\r\n except ValueError as e:\r\n message = error(\"No float value detected in function call: \" + str(e))\r\n except:\r\n message = error(\"Could not set i2gain of Arduino\" + num)\r\n\r\n elif (Data[4:19]).casefold() == (\".output_offset(\").casefold():\r\n try:\r\n offset = Data[19:len(Data)-1]\r\n flOffset = float(offset)\r\n ard.output_offset(flOffset)\r\n message = \"Arduino\" + num + \"'s Offset has been set\"\r\n except ValueError as e:\r\n message = error(\"No float value detected in function call: \" + str(e))\r\n except:\r\n message = error(\"Could not set offset of Arduino\" + num)\r\n\r\n elif (Data[4:]).casefold() == (\".increase_offset()\").casefold():\r\n try:\r\n ard.increase_offset()\r\n message = \"Arduino\" + num + \"'s Offset has sucessfully been Increased\"\r\n except:\r\n message = error(\"Arduino\" + num + \"'s Offset has failed to increase\")\r\n\r\n elif (Data[4:]).casefold() == (\".decrease_offset()\").casefold():\r\n try:\r\n ard.dectrase_offset()\r\n message = \"Arduino\" + num + \"'s offset has sucessfully been Decreased\"\r\n except:\r\n message = error(\"Arduino\" + num + \"'s offset has failed to decrease\")\r\n\r\n elif ((Data[4:11]).casefold() == \".alpha(\"):\r\n try:\r\n alpha= Data[11:len(Data)-1]\r\n flAlpha = float(alpha)\r\n ard.alpha(flApha)\r\n message = \"Arduino\" + num + \"'s Alpha value has been set\"\r\n except ValueError as e:\r\n message = error(\"No float value detected in function call: \" + str(e))\r\n except:\r\n message = error(\"Could not set Alpha of Arduino\" + num)\r\n\r\n elif ((Data[4:22]).casefold() == \".set_jump_voltage(\"):\r\n try:\r\n jump= Data[22:len(Data)-1]\r\n flJump = float(jump)\r\n ard.set_jump_voltage(flJump)\r\n message = \"Arduino\" + num + \"'s Jump Voltage value has been set\"\r\n except ValueError as e:\r\n message = error(\"No float value detected in function call: \" + str(e))\r\n except:\r\n message = error(\"Could not set Jump Voltage Value of Arduino\" + num)\r\n\r\n elif ((Data[4:14]).casefold() == \".pmt_gain(\"):\r\n try:\r\n pmtGain= Data[14:len(Data)-1]\r\n flPMTGain = float(pmtGain)\r\n ard.pmt_gain(flPMTGain)\r\n message = \"Arduino\" + num + \"'s PMT Gain value has been set\"\r\n except ValueError as e:\r\n message = error(\"No float value detected in function call: \" + str(e))\r\n except:\r\n message = error(\"Could not set PMT Gain value of Arduino\" + num)\r\n \r\n \r\n elif (Data[0:9]).casefold() == (\"get_temp(\").casefold():\r\n try:\r\n res = Data[9:len(Data)-1]\r\n flRes = float(res)\r\n temp = get_temp(flRes)\r\n strTemp = str(temp)\r\n message = \"Temperature is of \" + strTemp\r\n except:\r\n message = error(\"Could not get the Temperature\")\r\n\r\n\r\n elif (Data[0:15]).casefold() == (\"get_resistance(\").casefold():\r\n try:\r\n temp = Data[15:len(Data)-1]\r\n flTemp = float(temp)\r\n res = get_resistance(temp)\r\n strRes = str(res)\r\n message = \"The resistance is of: \"+ strRes\r\n except:\r\n message = error(\"Could not get the Resistance\") \r\n \r\n elif (Data[0:2]).casefold() == (\"kc\").casefold():\r\n try:\r\n if (Data[2]).casefold() == (\"1\").casefold():\r\n kc = kc1\r\n num = \" 1\"\r\n else:\r\n kc = kc2\r\n num = \" 2\"\r\n except:\r\n message += error(\"Could not connect to Koherons\")\r\n num = \" -1\"\r\n\r\n if (Data[3:10]).casefold() == (\".write(\").casefold():\r\n try:\r\n command = Data[10:len(Data)-1]\r\n kc.write(command)\r\n message = \"Koheron\" + num + \" wrote: \" + command\r\n except:\r\n message = error(\"Koheron\" +num + \"could not write the command\")\r\n\r\n elif (Data[3:8]).casefold() == (\".ask(\").casefold():\r\n try:\r\n command = Data[8:len(Data)-1]\r\n message = \"Response: \" + str(kc.ask(command))\r\n except:\r\n message = error(\"Koheron\" + num + \" could not ask the query\")\r\n\r\n elif (Data[3:9]).casefold() == (\".close\").casefold():\r\n try:\r\n kc.close()\r\n message = \"Koheron\" + num + \" has been Closed\"\r\n except:\r\n message = error(\"Could not close Koheron\" + num)\r\n\r\n elif (Data[3:13]).casefold() == (\".set_temp(\").casefold():\r\n try:\r\n temp = Data[13:len(Data)-1]\r\n flTemp = float(temp)\r\n kc.set_temp(flTemp)\r\n message = \"Temperature has been set to: \" + temp\r\n except ValueError as e:\r\n message = error(\"No float value detected in the function call: \" + str(e))\r\n except:\r\n message = error(\"Could not Set the Temperature of Koheron\" + num)\r\n\r\n elif (Data[3:17]).casefold() == (\".read_set_temp\").casefold():\r\n try:\r\n temp = str(kc.read_set_temp())\r\n message = \"Koheron 1's set Temperature is: \" + temp\r\n except:\r\n message = error(\"Could not read Koheron\" + num +\"'s Set Temp\")\r\n\r\n elif (Data[3:13]).casefold() == (\".read_temp\").casefold():\r\n try:\r\n temp = kc.read_temp()\r\n strTemp = str(temp)\r\n message = \"Temperature is:\" + strTemp\r\n except:\r\n message = error(\"Could not Read the Temperature of Koheron\" + num)\r\n\r\n ## Homebrew Stream_data(), which prints out one line\r\n elif (Data[3:]).casefold() == (\".stream_data()\").casefold():\r\n try:\r\n val = kc.ask('rtact')\r\n flVal = float(val)\r\n temp = get_temp(flVal)\r\n\r\n curr = kc.ask('ilaser')\r\n flCurr = float(curr)\r\n if(float(kc.ask('lason'))==1):\r\n onoff = 'On'\r\n else:\r\n onoff = 'Off'\r\n message = \"Temperature: \" + str(temp) + \" C Laser: \" + onoff + \" Current: \" + curr + \" mA\"\r\n except ValueError as e:\r\n message = error(\"Parsing Error: \" + str(e))\r\n except:\r\n message = error(\"Could not stream Data from Koheron\" + num)\r\n\r\n elif (Data[3:16]).casefold() == (\".set_current(\").casefold():\r\n try:\r\n curr = Data[16:len (Data)-1]\r\n fltCurr = float(curr)\r\n kc.set_current(fltCurr) \r\n message = \"Koheron\" + num + \"'s current has been set to: \" + curr\r\n except ValueError as e:\r\n message = error(\"No float value detected in the function call: \" + str(e))\r\n except:\r\n message = error(\"Could not set the Current of Koheron\" + num)\r\n\r\n\r\n elif (Data[3:12]).casefold() == (\".laser_on\").casefold():\r\n try:\r\n kc.laser_on()\r\n message = \"Koheron\" + num + \"'s Laser has been turned On\"\r\n except:\r\n message = error(\"Could not turn on Koheron\" + num + \"'s Laser\")\r\n\r\n elif (Data[3:13]).casefold() == (\".laser_off\").casefold():\r\n try:\r\n kc.laser_off()\r\n message = \"Koheron\" + num + \"'s Laser has been turned off\"\r\n except:\r\n message = error(\"Could not turn off Koheron\" + num + \"'s Laser\")\r\n\r\n elif (Data[3:16]).casefold() == (\".read_current\").casefold():\r\n try:\r\n curr = kc.read_current()\r\n strCurr = str(curr)\r\n message = \"Koheron\" + num + \"'s Current is of: \" + strCurr\r\n except:\r\n message = error(\"Could not read Koheron\" + num + \"'s current\")\r\n\r\n elif (Data[3:21]).casefold() == (\".increase_current(\").casefold():\r\n try:\r\n adj = Data[21:len(Data)-1]\r\n flAdj = float(adj)\r\n kc.increase_current(flAdj)\r\n message = \"Koheron\" + num + \"'s Current has been increased to: \" + adj\r\n except:\r\n message = error(\"Could not increase Koheron\" + num + \"'s current\")\r\n\r\n elif (Data[3:21]).casefold() == (\".decrease_current(\").casefold():\r\n try:\r\n adj = Data[21:len(Data)-1]\r\n flAdj = float(adj)\r\n kc.decrease_current(flAdj)\r\n message = \"Koheron\" + num + \"'s Current has been decreased to: \" + adj\r\n except:\r\n message = error(\"Could not decrease Koheron\" + num + \"'s current\")\r\n\r\n elif (Data[3:17]).casefold() == (\".ramp_current(\").casefold():\r\n try:\r\n vals = (Data[17:len(Data)-1]).split(\",\")\r\n amplitude = float(vals[0])\r\n n_steps = float(vals[1])\r\n freq = float(val[2])\r\n\r\n try:\r\n time_delay = 1/(n_steps*freq) #in s\r\n step_size = 2.0*amplitude/n_steps\r\n start_curr = float(self.ask('ilaser')) #mA\r\n curr=start_curr\r\n \r\n if(start_currCURR_MIN):\r\n self.ramp = True\r\n t0 = time.time()\r\n while((time.time())- t0 < 1):\r\n try:\r\n new_curr = start_curr - amplitude/2.0\r\n for i in range(n_steps):\r\n self.write('ilaser '+str(new_curr))\r\n new_curr += step_size\r\n time.sleep(time_delay)\r\n for i in range(n_steps):\r\n self.write('ilaser '+str(new_curr))\r\n new_curr -= step_size\r\n time.sleep(time_delay)\r\n except(KeyboardInterrupt):\r\n self.ramp = False\r\n break\r\n message = \"Ramped Current of Koheron\" + num\r\n\r\n except:\r\n message = error(\"Could not Ramp Current of Koheron\" + num)\r\n\r\n except ValueError as e:\r\n message = error(\"Invalid Triplet entered: \" + str(e))\r\n except:\r\n message = error(\"Could not Ramp the current of Koheron\" + num) \r\n \r\n\r\n if message == \"\":\r\n message = \"Invalid Input\"\r\n\r\n return message\r\n\r\n### Code ran on the 3rd thread, to log any variables or error messages from the arduinos.\r\ndef getArduinoUpdates():\r\n #Give the arduinos a second to connect properly\r\n time.sleep(1)\r\n #Permanant loop for receiving the data from the arduinos\r\n while True: \r\n #Writes all of the data to a different file.\r\n try:\r\n ArduinoLog = open(\"arduinoLog.txt\",\"a+\")\r\n update1 = ard1.ser.readline().decode(\"utf-8\").replace(\"\\n\",\"\")\r\n update2 = ard2.ser.readline().decode(\"utf-8\").replace(\"\\n\",\"\")\r\n message = str(datetime.datetime.now()) + \"\\t\" + str(update1[0:len(update1)-1])+ \"\\t\" + str(update2[0:len(update2)-1]) + \"\\n\"\r\n ArduinoLog.write(message)\r\n #print(\"Arduino1's update \" + update1[0:len(update1)-1])\r\n #print(\"Arduino2's update \" + update2[0:len(update2)-1])\r\n ArduinoLog.close()\r\n except:\r\n print(\"Error in getting updates from arduinos\")\r\n try:\r\n ArduinoLog.close()\r\n except:\r\n print(\"Already closed\")\r\n return True\r\n \r\n\r\ndef reader():\r\n lineNum = 0\r\n\r\n while True:\r\n\r\n DHOST = \"\"\r\n DPORT = 1329 ###Data Port\r\n d = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n d.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n\r\n ##Tries to create the data connection to 1329, if it fails to 1330\r\n try:\r\n d.bind((DHOST,DPORT))\r\n except:\r\n d.bind((DHOST,DPORT+1))\r\n \r\n try:\r\n # Opening the Data Connection\r\n d.listen()\r\n dConn, dAddr = d.accept()\r\n print(\"Connection at\",dAddr)\r\n except:\r\n print(\"Data not Connected\")\r\n \r\n #Give the connection a second\r\n time.sleep(1)\r\n\r\n \r\n while True:\r\n file = open(\"DataLog.txt\",\"r\")\r\n lines = file.readlines()\r\n try:\r\n dConn.sendto((lines[lineNum] + \"\\r\").encode(),dAddr)\r\n lineNum +=1\r\n file.close()\r\n lines = []\r\n except IndexError:\r\n pass\r\n except:\r\n print(\"Disconnected at\", str(datetime.datetime.now()))\r\n print(\"Failed\")\r\n dConn.close()\r\n file.close()\r\n lines = []\r\n try:\r\n d.shutdown(socket.SHUT_RDWR)\r\n except:\r\n d.close()\r\n break\r\n\r\n\r\n\r\n\r\n### Code that sends the stream of data constantly\r\ndef run():\r\n while True:\r\n\r\n try:\r\n MCAST_GRP = '225.0.0.0'\r\n MCAST_PORT = 4446\r\n IS_ALL_GROUPS = False\r\n\r\n mCastSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\r\n mCastSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n\r\n #on this port, listen ONLY to MCAST_GRP\r\n mCastSocket.bind((MCAST_GRP, MCAST_PORT))\r\n\r\n mreq = struct.pack(\"4sl\", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)\r\n mCastSocket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\r\n except:\r\n error(\"Could not connect to Multicast Group\")\r\n ### Loop for the logged and sent data.\r\n ### Currently Logs: Temperature from both sensors, Frequency from the Frequency counter and the Local time.\r\n ### Needs to log time from RTC and Altitude of the Gondola (Waiting on CSA for that) 2019-08-02\r\n # [X] Sent them an email\r\n # [X] Received Example Code\r\n # [X] Implementing Example Code\r\n # [X] Getting Jean-François to test the code\r\n # [ ] Getting a response form Jean-François\r\n\r\n threadConnectSend = threading.Thread(target=reader)\r\n threadConnectSend.start()\r\n\r\n\r\n RTCTime = \"\"\r\n altitude = \"0\"\r\n while True:\r\n time.sleep(0.1)\r\n DataLog = open(\"DataLog.txt\",\"a+\")\r\n message = \"\"\r\n try:\r\n prismMSG = (mCastSocket.recv(1024)).decode()\r\n prism_data = prismMSG.split(\",\")\r\n if prism_data[3] == \"POS0\":\r\n RTCTime = str(prism_data[1])\r\n altitude = str(prism_data[6])\r\n except:\r\n try:\r\n MCAST_GRP = '225.0.0.0'\r\n MCAST_PORT = 4446\r\n IS_ALL_GROUPS = False\r\n\r\n mCastSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\r\n mCastSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n\r\n #on this port, listen ONLY to MCAST_GRP\r\n mCastSocket.bind((MCAST_GRP, MCAST_PORT))\r\n\r\n mreq = struct.pack(\"4sl\", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)\r\n mCastSocket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\r\n except:\r\n pass\r\n RTCTime = str(datetime.datetime.now())\r\n altitude= \"0\"\r\n message = RTCTime + \"\\t\" + altitude + \"\\t\"\r\n try:\r\n temp = DualBME280s.temp()\r\n message += str(temp[0]) + \"\\t\" + str(temp[1]) + \"\\t\" \r\n except:\r\n message +=\"999\\t 999\\t\"\r\n\r\n try:\r\n freq = freqCounter() \r\n message += str(freq[1]) + \"\\t\"\r\n except:\r\n message += \"0\\t\"\r\n message = message + \"\\n\"\r\n\r\n try:\r\n DataLog.write(message)\r\n DataLog.close() \r\n \r\n except:\r\n print(\"Could not write to file\")\r\n \r\n print(\"over\")\r\n return True\r\n \r\n \r\n### Main thread, handles the sending and receiving of commands.\r\ndef main():\r\n print(\"Start\")\r\n \r\n TimeOutTime = 150 *3600 #in seconds\r\n StartTime= time.time()\r\n\r\n ## Loop over everything\r\n while True:\r\n # Initializing the connections\r\n\r\n ### CMD connection\r\n HOST = \"\"\r\n PORT = 1313 ###Data Port\r\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n ##Tries to create the connection at the port 1313, and if it fails it will create it to 1314.\r\n try:\r\n s.bind((HOST,PORT))\r\n except:\r\n s.bind((HOST,PORT+1)) \r\n Started = False\r\n \r\n \r\n #Trying to connect the connection\r\n try:\r\n # Opening the CMD connection\r\n s.listen(10)\r\n conn, addr = s.accept()\r\n\r\n print(\"Connection at\",addr)\r\n except:\r\n print(\"CMD not Connected\")\r\n time.sleep(0.5) \r\n \r\n ### Loop to start the connection\r\n while True:\r\n data = conn.recv(1024)\r\n if data.decode() == \"Start\":\r\n\r\n\r\n ### Open the command/warning Log\r\n try:\r\n log = open(\"logs.txt\",\"a+\")\r\n log.write(\"---------------------------------------------------------------------------------------------------------------\\n\")\r\n log.write(\"Time: \" + str(datetime.datetime.now()) + \" Connected: \" + str(addr) + \"\\n\") \r\n except:\r\n log.write(\"Log already opened!\\n\")\r\n ### Data Thread Starting\r\n try:\r\n # Starts the data sending thread\r\n threadData = threading.Thread(target=run)\r\n threadData.start()\r\n # Starts the Arduino Updates thread\r\n threadUpdate = threading.Thread(target=getArduinoUpdates)\r\n threadUpdate.start()\r\n\r\n except:\r\n log.write(\"Time: \" + str(datetime.datetime.now()) + \" WARNING: THREAD ALREADY INITIATED\\n\")\r\n\r\n ### Validation of Connection\r\n message = \"Connected!\"\r\n conn.sendall(message.encode())\r\n logLine = \"Time: \" + str(datetime.datetime.now()) + \" Input: \" + data.decode() + \" Output: \" + message + \"\\n\"\r\n log.write(logLine)\r\n \r\n ### Breaking out of loop\r\n Started = True\r\n break\r\n\r\n ### Incase the client tries to send a command before initializing the connection.\r\n else:\r\n message = \"ERROR: Process has not started\"\r\n conn.sendall(message.encode())\r\n \r\n ### Loop that handles communication to the client\r\n while True:\r\n # Code first checks if more time has elapsed than the alloted time (Maximum time alloted = TimeOutTime)\r\n if (time.time() - StartTime) >= TimeOutTime:\r\n try: \r\n while float(kc1.ask('lason'))==1:\r\n kc1.laser_off()\r\n while float(kc2.ask('lason'))==1:\r\n kc2.laser_off()\r\n except:\r\n error(\"Could not turn off lasers\")\r\n\r\n # Code tries to read the query of the Client\r\n try:\r\n data = conn.recv(1024)\r\n except:\r\n # If no query has been received, the code logs it as an error and closes the log and restarts the connection process\r\n log.write(\"Time: \" + str(datetime.datetime.now()) + \" No Response From: \" + str(addr) + \"\\n\")\r\n print(\"Time: \" + str(datetime.datetime.now()) + \" No Response From: \" + str(addr))\r\n\r\n log.close()\r\n Started = False\r\n conn.close()\r\n\r\n break\r\n # If the Query is somehow invalid, (returns a false?) it resets the question\r\n if not data:\r\n break\r\n\r\n ### If the client wants to terminate, this clause is initiated.\r\n # This clause essentially disconnects the user, closes the log and closes the socket properly\r\n if data.decode() == \"Terminate\":\r\n log.write(\"Time: \" + str(datetime.datetime.now()) + \" Disconnected: \" + str(addr) + \"\\n\")\r\n print(\"Time: \" + str(datetime.datetime.now()) + \" Disconnected: \" + str(addr) + \"\\n\")\r\n\r\n\r\n log.close() \r\n Started = False\r\n conn.close()\r\n try:\r\n s.shutdown(socket.SHUT_RDWR)\r\n except:\r\n s.close()\r\n\r\n break\r\n\r\n ### If the client does not want to terminate, the server decodes the data and accomplishes the command.\r\n else:\r\n # Fist checks that the process is \"started\"\r\n if Started == True: \r\n message = associate(data.decode(),conn)\r\n \r\n else:\r\n message = \"ERROR: Process has not started\"\r\n # After a successful translation, it sends the client a message and saves a copy to log.\r\n conn.sendall(message.encode())\r\n logLine = \"Time: \" + str(datetime.datetime.now()) + \" Input: \" + data.decode() + \" Output: \" + message + \"\\n\"\r\n log.write(logLine)\r\n\r\n\r\n # After running the main loop sucessfully and ending it, the connection is then closed. \r\n conn.close() \r\n \r\n \r\nmain()","sub_path":"Server/SORCETelecomV10.py","file_name":"SORCETelecomV10.py","file_ext":"py","file_size_in_byte":36308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"639357936","text":"from tkinter import *\r\nimport tkinter.dialog\r\ndef jpadEditor(file=None):\r\n global askopenfilename\r\n \"\"\"\r\n Starts Jpad\r\n \"\"\"\r\n global rootJpad\r\n colour = \"#00ff00\"\r\n\r\n width = \"500\"\r\n height = \"400\"\r\n\r\n widthHeight = width + \"x\" + height\r\n\r\n rootJpad = Tk()\r\n\r\n sWidth = rootJpad.winfo_screenwidth()\r\n sHeight = rootJpad.winfo_screenheight()\r\n\r\n rootJpad.title(\"Jpad\")\r\n rootJpad.geometry(widthHeight)\r\n rootJpad.maxsize(sWidth, sHeight)\r\n rootJpad.minsize(\"200\", \"200\")\r\n\r\n textPad = Text(rootJpad)\r\n textPad.configure(bg=colour)\r\n textPad.focus()\r\n\r\n textPad.pack(expand=YES, fill=BOTH)\r\n\r\n font = [\"Arial\", \"11\", \"normal\"]\r\n\r\n textPad.configure(font=(font[0], int(font[1]), font[2]))\r\n\r\n def chfont():\r\n def apply():\r\n try:\r\n textPad.configure(font=(font1.get(), int(font2.get()), font3.get()))\r\n font[0] = font1.get()\r\n font[1] = font2.get()\r\n font[2] = font3.get()\r\n\r\n rootFont.destroy()\r\n except:\r\n msg.configure(text=\"Whoops, something went wrong while applying your font!\")\r\n\r\n rootFont = Tk()\r\n rootFont.title(\"Font\")\r\n rootFont.geometry(\"320x110\")\r\n\r\n font1 = Entry(rootFont)\r\n font2 = Entry(rootFont)\r\n font3 = Entry(rootFont)\r\n\r\n font1.insert(0, font[0])\r\n font2.insert(0, font[1])\r\n font3.insert(0, font[2])\r\n\r\n applyButton = Button(rootFont, text=\"Apply Font\", command=apply)\r\n msg = Label(rootFont)\r\n\r\n font1.pack()\r\n font2.pack()\r\n font3.pack()\r\n applyButton.pack()\r\n msg.pack()\r\n\r\n rootFont.mainloop()\r\n\r\n def open_command():\r\n file = tkFileDialog.askopenfilename(defaultextension=\".txt\",\r\n filetypes=[(\"Text Files\", \".txt\"), (\"All Files\")])\r\n\r\n rootJpad.title(\"Jpad Text Editor\" + \" File: \" + file)\r\n file = open(file, \"r\")\r\n if file != None:\r\n contents = file.read()\r\n textPad.delete(0.0, END)\r\n textPad.insert(0.0, contents)\r\n file.close()\r\n\r\n def save_command():\r\n file = asksaveasfilename(defaultextension=\".txt\",\r\n filetypes=[(\"Text Files\", \".txt\"), (\"All Files\", \".*\")])\r\n rootJpad.title(\"Jpad Text Editor\" + \" File: \" + file)\r\n file = open(file, \"w\")\r\n if file != None:\r\n # slice off the last character from get, as an extra return is added\r\n data = textPad.get(0, 0)\r\n file.write(data)\r\n file.close()\r\n\r\n def exit_command():\r\n closeApp()\r\n\r\n def new():\r\n rootJpad.title(\"Jpad Text Editor\" + \" File: New File\")\r\n textPad.delete(0.0, END)\r\n\r\n if file != None:\r\n rootJpad.title(\"Jpad Text Editor\" + \" File: \" + str(file))\r\n file = open(file, \"r\")\r\n contents = file.read()\r\n textPad.delete(0.0, END)\r\n textPad.insert(0.0, contents)\r\n file.close()\r\n\r\n menu = Menu(rootJpad)\r\n rootJpad.config(menu=menu)\r\n rootJpad.config(bg=colour)\r\n filemenu = Menu(menu)\r\n menu.add_cascade(label=\"File\", menu=filemenu)\r\n filemenu.add_command(label=\"New\", command=new)\r\n filemenu.add_command(label=\"Open...\", command=open_command)\r\n filemenu.add_command(label=\"Save\", command=save_command)\r\n filemenu.add_separator()\r\n filemenu.add_command(label=\"Exit\", command=exit_command)\r\n\r\n fontMenu = Menu(menu)\r\n menu.add_cascade(label=\"Font\", menu=fontMenu)\r\n fontMenu.add_command(label=\"font\", command=chfont)\r\n\r\n rootJpad.mainloop()\r\njpadEditor()\r\n","sub_path":"files/download/Jpad.py","file_name":"Jpad.py","file_ext":"py","file_size_in_byte":3696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"35450830","text":"#!/usr/bin/env python\nimport operator\nimport sys\nfrom itertools import combinations\n\nfrom EPPs.common import StepEPP, InvalidStepError\n\n\nclass CheckIndexCompatibility(StepEPP):\n '''Checks the index compatibility within pools created in the step and populate artifact udfs with the Hamming\n distances separately for both the I7 and I5 indexes.'''\n\n def populate_output_udfs(selfs, hamming_distances, outputs_to_put, output):\n output.udf['Min I7 Hamming Distance'] = str(hamming_distances[0])\n output.udf['Min I5 Hamming Distance'] = str(hamming_distances[1])\n outputs_to_put.append(output)\n\n\n\n def qc_check_hamming_distances(self, hamming_distances, output):\n '''Compares the Hamming distances of the indexes against the thresholds defined by step UDFs.\n If for a \"Single Read\" sequencing run then there must be a difference in the I7 index. If for a \"Dual Read\"\n sequencing run then the difference can be in either the I7 or I5 (or both).'''\n if self.process.udf['Compatibility Check'] == 'Single Read':\n if hamming_distances[0] < int(self.process.udf['Single Read Minimum Hamming Distance']):\n raise InvalidStepError('Indexes not compatible within pool %s' % output.name)\n elif self.process.udf['Compatibility Check'] == 'Dual Read':\n if hamming_distances[0] + hamming_distances[1] < int(\n self.process.udf['Dual Read Minimum Hamming Distance']):\n raise InvalidStepError('Indexes not compatible within pool %s' % output.name)\n\n def calculate_hamming_distances(self, indexes_list):\n ''' Calculates the minimum I7 and I5 Hamming distances for the indexes in the pool. Performs a pairwise comparison\n of all possible I7 pairs and all possible I5 pairs. Measures the length of the indexes in each pair and only\n compares a length from 0 to the length of the shortest index.'''\n hamming_distance_i7_list = []\n hamming_distance_i5_list = []\n for indexes in combinations(indexes_list, 2):\n ne = operator.ne\n index_0_i7, index_0_i5 = indexes[0].split('-')\n index_1_i7, index_1_i5 = indexes[1].split('-')\n # obtain length of smallest index in the i7 comparison (although often will be standard)\n length = min(len(index_0_i7), len(index_1_i7))\n # calculate the hamming distance for i7\n hamming_distance_i7_list.append(sum(map(ne, index_0_i7[:length], index_1_i7[:length])))\n # obtain length of smallest index in the i7 comparison (although often will be standard)\n\n length = min(len(index_0_i5), len(index_1_i5))\n # calculate the hamming distance for i5\n hamming_distance_i5_list.append(sum(map(ne, index_0_i5[:length], index_1_i5[:length])))\n\n hamming_distance_i7_min = min(hamming_distance_i7_list)\n hamming_distance_i5_min = min(hamming_distance_i5_list)\n return [hamming_distance_i7_min, hamming_distance_i5_min]\n\n def get_indexes_list(self, inputs):\n # generate a list of indexes from all of the inputs for the pool\n indexes_list = []\n for input in inputs:\n index_pair = input.reagent_labels[0].split('(')[1]\n index_pair = index_pair.split(')')[0]\n indexes_list.append(index_pair)\n return indexes_list\n\n def _run(self):\n\n outputs_to_put = []\n # for each output pool find all the input artifacts, obtain their indexes and calculate the minimum Hamming\n #distances between I7 and I5 indexes\n\n for output in self.output_artifacts:\n\n #find the output pools i.e. outputs with type 'Analyte'\n if output.type == 'Analyte':\n # find all the input_output maps for the output artifact\n inputs_outputs = [io for io in self.process.input_output_maps if io[1]['limsid'] == output.id]\n\n inputs = [io[0]['uri'] for io in inputs_outputs]\n\n indexes_list = self.get_indexes_list(inputs)\n\n hamming_distances = self.calculate_hamming_distances(indexes_list)\n self.qc_check_hamming_distances(hamming_distances, output)\n self.populate_output_udfs(hamming_distances, outputs_to_put, output)\n\n self.lims.put_batch(outputs_to_put)\n\n\nif __name__ == '__main__':\n sys.exit(CheckIndexCompatibility().run())\n","sub_path":"scripts/check_index_compatibility.py","file_name":"check_index_compatibility.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"61508299","text":"import boto3\nfrom botocore.exceptions import ClientError\n\ndef create_instance():\n ec2_resource = boto3.resource('ec2')\n instances = ec2_resource.create_instances(ImageId='ami-6871a115',\n MinCount=1, MaxCount=3,InstanceType='t2.micro',\n SecurityGroupIds=['sg-05198f9df4a5885af'],KeyName='fullstack')\n \n instance_ids = []\n for instance in instances:\n instance_ids.append(instance.id)\n ec2_client = boto3.client('ec2')\n waiter=ec2_client.get_waiter('instance_running')\n waiter.wait(InstanceIds=instance_ids)\n print (\"Instance is Running now!\")\n\n\ndef prepare_instance_list():\n mylist = []\n ec2_resource = boto3.resource('ec2')\n instances = ec2_resource.instances.filter(\n Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])\n for instance in instances:\n print(instance.id, instance.instance_type)\n mylist.append(instance.id)\n return mylist\n\ndef delete_instances(instance_list):\n ec2_client = boto3.client('ec2')\n try:\n ec2_client.terminate_instances(InstanceIds=instance_list,DryRun=True)\n except ClientError as e:\n if 'DryRunOperation' not in str(e):\n raise\n\n ec2_client.terminate_instances(InstanceIds=instance_list,DryRun=False)\n\nif __name__ == \"__main__\":\n\n#call to create instance\n create_instance()\n\n#call to terminate instance\n instance_list = prepare_instance_list()\n if len(instance_list) !=0:\n print ( \"Deleting Instances\", instance_list)\n delete_instances(instance_list)\n else:\n print ( \"No Instances to delete \")\n\n ","sub_path":"lab-07/create3.py","file_name":"create3.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"535416329","text":"from rest_framework import serializers\n\nfrom .models import Snippet\n\n\n# Post\n# List PostSerializer\n# Retrieve PostDetailSerializer\n# Update PostUpdateSerializer\n# Create PostCreateSerializer\nclass SnippetSerializer(serializers.ModelSerializer):\n class Meta:\n model = Snippet\n fields = (\n 'pk',\n 'author',\n 'title',\n 'code',\n 'linenos',\n 'language',\n 'style',\n 'created',\n )\n\n\nclass SnippetCreateSerializer(serializers.ModelSerializer):\n class Meta:\n model = Snippet\n fields = (\n 'title',\n 'code',\n 'linenos',\n 'language',\n 'style',\n 'created',\n )\n\n def to_representation(self, instance):\n return SnippetSerializer(instance).data","sub_path":"app/snippets/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"22649605","text":"import requests\nfrom re import finditer\nfrom os.path import join\nfrom DataMining.utils import touch_dir, complete_digits\n\n\nclass CloneWarsDownloader(object):\n def __init__(self, download_folder):\n self.download_folder = download_folder\n self.home_page = \"https://toonitalia.org/star-wars-the-clone-wars/\"\n self.n_seasons = 6\n\n @staticmethod\n def get_list_from_url(url):\n content = requests.get(url).content # bytes\n content = str(content)[2:] # str\n content = content.replace(\"\\\\t\", \" \")\n content = content.replace(\"\\\\xc2\\\\xb0\", \"°\")\n content = content.replace(\"\\\\\\'\", \"\\'\")\n content = content.rsplit(\"\\\\n\") # list of str\n return content\n\n def run(self):\n # mining home_page content\n home_page_content = self.get_list_from_url(self.home_page)\n\n for c_season in range(1, self.n_seasons + 1):\n # for each season there is an header\n c_header = '

' + \\\n str(c_season) + '° Stagione:

'\n\n # we can easily find the line in which this header appear with the\n # index method for list in python\n c_header_index = home_page_content.index(c_header)\n\n # in the lines after the header we have to find the substring\n # that contains the video streaing url; we can easily find\n # substrings with the find method for strings; if the https\n # substring is not found, the find method returns -1, so we can\n # use a while cycle on lines.\n line_index = c_header_index + 1\n episode_index = 1\n while home_page_content[line_index].find('https://') != -1:\n # extracting current line\n c_line = home_page_content[line_index]\n\n # find all occurrences of the \"https://\" substring\n all_occurrences = [\n m.start() for m in finditer('https://', c_line)\n ]\n\n # only the last one is the right one\n url_start = all_occurrences[-1]\n\n # in the substring found, finding the end of the url looking\n # for the .html word\n c_line = c_line[url_start:]\n url_end = c_line.find('.html') + 5\n\n # extracting url:\n c_url = c_line[0:url_end]\n\n # mining the html page found\n c_page_content = self.get_list_from_url(c_url)\n\n # finding the window.hola_player index\n hola_header = 'window.hola_player({ player: \\'#hola\\','\n hola_player_index = c_page_content.index(hola_header)\n\n # looking for the source line\n c_page_line = hola_player_index + 1\n while c_page_content[c_page_line].find('sources: [{src') == -1:\n c_page_line += 1\n\n # getting the line\n source_line = c_page_content[c_page_line]\n\n # getting the url\n url_start = source_line.find('https://')\n source_line = source_line[url_start:]\n url_end = source_line.find('\"')\n video_url = source_line[0:url_end]\n\n # downloading video\n output_folder = join(\n self.download_folder,\n 'Season ' + complete_digits(str(c_season), 2)\n )\n touch_dir(output_folder)\n output_path = join(\n output_folder,\n 'Star Wars The Clone Wars - s{}e{}.mp4'.format(\n complete_digits(str(c_season), 2),\n complete_digits(str(episode_index), 2)\n )\n )\n print(output_path)\n r = requests.get(video_url)\n with open(output_path, 'wb') as code:\n code.write(r.content)\n\n line_index += 1\n episode_index += 1\n","sub_path":"DataMining/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":4118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"228666097","text":"''' Pretrain bert in the language model task '''\nfrom __future__ import unicode_literals\nfrom collections import defaultdict\nimport random\nimport numpy\nimport plac\nfrom collections import Counter\nimport spacy\nfrom spacy.tokens import Doc\nfrom spacy.attrs import ID, ORTH, SHAPE, PREFIX, SUFFIX\nfrom thinc.neural.util import to_categorical, minibatch\nfrom thinc.neural._classes.encoder_decoder import EncoderDecoder\nfrom thinc.neural._classes.softmax import Softmax\nfrom thinc.misc import FeatureExtracter\nfrom thinc.api import wrap, chain, with_flatten, with_reshape\nfrom attention_is_all_you_need import get_dicts, pad_sequences, \\\n PositionEncode, docs2ids, FancyEmbed, set_rank, set_numeric_ids\nfrom bert_textcat import create_model_input, get_mask\nfrom thinc.misc import Residual\nfrom thinc.v2v import Model\nfrom thinc.neural._classes.encoder_decoder import Encoder\nfrom thinc.extra.datasets import get_iwslt\n\n\ndef random_mask(X0, nlp, indx2word, vocab, mL):\n nB = len(X0)\n nL = max([len(x) for x in X0])\n nC = int(0.15 * nL)\n # produce masked tokens indices\n indices = \\\n [Model.ops.xp.random.randint(0, len(x), nC) for x in X0]\n ''' We need to compute loss only for the masked tokens '''\n loss_mask = Model.ops.xp.zeros((nB, nL))\n docs = []\n for sent_indx in range(nB):\n words = [w.text for w in X0[sent_indx]]\n new_words = []\n for i, word in enumerate(words):\n dice = int(Model.ops.xp.random.randint(1, 11, 1))\n if i not in indices[sent_indx]:\n new_words.append(word)\n else:\n loss_mask[sent_indx, i] = 1.0\n if dice == 10:\n new_words.append(word)\n elif dice <= 8:\n new_words.append('')\n else:\n ''' Choose a random word from the vocabulary '''\n vocab_indx = \\\n int(Model.ops.xp.random.randint(0, len(nlp.vocab), 1))\n random_word = indx2word[vocab_indx]\n new_words.append(random_word)\n docs.append(Doc(vocab, words=new_words))\n return docs, loss_mask\n\n\ndef spacy_tokenize(X_tokenizer, X, mL=50):\n X_out = []\n for x in X:\n xdoc = X_tokenizer(' ' + x.strip())\n if len(xdoc) < mL:\n X_out.append(xdoc)\n return X_out\n\n\ndef get_loss(Xh, original_docs, masked_docs, loss_mask):\n ''' Calculate loss '''\n\n ''' Convert original docs to (nB, nL, nTGT) with one hot encoding '''\n X_ids = docs2ids(original_docs)\n nb_classes = Xh.shape[-1]\n X = [to_categorical(y, nb_classes=nb_classes) for y in X_ids]\n X, _ = pad_sequences(Model.ops, X)\n\n ''' Loss calculation only on the masked positions '''\n dXh = Xh - X\n dXh = dXh * Model.ops.xp.expand_dims(loss_mask, axis=2)\n\n ''' Calculate number of accurate, inaccurate tokens '''\n accurate = Xh.argmax(axis=-1) == X.argmax(axis=-1)\n inaccurate = Xh.argmax(axis=-1) != X.argmax(axis=-1)\n accurate = accurate * loss_mask\n inaccurate = inaccurate * loss_mask\n\n return dXh, accurate.sum(), accurate.sum() + inaccurate.sum()\n\n\n@plac.annotations(\n nH=(\"number of heads of the multiheaded attention\", \"option\", \"nH\", int),\n dropout=(\"model dropout\", \"option\", \"d\", float),\n nS=('Number of encoders in the enc stack.', \"option\", \"nS\", int),\n nB=('Batch size for the training', \"option\", \"nB\", int),\n nE=('Number of epochs for the training', \"option\", \"nE\", int),\n use_gpu=(\"Which GPU to use. -1 for CPU\", \"option\", \"g\", int),\n lim=(\"Number of sentences to load from dataset\", \"option\", \"l\", int),\n nM=(\"Embeddings size\", \"option\", \"nM\", int),\n nTGT=(\"Vocabulary size\", \"option\", \"nTGT\", int),\n mL=(\"Max length sentence in dataset\", \"option\", \"mL\", int),\n save=(\"Save model to disk\", \"option\", \"save\", bool),\n save_name=(\"Name of file saved to disk. Save option must be enabled\")\n)\ndef main(nH=6, dropout=0.1, nS=6, nB=64, nE=20, use_gpu=-1, lim=1000000,\n nM=300, mL=100, save=False, nTGT=5000, save_name=\"model.pkl\"):\n if use_gpu != -1:\n spacy.require_gpu()\n device = 'cuda'\n else:\n device = 'cpu'\n\n ''' Read dataset '''\n nlp = spacy.load('en_core_web_sm')\n print('English model loaded')\n for control_token in (\"\", \"\", \"\", \"\", \"\"):\n nlp.tokenizer.add_special_case(control_token, [{ORTH: control_token}])\n\n train, dev, test = get_iwslt()\n print('Dataset loaded')\n\n train, _ = zip(*train)\n dev, _ = zip(*dev)\n test, _ = zip(*test)\n\n train = train[:lim]\n dev = dev[:lim]\n test = test[:lim]\n\n ''' Tokenize '''\n train = spacy_tokenize(nlp.tokenizer, train, mL=mL)\n dev = spacy_tokenize(nlp.tokenizer, dev, mL=mL)\n test = spacy_tokenize(nlp.tokenizer, test, mL=mL)\n print('Tokenization finished')\n\n ''' Set rank based on all the docs '''\n all_docs = train + dev + test\n set_rank(nlp.vocab, all_docs, nTGT=nTGT)\n\n train = set_numeric_ids(nlp.vocab, train)\n dev = set_numeric_ids(nlp.vocab, dev)\n test = set_numeric_ids(nlp.vocab, test)\n print('Numeric ids set')\n\n word2indx, indx2word = get_dicts(nlp.vocab)\n print('Vocab dictionaries grabbed')\n\n with Model.define_operators({\">>\": chain}):\n embed_cols = [ORTH, SHAPE, PREFIX, SUFFIX]\n extractor = FeatureExtracter(attrs=embed_cols)\n position_encode = PositionEncode(mL, nM)\n model = (\n FeatureExtracter(attrs=embed_cols)\n >> with_flatten(FancyEmbed(nM, nTGT, cols=embed_cols))\n >> Residual(position_encode)\n >> create_model_input()\n >> Encoder(nM=nM, nS=nS, nH=nH, device=device)\n >> with_reshape(Softmax(nO=nTGT, nI=nM))\n )\n ''' Progress tracking '''\n losses = [0.]\n train_accuracies = [0.]\n train_totals = [0.]\n dev_accuracies = [0.]\n dev_loss = [0.]\n\n def track_progress():\n correct = 0.\n total = 0.\n ''' Get dev stats '''\n for X0 in minibatch(dev, size=nB):\n X1, loss_mask = random_mask(X0, nlp, indx2word, nlp.vocab, mL)\n Xh = model(X1)\n L, C, t = get_loss(Xh, X0, X1, loss_mask)\n correct += C\n total += t\n dev_loss[-1] += (L**2).sum()\n dev_accuracies[-1] = correct / total\n print(len(losses), losses[-1], train_accuracies[-1] / train_totals[-1],\n dev_loss[-1], dev_accuracies[-1])\n dev_loss.append(0.)\n losses.append(0.)\n train_accuracies.append(0.)\n dev_accuracies.append(0.)\n train_totals.append(0.)\n if save:\n model.to_disk('.models/' + save_name)\n\n ''' Model training '''\n with model.begin_training(batch_size=nB, nb_epoch=nE) as (trainer, optimizer):\n trainer.dropout = dropout\n trainer.dropout_decay = 1e-4\n optimizer.alpha = 0.001\n optimizer.L2 = 1e-6\n optimizer.max_grad_norm = 1.0\n trainer.each_epoch.append(track_progress)\n optimizer.alpha = 0.001\n optimizer.L2 = 1e-6\n optimizer.max_grad_norm = 1.0\n for X0, _ in trainer.iterate(train, train):\n X1, loss_mask = random_mask(X0, nlp, indx2word, nlp.vocab, mL)\n Xh, backprop = model.begin_update(X1, drop=dropout)\n dXh, C, total = get_loss(Xh, X0, X1, loss_mask)\n backprop(dXh, sgd=optimizer)\n losses[-1] += (dXh**2).sum()\n train_accuracies[-1] += C\n train_totals[-1] += total\n\n\nif __name__ == '__main__':\n plac.call(main)\n","sub_path":"examples/pretrain_bert.py","file_name":"pretrain_bert.py","file_ext":"py","file_size_in_byte":7782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"389386635","text":"#!/usr/bin/python\r\n\r\nimport sys\r\nimport re\r\nimport collections\r\n\r\ntime = re.compile(r'global=([+-]?\\d+(\\.\\d+)?([eE][+-]?\\d+)?)') # Read the current time from the clock named \"global\" (note that values can also be 1234.567e+23 so we look also for that kind of numbers)\r\nstate = re.compile(r'^\\( (.*) \\)') # The current state definition (it is in the line that starts with \"( \" and goes on until \" )\")\r\npName = re.compile(r'(P_\\w*).(\\w*)') # The name of a processor, and its state. Before the \".\" we have the name (which goes in group(1)) and after the \".\" we have the current state (in group(2))\r\nschedulingTransition = re.compile(r'(P_\\w*).\\w*->P_\\w*.\\w* { 1, fire\\[p_id\\]\\[(\\w*)\\]') # Schedule a new task on a processor: it changes state and we read from the synchronization label which task it was asked to perform. So group(1) will tell us the processor name and group(2) the task name\r\nendTaskTransition = re.compile(r'(P_\\w*).\\w*->P_\\w*.\\w* { \\w* == \\d*, end\\[p_id\\]\\[(\\w*)\\]') # A processor has finished its task. Also here, group(1) is the processor name and group(2) is the task name\r\ndelay = re.compile(r'Delay: \\d*') # A delay transition\r\n\r\ncurrentState = \"\"\r\ncurrentTime = \"\"\r\nfirstLine = True\r\ntaskNames = []\r\ntasks = collections.OrderedDict()\r\ntasks['fw_dist_db'] = ''\r\ntasks['im_read'] = ''\r\ntasks['fw_dupl_mat_1'] = ''\r\ntasks['fw_integral'] = ''\r\ntasks['fw_haar_casc_detector'] = ''\r\ntasks['fw_haar_casc_detect_scale'] = ''\r\ntasks['fw_collect_objs'] = ''\r\ntasks['fw_group_rect'] = ''\r\ntasks['face_resize'] = ''\r\ntasks['fw_imprepare'] = ''\r\ntasks['fw_mat_pow'] = ''\r\ntasks['fw_conv2d_0'] = ''\r\ntasks['fw_conv2d_1'] = ''\r\ntasks['fw_equalize_contrast'] = ''\r\ntasks['fw_normalize_intesity'] = ''\r\ntasks['fw_lbp_op'] = ''\r\ntasks['fw_split_mat'] = ''\r\ntasks['fw_hist_1d'] = ''\r\ntasks['fw_join_mat'] = ''\r\ntasks['fw_dupl_mat_2'] = ''\r\ntasks['fw_compare_hist0'] = ''\r\ntasks['fw_best_score'] = ''\r\ntasks['pr_result'] = ''\r\n\r\n\r\nfor line in sys.stdin:\r\n\tl = line.strip()\r\n\tif (state.match(l)): # Each state on a trace shows first the automata locations (\"State: ...\") and then the variable and clock values, so we will output something only after we have read the time\r\n\t\ts = state.search(l)\r\n\t\tcurrentState = s.group(1)\r\n\tif (schedulingTransition.match(l)):\r\n\t\tt = schedulingTransition.search(l)\r\n\t\tprocName = t.group(1)\r\n\t\ttaskName = t.group(2)\r\n\t\ttasks[taskName] = procName\r\n\t\t#sys.stderr.write(taskName + \" started on \" + procName + \"\\n\")\r\n\tif (endTaskTransition.match(l)):\r\n\t\te = endTaskTransition.search(l)\r\n\t\tprocName = e.group(1)\r\n\t\ttaskName = e.group(2)\r\n\t\ttasks[taskName] = ''\r\n\t\t#sys.stderr.write(taskName + \" finished on \" + procName + \"\\n\")\r\n\tif (time.match(l)):\r\n\t\tt = time.search(l)\r\n\t\tcurrentTime = t.group(1)\r\n\t\tif (not firstLine):\r\n\t\t\tcontinue\r\n\t\telse: # First line of the output file: write simply the column headers (so \"Time\" and the processor names)\r\n\t\t\tfirstLine = False\r\n\t\t\tsys.stdout.write(\"Time\")\r\n\t\t\tfor n in pName.finditer(currentState):\r\n\t\t\t\tsys.stdout.write(\";\" + n.group(1))\r\n\t\t\tfor taskName, scheduledProcessor in tasks.items(): # In this case, scheduledProcessor should always yield '', as we are looking at this for the first time\r\n\t\t\t\tsys.stdout.write(\";\" + taskName)\r\n\t\t\tsys.stdout.write(\"\\n\")\r\n\tif (delay.match(l)): # We are at a delay transition, so output the latest state at the current time\r\n\t\tsys.stdout.write(currentTime)\r\n\t\tfor n in pName.finditer(currentState):\r\n\t\t\tprocState = n.group(2)\r\n\t\t\tif (procState == \"Idle\"):\r\n\t\t\t\tprocState = \"-\"\r\n\t\t\telif (procState.startswith(\"InUse_\")):\r\n\t\t\t\tprocState = procState[len(\"InUse_\"):]\r\n\t\t\t\tif (procState not in taskNames):\r\n\t\t\t\t\ttaskNames.append(procState)\r\n\t\t\tsys.stdout.write(\";\" + procState)\r\n\t\tfor taskName, scheduledProcessor in tasks.items(): # In this case, scheduledProcessor should contain the processor on which the task was scheduled (or '' if the task was completed in the meantime)\r\n\t\t\tsys.stdout.write(\";\" + scheduledProcessor)\r\n\t\tsys.stdout.write(\"\\n\")\r\n# At the end, we write the last state we found\r\nsys.stdout.write(currentTime)\r\nfor n in pName.finditer(currentState):\r\n\tsys.stdout.write(\";\" + n.group(2))\r\nsys.stdout.write(\"\\n\")\r\nsys.stderr.write(\"\\ntasks = collections.OrderedDict()\\n\")\r\nfor t in taskNames:\r\n\tsys.stderr.write(\"tasks['\" + t + \"'] = ''\\n\")\r\nsys.stderr.write(\"\\n\")\r\nsys.stderr.write(\"If this was the first time you called this script on this input data, please copy the above declaration of the 'tasks' ordered dictionary in the .py script (replacing the existing one) and re-run the script.\\n\")\r\n","sub_path":"PythonScript/parse_results_delay.py","file_name":"parse_results_delay.py","file_ext":"py","file_size_in_byte":4522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"182464832","text":"import tkinter as tk\r\nimport cv2,os,csv\r\nimport pandas as pd\r\nimport datetime\r\nimport time\r\nfrom tkinter import Message ,Text\r\nimport cv2,os\r\nimport csv\r\nimport numpy as np\r\nfrom PIL import Image, ImageTk\r\nimport tkinter.ttk as ttk\r\nfrom tkinter import messagebox\r\nimport tkinter.font as font\r\n\r\n\r\ndef Attendance():\r\n\twindow = tk.Tk()\r\n\r\n\twindow.title(\"Face_Recogniser\")\r\n\r\n\t#window.geometry('1300x700')\r\n\r\n\t#for window background color\r\n\twindow.configure(background='white')\r\n\r\n\t#for full screen window \r\n\twindow.attributes('-fullscreen', True)\r\n\r\n\twindow.grid_rowconfigure(0, weight=1)\r\n\twindow.grid_columnconfigure(0, weight=1)\r\n\tmessage = tk.Label(window, text=\"Face-Recognition-Based-Attendance-Management-System\" ,bg=\"Green\" ,fg=\"white\" ,width=45 ,height=3,font=('times', 30, 'italic bold underline')) \r\n\tmessage.place(x=150, y=20)\r\n\r\n\tlbl3 = tk.Label(window, text=\"Attendance list: \",width=20 ,fg=\"red\" ,bg=\"white\" ,height=2 ,font=('times', 15, ' bold underline')) \r\n\tlbl3.place(x=150, y=300)\r\n\r\n\r\n\r\n\tmessage2 = tk.Label(window, text=\"\" ,fg=\"red\" ,justify=tk.RIGHT ,bg=\"light cyan\",activeforeground = \"green\",width=45 ,height=10 ,font=('times', 15, ' bold ')) \r\n\tmessage2.place(x=500, y=300)\r\n\r\n\r\n\tdef TrackImages():\r\n\t recognizer = cv2.face.LBPHFaceRecognizer_create()#cv2.createLBPHFaceRecognizer()\r\n\t recognizer.read(\"TrainingImageLabel\\Trainner.yml\")\r\n\t harcascadePath = \"haarcascade_frontalface_default.xml\"\r\n\t faceCascade = cv2.CascadeClassifier(harcascadePath); \r\n\t df=pd.read_csv(\"StudentDetails\\StudentDetails.csv\")\r\n\t cam = cv2.VideoCapture(0)\r\n\t font = cv2.FONT_HERSHEY_SIMPLEX \r\n\t col_names = ['Id','Name','Date','Time']\r\n\t attendance = pd.DataFrame(columns = col_names) \r\n\t while True:\r\n\t ret, im =cam.read()\r\n\t gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)\r\n\t faces=faceCascade.detectMultiScale(gray, 1.2,5) \r\n\t for(x,y,w,h) in faces:\r\n\t cv2.rectangle(im,(x,y),(x+w,y+h),(225,0,0),2)\r\n\t Id, conf = recognizer.predict(gray[y:y+h,x:x+w])\r\n\t print(\"id=\"+str(Id)+\" confidence=\"+str(conf)) \r\n\t if(conf < 50):\r\n\t ts = time.time() \r\n\t date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')\r\n\t timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')\r\n\t aa=df.loc[df['Id'] == Id]['Name'].values\r\n\t tt=str(Id)+\"-\"+aa\r\n\t aa=aa[0]\r\n\t attendance.loc[len(attendance)] = [Id,aa,date,timeStamp]\r\n\t \r\n\t else:\r\n\t Id='Unknown' \r\n\t tt=str(Id) \r\n\t #if(conf > 75):\r\n\t #noOfFile=len(os.listdir(\"ImagesUnknown\"))+1\r\n\t #cv2.imwrite(\"ImagesUnknown\\Image\"+str(noOfFile) + \".jpg\", im[y:y+h,x:x+w]) \r\n\t cv2.putText(im,str(tt),(x,y+h), font, 1,(255,255,255),2) \r\n\t attendance=attendance.drop_duplicates(subset=['Id'],keep='first') \r\n\t cv2.imshow('attendance',im) \r\n\t if (cv2.waitKey(1)==ord('q')):\r\n\t break\r\n\t ts = time.time() \r\n\t date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')\r\n\t timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')\r\n\t Hour,Minute,Second=timeStamp.split(\":\")\r\n\t global fileName;\r\n\t fileName=\"Attendance\\Attendance_\"+date+\"_\"+Hour+\"-\"+Minute+\"-\"+Second+\".csv\"\r\n\t attendance.to_csv(fileName,index=False)\r\n\t cam.release()\r\n\t cv2.destroyAllWindows()\r\n\t print(attendance)\r\n\t res=attendance\r\n\t message2.configure(text=res)\r\n\t takeImg = tk.Button(window, text=\"View attendance\", command=openf ,fg=\"red\" ,bg=\"deep sky blue\" ,width=20 ,height=2, activebackground = \"deep sky blue\" ,font=('times', 15, ' bold '))\r\n\t takeImg.place(x=150, y=500)\r\n\r\n\tdef openf():\r\n\t\tos.system(fileName)\r\n\r\n\ttrackImg = tk.Button(window, text=\"Attendance\", command=TrackImages ,fg=\"red\" ,bg=\"yellow\" ,width=20 ,height=2, activebackground = \"Red\" ,font=('times', 15, ' bold '))\r\n\ttrackImg.place(x=150, y=200)\r\n\tquitWindow = tk.Button(window, text=\"Quit\", command=window.destroy ,fg=\"black\" ,bg=\"red\" ,width=20 ,height=2, activebackground = \"Red\" ,font=('times', 15, ' bold '))\r\n\tquitWindow.place(x=500, y=200)\r\n\r\n\tcopyWrite = tk.Text(window, background=window.cget(\"background\"), borderwidth=0,font=('times', 20, 'italic bold underline'))\r\n\tcopyWrite.tag_configure(\"superscript\", offset=10)\r\n\tcopyWrite.insert(\"insert\", \"Developed by: Durgesh Patidar\")\r\n\tcopyWrite.configure(state=\"disabled\",fg=\"red\" )\r\n\tcopyWrite.pack(side=\"left\")\r\n\tcopyWrite.place(x=830, y=700)\r\n\r\n\r\n\twindow.mainloop()\r\n\r\ndef train():\r\n\twindow = tk.Tk()\r\n\twindow.title(\"Face_Recogniser\")\r\n\r\n\t#for set window size \r\n\t#window.geometry('1300x700')\r\n\r\n\t#for window background color\r\n\twindow.configure(background='white')\r\n\r\n\t#for full screen window \r\n\twindow.attributes('-fullscreen', True)\r\n\r\n\twindow.grid_rowconfigure(0, weight=1)\r\n\twindow.grid_columnconfigure(0, weight=1)\r\n\r\n\tmessag = tk.Label(window, text=\"Face-Recognition-Based-Attendance-Management-System\" ,bg=\"Green\" ,fg=\"white\" ,width=45 ,height=3,font=('times', 30, 'italic bold underline')) \r\n\r\n\tmessag.place(x=150, y=20)\r\n\r\n\tlbl = tk.Label(window, text=\"Enter scholar No\",width=20 ,height=2 ,fg=\"red\" ,bg=\"yellow\" ,font=('times', 15, ' bold ') ) \r\n\tlbl.place(x=150, y=200)\r\n\r\n\ttxt = tk.Entry(window,width=20 ,bg=\"white\" ,fg=\"red\",font=('times', 15, ' bold '))\r\n\ttxt.place(x=500, y=215)\r\n\r\n\tlbl2 = tk.Label(window, text=\"Enter Name\",width=20 ,fg=\"red\" ,bg=\"yellow\" ,height=2 ,font=('times', 15, ' bold ')) \r\n\tlbl2.place(x=150, y=300)\r\n\r\n\ttxt2 = tk.Entry(window,width=20 ,bg=\"white\" ,fg=\"red\",font=('times', 15, ' bold ') )\r\n\ttxt2.place(x=500, y=315)\r\n\r\n\t#method for clear first text box\r\n\tdef clear():\r\n\t txt.delete(0, 'end')\r\n\t#method for clear second text box\r\n\tdef clear2():\r\n\t txt2.delete(0, 'end') \r\n\t#method for checking user input scholar number is numerical or not\r\n\tdef is_number(s):\r\n\t try:\r\n\t float(s)\r\n\t return True\r\n\t except ValueError:\r\n\t pass\r\n\t \r\n\t try:\r\n\t import unicodedata\r\n\t unicodedata.numeric(s)\r\n\t return True\r\n\t except (TypeError, ValueError):\r\n\t pass\r\n\t \r\n\t return False\r\n\t#method for taking \r\n\tdef TakeImages(): \r\n\t Id=(txt.get())\r\n\t name=(txt2.get())\r\n\t name1=name.replace(\" \",\"\")\r\n\t if(is_number(Id) and name1.isalpha()):\r\n\t cam = cv2.VideoCapture(0)\r\n\t harcascadePath = \"haarcascade_frontalface_default.xml\"\r\n\t detector=cv2.CascadeClassifier(harcascadePath)\r\n\t sampleNum=0\r\n\t while(True):\r\n\t ret, img = cam.read()\r\n\t gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n\t faces = detector.detectMultiScale(gray, 1.3, 5)\r\n\t for (x,y,w,h) in faces:\r\n\t cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) \r\n\t #incrementing sample number \r\n\t sampleNum=sampleNum+1\r\n\t #saving the captured face in the dataset folder TrainingImage\r\n\t cv2.imwrite(\"TrainingImage\\ \"+name +\".\"+Id +'.'+ str(sampleNum) + \".jpg\", gray[y:y+h,x:x+w])\r\n\t #display the frame\r\n\t cv2.imshow('We taking your picture and train them',img)\r\n\t #wait for 100 miliseconds \r\n\t if cv2.waitKey(100) & 0xFF == ord('q'):\r\n\t break\r\n\t # break if the sample number is morethan 60\r\n\t elif sampleNum>60:\r\n\t break\r\n\t cam.release()\r\n\t cv2.destroyAllWindows() \r\n\t res = \"Images Saved for ID : \" + Id +\" Name : \"+ name\r\n\t row = [Id , name]\r\n\t with open('StudentDetails\\StudentDetails.csv','a+') as csvFile:\r\n\t writer = csv.writer(csvFile)\r\n\t writer.writerow(row)\r\n\t csvFile.close()\r\n\t messagebox.showinfo(title=\"alert\" ,message=res)\r\n\t else:\r\n\t if(is_number(Id)):\r\n\t messagebox.showinfo(title=\"alert\" ,message='Enter Alphabetical Name')\r\n\t if(name1.isalpha()):\r\n\t \tmessagebox.showinfo(title=\"alert\" ,message='Enter Numeric Scholar number')\r\n\r\n\tdef TrainImages():\r\n\t recognizer = cv2.face_LBPHFaceRecognizer.create()\r\n\t harcascadePath = \"haarcascade_frontalface_default.xml\"\r\n\t detector =cv2.CascadeClassifier(harcascadePath)\r\n\t faces,Id = getImagesAndLabels(\"TrainingImage\")\r\n\t recognizer.train(faces, np.array(Id))\r\n\t recognizer.save(\"TrainingImageLabel\\Trainner.yml\")\r\n\t res = \"Image Trained Successfully\"\r\n\t messagebox.showinfo(title=\"alert\" ,message=res)\r\n\r\n\tdef getImagesAndLabels(path):\r\n\t #get the path of all the files in the folder\r\n\t imagePaths=[os.path.join(path,f) for f in os.listdir(path)] \r\n\t #create empty face list\r\n\t faces=[]\r\n\t #create empty ID list\r\n\t Ids=[]\r\n\t #now looping through all the image paths and loading the Ids and the images\r\n\t for imagePath in imagePaths:\r\n\t #loading the image and converting it to gray scale\r\n\t pilImage=Image.open(imagePath).convert('L')\r\n\t #Now we are converting the PIL image into numpy array\r\n\t imageNp=np.array(pilImage,'uint8')\r\n\t #getting the Id from the image\r\n\t Id=int(os.path.split(imagePath)[-1].split(\".\")[1])\r\n\t # extract the face from the training image sample\r\n\t faces.append(imageNp)\r\n\t Ids.append(Id) \r\n\t return faces,Ids\r\n\r\n\tclearButton = tk.Button(window, text=\"Clear\", command=clear ,fg=\"red\" ,bg=\"yellow\" ,width=8 ,height=1 ,activebackground = \"Red\" ,font=('times', 15, ' bold '))\r\n\tclearButton.place(x=750, y=200)\r\n\tclearButton2 = tk.Button(window, text=\"Clear\", command=clear2 ,fg=\"red\" ,bg=\"yellow\" ,width=8 ,height=1, activebackground = \"Red\" ,font=('times', 15, ' bold '))\r\n\tclearButton2.place(x=750, y=300) \r\n\ttakeImg = tk.Button(window, text=\"Take Images\", command=TakeImages ,fg=\"red\" ,bg=\"deep sky blue\" ,width=20 ,height=2, activebackground = \"Red\" ,font=('times', 15, ' bold '))\r\n\ttakeImg.place(x=150, y=500)\r\n\ttrainImg = tk.Button(window, text=\"Train Images\", command=TrainImages ,fg=\"red\" ,bg=\"green2\" ,width=20 ,height=2, activebackground = \"Red\" ,font=('times', 15, ' bold '))\r\n\ttrainImg.place(x=500, y=500)\r\n\tquitWindow = tk.Button(window, text=\"Quit\", command=window.destroy ,fg=\"black\" ,bg=\"red\" ,width=20 ,height=2, activebackground = \"Red\" ,font=('times', 15, ' bold '))\r\n\tquitWindow.place(x=800, y=500)\r\n\r\n\tcopyWrite = tk.Text(window, background=window.cget(\"background\"), borderwidth=0,font=('times', 20, 'italic bold underline'))\r\n\tcopyWrite.tag_configure(\"superscript\", offset=10)\r\n\tcopyWrite.insert(\"insert\", \"Developed by: Durgesh Patidar\")\r\n\tcopyWrite.configure(state=\"disabled\",fg=\"red\" )\r\n\tcopyWrite.pack(side=\"left\")\r\n\tcopyWrite.place(x=830, y=700)\r\n\t \r\n\twindow.mainloop()\r\n\r\nwindows = tk.Tk()\r\n\r\nwindows.title(\"Face_Recogniser\")\r\n#for window background color\r\nwindows.configure(background='white')\r\n\r\n#for full screen window \r\nwindows.attributes('-fullscreen', True)\r\n\r\nwindows.grid_rowconfigure(0, weight=1)\r\nwindows.grid_columnconfigure(0, weight=1)\r\nmessages = tk.Label(windows, text=\"Face-Recognition-Based-Attendance-Management-System\" ,bg=\"Green\" ,fg=\"white\" ,width=45 ,height=3,font=('times', 30, 'italic bold underline')) \r\nmessages.place(x=150, y=20)\r\n\r\ntakeImgs = tk.Button(windows, text=\"Train and store records\", command=train ,fg=\"red\" ,bg=\"deep sky blue\" ,width=20 ,height=2, activebackground = \"Red\" ,font=('times', 15, ' bold '))\r\ntakeImgs.place(x=150, y=300)\r\ntrainImgs = tk.Button(windows, text=\"Attendance\", command=Attendance ,fg=\"red\" ,bg=\"green2\" ,width=20 ,height=2, activebackground = \"Red\" ,font=('times', 15, ' bold '))\r\ntrainImgs.place(x=500, y=300)\r\n\r\nquitWindow = tk.Button(windows, text=\"Quit\", command=windows.destroy ,fg=\"black\" ,bg=\"red\" ,width=20 ,height=2, activebackground = \"Red\" ,font=('times', 15, ' bold '))\r\nquitWindow.place(x=800, y=300)\r\n\r\ncopyWrite = tk.Text(windows, background=windows.cget(\"background\"), borderwidth=0,font=('times', 20, 'italic bold underline'))\r\ncopyWrite.tag_configure(\"superscript\", offset=10)\r\ncopyWrite.insert(\"insert\", \"Developed by: Durgesh Patidar\")\r\ncopyWrite.configure(state=\"disabled\",fg=\"red\" )\r\ncopyWrite.pack(side=\"left\")\r\ncopyWrite.place(x=830, y=700)\r\n\r\nwindows.mainloop()\r\n","sub_path":"FaceRecognitionAttendanceSystem/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"160394770","text":"import warnings\nimport numpy as np\nfrom sklearn.utils import check_random_state\nfrom skopt.utils import create_result, normalize_dimensions, is_listlike, is_2Dlistlike\n\nfrom . import acquisition\nfrom .bayesgpr import BayesGPR\nfrom .utils import r2_sequence, guess_priors, construct_default_kernel\nfrom bask.acquisition import evaluate_acquisitions\n\n__all__ = [\"Optimizer\"]\n\nACQUISITION_FUNC = {\n \"ei\": acquisition.ExpectedImprovement(),\n \"lcb\": acquisition.LCB(),\n \"mean\": acquisition.Expectation(),\n \"mes\": acquisition.MaxValueSearch(),\n \"pvrs\": acquisition.PVRS(),\n \"ts\": acquisition.ThompsonSampling(),\n \"ttei\": acquisition.TopTwoEI(),\n \"vr\": acquisition.VarianceReduction(),\n}\n\n\nclass Optimizer(object):\n \"\"\"Execute a stepwise Bayesian optimization.\n\n Parameters\n ----------\n dimensions : list, shape (n_dims,)\n List of search space dimensions.\n Each search dimension can be defined either as\n\n - a `(lower_bound, upper_bound)` tuple (for `Real` or `Integer`\n dimensions),\n - a `(lower_bound, upper_bound, \"prior\")` tuple (for `Real`\n dimensions),\n - as a list of categories (for `Categorical` dimensions), or\n - an instance of a `Dimension` object (`Real`, `Integer` or\n `Categorical`).\n n_points : int, default=500\n Number of random points to evaluate the acquisition function on.\n n_initial_points : int, default=10\n Number of initial points to sample before fitting the GP.\n init_strategy : string or None, default=\"r2\"\n Sampling strategy to use for the initial ``n_initial_points``.\n \"r2\" computes points using the quasirandom R2 sequence. If the value\n is None or any other string, uniform random sampling is employed.\n gp_kernel : kernel object\n The kernel specifying the covariance function of the GP. If None is\n passed, a suitable default kernel is constructed.\n Note that the kernel’s hyperparameters are estimated using MCMC during\n fitting.\n gp_kwargs : dict, optional\n Dict of arguments passed to :class:`BayesGPR`. For example,\n ``{'normalize_y': True}`` would allow the GP to normalize the output\n values before fitting.\n acq_func : string or Acquisition object, default=\"pvrs\"\n Acquisition function to use as a criterion to select new points to test.\n By default we use \"pvrs\", which is a very robust criterion with fast\n convergence.\n Should be one of\n - 'pvrs' Predictive variance reductions search\n - 'mes' Max-value entropy search\n - 'ei' Expected improvement\n - 'ttei' Top-two expected improvement\n - 'lcb' Lower confidence bound\n - 'mean' Expected value of the GP\n - 'ts' Thompson sampling\n - 'vr' Global variance reduction\n Can also be a custom :class:`Acquisition` object.\n acq_func_kwargs : dict, optional\n Dict of arguments passed to :class:`Acquisition`.\n random_state : int or RandomState or None, optional, default=None\n Pseudo random number generator state used for random uniform sampling\n from lists of possible values instead of scipy.stats distributions.\n\n Attributes\n ----------\n Xi : list\n Points at which objective has been evaluated.\n yi : scalar\n Values of objective at corresponding points in `Xi`.\n space : Space\n An instance of :class:`skopt.space.Space`. Stores parameter search\n space used to sample points, bounds, and type of parameters.\n gp : BayesGPR object\n The current underlying GP model, which is used to calculate the\n acquisition function.\n gp_priors : list of callables\n List of prior distributions for the kernel hyperparameters of the GP.\n Each callable returns the logpdf of the prior distribution.\n n_initial_points_ : int\n Number of initial points to sample\n noisei : list of floats\n Additional pointwise noise which is added to the diagonal of the\n kernel matrix\n \"\"\"\n def __init__(\n self,\n dimensions,\n n_points=500,\n n_initial_points=10,\n init_strategy=\"r2\",\n gp_kernel=None,\n gp_kwargs=None,\n gp_priors=None,\n acq_func=\"pvrs\",\n acq_func_kwargs=None,\n random_state=None,\n **kwargs\n ):\n self.rng = check_random_state(random_state)\n\n if callable(acq_func):\n self.acq_func = acq_func\n else:\n self.acq_func = ACQUISITION_FUNC[acq_func]\n if acq_func_kwargs is None:\n acq_func_kwargs = dict()\n self.acq_func_kwargs = acq_func_kwargs\n\n self.space = normalize_dimensions(dimensions)\n self._n_initial_points = n_initial_points\n self.n_initial_points_ = n_initial_points\n self.init_strategy = init_strategy\n if self.init_strategy == \"r2\":\n self._initial_points = self.space.inverse_transform(\n r2_sequence(n=n_initial_points, d=self.space.n_dims)\n )\n self.n_points = n_points\n\n if gp_kwargs is None:\n gp_kwargs = dict()\n if gp_kernel is None:\n # For now the default kernel is not adapted to the dimensions,\n # which is why a simple list is passed:\n gp_kernel = construct_default_kernel(\n list(range(self.space.transformed_n_dims))\n )\n\n self.gp = BayesGPR(\n kernel=gp_kernel,\n random_state=self.rng.randint(0, np.iinfo(np.int32).max),\n **gp_kwargs,\n )\n # We are only able to guess priors now, since BayesGPR can add\n # another WhiteKernel, when noise is set to \"gaussian\":\n if gp_priors is None:\n gp_priors = guess_priors(self.gp.kernel)\n self.gp_priors = gp_priors\n\n self.Xi = []\n self.yi = []\n self.noisei = []\n self._next_x = None\n\n def ask(self, n_points=1):\n if n_points > 1:\n raise NotImplementedError(\n \"Returning multiple points is not implemented yet.\"\n )\n if (\n self._n_initial_points > 0\n ): # TODO: Make sure estimator is trained here always\n if self.init_strategy == \"r2\":\n return self._initial_points[self._n_initial_points - 1]\n return self.space.rvs()\n else:\n if not self.gp.kernel_:\n raise RuntimeError(\n \"Initialization is finished, but no model has been fit.\"\n )\n return self._next_x\n\n def tell(\n self,\n x,\n y,\n noise_vector=None,\n fit=True,\n replace=False,\n n_samples=0,\n gp_samples=100,\n gp_burnin=10,\n progress=False,\n ):\n # if y isn't a scalar it means we have been handed a batch of points\n\n # TODO (noise vector):\n # 1. Replace case should be easy\n # 2. Add case should add noise values to list\n # -> What if noise_vector is None? (have to set noise to 0)\n if replace:\n self.Xi = []\n self.yi = []\n self.noisei = []\n self._n_initial_points = self.n_initial_points_\n if is_listlike(y) and is_2Dlistlike(x):\n self.Xi.extend(x)\n self.yi.extend(y)\n if noise_vector is None:\n noise_vector = [0.0] * len(y)\n elif not is_listlike(noise_vector) or len(noise_vector) != len(y):\n raise ValueError(\n f\"Vector of noise variances needs to be of equal length as `y`.\"\n )\n self.noisei.extend(noise_vector)\n self._n_initial_points -= len(y)\n elif is_listlike(x):\n self.Xi.append(x)\n self.yi.append(y)\n if noise_vector is None:\n noise_vector = 0.0\n elif is_listlike(noise_vector):\n raise ValueError(\n f\"Vector of noise variances is a list, while tell only received one datapoint.\"\n )\n self.noisei.append(noise_vector)\n self._n_initial_points -= 1\n else:\n raise ValueError(\n f\"Type of arguments `x` ({type(x)}) and `y` ({type(y)}) \"\n \"not compatible.\"\n )\n\n if fit and self._n_initial_points <= 0:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n if self.gp.pos_ is None or replace:\n self.gp.fit(\n self.space.transform(self.Xi),\n self.yi,\n noise_vector=np.array(self.noisei),\n priors=self.gp_priors,\n n_desired_samples=gp_samples,\n n_burnin=gp_burnin,\n progress=progress,\n )\n else:\n self.gp.sample(\n self.space.transform(self.Xi),\n self.yi,\n noise_vector=np.array(self.noisei),\n priors=self.gp_priors,\n n_desired_samples=gp_samples,\n n_burnin=gp_burnin,\n progress=progress,\n )\n\n X = self.space.transform(\n self.space.rvs(n_samples=self.n_points, random_state=self.rng)\n )\n acq_values = evaluate_acquisitions(\n X=X,\n gpr=self.gp,\n acquisition_functions=(self.acq_func,),\n n_samples=n_samples,\n progress=False,\n random_state=self.rng.randint(0, np.iinfo(np.int32).max),\n **self.acq_func_kwargs,\n ).flatten()\n\n self._next_x = self.space.inverse_transform(\n X[np.argmax(acq_values)].reshape((1, -1))\n )[0]\n\n return create_result(self.Xi, self.yi, self.space, self.rng, models=[self.gp])\n\n def run(self, func, n_iter=1, n_samples=5, gp_burnin=10):\n for _ in range(n_iter):\n x = self.ask()\n self.tell(x, func(x), n_samples=n_samples, gp_burnin=gp_burnin)\n\n return create_result(self.Xi, self.yi, self.space, self.rng, models=[self.gp])\n","sub_path":"bask/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":10406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"465019420","text":"from typing import TYPE_CHECKING\n\nimport urwid\n\nif TYPE_CHECKING:\n from scronsole.widgets.main_screen import MainScreen\n\n\nclass MainMenu(urwid.WidgetWrap):\n def item_chosen(self, _button, user_info):\n self.main_screen.show_server_screen(user_info)\n\n def __init__(self, main_screen: \"MainScreen\"):\n super().__init__(\"\")\n self.main_screen = main_screen\n choices = main_screen.config.get_servers()\n body = [urwid.Text(\"Server\"), urwid.Divider()]\n for c in choices:\n label = c.host\n if not label:\n label = \"screeps.com\"\n if c.ptr:\n label += \" (ptr)\"\n button = urwid.Button(label)\n urwid.connect_signal(button, 'click', self.item_chosen, c)\n body.append(urwid.AttrMap(button, None, focus_map='reversed'))\n\n box = urwid.LineBox(urwid.ListBox(urwid.SimpleFocusListWalker(body)))\n self._w = urwid.Overlay(box, urwid.SolidFill(u'\\N{MEDIUM SHADE}'), align='center', width=('relative', 50),\n valign='middle', height=('relative', 50),\n min_width=20, min_height=4)\n","sub_path":"scronsole/widgets/main_menu.py","file_name":"main_menu.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"177237543","text":"from pygame_standard.window import Window\nfrom pygame_standard.content import Screen, VerticalSlider\n\n\nsize = (100,200)\nwindow = Window(size)\n\ninterface_screen = Screen(screen_id=\"interface\")\n\npos = (50,50)\nlength = 100\nslider = VerticalSlider(pos,length,\"test_slider\")\ninterface_screen.add_component(slider)\nwindow.add_screen(interface_screen)\n\nwindow.run()\n\n\n","sub_path":"examples/slider_example.py","file_name":"slider_example.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"44898208","text":"import os\nfrom collections import defaultdict\n\nimport cv2\nimport numpy as np\nfrom tqdm import tqdm\nfrom argparse import ArgumentParser\n\ndef compute(path, save_dir):\n file_names = os.listdir(path)\n file_name_green = []\n file_name_none = []\n for file_name in tqdm(file_names):\n try:\n img = cv2.imread(os.path.join(path, file_name))\n per_image_Bmean = np.mean(img[:, :, 0])\n per_image_Gmean = np.mean(img[:, :, 1])\n per_image_Rmean = np.mean(img[:, :, 2])\n if per_image_Bmean > 65 and per_image_Gmean > 65 and per_image_Rmean > 65:\n file_name_green.append(file_name)\n else:\n file_name_none.append(file_name)\n except:\n print(os.path.join(path, file_name))\n continue\n file = open(os.path.join(save_dir, path.split('/')[-1]+'_green.txt'), 'w')\n\n for filename in sorted(file_name_green):\n file.write(str(filename+'\\n'))\n file.close()\n file = open(os.path.join(save_dir, path.split('/')[-1]+'_normal.txt'), 'w')\n for filename in sorted(file_name_none):\n file.write(str(filename+'\\n'))\n file.close()\n\ndef compute_unlabeled(path='/raid/chenby/person_rID/train/images', save_dir='/raid/chenby/person_rID/train',\n unlabel_txt='/raid/chenby/person_rID/train/unlabel.txt'):\n with open(unlabel_txt, \"r\") as f:\n file_names = f.readlines()\n file_name_green = []\n file_name_none = []\n for file_name in tqdm(file_names):\n img = cv2.imread(os.path.join(path, file_name))\n per_image_Bmean = np.mean(img[:, :, 0])\n per_image_Gmean = np.mean(img[:, :, 1])\n per_image_Rmean = np.mean(img[:, :, 2])\n if per_image_Bmean > 65 and per_image_Gmean > 65 and per_image_Rmean > 65:\n file_name_green.append(file_name)\n else:\n file_name_none.append(file_name)\n file = open(os.path.join(save_dir, path.split('/')[-1]+'_green.txt'), 'w')\n\n for filename in sorted(file_name_green):\n file.write(str(filename+'\\n'))\n file.close()\n file = open(os.path.join(save_dir, path.split('/')[-1]+'_normal.txt'), 'w')\n for filename in sorted(file_name_none):\n file.write(str(filename+'\\n'))\n file.close()\n\ndef get_unlabeled_data(label_txt='/raid/chenby/person_rID/train/label.txt',\n unlabel_txt='/raid/chenby/person_rID/train/unlabel.txt',\n root_path='/raid/chenby/person_rID/train/images'):\n images = os.listdir(root_path)\n with open(label_txt, \"r\") as f:\n labeled_images = f.readlines()\n labels = {}\n for line in labeled_images:\n name, id = line.split(':')\n labels[name] = id\n print(len(images), len(labeled_images))\n unlabeled_images = []\n for image in images:\n if image not in labels:\n unlabeled_images.append(image)\n print(len(images), len(labeled_images), len(unlabeled_images))\n with open(unlabel_txt, \"w\") as f:\n for line in unlabeled_images:\n f.write(line + '\\n')\n\n with open(unlabel_txt, \"r\") as f:\n unlabeled_images = f.readlines()\n print(len(unlabeled_images))\n\ndef select_validation_data(root_path='/raid/chenby/person_rID/2019/REID2019_A',\n train_txt='/raid/chenby/person_rID/2019/REID2019_A/train_list.txt'):\n print(len(os.listdir(root_path + '/train')))\n with open(train_txt, \"r\") as f:\n lines = f.readlines()\n labels_dict = defaultdict(list)\n for line in lines:\n img_name, img_label = [i for i in line.replace('\\n', '').split()]\n labels_dict[img_label].append(img_name.replace('train/', ''))\n\n query = []\n gallery = []\n for pid, img_name in labels_dict.items():\n if len(img_name) < 5:\n gallery += img_name\n else:\n query += img_name[:1]\n gallery += img_name[1:]\n\n print(len(query), len(gallery))\n\n file = open(os.path.join(root_path, 'query.txt'), 'w')\n\n for filename in sorted(query):\n file.write(str(filename + '\\n'))\n file.close()\n file = open(os.path.join(root_path, 'gallery.txt'), 'w')\n for filename in sorted(gallery):\n file.write(str(filename + '\\n'))\n file.close()\n\nif __name__ == '__main__':\n parser = ArgumentParser(description='vis txt result Tool')\n parser.add_argument('--data_dir_query', help='dir to the query datasets')\n parser.add_argument('--data_dir_gallery', help='dir to the gallery datasets')\n parser.add_argument('--save_dir', help='dir to save the generated txt file')\n args = parser.parse_args()\n compute(args.data_dir_query, args.save_dir)\n compute(args.data_dir_gallery, args.save_dir)\n\n # get_unlabeled_data()\n # select_validation_data()\n\n","sub_path":"divided_dataset.py","file_name":"divided_dataset.py","file_ext":"py","file_size_in_byte":4769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"167456035","text":"import numpy as np\n\ndef perceptron_dual(x_input,y_input,gram):\n alpha_star = np.zeros(y_input.shape[0]) # alpha矩阵,x_input为n行矩阵\n b_star = 0\n learning_rate = 1\n classification_right_count = 0 # 正确分类计数\n while True:\n for i in range(x_input.shape[0]):\n y = y_input[i]\n # 判断是否满足条件\n value = (np.sum(gram[i]*(alpha_star*y_input)) + b_star)\n if y*value <= 0:\n alpha_star[i] += learning_rate\n b_star += y\n print(\"update , alpha =\", alpha_star)\n print(\"update , b_star = \",b_star)\n else:\n classification_right_count += 1\n # 若都已经分类正确,则退出\n if classification_right_count >= y_input.shape[0]: # y_input,行\n print(\"end, alpha = \",alpha_star)\n print(\"end, b_star = \" , b_star)\n break\n # 否则,继续循环\n else:\n classification_right_count = 0\n\n# 1.准备数据\ndata_coord = np.asarray(((3, 3), (4, 3), (1, 1)))\ndata_label = np.asarray((1, 1, -1))\n# 2.计算gram矩阵\nx = np.asarray([data_coord[0],data_coord[1],data_coord[2]])\ngram = np.matmul(x,x.T)\nprint(\"gram = \",gram)\n# 3.感知机 对偶形式求解\nperceptron_dual(data_coord,data_label,gram)","sub_path":"1.perceptron/perceptron_dual.py","file_name":"perceptron_dual.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"514293160","text":"import numpy as np\nimport h5py\nimport os\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--f1\", type=str, default='uc_lf_data')\nparser.add_argument(\"--f2\", type=str, default='test')\nparser.add_argument(\"--f3\", type=str, default='mix_data')\ncfg = parser.parse_args()\n\nf1, f2, f3 = cfg.f1+'.hdf5',cfg.f2+'.hdf5',cfg.f3+'.hdf5'\ndata1 = h5py.File(f1,\"r\")\ndata2 = h5py.File(f2,\"r\")\n\nprint('copy large file...')\nif len(list(data1.keys()))>= len(list(data2.keys())):\n\tos.system('cp '+f1+' '+f3)\n\tdata1.close()\n\trest = data2\nelse:\n\tos.system('cp '+f2+' '+f3)\n\tdata2.close()\n\trest = data1\n\ndata3 = h5py.File(f3,\"r+\")\n\n# for key in ucsd:\n# \tdata = ucsd[key][:]\n# \tmix.create_dataset(key, data=data, dtype=np.uint8, compression=9)\nprint('writing...')\nfor key in rest:\n\tdata = rest[key][:]\n\t# s,h,w,_=data.shape\n\t# data = np.resize(data,(9,9,h,w,3))\n\t# data = np.resize(data[1:-1,1:-1,...], (49,h,w,3))\n\t# mix[key] = data\n\t# print(data.shape)\n\tdata3.create_dataset(key, data=data, dtype=np.uint8, compression=9)\n\ndata3.close()","sub_path":"data/mix_data.py","file_name":"mix_data.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"328211266","text":"from itertools import islice\nfrom math import ceil\n\nfrom instaloader import Instaloader, Post\n\nSHORTCODE = '...' # post to download from\nX_percentage = 10 # percentage of comment that should be downloaded\n\nL = Instaloader()\n\npost = Post.from_shortcode(L.context, SHORTCODE)\ncomments_sorted_by_likes = sorted(post.get_comments(),key=lambda p: p.likes_count, reverse=True)\n\nfor comment in islice(comments_sorted_by_likes, ceil(post.comments * X_percentage / 100)):\n print(comment.text)\n","sub_path":"docs/codesnippets/457_top_x_comments_of_post.py","file_name":"457_top_x_comments_of_post.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"478097214","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n# Configuration\r\nimport os\r\nfrom config import Config\r\nwith open('/home/webmaster/dw_web/dicci/src/custom.cfg', 'r') as f:\r\n cfg = Config(f)\r\n\r\nimport sys\r\nsys.path.append(cfg.root)\r\nfrom dicci_src import Run\r\nrun = Run()\r\n\r\n# Import Model\r\nfpath_ner_corpus = os.path.join(cfg.database, cfg.fdir_ner_corpus, 'ner_corpus_20200318_223912.pk')\r\nfpath_ner_model = os.path.join(cfg.database, cfg.fdir_ner_model, 'ner_model_20200318_233801.h5')\r\nner_model = run.develop_ner_model(\r\n fpath_ner_model=fpath_ner_model,\r\n fpath_ner_corpus=fpath_ner_corpus,\r\n do_train=False\r\n)\r\nner_model.fit()\r\n\r\n# Test\r\ntext = 'Depth of bituminous pavement should be less than 5 mm in average.'\r\nsent = text.split(' ')\r\nner_result = ner_model.predict(sent)\r\n\r\nprint('>>INPUT:\\n{}'.format(ner_result.sent))\r\nprint('>>OUTPUT:\\n{}'.format(ner_result.pred))\r\n\r\nprint()\r\nprint('>>RESULT (NON): {}'.format(', '.join(ner_result.result['NON'])))\r\nprint('>>RESULT (ORG): {}'.format(', '.join(ner_result.result['ORG'])))\r\nprint('>>RESULT (ACT): {}'.format(', '.join(ner_result.result['ACT'])))\r\nprint('>>RESULT (ELM): {}'.format(', '.join(ner_result.result['ELM'])))\r\nprint('>>RESULT (STD): {}'.format(', '.join(ner_result.result['STD'])))\r\nprint('>>RESULT (REF): {}'.format(', '.join(ner_result.result['REF'])))","sub_path":"test/standard_extraction.py","file_name":"standard_extraction.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"6060890","text":"# -*- coding: utf-8 -*-\n# TwoSampleTTestPValueTwoTailedEqualVariance\n# mu=70\nfrom pandas import Series\nimport scipy.stats as st\nx=Series([71, 69, 67, 68, 73, 72, 71, 71, 68, 72, 69, 72])\ny=Series([71, 67, 73, 71, 68, 69])\np_value=st.ttest_ind(a=x, b=y, equal_var=True).pvalue\nresult=0.05 0.05\")\n print(\"Accept null hypothesis\")\nif result==False:\n print(\"P-Value:\", p_value, \"< 0.05\")\n print(\"Reject null hypothesis\")\n# P-Value: 0.7063836738114528 > 0.05\n# Accept null hypothesis","sub_path":"fig/TwoSampleTTestPValueTwoTailedEqualVariance.py","file_name":"TwoSampleTTestPValueTwoTailedEqualVariance.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"277307910","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom back_end.common.QRCode import qr_encode, qr_decode\nfrom django.conf import settings\nfrom uuid import uuid4\nimport os\nfrom back_end.common.Renderer import Renderer\nfrom fpdf import Template\nfrom PIL import Image\nfrom pdf2image import convert_from_path\nfrom rest_framework.decorators import api_view\nimport cv2\nimport numpy as np\nimport json\n\nfrom django.core.files.base import ContentFile\n\ndef detect_markers():\n # Read image\n im = cv2.imread(\"./markers.png\", cv2.IMREAD_GRAYSCALE)\n im = cv2.resize(im, (300, 400))\n # Setup SimpleBlobDetector parameters.\n params = cv2.SimpleBlobDetector_Params()\n\n params.filterByCircularity = True\n params.maxCircularity = .85\n params.minCircularity = .785\n # Create a detector with the parameters\n ver = (cv2.__version__).split('.')\n if int(ver[0]) < 3:\n detector = cv2.SimpleBlobDetector(params)\n else:\n detector = cv2.SimpleBlobDetector_create(params)\n\n # Detect blobs.\n keypoints = detector.detect(im)\n im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]), (0, 0, 255),\n cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n\n # Show blobs\n cv2.imshow(\"Keypoints\", im_with_keypoints)\n cv2.waitKey(0)\n\ndef crop(image_path, coords, saved_location):\n \"\"\"\n @param image_path: The path to the image to edit\n @param coords: A tuple of x/y coordinates (x1, y1, x2, y2)\n @param saved_location: Path to save the cropped image\n \"\"\"\n image_obj = convert_from_path(image_path)[0]\n width, height = image_obj.size\n print(width, height)\n xScale = width/215.9\n yScale = height/279.4\n margin = 5\n arr = [coords[0] * xScale + margin, coords[1] * yScale + margin, coords[2] * xScale -margin , coords[3] * yScale -margin]\n cropped_image = image_obj.crop(tuple(arr))\n cropped_image.save(saved_location)\n cropped_image.show()\n\ndef crop_textboxes(template, elements, out):\n for el in elements:\n if el['type'] == 'B':\n coords = (el['x1'] ,el['y1'], el['x2'], el['y2'])\n outFN = out + '/' + el['name'] + '.png'\n crop(template, coords, outFN)\n\ndef processDocument(doc_path, elements):\n image_obj = convert_from_path(doc_path)[0]\n image_obj.save(doc_path)\n crop_textboxes(doc_path, elements, './back_end/crops')\n\nelements_ = []\n@api_view(['GET', 'POST', ])\ndef upload(request, format=None):\n uploaded_filename = request.FILES['file'].name\n # save the uploaded file inside that folder.\n full_filename = './back_end/crops/uploads/' + uploaded_filename\n fout = open(full_filename, 'wb+')\n # Iterate through the chunks.\n file_content = ContentFile(request.FILES['file'].read())\n for chunk in file_content.chunks():\n fout.write(chunk)\n fout.close()\n\n base_name = uploaded_filename.split('.')[0]\n elements = loadElements('./back_end/crops/uploads/' + base_name + '.json')\n processDocument(full_filename, elements)\n return Response({'uuid': \"Suss\"})\n\ndef saveElements( elements, path):\n with open(path, 'w') as outfile:\n json.dump(elements, outfile)\n\ndef loadElements(path):\n with open(path) as f:\n data = json.load(f)\n return data\n\nclass FormBuilderView(APIView):\n\n def get(self, request):\n uuid = str(uuid4())\n media_name = uuid + '.png'\n out_path = os.path.join(settings.MEDIA_ROOT, media_name)\n qr_encode(uuid, out_path)\n return Response({'uuid': uuid, 'qr': settings.MEDIA_URL + media_name})\n\n def post(self, request):\n renderer = Renderer()\n result = renderer.render(request.data)\n form_uuid = result['uuid']\n elements = result['items']\n saveElements(elements, './back_end/crops/uploads/' + form_uuid +'.json')\n media_name = form_uuid + '.png'\n qrcode = os.path.join(settings.MEDIA_ROOT, media_name)\n f = Template(format=\"letter\", elements=elements,title=\"DocuScan\")\n f.add_page()\n f['company_logo'] = qrcode\n f.render(\"./template.pdf\")\n os.system('open ' + './template.pdf')\n return Response({'uuid':\"Suss\"})\n\n\n","sub_path":"back_end/back_end/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"530083919","text":"#!/usr/bin/env python3\n\n\"\"\"This is a wrapper script around the Saxon command line interface.\nIt attempts to make sure that the classpath is correct and that third\nparty and other libraries are available.\"\"\"\n\nimport os\nimport sys\nimport json\nimport shutil\nimport subprocess\nfrom pathlib import Path\nfrom xml.dom.minidom import parseString, Node\nimport requests\n\n\nclass JavaClassRunner:\n \"\"\"Executes a java process based on a set of parameters read from a\n configuration file. It uses `mvn` to download dependencies and constructs\n a class path that contains the transitive closure of all dependencies\n rooted at the modules listed in `maven-packages`.\n \"\"\"\n # Yes, I have a lot of instance attributes. I'm also using camelCase names,\n # which aren't the Pythonic way, but they are the POM way. And I know some\n # methods could be functions.\n # pylint: disable=R0902,C0103,R0201\n\n\n def __init__(self):\n # The ~ just makes it sort last\n self.depkey = \"~depends\"\n self.seeds = set([\"@@PACKAGE_LIST@@\"])\n self.config = {\n \"maven-local\": str(Path.home()) + \"/.m2/repository\",\n \"maven-repositories\": [\"https://repo1.maven.org/maven2\",\n \"https://maven.restlet.com\"],\n \"maven-packages\": [],\n \"pin-packages\": [\"xml-apis:xml-apis:1.4.01\"],\n \"args\": [\"-init:org.docbook.extensions.xslt.Register\"],\n \"classpath\": [],\n \"class\": \"net.sf.saxon.Transform\"\n }\n self.mvn_dep = \"org.apache.maven.plugins:maven-dependency-plugin:2.1:get\"\n self._cp = {}\n self._seen = {}\n\n self.config_file = str(Path.home()) + \"/.docbook-xsltng.json\"\n self.verbose = False\n self.debug = False\n self._mvn = None\n self._java = None\n self._app_args = []\n self._parse_args()\n\n try:\n with open(self.config_file, \"r\") as depfile:\n self.config = json.load(depfile)\n except FileNotFoundError:\n with open(self.config_file, \"w\") as depfile:\n depfile.write(json.dumps(self.config, indent=2, sort_keys=True))\n\n self.verbose = self.verbose or self.config.get(\"verbose\", False)\n\n if not self._mvn:\n self._mvn = self.config.get(\"mvn\", shutil.which(\"mvn\"))\n if not self._mvn:\n raise RuntimeError(\"The Maven 'mvn' command is not on your path.\")\n\n if not self._java:\n self._java = self.config.get(\"java\", shutil.which(\"java\"))\n if not self._java:\n raise RuntimeError(\"The 'java' command is not on your path.\")\n\n for key in [\"maven-local\", \"maven-repositories\"]:\n if not key in self.config:\n raise RuntimeError(f\"Configuration must specify '{key}'\")\n\n for pkg in self.config.get(\"maven-packages\", []):\n self.seeds.add(pkg)\n\n # Unify the config file with the \n\n if \"class\" not in self.config:\n raise RuntimeError(f\"Configuration must specify 'class'\")\n\n if \"verbose\" not in self.config:\n self.config[\"verbose\"] = False\n\n if self.depkey not in self.config:\n self.config[self.depkey] = {}\n\n def _parse_args(self):\n # Can't use any of the nice arg parsers here because these\n # are mostly args for some other application\n done = False\n for arg in sys.argv[1:]:\n if done:\n self._app_args.append(arg)\n else:\n if arg == \"--\":\n done = True\n elif arg.startswith(\"--config:\"):\n self.config_file = arg[9:]\n elif arg.startswith(\"--mvn:\"):\n self._mvn = arg[6:]\n elif arg.startswith(\"--java:\"):\n self._java = arg[7:]\n elif arg == \"--verbose\":\n self.verbose = True\n elif arg == \"--debug\":\n self.debug = True\n else:\n self._app_args.append(arg)\n done = True\n\n def _message(self, message):\n if self.verbose:\n print(message)\n\n def _pom(self, repo, groupId, artifactId, version):\n groupPath = groupId.replace(\".\", \"/\")\n uri = f\"{repo}/{groupPath}/{artifactId}/{version}/{artifactId}-{version}.pom\"\n # print(uri)\n resp = requests.get(uri)\n if resp.status_code == 200:\n return parseString(resp.text)\n return None\n\n def _get_value(self, node, tag):\n for child in node.childNodes:\n if child.nodeType == Node.ELEMENT_NODE and child.tagName == tag:\n return child.childNodes[0].nodeValue\n return None\n\n def _jar(self, groupId, artifactId, version):\n mavenLocal = self.config[\"maven-local\"]\n jardir = groupId.replace(\".\", \"/\")\n jardir = f\"{mavenLocal}/{jardir}/{artifactId}/{version}\"\n jarfile = f\"{jardir}/{artifactId}-{version}.jar\"\n if os.path.exists(jarfile):\n return jarfile\n return None\n\n def _skip(self, groupId, artifactId, version):\n return (groupId is None or \"${\" in groupId\n or artifactId is None or \"R{\" in artifactId\n or version is None or \"${\" in version)\n\n def _install(self, groupId, artifactId, version):\n # I'm not really sure how mvn works.\n if self._skip(groupId, artifactId, version):\n self._message(f\"Skipping {groupId}:{artifactId}:{version}\")\n return \"SKIPPED\"\n\n for repo in self.config[\"maven-repositories\"]:\n run = [\"mvn\",\n self.mvn_dep,\n f\"-DrepoUrl={repo}\",\n f\"-Dartifact={groupId}:{artifactId}:{version}\"]\n returnCode = subprocess.run(run, capture_output=True, check=True)\n if returnCode == 0:\n break\n\n jar = self._jar(groupId, artifactId, version)\n if not jar:\n self._message(f\"Failed {groupId}:{artifactId}:{version}\")\n return \"NOTFOUND\"\n\n self._message(f\"Downloaded {groupId}:{artifactId}:{version}\")\n return jar\n\n def _save_config(self):\n with open(self.config_file, \"w\") as depfile:\n depfile.write(json.dumps(self.config, indent=2, sort_keys=True))\n\n def _update_dependencies(self, groupId, artifactId, version):\n if groupId not in self.config[self.depkey]:\n self.config[self.depkey][groupId] = {}\n\n if artifactId not in self.config[self.depkey][groupId]:\n self.config[self.depkey][groupId][artifactId] = {}\n\n if version in self.config[self.depkey][groupId][artifactId]:\n return\n\n jar = self._jar(groupId, artifactId, version)\n if not jar:\n jar = self._install(groupId, artifactId, version)\n\n pkgconfig = {}\n pkgconfig[\"jar\"] = jar\n pkgconfig[\"dependencies\"] = []\n self.config[self.depkey][groupId][artifactId][version] = pkgconfig\n\n if self._skip(groupId, artifactId, version):\n self._message(f\"Skipping: {groupId}:{artifactId}:{version}\")\n return\n\n # Get the dependencies from the POM\n for repo in self.config[\"maven-repositories\"]:\n pom = self._pom(repo, groupId, artifactId, version)\n if pom:\n break\n\n if not pom:\n print(f\"Error: failed to get {artifactId} POM for {groupId} version {version}\")\n return\n\n self._message(f\"Checking {groupId}:{artifactId}:{version}\")\n pkgconfig[\"dependencies\"] = self._artifact_dependencies(pom)\n self.config[self.depkey][groupId][artifactId][version] = pkgconfig\n self._save_config()\n\n def _artifact_dependencies(self, pom):\n # Note: we blindly assume the POM will be formatted the way we expect\n deps = []\n for dependencies in pom.getElementsByTagName(\"dependencies\"):\n for node in dependencies.getElementsByTagName(\"dependency\"):\n depGroupId = self._get_value(node, \"groupId\")\n depArtifactId = self._get_value(node, \"artifactId\")\n depVersion = self._get_value(node, \"version\")\n #print(depGroupId, depArtifactId, depVersion)\n if depGroupId is None or depArtifactId is None or depVersion is None:\n pass\n else:\n scope = self._get_value(node, \"scope\")\n if not scope or scope != \"test\":\n depkey = f\"{depGroupId}:{depArtifactId}:{depVersion}\"\n deps.append(depkey)\n self._update_dependencies(depGroupId, depArtifactId, depVersion)\n return deps\n\n def download_dependencies(self):\n \"\"\"Download all missing packages, including packages that any of the\n downloaded packages depend on.\n \"\"\"\n for package in self.seeds:\n group, artifact, version = package.split(\":\")\n self._update_dependencies(group, artifact, version)\n for package in self.config[\"pinned-packages\"]:\n group, artifact, version = package.split(\":\")\n self._update_dependencies(group, artifact, version)\n\n def _higher_version(self, curver, newver):\n if curver == newver:\n return False\n\n curlist = curver.split(\".\")\n newlist = newver.split(\".\")\n while curlist and newlist:\n cur = curlist[0]\n curlist = curlist[1:]\n new = newlist[0]\n newlist = newlist[1:]\n\n if cur != new:\n if cur.isdigit() and new.isdigit():\n #print(f\"{curver}/{newver}: {cur}/{new}: {int(new)>int(cur)}\")\n return int(new) > int(cur)\n # Meh. We could try to do better, but..\n #print(f\"{curver}/{newver}: {cur}/{new}: {new>cur}\")\n return new > cur\n\n # If there are more pieces in the new version, call it newer\n return len(newlist) > 0\n\n def _add_to_classpath(self, package):\n # I don't think reorganizing this method into smaller pieces\n # would make it easier to understand. It's just messy.\n # pylint: disable=R0912\n\n if package in self._seen:\n return\n self._seen[package] = True\n\n group, artifact, version = package.split(\":\")\n\n try:\n if group not in self._cp:\n self._cp[group] = {}\n if artifact not in self._cp[group]:\n self._cp[group][artifact] = {}\n\n if version in self._cp[group][artifact]:\n # We already have this version of this package\n return\n\n # [expletive] xml-apis:xml-apis:2.x is not\n # compatible with xml-apis:xml-apis:1.x so we\n # need a provision for pinning versions. Sigh.\n basepkg = f\"{group}:{artifact}\"\n usever = None\n for pkg in self.config.get(\"pinned-packages\", []):\n if pkg.startswith(basepkg):\n usever = pkg[len(basepkg)+1:]\n\n if usever:\n pass\n elif not self._cp[group][artifact]:\n usever = version\n else:\n # Sigh again. We've already got a jar for this artifact\n # but we're being asked to add another. Pick the one\n # with the higher version number. N.B. There should\n # only ever be one key in the artifact dict\n curver = list(self._cp[group][artifact].keys())[0]\n if self._higher_version(curver, version):\n usever = version\n else:\n usever = curver\n\n if usever in self._cp[group][artifact]:\n # We already have this version of this package\n return\n\n jar = self.config[self.depkey][group][artifact][usever][\"jar\"]\n if jar not in (\"SKIPPED\", \"NOTFOUND\"):\n self._cp[group][artifact] = {}\n self._cp[group][artifact][usever] = jar\n except KeyError:\n # I guess we don't have one\n pass\n\n # Note that we could end up with more things on the classpath\n # than we need. If, for example, we add x:y for version 1.4 of\n # some package and then later we replace 1.4 with 1.5.2 which\n # no longer has a dependency on x:y. I'm assuming that'll be\n # harmless.\n if \"dependencies\" in self.config[self.depkey][group][artifact][version]:\n for dep in self.config[self.depkey][group][artifact][version][\"dependencies\"]:\n self._add_to_classpath(dep)\n\n def classpath(self):\n \"\"\"Compute the class path for this run.\"\"\"\n for package in self.seeds:\n self._add_to_classpath(package)\n\n cplist = []\n for group in self._cp:\n for archive in self._cp[group]:\n for version in self._cp[group][archive]:\n cplist.append(self._cp[group][archive][version])\n\n # Where is the distribution jar file?\n libpath = os.path.abspath(__file__)\n libpath = libpath[0:libpath.rfind(os.sep)] # strip /docbook\n libpath = libpath[0:libpath.rfind(os.sep)] # strip /bin\n libpath = os.sep.join([libpath, \"lib/docbook-xslTNG-0.1.14.jar\"])\n cplist.append(libpath)\n\n for path in self.config.get(\"classpath\", []):\n cplist.append(path)\n\n return os.pathsep.join(cplist)\n\n def args(self):\n \"\"\"Compute the java arguments.\"\"\"\n args = []\n argset = set()\n for arg in self._app_args:\n args.append(arg)\n if \":\" in arg:\n argset.add(arg[0:arg.index(\":\")])\n else:\n argset.add(arg)\n for arg in self.config.get(\"args\", []):\n if \":\" in arg:\n key = arg[0:arg.index(\":\")]\n else:\n key = arg\n if key not in argset:\n args.append(arg)\n return args\n\n def run(self):\n \"\"\"Run the process.\"\"\"\n cp = self.classpath()\n args = self.args()\n jopt = self.config.get(\"java-options\", [])\n if self.debug:\n print(self._java)\n for item in jopt:\n print(f\"\\t{item}\")\n print(\"-cp\")\n for item in cp.split(os.pathsep):\n print(f\"\\t{item}\")\n print(self.config['class'])\n for item in args:\n print(f\"\\t{item}\")\n else:\n cmd = [self._java] + jopt + [\"-cp\", cp] + [self.config['class']] + args\n subprocess.call(cmd)\n\nif __name__ == \"__main__\":\n # I'm perfectly happy with the name 'docbook'\n # pylint: disable=C0103\n\n # N.B. JavaClassRunner parses sys.argv!\n docbook = JavaClassRunner()\n docbook.download_dependencies()\n docbook.run()\n","sub_path":"src/bin/docbook.py","file_name":"docbook.py","file_ext":"py","file_size_in_byte":15025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"159604116","text":"#Webserver\nimport tornado.ioloop\nimport tornado.web\n\n# Take Image\nfrom VideoCapture import Device\n\n# Cache image\nimport time\nimport os.path\n\ndef saveImage(fname):\n cam = Device()\n cam.saveSnapshot(fname)\n del cam\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"index.html\")\n\nclass ImageHandler(tornado.web.RequestHandler):\n def get(self):\n fname = \"0.jpg\"\n\n # Dont recreate image for every request,\n # because multiple requests can bog the camera\n if (time.time() - os.path.getmtime(fname)) > 3:\n saveImage(fname)\n\n with open(fname, 'rb') as f:\n data = f.read()\n self.set_header('Content-Type', 'image/jpg')\n self.write(data)\n\n self.finish()\n\n\napplication = tornado.web.Application([\n (r\"/\", MainHandler),\n (r\"/img\", ImageHandler),\n])\n\nif __name__ == \"__main__\":\n saveImage(\"0.jpg\")\n application.listen(8080)\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"winapp.py","file_name":"winapp.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"175249676","text":"#coding=utf-8\n\nimport numpy as np\nimport torch\nfrom torch.utils import data\nfrom torchvision import transforms\nimport os\nimport cv2\nfrom PIL import Image,ImageFile\n'''\n该文件实现数据的读取\n'''\nclass SimpleDataSet(data.Dataset):\n def __init__(self,rootpath,transforms=None):\n '''\n 读取数据集\n rootpath:图像的根目录\n '''\n self.files=os.listdir(rootpath)\n self.classes={\"cat\":0,\"dog\":1}\n \n self.all_inputs=[]\n self.all_targets=[]\n for file in self.files:\n abspath=os.path.join(rootpath,file)\n label=int(self.classes[file.split('.')[0]])\n self.all_inputs.append(abspath)\n self.all_targets.append(label)\n self.all_inputs=np.array(self.all_inputs).reshape(len(self.all_inputs),1)\n self.all_targets=np.array(self.all_targets).reshape(self.all_inputs.shape[0],1)\n self.total_inputs=np.concatenate((self.all_inputs,self.all_targets),axis=1)\n \n # print(\"self.all_inputs:\",self.all_inputs.shape)\n self.transforms=transforms#数据增强\n\n def __getitem__(self,index):\n '''\n 返回训练数据\n '''\n #读取数据\n # print(self.total_inputs[index])\n img=cv2.imread(self.total_inputs[index][0])\n label=int(self.total_inputs[index][1])\n label=torch.from_numpy(np.array(label))\n img=np.ascontiguousarray(img[:, :, ::-1])#转为rgb\n if self.transforms is not None:\n img=Image.fromarray(img)\n img=self.transforms(img)\n \n return img,label\n def __len__(self):\n '''\n 返回样本总数\n '''\n return len(self.total_inputs)\n\n\n\n ","sub_path":"23-王锦文-广州/第11周/resnet50-pytorch/read_dataset.py","file_name":"read_dataset.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"94724926","text":"\"\"\"DataMapNcsmOut\nImlementation of DataMap (see DataMap.py) for *.out files produced by\nrunning NCSD\n\"\"\"\nfrom __future__ import print_function, division\n\nfrom os import sep\n\nfrom DatumNcsmOut import DatumNcsmOut\nfrom DatumNcsmOut import IncompleteArgumentsException\nfrom ExpNcsmOut import ExpNcsmOut\nfrom parser import exp\n\nfrom constants import FN_PARSE_NCSMVCE_OUT_RGX_FNAME as _RGX_FNAME\nfrom deprecated.DataMap import DataMap\nfrom parse import matches_completely, get_files_r\n\n\nclass DataMapNcsmOut(DataMap):\n \"\"\"Stores map containing data retrieved from NCSD *.out files\n \"\"\"\n # noinspection PyUnusedLocal\n def __init__(self, parent_directory, exp_list=None, exp_filter_fn=None,\n **kwargs):\n \"\"\"Initialize the DataMap in the given parent_directory\n :param parent_directory: directory in which to recursively retrieve\n files\n :param exp_list: list of exp for which to gather data\n :param exp_filter_fn: function with which to filter files by their exp\n :param kwargs: other arguments to pass to DatumNcsmOut\n \"\"\"\n self._rgx_fname = _RGX_FNAME\n super(DataMapNcsmOut, self).__init__(\n parent_directory=parent_directory,\n exp_type=ExpNcsmOut, datum_type=DatumNcsmOut,\n exp_list=exp_list, exp_filter_fn=exp_filter_fn\n )\n\n def _exp_from_file_path(self, f):\n return exp(filepath=f)\n\n def _get_files(self):\n def ncsmvce_out_file_filter(filepath):\n filename = filepath[filepath.rfind(sep)+1:]\n return matches_completely(regex=self._rgx_fname, string=filename)\n return get_files_r(directory=self.parent_dir,\n filterfn=ncsmvce_out_file_filter)\n\n def scale_to_aeff_exact_to_ground_energy_map(\n self, z, n1, n2, nshell, nhw=None, nmax=None):\n \"\"\"Returns a map\n scale -> A=Aeff -> Ground energy\n from the interaction scale factor to the mass number to the ground\n state energy associated with the case in which Aeff=A.\n One of nhw or nmax must be provided.\n :param z: proton number (Z)\n :param n1: one-particle truncation level\n :param n2: two-particle truncation level\n :param nshell: major oscillator shell (0=s, 1=p, 2=sd, ...)\n :param nhw: major oscillator shell truncation\n :param nmax: major oscillator shell truncation - minimum needed\n orbitals\n \"\"\"\n m = dict()\n for k, v in self.map.items():\n if k.Z != z or k.n1 != n1 or k.n2 != n2:\n continue\n scale = k.scale if k.scale is not None else 1.0\n try:\n m[scale] = v.aeff_exact_to_ground_state_energy_map(\n nhw=nhw, nmax=nmax, z=z, nshell=nshell)\n except IncompleteArgumentsException:\n raise\n return m\n\n","sub_path":"src/deprecated/ncsm_out/DataMapNcsmOut.py","file_name":"DataMapNcsmOut.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"17574225","text":"# -*- coding:utf-8 -*-\n\nimport tushare as ts\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\n\ndef get_data():\n pro = ts.pro_api(\"fb14a04ff5cdae480ffcf2db551f15668a1c0bd5de1a137f4dde5b9a\")\n df = pro.query(\"stock_basic\", exchange=\"SSE\")\n data = pd.DataFrame(data=df, columns=[\"ts_code\", \"name\", \"industry\"])\n return data\n\ndef mysql_conn():\n engine = create_engine('mysql+pymysql://root:Lyf123..@127.0.0.1/chinastockanalyse?charset=utf8')\n return engine\n\nif __name__ == \"__main__\":\n engine = mysql_conn()\n data = get_data()\n data.to_sql('sh_weight', engine, if_exists='append')","sub_path":"sh_code/get_sh_code.py","file_name":"get_sh_code.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"20004741","text":"import numpy as np\ndef getNearestValue(list, num):\n \"\"\"\n 概要: リストからある値に最も近い値を返却する関数\n @param list: データ配列\n @param num: 対象値\n @return 対象値に最も近い値\n \"\"\"\n\n # リスト要素と対象値の差分を計算し最小値のインデックスを取得\n idx = np.abs(np.asarray(list) - num).argmin()\n return list[idx]\n\nN = int(input())\nA = list(map(int, input().split()))\nA = np.array(A)\nsum_A = np.sum(A)\nres = np.cumsum(A)\nvalue = getNearestValue(res, sum_A/2)\nprint(abs(value - (sum_A - value)))\n","sub_path":"AtCoder_Python/other_contest/DDCC2020/DDCC2020_B.py","file_name":"DDCC2020_B.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"136812608","text":"import numpy as np\r\nfrom sistema_ativos import Ativo\r\n#from func_auxiliares import *\r\nimport csv\r\nimport os\r\nimport locale\r\nimport codecs\r\nimport copy\r\nfrom datetime import datetime,timedelta\r\n\r\n\r\ndef create_folder(directory):\r\n\tif not os.path.exists(directory):\r\n\t\tos.makedirs(directory)\r\n\r\ndef ler_dados_arq(caminho):\r\n\tarq = open(caminho,\"r\")\r\n\tl = list()\r\n\tlinha = arq.readline()\r\n\r\n\twhile linha:\r\n\t\tl.append(float(linha))\r\n\t\tlinha = arq.readline()\r\n\tarq.close()\r\n\treturn l\r\n\r\n\r\ndef pegar_nome_ativo(caminho):\r\n\ttam = len(caminho)-1\r\n\r\n\twhile caminho[tam] != '\\\\':\r\n\t\ttam = tam-1\r\n\treturn caminho[tam+1:]\r\n\r\n\r\ndef get_limites(caminho):\r\n\tarq = ler_dados_arq(caminho)\r\n\r\n\tmaximo = max(arq)\r\n\tminimo = min(arq)\r\n\tminimo -= 0.2*minimo\r\n\tmaximo += 0.2*maximo\r\n\t\r\n\treturn (minimo,maximo)\r\n\r\ndef csv_to_list(arq):\r\n\tl = list()\r\n\tcsvReader = csv.reader(codecs.open(arq+'.csv', 'rU', 'utf-8'),delimiter=';')\r\n\r\n\tfor row in csvReader:\r\n\t\tl.append(row)\r\n\treturn l\r\n\r\ndef search(nome_ativo,l):\r\n\tfor aux in l:\r\n\t\tif aux[0] == nome_ativo:\r\n\t\t\treturn aux[1:]\r\n\treturn NULL\r\n\r\n\r\ndef lendo_bloco(num_linha,x):\r\n\tnum_linha+=1\r\n\td = x[num_linha]\r\n\t#print(d)\r\n\tnum_linha+=1\r\n\tn = x[num_linha]\r\n\tnum_linha+=1\r\n\tnum_linha+=1\r\n\tj = x[num_linha]\r\n\tnum_linha+=3\r\n\r\n\treturn (d,n,j,num_linha)\r\n\r\ndef ler_params(args,num_ativos):\r\n\tparams_delay = np.zeros((num_ativos,4), dtype=int)\r\n\tparams_neurons = np.zeros((num_ativos,4), dtype=int)\r\n\tparams_janela = np.zeros((num_ativos,4), dtype=int)\r\n\tpath = '../parametros/'\r\n\tcont = 0\r\n\t\r\n\tfor arg in args:\r\n\t\tprint(arg)\r\n\t\tarq = open(path+arg,\"r\")\r\n\t\tl = list()\r\n\t\tx = arq.read().splitlines()\r\n\t\t#print(x)\r\n\t\tarq.close()\r\n\t\tlinha = 0\r\n\t\tfor i in range(num_ativos):\r\n\t\t\td,n,j,linha = lendo_bloco(linha,x)\r\n\t\t\tparams_delay[i][cont] = d\r\n\t\t\tparams_janela[i][cont] = j\r\n\t\t\tparams_neurons[i][cont] = n\r\n\t\tcont+=1\r\n\r\n\treturn (params_delay,params_janela,params_neurons)\r\n\r\ndef ler_params_with_lag(args,num_ativos,lag):\r\n\tparams_delay = np.zeros((num_ativos,4), dtype=int)\r\n\tparams_neurons = np.zeros((num_ativos,4), dtype=int)\r\n\tparams_janela = np.zeros((num_ativos,4), dtype=int)\r\n\tpath = '../parametros/'\r\n\tcont = 0\r\n\tfor arg in args:\r\n\t\tprint(arg)\r\n\t\tarq = open(path+arg,\"r\")\r\n\t\tl = list()\r\n\t\tx = arq.read().splitlines()\r\n\t\t#print(x)\r\n\t\tarq.close()\r\n\t\tlinha = 0\r\n\t\tfor i in range(num_ativos):\r\n\t\t\td,n,j,linha = lendo_bloco(linha,x)\r\n\t\t\tparams_delay[i][cont] = lag[i][cont]\r\n\t\t\tparams_janela[i][cont] = j\r\n\t\t\tparams_neurons[i][cont] = n\r\n\t\tcont+=1\r\n\r\n\treturn (params_delay,params_janela,params_neurons)\r\n\r\ndef MAPE(real,pred):\r\n\treturn (abs((real - pred))/(real+0.000001))*100\r\n\r\ndef MAPE_completo(predito, real):\r\n\terro = list()\r\n\r\n\tfor i in range(len(predito)):\r\n\t\taux = list()\r\n\r\n\t\tfor j in range(1,5):\r\n\t\t\tvalor = float(predito[i][j].replace(',','.'))\r\n\t\t\tvalor_real = float(real[i][j-1])\r\n\r\n\t\t\taux.append(str(MAPE(valor_real,valor)).replace('.',',')[0:7])\r\n\t\terro.append(aux)\r\n\t\tdel aux\r\n\treturn erro\r\n\r\ndef files_path09(path):\r\n\t'''return list of tuple(path, file)'''\r\n\treturn [file for p, _, files in os.walk(os.path.abspath(path)) for file in files]\r\n\r\ndef registrar_resultados(at,nome_arq,dia):\r\n\t#f = open('resultados.csv','w')\r\n\t#writer = csv.Writer(f, delimiter=';')\r\n\t#reais = csv_to_list('../min_max/'+dia)\r\n\tlocale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')\r\n\tcsv.register_dialect('myDialect',delimiter = ';',quoting=csv.QUOTE_NONE,skipinitialspace=True)\r\n \r\n\twith open(nome_arq+'-com_pesos_elm.csv', 'w') as csvFile:\r\n\t\twriter = csv.writer(csvFile,dialect='myDialect')\r\n\t\tfor i in range(at.num_rodadas):\r\n\t\t\twriter.writerow([\"rodada \"+str(i)])\r\n\t\t\tfor keys,values in at.conj_ativo.items():\r\n\t\t\t\tlist_aux = [keys]\r\n\t\t\t\t#l = search(keys,reais)\r\n\t\t\t\taux = values[i].retornar_valores()\r\n\t\t\t\tres = list()\r\n\t\t\t\t'''res.append(aux[0])\r\n\t\t\t\tres.append(aux[1])\r\n\t\t\t\tres.append(aux[2])\r\n\t\t\t\tres.append(aux[3])'''\r\n\t\t\t\tres.append(locale.currency(aux[0], grouping=True, symbol=None))\r\n\t\t\t\tres.append(locale.currency(aux[1], grouping=True, symbol=None))\r\n\t\t\t\tres.append(locale.currency(aux[2], grouping=True, symbol=None))\r\n\t\t\t\tres.append(locale.currency(aux[3], grouping=True, symbol=None))\r\n\t\t\t\tres.append(aux[4])\r\n\t\t\t\t'''res.append(\" \")\r\n\t\t\t\tres.append(locale.currency(float(l[0]), grouping=True, symbol=None))\r\n\t\t\t\tres.append(locale.currency(float(l[1]), grouping=True, symbol=None))\r\n\t\t\t\tres.append(locale.currency(float(l[2]), grouping=True, symbol=None))\r\n\t\t\t\tres.append(locale.currency(float(l[3]), grouping=True, symbol=None))'''\r\n\r\n\t\t\t\twriter.writerow(list_aux+res)\r\n\tcsvFile.close()\r\n\r\n\r\ndef registrar_resultados_elm(at,nome_arq,dia):\r\n\t#f = open('resultados.csv','w')\r\n\t#writer = csv.Writer(f, delimiter=';')\r\n\treais = csv_to_list('../real/'+dia)\r\n\tlocale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')\r\n\tcsv.register_dialect('myDialect',delimiter = ';',quoting=csv.QUOTE_NONE,skipinitialspace=True)\r\n\r\n\twith open(nome_arq+'.csv', 'w') as csvFile:\r\n\t\twriter = csv.writer(csvFile,dialect='myDialect')\r\n\t\tfor i in range(1):\r\n\t\t\twriter.writerow([\"rodada \"+str(i)])\r\n\t\t\tj = 0\r\n\t\t\tfor keys,values in at.conj_ativo.items():\r\n\t\t\t\tlist_aux = [keys]\r\n\t\t\t\taux = values[i].retornar_valor_elm()\r\n\t\t\t\tres = list()\r\n\t\t\t\tres.append(aux[0][0])\r\n\t\t\t\tres.append(aux[1][0])\r\n\t\t\t\tres.append(aux[2][0])\r\n\t\t\t\tres.append(aux[3][0])\r\n\t\t\t\tres.append(\" \")\r\n\t\t\t\tres.append(reais[j][0])\r\n\t\t\t\tres.append(reais[j][1])\r\n\t\t\t\tres.append(reais[j][2])\r\n\t\t\t\tres.append(reais[j][3])\r\n\t\t\t\tres.append(\" \")\r\n\t\t\t\tres.append(locale.currency(MAPE(float(reais[j][0]),float(aux[0][0])), grouping=True, symbol=None))\r\n\t\t\t\tres.append(locale.currency(MAPE(float(reais[j][1]),float(aux[1][0])), grouping=True, symbol=None))\r\n\t\t\t\tres.append(locale.currency(MAPE(float(reais[j][2]),float(aux[2][0])), grouping=True, symbol=None))\r\n\t\t\t\tres.append(locale.currency(MAPE(float(reais[j][3]),float(aux[3][0])), grouping=True, symbol=None))\r\n\r\n\t\t\t\tj +=1\r\n\t\t\t\twriter.writerow(list_aux+res)\r\n\tcsvFile.close()\r\n\r\ndef split_date(dat):\r\n\tprint(dat)\r\n\td = copy.copy(dat[0:2])\r\n\r\n\tif d[1] == '-':\r\n\t\td = '0'+d[0]\r\n\tm = copy.copy(dat[2:])\r\n\r\n\treturn (d,m)\r\n\r\ndef lista_dias(N,data):\r\n\thistorico = [nome for nome in os.listdir('../historico3')]\r\n\tl = list()\r\n\tctd = 0\r\n\tano = str(datetime.today().year)\r\n\tday,month = split_date(data)\r\n\r\n\tif month[0] == '-':\r\n\t\tmonth = month[1:]\r\n\r\n\td_completa = ano+'-'+month+'-'+day\r\n\tprint(ano)\r\n\tprint(month)\r\n\tprint(day)\r\n\r\n\t#print(d_completa)\r\n\tdata_pred = datetime.strptime(d_completa, '%Y-%m-%d')\r\n\r\n\tprint(type(day))\r\n\r\n\twhile(len(l) < N):\r\n\t\tctd = ctd+1\r\n\t\tdate_N_days_ago = data_pred - timedelta(days=ctd)\r\n\r\n\t\tif not date_N_days_ago.weekday() == 5 and not date_N_days_ago.weekday() == 6:\r\n\t\t\tdia = str(date_N_days_ago.day)\r\n\t\t\tmes = str(date_N_days_ago.month)\r\n\r\n\t\t\tdata = dia+'-'+mes\r\n\r\n\t\t\tif data in historico:\r\n\t\t\t\tl.append(data)\r\n\r\n\treturn l\r\n\r\ndef delete_vazio(estimado):\r\n\tlista = list()\r\n\r\n\tfor aux in estimado:\r\n\t\tif not aux == [] and not aux[0] == 'Ativo':\r\n\t\t\tlista.append(copy.copy(aux))\r\n\treturn lista\r\n\r\ndef mean_N_dias(dia,n,tam,nome_arq,opcao):\r\n\tl_dias = lista_dias(tam,dia)\r\n\tm_mape = np.zeros((n,3))\r\n\tfor d in l_dias:\r\n\t\tprint(d)\r\n\t\treal = csv_to_list('../real/'+d)\r\n\t\tpredito = csv_to_list(nome_arq+d)\r\n\t\tpredito = delete_vazio(predito)\r\n\r\n\t\tif opcao == 1:\r\n\t\t\tpredito = predito[5:8]\r\n\r\n\t\t\tif len(real) > 3:\r\n\t\t\t\treal = real[5:8]\r\n\t\t\telse:\r\n\t\t\t\treal = real\r\n\t\telif opcao == 2:\r\n\t\t\tpredito = predito[0:5]+predito[8:]\r\n\t\t\treal = real[0:5]+real[8:]\r\n\t\t\r\n\t\tfor i in range(len(predito)):\r\n\r\n\t\t\tfechamento = predito[i][2].replace(',','.',1)\r\n\t\t\tmaximo = predito[i][3].replace(',','.',1)\r\n\t\t\tminimo = predito[i][4].replace(',','.',1)\r\n\r\n\t\t\tm_mape[i][1] = m_mape[i][0] + MAPE(float(real[i][0]),float(fechamento))\r\n\t\t\tm_mape[i][2] = m_mape[i][1] + MAPE(float(real[i][1]),float(maximo))\r\n\t\t\tm_mape[i][3] = m_mape[i][2] + MAPE(float(real[i][2]),float(minimo))\r\n\r\n\tm_mape = m_mape/tam\r\n\r\n\treturn m_mape\r\n\r\ndef registrar_best(X,nome_arq,dia,num_rodadas,opcao,media= True):\r\n\tlocale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')\r\n\tcsv.register_dialect('myDialect',delimiter = ';',quoting=csv.QUOTE_NONE,skipinitialspace=True)\r\n\ttam = len(X)\r\n\tmedias = 0\r\n\tultimo = 0\r\n\r\n\tif media:\r\n\t\tmedias = mean_N_dias(dia,tam,num_rodadas,'Predicoes/completo_',opcao)\r\n\t\tultimo = mean_N_dias(dia,tam,1,'Predicoes/completo_',opcao)\r\n \r\n\twith open(nome_arq+'.csv', 'w') as csvFile:\r\n\t\twriter = csv.writer(csvFile,dialect='myDialect')\r\n\t\tfor i in range(1):\r\n\t\t\tfor j in range(tam):\r\n\t\t\t\tlist_aux = [X[j][0]]\r\n\t\t\t\t\r\n\t\t\t\taux = X[j][1].retornar_valores()\r\n\t\t\t\tres = list()\r\n\r\n\t\t\t\tres.append(str(aux[0]).replace('.',',')[0:5])\r\n\t\t\t\tres.append(str(aux[1]).replace('.',',')[0:5])\r\n\t\t\t\tres.append(str(aux[2]).replace('.',',')[0:5])\r\n\t\t\t\tres.append(str(aux[3]).replace('.',',')[0:5])\r\n\t\t\t\tres.append(\" \")\r\n\t\t\t\tres.append(aux[4])\r\n\r\n\t\t\t\tres.append(\" \")\r\n\t\t\t\t\r\n\t\t\t\tif media:\r\n\t\t\t\t\tfor k in range(3):\r\n\t\t\t\t\t\tres.append(str(medias[j][k]).replace('.',',')[0:5])\r\n\t\t\t\t\tres.append(\" \")\r\n\t\t\t\t\tfor k in range(3):\r\n\t\t\t\t\t\tres.append(str(ultimo[j][k]).replace('.',',')[0:5])\r\n\r\n\r\n\t\t\t\twriter.writerow(list_aux+res)\r\n\tcsvFile.close()\r\n\r\ndef unir_best(X,dia,num_rodadas,opcao,media = True):\r\n\tcsv.register_dialect('myDialect',delimiter = ';',quoting=csv.QUOTE_NONE,skipinitialspace=True)\r\n\ttam = len(X)\r\n\tmedias = 0\r\n\tultimo = 0\r\n\r\n\tif media:\r\n\t\tmedias = mean_N_dias(dia,tam,num_rodadas,'Predicoes/completo_',opcao)\r\n\t\tultimo = mean_N_dias(dia,tam,1,'Predicoes/completo_',opcao)\r\n\r\n\tdol_ind = csv_to_list('Predicoes/dol_ind_'+dia)\r\n\tcompleto = list()\r\n\twith open('Predicoes/completo_'+dia+'.csv', 'w') as csvFile:\r\n\t\twriter = csv.writer(csvFile,dialect='myDialect')\r\n\t\twriter.writerow(['Ativo','Open','Close','High','Low',' ','Fit',' ','Close err medio',\r\n\t\t'High err medio','Low err medio',' ','Close err','High err','Low err'])\r\n\t\tfor i in range(1):\r\n\t\t\tfor j in range(tam):\r\n\r\n\t\t\t\tlist_aux = [X[j][0]]\r\n\r\n\t\t\t\taux = X[j][1].retornar_valores()\r\n\t\t\t\tres = list()\r\n\r\n\t\t\t\tres.append(str(aux[0]).replace('.',','))\r\n\t\t\t\tres.append(str(aux[1]).replace('.',',')[0:5])\r\n\t\t\t\tres.append(str(aux[2]).replace('.',',')[0:5])\r\n\t\t\t\tres.append(str(aux[3]).replace('.',',')[0:5])\r\n\t\t\t\tres.append(\" \")\r\n\t\t\t\tres.append(aux[4])\r\n\r\n\t\t\t\tif media:\r\n\r\n\t\t\t\t\tres.append(\" \")\r\n\t\t\t\t\t\r\n\t\t\t\t\tfor k in range(3):\r\n\t\t\t\t\t\tres.append(str(medias[j][k]).replace('.',',')[0:5])\r\n\t\t\t\t\t\r\n\t\t\t\t\tres.append(\" \")\r\n\t\t\t\t\t\r\n\t\t\t\t\tfor k in range(3):\r\n\t\t\t\t\t\tres.append(str(ultimo[j][k]).replace('.',',')[0:5])\r\n\r\n\t\t\t\tcompleto.append(list_aux+res)\r\n\t\tdol_ind = delete_vazio(dol_ind)\r\n\t\tcompleto = completo[0:5] + dol_ind + completo[5:]\r\n\r\n\t\tfor i in range(len(completo)):\r\n\t\t\twriter.writerow(completo[i])\r\n\tcsvFile.close()\r\n\r\ndef registrar_elm(X,nome_arq,dia,opcao):\r\n\tlocale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')\r\n\tcsv.register_dialect('myDialect',delimiter = ';',quoting=csv.QUOTE_NONE,skipinitialspace=True)\r\n\ttam = len(X)\r\n \r\n\twith open(nome_arq+'.csv', 'w') as csvFile:\r\n\t\twriter = csv.writer(csvFile,dialect='myDialect')\r\n\t\tfor i in range(1):\r\n\t\t\tfor j in range(tam):\r\n\t\t\t\tlist_aux = [X[j][0]]\r\n\t\t\t\t\r\n\t\t\t\taux = X[j][1].retornar_valor_elm()\r\n\t\t\t\tres = list()\r\n\r\n\t\t\t\tres.append(str(aux[0]).replace('.',',')[0:7])\r\n\t\t\t\tres.append(str(aux[1]).replace('.',',')[0:7])\r\n\t\t\t\tres.append(str(aux[2]).replace('.',',')[0:7])\r\n\t\t\t\tres.append(str(aux[3]).replace('.',',')[0:7])\r\n\r\n\t\t\t\twriter.writerow(list_aux+res)\r\n\tcsvFile.close()\r\n\r\n\r\ndef unir_elm(X,dia,opcao):\r\n\tcsv.register_dialect('myDialect',delimiter = ';',quoting=csv.QUOTE_NONE,skipinitialspace=True)\r\n\ttam = len(X)\r\n\tdol_ind = csv_to_list('Predicoes/dol_ind_elm_'+dia)\r\n\tind_real = csv_to_list('../real/IND_'+dia)\r\n\tcompleto = list()\r\n\twith open('Predicoes/completo_elm2_'+dia+'.csv', 'w') as csvFile:\r\n\t\twriter = csv.writer(csvFile,dialect='myDialect')\r\n\r\n\t\tfor i in range(1):\r\n\t\t\tfor j in range(tam):\r\n\r\n\t\t\t\tlist_aux = [X[j][0]]\r\n\r\n\t\t\t\taux = X[j][1].retornar_valor_elm()\r\n\t\t\t\tres = list()\r\n\r\n\t\t\t\tres.append(str(aux[0]).replace('.',','))\r\n\t\t\t\tres.append(str(aux[1]).replace('.',',')[0:5])\r\n\t\t\t\tres.append(str(aux[2]).replace('.',',')[0:5])\r\n\t\t\t\tres.append(str(aux[3]).replace('.',',')[0:5])\r\n\r\n\t\t\t\tres.append(\" \")\r\n\t\t\t\t\r\n\r\n\t\t\t\tcompleto.append(list_aux+res)\r\n\t\tdol_ind = delete_vazio(dol_ind)\r\n\t\tcompleto = completo[0:5] + dol_ind + completo[5:]\r\n\r\n\t\terro = MAPE_completo(completo,ind_real)\r\n\r\n\t\tfor i in range(len(completo)):\r\n\t\t\tlinha = completo[i]+erro[i]\r\n\t\t\twriter.writerow(linha)\r\n\tcsvFile.close()\r\n","sub_path":"IO.py","file_name":"IO.py","file_ext":"py","file_size_in_byte":12284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"38592224","text":"# -*- coding:utf-8 -*-\n# Copyright 2019 Huawei Technologies Co.,Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use\n# this file except in compliance with the License. You may obtain a copy of the\n# 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 distributed\n# under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations under the License.\n\nimport os\n\nfrom openstack import connection\n\nauth_url = '******'\nuserDomainId = '******'\nprojectId = '******'\nusername = '******'\npassword = os.getenv('get_secret_code')\n\nconn = connection.Connection(\n auth_url=auth_url,\n user_domain_id=userDomainId,\n project_id=projectId,\n username=username,\n password=password\n)\n\n\ndef test_private_ips(_conn):\n query = {\n \"limit\": 2\n }\n objs = _conn.vpcv1.private_ips('6df498a2-3480-4faf-b6e7-ac25a053bbbc', **query)\n for obj in objs:\n print(obj)\n\n\ndef test_get_private_ip(_conn):\n print(_conn.vpcv1.get_private_ip('120f4621-be02-4412-b743-6e896bb88e32'))\n\n\ndef test_create_private_ip(_conn):\n data = {\n \"subnet_id\": \"6df498a2-3480-4faf-b6e7-ac25a053bbbc\"\n }\n print(_conn.vpcv1.create_private_ip(**data))\n\n\ndef test_create_private_ips(_conn):\n data = [\n {\n \"subnet_id\": \"6df498a2-3480-4faf-b6e7-ac25a053bbbc\"\n },\n {\n \"subnet_id\": \"6df498a2-3480-4faf-b6e7-ac25a053bbbc\"\n }\n ]\n print(_conn.vpcv1.create_private_ips(*data))\n\n\ndef test_delete_private_ip(_conn):\n print(_conn.vpcv1.delete_private_ip('c085815e-f43d-418a-913b-87771f8e7200'))\n\n\ndef test_find_private_ip(_conn):\n private_ip_id = 'c085815e-f43d-418a-913b-87771f8e7200'\n subnet_id = '6df498a2-3480-4faf-b6e7-ac25a053bbbc'\n print(_conn.vpcv1.find_private_ip(private_ip_id, subnet_id))\n\n\nif __name__ == '__main__':\n test_private_ips(conn)\n test_get_private_ip(conn)\n test_create_private_ip(conn)\n test_create_private_ips(conn)\n test_delete_private_ip(conn)\n test_find_private_ip(conn)\n","sub_path":"examples/vpc/v1/private_ip.py","file_name":"private_ip.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"644127122","text":"# coding: utf-8\n#\n# Copyright 2022 The Oppia Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Unit tests for scripts/rtl_css.py.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport subprocess\n\nfrom core import utils\nfrom core.tests import test_utils\n\nfrom . import rtl_css\n\n\nclass RtlCSSTests(test_utils.GenericTestBase):\n \"\"\"Test the methods for the rtl css validation script.\"\"\"\n\n def setUp(self):\n super(RtlCSSTests, self).setUp()\n self.observed_rtl_file_count = 0\n self.validated_rtl_css_file_count = 0\n self.validated_css_file_count = 0\n\n def test_main_generate(self):\n \"\"\"Tests that all the .rtl.css files in the codebase are regenerated\n with the '--generate' command.\n \"\"\"\n process = subprocess.Popen(\n ['echo', 'test'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n def mock_popen_without_std_in( # pylint: disable=unused-argument\n unused_cmd_tokens, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE):\n self.observed_rtl_file_count += 1\n return process\n popen_swap_without_stdin = self.swap(\n subprocess, 'Popen', mock_popen_without_std_in)\n expected_rtl_file_count = 0\n pages_base_dir = os.path.join(os.getcwd(), 'core', 'templates')\n\n # Count rtl css files of pages.\n for _, _, files in os.walk(pages_base_dir):\n for file in files:\n if file.endswith('.rtl.css'):\n expected_rtl_file_count += 1\n\n with popen_swap_without_stdin:\n rtl_css.main(args=['--mode', 'generate'])\n self.assertEqual(\n self.observed_rtl_file_count, expected_rtl_file_count)\n\n def test_main_validate(self):\n \"\"\"Tests that the .rtl.css files are validated with the '--validate'\n command.\n \"\"\"\n class MockFile:\n def __init__(self, filepath):\n self.filepath = filepath\n\n def read(self): # pylint: disable=missing-docstring\n return self.filepath.encode()\n\n class StdinProcess: # pylint: disable=missing-docstring\n # The disable=W0622 is for the error - Redefining built-in 'input'\n # which is not applicable here as this class is only sued for\n # mocking.\n def communicate(self, input): # pylint: disable=missing-docstring disable=redefined-builtin\n return input, None\n\n def mock_popen_with_std_in( # pylint: disable=unused-argument\n unused_cmd_tokens, stdin=subprocess.PIPE,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE):\n return StdinProcess()\n\n def mock_open(filepath, mode, encoding=None): # pylint: disable=unused-argument\n if filepath.endswith('.rtl.css'):\n self.validated_rtl_css_file_count += 1\n return MockFile(filepath[:-8])\n self.validated_css_file_count += 1\n return MockFile(filepath[:-4])\n\n def errorred_mock_open(filepath, mode, encoding=None): # pylint: disable=unused-argument\n if filepath.endswith('.rtl.css'):\n return MockFile(filepath[:-8])\n\n # Mocks an error in only one file.\n if filepath.endswith('splash-page.component.css'):\n return MockFile(filepath)\n return MockFile(filepath[:-4])\n\n popen_swap_with_stdin = self.swap(\n subprocess, 'Popen', mock_popen_with_std_in)\n open_swap = self.swap(utils, 'open_file', mock_open)\n errorred_open_swap = self.swap(\n utils, 'open_file', errorred_mock_open)\n\n raises_exception = self.assertRaisesRegex(\n Exception, 'Invalid RTL CSS for the following files')\n with popen_swap_with_stdin:\n with open_swap:\n rtl_css.main(args=['--mode', 'validate'])\n self.assertEqual(\n self.validated_css_file_count,\n self.validated_rtl_css_file_count)\n\n with errorred_open_swap, raises_exception:\n rtl_css.main(args=['--mode', 'validate'])\n\n def test_no_rtlcss_installed(self):\n \"\"\"Tests that error is thrown if rtlcss is not installed.\"\"\"\n class MockPath:\n def join(self, filename, *_): # pylint: disable=missing-docstring\n return filename\n\n def exists(self): # pylint: disable=missing-docstring\n return False\n\n os_swap = self.swap(os, 'path', MockPath)\n raises_exception = self.assertRaisesRegex(\n Exception, 'ERROR Please run start.py first to install rtlcss '\n 'and its dependencies.')\n with os_swap, raises_exception:\n rtl_css.main(args=['--mode', 'validate'])\n\n def test_error_caught_in_generate(self):\n \"\"\"Tests that error is caught correctly in the generate script.\"\"\"\n class MockErroredProcess:\n def communicate(self): # pylint: disable=missing-docstring\n return None, 'Error'\n\n def mock_popen( # pylint: disable=unused-argument\n unused_cmd_tokens, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE):\n return MockErroredProcess()\n\n raises_exception = self.assertRaisesRegex(\n Exception, 'Error')\n popen_swap = self.swap(subprocess, 'Popen', mock_popen)\n with popen_swap, raises_exception:\n rtl_css.main(args=['--mode', 'generate'])\n","sub_path":"scripts/rtl_css_test.py","file_name":"rtl_css_test.py","file_ext":"py","file_size_in_byte":6057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"607023413","text":"import functions\nfrom torch import nn\nfrom torch import optim\n\n\nfrom torchvision import models\n\n# 1. 이미지 파일 디렉로티 지정\ndata_dir = r'D:\\#.Secure Work Folder\\1. Data\\1. CMI\\1. FLD\\Train_3rd'\ntrain_dir = data_dir + '/train'\nvalid_dir = data_dir + '/valid'\ntest_dir = data_dir + '/test'\n\n# 2. Data Loading and Transforms\n\ntrain_loader, validate_loader, test_loader, training_dataset, validation_dataset, testing_dataset = functions.loader(train_dir, valid_dir, test_dir)\n\n\n# 3. Label Mapping\nimport json\n\nwith open('defect_type.json', 'r') as f:\n defect_type = json.load(f)\n\nprint(len(defect_type))\nprint(defect_type)\n\n# 4. model selection\n\nmodel = models.vgg11()\n\n# 5. Build Custom Classifier\n\nfrom collections import OrderedDict\n\nclassifier = nn.Sequential(OrderedDict([('fc1', nn.Linear(25088, 5000)),\n ('relu', nn.ReLU()),\n ('drop', nn.Dropout(p=0.5)),\n ('fc2', nn.Linear(5000, 3)),\n ('output', nn.LogSoftmax(dim=1))]))\nmodel.classifier = classifier\n\n# 6. Loss function and gradient descent\n\ncriterion = nn.NLLLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)\n\n# 7. model training\n\nmodel = functions.train_classifier(model, train_loader, validate_loader, optimizer, criterion)\n\n# 8. test accuracy\n\nfunctions.test_accuracy(model, test_loader)\n\n# 9. model save\n\nmodel_save_path = r\"C:/Users/LG/Desktop/ksb/3. CODE/model/\"\nfilename = 'sepa_image_classifier2.pth'\nfunctions.save_checkpoint(model, training_dataset, model_save_path, filename)","sub_path":"model_learning.py","file_name":"model_learning.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"334506795","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sublime\nimport sublime_plugin\n\nclass TransliterateTextCommand(sublime_plugin.TextCommand):\n\n def run(self, edit, dictionary_file):\n s = sublime.load_settings(dictionary_file)\n dictionary = s.get('chars_mapping')\n\n # Some text is selected\n if not self.view.sel()[0].empty():\n\n # Go throught selections\n selections = self.view.sel()\n for sel in selections:\n selection_text = self.view.substr(sel)\n self.view.replace(edit, sel, self.transliterateText(selection_text, dictionary))\n\n # Nothing is selected\n else :\n\n # Get entire view\n sel = sublime.Region(0, self.view.size())\n selection_text = self.view.substr(sel)\n self.view.replace(edit, sel, self.transliterateText(selection_text, dictionary))\n\n def transliterateText(self, input_string, dictionary):\n translit_string = []\n for char in input_string:\n translit_string.append(dictionary.get(char, char))\n return ''.join(translit_string)\n","sub_path":"TransliterateText.py","file_name":"TransliterateText.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"356793756","text":"# -*- coding: utf-8 -*-\r\n#########################################################\r\n# 고정영역\r\n#########################################################\r\n# python\r\nimport os\r\nimport sys\r\nimport traceback\r\nimport json\r\n\r\n# third-party\r\nfrom flask import Blueprint, request, Response, render_template, redirect, jsonify, url_for, send_from_directory\r\nfrom flask_login import login_required\r\nfrom flask_socketio import SocketIO, emit, send\r\n\r\n# sjva 공용\r\nfrom framework.logger import get_logger\r\nfrom framework import app, db, scheduler, socketio, path_app_root\r\nfrom framework.util import Util, AlchemyEncoder\r\nfrom system.logic import SystemLogic\r\n \r\n# 패키지\r\npackage_name = __name__.split('.')[0]\r\nlogger = get_logger(package_name)\r\n\r\nfrom .logic import Logic\r\nfrom .model import ModelSetting\r\n\r\n\r\nblueprint = Blueprint(package_name, package_name, url_prefix='/%s' % package_name, template_folder=os.path.join(os.path.dirname(__file__), 'templates'), static_folder=os.path.join(os.path.dirname(__file__), 'kthoom'), static_url_path='kthoom')\r\n\r\ndef plugin_load():\r\n Logic.plugin_load()\r\n\r\ndef plugin_unload():\r\n Logic.plugin_unload()\r\n\r\nplugin_info = {\r\n 'version' : '0.2.1',\r\n 'name' : '마나모아 다운로드',\r\n 'category_name' : 'service',\r\n 'icon' : '',\r\n 'developer' : 'soju6jan',\r\n 'description' : '마나모아 다운로드
원작자 :noname님',\r\n 'home' : 'https://github.com/soju6jan/manamoa',\r\n 'more' : '',\r\n}\r\n#########################################################\r\n\r\n# 메뉴 구성.\r\nmenu = {\r\n 'main' : [package_name, '마나모아 다운로드'],\r\n 'sub' : [\r\n ['setting', '설정'], ['request', '요청'], ['queue', '큐'], ['list', '목록'], ['log', '로그']\r\n ], \r\n 'category' : 'service',\r\n} \r\n\r\n#########################################################\r\n# WEB Menu\r\n#########################################################\r\n@blueprint.route('/')\r\ndef home():\r\n return redirect('/%s/setting' % package_name)\r\n \r\n@blueprint.route('/')\r\n@login_required\r\ndef first_menu(sub): \r\n arg = ModelSetting.to_dict()\r\n arg['package_name'] = package_name\r\n if sub == 'setting':\r\n arg['scheduler'] = str(scheduler.is_include(package_name))\r\n arg['is_running'] = str(scheduler.is_running(package_name))\r\n return render_template('%s_%s.html' % (package_name, sub), arg=arg)\r\n elif sub == 'request':\r\n arg['is_running'] = str(scheduler.is_running(package_name))\r\n return render_template('%s_%s.html' % (package_name, sub), arg=arg)\r\n elif sub in ['queue', 'list']:\r\n return render_template('%s_%s.html' % (package_name, sub))\r\n elif sub == 'log':\r\n return render_template('log.html', package=package_name)\r\n return render_template('sample.html', title='%s - %s' % (package_name, sub))\r\n\r\n#########################################################\r\n# For UI (보통 웹에서 요청하는 정보에 대한 결과를 리턴한다.)\r\n#########################################################\r\n@blueprint.route('/ajax/', methods=['GET', 'POST'])\r\n@login_required\r\ndef ajax(sub):\r\n logger.debug('AJAX %s %s', package_name, sub)\r\n try:\r\n if sub == 'setting_save':\r\n ret = ModelSetting.setting_save(request)\r\n return jsonify(ret)\r\n elif sub == 'scheduler':\r\n go = request.form['scheduler']\r\n logger.debug('scheduler :%s', go)\r\n if go == 'true':\r\n Logic.scheduler_start()\r\n else:\r\n Logic.scheduler_stop()\r\n return jsonify(go)\r\n elif sub == 'one_execute':\r\n ret = Logic.one_execute()\r\n return jsonify(ret)\r\n elif sub == 'reset_db':\r\n ret = Logic.reset_db()\r\n return jsonify(ret)\r\n\r\n\r\n\r\n \r\n \r\n elif sub == 'download_by_request':\r\n try:\r\n ret = Logic.download_by_request(request)\r\n return jsonify(ret)\r\n except Exception as e: \r\n logger.error('Exception:%s', e)\r\n logger.error(traceback.format_exc())\r\n elif sub == 'completed_remove':\r\n try:\r\n from logic_queue import LogicQueue\r\n ret = LogicQueue.completed_remove()\r\n return jsonify(ret)\r\n except Exception as e: \r\n logger.error('Exception:%s', e)\r\n logger.error(traceback.format_exc())\r\n elif sub == 'reset_queue':\r\n try:\r\n from logic_queue import LogicQueue\r\n ret = LogicQueue.reset_queue()\r\n return jsonify(ret)\r\n except Exception as e: \r\n logger.error('Exception:%s', e)\r\n logger.error(traceback.format_exc())\r\n elif sub == 'item_list':\r\n try:\r\n ret = Logic.item_list(request)\r\n return jsonify(ret)\r\n except Exception as e: \r\n logger.error('Exception:%s', e)\r\n logger.error(traceback.format_exc())\r\n elif sub == 'list_remove':\r\n try:\r\n ret = Logic.list_remove(request)\r\n return jsonify(ret)\r\n except Exception as e: \r\n logger.error('Exception:%s', e)\r\n logger.error(traceback.format_exc())\r\n elif sub == 'list_all_download':\r\n try:\r\n ret = Logic.list_all_download(request)\r\n return jsonify(ret)\r\n except Exception as e: \r\n logger.error('Exception:%s', e)\r\n logger.error(traceback.format_exc())\r\n elif sub == 'list_add_blacklist':\r\n try:\r\n ret = Logic.list_add_blacklist(request)\r\n return jsonify(ret)\r\n except Exception as e: \r\n logger.error('Exception:%s', e)\r\n logger.error(traceback.format_exc())\r\n except Exception as e: \r\n logger.error('Exception:%s', e)\r\n logger.error(traceback.format_exc()) \r\n return jsonify('fail') \r\n\r\n \r\n\r\n\r\n \r\n#########################################################\r\n# kthroom\r\n#########################################################\r\n@blueprint.route('/code/', methods=['GET', 'POST'])\r\ndef kthroom(path):\r\n return blueprint.send_static_file('code/' + path)\r\n\r\n@blueprint.route('/images/', methods=['GET', 'POST'])\r\ndef kthroom_images(path):\r\n return blueprint.send_static_file('images/' + path)\r\n\r\n@blueprint.route('/examples/', methods=['GET', 'POST'])\r\ndef kthroom_examples(path):\r\n return blueprint.send_static_file('examples/' + path)\r\n\r\n@blueprint.route('/dp/', methods=['GET', 'POST'])\r\ndef kthroom_dp(path):\r\n tmp = path.split('/')\r\n real_path = os.path.join(ModelSetting.get('dfolder'), tmp[0], tmp[1])\r\n real_path = real_path.replace(path_app_root, '')[1:].replace('\\\\', '/')\r\n logger.debug('load:%s', real_path)\r\n return send_from_directory('', real_path)\r\n\r\n#########################################################\r\n# socketio\r\n#########################################################\r\nsid_list = []\r\n@socketio.on('connect', namespace='/%s' % package_name)\r\ndef connect():\r\n try:\r\n logger.debug('socket_connect')\r\n sid_list.append(request.sid)\r\n send_queue_list()\r\n except Exception as e: \r\n logger.error('Exception:%s', e)\r\n logger.error(traceback.format_exc())\r\n\r\n\r\n@socketio.on('disconnect', namespace='/%s' % package_name)\r\ndef disconnect():\r\n try:\r\n sid_list.remove(request.sid)\r\n logger.debug('socket_disconnect')\r\n except Exception as e: \r\n logger.error('Exception:%s', e)\r\n logger.error(traceback.format_exc())\r\n\r\ndef socketio_callback(cmd, data, encoding=True):\r\n if sid_list:\r\n if encoding:\r\n data = json.dumps(data, cls=AlchemyEncoder)\r\n data = json.loads(data)\r\n socketio.emit(cmd, data, namespace='/%s' % package_name, broadcast=True)\r\n\r\n\r\ndef send_queue_list():\r\n from logic_queue import QueueEntity\r\n tmp = QueueEntity.entity_list\r\n t = [x.as_dict() for x in tmp]\r\n socketio_callback('queue_list', t, encoding=False)\r\n","sub_path":"plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":8275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"27049593","text":"from setuptools import setup\nfrom setuptools.command.develop import develop\nfrom setuptools.command.install import install\nimport os\nimport sys\nimport platform\nimport errno\nimport shutil\n\nversion = '0.4.51'\ndllversion = '0.4.26'\n\n\ndef force_symlink(target, link_name):\n try:\n print('creating sim link from ' + link_name + ' ->' + target)\n os.symlink(target, link_name)\n except OSError as e:\n if e.errno == errno.EEXIST:\n try:\n os.remove(link_name)\n os.symlink(target, link_name)\n except OSError as e:\n print('deleted could not create simlink ' + link_name + ' ->' + target)\n else:\n print('could not create simlink ' + link_name + ' ->' + target)\n raise e\n\n\ndef force_move(og_name, target):\n try:\n print('moveing file from ' + og_name + ' ->' + target)\n shutil.move(og_name, target)\n except OSError as e:\n if e.errno == errno.EEXIST:\n os.remove(target)\n shutil.move(og_name, target)\n else:\n print('could not move file ' + og_name + ' ->' + target)\n raise e\n\n\ndef force_remove(target):\n try:\n print('removing file ' + target)\n os.remove(target)\n except OSError as e:\n print('could not remove file ' + target)\n raise e\n\n\ndef get_datafileioLib_for_platform():\n global dllversion\n py_major = sys.version_info[0]\n py_minor = sys.version_info[1]\n\n if py_major is not 3:\n raise \"this module is a python 3 module only\"\n\n print(\"seting up for \" + platform.system() + \" \" + platform.architecture()[0] + \" platform\")\n if py_minor is 7:\n if platform.system() == 'Windows' and platform.architecture()[0] == '32bit':\n return \"_DataFileIOLibraryInterface-py3.7-v\" + dllversion + \"-32.pyd\"\n elif platform.system() == 'Windows' and platform.architecture()[0] == '64bit':\n return \"_DataFileIOLibraryInterface-py3.7-v\" + dllversion + \"-64.pyd\"\n elif platform.system() == 'Linux' and platform.architecture()[0] == '64bit':\n return \"_DataFileIOLibraryInterface-py3.7-v\" + dllversion + \"-64.so\"\n else:\n raise \"Platform or python version is not supported\"\n elif py_minor is 6:\n if platform.system() == 'Windows' and platform.architecture()[0] == '32bit':\n return \"_DataFileIOLibraryInterface-py3.6-v\" + dllversion + \"-32.pyd\"\n elif platform.system() == 'Windows' and platform.architecture()[0] == '64bit':\n return \"_DataFileIOLibraryInterface-py3.6-v\" + dllversion + \"-64.pyd\"\n elif platform.system() == 'Linux' and platform.architecture()[0] == '64bit':\n return \"_DataFileIOLibraryInterface-py3.6-v\" + dllversion + \"-64.so\"\n else:\n raise \"Platform or python version is not supported\"\n elif py_minor is 5:\n if platform.system() == 'Linux' and platform.architecture()[0] == '64bit':\n return \"_DataFileIOLibraryInterface-py3.5-v\" + dllversion + \"-64.so\"\n else:\n raise \"Platform or python version is not supported\"\n elif py_minor is 4:\n if platform.system() == 'Linux' and platform.architecture()[0] == '64bit':\n return \"_DataFileIOLibraryInterface-py3.4-v\" + dllversion + \"-64.so\"\n else:\n raise \"Platform or python version is not supported\"\n else:\n raise \"python version is not supported\"\n\n\nclass PostInstallCommand(install):\n def run(self):\n install.run(self)\n print('starting post install')\n datafile = get_datafileioLib_for_platform()\n for script in self.get_outputs():\n if os.path.basename(script).startswith(\"_DataFileIOLibraryInterface-\"):\n if (script.endswith(datafile)):\n if platform.system() == 'Windows':\n force_move(script, os.path.join(os.path.dirname(script), \"_DataFileIOLibraryInterface.pyd\"))\n else:\n force_move(script, os.path.join(os.path.dirname(script), \"_DataFileIOLibraryInterface.so\"))\n else:\n force_remove(script) \n\n\nclass PostDevelopCommand(develop):\n def run(self):\n develop.run(self)\n print('starting post develop')\n file = os.path.join(os.getcwd(), \"ICS_IPA\", get_datafileioLib_for_platform())\n #if platform.system() == 'Windows':\n # force_symlink(file, os.path.join(os.getcwd(), \"ICS_IPA\", \"_DataFileIOLibraryInterface.pyd\"))\n #else:\n # force_symlink(file, os.path.join(os.getcwd(), \"ICS_IPA\", \"_DataFileIOLibraryInterface.so\"))\n\n\nsetup(\n name='ICS_IPA',\n packages=['ICS_IPA'],\n version=version,\n description='API used for DataMining mdf data files using DataSpy',\n long_description='This repo is designed to manage the library functions used \\\n for DataMining through mdf data files using the DataSpy \\\n product made by Intrepid Control System. The library \\\n contains a bunch of File I/O functions in a dll that \\\n allow users to parse through mdf data files using their \\\n own applications like Python, Excel, Matlab, C# etc. \\\n This library of functions is duplicated on Intrepids \\\n wireless data server (Wireless NeoVI) allowing users to \\\n develop scripts on their PC and then run those scripts \\\n on the Wireless Neo VI data server without requiring \\\n the data to be downloaded.',\n maintainer='Zaid Nackasha',\n maintainer_email='ZNackasha@intrepidcs.com',\n url='https://github.com/intrepidcs/ICS_IPA',\n download_url='https://github.com/intrepidcs/ICS_IPA/archive/' +\n version + '.tar.gz',\n package_data={'ICS_IPA':\n ['_DataFileIOLibraryInterface*.[pyd|so]']},\n include_package_data=True,\n #classifiers=['Operating System :: Microsoft :: Windows',\n # 'Programming Language :: Python',\n # 'Programming Language :: Python :: 3.6'],\n cmdclass={\n 'install': PostInstallCommand,\n 'develop': PostDevelopCommand,\n }\n)\n","sub_path":"pypi_install_script/ICS_IPA-0.4.51.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":6279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"649234772","text":"class node:\n def __init__(self):\n self.key = False\n self.child = {}\nclass WordDictionary:\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.root = node()\n\n def addWord(self, word: str) -> None:\n \"\"\"\n Adds a word into the data structure.\n \"\"\"\n nd = self.root\n for ch in word:\n if ch not in nd.child:\n nd.child[ch] = node()\n nd = nd.child[ch]\n \n nd.key = True; \n return None\n \n def DFSSearch(self, nd: node, word: str) -> bool:\n for i in range(len(word)):\n if not len(nd.child):\n return False\n if word[i] in nd.child:\n nd = nd.child[word[i]]\n elif word[i] != '.' and word[i] not in nd.child:\n return False\n if word[i] == '.':\n for ch in nd.child.keys():\n newWord = ch + word[i+1:]\n if self.DFSSearch(nd, newWord):\n return True\n return False\n\n if nd.key: \n return True\n else:\n return False\n \n def search(self, word: str) -> bool:\n \"\"\"\n Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.\n \"\"\"\n return self.DFSSearch(self.root, word)\n \n\n\n# Your WordDictionary object will be instantiated and called as such:\n# obj = WordDictionary()\n# obj.addWord(word)\n# param_2 = obj.search(word)\n","sub_path":"Python/211. Add_and_Search_Word-Data_structure_design.py","file_name":"211. Add_and_Search_Word-Data_structure_design.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"638791780","text":"'''\nThis script produces a scatter plot of valid votes for a particular candidate across all MERs not included in the \nrecount election (clean MERs). Requires both the original election dataset and recount election dataset. \nEthan Eason, August 2019\n'''\nimport pandas as pd\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\n# reads in data from the original election and recount election data sets\ndata_path = os.path.join('C:/Users/ethan/OneDrive - California Institute of Technology/SURF/Data', 'Honduras_Election_Data.csv')\nog_df = pd.read_csv(data_path)\n\ndata_path2 = os.path.join('C:/Users/ethan/OneDrive - California Institute of Technology/SURF/Data', 'Honduras_Recount_Election_Data.csv')\nre_df = pd.read_csv(data_path2)\n\n# shifts each MER data entry in the recount election dataset by one such that the MER column will match the indices \n# of each MER in the recount election\nto_remove = np.array(re_df['MER'])\nfor i in range(len(to_remove)):\n to_remove[i] = to_remove[i] - 1\n\n# removes all the recounted MER rows from the original election dataset\nog_df = og_df.drop(to_remove)\n\n# stores the ballots received and total votes from the modified original election dataset (only clean MERs)\nballots_total = np.array(og_df['BR'])\ntotal_votes = np.array(og_df['TV'])\n\n# temp array to store calculated turnout data\nturnout = []\n\n# array to store vote shares for a particular candidate\nSACNS = np.array(og_df['LOZM'])\n\n# temp array to store the vote shares array for a particular candidate minus the recount MERs\nSACNS_corrected = []\n\n# loop to construct the modified vote shares and turnout arrays\nfor i in range(len(ballots_total)):\n votes = int(total_votes[i])\n ballots = int(ballots_total[i])\n if ballots != 0 and votes < ballots:\n SACNS_corrected.append((100 * SACNS[i] / votes))\n \n # two lines below give options as to whether the scatter plot has raw turnout or turnout percentage\n turnout.append(int(100 * votes / ballots))\n # turnout.append(votes)\n\n# plt.hist(turnout, bins=range(min(turnout), max(turnout) + 200, 200), color='blue')\n\n# produces scatter plot of candidate vote shares versus turnout\nplt.scatter(turnout, SACNS_corrected, s=1)\nplt.xlabel('Turnout Percentage per MER')\nplt.ylabel('Vote Share Percentage for Juan Orlando Hernandez Alvarado per MER')\nplt.title('Vote Share Percentage for Juan Orlando Hernandez Alvarado versus Turnout Percentage per MER')\nplt.show()\n","sub_path":"analytics/Turnout_Distribution_across_all_MERs_not_included_in_the_recount.py","file_name":"Turnout_Distribution_across_all_MERs_not_included_in_the_recount.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"497582473","text":"import os\nimport time\n\nfrom django.apps.registry import AppRegistryNotReady\nfrom django.core.management import call_command\nfrom django.http.response import Http404\nfrom django.utils.translation import gettext_lazy as _\nfrom iceqube.classes import State\nfrom iceqube.exceptions import JobNotFound\nfrom iceqube.exceptions import UserCancelledError\nfrom rest_framework import serializers\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import list_route\nfrom rest_framework.response import Response\nfrom six import string_types\n\nfrom .queue import get_queue\nfrom kolibri.core.content.permissions import CanManageContent\nfrom kolibri.core.content.utils.channels import get_mounted_drive_by_id\nfrom kolibri.core.content.utils.channels import get_mounted_drives_with_channel_info\nfrom kolibri.core.content.utils.paths import get_content_database_file_path\nfrom kolibri.utils import conf\n\ntry:\n from django.apps import apps\n\n apps.check_apps_ready()\nexcept AppRegistryNotReady:\n import django\n\n django.setup()\n\n\nNETWORK_ERROR_STRING = _(\"There was a network error.\")\n\nDISK_IO_ERROR_STRING = _(\"There was a disk access error.\")\n\nCATCHALL_SERVER_ERROR_STRING = _(\"There was an unknown error.\")\n\n\nclass TasksViewSet(viewsets.ViewSet):\n permission_classes = (CanManageContent,)\n\n def list(self, request):\n jobs_response = [_job_to_response(j) for j in get_queue().jobs]\n\n return Response(jobs_response)\n\n def create(self, request):\n # unimplemented. Call out to the task-specific APIs for now.\n pass\n\n def retrieve(self, request, pk=None):\n try:\n task = _job_to_response(get_queue().fetch_job(pk))\n return Response(task)\n except JobNotFound:\n raise Http404(\"Task with {pk} not found\".format(pk=pk))\n\n def destroy(self, request, pk=None):\n # unimplemented for now.\n pass\n\n @list_route(methods=[\"post\"])\n def startremotechannelimport(self, request):\n\n try:\n channel_id = request.data[\"channel_id\"]\n except KeyError:\n raise serializers.ValidationError(\"The channel_id field is required.\")\n\n baseurl = request.data.get(\n \"baseurl\", conf.OPTIONS[\"Urls\"][\"CENTRAL_CONTENT_BASE_URL\"]\n )\n\n job_metadata = {\"type\": \"REMOTECHANNELIMPORT\", \"started_by\": request.user.pk}\n\n job_id = get_queue().enqueue(\n call_command,\n \"importchannel\",\n \"network\",\n channel_id,\n baseurl=baseurl,\n extra_metadata=job_metadata,\n cancellable=True,\n )\n resp = _job_to_response(get_queue().fetch_job(job_id))\n\n return Response(resp)\n\n @list_route(methods=[\"post\"])\n def startremotecontentimport(self, request):\n\n try:\n channel_id = request.data[\"channel_id\"]\n except KeyError:\n raise serializers.ValidationError(\"The channel_id field is required.\")\n\n # optional arguments\n baseurl = request.data.get(\n \"baseurl\", conf.OPTIONS[\"Urls\"][\"CENTRAL_CONTENT_BASE_URL\"]\n )\n node_ids = request.data.get(\"node_ids\", None)\n exclude_node_ids = request.data.get(\"exclude_node_ids\", None)\n\n if node_ids and not isinstance(node_ids, list):\n raise serializers.ValidationError(\"node_ids must be a list.\")\n\n if exclude_node_ids and not isinstance(exclude_node_ids, list):\n raise serializers.ValidationError(\"exclude_node_ids must be a list.\")\n\n job_metadata = {\"type\": \"REMOTECONTENTIMPORT\", \"started_by\": request.user.pk}\n\n job_id = get_queue().enqueue(\n call_command,\n \"importcontent\",\n \"network\",\n channel_id,\n baseurl=baseurl,\n node_ids=node_ids,\n exclude_node_ids=exclude_node_ids,\n extra_metadata=job_metadata,\n track_progress=True,\n cancellable=True,\n )\n\n resp = _job_to_response(get_queue().fetch_job(job_id))\n\n return Response(resp)\n\n @list_route(methods=[\"post\"])\n def startdiskchannelimport(self, request):\n\n # Load the required parameters\n try:\n channel_id = request.data[\"channel_id\"]\n except KeyError:\n raise serializers.ValidationError(\"The channel_id field is required.\")\n\n try:\n drive_id = request.data[\"drive_id\"]\n except KeyError:\n raise serializers.ValidationError(\"The drive_id field is required.\")\n\n try:\n drive = get_mounted_drive_by_id(drive_id)\n except KeyError:\n raise serializers.ValidationError(\n \"That drive_id was not found in the list of drives.\"\n )\n\n job_metadata = {\"type\": \"DISKCHANNELIMPORT\", \"started_by\": request.user.pk}\n\n job_id = get_queue().enqueue(\n call_command,\n \"importchannel\",\n \"disk\",\n channel_id,\n drive.datafolder,\n extra_metadata=job_metadata,\n cancellable=True,\n )\n\n resp = _job_to_response(get_queue().fetch_job(job_id))\n return Response(resp)\n\n @list_route(methods=[\"post\"])\n def startdiskcontentimport(self, request):\n\n try:\n channel_id = request.data[\"channel_id\"]\n except KeyError:\n raise serializers.ValidationError(\"The channel_id field is required.\")\n\n try:\n drive_id = request.data[\"drive_id\"]\n except KeyError:\n raise serializers.ValidationError(\"The drive_id field is required.\")\n\n try:\n drive = get_mounted_drive_by_id(drive_id)\n except KeyError:\n raise serializers.ValidationError(\n \"That drive_id was not found in the list of drives.\"\n )\n\n # optional arguments\n node_ids = request.data.get(\"node_ids\", None)\n exclude_node_ids = request.data.get(\"exclude_node_ids\", None)\n\n if node_ids and not isinstance(node_ids, list):\n raise serializers.ValidationError(\"node_ids must be a list.\")\n\n if exclude_node_ids and not isinstance(exclude_node_ids, list):\n raise serializers.ValidationError(\"exclude_node_ids must be a list.\")\n\n job_metadata = {\"type\": \"DISKCONTENTIMPORT\", \"started_by\": request.user.pk}\n\n job_id = get_queue().enqueue(\n call_command,\n \"importcontent\",\n \"disk\",\n channel_id,\n drive.datafolder,\n node_ids=node_ids,\n exclude_node_ids=exclude_node_ids,\n extra_metadata=job_metadata,\n track_progress=True,\n cancellable=True,\n )\n\n resp = _job_to_response(get_queue().fetch_job(job_id))\n\n return Response(resp)\n\n @list_route(methods=[\"post\"])\n def startdeletechannel(self, request):\n \"\"\"\n Delete a channel and all its associated content from the server\n \"\"\"\n\n if \"channel_id\" not in request.data:\n raise serializers.ValidationError(\"The 'channel_id' field is required.\")\n\n channel_id = request.data[\"channel_id\"]\n\n job_metadata = {\"type\": \"DELETECHANNEL\", \"started_by\": request.user.pk}\n\n task_id = get_queue().enqueue(\n call_command,\n \"deletechannel\",\n channel_id,\n track_progress=True,\n extra_metadata=job_metadata,\n )\n\n # attempt to get the created Task, otherwise return pending status\n resp = _job_to_response(get_queue().fetch_job(task_id))\n\n return Response(resp)\n\n @list_route(methods=[\"post\"])\n def startdiskexport(self, request):\n \"\"\"\n Export a channel to a local drive, and copy content to the drive.\n\n \"\"\"\n\n # Load the required parameters\n try:\n channel_id = request.data[\"channel_id\"]\n except KeyError:\n raise serializers.ValidationError(\"The channel_id field is required.\")\n\n try:\n drive_id = request.data[\"drive_id\"]\n except KeyError:\n raise serializers.ValidationError(\"The drive_id field is required.\")\n\n # optional arguments\n node_ids = request.data.get(\"node_ids\", None)\n exclude_node_ids = request.data.get(\"exclude_node_ids\", None)\n\n if node_ids and not isinstance(node_ids, list):\n raise serializers.ValidationError(\"node_ids must be a list.\")\n\n if exclude_node_ids and not isinstance(exclude_node_ids, list):\n raise serializers.ValidationError(\"exclude_node_ids must be a list.\")\n\n job_metadata = {\"type\": \"DISKEXPORT\", \"started_by\": request.user.pk}\n\n task_id = get_queue().enqueue(\n _localexport,\n channel_id,\n drive_id,\n track_progress=True,\n cancellable=True,\n node_ids=node_ids,\n exclude_node_ids=exclude_node_ids,\n extra_metadata=job_metadata,\n )\n\n # attempt to get the created Task, otherwise return pending status\n resp = _job_to_response(get_queue().fetch_job(task_id))\n\n return Response(resp)\n\n @list_route(methods=[\"post\"])\n def canceltask(self, request):\n \"\"\"\n Cancel a task with its task id given in the task_id parameter.\n \"\"\"\n\n if \"task_id\" not in request.data:\n raise serializers.ValidationError(\"The 'task_id' field is required.\")\n if not isinstance(request.data[\"task_id\"], string_types):\n raise serializers.ValidationError(\"The 'task_id' should be a string.\")\n try:\n get_queue().cancel(request.data[\"task_id\"])\n waiting_time = 0\n job = get_queue().fetch_job(request.data[\"task_id\"])\n interval = 0.1\n while job.state != State.CANCELED or waiting_time < 5.0:\n time.sleep(interval)\n waiting_time += interval\n job = get_queue().fetch_job(request.data[\"task_id\"])\n if job.state != State.CANCELED:\n return Response(status=408)\n get_queue().clear_job(request.data[\"task_id\"])\n except JobNotFound:\n pass\n\n return Response({})\n\n @list_route(methods=[\"post\"])\n def cleartasks(self, request):\n \"\"\"\n Cancels all running tasks.\n \"\"\"\n\n get_queue().empty()\n return Response({})\n\n @list_route(methods=[\"post\"])\n def deletefinishedtasks(self, request):\n \"\"\"\n Delete all tasks that have succeeded, failed, or been cancelled.\n \"\"\"\n get_queue().clear()\n return Response({})\n\n @list_route(methods=[\"get\"])\n def localdrive(self, request):\n drives = get_mounted_drives_with_channel_info()\n\n # make sure everything is a dict, before converting to JSON\n assert isinstance(drives, dict)\n out = [mountdata._asdict() for mountdata in drives.values()]\n\n return Response(out)\n\n @list_route(methods=[\"post\"])\n def startexportlogcsv(self, request):\n \"\"\"\n Dumps in csv format the required logs.\n By default it will be dump contentsummarylog.\n\n :param: logtype: Kind of log to dump, summary or session\n :returns: An object with the job information\n\n \"\"\"\n csv_export_filenames = {\n \"session\": \"content_session_logs.csv\",\n \"summary\": \"content_summary_logs.csv\",\n }\n log_type = request.data.get(\"logtype\", \"summary\")\n if log_type in csv_export_filenames.keys():\n logs_dir = os.path.join(conf.KOLIBRI_HOME, \"log_export\")\n filepath = os.path.join(logs_dir, csv_export_filenames[log_type])\n else:\n raise Http404(\n \"Impossible to create a csv export file for {}\".format(log_type)\n )\n if not os.path.isdir(logs_dir):\n os.mkdir(logs_dir)\n\n job_type = (\n \"EXPORTSUMMARYLOGCSV\" if log_type == \"summary\" else \"EXPORTSESSIONLOGCSV\"\n )\n\n job_metadata = {\"type\": job_type, \"started_by\": request.user.pk}\n\n job_id = get_queue().enqueue(\n call_command,\n \"exportlogs\",\n log_type=log_type,\n output_file=filepath,\n overwrite=\"true\",\n extra_metadata=job_metadata,\n track_progress=True,\n )\n\n resp = _job_to_response(get_queue().fetch_job(job_id))\n\n return Response(resp)\n\n\ndef _localexport(\n channel_id,\n drive_id,\n update_progress=None,\n check_for_cancel=None,\n node_ids=None,\n exclude_node_ids=None,\n extra_metadata=None,\n):\n drive = get_mounted_drive_by_id(drive_id)\n\n call_command(\n \"exportchannel\",\n channel_id,\n drive.datafolder,\n update_progress=update_progress,\n check_for_cancel=check_for_cancel,\n )\n try:\n call_command(\n \"exportcontent\",\n channel_id,\n drive.datafolder,\n node_ids=node_ids,\n exclude_node_ids=exclude_node_ids,\n update_progress=update_progress,\n check_for_cancel=check_for_cancel,\n )\n except UserCancelledError:\n try:\n os.remove(\n get_content_database_file_path(channel_id, datafolder=drive.datafolder)\n )\n except OSError:\n pass\n raise\n\n\ndef _job_to_response(job):\n if not job:\n return {\n \"type\": None,\n \"started_by\": None,\n \"status\": State.SCHEDULED,\n \"percentage\": 0,\n \"progress\": [],\n \"id\": None,\n \"cancellable\": False,\n }\n else:\n return {\n \"type\": getattr(job, \"extra_metadata\", {}).get(\"type\"),\n \"started_by\": getattr(job, \"extra_metadata\", {}).get(\"started_by\"),\n \"status\": job.state,\n \"exception\": str(job.exception),\n \"traceback\": str(job.traceback),\n \"percentage\": job.percentage_progress,\n \"id\": job.job_id,\n \"cancellable\": job.cancellable,\n }\n","sub_path":"kolibri/core/tasks/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":14105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"407729896","text":"import logging\nfrom functools import wraps\nfrom threading import local\nfrom operator import itemgetter\n\nfrom pyes import ES, exceptions\nfrom pyes.es import thrift_enable\n\ntry:\n from statsd import statsd\nexcept ImportError:\n statsd = None\n\ntry:\n from django.conf import settings\nexcept ImportError:\n import es_settings as settings\n\n\n_local = local()\n_local.disabled = {}\nlog = logging.getLogger('elasticsearch')\n\n\ndef get_es():\n \"\"\"Return one es object.\"\"\"\n if not hasattr(_local, 'es'):\n timeout = getattr(settings, 'ES_TIMEOUT', 1)\n dump = getattr(settings, 'ES_DUMP_CURL', False)\n if (not thrift_enable and\n not settings.ES_HOSTS[0].split(':')[1].startswith('92')):\n raise ValueError('ES_HOSTS is not set to a valid port starting '\n 'with 9200-9299 range. Other ports are valid '\n 'if using pythrift.')\n _local.es = ES(settings.ES_HOSTS,\n default_indexes=[settings.ES_INDEXES['default']],\n timeout=timeout, dump_curl=dump)\n return _local.es\n\n\ndef es_required(f):\n @wraps(f)\n def wrapper(*args, **kw):\n if settings.ES_DISABLED:\n # Log once.\n if f.__name__ not in _local.disabled:\n log.debug('Search disabled for %s.' % f)\n _local.disabled[f.__name__] = 1\n return\n\n return f(*args, es=get_es(), **kw)\n return wrapper\n\n\ndef es_required_or_50x(disabled_msg, error_msg):\n \"\"\"\n This takes a Django view that requires ElasticSearch.\n\n If `ES_DISABLED` is `True` then we raise a 501 Not Implemented and display\n the disabled_msg. If we try the view and an ElasticSearch exception is\n raised we raise a 503 error with the error_msg.\n\n We use user-supplied templates in elasticutils/501.html and\n elasticutils/503.html.\n \"\"\"\n def wrap(f):\n @wraps(f)\n def wrapper(request, *args, **kw):\n from django.shortcuts import render\n if settings.ES_DISABLED:\n response = render(request, 'elasticutils/501.html',\n {'msg': disabled_msg})\n response.status_code = 501\n return response\n else:\n try:\n return f(request, *args, **kw)\n except exceptions.ElasticSearchException as error:\n response = render(request, 'elasticutils/503.html',\n {'msg': error_msg, 'error': error})\n response.status_code = 503\n return response\n\n return wrapper\n\n return wrap\n\n\ndef _split(string):\n if '__' in string:\n return string.rsplit('__', 1)\n else:\n return string, None\n\n\ndef _process_filters(filters):\n rv = []\n for f in filters:\n if isinstance(f, F):\n rv.append(f.filters)\n else:\n key, val = f\n key, field_action = _split(key)\n if key == 'or_':\n rv.append({'or':_process_filters(val.items())})\n elif field_action is None:\n rv.append({'term': {key: val}})\n elif field_action == 'in':\n rv.append({'in': {key: val}})\n elif field_action in ('gt', 'gte', 'lt', 'lte'):\n rv.append({'range': {key: {field_action: val}}})\n return rv\n\n\nclass F(object):\n \"\"\"\n Filter objects.\n \"\"\"\n def __init__(self, **filters):\n if filters:\n items = _process_filters(filters.items())\n if len(items) > 1:\n self.filters = {'and': items }\n else:\n self.filters = items[0]\n else:\n self.filters = {}\n\n def _combine(self, other, conn='and'):\n \"\"\"\n OR and AND will create a new F, with the filters from both F objects\n combined with the connector `conn`.\n \"\"\"\n f = F()\n if conn in self.filters:\n f.filters = self.filters\n f.filters[conn].append(other.filters)\n elif conn in other.filters:\n f.filters = other.filters\n f.filters[conn].append(self.filters)\n else:\n f.filters = {conn: [self.filters, other.filters]}\n return f\n\n def __or__(self, other):\n return self._combine(other, 'or')\n\n def __and__(self, other):\n return self._combine(other, 'and')\n\n def __invert__(self):\n f = F()\n if (len(self.filters) < 2 and\n 'not' in self.filters and 'filter' in self.filters['not']):\n f.filters = self.filters['not']['filter']\n else:\n f.filters = {'not': {'filter': self.filters}}\n return f\n\n\n# Number of results to show before truncating when repr(S)\nREPR_OUTPUT_SIZE = 20\n\n\nclass S(object):\n \"\"\"\n Represents a lazy ElasticSearch lookup, with a similar api to Django's\n QuerySet.\n \"\"\"\n def __init__(self, type_):\n self.type = type_\n self.steps = []\n self.start = 0\n self.stop = None\n self.as_list = self.as_dict = False\n self._results_cache = None\n\n def __repr__(self):\n data = list(self)[:REPR_OUTPUT_SIZE + 1]\n if len(data) > REPR_OUTPUT_SIZE:\n data[-1] = \"...(remaining elements truncated)...\"\n return repr(data)\n\n def _clone(self, next_step=None):\n new = self.__class__(self.type)\n new.steps = list(self.steps)\n if next_step:\n new.steps.append(next_step)\n new.start = self.start\n new.stop = self.stop\n return new\n\n def values(self, *fields):\n \"\"\"\n Returns a new S instance whose SearchResults will be of the class\n ListSearchResults.\n \"\"\"\n return self._clone(next_step=('values', fields))\n\n def values_dict(self, *fields):\n \"\"\"\n Returns a new S instance whose SearchResults will be of the class\n DictSearchResults.\n \"\"\"\n return self._clone(next_step=('values_dict', fields))\n\n def order_by(self, *fields):\n \"\"\"\n Returns a new S instance with the ordering changed.\n \"\"\"\n return self._clone(next_step=('order_by', fields))\n\n def query(self, **kw):\n \"\"\"\n Returns a new S instance with the query args combined to the existing\n set.\n \"\"\"\n return self._clone(next_step=('query', kw.items()))\n\n def filter(self, *filters, **kw):\n \"\"\"\n Returns a new S instance with the filter args combined to the existing\n set.\n \"\"\"\n return self._clone(next_step=('filter', list(filters) + kw.items()))\n\n def facet(self, **kw):\n \"\"\"\n Returns a new S instance with the facet args combined to the existing\n set.\n \"\"\"\n return self._clone(next_step=('facet', kw.items()))\n\n def extra(self, **kw):\n \"\"\"\n Returns a new S instance with the extra args combined with the existing\n set.\n \"\"\"\n new = self._clone()\n actions = 'values values_dict order_by query filter facet'.split()\n for key, vals in kw.items():\n assert key in actions\n if hasattr(vals, 'items'):\n new.steps.append((key, vals.items()))\n else:\n new.steps.append((key, vals))\n return new\n\n def count(self):\n \"\"\"\n Returns the number of hits for the current query and filters as an\n integer.\n \"\"\"\n if self._results_cache:\n return self._results_cache.count\n else:\n return self[:0].raw()['hits']['total']\n\n def __len__(self):\n return len(self._do_search())\n\n def __getitem__(self, k):\n new = self._clone()\n # TODO: validate numbers and ranges\n if isinstance(k, slice):\n new.start, new.stop = k.start or 0, k.stop\n return new\n else:\n new.start, new.stop = k, k + 1\n return list(new)[0]\n\n def _build_query(self):\n \"\"\"\n Loops self.steps to build the query format that will be sent to\n ElasticSearch, and returns it as a dict.\n \"\"\"\n filters = []\n queries = []\n sort = []\n fields = ['id']\n facets = {}\n as_list = as_dict = False\n for action, value in self.steps:\n if action == 'order_by':\n sort = []\n for key in value:\n if key.startswith('-'):\n sort.append({key[1:]: 'desc'})\n else:\n sort.append(key)\n elif action == 'values':\n fields.extend(value)\n as_list, as_dict = True, False\n elif action == 'values_dict':\n if not value:\n fields = []\n else:\n fields.extend(value)\n as_list, as_dict = False, True\n elif action == 'query':\n queries.extend(self._process_queries(value))\n elif action == 'filter':\n filters.extend(_process_filters(value))\n elif action == 'facet':\n facets.update(value)\n else:\n raise NotImplementedError(action)\n\n qs = {}\n if len(filters) > 1:\n qs['filter'] = {'and': filters}\n elif filters:\n qs['filter'] = filters[0]\n\n if len(queries) > 1:\n qs['query'] = {'bool': {'must': queries}}\n elif queries:\n qs['query'] = queries[0]\n\n if fields:\n qs['fields'] = fields\n if facets:\n qs['facets'] = facets\n # Copy filters into facets. You probably wanted this.\n for facet in facets.values():\n if 'facet_filter' not in facet and filters:\n facet['facet_filter'] = qs['filter']\n if sort:\n qs['sort'] = sort\n if self.start:\n qs['from'] = self.start\n if self.stop is not None:\n qs['size'] = self.stop - self.start\n\n self.fields, self.as_list, self.as_dict = fields, as_list, as_dict\n return qs\n\n def _process_queries(self, value):\n rv = []\n value = dict(value)\n or_ = value.pop('or_', [])\n for key, val in value.items():\n key, field_action = _split(key)\n if field_action is None:\n rv.append({'term': {key: val}})\n elif field_action == 'text':\n rv.append({'text': {key: val}})\n elif field_action == 'startswith':\n rv.append({'prefix': {key: val}})\n elif field_action in ('gt', 'gte', 'lt', 'lte'):\n rv.append({'range': {key: {field_action: val}}})\n elif field_action == 'fuzzy':\n rv.append({'fuzzy': {key: val}})\n if or_:\n rv.append({'bool': {'should': self._process_queries(or_.items())}})\n return rv\n\n def _do_search(self):\n \"\"\"\n Performs the search, then converts that raw format into a\n SearchResults instance and returns it.\n \"\"\"\n if not self._results_cache:\n hits = self.raw()\n if self.as_dict:\n ResultClass = DictSearchResults\n elif self.as_list:\n ResultClass = ListSearchResults\n else:\n ResultClass = ObjectSearchResults\n self._results_cache = ResultClass(self.type, hits, self.fields)\n return self._results_cache\n\n def raw(self):\n \"\"\"\n Builds query and passes to ElasticSearch, then returns the raw format\n returned.\n \"\"\"\n qs = self._build_query()\n es = get_es()\n index = (settings.ES_INDEXES.get(self.type)\n or settings.ES_INDEXES['default'])\n try:\n hits = es.search(qs, index, self.type._meta.db_table)\n except Exception:\n log.error(qs)\n raise\n if statsd:\n statsd.timing('search', hits['took'])\n log.debug('[%s] %s' % (hits['took'], qs))\n return hits\n\n def __iter__(self):\n return iter(self._do_search())\n\n def raw_facets(self):\n return self._do_search().results.get('facets', {})\n\n @property\n def facets(self):\n facets = {}\n for key, val in self.raw_facets().items():\n if val['_type'] == 'terms':\n facets[key] = [v for v in val['terms']]\n elif val['_type'] == 'range':\n facets[key] = [v for v in val['ranges']]\n return facets\n\n\nclass SearchResults(object):\n def __init__(self, type, results, fields):\n self.type = type\n self.took = results['took']\n self.count = results['hits']['total']\n self.results = results\n self.fields = fields\n self.set_objects(results['hits']['hits'])\n\n def set_objects(self, hits):\n raise NotImplementedError()\n\n def __iter__(self):\n return iter(self.objects)\n\n def __len__(self):\n return len(self.objects)\n\n\nclass DictSearchResults(SearchResults):\n def set_objects(self, hits):\n key = 'fields' if self.fields else '_source'\n self.objects = [r[key] for r in hits]\n\n\nclass ListSearchResults(SearchResults):\n def set_objects(self, hits):\n if self.fields:\n getter = itemgetter(*self.fields)\n objs = [getter(r['fields']) for r in hits]\n else:\n objs = [r['_source'].values() for r in hits]\n self.objects = objs\n\n\nclass ObjectSearchResults(SearchResults):\n def set_objects(self, hits):\n self.ids = [int(r['_id']) for r in hits]\n self.objects = self.type.objects.filter(id__in=self.ids)\n\n def __iter__(self):\n objs = dict((obj.id, obj) for obj in self.objects)\n return (objs[id] for id in self.ids if id in objs)\n\n","sub_path":"elasticutils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"483566978","text":"def Test():\n s=input()\n result=X(s)\n print(s)\n\ndef X(s):\n left=s.find(\"[\")\n right=s.rfind(\"]\")\n if(left!=-1 and right!=-1):\n numindex=left+1\n num=int(s[numindex])\n mask=s[numindex+1:right]\n answer=\"\"\n for i in range(0,num):\n answer=answer+X(mask)\n s=s[:left]+answer+s[right+1:]\n return s\n\nif __name__ == \"__main__\":\n Test()","sub_path":"Code/CodeRecords/2934/60595/237226.py","file_name":"237226.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"499772570","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom numpy.fft import rfft\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nmpl.rcParams['agg.path.chunksize'] = 10000\n\nimport general_tools, get_data\n\n\"\"\"\nSome general text definitions\n\"\"\"\nplotting_message=\"Plotting dump data...\"\ntime_label=\"Time (ms)\"\nfrequency_label=\"Frequency (Hz)\"\nspectral_power_density_label=r\"Power spectral density (dB/$\\sqrt{Hz}$)\"\nerror_t0_message=\"Wrong zoom parameter, t0 changed to 0s.\"\n\n# -----------------------------------------------------------------------\ndef mosaic_labels(ax, box, n_cols, n_lines, x_lab, y_lab):\n r\"\"\"\n This function defines the xlabel and ylabel for a plot in a plot mosaic.\n The xlabel is displayed only for the plots at the bottom of the mosaic.\n The ylabel is displayed only for the plots at the left of the mosaic.\n\n Parameters\n ----------\n ax : matplotlib axis\n\n box : number\n the number of the plot in the mosaic\n\n n_cols, n_lines : numbers\n the number of columns and lines in the mosaic\n\n x_lab, y_lab : string\n the x and y labels\n\n Returns\n -------\n Nothing\n\n \"\"\"\n if box//n_cols == n_lines-1:\n ax.set_xlabel(x_lab)\n else:\n plt.xticks(visible=False)\n if box%n_cols == 0:\n ax.set_ylabel(y_lab)\n else:\n plt.yticks(visible=False)\n\n\n# -----------------------------------------------------------------------------\ndef plot_science_dump(data, plotfilename, config, t0=0, duration=0, pix_zoom=0, noise=False, sav_spectra=False):\n r\"\"\"\n This function checks the data of a DRE-DEMUX science data dump.\n\n Parameters\n ----------\n data: numpy array\n The data of the dump \n\n plotfilename: string\n Name of the plot file (with the path)\n\n config: dictionnary\n contains different informations such as path and directory names\n\n t0: number, optional\n begining of zoom in seconds (default is 0)\n\n duration: number, optional\n zoom duration in seconds. If 0 all the data are plotted (default is 0)\n\n pix_zoom: number (integer)\n pixel id refering to the pixel for which we plot a zoom (default=0)\n\n noise: boolean\n Indicates if a noise analysis shall be done (default=False)\n\n sav_spectra: boolean\n indicates if spactra shall be saved in npy file (default=False)\n\n Returns\n -------\n Nothing\n\n \"\"\"\n print(plotting_message)\n plotfilename_zoom = plotfilename[:-4]+\"_zoom.png\"\n plotfilename_all = plotfilename[:-4]+\"_all.png\"\n print(\" >> \" + plotfilename_zoom)\n print(\" >> \" + plotfilename_all)\n\n npix = int(config[\"npix\"])\n fs = float(config[\"frow\"]/npix)\n t = np.arange(len(data[0,:]))/fs\n\n packet_nb = data[0,:]\n reference = packet_nb[0] + np.arange(len(packet_nb))\n if np.abs((packet_nb-reference)%2**32).max()>0:\n print(\" Error in the packet number !\")\n plt.plot(packet_nb-reference)\n plt.show()\n\n data = data[1:,:]\n\n \"\"\"\n Plotting data in time domain\n \"\"\"\n imin = int(t0*fs)\n if imin > len(data[0,:]):\n print(error_t0_message)\n imin = 0\n if duration == 0 :\n imax = len(data[0,:])\n else :\n imax = min(int((t0+duration)*fs), len(data[0,:]))\n mkr=''\n if imax - imin < 200:\n mkr='.'\n\n fig = plt.figure(figsize=(18, 12))\n xtitle = time_label\n\n ncols, nlines = 9, 4\n ymin, ymax = 0.98*data.min(), 1.02*data.max()\n for pix in range(npix):\n ax = fig.add_subplot(nlines, ncols, 1+pix)\n ax.plot(1000*t[imin:imax], data[pix,imin:imax], 'b')\n ax.set_title(\"Pixel {0:2d}\".format(1+pix))\n ax.grid(color='k', linestyle=':', linewidth=0.5)\n ax.set_xlim(t[imin]*1000, t[imax-1]*1000)\n ax.set_ylim(ymin, ymax)\n mosaic_labels(ax, pix, ncols, nlines, xtitle, r'ADU')\n for item in ([ax.title, ax.xaxis.label, ax.yaxis.label]):\n item.set_weight('bold')\n item.set_fontsize(12)\n for item in (ax.get_xticklabels() + ax.get_yticklabels()):\n item.set_fontsize(10)\n ax = fig.add_subplot(nlines, ncols, ncols*nlines)\n ax.plot(1000*t[imin:imax], packet_nb[imin:imax], 'b')\n ax.set_title(\"Packet number\")\n ax.set_xlabel(xtitle)\n ax.grid(color='k', linestyle=':', linewidth=0.5)\n\n fig.tight_layout()\n #plt.show()\n plt.savefig(plotfilename_all, bbox_inches='tight')\n\n \"\"\"\n doing zoom\n \"\"\"\n fig = plt.figure(figsize=(10, 8))\n ax = fig.add_subplot(1, 1, 1)\n ax.plot(1000*t[imin:imax], data[pix_zoom,imin:imax], 'b', marker=mkr)\n ax.set_title(\"Pixel {0:2d}\".format(1+pix_zoom))\n ax.set_xlabel(xtitle)\n ax.set_ylabel(r'ADU')\n ax.set_xlim(t[imin]*1000, t[imax-1]*1000)\n ax.grid(color='k', linestyle=':', linewidth=0.5)\n for item in ([ax.title, ax.xaxis.label, ax.yaxis.label]):\n item.set_weight('bold')\n item.set_fontsize(14)\n for item in (ax.get_xticklabels() + ax.get_yticklabels()):\n item.set_fontsize(12)\n\n fig.tight_layout()\n #plt.show()\n plt.savefig(plotfilename_zoom, bbox_inches='tight')\n\n \"\"\"\n Plotting spectra\n \"\"\"\n if noise:\n plot_science_dump_noise(data, config, plotfilename[:-4]+\"_noise.png\", pix_zoom, 8192, sav_spectra)\n\n# -----------------------------------------------------------------------------\ndef plot_science_dump_noise(data, config, plotfilename, pix_zoom=0, record_len=8192, sav=False):\n r\"\"\"\n This function measures noise spectra on science data\n\n Parameters\n ----------\n data: 2-dimensional numpy array\n The input science data\n\n config: dictionnary\n contains different informations such as path and directory names\n\n plotfilename: string\n Name of the plot file (with the path)\n\n pix_zoom: number (integer)\n pixel id refering to the pixel for which we plot a zoom (default=0)\n\n record_len: number (integer)\n number of samples per records (default = 8192)\n\n sav: boolean\n indicates if spactra shall be saved in npy file (default=False)\n\n Returns\n -------\n noise_spectra: 2-dimensional numpy array\n The noise spectra\n \"\"\"\n print(\"Plotting noise from dump data...\")\n plotfilename_zoom = plotfilename[:-4]+\"_zoom.png\"\n plotfilename_all = plotfilename[:-4]+\"_all.png\"\n print(\" >> \" + plotfilename_zoom)\n print(\" >> \" + plotfilename_all)\n\n n_pix = int(config[\"npix\"])\n fs = float(config[\"frow\"]/n_pix)\n ylabel=r\"Power density (dB/$\\sqrt{Hz}$)\"\n\n if record_len > len(data[0]):\n print(\" Requested record length is too high ({0:5d})...\".format(record_len))\n record_len = 2**(np.log10(len(data[0]))//np.log10(2))\n print(\" Record length reduced to {0:5d}\".format(record_len))\n else:\n print(\" Record length: {0:5d}\".format(record_len))\n\n n_records = int(len(data[0])/record_len)\n print(\" Number of records: {0:5d}\".format(n_records))\n\n noise_spectra = np.zeros((n_pix, int(record_len/2)+1))\n for pix in range(n_pix):\n noise_spectra[pix,:]=general_tools.do_spectrum(data[pix,0:n_records*record_len], record_len)\n\n noise_spectra_db = noise_spectra*0\n inotzero = np.where(noise_spectra != 0)\n noise_spectra_db[inotzero] = 20.*np.log10(noise_spectra[inotzero])\n\n # normalisation with respect to baseline\n for pix in range(n_pix):\n noise_spectra_db[pix,:] -= noise_spectra_db[pix,:].max()\n\n n = len(noise_spectra_db[0])\n f = np.arange(n)*(fs/2)/n\n\n if sav:\n dirname = os.path.join(os.path.normcase(config['path']), config['dir_data'])\n npy_file = os.path.join(dirname, 'sc_spectra.npy')\n with open(npy_file, 'wb') as file:\n np.save(file, f)\n np.save(file, noise_spectra_db)\n\n # plotting zoom\n db_step = 5\n ymin = db_step*(noise_spectra_db[pix_zoom, 1:].min()//db_step)\n ymax = db_step*(noise_spectra_db[pix_zoom, 1:].max()//db_step+1)\n fig = plt.figure(figsize=(10, 7))\n ax1 = fig.add_subplot(1, 1, 1)\n ax1.semilogx(f, noise_spectra_db[pix_zoom,:], marker='.')\n ax1.set_ylabel(ylabel)\n ax1.set_xlabel(frequency_label)\n ax1.set_title(\"Pixel {0:2d}\".format(1+pix_zoom))\n major_ticks=np.linspace(ymin,ymax,db_step)\n ax1.set_xlim(f[1], f[-1])\n ax1.set_ylim(ymin, ymax)\n ax1.set_yticks(major_ticks)\n ax1.grid(which=\"major\",alpha=0.6)\n for item in ([ax1.title, ax1.xaxis.label, ax1.yaxis.label]):\n item.set_weight('bold')\n item.set_fontsize(14)\n for item in (ax1.get_xticklabels() + ax1.get_yticklabels()):\n item.set_fontsize(12)\n #plt.show()\n fig.tight_layout()\n plt.savefig(plotfilename_zoom, bbox_inches='tight')\n\n fig = plt.figure(figsize=(18, 12))\n ncols, nlines = 9, 4\n ymin = db_step*(noise_spectra_db[:, 1:].min()//db_step)\n ymax = db_step*(noise_spectra_db[:, 1:].max()//db_step+1)\n major_ticks=np.linspace(ymin,ymax,db_step)\n for pix in range(n_pix):\n ax = fig.add_subplot(nlines, ncols, 1+pix)\n ax.semilogx(f, noise_spectra_db[pix,:], marker='.')\n ax.set_title(\"Pixel {0:2d}\".format(1+pix))\n ax.grid(color='k', linestyle=':', linewidth=0.5)\n ax.set_ylim(ymin, ymax)\n ax.set_xlim(f[1], f[-1])\n ax.set_yticks(major_ticks)\n mosaic_labels(ax, pix, ncols, nlines, frequency_label, ylabel)\n ax.grid(which=\"major\",alpha=0.6)\n for item in ([ax.title, ax.xaxis.label, ax.yaxis.label]):\n item.set_weight('bold')\n item.set_fontsize(12)\n for item in (ax.get_xticklabels() + ax.get_yticklabels()):\n item.set_fontsize(10)\n fig.tight_layout()\n #plt.show()\n plt.savefig(plotfilename_all, bbox_inches='tight')\n\n return(noise_spectra)\n\n# -----------------------------------------------------------------------------\ndef plot_adc_dump(data, plotfilename, config, t0=0, duration=0, spectral=False, sav=False):\n r\"\"\"\n This function checks the data of a DRE-DEMUX ADC data dump.\n\n Parameters\n ----------\n data: numpy array\n The data of the dump \n\n plotfilename: string\n Name of the plot file (with the path)\n\n config: dictionnary\n contains different informations such as path and directory names\n\n t0: number, optional\n begining of zoom in seconds (default is 0)\n\n duration: number, optional\n zoom duration in seconds. If 0 all the data are plotted (default is 0)\n\n spectral: boolean\n If True a spectral nalysis shall be done (default=False)\n\n sav: boolean\n indicates if spectra shall be saved in npy file (default=False)\n\n Returns\n -------\n Nothing\n\n \"\"\"\n ylabel_adu = \"ADC values (ADU)\"\n ylabel_v = \"ADC values (V)\"\n\n print(plotting_message)\n print(\" >> \" + plotfilename)\n\n fs = float(config[\"fs_ADC\"])\n t = np.arange(len(data))/fs\n\n \"\"\"\n Plotting data in time domain\n \"\"\"\n imin = int(t0*fs)\n if imin > len(data[:]):\n print(error_t0_message)\n imin = 0\n if duration == 0 :\n imax = len(data[:])\n else :\n imax = min(int((t0+duration)*fs), len(data[:]))\n\n fig = plt.figure(figsize=(6, 8))\n xtitle = time_label\n mkr='.'\n if imax-imin<300:\n mkr='.'\n\n ax1 = fig.add_subplot(2, 1, 1)\n ax1.plot(1000*t[imin:imax], data[imin:imax]/float(config[\"adc_1volt_in_adu\"]), 'b', marker=mkr)\n ax1.set_ylabel(ylabel_v)\n ax1.set_xlabel(xtitle)\n ax1.grid(color='k', linestyle=':', linewidth=0.5)\n y1min, y1max=ax1.get_ylim()\n ax11=ax1.twinx()\n ax11.set_ylabel(ylabel_adu)\n ax11.set_ylim(y1min*float(config[\"adc_1volt_in_adu\"]), y1max*float(config[\"adc_1volt_in_adu\"]))\n\n ax2 = fig.add_subplot(2, 1, 2)\n ax2.plot(1000*t, data/float(config[\"adc_1volt_in_adu\"]), 'b')\n ax2.set_ylabel(ylabel_v)\n ax2.set_xlabel(xtitle)\n ax2.grid(color='k', linestyle=':', linewidth=0.5)\n y2min, y2max=ax2.get_ylim()\n ax22=ax2.twinx()\n ax22.set_ylabel(ylabel_adu)\n ax22.set_ylim(y2min*float(config[\"adc_1volt_in_adu\"]), y2max*float(config[\"adc_1volt_in_adu\"]))\n\n fig.tight_layout()\n #plt.show()\n plt.savefig(plotfilename, bbox_inches='tight')\n\n if spectral:\n # Plotting data in frequency domain\n spt = general_tools.do_spectrum(data, int(2**20))\n spt_db = spt*0\n inotzero = np.where(spt != 0)[0]\n spt_db[inotzero] = 20*np.log10(spt[inotzero])\n\n f = np.arange(len(spt_db))*(fs/2)/len(spt_db)\n\n \"\"\"\n saving data in a npy file if requested\n \"\"\"\n if sav:\n dirname = os.path.join(os.path.normcase(config['path']), config['dir_data'])\n npy_file = os.path.join(dirname, 'adc_spectra.npy')\n with open(npy_file, 'wb') as file:\n np.save(file, f)\n np.save(file, spt_db)\n\n fig = plt.figure(figsize=(10, 8))\n ax1 = fig.add_subplot(1, 1, 1)\n ax1.semilogx(f, spt_db, 'b')\n ax1.set_ylabel(spectral_power_density_label)\n ax1.set_xlabel(frequency_label)\n ax1.grid(color='k', linestyle=':', linewidth=0.5)\n ax1.set_xlim(1e3, f[-1])\n for item in ([ax1.title, ax1.xaxis.label, ax1.yaxis.label]):\n item.set_weight('bold')\n item.set_fontsize(14)\n for item in (ax1.get_xticklabels() + ax1.get_yticklabels()):\n item.set_fontsize(12)\n\n fig.tight_layout()\n #plt.show()\n plt.savefig(plotfilename[:-4]+\"_F.png\", bbox_inches='tight')\n\n# -----------------------------------------------------------------------------\ndef plot_5mega_dump(data1, data2, plotfilename, config, title1, title2, t0=0, duration=0):\n r\"\"\"\n This function checks the data of a DRE-DEMUX ADC data dump.\n\n Parameters\n ----------\n data1, data2 : numpy arrays\n Contains the 2 sets of data\n\n plotfilename : string\n Name of the plot file (with the path)\n\n config: dictionnary\n contains different informations such as path and directory names\n\n title1 : string\n Name of the first data set\n\n title2 : string\n Name of the second data set\n\n t0: number, optional\n begining of zoom in seconds (default is 0)\n\n duration: number, optional\n zoom duration in seconds. If 0 all the data are plotted (default is 0)\n\n Returns\n -------\n Nothing\n\n \"\"\"\n print(plotting_message)\n print(\" >> \" + plotfilename)\n\n # In these dumps the 5MHz data are over sampled at 20MHz\n fs = float(config[\"frow\"])*4 # Approx 20MHz\n t = np.arange(len(data1))/fs\n\n \"\"\"\n Plotting data\n \"\"\"\n imin = int(t0*fs)\n if imin > len(data1):\n print(error_t0_message)\n imin = 0\n if duration == 0 :\n imax = len(data1)\n else :\n imax = min(int((t0+duration)*fs), len(data1))\n\n fig = plt.figure(figsize=(10, 8))\n xtitle = \"Time (ms)\"\n mkr=''\n if imax-imin<300:\n mkr='.'\n\n ax1 = fig.add_subplot(2, 2, 1)\n ax1.plot(1000*t[imin:imax], data1[imin:imax], 'b', marker=mkr)\n ax1.set_ylabel(title1)\n ax1.set_xlabel(xtitle)\n ax1.grid(color='k', linestyle=':', linewidth=0.5)\n\n ax3 = fig.add_subplot(2, 2, 3)\n ax3.plot(1000*t, data1, 'b')\n ax3.set_ylabel(title1)\n ax3.set_xlabel(xtitle)\n ax3.grid(color='k', linestyle=':', linewidth=0.5)\n\n ax2 = fig.add_subplot(2, 2, 2)\n ax2.plot(1000*t[imin:imax], data2[imin:imax], 'b', marker=mkr)\n ax2.set_ylabel(title2)\n ax2.set_xlabel(xtitle)\n ax2.grid(color='k', linestyle=':', linewidth=0.5)\n\n ax4 = fig.add_subplot(2, 2, 4)\n ax4.plot(1000*t, data2, 'b')\n ax4.set_ylabel(title2)\n ax4.set_xlabel(xtitle)\n ax4.grid(color='k', linestyle=':', linewidth=0.5)\n\n fig.tight_layout()\n #plt.show()\n plt.savefig(plotfilename, bbox_inches='tight')\n\n# -----------------------------------------------------------------------------\ndef plot_counter_dump(data, plotfilename, config):\n r\"\"\"\n This function checks the data of a DRE-DEMUX COUNTER data dump.\n\n Parameters\n ----------\n data : numpy array\n The data of the dump \n\n plotfilename : string\n Name of the plot file (with the path)\n\n config: dictionnary\n contains different informations such as path and directory names\n\n Returns\n -------\n Nothing\n\n \"\"\"\n print(plotting_message)\n print(\" >> \" + plotfilename)\n\n fs = float(config[\"frow\"])*4 # Approx 20MHz\n t = np.arange(len(data))/fs\n\n reference = np.arange(len(data))\n if np.abs(data-reference).max()>0:\n print(\" Error in the counter data.\")\n\n # Plotting data\n fig = plt.figure(figsize=(6, 8))\n fig.suptitle(\"Counter32 dump file\")\n xtitle = time_label\n\n ax1 = fig.add_subplot(2, 1, 1)\n ax1.plot(1000*t, data, 'b')\n ytitle = \"32-bit Counter values\"\n ax1.set_ylabel(ytitle)\n ax1.set_xlabel(xtitle)\n ax1.grid(color='k', linestyle=':', linewidth=0.5)\n\n ax2 = fig.add_subplot(2, 1, 2)\n ax2.plot(1000*t, data-reference, 'b')\n ytitle = \"32-bit counter - reference\"\n ax2.set_ylabel(ytitle)\n ax2.set_xlabel(xtitle)\n ax2.grid(color='k', linestyle=':', linewidth=0.5)\n\n fig.tight_layout()\n #plt.show()\n plt.savefig(plotfilename, bbox_inches='tight')\n\n# -----------------------------------------------------------------------------\n\"\"\"\nTesting the routines with test data.\n\"\"\"\nif __name__ == \"__main__\":\n\n print(\"Testing the dumps analysis...\")\n config=general_tools.configuration(\"demux_tools_cfg\")\n config.config[\"path\"]=\".\"\n config.config[\"dir_data\"]=\"test_data\"\n config.config[\"dir_plots\"]=\"test_plots\"\n datadirname = os.path.join(os.path.normcase(config.config['dir_data'])) \n dumpfilenames = [f for f in os.listdir(datadirname) \\\n if os.path.isfile(os.path.join(datadirname, f)) \\\n and f[-4:]==\".dat\"]\n\n for file in dumpfilenames:\n print('\\n#---------------------')\n d=get_data.data(file, config.config)\n d.print_dumptype()\n t0, duration = 0, 0\n pix_zoom = 0\n spectral = True\n noise = True\n check_noise_measurement = True\n d.plot(t0, duration, pix_zoom, spectral, noise, check_noise_measurement)\n\n# -----------------------------------------------------------------------------\ndef over_plot_records(records):\n fig = plt.figure(figsize=(10, 8))\n ax = fig.add_subplot(1, 1, 1)\n for i_record in range(len(records)):\n ax.plot(records[i_record,:])\n fig.tight_layout()\n plt.show()\n\n# -----------------------------------------------------------------------------\n","sub_path":"plotting_tools.py","file_name":"plotting_tools.py","file_ext":"py","file_size_in_byte":18853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"19189686","text":"\nimport time\nimport sys\nimport traceback\nimport datetime\nimport numpy as np\nimport pickle\nfrom optimizer_params import *\nimport tensorflow as tf\n\n#import matplotlib.pyplot as plt\nfrom dataset import DataSet\nfrom splitdataset import SplitDataset2\nfrom baseline_nn import Baseline_nn\nfrom baseline_cnn import Baseline_cnn\nfrom baseline_axn import Baseline_axn\nfrom baseline_axn2 import Baseline_axn2\nfrom baseline_lr import Baseline_lr\n\ndef run(model, iteration, num_batches=50000):\n\n try:\n start = time.time()\n\n model.run_session(num_batches)\n\n timeCompleted = round((time.time( ) -start ) /60, 2)\n print(\"Completed in {} minutes\".format(timeCompleted))\n model.params['time'] = timeCompleted\n\n # Save\n base_filename = 'saved_{}_{:03d}'.format(model.name, iteration)\n\n print(base_filename)\n\n np.save('{}.preds'.format(base_filename), model.test_preds)\n pickle.dump(model.params, open('{}.params'.format(base_filename), 'wb'))\n pickle.dump(model.optimizer_params, open('{}.opt'.format(base_filename), 'wb'))\n pickle.dump(model.epochs, open('{}.epochs'.format(base_filename), 'wb'))\n except:\n e = sys.exc_info()[0]\n print('Exception encountered: ', e)\n print(traceback.format_exc())\n\n\ndef searchForNNParams(ds, num_epochs=30000):\n\n # Define Hyper-parameters\n batch_sizes = { 64, 128, 256 }\n hidden_nodes = {512, 1024, 2048, 4096}\n lamb_regs = {0.005, 0.01, 0.05}\n\n iteration = 0\n\n # Perform a Grid Search on all hyper-parameters\n for batch_size in batch_sizes:\n for hidden_node in hidden_nodes:\n for lamb_reg in lamb_regs:\n nn = Baseline_nn(ds)\n nn.create(batch_size=batch_size, hidden_nodes=hidden_node, lamb_reg=lamb_reg)\n run(nn, iteration, num_epochs)\n nn = None\n iteration += 1\n\n\ndef searchForCNNParams(ds, num_batches=30000):\n # Define Hyper-parameters\n batch_sizes = { 8, 16, 32, 64, 128, 256 }\n patch_sizes = { 5, 6, 8, 10, 12 }\n\n # This seriously chews up memory\n depth1s = { 32, 64 }\n depth2s = { 64, 128 }\n num_hiddens = { 1024, 2048 }\n\n iteration = 0\n\n # Perform a Grid Search on all hyper-parameters\n for batch_size in batch_sizes:\n for patch_size in patch_sizes:\n for depth1 in depth1s:\n for depth2 in depth2s:\n for num_hidden in num_hiddens:\n cnn = Baseline_cnn(ds)\n cnn.create(batch_size=batch_size,\n patch_size=patch_size,\n depth1=depth1,\n depth2=depth2,\n num_hidden=num_hidden)\n run(cnn, iteration, num_batches)\n cnn = None\n iteration += 1\n\n\ndef searchForAXN2AdamParams(ds, num_batches=50000):\n # Define Hyper-parameters\n\n learning_rates = { 0.1, 0.01, 0.001, 0.0001 }\n beta1s = { 0.8, 0.9, 0.99, 0.999 }\n beta2s = { 0.8, 0.9, 0.99, 0.999 }\n\n epsilons = { 1e-10, 1e-8, 1e-6, 1e-4 }\n\n\n iteration = 200\n\n # Perform a Grid Search on all hyper-parameters\n for learning_rate in learning_rates:\n for beta1 in beta1s:\n for beta2 in beta2s:\n for epsilon in epsilons:\n cnn = Baseline_axn2(ds)\n cnn.create(optimizer_params=AdamParams(learning_rate=learning_rate,\n beta1=beta1,\n beta2=beta2,\n epsilon=epsilon))\n run(cnn, iteration, num_batches)\n iteration += 1\n\n\ndef searchForAXN2AdadeltaParams(ds, num_batches=50000):\n # Define Hyper-parameters\n\n learning_rates = { 0.1, 0.01, 0.001, 0.0001 }\n rhos = { 0.8, 0.9, 0.95, 0.999 }\n\n epsilons = { 1e-10, 1e-8, 1e-6, 1e-4 }\n\n\n iteration = 300\n\n # Perform a Grid Search on all hyper-parameters\n for learning_rate in learning_rates:\n for rho in rhos:\n for epsilon in epsilons:\n cnn = Baseline_axn2(ds)\n cnn.create(optimizer_params=AdadeltaParams(learning_rate=learning_rate,\n rho=rho,\n epsilon=epsilon))\n run(cnn, iteration, num_batches)\n iteration += 1\n\n\ndef searchForAXN2GDParams(ds, num_batches=50000):\n # Define Hyper-parameters\n\n learning_rates = { 0.1, 0.01, 0.001, 0.0001 }\n\n iteration = 0\n\n # Perform a Grid Search on all hyper-parameters\n for learning_rate in learning_rates:\n axn2 = Baseline_axn2(ds)\n axn2.create(optimizer_params=GradientDescentParams(learning_rate=learning_rate))\n run(axn2, iteration, num_batches)\n iteration += 1\n\n\ndef searchForAXN2AdagradParams(ds, num_batches=50000):\n # Define Hyper-parameters\n\n learning_rates = { 0.1, 0.01, 0.001, 0.0001 }\n initial_accumulator_values = {0.001, 0.01, 0.1, 1}\n\n iteration = 100\n\n # Perform a Grid Search on all hyper-parameters\n for learning_rate in learning_rates:\n for initial_accumulator_value in initial_accumulator_values:\n axn2 = Baseline_axn2(ds)\n axn2.create(optimizer_params=AdagradParams(learning_rate=learning_rate,\n initial_accumulator_value=initial_accumulator_value))\n run(axn2, iteration, num_batches)\n iteration += 1\n\n\ndef runNNs():\n flatDataSet = DataSet()\n flatDataSet.load()\n\n # Baseline Neural Network\n nn = Baseline_nn(flatDataSet)\n nn.create(start_learning_rate = 0.01)\n run(nn, 0, num_batches=50000)\n\n # Search for parameters\n #searchForNNParams(flatDataSet)\n\n\ndef runCNNs():\n\n shapedDataSet = DataSet()\n shapedDataSet.load(False)\n\n # Baseline CNN\n cnn = Baseline_cnn(shapedDataSet)\n cnn.create()\n run(cnn, 0, num_batches=50000)\n\n # Search for parameters\n #searchForCNNParams(shapedDataSet, num_batches=60000)\n\n\ndef runAXNs():\n\n shapedDataSet = DataSet(use_valid=False)\n shapedDataSet.load(False)\n\n # Baseline AXN\n axn = Baseline_axn(shapedDataSet)\n axn.create(AdamParams(), batch_size=128)\n run(axn, 0, num_batches=50000)\n\n # Search for parameters\n #searchForAXNParams(shapedDataSet, num_batches=1000)\n\n\ndef runSplitNNs():\n\n def runSingleNN(ds, iteration):\n axn = Baseline_nn(ds)\n axn.create()\n run(axn, iteration, num_batches=20000)\n\n ds = DataSet(use_valid=False)\n ds.load()\n\n split = SplitDataset()\n split.load(ds.train_dataset, ds.train_labels)\n\n ds.train_dataset = split.a_dataset\n ds.train_labels = split.a_labels\n runSingleNN(ds,0)\n\n ds.train_dataset = split.ab_dataset\n ds.train_labels = split.ab_labels\n runSingleNN(ds, 1)\n\n ds.train_dataset = split.abc_dataset\n ds.train_labels = split.abc_labels\n runSingleNN(ds, 2)\n\n ds.train_dataset = split.abcd_dataset\n ds.train_labels = split.abcd_labels\n runSingleNN(ds, 3)\n\n\ndef runSplitCNNs():\n\n def runSingleCNN(ds, iteration):\n axn = Baseline_cnn(ds)\n axn.create()\n run(axn, iteration, num_batches=20000)\n\n ds = DataSet(use_valid=False)\n ds.load(False)\n\n split = SplitDataset()\n split.load(ds.train_dataset, ds.train_labels)\n\n ds.train_dataset = split.a_dataset\n ds.train_labels = split.a_labels\n runSingleCNN(ds,0)\n\n ds.train_dataset = split.ab_dataset\n ds.train_labels = split.ab_labels\n runSingleCNN(ds, 1)\n\n ds.train_dataset = split.abc_dataset\n ds.train_labels = split.abc_labels\n runSingleCNN(ds, 2)\n\n ds.train_dataset = split.abcd_dataset\n ds.train_labels = split.abcd_labels\n runSingleCNN(ds, 3)\n\n\ndef runSplitAXNs():\n\n def runSingleAXN(ds, iteration):\n axn = Baseline_axn(ds)\n axn.create(AdamParams())\n run(axn, iteration, num_batches=20000)\n\n shapedDataSet = DataSet(use_valid=False)\n shapedDataSet.load(False)\n\n split = SplitDataset()\n split.load(shapedDataSet.train_dataset, shapedDataSet.train_labels)\n\n shapedDataSet.train_dataset = split.a_dataset\n shapedDataSet.train_labels = split.a_labels\n runSingleAXN(shapedDataSet,0)\n\n shapedDataSet.train_dataset = split.ab_dataset\n shapedDataSet.train_labels = split.ab_labels\n runSingleAXN(shapedDataSet, 1)\n\n shapedDataSet.train_dataset = split.abc_dataset\n shapedDataSet.train_labels = split.abc_labels\n runSingleAXN(shapedDataSet, 2)\n\n shapedDataSet.train_dataset = split.abcd_dataset\n shapedDataSet.train_labels = split.abcd_labels\n runSingleAXN(shapedDataSet, 3)\n\n\ndef runAXN2s():\n\n shapedDataSet = DataSet(use_valid=False)\n shapedDataSet.load(False )\n\n # Baseline CNN\n #axn2 = Baseline_axn2(shapedDataSet)\n #axn2.create(GradientDescentParams())\n #run(axn2, 0, num_batches=50000)\n\n # Search for parameters\n #searchForAXNParams(shapedDataSet, num_batches=1000)\n\n # GD tends to increase in error over 20000 batches\n searchForAXN2GDParams(shapedDataSet, num_batches=20000)\n searchForAXN2AdadeltaParams(shapedDataSet, num_batches=20000)\n searchForAXN2AdagradParams(shapedDataSet, num_batches=20000)\n searchForAXN2AdamParams(shapedDataSet, num_batches=20000)\n\n\n # Baseline CNN\n #axn = Baseline_axn2(shapedDataSet)\n #axn.create(AdamParams(),batch_size=128)\n #run(axn, 0, num_batches=50000)\n\n # axn = Baseline_axn2(shapedDataSet)\n # axn.create(AdagradParams())\n # run(axn, 1, num_batches=50000)\n #\n # axn = Baseline_axn2(shapedDataSet)\n # axn.create(GradientDescentParams())\n # run(axn, 2, num_batches=50000)\n #\n # axn = Baseline_axn2(shapedDataSet)\n # axn.create(AdadeltaParams())\n # run(axn, 3, num_batches=50000)\n\n\ndef runSingleLR(lr, X_train, y_train, X_valid, y_valid, X_test, y_test, iteration = 0):\n start = time.time()\n\n lr.create(X_train, y_train, X_valid, y_valid, X_test, y_test)\n\n timeCompleted = round((time.time() - start) / 60, 2)\n print(\"Completed in {} minutes\".format(timeCompleted))\n lr.params['time'] = timeCompleted\n\n base_filename = 'saved_lr_{:03d}'.format(iteration)\n np.save('{}.preds'.format(base_filename), lr.test_preds)\n pickle.dump(lr.params, open('{}.params'.format(base_filename), 'wb'))\n\n\ndef runLR():\n lr = Baseline_lr()\n X_train, y_train, X_valid, y_valid, X_test, y_test = lr.load()\n runSingleLR(lr, X_train, y_train, X_valid, y_valid, X_test, y_test)\n\n\ndef runSplitLR():\n lr = Baseline_lr()\n X_train, y_train, X_valid, y_valid, X_test, y_test = lr.load()\n\n spl = SplitDataset2()\n spl.load(X_train, y_train)\n\n print('LR on dataset A')\n runSingleLR(lr, spl.a_dataset, spl.a_labels, X_valid, y_valid, X_test, y_test, iteration = 1)\n\n print('LR on dataset AB')\n runSingleLR(lr, spl.ab_dataset, spl.ab_labels, X_valid, y_valid, X_test, y_test, iteration=2)\n\n print('LR on dataset ABC')\n runSingleLR(lr, spl.abc_dataset, spl.abc_labels, X_valid, y_valid, X_test, y_test, iteration=3)\n\n print('LR on dataset ABCD')\n runSingleLR(lr, spl.abcd_dataset, spl.abcd_labels, X_valid, y_valid, X_test, y_test, iteration=4)\n\ndef runBigAXN2():\n shapedDataSet = DataSet(use_valid=False)\n shapedDataSet.load(False )\n\n axn2 = Baseline_axn2(shapedDataSet)\n\n # Keep batch_size at 128 - it's half the time of 256\n axn2.create(optimizer_params=AdagradParams(learning_rate=0.001,\n initial_accumulator_value=0.01))\n # Run this half a million times\n run(axn2, 991, 5000)\n\n\ndef main():\n # Visualise the data for one image\n # d.display(40000)\n\n #runNNs()\n\n #\n #runCNNs()\n\n #runAXNs()\n\n #runAXN2s()\n\n #runSplitAXNs()\n #runSplitCNNs()\n\n #runLR()\n\n #runSplitLR()\n\n runBigAXN2()\n\n print('Finished')\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"submission/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"593214013","text":"import unittest\n\nfrom admin.add_poll import load_polls\nfrom admin.add_poll import validate_polls\nfrom admin.shared.poll import Answer\nfrom admin.shared.poll import Poll\nfrom unittest.mock import call\nfrom unittest.mock import MagicMock\nfrom unittest.mock import patch\n\n\nclass AddPollsTest(unittest.TestCase):\n\n def setUp(self):\n self.test_input_yml = \"admin/tests/test_input_cases.yml\"\n\n poll1 = Poll(\"Wed, Mar 8 Celtics vs. Warriors\", 40, 1489258327,\n [Answer(\"Celtics\"), Answer(\"Warriors\")])\n\n poll2 = Poll(\"Wed, Mar 8 Jazz vs. Rockets\", 40, 1489258327,\n [Answer(\"Jazz\"), Answer(\"Rockets\")])\n\n poll3 = Poll(\"How many 3's will Steph Curry attempt?\", 40, 1489258327,\n [Answer(\"less than 5\"), Answer(\"5-8\"),\n Answer(\"9, 10, or 11\"), Answer(\"12 or more\")])\n\n self.test_polls = [poll1, poll2, poll3]\n\n self.mock_cursor = MagicMock()\n self.mock_connection = MagicMock()\n\n def test_load_polls(self):\n\n result = load_polls(self.test_input_yml)\n\n self.assertEqual(\"Wed, Mar 8 Celtics vs. Warriors\", result[0].question)\n self.assertEqual(40, result[0].buy_in)\n self.assertEqual(1489258327, result[0].close_time)\n self.assertEqual(\"Celtics\", result[0].answers[0].answer_text)\n self.assertEqual(\"Warriors\", result[0].answers[1].answer_text)\n\n self.assertEqual(\"Wed, Mar 8 Jazz vs. Rockets\", result[1].question)\n self.assertEqual(40, result[1].buy_in)\n self.assertEqual(1489258327, result[1].close_time)\n self.assertEqual(\"Jazz\", result[1].answers[0].answer_text)\n self.assertEqual(\"Rockets\", result[1].answers[1].answer_text)\n\n self.assertEqual(\"How many 3's will Steph Curry attempt?\", result[2].question)\n self.assertEqual(50, result[2].buy_in)\n self.assertEqual(1489258327, result[2].close_time)\n self.assertEqual(\"less than 5\", result[2].answers[0].answer_text)\n self.assertEqual(\"5-8\", result[2].answers[1].answer_text)\n self.assertEqual(\"9, 10, or 11\", result[2].answers[2].answer_text)\n self.assertEqual(\"12 or more\", result[2].answers[3].answer_text)\n\n @patch(\"time.time\")\n @patch(\"sys.stdout\")\n def test_validate_polls_all_valid(self, stdout_mock, time_mock):\n\n time_mock.side_effect = [1489208327]\n self.mock_cursor.fetchone.side_effect = [None, None, None]\n\n resulting_polls = validate_polls(self.test_polls, self.mock_cursor, self.mock_connection)\n\n select_calls = [\n call(\"SELECT * from polls where title=%s\", (\"Wed, Mar 8 Celtics vs. Warriors\",)),\n call(\"SELECT * from polls where title=%s\", (\"Wed, Mar 8 Jazz vs. Rockets\",)),\n call(\"SELECT * from polls where title=%s\", (\"How many 3's will Steph Curry attempt?\",))\n ]\n\n self.mock_cursor.execute.assert_has_calls(select_calls, any_order=False)\n self.assertEqual(3, len(resulting_polls))\n self.assertEqual(self.test_polls[0].question, resulting_polls[0].question)\n self.assertEqual(self.test_polls[1].question, resulting_polls[1].question)\n self.assertEqual(self.test_polls[2].question, resulting_polls[2].question)\n\n @patch(\"time.time\")\n @patch(\"sys.stderr\")\n def test_validate_polls_some_exist(self, stderr_mock, time_mock):\n\n time_mock.side_effect = [1489208327]\n self.mock_cursor.fetchone.side_effect = [None, 1, 1]\n\n resulting_polls = validate_polls(self.test_polls, self.mock_cursor, self.mock_connection)\n\n select_calls = [\n call(\"SELECT * from polls where title=%s\", (\"Wed, Mar 8 Celtics vs. Warriors\",)),\n call(\"SELECT * from polls where title=%s\", (\"Wed, Mar 8 Jazz vs. Rockets\",)),\n call(\"SELECT * from polls where title=%s\", (\"How many 3's will Steph Curry attempt?\",))\n ]\n\n write_calls = [\n call(\"Poll with title: Wed, Mar 8 Jazz vs. Rockets already exists, skipping\\n\"),\n call(\"Poll with title: How many 3's will Steph Curry attempt? already exists, skipping\\n\"),\n ]\n\n stderr_mock.write.assert_has_calls(write_calls, any_order=False)\n self.mock_cursor.execute.assert_has_calls(select_calls, any_order=False)\n self.assertEqual(1, len(resulting_polls))\n self.assertEqual(self.test_polls[0].question, resulting_polls[0].question)\n\n @patch(\"time.time\")\n @patch(\"sys.stderr\")\n def test_validate_polls_too_close(self, stderr_mock, time_mock):\n\n time_mock.side_effect = [1489258000]\n self.mock_cursor.fetchone.side_effect = [None, None, None]\n\n resulting_polls = validate_polls(self.test_polls, self.mock_cursor, self.mock_connection)\n\n select_calls = [\n call(\"SELECT * from polls where title=%s\", (\"Wed, Mar 8 Celtics vs. Warriors\",)),\n call(\"SELECT * from polls where title=%s\", (\"Wed, Mar 8 Jazz vs. Rockets\",)),\n call(\"SELECT * from polls where title=%s\", (\"How many 3's will Steph Curry attempt?\",))\n ]\n\n write_calls = [\n call(\"Poll with close time: 1489258327 is in the past or less than 30 minutes from now, skipping\\n\"),\n call(\"Poll with close time: 1489258327 is in the past or less than 30 minutes from now, skipping\\n\"),\n call(\"Poll with close time: 1489258327 is in the past or less than 30 minutes from now, skipping\\n\"),\n\n ]\n\n stderr_mock.write.assert_has_calls(write_calls, any_order=False)\n self.mock_cursor.execute.assert_has_calls(select_calls, any_order=False)\n self.assertEqual(0, len(resulting_polls))\n","sub_path":"admin/tests/test_add_poll.py","file_name":"test_add_poll.py","file_ext":"py","file_size_in_byte":5645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"446884224","text":"from odoo import fields, models, api\n\nclass SaleOrderLineExt(models.Model):\n _inherit = 'sale.order.line'\n categ_id = fields.Many2one('product.category', string=\"catégorie\")\n\n @api.onchange('categ_id')\n def _onchange_categ(self):\n return {'domain': {\n 'product_id': [\n ('categ_id', '=', self.categ_id.id)\n ]\n }}\n","sub_path":"webmania_projects/wm_list_products_by_categories/models/SaleOrderLineExt.py","file_name":"SaleOrderLineExt.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"478867132","text":"from sort.authentication import token_required\nfrom sort import app\nfrom flask import render_template, request, jsonify\nfrom sort.database import *\nfrom sort.dataprocessing import *\nfrom sort.algorithm import *\nfrom ast import literal_eval\nfrom sort.authentication import token_required\nimport json\nimport os\nimport datetime\nimport jwt\n\n\nfrom sort import app\n \n@app.route('/unprotected')\ndef unprotected():\n return jsonify({'message' : 'Anyone can view this!'})\n\n@app.route('/protected')\n@token_required\ndef protected():\n return jsonify({'message' : 'This is only available for people with valid tokens.'})\n\n@app.route('/login', methods=['POST'])\ndef login():\n username = request.form['username']\n password = request.form['password']\n\n if username=='faziz' and password == 'hahaha':\n token = jwt.encode({'user' : username, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=10)}, app.config['SECRET_KEY'])\n return jsonify({'token' : token.decode('UTF-8')})\n return render_template('login.html')\n\n# Root URL\n@app.route('/')\n@app.route('/Home')\ndef home_page():\n return render_template('login.html')\n\n\n@app.route('/sort/', methods=['POST'])\n@token_required\ndef sort_page(methods):\n methods = methods\n items =[]\n uploaded_file = request.files['file']\n column = int(request.form['column'])-1\n order = request.form['order'].lower()\n if uploaded_file.filename != '':\n file_path = os.path.join(app.config['UPLOAD_FOLDER'], uploaded_file.filename)\n uploaded_file.save(file_path)\n items = parseCSV(file_path)\n\n if methods==\"selection\":\n items = selection_sort(items, column, order)\n elif methods==\"bubble\":\n items = bubble_sort(items, column, order)\n elif methods==\"insertion\":\n items = insertion_sort(items, column, order)\n elif methods==\"merge\":\n items = merge_sort(items, column, order)\n # Add more Sort \n else:\n return \"Coming Soon..\"\n return render_template('sort.html', items=items)\n\n\n@app.route('/sort/result', methods=['GET'])\n@token_required\ndef result():\n id = request.args.get('id', default=str(-1))\n latest = get_latest_id()\n if (id==str(-1)):\n id = str(latest)\n encoder = get_data(id)\n to_json = encoder.decode('utf8').replace(\"'\", '\"')\n data_json = json.loads(to_json)\n result = json.dumps(data_json)\n return render_template('sort.html', items=literal_eval(result))","sub_path":"sort/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"439190532","text":"from django.conf.urls import url\nfrom django.contrib.auth.decorators import login_required\nfrom device import views\n\n\napp_name = 'device'\nurlpatterns = [\n # индексная страница всего проекта / . Список устройств\n url(r'^$',\n views.device_index,\n name='device-index'\n ),\n # страница каждого устройства /device/2/\n url(r'^device/(?P[0-9]+)/$',\n login_required(views.DeviceDetail.as_view()),\n name='device-detail'\n ),\n # страница создания устройства /device/\n url(r'^device/$',\n login_required(views.DeviceCreate.as_view()),\n name='device-create'\n ),\n # список некорректных устройств\n url(r'^device/invalid/$',\n login_required(views.DeviceInvalidList.as_view()),\n name='device-invalid'\n ),\n # страница обновления устройства\n url(r'^device/(?P[0-9]+)/update/$',\n login_required(views.DeviceUpdate.as_view()),\n name='device-update'\n ),\n # страница создания категорий /device/category/\n url(r'^device/category/create/$',\n login_required(views.CategoryCreate.as_view()),\n name='category-create'\n ),\n # страница списка категорий /device/category/list/\n url(r'^device/category/$',\n login_required(views.CategoryIndex.as_view()),\n name='category'\n ),\n # страница каждой категории /device/category/3/\n url(r'^device/category/(?P[0-9]+)/$',\n login_required(views.CategoryDetail.as_view()),\n name='category-detail'\n ),\n # страница создания производителей\n url(r'^device/manufacturer/$',\n login_required(views.ManufacturerCreate.as_view()),\n name='manufacturer-create'\n ),\n # страница списка производителей\n url(r'^device/manufacturer/list/$',\n login_required(views.ManufacturerIndex.as_view()),\n name='manufacturer'\n ),\n # страница создания единиц измерения\n url(r'^device/measure/$',\n login_required(views.MeasureCreate.as_view()),\n name='measure-create'\n ),\n # страница списка единиц измерения\n url(r'^device/measure/list/$',\n login_required(views.MeasureIndex.as_view()),\n name='measure'\n ),\n # страница списка серийных номеров /device/serial/\n url(r'^device/serial/$',\n login_required(views.DeviceSerialIndex.as_view()),\n name='serial'\n ),\n # страница каждого серийного номера /device/serial/5/\n url(r'^device/serial/(?P[0-9]+)/$',\n login_required(views.DeviceSerialDetail.as_view()),\n name='serial-detail'\n ),\n]","sub_path":"device/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"18514841","text":"import numpy as np\nimport cv2\n\n# find position to crop image\nc_pose = []\ndef draw_circle(event,x,y,flags,param):\n if event == cv2.EVENT_LBUTTONUP:\n c_pose.append(y)\n c_pose.append(x)\n print(y,x)\n\ndef crop_ingredient() :\n cap = cv2.VideoCapture(1)\n cap.set(3, 1280)\n cap.set(4, 720)\n cv2.namedWindow('Output Image')\n cv2.setMouseCallback('Output Image',draw_circle)\n while True :\n ret,img = cap.read()\n cv2.imshow('Output Image',img)\n\n if cv2.waitKey(1) & 0xFF == 27 :\n break\n cv2.destroyAllWindows()\n file = open('crop_pose2.txt','w')\n file.write(str(c_pose)[1:-1])\n\n\ndef make_traindata_ingredient() :\n cap = cv2.VideoCapture(1)\n cap.set(3, 1280)\n cap.set(4, 720)\n file = open('crop_pose2.txt','r')\n L = file.read().split(',')\n c_p = []\n for i in L :\n c_p.append(int(i))\n print(c_p)\n\n # CROP LOOB\n pic_cnt = 1\n name_list=['Ham','Lettuce','MooYhong','Oreo','Ovaltine','Pu-At','Tangkwa','Tomato','xxx']\n while True :\n ret,img = cap.read()\n cv2.imshow(\"Press 's' to save & Esc to Exit\",img)\n \n if cv2.waitKey(1) & 0xFF == ord('s') :\n img_ingredient = []\n for i in range(0,len(c_p)-3,4) :\n img_ingredient.append(img[c_p[i]:c_p[i+2],c_p[i+1]:c_p[i+3]])\n\n name_cnt = 0\n for each_image in img_ingredient :\n cv2.imwrite('C:/Users/Oeysk/Documents/GitHub/dataset/' + name_list[name_cnt] + '/img' +str(pic_cnt)+'.jpg',each_image)\n pic_cnt += 1\n name_cnt += 1\n\n print('save : ' + str(pic_cnt-1))\n\n if cv2.waitKey(1) & 0xFF == 27 :\n break\n \n cap.release()\n cv2.destroyAllWindows()\n\n\nmake_traindata_ingredient()\n# crop_ingredient()\n","sub_path":"cameraMain.py","file_name":"cameraMain.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"130854138","text":"import subprocess\nimport os\nimport json\nfrom datetime import datetime\nfrom pathlib import Path\n\n\nwith open(\"settings.json\", encoding=\"utf8\") as f: \n try:\n data=json.loads(f.read())\n loc_7z=Path(data['loc_7z'])\n encoding=data['encoding']\n except:\n loc_7z = Path(\"C:\\\\Program Files\\\\7-Zip\\\\7z.exe\")\n encoding=\"utf8\"\n\n\n\"\"\"\nVõtab antud käsu ja käivitab selle käsurealt\nVäljastab kõik read, mida käsu täitmisel näidataks\n\"\"\"\ndef run_process(command): \n print(command)\n p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n while(True):\n retcode = p.poll() #returns None while subprocess is running\n #https://superuser.com/questions/1170656/windows-10-terminal-encoding\n line = p.stdout.readline().decode(encoding)\n yield line\n if(retcode is not None):\n break\n\n\"\"\"\nVõtab arhiivi nime ja tagastab kõikide seal olevate failide nimed\n\"\"\"\ndef get_filenames(arch_loc):\n names=False\n name_list=[]\n prev_line=\"\"\n startindex=0\n command = stringify(str(loc_7z)) + \" l \" + stringify(arch_loc)\n for line in run_process(command):\n if line.startswith(\"----\"):\n names=not names\n if names:\n startindex=prev_line.index(\"Name\")\n continue\n if names:\n #Juhuks, kui failinimed pole õiges formaadis\n try:\n name_list.append(line[startindex:].strip())\n except:\n pass\n prev_line=line\n return name_list\n\n\"\"\"\nAvab arhiivi ja võtab seal välja failid, mille nimed on antud\nArgumentideks on arhiivi asukoht, failinimed, väljundkaust\n\"\"\"\ndef unpack(arch_loc, filenames, output='*'):\n filenames_str=[stringify(filename) for filename in filenames]\n command = stringify(str(loc_7z))+\" e \"+ stringify(arch_loc) + \" -aoa -o\"+ stringify(output)+ \" \".join(filenames_str)\n for i in run_process(command):\n print(i, end=\"\")\n \n\"\"\"\nAvab arhiivi ja võtab sealt välja kõik failid\nTagastab failinimed\n\"\"\"\ndef unpack_all(arch_loc, output='*'):\n all_filenames=get_filenames(arch_loc)\n if output=='*':\n output, ext = os.path.splitext(arch_loc)\n \n unpack(arch_loc, [], output=output)\n \n filenames=[str(Path(output).joinpath(x)) for x in all_filenames]\n return filenames\n \n\"\"\"\nAvab arhiivi ja võtab sealt välja kõik failid\nSeejärel vaatab failid läbi ja eemaldab need, mis ei kuulu antud ajavahemikku\n\nTulemuskaust peab olema tühi selle töötamiseks\nTagastab allesjäänud failide nimed\n\"\"\" \ndef unpack_between_infile(arch_loc, start, end, output='*'):\n all_filenames=get_filenames(arch_loc)\n if output=='*':\n output, ext = os.path.splitext(arch_loc)\n unpack_all(arch_loc, output=output)\n for name in all_filenames[:]:\n to_remove=True\n p=Path(output).joinpath(name)\n with open(p, 'r', encoding=\"UTF8\") as f:\n try:\n data=json.loads(f.read())\n date=datetime.strptime(data[0]['time'], '%Y-%m-%dT%H:%M:%S.%f')\n if date>start and date screengeometry.width()) or \\\r\n ((size.height() + position.y()) > screengeometry.height()):\r\n size.setWidth(900)\r\n size.setHeight(600)\r\n position.setX(100)\r\n position.setY(50)\r\n elif (position.x() < -10) or \\\r\n (position.y() < -10):\r\n size.setWidth(900)\r\n size.setHeight(600)\r\n position.setX(100)\r\n position.setY(50)\r\n else: \r\n self.setGeometry(self._ui_settings.value('MainWindow/Geometry').toRect())\r\n self.restoreState(self._ui_settings.value('MainWindow/State').toByteArray())\r\n size = self._ui_settings.value('MainWindow/Size', QtCore.QVariant(QtCore.QSize(900, 600))).toSize()\r\n position = self._ui_settings.value('MainWindow/Position', QtCore.QVariant(QtCore.QPoint(100, 50))).toPoint()\r\n #\r\n self.resize(size)\r\n self.move(position) \r\n # Tell the user.\r\n tool_manager.ToolManager().show_tool_by_name('Toolbox logging') # Show the log tool if hidden.\r\n toolbox_utils.Logging().log('Welcome to the Plankton Toolbox.')\r\n toolbox_utils.Logging().log('Note: Log rows are both sent to the \"Toolbox logging\" tool and written to the text file \"plankton_toolbox_log.txt\".')\r\n # Load resources when the main event loop has started.\r\n# if toolbox_settings.ToolboxSettings().get_value('Resources:Load at startup'):\r\n# QtCore.QTimer.singleShot(10, toolbox_resources.ToolboxResources().loadAllResources)\r\n QtCore.QTimer.singleShot(100, self._loadResources)\r\n \r\n def closeEvent(self, event):\r\n \"\"\" Called on application shutdown. \"\"\"\r\n # Stores current window positions.\r\n self._ui_settings.setValue('MainWindow/Size', QtCore.QVariant(self.size()))\r\n self._ui_settings.setValue('MainWindow/Position', QtCore.QVariant(self.pos()))\r\n self._ui_settings.setValue('MainWindow/State', self.saveState())\r\n self._ui_settings.setValue('MainWindow/Geometry', self.geometry())\r\n self._logfile.close\r\n # Save toolbox settings.\r\n toolbox_settings.ToolboxSettings().save_settings(self._ui_settings)\r\n \r\n def _createMenu(self):\r\n \"\"\" \r\n The main menu of the application. \r\n Note: The Tools menu will be populated by the tool base class. Search\r\n for 'toggleViewAction' to see the implementation.\r\n \"\"\"\r\n self._filemenu = self.menuBar().addMenu(self.tr('&File'))\r\n self._filemenu.addSeparator()\r\n self._filemenu.addAction(self._quitaction)\r\n self._viewmenu = self.menuBar().addMenu(self.tr('&View'))\r\n self.toolsmenu = self.menuBar().addMenu(self.tr('&Extra tools')) # Note: Public.\r\n self._helpmenu = self.menuBar().addMenu(self.tr('&Help'))\r\n self._helpmenu.addAction(self._aboutaction)\r\n # Add sub-menu in the tools menu to hide all tools.\r\n self._hidealltools = QtGui.QAction(self.tr('Hide all extra tools'), self)\r\n self._hidealltools.setStatusTip(self.tr('Make all extra tools invisible.'))\r\n self._hidealltools.triggered.connect(self._hideAllTools)\r\n self.toolsmenu.addAction(self._hidealltools)\r\n #\r\n self.toolsmenu.addSeparator()\r\n \r\n def _hideAllTools(self):\r\n \"\"\" \"\"\"\r\n tools = self._toolmanager.get_tool_list()\r\n for tool in tools:\r\n tool.close()\r\n\r\n def _createStatusBar(self):\r\n \"\"\" \r\n The status bar is located at the bottom of the main window. Tools can\r\n write messages here by calling _writeToStatusBar located in the \r\n tool base class.\r\n \"\"\"\r\n self.statusBar().showMessage(self.tr('Plankton Toolbox.'))\r\n\r\n def _create_contentSelectors(self):\r\n \"\"\" \r\n The user should be able to choose one activity and a number of tools.\r\n \"\"\"\r\n # Dock widgets can be tabbed with vertical tabs.\r\n self.setDockOptions(QtGui.QMainWindow.AnimatedDocks | \r\n QtGui.QMainWindow.AllowTabbedDocks | \r\n QtGui.QMainWindow.VerticalTabs)\r\n # Create left dock widget and dock to main window.\r\n dock = QtGui.QDockWidget(self.tr(' Tool selector '), self)\r\n dock.setObjectName('Activities and tools selector')\r\n dock.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea)\r\n dock.setFeatures(QtGui.QDockWidget.NoDockWidgetFeatures)\r\n # dock.setFeatures(QtGui.QDockWidget.DockWidgetFloatable | \r\n # QtGui.QDockWidget.DockWidgetMovable)\r\n self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dock)\r\n # Widget to create space and layout for two groupboxes.\r\n content = QtGui.QWidget()\r\n widget = QtGui.QWidget()\r\n widget.setStyleSheet(\"\"\" \r\n QDockWidget .QWidget { background-color: white; }\r\n \"\"\")\r\n dock.setWidget(widget) \r\n # Add scroll.\r\n mainscroll = QtGui.QScrollArea()\r\n ### mainscroll.setFrameShape(QtGui.QFrame.NoFrame)\r\n mainscroll.setWidget(content)\r\n mainscroll.setWidgetResizable(True)\r\n mainlayout = QtGui.QVBoxLayout()\r\n mainlayout.setMargin(0)\r\n mainlayout.setSpacing(0)\r\n mainlayout.addWidget(mainscroll)\r\n \r\n self.test_mainscroll = mainscroll\r\n \r\n widget.setLayout(mainlayout)\r\n grid1 = QtGui.QVBoxLayout()\r\n content.setLayout(grid1) \r\n # Frame for activites. \r\n activitiesgroup = QtGui.QFrame()\r\n grid1.addWidget(activitiesgroup)\r\n activitiesvbox = QtGui.QVBoxLayout()\r\n activitiesgroup.setLayout(activitiesvbox)\r\n # Groupbox for tools.\r\n toolsgroup = QtGui.QGroupBox('Extra tools')\r\n grid1.addWidget(toolsgroup) \r\n toolsvbox = QtGui.QVBoxLayout()\r\n toolsgroup.setLayout(toolsvbox)\r\n grid1.addStretch(5)\r\n # Add one button for each activity. Create stacked widgets.\r\n for activity in self._activitymanager.get_activity_list():\r\n button = utils_qt.ActivityMenuQLabel(' ' + activity.objectName())\r\n activity.set_main_menu_button(button)\r\n activitiesvbox.addWidget(button) # Adds to stack. \r\n # The activity is called to select stack item by object, not index.\r\n self.connect(button, QtCore.SIGNAL('clicked()'), button.markAsSelected)\r\n self.connect(button, QtCore.SIGNAL('clicked()'), activity.show_in_main_window)\r\n # Create one layer in the stacked activity widget.\r\n self._activitystack.addWidget(activity)\r\n #\r\n activitiesvbox.addStretch(5)\r\n # Add one button for each tool.\r\n for tool in self._toolmanager.get_tool_list():\r\n button = utils_qt.ClickableQLabel(' ' + tool.objectName())\r\n button_hide = utils_qt.ClickableQLabel('- ')\r\n showhidehbox = QtGui.QHBoxLayout()\r\n showhidehbox.addWidget(button)\r\n showhidehbox.addWidget(button_hide)\r\n showhidehbox.addStretch(10)\r\n toolsvbox.addLayout(showhidehbox)\r\n self.connect(button, QtCore.SIGNAL('clicked()'), tool.show_tool) \r\n self.connect(button_hide, QtCore.SIGNAL('clicked()'), tool.hide_tool) \r\n #\r\n # Button to hide all tools.\r\n button = utils_qt.ClickableQLabel(' ')\r\n toolsvbox.addWidget(button)\r\n self.connect(button, QtCore.SIGNAL('clicked()'), self._hideAllTools) \r\n #\r\n toolsvbox.addStretch(10)\r\n # Activate startup activity. Select the first one in list.\r\n activities = self._activitymanager.get_activity_list()\r\n if len(activities) > 0:\r\n activities[0].show_in_main_window()\r\n\r\n def showActivity(self, activity):\r\n \"\"\" \"\"\"\r\n### self._activityheader.setText('' + activity.objectName() + '')\r\n self._activitystack.setCurrentWidget(activity)\r\n # Mark left menu item as active. \r\n if activity.get_main_menu_button():\r\n activity.get_main_menu_button().markAsSelected()\r\n\r\n def show_activity_by_name(self, activity_name):\r\n \"\"\" \"\"\"\r\n for activity in self._activitymanager.get_activity_list():\r\n if activity.objectName() == activity_name:\r\n self.showActivity(activity)\r\n return\r\n \r\n def _createCentralWidget(self):\r\n \"\"\" \r\n The central widget contains the selected activity. It is implemented as\r\n stacked layout, QStackedLayout, where the pages are selected from\r\n the activities group box. \r\n \"\"\"\r\n### self._activityheader = QtGui.QLabel('Activity not selected...\", self)\r\n### self._activityheader.setAlignment(QtCore.Qt.AlignHCenter)\r\n self._activitystack = QtGui.QStackedLayout() \r\n # Layout widgets.\r\n widget = QtGui.QWidget(self) \r\n layout = QtGui.QVBoxLayout()\r\n widget.setLayout(layout)\r\n self.setCentralWidget(widget)\r\n### layout.addWidget(self._activityheader)\r\n layout.addLayout(self._activitystack)\r\n # Dummy stack content.\r\n dummy = QtGui.QWidget(self)\r\n self._activitystack.addWidget(dummy)\r\n \r\n def _createActions(self):\r\n \"\"\" Common application related actions. \"\"\"\r\n self._quitaction = QtGui.QAction(self.tr('&Quit'), self)\r\n self._quitaction.setShortcut(self.tr('Ctrl+Q'))\r\n self._quitaction.setStatusTip(self.tr('Quit the application'))\r\n self._quitaction.triggered.connect(self.close)\r\n #\r\n self._aboutaction = QtGui.QAction(self.tr('&About'), self)\r\n self._aboutaction.setStatusTip(self.tr('Show the application\\'s About box'))\r\n self._aboutaction.triggered.connect(self._about)\r\n\r\n def write_to_log(self, message):\r\n \"\"\" Log to file and to the log tool when available. \"\"\"\r\n# self.console.addItem(message)\r\n self._logfile.write(message + '\\r\\n')\r\n self._logfile.flush() \r\n # Search for the console tool. Note: Not available during startup.\r\n if not self._logtool:\r\n for tool in self._toolmanager.get_tool_list():\r\n if type(tool) == log_tool.LogTool:\r\n self._logtool = tool\r\n # Log message. \r\n if self._logtool: self._logtool.write_to_log(message)\r\n\r\n def _loadResources(self):\r\n \"\"\" \"\"\"\r\n try:\r\n self.statusBar().showMessage(self.tr('Loading species lists...'))\r\n plankton_core.Species() # Load species files.\r\n finally:\r\n self.statusBar().showMessage(self.tr('')) \r\n\r\n def setVersion(self, version):\r\n \"\"\" \"\"\"\r\n self._version = version\r\n \r\n def _about(self):\r\n \"\"\" \"\"\"\r\n QtGui.QMessageBox.about(self, self.tr('About Plankton Toolbox'),\r\n self.tr(\r\n \"\"\"\r\n

\r\n Plankton Toolbox version %s\r\n

\r\n

\r\n The Plankton Toolbox is a free tool for aquatic scientists, and others, \r\n working with environmental monitoring related to phyto- and zooplankton.\r\n

\r\n

\r\n The software is under development and provided free with no \r\n guarantees regarding functionality. Comments, bug reports and requests \r\n for new functionality are welcome and can be sent to \r\n info@nordicmicroalgae.org\r\n

\r\n

\r\n Plankton Toolbox can be run on Windows, Mac OS X and Ubuntu (UNIX). No installation is needed.\r\n The latest version can be found at: \r\n http://nordicmicroalgae.org/tools.\r\n

\r\n

\r\n Plankton Toolbox is developed by the oceanographic unit of the \r\n Swedish Meterological and Hydrological Institute (SMHI).\r\n The software is a product of the \r\n Swedish LifeWatch project \r\n funded by the \r\n Swedish Science Council.\r\n

\r\n

\r\n Developed in Python 2.7 and Qt/PyQt4. Released under the MIT license.\r\n Source code and info for developers at: \r\n http://plankton-toolbox.org.\r\n

\r\n \"\"\" % (self._version)))\r\n \r\n","sub_path":"plankton_toolbox/toolbox/toolbox_main_window.py","file_name":"toolbox_main_window.py","file_ext":"py","file_size_in_byte":15946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"249283292","text":"class Solution:\n def find_median_sorted_arrays(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: float\n \"\"\"\n nums1_len = len(nums1)\n nums2_len = len(nums2)\n if nums1_len==0:\n return self.get_median(nums2)\n elif nums2_len==0:\n return self.get_median(nums1)\n else:\n nums1_median = self.get_median(nums1)\n nums2_median = self.get_median(nums2)\n if nums1_median == nums2_median:\n return nums1_median\n \n if nums1_len < nums2_len:\n remove_len = int(nums1_len/2)\n if nums1_len%2==0:\n remove_len -=1\n else:\n remove_len = int(nums2_len/2)\n if nums2_len%2==0:\n remove_len -=1\n \n if remove_len==0:\n return self.merge_get_median(nums1, nums2)\n\n if nums1_median < nums2_median:\n new_nums1 = nums1[remove_len:]\n new_nums2 = nums2[:-remove_len]\n print(new_nums1)\n print(new_nums2)\n print('1 less 2')\n return self.find_median_sorted_arrays(new_nums1, new_nums2)\n else:\n new_nums1 = nums1[:-remove_len]\n new_nums2 = nums2[remove_len:]\n print(new_nums1)\n print(new_nums2)\n print('2 less 1')\n return self.find_median_sorted_arrays(new_nums1, new_nums2)\n\n \n \n \n def get_median(self, list):\n length = len(list)\n halfLength = int(length/2)\n if length%2==0:\n median = (list[halfLength]+list[halfLength-1])/2\n else:\n median = list[halfLength] \n return median\n \n def merge_get_median(self, nums1, nums2):\n i = 0\n j = 0\n nums = []\n while i < len(nums1) and j < len(nums2):\n if nums1[i] < nums2[j]:\n nums.append(nums1[i])\n i +=1\n else:\n nums.append(nums2[j])\n j +=1\n\n if i < len(nums1):\n nums.extend(nums1[i:])\n elif j < len(nums2):\n nums.extend(nums2[j:])\n return self.get_median(nums)\n\nif __name__ == '__main__':\n nums1=[1, 2, 6, 7]\n nums2=[3, 4, 5, 8]\n result = Solution().find_median_sorted_arrays(nums1, nums2)\n print(result)","sub_path":"leet-code/find_median_sorted_arrays.py","file_name":"find_median_sorted_arrays.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"415251154","text":"import json\nclass Message:\n def __init__(self, code=0,msg=None, desc=None):\n self.code = code\n self.msg = msg\n self.desc = desc\n self.data = dict()\n self.data['priceHistory'] = []\n\n def set_location(self,province,city,citylevel):\n self.data['province'] = province\n self.data['city'] = city\n self.data['citylevel'] = citylevel\n\n def add_price(self, time, price_upper, price_lower, price):\n d = dict()\n d['time'] = time\n d['price'] = dict()\n d['price']['price_upper'] = price_upper\n d['price']['price_lower'] = price_lower\n d['price']['price'] = price\n self.data['priceHistory'].append(d)\n\n","sub_path":"server/msg.py","file_name":"msg.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"476499996","text":"class Cart:\n def __init__(self, request):\n self.request = request\n self.session = request.session\n cart = self.session.get(\"cart\")\n if not cart:\n cart = self.session[\"cart\"] = {}\n self.cart = cart\n \n def add(self, producto):\n if str(producto.id) not in self.cart.keys():\n self.cart[producto.id] = {\n \"producto_id\":producto.id,\n \"titulo\":producto.titulo,\n \"quantitu\":1,\n \"price\": str(producto.price),\n \"image\": producto.image.url\n }\n else:\n for key, value in self.cart.items():\n if key == str(producto.id):\n value[\"quantity\"] = value[\"quantity\"] + 1\n \n break\n self.save()\n\n def save(self):\n self.session[\"cart\"] = self.cart\n self.session.modified = True\n \n def remove(self, producto):\n producto_id = str(producto.id)\n if producto_id in self.cart:\n del self.cart[producto_id]\n self.save()\n \n def decrement(self, producto):\n for key, value in self.cart.items():\n if key == str(producto.id):\n value[\"quantity\"] = value [\"quantity\"] + 1\n if value[\"quantity\"] < 1:\n self.remove(producto)\n else:\n self.save()\n break\n else:\n print(\"El producto no existe en el carrito\")\n\n def clear(self):\n self.session[\"cart\"] = {}\n self.session,modified = True","sub_path":"TpFinal/Cart/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"105754990","text":"from flask_restful import Resource, abort\nfrom flask import make_response, request\n\nimport config\nfrom controller import experiment_store as es\n\n\nclass DeleteConfig(Resource):\n @staticmethod\n def post():\n try:\n e = es.get_experiment(request.json['hash'])\n change = e.remove_config(request.json['id'])\n if change:\n es_id = es.update_experiment(change, request.json['hash'])\n if es_id:\n return make_response(request.json['id'])\n\n return make_response('', 200)\n\n except Exception as e:\n if config.debug_mode:\n abort(400, message=str(e))\n\n else:\n abort(404, message=\"Page not found\")\n","sub_path":"DWF-server/routes/experiment/delete_config.py","file_name":"delete_config.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"379655038","text":"import sys\nimport pandas as pd\nfrom trafficintelligence import moving, metadata, storage\nfrom pathlib import Path\nimport numpy as np\nimport sqlite3\nfrom scipy.signal import savgol_filter\n\n\ndef angleBetweenUserAndAlignments(user, alignments):\n # Initial and final positions of the user\n u1 = user.getPositionAtInstant(user.getLastInstant())\n u2 = user.getPositionAtInstant(user.getFirstInstant())\n # Vector from first user pointing to the position of the user\n u1u2 = u2 - u1\n # First and last alignment positions\n a1 = alignments[0]\n a2 = alignments[1]\n # Vector from first user pointing to the position of the alignment\n a1a2 = a2 - a1\n return np.arccos(moving.Point.dot(a1a2, u1u2)/(a1a2.norm2()*u1u2.norm2()))\n\ndef calculateAngleBetweenUsers(firstUserObject, secondUserObject, instant):\n # Velocity vector for the first user\n v1 = firstUserObject.getVelocityAtInstant(instant)\n # Positions of the users at the given instant\n p1 = firstUserObject.getPositionAtInstant(instant)\n p2 = secondUserObject.getPositionAtInstant(instant)\n # Vector from first user pointing to the position of the second user\n p1p2 = p2 - p1\n # Returning the angle between speed v1 and p1p2\n return np.arccos(moving.Point.dot(v1, p1p2)/(v1.norm2()*p1p2.norm2()))\n\ndef findOvertakingManeuverFrames(roadUser1, roadUser2):\n maneuverBegingFrame = max(roadUser1.getFirstInstant(), roadUser2.getFirstInstant())\n maneuverEndingFrame = min(roadUser1.getLastInstant(), roadUser2.getLastInstant())\n # Initial assumption\n leader = roadUser1\n follower = roadUser2\n # Verification of the order\n f = maneuverBegingFrame\n angle = calculateAngleBetweenUsers(leader, follower, f)\n if angle < np.pi/2:\n leader = roadUser2\n follower = roadUser1\n # Recalculate the initial angle\n angle = calculateAngleBetweenUsers(leader, follower, f)\n # Overtaking started before the first frame of the interaction\n if angle < 160*np.pi/180:\n # Find the frame of the end of the maneuver\n while angle > 20*np.pi/180 and f < maneuverEndingFrame:\n angle = calculateAngleBetweenUsers(leader, follower, f)\n f += 1\n maneuverEndingFrame = f\n return maneuverBegingFrame, maneuverEndingFrame\n # Overtaking happening later in the interaction\n else:\n # Find the frame of the beginning of the maneuver\n while angle > 160*np.pi/180 and f < maneuverEndingFrame:\n angle = calculateAngleBetweenUsers(leader, follower, f)\n f += 1\n maneuverBegingFrame = f\n # Find the frame of the ending of the maneuver\n while angle > 20*np.pi/180 and f < maneuverEndingFrame:\n angle = calculateAngleBetweenUsers(leader, follower, f)\n f += 1\n maneuverEndingFrame = f\n return maneuverBegingFrame, maneuverEndingFrame\n\ndef calculateHeadway(roadUser1, roadUser2, projectionTrajecotry):\n HW = {}\n # Both users in interaction\n u1 = roadUser1\n u2 = roadUser2\n # Project positions in curvilinear domain\n u1.projectCurvilinear([projectionTrajecotry])\n u2.projectCurvilinear([projectionTrajecotry])\n # Store curvilinear position and frames of both users\n u1CurPos = {}\n u2CurPos = {}\n # Collecting all frames and positions of the first user\n for frame in u1.getTimeInterval():\n # If a curvilinear position could be calculated\n try:\n curPos = u1.getCurvilinearPositionAtInstant(frame)[0]\n u1CurPos[frame] = curPos\n except:\n pass\n # Collecting all frames and positions of the second user\n for frame in u2.getTimeInterval():\n # If a curvilinear position could be calculated\n try:\n curPos = u2.getCurvilinearPositionAtInstant(frame)[0]\n u2CurPos[frame] = curPos\n except:\n pass\n leading = u1.getNum()\n if len(u1CurPos) > 0 and len(u2CurPos) > 0:\n # Go through all the frames of the first user\n for frameU1 in list(u1CurPos):\n hwd = None\n # Find the frame of the minimum distance difference\n positionU1 = u1CurPos[frameU1]\n frameU2 = min(list(u2CurPos.items()), key=lambda t: np.abs(t[1]-positionU1))[0]\n # Corresponding frame and position for the second user\n positionU2 = u2CurPos[frameU2]\n # Discard if the distance is bigger than 0.5 m (e.g. trajectories of the users differ in traveled distances if a user stopped earlier, tracking error, etc.)\n if np.abs(positionU1 - positionU2) < 0.5:\n if int(frameU1) < int(frameU2):\n frame = int(frameU1)\n leading = u1.getNum()\n else:\n frame = int(frameU2)\n leading = u2.getNum()\n hwt = int(np.abs(frameU1 - frameU2))\n HW[frame] = [hwt, hwd, leading]\n # Compute headway distances\n for f in list(HW):\n if f in list(u1CurPos) and f in list(u2CurPos):\n HW[f][1] = np.abs(u1CurPos[f] - u2CurPos[f])\n return HW\n\ndef computeHeadway(o1, o2, t):\n interactionHw = None\n interactionHw = calculateHeadway(o1, o2, t)\n\n # Probable overtaking situation when hwt is very low\n if len(interactionHw.values()) > 0 and np.any(np.array(list(interactionHw.values()))[:,0] <= 8):\n try:\n # If there is an overtaking, find it's beginning and ending\n f, l = findOvertakingManeuverFrames(o1, o2)\n # Find and delete TIVs during the overtaking\n overtaking = True\n for frame in list(interactionHw):\n if f <= frame <= l:\n interactionHw.pop(frame)\n except:\n print(\"Index out of range\")\n return interactionHw\n\"\"\"\ndef avIdList(db):\n # Find id of all AVs\n conn = sqlite3.connect(db)\n cur = conn.cursor()\n cur.execute('''SELECT object_id FROM objects\n WHERE road_user_type == 7''')\n avIds = cur.fetchall()\n avIdL = [avId[0] for avId in avIds]\n conn.close()\n # Find all AVs prototypes\n return avIdL\n\ndef findAvPrototypes(db, avObjectIDs):\n avPrototypesID = set()\n connection = sqlite3.connect(db)\n conn = connection.cursor()\n # Reformating the set for the SQL command (ex.: \"... WHERE object_id IN (1, 2, 3)\"\n avObjectIDsStr = ' ,'.join(str(idNum) for idNum in avObjectIDs)\n # Find all prototypes associated with the AV objects\n conn.execute(\"SELECT prototype_id FROM objects_prototypes WHERE object_id IN ({})\".format(avObjectIDsStr))\n # Add the prototype IDs to avPrototypesID\n [avPrototypesID.add(foundID[0]) for foundID in conn.fetchall()]\n conn.close()\n return avPrototypesID\n\ndef isSimilar(db, user, avProIds):\n # Keep only cars for users with same trajectory\n if user.getUserType() == 1:\n connection = sqlite3.connect(db)\n conn = connection.cursor()\n prototypeId = conn.execute(\"SELECT prototype_id FROM objects_prototypes WHERE object_id == {}\".format(user.getNum())).fetchall()\n conn.close()\n if len(prototypeId) > 0:\n return prototypeId[0][0] in avProIds\n else:\n return False\n else:\n return False\n\ndef userIsSimilarOrShuttle(roadUser1, roadUser2, databaseFilename, avPrototypesIds):\n av = None\n u1 = roadUser1\n u2 = roadUser2\n # Determine if one of the two users is an AV, which overrides cases with similar users, to have similar vs other (excluding AV)\n if u1.userType == 7:\n av = 1\n elif u2.userType == 7:\n av = 1\n # Road user 1 should be av or similar user\n #roadUser1 = u2\n #roadUser2 = u1\n # Determine if one of the two users follows a path similar to AVs\n elif isSimilar(databaseFilename, roadUser1, avPrototypesIds):\n av = 0\n elif isSimilar(databaseFilename, roadUser2, avPrototypesIds):\n av = 0\n # Road user 1 should be av or similar user\n #roadUser1 = u2\n #roadUser2 = u1\n return av\n\"\"\"\ndef savgolFilteredSpeed(obj):\n return savgol_filter(obj.getVelocities().norm(), window_length=11, polyorder=9, mode=\"nearest\")\n\ndef savgolFilteredAcceleration(obj):\n return savgol_filter(obj.getSpeeds(), window_length=21, polyorder=15, deriv=1, mode=\"nearest\")\n\ndef extractInfoFromDirection(extractedData, orderedObjects, orientation):\n df = orderedObjects.loc[orderedObjects.direction == orientation]\n row_iterator = df.iterrows()\n _, nextRow = next(row_iterator)\n for i, row in row_iterator:\n # Find headway time and distance between two consecutive users\n leadingUser = nextRow[\"object\"]\n followingUser = row[\"object\"]\n hw = computeHeadway(leadingUser, followingUser, t)\n # Data of users\n leading_id = leadingUser.getNum()\n following_id = followingUser.getNum()\n leading_type = leadingUser.getUserType()\n following_type = followingUser.getUserType()\n\n leading_speeds = 3.6*30*(savgolFilteredSpeed(leadingUser)) # km/h\n leading_accs = 30**2*(savgolFilteredAcceleration(leadingUser)) # m/s²\n following_speeds = 3.6*30*(savgolFilteredSpeed(followingUser)) # km/h\n following_accs = 30**2*(savgolFilteredAcceleration(followingUser)) # m/s²\n\n for frame in list(hw):\n hwd = None\n hwt = None\n leading_speed = None\n following_speed = None\n leading_acc = None\n following_acc = None\n try:\n hwt = hw[frame][0]/30\n hwd = hw[frame][1]\n # leading and following switched\n if hw[frame][2] != leading_id:\n # object\n tempType = leadingUser\n leadingUser = followingUser\n followingUser = tempType\n # speeds\n tempSpeeds = leading_speeds\n leading_speeds = following_speeds\n following_speeds = tempSpeeds\n # accelerations\n tempAccs = leading_accs\n leading_accs = following_accs\n following_accs = tempAccs\n leading_id = leadingUser.getNum()\n following_id = followingUser.getNum()\n leading_type = leadingUser.getUserType()\n following_type = followingUser.getUserType()\n except:\n pass\n if frame in leadingUser.getTimeInterval():\n leading_speed = leading_speeds[frame - leadingUser.getFirstInstant()]\n leading_acc = leading_accs[frame - leadingUser.getFirstInstant()]\n if frame in followingUser.getTimeInterval():\n following_speed = following_speeds[frame - followingUser.getFirstInstant()]\n following_acc = following_accs[frame - followingUser.getFirstInstant()]\n extractedData.loc[len(extractedData)] = [leading_id, following_id, leading_type, following_type, database, frame, leading_speed, following_speed, leading_acc, following_acc, hwd, hwt]\n\n \"\"\"\n if len(hw) > 0:\n # headway time\n hwt = np.array(list(hw.values()))[:,0]\n # Remove None values\n hwt = hwt[hwt != np.array(None)]\n if len(hwt) > 0:\n # headway time statistics\n hwt_mean = np.mean(hwt)/30\n hwt_15 = np.percentile(hwt, 15)/30\n # headway distance\n hwd = np.array(list(hw.values()))[:,1]\n # Remove None values\n hwd = hwd[hwd != np.array(None)]\n if len(hwd) > 0:\n # headway distance statistics\n hwd_mean = np.mean(hwd)\n hwd_15 = np.percentile(hwd, 15)\n extractedData.loc[len(extractedData)] = [object_id, user_type, database, speed_mean, speed_15, speed_85, acc_mean, acc_15, acc_85, hwd_mean, hwd_15, hwt_mean, hwt_15]\n \"\"\"\n nextRow = row\n return extractedData\n\n\ndataPath = \"/media/disk2/etienne/Data/\"\n#locations = [\"letourneux-hochelaga\", \"letourneux-ontario\", \"montcalm-chartwell\", \"montcalm-inverness\", \"montcalm-voie\", \"montcalm-voie2\"]\nselectedSite = sys.argv[1]\nprint(\"Running script for {}\".format(selectedSite))\nlocations = [selectedSite] #[\"montcalm-voie2\"]\n# Creating a dataframe to store the variables\nextractedData = pd.DataFrame(columns=['leading_id', 'following_id', 'leading_type', 'following_type', 'database', 'frame', 'leading_speed', 'following_speed', 'leading_acc', 'following_acc', 'hwd', 'hwt'])\n\n# Connecting to metadata and extracting selected sites\nsession = metadata.connectDatabase(\"/media/disk2/etienne/Data/metadata.sqlite\")\nsites = [metadata.getSite(session, name=location)[0] for location in locations]\n\n# Going through all the sites (previously selected locations)\nfor site in sites:\n # *** Name of the intersection ***\n site_name = site.name\n print(\"----------------- Analysing {} -----------------\".format(site_name))\n\n # join montcalm-voie and montcalm-voie2\n if site_name == \"montcalm-voie2\":\n site_name = \"montcalm-voie\"\n\n worldSelectedPoints = site.alignments[0].getTrajectory().asArray().T # retrieve the site's alignments\n # Trajectory projection in curvilinear coordinates\n t = moving.Trajectory(worldSelectedPoints.T.tolist())\n t.computeCumulativeDistances()\n moving.prepareAlignments([t])\n\n # Getting all the videos from one site and analysing each one\n siteVideoSequences = metadata.getSiteVideoSequences(site)\n # Exclude removed databases\n siteVideoSequences = [vs for vs in siteVideoSequences if Path(dataPath + vs.getDatabaseFilename()).is_file()]\n\n for vs in siteVideoSequences:\n database = dataPath + vs.getDatabaseFilename()\n print(database)\n\n #videoSequenceStartTime = vs.startTime\n # *** Date of the video sequence ***\n #date = str(videoSequenceStartTime.year) + \"-\" + str(videoSequenceStartTime.month) + \"-\" + str(videoSequenceStartTime.day)\n\n # Load objects\n objects = storage.loadTrajectoriesFromSqlite(database, \"object\")\n # List of all AV id numbers\n #avIds = avIdList(database)\n # Find all AVs prototypes\n #avPrototypesIds = findAvPrototypes(database, avIds)\n\n # Sorting all objects for the heading direction and by instants\n orderedObjects = pd.DataFrame(columns=['object', 'firstFrame', 'direction'])\n for o in objects:\n # First possible direction\n direction = 0\n # Discard non motorized vehicles\n if o.userType not in (1, 3, 5, 6, 7):\n continue\n # Finding heading to sort objects accordingly afterwards\n angleWithHeading = angleBetweenUserAndAlignments(o, t)\n # Second possible direction\n if angleWithHeading <= np.pi/2:\n direction = 1\n orderedObjects.loc[len(orderedObjects)] = [o, o.getFirstInstant(), direction]\n orderedObjects = orderedObjects.sort_values(\"firstFrame\")\n\n # Go through all the objects in the second direction\n for d in (0,1):\n extractedData = extractInfoFromDirection(extractedData, orderedObjects, d)\n\nextractedData.to_csv(\"traffic-flow-data_{}.csv\".format(locations[0]), index=False)\n","sub_path":"results/performance/trafficflow/traffic-flow-data-extraction.py","file_name":"traffic-flow-data-extraction.py","file_ext":"py","file_size_in_byte":15425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"202812094","text":"import argparse\nimport base64\nfrom datetime import datetime\nimport os\nimport shutil\nimport cv2\nimport numpy as np\nimport socketio\nimport eventlet\nimport eventlet.wsgi\nfrom PIL import Image\nfrom flask import Flask\nfrom io import BytesIO\nimport tensorflow as tf \nfrom tensorflow import keras\nimport preprocess\n\nsio = socketio.Server()\napp = Flask(__name__)\nmodel = None\nprev_image_array = None\n\nMAX_SPEED = 25\nMIN_SPEED = 10\nspeed_limit = MAX_SPEED\n\nclass SimplePIController:\n def __init__(self, Kp, Ki):\n self.Kp = Kp\n self.Ki = Ki\n self.set_point = 0.\n self.error = 0.\n self.integral = 0.\n\n def set_desired(self, desired):\n self.set_point = desired\n\n def update(self, measurement):\n self.error = self.set_point - measurement\n\n self.integral += self.error\n\n return self.Kp * self.error + self.Ki * self.integral\n\ncontroller = SimplePIController(0.1, 0.002)\n\n@sio.on('telemetry')\ndef telemetry(sid, data):\n if data:\n steering_angle = float(data[\"steering_angle\"])\n throttle = float(data[\"throttle\"])\n speed = float(data[\"speed\"])\n print(\"1 \" + str(throttle) + \" \" + str(steering_angle))\n image = Image.open(BytesIO(base64.b64decode(data[\"image\"])))\n image = np.array(image)\n image = cv2.cvtColor(image,cv2.COLOR_RGB2BGR)\n #cv2.imshow('sds',image)\n #cv2.waitKey(1)\n image = preprocess.preprocessing_image_not_path(image) \n cv2.imshow('sds',image)\n cv2.waitKey(1)\n image = np.array([image]) \n steering_angle = float(model.predict(image, batch_size=1))\n\n global speed_limit\n if speed > speed_limit:\n speed_limit = MIN_SPEED # slow down\n else:\n speed_limit = MAX_SPEED\n throttle = 1.0 - steering_angle**2 - (speed/speed_limit)**2\n\n print('{} {} {}'.format(steering_angle, throttle, speed))\n send_control(steering_angle, throttle)\n else:\n print('123')\n sio.emit('manual', data={}, skip_sid=True)\n\n\n@sio.on('connect')\ndef connect(sid, environ):\n print(\"connect \", sid)\n send_control(0, 0)\n\n\ndef send_control(steering_angle, throttle):\n sio.emit(\n \"steer\",\n data={\n 'steering_angle': steering_angle.__str__(),\n 'throttle': throttle.__str__()\n },\n skip_sid=True)\n\n\nif __name__ == '__main__':\n\n model = keras.models.load_model('/home/comlab/Desktop/steer_models/nidivia_basemodel.h5')\n app = socketio.Middleware(sio, app)\n eventlet.wsgi.server(eventlet.listen(('', 4567)), app)","sub_path":"nvidia_model/drive.py","file_name":"drive.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"287395484","text":"def get_answer(filename=\"text_files/problem013.txt\", number_of_digits=10):\n \"\"\"\n Due to Python's arbitrary precision, you can just explicitly add all rows of filename together\n :return: The sum of all numbers (with each number on a newline) in file filename\n \"\"\"\n f = open(filename, \"r\")\n strings = f.readlines()\n f.close()\n summation = 0\n for x in range(len(strings)):\n summation += int(strings[x])\n return int(str(summation)[:number_of_digits])\n","sub_path":"project_euler/solutions/problem013.py","file_name":"problem013.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"422614737","text":"import requests\n\nfrom htpclient.config import *\n\n\nclass JsonRequest:\n def __init__(self, data):\n self.data = data\n self.config = Config()\n\n def execute(self):\n try:\n logging.debug(self.data)\n r = requests.post(self.config.get_value('url'), json=self.data)\n if r.status_code != 200:\n logging.error(\"Status code from server: \" + str(r.status_code))\n return None\n logging.debug(r.content)\n return r.json()\n except Exception as e:\n logging.error(\"Error occurred: \" + str(e))\n return None\n","sub_path":"python/htpclient/jsonRequest.py","file_name":"jsonRequest.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"397078626","text":"from osgeo import gdal\n\nimport utilsDEM as utDEM\n\n# shapefile='images/areaStudioQuad.shp'\n# src_ds = ogr.Open(shapefile)\n# src_lyr=src_ds.GetLayer()\n#\n# maskvalue = 1\n#\n# rasterfn = 'images/SRTMAreaCordobaQuad.tif'\n# newRasterfn = 'images/SRTMAreaCordobaQuadNew.tif'\n#\n# raster = gdal.Open(rasterfn)\n# geotransform = raster.GetGeoTransform()\n# originX = geotransform[0]\n# originY = geotransform[3]\n# pixelWidth = geotransform[1]\n# pixelHeight = geotransform[5]\n# cols = raster.RasterXSize\n# rows = raster.RasterYSize\n# driver = gdal.GetDriverByName('GTiff')\n# outRaster = driver.Create(newRasterfn, cols, rows, 1, gdal.GDT_Float32)\n# outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight))\n# outband = outRaster.GetRasterBand(1)\n# outband.Fill(0)\n# outband.SetNoDataValue(0)\n# outRaster.SetGeoTransform(geotransform)\n# err = gdal.RasterizeLayer(outRaster, [maskvalue], src_lyr)\n# outRaster.FlushCache()\n#\n# mask_arr=outRaster.GetRasterBand(1).ReadAsArray()\n\n\n####### OTRA PRUEBA\nzonaCordobaQuad = 'images/SRTMAreaCordobaQuad.tif'\nzonaCordobaQuadArr = gdal.Open(zonaCordobaQuad).ReadAsArray() # converting to array image file\n\nnan = -32768\n\nmaskArea = (zonaCordobaQuadArr != nan) * 1.0\nutDEM.array2raster(zonaCordobaQuad, 'images/maskArea.tif', maskArea)\n\nprint(\"Finish\")\n","sub_path":"maskFromShp.py","file_name":"maskFromShp.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"41996535","text":"import os\n\nimport pandas as pd\n\nimport config as cfg\nfrom src.tools.data_processing import download_file\n\n# ======================================================================================================================\n# download and process opsd time series\n\nurl_opsd = 'https://data.open-power-system-data.org/time_series/latest/time_series_60min_singleindex.csv'\nopsd_file = os.path.join(cfg.MEDEA_ROOT_DIR, 'data', 'raw', 'opsd_time_series_60min.csv')\ndownload_file(url_opsd, opsd_file)\nts_opsd = pd.read_csv(opsd_file)\n\n# create medea time series dataframe\nts_medea = ts_opsd[\n ['utc_timestamp', 'cet_cest_timestamp', 'AT_load_entsoe_transparency', 'AT_solar_generation_actual',\n 'AT_wind_onshore_generation_actual', 'DE_load_entsoe_transparency', 'DE_solar_profile',\n 'DE_wind_onshore_profile', 'DE_wind_offshore_profile', 'DE_price_day_ahead']]\ndel ts_opsd\nts_medea = ts_medea.copy()\nts_medea.set_index(pd.DatetimeIndex(ts_medea['utc_timestamp']), inplace=True)\nts_medea.drop('utc_timestamp', axis=1, inplace=True)\nts_medea.rename(columns={'AT_load_entsoe_transparency': 'AT-power-load',\n 'AT_solar_generation_actual': 'AT-pv-generation',\n 'AT_wind_onshore_generation_actual': 'AT-wind_on-generation',\n 'DE_load_entsoe_transparency': 'DE-power-load',\n 'DE_solar_profile': 'DE-pv-profile',\n 'DE_wind_onshore_profile': 'DE-wind_on-profile',\n 'DE_wind_offshore_profile': 'DE-wind_off-profile',\n 'DE_price_day_ahead': 'price_day_ahead'}, inplace=True)\nif ts_medea.index.max() < pd.Timestamp(f'{ts_medea.index.max().year}-07-01 00:00:00', tz='UTC'):\n df_expand = pd.DataFrame(\n index=pd.date_range(start=ts_medea.index.max()+pd.Timedelta(hours=1),\n end=pd.Timestamp(f'{ts_medea.index.max().year}-07-01 00:00:00', tz='UTC'), freq='H'),\n columns=ts_medea.columns)\n ts_medea = ts_medea.append(df_expand)\n\nts_medea['AT-power-load'] = ts_medea['AT-power-load'] / 1000\nts_medea['DE-power-load'] = ts_medea['DE-power-load'] / 1000\nts_medea['AT-pv-generation'] = ts_medea['AT-pv-generation'] / 1000\nts_medea['AT-wind_on-generation'] = ts_medea['AT-wind_on-generation'] / 1000\n\n# ----------------------------------------------------------------------------------------------------------------------\n# intermittent capacities\nitm_capacities = pd.read_excel(os.path.join(cfg.MEDEA_ROOT_DIR, 'data', 'processed', 'static_data.xlsx'),\n 'itm_installed',\n header=[0, 1], index_col=[0])\nitm_capacities['year'] = itm_capacities.index\nitm_capacities['date'] = pd.to_datetime(itm_capacities['year'] + 1, format='%Y', utc='true') - pd.Timedelta(days=184)\nitm_capacities.set_index('date', inplace=True)\nts_medea['AT-pv-capacity'] = itm_capacities[('AT', 'pv')]\nts_medea['AT-pv-capacity'] = ts_medea['AT-pv-capacity'].interpolate()\nts_medea['AT-wind_on-capacity'] = itm_capacities[('AT', 'wind_on')]\nts_medea['AT-wind_on-capacity'] = ts_medea['AT-wind_on-capacity'].interpolate()\nts_medea['AT-wind_on-profile'] = ts_medea['AT-wind_on-generation'] / ts_medea['AT-wind_on-capacity']\nts_medea['AT-wind_off-profile'] = 0\nts_medea['AT-pv-profile'] = ts_medea['AT-pv-generation'] / ts_medea['AT-pv-capacity']\n\n# ----------------------------------------------------------------------------------------------------------------------\n# heat consumption data\nts_load_ht = pd.read_csv(os.path.join(cfg.MEDEA_ROOT_DIR, 'data', 'processed', 'heat_hourly_consumption.csv'),\n index_col=[0], header=[0, 1])\nts_load_ht.index = pd.DatetimeIndex(ts_load_ht.index).tz_localize('utc')\nfor reg in cfg.zones:\n ts_medea[f'{reg}-heat-load'] = ts_load_ht.loc[:, reg].sum(axis=1)\n\n# ----------------------------------------------------------------------------------------------------------------------\n# read hydro data\nts_hydro_ror = pd.read_csv(os.path.join(cfg.MEDEA_ROOT_DIR, 'data', 'processed', 'generation_hydro.csv'), index_col=[0])\nts_hydro_ror.index = pd.DatetimeIndex(ts_hydro_ror.index).tz_localize('utc')\nfor reg in cfg.zones:\n ts_medea[f'{reg}-ror-capacity'] = itm_capacities[(reg, 'ror')]\n ts_medea[f'{reg}-ror-capacity'] = ts_medea[f'{reg}-ror-capacity'].interpolate()\n ts_medea[f'{reg}-ror-profile'] = ts_hydro_ror[f'ror_{reg}'] / 1000 / ts_medea[f'{reg}-ror-capacity']\n\n# ----------------------------------------------------------------------------------------------------------------------\n# commercial flows\nts_flows = pd.read_csv(os.path.join(cfg.MEDEA_ROOT_DIR, 'data', 'processed', 'commercial_flows.csv'), index_col=[0])\nts_flows.index = pd.DatetimeIndex(ts_flows.index).tz_localize('utc')\nfor reg in cfg.zones:\n ts_medea[f'{reg}-imports-flow'] = ts_flows.loc[:, f'imp_{reg}'] / 1000\n ts_medea[f'{reg}-exports-flow'] = ts_flows.loc[:, f'exp_{reg}'] / 1000\n\n# ----------------------------------------------------------------------------------------------------------------------\n# filling rates of hydro reservoirs\ndf_hydro_fill = pd.read_csv(os.path.join(cfg.MEDEA_ROOT_DIR, 'data', 'processed', 'reservoir_filling.csv'),\n index_col=[0])\ndf_hydro_fill.index = pd.DatetimeIndex(df_hydro_fill.index).tz_localize('utc')\nts_hydro_fill = pd.DataFrame(\n index=pd.date_range(pd.datetime(df_hydro_fill.head(1).index.year[0], 1, 1, 0, 0),\n pd.datetime(df_hydro_fill.tail(1).index.year[0], 12, 31, 23, 0),\n freq='h', tz='utc'), columns=cfg.zones)\nts_hydro_fill.update(df_hydro_fill[cfg.zones].resample('H').interpolate(method='pchip'))\nts_hydro_fill = ts_hydro_fill.fillna(method='pad')\nts_hydro_fill = ts_hydro_fill.fillna(method='bfill')\nfor reg in cfg.zones:\n ts_medea[f'{reg}-fill-reservoir'] = ts_hydro_fill.loc[:, reg] / df_hydro_fill[reg].max()\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n# reservoir inflows\ninflows = pd.DataFrame(columns=cfg.zones)\nfor reg in cfg.zones:\n # upsample turbining and pumping to fill rate times and calculate balance at time of fill readings\n inflows[reg] = (df_hydro_fill[reg] - df_hydro_fill[reg].shift(periods=-1) - ts_hydro_ror[f'psp_con_{reg}'].resample(\n 'W-MON').sum() + ts_hydro_ror[f'psp_gen_{reg}'].resample('W-MON').sum() + ts_hydro_ror[f'res_{reg}'].resample(\n 'W-MON').sum())/1000 / 168\n inflows.loc[inflows[reg]<0, reg] = 0\n # downsample to hours\n ts_medea[f'{reg}-inflows-reservoir'] = inflows[reg].resample('H').interpolate(method='pchip')\n ts_medea.loc[ts_medea[f'{reg}-inflows-reservoir'] < 0, f'{reg}-inflows-reservoir'] = 0\n\n# ----------------------------------------------------------------------------------------------------------------------\n# fuel and co2 price data\ndf_fuels = pd.read_csv(os.path.join(cfg.MEDEA_ROOT_DIR, 'data', 'processed', 'monthly_fuel_prices.csv'),\n index_col=[0], parse_dates=True)\nts_prices = df_fuels[['NGas_DE', 'Brent_UK', 'Coal_SA']]\nts_prices = ts_prices.resample('H').interpolate('pchip')\nts_prices.rename({'NGas_DE': 'Gas', 'Coal_SA': 'Coal', 'Brent_UK': 'Oil'}, axis=1, inplace=True)\nts_prices.index = ts_prices.index.tz_localize('utc')\ndf_eua = pd.read_csv(os.path.join(cfg.MEDEA_ROOT_DIR, 'data', 'processed', 'co2_price.csv'),\n index_col=[0], parse_dates=True)\ndf_eua.index = df_eua.index.tz_localize('utc')\nts_prices['EUA'] = df_eua.resample('H').interpolate('pchip')\nts_medea = pd.merge(ts_medea, ts_prices, how='outer', left_index=True, right_index=True)\n\n# ----------------------------------------------------------------------------------------------------------------------\n# Write only one date, call that column DateTime\nts_medea.index.name = 'DateTime'\nts_medea.drop(['cet_cest_timestamp'], axis=1, inplace=True)\nts_medea.to_csv(os.path.join(cfg.MEDEA_ROOT_DIR, 'data', 'processed', 'medea_regional_timeseries.csv'))\n","sub_path":"src/data/compile_timeseries.py","file_name":"compile_timeseries.py","file_ext":"py","file_size_in_byte":8058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"636169470","text":"# Simple robot using approxeng.input and redboard\n# Do pip3 install approxeng.input approxeng.task and attach a controller\nfrom approxeng.input.selectbinder import ControllerResource\nfrom redboard import RedBoard, Display\nfrom time import sleep\nfrom approxeng.task import task, run, register_resource, TaskStop\nfrom approxeng.task.menu import register_menu_tasks_from_yaml, MenuTask, MenuAction\n\n# Initialise the RedBoard and its attached OLED display, register them\n# as named resources to make them available to tasks later.\nregister_resource(name='board', value=RedBoard())\noled_display = Display()\nregister_resource(name='display', value=oled_display)\n\n\nclass MenuControllerTask(MenuTask):\n \"\"\"\n Use a connected gamepad as menu navigation, write out menus to the redboard's display module\n \"\"\"\n\n ACTIONS = {'dleft': MenuAction.previous,\n 'dright': MenuAction.next,\n 'cross': MenuAction.select,\n 'dup': MenuAction.up}\n\n def get_menu_action(self, world):\n for button, action in MenuControllerTask.ACTIONS.items():\n if button in world.joystick.presses:\n return action\n\n def display_menu(self, world, title, item_title, item_index, item_count):\n world.display.text(line1=title,\n line2=item_title,\n line3='{}/{}'.format(item_index + 1, item_count))\n\n\ndef mixer(yaw, throttle):\n \"\"\"\n Map x and y joystick axes to a pair of motor speeds\n \"\"\"\n left = throttle + yaw\n right = throttle - yaw\n scale = 1.0 / max(1, abs(left), abs(right))\n return int(left * scale), int(right * scale)\n\n\n@task(name='drive')\ndef manual_control(joystick, display, board):\n \"\"\"\n Manual control task, reads information from the left analogue stick and uses it to\n set motor values on the redboard's main motors, as well as showing information on\n the display and lighting up the LED.\n \"\"\"\n lx, ly = joystick['lx', 'ly']\n board.m0, board.m1 = mixer(yaw=lx, throttle=ly)\n display.text(line1='Simple Robot Script',\n line2='x={:.2f}, y={:.2f}'.format(lx, ly),\n line3='Press HOME to exit.')\n board.set_led(ly / 4, 1, ly) if ly >= 0 else board.set_led(1 + ly / 4, 1, abs(ly))\n\n\n@task(name='stop')\ndef turn_off(board):\n \"\"\"\n Turns off any motors and redirects back to the main menu.\n \"\"\"\n board.stop()\n return 'main_menu'\n\n\n# Load menus from a YAML file\nregister_menu_tasks_from_yaml('robot_menus.yml',\n menu_task_class=MenuControllerTask,\n resources=['joystick', 'display'])\n\n# Loop forever until a task exits for a reason other than disconnection\nwhile True:\n try:\n with ControllerResource() as controller:\n\n # Tell the task system about the joystick\n register_resource('joystick', controller)\n\n\n def check_joystick():\n \"\"\"\n Called before every tick, sets up button presses, checks for joystick\n disconnection, and bounces back to the home menu via a motor shutdown\n task if the home button is pressed.\n \"\"\"\n if not controller.connected:\n return TaskStop('disconnection')\n controller.check_presses()\n if 'home' in controller.presses:\n return 'stop'\n\n\n # Run the task loop\n exit_reason = run(root_task='main_menu',\n error_task='stop',\n check_tasks=[check_joystick])\n\n # If we disconnected then wait for reconnection, otherwise break out\n # and exit the script.\n if exit_reason is not 'disconnection':\n break\n\n except IOError:\n # Raised if there's no available controller, display this information\n oled_display.text(line1='Simple Robot Script', line3='Waiting for Controller')\n sleep(1)\n","sub_path":"scripts/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":4010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"501454627","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 13 22:36:15 2021\r\n\r\n@author: danli\r\n\"\"\"\r\nfrom netCDF4 import Dataset\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfrom datetime import date\r\nimport functools \r\nimport os \r\nfrom oceans.colormaps import cm\r\n\r\npath0='D:\\\\CIO\\\\pg_web\\\\'\r\ndir_list=os.listdir('D:\\\\CIO\\\\pg_web\\\\'); check= 't'\r\nbuoy_list = [idx for idx in dir_list if idx[0].lower() == check.lower()]\r\n\r\nfor kk in range(len(buoy_list)):\r\n fn=buoy_list[kk]\r\n print(fn)\r\n #fn='t0n110w_dy.cdf'\r\n data=Dataset(path0+fn)\r\n \r\n lat = data.variables['lat'][:]\r\n lon = data.variables['lon'][:]\r\n depth = data.variables['depth'][:]\r\n time = data.variables['time'][:]\r\n \r\n starting_date = data.variables['time'].units[11:21]\r\n \r\n \r\n temp = data.variables['T_20'][:][:,:,0,0]\r\n creation_day=data.variables['time'].units; yy=int(creation_day[11:15]); mm=int(creation_day[16:18]); dd=int(creation_day[19:21])\r\n fecha=time+np.array(date.toordinal(date(yy,mm,dd)))\r\n temp=np.array(temp,dtype='float32').T\r\n \r\n #start=2020\r\n yrst=2020; most=1; dast=1\r\n date_start=np.array(date.toordinal(date(yrst,most,dast)))\r\n find_stdate=np.where(fecha==date_start)\r\n fdt=functools.reduce(lambda sub, ele: sub * 10 + ele, find_stdate)\r\n if len(fdt)==0 :\r\n print(\"Starting date is out of range\")\r\n continue\r\n \r\n indx_date=int(fdt)\r\n fecha_inicio=fecha[indx_date:]; \r\n \r\n ending_date = date.fromordinal(int(fecha_inicio[-1])) \r\n date_range = pd.date_range(start= starting_date, end=ending_date)\r\n \r\n temp[temp==1.0000000e+35] = np.nan; sst=temp[:,indx_date:]\r\n \r\n cum_sst=[]\r\n df=pd.DataFrame(sst)\r\n for ik in range(len(sst)):\r\n ss=df.T[ik].rolling(window=5,min_periods=1).mean()\r\n cum_sst.append(ss)\r\n \r\n sst_moving_ave=np.array(cum_sst)\r\n \r\n #resta\r\n num_ave=len(sst[1])-len(sst_moving_ave[1])\r\n #plot\r\n plt.figure(figsize=(11.69,8.27))\r\n vmin=8; vmax=32; step=2;#colorscale\r\n cs = plt.pcolormesh(date_range[indx_date+num_ave:], -depth, sst_moving_ave, vmin=vmin, vmax=vmax, cmap=cm.avhrr, shading='flat')\r\n plt.yticks(list(range(0,-300-20,-20)))\r\n contours= plt.contour(date_range[indx_date+num_ave:], -depth, sst_moving_ave,levels=[10,11,12,15,20,25,28,30],colors='black',linewidths=0.5)\r\n plt.clabel(contours, inline=True,fmt = '%2.0f',fontsize=10)\r\n plt.ylim([-300,0])\r\n cb = plt.colorbar(cs, pad=0.02, orientation='vertical', fraction=0.1)\r\n cb.ax.locator_params(nbins=len(list(range(vmin,vmax,step))))\r\n cb.ax.tick_params(direction='out')\r\n cb.set_label('Temperature ($^\\circ$C)')\r\n plt.title('Daily Subsurface Temperature Buoy '+fn[1]+'º'+fn[2]+fn[3:6]+'º'+fn[6])\r\n plt.text(0.8, 0.05, str(ending_date),fontsize=10, transform=plt.gcf().transFigure)\r\n plt.text(0.07, 0.05, 'DALB',fontsize=10, transform=plt.gcf().transFigure)\r\n plt.tight_layout()\r\n \r\n # plt.savefig('D:\\\\CIO\\\\pg_web\\\\ST_boya'+fn[1:7]+'.png',\r\n # format='png', dpi=600, transparent=False)\r\n plt.show()\r\n \r\n \r\n \r\n \r\n \r\n \r\n","sub_path":"boyas_seccion_temp_moving_ave.py","file_name":"boyas_seccion_temp_moving_ave.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"212952324","text":"def sieve(n):\n\t\n\tif n < 2:\n\t\treturn None\t\n\n\tprimes = []\n\tn -= 2\n\tfor i in range(n):\n\t\tprimes.append(i + 2)\n\tfor i in range(n):\n\t\tif primes[i] == -1:\n\t\t\tcontinue\n\t\telm = primes[i]\n\t\tfor j in range(2, n):\n\t\t\tif elm * j > n + 1:\n\t\t\t\tbreak\n\t\t\tprimes[(elm * j) - 2] = -1\n\n\tprimes = [i for i in primes if i != -1]\n\treturn primes\n\ndef solution(n):\n\n\tif n < 4:\n\t\treturn None\n\n\tsolutions = []\n\tprimes = sieve(n)\n\tl = 0\n\tr = len(primes) - 1\n\twhile l <= r:\n\t\tsummed = primes[l] + primes[r]\n\t\tif summed == n:\n\t\t\tsolutions.append((primes[l], primes[r]))\n\t\t\tl += 1\n\t\telif summed < n:\n\t\t\tl += 1\n\t\telse:\n\t\t\tr -= 1\n\treturn solutions[0]\n\nprint(solution(26))\nprint(solution(40))\nprint(solution(100))\nprint(solution(12))\nprint(solution(6))\n","sub_path":"Problem_101/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"506212425","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.utils.timezone\nimport blanc_basic_assets.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('assets', '__first__'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Category',\n fields=[\n ('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),\n ('title', models.CharField(max_length=100, db_index=True)),\n ('slug', models.SlugField(max_length=100, unique=True)),\n ],\n options={\n 'verbose_name_plural': 'categories',\n 'ordering': ('title',),\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Post',\n fields=[\n ('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),\n ('title', models.CharField(max_length=100, db_index=True)),\n ('slug', models.SlugField(max_length=100, unique_for_date='date')),\n ('date', models.DateTimeField(default=django.utils.timezone.now, db_index=True)),\n ('date_url', models.DateField(db_index=True, editable=False)),\n ('teaser', models.TextField(blank=True)),\n ('content', models.TextField()),\n ('published', models.BooleanField(help_text='Post will be hidden unless this option is selected', default=True, db_index=True)),\n ('category', models.ForeignKey(to='news.Category')),\n ('image', blanc_basic_assets.fields.AssetForeignKey(to='assets.Image', null=True, blank=True)),\n ],\n options={\n 'ordering': ('-date',),\n 'get_latest_by': 'date',\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"blanc_basic_news/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"568764190","text":"import json\nfrom flask import Flask, render_template\nimport os\njson_data=open(r\"result.json\").readlines()\nnewsfeeds = []\nfor line in json_data:\n item=json.loads(line)\n if item['city']=='New York':\n newsfeeds.append(item)\n print(item.keys())\n\napp = Flask(\"homework\",template_folder='templates',)\n@app.route('/')\ndef hello_world():\n keys=['uuid', 'name', 'type', 'primary_role', 'cb_url', 'domain', 'homepage_url', 'logo_url', 'facebook_url', 'twitter_url', 'linkedin_url', 'combined_stock_symbols', 'city', 'region', 'country_code', 'short_description']\n return render_template('index.html', data =newsfeeds,keys=keys)\napp.run(host='localhost', port=5001)\n\n \n\n\n\n\n","sub_path":"flask应用/flask使用模板/作业.py","file_name":"作业.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"96360352","text":"\"\"\"\n说明:斐波那契数列(Fibonacci sequence),又称黄金分割数列,是意大利数学家莱昂纳多·斐波那契(Leonardoda Fibonacci)在《计算之书》中提出一个在理想假设条件下兔子成长率的问题而引入的数列,所以这个数列也被戏称为\"兔子数列\"。斐波那契数列的特点是数列的前两个数都是1,从第三个数开始,每个数都是它前面两个数的和,形如:1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...。斐波那契数列在现代物理、准晶体结构、化学等领域都有直接的应用。\n\"\"\"\n\nnum = int(input(\"请输入个数: \"))\nnum -= 2\nfiblist = [1, 1]\nfor x in range(num):\n fiblist.append(fiblist[-1] + fiblist[-2])\n\nprint(fiblist)\n\n","sub_path":"demo/python/cal_fibonacci_number.py","file_name":"cal_fibonacci_number.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"119814176","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n################################################################################\nfrom string import Template\nimport collections\n\nfrom wsgiref.simple_server import make_server\nfrom pyramid.config import Configurator\nfrom pyramid.response import Response\nfrom pyramid.location import lineage\n\nfrom pyramid.httpexceptions import HTTPFound\nfrom pyramid.traversal import (resource_path,\n traverse,\n find_resource)\nfrom pyramid.decorator import reify\n\n\nclass MyContainer(collections.MutableMapping):\n __parent__ = __name__ = None\n\n def __init__(self):\n self.ckeys = collections.deque()\n self.container = {}\n\n def __getitem__(self, key):\n try:\n item = self.container[key]\n return item\n except KeyError as e:\n raise\n\n def __setitem__(self, key, value):\n if key in self.ckeys:\n self.container[key] = value\n else:\n self.ckeys.append(key)\n self.container[key] = value\n value.__name__ = key\n value.__parent__ = self\n\n def __delitem__(self, key):\n if key in self.ckeys:\n self.ckeys.remove(key)\n del self.container[key]\n else:\n raise KeyError\n\n def __len__(self):\n return len(self.ckeys)\n\n def __iter__(self):\n return iter(self.ckeys)\n\n\nclass Folder(MyContainer):\n def __init__(self, title):\n super(Folder, self).__init__()\n self.title = title\n\n\nclass Document(object):\n __parent__ = __name__ = None\n def __init__(self, title, description, body):\n self.title = title\n self.description = description\n self.body = body\n\n\nclass SiteFolder(Folder):\n pass\n\n\nclass LibCategory(MyContainer):\n def __init__(self, title):\n super(LibCategory, self).__init__()\n self.title = title\n\n\nclass Library(MyContainer):\n def __init__(self, title, categories):\n super(Library, self).__init__()\n self.title = title\n # init categories containers\n for c in categories:\n self[c['href']] = LibCategory(title=c['title'])\n\n\n############################################################\n# functions\n#\ndef get_root(request):\n return RTREE\n\n\ndef getBreadCrumbs(request):\n cr = [(request.resource_url(i), i.title)\n for i in lineage(request.context)]\n cr.reverse()\n li = ['
  • ' + '' +\n i[1] + '
  • ' for i in cr[:-1]]\n #last item of breadcrumbs\n li.append('
  • ' + cr[-1][1] + '
  • ')\n return \"
      \" + \"\\n\".join(li) + \"
    \"\n\n\ndef getFolderLeaves(request):\n leaves = [(request.resource_url(v), v.title)\n for k, v in request.context.items()]\n li = ['
  • ' + '' +\n i[1] + '
  • ' for i in leaves]\n return \"
      \" + \"\\n\".join(li) + \"
    \"\n\n############################################################\n# views\n#\ndef view_site(context, request):\n s = Template(u\"\"\"\n \n \n \n $title\n \n \n

    Main page of site $title

    \n

    Leaves:

    $keys\n \n \n \"\"\")\n output = s.safe_substitute(title = context.title,\n keys = getFolderLeaves(request))\n\n return Response(body=output,\n charset='utf-8',\n content_type='text/html',\n content_language='ru')\n\n\ndef view_folder(context, request):\n s = Template(u\"\"\"\n \n \n \n Folder $name\n \n \n

    BC:

    $breadcrumbs\n
    \n

    title: $title

    \n
    \n

    Leaves:

    $keys\n \n \n \"\"\")\n\n output = s.safe_substitute(breadcrumbs = getBreadCrumbs(request),\n name = context.__name__,\n title = context.title,\n keys = getFolderLeaves(request))\n\n return Response(body=output,\n charset='utf-8',\n content_type='text/html',\n content_language='ru')\n\n\ndef view_doc(context, request):\n s = Template(u\"\"\"\n \n \n \n Document $name\n \n \n

    BC:

    $breadcrumbs\n
    \n

    $title

    \n $description\n $body\n
    \n \n \n \"\"\")\n\n output = s.safe_substitute(breadcrumbs = getBreadCrumbs(request),\n name = context.__name__,\n title = context.title,\n description = context.description,\n body = context.body)\n return Response(body=output,\n charset='utf-8',\n content_type='text/html',\n content_language='ru')\n\n\ndef view_library(context, request):\n s = Template(u\"\"\"\n \n \n \n Library $name\n \n \n

    BC:

    $breadcrumbs\n
    \n

    title: $title

    \n
    \n

    Leaves:

    $keys\n \n \n \"\"\")\n\n output = s.safe_substitute(breadcrumbs = getBreadCrumbs(request),\n name = context.__name__,\n title = context.title,\n keys = getFolderLeaves(request))\n\n return Response(body=output,\n charset='utf-8',\n content_type='text/html',\n content_language='ru')\n\ndef view_libcategory(context, request):\n s = Template(u\"\"\"\n \n \n \n Category $name\n \n \n

    BC:

    $breadcrumbs\n
    \n

    Категория: $title

    \n
    \n

    Leaves:

    $keys\n \n \n \"\"\")\n\n output = s.safe_substitute(breadcrumbs = getBreadCrumbs(request),\n name = context.__name__,\n title = context.title,\n keys = getFolderLeaves(request))\n\n return Response(body=output,\n charset='utf-8',\n content_type='text/html',\n content_language='ru')\n############################################################\n# library categories of books\nCATEGORIES = [\n {'id': 1,\n 'title': u'C++',\n 'href': 'cpp'},\n {'id': 2,\n 'title': u'python',\n 'href': 'python'},\n {'id': 3,\n 'title': u'васик',\n 'href': 'vasik'},\n]\n\n\n# resources tree\n#\nRTREE = SiteFolder(title=u'Library 1')\n\nfolder1 = Folder(title=u'Folder one')\nRTREE[u'f1'] = folder1\n\nfolder2 = RTREE[u'f2'] = Folder(title=u'Folder two')\n\nd1 = Document(title=u'document 1',\n description=u'No description',\n body=u'

    Body of testing document 1

    ')\nfolder1[u'd1'] = d1\n\nd2 = Document(title=u'document 2',\n description=u'No description also',\n body=u'

    Body of testing document 2

    ')\nfolder1[u'd2'] = d2\n\nlibrary = Library(title=u'Библиотека',\n categories=CATEGORIES)\nRTREE[u'lib'] = library\n\n\n\n\n\n\nif __name__ == '__main__':\n config = Configurator(root_factory=get_root)\n\n config.add_view(view=view_site,\n context=SiteFolder)\n\n config.add_view(view=view_folder,\n context=Folder)\n\n config.add_view(view=view_doc,\n context=Document)\n\n config.add_view(view=view_library,\n context=Library)\n config.add_view(view=view_libcategory,\n context=LibCategory)\n\n\n\n app = config.make_wsgi_app()\n server = make_server('0.0.0.0', 8080, app)\n server.serve_forever()\n","sub_path":"misc/traversal_basics/Library/library3.py","file_name":"library3.py","file_ext":"py","file_size_in_byte":8713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"230582181","text":"import sys\nfrom dotenv import load_dotenv\nimport os\nfrom pathlib import Path\nfrom step import Step\nfrom app_environment import AppEnvironment\n'''\nclass ProjectEnvironment(AppEnvironment):\n def __init__(self, project_name='example'):\n super().__init__()\n self.project_name = project_name\n # project folders eg example/docker, example/temp\n'''\nclass ProjectEnvironment(AppEnvironment):\n def __init__(self):\n super().__init__()\n self.description=['Placeholder for other project steps',\n 'Stash project-name, project-folder-name, and project-folder values.']\n #self.project_name = self.appSettings.getFolder('')\n # project folders eg example/docker, example/temp\n\n def process(self):\n super().process()\n\n self.set('project-name', self.get('LB_PROJECT.name'))\n # self.set('project-name', self.get('LB_PROJECT_name'))\n\n self.set('project-folder-name', '{}-{}'.format(self.get('project-name'), self.get('LB_ENV') ) )\n self.set('project-folder', self.appSettings.getFolder('project-folder'))\n #print('data', self.getData())\n\n #appSettings.createProje ctFolders()\n\n '''\n self.getData()['project-folders'] = {} # call to bring data forward\n prj_folder = '{}/.{}/projects/{}'.format(str(Path.home()),\n self.getData()['LB_WORKING_FOLDER_NAME'],\n self.project_name)\n\n self.getData()['project-name'] = self.project_name\n self.getData()['project-folders']['project-folder'] = prj_folder # create project file\n # put togethe full path with kev-val on end\n for key in self.child_folder_dict:\n self.getData()['project-folders'][key]='{}/{}'.format(prj_folder, self.child_folder_dict[key])\n '''\n return self\n'''\n def process(self):\n super().process()\n self.getData()['project-folders'] = {} # call to bring data forward\n prj_folder = '{}/.{}/projects/{}'.format(str(Path.home()),\n self.getData()['LB_WORKING_FOLDER_NAME'],\n self.project_name)\n\n self.getData()['project-name'] = self.project_name\n self.getData()['project-folders']['project-folder'] = prj_folder # create project file\n # put togethe full path with kev-val on end\n for key in self.child_folder_dict:\n self.getData()['project-folders'][key]='{}/{}'.format(prj_folder, self.child_folder_dict[key])\n\n return self\n'''\n\n\ndef main():\n from app_environment import AppEnvironment\n from app_create_folders import AppCreateFolders\n from app_initialize import AppInitialize\n from app_settings import AppSettingsTest\n from util import Util\n\n print('* ProjectEnvironment')\n os.environ['LB-TESTING'] = '1'\n appSettings = AppSettingsTest()\n\n #step = ProjectEnvironment('example').setWorkingFolder('temp').run()\n step = ProjectEnvironment().run()\n print('* {}'.format(step.getClassName()))\n print(' - {}'.format(step.getDescription()))\n\n print(' - set project data')\n #assert(step.getData()['LB_WORKING_FOLDER_NAME']=='temp')\n assert(step.getData()['project-name']== os.environ['LB_PROJECT_name'] or 'example')\n assert(step.get('project-folder').endswith(step.get('project-folder-name')))\n assert ('project-name' in step.getData())\n assert ('project-folder-name' in step.getData())\n assert ('project-folder' in step.getData())\n #step.log(step.getData(), echo=True)\n #appSettings.removeFolders()\n os.environ['LB-TESTING'] = '0'\n\nif __name__ == \"__main__\":\n main()","sub_path":"_app/project_environment.py","file_name":"project_environment.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"186288379","text":"# -*- coding: utf-8 -*-\n\nimport time\nimport requests\nfrom urllib2 import quote, urlopen, urlparse\nfrom scrapy import Spider, Item, Field\nfrom scrapy.http import Request\nfrom scrapy.contrib.loader import ItemLoader\nfrom scrapy.contrib.loader.processor import MapCompose\nfrom scrapy.utils.markup import remove_tags\nfrom scrapy.selector import Selector\nfrom search.items import SearchItem\n\n\nclass SearchSpider(Spider):\n\n download_delay = 1\n\n def __init__(self, kws=None):\n\n urls = self.conf['urls']\n if not kws:\n kws = urls['kws']\n\n if isinstance(kws, str):\n self.log('download: %s'%kws)\n kws = urlopen(kws).readlines()\n\n self.kws = kws\n self.allowed_domains = [urlparse.urlparse(urls['fmt']).netloc]\n\n super(SearchSpider, self).__init__()\n\n def start_requests(self):\n\n enc = self.conf['urls'].get('enc', 'utf-8')\n\n for kw in self.kws:\n kw = unicode(kw, encoding='utf-8').strip()\n page = self.conf['page']\n start, step, stop = page['start'], page['step'], page['stop']\n for pg in xrange(start, stop, step):\n url = self.conf['urls']['fmt'].format(\n kw=quote(kw.encode(enc)),\n pg=pg\n )\n yield Request(url, meta={'kw': kw})\n \n self.start_urls = gen_urls()\n\n def parse(self, response):\n\n sel = Selector(response)\n\n for e in sel.xpath(self.conf['loop']):\n loader = ItemLoader(SearchItem(), selector=e)\n loader.add_value('bot', self.name)\n loader.add_xpath('url', self.conf['fields']['url'])\n loader.add_xpath('title', self.conf['fields']['title'], MapCompose(remove_tags, lambda x: x.strip()))\n loader.add_value('word', response.meta['kw'])\n loader.add_value('time', time.time())\n yield loader.load_item()\n\n\nclass SoSpider(SearchSpider):\n\n name = 'so'\n\n conf = {\n 'urls': {\n 'fmt': 'http://www.so.com/s?q={kw}&pn={pg}',\n 'kws': ['hello', 'world'],\n 'enc': 'utf-8',\n },\n 'page': {\n 'start': 1,\n 'step': 1,\n 'stop': 10,\n },\n 'loop': '//ul[@id=\"m-result\"]/li[@class=\"res-list\"]',\n 'fields': {\n 'url': './h3/a/@href',\n 'title': './h3/a',\n }\n }\n\n\nclass SogouSpider(SearchSpider):\n\n name = 'sogou'\n\n conf = {\n 'urls': {\n 'fmt': 'http://www.sogou.com/web?query={kw}&page={pg}',\n 'kws': [u'你好', u'世界'],\n 'enc': 'utf-8',\n },\n 'page': {\n 'start': 1,\n 'step': 1,\n 'stop': 10,\n },\n 'loop': '//div[@class=\"results\"]/div[@class=\"rb\"]',\n 'fields': {\n 'url': './h3/a/@href',\n 'title': './h3/a',\n }\n }\n\n\nclass BaiduSpider(SearchSpider):\n\n name = 'baidu'\n\n conf = {\n 'urls': {\n 'fmt': 'http://www.baidu.com/s?wd={kw}&pn={pg}',\n 'kws': [u'你好', u'世界'],\n 'enc': 'utf-8',\n },\n 'page': {\n 'start': 0,\n 'step': 10,\n 'stop': 100,\n },\n 'loop': '//div[@id=\"content_left\"]/div',\n 'fields': {\n 'url': './h3/a/@href',\n 'title': './h3/a',\n }\n }\n\n def parse(self, response):\n\n for item in super(BaiduSpider, self).parse(response):\n url = item['url'][0]\n res = requests.head(url)\n if res.status_code == 302:\n item['url'] = [res.headers['location']]\n yield item\n\n","sub_path":"webbot/search/spiders/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"29670189","text":"import imaplib\nimport gmail_mailboxes, gmail_messages, gmail_message\nimport datetime as dt\nimport getpass\nimport re\nimport geojson\nimport numpy as np\n\nfrom pymongo import MongoClient\nfrom email.utils import parseaddr\n\nclass gmail_imap:\n\n def __init__ (self, username, password):\n self.imap_server = imaplib.IMAP4_SSL(\"imap.gmail.com\",993)\n self.username = username\n self.password = password\n self.loggedIn = False\n \n self.mailboxes = gmail_mailboxes.gmail_mailboxes(self)\n self.messages = gmail_messages.gmail_messages(self)\n \n def login (self):\n self.imap_server.login(self.username,self.password)\n self.loggedIn = True\n \n def logout(self):\n self.imap_server.close()\n self.imap_server.logout()\n self.loggedIn = False\n\n\nif __name__ == '__main__':\n\n user = 'erddapfish@gmail.com'\n pw = 'erd8apfish'\n gmail = gmail_imap(user, pw)\n \n gmail.mailboxes.load()\n #print gmail.mailboxes\n \n gmail.messages.process(\"INBOX\")\n #print gmail.messages\n \n client = MongoClient()\n client = MongoClient('localhost', 27017) \n db = client['mbari-odss-map'] \n layers = db.layers\n extents = db.extents\n\n #for msg in gmail.messages[0:2]:\n for msg in gmail.messages:\n message = gmail.messages.getMessage(msg.uid) \n mail_from = parseaddr(message.From)\n subject1 = 'datasetID'\n subject2 = 'changed'\n if message.Subject.find(subject1) != -1:\n #print message\n #print message.Body\n if message.date.find('+') != -1:\n dateStr,tz = message.date.split('+') #remove tz identifier\n elif message.date.find('-') != -1:\n dateStr,tz = message.date.split('-') #remove tz identifier\n else:\n dateStr = message.date\n\n mail_date = dt.datetime.strptime(dateStr, \"%a, %d %b %Y %H:%M:%S \") \n elapsed = (dt.datetime.now() - mail_date)\n elapsed_hours = elapsed.seconds/3600 # assuming same timezone...\n\n #if elapsed_hours < 12:\n m = re.match(\".*datasetID=(\\w+).*\",message.Subject)\n if m:\n datasetid = m.group(1)\n\n # found layer with same dataset\n for layer in layers.find({\"download.datasetid\": datasetid}):\n\n olimage = layer['olimage']\n mapfile = olimage['map']\n\n options = layer['options']\n forecastoffsethours = options['forecastoffsethours']\n minlegend = options['minlegend']\n maxlegend = options['maxlegend']\n\n download = layer['download']\n url = download['url']\n dims = download['dims']\n outdir = download['outdir']\n lonwrap = download['lonwrap']\n datatype = download['datatype']\n datasetid = download['datasetid']\n timeformat = download['timeformat']\n\n timeformat = download['timeformat']\n extent_id = download['extent']\n raster = download['raster']\n\n # get extent and calculate ranges for latitude and longitude download\n extent = extents.find_one({\"_id\": extent_id})\n geoJson = geojson.loads(extent[\"geojson\"])\n coordinates = np.array(geoJson[\"coordinates\"])\n points = coordinates[0]\n min = np.amin(points,axis=0)\n max = np.amax(points,axis=0)\n lonmin = min[0]\n latmin = min[1]\n lonmax = max[0]\n latmax = max[1]\n\n\n # if from external NOAA erddap server\n if 'erd.data@noaa.gov' in mail_from:\n # submit condor job for to download\n with open(datasetid + '.dag', 'w') as dagfile:\n dagfile.write('JOB DOWNLOAD download-remotesensing.job \\n')\n dagfile.write('SCRIPT POST DOWNLOAD postscript.sh '+ datasetid +' /ODSS/' + outdir + '\\n')\n vars = 'timeformat=\"%s\" url=\"%s\" datasetid=\"%s\" datatype=\"%s\" outdir=\"%s\" ' \\\n 'dims=\"%s\" lonwrap=\"%s\" lonmin=\"%s\" lonmax=\"%s\" latmin=\"%s\" latmax=\"%s\"' \\\n % (timeformat,url,datasetid,datatype,'/ODSS/'+outdir,dims,lonwrap,lonmin,lonmax,latmin,latmax)\n dagfile.write('VARS DOWNLOAD ' + vars)\n\n\n # if from internal erddap server\n if 'erddapfish@gmail.com' in mail_from:\n # submit condor job for download\n if raster is \"true\":\n dagfile.write('JOB UPDATE_MAP update_map.job\\n')\n dagfile.write('JOB CREATE_UVRASTER create_uvraster.job\\n')\n dagfile.write('SCRIPT POST CREATE_UVRASTER postscript.sh output.tar.gz ' + outdir + '\\n')\n vars = 'timeformat=\"%s\" datasetid=\"%s\" datatype=\"%s\" dims=\"%s\" ' \\\n 'mapfile=\"%s\" forecastoffsethours=\"%s\" minlegend=\"%s\" maxlegend=\"%s\" ' \\\n % (timeformat,url,datasetid,datatype,outdir,dims,lonwrap,lonmin,lonmax,latmin,latmax)\n\n else:\n dagfile.write('JOB UPDATE_MAP update_map.job\\n')\n\n\n\n# search for layer name with similar to erddap notification \n gmail.logout()\n","sub_path":"src/gmail_imap-master/gmail_imap.py","file_name":"gmail_imap.py","file_ext":"py","file_size_in_byte":5428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"146970439","text":"\r\nimport numpy as np\r\nfrom scipy.linalg import solve_triangular\r\nimport csv\r\nfrom joblib import Parallel, delayed\r\nimport time\r\nimport gc\r\nimport os\r\n\r\n\r\n#from os.path import dirname, basename, isfile, join\r\n#import glob\r\n#modules = glob.glob(join(dirname(__file__), \"*.py\"))\r\n#__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]\r\nimport sys \r\n \r\n#print(\"This is the name of the program:\", sys.argv[0])\r\n#print(\"Argument List:\", str(sys.argv))\r\n\r\n#from sys.argv[2] import * \r\n#for i in range(len(sys.argv-1)):from sys.argv[i+1] import *\r\nfrom kryovdiction import *\r\nfrom kryovmultiply import *\r\nfrom kryovlinear_algebra import *\r\nfrom kryovobservable import *\r\n###############input dim#############\r\nNx=10\r\nNy=10\r\n########################\r\nN=Nx*Ny\r\nwritem=False\r\nwriteHk=True\r\nwriteHm=True\r\nwritronsiteMz=False\r\nwriteMz=False\r\nwriteMx=False\r\nwriteCzz17=False\r\nwriteoneforall=False\r\nwriteCzzmid=True\r\n\r\nHm={}\r\nallI=''\r\nfor p in range(N):allI=allI+'I'\r\n\r\n\r\n \r\n \r\n \r\nstart_time = time.time()\r\nwith open('H0m.csv') as csv_file:\r\n reader = csv.reader(csv_file)\r\n read = [(x,float(y)) for (x,y) in reader]\r\n Hm['H0'] = dict(read)\r\nwith open('H1m.csv') as csv_file:\r\n reader = csv.reader(csv_file)\r\n read = [(x,float(y)) for (x,y) in reader]\r\n Hm['H1'] = dict(read)\r\nwith open('H2m.csv') as csv_file:\r\n reader = csv.reader(csv_file)\r\n read = [(x,float(y)) for (x,y) in reader]\r\n Hm['H2'] = dict(read)\r\nwith open('H3m.csv') as csv_file:\r\n reader = csv.reader(csv_file)\r\n read = [(x,float(y)) for (x,y) in reader]\r\n Hm['H3'] = dict(read)\r\nwith open('H4m.csv') as csv_file:\r\n reader = csv.reader(csv_file)\r\n read = [(x,float(y)) for (x,y) in reader]\r\n Hm['H4'] = dict(read)\r\nprint(\"loading Hm--- %s seconds ---\" % (time.time() - start_time))\r\nm=len(Hm)\r\nR={}\r\n#############input R by hand###############################3\r\nR0={'H0':{allI: 1.0},'H1':{},'H2':{allI: 3646.000000000008},'H3':{allI: -10800.0},'H4':{allI: 39183899.379999794}}\r\nR1={'H1':{allI[1:N]+'x': 60.38211655780212},'H2':{allI[1:N]+'x': -178.8609047790075},'H3':{allI[1:N]+'x': 648932.1940626296},'H4':{allI[1:N]+'x': -6284651.5099670775}}\r\nR2={'H2':{allI[1:N]+'y': 5085.134428583784},'H3':{allI[1:N]+'y': -44056.88065405637},'H4':{allI[1:N]+'y':107480748.12699133}}\r\nR3={'H3':{allI[1:N]+'z': 517080.25208282424},'H4':{allI[1:N]+'z': -8729347.961129703}}\r\nR4={'H4':{allI[2:N]+'xI': 59831907.530641586}}\r\n\r\n###############################################################\r\nR['R0']=R0\r\nR['R1']=R1\r\nR['R2']=R2\r\nR['R3']=R3\r\nR['R4']=R4 \r\n'''\r\nfor i in range(m):\r\n# print(Hm['H'+str(i)])\r\n with open('R'+str(i)+'.csv') as csv_file:\r\n reader = csv.reader(csv_file)\r\n read = [(y[3:3+N-1],y[5+N:]) for (x,y) in reader] \r\n #R['R'+str(i)] = \r\n print(dict(read))\r\n'''\r\ngc.collect()\r\n\r\nCm={}\r\nfor E in range(-19,11,2):\r\n Cm[E*0.1]=get_Cm(R,E*0.1*N)\r\n#Et=-5.0\r\n#Cm[Et*0.1]=get_Cm(R,Et*0.1*N)\r\ngc.collect()\r\n # if E ==0:Cm[0.4]=get_Cm(R,0.4*N)\r\n # if E ==1:Cm[-0.2]=get_Cm(R,-0.2*N)\r\n # if E ==2:Cm[-0.8]=get_Cm(R,-0.8*N)\r\n#Cm=get_Cm(R,-22.0)\r\nprint('\\nwriting result in csv\\n')\r\nif(writeMx):\r\n start_time = time.time()\r\n with open('EvsMx.csv', 'w', newline=\"\") as csv_file:\r\n writer = csv.writer(csv_file)\r\n for E,C in Cm.items():\r\n if(writem):\r\n for maxm in range(m-1):writer.writerow([E, Mx(C,Hm,N,maxm+1)])\r\n else:\r\n writer.writerow([E, Mx(C,Hm,N,m-1)])\r\n print(\"for 30 Mx--- %s seconds ---\" % (time.time() - start_time))\r\nif(writeMz):\r\n with open('EvsMz.csv', 'w', newline=\"\") as csv_file:\r\n writer = csv.writer(csv_file)\r\n for E,C in Cm.items():\r\n if(writem):\r\n for maxm in range(m-1):\r\n Mzper,Mzonsite=Mz(C,Hm,N,Nx,Ny,maxm+1)\r\n writer.writerow([E, Mzper])\r\n if(writronsiteMz):np.savetxt(\"MzonsiteE=\"+str(E)+\".csv\", Mzonsite, delimiter=\",\")\r\n else:\r\n Mzper,Mzonsite=Mz(C,Hm,N,Nx,Ny,m-1)\r\n writer.writerow([E, Mzper])\r\n if(writronsiteMz):np.savetxt(\"MzonsiteE=\"+str(E)+\".csv\", Mzonsite, delimiter=\",\")\r\n\r\n \r\n\r\nif(writeCzz17): \r\n start_time = time.time()\r\n with open('EvsCzz.csv', 'w', newline=\"\") as csv_file:\r\n writer = csv.writer(csv_file)\r\n \r\n for E,C in Cm.items():#writer.writerow([E, Czzdr(C,Hm,N,Nx,1)])\r\n if(writem):\r\n for maxm in range(m-1):\r\n for i in range(7):\r\n Czzc,Czz=Czzdr(C,Hm,N,Nx,i+1,maxm+1)\r\n writer.writerow([E, Czzc,Czz])\r\n else:\r\n for i in range(7):\r\n Czzc,Czz=Czzdr(C,Hm,N,Nx,i+1,m-1)\r\n writer.writerow([E, Czzc,Czz])\r\n print(\"for 30 Czz(1)-(7)--- %s seconds ---\" % (time.time() - start_time))\r\nif(writeoneforall): \r\n start_time = time.time()\r\n with open('EvsALLobs.csv', 'w', newline=\"\") as csv_file:\r\n writer = csv.writer(csv_file)\r\n \r\n for E,C in Cm.items():#writer.writerow([E, Czzdr(C,Hm,N,Nx,1)])\r\n if(writem):\r\n for maxm in range(m-1):\r\n for i in range(5):\r\n sumMx,sumMz,sitesxy,sumCzzc,sumCzz=obsoneforall(C,Hm,N,Nx,maxm+1,i)\r\n if(writronsiteMz and i==0):np.savetxt(\"MzonsiteE=\"+str(round(E,1))+\"obs.csv\", sitesxy, delimiter=\",\")\r\n writer.writerow([E,sumMx,sumMz,sumCzzc,sumCzz])\r\n else:\r\n for i in range(5):\r\n sumMx,sumMz,sitesxy,sumCzzc,sumCzz=obsoneforall(C,Hm,N,Nx,m-1,i)\r\n if(writronsiteMz and i==0):np.savetxt(\"MzonsiteE=\"+str(round(E,1))+\"obs.csv\", sitesxy, delimiter=\",\")\r\n writer.writerow([E,sumMx,sumMz,sumCzzc,sumCzz])\r\n gc.collect() \r\n print(\"for 30 Czz(1)-(7)--- %s seconds ---\" % (time.time() - start_time))\r\nif(writeCzzmid): \r\n start_time = time.time()\r\n with open('EvsCzzmide-1.0to0ex-0.5.csv', 'w', newline=\"\") as csv_file:\r\n writer = csv.writer(csv_file)\r\n \r\n for E,C in Cm.items():#writer.writerow([E, Czzdr(C,Hm,N,Nx,1)])\r\n if(writem):\r\n \r\n for maxm in range(m-1):\r\n Czzdrcnp,Czzdrnp=Czzdrmid(C,Hm,N,Nx,maxm+1)\r\n for i in range(len(Czzdrcnp)):\r\n writer.writerow([E,Czzdrcnp[i],Czzdrnp[i]])\r\n # if(writronsiteMz and i==0):np.savetxt(\"MzonsiteE=\"+str(E)+\".csv\", sitesxy, delimiter=\",\")\r\n \r\n else:\r\n Czzdrcnp,Czzdrnp=Czzdrmid(C,Hm,N,Nx,m-1)\r\n for i in range(len(Czzdrcnp)):\r\n writer.writerow([E,Czzdrcnp[i],Czzdrnp[i]])\r\n gc.collect() \r\n print(\"for 30 Czzmid--- %s seconds ---\" % (time.time() - start_time))\r\n#print(Mx(Cm,Hm,N))\r\nprint('\\nresult written in csv\\n')\r\nprint(R)\r\n#print(Mz(Cm,Hm,N))\r\n\r\n","sub_path":"oopexobs.py","file_name":"oopexobs.py","file_ext":"py","file_size_in_byte":6940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"310383309","text":"from .Constants import Ops, Addr\nfrom .Image import Image\nfrom .RTIBlock import RTIBlock\nfrom .Position import Position\n\n\nclass Sequence:\n def __init__(self, bank, index):\n self.bank = bank\n self.index = index\n\n self.repeat = 1\n\n # Add 8 RTI blocks\n self.images = []\n for index in range(8):\n self.images.append(RTIBlock(self, index))\n\n # Empty position list\n self.positions = []\n\n def append_image(self, width, image_filename='', image_data=[], image_bytes=[]):\n image = Image(self, len(self.images), width, image_filename, image_data, image_bytes)\n self.images.append(image)\n self._renumber_images()\n return image\n\n def _renumber_images(self):\n for index in range(len(self.images)):\n self.images[index].index = index\n\n def append_position(self):\n position = Position(self, len(self.positions))\n self.positions.append(position)\n self._renumber_positions()\n return position\n\n def _renumber_positions(self):\n for index in range(len(self.positions)):\n self.positions[index].index = index\n\n def bs(self):\n return self.bank.bs() | self.index\n\n def upload(self, connection):\n print(\"Uploading B{bank}S{sequence}\".format(\n bank=self.bank.index,\n sequence=self.index,\n ))\n self.upload_images(connection)\n self.upload_positions(connection)\n\n def upload_images(self, connection):\n self.bank.zone.target(connection, True)\n\n # Reset the running sum for image checksum\n connection.running_sum = 0\n\n # Upload each image\n offset = Addr.DATA_BASE\n for image in self.images:\n image.upload(connection, offset)\n offset += image.length\n\n print(\"Uploading B{bank}S{sequence}Imd\".format(\n bank=self.bank.index,\n sequence=self.index,\n ))\n # Set the image metadata\n offset = Addr.DATA_BASE\n bs = self.bs()\n for index in range(256):\n if index < len(self.images):\n # Image entry\n image = self.images[index]\n image.upload_metadata(connection)\n offset = image.offset + image.length\n else:\n # No image\n connection.send(Ops.STORE, Addr.IMAGE_BASE + (index * 4), bs,\n [0, 0, offset, 0x00FF]) # FIXME What is 0, and 0xff?\n\n print(\"Uploading B{bank}S{sequence}Ics\".format(\n bank=self.bank.index,\n sequence=self.index,\n ))\n # Save the image checksum\n sum = connection.running_sum\n sum_hi = int((sum & 0xffff0000) >> 16)\n sum_lo = (sum & 0x0000ffff)\n connection.send(Ops.STORE, 0x2003, bs, [sum_hi, sum_lo])\n\n self.bank.zone.target(connection, False)\n\n def upload_positions(self, connection):\n self.bank.zone.target(connection, True)\n\n # Upload each position\n for position in self.positions:\n position.uploadbulk(connection)\n\n # Blank out the next position\n print(\"Uploading B{bank}S{sequence}PX\".format(\n bank=self.bank.index,\n sequence=self.index,\n ))\n bs = self.bs()\n connection.send(Ops.STORE, Addr.POSITION_BASE + (len(self.positions) << 4), bs,\n [0x0000, 0x0100, 0x0000, 0x00FF, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1023, 0x0201, 0x0001, 0x0000, 0x0009])\n\n # Upload each position (additional attributes)\n for position in self.positions:\n position.upload(connection)\n\n # Update sequence parameters\n connection.send(Ops.STORE, 0x2002, bs, [len(self.positions)])\n connection.send(Ops.STORE, 0x2001, bs, [self.repeat - 1])\n\n self.bank.zone.target(connection, False)\n","sub_path":"pyBallLib/Sequence.py","file_name":"Sequence.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"625421618","text":"# mypy: ignore-errors\nfrom typing import List, Optional\n\n\ndef two_sum(nums: List, target: int) -> Optional[List[int]]:\n seen = {}\n for i, num in enumerate(nums):\n typo\n complement = target - num\n if complement in seen:\n return [seen[complement], i]\n seen[num] = i\n return None\n","sub_path":"tests/challenges/debug_code/data/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"101904421","text":"import urllib.request, urllib.parse, urllib.error\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nRESOURCE_PATH = 'resources'\n\n\ndef download_data():\n \"\"\"download MIT-BIH data file from website and save to resources\n\n \"\"\"\n if not os.path.exists(RESOURCE_PATH):\n os.mkdir(RESOURCE_PATH)\n\n base_url = 'https://www.physionet.org/physiobank/database/mitdb/'\n suffix = ['.dat', '.atr', '.hea']\n\n for i in range(100, 235):\n try:\n # urls = list(map(lambda s: urllib.parse.urljoin(base_url, str(i) + s), suffix))\n # files = list(map(lambda s: os.path.join(RESOURCE_PATH, str(i) + s), suffix))\n urls = [urllib.parse.urljoin(base_url, str(i) + s) for s in suffix]\n files = [os.path.join(RESOURCE_PATH, str(i) + s) for s in suffix]\n for url, file in zip(urls, files):\n urllib.request.urlretrieve(url, file)\n print('download ', file)\n except urllib.error.HTTPError:\n pass\n\n print('finished')\n\n\ndef read_data(display=False):\n if not os.path.exists(RESOURCE_PATH):\n print('please download the data file first')\n files = os.listdir(RESOURCE_PATH)\n if len(files) == 0:\n print('please download the data file first')\n return\n\n\ndef read_one_set(number, display=False):\n atr_file = os.path.join(RESOURCE_PATH, str(number) + '.atr')\n data_file = os.path.join(RESOURCE_PATH, str(number) + '.dat')\n head_file = os.path.join(RESOURCE_PATH, str(number) + '.hea')\n\n if not os.path.exists(atr_file):\n print('file is not found !')\n return\n\n with open(head_file, 'rb') as f:\n head = f.readline().split()\n num_signal, sample_freq, signal_len = int(head[1]), int(head[2]), int(head[3])\n\n data_format, gain, bit_resolution, zero_value, first_value = [], [], [], [], []\n for _ in range(num_signal):\n record = f.readline().split()\n data_format.append(int(record[1]))\n gain.append(int(record[2]))\n bit_resolution.append(int(record[3]))\n zero_value.append(int(record[4]))\n first_value.append(int(record[5]))\n\n with open(data_file, 'rb') as f:\n data = f.read()\n\n data = np.frombuffer(data, np.uint8)\n data = np.reshape(data, [-1, 3])\n\n M1H = data[:, 1] >> 4\n M2H = data[:, 1] & 15\n\n signal = np.zeros([signal_len, 2])\n\n signal[:, 0] = data[:, 0] + M1H * (2 ** 8)\n signal[:, 1] = data[:, 2] + M2H * (2 ** 8)\n\n with open(atr_file, 'rb') as f:\n atr_record = f.read()\n\n atr_record = np.frombuffer(atr_record, np.uint8)\n atr_record = np.array(atr_record, np.uint32) # trans to unsigned int32\n atr_record = np.reshape(atr_record, [-1, 2])\n\n annotation, atr_time = [], []\n\n i = 0\n while i < atr_record.shape[0]:\n a = atr_record[i, 1] >> 2\n if a == 59:\n annotation.append(atr_record[i + 3, 1] >> 2)\n atr_time.append(\n atr_record[i+2, 0] + atr_record[i+2, 1] << 8 + atr_record[i+1, 0] << 16 + atr_record[i+1, 1] << 24)\n elif a == 60:\n pass\n elif a == 61:\n pass\n elif a == 62:\n pass\n elif a == 63:\n supplement = (atr_record[i, 1] & 3 << 8 + atr_record[i, 0])\n supplement = supplement + supplement % 2\n i = i + int(supplement / 2)\n else:\n annotation.append(a)\n atr_time.append(atr_record[i, 1] & 3 << 8 + atr_record[i, 0])\n i = i + 1\n\n atr_time = np.array(atr_time)\n atr_time = np.cumsum(atr_time) / sample_freq\n\n signal[:, 0] = signal[:, 0] - zero_value[0]\n signal[:, 1] = signal[:, 1] - zero_value[1]\n if num_signal == 2:\n signal[:, 0] = signal[:, 0] / gain[0]\n signal[:, 1] = signal[:, 1] / gain[1]\n else:\n signal = np.reshape(signal, -1)\n signal = signal / gain[0]\n\n if display:\n if num_signal == 2:\n time = np.linspace(0, signal_len-1, signal_len) / sample_freq\n plt.plot(time[:1000], signal[0:1000, 0])\n plt.plot(time[:1000], signal[0:1000, 1])\n plt.xlabel('time / seconds')\n plt.ylabel('voltage / mV')\n plt.title(str(number) + \".data\")\n plt.show()\n else:\n time = np.linspace(0, 2*signal_len-1, signal_len) / sample_freq\n plt.plot(time, signal)\n plt.show()\n\n return signal, annotation, atr_time\n\n\nif __name__ == \"__main__\":\n read_one_set(117, True)\n","sub_path":"arrhythmias/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"343065722","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport torch.optim as optim\nfrom ens_utils import *\nfrom purchase import purchase\nfrom estgrad import estgrad\nimport torchvision.transforms as transforms\n\ndef _entr_comp(prediction):\n entr = 0\n for num in prediction:\n if num != 0:\n entr += -1*num*np.log(num)\n return entr\n \ndef _m_entr_comp(prediction, label):\n entr = 0\n for i in range(len(prediction)):\n p = prediction[i]\n if i==label:\n if p==0:\n entr += -1*1*np.log(1e-30)\n else:\n entr += -1*(1-p)*np.log(p)\n else:\n if p==1:\n entr += -1*1*np.log(1e-30)\n else:\n entr += -1*p*np.log(1-p)\n return entr\n\ndef _thre_setting(tr_values, te_values):\n value_list = np.concatenate((tr_values, te_values))\n thre, max_acc = 0, 0\n for value in value_list:\n tr_ratio = np.sum(tr_values>=value)/(len(tr_values)+0.0)\n te_ratio = np.sum(te_values max_acc:\n thre, max_acc = value, acc\n return thre\n\ndef _mem_inf_thre(num_classes, s_tr_values, s_te_values, t_tr_values, t_te_values, s_tr_labels,\n s_te_labels, t_tr_labels, t_te_labels):\n # perform membership inference attack by thresholding feature values: the feature can be prediction confidence,\n # (negative) prediction entropy, and (negative) modified entropy\n predicted = torch.ones(9866)\n thresholds = np.zeros(100)\n for num in range(num_classes):\n thre = _thre_setting(s_tr_values[s_tr_labels==num], s_te_values[s_te_labels==num])\n thresholds[num] = thre\n\n for i in range(0,4933):\n if(t_tr_values[i]>=thresholds[t_tr_labels[i]]):\n predicted[i] = 0\n for i in range(0,4933):\n if(t_te_values[i]>=thresholds[t_te_labels[i]]):\n predicted[4933+i] = 0\n return predicted\n\n# load pretrained model\ntarget = purchase(num_classes=100)\ncheckpoint = torch.load('purchase_advreg')\nstate_dict = checkpoint['state_dict']\n\nfrom collections import OrderedDict\nnew_state_dict = OrderedDict()\n\nfor k, v in state_dict.items():\n if 'module' not in k:\n k = k\n else:\n k = k.replace('module.', '')\n new_state_dict[k] = v\n\ntarget.load_state_dict(new_state_dict)\ntarget.eval()\n\n# set criterion\ncriterion = nn.CrossEntropyLoss()\n\ntrain_size = 9866\nsplit_size = int(train_size/2)\nval_size = split_size\ntest_size = split_size\n\n#load in data\natt_train_train, att_train_test, target_train, target_test = prepare_purchase_data(100)\ntorch.manual_seed(42)\natt_val_train, att_test_train = torch.utils.data.random_split(target_train, [split_size, split_size])\ntorch.manual_seed(torch.initial_seed())\natt_val_test, att_test_test = torch.utils.data.random_split(target_test, [split_size, split_size])\n\natt_train_train_loader = torch.utils.data.DataLoader(att_train_train, batch_size=50, shuffle=True, num_workers=2)\natt_train_test_loader = torch.utils.data.DataLoader(att_train_test, batch_size=50, shuffle=True, num_workers=2)\natt_val_train_loader = torch.utils.data.DataLoader(att_val_train, batch_size=50, shuffle=False, num_workers=2)\natt_val_test_loader = torch.utils.data.DataLoader(att_val_test, batch_size=50, shuffle=False, num_workers=2)\natt_test_train_loader = torch.utils.data.DataLoader(att_test_train, batch_size=test_size, shuffle=True, num_workers=2)\natt_test_test_loader = torch.utils.data.DataLoader(att_test_test, batch_size=test_size, shuffle=True, num_workers=2)\n\n# prepare test data\nfor data in att_test_train_loader:\n att_test_train_data, att_test_train_target = data\nfor data in att_test_test_loader:\n att_test_test_data, att_test_test_target = data\natt_test_data = torch.cat((att_test_train_data, att_test_test_data))\natt_test_target = torch.cat((att_test_train_target, att_test_test_target))\n\n# make targets \natt_test_label = torch.ones(2*test_size, dtype = torch.int64)\nfor i in range(0,test_size):\n att_test_label[i] = 0\n\nprint(\"Loading Test Data\")\natt_test_dataloader = estgrad(target, criterion, att_test_train_loader, att_test_test_loader, test_size, 256, './advreg_test.t', True, False)\nprint(\"Data has been loaded\")\n\nattack = purchase(num_classes = 2)\n\n# load best model\nPATH = './attack_net_advreg5.pth'\nattack.load_state_dict(torch.load(PATH))\n\nattack.eval()\n\n# get prediction of gradient\ncorrect = 0\ntotal = 0\npredicted_grad = torch.zeros(0, dtype = torch.int64)\nwith torch.no_grad():\n for data in att_test_dataloader:\n images, labels = data\n outputs = attack(images.float())\n _, pred = torch.max(outputs.data, 1)\n predicted_grad = torch.cat((predicted_grad, pred))\n total += labels.size(0)\n correct += (pred == labels).sum().item()\n \nprint('Accuracy of the network on the test images using gradients of inputs: {acc:.3f}'.format(acc=100*correct/total))\n\n#get prediction of correctness\ntest_size = 2*test_size\npredicted_corr = torch.ones(test_size)\ncorrect = 0\nfor i in range(0, test_size):\n target.zero_grad()\n input = att_test_data[[i]]\n output = target(input.float())\n _, predicted = torch.max(output.data, 1)\n label = att_test_target[[i]]\n if(predicted == label):\n predicted_corr[i] = 0\n\nfor i in range(0,test_size):\n if(predicted_corr[i] == att_test_label[i]):\n correct +=1\n\nprint('Accuracy of the network on the test images using correctness: {acc:.3f}'.format(acc=100*correct/total))\n\n# create blackbox_attacks variables\nshadow_train_performance,shadow_test_performance,target_train_performance,target_test_performance = \\\n prepare_model_performance(target, att_train_train_loader, att_train_test_loader, \n target, att_test_train_loader, att_test_test_loader)\n\nnum_classes = 100\n \ns_tr_outputs, s_tr_labels = shadow_train_performance\ns_te_outputs, s_te_labels = shadow_test_performance\nt_tr_outputs, t_tr_labels = target_train_performance\nt_te_outputs, t_te_labels = target_test_performance\n\ns_tr_conf = np.array([s_tr_outputs[i, s_tr_labels[i]] for i in range(len(s_tr_labels))])\ns_te_conf = np.array([s_te_outputs[i, s_te_labels[i]] for i in range(len(s_te_labels))])\nt_tr_conf = np.array([t_tr_outputs[i, t_tr_labels[i]] for i in range(len(t_tr_labels))])\nt_te_conf = np.array([t_te_outputs[i, t_te_labels[i]] for i in range(len(t_te_labels))])\n\ns_tr_entr = np.array([_entr_comp(s_tr_outputs[i]) for i in range(len(s_tr_labels))])\ns_te_entr = np.array([_entr_comp(s_te_outputs[i]) for i in range(len(s_te_labels))])\nt_tr_entr = np.array([_entr_comp(t_tr_outputs[i]) for i in range(len(t_tr_labels))])\nt_te_entr = np.array([_entr_comp(t_te_outputs[i]) for i in range(len(t_te_labels))])\n\ns_tr_m_entr = np.array([_m_entr_comp(s_tr_outputs[i], s_tr_labels[i]) for i in range(len(s_tr_labels))])\ns_te_m_entr = np.array([_m_entr_comp(s_te_outputs[i], s_te_labels[i]) for i in range(len(s_te_labels))])\nt_tr_m_entr = np.array([_m_entr_comp(t_tr_outputs[i], t_tr_labels[i]) for i in range(len(t_tr_labels))])\nt_te_m_entr = np.array([_m_entr_comp(t_te_outputs[i], t_te_labels[i]) for i in range(len(t_te_labels))])\n\n# get prediction of confidence\npredicted_conf = _mem_inf_thre(num_classes, s_tr_conf, s_te_conf, t_tr_conf, t_te_conf, s_tr_labels,\n s_te_labels, t_tr_labels, t_te_labels)\ncorrect = 0\nfor i in range(0,test_size):\n if(predicted_conf[i] == att_test_label[i]):\n correct +=1\n\nprint('Accuracy of the network on the test images using confidence: {acc:.3f}'.format(acc=100*correct/total))\n\n# get prediction of entropy\npredicted_entr = _mem_inf_thre(num_classes, -s_tr_entr, -s_te_entr, -t_tr_entr, -t_te_entr, s_tr_labels,\n s_te_labels, t_tr_labels, t_te_labels)\ncorrect = 0\nfor i in range(0,test_size):\n if(predicted_entr[i] == att_test_label[i]):\n correct +=1\n\nprint('Accuracy of the network on the test images using entropy: {acc:.3f}'.format(acc=100*correct/total))\n\n# get prediction of modified entropy\npredicted_m_entr = _mem_inf_thre(num_classes, -s_tr_m_entr, -s_te_m_entr, -t_tr_m_entr, -t_te_m_entr, s_tr_labels,\n s_te_labels, t_tr_labels, t_te_labels)\ncorrect = 0\nfor i in range(0,test_size):\n if(predicted_m_entr[i] == att_test_label[i]):\n correct +=1\n\nprint('Accuracy of the network on the test images using modified entropy: {acc:.3f}'.format(acc=100*correct/total))\n\npredicted_ens = torch.zeros(test_size)\nfor i in range(0,test_size):\n ens = predicted_grad[i] + predicted_corr[i] + predicted_conf[i] + predicted_entr[i] + predicted_m_entr[i]\n if(ens >= 3):\n predicted_ens[i] = 1\n\ncorrect = 0\nfor i in range(0,test_size):\n if(predicted_ens[i] == att_test_label[i]):\n correct +=1\n\nprint('Accuracy of the network on the test images using ensemble: {acc:.3f}'.format(acc=100*correct/total))\n","sub_path":"Purchase100/Purchase100Ensemble.py","file_name":"Purchase100Ensemble.py","file_ext":"py","file_size_in_byte":8978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"314139591","text":"from django.urls import path\n#from .views import exp\nfrom . import views\nurlpatterns = [\npath('exp/',views.exp, name='exp') ,\npath('upload/',views.upload, name='upload') ,\npath('list/',views.book_list, name='book_list') ,\npath('uploadbook/',views.upload_book, name='upload_book') ,\n\n\n\n]\n","sub_path":"myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"132381860","text":"#!/usr/bin/python3\n# encoding: utf-8\n\n\"\"\"\n@author: chsh\n@file: scores.py\n@time: 2020/6/15 17:33\n@title:\n@content: 各棋子的价值以及棋子位置的价值得分\n\"\"\"\nclass Scores():\n '''\n 得分规则:\n 1、吃棋得分为千位分数;\n 2、棋子自身价值为百位分数;\n 3、打开特殊棋子位置得分为十位分数(50,60,70,80);\n 4、打开一个棋子得分为10分;\n 5、替换位得分为个位得分,是棋子自身价值得分/10000而来,便于区分打开棋子或移动棋子的不同得分来判断棋子的优先级;\n '''\n @staticmethod\n def piece_score(piece_name):\n # 棋子的自身价值得分为百位分数\n piece_score_dict = {\n 'jiang': 900,\n 'shi': 800,\n 'xiang': 700,\n 'ma': 400,\n 'ju': 300,\n 'pao': 600,\n 'zu': 500,\n 'zu_no_jiang': 200,\n }\n return piece_score_dict[piece_name]\n\n @staticmethod\n def eat_score(key):\n # 吃棋得分为千位分数\n eat_score_dict = {\n 'jiang_jiang': 1000,\n 'zu_jiang': 9000,\n 'pao_jiang': 9000,\n 'shi_shi': 1000,\n 'jiang_shi': 8000,\n 'pao_shi': 8000,\n 'xiang_xiang': 1000,\n 'jiang_xiang': 7000,\n 'shi_xiang': 7000,\n 'pao_xiang': 7000,\n 'ma_ma': 1000,\n 'jiang_ma': 4000,\n 'shi_ma': 4000,\n 'xiang_ma': 4000,\n 'pao_ma': 4000,\n 'ju_ju': 1000,\n 'jiang_ju': 3000,\n 'shi_ju': 3000,\n 'xiang_ju': 3000,\n 'ma_ju': 3000,\n 'pao_ju': 3000,\n 'pao_pao': 6000,\n 'shi_pao': 6000,\n 'xiang_pao': 6000,\n 'ma_pao': 6000,\n 'ju_pao': 6000,\n 'zu_zu': 5000,\n 'shi_zu': 5000,\n 'xiang_zu': 5000,\n 'ma_zu': 5000,\n 'ju_zu': 5000,\n 'pao_zu': 5000,\n 'zu_zu_no_jiang': 2000,\n 'shi_zu_no_jiang': 2000,\n 'xiang_zu_no_jiang': 2000,\n 'ma_zu_no_jiang': 2000,\n 'ju_zu_no_jiang': 2000,\n 'pao_zu_no_jiang': 2000,\n }\n return eat_score_dict[key]\n\n @staticmethod\n def other_pieces_score(key):\n # 棋盘特殊棋子位置得分十位分数\n other_score_dict = {\n 'zu_ju': 20,\n 'zu_pao': 22,\n 'pao_jiang': 23,\n 'pao_ju': 21\n }\n return other_score_dict[key]\n\n","sub_path":"ChineseChess/algorithm/scores.py","file_name":"scores.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"414592308","text":"import sys\r\nfrom PyQt4 import QtGui, QtCore\r\nimport pyqtgraph as pq\r\nfrom kernel import kernel\r\nimport scipy as sp\r\n\r\nclass UI(QtGui.QWidget):\r\n\r\n def __init__(self, camp_dist):\r\n pq.setConfigOption('background', 'w')\r\n self.widget = pq.PlotWidget()\r\n self.kernel = kernel('../data/csv/out.csv', camp_dist)\r\n self.kernel.pars()\r\n super(UI, self).__init__()\r\n self.initUI()\r\n\r\n def initUI(self):\r\n\r\n \"\"\"cb = QtGui.QCheckBox('Show title', self)\r\n cb.move(20, 20)\r\n cb.toggle()\r\n cb.stateChanged.connect(self.changeTitle)\"\"\"\r\n\r\n #x = np.random.normal(size=1000)\r\n x = [1, 2, 423, 234 ,52]\r\n button1 = QtGui.QPushButton('Open file', self)\r\n button1.resize(70, 40)\r\n button1.clicked.connect(self.choseFile)\r\n\r\n button2 = QtGui.QPushButton('Create chart', self)\r\n button2.resize(70, 40)\r\n button2.move(0, 50)\r\n button2.clicked.connect(self.createChart)\r\n\r\n self.setGeometry(30, 30, 790, 720)\r\n self.setWindowTitle('valentines mum stupid cunt')\r\n self.show()\r\n\r\n def choseFile(self):\r\n\r\n arr = QtGui.QFileDialog.getOpenFileName(self)\r\n file = open(arr, 'r')\r\n self.full_data = file.read()\r\n file.close()\r\n\r\n def createChart(self):\r\n data = self.kernel.comput_first()\r\n self.widget.plotItem.plot(data, symbol='o')\r\n self.widget.resize(700, 700)\r\n self.widget.move(80, 10)\r\n self.widget.show()\r\n\r\n\r\n\r\ndef main(camp_dist):\r\n app = QtGui.QApplication(sys.argv)\r\n ex = UI(camp_dist)\r\n sys.exit(app.exec_())\r\n\r\nif __name__ == '__main__':\r\n camp_dist = sp.genfromtxt('../data/camp_dist.tsv', delimiter='\\t')\r\n main(camp_dist)\r\n","sub_path":"scripts/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"478217427","text":"import os\nimport glob\nimport numpy\nimport random\nimport string\nimport utils.kernel_module as kernel_module\nfrom utils.serializer import DillSerializer\nfrom send_light.send_light_user import LightSender\nfrom localvlc.testbed_setting import Testbed\n\nsender = False\n\ndef bit_error_ratio(result, template):\n byte_diff = 0\n result = \"\".join(result.split())\n template = \"\".join(template.split())\n for char1, char2 in zip(result, template):\n if char1 != char2:\n byte_diff += 1\n data_len = min(len(result), len(template))\n return byte_diff / data_len\n\ndef main():\n if sender:\n kernel_module.remove(kernel_module.SEND_KERNEL_MODULE)\n __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n data_len = 5 # 5, 10, 50, 100, 150, 200, 300, 400, 500, 700, 900, 1024\n led = Testbed.Pervasive_LED\n path = os.path.join(__location__, \"..\", \"..\", \"localvlc\", \"results\", \n \"error_data_len\", led.get_name(), \"groundtruth_data_len_\" + str(data_len))\n test_string = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(data_len))\n light_sender = LightSender()\n light_sender.set_data(test_string)\n light_sender.set_time_base_unit(led.get_time_base_unit())\n light_sender.start()\n serializer = DillSerializer(path)\n serializer.serialize(test_string)\n else:\n leds = [\"directed_led\", \"pervasive_led\"]\n base_path = \"../results/error_data_len/\"\n for led in leds:\n print(\"led: \", led)\n path_groundtruth = os.path.join(base_path, led, \"groundtruth_data_len_*\")\n for path_groundtruth in glob.glob(path_groundtruth):\n data_len = path_groundtruth.split(\"_\")[-1]\n path_raw_data = os.path.join(base_path, led, \"data_len_\" + data_len)\n groundtruth = DillSerializer(path_groundtruth).deserialize()\n raw_data = DillSerializer(path_raw_data).deserialize().raw_data\n count = 0\n result = list()\n for series in raw_data:\n for msg in series:\n count += 1 \n result.append(bit_error_ratio(msg, groundtruth))\n print(\"data len: \", len(groundtruth))\n print(\"count: \", count)\n #print(\"groundtruth: \", groundtruth)\n #print(\"raw data: \", raw_data[0][0])\n print(\"bit error ratio: \", numpy.mean(result))\n print(\"max bit error ratio: \", numpy.max(result))\n print(\"---\")\n print(\"###\")\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"light-communication-signaling/src/localvlc/performance/error_rate_data_len.py","file_name":"error_rate_data_len.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"509191260","text":"import time\r\nimport json\r\nimport ssl\r\nimport urllib.request\r\nimport sys\r\nimport psutil\r\nfrom pypresence import exceptions as pypresenceException\r\nfrom pypresence import Presence\r\nimport pymem\r\nimport gameinfo\r\nfrom logs import logger\r\n\r\nSSLCONTEXT = ssl.create_default_context()\r\nSSLCONTEXT.check_hostname = False\r\nSSLCONTEXT.verify_mode = ssl.CERT_NONE\r\n\r\nCLIENT_ID = '699358451494682714'\r\nRPC = Presence(CLIENT_ID)\r\n\r\njoin_button = True\r\n\r\ndef clear_rpc(rpc_pid):\r\n '''for two exceptions in update_presence() to keep code a bit cleaner'''\r\n\r\n logger.info(\"Process was closed. Clearing presence.\")\r\n try:\r\n RPC.clear(pid=rpc_pid)\r\n except AttributeError:\r\n pass\r\n return\r\n\r\n\r\ndef fetch_data(cmdline_again, keys):\r\n global join_button\r\n join_button = True\r\n identifier = cmdline_again.strip('/')\r\n\r\n lhostmatch = identifier.find(\"aos://16777343\")\r\n\r\n if lhostmatch != -1 and keys[0] == 'name':\r\n # If player plays on localhost then just pass this info and done\r\n join_button = False\r\n return ['(Playing on localhost)', '-', '-', '-', '-', '-']\r\n else:\r\n try:\r\n # Request json serverlist that buildandshoot hosts.\r\n request = urllib.request.urlopen(\"https://services.buildandshoot.com/serverlist.json\", context=SSLCONTEXT)\r\n except urllib.error.URLError:\r\n logger.warning('No internet connection.')\r\n time.sleep(5)\r\n return\r\n\r\n data = request.read()\r\n encoding = request.info().get_content_charset('utf-8')\r\n serverlist = json.loads(data.decode(encoding))\r\n\r\n try:\r\n for server_num in range(0, len(serverlist)+1):\r\n presence_info = []\r\n\r\n if serverlist[server_num]['identifier'] == identifier:\r\n current_server = serverlist[server_num]\r\n for variable in keys:\r\n presence_info.append(current_server[variable])\r\n\r\n if len(presence_info) == 6:\r\n return presence_info\r\n except IndexError:\r\n join_button = False\r\n return ['(Server is not broadcasting to master server)', '-', '-', '-', '-', '-']\r\n\r\ndef update_presence(pid, cmdline, p_handle):\r\n playtime_start = time.time()\r\n current_map = None\r\n\r\n logger.info('Process found. Starting presence.')\r\n\r\n while pid is not None:\r\n # Check if the process still exists. If not, then go back to process searching.\r\n if psutil.pid_exists(pid) is False:\r\n logger.info('Process was closed. Clearing presence.')\r\n RPC.clear(pid=pid)\r\n return\r\n\r\n try:\r\n logger.debug('Getting base address.')\r\n base_addr = p_handle.process_base.lpBaseOfDll\r\n except pymem.exception.ProcessNotFound:\r\n clear_rpc(pid)\r\n except pymem.exception.ProcessError:\r\n clear_rpc(pid)\r\n\r\n logger.debug('Fetching server data')\r\n server_info = fetch_data(cmdline, ['name', 'map', 'game_mode', 'players_current', 'players_max', 'game_version'])\r\n\r\n server_name = server_info[0]\r\n server_map = server_info[1]\r\n server_game_mode = server_info[2]\r\n server_players_current = server_info[3]\r\n server_players_max = server_info[4]\r\n server_game_version = server_info[5]\r\n\r\n if server_map != current_map:\r\n # reset the \"time elapsed\" when map changes\r\n playtime_start = time.time()\r\n logger.debug(\"Map changed. Resetting \\\"time elapsed\\\".\")\r\n current_map = server_map\r\n\r\n logger.info('Updating presence.')\r\n\r\n try:\r\n player_status = gameinfo.update(pid=pid, version=server_game_version, proc_handle=p_handle, base_address=base_addr)\r\n\r\n if player_status[0][0] != 'ace_of_spades':\r\n s_image = 'ace_of_spades'\r\n s_additional_text = ''\r\n\r\n if server_game_mode in ('tow', 'tc'):\r\n pass\r\n elif player_status[1]: # if holds_intel from gameinfo.update() is true\r\n s_image = 'smallimagekey_intel'\r\n s_additional_text = 'Holds enemy intel!'\r\n\r\n s_text = '{} Players: {}/{}, Version: {}'.format(s_additional_text,\r\n server_players_current,\r\n server_players_max,\r\n server_game_version)\r\n else:\r\n s_image = None\r\n s_text = None\r\n\r\n logger.debug(RPC.update(pid=pid,\r\n details=server_name,\r\n state='Map: {} ({})'.format(server_map, server_game_mode),\r\n start=playtime_start,\r\n large_image=player_status[0][0],\r\n large_text=player_status[0][1],\r\n small_image=s_image,\r\n small_text=s_text,\r\n buttons = [{\"label\": \"Join\", \"url\": cmdline}, {\"label\": \"Server list\", \"url\": \"http://aos.acornserver.com\"}] if join_button else None ))\r\n except pypresenceException.InvalidID:\r\n logger.warning('Discord is not running, or client ID isn\\'t valid.')\r\n RPC.clear(pid=pid)\r\n RPC.close()\r\n connect_discord()\r\n except pymem.exception.CouldNotOpenProcess:\r\n logger.info('Could not open process.')\r\n RPC.clear(pid=pid)\r\n return\r\n except pypresenceException.ServerError as e:\r\n logger.warning('Button load fail {}'.format(e.with_traceback()))\r\n RPC.clear(pid=pid)\r\n return\r\n\r\n time.sleep(7.5)\r\n\r\ndef scan_for_process():\r\n logger.info('Waiting for aos client.')\r\n\r\n ps_pid = None\r\n ps_cmdline = None\r\n\r\n while True:\r\n # Iterate thru processes to find one that matches our wanted one\r\n # and assign important variables for further functions that will be executed\r\n for proc in psutil.process_iter(['name', 'pid', 'cmdline']):\r\n if proc.info['name'] == 'client.exe':\r\n ps_pid = proc.info['pid']\r\n\r\n try:\r\n ps_cmdline = proc.info['cmdline'][1] # This is the server identifier \"aos://XXXXXXXXXX:XXXXX\"\r\n\r\n handle = pymem.Pymem('client.exe')\r\n if handle.process_id != ps_pid:\r\n logger.info(\"Not a valid aos process.\")\r\n return\r\n \r\n except IndexError:\r\n break\r\n except pymem.exception.ProcessNotFound:\r\n break\r\n except pymem.exception.CouldNotOpenProcess:\r\n break\r\n\r\n update_presence(ps_pid, ps_cmdline, handle)\r\n else:\r\n time.sleep(0.05)\r\n\r\ndef connect_discord():\r\n logger.info('Waiting for discord')\r\n while True:\r\n try:\r\n RPC.connect()\r\n logger.info('Connected to Discord.')\r\n scan_for_process()\r\n except pypresenceException.DiscordNotFound:\r\n time.sleep(3)\r\n except pypresenceException.InvalidID:\r\n logger.info('Discord is not running, or client ID isn\\'t valid.')\r\n time.sleep(3)\r\n except pypresenceException.InvalidPipe:\r\n time.sleep(3)\r\n except pypresenceException.PipeClosed:\r\n time.sleep(3)\r\n\r\nif __name__ == \"__main__\":\r\n try:\r\n connect_discord()\r\n except KeyboardInterrupt:\r\n logger.warning('KeyboardInterrupt caught. Closing.')\r\n sys.exit(0)\r\n","sub_path":"rpc.py","file_name":"rpc.py","file_ext":"py","file_size_in_byte":7893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"203634733","text":"\"\"\"This module contains the RandomShootingStrategy class definition.\n\n\"\"\"\n\nfrom copy import deepcopy\n\nimport numpy as np\n\nfrom rsbackend.common.enums import ShipState, ShootingMode, SquareState\nfrom rsbackend.common.shooting_strategy_base import ShootingStrategyBase\n\n\nclass RandomShootingStrategy(ShootingStrategyBase):\n\n \"\"\"A concrete implementation of the ShootingStrategyBase class.\n\n \"\"\"\n def shoot(self, opponent_grid):\n # work with a copy of the opponent's grid and fetch the remaining ships\n opponent_grid_copy = deepcopy(opponent_grid)\n remaining_ships = super(RandomShootingStrategy, self).\\\n _filter_opponent_grid(opponent_grid_copy)\n # consider every square at which any of the remaining ships may be\n # positioned\n non_hit_squares_coordinates = (\n opponent_grid_copy.get_non_hit_squares_coordinates(remaining_ships)\n )\n\n # shuffle the list and pick a random square as a target\n np.random.shuffle(non_hit_squares_coordinates)\n\n random_square_coordinates = (\n np.random.choice(non_hit_squares_coordinates)\n )\n target_square = opponent_grid.squares.item(\n (random_square_coordinates.x, random_square_coordinates.y)\n )\n target_square.square_state = SquareState.hit\n\n owner = target_square.owner\n\n # check whether the shot was successful or not\n if owner is not None:\n # adjust the ship's state and decrement its remaining squares\n owner.ship_state = ShipState.damaged\n owner.remaining_squares -= 1\n # fill the shooting context with relevant information (moving on to\n # the explorative mode)\n self._shooting_context.current_hit_square = target_square\n self._shooting_context.shooting_mode = ShootingMode.explorative\n","sub_path":"rsbackend/core/strategies/random_shooting_strategy.py","file_name":"random_shooting_strategy.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"187481147","text":"import sys\n\nimport mock\nimport pytest\n\nfrom rotest.cli.main import main\n\n\n@mock.patch(\"rotest.cli.server.ResourceManagerServer\")\ndef test_using_default_port(resource_manager, capsys):\n sys.argv = [\"rotest\", \"server\"]\n main()\n\n resource_manager.assert_called_once_with(port=7777)\n out, _ = capsys.readouterr()\n assert \"Running in attached mode\" in out\n\n\n@mock.patch(\"rotest.cli.server.ResourceManagerServer\",\n mock.MagicMock())\n@mock.patch(\"subprocess.Popen\")\ndef test_running_django_server(popen, capsys):\n sys.argv = [\"rotest\", \"server\"]\n main()\n\n popen.assert_called_once_with([\"django-admin\",\n \"runserver\",\n \"0.0.0.0:8000\"])\n\n out, _ = capsys.readouterr()\n assert \"Running the Django server as well\" in out\n\n\n@mock.patch(\"rotest.cli.server.ResourceManagerServer\")\ndef test_using_custom_port(resource_manager, capsys):\n sys.argv = [\"rotest\", \"server\", \"--port\", \"8888\"]\n main()\n\n resource_manager.assert_called_once_with(port=8888)\n\n out, _ = capsys.readouterr()\n assert \"Running in attached mode\" in out\n\n\n@mock.patch(\"rotest.cli.server.ResourceManagerServer\",\n mock.MagicMock())\n@mock.patch(\"subprocess.Popen\")\ndef test_not_running_django_server(popen, capsys):\n sys.argv = [\"rotest\", \"server\", \"--no-django\"]\n main()\n\n popen.assert_not_called()\n\n out, _ = capsys.readouterr()\n assert \"Running the Django server as well\" not in out\n\n\n@pytest.mark.skipif(sys.platform == \"win32\",\n reason=\"Daemon mode isn't implemented in Windows\")\n@mock.patch(\"daemon.DaemonContext\")\n@mock.patch(\"rotest.cli.server.ResourceManagerServer\")\ndef test_using_daemon_mode(resource_manager, daemon_context, capsys):\n sys.argv = [\"rotest\", \"server\", \"--daemon\"]\n main()\n\n resource_manager.assert_called_once_with(port=7777)\n daemon_context.assert_called_once()\n\n out, _ = capsys.readouterr()\n assert \"Running in detached mode (as daemon)\" in out\n\n\n@pytest.mark.skipif(sys.platform != \"win32\",\n reason=\"Windows only behaviour\")\n@mock.patch(\"rotest.cli.server.ResourceManagerServer\")\ndef test_raising_on_windows_when_user_tries_daemon_mode(resource_manager):\n sys.argv = [\"rotest\", \"server\", \"--daemon\"]\n with pytest.raises(RuntimeError,\n match=\"Cannot run as daemon on Windows\"):\n main()\n\n resource_manager.assert_not_called()\n","sub_path":"tests/cli/test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"360015156","text":"# 764. Largest Plus Sign\n# 2021/09/09\n\n# Runtime: 5173 ms, faster than 17.65% of Python3 online submissions for Largest Plus Sign.\n# # Memory Usage: 32.5 MB, less than 38.75% of Python3 online submissions for Largest Plus Sign.\n\n# 动态规划,前缀和解法。比较暴力。O(n* n)\n# 刚开始没啥思路,后面看了tag是动态规划,就大概知道怎么做了。\n# 将每个结点上/下/左/右四个方向中1的数量全部计算出来\n# 在某个结点(i,j)处的加号的长度,即为四个方向1的长度的最小值。遍历所有的结点找到最大值即可。\n\n\nclass Solution:\n def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:\n L, R, U, D = [[None] * n for _ in range(n)], [[None] * n for _ in range(n)], [[None] * n for _ in range(n)], [\n [None] * n for _ in range(n)]\n grid = [[1] * n for _ in range(n)]\n for x, y in mines:\n grid[x][y] = 0\n\n for i in range(n):\n for j in range(n):\n if j == 0:\n L[i][j] = grid[i][j]\n else:\n L[i][j] = L[i][j - 1] + 1 if grid[i][j] else 0\n for i in range(n):\n for j in range(n - 1, -1, -1):\n if j == n - 1:\n R[i][j] = grid[i][j]\n else:\n R[i][j] = R[i][j + 1] + 1 if grid[i][j] else 0\n for j in range(n):\n for i in range(n):\n if i == 0:\n U[i][j] = grid[i][j]\n else:\n U[i][j] = U[i - 1][j] + 1 if grid[i][j] else 0\n for j in range(n):\n for i in range(n - 1, -1, -1):\n if i == n - 1:\n D[i][j] = grid[i][j]\n else:\n D[i][j] = D[i + 1][j] + 1 if grid[i][j] else 0\n ans = 0\n for i in range(n):\n for j in range(n):\n ans = max(ans, min(L[i][j], R[i][j], U[i][j], D[i][j]))\n return ans","sub_path":"0764. Largest Plus Sign.py","file_name":"0764. Largest Plus Sign.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"374080545","text":"# 数组方法\n# sum() 求和\n# prod() 求积\n# min() 最小值\n# max() 最大值\n# argmin() 最小值的位置\n# argmax() 最大值的位置\n# mean() 均值\n# average() 均值,支持加权平均\n# std() 计算标准差\n# var() 计算标准差\n# clip() 将数值限制在某个范围内\n# ptp() 计算最大值和最小值之差\n# round() 近似,默认到整数\n\n\nfrom numpy import *\n\na = array([[1, 2, 3],\n [4, 5, 6]])\nsum(a)\n\n# 指定求和的维度\n# 沿着第一维度求和\nsum(a, axis=0)\n\n# 沿着第二维度求和\nsum(a, axis=1)\n\n# 沿着最后一维求和\nsum(a, axis=-1)\n\n# 或者使用sum()方法\na.sum()\na.sum(axis=0)\na.sum(axis=-1)\n\n# 求积\n# 求所有元素的乘积\n\na.prod()\n# 或\nprod(a, axis=0)\n\n# 最大值 最小值\nfrom numpy.random import rand\na = rand(3, 4)\n\na\n# 全局最小\na.min()\n# 沿着某个轴的最小\na.min(axis=0)\n# 全局最大\na.max()\n# 沿着某个轴的最大\na.max(axis=-1)\n\n# 最大值 最小值的位置 使用argmin argmax 方法\na.argmin()\na.argmin(axis=0)\na.argmax()\n\n# 均值\n# 可以使用mean 方法\na = array([[1, 2, 3], [4, 5, 6]])\na.mean()\na.mean(axis=1)\nmean(a)\n\n# 也可以使用average函数\naverage(a, axis=0)\n\n# average 函数还支持加权平均\naverage(a, axis=0, weights=[1, 2])\n\n# 标准差\n# 用std方法计算标准差\na.std(axis=1)\n# 用var\na.var(axis=1)\n# 或使用函数\nvar(a, axis=0)\nstd(a, axis=1)\n\n# clip 方法\n# 将数值限制在某个范围内\n\na.clip(3, 5)\n# 小于3的变成3,大于5的变成5\n\n# ptp方法\n# 计算最大值和最小值之差\n\na.ptp(axis=1)\na.ptp()\n\n# round 方法\n# 近似,默认到整数\na = array([1.2, 3.5, 4.5, 6.5, 8.6])\na.round()\na.round(decimals=1)\n","sub_path":"var/notes/python/numpy/005-array-calculation-method.py","file_name":"005-array-calculation-method.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"25223989","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n# Generated file, DO NOT EDIT\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass LicensingOverride(Model):\n \"\"\"LicensingOverride.\n\n :param behavior: How the inclusion of this contribution should change based on licensing\n :type behavior: object\n :param id: Fully qualified contribution id which we want to define licensing behavior for\n :type id: str\n \"\"\"\n\n _attribute_map = {\n 'behavior': {'key': 'behavior', 'type': 'object'},\n 'id': {'key': 'id', 'type': 'str'}\n }\n\n def __init__(self, behavior=None, id=None):\n super(LicensingOverride, self).__init__()\n self.behavior = behavior\n self.id = id\n","sub_path":"vsts/vsts/contributions/v4_1/models/licensing_override.py","file_name":"licensing_override.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"483097585","text":"#!/usr/bin/env python3\n\"\"\"\n\nZOOM POLL VIEWER v0.1\nPOLL CLASS\n11 Function\n3 Object\n\"\"\"\nfrom .Question import Question\n\n\nclass Poll:\n\n def __init__(self, zpv, poll_name, poll_type=\"QUIZ\"):\n\n self.zpv = zpv\n self._name = poll_name\n self._type = poll_type\n self._questions = []\n\n self._number_of_questions = None\n self._session_grades = {}\n self._number_of_students = {}\n\n def get_name(self):\n # Returns name\n return self._name\n\n def get_type(self):\n # Returns type\n return self._type\n\n def get_questions(self):\n # Returns question object\n return self._questions\n\n def get_question(self, question_text):\n # Returns question of given text\n for question in self._questions:\n if question.get_text() == question_text:\n return question\n question_text = self.question_formatter(question_text)\n for question in self._questions:\n if self.question_formatter(question.get_text()) == self.question_formatter(question_text):\n return question\n return False\n\n def question_formatter(self, question_text):\n result = question_text.replace(\" \", \"\")\n result = result.replace(\"\\t\", \"\")\n result = result.replace(\"\\n\", \"\")\n return result\n\n\n def get_number_of_questions(self):\n # Returns number of questions\n if self._number_of_questions is None:\n self._number_of_questions = len(self._questions)\n return self._number_of_questions\n\n def get_number_of_students(self):\n # Returns number of student\n total = 0\n print(self._number_of_students)\n for session in self._number_of_students:\n if self._number_of_students[session] > total:\n total = self._number_of_students[session]\n return total\n\n def add_question(self, question_text):\n # Adds question object and returns it\n question = self.get_question(question_text)\n if question:\n return question\n else:\n question = Question(self, question_text)\n self._questions.append(question)\n return question\n\n def set_session_grades(self, session, grades):\n # Sets grade of given session\n self._session_grades[session] = grades\n\n def get_grades_of_seesion(self, session):\n # Returns grade of given session\n return self._session_grades[session]\n\n def set_session_number_of_students(self, session, number_of_students):\n # Sets session attendance\n self._number_of_students[session] = number_of_students\n\n def calculate_session_average_grade(self):\n # Calculates average grade\n if len(self._session_grades) > 0:\n for i in self._session_grades:\n grades = self._session_grades[i]\n break\n if len(grades) > 0:\n return sum(grades) / len(grades)\n else:\n return 0\n\n def get_number_of_max_choices(self):\n # Returns number of choices\n new_max = 0\n for question in self.get_questions():\n if len(question._choices) > new_max:\n new_max = len(question._choices)\n return new_max\n","sub_path":"iteration2/ZoomPollViewer/Poll.py","file_name":"Poll.py","file_ext":"py","file_size_in_byte":3285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"15409088","text":"from CommonVariables import *\nimport matplotlib.pyplot as plt\nfrom decimal import *\nfrom keras.callbacks import ReduceLROnPlateau, TensorBoard, EarlyStopping, ModelCheckpoint\nfrom keras.layers import Activation, BatchNormalization, concatenate, Conv2D, Conv2DTranspose, Dense, Dropout, Flatten, Input, LeakyReLU, MaxPooling2D, multiply, Reshape\nfrom keras.losses import categorical_crossentropy\nfrom keras.models import Model, load_model, model_from_json, Sequential\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import Adam\nfrom keras.regularizers import l2\nfrom sklearn.model_selection import KFold\n\n# Seed for KFold, dropout and other functions.\nseed = 56\n\n# Variables.\nmin_validation_losses = []\nmin_validation_losses_epochs = []\nmax_validation_accuracies = []\nmax_validation_accuracies_epochs = []\nfinal_validation_losses = []\nfinal_validation_accuracies = []\nno_of_epochs = []\ntest_accuracies = []\n\ntrain_images = np.load(output_folder + '/Data/Train_images.npy')\ntrain_ground_truth = np.load(output_folder + '/Data/Train_ground_truth.npy')\ntest_images = np.load(output_folder + '/Data/Test_images.npy')\ntest_ground_truth = np.load(output_folder + '/Data/Test_ground_truth.npy')\n\n# Uncomment for a preview of the images.\n#for img in range(10):\n# plt.figure(img)\n# plt.imshow(train_images[img].reshape((image_size, image_size)), interpolation='none', cmap='gray')\n#plt.show()\n\n\n# Function for creating directories.\ndef create_directory(dirName):\n if not os.path.exists(dirName):\n os.mkdir(dirName)\n print(\"Directory \", dirName, \" Created \")\n else:\n print(\"Directory \", dirName, \" already exists\")\n\n\n# Creating directories.\ncreate_directory(output_folder + '/Data')\ncreate_directory(output_folder + '/Models')\n\nfor i in range(0,folds):\n create_directory(output_folder + '/Models/Model'+str(i))\n\n\n# Function for defining the model.\ndef get_model():\n # Model taken from: S. Miao, H. Xu, Z. Han, and Y. Zhu, \"Recognizing facial expressions using a shallow convolutional neural network\", IEEE Access, 7:78000-78011, 2019.\n model = Sequential()\n model.add(Conv2D(44, kernel_size=(5, 5), padding='same', data_format='channels_last', input_shape=(image_size, image_size, 1)))\n model.add(LeakyReLU(alpha=0.02))\n model.add(MaxPooling2D(pool_size=(2, 2), data_format='channels_last'))\n model.add(Conv2D(44, kernel_size=(3, 3), padding='same', data_format='channels_last'))\n model.add(LeakyReLU(alpha=0.02))\n model.add(MaxPooling2D(pool_size=(2, 2), data_format='channels_last'))\n model.add(Conv2D(88, kernel_size=(5, 5), padding='same', data_format='channels_last'))\n model.add(LeakyReLU(alpha=0.02))\n model.add(MaxPooling2D(pool_size=(2, 2), data_format='channels_last'))\n model.add(Flatten())\n model.add(Dense(2048))\n model.add(LeakyReLU(alpha=0.02))\n model.add(Dropout(0.4, seed=seed))\n model.add(Dense(1024))\n model.add(LeakyReLU(alpha=0.02))\n model.add(Dropout(0.4, seed=seed))\n model.add(Dense(class_number, activation=\"softmax\"))\n\n model.compile(loss=categorical_crossentropy,\n optimizer=Adam(lr=learning_rate, beta_1=0.9, beta_2=0.999, epsilon=1e-6), metrics=['accuracy'])\n model.summary()\n return model\n\n\n# Function for plotting the loss and accuracy for the training and validation set.\n# Taken from https://www.kaggle.com/danbrice/keras-plot-history-full-report-and-grid-search\ndef plot_and_save_history(history):\n loss_list = [s for s in history.history.keys() if 'loss' in s and 'val' not in s]\n val_loss_list = [s for s in history.history.keys() if 'loss' in s and 'val' in s]\n acc_list = [s for s in history.history.keys() if 'acc' in s and 'val' not in s]\n val_acc_list = [s for s in history.history.keys() if 'acc' in s and 'val' in s]\n\n if len(loss_list) == 0:\n print('Loss is missing in history')\n return\n\n ## As loss always exists.\n epochs = range(1, len(history.history[loss_list[0]]) + 1)\n\n ## Loss.\n plt.figure()\n for l in loss_list:\n plt.plot(epochs, history.history[l], 'b',\n label='Training loss (' + str(str(format(history.history[l][-1], '.5f')) + ')'))\n for l in val_loss_list:\n plt.plot(epochs, history.history[l], 'g',\n label='Validation loss (' + str(str(format(history.history[l][-1], '.5f')) + ')'))\n\n plt.title('Loss')\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.legend()\n plt.savefig(output_folder + '/Models/Model' + str(count)+'/Loss.png')\n #Clear axis and figure.\n plt.cla()\n plt.clf()\n\n ## Accuracy.\n plt.figure()\n for l in acc_list:\n plt.plot(epochs, history.history[l], 'b',\n label='Training accuracy (' + str(format(history.history[l][-1], '.5f')) + ')')\n for l in val_acc_list:\n plt.plot(epochs, history.history[l], 'g',\n label='Validation accuracy (' + str(format(history.history[l][-1], '.5f')) + ')')\n\n plt.title('Accuracy')\n plt.xlabel('Epochs')\n plt.ylabel('Accuracy')\n plt.legend()\n #plt.show()\n plt.savefig(output_folder + '/Models/Model' + str(count) + '/Accuracy.png')\n #Clear axis and figure.\n plt.cla()\n plt.clf()\n\n\n# Generator for images - data augmentation.\nTrainAndValidationDatagen = ImageDataGenerator(\n samplewise_center = True, # subtract the mean from the image.\n samplewise_std_normalization = True, # divides by the standard deviation.\n #rescale = 1.0 / 255.0, # a value by which we will multiply the data after any other processing.\n brightness_range = [0.5, 1.0], # a range withing each augmented image will be darkened or brightened.\n rotation_range = 2.5, # a range within which to randomly rotate pictures.\n width_shift_range = 0.025, # range within which to randomly translate pictures horizontally.\n height_shift_range = 0.025, # range within which to randomly translate pictures vertically.\n shear_range = 0.025, # for randomly applying shearing transformations.\n zoom_range = 0.025, # for randomly zooming inside pictures\n #channel_shift_range = 5, # for randomly shifting the channel values.\n #vertical_flip = False, # for randomly flipping half of the images vertically.\n horizontal_flip = True, # for randomly flipping half of the images horizontally.\n fill_mode = 'nearest') # the strategy used for filling in newly created pixels, which can appear after applying the transformation.\n\ntestDatagen = ImageDataGenerator(\n samplewise_center = True, # subtract the mean from the image.\n samplewise_std_normalization = True, # divides by the standard deviation.\n #rescale = 1.0 / 255.0, # a value by which we will multiply the data after any other processing.\n )\n\n# Initialize the function for performing k-Fold on data.\nkf = KFold(n_splits = folds, shuffle = True, random_state = seed)\n\nfor train_index, validation_index in kf.split(train_images):\n\n print('\\nFOLD '+str(count))\n\n # Generate batches from indices.\n X_train, X_validation = train_images[train_index], train_images[validation_index]\n y_train, y_validation = train_ground_truth[train_index], train_ground_truth[validation_index]\n\n # Get the model and compile it.\n model = None\n model = get_model()\n\n # Train variables.\n # We stop the training of the model if the value of the loss function of the validation set does not improve after a certain number of epochs (patience).\n early_stopper = EarlyStopping(monitor = 'val_loss', min_delta = 0, patience = 20, verbose = 1, mode = 'auto')\n\n # We'll save our model during training as long as it gets a better result than the previous epoch. Thus, we will have the best possible model at the end of the training.\n checkpointer = ModelCheckpoint(output_folder + '/Models/Model' + str(count) + '/Checkpoint_Model.h5', monitor = 'val_loss', mode = 'min', save_best_only = True, verbose = 1)\n\n # We'll help the loss function to get rid of the “plateaus” by reducing the learning rate parameter of the optimization function of a certain value (factor) if the value of the loss function of the validation set does not improve after a certain number of epochs (patience).\n lr_reducer = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.99, patience = 1, mode = 'auto', verbose = 1)\n\n # TensorBoard allows to visualize dynamic graphs of the training and test metrics, as well as activation histograms for the different layers in the model.\n tensorboard = TensorBoard(log_dir = './Logs')\n\n # Generate the batches for train and validation.\n train_iterator = TrainAndValidationDatagen.flow(X_train, y_train, batch_size = batch_size)\n validation_iterator = TrainAndValidationDatagen.flow(X_validation, y_validation, batch_size = batch_size)\n\n history = None\n # Fits the model on batches with real-time data augmentation:\n history = model.fit_generator(train_iterator,\n epochs = epochs,\n steps_per_epoch = len(train_iterator),\n validation_data = validation_iterator,\n validation_steps = len(validation_iterator),\n verbose = 2,\n shuffle = True,\n callbacks = [lr_reducer, tensorboard, early_stopper, checkpointer])\n\n # Plot and save the history.\n plot_and_save_history(history)\n\n # Save the min losses, the related epochs, the max accuracies, the related epochs, the final losses, the final accuracies, and the total number of epochs of the networks.\n min_validation_losses.append(str(Decimal(min(history.history['val_loss'])).quantize(Decimal('1.00000'))))\n min_validation_losses_epochs.append(str(history.history['val_loss'].index(min(history.history['val_loss'])) + 1))\n\n max_validation_accuracies.append(str(Decimal(max(history.history['val_acc'])).quantize(Decimal('1.00000'))))\n max_validation_accuracies_epochs.append(str(history.history['val_acc'].index(max(history.history['val_acc'])) + 1))\n\n final_validation_losses.append(str(Decimal(history.history['val_loss'][len(history.history['val_loss']) - 1]).quantize(Decimal('1.00000'))))\n final_validation_accuracies.append(str(Decimal(history.history['val_acc'][len(history.history['val_acc'])-1]).quantize(Decimal('1.00000'))))\n\n no_of_epochs.append(str(len(history.history['loss'])))\n\n # Save the model to be used later.\n fer_json = model.to_json()\n with open(output_folder + '/Models/Model' + str(count) + '/Model.json', 'w') as json_file:\n json_file.write(fer_json)\n model.save_weights(output_folder + '/Models/Model' + str(count) + '/Model_weights.h5')\n print(\"Model saved.\")\n\n # Evaluate network with the test data.\n test_iterator = testDatagen.flow(test_images, test_ground_truth, batch_size = batch_size)\n score = model.evaluate_generator(test_iterator, steps = len(test_iterator), verbose=0)\n test_accuracies.append(str(Decimal(score[1]).quantize(Decimal('1.00000'))))\n\n # Next fold.\n count+=1\n\n\n# Write losses and accuracies on file and on screen.\nfile = open(output_folder + '/Data/results.txt', 'w')\n\ncount=0\nprint ('\\nTest accuracies:\\n')\nfile.write('Test accuracies:\\n')\nfor i in test_accuracies:\n print('Fold '+ str(count) + ': ' + i)\n file.write('Fold '+ str(count) +': ' + i + '\\n')\n count+=1\n\ncount=0\nprint ('\\nMinimum validation losses:\\n')\nfile.write('\\nMinimum validation losses:\\n')\nfor i, j in zip(min_validation_losses, min_validation_losses_epochs):\n print('Fold '+ str(count) + ': ' + i + ' at epoch ' + j)\n file.write('Fold '+ str(count) +': ' + i + ' at epoch ' + j + '\\n')\n count+=1\n\ncount=0\nprint ('\\nMaximum validation accuracies:\\n')\nfile.write('\\nMaximum validation accuracies:\\n')\nfor i, j in zip(max_validation_accuracies, max_validation_accuracies_epochs):\n print('Fold '+ str(count) + ': ' + i + ' at epoch ' + j)\n file.write('Fold '+ str(count) +': ' + i + ' at epoch ' + j + '\\n')\n count+=1\n\ncount=0\nprint ('\\nFinal validation losses:\\n')\nfile.write('\\nFinal validation losses:\\n')\nfor i in final_validation_losses:\n print('Fold '+ str(count) + ': ' + i)\n file.write('Fold '+ str(count) +': ' + i + '\\n')\n count+=1\n\ncount=0\nprint ('\\nFinal validation accuracies:\\n')\nfile.write('\\nFinal validation accuracies:\\n')\nfor i in final_validation_accuracies:\n print('Fold '+ str(count) + ': ' + i)\n file.write('Fold '+ str(count) +': ' + i + '\\n')\n count+=1\n\ncount=0\nprint ('\\nEpochs of training:\\n')\nfile.write('\\nEpochs of training:\\n')\nfor i in no_of_epochs:\n print('Fold '+ str(count) + ': ' + i)\n file.write('Fold '+ str(count) +': ' + i + '\\n')\n count+=1\n\nfile.close()","sub_path":"TrainWithDataAugmentation.py","file_name":"TrainWithDataAugmentation.py","file_ext":"py","file_size_in_byte":12764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"125597854","text":"import requests\nfrom config import Config\n\nclass SpotifyClient:\n\n class SpotifyClientError(Exception):\n pass\n\n __instance = None\n\n def __new__(cls):\n if SpotifyClient.__instance is None:\n SpotifyClient.__instance = object.__new__(cls)\n\n # get the token\n resp = requests.post('https://accounts.spotify.com/api/token',\n data={'grant_type': 'client_credentials'},\n auth=Config.get_instance().spotify_credential)\n \n if resp.status_code == 200:\n body = resp.json()\n SpotifyClient.__instance._token = body['access_token']\n else:\n raise SpotifyClient.SpotifyClientError('Failed to auth')\n\n return SpotifyClient.__instance\n\n def __get_headers(self):\n return {\n 'Authorization': 'Bearer {}'.format(self._token)\n }\n\n def get_artist_id(self, name):\n headers = self.__get_headers()\n params = {\n 'q': name,\n 'type': 'artist'\n }\n resp = requests.get('https://api.spotify.com/v1/search', params=params, headers=headers)\n\n if resp.status_code == 200:\n body = resp.json()\n if body['artists']['total'] > 0:\n return body['artists']['items'][0]['id']\n else:\n raise SpotifyClient.SpotifyClientError('Failed to fetch artist info')\n\n def get_top_tracks_by_artist_id(self, artist_id, limit=None):\n headers = self.__get_headers()\n params = {\n 'country': 'TW'\n }\n resp = requests.get('https://api.spotify.com/v1/artists/{}/top-tracks'.format(artist_id), params=params, headers=headers)\n\n if resp.status_code == 200:\n body = resp.json()\n return body['tracks'][:5]\n else:\n raise SpotifyClient.SpotifyClientError('Failed to fetch popular track by artist id')","sub_path":"src/models/spotify.py","file_name":"spotify.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"505036266","text":"\"\"\"\nExample lambda configuation file, including `config` dictionary and\nan example handler function. This one is slightly different than the other. The\npoint is to see that it has been updated.\n\nWould deploy with:\n```\nfrom aws_lambda import deploy_function\nfrom aws_lambda.examples import example_function\ndeploy_function(example_function,\n function_name_suffix=,\n package_objects=,\n requirements_fpath=,\n extra_config=)\n```\n\"\"\"\n\nconfig = {\n 'function_name': 'my_test_function',\n 'function_module': 'service',\n 'function_handler': 'handler',\n 'handler': 'service.handler',\n 'region': 'us-east-1',\n 'runtime': 'python3.6',\n 'role': 'helloworld',\n 'description': 'Test lambda'\n}\n\n\ndef handler(event, context):\n return 'Hello! I have been updated! My input event is %s' % event\n","sub_path":"tests/test_lambdas/example_function_update.py","file_name":"example_function_update.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"2100528","text":"# SPDX-FileCopyrightText: 2020 2020\n#\n# SPDX-License-Identifier: Apache-2.0\n\nfrom builtins import object\nimport json\nimport os\nfrom jsl import AnyOfField, ArrayField, BooleanField, DictField, Document\nfrom jsl import DocumentField, NumberField, OneOfField, StringField, UriField\n\n###\n# TODO Need to fix this: Make sure schemagenerator generates proper element for hook\n# For time being do the following change in generated schema.json\n# replace: \"hook\": {\"$ref\": \"#/definitions/Hooks\"} with \"hook\": {\"type\": \"object\"}\n###\n\n# Base Document Class with restricting properties population\nclass DocumentWithoutAddProp(Document):\n class Options(object):\n additional_properties = False\n\n\n# Document Element with Label and Value element. Possible values are text, numeric and boolean types\nclass ValueLabelPair(DocumentWithoutAddProp):\n value = OneOfField([\n NumberField(),\n StringField(max_length=250),\n BooleanField()\n ])\n label = StringField(required=True, max_length=100)\n\n\nclass OAuthFields(DocumentWithoutAddProp):\n oauth_field = StringField(max_length=100)\n label = StringField(max_length=100)\n field = StringField(max_length=100)\n help = StringField(max_length=200)\n encrypted = BooleanField()\n\n\n\n# Base Validator Wrapper component which is extension of DocumentWithoutAddProp Wrapper Component\nclass ValidatorBase(DocumentWithoutAddProp):\n errorMsg = StringField(max_length=400)\n\n\n# MetaData component for detailing brief imformation of document/component\nclass Meta(DocumentWithoutAddProp):\n displayName = StringField(required=True, max_length=200)\n name = StringField(required=True, pattern=\"^[^<>\\:\\\"\\/\\\\\\|\\?\\*]+$\")\n restRoot = StringField(required=True, pattern=\"^\\w+$\")\n apiVersion = StringField(required=True, pattern=\"^(?:\\d{1,3}\\.){2}\\d{1,3}$\")\n version = StringField(required=True)\n schemaVersion = StringField( pattern=\"^(?:\\d{1,3}\\.){2}\\d{1,3}$\")\n\n\n# Text validator for the String Field Value input\nclass StringValidator(ValidatorBase):\n type = StringField(required=True, enum=[\"string\"])\n minLength = NumberField(required=True, minimum=0)\n maxLength = NumberField(required=True, minimum=0)\n\n\n# Numeric validator for the Number Field Value input\nclass NumberValidator(ValidatorBase):\n type = StringField(required=True, enum=[\"number\"])\n range = ArrayField(NumberField(), required=True)\n\n\n# Regex validator for the text Field Value input\nclass RegexValidator(ValidatorBase):\n type = StringField(required=True, enum=[\"regex\"])\n pattern = StringField(required=True)\n\n\n# Email validator for the text Field Value input\nclass EmailValidator(ValidatorBase):\n type = StringField(required=True, enum=[\"email\"])\n\n\n# Ipv4 represenation validator\nclass Ipv4Validator(ValidatorBase):\n type = StringField(required=True, enum=[\"ipv4\"])\n\n\n# Date Validator\nclass DateValidator(ValidatorBase):\n type = StringField(required=True, enum=[\"date\"])\n\n\n# URL Validator\nclass UrlValidator(ValidatorBase):\n type = StringField(required=True, enum=[\"url\"])\n\n# Entity for Alert Actions\nclass AlertEntity(DocumentWithoutAddProp):\n field = StringField(required=True, pattern=\"^\\w+$\")\n label = StringField(required=True, max_length=30)\n type = StringField(required=True,\n enum=[\"text\", \"singleSelect\", \"checkbox\", \"radio\", \"singleSelectSplunkSearch\"])\n help = StringField(max_length=200)\n defaultValue = OneOfField([\n NumberField(),\n StringField(max_length=250),\n BooleanField()\n ])\n required = BooleanField()\n search = StringField(max_length=200)\n valueField = StringField(max_length=200)\n labelField = StringField(max_length=200)\n options = DictField(\n properties={\n \"items\": ArrayField(DocumentField(ValueLabelPair, as_ref=True))\n }\n )\n\n##\n# Entity Form Field Component Wrapper having field name, label, field types, help/tooltips support, default value\n# Validators and UI Controls such as visibility etc\n##\nclass Entity(DocumentWithoutAddProp):\n field = StringField(required=True, pattern=\"^\\w+$\")\n label = StringField(required=True, max_length=30)\n type = StringField(required=True,\n enum=[\"custom\", \"text\", \"singleSelect\", \"checkbox\", \"multipleSelect\", \"radio\", \"placeholder\", \"oauth\", \"helpLink\"])\n help = StringField(max_length=200)\n tooltip = StringField(max_length=250)\n defaultValue = OneOfField([\n NumberField(),\n StringField(max_length=250),\n BooleanField()\n ])\n options = DictField(\n properties={\n \"disableSearch\": BooleanField(),\n \"autoCompleteFields\": OneOfField([\n ArrayField(DictField(\n properties={\n \"label\": StringField(required=True, max_length=150),\n \"children\": ArrayField(DocumentField(ValueLabelPair, as_ref=True), required=True)\n }\n )),\n ArrayField(DocumentField(ValueLabelPair, as_ref=True))\n ]),\n \"endpointUrl\": StringField(max_length=350),\n \"denyList\": StringField(max_length=350),\n \"allowList\": StringField(max_length=350),\n \"delimiter\": StringField(max_length=1),\n \"items\": ArrayField(DocumentField(ValueLabelPair, as_ref=True)),\n \"referenceName\": StringField(max_length=250),\n \"enable\": BooleanField(),\n \"placeholder\": StringField(max_length=250),\n \"display\": BooleanField(),\n \"labelField\": StringField(max_length=250),\n \"src\": StringField(max_length=250),\n \"defaultValue\": StringField(max_length=250),\n \"disableonEdit\": BooleanField(),\n \"basic\": ArrayField(DocumentField(OAuthFields, as_ref=True)),\n \"oauth\": ArrayField(DocumentField(OAuthFields, as_ref=True)),\n \"auth_type\": ArrayField(StringField(max_length=100)),\n \"auth_label\": StringField(max_length=250),\n \"oauth_popup_width\": NumberField(),\n \"oauth_popup_height\": NumberField(),\n \"oauth_timeout\": NumberField(),\n \"auth_code_endpoint\": StringField(max_length=350),\n \"access_token_endpoint\": StringField(max_length=350),\n \"text\": StringField(max_length=50),\n \"link\": StringField()\n }\n )\n required = BooleanField()\n encrypted = BooleanField()\n # List of inbuilt field validator\n validators = ArrayField(AnyOfField([\n DocumentField(StringValidator, as_ref=True),\n DocumentField(NumberValidator, as_ref=True),\n DocumentField(RegexValidator, as_ref=True),\n DocumentField(EmailValidator, as_ref=True),\n DocumentField(Ipv4Validator, as_ref=True),\n DocumentField(UrlValidator, as_ref=True),\n DocumentField(DateValidator, as_ref=True)\n ]))\n\n\n##\n# Input Entity is super class of Entity to restrict the predefined field name holding entity field\n##\nclass InputsEntity(Entity):\n # Prevnet Splunk reserved inputs field keys being used in the user customized inputs\n # https://jira.splunk.com/browse/ADDON-13014#comment-1493170\n\n field = StringField(\n required=True,\n pattern=\"(?!^(?:persistentQueueSize|queueSize|start_by_shell|output_mode|output_field|owner|app|sharing)$)(?:^\\w+$)\"\n )\n\n\n##\n# ConfigurationEntity is super class of Entity to restrict the predefined field name holding entity field such as\n# output_mode\n# output_field\n# owner\n# app\n# sharing\n# ##\nclass ConfigurationEntity(Entity):\n field = StringField(\n required=True,\n pattern=\"(?!^(?:output_mode|output_field|owner|app|sharing)$)(?:^\\w+$)\"\n )\n\n\n##\n# Table component schema with headers, additional info and customization row extension\n##\nclass Table(DocumentWithoutAddProp):\n moreInfo = ArrayField(DictField(\n properties={\n \"field\": StringField(required=True, pattern=\"^\\w+$\"),\n \"label\": StringField(required=True, max_length=30),\n \"mapping\": DictField(required=False)\n }\n ))\n # Header field names needs to be display on UI\n header = ArrayField(DictField(\n properties={\n \"field\": StringField(required=True, pattern=\"^\\w+$\"),\n \"label\": StringField(required=True, max_length=30),\n \"mapping\": DictField(required=False),\n \"customCell\": DictField(required=False)\n }\n ), required=True)\n # custom Row implementation if required for special cases\n customRow = DictField(required=False)\n\n\n##\n# Input table having all functions of table and edit|delete|clone|enable/disable actions for each row\n##\nclass InputsTable(Table):\n actions = ArrayField(StringField(enum=[\"edit\", \"delete\", \"clone\", \"enable\"]), required=True)\n\n\n##\n# Configuration table having all functions of table and edit|delete|clone|enable/disable actions for each row\n##\nclass ConfigurationTable(Table):\n actions = ArrayField(StringField(enum=[\"edit\", \"delete\", \"clone\"]), required=True)\n\n\n##\n# Hook attribute scheme to define custom Hook for various events such as on load, on save and on save\n##\nclass Hooks(DocumentWithoutAddProp):\n saveValidator = StringField(max_length=3000)\n onLoad = StringField(max_length=3000)\n onChange = StringField(max_length=3000)\n\n\n##\n# Tab Content holding the wrapper of Table and Rest Handler Mapping\n##\nclass TabContent(DocumentWithoutAddProp):\n entity = ArrayField(DocumentField(ConfigurationEntity, as_ref=True), required=True)\n name = StringField(required=True, pattern=\"^[\\/\\w]+$\", max_length=250)\n title = StringField(required=True, max_length=50)\n options = DocumentField(Hooks, as_ref=True)\n table = DocumentField(ConfigurationTable, as_ref=True)\n conf = StringField(required=False, max_length=100)\n restHandlerName = StringField(required=False, max_length=100)\n # Provisioning tab level hook on configuration page\n hook = DocumentField(Hooks, as_ref=True)\n\n\n##\n# ConfigurationPage Component having tabbing pages for configuration of various module\n# Each tab is individual TabContent\n##\nclass ConfigurationPage(DocumentWithoutAddProp):\n title = StringField(required=True, max_length=60)\n description = StringField(max_length=200)\n tabs = ArrayField(DocumentField(TabContent, as_ref=True), required=True, min_items=1)\n\n\n##\n# InputsPage Component having table and entity dialogue driven by service handler to add new entry\n##\nclass InputsPage(DocumentWithoutAddProp):\n title = StringField(required=True, max_length=60)\n description = StringField(max_length=200)\n table = DocumentField(InputsTable, as_ref=True, required=True)\n services = ArrayField(DictField(\n properties={\n \"name\": StringField(required=True, pattern=\"^[0-9a-zA-Z][0-9a-zA-Z_-]*$\", max_length=50),\n \"title\": StringField(required=True, max_length=100),\n \"entity\": ArrayField(DocumentField(InputsEntity, as_ref=True), required=True),\n \"options\": DocumentField(Hooks, as_ref=True),\n \"groups\": ArrayField(DictField(\n properties={\n \"options\": DictField(\n properties={\n \"isExpandable\": BooleanField(),\n \"expand\": BooleanField()\n }\n ),\n \"label\": StringField(required=True, max_length=100),\n \"field\": ArrayField(StringField(required=True, pattern=\"^\\w+$\"))\n }\n ), required=False),\n \"style\": StringField(required=False, enum=[\"page\", \"dialog\"]),\n \"hook\": DictField(required=False),\n \"conf\": StringField(required=False, max_length=100),\n \"restHandlerName\": StringField(required=False, max_length=100)\n }\n ), required=True)\n menu = DictField(required=False)\n\n\n##\n# Main Page to holding configuration and input page\n##\nclass Pages(DocumentWithoutAddProp):\n configuration = DocumentField(ConfigurationPage, as_ref=True, required=False)\n inputs = DocumentField(InputsPage, as_ref=True, required=False)\n\n\n##\n# Component holding Technology dict in active_response\n##\nclass Technology(DocumentWithoutAddProp):\n version = ArrayField(StringField(required=True, pattern=\"^\\d+(?:\\.\\d+)*$\"),required=True, min_items=1)\n product = StringField(required=True, max_length=100)\n vendor = StringField(required=True, max_length=100)\n\n\n##\n# Main Component holding the alert actions \n##\nclass Alerts(DocumentWithoutAddProp):\n name = StringField(required=True, pattern=\"^[a-zA-Z0-9_]+$\", max_length=100)\n label = StringField(required=True, max_length=100)\n description = StringField(required=True)\n activeResponse = DictField(properties={\n \"task\": ArrayField(StringField(required=True), required=True, min_items=1),\n \"supportsAdhoc\": BooleanField(required=True),\n \"subject\": ArrayField(StringField(required=True), required=True, min_items=1),\n \"category\": ArrayField(StringField(required=True), required=True, min_items=1),\n \"technology\": ArrayField(DocumentField(Technology,as_ref=True),required=True, min_items=1),\n \"drilldownUri\":StringField(required=False),\n \"sourcetype\":StringField(required=False, pattern=\"^[a-zA-Z0-9:-_]+$\", max_length=50)\n }, required=False)\n entity = ArrayField(DocumentField(AlertEntity, as_ref=True))\n\n##\n# Root Component holding all pages and meta information\n##\nclass UCCConfig(DocumentWithoutAddProp):\n meta = DocumentField(Meta, as_ref=True, required=True)\n pages = DocumentField(Pages, as_ref=True, required=True)\n alerts = ArrayField(DocumentField(Alerts, as_ref=True), required=False, min_items=1)\n\n##\n# SchemaGenerator responsible to generate schema json file holding information of Flow of UI based on UCCConfig Object\n##\nif __name__ == \"__main__\":\n formated = json.dumps(UCCConfig.get_schema(ordered=True), indent=4)\n formated = formated.replace(\"__main__.\", \"\")\n\n cur_dir = os.path.dirname(__file__)\n with open(os.path.join(cur_dir, 'schema.json'), 'w+') as schema_handler:\n schema_handler.write(formated)","sub_path":"splunk_add_on_ucc_framework/UCC-UI-lib/schema/schemaGenerator.py","file_name":"schemaGenerator.py","file_ext":"py","file_size_in_byte":14331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"165942936","text":"\"\"\"\nCopyright 2017 ARM Limited\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport pytest\n\npytest_plugins = ['pelion_test_lib.fixtures.client_fixtures',\n 'pelion_test_lib.fixtures.cloud_fixtures']\n\n\ndef pytest_addoption(parser):\n \"\"\"\n Function to enable pytest commandline arguments\n :param parser: argparser\n :return:\n \"\"\"\n parser.addoption('--target_id', action='store', help='mbed device target id')\n parser.addoption('--update_bin', action='store', help='mbed device update binary')\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"583367062","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom collections import Counter\n\nfrom childeshub.hub import Hub\n\nDPI = 196\nNUM_PARTITIONS = 8\nHUB_MODE = 'sem'\n\nhub = Hub(mode=HUB_MODE)\n\n# term distributions\npart_size = hub.train_terms.num_tokens // NUM_PARTITIONS\ndists = []\nfig, ax = plt.subplots(dpi=DPI)\nfor n, part in enumerate(hub.split(hub.reordered_token_ids, part_size)):\n c = Counter(part)\n dist = np.sort(np.log(list(c.values())))[::-1]\n dists.append(dist)\n ax.plot(dist, label='{}th corpus partition'.format(n + 1))\nax.set_ylabel('Log Freq')\nax.set_xlabel('Term Id')\nplt.legend()\nplt.show()\n\n","sub_path":"analysis/analyze_term_distributions.py","file_name":"analyze_term_distributions.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"462697590","text":"# coding=utf-8\ndef main():\n import sys\n import os\n\n os.environ['DB_INIT_SCRIPT'] = 'True'\n\n if os.path.dirname(__file__) != '':\n os.chdir(os.path.dirname(__file__) + os.sep + os.path.pardir)\n else:\n os.chdir(os.path.pardir)\n\n cwd = os.getcwd()\n sys.path.insert(0, cwd)\n\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"newsee.settings\")\n\n import django\n django.setup()\n\n from Reader.models import Reader, Chosen\n from Channel.models import Channel\n from Category.models import Category\n from News.models import News\n\n Chosen.objects.all().delete()\n Reader.objects.all().delete()\n News.objects.all().delete()\n Category.objects.all().delete()\n Channel.objects.all().delete()\n\n Channel.init()\n News.update()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Dev/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"58132597","text":"import unittest\nfrom .. import xml_utils as xml_utils\nimport xml.etree.ElementTree as ET\nimport re\nimport time\nfrom xml.etree.ElementTree import Element\nfrom xml.etree.ElementTree import ElementTree\nimport os\n\n\nclass TestXmlUtils(unittest.TestCase):\n\n def test_get_tag_name(self):\n values = [[\"A\", \"A\"],\n [\"A\", \"{}A\"],\n [\"A\", \"{A}A\"],\n [\"A\", \"{xhtml:aa}A\"],\n [\"\", \"{}\"],\n [\"\", None]]\n for value in values:\n self.assertEqual(xml_utils.get_tag_name(value[1]), value[0])\n\n def test_check_tag_name(self):\n values = [[True, \"A\", \"A\"],\n [True, \"{}A\", \"A\"],\n [True, \"{A}A\", \"A\"],\n [True, \"{xhtml:aa}A\", \"A\"],\n [False, \"{}\", \"A\"],\n [False, None, \"A\"],\n [False, \"{}A\", \"B\"],\n [False, \"A\", \"B\"],\n [False, \"{xhtml:aa}A\", \"B\"],\n [False, \"{}A\", None],\n [False, None, \"A\"],\n [True, None, \"\"]]\n for value in values:\n self.assertEqual(xml_utils.check_tag_name(\n value[1], value[2]), value[0])\n\n def test_get_tag_namespace(self):\n values = [[\"\", \"A\"],\n [\"{}\", \"{}A\"],\n [\"{A}\", \"{A}A\"],\n [\"{xhtml:aa}\", \"{xhtml:aa}A\"],\n [\"{}\", \"{}\"],\n [\"\", None]]\n for value in values:\n self.assertEqual(xml_utils.get_tag_namespace(value[1]), value[0])\n\n def test_get_text_from_element(self):\n res = xml_utils.get_text_from_element(ET.fromstring(\"textabc\"), \"./b\")\n self.assertEqual(\"text\", res)\n\n res = xml_utils.get_text_from_element(ET.fromstring(\"text\"), \".\")\n self.assertEqual(None, res)\n\n res = xml_utils.get_text_from_element(ET.fromstring(\"abctext\"), \".\")\n self.assertEqual(\"abc\", res)\n\n def test_get_element(self):\n res = xml_utils.get_element(ET.fromstring(\"textabc\"), \"./b\")\n self.assertEqual(\"b\", res.tag)\n\n res = xml_utils.get_element(ET.fromstring(\"text\"), \".\")\n self.assertEqual(\"a\", res.tag)\n\n res = xml_utils.get_element(ET.fromstring(\"abctext\"), \"./b/c\")\n self.assertEqual(None, res)\n \n def test_get_elements(self):\n res = xml_utils.get_elements(ET.fromstring(\"textabc\"), \"./b\")\n self.assertEqual(\"b\", res[0].tag)\n\n res = xml_utils.get_elements(ET.fromstring(\"text\"), \".\")\n self.assertEqual(\"a\", res[0].tag)\n\n res = xml_utils.get_elements(ET.fromstring(\"abctext\"), \"./b/c\")\n self.assertEqual([], res)\n \n res = xml_utils.get_elements(ET.fromstring(\"texttext2\"), \"./b\")\n self.assertEqual(\"text\", res[0].text)\n self.assertEqual(\"text2\", res[1].text)\n self.assertEqual(2, len(res))\n\n def test_current_timestamp(self):\n firstTimestamp = xml_utils.current_timestamp()\n time.sleep(1)\n secondTimestamp = xml_utils.current_timestamp()\n self.assertNotEqual(firstTimestamp, secondTimestamp)\n\n def test_merge_elements(self):\n obj = Element(\"A\")\n xml_utils.merge_elements(obj, Element(\"B\", attrib={}))\n self.assertEqual(obj.tag, 'A')\n\n xml_utils.merge_elements(obj, Element(\"B\", attrib={\"a\":\"b\"}))\n self.assertEqual(obj.tag, 'A')\n self.assertEqual(obj.get('a'), 'b')\n\n xml_utils.merge_elements(obj, Element(\"B\", attrib={\"a\":\"c\"}))\n self.assertEqual(obj.get('a'), 'b')\n\n def test_setElementAttribute(self):\n elem = xml_utils.createSubElement(\"element\")\n xml_utils.setElementAttribute(elem, \"attrib\", \"value\")\n self.assertEqual(\"value\", elem.get(\"attrib\"))\n xml_utils.setElementAttribute(elem, \"attrib\", \"value2\")\n self.assertEqual(\"value2\", elem.get(\"attrib\"))\n xml_utils.setElementAttribute(elem, \"attrib\", None)\n self.assertEqual(\"value2\", elem.get(\"attrib\"))\n\n def test_createSubElement(self):\n elem = xml_utils.createSubElement(\"element\")\n self.assertEqual(\"element\", elem.tag)\n self.assertEqual(None, elem.text)\n\n elem2 = xml_utils.createSubElement(\"element\", \"content\")\n self.assertEqual(\"element\", elem2.tag)\n self.assertEqual(\"content\", elem2.text)\n\n def test_addRequiredSubElement(self):\n elem = Element(\"A\")\n xml_utils.addRequiredSubElement(elem, \"B\", \"content\")\n self.assertEqual(elem.tag, 'A')\n self.assertEqual(elem.text, None)\n self.assertEqual(len(list(elem)), 1) #.getchildren() removed\n childs = list(elem) # .getchildren() removed\n self.assertEqual(childs[0].tag, 'B')\n self.assertEqual(childs[0].text, \"content\")\n\n def test_addEncodedSubElement(self):\n class internalTestClass:\n def __init__(self, content:str):\n self.content=content\n def encode(self):\n return Element(self.content)\n\n elem = Element(\"A\")\n elem2 = internalTestClass(\"B\")\n xml_utils.addEncodedSubElement(elem, elem2)\n self.assertEqual(elem.tag, 'A')\n self.assertEqual(elem.text, None)\n self.assertEqual(len(list(elem)), 1) # .getchildren() removed\n childs = list(elem) # .getchildren() removed\n self.assertEqual(childs[0].tag, \"B\")\n\n def test_generateMd5(self):\n res = xml_utils.generateMd5('A')\n res2 = xml_utils.generateMd5('A')\n self.assertEqual(res, res2)\n res3 = xml_utils.generateMd5('BB')\n self.assertNotEqual(res, res3)\n self.assertTrue(re.match(\"^[a-f0-9]{32}$\", res))\n\n def test_validateXmlFile(self):\n self.assertTrue(xml_utils.validateXmlFile(os.path.dirname(__file__)+'/../../TReqz/examples/exampleA/Test_000977e1.reqif', os.path.dirname(__file__)+\"/../../TReqz/reqif.xsd\"))\n self.assertFalse(xml_utils.validateXmlFile(os.path.dirname(__file__)+'/../../TReqz/examples/exampleA/unknownFile.reqif', os.path.dirname(__file__)+\"/../../TReqz/reqif.xsd\" ))\n\n def test_decodeXhtml(self):\n self.assertEqual(\"

    \", xml_utils.decodeXhtml(ET.fromstring(\"

    \")))\n self.assertEqual(\"\", xml_utils.decodeXhtml(None))\n self.assertEqual(\"

    \", xml_utils.decodeXhtml(ET.fromstring(\"\")))\n\n def test_encodeXhtml(self):\n self.assertEqual(b\"\", ET.tostring(xml_utils.encodeXhtml(None)))\n self.assertEqual(b\"\", ET.tostring(xml_utils.encodeXhtml(\"\")))\n self.assertEqual(b\"\", ET.tostring(xml_utils.encodeXhtml(\"\")))\n\n def test_stringIsWellFormedXml(self):\n self.assertFalse(xml_utils.stringIsWellFormedXml(\"\"))\n self.assertFalse(xml_utils.stringIsWellFormedXml(None))\n self.assertTrue(xml_utils.stringIsWellFormedXml(\"\"))\n self.assertFalse(xml_utils.stringIsWellFormedXml(\"\"))\n self.assertFalse(xml_utils.stringIsWellFormedXml(\"abc\"))\n\n def test_normalizeXhtml(self):\n values = [[\"\", \"\"],\n [None, None],\n [\"AA\", \"AA\"],\n [\"AA\", \"AA\"],\n [\"A\\nA\", \"AA\"],\n [\"AA\", \"AA\"],\n [\"AA A\", \"AA A\"]]\n for value in values:\n self.assertEqual(xml_utils.normalizeXhtml(value[0]), value[1])","sub_path":"xmlHelper/tests/test_xml_utils.py","file_name":"test_xml_utils.py","file_ext":"py","file_size_in_byte":7686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"161883149","text":"import uuid\nfrom unittest import mock\n\nimport pytest\nfrom django.conf import settings\nfrom django.test import TestCase, override_settings\nfrom model_bakery import baker\n\nfrom operations.exceptions import OperationNotCompleteException\nfrom operations.models import Operacao\n\n\nclass TestOperationModel(TestCase):\n def setUp(self):\n self.operacao = baker.make(Operacao)\n\n def test_get_admin_url(self):\n admin_url = self.operacao.get_admin_url\n expected = f\"{settings.SITE_URL}/admin/operations/operacao/{self.operacao.id}/change/\"\n\n assert admin_url == expected\n\n\nclass TestOperationFlow(TestCase):\n def setUp(self):\n self.form_uuid = uuid.uuid4()\n self.operacao = baker.make(\n Operacao,\n identificador=self.form_uuid,\n )\n\n def test_operacao_starts_at_secao_1(self):\n assert self.operacao.secao_atual == 1\n\n def test_update_section(self):\n new_section = 2\n section = self.operacao.update_section(new_section)\n\n self.operacao.refresh_from_db()\n assert section == new_section\n assert self.operacao.secao_atual == new_section\n\n def test_go_to_next_section(self):\n new_section = 3\n self.operacao.houve_ocorrencia_operacao = True\n self.operacao.update_section(new_section)\n\n self.operacao.refresh_from_db()\n assert self.operacao.secao_atual == new_section\n\n\nclass TestOperationMakeComplete(TestCase):\n def setUp(self):\n self.form_uuid = uuid.uuid4()\n\n self.p_notify = mock.patch.object(Operacao, \"notify_completion\")\n self.m_notify = self.p_notify.start()\n\n def tearDown(self):\n self.p_notify.stop()\n\n def test_operacao_starts_with_status_incomplete(self):\n operacao = baker.make(\n Operacao,\n identificador=self.form_uuid,\n )\n\n assert operacao.situacao == \"incompleto\"\n\n def test_make_complete(self):\n operacao = baker.make(\n Operacao,\n completo=False,\n identificador=self.form_uuid,\n houve_ocorrencia_operacao=True\n )\n operacao.make_complete()\n\n operacao.refresh_from_db()\n assert operacao.completo\n assert operacao.situacao == \"completo com ocorrencia\"\n self.m_notify.assert_called_once_with()\n\n def test_make_complete_with_status_not_all_sections_filled(self):\n operacao = baker.make(\n Operacao,\n completo=False,\n identificador=self.form_uuid,\n houve_ocorrencia_operacao=False\n )\n operacao.make_complete()\n\n operacao.refresh_from_db()\n assert operacao.completo\n assert operacao.situacao == \"completo sem ocorrencia\"\n self.m_notify.assert_called_once_with()\n\n def test_only_notify_when_complete_for_the_first_time(self):\n operacao = baker.make(\n Operacao,\n completo=True,\n identificador=self.form_uuid,\n houve_ocorrencia_operacao=False\n )\n operacao.make_complete()\n\n operacao.refresh_from_db()\n assert operacao.completo\n assert operacao.situacao == \"completo sem ocorrencia\"\n self.m_notify.assert_not_called()\n\n\nclass TestNotifyOperationComplete(TestCase):\n def setUp(self):\n self.identificador = uuid.uuid4()\n self.operacao_completa = baker.make(\n Operacao,\n completo=True,\n identificador=self.identificador\n )\n self.operacao_incompleta = baker.make(\n Operacao,\n completo=False,\n identificador=uuid.uuid4()\n )\n self.p_notifica_por_email = mock.patch(\"operations.models.notifica_por_email\")\n self.m_noifica_por_email = self.p_notifica_por_email.start()\n\n def tearDown(self):\n self.p_notifica_por_email.stop()\n\n @override_settings(DEBUG=False)\n def test_notify_when_complete(self):\n self.operacao_completa.notify_completion()\n\n self.m_noifica_por_email.assert_called_once_with(self.operacao_completa)\n\n def test_raise_exception_when_not_complete(self):\n with pytest.raises(OperationNotCompleteException):\n self.operacao_incompleta.notify_completion()\n\n @override_settings(DEBUG=True)\n def test_donot_notfy_when_in_debug_mode(self):\n self.operacao_completa.notify_completion()\n\n self.m_noifica_por_email.assert_not_called()\n","sub_path":"operations/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"240420887","text":"#!/usr/bin/env python\n\n# Grant Nelson and John M. Singleton\n# CSCI 520 - Distributed Systems\n# Project 3 (Blockchain Programming Project)\n# due May 7, 2020 by 11:59 PM\n\n# Simple multiple socket manager with\n# message framing and node Id determination.\n\nimport threading\nimport socket\nimport time\nimport re\n\n\nclass SocketConst:\n # Maximum size a chunk can grow without hitting a message delimiter.\n # If a chunk reaches this size the current growing message is dumped, meaning\n # if a delimiter is reached shortly after, it could create a bad message.\n maximumChunkSize = 100000\n\n # The byte size of the chunks to read from the socket at one time.\n receiveChunkSize = 256\n\n # The delimiter to use to indicate the end of a message.\n messageDelimiter = \"#\"\n\n # The escape character used to indicate the delimiter is part of the message.\n messageEscape = \"/\"\n\n # The double escape is used to replace escape characters in the messages.\n messageDoubleEscape = messageEscape + messageEscape\n\n # The escaped delimiter is used to replace delimiter characters in the messages.\n messageEscapedDelimiter = messageEscape + messageDelimiter\n\n # The regular expression used to pull out the node Id from a node Id\n # message. The node Id message is used to tell in-sockets which node Id\n # the in-socket is connected to.\n nodeIdRegex = \"MSU>>>(\\d+)<<>>%d<< [str]:\n # Adds more content into the growing message(s).\n # If one or more message has been found they will be returned.\n # Only complete messages will be returned, partial messages will wait until complete.\n messages = []\n for c in chunk:\n if self.__escaped:\n self.__data.append(c)\n self.__escaped = False\n elif c == ord(SocketConst.messageEscape):\n self.__escaped = True\n elif c == ord(SocketConst.messageDelimiter):\n messages.append(self.__data.decode())\n self.__data.clear()\n else:\n self.__data.append(c)\n if len(self.__data) > SocketConst.maximumChunkSize:\n self.__data.clear()\n self.__escaped = False\n return messages\n\n def encode(self, msg: str) -> bytes:\n # Escapes and frames the message so it can be decoded later.\n msg = msg.replace(SocketConst.messageEscape, SocketConst.messageDoubleEscape)\n msg = msg.replace(SocketConst.messageDelimiter, SocketConst.messageEscapedDelimiter)\n msg += SocketConst.messageDelimiter\n return msg.encode()\n\n\nclass InSocket:\n # This is a handler for a socket from an incoming connection to the local host.\n\n def __init__(self, conn, onConnected, onMessages, onClosed):\n # Creates a new socket for the given connection, `conn`.\n self.__conn = conn\n self.__onConnected = onConnected\n self.__onMessages = onMessages\n self.__onClosed = onClosed\n self.__keepAlive = True\n self.__defrag = MessageDefragger()\n self.__nodeId = -1\n\n thread = threading.Thread(target=self.__listen)\n thread.start()\n\n def __listen(self):\n # Asynchronously listen for messages on this socket.\n while self.__keepAlive:\n try:\n chunk = self.__conn.recv(SocketConst.receiveChunkSize)\n if chunk:\n self.__addMessageChunk(chunk)\n except socket.error as e:\n if e.errno in SocketConst.errorsToIgnore:\n break\n else:\n print(\"InSocket exception:\", e)\n break\n except Exception as e:\n print(\"InSocket exception:\", e)\n break\n self.__onClosed(self)\n\n def __addMessageChunk(self, chunk: bytearray):\n # Deals with new chunk of a message being received.\n messages = self.__defrag.decode(chunk)\n messages = self.__checkNodeId(messages)\n if messages:\n self.__onMessages(self, messages)\n\n def __checkNodeId(self, messages: [str]) -> [str]:\n # Checks if the node Id is set and looks for the first message containing the nodeId.\n if self.__nodeId < 0:\n while len(messages) > 0:\n msg = messages[0]\n messages = messages[1:]\n match = re.search(SocketConst.nodeIdRegex, msg)\n if match:\n self.__nodeId = int(match.group(1))\n self.__onConnected(self)\n break\n return messages\n\n def nodeId(self):\n # Gets the node Id for this socket.\n # Will return negative until fully connected and\n # the node Id message has been received.\n return self.__nodeId\n\n def send(self, message: str):\n # Sends a message out of this channel.\n data = self.__defrag.encode(message)\n self.__conn.send(data)\n\n def close(self):\n # Closes this socket.\n self.__keepAlive = False\n self.__conn.close()\n\n\nclass InSocketHost:\n # This handles opening a host for all incoming sockets connections.\n\n def __init__(self, url: str, useHost: bool, onConnected, onMessages, onClosed):\n # Creates a new in-socket host with the given URL to host.\n self.__url = url\n self.__useHost = useHost\n self.__onConnected = onConnected\n self.__onMessages = onMessages\n self.__onClosed = onClosed\n self.__dataLock = threading.Lock()\n self.__keepAlive = True\n self.__pending = []\n self.__sockets = {}\n\n thread = threading.Thread(target=self.__run)\n thread.start()\n\n def __run(self):\n # Asynchronous method to listen for incoming connections.\n parts = self.__url.split(\":\")\n host = parts[0] if self.__useHost else \"\"\n port = int(parts[1])\n\n while self.__keepAlive:\n # Try to setup the socket host.\n try:\n self.__serverSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.__serverSock.bind((host, port))\n except OSError as e:\n print(\"Failed to bind host:\", e)\n time.sleep(SocketConst.hostRebindDelay)\n continue\n\n # Listen for connections and accept any incoming sockets.\n self.__serverSock.listen(SocketConst.socketServerBacklog)\n while self.__keepAlive:\n try:\n conn, addr = self.__serverSock.accept()\n self.__addConnection(conn, addr)\n except socket.error as e:\n if e.errno in SocketConst.errorsToIgnore:\n # Likely `accept` can't be called, socket closed, go back to binding\n break\n else:\n print(\"InSocketHost exception:\", e)\n break\n\n def __addConnection(self, conn, addr):\n # Adds a new in-socket for the new connection.\n sock = InSocket(\n conn,\n self.__onInSocketConnected,\n self.__onInSocketMessages,\n self.__onInSocketClosed,\n )\n with self.__dataLock:\n self.__pending.append(sock)\n\n def __onInSocketConnected(self, sock):\n # Handles a socket being connected and receiving the node Id.\n nodeId = sock.nodeId()\n with self.__dataLock:\n if sock in self.__pending:\n self.__pending.remove(sock)\n #\n # TODO: If another connection to the same node Id exists, close it and take newer\n #\n self.__sockets[nodeId] = sock\n self.__onConnected(nodeId)\n\n def __onInSocketMessages(self, sock, messages: [str]):\n # Handles a socket receiving a message.\n self.__onMessages(sock.nodeId(), messages)\n\n def __onInSocketClosed(self, sock):\n # Handles a socket closing.\n nodeId = sock.nodeId()\n wasConnected = False\n with self.__dataLock:\n if nodeId in self.__sockets:\n del self.__sockets[nodeId]\n wasConnected = True\n else:\n self.__pending.remove(sock)\n if wasConnected:\n self.__onClosed(nodeId)\n\n def sendTo(self, nodeId: int, message: str) -> bool:\n # Sends a message to the given node Id. If no socket has connected for the node Id,\n # then this call has no effect. Returns true if socket by that node Id exists.\n sock = None\n with self.__dataLock:\n if nodeId in self.__sockets:\n sock = self.__sockets[nodeId]\n if sock:\n sock.send(message)\n return True\n return False\n\n def sendToAll(self, message: str) -> bool:\n # Sends the message to all the connected sockets.\n # Returns true if any socket sent a massage, false if no message was sent.\n socks = {}\n with self.__dataLock:\n socks = self.__sockets.copy()\n for sock in socks.values():\n sock.send(message)\n if socks:\n return True\n return False\n\n def close(self):\n # Closes all the in-sockets, both connected and pending.\n self.__keepAlive = False\n socks = {}\n pends = []\n with self.__dataLock:\n socks = self.__sockets.copy()\n pends = self.__pending.copy()\n for sock in socks.values():\n sock.close()\n for pend in pends:\n pend.close()\n self.__serverSock.close()\n\n\nclass OutSocket:\n # This is an outgoing socket which continues to try to connect and stay connected to a host until closed.\n\n def __init__(self, nodeId: int, targetId: int, url: str, onConnected, onMessages, onClosed):\n # Creates a new outgoing socket for this `nodeId` to connect with the\n # host `targetId` via the given `url` to the `targetId`.\n self.__nodeId = nodeId\n self.__targetId = targetId\n self.__onConnected = onConnected\n self.__onMessages = onMessages\n self.__onClosed = onClosed\n self.__dataLock = threading.Lock()\n self.__keepAlive = True\n self.__defrag = MessageDefragger()\n self.__pending = None\n self.__sock = None\n\n parts = url.split(\":\")\n host = parts[0]\n port = int(parts[1])\n thread = threading.Thread(target=self.__run, args=(host, port))\n thread.start()\n\n def __run(self, host: str, port: str):\n # Asynchronously attempt to connect to the host until a connection is made or closed.\n # If a connection is made this will call `listen` so that if the connection is lost\n # then it will drop back to this method to continue trying to reconnect.\n while self.__keepAlive:\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n with self.__dataLock:\n self.__pending = sock\n\n sock.settimeout(SocketConst.connectTimeout)\n sock.connect((host, port))\n sock.settimeout(None)\n\n self.__socketConnected(sock)\n self.__listen()\n except socket.timeout:\n # Socket failed to connect in specified timeout, check \"keep alive\" and try again.\n self.__closeConnection()\n continue\n except socket.error as e:\n if e.errno in SocketConst.errorsToIgnore:\n # Attempt to connect/reconnect to host again.\n pass\n else:\n print(\"OutSocket expection:\", e)\n\n # Failed to connect or lost connection, wait a little bit then try again.\n self.__closeConnection()\n if self.__keepAlive:\n time.sleep(SocketConst.reconnectDelay)\n continue\n self.__closeConnection()\n\n def __listen(self):\n # Listens to the socket to receive messages.\n while self.__keepAlive:\n chunk = self.__sock.recv(SocketConst.receiveChunkSize)\n if chunk:\n self.__addMessageChunk(chunk)\n\n def __socketConnected(self, sock):\n # The socket has been connected, prepare to start listening.\n # Sends the node Id message to the host to let it know who connected to it.\n with self.__dataLock:\n self.__pending = None\n self.__sock = sock\n self.sendTo(SocketConst.nodeIdMessage % (self.__nodeId))\n self.__onConnected(self.__targetId)\n\n def __addMessageChunk(self, chunk: bytes):\n # Adds a new chunk of a message to the growing messages.\n # Sends any messages which have been creates.\n messages = self.__defrag.decode(chunk)\n self.__onMessages(self.__targetId, messages)\n\n def __closeConnection(self):\n # The connection has been or is closing, update the state of the connection.\n closed = False\n if self.__sock:\n closed = True\n self.__pending = None\n self.__sock = None\n if closed:\n self.__onClosed(self.__targetId)\n\n def sendTo(self, message: str) -> bool:\n # Sends a message to the connected socket.\n # If the socket is not connected then the message is not sent.\n if message:\n sock = None\n with self.__dataLock:\n if self.__sock:\n sock = self.__sock\n if sock:\n data = self.__defrag.encode(message)\n sock.send(data)\n return True\n\n def close(self):\n # Closes this out-socket connection.\n self.__keepAlive = False\n if self.__pending:\n self.__pending.close()\n if self.__sock:\n self.__sock.close()\n\n\nclass SocketManager:\n # A tool for setting up and maintaining several connections\n # for processes identified with an integer, the node Id.\n\n def __init__(self, nodeId: int, onConnected, onMessage, onClosed, verbose: bool = False):\n # Creates a new socket manager for the process with the given `nodeId`.\n # The given callback methods maybe set to `None` to not have it callback.\n # The `onConnected` and `onClosed` is called when a connection has been made,\n # however an outgoing connection will automatically attempt to reconnect. The point\n # of those two callbacks is to indicate when a message can be sent or not.\n # The callback methods are called asynchronously and multiple may be called\n # at the same time. If you need to synchronize then you must add a lock.\n self.__nodeId = nodeId\n self.__outSockets = {}\n self.__onConnected = onConnected\n self.__onMessage = onMessage\n self.__onClosed = onClosed\n self.__inSocketHost = None\n self.__verbose = verbose\n\n def startFullyConnected(self, socketURLs: [str], useHost: bool = True):\n # Starts a fully connected group of nodes. The given `socketURLs` contains\n # the URLs for the node Id where the node Id is the index of the URL in the list.\n # This will start a socket host for this manager's node Id, the host will be contacted by all\n # higher value node Id processes. It will attempt to connect to all lower node Id processes.\n self.startSocketHost(socketURLs[self.__nodeId], useHost)\n for targetId in range(0, self.__nodeId):\n self.connectTo(targetId, socketURLs[targetId])\n\n def startSocketHost(self, url: str, useHost: bool = True):\n # Starts a socket host for this manager's node Id and the given URL. If a socket host\n # already has been started the older socket host will be closed.\n if self.__inSocketHost:\n self.__inSocketHost.close()\n self.__inSocketHost = InSocketHost(\n url,\n useHost,\n self.__onInnerConnected,\n self.__onInnerMessages,\n self.__onInnerClosed,\n )\n\n def connectTo(self, targetId: int, url: str):\n # Connects this manager to another node which has a socket hosted.\n # If the other node hasn't started the host yet, this will continue to attempt to connect\n # until it has been connected or the manager is closed.\n outSock = OutSocket(\n self.__nodeId,\n targetId,\n url,\n self.__onInnerConnected,\n self.__onInnerMessages,\n self.__onInnerClosed,\n )\n self.__outSockets[targetId] = outSock\n\n def __onInnerConnected(self, nodeId: int):\n # Handles a socket being connected.\n if self.__onConnected:\n self.__onConnected(nodeId)\n\n def __onInnerMessages(self, nodeId: int, messages: [str]):\n # Handles a socket receiving zero or more message.\n if self.__onMessage:\n for message in messages:\n if self.__verbose:\n print(\"Received(%d): %s\" % (nodeId, message))\n self.__onMessage(nodeId, message)\n\n def __onInnerClosed(self, nodeId: int):\n # Handles a socket being closed.\n if self.__onClosed:\n self.__onClosed(nodeId)\n\n def sendToAll(self, message: str) -> bool:\n # Sends a message to all sockets which have been connected.\n # Returns true if one or more messages were sent, false if no message was sent out.\n if self.__verbose:\n print(\"sendToAll: %s\" % (message))\n anySent = False\n if self.__inSocketHost.sendToAll(message):\n anySent = True\n for sock in self.__outSockets.values():\n if sock.sendTo(message):\n anySent = True\n return anySent\n\n def sendTo(self, nodeId: int, message: str) -> bool:\n # Sends a message to the process with the given node Id.\n # Returns true if the message was sent and false if that node Id is not connected.\n if self.__verbose:\n print(\"sendTo(%d): %s\" % (nodeId, message))\n if nodeId == self.__nodeId:\n return False\n elif nodeId < self.__nodeId:\n if nodeId in self.__outSockets:\n return self.__outSockets[nodeId].sendTo(message)\n return False\n else:\n return self.__inSocketHost.sendTo(nodeId, message)\n\n def close(self):\n # Closes and cleanup all the sockets being used by this manager.\n if self.__inSocketHost:\n self.__inSocketHost.close()\n for sock in self.__outSockets.values():\n sock.close()\n","sub_path":"Project3/Part2/sockets.py","file_name":"sockets.py","file_ext":"py","file_size_in_byte":20561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"535524297","text":"from AbstractTask import AbstractTask\nimport configparser\nimport threading\nimport re\nimport json\n\nclass CsvToSenMLParse(AbstractTask):\n timestampField = 0\n sampledata = \"\"\n useMsgField = 0\n schemaMap = {}\n\n def setup(self):\n lock = threading.Lock()\n yield from lock\n config = configparser.ConfigParser()\n schemaFilePath = config.get(\"PARSE.CSV_SCHEMA_WITH_ANNOTATEDFIELDS_FILEPATH\")\n self.useMsgField = config.get(\"PARSE.CSV_SENML_USE_MSG_FIELD\")\n\n try:\n fo = open(schemaFilePath,\"rw+\")\n\n column = fo.readline()\n unit = fo.readline()\n type = fo.readline()\n\n columns = re.split(\",\",column)\n units = re.split(\",\",unit)\n types = re.split(\",\",type)\n\n for i in range(0,len(columns)):\n if(columns[i] == \"timestamp\"):\n self.timestampField = i\n\n self.schemaMap[i] = columns[i]+','+units[i]+','+types[i]\n except(IOError):\n print(\"Error\")\n\n sampledata = \"024BE2DFD1B98AF1EA941DEDA63A15CB,9F5FE566E3EE57B85B723B71E370154C,2013-01-14 03:57:00,2013-01-14 04:23:00,200,10,-73.953178,40.776016,-73.779190,40.645145,CRD,52.00,0.00,0.50,13.00,4.80,70.30,uber,sam,Houston\";\n\n lock.release()\n\n\n def doTaskLogic(self):\n obj = {}\n jsonArray = []\n\n try:\n if(self.useMsgField == -1):\n m = self.sampledata\n else:\n m = str(map[AbstractTask.DEFAULT_KEY])\n\n val = re.split(',',m)\n finalSenML = {}\n finalSenML[\"bt\"] = val[self.timestampField]\n\n for i in range(len(self.schemaMap)):\n sch = re.split(',',self.schemaMap.get(i))\n if(i != self.timestampField):\n obj[\"n\"] = sch[0]\n obj[sch[2]] = val[i]\n obj[\"u\"] = sch[1]\n jsonArray += obj\n\n\n finalSenML[\"e\"] = jsonArray\n self.setLastResult(str(finalSenML))\n return None\n\n except():\n print(\"Error\")\n\n\n\n\n\n\n\n","sub_path":"main/cofee_fog_service/fog_user_data/tasks_library/RiotbenchTasks/parse/CsvToSenMLParse.py","file_name":"CsvToSenMLParse.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"155578290","text":"import unittest\nimport json\nimport os\nfrom src.role.WorkerFunctions import store, PATH_TO_CROSSWALKS\nfrom src.base.Node import Node\n\n\nclass TestWorkerFunctions(unittest.TestCase):\n\n def setUp(self):\n self.remove_file()\n\n def tearDown(self):\n self.remove_file()\n\n def test_store_zero_crosswalks(self):\n store([])\n with open(PATH_TO_CROSSWALKS, 'r') as f:\n data = json.load(f)\n self.assertTrue(len(data['crosswalks']) == 0)\n\n def test_store_in_two_steps_crosswalks(self):\n crosswalks = [Node(47.0, 8.0), Node(47.1, 8.1)]\n store(crosswalks)\n store(crosswalks)\n with open(PATH_TO_CROSSWALKS, 'r') as f:\n data = json.load(f)\n self.assertTrue(len(data['crosswalks']) == 4)\n\n def test_store_two_crosswalks(self):\n crosswalks = [Node(47.0, 8.0), Node(47.1, 8.1)]\n store(crosswalks)\n with open(PATH_TO_CROSSWALKS, 'r') as f:\n data = json.load(f)\n self.assertTrue(len(data['crosswalks']) == 2)\n\n @staticmethod\n def remove_file():\n if os.path.exists(PATH_TO_CROSSWALKS):\n os.remove(PATH_TO_CROSSWALKS)\n","sub_path":"tests/role/testWorkerFunctions.py","file_name":"testWorkerFunctions.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"556757285","text":"from __future__ import print_function\nimport sys\nimport cv2\nimport numpy as np\n \ndef main():\n #capture from camera at location 0\n\n capL = cv2.VideoCapture(int(sys.argv[1]))\n capL.set(3, 160)\n capL.set(4, 120)\n\n while True:\n retL, imgL = capL.read()\n cv2.imshow(\"input\", imgL)\n\n key = cv2.waitKey(10)\n if key == 27:\n break\n\n cv2.destroyAllWindows()\n cv2.VideoCapture(int(sys.argv[1])).release()\n\nif __name__ == '__main__':\n main()\n","sub_path":"project/runOnPi/opencv_usbtest.py","file_name":"opencv_usbtest.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"363137422","text":"__author__ = 'sunghyo.jung'\nfrom collections import defaultdict\nn, m = map(int, input().split())\na = defaultdict(list)\nb = defaultdict(list)\nfor i in range(n):\n v = input()\n a[v].append(i + 1)\n\nfor i in range(m):\n v = input()\n if v in a:\n for e in a[v]:\n print(e, end=' ')\n print()\n else:\n print(-1)\n","sub_path":"domains/python/py-collections/defaultdict-tutorial_sunghyo.jung.py","file_name":"defaultdict-tutorial_sunghyo.jung.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"284438962","text":"\n\nfrom xai.brain.wordbase.nouns._satchel import _SATCHEL\n\n#calss header\nclass _SATCHELS(_SATCHEL, ):\n\tdef __init__(self,): \n\t\t_SATCHEL.__init__(self)\n\t\tself.name = \"SATCHELS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"satchel\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_satchels.py","file_name":"_satchels.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"174577829","text":"'''\nhttps://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/\n'''\n\nclass Solution:\n def findDisappearedNumbers(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n if(not nums):\n return []\n res = []\n size = len(nums)\n nums = set(nums)\n for i in range(size):\n if(i+1 not in nums):\n res.append(i+1)\n return res\n ","sub_path":"LeetCode/1. Easy/Find All Numbers Disappeared in an Array.py","file_name":"Find All Numbers Disappeared in an Array.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"221627107","text":"from PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\n\nfrom misc.callback import callback\n\nfrom osu.local.replay.replayIO import ReplayIO\nfrom osu.local.beatmap.beatmapIO import BeatmapIO\n\nfrom gui.objects.layer.layers.std.hitobject_outline_layer import HitobjectOutlineLayer\nfrom gui.objects.layer.layers.std.replay_cursor_layer import StdReplayCursorLayer\n\nfrom gui.objects.scene import Scene\nfrom gui.objects.display import Display\nfrom gui.objects.layer.layer_manager import LayerManager\n\n\nclass StdReplayTest(QMainWindow):\n\n title = 'Replay Test'\n left = 100\n top = 100\n width = 1080\n height = 720\n\n def __init__(self, app):\n QMainWindow.__init__(self)\n\n self.display = Display()\n self.display.setFocusPolicy(Qt.NoFocus)\n\n self.beatmap = BeatmapIO.open_beatmap('unit_tests\\\\maps\\\\Within Temptation - The Unforgiving (Armin) [Marathon].osu')\n self.replay = ReplayIO.open_replay('unit_tests\\\\replays\\\\Toy - Within Temptation - The Unforgiving [Marathon] (2018-02-06) Osu.osr')\n\n self.layer_manager = LayerManager()\n self.layer_manager.add_layer('Hitobject outline', HitobjectOutlineLayer(self.beatmap, self.time_browse_test))\n self.layer_manager.add_layer('Replay cursor', StdReplayCursorLayer(self.replay, self.time_browse_test))\n\n self.display.setScene(self.layer_manager)\n\n self.setCentralWidget(self.display)\n self.setWindowTitle(StdReplayTest.title)\n self.setGeometry(0, 0, self.display.width(), self.display.height())\n self.show()\n\n self.time_browse_test(app)\n \n \n @callback\n def time_browse_test(self, app):\n print('time_browse_test')\n for t in range(0, 40000, 10):\n self.time_browse_test.emit(t)\n app.processEvents() ","sub_path":"unit_tests/std_replay_test.py","file_name":"std_replay_test.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"545084929","text":"# --- Python Imports ---\r\nimport numpy as np\r\n\r\n# --- Internal Imports ---\r\nfrom cie.fem.numeric import Integrator\r\n\r\n# ---------------------------------------------------------\r\ndef squaredSolutionErrorFunctional( solution, referenceSolution, model, integrationOrder=None ):\r\n '''\r\n Integrates the squared difference of the specified solution and a reference solution over the space domain.\r\n INTEGRATE{ (u_ref - u)^2 }dx\r\n\r\n Arguments:\r\n solution : solution to compare the reference solution to\r\n referenceSolution : desired solution\r\n model : FEModel\r\n [integrationOrder] : optional, default will use the double the first elements's integration order in the model\r\n '''\r\n # Initialize\r\n functionalValue = 0.0\r\n\r\n integrate = None\r\n if integrationOrder is None:\r\n integrate = Integrator( 2 * model.elements[0].integrator.polynomialOrder + 1 )\r\n else:\r\n integrate = Integrator( integrationOrder )\r\n \r\n for element in model.elements:\r\n localFunctional = lambda x: element( referenceSolution[element.DoFs] - solution[element.DoFs], x )**2\r\n functionalValue += integrate( localFunctional, element.domain )\r\n\r\n return functionalValue","sub_path":"libraries/fem/python/modules/fem/optcontrol/functional.py","file_name":"functional.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"629552197","text":"from module.testsuite.benchmark.l2l3.rfc3918.rfc3918_command import Rfc3918Command\nfrom framework.rom import meta\nfrom framework.smart_scripter.control_commands import *\nfrom framework.smart_scripter import smart_scripter\nfrom .group_command import MulticastGroupCapacityGroupCommand\nfrom module.testsuite.suite_base.enum_types import *\nfrom .write_db_command import MulticastGroupCapacityWriteDbCommand\n\n\n@meta.rom(description='Rfc3918 Multicast Group Capacity command')\nclass MulticastGroupCapacityCommand(Rfc3918Command):\n\n def _create_test_loops(self):\n super()._create_test_loops()\n self.iteration_load_size_command = self._build_iteration_load_size_command()\n self.iteration_load_size_command.command = self\n self.iteration_group_count_command = self._build_iteration_search_group_count_command()\n self.iteration_group_count_command.command = self\n\n def _create_test_sequence(self):\n self.multicast_join_command = self._build_join_group_command()\n self.commands.append(self.multicast_join_command)\n\n self.multicast_join_delay_command = self._build_join_delay_command()\n self.commands.append(self.multicast_join_delay_command)\n\n self.clear_all_results_command = self._build_clear_all_results_command()\n self.commands.append(self.clear_all_results_command)\n\n self.start_traffic_command = self._build_start_traffic_command()\n self.commands.append(self.start_traffic_command)\n\n self.wait_traffic_stop_command = self._build_wait_for_stop_command()\n self.commands.append(self.wait_traffic_stop_command)\n\n # delay before leave group command\n self.delay_after_transmit_command = self._build_delay_after_transmit_command()\n self.commands.append(self.delay_after_transmit_command)\n\n self.multicast_leave_command = self._build_leave_group_command()\n self.commands.append(self.multicast_leave_command)\n\n self.multicast_leave_delay_command = self._build_leave_delay_command()\n self.commands.append(self.multicast_leave_delay_command)\n\n self.write_iteration_result_command = self._build_write_iteration_result_command()\n self.commands.append(self.write_iteration_result_command)\n\n for cmd in self.commands:\n cmd.command = self\n\n def publish_internal_commands(self):\n if smart_scripter.SmartScripter.instance().State != smart_scripter.EnumSmartScripterState.IDLE:\n log.Logger.CL.Error('SS is not idle')\n return False\n ss_global_group = smart_scripter.SmartScripter.instance().get_global_group()\n\n # multicast group count\n multicast_group_loop = LoopCommand()\n multicast_group_loop.Name = 'Search Multicast Group Capacity Loop'\n multicast_group_loop.LoopCount = -1\n multicast_group_loop.append_command(self.iteration_group_count_command)\n multicast_group_loop.append_commands(self.commands)\n\n # load_loop\n load_loop = LoopCommand()\n load_loop.Name = 'Load Loop' # ? need?\n load_loop.LoopCount = -1\n load_loop.append_command(self.iteration_load_size_command)\n load_loop.append_command(multicast_group_loop)\n\n # frame_loop\n frame_loop = LoopCommand()\n frame_loop.Name = 'Frame Size Loop'\n frame_loop.append_command(self.iteration_frame_size_command)\n frame_loop.append_command(load_loop)\n\n # trial_loop\n trial_loop = LoopCommand()\n trial_loop.Name = 'Trial Loop'\n trial_loop.append_command(self.iteration_trial_command)\n trial_loop.append_command(frame_loop)\n\n group_command = MulticastGroupCapacityGroupCommand()\n group_command.Name = 'RFC3918: Multicast Group Capacity Test'\n group_command.append_command(self.test_start_command)\n group_command.append_command(self.set_duration_command)\n group_command.append_command(self.verify_link_delay)\n group_command.append_command(self.if_verify_link_command)\n group_command.append_command(trial_loop)\n group_command.append_command(self.test_stop_command)\n group_command.establish_relation(self)\n\n ss_global_group.append_command(group_command)\n return True\n\n def _build_write_iteration_result_command(self):\n command = MulticastGroupCapacityWriteDbCommand()\n command.Name = 'Save Results'\n self._populate_write_iteration_result_command(command)\n return command\n\n def execute_init_group_count_iteration_command_fun(self):\n self._group_count_index = 0\n if self.iteration_group_count_command:\n self.iteration_group_count_command.iteration = self._group_count_index\n return SSExecutionEnum.EXECUTE_NONE\n\n def execute_prev_group_count_iteration_command_fun(self):\n pass\n\n def execute_post_group_count_iteration_command_fun(self):\n if self.iteration_group_count_command and self.iteration_group_count_command.tput_found:\n return SSExecutionEnum.EXECUTE_BREAK\n return SSExecutionEnum.EXECUTE_NONE\n\n def execute_end_group_count_iteration_command_fun(self):\n self._group_count_index += 1\n self.iteration_group_count_command.iteration = self._group_count_index\n return SSExecutionEnum.EXECUTE_NONE","sub_path":"CL/module/testsuite/benchmark/l2l3/rfc3918/multicast_group_capacity/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":5308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"390339833","text":"import os\nimport urllib2\n\nfrom PIL import Image\n\nfrom common_libs import files\n\n\n# Constants\n#=======================================================================================================================\ni_WIDTH = 320\ndf_ASPECT_RATIOS = {\n u'gbo': 1.1111, # 160/144\n u'gba-crt': 1.5000, # 240/160\n u'gbc': 1.1111, # 160/144\n u'lnx': 1.5686, # 160/102\n u'ngp': 1.0526, # 160/152\n u'ngc': 1.0526, # 160/152\n }\n\n\n# Classes\n#=======================================================================================================================\nclass Downloader(object):\n def __init__(self):\n pass\n\n def _download(self, pu_url, pu_local_path):\n \"\"\"\n\n :param pu_url:\n :param pu_path:\n :return:\n \"\"\"\n b_download = False\n\n try:\n o_data = urllib2.urlopen(pu_url).read()\n except (urllib2.HTTPError, AttributeError):\n o_data = None\n\n if o_data is not None:\n with open(pu_local_path, 'wb') as o_file:\n o_data = urllib2.urlopen(pu_url).read()\n o_file.write(o_data)\n b_download = True\n\n return b_download\n\n def download_images(self, po_dir, po_romdb_version):\n \"\"\"\n Function to download the image(s) from ROMdb.\n\n :param po_dir: Destination directory for the downloaded images.\n :type po_dir: common_libs.files.FilePath\n\n :param po_romdb_version: ROMdb object.\n :type po_romdb_version: romdb_tools.libs.romdb_data.Version\n\n :return:\n \"\"\"\n\n # Download of the image\n # ----------------------\n o_local_original_file = files.FilePath(po_dir.u_path, u'%s.png' % po_romdb_version.u_romset_crc32)\n b_dl = self._download(po_romdb_version.u_screenshot_ingame, o_local_original_file.u_path)\n\n # Resizing of the image\n # ----------------------\n if not b_dl:\n u_img = u''\n else:\n # Resizing preparation\n u_platform = po_romdb_version.u_dat_name.partition(u'_')[0]\n f_ratio = df_ASPECT_RATIOS.get(u_platform, 1.333)\n i_height = int(i_WIDTH / f_ratio)\n\n # Resizing\n o_image_src = Image.open(o_local_original_file.u_path)\n o_image_dst = o_image_src.resize((i_WIDTH, i_height), Image.BICUBIC)\n o_image_dst = o_image_dst.convert('RGB')\n\n # Saving to disc and removing the original one\n o_local_modified_file = files.FilePath(po_dir.u_path, u'%s.jpg' % po_romdb_version.u_romset_crc32)\n o_image_dst.save(o_local_modified_file.u_path)\n os.remove(o_local_original_file.u_path)\n u_img = o_local_modified_file.u_path\n\n return b_dl, u_img\n\n","sub_path":"libs/romdb_tools_v2/libs/download_default.py","file_name":"download_default.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"194496381","text":"import pickle\n\ndef cause_projection(civil=False):\n def _fix_cause_tree(cause_tree):\n cause_tree['刑事']['破坏社会主义市场经济秩序罪']['危害税收征管罪'].pop('虚开增值税专用发票、用于骗取出口退税、抵押税款发票罪')\n cause_tree['刑事']['破坏社会主义市场经济秩序罪']['危害税收征管罪']['虚开增值税专用发票、用于骗取出口退税、抵扣税款发票罪'] = {}\n return cause_tree\n with open('projection.pkl', 'rb') as f:\n cause2index, cause_tree = pickle.load(f)\n if not civil:\n cause_tree = _fix_cause_tree(cause_tree)\n return cause_tree\n cause2index, cause_tree = pickle.load(f)\n return cause_tree\n\ndef tree_find_trace(tree, key):\n def _tree_find_trace(tree, key, box):\n if key in tree:\n box.append(key)\n return True\n have = False\n for node in tree:\n if tree[node]:\n if _tree_find_trace(tree[node], key, box):\n box.append(node)\n have = True\n return have\n box = []\n _tree_find_trace(tree, key, box)\n box.reverse()\n return box\n\ndef tree_find_relevant_nodes(tree, leaves):\n relevant_nodes = []\n for leaf in leaves:\n trace = tree_find_trace(tree, leaf)\n relevant_nodes += trace\n relevant_nodes = set(relevant_nodes)\n return relevant_nodes\n\n\nif __name__ == '__main__':\n print(cause_projection())","sub_path":"cause_loader.py","file_name":"cause_loader.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"526497327","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nimport requests\nimport uuid\nimport docker\nimport os\nimport subprocess\nimport sys\nimport json\nimport click\nimport zipfile\nfrom base64 import b64encode, b64decode\nfrom hashlib import sha256\nfrom time import time\nimport fnmatch\nimport inspect\nfrom hmac import HMAC\nfrom shutil import copyfile\nfrom enum import Enum\nfrom distutils.util import strtobool\nfrom dotenv import load_dotenv\n\ndotenv_path = os.path.join(os.getcwd(), '.env')\nload_dotenv(dotenv_path)\n\nif sys.version_info.major >= 3:\n from urllib.parse import quote, urlencode\nelse:\n from urllib import quote, urlencode\n\n#print(\"Python Version: \" + sys.version)\n\n\nclass Output:\n\n def info(self, text):\n click.secho(text, fg='yellow')\n\n def error(self, text):\n click.secho(text, fg='red')\n\n def header(self, text):\n click.secho(\"======== {0} ========\".format(text).upper(), fg='white')\n\n def footer(self, text):\n self.info(text.upper())\n self.line()\n\n def procout(self, text):\n click.secho(text, dim=True)\n\n def line(self):\n click.secho(\"\")\n\n\nclass EnvVars:\n def __init__(self, output):\n self.output = output\n self.checked = False\n\n def check(self):\n if not self.checked:\n try:\n self.IOTHUB_NAME = os.environ[\"IOTHUB_NAME\"]\n self.IOTHUB_KEY = os.environ[\"IOTHUB_KEY\"]\n self.DEVICE_CONNECTION_STRING = os.environ[\"DEVICE_CONNECTION_STRING\"]\n self.EDGE_DEVICE_ID = os.environ[\"EDGE_DEVICE_ID\"]\n self.RUNTIME_HOST_NAME = os.environ[\"RUNTIME_HOST_NAME\"]\n self.ACTIVE_MODULES = os.environ[\"ACTIVE_MODULES\"]\n self.ACTIVE_DOCKER_DIRS = os.environ[\"ACTIVE_DOCKER_DIRS\"]\n self.CONTAINER_REGISTRY_SERVER = os.environ[\"CONTAINER_REGISTRY_SERVER\"]\n self.CONTAINER_REGISTRY_USERNAME = os.environ[\"CONTAINER_REGISTRY_USERNAME\"]\n self.CONTAINER_REGISTRY_PASSWORD = os.environ[\"CONTAINER_REGISTRY_PASSWORD\"]\n self.IOTHUB_POLICY_NAME = os.environ[\"IOTHUB_POLICY_NAME\"]\n self.CONTAINER_TAG = os.environ[\"CONTAINER_TAG\"]\n self.RUNTIME_TAG = os.environ[\"RUNTIME_TAG\"]\n self.RUNTIME_VERBOSITY = os.environ[\"RUNTIME_VERBOSITY\"]\n self.RUNTIME_HOME_DIR = os.environ[\"RUNTIME_HOME_DIR\"]\n self.MODULES_CONFIG_FILE = os.environ[\"MODULES_CONFIG_FILE\"]\n self.RUNTIME_CONFIG_FILE = os.environ[\"RUNTIME_CONFIG_FILE\"]\n self.LOGS_PATH = os.environ[\"LOGS_PATH\"]\n self.MODULES_PATH = os.environ[\"MODULES_PATH\"]\n self.IOT_REST_API_VERSION = os.environ[\"IOT_REST_API_VERSION\"]\n self.DOTNET_VERBOSITY = os.environ[\"DOTNET_VERBOSITY\"]\n self.LOGS_CMD = os.environ[\"LOGS_CMD\"]\n if \"DOCKER_HOST\" in os.environ:\n self.DOCKER_HOST = os.environ[\"DOCKER_HOST\"]\n else:\n self.DOCKER_HOST = None\n except Exception as e:\n self.output.error(\n \"Environment variables not configured correctly. Run `iotedgedev project --create [name]` to create a new project with sample .env file. Please see README for variable configuration options. Tip: You might just need to restart your command prompt to refresh your Environment Variables.\")\n self.output.error(\"Variable that caused exception: \" + str(e))\n sys.exit(-1)\n\n self.checked = True\n\n\nclass Utility:\n def __init__(self, envvars, output):\n self.envvars = envvars\n self.envvars.check()\n self.output = output\n self.config_set = False\n\n def exe_proc(self, params, shell=False):\n proc = subprocess.Popen(\n params, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell)\n\n stdout_data, stderr_data = proc.communicate()\n if stdout_data != \"\":\n self.output.procout(self.decode(stdout_data))\n\n if proc.returncode != 0:\n self.output.error(self.decode(stderr_data))\n sys.exit()\n\n def find_files(self, directory, pattern):\n # find all files in directory that match the pattern.\n for root, dirs, files in os.walk(directory):\n for basename in files:\n if fnmatch.fnmatch(basename, pattern):\n filename = os.path.join(root, basename)\n yield filename\n\n def get_iot_hub_sas_token(self, uri, key, policy_name, expiry=3600):\n ttl = time() + expiry\n sign_key = \"%s\\n%d\" % ((quote(uri)), int(ttl))\n signature = b64encode(\n HMAC(b64decode(key), sign_key.encode(\"utf-8\"), sha256).digest())\n\n rawtoken = {\n \"sr\": uri,\n \"sig\": signature,\n \"se\": str(int(ttl))\n }\n\n if policy_name is not None:\n rawtoken[\"skn\"] = policy_name\n\n return \"SharedAccessSignature \" + urlencode(rawtoken)\n\n def get_file_contents(self, file):\n with open(file, \"r\") as file:\n return file.read()\n\n def decode(self, val):\n return val.decode(\"utf-8\").strip()\n\n def get_config_files(self):\n config_dir = \"config\"\n\n # Create config dir if it doesn't exist\n if not os.path.exists(config_dir):\n os.makedirs(config_dir)\n\n # Get all config files in \\config dir.\n return [os.path.join(config_dir, f) for f in os.listdir(\n config_dir) if f.endswith(\".json\")]\n\n def get_active_modules(self):\n return [module.strip()\n for module in self.envvars.ACTIVE_MODULES.split(\",\") if module]\n\n def get_modules_in_config(self, moduleType):\n modules_config = json.load(open(self.envvars.MODULES_CONFIG_FILE))\n\n props = modules_config[\"moduleContent\"][\"$edgeAgent\"][\"properties.desired\"]\n\n system_modules = props[\"systemModules\"]\n user_modules = props[\"modules\"]\n\n if moduleType == ModuleType.System:\n return system_modules\n elif moduleType == ModuleType.User:\n return user_modules\n else:\n return_modules = {}\n return_modules.update(system_modules)\n return_modules.update(user_modules)\n return return_modules\n\n def set_config(self, force=False):\n\n if not self.config_set or force:\n self.envvars.check()\n self.output.header(\"PROCESSING CONFIG FILES\")\n\n build_config_dir = os.path.join(\"build\", \"config\")\n\n # Create config dir if it doesn't exist\n if not os.path.exists(build_config_dir):\n os.makedirs(build_config_dir)\n\n config_files = self.get_config_files()\n\n if len(config_files) == 0:\n self.output.info(\n \"Unable to find config files in config directory\")\n sys.exit()\n\n # Expand envars and rewrite to \\build\\config\n for config_file in config_files:\n\n build_config_file = os.path.join(\n build_config_dir, os.path.basename(config_file))\n\n self.output.info(\"Expanding '{0}' to '{1}'\".format(\n config_file, build_config_file))\n\n config_file_expanded = os.path.expandvars(\n self.get_file_contents(config_file))\n\n with open(build_config_file, \"w\") as config_file_build:\n config_file_build.write(config_file_expanded)\n\n self.output.line()\n\n self.config_set = True\n\n\nclass Project:\n def __init__(self, output):\n self.output = output\n\n def create(self, name):\n self.output.header(\"CREATING AZURE IOT EDGE PROJECT\")\n\n try:\n template_zip = os.path.join(os.path.split(\n __file__)[0], \"template\", \"template.zip\")\n except Exception as e:\n self.output.error(\"Error while trying to load template.zip\")\n self.output.error(e)\n\n if name == \".\":\n name = \"\"\n\n zipf = zipfile.ZipFile(template_zip)\n zipf.extractall(name)\n\n self.output.footer(\"Azure IoT Edge project created\")\n\n\nclass Runtime:\n def __init__(self, envvars, utility, output, dock):\n self.envvars = envvars\n self.envvars.check()\n self.utility = utility\n self.utility.set_config()\n self.dock = dock\n self.output = output\n\n def start(self):\n self.output.header(\"Starting Edge Runtime\")\n self.utility.exe_proc([\"iotedgectl\", \"--verbose\",\n self.envvars.RUNTIME_VERBOSITY, \"start\"])\n\n def stop(self):\n self.output.header(\"Stopping Edge Runtime\")\n self.utility.exe_proc([\"iotedgectl\", \"--verbose\",\n self.envvars.RUNTIME_VERBOSITY, \"stop\"])\n\n def setup(self):\n self.output.header(\"Setting Up Edge Runtime\")\n self.utility.exe_proc([\"iotedgectl\", \"--verbose\", self.envvars.RUNTIME_VERBOSITY,\n \"setup\", \"--config-file\", self.envvars.RUNTIME_CONFIG_FILE])\n\n def status(self):\n self.output.header(\"Getting Edge Runtime Status\")\n self.utility.exe_proc([\"iotedgectl\", \"--verbose\", self.envvars.RUNTIME_VERBOSITY,\n \"status\"])\n\n def restart(self):\n self.stop()\n self.dock.remove_modules()\n self.setup()\n self.start()\n\n\nclass Modules:\n def __init__(self, envvars, utility, output, dock):\n self.envvars = envvars\n self.envvars.check()\n self.utility = utility\n self.utility.set_config()\n self.output = output\n self.dock = dock\n self.dock.init_registry()\n\n def build(self):\n self.output.header(\"BUILDING MODULES\")\n\n # Get all the modules to build as specified in config.\n modules_to_process = self.utility.get_active_modules()\n\n for module in os.listdir(self.envvars.MODULES_PATH):\n\n if len(\n modules_to_process) == 0 or modules_to_process[0] == \"*\" or module in modules_to_process:\n\n module_dir = os.path.join(self.envvars.MODULES_PATH, module)\n\n self.output.info(\"BUILDING MODULE: {0}\".format(module_dir))\n\n # Find first proj file in module dir and use it.\n project_files = [os.path.join(module_dir, f) for f in os.listdir(\n module_dir) if f.endswith(\"proj\")]\n\n if len(project_files) == 0:\n self.output.error(\"No project file found for module.\")\n continue\n\n self.utility.exe_proc([\"dotnet\", \"build\", project_files[0],\n \"-v\", self.envvars.DOTNET_VERBOSITY])\n\n # Get all docker files in project\n docker_files = self.utility.find_files(\n module_dir, \"Dockerfile*\")\n\n # Filter by Docker Dirs in envvars\n docker_dirs_process = [docker_dir.strip()\n for docker_dir in self.envvars.ACTIVE_DOCKER_DIRS.split(\",\") if docker_dir]\n\n # Process each Dockerfile found\n for docker_file in docker_files:\n\n docker_file_parent_folder = os.path.basename(\n os.path.dirname(docker_file))\n\n if len(\n docker_dirs_process) == 0 or docker_dirs_process[0] == \"*\" or docker_file_parent_folder in docker_dirs_process:\n\n self.output.info(\n \"PROCESSING DOCKER FILE: \" + docker_file)\n\n docker_file_name = os.path.basename(docker_file)\n\n # assume /Docker/{runtime}/Dockerfile folder structure\n # image name will be the same as the module folder name, filter-module\n # tag will be {runtime}{ext}{container_tag}, i.e. linux-x64-debug-jong\n # runtime is the Dockerfile immediate parent folder name\n # ext is Dockerfile extension for example with Dockerfile.debug, debug is the mod\n # CONTAINER_TAG is env var\n\n # i.e. when found: filter-module/Docker/linux-x64/Dockerfile.debug and CONTAINER_TAG = jong\n # we'll get: filtermodule:linux-x64-debug-jong\n\n runtime = os.path.basename(\n os.path.dirname(docker_file))\n ext = \"\" if os.path.splitext(docker_file)[\n 1] == \"\" else \"-\" + os.path.splitext(docker_file)[1][1:]\n container_tag = \"\" if self.envvars.CONTAINER_TAG == \"\" else \"-\" + \\\n self.envvars.CONTAINER_TAG\n\n tag_name = runtime + ext + container_tag\n\n # construct the build output path\n build_path = os.path.join(\n os.getcwd(), \"build\", \"modules\", module, runtime)\n if not os.path.exists(build_path):\n os.makedirs(build_path)\n\n # dotnet publish\n self.output.info(\n \"PUBLISHING PROJECT: \" + project_files[0])\n\n self.utility.exe_proc([\"dotnet\", \"publish\", project_files[0], \"-f\", \"netcoreapp2.0\",\n \"-o\", build_path, \"-v\", self.envvars.DOTNET_VERBOSITY])\n\n # copy Dockerfile to publish dir\n build_dockerfile = os.path.join(\n build_path, docker_file_name)\n\n copyfile(docker_file, build_dockerfile)\n\n image_destination_name = \"{0}/{1}:{2}\".format(\n self.envvars.CONTAINER_REGISTRY_SERVER, module, tag_name).lower()\n\n self.output.info(\n \"BUILDING DOCKER IMAGE: \" + image_destination_name)\n\n # cd to the build output to build the docker image\n project_dir = os.getcwd()\n os.chdir(build_path)\n\n # BUILD DOCKER IMAGE\n build_result = self.dock.docker_client.images.build(\n tag=image_destination_name, path=\".\", dockerfile=docker_file_name)\n self.output.info(\n \"DOCKER IMAGE DETAILS: {0}\".format(build_result))\n\n # CD BACK UP\n os.chdir(project_dir)\n\n # PUSH TO CONTAINER REGISTRY\n self.output.info(\n \"PUSHING DOCKER IMAGE TO: \" + image_destination_name)\n\n for line in self.dock.docker_client.images.push(repository=image_destination_name, tag=tag_name, stream=True, auth_config={\n \"username\": self.envvars.CONTAINER_REGISTRY_USERNAME, \"password\": self.envvars.CONTAINER_REGISTRY_PASSWORD}):\n self.output.procout(self.utility.decode(line))\n\n self.output.footer(\"BUILD COMPLETE\")\n\n def deploy(self):\n self.output.header(\"DEPLOYING MODULES\")\n self.deploy_device_configuration(\n self.envvars.IOTHUB_NAME, self.envvars.IOTHUB_KEY,\n self.envvars.EDGE_DEVICE_ID, self.envvars.MODULES_CONFIG_FILE,\n self.envvars.IOTHUB_POLICY_NAME, self.envvars.IOT_REST_API_VERSION)\n self.output.footer(\"DEPLOY COMPLETE\")\n\n def deploy_device_configuration(\n self, iothub_name, iothub_key, device_id, config_file, iothub_policy_name, api_version):\n resource_uri = iothub_name + \".azure-devices.net\"\n token_expiration_period = 60\n deploy_uri = \"https://{0}/devices/{1}/applyConfigurationContent?api-version={2}\".format(\n resource_uri, device_id, api_version)\n iot_hub_sas_token = self.utility.get_iot_hub_sas_token(\n resource_uri, iothub_key, iothub_policy_name, token_expiration_period)\n\n deploy_response = requests.post(deploy_uri,\n headers={\n \"Authorization\": iot_hub_sas_token,\n \"Content-Type\": \"application/json\"\n },\n data=self.utility.get_file_contents(\n config_file)\n )\n\n # self.output.info(deploy_uri)\n # self.output.info(deploy_response.status_code)\n # self.output.info(deploy_response.text)\n\n if deploy_response.status_code == 204:\n self.output.info(\n \"Edge Device configuration successfully deployed to '{0}'.\".format(device_id))\n else:\n self.output.error(\n \"There was an error applying the configuration. You should see an error message above that indicates the issue.\")\n\n\nclass Docker:\n\n def __init__(self, envvars, utility, output):\n self.envvars = envvars\n self.envvars.check()\n self.utility = utility\n self.utility.set_config()\n self.output = output\n\n if self.envvars.DOCKER_HOST:\n self.docker_client = docker.DockerClient(base_url=self.envvars.DOCKER_HOST)\n self.docker_api = docker.APIClient(base_url=self.envvars.DOCKER_HOST)\n else:\n self.docker_client = docker.from_env()\n self.docker_api = docker.APIClient()\n\n def init_registry(self):\n\n self.output.header(\"INITIALIZING CONTAINER REGISTRY\")\n self.output.info(\"REGISTRY: \" + self.envvars.CONTAINER_REGISTRY_SERVER)\n\n if \"localhost\" in self.envvars.CONTAINER_REGISTRY_SERVER:\n self.init_local_registry()\n\n self.login_registry()\n self.output.line()\n\n def init_local_registry(self):\n\n parts = self.envvars.CONTAINER_REGISTRY_SERVER.split(\":\")\n\n if len(parts) < 2:\n self.output.error(\"You must specific a port for your local registry server. Expected: 'localhost:5000'. Found: \" +\n self.envvars.CONTAINER_REGISTRY_SERVER)\n sys.exit()\n\n port = parts[1]\n ports = {'{0}/tcp'.format(port): int(port)}\n\n try:\n self.output.info(\"Looking for local 'registry' container\")\n self.docker_client.containers.get(\"registry\")\n self.output.info(\"Found local 'registry' container\")\n except docker.errors.NotFound:\n self.output.info(\"Local 'registry' container not found\")\n\n try:\n self.output.info(\"Looking for local 'registry' image\")\n self.docker_client.images.get(\"registry:2\")\n self.output.info(\"Local 'registry' image found\")\n except docker.errors.ImageNotFound:\n self.output.info(\"Local 'registry' image not found\")\n self.output.info(\"Pulling 'registry' image\")\n self.docker_client.images.pull(\"registry\", tag=\"2\")\n\n self.output.info(\"Running registry container\")\n self.docker_client.containers.run(\n \"registry:2\", detach=True, name=\"registry\", ports=ports, restart_policy={\"Name\": \"always\"})\n\n def login_registry(self):\n try:\n\n if \"localhost\" in self.envvars.CONTAINER_REGISTRY_SERVER:\n client_login_status = self.docker_client.login(\n self.envvars.CONTAINER_REGISTRY_SERVER)\n\n api_login_status = self.docker_api.login(\n self.envvars.CONTAINER_REGISTRY_SERVER)\n else:\n\n client_login_status = self.docker_client.login(registry=self.envvars.CONTAINER_REGISTRY_SERVER,\n username=self.envvars.CONTAINER_REGISTRY_USERNAME, \n password=self.envvars.CONTAINER_REGISTRY_PASSWORD)\n\n api_login_status = self.docker_api.login(registry=self.envvars.CONTAINER_REGISTRY_SERVER,\n username=self.envvars.CONTAINER_REGISTRY_USERNAME, \n password=self.envvars.CONTAINER_REGISTRY_PASSWORD)\n \n self.output.info(\"Successfully logged into container registry: \" + self.envvars.CONTAINER_REGISTRY_SERVER)\n \n except Exception as ex:\n self.output.error(\n \"ERROR: Could not login to Container Registry. Please verify your credentials in CONTAINER_REGISTRY_ environment variables. If you are using WSL, then please set DOCKER_HOST Environment Variable. See the projects readme for full instructions.\")\n self.output.error(str(ex))\n sys.exit(-1)\n\n def setup_registry(self):\n self.output.header(\"SETTING UP CONTAINER REGISTRY\")\n self.init_registry()\n self.output.info(\"PUSHING EDGE IMAGES TO CONTAINER REGISTRY\")\n image_names = [\"azureiotedge-agent\", \"azureiotedge-hub\",\n \"azureiotedge-simulated-temperature-sensor\"]\n\n for image_name in image_names:\n\n microsoft_image_name = \"microsoft/{0}:{1}\".format(\n image_name, self.envvars.RUNTIME_TAG)\n\n container_registry_image_name = \"{0}/{1}:{2}\".format(\n self.envvars.CONTAINER_REGISTRY_SERVER, image_name, self.envvars.RUNTIME_TAG)\n\n # Pull image from Microsoft Docker Hub\n try:\n self.output.info(\n \"PULLING IMAGE: '{0}'\".format(microsoft_image_name))\n image_pull = self.docker_client.images.pull(\n microsoft_image_name)\n self.output.info(\n \"SUCCESSFULLY PULLED IMAGE: '{0}'\".format(microsoft_image_name))\n self.output.info(str(image_pull))\n except docker.errors.APIError as e:\n self.output.error(\n \"ERROR WHILE PULLING IMAGE: '{0}'\".format(microsoft_image_name))\n self.output.error(e)\n\n # Tagging Image with Container Registry Name\n try:\n tag_result = self.docker_api.tag(image=microsoft_image_name, repository=container_registry_image_name)\n except docker.errors.APIError as e:\n self.output.error(\n \"ERROR WHILE TAGGING IMAGE: '{0}'\".format(microsoft_image_name))\n self.output.error(e)\n \n # Push Image to Container Registry\n try:\n self.output.info(\"PUSHING IMAGE: '{0}'\".format(\n container_registry_image_name))\n\n for line in self.docker_client.images.push(repository=container_registry_image_name, tag=self.envvars.RUNTIME_TAG, stream=True, auth_config={\"username\": self.envvars.CONTAINER_REGISTRY_USERNAME, \"password\": self.envvars.CONTAINER_REGISTRY_PASSWORD}):\n self.output.procout(self.utility.decode(line))\n\n self.output.info(\"SUCCESSFULLY PUSHED IMAGE: '{0}'\".format(\n container_registry_image_name))\n except docker.errors.APIError as e:\n self.output.error(\"ERROR WHILE PUSHING IMAGE: '{0}'\".format(\n container_registry_image_name))\n self.output.error(e)\n\n self.setup_registry_in_config(image_names)\n\n self.utility.set_config(force=True)\n\n self.output.footer(\"Container Registry Setup Complete\")\n\n def setup_registry_in_config(self, image_names):\n self.output.info(\n \"Replacing 'microsoft/' with '{CONTAINER_REGISTRY_SERVER}/' in config files.\")\n\n # Replace microsoft/ with ${CONTAINER_REGISTRY_SERVER}\n for config_file in self.utility.get_config_files():\n config_file_contents = self.utility.get_file_contents(config_file)\n for image_name in image_names:\n config_file_contents = config_file_contents.replace(\n \"microsoft/\" + image_name, \"${CONTAINER_REGISTRY_SERVER}/\" + image_name)\n\n with open(config_file, \"w\") as config_file_build:\n config_file_build.write(config_file_contents)\n\n def remove_modules(self):\n self.output.info(\n \"Removing Edge Modules Containers and Images from Docker\")\n\n modules_in_config = self.utility.get_modules_in_config(ModuleType.User)\n\n for module in modules_in_config:\n self.output.info(\"Searching for {0} Containers\".format(module))\n containers = self.docker_client.containers.list(\n filters={\"name\": module})\n for container in containers:\n self.output.info(\"Removing Container: \" + str(container))\n container.remove(force=True)\n\n self.output.info(\"Searching for {0} Images\".format(module))\n for image in self.docker_client.images.list():\n if module in str(image):\n self.output.info(\n \"Removing Module Image: \" + str(image))\n self.docker_client.images.remove(\n image=image.id, force=True)\n\n def remove_containers(self):\n self.output.info(\"Removing Containers....\")\n containers = self.docker_client.containers.list(all=True)\n self.output.info(\"Found {0} Containers\".format(len(containers)))\n for container in containers:\n self.output.info(\"Removing Container: {0}:{1}\".format(\n container.id, container.name))\n container.remove(force=True)\n self.output.info(\"Containers Removed\")\n\n def remove_images(self):\n self.output.info(\"Removing Dangling Images....\")\n images = self.docker_client.images.list(\n all=True, filters={\"dangling\": True})\n self.output.info(\"Found {0} Images\".format(len(images)))\n\n for image in images:\n self.output.info(\"Removing Image: {0}\".format(str(image.id)))\n self.docker_client.images.remove(image=image.id, force=True)\n self.output.info(\"Images Removed\")\n\n self.output.info(\"Removing Images....\")\n images = self.docker_client.images.list()\n self.output.info(\"Found {0} Images\".format(len(images)))\n\n for image in images:\n self.output.info(\"Removing Image: {0}\".format(str(image.id)))\n self.docker_client.images.remove(image=image.id, force=True)\n self.output.info(\"Images Removed\")\n\n def handle_logs_cmd(self, show, save):\n\n # Create LOGS_PATH dir if it doesn't exist\n if save and not os.path.exists(self.envvars.LOGS_PATH):\n os.makedirs(self.envvars.LOGS_PATH)\n\n modules_in_config = self.utility.get_modules_in_config(ModuleType.Both)\n\n for module in modules_in_config:\n if show:\n try:\n command = self.envvars.LOGS_CMD.format(module)\n os.system(command)\n except Exception as e:\n self.output.error(\n \"Error while trying to open module log '{0}' with command '{1}'. Try iotedgedev docker --save-logs instead.\".format(module, command))\n self.output.error(e)\n if save:\n try:\n self.utility.exe_proc([\"docker\", \"logs\", module, \">\",\n os.path.join(self.envvars.LOGS_PATH, module + \".log\")], True)\n except Exception as e:\n self.output.error(\n \"Error while trying to save module log file '{0}'\".format(module))\n self.output.error(e)\n\n if save:\n self.zip_logs()\n\n def zip_logs(self):\n log_files = [os.path.join(self.envvars.LOGS_PATH, f)\n for f in os.listdir(self.envvars.LOGS_PATH) if f.endswith(\".log\")]\n zip_path = os.path.join(self.envvars.LOGS_PATH, 'edge-logs.zip')\n\n self.output.info(\"Creating {0} file\".format(zip_path))\n\n zipf = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)\n\n for log_file in log_files:\n self.output.info(\"Adding {0} to zip\". format(log_file))\n zipf.write(log_file)\n\n zipf.close()\n\n self.output.info(\"Log files successfully saved to: \" + zip_path)\n\n\nclass ModuleType(Enum):\n System = 1\n User = 2\n Both = 3\n","sub_path":"iotedgedev/iotedgedev.py","file_name":"iotedgedev.py","file_ext":"py","file_size_in_byte":28790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"233136559","text":"import pygame\nfrom pygame.locals import *\n\nCOLOR_BACKGROUND = [128, 0, 128]\nCOLOR_WHITE = (255, 255, 255)\nFPS = 60\nH_SIZE = 600 \nW_SIZE = 800\nMX_TIME = 300\n\npygame.init()\n\n\nsurface = pygame.display.set_mode((W_SIZE, H_SIZE))\n\nclock = pygame.time.Clock()\ntimer = [0.0]\ndt = 1.0 / FPS\ntimer_font = pygame.font.SysFont(\"Calibri\", 100)\n\nwhile True:\n clock.tick_busy_loop(60)\n surface.fill(COLOR_BACKGROUND)\n\n events = pygame.event.get()\n for event in events:\n if event.type == QUIT:\n exit()\n\n timer[0] += dt\n MX_TIME -= dt\n time = int(MX_TIME) \n time_string = str(time)\n\n time_blit = timer_font.render(time_string, 1, COLOR_WHITE)\n time_blit_size = time_blit.get_size()\n surface.blit(time_blit,(W_SIZE / 2 - time_blit_size[0] / 2, H_SIZE / 2 - time_blit_size[1] / 2))\n\n pygame.display.flip()\n","sub_path":"tinytimer.py","file_name":"tinytimer.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"161978944","text":"from . import africastalking\n\nsms = africastalking.SMS\n\n\n# Use the service synchronously\ndef send_sms(to, message, raise_exception=False):\n # Or use it asynchronously\n success = False\n\n def on_finish(error, response):\n if raise_exception and error is not None:\n raise error\n if not error:\n global success\n success = True\n\n sms.send(message, [to], callback=on_finish)\n\n return success\n","sub_path":"dj_africastalking/sms.py","file_name":"sms.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"606781794","text":"\"\"\"\nCreated on 21 Jun 2017\n\n@author: Bruno Beloff (bruno.beloff@southcoastscience.com)\n\nspecifies which PSU is present, if any\n\nexample JSON:\n{\"model\": \"MobileV2\", \"batt-model\": \"PackV1\", \"ignore-threshold\": true, \"reporting-interval\": 10,\n\"report-file\": \"/tmp/southcoastscience/psu_status_report.json\"}\n\"\"\"\n\nfrom scs_core.psu.psu_conf import PSUConf as AbstractPSUConf\n\nfrom scs_dfe.interface.opcube.opcube_mcu_t1 import OPCubeMCUt1\n\nfrom scs_dfe.interface.pzhb.pzhb_mcu_t1_f1 import PZHBMCUt1f1\nfrom scs_dfe.interface.pzhb.pzhb_mcu_t2_f1 import PZHBMCUt2f1\nfrom scs_dfe.interface.pzhb.pzhb_mcu_t3_f1 import PZHBMCUt3f1\n\nfrom scs_psu.batt_pack.batt_pack_v1 import BattPackV1\nfrom scs_psu.batt_pack.batt_pack_v2 import BattPackV2\n\nfrom scs_psu.psu.opcube_v1.psu_opcube_v1 import PSUOPCubeV1p0, PSUOPCubeV1p1\n\nfrom scs_psu.psu.mobile_v1.psu_mobile_v1 import PSUMobileV1\nfrom scs_psu.psu.mobile_v2.psu_mobile_v2 import PSUMobileV2\n\nfrom scs_psu.psu.oslo_v1.psu_oslo_v1 import PSUOsloV1\n\nfrom scs_psu.psu.prototype_v1.psu_prototype_v1 import PSUPrototypeV1\n\nfrom scs_psu.psu.psu_monitor import PSUMonitor\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\nclass PSUConf(AbstractPSUConf):\n \"\"\"\n classdocs\n \"\"\"\n\n __PSU_CLASSES = {\n PSUMobileV1.name(): PSUMobileV1,\n PSUMobileV2.name(): PSUMobileV2,\n PSUOPCubeV1p0.name(): PSUOPCubeV1p0,\n PSUOPCubeV1p1.name(): PSUOPCubeV1p1,\n PSUOsloV1.name(): PSUOsloV1,\n PSUPrototypeV1.name(): PSUPrototypeV1\n }\n\n @classmethod\n def psu_models(cls):\n return sorted(cls.__PSU_CLASSES.keys())\n\n\n __BATT_CLASSES = {\n BattPackV1.name(): BattPackV1,\n BattPackV2.name(): BattPackV2\n }\n\n @classmethod\n def batt_models(cls):\n return sorted(cls.__BATT_CLASSES.keys())\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n @classmethod\n def construct_from_jdict(cls, jdict, skeleton=False):\n if not jdict:\n return PSUConf(None, None, False, 0, None)\n\n psu_model = jdict.get('model')\n batt_model = jdict.get('batt-model')\n ignore_threshold = jdict.get('ignore-threshold', False)\n\n reporting_interval = jdict.get('reporting-interval')\n report_file = jdict.get('report-file')\n\n return cls(psu_model, batt_model, ignore_threshold, reporting_interval, report_file)\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def __init__(self, psu_model, batt_model, ignore_threshold, reporting_interval, report_file):\n \"\"\"\n Constructor\n \"\"\"\n super().__init__(psu_model, batt_model, ignore_threshold, reporting_interval, report_file)\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def psu(self, host, interface_model):\n if self.psu_model is None:\n return None\n\n if self.psu_model not in self.__PSU_CLASSES.keys():\n raise ValueError('unknown PSU model: %s' % self.psu_model)\n\n psu_class = self.__PSU_CLASSES[self.__psu_model]\n\n batt_class = None if self.__batt_model is None else self.__BATT_CLASSES[self.__batt_model]\n batt_pack = None if batt_class is None else batt_class.construct()\n\n if self.psu_model == PSUMobileV1.name():\n if interface_model == 'PZHBt1':\n return psu_class(PZHBMCUt1f1(PZHBMCUt1f1.DEFAULT_ADDR))\n\n if interface_model == 'PZHBt2':\n return psu_class(PZHBMCUt2f1(PZHBMCUt2f1.DEFAULT_ADDR))\n\n raise ValueError('incompatible interface model for MobileV1: %s' % interface_model)\n\n if self.psu_model == PSUMobileV2.name():\n if interface_model == 'PZHBt3':\n return psu_class(PZHBMCUt3f1(PZHBMCUt3f1.DEFAULT_ADDR), batt_pack)\n\n raise ValueError('incompatible interface model for MobileV2: %s' % interface_model)\n\n if self.psu_model in (PSUOPCubeV1p0.name(), PSUOPCubeV1p1.name()):\n return psu_class(OPCubeMCUt1(OPCubeMCUt1.DEFAULT_ADDR), batt_pack)\n\n return psu_class(host.psu_device())\n\n\n def psu_monitor(self, host, interface_model, ignore_standby):\n psu = self.psu(host, interface_model)\n\n if psu is None:\n return None\n\n return PSUMonitor(host, psu, ignore_standby, self.ignore_threshold)\n\n\n def psu_class(self):\n if self.psu_model is None:\n return None\n\n return self.__PSU_CLASSES[self.psu_model]\n\n\n def psu_report_class(self):\n if self.psu_model is None:\n return None\n\n psu_class = self.__PSU_CLASSES[self.psu_model] # may raise KeyError\n\n return psu_class.report_class()\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def __str__(self, *args, **kwargs):\n return \"PSUConf(psu):{psu_model:%s, batt_model:%s, ignore_threshold:%s, reporting_interval:%s, \" \\\n \"report_file:%s}\" % \\\n (self.psu_model, self.batt_model, self.ignore_threshold, self.reporting_interval,\n self.report_file)\n","sub_path":"src/scs_psu/psu/psu_conf.py","file_name":"psu_conf.py","file_ext":"py","file_size_in_byte":5336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"79405108","text":"import json\nfrom bokeh.plotting import figure, show\nfrom bokeh.embed import components\nfrom bokeh.layouts import gridplot\nfrom bokeh.models import Label\n\nfrom .models import (\n Survey,\n SurveyResult\n)\n\n\ndef response_with_x_frames(response, origin):\n\n if origin:\n response['X-FRAME-OPTIONS'] = 'ALLOW-FROM ' + origin\n\n return response\n\n\ndef average(arr):\n\n if len(arr) > 0:\n return sum(arr) / len(arr)\n else:\n return 0\n\n\ndef get_groups_context(current_group):\n\n context = dict()\n plots = []\n\n current_survey = Survey.objects.all()[0]\n current_results = SurveyResult.objects.filter(survey=current_survey)\n current_group_infos = current_group.groupinfo_set.all()\n num_entries = current_results.count()\n\n dates = [current_result.created_on for current_result in current_results]\n\n\n\n current_ratings = [[average(arr) for arr in json.loads(current_result.result)]\n for current_result in current_results]\n\n average_ratings = [[] for i in range(4)]\n\n total_ratings = [0, 0, 0, 0]\n\n for i in range(num_entries):\n for j in range(4):\n total_ratings[j] += current_ratings[i][j]\n average_ratings[j].append(total_ratings[j] / (i + 1))\n\n plot1 = figure(\n width=380, height=400, title='Engagement over time',\n x_axis_label='Date Time', y_axis_label='Engagement',\n x_axis_type='datetime', y_range=(0, 6)\n )\n\n plot1.line(dates, average_ratings[0], legend='Reinforcement of needs')\n plot1.line(dates, average_ratings[1], legend='Membership', color='red')\n plot1.line(dates, average_ratings[2], legend=\"Influence\", color='orange')\n\n\n plot1.line(dates, average_ratings[3], legend=\"Shared Emotional Connections\", color='green')\n\n if len(dates) < 2:\n p1_label = Label(x=70, y=70, x_units='screen', y_units='screen',\n text='There is not Engagement Data', render_mode='css',\n border_line_color='black', border_line_alpha=1.0,\n background_fill_color='white', background_fill_alpha=1.0)\n\n plot1.add_layout(p1_label)\n\n plots.append([plot1])\n\n activity_dates = [group_info.created_on for group_info in current_group_infos]\n\n activity_scores = [group_info.activity_score for group_info in current_group_infos]\n\n\n plot2 = figure(width=380, height=400, title='Activity score over time',\n x_axis_label='Date Time', y_axis_label='Activity Score',\n x_axis_type='datetime')\n\n plot2.line(activity_dates, activity_scores, legend='Activity Score')\n\n plots.append([plot2])\n\n if len(activity_dates) < 2:\n p2_label = Label(x=70, y=70, x_units='screen', y_units='screen',\n text='There is not Activity Score data', render_mode='css',\n border_line_color='black', border_line_alpha=1.0,\n background_fill_color='white', background_fill_alpha=1.0)\n\n plot2.add_layout(p2_label)\n\n final_plot = gridplot(plots)\n\n script, div = components(final_plot)\n\n context['div'] = div\n context['script'] = script\n\n return context\n","sub_path":"pamoja/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"306801602","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.shortcuts import redirect\nfrom django.db.models import Q\nfrom django.core.cache import cache\nfrom django.views.decorators.cache import cache_page\nfrom .forms import *\nfrom .models import *\nimport json\nimport hashlib\nfrom enum import Enum\n\nimgType = ['pf_scenery', 'zh_scenery', 'pf_canteen', 'zh_canteen', 'pf_doom', 'zh_doom']\nimg_folder = {'pf_scenery': '屏峰风光', 'zh_scenery': '朝晖风光', 'pf_canteen': '屏峰食堂',\n 'zh_canteen': '朝晖食堂', 'pf_doom': '屏峰寝室', 'zh_doom': '朝晖寝室'}\n\n\nclass res_msg(Enum):\n MSG_ERROR = \"请正确填写信息\"\n MSG_NOT_FOUND = \"没有查到你的信息\"\n\n@cache_page(60*15)\ndef page_not_found(request, exception=None):\n return render(request, 'index.html')\n\n@cache_page(60*15)\ndef page_error(request, exception=None):\n return render(request, 'index.html')\n\ndef img_show(request):\n img_type = request.GET.get('type')\n if not img_type.isdigit():\n message = res_msg.MSG_ERROR.value\n return render(request, 'index.html', locals())\n\n img_type = imgType[int(img_type) - 1]\n image_list = [i.imgurl for i in CampusImg.objects.filter(imgtype=img_type)]\n context = {'imgList': json.dumps(image_list), 'sname': 'sname'}\n return render(request, 'imgShow.html', context)\n\ndef index_dorm(request):\n if request.method != \"POST\":\n return render(request, 'indexDorm.html')\n\n uf = getDormForm(request.POST)\n if not uf.is_valid():\n return render(request, 'indexDorm.html', {\"message\": res_msg.MSG_ERROR.value})\n\n sname = uf.cleaned_data['sname']\n sid = uf.cleaned_data['sid']\n sha = hashlib.md5()\n sha.update(sid.encode('utf8'))\n sid = sha.hexdigest()\n\n stu_cache=cache.get('GetID'+sname+sid)\n if stu_cache is None:\n stu = Student.objects.filter(sname=sname, sid=sid)\n \n if not stu:\n return render(request, 'indexDorm.html', {\"message\": res_msg.MSG_NOT_FOUND.value})\n \n stu = stu[0]\n cache.set('GetID'+sname+sid,stu)\n else:\n stu=stu_cache\n\n room_cache=cache.get('GetRoom'+stu.shouse+stu.sroom)\n if room_cache is None:\n roommate = Student.objects.filter(sroom=stu.sroom, shouse=stu.shouse)\n cache.set('GetRoom'+stu.shouse+stu.sroom,roommate)\n else:\n roommate=room_cache\n\n roommate = roommate.filter(~Q(sid=stu.sid))\n\n request.session['sname'] = sname\n context = {'sname': stu.sname, 'sroom': stu.sroom, 'roommate': roommate,\n 'sbed': stu.sbed,'shouse': stu.shouse, 'scampus': stu.scampus}\n return render(request, 'getDorm.html', context)\n\ndef index(request):\n if request.method != \"POST\":\n return render(request, 'index.html', locals())\n\n uf = getIDForm(request.POST)\n if not uf.is_valid():\n message = res_msg.MSG_ERROR.value\n return render(request, 'index.html', locals())\n\n sname = uf.cleaned_data['sname']\n sid = uf.cleaned_data['sid']\n sha = hashlib.md5()\n sha.update(sid.encode('utf8'))\n sid = sha.hexdigest()\n print(sname,sid)\n stu_cache=cache.get('GetID'+sname+sid)\n if stu_cache is None:\n stu = Student.objects.filter(sname=sname, sid=sid)\n if not stu:\n message = res_msg.MSG_NOT_FOUND.value\n return render(request, 'index.html', locals())\n stu = stu[0]\n cache.set('GetID'+sname+sid,stu)\n else:\n stu=stu_cache\n\n request.session['sname'] = sname\n context = {'sname': stu.sname, 'scard': stu.scard, 'smajor': stu.smajor,\n 'sclass': stu.sclass, 'scampus': stu.scampus}\n return render(request, 'getID.html', context)\n","sub_path":"GetID/ID/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"604531199","text":"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nX = np.linspace(-np.pi, np.pi, 256)\nY1 = np.sin(X)\nY2 = np.cos(X)\nY3 = np.tan(X)\nY4 = np.sqrt(1 - X*X)\n\nplt.figure(figsize=(6,4), dpi=80) # 6 for x axis and 4 for y axis, dpi decides how large the plot will be,\n# figsize is proportional x and y values\n\nplt.plot(X,Y1, color='blue',linewidth=2.5, linestyle=':', label='sin')\n#plt.show()\n\nplt.plot(X,Y2,color='red', linewidth=2.5, label='cos')\nplt.xlim(X.min()*1.2)\nplt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],[r'$-\\pi$',r'$-\\pi/2$',r'$0$',r'$\\pi/2$',r'$\\pi$'],rotation=30) # to view the actual values\nplt.yticks([+1,0,-1],rotation=30)\n\nax = plt.gca()\nax.spines['right'].set_color(None)\nax.spines['top'].set_color(None)\nax.xaxis.set_ticks_position('bottom') # top means the x-axis values will be floating at the top\nax.spines['left'].set_position(('data',0))\nax.spines['bottom'].set_position(('data',0))\nplt.legend(loc='best')\n\nfor labels in ax.get_xticklabels() + ax.get_yticklabels():\n labels.set_fontsize(16)\n labels.set_bbox(dict(facecolor='grey', # to create a box around the values ( color of box -> facecolor,\n edgecolor='red', # outline of box -> edgecolor, alpha-> transparency of box\n alpha=0.35))\nplt.savefig('myplot.png') #savefig before show\n\nplt.show()\n\nplt.plot(X,Y3)\nplt.ylim(Y3.min()*1.5)\nplt.show()\n\nplt.plot(X,Y4)\nplt.show()\n\n\n\n","sub_path":"python_training/samp_proj1/day_011118/plotting1.py","file_name":"plotting1.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"404804247","text":"from kivy.uix.screenmanager import Screen\n\nfrom Camera import Camera\nfrom TelegramBot import TelegramBot\nfrom datetime import datetime\n\nimport threading\n\nimport settings\n\nclass HelpScreen(Screen):\n def on_pre_enter(self):\n self.ids.HelpImageId.source = settings.myList['config']['images']['help_person']\n self.ids.HelpScreenLabel.text = settings.myList['config']['text']['help_text']\n\n def sending_help(self):\n self.ids.HelpScreenLabel.text = settings.myList['config']['text']['help_sending_text'] \n\n def send_help(self):\n print(\"send_help ausgeführt\")\n\n # Create Imagestream Objekt and Take Picture\n camera = Camera()\n camera.stream()\n # Bild wird in camera.imagestream gespeichert\n\n telegrambot = TelegramBot()\n senddatetime = datetime.now().strftime(\"%Y-%m-%d - %H:%M:%S\")\n telegrambot.text = settings.myList['config']['text']['photobox_sos'] + ' [' + senddatetime + ']'\n telegrambot.photo = camera.imagestream\n telegrambot.updateHelpPerson()\n #telegrambot.send()\n\n telegram_thread = threading.Thread(target=telegrambot.send, args=())\n telegram_thread.start()\n\n # # Telegram\n # import telegram\n # chat_id = settings.myList['private_config']['telegram']['help_person_id']\n\n # #image.save(bio, 'JPEG')\n # #bio.seek(0)\n\n # print(\"Create BOT start\")\n # bot = telegram.Bot(token=settings.myList['private_config']['telegram']['api-token'])\n # print(\"Create BOT end\")\n # #print(bot.get_me())\n # print(\"Send message start\")\n # bot.send_message(chat_id, text=settings.myList['config']['text']['photobox_sos'])\n # print(\"Send image start\")\n # bot.send_photo(chat_id, photo=camera.imagestream)\n # print(\"Send ENDE\")\n\n self.ids.HelpScreenLabel.text = settings.myList['config']['text']['help_success_text'] \n","sub_path":"screens/HelpScreen.py","file_name":"HelpScreen.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"397922988","text":"from d3m.metadata import base as metadata_base, hyperparams, params\nfrom d3m import container, exceptions\nfrom d3m.primitive_interfaces.unsupervised_learning import UnsupervisedLearnerPrimitiveBase\nfrom typing import Dict, Optional, Sequence\nfrom featuretools_ta1 import config as CONFIG\nfrom d3m.primitive_interfaces.base import CallResult, DockerContainer, MultiCallResult\nfrom d3m.exceptions import PrimitiveNotFittedError\nfrom featuretools_ta1.utils import drop_percent_null, select_one_of_correlated\nimport featuretools_ta1\nfrom featuretools_ta1.utils import get_featuretools_variable_types, find_primary_key, add_metadata, find_target_column\nimport featuretools as ft\nimport numpy as np\nimport pandas as pd\nimport featuretools_ta1.semantic_types as st\n\nInputs = container.DataFrame\nOutputs = container.DataFrame\nTARGET_ENTITY = \"table\"\n\n\nclass Params(params.Params):\n # A named tuple for parameters.\n features: Optional[bytes]\n\n\nclass Hyperparams(hyperparams.Hyperparams):\n max_percent_null = hyperparams.Bounded[float](\n default=.5,\n lower=0,\n upper=1,\n description='The maximum percentage of null values allowed in returned features. A lower value means features may have more null nulls.',\n semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']\n )\n max_correlation = hyperparams.Bounded[float](\n default=.9,\n lower=0,\n upper=1,\n description='The maximum allowed correlation between any two features returned. A lower value means features will be more uncorrelated',\n semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter']\n )\n use_columns = hyperparams.Set(\n elements=hyperparams.Hyperparameter[int](-1),\n default=(),\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\"A set of column indices to force primitive to operate on. If any specified column cannot be parsed, it is skipped.\",\n )\n exclude_columns = hyperparams.Set(\n elements=hyperparams.Hyperparameter[int](-1),\n default=(),\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\"A set of column indices to not operate on. Applicable only if \\\"use_columns\\\" is not provided.\",\n )\n return_result = hyperparams.Enumeration(\n values=['append', 'replace', 'new'],\n default='new',\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\"Should parsed columns be appended, should they replace original columns, or should only parsed columns be returned? This hyperparam is ignored if use_semantic_types is set to false.\",\n )\n max_features = hyperparams.Hyperparameter[int](\n default=100,\n semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter'],\n description=\"Cap the number of generated features to this number. If -1, no limit.\"\n )\n\n\nclass SingleTableFeaturization(UnsupervisedLearnerPrimitiveBase[Inputs, Outputs, Params, Hyperparams]):\n \"\"\"This primitive creates new interaction features for an input dataframe.\n After creating features it reduces the set of possible features using an unsupervised approach\"\"\"\n __author__ = 'Max Kanter '\n metadata = metadata_base.PrimitiveMetadata(\n {\n 'id': '6c5dcfa3-1f87-4066-b16a-88c9c971f6e3',\n 'version': featuretools_ta1.__version__,\n 'name': \"Single Table Deep Feature Synthesis\",\n 'python_path': 'd3m.primitives.feature_construction.deep_feature_synthesis.SingleTableFeaturization',\n 'source': {\n 'name': CONFIG.AUTHOR,\n 'contact': CONFIG.CONTACT,\n 'uris': ['https://docs.featuretools.com'],\n 'license': 'BSD-3-Clause'\n },\n 'installation': CONFIG.INSTALLATION,\n 'algorithm_types': [\n metadata_base.PrimitiveAlgorithmType.DEEP_FEATURE_SYNTHESIS,\n ],\n 'primitive_family': metadata_base.PrimitiveFamily.FEATURE_CONSTRUCTION,\n 'keywords': [\n 'featurization',\n 'feature engineering',\n 'feature extraction',\n 'feature construction'\n ],\n 'hyperparameters_to_tune': ['max_percent_null', 'max_correlation', 'max_features'],\n },\n )\n\n def __init__(self, *,\n hyperparams: Hyperparams,\n random_seed: int = 0,\n docker_containers: Dict[str, DockerContainer] = None) -> None:\n self._fitted = False\n\n # todo handle use_columns, exclude_columns\n # todo handle return result\n\n super().__init__(hyperparams=hyperparams, random_seed=random_seed, docker_containers=docker_containers)\n\n def set_training_data(self, *, inputs: Inputs) -> None:\n self._input_df = inputs\n self._fitted = False\n\n def fit(self, *, timeout: float = None, iterations: int = None) -> CallResult[None]:\n es = self._make_entityset(self._input_df)\n\n trans_primitives = [\"is_weekend\", \"day\", \"month\", \"year\", \"week\", \"weekday\", \"num_words\", \"num_characters\",\n \"add_numeric\", \"subtract_numeric\", \"multiply_numeric\", \"divide_numeric\"]\n\n # generate all the features\n fm, features = ft.dfs(\n target_entity=TARGET_ENTITY,\n entityset=es,\n agg_primitives=[],\n trans_primitives=trans_primitives,\n max_depth=1,\n max_features=self.hyperparams[\"max_features\"]\n )\n\n # treat inf as null. repeat in produce step\n fm = fm.replace([np.inf, -np.inf], np.nan)\n\n # filter based on nulls and correlation\n fm, features = drop_percent_null(fm, features, max_percent_null=self.hyperparams['max_percent_null'])\n fm, features = select_one_of_correlated(fm, features, threshold=self.hyperparams['max_correlation'])\n self.features = features\n\n self._fitted = True\n fm = add_metadata(fm, self.features)\n return CallResult(fm)\n\n def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> CallResult[Outputs]:\n if not self._fitted:\n raise PrimitiveNotFittedError(\"Primitive not fitted.\")\n\n es = self._make_entityset(inputs)\n\n fm = ft.calculate_feature_matrix(\n entityset=es,\n features=self.features\n )\n\n # make sure the feature matrix is ordered the same as the input\n fm = fm.reindex(es[TARGET_ENTITY].df.index)\n fm = fm.reset_index(drop=True) # d3m wants index to increment by 1\n\n # treat inf as null like fit step\n fm = fm.replace([np.inf, -np.inf], np.nan)\n\n fm = add_metadata(fm, self.features)\n\n pk_index = find_primary_key(inputs, return_index=True)\n # if a pk is found\n if pk_index is not None:\n pk_col = inputs.select_columns([pk_index])\n fm = fm.append_columns(pk_col)\n\n target_index = find_target_column(inputs, return_index=True)\n # if a target is found,\n if target_index is not None:\n labels = inputs.select_columns(target_index)\n fm = fm.append_columns(labels)\n\n return CallResult(fm)\n\n def get_params(self) -> Params:\n if not self._fitted:\n return Params(features=None)\n\n return Params(features=None)\n\n def set_params(self, *, params: Params) -> None:\n self.features = params[\"features\"]\n\n # infer if it is fitted\n if self.features:\n self._fitted = True\n\n def _make_entityset(self, input_df):\n es = ft.EntitySet()\n\n primary_key = find_primary_key(input_df)\n make_index = False\n\n if primary_key is None:\n primary_key = \"D3M_INDEX\"\n make_index = True\n\n cols_to_use = input_df.metadata.list_columns_with_semantic_types([st.PRIMARY_KEY, st.ATTRIBUTE])\n\n input_df = input_df.select_columns(cols_to_use)\n\n variable_types = get_featuretools_variable_types(input_df)\n\n es.entity_from_dataframe(entity_id=TARGET_ENTITY,\n dataframe=pd.DataFrame(input_df.copy()),\n index=primary_key,\n make_index=make_index,\n variable_types=variable_types)\n\n return es\n\n def fit_multi_produce(self, *, produce_methods: Sequence[str], inputs: Inputs, timeout: float = None, iterations: int = None) -> MultiCallResult:\n self.set_training_data(inputs=inputs) # type: ignore\n\n method_name = produce_methods[0]\n if method_name != 'produce':\n raise exceptions.InvalidArgumentValueError(\"Invalid produce method name '{method_name}'.\".format(method_name=method_name))\n\n result = self.fit(timeout=timeout, iterations=iterations)\n\n return MultiCallResult(\n values={method_name: result.value},\n )\n\n\n\"\"\"\ndo we need the docker containers input to init?\n# def set_training_data(self, *, inputs: Inputs, outputs: Outputs) -> None:\nfix path\nTODOS\n* handle non numeric\n\"\"\"\n","sub_path":"featuretools_ta1/single_table.py","file_name":"single_table.py","file_ext":"py","file_size_in_byte":9304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"138463672","text":"import cv2\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\n\r\n\r\ndef nothing(x):\r\n pass\r\n\r\n# Create a black image, a window\r\nimg = cv2.imread('ex1.jpg',0)\r\ncv2.namedWindow('image')\r\n\r\n# create trackbars for color change\r\ncv2.createTrackbar('H','image',0,255,nothing)\r\ncv2.createTrackbar('W','image',0,255,nothing)\r\n\r\n\r\n# create switch for ON/OFF functionality\r\nswitch = '0 : OFF \\n1 : ON'\r\ncv2.createTrackbar(switch, 'image',0,1,nothing)\r\n\r\nwhile(1):\r\n \r\n k = cv2.waitKey(1) & 0xFF\r\n if k == 27:\r\n break\r\n\r\n # get current positions of four trackbars\r\n H = cv2.getTrackbarPos('H','image')\r\n W = cv2.getTrackbarPos('W','image')\r\n \r\n s = cv2.getTrackbarPos(switch,'image')\r\n\t\r\n\t\r\n\r\n if s == 0:\r\n edges = img\r\n\r\n else:\r\n edges = cv2.Canny(img,H,W)\r\n cv2.imshow('image',edges)\r\n\t\r\n\r\ncv2.destroyAllWindows()\r\ncv2.destroyAllWindows()","sub_path":"lab3/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"99592714","text":"## begin license ##\n#\n# \"Meresco Fetch\" is a small framework to build simple, custom harvesters.\n#\n# Copyright (C) 2015 Netherlands Institute for Sound and Vision http://instituut.beeldengeluid.nl/\n# Copyright (C) 2015-2016 Seecr (Seek You Too B.V.) http://seecr.nl\n# Copyright (C) 2016 Drents Archief http://www.drentsarchief.nl\n#\n# This file is part of \"Meresco Fetch\"\n#\n# \"Meresco Fetch\" is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# \"Meresco Fetch\" 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 \"Meresco Fetch\"; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n#\n## end license ##\n\nfrom meresco.fetch.harvester import BatchProtocol, RecordProtocol\n\nfrom meresco.oai.tools import OaiListRequest\n\nclass OaiPmhDownload(object):\n def __init__(self, repositories, log, recordAllowedFilter=None):\n self._repositories = repositories\n self._log = log\n self._recordAllowedFilter = (lambda record: True) if recordAllowedFilter is None else recordAllowedFilter\n self._OaiListRequest = OaiListRequest\n\n def downloadBatch(self, resumptionAttributes):\n repositoriesRemaining = resumptionAttributes.get('repositoriesRemaining')\n if not repositoriesRemaining:\n repositoriesRemaining = self._repositories[:]\n currentRepository = first(repositoriesRemaining)\n if currentRepository is None:\n self._log.write('no repositories configured for OaiPmhDownload.\\n')\n return\n baseurl = currentRepository.get('baseurl')\n assert baseurl, \"Got repository description without 'baseurl': %s\" % repr(currentRepository)\n metadataPrefix = currentRepository.get('metadataPrefix')\n assert metadataPrefix, \"Got repository description without 'metadataPrefix': %s\" % repr(currentRepository)\n\n resumptionToken = resumptionAttributes.get('resumptionToken', 0)\n self._log.write(\"Batch download; repository: %s, resumptionToken: %s\\n\" % (currentRepository, resumptionToken))\n if resumptionToken:\n oaiListRequest = self._OaiListRequest(baseurl=baseurl, resumptionToken=resumptionToken)\n else:\n oaiListRequest = self._OaiListRequest(baseurl=baseurl, metadataPrefix=metadataPrefix, set=currentRepository.get('setSpec'))\n\n self._log.write('requesting %s\\n' % oaiListRequest.buildUrl())\n oaiBatch = oaiListRequest.retrieveBatch()\n batch = _Batch(oaiBatch=oaiBatch, repositoriesRemaining=repositoriesRemaining)\n self._log.write('nrOfResults: %s, next resumptionToken: %s\\n' % (len(oaiBatch.items), batch.resumptionToken))\n if not batch.resumptionToken:\n batch.repositoriesRemaining.pop(0)\n if not batch.repositoriesRemaining:\n batch.harvestingReady = True\n batch.records = [r for r in [Record(batch, item) for item in batch.oaiBatch.items] if self._recordAllowedFilter(r)]\n return batch\n\n\n\nclass _Batch(BatchProtocol):\n def __init__(self, oaiBatch, repositoriesRemaining):\n BatchProtocol.__init__(self)\n self.repositoriesRemaining = repositoriesRemaining\n currentRepository = first(repositoriesRemaining)\n self.oaiBatch = oaiBatch\n self.resumptionToken = oaiBatch.resumptionToken\n self.baseurl = oaiBatch.request.baseurl\n self.repositoryGroupId = currentRepository.get('repositoryGroupId')\n self.repositoryId = currentRepository.get('repositoryId')\n self.setSpec = currentRepository.get('setSpec') or ''\n self.metadataPrefix = currentRepository.get('metadataPrefix') or ''\n\n def resumptionAttributes(self):\n return {\n 'resumptionToken': self.resumptionToken,\n 'repositoriesRemaining': self.repositoriesRemaining\n }\n\n\nclass Record(RecordProtocol):\n def __init__(self, batch, item):\n self.batch = batch\n self.item = item\n self.repositoryGroupId = batch.repositoryGroupId\n self.repositoryId = batch.repositoryId\n self.setSpec = batch.setSpec\n self.metadataPrefix = batch.metadataPrefix\n self.baseurl = batch.baseurl\n self.recordIdentifier = item.identifier\n self.identifier = \"%s:%s\" % (batch.repositoryGroupId, self.recordIdentifier)\n\n def mustAdd(self):\n return not self.item.deleted\n\n def mustDelete(self):\n return self.item.deleted\n\n def asString(self):\n return str(self.item)\n\ndef first(l, default=None):\n if l:\n for v in l:\n return v\n return default\n","sub_path":"meresco/fetch/oaipmhdownload.py","file_name":"oaipmhdownload.py","file_ext":"py","file_size_in_byte":5018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"427999488","text":"'''\nEE 381 Spring 2020 Project 3 Part 2\nName: Kristinann Osborn\nID: 016731726\nStart Date: 2/19/2020\nEnd Date: 2/24/2020\nDescription: Simulating a Bernoulli RV and using\nit to make a simple Markov chain.\n'''\n\nimport random # Importing python's RNG\n\nlocation = [] # where the particle is located\n\np_A = float(input('Enter the probability of leaving node 0. '))\n\np_B = float(input('Enter the probability of leaving node 1. '))\n\nS = int(input(\"Enter either a '0' or a '1' to start. \"))\nlocation.append(S)\n\nfor i in range(25):\n r = random.uniform(0,1) # Generating a uniform random number on [0,1]\n \n if r < p_A and S == 0: # At 0 and success\n S = 1 # reassign to 1\n elif r < p_B and S == 1: # At 1 and success\n S = 0 # reassign to 0\n location.append(S)\n \nfor i in location:\n print(i, end=' ')","sub_path":"Project3Part2Sec02KristinannOsborn.py","file_name":"Project3Part2Sec02KristinannOsborn.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"17439575","text":"\n\nfrom xai.brain.wordbase.nouns._rap import _RAP\n\n#calss header\nclass _RAPPED(_RAP, ):\n\tdef __init__(self,): \n\t\t_RAP.__init__(self)\n\t\tself.name = \"RAPPED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"rap\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_rapped.py","file_name":"_rapped.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"49307044","text":"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nimport math\nimport copy\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport torch.nn.functional as F\n\nclass Sobel(nn.Module):\n def __init__(self):\n super(Sobel, self).__init__()\n self.edge_conv = nn.Conv2d(1, 2, kernel_size=3, stride=1, padding=1, bias=False)\n edge_kx = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])\n edge_ky = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])\n edge_k = np.stack((edge_kx, edge_ky))\n\n edge_k = torch.from_numpy(edge_k).float().view(2, 1, 3, 3)\n self.edge_conv.weight = nn.Parameter(edge_k)\n \n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, x):\n out = self.edge_conv(x) \n out = out.contiguous().view(-1, 2, x.size(2), x.size(3))\n return out\n\nclass DepthLoss(nn.Module):\n \"\"\"\n Main class for Generalized R-CNN. Currently supports boxes and masks.\n It consists of three main parts:\n - backbone\n - rpn\n - heads: takes the features + the proposals from the RPN and computes\n detections / masks from it.\n \"\"\"\n\n def __init__(self, invalid_value=None):\n super(DepthLoss, self).__init__()\n self.cos_loss = torch.nn.CosineSimilarity(dim=1, eps=0)\n self.get_gradient = Sobel().cuda()\n self.criterionL1 = torch.nn.functional.l1_loss\n self.invalid_value = invalid_value\n\n def forward(self, features, depth_target):\n depth_target = depth_target.unsqueeze(1).contiguous()\n grad_target = self.get_gradient(depth_target)\n grad_pred = self.get_gradient(features)\n\n grad_target_dx = grad_target[:, 0, :, :].contiguous().view_as(depth_target)\n grad_target_dy = grad_target[:, 1, :, :].contiguous().view_as(depth_target)\n grad_pred_dx = grad_pred[:, 0, :, :].contiguous().view_as(depth_target)\n grad_pred_dy = grad_pred[:, 1, :, :].contiguous().view_as(depth_target)\n\n ones = torch.ones(depth_target.size(0), 1, depth_target.size(2), depth_target.size(3)).float().cuda()\n normal_target = torch.cat((-grad_target_dx, -grad_target_dy, ones), 1)\n normal_pred = torch.cat((-grad_pred_dx, -grad_pred_dy, ones), 1)\n\n # filter out invalid\n mask = torch.ones_like(depth_target).bool().cuda()\n if self.invalid_value is not None:\n mask = (depth_target != self.invalid_value).bool().cuda()\n\n loss_depth = torch.log(torch.abs(depth_target[mask] - features[mask]) + 0.5).mean()\n\n loss_dx = torch.log(torch.abs(grad_target_dx[mask] - grad_pred_dx[mask]) + 0.5).mean()\n loss_dy = torch.log(torch.abs(grad_target_dy[mask] - grad_pred_dy[mask]) + 0.5).mean()\n loss_gradient = loss_dx + loss_dy\n\n loss_normal = torch.abs(1 - self.cos_loss(normal_pred, normal_target))\n loss_normal = loss_normal[mask[:,0,:,:]].mean()\n\n #losses = {'l1': loss_depth, 'normal': loss_normal, 'gradient': loss_gradient}\n loss = (loss_depth + loss_normal + loss_gradient) / 3\n\n return loss\n\n#---------------------------------------------------------------------------------------------------\n\nclass ReconstructionLoss(nn.Module):\n \"\"\"\n Main class for Generalized R-CNN. Currently supports boxes and masks.\n It consists of three main parts:\n - backbone\n - rpn\n - heads: takes the features + the proposals from the RPN and computes\n detections / masks from it.\n \"\"\"\n\n def __init__(self):\n super(ReconstructionLoss, self).__init__()\n\n def forward(self, features, target):\n loss = torch.log(torch.abs(target - features) + 0.5).mean()\n\n return loss\n\n#---------------------------------------------------------------------------------------------------\n\nclass SemanticLoss(nn.Module):\n \"\"\"\n Main class for Generalized R-CNN. Currently supports boxes and masks.\n It consists of three main parts:\n - backbone\n - rpn\n - heads: takes the features + the proposals from the RPN and computes\n detections / masks from it.\n \"\"\"\n\n def __init__(self, loss_reweight):\n super(SemanticLoss, self).__init__()\n # semantic segmentation\n self.loss_reweight = loss_reweight\n\n def forward(self, features, target):\n output = F.log_softmax(features, dim=1)\n labels = target.cuda().long()\n loss = F.nll_loss(output, labels, weight=self.loss_reweight)\n return loss\n\n#---------------------------------------------------------------------------------------------------\n\nclass ContrastiveLoss(nn.Module):\n \"\"\"\n Main class for Generalized R-CNN. Currently supports boxes and masks.\n It consists of three main parts:\n - backbone\n - rpn\n - heads: takes the features + the proposals from the RPN and computes\n detections / masks from it.\n \"\"\"\n\n def __init__(self, nceT):\n super(ContrastiveLoss, self).__init__()\n # semantic segmentation\n self.T = nceT\n self.criterion = nn.CrossEntropyLoss()\n self.LARGE_NUM = 1e9\n\n def forward(self, q, k, mask=None):\n npos = q.shape[0] \n q = q / torch.norm(q, p=2, dim=1, keepdim=True)\n k = k / torch.norm(k, p=2, dim=1, keepdim=True)\n logits = torch.mm(q, k.transpose(1, 0)) # npos by npos\n out = torch.div(logits, self.T)\n\n if mask != None:\n out = out - self.LARGE_NUM * mask.float()\n\n labels = torch.arange(npos).cuda().long()\n loss1 = self.criterion(out, labels)\n loss2 = self.criterion(out.transpose(1, 0), labels)\n return (loss1 + loss2) / 2","sub_path":"pretrain/pri3d/model/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":5653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"647572995","text":"#! /usr/local/bin/python3\n\n# loadSFSite.py\n# Parse All Clients CSV with Python and SQLite\n# Copyright 2015 Chris Kauffman\n\nimport argparse\nimport csv\nimport sqlite3\nimport logging\nimport logging.config\nfrom apiReportToolsCommon import cleanStr\nfrom apiReportToolsCommon import cleanStrLower\n\nlogging.config.fileConfig('apiReportToolsLogging.conf')\nlogger = logging.getLogger('loadSFSite')\n\nparser = argparse.ArgumentParser(description='Send some emails through AWS.')\n\nparser.add_argument('-i', '--input', dest ='inputFile', help='csv input file', required=True)\nparser.add_argument('-d', '--dbfile', dest ='database', help='database file', default=':memory:')\nparser.add_argument('-u', '--update', dest ='update', action='store_true', help='Update fields when values differ')\n\nargs = parser.parse_args()\n\nlogger.info('Processing: ' + args.inputFile)\nlogger.info('Database: ' + args.database)\n\n# Open the input csv file\ntry:\n inputFileHandle = open(args.inputFile, 'r')\nexcept:\n print(\"Input file \" + args.inputFile + \" error.\")\n logger.error(\"Input file \" + args.inputFile + \" error.\")\n quit()\ninputDictReader = csv.DictReader(inputFileHandle, delimiter=',')\n\n# Setup the database connection\ndbConnection = sqlite3.connect(args.database)\ndbReadCursor = dbConnection.cursor()\ndbUpdateCursor = dbConnection.cursor()\n\ntotalCount = 0\nuniqueKeyCount = 0\nupdateKeyCount = 0\nbadRecordCount = 0\n\nbadAccountID = ('All Accounts',\n 'Copyright (c) 2000-2015 salesforce.com, inc. All rights reserved.',\n 'Confidential Information - Do Not Distribute',\n 'Bazaarvoice, Inc.')\n\nfor inputSiteRecord in inputDictReader:\n totalCount += 1\n \n #Validate input record \n if inputSiteRecord['Account ID'] is not None and len(inputSiteRecord['Account ID']) > 0 and inputSiteRecord['Account ID'] not in badAccountID and \"Generated\" not in inputSiteRecord['Account ID'] and inputSiteRecord['BV Site: BV Site Name'] is not None:\n # Check to see if we have seen this record\n SQL = '''SELECT ID,\n SF_ID,\n SF_ID_18,\n Name,\n fk_Accounts_ID,\n fk_Accounts_SF_ID_18\n FROM Sites\n WHERE ID = ?;'''\n SQLdata = (cleanStrLower(inputSiteRecord['BV Site: BV Site Name']), )\n dbReadCursor.execute(SQL, SQLdata)\n dbSiteRecord = dbReadCursor.fetchone()\n if dbSiteRecord is None:\n #Record does not exist. Adding a new record.\n uniqueKeyCount += 1\n SQL = '''INSERT INTO Sites (ID,\n SF_ID,\n SF_ID_18,\n Name,\n fk_Accounts_ID,\n fk_Accounts_SF_ID_18)\n VALUES (?, ?, ?, ?, ?, ?);'''\n SQLdata = (cleanStrLower(inputSiteRecord['BV Site: BV Site Name']),\n cleanStr(inputSiteRecord['BV Site: ID']),\n \"\",\n cleanStr(inputSiteRecord['BV Site: BV Site Name']),\n cleanStr(inputSiteRecord['Account ID']),\n cleanStr(inputSiteRecord['SFDC Account ID 18']), )\n try:\n dbUpdateCursor.execute(SQL, SQLdata)\n except sqlite3.Error as errorMessage:\n logger.error('SQL error on insert into Sites: ' + str(errorMessage) + ' on record: ' + str(inputSiteRecord))\n else:\n #Record exists. Will update if flag is set.\n updateKeyCount += 1\n if args.update:\n logger.info('Updating: ' + cleanStr(inputSiteRecord['BV Site: ID']) + ', \"' + cleanStr(inputSiteRecord['BV Site: BV Site Name']) + '\"')\n SQL = '''UPDATE Sites SET SF_ID = ?,\n SF_ID_18 = ?,\n Name = ?,\n fk_Accounts_ID = ?,\n fk_Accounts_SF_ID_18 = ?\n WHERE ID = ?;'''\n SQLdata = (cleanStr(inputSiteRecord['BV Site: ID']),\n \"\",\n cleanStr(inputSiteRecord['BV Site: BV Site Name']),\n cleanStr(inputSiteRecord['Account ID']),\n cleanStr(inputSiteRecord['SFDC Account ID 18']),\n cleanStrLower(inputSiteRecord['BV Site: BV Site Name']), )\n try:\n dbUpdateCursor.execute(SQL, SQLdata)\n except sqlite3.Error as errorMessage:\n logger.error('SQL error on update Sites: ' + str(errorMessage) + ' on record: ' + str(inputSiteRecord))\n else:\n logger.info('Skipping - No Update Flag: ' + cleanStr(inputSiteRecord['BV Site: ID']) + ', \"' + cleanStr(inputSiteRecord['BV Site: BV Site Name']) + '\"')\n else:\n logger.debug('Skipping - Bad Record: ' + cleanStr(inputSiteRecord['BV Site: ID']) + ', \"' + cleanStr(inputSiteRecord['BV Site: BV Site Name']) + '\"') \n badRecordCount += 1\n\ninputFileHandle.close()\ndbConnection.commit()\ndbConnection.close()\n \nlogger.info('Total Records: ' + str(totalCount))\nlogger.info('Bad Records: ' + str(badRecordCount))\nlogger.info('Added Records: ' + str(uniqueKeyCount))\nlogger.info('Existing Records: ' + str(updateKeyCount))\n\nquit()\n","sub_path":"loadSFSite.py","file_name":"loadSFSite.py","file_ext":"py","file_size_in_byte":5569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"77980319","text":"'''\n09/09/2018\n\nThis is a graph problem. We count the number of valid paths,\nof a certain length, from a certain point.\n\nWhat are the nodes? The 9 positions of the android keyboard.\n\nWhat are the adjacency relationships / how do we traverse?\nYou can move to an adjacent node if the adj node is unvisited.\nYou can skip over to certain nodes, but only if the 'middleman' node is\nvisited.\n\nWe can track visits easily through a boolean array, where indices are\nthe grid numbers, and values are whether or not the position is visited.\nWe create a nested array that tells us which grid pos to look at,\nin order to ascertain if a 'skip' position can be travelled to, based\non the value of the visit array.\n\nCombining the aforementioned features, we perform dfs with backtracking,\nto exhaust all possibilities of potential paths. The dfs 'lags', once we\nenter a position, we have to adjust the visited array, and prepare to enter\nthe next positions from it. Like all backtracking methods, we need a base case,\nwhich here is rem == 0, which means, we are 0 spots away from a path.\n\nIf we aren't, then we see if there are any other places we can visit.\nFirst, we mark this position as visited, before trying to visit an unvisited\nneighbor or 'skip' position. \n\nAgain, like other backtracking methods, once we thoroughly explore possibilities\nfrom this context, we 'clean up' before returning, by marking the spot as unvisited,\nso that the previous context, which will try a different position to backtrack on,\nwon't be affected.\n\nIt's worth really thinking about backtracking. On the abstract level, it's about building\na combo, returning/adding the combo eventually when a condition is reached, but not fully\nbacktracking to the start, so we can intelligently use the 'prefix' of the combo and save\nus some work in finding the next combo.\n\n1 is marked...\n1->x\n1->y\n1->z\nunmark\n\n2 is marked\n2->x\n2->y\n2->z\n'''\n\n# dfs with backtracking - 4 parts\ndef dfs(rem, skip, vis, pos):\n if rem == 0: return 1 # 1) base case, return, or attach the completed partial to a larger result array\n total = 0\n for i in range(1,10): # 3) from this context, recurse/ visit other positions, but on the basis that this pos is marked\n if not vis[i] and (skip[pos][i] == 0 or vis[skip[pos][i]]):\n vis[i] = True # 2) not base case, mark this position 'into the prefix'\n total += dfs(rem-1, skip, vis, i)\n vis[i] = False # 4) un-mark pos on your way out / unmark this context from the 'prefix'\n return total\n\nclass Solution(object):\n def numberOfPatterns(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n skip = [[0]*10 for _ in range(10)]\n skip[1][3] = skip[3][1] = 2\n skip[1][7] = skip[7][1] = 4\n skip[3][9] = skip[9][3] = 6\n skip[7][9] = skip[9][7] = 8\n skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip[7][3] = skip[4][6] = skip[6][4] = 5\n paths = 0\n for i in range(m,n+1):\n vis = [0]*10\n vis[2] = True\n paths += 4*dfs(i-1, skip, vis, 2)\n vis = [0]*10\n vis[1] = True\n paths += 4*dfs(i-1, skip, vis, 1)\n vis = [0]*10\n vis[5] = True\n paths += dfs(i-1, skip, vis, 5)\n return paths","sub_path":"recursion/dfs/android-unlock-patterns.py","file_name":"android-unlock-patterns.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"354223930","text":"#################################################################################### \r\n# Python ODBC API Segment, Developed by M.M. Todinov Build: 1.0.4 DATE: 01/11/2019 #\r\n####################################################################################\r\n\r\n################################\r\n#Library Declaration sequence. #\r\n################################\r\nimport pyodbc as pyodbc\r\nimport json\r\nimport pandas\r\nimport sys\r\nimport os\r\nimport operator\r\nimport time\r\nimport datetime\r\nimport binascii\r\nimport codecs\r\nfrom datetime import datetime\r\n################################\r\n# #\r\n################################\r\n# Keep it Simple Stupid! #\r\n####################################################################################\r\n# Global Variable Declaration sequence #\r\n####################################################################################\r\n\r\nx = 250\r\n\r\nx2 = 0.000000000001 #incremental seed\r\n\r\nsecs = 5 #seed initiator for pause sequence\r\n\r\n####################################################################################\r\n# Global variable declaration end #\r\n####################################################################################\r\n\r\n###################################################################\r\n# Some other example server values are / alternate login strings. #\r\n# server = 'localhost\\sqlexpress' # for a named instance #\r\n# server = 'myserver,port' # to specify an alternate port #\r\n###################################################################\r\n# server configuration changed via json file configuration. #\r\n# safer for parsing server credentials #\r\n###################################################################\r\nwith open('config.json') as json_data_file:\r\n data = json.load(json_data_file)\r\n\r\nserver = data['host'] \r\ndatabase = data['name']\r\nusername = data['user']\r\npassword = data['pass'] \r\nconn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+' ;DATABASE='+database+';UID='+username+';PWD='+ password)\r\ncursor = conn.cursor()\r\n\r\n#######################\r\n# SQL Queries segment #\r\n#######################\r\n\r\nsql_command_line_Code = 'Select TOP 10 * FROM HelloTelecomData'\r\n\r\nstaff_telephones = 'SELECT Name, Extension_Number FROM Staff_Telephones'\r\n\r\ninsertion_string_values = ()\r\n\r\n\r\n#Function Declaration sequence\r\n\r\n#Talk Time BULK Declaration\r\n#Runs SQL query based on INPUT team,\r\n# Finds Extensions\r\n# Cleans Strings\r\n# Commences insertion\r\n# using conglomoration of insertion for loop query sequences\r\n# ellegant solution.\r\ndef insert_Bulk_SystemIDs():\r\n print(\" #################################################################### \")\r\n print(\" # Welcome to the bulk talk time insertion segment # \")\r\n print(\" # Please select from the available teams # \")\r\n print(\" #################################################################### \")\r\n print(\" * Available Teams: SME GS, SME AT, SME CW, SME TW, LG * \")\r\n print(\" *******************************************************\")\r\n TeamSelection = input()\r\n print(\" selection: \" + TeamSelection)\r\n\r\n #query that finds the relevant extensions related to a specific team\r\n group_team_query = 'SELECT [Extension_Number] FROM [HelloTelecom].[dbo].[Staff_Telephones] WHERE Team = ?'\r\n\r\n #execute query\r\n cursor.execute(group_team_query, TeamSelection)\r\n data = cursor.fetchall()\r\n print(data)\r\n #testing access to storage array\r\n # c = str(data[1])\r\n # c = c.replace('(', '')\r\n # c = c.replace(')', '')\r\n # c = c.replace(',', '')\r\n # c = c.replace(' ', '')\r\n # c = c.replace (\"'\",'' )\r\n # c = int(c)\r\n #\r\n #c = str(c)\r\n # Test scripts for testing stripping of excess from SQL tuple, conversion ftw!\r\n \r\n # asking first for Duration and Date Time, so that we can mimick in the for loop and menifest dynamic insertion strings.\r\n\r\n print(\"Select date time stamp e.g. THIS FORMAT 24/10/2192\")\r\n preDeterminedTime = ' 16:00:01'\r\n StartTime = input()\r\n StartTime2 = StartTime + preDeterminedTime\r\n\r\n print(\"Duration 1 e.g. 00:00:00 please insert\")\r\n Duration = input()\r\n\r\n #commence creation of multiple insertion strings, cleaning and insertion of duplicated data for all aspects.\r\n\r\n for source in data:\r\n file = open(\"FindMaxPrimKey.sql\", encoding = 'utf-8-sig')\r\n\r\n c = str(source)\r\n c = c.replace('(', '')\r\n c = c.replace(')', '')\r\n c = c.replace(',', '')\r\n c = c.replace(' ', '')\r\n c = c.replace (\"'\",'' )\r\n c = int(c)\r\n c = str(c)\r\n\r\n full_sql = file.read()\r\n # sql_commandz = full_sql.split(';') #left in incase split needed later on\r\n\r\n# sql_commandz.decode('utf-8') # inactive decode utf 8 script.\r\n\r\n# auto primary key generation, tested for validity, floating point increment.\r\n \r\n cursor.execute(full_sql) \r\n \r\n zMaxTemp = cursor.fetchone()\r\n\r\n Temp2 = float(zMaxTemp[0])\r\n\r\n newPrimKey = str(Temp2 + x2) \r\n\r\n \r\n # using same primary key creation with mass insertion, after individual insertion, it finds max again and re inserts for max :), always guaranteeing the sucess of\r\n # primary key relationships! \r\n \r\n Id = newPrimKey\r\n\r\n\r\n print(\"Select Source\")\r\n SourceNumber = c\r\n DestinationNumber = \"Time Reimbursed\"\r\n Disposition = \"ANSWERED\"\r\n\r\n \r\n Billing = Duration\r\n \r\n Recording = \"Sanctioned by Richard F.\"\r\n FingerPrint = \"Auto Insertion, PYODBC_Conn_Proj ver 1.0.4\"\r\n DataRunId = \"2094\"\r\n\r\n\r\n SQLCommand = (\"INSERT INTO HelloTelecomData (Id, StartTime, SourceNumber, DestinationNumber, Disposition, Duration, Billing, Recording, FingerPrint, DataRunId) VALUES (?,?,?,?,?,?,?,?,?,?)\")\r\n Values = [Id, StartTime2, SourceNumber, DestinationNumber, Disposition, Duration, Billing, Recording, FingerPrint, DataRunId]\r\n print(\"insertion will now take place\")\r\n cursor.execute(SQLCommand, Values)\r\n conn.commit()\r\n print(\"Insertion String Sucess\")\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# plan to confine primary key function to separate function for simplicity and debugging characteristics.\r\n\r\ndef primaryKeyFunction():\r\n print(\"PrimaryKeyInitiated\")\r\n\r\n############################################################\r\n# insertion custom function declaration sequence commence! #\r\n############################################################\r\n\r\ndef talk_time_insert():\r\n\r\n file = open(\"FindMaxPrimKey.sql\", encoding = 'utf-8-sig')\r\n\r\n full_sql = file.read()\r\n\r\n\r\n\r\n# sql_commandz = full_sql.split(';') #left in incase split needed later on\r\n\r\n# sql_commandz.decode('utf-8') # inactive decode utf 8 script.\r\n\r\n# auto primary key generation, tested for validity, floating point increment.\r\n \r\n cursor.execute(full_sql) \r\n \r\n zMaxTemp = cursor.fetchone()\r\n\r\n Temp2 = float(zMaxTemp[0])\r\n\r\n newPrimKey = str(Temp2 + x2) \r\n\r\n \r\n\r\n \r\n Id = newPrimKey\r\n print(\"Select date time stamp e.g. THIS FORMAT 24/10/2192\")\r\n preDeterminedTime = ' 16:00:01'\r\n StartTime = input()\r\n StartTime2 = StartTime + preDeterminedTime\r\n\r\n print(\"Select Source\")\r\n SourceNumber = input()\r\n DestinationNumber = \"Time Reimbursed\"\r\n Disposition = \"ANSWERED\"\r\n print(\"Duration 1 e.g. 00:00:00 please insert\")\r\n Duration = input()\r\n \r\n Billing = Duration\r\n \r\n Recording = \"Sanctioned by Richard F.\"\r\n FingerPrint = \"Auto Insertion, PYODBC_Conn_Proj ver 1.0\"\r\n DataRunId = \"2094\"\r\n\r\n\r\n SQLCommand = (\"INSERT INTO HelloTelecomData (Id, StartTime, SourceNumber, DestinationNumber, Disposition, Duration, Billing, Recording, FingerPrint, DataRunId) VALUES (?,?,?,?,?,?,?,?,?,?)\")\r\n Values = [Id, StartTime2, SourceNumber, DestinationNumber, Disposition, Duration, Billing, Recording, FingerPrint, DataRunId]\r\n print(\"insertion will now take place\")\r\n cursor.execute(SQLCommand, Values)\r\n conn.commit()\r\n print(\"Insertion String Sucess\")\r\n\r\n ##########################################################################\r\n # Alternate close scripts.\r\n #conn.close()\r\n #print(\"Connection Close\")\r\n #\r\n # if confused about what extension an individual is at, search the db!!!\r\n ##########################################################################\r\ndef SearchEmployeeDataBase():\r\n print(\" \")\r\n print(\" #################################################################### \")\r\n print(\" # Option 2 - Database Search option selected! # \")\r\n print(\" # Please select a name followed by % to search for specific source # \")\r\n print(\" #################################################################### \")\r\n print(\" * \")\r\n print(\" * \")\r\n print(\" * \")\r\n print(\" * \")\r\n name = input()\r\n print(\"Thanks:\")\r\n SQL = \"SELECT Extension_Number, Name FROM Staff_Telephones WHERE Full_Name LIKE ?\"\r\n cursor.execute(SQL, name)\r\n data = cursor.fetchall()\r\n print( data )\r\n\r\n\r\n#End\r\ndef menu():\r\n print(\" _____________________________________________________________________ \")\r\n print(\" (#####################################################################) \")\r\n print(\" ) ( \")\r\n print(\" ( Welcome to the automated BSI Report Management System ) \")\r\n print(\" ) + ( \")\r\n print(\" ( Please select a number from the menu options ) \")\r\n print(\" ) ( \")\r\n print(\" (_____________________________________________________________________) \")\r\n print(\" ) 1. Talk_Time_Once | | 2. Search for Name | | 3. Exit BRMS system ( \")\r\n print(\" ( 4. Team TT alloc | | 5. [input menu] | | 6. [input menu] ) \")\r\n print(\" )___________________|_|____________________|_|______________________( \")\r\n print(\" (#####################################################################) \")\r\n print(\" * \")\r\n print(\" * \")\r\n print(\" * \")\r\n print(\" * \")\r\n a = input()\r\n if (a == \"1\"):\r\n talk_time_insert()\r\n print(\"Talk Time Assigned!\")\r\n elif (a == \"2\"):\r\n SearchEmployeeDataBase()\r\n elif (a == \"3\"):\r\n print(\"Follow the white rabbit...\")\r\n time.sleep(secs)\r\n exit()\r\n conn.close()\r\n elif (a == \"4\"):\r\n insert_Bulk_SystemIDs()\r\n \r\n menu()\r\n#declaration end \r\n\r\n########\r\n#\r\n# Custom Main Function, calls menu, recalls..\r\n#\r\n########\r\n\r\nmenu()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"PYODBC_Connector_Project.py","file_name":"PYODBC_Connector_Project.py","file_ext":"py","file_size_in_byte":11571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"556888118","text":"# --- coding: utf-8 ---\n\"\"\"\nebookjapanの操作を行うためのクラスモジュール\n\"\"\"\n\nimport base64\nimport io\nimport re\nimport time\nfrom PIL import Image\nfrom retry import retry\nfrom selenium.webdriver.common.keys import Keys\nfrom manager import AbstractManager\n\n\nclass Manager(AbstractManager):\n \"\"\"\n ebookjapanの操作を行うためのクラス\n\n TODO reset to first page\n \"\"\"\n\n def __init__(self, driver, config=None, directory='./', prefix=''):\n \"\"\"\n ebookjapanの操作を行うためのコンストラクタ\n @param driver splinter のブラウザインスタンス\n \"\"\"\n super().__init__(driver, config, directory, prefix)\n\n self.next_key = Keys.ARROW_LEFT\n \"\"\"\n 次のページに進むためのキー\n \"\"\"\n self.previous_key = None\n \"\"\"\n 前のページに戻るためのキー\n \"\"\"\n self.current_page_element = None\n \"\"\"\n 現在表示されているページのページ番号が表示されるエレメント\n \"\"\"\n self.retry_count = 0\n\n def _fix_window_size(self):\n canvas = self.driver.find_elements_by_css_selector('canvas')[0]\n\n w = 480\n h = 640\n\n self.driver.set_window_size(w, h)\n self._sleep(1)\n\n self.set_attribute(canvas, 'style', f'width: {w}px; height: {h}px;')\n self._sleep(1)\n\n height = int(canvas.get_attribute('height'))\n print(f'height: {height}')\n\n self.driver.set_window_size(w, height)\n self._sleep(1)\n\n style = canvas.get_attribute('style')\n style = re.sub(r'height:\\s+\\d+px;$', f'height: {height}px;', style)\n self.set_attribute(canvas, 'style', style)\n print(f'style: {style}')\n self._sleep()\n\n width = int(canvas.get_attribute('width'))\n print(f'width: {width}')\n\n self.driver.set_window_size(width, height)\n print(f'window: {width}x{height}')\n self._sleep(1)\n\n print(f\"canvas: {canvas.get_attribute('width')}x{canvas.get_attribute('height')}\")\n style = canvas.get_attribute('style')\n print(f'style: {style}')\n\n def start(self, url=None):\n \"\"\"\n ページの自動スクリーンショットを開始する\n @return エラーが合った場合にエラーメッセージを、成功時に True を返す\n \"\"\"\n self._wait()\n\n # resize by option\n self._sleep(2)\n\n self.driver.switch_to.frame(0)\n self._fix_window_size()\n\n total = self._get_total_page()\n if total is None:\n return '全ページ数の取得に失敗しました'\n\n excludes = self._get_blank_check_exclude_pages(total)\n print(f'excludes: {excludes}')\n\n self.current_page_element = self._get_current_page_element()\n if self.current_page_element is None:\n return '現在のページ情報の取得に失敗しました'\n\n self._set_total(total)\n\n self._save_image(0, self._capture())\n\n self.driver.find_element_by_css_selector('body').click()\n self._press_key(self.next_key)\n self.pbar.update(1)\n\n # different size from cover\n self._fix_window_size()\n\n for _count in range(1, total):\n\n self.retry_count = 0\n self._save_image(_count, self._capture(_count in excludes))\n self.pbar.update(1)\n\n self._next()\n self._sleep()\n\n return True\n\n def _get_blank_check_exclude_pages(self, _total):\n return [(_total - 1 + p) if p <= 0 else p for p in self.sub_config.blank_check_excludes]\n\n def _get_total_page(self):\n \"\"\"\n 全ページ数を取得する\n 最初にフッタの出し入れをする\n @return 取得成功時に全ページ数を、失敗時に None を返す\n \"\"\"\n elements = self.driver.find_elements_by_css_selector('.footer__page-output > .total-pages')\n if len(elements) == 0:\n return None\n for _ in range(Manager.MAX_LOADING_TIME):\n if elements[0].get_attribute('innerHTML') != '0':\n return int(elements[0].get_attribute('innerHTML'))\n time.sleep(1)\n return None\n\n def _get_current_page_element(self):\n \"\"\"\n 現在表示されているページのページ数が表示されているエレメントを取得する\n @return ページ数が表示されているエレメントがある場合はそのエレメントを、ない場合は None を返す\n \"\"\"\n elements = self.driver.find_elements_by_css_selector('.footer__page-output > output')\n if len(elements) != 0:\n return elements[0]\n print(\"*** NO CURRENT ELEMENT ***\")\n return None\n\n def _get_current_page(self):\n \"\"\"\n 現在のページを取得する\n @return 現在表示されているページ\n \"\"\"\n try:\n return int(self.current_page_element.get_attribute('innerHTML')[:-2])\n except:\n print(\"*** NO CURRENT PAGE ***\")\n return 0\n\n @retry(tries=10, delay=1)\n def _capture(self, ignore_blank=False):\n \"\"\"\n @param ignore_blank ignore mistaken capture or not\n \"\"\"\n base64_image = self.driver.get_screenshot_as_base64()\n image = Image.open(io.BytesIO(base64.b64decode(base64_image)))\n if self._is_config_jpeg():\n image = image.convert('RGB')\n\n if self._is_blank_image(image, 255) or self._is_blank_image(image, 245):\n print(f' blank page detected {self.retry_count}')\n if not ignore_blank:\n if self.retry_count < self.sub_config.blank_check_giveup:\n self.retry_count += 1\n raise Exception\n else:\n print(' give up checking, ignore blank')\n\n return image\n\n @staticmethod\n def _is_blank_image(image, color):\n width, height = image.size\n for y in range(height):\n for x in range(width):\n r, g, b = image.getpixel((x, y))\n if r != color or g != color or b != color:\n return False\n return True\n\n def _next(self):\n \"\"\"\n 次のページに進む\n スペースで次のページにすすめるのでスペースキー固定\n \"\"\"\n current_page = self._get_current_page()\n self._press_key(self.next_key)\n if self._get_current_page() and self._get_current_page() < self.pbar.total - 1:\n while self._get_current_page() and self._get_current_page() != current_page + 1:\n time.sleep(0.1)\n","sub_path":"ebookjapan/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":6721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"551874830","text":"from flask import Flask, redirect, url_for, render_template, request, jsonify\nfrom flask_bootstrap import Bootstrap\nfrom beatCount import countBeats\n\n# declare constants\nHOST = '0.0.0.0'\nPORT = 5000\n\nbeats = 0\n\n# initialize flask application\napp = Flask(__name__)\nBootstrap(app)\n\n# sample hello world page\n@app.route('/')\ndef home():\n return render_template(\"home.html\")\n\n@app.route('/about/')\ndef about():\n return render_template(\"about.html\")\n \n@app.route('/resources/')\ndef resources():\n return render_template(\"resources.html\")\n\n#actual app components\n@app.route('/start/', methods=['GET','POST'])\ndef start():\n return render_template(\"start.html\")\n\n#print(request.form)\n@app.route('/meditating/', methods=['GET','POST'])\ndef med():\n if request.method == 'POST':\n #request.form\n # values=countBeats('https://open.spotify.com/track/6K4t31amVTZDgR3sKmwUJJ?si=S53B-lXPR9SFaku_RnzLsg', '4-4-8') \n songURL = request.form['songURL']\n # Getting the embed url:\n embedURL = songURL[:24] + \"/embed\" + songURL[24:]\n\n breathTechnique = request.form['breathTechnique']\n values=countBeats(songURL, breathTechnique)\n return render_template('med.html' ,inhale=values['inhale'], hold=values['hold'], exhale=values['exhale'], songURL=songURL, breathTechnique=breathTechnique, emb = embedURL)\n else:\n songURL = request.args.get['songURL']\n embedURL = songURL[:24] + \"/embed\" + songURL[24:]\n breathTechnique = request.args.get['breathTechnique']\n values=countBeats(songURL, breathTechnique)\n return render_template('med.html' ,inhale=values['inhale'], hold=values['hold'], exhale=values['exhale'], songURL=songURL, breathTechnique=breathTechnique, emb = embedURL)\n\n#sample api endpoint\n@app.route('/api/test', methods=['GET', 'POST'])\ndef test():\n if request.method == 'POST':\n # get parameters from post request\n parameters = request.get_json()\n if 'test' in parameters:\n return jsonify({'value': parameters['test']})\n return jsonify({'error'})\n else:\n return jsonify({'test': 'success'})\n\nif __name__ == '__main__':\n app.run(host=HOST, debug=True, port=PORT)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"424977901","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\ndef add_pedi(apps, schema_editor):\n Instruments = apps.get_model(\"study\", \"Instruments\")\n new_inst,c = Instruments.objects.get_or_create(pk=33,instrument_name='PEDI')\n new_inst.save()\n VisitInstrumentLookup = apps.get_model(\"study\", \"VisitInstrumentLookup\")\n Visit = apps.get_model(\"study\", \"Visit\")\n for v in Visit.objects.all():\n vnum = v.visit_num\n for cid in range(1,3):\n new_vil,c = VisitInstrumentLookup.objects.get_or_create(visit_num = vnum, instrument = new_inst, cohort_id=cid)\n new_vil.save()\n\n\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('study', '0036_tblpedi'),\n ]\n\n operations = [\n migrations.RunPython(add_pedi),\n ]\n\n\n\n\n\n\n\n\n","sub_path":"study/migrations/0037_auto_20150417_1357.py","file_name":"0037_auto_20150417_1357.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"103469599","text":"import json\nfrom _decimal import Decimal\nfrom json import JSONDecodeError\n\nimport dateutil\nfrom flask import request, jsonify, current_app\n\nfrom pa import db\nfrom pa.fin.models import Asset, Currency, Record\nfrom ..csv import csv\n\nFILES_NOT_FOUND_ERROR_MESSAGE = 'Files Not Found'\nINVALID_FILES_ERROR_MESSAGE = 'Invalid File Format'\n\n\n@csv.route('csv/save', methods=[\"POST\"])\ndef save():\n raw_data = request.form.get('data')\n if raw_data is None:\n return jsonify({'error': FILES_NOT_FOUND_ERROR_MESSAGE}), 400\n try:\n json_data = json.loads(raw_data)\n except JSONDecodeError as error:\n current_app.logger.exception(error)\n return jsonify({'error': INVALID_FILES_ERROR_MESSAGE}), 400\n\n asset_query = db.session.query(Asset.name)\n existing_assets = [asset.name for asset in asset_query]\n new_assets = [Asset(name=name, currency=Currency(name.split('_')[0]))\n for name in json_data.keys() if name not in existing_assets]\n if new_assets:\n db.session.bulk_save_objects(\n new_assets\n )\n db.session.commit()\n\n involved_assets = db.session.query(Asset).filter(Asset.name.in_(json_data.keys()))\n income_records = []\n for asset in involved_assets:\n for record in json_data[asset.name]:\n income_records.append(Record(date=dateutil.parser.parse(record['date']).date(),\n amount=Decimal(record['amount'].replace(',', '.')),\n is_replenish=record['category'],\n asset_id=asset.id))\n\n record_query = db.session.query(Record)\n new_records = []\n for record in income_records:\n duplicate = False\n for db_record in record_query:\n if record.date == db_record.date \\\n and record.amount == db_record.amount \\\n and record.is_replenish == db_record.is_replenish:\n duplicate = True\n break\n if not duplicate:\n new_records.append(record)\n db.session.bulk_save_objects(new_records)\n db.session.commit()\n return jsonify()\n","sub_path":"pa/fin/routes/csv/save.py","file_name":"save.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"217135217","text":"def main():\n ar = []\n leftSide = []\n rightSide = []\n vahinPe = []\n kitneAadmiThey = int(input())\n numbersKiKataar = input().split(\" \")\n for index in range(0,kitneAadmiThey):\n ar.append(int(numbersKiKataar[index]))\n for num in ar:\n if ar[0] == num:\n vahinPe.append(num)\n else:\n if num < ar[0]:\n leftSide.append(num)\n else:\n rightSide.append(num)\n for num in leftSide:\n print(num,end=' ')\n for num in vahinPe:\n print(num,end=' ')\n for num in rightSide:\n print(num,end=' ')\nif __name__ == '__main__':\n main()\n","sub_path":"HRC/hackerRankQuickSort.py","file_name":"hackerRankQuickSort.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"571436611","text":"# !/usr/bin/env python\r\n\r\nimport math\r\nimport time\r\nimport datetime\r\nimport grovepi\r\nimport json\r\nfrom time import sleep\r\nfrom grovepi import *\r\nimport sqlite3 as sql\r\nfrom math import isnan\r\n\r\n# Temp/humidity sensor port\r\nsensor_port = 7\r\nsensor_type = 0\r\n\r\n# List to hold tuples of sensor data\r\nsensorData = []\r\n\r\ndef readData():\r\n # insert reading as tuple in list\r\n [temp, humidity] = grovepi.dht(sensor_port, sensor_type)\r\n\r\n # ensure that reading is a number\r\n if not math.isnan(temp) and not math.isnan(humidity):\r\n\r\n # celsius to fahrenheit\r\n fahrenheit = ((temp * 9) / 5.0) + 32\r\n print(\"temp = %.02f F humidity =%.02f%%\" % (fahrenheit, humidity))\r\n t = fahrenheit\r\n h = humidity\r\n\r\n sensorData.append([t, h])\r\n\r\n# node data\r\nclass reading:\r\n temp = 0\r\n hum = 0\r\n\r\n # parameterized constructor\r\n def __init__(self, t, h):\r\n self.temp = t\r\n self.hum = h\r\n\r\n\r\n# node struct\r\nclass newNode:\r\n\r\n # Node constructor\r\n def __init__(self, key, reading):\r\n\r\n self.data = reading\r\n self.key = key\r\n self.count = 1\r\n self.left = None\r\n self.right = None\r\n self.height = 1\r\n\r\n\r\n# The function finds keys in range [low, high)\r\ndef range(root, low, high, range_list):\r\n # Base Case\r\n if root is None:\r\n return\r\n\r\n # move toward low end of range\r\n if low < root.key:\r\n range(root.left, low, high, range_list)\r\n\r\n # If data is in range\r\n if low <= root.key and high > root.key:\r\n\r\n # add in-range data to list\r\n range_list.append([root.data.temp, root.data.hum])\r\n\r\n # move toward high end of range\r\n if high > root.key:\r\n range(root.right, low, high, range_list)\r\n\r\n return range_list\r\n\r\n# inorder traversal function\r\ndef inorder(root, order_list):\r\n\r\n if root is not None:\r\n\r\n # move to left subtree\r\n inorder(root.left, order_list)\r\n\r\n # add data to list\r\n order_list.append([root.data.temp, root.data.hum])\r\n\r\n # move to right subtree\r\n inorder(root.right, order_list)\r\n\r\n return order_list\r\n\r\n\r\n# Insert a node function\r\ndef insert(root, key, bid):\r\n # If tree is empty, create new node\r\n if root is None:\r\n k = newNode(key, bid)\r\n return k\r\n\r\n # recursive function moves down the tree\r\n if key < root.key:\r\n root.left = insert(root.left, key, bid)\r\n else:\r\n root.right = insert(root.right, key, bid)\r\n\r\n # calculate height\r\n root.height = 1 + max(getHeight(root.left),\r\n getHeight(root.right))\r\n\r\n # get balance\r\n bal = getBalance(root)\r\n\r\n # If the node is unbalanced, re-balance\r\n # case 1\r\n if bal > 1 and key < root.left.key:\r\n return rotateRight(root)\r\n\r\n # case 2\r\n if bal < -1 and key > root.right.key:\r\n return rotateLeft(root)\r\n\r\n # case 3\r\n if bal > 1 and key > root.left.key:\r\n root.left = rotateLeft(root.left)\r\n return rotateRight(root)\r\n\r\n # case 4\r\n if bal < -1 and key < root.right.key:\r\n root.right = rotateRight(root.right)\r\n return rotateLeft(root)\r\n\r\n return root\r\n\r\n# left rotation\r\ndef rotateLeft(z):\r\n\r\n y = z.right\r\n tree2 = y.left\r\n\r\n # rotate\r\n y.left = z\r\n z.right = tree2\r\n\r\n # Update height\r\n z.height = 1 + max(getHeight(z.left),\r\n getHeight(z.right))\r\n y.height = 1 + max(getHeight(y.left),\r\n getHeight(y.right))\r\n\r\n # Return the new root\r\n return y\r\n\r\n# right rotation\r\ndef rotateRight(z):\r\n\r\n y = z.left\r\n tree3 = y.right\r\n\r\n # rotate\r\n y.right = z\r\n z.left = tree3\r\n\r\n # update height\r\n z.height = 1 + max(getHeight(z.left),\r\n getHeight(z.right))\r\n y.height = 1 + max(getHeight(y.left),\r\n getHeight(y.right))\r\n\r\n # Return the new root\r\n return y\r\n\r\n\r\n# calc height\r\ndef getHeight(root):\r\n\r\n if not root:\r\n return 0\r\n\r\n return root.height\r\n\r\n\r\n# calc balance\r\ndef getBalance(root):\r\n\r\n if not root:\r\n return 0\r\n\r\n return getHeight(root.left) - getHeight(root.right)\r\n\r\n\r\n# delete entire tree function\r\ndef deleteTree(node):\r\n if node:\r\n\r\n # recursively visit all nodes\r\n deleteTree(node.left)\r\n deleteTree(node.right)\r\n\r\n # delete pointers\r\n node.left = None\r\n node.right = None\r\n\r\n\r\n# find minimum key value\r\ndef minNode(node, min_data):\r\n current = node\r\n\r\n # move only left\r\n while current.left is not None:\r\n current = current.left\r\n\r\n # add min temp node to list\r\n min_data.append([current.data.temp, current.data.hum])\r\n return min_data\r\n\r\n\r\n# find maximum key value\r\ndef maxNode(node, max_data):\r\n\r\n current = node\r\n\r\n # move only to right\r\n while current.right is not None:\r\n current = current.right\r\n\r\n # add max temp node to list\r\n max_data.append([current.data.temp, current.data.hum])\r\n return max_data\r\n\r\n\r\n# calculates average of list\r\ndef calc_avg(num):\r\n\r\n avg = None\r\n sums = 0\r\n for t in num:\r\n sums = sums + t\r\n\r\n avg = sums / len(num)\r\n return avg\r\n\r\n# find average of tuple indices in list of tuples\r\ndef list_tuple_avg(list, tuple_index):\r\n\r\n avg = None\r\n\r\n if list:\r\n t = [lis[tuple_index] for lis in list]\r\n avg = calc_avg(t)\r\n\r\n return avg\r\n\r\n# get name of previous month\r\ndef find_previous_month(mo):\r\n\r\n monthList = [\"December\", \"January\", \"February\", \"March\", \"April\",\r\n \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\"]\r\n\r\n num = int(mo)\r\n num2 = (num - 1)\r\n\r\n last_month = monthList[num2]\r\n\r\n return last_month\r\n\r\n\r\n# connect to database\r\ndef create_connection():\r\n\r\n conn = None\r\n\r\n try:\r\n conn = sql.connect('today.db')\r\n except sql.Error as e:\r\n print(e)\r\n\r\n return conn\r\n\r\n\r\n# create tables\r\ndef create_tables(conn):\r\n\r\n cur = conn.cursor()\r\n cur.execute(\"\"\"CREATE TABLE IF NOT EXISTS today ( \r\n Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,\r\n avgTemp REAL,\r\n high REAL,\r\n low REAL,\r\n tempSwing REAL,\r\n avgHum REAL, \r\n avgFreezeHum REAL,\r\n avgHotHum REAL \r\n\r\n )\"\"\")\r\n\r\n cur.execute(\"\"\"CREATE TABLE IF NOT EXISTS month (\r\n id INTEGER primary key,\r\n monthName TEXT, \r\n avgTemp REAL,\r\n high REAL,\r\n low REAL,\r\n tempSwing REAL,\r\n avgHum REAL,\r\n avgFreezeHum REAL,\r\n avgHotHum REAL \r\n\r\n )\"\"\")\r\n conn.commit()\r\n\r\n\r\n# insert daily record\r\ndef insert_today(conn):\r\n\r\n # insert tuple as record\r\n cur = conn.cursor()\r\n cur.execute(\"INSERT INTO today (avgTemp, high, low, tempSwing, avgHum, avgFreezeHum, avgHotHum)\"\r\n \" VALUES (?,?,?,?,?,?,?)\", (a, b, c, d, e, f, g)) # record\r\n conn.commit()\r\n\r\n\r\ndef select_today(conn, last_month):\r\n # insert tuple as record\r\n cur = conn.cursor()\r\n cur.execute(\"SELECT MAX(high), MIN(low), MAX(tempSwing) FROM today\")\r\n selection = (cur.fetchall())\r\n high = selection[0][0]\r\n low = selection[0][1]\r\n swing = selection[0][2]\r\n cur.execute(\"SELECT COUNT(high) FROM today WHERE avgHum > 80\")\r\n sel = (cur.fetchall())\r\n dd = sel[0][0]\r\n cc = str(dd)\r\n\r\n # display data/statistics\r\n print(\"Daily Extremes for the Previous Month (\", last_month, \")\")\r\n print(\"High Temperature: \", high)\r\n print(\"Low Temperature: \", low)\r\n print(\"High Daily Swing: \", swing)\r\n print(\"Humid Days: \", cc)\r\n print()\r\n\r\n\r\ndef insert_select_month(conn, prev_mo):\r\n\r\n # insert tuple as record\r\n cur = conn.cursor()\r\n cur.execute((\"INSERT INTO month (avgTemp, high, low, tempSwing, avgHum, avgFreezeHum, avgHotHum)\"\r\n \" SELECT avg(avgTemp), avg(high), avg(low), avg(tempSwing), \"\r\n \"avg(avgHum), avg(avgFreezeHum), avg(avgHotHum) FROM today\"))\r\n conn.commit()\r\n\r\n # add month name into record\r\n lastRecord = (cur.lastrowid)\r\n cur.execute(\"UPDATE month SET monthName=? WHERE ID=?\", (prev_mo, lastRecord))\r\n conn.commit()\r\n\r\n # count number of records\r\n cur.execute(\"SELECT COUNT(*) FROM month\")\r\n sel = (cur.fetchall())\r\n dd = sel[0][0]\r\n cc = str(dd)\r\n\r\n # select most recend record\r\n cur.execute(\"SELECT * FROM month WHERE id=?\", cc)\r\n selection = (cur.fetchall())\r\n\r\n # generate output variables\r\n avg = selection[0][2]\r\n high = selection[0][3]\r\n low = selection[0][4]\r\n swing = selection[0][5]\r\n hum = selection[0][6]\r\n freeze = selection[0][7]\r\n hot = selection[0][8]\r\n\r\n # display data/statistics\r\n print(\"Monthly Averages For The Previous Month (\", prev_mo, \")\")\r\n print(\"Average Temperature: \", avg)\r\n print(\"Average High Temperature: \", high)\r\n print(\"Average Low Temperature: \", low)\r\n print(\"Average Swing: \", swing)\r\n print(\"Average Humidity: \", hum)\r\n print(\"Average Humidity When Temp Below Freezing: \", freeze)\r\n print(\"Average Humidity When Temp > 85 Degrees: \", hot)\r\n\r\n \r\n# Driver Code\r\nif __name__ == '__main__':\r\n\r\n while True:\r\n\r\n # check local time\r\n curr_time = time.localtime()\r\n curr_clock = time.strftime(\"%H:%M:%S\", curr_time)\r\n\r\n try:\r\n # read sensor data all day, every 10 minutes(600), approx. 144/day\r\n if curr_clock < '23:59:00':\r\n readData()\r\n sleep(600)\r\n\r\n # last minute of day: begin operations\r\n else:\r\n\r\n root = None\r\n\r\n # int appended to string to create unique keys\r\n j = 1\r\n\r\n # iterate sensor data list\r\n for index, tuple in enumerate(sensorData):\r\n element_one = tuple[0]\r\n element_two = tuple[1]\r\n\r\n # create new node parameter variables\r\n read = reading(element_one, element_two)\r\n x = str(element_one) + str(j)\r\n yy = float(x)\r\n\r\n # insert node with unique key into tree\r\n root = insert(root, yy, read)\r\n j = j + 1\r\n\r\n # call tree functions that read, then write to lists\r\n allList = inorder(root, [])\r\n range1 = range(root, 0, 75.5, [])\r\n range2 = range(root, 75.5, 80.0, [])\r\n minList = minNode(root, [])\r\n maxList = maxNode(root, [])\r\n\r\n # calculate daily data/stats for database\r\n a = list_tuple_avg(allList, 0)\r\n b = maxList[0][0]\r\n c = minList[0][0]\r\n d = round(maxList[0][0] - minList[0][0], 1)\r\n e = list_tuple_avg(allList, 1)\r\n f = list_tuple_avg(range1, 0)\r\n g = list_tuple_avg(range2, 1)\r\n\r\n # connect to db and initialize cursor\r\n conn = create_connection()\r\n cur = conn.cursor()\r\n\r\n # SQL statements\r\n create_tables(conn)\r\n insert_today(conn)\r\n\r\n # get index of day and month value in datestring\r\n datestring = str(datetime.datetime.now())\r\n # string[ start_index_pos: end_index_pos: step_size]\r\n day = datestring[8: 10]\r\n month = datestring[5: 7]\r\n\r\n # get name of previous month\r\n previousMonth = find_previous_month(month)\r\n\r\n # create last month's record if first of month\r\n if day == '01':\r\n # insert month SQL\r\n select_today(conn, previousMonth)\r\n insert_select_month(conn, previousMonth)\r\n cur.execute(\"DROP TABLE today\")\r\n conn.commit()\r\n conn.close()\r\n\r\n \r\n # delete lists in preperation for new day of data\r\n del sensorData[:]\r\n del allList[:]\r\n del range1[:]\r\n del range2[:]\r\n del minList[:]\r\n del maxList[:]\r\n\r\n # wait at least until next day begins (local time)\r\n sleep(60)\r\n\r\n # handle input/output error\r\n except IOError:\r\n print(\"Error\")\r\n\r\n # handle keyboard interrupt exit\r\n except KeyboardInterrupt as e:\r\n print(str(e))\r\n\r\n break\r\n\r\n\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"358814327","text":"import sys\nsys.path.append('../queue_and_stack')\nfrom dll_queue import Queue\nfrom dll_stack import Stack\n\n\nclass BinarySearchTree:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n # Insert the given value into the tree\n def insert(self, num):\n # base case:\n # if there is no node at root:\n if (self.value == None):\n # insert this node at root\n self = BinarySearchTree(num)\n return\n\n else:\n # compare value to the root\n if num < self.value:\n # if value < root:\n # look left,\n if self.left is not None:\n #if node: repeat steps\n return self.left.insert(num)\n else:\n # else: no node, make new one w this value \n self.left = BinarySearchTree(num)\n # if value >= root:\n if num >= self.value:\n # look right\n if self.right is not None:\n #if node: repeat steps\n return self.right.insert(num)\n # else, no node, make new one w this value\n else:\n self.right = BinarySearchTree(num)\n \n # Return True if the tree contains the value\n # False if it does not\n def contains(self, target):\n if target == self.value:\n return True\n # if value < root, go left\n elif self.left and target < self.value:\n return self.left.contains(target)\n elif self.right and target >= self.value:\n return self.right.contains(target)\n return False\n\n # Return the maximum value found in the tree\n def get_max(self):\n # if no right child, return\n if not self.right:\n return self.value\n else:\n # else, go right\n return self.right.get_max()\n \n\n # Call the function `cb` on the value of each node\n # You may use a recursive or iterative approach\n def for_each(self, cb):\n cb(self.value)\n if self.left:\n self.left.for_each(cb)\n if self.right:\n self.right.for_each(cb)\n else:\n return\n\n \n # DAY 2 Project -----------------------\n\n # Print all the values in order from low to high\n # Hint: Use a recursive, depth first traversal\n def in_order_print(self, node):\n if node.left:\n node.left.in_order_print(node.left)\n print(node.value)\n if node.right:\n node.right.in_order_print(node.right)\n\n # Print the value of every node, starting with the given node,\n # in an iterative breadth first traversal\n def bft_print(self, node):\n q = Queue()\n q.enqueue(node)\n\n while q.len() is not 0:\n temp = q.dequeue()\n print(temp.value)\n\n if temp.right:\n q.enqueue(temp.right)\n if temp.left:\n q.enqueue(temp.left)\n\n # Print the value of every node, starting with the given node,\n # in an iterative depth first traversal\n def dft_print(self, node):\n s = Stack()\n s.push(node)\n\n while s.len() is not 0:\n temp = s.pop()\n print(temp.value)\n\n if temp.right:\n s.push(temp.right)\n if temp.left:\n s.push(temp.left)\n\n\n # STRETCH Goals -------------------------\n # Note: Research may be required\n\n # Print Pre-order recursive DFT\n def pre_order_dft(self, node):\n # data, complete entire left tree, complete entire right tree\n print(node.value)\n # continue going left\n if node.left:\n node.left.pre_order_dft(node.left)\n if node.right:\n node.right.pre_order_dft(node.right)\n # Print Post-order recursive DFT\n def post_order_dft(self, node):\n # left, right, data\n if node.left:\n node.left.post_order_dft(node.left)\n if node.right:\n node.right.post_order_dft(node.right)\n print(node.value)\n","sub_path":"binary_search_tree/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":4148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"630428861","text":"NDex = {}\nNDex[1] = \"bulbasaur\"\nNDex[2] = \"ivysaur\"\nNDex[3] = \"venusaur\"\nNDex[4] = \"charmander\"\nNDex[5] = \"charmeleon\"\nNDex[6] = \"charizard\"\nNDex[7] = \"squirtle\"\nNDex[8] = \"wartortle\"\nNDex[9] = \"blastoise\"\nNDex[10] = \"caterpie\"\nNDex[11] = \"metapod\"\nNDex[12] = \"butterfree\"\nNDex[13] = \"weedle\"\nNDex[14] = \"kakuna\"\nNDex[15] = \"beedrill\"\nNDex[16] = \"pidgey\"\nNDex[17] = \"pidgeotto\"\nNDex[18] = \"pidgeot\"\nNDex[19] = \"rattata\"\nNDex[20] = \"raticate\"\nNDex[21] = \"spearow\"\nNDex[22] = \"fearow\"\nNDex[23] = \"ekans\"\nNDex[24] = \"arbok\"\nNDex[25] = \"pikachu\"\nNDex[26] = \"raichu\"\nNDex[27] = \"sandshrew\"\nNDex[28] = \"sandslash\"\nNDex[29] = \"nidoran-f\"\nNDex[30] = \"nidorina\"\nNDex[31] = \"nidoqueen\"\nNDex[32] = \"nidoran-m\"\nNDex[33] = \"nidorino\"\nNDex[34] = \"nidoking\"\nNDex[35] = \"clefairy\"\nNDex[36] = \"clefable\"\nNDex[37] = \"vulpix\"\nNDex[38] = \"ninetales\"\nNDex[39] = \"jigglypuff\"\nNDex[40] = \"wigglytuff\"\nNDex[41] = \"zubat\"\nNDex[42] = \"golbat\"\nNDex[43] = \"oddish\"\nNDex[44] = \"gloom\"\nNDex[45] = \"vileplume\"\nNDex[46] = \"paras\"\nNDex[47] = \"parasect\"\nNDex[48] = \"venonat\"\nNDex[49] = \"venomoth\"\nNDex[50] = \"diglett\"\nNDex[51] = \"dugtrio\"\nNDex[52] = \"meowth\"\nNDex[53] = \"persian\"\nNDex[54] = \"psyduck\"\nNDex[55] = \"golduck\"\nNDex[56] = \"mankey\"\nNDex[57] = \"primeape\"\nNDex[58] = \"growlithe\"\nNDex[59] = \"arcanine\"\nNDex[60] = \"poliwag\"\nNDex[61] = \"poliwhirl\"\nNDex[62] = \"poliwrath\"\nNDex[63] = \"abra\"\nNDex[64] = \"kadabra\"\nNDex[65] = \"alakazam\"\nNDex[66] = \"machop\"\nNDex[67] = \"machoke\"\nNDex[68] = \"machamp\"\nNDex[69] = \"bellsprout\"\nNDex[70] = \"weepinbell\"\nNDex[71] = \"victreebel\"\nNDex[72] = \"tentacool\"\nNDex[73] = \"tentacruel\"\nNDex[74] = \"geodude\"\nNDex[75] = \"graveler\"\nNDex[76] = \"golem\"\nNDex[77] = \"ponyta\"\nNDex[78] = \"rapidash\"\nNDex[79] = \"slowpoke\"\nNDex[80] = \"slowbro\"\nNDex[81] = \"magnemite\"\nNDex[82] = \"magneton\"\nNDex[83] = \"farfetchd\"\nNDex[84] = \"doduo\"\nNDex[85] = \"dodrio\"\nNDex[86] = \"seel\"\nNDex[87] = \"dewgong\"\nNDex[88] = \"grimer\"\nNDex[89] = \"muk\"\nNDex[90] = \"shellder\"\nNDex[91] = \"cloyster\"\nNDex[92] = \"gastly\"\nNDex[93] = \"haunter\"\nNDex[94] = \"gengar\"\nNDex[95] = \"onix\"\nNDex[96] = \"drowzee\"\nNDex[97] = \"hypno\"\nNDex[98] = \"krabby\"\nNDex[99] = \"kingler\"\nNDex[100] = \"voltorb\"\nNDex[101] = \"electrode\"\nNDex[102] = \"exeggcute\"\nNDex[103] = \"exeggutor\"\nNDex[104] = \"cubone\"\nNDex[105] = \"marowak\"\nNDex[106] = \"hitmonlee\"\nNDex[107] = \"hitmonchan\"\nNDex[108] = \"lickitung\"\nNDex[109] = \"koffing\"\nNDex[110] = \"weezing\"\nNDex[111] = \"rhyhorn\"\nNDex[112] = \"rhydon\"\nNDex[113] = \"chansey\"\nNDex[114] = \"tangela\"\nNDex[115] = \"kangaskhan\"\nNDex[116] = \"horsea\"\nNDex[117] = \"seadra\"\nNDex[118] = \"goldeen\"\nNDex[119] = \"seaking\"\nNDex[120] = \"staryu\"\nNDex[121] = \"starmie\"\nNDex[122] = \"mr-mime\"\nNDex[123] = \"scyther\"\nNDex[124] = \"jynx\"\nNDex[125] = \"electabuzz\"\nNDex[126] = \"magmar\"\nNDex[127] = \"pinsir\"\nNDex[128] = \"tauros\"\nNDex[129] = \"magikarp\"\nNDex[130] = \"gyarados\"\nNDex[131] = \"lapras\"\nNDex[132] = \"ditto\"\nNDex[133] = \"eevee\"\nNDex[134] = \"vaporeon\"\nNDex[135] = \"jolteon\"\nNDex[136] = \"flareon\"\nNDex[137] = \"porygon\"\nNDex[138] = \"omanyte\"\nNDex[139] = \"omastar\"\nNDex[140] = \"kabuto\"\nNDex[141] = \"kabutops\"\nNDex[142] = \"aerodactyl\"\nNDex[143] = \"snorlax\"\nNDex[144] = \"articuno\"\nNDex[145] = \"zapdos\"\nNDex[146] = \"moltres\"\nNDex[147] = \"dratini\"\nNDex[148] = \"dragonair\"\nNDex[149] = \"dragonite\"\nNDex[150] = \"mewtwo\"\nNDex[151] = \"mew\"","sub_path":"pokemon_helper.py","file_name":"pokemon_helper.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"221328862","text":"import requests\nimport logging\n\n#读入文件名\nFilename = \"data.in\"\nCodename = 'code.cpp'\n\nData = {}\ntry:\n Input_Data = []\n with open(Filename, 'r') as fin:\n Input_Data = fin.readlines()\n T = 0\n for i in Input_Data:\n T += 1\n tmp = i.strip().split(':', 1)\n if (len(tmp) != 2):\n print(Filename + ' : Line '+ str(T) + ': Wrong format')\n else:\n Data[tmp[0].strip().lower()] = tmp[1].strip()\nexcept:\n print(\"File Error\")\n exit(0)\n\nlogging.info('Input Successfully')\n\n#目标IP\ntry:\n TargetAddress = Data['targetaddress']\nexcept:\n print(Filename + ' : TargetAddress is lost')\n exit(0)\nif TargetAddress[0:4].lower() == 'http':\n print(\"Warning: TargetAddress don't need 'http'/'https'\")\n\npost_headers = {\n 'Host' : TargetAddress,\n 'Connection' : 'keep-alive',\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'\n}\n\n#登录方式\ntry:\n LoginMode = Data['loginmode']\nexcept:\n LoginMode = 'default'\n\nif LoginMode.lower() == 'default':\n #账号密码登录\n print('LoginMode is default')\n user_data = {}\n try:\n user_data['username'] = Data['username']\n except:\n print(Filename + ' : username is lost')\n exit(0)\n try:\n user_data['password'] = Data['password']\n except:\n print(Filename + ' : password is lost')\n exit(0)\n \n post_res = requests.post(\n url = 'http://' + TargetAddress + '/api/login',\n headers = post_headers ,\n data = user_data\n )\n if post_res.status_code != 200:\n exit(\"Login ERR\")\n\n post_headers['Cookie'] = post_res.headers['set-cookie']\n print('Cookie is: ' + post_headers['Cookie'])\nelse:\n if LoginMode.lower() == 'cookie':\n #Cookie登录\n print('LoginMode is Cookie')\n try:\n Cookie = Data['cookie']\n except:\n print(Filename + ' : Cookie is lost')\n exit(0)\n post_headers['Cookie'] = Cookie\n else:\n print('Unknown LoginMode')\n\nlogging.info('Login Successfully')\n\n#获取页面\ndef GetPage():\n get_headers = {\n 'Host' : TargetAddress,\n 'Connection' : 'keep-alive',\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36',\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'\n }\n get_headers['Cookie'] = post_res.headers['set-cookie']\n\n get_res = requests.get(\n url = 'http://' + TargetAddress + '/admin/info',\n headers = get_headers\n )\n\n if get_res.status_code == 200:\n print('GET Successfully')\n print(get_res.text)\n else:\n print('GET ERR')\n print(get_res)\n\n#自动发帖\ndef NewTopic():\n for i in range(0,1):\n print(\"----- Case: \" + str(i))\n\n #题目编号\n post_params = {'problem_id' : '1235'}\n #发帖内容\n post_data = {\n 'title' : 'test' + str(i),\n 'content' : 'tmp' + str(i)\n }\n post_res = requests.post(\n url = 'http://' + TargetAddress + '/article/0/edit',\n headers = post_headers,\n params = post_params,\n data = post_data\n )\n \n print(post_res)\n\n#自动删帖\ndef DelTopic():\n for i in range(10,17): #删帖编号\n print(\"----- Delte: \" + str(i))\n \n post_res = requests.post(\n url = 'http://' + TargetAddress + '/article/' + str(i) + '/delete',\n headers = post_headers\n )\n \n print(post_res)\n\n#自动回复\ndef Reply():\n for i in range(1,1+30):\n print(\"----- Case: \" + str(i))\n\n #题目编号\n comment_id = 22\n #回复内容\n post_data = {\n 'comment' : 'orz hkk ×' + str(i)\n }\n post_res = requests.post(\n url = 'http://' + TargetAddress + '/article/' + str(comment_id) + '/comment',\n headers = post_headers,\n data = post_data\n )\n\n print(post_res)\n\n#自动删回复\ndef DelReply():\n for i in range(84,84+30): #删回复编号\n print(\"----- Delte: \" + str(i))\n \n #题目编号\n comment_id = 22\n post_res = requests.post(\n url = 'http://' + TargetAddress + '/article/' + str(comment_id) + '/comment/' + str(i) + '/delete',\n headers = post_headers\n )\n \n print(post_res)\n\n#自动提交\ndef Submit():\n try:\n with open(Codename, 'rb') as fin:\n codes = fin.read().decode(\"UTF+8\")\n except:\n print(\"Codefile Error\")\n exit(0)\n\n from requests_toolbelt import MultipartEncoder\n for i in range(0,1):\n print(\"----- Case: \" + str(i))\n\n #题目编号\n comment_id = 3\n #比赛编号\n post_params = {'contest_id' : ''}\n #提交代码\n post_data = MultipartEncoder(fields={\n 'language': 'cpp11',\n 'code': codes\n })\n post_headers['Content-Type'] = post_data.content_type\n post_res = requests.post(\n url = 'http://' + TargetAddress + '/problem/' + str(comment_id) + '/submit',\n headers = post_headers,\n params = post_params,\n data = post_data\n )\n \n print(post_res)\n\n#自动加group\ndef AddGroup():\n for i in range(210, 227 + 1):\n print(\"----- Problem: \" + str(i))\n\n #group内容\n post_data = {\n 'name' : 'NOIP2018'\n }\n post_res = requests.post(\n url = 'http://' + TargetAddress + '/problem/' + str(i) + '/group',\n headers = post_headers,\n data = post_data\n )\n \n print(post_res)\n\n","sub_path":"ojscript.py","file_name":"ojscript.py","file_ext":"py","file_size_in_byte":5996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"285433524","text":"# -*- coding:utf-8 -*-\n# @Time : 2018/9/11 下午2:57\n# @Author : Ding Xiao Fang\n# @File : show2D.py\n# @Software: PyCharm\nimport vtk\nimport preprocess as pre\nimport SimpleITK as sitk\nimport os\n\n\ndef show_image2(im_data):\n image = sitk.GetImageFromArray(im_data)\n \n castFilter = sitk.CastImageFilter()\n castFilter.SetOutputPixelType(sitk.sitkUInt8)\n image = castFilter.Execute(image)\n # sitk.Show(image)\n [z, y, x] = im_data.shape\n writerpath = '/Users/potato/Pictures/project_image/tmp/' # 分割出来的图像保存路径\n filenames = []\n for i in range(z):\n tmpstr = writerpath + str(i) + '.jpg'\n filenames.append(tmpstr)\n sitk.WriteImage(image, filenames)\n reader = vtk.vtkJPEGReader()\n reader.SetFileName(filenames[0])\n reader.SetDataExtent(0, x, 0, y, 0, z)\n reader.SetDataScalarTypeToUnsignedInt()\n reader.SetFilePrefix(writerpath)\n reader.SetFilePattern('%s%d.jpg')\n reader.SetFileNameSliceOffset(0)\n reader.SetFileNameSliceSpacing(1)\n reader.SetDataSpacing(1, 1, 1)\n #\n # reader = vtk.vtkDICOMImageReader()\n # reader.SetFileName(\"/Users/potato/Pictures/project_image/head/ser003img00001.dcm\")\n imageViewer = vtk.vtkImageViewer2()\n imageViewer.SetInputConnection(reader.GetOutputPort())\n renderWindowInteractor = vtk.vtkRenderWindowInteractor()\n imageViewer.SetupInteractor(renderWindowInteractor)\n # imageViewer.SetColorLevel(50)\n # imageViewer.SetColorWindow(90)\n imageViewer.SetSlice(40)\n imageViewer.SetSliceOrientationToXY()\n imageViewer.Render()\n imageViewer.Render()\n imageViewer.GetRenderer().ResetCamera()\n imageViewer.Render()\n renderWindowInteractor.Start()\n","sub_path":"show_image2.py","file_name":"show_image2.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"296879068","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"This module contains all of tools and functions used for seeking out individuals and collecting\ndata, such as email addresses and social media account data.\n\"\"\"\n\nimport requests\nimport tweepy\nfrom colors import red, green, yellow\nfrom bs4 import BeautifulSoup as BS\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException\nfrom http.cookiejar import CookieJar, Cookie\nfrom time import sleep\nimport json\nfrom lib.theharvester import googlesearch, linkedinsearch, \\\ntwittersearch, yahoosearch, bingsearch, jigsaw\nfrom lib import helpers\n\n\nclass PeopleCheck(object):\n \"\"\"A class containing the tools for performing OSINT for people.\"\"\"\n\n # Headers for use with Requests\n user_agent = \"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)\"\n headers = {'User-Agent' : user_agent}\n\n def __init__(self):\n \"\"\"Everything that should be initiated with a new object goes here.\"\"\"\n # Collect the API keys from the config file\n try:\n consumer_key = helpers.config_section_map(\"Twitter\")[\"consumer_key\"]\n consumer_key_secret = helpers.config_section_map(\"Twitter\")[\"key_secret\"]\n access_token = helpers.config_section_map(\"Twitter\")[\"access_token\"]\n access_token_secret = helpers.config_section_map(\"Twitter\")[\"token_secret\"]\n twit_auth = tweepy.OAuthHandler(consumer_key, consumer_key_secret)\n twit_auth.set_access_token(access_token, access_token_secret)\n self.twit_api = tweepy.API(twit_auth, timeout=10)\n except Exception:\n self.twit_api = None\n print(yellow(\"[!] Could not setup OAuth for Twitter API.\"))\n\n try:\n self.emailhunter_api_key = helpers.config_section_map(\"EmailHunter\")[\"api_key\"]\n except Exception:\n self.emailhunter_api_key = \"\"\n print(yellow(\"[!] Could not fetch EmailHunter API key.\"))\n\n try:\n self.contact_api_key = helpers.config_section_map(\"Full Contact\")[\"api_key\"]\n except Exception:\n self.contact_api_key = \"\"\n print(yellow(\"[!] Could not fetch Full Contact API key.\"))\n\n try:\n self.chrome_driver_path = helpers.config_section_map(\"WebDriver\")[\"driver_path\"]\n # Try loading the driver as a test\n self.chrome_options = Options()\n self.chrome_options.add_argument(\"--headless\")\n self.chrome_options.add_argument(\"--window-size=1920x1080\")\n self.browser = webdriver.Chrome(chrome_options=self.chrome_options, executable_path=self.chrome_driver_path)\n # Catch issues with the web driver or path\n except WebDriverException:\n self.chrome_driver_path = None\n self.browser = webdriver.PhantomJS()\n print(yellow(\"[!] There was a problem with the specified Chrome web driver in your \\\nkeys.config! Please check it. For now ODIN will try to use PhantomJS for HaveIBeenPwned.\"))\n # Catch issues loading the value from the config file\n except Exception:\n self.chrome_driver_path = None\n self.browser = webdriver.PhantomJS()\n print(yellow(\"[!] Could not load a Chrome webdriver for Selenium, so we will tryuse \\\nto use PantomJS for haveIBeenPwned.\"))\n\n def pwn_check(self, email):\n \"\"\"Use HIBP's API to check for the target's email in public security breaches.\"\"\"\n try:\n self.browser.get('https://haveibeenpwned.com/api/v2/breachedaccount/{}'.format(email))\n # cookies = browser.get_cookies()\n json_text = self.browser.find_element_by_css_selector('pre').get_attribute('innerText')\n pwned = json.loads(json_text)\n\n return pwned\n except TimeoutException:\n print(red(\"[!] Connectionto HaveIBeenPwned timed out!\"))\n return []\n except NoSuchElementException:\n # This is likely an \"all clear\" -- no hits in HIBP\n return []\n except WebDriverException:\n # print(red(\"[!] Connectionto HaveIBeenPwned timed out!\"))\n return []\n\n def paste_check(self, email):\n \"\"\"Use HIBP's API to check for the target's email in pastes across multiple paste websites.\n This includes sites like Slexy, Ghostbin, Pastebin.\n \"\"\"\n try:\n self.browser.get('https://haveibeenpwned.com/api/v2/pasteaccount/{}'.format(email))\n # cookies = browser.get_cookies()\n json_text = self.browser.find_element_by_css_selector('pre').get_attribute('innerText')\n pastes = json.loads(json_text)\n\n return pastes\n except TimeoutException:\n print(red(\"[!] Connectionto HaveIBeenPwned timed out!\"))\n return []\n except NoSuchElementException:\n # This is likely an \"all clear\" -- no hits in HIBP\n return []\n except WebDriverException:\n # print(red(\"[!] Connectionto HaveIBeenPwned timed out!\"))\n return []\n\n def full_contact_email(self, email):\n \"\"\"Use the Full Contact API to collect social information for the target email address.\"\"\"\n # TODO: Implement the use of the People API -- Also, update this for v3 of the API.\n if self.contact_api_key is None:\n print(red(\"[!] No Full Contact API key, so skipping these searches.\"))\n else:\n base_url = \"https://api.fullcontact.com/v2/person.json\"\n payload = {'email':email, 'apiKey':self.contact_api_key}\n resp = requests.get(base_url, params=payload)\n if resp.status_code == 200:\n return resp.json()\n\n def full_contact_company(self, domain):\n \"\"\"Use the Full Contact API to collect company profile information for the target domain.\"\"\"\n if self.contact_api_key is None:\n print(red(\"[!] No Full Contact API key, so skipping company lookup.\"))\n return None\n else:\n base_url = \"https://api.fullcontact.com/v3/company.enrich\"\n headers = {\"Authorization\":\"Bearer %s\" % self.contact_api_key}\n payload = {'domain':domain}\n resp = requests.post(base_url, data=json.dumps(payload), headers=headers)\n if resp.status_code == 200:\n return resp.json()\n\n def harvest_all(self, domain):\n \"\"\"Use TheHarvester to discover email addresses and employee names.\"\"\"\n # Set the search configuration for TheHarvester\n harvest_limit = 100\n harvest_start = 0\n\n print(green(\"[+] Beginning the harvesting of email addresses for {}...\".format(domain)))\n # Search through most of Harvester's supported engines\n # No Baidu because it always seems to hang or take way too long\n print(green(\"[*] Harvesting Google\"))\n search = googlesearch.search_google(domain, harvest_limit, harvest_start)\n search.process()\n google_harvest = search.get_emails()\n\n print(green(\"[*] Harvesting LinkedIn\"))\n search = linkedinsearch.search_linkedin(domain, harvest_limit)\n search.process()\n link_harvest = search.get_people()\n\n print(green(\"[*] Harvesting Twitter\"))\n search = twittersearch.search_twitter(domain, harvest_limit)\n search.process()\n twit_harvest = search.get_people()\n\n print(green(\"[*] Harvesting Yahoo\"))\n search = yahoosearch.search_yahoo(domain, harvest_limit)\n search.process()\n yahoo_harvest = search.get_emails()\n\n print(green(\"[*] Harvesting Bing\"))\n search = bingsearch.search_bing(domain, harvest_limit, harvest_start)\n search.process('no')\n bing_harvest = search.get_emails()\n\n print(green(\"[*] Harvesting Jigsaw\"))\n search = jigsaw.search_jigsaw(domain, harvest_limit)\n search.process()\n jigsaw_harvest = search.get_people()\n\n # Combine lists and strip out duplicate findings for unique lists\n all_emails = google_harvest + bing_harvest + yahoo_harvest\n all_people = link_harvest + jigsaw_harvest\n\n print(green(\"[+] The search engines returned {} emails, {} names, and {} Twitter \\\nhandles.\".format(len(all_emails), len(all_people), len(twit_harvest))))\n\n # Return the results for emails, people, and Twitter accounts\n return all_emails, all_people, twit_harvest\n\n def harvest_twitter(self, handle):\n \"\"\"Function to lookup the provided handle on Twitter using Tweepy.\"\"\"\n if self.twit_api is None:\n print(yellow(\"[*] Twitter API access is not setup, so skipping Twitter handle \\\nlookups.\"))\n else:\n # Drop the lonely @ Harvester often includes and common false positives\n if handle == '@' or handle == '@-moz-keyframes' or \\\n handle == '@keyframes' or handle == '@media' or handle == '@broofa.com':\n print(yellow(\"[*] Skipping dead end Twitter handle, {}\".format(handle)))\n else:\n try:\n print(green(\"[+] Looking up {} on Twitter\".format(handle)))\n user_data = {}\n user = self.twit_api.get_user(handle.strip('@'))\n user_data['real_name'] = user.name\n user_data['handle'] = user.screen_name\n user_data['location'] = user.location\n user_data['followers'] = user.followers_count\n user_data['user_description'] = user.description\n\n return user_data\n except Exception as error:\n print(red(\"[!] Error involving {} -- could be an invalid \\\naccount.\".format(handle)))\n print(red(\"L.. Details: {}\".format(error)))\n\n def harvest_linkedin(self, target, company):\n \"\"\"Construct a Bing search URL and scrape for LinkedIn profile links related to the\n target's name and company.\n \"\"\"\n print(green(\"[+] Looking for potential LinkedIn profiles \\\nfor {} at {}\".format(target, company)))\n url = 'http://www.bing.com/search?q=site:linkedin.com%20\"{}\"%20\"{}\"'.format(target, company)\n html = requests.get(url)\n soup = BS(html.text, \"html.parser\")\n result = soup.findAll('li', {'class': 'b_algo'})\n name = target.split(\" \")\n refs = []\n for i in result:\n # Get href links from Bing's source\n link = i.a['href']\n if '/dir/' in link or '/title/' in link or 'groupItem' in link or \\\n not 'linkedin.com' in link:\n continue\n else:\n if name[0].lower() in link or name[1].lower() in link:\n refs.append(link)\n # Take just the first result to avoid large, unmanageable lists\n break\n # Remove duplicate results\n no_dups = set(refs)\n\n return no_dups\n\n def harvest_emailhunter(self, domain):\n \"\"\"\"Call upon EmailHunter's API to collect known email addresses for a domain and other\n information, such as names, job titles, and the original source of the data.\n\n A free EmailHunter API key is required.\n \"\"\"\n results = None\n\n if self.emailhunter_api_key:\n emailhunter_api_url = \"https://api.hunter.io/v2/domain-search?\\\ndomain={}&api_key={}\".format(domain, self.emailhunter_api_key)\n request = requests.get(emailhunter_api_url)\n results = request.json()\n\n if \"errors\" in results:\n print(red(\"[!] The request to EmailHunter returned an error!\"))\n print(red(\"L.. Details: {}\".format(results['errors'])))\n return None\n\n print(green(\"[+] Hunter has contact data for {} \\\npeople.\".format(len(results['data']['emails']))))\n\n return results\n\n def process_harvested_lists(self, harvester_emails, harvester_people,\\\n harvester_twitter, hunter_json):\n \"\"\"Take data harvested from EmailHunter and TheHarvester, combine it, make unique lists,\n and return the total results.\n \"\"\"\n temp_emails = []\n twitter_handles = []\n job_titles = {}\n linkedin = {}\n phone_nums = {}\n\n # Process emails found by TheHarvester\n for email in harvester_emails:\n email = email.lower()\n temp_emails.append(email)\n\n # Process emails and people found by Hunter\n if hunter_json:\n for result in hunter_json['data']['emails']:\n email = result['value'].lower()\n temp_emails.append(email)\n\n if \"first_name\" in result and \"last_name\" in result:\n if result['first_name'] is not None and result['last_name'] is not None:\n person = result['first_name'] + \" \" + result['last_name']\n harvester_people.append(person)\n if \"position\" in result:\n if result['position'] is not None:\n job_titles[person] = result['position']\n if \"linkedin\" in result:\n if result['linkedin'] is not None:\n linkedin[person] = result['linkedin']\n if \"phone_number\" in result:\n if result['phone_number'] is not None:\n phone_nums[person] = result['phone_number']\n\n if \"twitter\" in email:\n if result['twitter'] is not None:\n harvester_twitter.append(result['twitter'])\n\n # Remove any duplicate results\n unique = set(temp_emails)\n unique_emails = list(unique)\n\n unique = set(harvester_people)\n unique_people = list(unique)\n\n for twit in harvester_twitter:\n # Split handle from account description and strip rogue periods\n handle = twit.split(' ')[0]\n handle = handle.rstrip('.')\n twitter_handles.append(handle.lower())\n unique = set(twitter_handles)\n unique_twitter = list(unique)\n\n print(green(\"[+] Final unique findings: {} emails, {} people, \\\n{} Twitter handles.\".format(len(unique_emails), len(unique_people), len(unique_twitter))))\n\n return unique_emails, unique_people, unique_twitter, job_titles, linkedin, phone_nums\n","sub_path":"lib/email_tools.py","file_name":"email_tools.py","file_ext":"py","file_size_in_byte":14563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"30569041","text":"import os\nimport torch\nimport glob\nimport warnings\nimport soundfile\nimport librosa\nimport librosa.display\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nfrom .training_process import TrainingProcessCallback\n\n# ignore matplotlib warnings\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\n\n\nclass ScheduledCheckpointCallback(TrainingProcessCallback):\n def __init__(self,\n epoch_interval: int = 25,\n checkpoint_prefix: str = 'scheduled_',\n start_epoch: int = 0,\n # TODO: to be implemented for overfit\n save_last_epoch: bool = True,\n verbose: bool = False):\n super().__init__()\n self.epoch_interval = epoch_interval\n self.checkpoint_prefix = checkpoint_prefix\n self.start_epoch = start_epoch\n self.save_last_epoch = save_last_epoch\n self._ts_fmt = '%Y-%m-%d %H:%M:%S'\n self.verbose = verbose\n\n def on_val_epoch_end(self, training_process):\n current_epoch = training_process.current_epoch\n\n # epochs are 0-indexed\n if (\n self.start_epoch > 0 and \n current_epoch < self.start_epoch\n ):\n return\n elif (current_epoch + 1) % self.epoch_interval == 0:\n checkpoint_path = training_process.save_checkpoint(\n prefix=self.checkpoint_prefix\n )\n \n if self.verbose:\n ts = datetime.now().strftime(self._ts_fmt)\n print(f'[{ts}] Scheduled checkpoint saved to '\n f'{checkpoint_path}')\n\n def on_overfit_val_epoch_end(self, training_process):\n current_epoch = training_process.current_epoch\n\n if (current_epoch + 1) == training_process.max_epochs:\n checkpoint_path = training_process.save_checkpoint(\n prefix=self.checkpoint_prefix\n )\n\n if self.verbose:\n ts = datetime.now().strftime(self._ts_fmt)\n print(f'[{ts}] Last epoch checkpoint saved to '\n f'{checkpoint_path}')\n\n\nclass BestCheckpointCallback(TrainingProcessCallback):\n def __init__(self,\n n_best: int = 3,\n checkpoint_prefix: str = 'best_',\n metric: str = 'avg_val_loss',\n direction: str = 'min',\n verbose: bool = False):\n super().__init__()\n self.n_best = n_best\n self._session_history = [] # keeps (metric, filepath) tuples\n self.checkpoint_prefix = checkpoint_prefix\n self.metric = metric\n self.direction = direction\n self._ts_fmt = '%Y-%m-%d %H:%M:%S'\n self.verbose = verbose\n\n def _evaluate_metric(self, metric):\n if len(self._session_history) < self.n_best:\n return True\n\n session_metrics = [\n checkpoint_data[0] for checkpoint_data in self._session_history\n ]\n\n if self.direction == 'min' and all(\n session_metric > metric for session_metric in session_metrics\n ):\n return True\n\n elif self.direction == 'max' and all(\n session_metric > metric for session_metric in session_metrics\n ):\n raise NotImplementedError\n else:\n return False\n\n def on_val_epoch_end(self, training_process):\n # get metric\n metric = training_process.running_dict.get_last_value('avg_val_loss')\n epoch = training_process.current_epoch\n\n if self._evaluate_metric(metric):\n checkpoint_path = training_process.save_checkpoint(\n prefix=self.checkpoint_prefix\n )\n\n # log to terminal\n if self.verbose:\n ts = datetime.now().strftime(self._ts_fmt)\n print(f'[{ts}] Best checkpoint saved to '\n f'{checkpoint_path}')\n\n # most recent element always goes at the beginning\n self._session_history.insert(0, (metric, checkpoint_path))\n\n if len(self._session_history) > self.n_best:\n checkpoint_file_to_delete = self._session_history[-1][1]\n os.remove(checkpoint_file_to_delete)\n del self._session_history[-1]\n\n if self.verbose:\n ts = datetime.now().strftime(self._ts_fmt)\n print(f'[{ts}] Old best checkpoint deleted from '\n f'{checkpoint_file_to_delete}')\n\n\n# TODO: Do a generalize object that can take i/o from different types such as\n# spectrogram, complex input, only audio data, etc\nclass AudioProcessTrackerCallback(TrainingProcessCallback):\n def __init__(self,\n input_dir: str = None,\n output_dir: str = None,\n epoch_interval: int = 25,\n overfit_epoch_interval: int = 500, # to be implemented\n sample_original_files: bool = True,\n sample_rate: int = 16000,\n sample_duration: int = 10,\n log_audio_file: bool = True,\n log_waveform_fig: bool = True,\n log_linspec_fig: bool = True,\n log_logspec_fig: bool = True,\n window_size: int = 320,\n hop_size: int = 160,\n # TODO: to be replaced by util or union with callable\n pred_fn: str = 'std_pred_fn'):\n super().__init__()\n self.input_dir = input_dir\n self.output_dir = output_dir\n self.epoch_interval = epoch_interval\n self.sample_original_files = sample_original_files\n self.sample_rate = sample_rate\n self.sample_duration = sample_duration\n self.log_audio_file = log_audio_file\n self.log_waveform_fig = log_waveform_fig\n self.log_linspec_fig = log_linspec_fig\n self.log_logspec_fig = log_logspec_fig\n self.window_size = window_size\n self.hop_size = hop_size\n\n # TODO: fix to accept only callable\n if callable(pred_fn):\n self.pred_fn = pred_fn\n else:\n self.pred_fn = getattr(self, pred_fn)\n\n self.input_files, self.output_files = self._collect_files()\n\n def std_pred_fn(self, audio_data: torch.tensor, training_process):\n pred_audio = training_process.model(audio_data)\n pred_audio = pred_audio.cpu().numpy().reshape(-1)\n\n return pred_audio\n\n def cruse_pred_fn(self, audio_data: torch.tensor, training_process):\n \"\"\" Must return the predicted audio ready to be plotted \"\"\"\n # calculate complex spectrum and log pow spec (lps)\n\n # TODO: avoid hardcoding window\n hann_window = torch.hann_window(self.window_size).to(audio_data.device)\n\n # TODO: fixed transformation for now, allow flexibility\n # or allow just external callables\n audio_complex = torch.stft(audio_data,\n onesided=True,\n n_fft=self.window_size,\n center=True,\n hop_length=self.hop_size,\n normalized=False,\n window=hann_window,\n return_complex=True)\n\n audio_lps = torch.log10(torch.abs(audio_complex) ** 2 + 1e-7)\n pred_audio_mask = training_process.model(audio_lps)\n pred_audio_complex = (\n pred_audio_mask.squeeze(1).permute(0, 2, 1) * audio_complex\n )\n\n pred_audio = torch.istft(pred_audio_complex,\n onesided=True,\n n_fft=self.window_size,\n center=True,\n hop_length=self.hop_size,\n normalized=False,\n window=hann_window)\n\n pred_audio = pred_audio.cpu().numpy().reshape(-1)\n\n return pred_audio\n\n def _collect_files(self, ext='*.wav'):\n # assumes equal names on input and output\n # TODO: allow key callback to sort files\n input_files = glob.glob(os.path.join(self.input_dir, ext))\n output_files = glob.glob(os.path.join(self.output_dir, ext))\n return sorted(input_files), sorted(output_files)\n\n def _log_audio_file(self, logger, tag, audio_data, epoch, sample_rate):\n logger.add_audio(tag, audio_data, epoch, sample_rate)\n\n def _log_waveform_fig(self, logger, tag, audio_data, epoch, sample_rate):\n t_ax = np.linspace(0, len(audio_data) / sample_rate, len(audio_data))\n\n fig, ax = plt.subplots()\n ax.set_title(tag)\n ax.set_xlim([0, len(audio_data) / sample_rate])\n ax.set_ylim([-1.0, 1.0])\n ax.set_xlabel('Time (s)')\n ax.set_ylabel('Amplitude')\n ax.plot(t_ax, audio_data)\n\n logger.add_figure(tag, fig, epoch)\n\n def _log_spectrogram_fig(self, logger, tag, audio_data,\n epoch, sample_rate, \n window_size=2048, hop_size=512,\n x_axis='time', y_axis='linear', fmt='%+.2d dB'):\n audio_data_stft = librosa.stft(audio_data,\n n_fft=window_size,\n hop_length=hop_size)\n audio_data_stft_db = librosa.amplitude_to_db(np.abs(audio_data_stft),\n ref=np.max)\n\n fig, ax = plt.subplots()\n img = librosa.display.specshow(audio_data_stft_db,\n x_axis=x_axis,\n y_axis=y_axis,\n ax=ax,\n sr=sample_rate,\n hop_length=hop_size)\n ax.set_title(tag)\n ax.set_xlabel('Time (s)')\n ax.set_ylabel('Frequency (Hz)')\n fig.colorbar(img, ax=ax, format=fmt)\n logger.add_figure(tag, fig, epoch)\n\n def on_val_epoch_end(self, training_process):\n current_epoch = training_process.current_epoch\n logger = training_process.logger\n\n if current_epoch == 0:\n for idx, input_file in enumerate(self.input_files):\n audio_data, _ = soundfile.read(\n input_file,\n frames=(self.sample_rate * self.sample_duration),\n dtype='float32'\n )\n\n if self.log_audio_file:\n self._log_audio_file(logger, \n f'Initial/source_{idx}',\n audio_data,\n current_epoch,\n self.sample_rate)\n\n if self.log_waveform_fig:\n self._log_waveform_fig(logger,\n f'Initial/source_{idx}.waveform',\n audio_data,\n current_epoch,\n self.sample_rate)\n\n if self.log_linspec_fig:\n self._log_spectrogram_fig(logger,\n f'Initial/source_{idx}.linspec',\n audio_data,\n current_epoch,\n self.sample_rate)\n\n if self.log_logspec_fig:\n self._log_spectrogram_fig(logger,\n f'Initial/source_{idx}.logspec',\n audio_data,\n current_epoch,\n self.sample_rate,\n y_axis='log')\n\n for idx, output_file in enumerate(self.output_files):\n audio_data, _ = soundfile.read(\n output_file,\n frames=(self.sample_rate * self.sample_duration),\n dtype='float32'\n )\n\n if self.log_audio_file:\n self._log_audio_file(logger,\n f'Initial/target_{idx}',\n audio_data,\n current_epoch,\n self.sample_rate)\n\n if self.log_waveform_fig:\n self._log_waveform_fig(logger,\n f'Initial/target_{idx}.waveform',\n audio_data,\n current_epoch,\n self.sample_rate)\n\n if self.log_linspec_fig:\n self._log_spectrogram_fig(logger,\n f'Initial/target_{idx}.linspec',\n audio_data,\n current_epoch,\n self.sample_rate)\n\n if self.log_logspec_fig:\n self._log_spectrogram_fig(logger,\n f'Initial/target_{idx}.logspec',\n audio_data,\n current_epoch,\n self.sample_rate,\n y_axis='log')\n\n if (current_epoch == 0 or\n (current_epoch + 1) % self.epoch_interval == 0):\n \n for idx, input_file in enumerate(self.input_files):\n audio_data, _ = soundfile.read(\n input_file,\n frames=(self.sample_rate * self.sample_duration),\n dtype='float32'\n )\n \n # add reshaping to external process\n audio_data = audio_data.reshape(1, -1)\n audio_data = torch.from_numpy(audio_data) \\\n .to(training_process.device)\n\n if callable(self.pred_fn):\n pred_audio_data = self.pred_fn(audio_data)\n elif self.pred_fn is not None:\n pred_audio_data = self.pred_fn(audio_data, training_process)\n else:\n raise NotImplementedError(\n \"A prediction function is required\"\n )\n\n if self.log_audio_file:\n self._log_audio_file(logger,\n f'Predicted/result_{idx}',\n pred_audio_data,\n current_epoch,\n self.sample_rate)\n\n if self.log_waveform_fig:\n self._log_waveform_fig(logger,\n f'Predicted/result_{idx}.waveform',\n pred_audio_data,\n current_epoch,\n self.sample_rate)\n\n if self.log_linspec_fig:\n self._log_spectrogram_fig(logger,\n f'Predicted/result_{idx}.linspec',\n pred_audio_data,\n current_epoch,\n self.sample_rate)\n\n if self.log_logspec_fig:\n self._log_spectrogram_fig(logger,\n f'Predicted/result_{idx}.logspec',\n pred_audio_data,\n current_epoch,\n self.sample_rate,\n y_axis='log')\n\n def on_overfit_val_epoch_end(self, training_process):\n self.on_val_epoch_end(training_process)\n\n\n# TODO: to be implemented\nclass SlackNotificationCallback(TrainingProcessCallback):\n def __init__():\n super().__init__()\n","sub_path":"recipes/experiments_dtln/dtln_utils/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":16445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"116354601","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nfrom google.cloud.bigquery import TableReference\nfrom google.cloud.bigquery.table import Table\n\nfrom bqdm.model.schema import BigQuerySchemaField\nfrom bqdm.util import parse_expires\n\n\nclass BigQueryTable(object):\n\n def __init__(self, table_id, friendly_name=None, description=None,\n expires=None, partitioning_type=None, view_use_legacy_sql=None,\n view_query=None, schema=None, labels=None):\n # TODO encryption_configuration\n # TODO external_data_configuration\n self.table_id = table_id\n self.friendly_name = friendly_name\n self.description = description\n self.expires = expires\n self.partitioning_type = partitioning_type\n self.view_use_legacy_sql = view_use_legacy_sql\n self.view_query = view_query\n self.schema = tuple(schema) if schema else None\n self.labels = labels if labels else None\n\n @staticmethod\n def from_dict(value):\n schema = value.get('schema', None)\n if schema:\n schema = tuple(BigQuerySchemaField.from_dict(s) for s in schema)\n expires = value.get('expires', None)\n if expires:\n expires = parse_expires(expires)\n return BigQueryTable(\n table_id=value.get('table_id', None),\n friendly_name=value.get('friendly_name', None),\n description=value.get('description', None),\n expires=expires,\n partitioning_type=value.get('partitioning_type', None),\n view_use_legacy_sql=value.get('view_use_legacy_sql', None),\n view_query=value.get('view_query', None),\n schema=schema,\n labels=value.get('labels', None),)\n\n @staticmethod\n def from_table(table):\n schema = tuple(BigQuerySchemaField.from_schema_field(s)\n for s in table.schema) if table.schema else None\n return BigQueryTable(\n table_id=table.table_id,\n friendly_name=table.friendly_name,\n description=table.description,\n expires=table.expires,\n partitioning_type=table.partitioning_type,\n view_use_legacy_sql=table.view_use_legacy_sql if table.view_query else None,\n view_query=table.view_query if table.view_query else None,\n schema=None if table.view_query else schema,\n labels=table.labels)\n\n @staticmethod\n def to_table(dataset_ref, model):\n schema = model.schema\n if schema:\n schema = tuple(BigQuerySchemaField.to_schema_field(s) for s in schema)\n else:\n schema = None\n table_ref = TableReference(dataset_ref, model.table_id)\n table = Table(table_ref, schema)\n table.friendly_name = model.friendly_name\n table.description = model.description\n table.expires = model.expires\n table.partitioning_type = model.partitioning_type\n if model.view_use_legacy_sql is not None:\n table.view_use_legacy_sql = model.view_use_legacy_sql\n if model.view_query is not None:\n table.view_query = model.view_query\n table.labels = model.labels if model.labels is not None else dict()\n return table\n\n def schema_dict(self):\n return {\n 'fields': [s.dict() for s in self.schema]\n }\n\n def schema_exclude_description(self):\n schema = None\n if self.schema:\n schema = tuple(s.exclude_description() for s in self.schema)\n return schema\n\n @staticmethod\n def represent(dumper, data):\n return dumper.represent_mapping(\n 'tag:yaml.org,2002:map',\n (\n ('table_id', data.table_id),\n ('friendly_name', data.friendly_name),\n ('description', data.description),\n ('expires', data.expires.strftime(\n '%Y-%m-%dT%H:%M:%S.%f%z') if data.expires else data.expires),\n ('partitioning_type', data.partitioning_type),\n ('view_use_legacy_sql', data.view_use_legacy_sql if data.view_query else None),\n ('view_query', data.view_query if data.view_query else None),\n ('schema', data.schema),\n ('labels', data.labels),\n )\n )\n\n def _key(self):\n return (self.table_id,\n self.friendly_name,\n self.description,\n self.expires,\n self.partitioning_type,\n self.view_use_legacy_sql,\n self.view_query,\n frozenset(self.schema) if self.schema is not None\n else self.schema,\n frozenset(sorted(self.labels.items())) if self.labels is not None\n else self.labels,)\n\n def __eq__(self, other):\n if not isinstance(other, BigQueryTable):\n return NotImplemented\n return self._key() == other._key()\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n return hash(self._key())\n\n def __repr__(self):\n return 'BigQueryTable{0}'.format(self._key())\n","sub_path":"bqdm/model/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":5166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"79123851","text":"import socket\n\nTCP_IP = '127.0.0.1'\nBUFFER_SIZE = 1024\nred = \"\\033[0;31m\"\ngreen = \"\\033[0;32m\"\nblue = \"\\033[0;34m\"\nnc = \"\\033[0m\"\n\ndef unknown_method(port):\n print(red + \"Test Unknown Method\" + nc)\n print(green + \"Expected: Error\" + nc)\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((TCP_IP, port))\n toSend = \"Get / HTTP/1.1\\r\\nHost: localhost:\" + str(port) + \"\\r\\n\\r\\n\"\n print(blue + \"I send:\\n\" + nc)\n print(toSend)\n s.send(bytes(toSend, encoding=\"utf-8\"))\n data = s.recv(1000)\n print(blue + \"I received:\\n\" + nc)\n print(data.decode(\"ascii\"))\n s.close()\n","sub_path":"test/starting_line/unknown_method.py","file_name":"unknown_method.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"347298005","text":"import sqlite3\nfrom pandas import Series\nimport pandas as pd\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nimport time, datetime\nfrom time import mktime\n\ndef update_task(conn, task):\n sql = \"UPDATE outbound SET days = \" + str(p[1])+ \" WHERE TransactionId = \" + str(p[0])\n cur = conn.cursor()\n cur.execute(sql)\n\n\n# load data\nconn = sqlite3.connect('inventory.db')\nc = conn.cursor()\nc.execute(\"SELECT TransactionId, IssueDate FROM outbound\")\nd = c.fetchall()\nepoch = datetime.datetime.utcfromtimestamp(0)\ndi = {}\nfor row in d:\n\tx = row[1]\n\tf = (time.strptime(x, '%m/%d/%Y'))\n\tg = datetime.datetime.fromtimestamp(mktime(f))\n\tdi[row[0]] = (g - epoch).days\n\tp = (row[0], ((g - epoch).days))\n\tprint(p)\n\tupdate_task(conn, p)\nconn.commit()\n","sub_path":"arima2.py","file_name":"arima2.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"378866155","text":"import pytest\nfrom src.dm import dm_details_v1, dm_list_v1, dm_create_v1, dm_remove_v1, dm_invite_v1, dm_leave_v1, dm_messages_v1\nfrom src.error import AccessError, InputError\nfrom src.message import message_senddm_v1, message_react_v1\nfrom src.other import SECRET\nimport src.auth, src.channel, src.other\nimport jwt\nfrom src.config import url\n\nAuID = 'auth_user_id'\nuID = 'u_id'\ncID = 'channel_id'\nallMems = 'all_members'\nName = 'name'\ndmName = 'dm_name'\nfName = 'name_first'\nlName = 'name_last'\nchans = 'channels'\ntoken = 'token'\ndmID = 'dm_id'\nhandle = 'handle_str'\nthumbsUp = 1\n\n#* Fixture that returns a JWT with invalid u_id and session_id\n@pytest.fixture\ndef invalid_token():\n return jwt.encode({'session_id': -1, 'user_id': -1}, SECRET, algorithm='HS256')\n\n\n#* Fixture that clears and registers the first user\n@pytest.fixture\ndef user1():\n src.other.clear_v1() \n return src.auth.auth_register_v2(\"first@gmail.com\", \"password\", \"User\", \"1\")\n\n#* Fixture that registers a second user\n@pytest.fixture\ndef user2():\n return src.auth.auth_register_v2(\"second@gmail.com\", \"password\", \"User\", \"2\")\n\n#* Fixture that registers a third user\n@pytest.fixture\ndef user3():\n return src.auth.auth_register_v2(\"third@gmail.com\", \"password\", \"User\", \"3\")\n\n#* Test that dm_details returns the correct values for valid inputs\ndef test_dm_details_valid(user1, user2):\n dm1 = dm_create_v1(user1[token], [user2[AuID]])\n expected = {\n Name: 'user1, user2',\n 'members': [{\n uID: user1[AuID], \n fName: \"User\",\n lName: '1',\n 'email': 'first@gmail.com',\n handle: 'user1',\n 'profile_img_url': f\"{url}static/default.jpg\"\n }, {\n uID: user2[AuID], \n fName: \"User\",\n lName: '2',\n 'email': 'second@gmail.com',\n handle: 'user2',\n 'profile_img_url': f\"{url}static/default.jpg\"\n }\n ]\n }\n\n assert dm_details_v1(user1[token], dm1[dmID]) == expected\n assert dm_details_v1(user2[token], dm1[dmID]) == expected\n\n#* Test that an InputError is raised when a user calls dm_details for a DM they are not in\ndef test_dm_details_access_error(user1, user2, user3):\n dm1 = dm_create_v1(user1[token], [user2[AuID]])\n\n with pytest.raises(AccessError):\n dm_details_v1(user3[token], dm1[dmID])\n\n#* Test that an InputError is raised when an invalid dm_id is given\ndef test_dm_details_input_error(user1):\n invalid_dm_id = -2\n\n with pytest.raises(InputError):\n dm_details_v1(user1[token], invalid_dm_id)\n\n#* Test when function is called when they are not in any DM\ndef test_dm_list_none(user1, user2, user3):\n dm_create_v1(user1[token], [user2[AuID]])\n \n assert dm_list_v1(user3[token]) == {'dms': []}\n\n#* Test when function is called when they are in all DMs\ndef test_dm_list_all(user1, user2):\n dm_create_v1(user1[token], [user2[AuID]])\n \n assert dm_list_v1(user2[token]) == {'dms': [{\n dmID: 0,\n Name: 'user1, user2',\n }]}\n\n#* Test when function is called when they are in some DMs\ndef test_dm_list_some(user1, user2, user3):\n dm_create_v1(user1[token], [user2[AuID]])\n dm2 = dm_create_v1(user1[token], [user2[AuID], user3[AuID]])\n \n assert dm_list_v1(user3[token]) == {'dms': [{\n dmID: dm2[dmID],\n Name: 'user1, user2, user3',\n }]}\n\n#* Test that dm_create returns the correct values for valid inputs\ndef test_dm_create_valid(user1, user2):\n assert dm_create_v1(user1[token], [user2[AuID]]) == {\n dmID: 0,\n 'dm_name': 'user1, user2',\n }\n\n#* Test that dm_id increases correctly\ndef test_dm_id_linear_increase(user1, user2):\n assert dm_create_v1(user1[token], [user2[AuID]]) == {\n dmID: 0,\n 'dm_name': 'user1, user2',\n }\n\n assert dm_create_v1(user1[token], [user2[AuID]]) == {\n dmID: 1,\n 'dm_name': 'user1, user2',\n }\n\n assert dm_create_v1(user1[token], [user2[AuID]]) == {\n dmID: 2,\n 'dm_name': 'user1, user2',\n }\n\n#* Test that a DMs name doesn't change after users join/leave the DM\ndef test_dm_name(user1, user2, user3):\n dm1 = dm_create_v1(user1[token], [user2[AuID]])\n\n assert dm1[dmName] == 'user1, user2'\n\n dm_invite_v1(user1[token], dm1[dmID], user3[AuID])\n result1 = dm_details_v1(user1[token], dm1[dmID])\n \n assert result1[Name] == 'user1, user2'\n\n dm_leave_v1(user2[token], dm1[dmID])\n result2 = dm_details_v1(user1[token], dm1[dmID])\n \n assert result2[Name] == 'user1, user2'\n\n#* Test that trying to create a dm with an invalid u_id raises an InputError\ndef test_dm_create_errors(user1):\n invalid_u_id = -1\n \n with pytest.raises(InputError):\n dm_create_v1(user1[token], [invalid_u_id])\n\n#Test for function which removes a dm from all dm's\ndef test_dm_remove(user1, user2, user3):\n #Create two dm's: one which we will remove and one we will keep\n dm_0 = dm_create_v1(user1[token], [user2[AuID]])\n #This second dm will have dm_id 1 \n dm_create_v1(user1[token], [user3[AuID]])\n #Test for input error, when dm input is invalid \n invalid_dm = -2\n with pytest.raises(InputError):\n dm_remove_v1(user1[token], invalid_dm)\n #Test for access error, when user requesting remove is not original creator \n with pytest.raises(AccessError):\n dm_remove_v1(user2[token], dm_0['dm_id'])\n #Now that errors are omitted, can assert that we only have 1 dm remaining \n dm_remove_v1(user1[token],dm_0['dm_id'])\n return_dict = dm_list_v1(user1[token])\n assert len(return_dict['dms']) == 1\n\n#Test that a user can be invited to a DM\ndef test_dm_invite(user1, user2, user3):\n dm_0 = dm_create_v1(user1[token], [user2[AuID]])\n #Test for input error, when dm input is invalid \n invalid_dm = -1\n with pytest.raises(InputError):\n dm_invite_v1(user1[token], invalid_dm, user3[AuID])\n #AccessError when user who is not in DM tries to invite \n with pytest.raises(AccessError):\n dm_invite_v1(user3[token], dm_0['dm_id'], user2[AuID])\n #Now that errors are committed can check that user3 has been invited to dm_0\n dm_invite_v1(user1[token], dm_0['dm_id'], user3[AuID])\n assert dm_list_v1(user3[token]) == {'dms': [{\n 'dm_id': dm_0['dm_id'],\n 'name': 'user1, user2',\n }]}\n\n#Test that a user within a DM can leave that DM\ndef test_dm_leave(user1, user2, user3):\n dm_0 = dm_create_v1(user1[token], [user2[AuID]])\n #InputError when dm input is not a valid dm \n invalid_dm = -1\n with pytest.raises(InputError):\n dm_leave_v1(user1[token], invalid_dm)\n #AccessError when user not in DM tries to leave \n with pytest.raises(AccessError):\n dm_leave_v1(user3[token], dm_0['dm_id'])\n \n #Check that owner can't leave dm \n dm_leave_v1(user1[token], dm_0['dm_id'])\n assert {dmID: dm_0[dmID], Name: 'user1, user2'} in dm_list_v1(user1[token])['dms']\n \n #Now that errors are omitted, can use user2 to leave dm \n dm_leave_v1(user2[token], dm_0['dm_id'])\n #Assert that dm is still in user1 but not in user2\n assert {dmID: dm_0[dmID], Name: 'user1, user2'} in dm_list_v1(user1[token])['dms']\n #User 2 has no more dms\n assert dm_list_v1(user2[token]) == {'dms': []}\n \n#Test that up to 50 dms can be displayed \ndef test_dm_messages(user1, user2, user3):\n dm_0 = dm_create_v1(user1[token], [user2[AuID]])\n dm_1 = dm_create_v1(user2[token], [user3[AuID]])\n #Input error when DM ID not valid or start is greater than # of messages in DM\n with pytest.raises(InputError):\n #Start greater than # of messages in DM\n dm_messages_v1(user1[token], dm_0['dm_id'], 1)\n \n invalid_dm = -1\n with pytest.raises(InputError):\n #DM ID not valid\n dm_messages_v1(user1[token], invalid_dm, 0)\n \n #Access error when Authorised user is not a member of DM with dm_id\n with pytest.raises(AccessError):\n dm_messages_v1(user3[token], dm_0['dm_id'], 0)\n\n assert dm_messages_v1(user1[token], dm_0['dm_id'], 0) == {\n 'messages': [],\n 'start': 0,\n 'end': -1,\n }\n\n #Send DM to dm_1 to make sure that it is sending to the correct dm\n DM1 = message_senddm_v1(user2[token], dm_1['dm_id'], \"Lawl\")\n message_react_v1(user3[token], DM1['message_id'], thumbsUp)\n\n #Add certain number of DMs to dm_0 e.g. 10\n message_counter = 0\n while message_counter < 10:\n message_senddm_v1(user1[token], dm_0['dm_id'], f\"{message_counter}\")\n message_counter += 1\n\n #Check dm_0 is correct\n return_dict = dm_messages_v1(user1[token], dm_0['dm_id'],0)\n assert len(return_dict['messages']) == 10\n assert return_dict['start'] == 0\n assert return_dict['end'] == -1\n \n \n #Check dm_1 is unaffected\n return_dict_dm_1 = dm_messages_v1(user2[token], dm_1['dm_id'],0)\n assert len(return_dict_dm_1['messages']) == 1\n assert return_dict_dm_1['start'] == 0\n assert return_dict_dm_1['end'] == -1\n\n #add so that there are 51 messages in DM\n while message_counter < 51:\n message_senddm_v1(user1[token], dm_0[dmID], f\"{message_counter}\")\n message_counter += 1\n\n return_dict2 = dm_messages_v1(user1[token], dm_0['dm_id'], 0)\n assert len(return_dict2['messages']) == 50\n assert return_dict2['start'] == 0\n assert return_dict2['end'] == 50\n\n #Case when start is not equal to 0 but there are 51 messages in DM\n #If start is 20, there should be 32 messages in dictionary\n return_dict3 = dm_messages_v1(user1[token], dm_0['dm_id'], 20)\n assert len(return_dict3['messages']) == 31\n assert return_dict3['start'] == 20\n assert return_dict3['end'] == -1\n\n#* Test for unauthorised users for all dm functions\ndef test_dm_unauthorised_user(user1, user2, invalid_token):\n dm1 = dm_create_v1(user1[token], [user2[AuID]])\n\n with pytest.raises(AccessError):\n dm_details_v1(invalid_token, dm1[dmID])\n \n with pytest.raises(AccessError):\n dm_list_v1(invalid_token)\n\n with pytest.raises(AccessError):\n dm_create_v1(invalid_token, [user1[AuID]])\n\n with pytest.raises(AccessError):\n dm_remove_v1(invalid_token, dm1[dmID])\n\n with pytest.raises(AccessError):\n dm_invite_v1(invalid_token, dm1[dmID], user2[AuID])\n\n with pytest.raises(AccessError):\n dm_leave_v1(invalid_token, dm1[dmID])\n\n with pytest.raises(AccessError):\n dm_messages_v1(invalid_token, dm1[dmID], 0)\n","sub_path":"tests/dm_test.py","file_name":"dm_test.py","file_ext":"py","file_size_in_byte":10487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"571396654","text":"import numpy as np\r\nimport cv2\r\nimport os\r\nimport matplotlib.pyplot as plt # for plotting histogram\r\nimport Constants as C\r\n#import image_quality_check as iqc\r\n#import get_mouse_subtract as gms\r\n\r\n##################################################################################\r\n##import csv files and calculate average hsv values\r\n##added sample csv file\r\n##background correction not functional here\r\n\r\nimgOrig= cv2.imread(C.img)\r\npc=np.genfromtxt(C.PIXEL_COORDINATES,delimiter=',', dtype=\"int\")\r\nspc = np.genfromtxt(C.SAMPLE_PIXEL_COORDINATES,delimiter=',', dtype=\"int\")\r\n#bpc=np.genfromtxt(C.BLANK_PIXEL_COORDINATES,delimiter=',', dtype=\"int\")\r\nimgsmall=cv2.resize(imgOrig,(1000, 400))\r\nhsvImg= cv2.cvtColor(imgsmall,cv2.COLOR_BGR2HSV)\r\n\r\n##################average HSV values for color chart selection#######################\r\nh = []\r\ns = []\r\nv = []\r\nfor i in range(len(pc[0, :])):\r\n hi = hsvImg[pc[1, i]-C.W:pc[1, i]+C.W, pc[0, i]-C.W:pc[0, i]+C.W, 0] #2W by 2W HSV img\r\n h=np.append(h, int(np.average(hi)))\r\n si = hsvImg[pc[1, i]-C.W:pc[1, i]+C.W, pc[0, i]-C.W:pc[0, i]+C.W, 1] #2W by 2W HSV img \r\n s=np.append(s,int(np.average(si)))\r\n vi = hsvImg[pc[1, i]-C.W:pc[1, i]+C.W, pc[0, i]-C.W:pc[0, i]+C.W, 2] #2W by 2W HSV img\r\n v=np.append(v, int(np.average(vi)))\r\n#coord = np.savetxt('HSV_files/HSV_values_'+str(os.path.split(C.PIXEL_COORDINATES)[-1])+'.csv', (h,s,v), fmt ='%f', delimiter = ',')\r\n\r\n\r\n \r\n########################average HSV values for sample ##############################\r\nhs=[]\r\nss=[]\r\nvs=[]\r\nfor i in range(len(spc[0, :])):\r\n hsi = hsvImg[spc[1, i]-C.WS:spc[1, i]+C.WS, spc[0, i]-C.WS:spc[0, i]+C.WS, 0] #2W by 2W HSV img\r\n hs= np.append(hs, int(np.average(hsi)))\r\n ssi = hsvImg[spc[1, i]-C.WS:spc[1, i]+C.WS, spc[0, i]-C.WS:spc[0, i]+C.WS, 1] #2W by 2W HSV img \r\n ss= np.append(ss, int(np.average(ssi)))\r\n vsi = hsvImg[spc[1, i]-C.WS:spc[1, i]+C.WS, spc[0, i]-C.WS:spc[0, i]+C.WS, 2] #2W by 2W HSV img\r\n vs= np.append(vs, int(np.average(vsi)))\r\n#coord = np.savetxt('Sample_HSV_files/Sample_HSV_values_'+str(os.path.split(C.PIXEL_COORDINATES)[-1])+'.csv', (hs,ss,vs), fmt ='%f', delimiter = ',')\r\n\r\n\r\n#######################average HSV values for background#########################\r\nhb = []\r\nsb = []\r\nvb= []\r\n##for i in range(len(bpc[0, :])):\r\n## hblank = hsvImg[bpc[1, i]-C.W:bpc[1, i]+C.W, bpc[1, i]-C.W:bpc[1, i]+C.W, 0] #2W by 2W HSV img\r\n## hb.append(np.average(hblank))\r\n## sblank = hsvImg[bpc[1, i]-C.W:bpc[1, i]+C.W, bpc[1, i]-C.W:bpc[1, i]+C.W, 1] #2W by 2W HSV img\r\n## sb.append(np.average(sblank))\r\n## vblank = hsvImg[bpc[1, i]-C.W:bpc[1, i]+C.W, bpc[1, i]-C.W:bpc[1, i]+C.W, 2] #2W by 2W HSV img\r\n## vb.append(np.average(vblank))\r\n##\r\n##hbsample = np.array(hb)[-1] # for last column\r\n##hb = np.array(hb)[:-1] # for all but last column\r\n##sbsample = np.array(sb)[-1] # for last column\r\n##sb = np.array(sb)[:-1] # for all but last column\r\n##vbsample = np.array(vb)[-1] # for last column\r\n##vb = np.array(vb)[:-1] # for all but last column\r\n##\r\n\r\n\r\n###uncomment for images separated in H, S, V space\r\n##cv2.imshow(\"R\", imgsmall[:,:,2])\r\n##cv2.imshow(\"G\",imgsmall[:, :, 1])\r\n##cv2.imshow(\"B\", imgsmall[:, :, 0])\r\n#uncomment for images separated in B, G, R space\r\ncv2.imshow(\"H\", hsvImg[:,:, 0])\r\ncv2.imshow(\"S\", hsvImg[:, :, 1])\r\ncv2.imshow(\"V\", hsvImg[:, :, 2])\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"ENV_SCI_analyze_color_subtract_5.py","file_name":"ENV_SCI_analyze_color_subtract_5.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"575388567","text":"# Dictionary to recommend basic outfits based on weather forecast\nclothing = {\n\t83: ['fTshirt.png', 'Shorts.png'],\n \t67: ['polo.png', 'jeans.png'],\n \t53: ['hoodie.png', 'seatpants.png'],\n \t52: ['jacket.png', 'sweatpants.png'],\n \t'rain': ['rainCoat.png', 'jeans.png']\n \t}\ndef recommendation(temperature, description):\n\ttemperature = int(temperature)\n\t# Conditional statements give outfit recommendations based on temperature\n\t# from hot, warm, mild, and cold\n\tif temperature >= 75:\n\t\titems = {'top': clothing[83][0], 'bottom': clothing[83][1]}\n\t\t\n\t\treturn items\n\n\telif temperature >= 67 and temperature <= 74:\n\t\titems = {'top': clothing[67][0], 'bottom': clothing[67][1]}\n\t\treturn items\n\n\telif temperature >= 53 and temperature <= 66:\n\t\titems = {'top': clothing[67][0], 'bottom': clothing[67][1]}\n\t\treturn items\n\n\telif temperature <= 52:\n\t\treturn clothing[52]","sub_path":"clothing.py","file_name":"clothing.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"360250938","text":"\n\"\"\" \nSet up the plot figures, axes, and items to be done for each frame.\n\nThis module is imported by the plotting routines and then the\nfunction setplot is called to set the plot parameters.\n \n\"\"\"\n#--------------------------\ndef setplot(plotdata):\n#--------------------------\n \n \"\"\" \n Specify what is to be plotted at each frame.\n Input: plotdata, an instance of clawpack.visclaw.data.ClawPlotData.\n Output: a modified version of plotdata.\n \n \"\"\"\n from clawpack.visclaw import colormaps\n \n # Reversing time in adjoint output\n setadjoint()\n\n plotdata.clearfigures() # clear any old figures,axes,items data\n plotdata.format = 'binary'\n \n\n # Figure for pressure\n # -------------------\n\n plotfigure = plotdata.new_plotfigure(name='Pressure', figno=0)\n plotfigure.kwargs = {'figsize': (14,5)}\n\n # Set up for axes in this figure:\n plotaxes = plotfigure.new_plotaxes()\n plotaxes.axescmd = 'axes([-0.22,0.1,0.8,0.8])'\n plotaxes.xlimits = [-3,8]\n plotaxes.ylimits = [-1,10]\n plotaxes.title = 'Pressure'\n plotaxes.scaled = True # so aspect ratio is 1\n plotaxes.afteraxes = fixup\n\n # Set up for item on these axes:\n plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')\n plotitem.plot_var = 0\n plotitem.pcolor_cmap = colormaps.blue_white_red\n plotitem.add_colorbar = False\n plotitem.show = True # show on plot?\n plotitem.pcolor_cmin = -1.0\n plotitem.pcolor_cmax = 1.0\n plotitem.amr_patchedges_show = [1,1,1]\n plotitem.amr_celledges_show = [0,0,0]\n \n # Adding innerproduct plot\n \n # Set up for axes in this figure:\n plotaxes = plotfigure.new_plotaxes()\n plotaxes.title = 'Inner Product'\n plotaxes.axescmd = 'axes([0.11,0.1,0.8,0.8])'\n plotaxes.xlimits = [-3,8]\n plotaxes.ylimits = [-1,10]\n plotaxes.title = 'Inner Product'\n plotaxes.scaled = True # so aspect ratio is 1\n plotaxes.afteraxes = fixup_innerprod\n \n # Set up for item on these axes:\n plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')\n plotitem.plot_var = plot_innerprod\n plotitem.pcolor_cmap = colormaps.white_red\n plotitem.add_colorbar = False\n plotitem.show = True # show on plot?\n plotitem.pcolor_cmin = 0.0\n plotitem.pcolor_cmax = 0.15\n plotitem.amr_patchedges_show = [0,0,0]\n plotitem.amr_celledges_show = [0,0,0]\n plotitem.amr_data_show = [1,1,0]\n \n # Adding adjoint plot\n \n # Set up for axes in this figure:\n plotaxes = plotfigure.new_plotaxes()\n plotaxes.title = 'Inner Product'\n plotaxes.axescmd = 'axes([0.44,0.1,0.8,0.8])'\n plotaxes.xlimits = [-3,8]\n plotaxes.ylimits = [-1,10]\n plotaxes.title = 'Adjoint'\n plotaxes.scaled = True # so aspect ratio is 1\n plotaxes.afteraxes = fixup_adjoint\n \n # Set up for item on these axes:\n plotitem = plotaxes.new_plotitem(plot_type='2d_pcolor')\n import os\n plotitem.outdir = os.path.join(os.getcwd(), '../adjoint/_outputReversed')\n plotitem.plot_var = 0\n plotitem.pcolor_cmap = colormaps.blue_white_red\n plotitem.add_colorbar = False\n plotitem.show = True # show on plot?\n plotitem.pcolor_cmin = -0.2\n plotitem.pcolor_cmax = 0.2\n plotitem.amr_patchedges_show = [0,0,0]\n plotitem.amr_celledges_show = [0,0,0]\n \n #-----------------------------------------\n # Figures for gauges\n #-----------------------------------------\n plotfigure = plotdata.new_plotfigure(name='q', figno=300, \\\n type='each_gauge')\n plotfigure.clf_each_gauge = True\n \n plotaxes = plotfigure.new_plotaxes()\n plotaxes.xlimits = 'auto'\n plotaxes.ylimits = 'auto'\n plotaxes.title = 'Pressure'\n plotitem = plotaxes.new_plotitem(plot_type='1d_plot')\n plotitem.plot_var = 0\n plotitem.plotstyle = 'b-'\n plotitem.kwargs = {'linewidth': 3}\n plotaxes.afteraxes = fixup_gauge\n \n # Plot q[0] from previous run as red squares:\n plotitem = plotaxes.new_plotitem(plot_type='1d_plot')\n plotitem.plot_var = 0\n plotitem.plotstyle = 'rs'\n plotitem.outdir = os.path.join(os.getcwd(), '_output_pflag')\n\n # Parameters used only when creating html and/or latex hardcopy\n # e.g., via clawpack.visclaw.frametools.printframes:\n\n plotdata.printfigs = True # print figures\n plotdata.print_format = 'png' # file format\n plotdata.print_framenos = 'all' # list of frames to print\n plotdata.print_fignos = 'all' # list of figures to print\n plotdata.html = True # create html files of plots?\n plotdata.html_homelink = '../README.html' # pointer for top of index\n plotdata.html_movie = 'JSAnimation' # new style, or \"4.x\" for old style\n plotdata.latex = True # create latex file of plots?\n plotdata.latex_figsperline = 2 # layout of plots\n plotdata.latex_framesperline = 1 # layout of plots\n plotdata.latex_makepdf = False # also run pdflatex?\n\n return plotdata\n\ndef plot_innerprod(current_data):\n return current_data.aux[0,:,:]\n\n# Afteraxis functions:\n\ndef addgauges(current_data):\n from clawpack.visclaw import gaugetools\n gaugetools.plot_gauge_locations(current_data.plotdata, \\\n gaugenos='all', format_string='ko', add_labels=True)\n\ndef fixup(current_data):\n import pylab\n size = 34\n addgauges(current_data)\n pylab.title('Forward Pressure', fontsize=size)\n pylab.xticks([-2, 0, 2, 4, 6], fontsize=size)\n pylab.yticks([0, 2, 4, 6, 8], fontsize=size)\n\ndef fixup_innerprod(current_data):\n import pylab\n size = 36\n addgauges(current_data)\n pylab.title('Inner Product', fontsize=size)\n pylab.xticks([-2, 0, 2, 4, 6], fontsize=size)\n pylab.tick_params(axis='y', labelleft='off')\n\ndef fixup_adjoint(current_data):\n import pylab\n size = 36\n addgauges(current_data)\n pylab.title('Adjoint Pressure', fontsize=size)\n pylab.xticks([-2, 0, 2, 4, 6], fontsize=size)\n pylab.tick_params(axis='y', labelleft='off')\n\ndef fixup_gauge(current_data):\n import pylab\n size = 36\n pylab.title('Pressure at Gauge 0', fontsize=size)\n pylab.xticks([1.25, 1.35, 1.45], fontsize=size)\n pylab.yticks([0, 0.1, 0.2, 0.3, 0.4], fontsize=size)\n\n\n#-------------------\ndef setadjoint():\n #-------------------\n \n \"\"\"\n Reverse order of adjoint images, for plotting\n adjacent to forward plots.\n \"\"\"\n \n import os,sys,glob\n from clawpack.pyclaw import io\n from clawpack.pyclaw.util import read_data_line\n \n outdir = '../adjoint/_output'\n outdir2 = '../adjoint/_outputReversed'\n \n os.system('mkdir -p %s' % outdir2)\n \n files = glob.glob(outdir+'/fort.b*')\n files.sort()\n n = len(files)\n \n if (n >= 1):\n # Find the final time.\n fname = files[n-1]\n fname = fname.replace('b','t')\n f = open(fname,'r')\n tfinal,meqn,npatches,maux,num_dim = io.ascii.read_t(n-1,path=outdir)\n \n for k in range(n):\n # Creating new files\n fname = files[k]\n newname = outdir2 + '/fort.b%s' % str(n-k-1).zfill(4)\n cmd = 'cp %s %s' % (fname,newname)\n os.system(cmd)\n \n fname = fname.replace('b','q')\n newname = newname.replace('b','q')\n cmd = 'cp %s %s' % (fname,newname)\n os.system(cmd)\n \n fname = fname.replace('q','t')\n newname = newname.replace('q','t')\n cmd = 'cp %s %s' % (fname,newname)\n os.system(cmd)\n \n # Reversing time\n f = open(newname,'r+')\n frameno = n-k-1\n \n t = read_data_line(f)\n \n t = tfinal - t\n \n # Writting new time out to file\n f.seek(0)\n f.write('%18.8e time\\n' % t)\n f.close()\n# end of function setadjoint\n# ----------------------","sub_path":"examples/acoustics_2d_radial_timepoint/compare/setplot_compare.py","file_name":"setplot_compare.py","file_ext":"py","file_size_in_byte":8063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"521815627","text":"#!/usr/bin/env python3\n\nimport math\nimport mpi4py.MPI as MPI\nimport numpy as np\nimport random\n\n# a random seed to produce repeatable results\nseed = 42\n# number of sampling points for MC integratin\ntotal_points = 3600000\n\nrank = MPI.COMM_WORLD.Get_rank()\nsz = MPI.COMM_WORLD.Get_size()\n\n# set up random seeds for MC integration\nmy_seed = np.empty(shape=1, dtype='i')\nif (rank == 0): \n my_seed[:] = seed\nMPI.COMM_WORLD.Bcast(my_seed, 0)\n\nrandom.seed(int(my_seed[0]) + rank)\n\n# how many points on each rank?\nlocal_points = int(total_points / sz)\ntotal_points = local_points * sz\n\nstart_time = MPI.Wtime()\n\n# count how many points are inside of circle of radius 1\nlocal_inside = np.zeros(shape=1,dtype=int)\nfor point in range(0,local_points):\n x = random.random()\n y = random.random()\n r2 = (2.0*(x-0.5))**2 + (2.0*(y-0.5))**2\n if(r2 < 1.0):\n local_inside = local_inside + 1\n\n# combine all rank results\nglobal_inside = np.empty_like(local_inside)\nMPI.COMM_WORLD.Reduce(local_inside, global_inside, MPI.SUM, 0)\nmy_pi = 4.0*global_inside / total_points\n\nend_time = MPI.Wtime()\n\nif (rank == 0):\n print(\"pi is approximated as %g\" % my_pi)\n print(\"real pi is %g diff %g\" % \\\n (4.0*math.atan(1.0), 4.0*math.atan(1.0) - my_pi))\n print(\"Took %g ms\" % ((end_time - start_time)*1e3))\n","sub_path":"examples/pi.py","file_name":"pi.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"468615200","text":"from contact_new import Contact\n\n\nclass CRM:\n\n def main_menu(self):\n while True: # repeat indefinitely\n self.print_main_menu()\n user_selected = int(input())\n self.call_option(user_selected)\n\n def print_main_menu(self):\n print('[1] Add a new contact')\n print('[2] Modify an existing contact')\n print('[3] Delete a contact')\n print('[4] Display all the contacts')\n print('[5] Search by attribute')\n print('[6] Exit')\n print('Enter a number: ')\n\n def call_option(self, user_selected):\n if user_selected == 1:\n self.add_new_contact()\n elif user_selected == 2:\n self.modify_existing_contact()\n elif user_selected == 3:\n self.delete_contact()\n elif user_selected == 4:\n self.display_all_contacts()\n elif user_selected == 5:\n self.search_by_attribute()\n elif user_selected == 6:\n quit()\n\n def add_new_contact(self):\n print(\"What is the first name?\")\n new_first_name = input()\n print(\"What is the last name?\")\n new_last_name = input()\n print(\"What is the email?\")\n new_email = input()\n print(\"What is the note?\")\n new_note = input()\n new_contact = Contact.create(\n first_name=new_first_name,\n last_name=new_last_name,\n email=new_email,\n note=new_note)\n print(\"New contact added:\\n{}\".format(new_contact))\n\n def modify_existing_contact(self):\n print(\"Please select the id of the contact you would like to modify\")\n for contact in Contact.select():\n print(\"{} {} {}\".format(contact.id, contact.first_name, contact.email))\n input_id = int(input())\n contact_detail = Contact.get(id=input_id)\n # Contact.update(contact_detail)\n print(\"Copy and paste the attribute would you like to modify:\\nfirst_name\\nlast_name\\nemail\\nnote\")\n mod_field = input()\n print(\"What would you like to change {} to?\".format(mod_field))\n new_val = input()\n if mod_field == \"first_name\":\n contact_detail.first_name = new_val\n contact_detail.save()\n elif mod_field == \"last_name\":\n contact_detail.last_name = new_val\n contact_detail.save()\n elif mod_field == \"email\":\n contact_detail.email = new_val\n contact_detail.save()\n elif mod_field == \"note\":\n contact_detail.note = new_val\n contact_detail.save()\n print(\"Contact updated\")\n\n def delete_contact(self):\n print(\"Please select the id of the contact you would like to delete\")\n for contact in Contact.select():\n print(\"{} {} {}\".format(contact.id, contact.first_name, contact.email))\n input_id = int(input())\n contact_detail = Contact.get(id=input_id)\n contact_detail.delete_instance()\n print(\"contact deleted\")\n\n def display_all_contacts(self):\n for contact in Contact.select():\n print(\"{} {} {} {}\".format(contact.id, contact.first_name, contact.email, contact.note))\n\n def search_by_attribute(self):\n print(\"Copy and paste the attribute would you like to search by:\\nfirst_name\\nlast_name\\nemail\\nnote\")\n search_field = input()\n print(\"What value would you like to search by?\")\n search_value = input()\n if search_field == \"first_name\":\n result = Contact.get(Contact.first_name == search_value)\n elif search_field == \"last_name\":\n result = Contact.get(Contact.last_name == search_value)\n elif search_field == \"email\":\n result = Contact.get(Contact.email == search_value)\n elif search_field == \"note\":\n result = Contact.get(Contact.note == search_value)\n else:\n print(\"Incorrect query\")\n if result:\n print(\"Your contact:{} {}, email: {}, note {}\".format(result.first_name, result.last_name, result.email, result.note))\n else:\n print(\"Incorrect query\")\n\na_crm_app = CRM()\na_crm_app.main_menu()\n","sub_path":"CRM with DBs/crm_new.py","file_name":"crm_new.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"520180985","text":"# THIS SHOWS THAT NOBODY IS AN ACTUAL CANDIDATE\nimport extract\nimport numpy as np\nimport operator\nfrom collections import defaultdict\nimport scipy.optimize\nimport sys\n\nf_hash = open(\"hash_movie.txt\",\"w\")\nf_clear = open(\"clear_movie.txt\",\"w\")\ndef count_frequencies(entries, key_fun=None):\n counters = defaultdict(rated_element)\n\n for i in entries:\n counters[key_fun(i)].n_ratings += 1\n counters[key_fun(i)].all_ratings[i.rating] += 1\n counters[key_fun(i)].name = key_fun(i)\n\n as_list = [value for key, value in counters.items()]\n\n\n as_list.sort()\n return as_list\n\ndef p_list(in_list, file = sys.stdout):\n for i in in_list:\n print(i, file = file)\nclass rated_element:\n def __init__(self):\n self.n_ratings = 0\n self.all_ratings = np.zeros(6)\n self.name = 0\n\n def __gt__(self, other):\n return self.n_ratings > other.n_ratings\n\n def __str__(self):\n return \"r_el[ {},{},{} ]\".format(self.n_ratings, self.all_ratings, self.name)\n\n def __repr__(self):\n return self.__str__()\nif __name__ == \"__main__\":\n com_entries = extract.get_contents(\"./data/com402-2.csv\")\n imdb_entries = extract.get_contents(\"./data/imdb-2.csv\")\n my_mail = \"jorn.hofstad@epfl.ch\"\n clear_entries = count_frequencies(imdb_entries, lambda x: x.email)\n hashed_entries = count_frequencies(com_entries, lambda x: x.email)\n\n my_entry = [ i for i in clear_entries if i.name == my_mail ][0]\n # print(my_entry)\n\n tot_my_ratings = my_entry.n_ratings\n my_ratings = np.array(my_entry.all_ratings)\n \n candidates = []\n for i in hashed_entries:\n test_rating = np.array(i.all_ratings)\n if np.any( my_ratings > test_rating ):\n # print(i.name)\n print(my_ratings, test_rating )\n continue # Not a candidate\n if i.n_ratings - tot_my_ratings < test_rating - my_ratings:\n print(i)\n continue\n \n print( test_rating, i.name, my_ratings )\n candidtes.append(i)\n print(candidates)\n\n \n\n # p_list(entries)\n\n\n\n \n","sub_path":"courses_exchange/courses_exchange/Ferdig/Information_security/Ovinger/Oving_3/Part_1/src_b/find_candidates.py","file_name":"find_candidates.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"180508555","text":"import numpy as np\nfrom flask import Flask, request, jsonify, render_template\nimport simpletransformers\nimport pandas as pd\nimport requests\nfrom simpletransformers.ner import NERModel\nimport json\nimport io\nimport torch\n\nimport pickle\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\n@app.route('/predict', methods=['POST', \"GET\"])\ndef predict():\n int_features = [x for x in request.form.values()]\n print(int_features)\n\n text = int_features[0]\n model_bert = open('NER_model.pkl', 'rb')\n model_bert_2 = pickle.load(model_bert)\n text = text.upper()\n\n predictions, raw_outputs = model_bert_2.predict([text])\n perfect_words = {}\n meaningless_words = []\n if int_features[1] == 'kamal':\n for t in predictions:\n for i in range(len(t)):\n for l, k in t[i].items():\n if k == 'O':\n meaningless_words.append(l)\n else:\n perfect_words[l] = k\n\n result = json.dumps(perfect_words)\n return render_template('index.html', prediction_text=result)\n\n\nif __name__=='__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"8162644","text":"# -*- coding: utf-8 -*-\n\nfrom flask import Flask, request\nfrom flask.ext.mail import Mail\nfrom flask.ext.peewee.db import Database\nfrom peewee import fn\nfrom werkzeug.contrib.atom import AtomFeed\n\nfrom waikup import settings\nfrom waikup.lib import globals as g\nfrom waikup.lib.errors import ApiError, http_error\n\n\n# Setup application\n\napp = Flask(__name__)\napp.config.from_object(settings)\ng.app = app\nif app.config.get('DEBUG'):\n from flask_debugtoolbar import DebugToolbarExtension\n app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False\n toolbar = DebugToolbarExtension(app)\n\n# Setup database\n\ndb = Database(app)\ng.db = db\n\n\n# Setup mailing\n\nmail = Mail(app)\ng.mail = mail\n\n\n# Setup authentication and admin panel\n\nfrom flask.ext.peewee.admin import Admin\nfrom waikup.models import HybridAuth\nfrom waikup.models import User, Token, Link, Category\nfrom waikup.models import UserAdmin, TokenAdmin, LinkAdmin, CategoryAdmin\n\nauth = HybridAuth(app, db)\ng.auth = auth\n\nadmin = Admin(app, auth)\nadmin.register(User, UserAdmin)\nadmin.register(Token, TokenAdmin)\nadmin.register(Link, LinkAdmin)\nadmin.register(Category, CategoryAdmin)\nadmin.setup()\ng.admin = admin\n\n\n# Setup views\n\n# from waikup.views.api.links import links\n# from waikup.views.api.users import users\nfrom waikup.views.webui import webui\n\napp.register_blueprint(webui)\n# app.register_blueprint(links, url_prefix='/api/links')\n# app.register_blueprint(users, url_prefix='/api/users')\n\n\n@app.route('/links.atom')\ndef links_feed():\n feed_title = 'Recently submitted links'\n cat = request.args.get('cat')\n if cat is not None:\n feed_title += (' - %s' % cat.title())\n category = Category.get(fn.lower(Category.name) == cat.lower())\n all_links = Link.select().where(Link.category == category).limit(settings.ATOM_LINKS_COUNT)\n else:\n all_links = Link.select().limit(settings.ATOM_LINKS_COUNT)\n feed = AtomFeed(\n feed_title,\n feed_url=request.url,\n url=request.base_url\n )\n for link in all_links:\n feed.add(\n link.title,\n unicode(link.description),\n content_type='text',\n author='%s %s' % (link.author.first_name, link.author.last_name),\n url=link.url,\n updated=link.submitted\n )\n return feed.get_response()\n\n\n@app.context_processor\ndef global_forms():\n from waikup.forms import NewLinkForm, ChangePasswordForm\n newlink_form = NewLinkForm()\n newlink_form.set_category_choices()\n return {\n 'new_link_form': newlink_form,\n 'chpasswd_form': ChangePasswordForm()\n }\n\n\n# @app.context_processor\n# def global_variables():\n# from waikup.models import User\n# api_user = User.get(username='waikupapi')\n# return {\n# 'internal_api_token': api_user.token.get().token\n# }\n\n\n# Setup custom error handlers\n\n@app.errorhandler(ApiError)\ndef api_error_handler(error):\n response = error.json\n response.status_code = error.status_code\n return response\n\n\n@app.errorhandler(401)\ndef unauthorized_handler(error):\n return http_error(error)\n\n\n@app.errorhandler(403)\ndef forbidden_error(error):\n return http_error(error)\n\n\n@app.errorhandler(404)\ndef not_found_handler(error):\n return http_error(error)\n\n\n@app.errorhandler(410)\ndef gone_handler(error):\n return http_error(error)\n\n\n@app.errorhandler(500)\ndef server_error_handler(error):\n return http_error(error)\n","sub_path":"waikup/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"218437498","text":"import random\nimport itertools\nimport collections\n\ndef get_words(filename):\n with open(filename) as fp:\n for line in fp:\n for word in line.split():\n yield word\n\nword_map = collections.defaultdict(list)\nfirst, second = itertools.tee(get_words('alice.txt'))\nnext(second)\nfor first_word, next_word in zip(first, second):\n word_map[first_word].append(next_word)\n\nword = 'Alice'\nfor count in range(100):\n print(word, end=' ')\n word = random.choice(word_map[word])\n","sub_path":"gibberish/gibberish2.py","file_name":"gibberish2.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"310260214","text":"import xlrd\ndef fileinput(fileaddress):\n data = xlrd.open_workbook(fileaddress)\n table = data.sheet_by_index(0)\n lnum = table.nrows\n datalist = []\n for i in range(1, lnum):\n datalist.append(table.row_values(i))\n varname = table.row_values(0)\n dataset = []\n data0 = {}\n c = 0\n vn = 0\n while c < len(datalist):\n ro = datalist[c]\n while vn < len(varname):\n data0[varname[vn]] = ro[vn]\n vn = vn + 1\n dataset.append(data0)\n c = c + 1\n vn = 0\n data0 = {}\n return dataset\n","sub_path":"xlio.py","file_name":"xlio.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"27511342","text":"def count_sheep(N):\n\n if N==0:\n return \"INSOMNIA\"\n sheep = set()\n k = 0\n while len(sheep) < 10:\n k = k + 1\n last_N=N*k\n sheep |= set(str(last_N))\n\n return last_N\n\n\ndef test_small(max_N):\n\n for i in range(1,max_N,1):\n print(count_sheep(i))\n\n\n\ndef run_contest(in_file=\"test_micro.in\",out_file=\"test_micro.out\"):\n\n\n fp = open(in_file, 'r')\n op = open(out_file, 'w')\n N = int(fp.readline())\n\n for i in range(N):\n\n D = int(fp.readline())\n\n op.write(\"Case #%s: \" % (i + 1))\n\n op.write(str(count_sheep(D)))\n\n op.write(\"\\n\")\n\n\nif __name__==\"__main__\":\n #test_small(10000000)\n\n #print(count_sheep(1692))\n\n #run_contest(in_file=\"A-small-attempt0.in.txt\",out_file=\"A-small-attempt0.out\")\n\n run_contest(in_file=\"A-large.in.txt\",out_file=\"A-large.out\")","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_kanhua_counting_sheep.py","file_name":"16_0_1_kanhua_counting_sheep.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"626985448","text":"import os\nimport io\nimport behave\n\n\n@behave.when(u'I get assignment items')\ndef step_impl(context):\n context.assignment_items = context.assignment.get_items()\n\n\n@behave.then(u'I receive a list of \"{count}\" assignment items')\ndef step_impl(context, count):\n assert context.assignment_items.items_count == int(count)\n\n\n@behave.when(u'I add \"{count}\" items to assignment')\ndef step_impl(context, count):\n local_path = '0000000162.jpg'\n local_path = os.path.join(os.environ[\"DATALOOP_TEST_ASSETS\"], local_path)\n with open(local_path, \"rb\") as f:\n buffer = io.BytesIO(f.read())\n items = list()\n for i in range(int(count)):\n buffer.name = 'item-{}'.format(i)\n items.append(context.dataset.items.upload(local_path=buffer))\n context.assignment.assign_items(items=items)\n\n\n@behave.when(u'I delete all items from assignment')\ndef step_impl(context):\n context.assignment.remove_items(filters=context.dl.Filters())\n\n","sub_path":"tests/features/steps/assignments_repo/test_assignments_items_operations.py","file_name":"test_assignments_items_operations.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"563394232","text":"# simu - Robot simulation. {{{\n#\n# Copyright (C) 2011 Nicolas Schodet\n#\n# APBTeam:\n# Web: http://apbteam.org/\n# Email: team AT apbteam DOT org\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n#\n# }}}\n\"\"\"Table model for Eurobot 2012.\"\"\"\nimport simu.model.table\nfrom simu.model.round_obstacle import RoundObstacle\nfrom simu.model.rectangular_obstacle import RectangularObstacle\nfrom math import pi\nimport math\nimport random\n\nclass Table (simu.model.table.Table):\n\n def __init__ (self, cards = None):\n simu.model.table.Table.__init__ (self)\n # Well, this is a boring write only code which create every elements.\n # Add coins.\n self.coins = [ ]\n def add_coin (pos, angle, level = 1):\n coin = RoundObstacle (60, level)\n coin.pos = pos\n coin.angle = angle\n coin.value = 1\n self.coins.append (coin)\n def add_coin_circle (center, radius, start, step, n, level = 1):\n angle = start\n for i in xrange (n):\n pos = (center[0] + radius * math.cos (angle),\n center[1] + radius * math.sin (angle))\n add_coin (pos, angle, level)\n angle += step\n add_coin ((1000, 1500), 0)\n add_coin ((2000, 1500), pi)\n add_coin ((450, 300), pi)\n add_coin ((3000 - 450, 300), 0)\n add_coin_circle ((1500, 300), 90, 0, pi / 2, 4)\n add_coin_circle ((1500 - 400, 1000), 300 - 60, pi / 4, pi / 4, 7)\n add_coin_circle ((1500 + 400, 1000), 300 - 60, pi + pi / 4, pi / 4, 7)\n add_coin_circle ((1500 - 400, 1000), 115, pi / 4, pi / 2, 4)\n add_coin_circle ((1500 + 400, 1000), 115, pi / 4, pi / 2, 4)\n add_coin_circle ((1500 - 400, 1000), 105, pi / 4, pi / 2, 4, 3)\n add_coin_circle ((1500 + 400, 1000), 105, pi / 4, pi / 2, 4, 3)\n # Add gold bars.\n self.gold_bars = [ ]\n def add_gold_bar (pos, angle, level = 1):\n gold_bar = RectangularObstacle ((150, 70), level)\n gold_bar.pos = pos\n gold_bar.angle = angle\n gold_bar.value = 3\n self.gold_bars.append (gold_bar)\n add_gold_bar ((1500, 647), 0)\n add_gold_bar ((1500 - 400, 1000 + 125 - 35), 0, 2)\n add_gold_bar ((1500 + 400, 1000 + 125 - 35), 0, 2)\n add_gold_bar ((1500 - 400, 1000 - 125 + 35), 0, 2)\n add_gold_bar ((1500 + 400, 1000 - 125 + 35), 0, 2)\n ba = pi / 2 - 0.04995839\n cba = math.cos (ba)\n sba = math.sin (ba)\n gbx = 400 - (285 + 75) * cba + 35\n gby = 1500 - (285 + 75) * sba\n add_gold_bar ((gbx, gby), ba)\n add_gold_bar ((3000 - gbx, gby), pi - ba)\n # Set random black coins.\n nblack = 0\n while nblack < 4:\n coin = random.choice (self.coins[2:])\n if coin.value:\n coin.value = 0\n nblack += 1\n # Add everything to obstacles.\n self.obstacles += self.coins\n self.obstacles += self.gold_bars\n # Add totem as obstacles.\n for i in (-1, 1):\n o = RectangularObstacle ((250, 250), 3)\n o.pos = (1500 + i * 400, 1000)\n self.obstacles.append (o)\n\n","sub_path":"host/simu/model/table_eurobot2012.py","file_name":"table_eurobot2012.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"352050978","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 03 19:41:33 2017\n\n@author: The One\n\"\"\"\nimport numpy as np\n#import matplotlib as mpl\n#mpl.use('pgf')\nfrom matplotlib import pyplot\nimport mpl_toolkits.mplot3d.axes3d as p3\nimport matplotlib.animation as animation\nimport matplotlib.cm as mplcm\nimport matplotlib.colors as colors\n#import get_tilt_angle_full_v2.rotation_matrix\n#import get_tilt_angle_full_v2.circle_arc\n\ndef rotation_matrix(axis,theta):\n axis = axis/np.sqrt(np.dot(axis,axis))\n a = np.cos(theta/2)\n b,c,d = axis*np.sin(theta/2)\n return np.array([[a*a+b*b-c*c-d*d, 2*(b*c-a*d), 2*(b*d+a*c)],\n [2*(b*c+a*d), a*a+c*c-b*b-d*d, 2*(c*d-a*b)],\n [2*(b*d-a*c), 2*(c*d+a*b), a*a+d*d-b*b-c*c]])\ndef circle_arc(axis,start_v,end_v,num_points):\n axis = axis/np.linalg.norm(axis)\n start_v = start_v/np.linalg.norm(start_v)\n end_v = end_v/np.linalg.norm(end_v)\n theta = np.arccos(np.dot(start_v,end_v))\n theta_s = list(np.arange(0.0, theta + theta/num_points, theta/num_points))\n circle_vecs = np.zeros([len(theta_s),3])\n for i,thetai in enumerate(theta_s):\n makecir = rotation_matrix(axis,thetai)\n circle_vecs[i,:] = np.dot(makecir,start_v)\n return circle_vecs\n\n#2down\n### Turn off the perspective/orthogonal viewing effect (it works but has some side problems)\nfrom mpl_toolkits.mplot3d import proj3d\ndef orthogonal_proj(zfront, zback):\n a = (zfront+zback)/(zfront-zback)\n b = -2*(zfront*zback)/(zfront-zback)\n return np.array([[1,0,0,0],\n [0,1,0,0],\n [0,0,a,b],\n [0,0,0,zback]])\n#proj3d.persp_transformation = orthogonal_proj\n###\n\n### Draw fancy arrows\n\nfrom matplotlib.patches import FancyArrowPatch\n\nclass Arrow3D(FancyArrowPatch):\n def __init__(self, xs, ys, zs, *args, **kwargs):\n FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)\n self._verts3d = xs, ys, zs\n\n def draw(self, renderer):\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))\n FancyArrowPatch.draw(self, renderer)\n###\n\n\n\n#### The plotting of a vector-based graphics using the above points location information.\nfig2 = pyplot.figure(2,figsize=(4, 4),dpi=100)\nax2 = p3.Axes3D(fig2)\nax2.view_init(elev=55, azim=-6)\nax2.set_color_cycle('b')\n\n'''\nlinex, = ax2.plot([0,6],[0,0],[0,0])\nlinex.set_linewidth(1)\nlinex.set_color('k')\nliney, = ax2.plot([0,0],[0,6],[0,0])\nliney.set_linewidth(1)\nliney.set_color('k')\nlinez, = ax2.plot([0,0],[0,0],[0,3])\nlinez.set_linewidth(1)\nlinez.set_color('k')\nax2.text(0,0,6, r'$z_s$', fontsize=18,verticalalignment='bottom', horizontalalignment='left')\n'''\n\npA = np.array([0,0,0])\npC = np.array([0,6,0])\npB = np.array([2,4,6])\npAp = np.array([10,2.5,0])\npO = (pA + pAp)/3\npD = pO + ((pB-pO) + (pC-pO))/4\n\nDOunit = (pD-pO)/np.linalg.norm(pD-pO)\npE = np.dot(-pO,DOunit)*DOunit + pO\npF= np.dot(pAp-pO,DOunit)*DOunit + pO\n\nlineAC, = ax2.plot(*zip(pA,pC),linewidth = 2,color='b')\nlineAB, = ax2.plot(*zip(pA,pB),linewidth = 2,color='b')\nlineCB, = ax2.plot(*zip(pC,pB),linewidth = 2,color='b')\nlineAAp, = ax2.plot(*zip(pA,pAp),linewidth = 2,color='b')\nlineBAp, = ax2.plot(*zip(pB,pAp),linewidth = 2,color='b')\nlineCAp, = ax2.plot(*zip(pC,pAp),linewidth = 2,color='b')\nlineAE, = ax2.plot(*zip(pA,pE),linewidth = 1,color='b',linestyle=':')\nlineApF, = ax2.plot(*zip(pAp,pF),linewidth = 1,color='b',linestyle=':')\nlineDF, = ax2.plot(*zip(pO + ((pB-pO) + (pC-pO))/2,pF),linewidth = 1,color='b',linestyle=':')\n\nfor vertex in [pA,pB,pC,pAp]:\n ax2.plot(*zip(pD,vertex),linewidth = 1,color='b')\n \nax2.text(*pA, s = r'$A$', fontsize=12,verticalalignment='bottom', horizontalalignment='right')\nax2.text(*pB, s = r'$B$', fontsize=12,verticalalignment='bottom', horizontalalignment='right')\nax2.text(*pC, s = r'$C$', fontsize=12,verticalalignment='bottom', horizontalalignment='left')\nax2.text(*pAp, s = r\"$A'$\", fontsize=12,verticalalignment='top', horizontalalignment='left')\nax2.text(*pD, s = r\"$D$\", fontsize=12,verticalalignment='bottom', horizontalalignment='right')\nax2.text(*pO, s = r\"$O$\", fontsize=12,verticalalignment='top', horizontalalignment='right')\nax2.text(*pE, s = r\"$E$\", fontsize=12,verticalalignment='top', horizontalalignment='left')\nax2.text(*pF, s = r\"$E'$\", fontsize=12,verticalalignment='bottom', horizontalalignment='right')\nax2.scatter(*pO, marker='o',color = 'k')\n\ndef draw_perpendicular_sign(rot_vec,first_axis,second_axis,location_point,ax):\n data = 0.3*circle_arc(rot_vec,first_axis,second_axis,2)\n data[1,:]=data[1,:]*np.sqrt(2)\n data = data+location_point\n ldata, = ax.plot(data[:,0],data[:,1],data[:,2],'k')\n\ndraw_perpendicular_sign(np.cross(DOunit,-pO),-pE,-pD+pO,pE,ax2)\ndraw_perpendicular_sign(np.cross(DOunit,-pO),pAp-pF,DOunit,pF,ax2)\n\n#axis1.Axis(ax2,'r')\n#ax2.autoscale_view()\n#ax2.pbaspect= [1,1,0.5]\n#ax2.auto_scale_xyz()\n\nXt,Yt,Zt = zip(pA,pB,pC,pAp)\nX = np.array(Xt)\nY = np.array(Yt)\nZ = np.array(Zt)\n\nmax_range = np.array([X.max()-X.min(), Y.max()-Y.min(), Z.max()-Z.min()]).max() / 3.0\n\n\nmid_x = (X.max()+X.min()) * 0.5\nmid_y = (Y.max()+Y.min()) * 0.5\nmid_z = (Z.max()+Z.min()) * 0.5\nax2.set_xlim3d(mid_x - max_range, mid_x + max_range)\nax2.set_ylim3d(mid_y - max_range, mid_y + max_range)\nax2.set_zlim3d(mid_z - max_range, mid_z + max_range)\n#ax2.set_xlim3d([-3, 8])\n#ax2.set_ylim3d([-3,8])\n#ax2.set_zlim3d([-3,8])\n#ax2.set_xlim([-0.5,3.7])\n#ax2.set_ylim([-0.5,3.7])\n#ax2.set_zlim([0,6])\nax2.set_xticks([])\nax2.set_yticks([])\nax2.set_zticks([])\nax2.w_xaxis.line.set_visible(False) #turn off axis visibility\n#ax2.w_xaxis.line.set_color([0,0,0,0])\nax2.w_yaxis.line.set_color([0,0,0,0]) # change the color of axis\nax2.w_zaxis.line.set_color([0,0,0,0])\n#ax2.spines['left'].set_color('b') didn't work on 3D\nax2.set_axis_off() #-> this can turn off the background curtain\n#ax2.axhline(y=1,xmin=0,xmax=1)\n#ax2.set_frame_on(True)\n#ax2.set_axis_bgcolor('b')\n#ax2.set_position() #set the bbox of the whole axes\n#ax2.set_zbound()\npyplot.show()\npyplot.savefig(r'C:\\Documents and Settings\\The One\\My Documents\\tony\\2014\\xelatexfolder\\pgf related\\pgf\\tetra_premise_1.pgf')","sub_path":"pgf_related/tetra_premise_1.py","file_name":"tetra_premise_1.py","file_ext":"py","file_size_in_byte":6221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"410944371","text":"########################################################################################################\n#\n# Author : Vishal Paliwal\n# Description : This Script updates Customer Address Fields in the \n# IM_CUSTOMER_ATTRIBUTE_REF_TABLE from IM_CUSTOMER_ADDRESS_SCD Table.\n# Version : 1.0\n# Created : 08.11.2019\n# Modified : 08.11.2019\n#\n# P.S: This script points to a specific GCP environment, \n# for running it in a different environment make suitable changes in some configuration fields. \n#########################################################################################################\n\nfrom __future__ import absolute_import\nimport logging\nimport apache_beam as beam\nfrom apache_beam.options.pipeline_options import PipelineOptions\nfrom apache_beam.options.pipeline_options import GoogleCloudOptions\nfrom apache_beam.options.pipeline_options import StandardOptions\n\noutput_table = 'automatic-asset-253215:CORE.IM_CUSTOMER_ATTRIBUTE_REF'\ndataflow_options = {'--project=automatic-asset-253215',\n '--job_name=upd-imcustomerattributeref',\n '--temp_location=gs://raw_source_files/Customers/temp',\n '--staging_location=gs://raw_source_files/Customers/temp/stg'}\noptions = PipelineOptions(dataflow_options)\ngcloud_options = options.view_as(GoogleCloudOptions)\noptions.view_as(StandardOptions).runner = 'dataflow'\n\n\ndef printval(value):\n print('#################')\n print(value)\n\n\nclass LeftJoin(beam.PTransform):\n \"\"\"This PTransform performs a left join given source_pipeline_name, source_data,\n join_pipeline_name, join_data, common_key constructors\"\"\"\n\n def __init__(self,src_pipeline,src_pipeline_name,join_pipeline,join_pipeline_name,common_key):\n self.join_pipeline = join_pipeline\n self.src_pipeline_name = src_pipeline_name\n self.src_pipeline = src_pipeline\n self.join_pipeline_name = join_pipeline_name\n self.common_key = common_key\n\n def expand(self,pcolls):\n def _format_as_common_key_tuple(data_dict,common_key):\n return data_dict[common_key],data_dict\n\n return ({pipeline_name:pcoll\n | 'Convert to ({0}, object) for {1}'.format(self.common_key,pipeline_name) >> beam.Map(\n _format_as_common_key_tuple,self.common_key)\n for (pipeline_name,pcoll) in pcolls.items()}\n | 'CoGroupByKey {0}'.format(pcolls.keys()) >> beam.CoGroupByKey()\n | 'Unnest Cogrouped' >> beam.ParDo(UnnestCoGrouped(),self.src_pipeline,\n self.join_pipeline)\n )\n\n\nclass UnnestCoGrouped(beam.DoFn):\n \"\"\"This DoFn class unnests and emits the CogroupBykey output\"\"\"\n\n def process(self,input_element,src_pipeline,join_pipeline):\n group_key,grouped_dict = input_element\n join_dictionary = grouped_dict[join_pipeline]\n source_dictionaries = grouped_dict[src_pipeline]\n for source_dictionary in source_dictionaries:\n try:\n source_dictionary.update(join_dictionary[0])\n yield source_dictionary\n except IndexError: # found no join_dictionary\n yield source_dictionary\n\n\ndef run():\n p = beam.Pipeline(options=options)\n\n customer_attrbute_ref_data = \"\"\"SELECT * FROM `automatic-asset-253215.CORE.IM_CUSTOMER_ATTRIBUTE_REF`\"\"\"\n primary_pipeline_1 = 'target_table'\n target_table = p | 'Target Table' >> beam.io.Read(beam.io.BigQuerySource(\n query=customer_attrbute_ref_data,\n use_standard_sql=True))\n\n # ------- UPDATING IM_CUSTOMER_ATTRIBUTE_REF TABLE FROM IM_CUSTOMER_ADDRESS_SCD TABLE ----------\n\n SHIPADDR0_addressSCD_data = \"\"\"SELECT\n CUSTOMER_ADDRESS_KEY AS BILLING_ADDRESS_KEY,\n CUSTOMER_ADDRESS_KEY AS PRIMARY_ADDRESS_KEY,\n CUSTOMER_KEY,\n CAST(FORMAT_DATETIME('%Y%m%d%H%M%S', CURRENT_DATETIME()) AS INT64) AS UPD_BATCH_NBR\n FROM `automatic-asset-253215.CORE.IM_CUSTOMER_ADDRESS_SCD` a\n WHERE a.ADDR_NAME = 'SHIPADDR0'\"\"\"\n\n BILLADDR1_addressSCD_data = \"\"\"SELECT\n CUSTOMER_ADDRESS_KEY AS BILLING_ADDRESS_KEY,\n CUSTOMER_KEY,\n CAST(FORMAT_DATETIME('%Y%m%d%H%M%S', CURRENT_DATETIME()) AS INT64) AS UPD_BATCH_NBR\n FROM `automatic-asset-253215.CORE.IM_CUSTOMER_ADDRESS_SCD` a\n WHERE a.ADDR_NAME = 'BILLADDR1'\"\"\"\n\n MKTADDR_addressSCD_data = \"\"\"SELECT\n CUSTOMER_ADDRESS_KEY AS MKTADDR_ADDRESS_KEY,\n CUSTOMER_KEY,\n CAST(FORMAT_DATETIME('%Y%m%d%H%M%S', CURRENT_DATETIME()) AS INT64) AS UPD_BATCH_NBR\n FROM `automatic-asset-253215.CORE.IM_CUSTOMER_ADDRESS_SCD` a\n WHERE a.ADDR_NAME = 'MKTADDR'\"\"\"\n\n join_pipeline_SHIPADDR0 = 'SHIPADDR0_ADDRS'\n SHIPADDR0_ADDRS = p | 'SHIPADDR0_ADDRS' >> beam.io.Read(beam.io.BigQuerySource(\n query=SHIPADDR0_addressSCD_data,use_standard_sql=True))\n\n join_pipeline_BILLADDR1 = 'BILLADDR1_ADDRS'\n BILLADDR1_ADDRS = p | 'BILLADDR1_ADDRS' >> beam.io.Read(beam.io.BigQuerySource(\n query=BILLADDR1_addressSCD_data,use_standard_sql=True))\n\n join_pipeline_MKTADDR = 'MKTADDR_ADDRS'\n MKTADDR_ADDRS = p | 'MKTADDR_ADDRS' >> beam.io.Read(beam.io.BigQuerySource(\n query=MKTADDR_addressSCD_data,use_standard_sql=True))\n\n common_key_2 = 'CUSTOMER_KEY'\n\n pipelines_dictionary_1 = {primary_pipeline_1:target_table,join_pipeline_SHIPADDR0:SHIPADDR0_ADDRS}\n primary_pipeline_2 = 'SHIPADDR0_data'\n SHIPADDR0_data = (pipelines_dictionary_1 | 'Left Join 1' >> LeftJoin(\n primary_pipeline_1,target_table,join_pipeline_SHIPADDR0,SHIPADDR0_ADDRS,common_key_2)\n )\n\n pipelines_dictionary_2 = {primary_pipeline_2:SHIPADDR0_data,join_pipeline_BILLADDR1:BILLADDR1_ADDRS}\n primary_pipeline_3 = 'BILLADDR1_data'\n BILLADDR1_data = (pipelines_dictionary_2 | 'Left Join 2' >> LeftJoin(\n primary_pipeline_2,SHIPADDR0_data,join_pipeline_BILLADDR1,BILLADDR1_ADDRS,common_key_2)\n )\n\n pipelines_dictionary_3 = {primary_pipeline_3:BILLADDR1_data,join_pipeline_MKTADDR:MKTADDR_ADDRS}\n (pipelines_dictionary_3 | 'Left Join 3' >> LeftJoin(\n primary_pipeline_3,BILLADDR1_data,join_pipeline_MKTADDR,MKTADDR_ADDRS,common_key_2)\n | 'Write to IM_CUSTOMER_ATTRIBUTE_REF' >> beam.io.WriteToBigQuery(\n output_table,\n write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE,\n create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER)\n )\n\n p.run().wait_until_finish()\n\n\nif __name__ == '__main__':\n logging.getLogger().setLevel(logging.INFO)\n run()\n","sub_path":"PILOT_CLIC_CUST_3.0/IM_CUSTOMER_ATTRIBUTE_REF/updatingAddressFieldsInAttributeRef.py","file_name":"updatingAddressFieldsInAttributeRef.py","file_ext":"py","file_size_in_byte":6823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"209175379","text":"def test_range():\n a = range(10)\n print(a)\n print(list(a))\n\n\ndef my_generator(filename):\n results = []\n with open(filename, 'r') as file:\n keys = file.readline().strip().split(';')\n for line in file:\n values = line.strip().split(';')\n single_dict = {key: value for key, value in zip(keys, values)}\n results.append(single_dict)\n return results\n\n\ndef test_my_generator():\n results = my_generator(filename='box_since_2000.csv')\n for single_dict in results:\n print(single_dict['Name'], single_dict['Height'], single_dict['Weight'])\n\n\nif __name__ == '__main__':\n test_my_generator()\n","sub_path":"week03_day02/generators.py","file_name":"generators.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"22393134","text":"from flask_restful import Resource, reqparse, abort, fields, marshal, marshal_with \nfrom bson.objectid import ObjectId \nfrom datetime import datetime\nfrom pymongo import ReturnDocument\n\nfrom src.auth.auths import Auth\nfrom src.db.main import get_db\n\n\n_blog_parser = reqparse.RequestParser()\n\n_blog_parser.add_argument('title', required=True, help='{error_msg}')\n_blog_parser.add_argument('summary', required=True, help='{error_msg}')\n_blog_parser.add_argument('content', required=True, help='{error_msg}')\n_blog_parser.add_argument('tags',action=\"append\", required=True, help='{error_msg}')\n_blog_parser.add_argument('catalogs', required=True, help='{error_msg}') # 列表的话要加action='append'\n\n\n_blog_fields = {\n 'id': fields.Integer(attribute='blog_id'),\n 'title': fields.String,\n 'summary': fields.String,\n 'content': fields.String,\n 'readSize': fields.Integer(attribute='read_size'),\n 'commentSize': fields.Integer(attribute='comment_size'),\n 'tags': fields.List(fields.String),\n 'createAt': fields.DateTime(attribute='create_at'),\n 'updateAt': fields.DateTime(attribute='update_at'),\n 'catalogs': fields.String,\n 'username': fields.String\n }\n\n\n\nclass Blogs(Resource):\n \"\"\" blog rest api\"\"\"\n\n method_decorators = [Auth.authenticate]\n\n @marshal_with(_blog_fields,envelope='resource')\n def get(self):\n blogs = get_db().blogs.find()\n return list(blogs)\n\n def post(self):\n args = _blog_parser.parse_args()\n db = get_db()\n create_at = datetime.now() # 官网建议用 utcnow()\n update_at = datetime.now()\n max_id = max([item.get('blog_id',0) for item in list(db.blogs.find())] or (0,)) # 找到最大的id\n args.update({\n 'blog_id': max_id + 1,\n 'read_size': 0,\n 'comment_size': 0,\n 'create_at': create_at,\n 'update_at': update_at,\n 'username': ''\n })\n query_id = db.blogs.insert_one(args).inserted_id\n return marshal(db.blogs.find_one({'_id':query_id}), _blog_fields), 201\n\n def put(self):\n pass\n\n def delete(self):\n pass\n\n\nclass Blog(Resource):\n \"\"\"one blog info\"\"\"\n\n method_decorators = [Auth.authenticate]\n\n @marshal_with(_blog_fields, envelope='resource')\n def get(self,blog_id):\n return get_db().blogs.find_one({'blog_id': blog_id})\n\n def post(self,blog_id):\n \"\"\"不被restful允许的操作\"\"\"\n pass\n\n def put(self,blog_id):\n \"\"\"update blog\"\"\"\n args = _blog_parser.parse_args()\n args.update({'update_at': datetime.now()})\n result = get_db().blogs.find_one_and_update({'blog_id': blog_id}, {'$set': args }, return_document=ReturnDocument.AFTER)\n return marshal(result, _blog_fields), 201\n\n def delete(self,blog_id):\n \"\"\"delete blog\"\"\"\n get_db().blogs.find_one_and_delete({'blog_id': blog_id})\n return '', 204\n\n\n\n","sub_path":"src/resources/blogs.py","file_name":"blogs.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"535441692","text":"import numpy as np\r\n\r\nfrom keras.optimizers import SGD\r\n\r\nfrom dlgo import encoders\r\nfrom dlgo import goboard\r\nfrom dlgo import kerasutil\r\nfrom dlgo.agent import Agent\r\nfrom dlgo.agent.helpers import is_point_an_eye\r\n\r\n__all__ = [\r\n 'ACAgent',\r\n 'load_ac_agent',\r\n]\r\n\r\n\r\nclass ACAgent(Agent): # 12.6\r\n def __init__(self, model, encoder):\r\n Agent.__init__(self)\r\n self.model = model\r\n self.encoder = encoder\r\n self.collector = None\r\n self.temperature = 1.0\r\n self.last_state_value = 0\r\n\r\n def set_temperature(self, temperature):\r\n self.temperature = temperature\r\n\r\n def set_collector(self, collector):\r\n self.collector = collector\r\n\r\n def select_move(self, game_state):\r\n num_moves = self.encoder.board_width * self.encoder.board_height\r\n\r\n board_tensor = self.encoder.encode(game_state)\r\n x = np.array([board_tensor])\r\n\r\n # Because this is a two-output model, predict returns a tuple containing two NumPy arrays\r\n actions, values = self.model.predict(x)\r\n\r\n # predict is a batch call that can process several boards at once,\r\n # so you must select the first element of the array to get the probability\r\n # distribution you want.\r\n move_probs = actions[0]\r\n\r\n # The values are represented as a one-dimensional vector,\r\n # so you must pull out the first element to get the value as a plain float\r\n estimated_value = values[0][0]\r\n\r\n eps = 1e-6\r\n move_probs = np.clip(move_probs, eps, 1 - eps)\r\n move_probs = move_probs / np.sum(move_probs)\r\n\r\n candidates = np.arange(num_moves)\r\n ranked_moves = np.random.choice(\r\n candidates, num_moves, replace=False, p=move_probs)\r\n for point_idx in ranked_moves:\r\n point = self.encoder.decode_point_index(point_idx)\r\n move = goboard.Move.play(point)\r\n move_is_valid = game_state.is_valid_move(move)\r\n fills_own_eye = is_point_an_eye(\r\n game_state.board, point, game_state.next_player)\r\n if move_is_valid and (not fills_own_eye):\r\n if self.collector is not None:\r\n # Include the estimated value in the experience buffer\r\n self.collector.record_decision(\r\n state=board_tensor,\r\n action=point_idx,\r\n estimated_value=estimated_value)\r\n return goboard.Move.play(point)\r\n return goboard.Move.pass_turn()\r\n\r\n # lr (learning rate) and batch_size are tuning parameters for the optimizer;\r\n # refer to chapter 10 for more discussion\r\n def train(self, experience, lr=0.1, batch_size=128): # 12.7\r\n opt = SGD(lr=lr)\r\n self.model.compile(\r\n optimizer=opt,\r\n loss=['categorical_crossentropy', 'mse'],\r\n loss_weights=[1.0, 0.5]) # 1.0 applies to policy output and 0.5 applies to value output\r\n\r\n n = experience.states.shape[0]\r\n num_moves = self.encoder.num_points()\r\n policy_target = np.zeros((n, num_moves))\r\n value_target = np.zeros((n,))\r\n for i in range(n):\r\n # This is the same as the encoding scheme in chapter 10, but weighted by the advantage\r\n action = experience.actions[i]\r\n policy_target[i][action] = experience.advantages[i]\r\n # This is the same as the encoding scheme in chapter 11\r\n reward = experience.rewards[i]\r\n value_target[i] = reward\r\n\r\n self.model.fit(\r\n experience.states,\r\n [policy_target, value_target],\r\n batch_size=batch_size,\r\n epochs=1)\r\n\r\n def serialize(self, h5file):\r\n h5file.create_group('encoder')\r\n h5file['encoder'].attrs['name'] = self.encoder.name()\r\n h5file['encoder'].attrs['board_width'] = self.encoder.board_width\r\n h5file['encoder'].attrs['board_height'] = self.encoder.board_height\r\n h5file.create_group('model')\r\n kerasutil.save_model_to_hdf5_group(self.model, h5file['model'])\r\n\r\n def diagnostics(self):\r\n return {'value': self.last_state_value}\r\n\r\n\r\ndef load_ac_agent(h5file):\r\n model = kerasutil.load_model_from_hdf5_group(h5file['model'])\r\n encoder_name = h5file['encoder'].attrs['name']\r\n if not isinstance(encoder_name, str):\r\n encoder_name = encoder_name.decode('ascii')\r\n board_width = h5file['encoder'].attrs['board_width']\r\n board_height = h5file['encoder'].attrs['board_height']\r\n encoder = encoders.get_encoder_by_name(\r\n encoder_name,\r\n (board_width, board_height))\r\n return ACAgent(model, encoder)\r\n","sub_path":"dlgo/rl/ac.py","file_name":"ac.py","file_ext":"py","file_size_in_byte":4718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"239116451","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 14 21:37:43 2018\nTrack analysis for gravity machine\n1. RMSD of tracks\n2. Velocity distributions\n@author: deepak\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport cmocean\nimport os\nimport time\nimport scipy\nimport scipy.ndimage as ndimage\nimport smoothn\nfrom roipoly import roipoly\nfrom mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar\nimport pickle\nplt.close(\"all\")\nfrom PIL import Image\nimport imp\nimport Track\nimp.reload(Track)\nimport numpy as np\n\ndef squared_displacement(data,i,n):\n # n is the track len over which an ensemble is calculated\n return (data[i:i+n]-data[i])**2\n\ndef squared_vector_3d(X,Y,Z,i,n):\n \n return (X[i:i+n] - X[i])**2 + (Y[i:i+n] - Y[i])**2 + (Z[i:i+n] - Z[i])**2 \n\ndef makeSubtracks(Track, Dia):\n # Binary Mask of the track: Near Wall: 1 Away From Wall: 0\n \n \n atWall = (Track.X < (Track.xmin+Dia))|(Track.X>(Track.xmax-Dia))|(Track.Y<(Track.ymin+Dia))|(Track.Y>(Track.ymax-Dia))\n print(np.sum(atWall))\n \n subTrackIndex = 0\n counter = 0\n startIndex = {}\n stopIndex = {}\n # If the first element is part of the track then initialize the subTrack\n if(atWall[0]==0):\n startIndex[counter]=0\n \n for ii in range(1,len(atWall)):\n # print(ii)\n # print(counter)\n \n if(atWall[ii-1] == 0 and atWall[ii] == 1):\n stopIndex[counter] = ii-1\n counter += 1 \n elif (atWall[ii-1]==1 and atWall[ii]== 0):\n startIndex [counter] = ii\n \n # if not stopIndex:\n # stopIndex[counter]=len(atWall)-1\n \n if (len(stopIndex.keys()) < len(startIndex.keys())):\n stopIndex[counter] = len(atWall)-1\n \n print(startIndex)\n print(stopIndex)\n \n subTrack={}\n sqDispSubTrack = {}\n trackLens = {}\n # Create subtracks\n print(startIndex.keys())\n for ii in startIndex.keys():\n \n subTrack[ii] = np.array([Track.X[startIndex[ii]:stopIndex[ii]+1],Track.Y[startIndex[ii]:stopIndex[ii]+1],Track.Z[startIndex[ii]:stopIndex[ii]+1]])\n \n sqDispSubTrack[ii] = squared_vector_3d(subTrack[ii][0,:],subTrack[ii][1,:],subTrack[ii][2,:],0,np.size(subTrack[ii],axis=1))\n trackLens[ii] = np.size(subTrack[ii],axis=1)\n \n # Calculate the MSD using the ensemble average of the subtracks\n maxTrackLen = max(trackLens.values())\n numSubTracks = len(subTrack.keys())\n \n print('No:of subtracks : {}'.format(numSubTracks))\n \n SumSqDisp_subTracks = np.zeros(maxTrackLen,)\n meanWeights = np.zeros(maxTrackLen,)\n \n for ii in range(0,numSubTracks):\n for jj in range(0,np.size(subTrack[ii],axis=1)):\n SumSqDisp_subTracks[jj] += sqDispSubTrack[ii][jj]\n meanWeights[jj]+=1\n \n MSD_subTracks = SumSqDisp_subTracks/meanWeights\n \n T_subTrack = np.array(T[0:maxTrackLen])\n\n \n\ndef main():\n \n # Organism\n \n # Dendraster\n \n # Largest Organism diameter in mm\n Dorg = 0.3 \n \n dataFolder = '/Volumes/GRAVMACH1 2/HopkinsEmbroyologyCourse_GoodData/2018_06_11/Dendraster_starved_11Days_nofood'\n \n # Load the set of tracks we want to analyze\n TrackNames = {0:'Dendraster1',1:'Dendraster2',2:'Dendraster3'}\n \n TrackFile = 'track.csv'\n \n SquaredDisp_XY = []\n SquaredDisp_Z = []\n \n trackLen_array = np.zeros(len(TrackNames.keys()))\n \n# SquaredDisp_subtracks = \n for ii,currFolder in TrackNames.items():\n \n \n Track_curr = Track.GravMachineTrack(os.path.join(dataFolder,currFolder,TrackFile))\n \n trackLen_array[ii] = Track_curr.trackLen\n \n SquaredDisp_Z.append(squared_displacement(Track_curr.Z,0,Track_curr.trackLen))\n \n SquaredDisp_XY.append(squared_displacement(Track_curr.X,0,Track_curr.trackLen) + squared_displacement(Track_curr.Y,0,Track_curr.trackLen))\n \n \n maxTrackLen = np.max(trackLen_array)\n \n stackedArray_Z = np.zeros((len(TrackNames.keys(), maxTrackLen)))\n stackedArray_XY = np.zeros((len(TrackNames.keys(), maxTrackLen)))\n \n for ii in TrackNames.keys():\n stackedArray_Z[ii,:trackLen_array[ii]] = SquaredDisp_Z[ii]\n stackedArray_XY[ii,:trackLen_array[ii]] = SquaredDisp_XY[ii]\n \n \n stackedArray_Z = np.ma.array(stackedArray_Z, mask = stackedArray_Z==0)\n stackedArray_XY = np.ma.array(stackedArray_XY, mask = stackedArray_XY==0)\n \n RMSD_Z = (stackedArray_Z.mean(axis=0))\n RMSD_XY = (stackedArray_XY.mean(axis=0))\n \n \nif __name__ == '__main__':\n main()\n \n","sub_path":"DataAnalysisScripts/OldFiles/TrackAnalysis_MSD.py","file_name":"TrackAnalysis_MSD.py","file_ext":"py","file_size_in_byte":4626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"10"} +{"seq_id":"26519995","text":"from win32com import client\r\nimport openpyxl\r\nfrom openpyxl.chart import BarChart,Reference\r\ndef xltopdfconvert(inputfile_name,outfile_name):\r\n\txlApp = client.Dispatch(\"Excel.Application\")\r\n\tbooks = xlApp.Workbooks.Open('E:/New folder (3)/{0}'.format(inputfile_name))\r\n\tws = books.Worksheets[0]\r\n\tws.PageSetup.PrintGridlines=1\r\n\tws.SaveAs('{0}'.format(outfile_name),FileFormat=57)\r\n\tbooks.Close(SaveChanges=False)\r\n\txlApp.Quit()\r\n\r\n\t#ws.Visible = 1\r\n\t#ws.ExportAsFixedFormat(0, 'C:/Users/acer/desktop/New folder (3)/{0}'.format(outfile_name))\r\n\r\nif __name__ == \"__main__\":\r\n\txltopdfconvert('28 May.xlsx','out.pdf')","sub_path":"upestithi/ty.py","file_name":"ty.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"475974767","text":"import numpy as np\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import adjusted_rand_score\nfrom sklearn.metrics import adjusted_mutual_info_score\nfrom sklearn.metrics.cluster import normalized_mutual_info_score\nfrom sklearn.metrics import accuracy_score\n\ndef get_avg_f1(y_true, y_pred):\n labels = np.unique(y_true)\n pred_labels = np.unique(y_pred)\n # we take the average of best f1 match scores as defined in Yang et al.\n avg_f1_score = 0\n for l in labels:\n #fit pred to true\n c1 = np.where(y_true == l, 1, 0)\n g1_scores = [f1_score(c1, np.where(y_pred == c, 1, 0)) for c in labels]\n g1 = np.max(g1_scores) / len(labels)\n \n if l in pred_labels:\n g2_scores = [f1_score(np.where(y_true == c, 1, 0), \n np.where(y_pred == l, 1, 0)) \n for c in pred_labels]\n g2 = np.max(g2_scores) / len(pred_labels)\n avg_f1_score += g2\n \n avg_f1_score += g1\n \n avg_f1_score /= 2\n \n return avg_f1_score\n\ndef topic_stats(embeddings, y_true, num_classes, geo_vec=False):\n \"\"\" Computes topic cluster statistics for document vectors\n Param:\n embeddings: (geo_vec), (D, B, C) tensor, where D is num documents, \n BxD final embedding.\n (D, C) tensor, where D is num documents, C embedding.\n y_true: (D, 1), correct topic per document\n num_classes: total number of classes in the dataset \n geo_vec: check the simple topic activation\n Returns:\n f1_s: weighted f1 score\n ari: adjusted rand score\n ami: adjusted mutual information score\n nmi: normalized mutual information score\n topic_s: maxed topic activations\n \"\"\"\n if geo_vec:\n topic_act = np.argmax(np.sum(embeddings, axis=2), axis=1)\n embeddings = np.reshape(c, (np.shape(c)[0], -1))\n\n kmeans = KMeans(n_clusters=num_classes, random_state=0).fit(embeddings)\n \n f1_s, ari, ami, nmi, topic_s = 0, 0, 0, 0, 0\n def score(y_true, y_pred, name):\n n = ['avg_f1', 'adj_ri', 'adj_mi', 'norm_mi', 'topic_act']\n s = [get_avg_f1(y_true, y_pred), adjusted_rand_score(y_true, y_pred), \n adjusted_mutual_info_score(y_true, y_pred),\n normalized_mutual_info_score(y_true, y_pred),float('NaN')]\n if geo_vec:\n s[-1] = (accuracy_score(y_true, topic_act))\n print (' %10s %10s %10s %10s %10s \\n %3s %8.3f %10.3f %10.3f %10.3f %10.3f\\n' % (\n n[0],n[1],n[2],n[3],n[4],name,s[0],s[1],s[2],s[3], s[4]))\n return s\n\n cl_methods = [kmeans.labels_]\n cl_names = ['kmeans']\n \n y_pred = []\n for y_pred_, name in zip(cl_methods, cl_names):\n f1_s, ari, ami, nmi, topic_s = score(y_true, y_pred_, name)\n \n return f1_s, ari, ami, nmi, topic_s\n\na = np.array([[[0, 5],[2, 2]]])\nb = np.array([[[0, 1],[2, 2]]])\n# geo_vec model example\nc = np.vstack((a, b))\n# regular doc embedding example\n#c = np.squeeze(a)\ncl = np.array([0, 1])\ntopic_stats(c, cl, 2, True)\n\n\n","sub_path":"topics_docs.py","file_name":"topics_docs.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"10374175","text":"#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\n\n\nimport tensorflow as tf\nfrom tensorflow import layers\nfrom tensorflow.contrib import rnn\nimport db_explore\n\n\ndef lstm_model(features, mode):\n \"\"\"\n cnn model structure\n :param features: images\n :return: predicts\n \"\"\"\n input_layer = tf.unstack(value=features, num=28, axis=1, name='input')\n lstm_cell = rnn.BasicLSTMCell(num_units=128, name='lstm')\n lstm_out, _ = rnn.static_rnn(lstm_cell, input_layer, dtype=tf.float32, )\n flatten_layer = layers.flatten(lstm_out[-1], name='flatten')\n dense_layer = layers.dense(inputs=flatten_layer, units=512, name='dense')\n dropout = layers.dropout(inputs=dense_layer, rate=0.5, training=(mode == tf.estimator.ModeKeys.TRAIN),\n name='dropout')\n logits = layers.dense(inputs=dropout, units=10, name='logits')\n return logits\n\n\ndef Loss(labels, logits, mode):\n \"\"\"\n loss of the model in training and evaluating\n :param labels:\n :param logits: predictions of cnn model\n :param mode: Train, Evaluate, Predict\n :return: loss\n \"\"\"\n if mode != tf.estimator.ModeKeys.PREDICT:\n return tf.losses.softmax_cross_entropy(onehot_labels=labels, logits=logits)\n\n\ndef Train_op(loss, mode):\n \"\"\"\n set the optimizer of the train step\n :param loss:\n :param mode: Train, Evaluate, Predict\n :return: trainer\n \"\"\"\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.AdamOptimizer(learning_rate=0.01)\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n return train_op\n\n\n# build mode\ndef lstm_model_fn(features, labels, mode):\n \"\"\"\n build the hole cnn model for tf.estimator\n :param features: image arrays of shape (batch_size, 28, 28, 1)\n :param labels: one hot label of shape (batch_size, 10)\n :param mode: passed by tf.estimator\n :return: tf.estimator.EstimatorSpec\n \"\"\"\n logits = lstm_model(features=features, mode=mode)\n\n # predictions\n predictions = {\"classes\": tf.argmax(input=logits, axis=1, name='y_pred'),\n \"probabilities\": tf.nn.softmax(logits, name=\"y_prob\")}\n\n loss = Loss(labels=labels, logits=logits, mode=mode)\n\n train_op = Train_op(loss=loss, mode=mode)\n\n if mode == tf.estimator.ModeKeys.EVAL:\n accuracy = tf.metrics.accuracy(labels=tf.argmax(labels, axis=1), predictions=predictions[\"classes\"],\n name='accuracy')\n eval_metric_ops = {'accuracy': accuracy, }\n else:\n eval_metric_ops = None\n\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions, loss=loss, train_op=train_op,\n eval_metric_ops=eval_metric_ops)\n\n\ndef main(argv):\n # set logging verbosity high enough\n tf.logging.set_verbosity(tf.logging.INFO)\n\n # build estimator\n run_config = tf.estimator.RunConfig(model_dir='./model/lstm', keep_checkpoint_max=2, save_checkpoints_steps=500,\n tf_random_seed=2018)\n estimator = tf.estimator.Estimator(model_fn=lstm_model_fn, config=run_config)\n\n # load mnist data\n train, test = db_explore.load_mnist()\n\n x_train, y_train = train\n train_input_fn = lambda: db_explore.train_input_fn(x_train, y_train, 32)\n x_test, y_test = test\n eval_input_fn = lambda: db_explore.eval_input_fn(x_test, y_test, 32)\n\n for _ in range(10):\n estimator.train(input_fn=train_input_fn, steps=2000, )\n eval = estimator.evaluate(input_fn=eval_input_fn, steps=500)\n print(eval)\n eval = estimator.evaluate(input_fn=eval_input_fn, )\n print(eval)\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"LSTM.py","file_name":"LSTM.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"} +{"seq_id":"531137445","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import messagebox\nimport estudante as est \nimport disciplina as disc\n\nclass CampoVazio(Exception):\n pass\n\nclass FaltouCodigo(Exception):\n pass\n\nclass FaltouAluno(Exception):\n pass\n\nclass turmaDuplicada(Exception):\n pass\n\nclass Turma:\n\n def __init__(self, codigo, disciplina, estudantes):\n self.__codigo = codigo\n self.__disciplina = disciplina\n self.__estudantes = estudantes\n\n def getCodigo(self):\n return self.__codigo\n \n def getDisciplina(self):\n return self.__disciplina\n\n def getEstudantes(self):\n return self.__estudantes\n\nclass LimiteInsereTurma(tk.Toplevel):\n def __init__(self, controle, listaCodDiscip, listaNroMatric):\n\n tk.Toplevel.__init__(self)\n self.geometry('300x250')\n self.title(\"Disciplina\")\n self.controle = controle\n\n self.frameCodTurma = tk.Frame(self)\n self.frameDiscip = tk.Frame(self)\n self.frameEstudante = tk.Frame(self)\n self.frameButton = tk.Frame(self)\n self.frameCodTurma.pack()\n self.frameDiscip.pack()\n self.frameEstudante.pack()\n self.frameButton.pack() \n\n self.labelCodTurma = tk.Label(self.frameCodTurma,text=\"INFORME O CODIGO DA TURMA: \")\n self.labelCodTurma.pack(side=\"left\")\n self.inputCodTurma = tk.Entry(self.frameCodTurma, width=20)\n self.inputCodTurma.pack(side=\"left\")\n\n self.labelDiscip = tk.Label(self.frameDiscip,text=\"QUAL A DISCIPLINA? : \")\n self.labelDiscip.pack(side=\"left\")\n self.escolhaCombo = tk.StringVar()\n self.combobox = ttk.Combobox(self.frameDiscip, width = 15 , textvariable = self.escolhaCombo)\n self.combobox.pack(side=\"left\")\n self.combobox['values'] = listaCodDiscip\n\n self.labelEst = tk.Label(self.frameEstudante,text=\"QUAL O ESTUDANTE? : \\n\")\n self.labelEst.pack(side=\"left\") \n self.listbox = tk.Listbox(self.frameEstudante)\n self.listbox.pack(side=\"left\")\n for nro in listaNroMatric:\n self.listbox.insert(tk.END, nro)\n\n self.buttonInsere = tk.Button(self.frameButton ,text=\"INSERIR ALUNO\", font = ('Negrito', 9)) \n self.buttonInsere.pack(side=\"left\")\n self.buttonInsere.bind(\"