diff --git "a/5845.jsonl" "b/5845.jsonl" new file mode 100644--- /dev/null +++ "b/5845.jsonl" @@ -0,0 +1,802 @@ +{"seq_id":"71480955998","text":"#!/usr/bin/python3\n\nimport csv\nfrom pprint import pprint\n\nfrom lxml import html\nimport requests\n\nFIELDNAMES = [\"url\", \"name\", \"cdm_url\", \"homepage_url\"]\n\n\ndef main():\n in_f = open(\n \"moz-inbound-links-for-pricetransparency_accureg_net-2022-03-29_09_55_24_080947Z.csv\",\n \"r\",\n )\n csv_reader = csv.reader(in_f)\n\n out_f = open(\"todo.csv\", \"w\", encoding=\"utf-8\")\n csv_writer = csv.DictWriter(out_f, fieldnames=FIELDNAMES, lineterminator=\"\\n\")\n csv_writer.writeheader()\n\n seen_urls = set()\n\n for row in csv_reader:\n if len(row) != 17:\n continue\n\n url = row[7]\n if url == \"Target URL\":\n continue\n\n url = \"https://\" + url\n\n if url in seen_urls:\n continue\n\n seen_urls.add(url)\n\n resp = requests.get(url)\n print(resp.url)\n\n tree = html.fromstring(resp.text)\n\n homepage_url = row[0]\n\n for dl_row in tree.xpath('//div[@class=\"ptdownloadrow\"]'):\n name = dl_row.xpath('.//div[@class=\"ptdownloadrowfacilityname\"]/text()')\n if len(name) == 0:\n continue\n\n name = name[0]\n name = name.split(\" - \")[0]\n\n cdm_url = dl_row.xpath('.//a[contains(@href, \".csv\")]/@href')\n if len(cdm_url) == 0:\n continue\n\n cdm_url = cdm_url[0]\n\n row = {\n \"url\": url,\n \"name\": name,\n \"cdm_url\": cdm_url,\n \"homepage_url\": homepage_url,\n }\n\n pprint(row)\n csv_writer.writerow(row)\n\n in_f.close()\n out_f.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rl1987/dolthub-bounty-hospital-price-transparency-v3","sub_path":"pricetransparency.accureg.net/1_scrape_cdm_urls.py","file_name":"1_scrape_cdm_urls.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"30271859775","text":"from __future__ import annotations\n\nfrom tortoise.models import Model\nfrom tortoise.manager import Manager\nfrom tortoise import fields\nfrom tortoise.queryset import QuerySet\nfrom tortoise.expressions import F\nfrom .attributes import Attributes\n\n\nclass EpisodesAttributes:\n pass\n\n\nfor attribute_name in Attributes.types:\n foreign_key = fields.ForeignKeyField(\n f\"models.{attribute_name}\",\n related_name=\"episodes\",\n null=True,\n )\n setattr(EpisodesAttributes, attribute_name.lower(), foreign_key)\n\n\nclass Episode(Model, EpisodesAttributes):\n id = fields.IntField(pk=True)\n url = fields.CharField(max_length=511)\n thumbnail = fields.CharField(max_length=511)\n title = fields.CharField(max_length=511)\n description = fields.TextField()\n\n fans = fields.ManyToManyField(\"models.User\", related_name=\"favorites\")\n\n @classmethod\n async def list(cls, limit=None, offset=None) -> QuerySet[Episode]:\n limit = min(max(0, limit), 50) if limit else 50\n offset = offset or 0\n return cls.all().limit(limit).offset(offset)\n","repo_name":"tlebrize/YO","sub_path":"server/models/episode.py","file_name":"episode.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"51"} +{"seq_id":"7562772222","text":"food_quantity = float(input()) * 1000\nhay_quantity = float(input()) * 1000\ncover_quantity = float(input()) * 1000\nweight = float(input()) * 1000\nday_count = 0\nwhile day_count < 30:\n day_count += 1\n food_quantity -= 300\n if day_count % 2 == 0:\n hay_quantity = hay_quantity - (food_quantity * 0.05)\n if day_count % 3 == 0:\n cover_quantity = cover_quantity - (weight / 3)\n\nif food_quantity > 0 and hay_quantity > 0 and cover_quantity > 0:\n print(f\"Everything is fine! Puppy is happy! Food: {food_quantity/1000:.2f}, Hay: {hay_quantity/1000:.2f}, Cover: {cover_quantity/1000:.2f}.\")\nelse:\n print(\"Merry must go to the pet store!\")\n","repo_name":"ostrev/SoftUni-courses","sub_path":"Fundamentals/exam_preparation/guinea_pig.py","file_name":"guinea_pig.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"11389851321","text":"\"\"\"本模块定义了插件导出的内容对象。\n\n在新版插件系统中,推荐优先使用直接 import 所需要的插件内容。\n\nFrontMatter:\n sidebar_position: 4\n description: nonebot.plugin.export 模块\n\"\"\"\n\nimport warnings\n\nfrom . import _current_plugin\n\n\nclass Export(dict):\n \"\"\"插件导出内容以使得其他插件可以获得。\n\n 用法:\n ```python\n nonebot.export().default = \"bar\"\n\n @nonebot.export()\n def some_function():\n pass\n\n # this doesn't work before python 3.9\n # use\n # export = nonebot.export(); @export.sub\n # instead\n # See also PEP-614: https://www.python.org/dev/peps/pep-0614/\n @nonebot.export().sub\n def something_else():\n pass\n ```\n \"\"\"\n\n def __call__(self, func, **kwargs):\n self[func.__name__] = func\n self.update(kwargs)\n return func\n\n def __setitem__(self, key, value):\n super().__setitem__(key, Export(value) if isinstance(value, dict) else value)\n\n def __setattr__(self, name, value):\n self[name] = Export(value) if isinstance(value, dict) else value\n\n def __getattr__(self, name):\n if name not in self:\n self[name] = Export()\n return self[name]\n\n\ndef export() -> Export:\n \"\"\"获取当前插件的导出内容对象\"\"\"\n warnings.warn(\n \"nonebot.export() is deprecated. \"\n \"See https://github.com/nonebot/nonebot2/issues/935.\",\n DeprecationWarning,\n )\n plugin = _current_plugin.get()\n if not plugin:\n raise RuntimeError(\"Export outside of the plugin!\")\n return plugin.export\n","repo_name":"yamdereneko/pythonProject","sub_path":"nonebot2-master/nonebot/plugin/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"37153046556","text":"import cv2\nimport numpy as np\n\n# Capture calibration images and prepare object and image points\n\n# Calibration pattern\nobjp = np.zeros((6*6, 3), np.float32)\nobjp[:, :2] = np.mgrid[0:6, 0:6].T.reshape(-1, 2)\n\nobjpoints = [] # 3D points in real world space\nimgpoints = [] # 2D points in image plane\n\ncalibration_images = [\n 'calibration_images/calib_img1.jpeg',\n 'calibration_images/calib_img2.jpeg',\n 'calibration_images/calib_img3.jpeg',\n 'calibration_images/calib_img4.jpeg',\n 'calibration_images/calib_img5.jpeg',\n 'calibration_images/calib_img6.jpeg',\n 'calibration_images/calib_img7.jpeg',\n # Add more image file paths as needed\n]\n\n# Capture calibration images and detect corners\nfor img_file in calibration_images:\n img = cv2.imread(img_file)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n ret, corners = cv2.findChessboardCorners(gray, (6, 6), None)\n\n if ret:\n objpoints.append(objp)\n imgpoints.append(corners)\n img = cv2.drawChessboardCorners(img, (6, 6), corners, ret)\n\n cv2.imshow('img',img)\n cv2.waitKey(0)\n\n# Calibrate the camera\nret, camera_matrix, dist_coeffs, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)\n\n# Save camera matrix and distortion coefficients to a file\nprint(camera_matrix)\nprint(dist_coeffs)\nnp.save('camera_matrix.npy', camera_matrix)\nnp.save('dist_coeffs.npy', dist_coeffs)\n","repo_name":"IDontWannaPlay/AutoPaintBot","sub_path":"calibration_matrix/CamCalibrate.py","file_name":"CamCalibrate.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"7157109340","text":"'''\nClass for interacting with the BOSS\nStores BOSS resources\nAssociated with an ingest job\n'''\n\nimport math\nimport os\n\nfrom requests import HTTPError\n\nfrom intern.remote.boss import BossRemote\nfrom intern.resource.boss.resource import *\nfrom intern.service.boss.httperrorlist import HTTPErrorList\n\n\nclass BossResParams:\n def __init__(self, ingest_job):\n self.ingest_job = ingest_job\n\n self.coord_frame_name = '_'.join(\n (ingest_job.coll_name, ingest_job.exp_name))\n\n self.rmt = self.setup_remote()\n\n def get_resources(self, get_only=True):\n self.coll_resource = self.setup_boss_collection(get_only=get_only)\n\n self.coord_frame_resource = self.setup_boss_coord_frame(\n get_only=get_only)\n\n self.exp_resource = self.setup_boss_experiment(get_only=get_only)\n\n self.ch_resource = self.setup_boss_channel(get_only=get_only)\n\n def setup_remote(self):\n if self.ingest_job.boss_config_file:\n return BossRemote(self.ingest_job.boss_config_file)\n else:\n # try to load from environment variable\n token = os.environ['BOSS_TOKEN']\n protocol = 'https'\n host = 'api.boss.neurodata.io'\n config_dict = {'token': token, 'protocol': protocol, 'host': host}\n return BossRemote(config_dict)\n\n def get_boss_project(self, proj_setup, get_only):\n try:\n proj_actual = self.rmt.get_project(proj_setup)\n except HTTPError as e:\n if get_only is False:\n try:\n proj_actual = self.rmt.create_project(proj_setup)\n except Exception as e:\n print(type(e), e)\n raise(e)\n else:\n print(type(e), e)\n raise e\n except Exception as e:\n print(type(e), e)\n raise(e)\n return proj_actual\n\n def setup_boss_collection(self, get_only=True):\n coll_setup = CollectionResource(self.ingest_job.coll_name)\n return self.get_boss_project(coll_setup, get_only)\n\n def setup_boss_coord_frame(self, get_only=True):\n # if we don't know the coordinate frame parameters, get the one with the same name\n if get_only:\n coord_setup = CoordinateFrameResource(self.coord_frame_name)\n else:\n coord_setup = CoordinateFrameResource(self.coord_frame_name, '',\n self.ingest_job.coord_frame_x_extent[0],\n self.ingest_job.coord_frame_x_extent[1],\n self.ingest_job.coord_frame_y_extent[0],\n self.ingest_job.coord_frame_y_extent[1],\n self.ingest_job.coord_frame_z_extent[0],\n self.ingest_job.coord_frame_z_extent[1],\n self.ingest_job.voxel_size[0],\n self.ingest_job.voxel_size[1],\n self.ingest_job.voxel_size[2],\n self.ingest_job.voxel_unit)\n coord_frame_resource = self.get_boss_project(coord_setup, get_only)\n\n if get_only:\n # matching ingest_job values to coordinate frame values (if they weren't specified, they are now populated)\n self.ingest_job.voxel_size = [coord_frame_resource.x_voxel_size,\n coord_frame_resource.y_voxel_size,\n coord_frame_resource.z_voxel_size]\n self.ingest_job.voxel_unit = coord_frame_resource.voxel_unit\n if self.ingest_job.get_extents:\n self.ingest_job.coord_frame_x_extent = [coord_frame_resource.x_start,\n coord_frame_resource.x_stop]\n self.ingest_job.coord_frame_y_extent = [coord_frame_resource.y_start,\n coord_frame_resource.y_stop]\n self.ingest_job.coord_frame_z_extent = [coord_frame_resource.z_start,\n coord_frame_resource.z_stop]\n self.ingest_job.x_extent = self.ingest_job.coord_frame_x_extent\n self.ingest_job.y_extent = self.ingest_job.coord_frame_y_extent\n self.ingest_job.z_extent = self.ingest_job.coord_frame_z_extent\n\n return coord_frame_resource\n\n def setup_boss_experiment(self, get_only=True):\n # if we don't know the coordinate frame parameters, get the one with the same name\n if get_only:\n exp_setup = ExperimentResource(\n self.ingest_job.exp_name, self.ingest_job.coll_name, self.coord_frame_name)\n else:\n # if all elements are the same, isotropic, otherwise anisotropic\n if len(set(self.ingest_job.voxel_size)) <= 1:\n hierarchy_method = 'isotropic'\n else:\n hierarchy_method = 'anisotropic'\n\n num_hierarchy_levels = self.calc_hierarchy_levels()\n\n exp_setup = ExperimentResource(self.ingest_job.exp_name, self.ingest_job.coll_name, self.coord_frame_name, '',\n num_hierarchy_levels, hierarchy_method)\n exp_resource = self.get_boss_project(exp_setup, get_only)\n\n # record the offset (if there is any) into BOSS metadata field for experiment\n self.record_offsets(exp_resource)\n\n return exp_resource\n\n def record_offsets(self, exp_resource):\n if any([a > 0 for a in self.ingest_job.offsets]):\n offsets_dict = {'offsets': self.ingest_job.offsets}\n try:\n self.rmt.create_metadata(exp_resource, offsets_dict)\n except HTTPErrorList: # keys already exist\n self.rmt.update_metadata(exp_resource, offsets_dict)\n\n def setup_boss_channel(self, ch_description='', get_only=True):\n ch_args = [self.ingest_job.ch_name,\n self.ingest_job.coll_name, self.ingest_job.exp_name]\n if not get_only:\n ch_args.extend((self.ingest_job.ch_type, ch_description,\n 0, self.ingest_job.boss_datatype, self.ingest_job.res))\n\n # annotation data\n if self.ingest_job.source_channel is not None:\n ch_args.append([self.ingest_job.source_channel])\n\n # checking to make sure source channel exists (creating if needed)\n try:\n source_args = [self.ingest_job.source_channel,\n self.ingest_job.coll_name, self.ingest_job.exp_name]\n source_setup = ChannelResource(*source_args)\n self.get_boss_project(source_setup, True)\n except:\n self.ingest_job.send_msg(\n 'Creating a dummy source channel for this annotation because none exists yet')\n source_args.extend(('image', '', 0, 'uint8', 0))\n source_setup = ChannelResource(*source_args)\n self.get_boss_project(source_setup, False)\n\n ch_setup = ChannelResource(*ch_args)\n ch_resource = self.get_boss_project(ch_setup, get_only)\n\n if get_only:\n self.ingest_job.boss_datatype = ch_resource.datatype\n if self.ingest_job.datatype is None:\n self.ingest_job.datatype = ch_resource.datatype\n self.ingest_job.res = ch_resource.base_resolution\n\n return ch_resource\n\n def calc_hierarchy_levels(self, lowest_res=512):\n img_size = [self.coord_frame_resource.x_stop - self.coord_frame_resource.x_start,\n self.coord_frame_resource.y_stop - self.coord_frame_resource.y_start,\n self.coord_frame_resource.z_stop - self.coord_frame_resource.z_start]\n\n max_xy = max(img_size[0:1])\n # we add one because 0 is included in the number of downsampling levels\n num_levels = max(1, math.ceil(math.log(max_xy / lowest_res, 2)) + 1)\n return num_levels\n","repo_name":"neurodata/ndex","sub_path":"ndex/ndpush/boss_resources.py","file_name":"boss_resources.py","file_ext":"py","file_size_in_byte":8305,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"51"} +{"seq_id":"23099101207","text":"import shutil\nimport logging\nimport flows\nimport argparse\nimport time, datetime\nimport os,sys\nimport ssh_nodes\nimport gc\n\nfrom flows import *\nfrom ssh_nodes import *\n\nparser = argparse.ArgumentParser(description='Run a bufferbloat test')\nparser.add_argument('--host_wan', type=str, default=\"10.19.85.xx\", required=False, help='PC WAN host to run iperf')\nparser.add_argument('--host_sta1', type=str, default=\"10.19.85.xx\", required=False, help='STA host to run iperf')\nparser.add_argument('--host_sta2', type=str, default=\"10.19.85.xx\", required=False, help='STA host to run iperf')\nparser.add_argument('--host_sta3', type=str, default=\"10.19.85.xx\", required=False, help='STA host to run iperf')\nparser.add_argument('-i','--interval', type=int, required=False, default=1, help='iperf report interval')\nparser.add_argument('-n','--runcount', type=int, required=False, default=2, help='number of runs')\nparser.add_argument('-t','--time', type=float, default=10, required=False, help='time or duration to run traffic')\nparser.add_argument('-o','--output_directory', type=str, required=False, default='./pyflow_log', help='output directory')\nparser.add_argument('--test_name', type=str, default='lat1', required=False)\nparser.add_argument('--loglevel', type=str, required=False, default='INFO', help='python logging level, e.g. INFO or DEBUG')\n\n# Parse command line arguments\nargs = parser.parse_args()\n\n# Set up logging below\nlogfilename='test.log'\ntestselect_dir = args.test_name\nargs.output_directory = os.path.join(args.output_directory, testselect_dir)\nif not os.path.exists(args.output_directory):\n print('Making log directory {}'.format(args.output_directory))\n os.makedirs(args.output_directory)\n\nfqlogfilename = os.path.join(args.output_directory, logfilename)\nnumeric_level = getattr(logging, args.loglevel.upper(), None)\nif not isinstance(numeric_level, int):\n raise ValueError('Invalid log level: %s' % args.loglevel)\nlogging.basicConfig(filename=fqlogfilename, level=numeric_level, format='%(asctime)s %(name)s %(module)s %(levelname)-8s %(message)s')\nlogging.info(\"log file setup for {}\".format(fqlogfilename), exc_info=True)\nprint('Writing log to {}'.format(fqlogfilename))\n\n#configure asyncio logging\nlogging.getLogger('asyncio').setLevel(logging.INFO)\nlogger = logging.getLogger(__name__)\nloop = asyncio.get_event_loop()\nloop.set_debug(False)\n\n#instantiate DUT host and NIC devices\npc_wan = ssh_node(name='PC-10G', ipaddr=args.host_wan, device='enp1s0', devip='192.168.1.15')\nsta1 = ssh_node(name='4389a', ipaddr=args.host_sta1, device='eth1', devip='192.168.1.233')\nsta2 = ssh_node(name='4388b', ipaddr=args.host_sta2, device='eth1', devip='192.168.1.231')\nsta3 = ssh_node(name='4388c', ipaddr=args.host_sta3, device='eth1', devip='192.168.1.232')\n\nif args.test_name == 'lat1' :\n #instantiate traffic objects\n trfc1=iperf_flow(name='UDP_LA1', user='root', server=sta1, client=pc_wan, dstip=sta1.devip, proto='UDP', interval=1, debug=False, window='24M', srcip=pc_wan.devip, srcport='6001', dstport='6001', offered_load='1M')\n trfc2=iperf_flow(name='UDP_LA2', user='root', server=sta2, client=pc_wan, dstip=sta2.devip, proto='UDP', interval=1, debug=False, window='24M', srcip=pc_wan.devip, srcport='6002', dstport='6002', offered_load='1M')\n trfc3=iperf_flow(name='UDP_LIA', user='root', server=sta3, client=pc_wan, dstip=sta3.devip, proto='UDP', interval=1, debug=False, window='24M', srcip=pc_wan.devip, srcport='7001', dstport='7001', offered_load='3G')\n\n\nssh_node.open_consoles(silent_mode=True)\n\ntraffic_flows = iperf_flow.get_instances()\ntry:\n if traffic_flows:\n for runid in range(args.runcount) :\n for traffic_flow in traffic_flows:\n print(\"Running ({}/{}) {} traffic client={} server={} dest={} with load {} for {} seconds\".format(str(runid+1), str(args.runcount), traffic_flow.proto, traffic_flow.client, traffic_flow.server, traffic_flow.dstip, traffic_flow.offered_load, args.time))\n gc.disable()\n iperf_flow.run(time=args.time, flows='all')\n gc.enable()\n try :\n gc.collect()\n except:\n pass\n\n for traffic_flow in traffic_flows :\n traffic_flow.compute_ks_table(directory=args.output_directory, title=args.test_name)\n\n else:\n print(\"No traffic Flows instantiated per test {}\".format(args.test_name))\n\nfinally :\n ssh_node.close_consoles()\n if traffic_flows:\n iperf_flow.close_loop()\n logging.shutdown()\n","repo_name":"neel-patel-1/iperf_qtls","sub_path":"flows/router_latency.py","file_name":"router_latency.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"31889851782","text":"import random\n\nfortune = []\nfortune.append(\"YES!\")\nfortune.append(\"NO!\")\nfortune.append(\"Maybe?\")\n\n\ncont = \"Yes\"\nwhile cont == \"Yes\":\n print(\"Ask me a yes or no question\")\n question = input()\n answer = random.choice(fortune)\n print(answer)\n print (\"Do you want to ask another question?\")\n cont = input(\"Yes or No: \")","repo_name":"anton-hamuha/python-edu","sub_path":"fortune-teller.py","file_name":"fortune-teller.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"3529418459","text":"\"\"\"For our text classification, we have to find some way to \"describe\" bits of data, which are labeled as either\npositive or negative for machine learning training purposes. These descriptions are called \"features\" in machine learning.\nFor our project, we're just going to simply classify each word within a positive or negative review as a \"feature\" of that review. \n\nThen, as we go on, we can train a classifier by showing it all of the features of positive and negative reviews (all the words),\nand let it try to figure out the more meaningful differences between a positive review and a negative review,\nby simply looking for common negative review words and common positive review words. \"\"\" \n\n\n\n\nimport nltk\nimport random\nfrom nltk.corpus import movie_reviews\n\ndocuments = []\n\nfor category in movie_reviews.categories():\n for fileid in movie_reviews.fileids(category):\n documents.append(list(movie_reviews.words(fileid)))\n\nrandom.shuffle(documents)\n\nall_words = []\nfor w in movie_reviews.words():\n all_words.append(w.lower())\n\nall_words = nltk.FreqDist(all_words)\nword_features = list(all_words.keys())[:3000]\n\ndef find_features(document):\n words = set(document)\n features = {}\n for w in word_features:\n features[w] = (w in words)\n return features\n\nprint((find_features(movie_reviews.words('neg/cv000_29416.txt'))))\n\nfeaturesets = [(find_features(rev), category) for (rev,category) in documents]\n\n\n\n\n\n\n\n\n\n\n \n","repo_name":"siddhantkatyan/NLP_MOOC","sub_path":"Features_learning.py","file_name":"Features_learning.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"40304728614","text":"import re\n\n# NOC modules\nfrom noc.core.profile.base import BaseProfile\n\n\nclass Profile(BaseProfile):\n name = \"Dahua.DH\"\n enable_http_session = True\n http_request_middleware = [\n \"digestauth\",\n \"noc.sa.profiles.Dahua.DH.middleware.dahuaauth.DahuaAuthMiddeware\",\n (\"jsonrequestid\", {\"request_id_param\": \"id\"}),\n ]\n config_tokenizer = \"line\"\n config_tokenizer_settings = {\"line_comment\": \"#\", \"rewrite\": [(re.compile(r\"[\\.=\\[\\]]\"), \" \")]}\n config_normalizer = \"DHNormalizer\"\n\n matchers = {\n \"is_rvi\": {\"platform\": {\"$regex\": \"RVi.+\"}},\n \"is_vto\": {\"platform\": {\"$regex\": \"VTO.+\"}},\n }\n\n rx_depth = re.compile(r\"\\S+(\\[[\\S\\d]+\\])\")\n\n @staticmethod\n def parse_equal_output(string):\n r = dict(line.split(\"=\", 1) for line in string.splitlines())\n return r\n\n def parse_tokens(self, string):\n for line in string.splitlines():\n key, value = line.split(\"=\")\n path = []\n for p in key.split(\".\"):\n if self.rx_depth.match(p):\n p1, p2 = p.split(\"[\", 1)\n p2 = [int(x.strip(\"[]\")) for x in p2.split(\"][\")]\n else:\n p1, p2 = p, []\n path += [p1]\n path += p2\n yield path, value\n","repo_name":"nocproject/noc","sub_path":"sa/profiles/Dahua/DH/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"51"} +{"seq_id":"5589877682","text":"\nimport sys\n\n\ndef DFS(L):\n global word,cnt\n if L == len(n):\n cnt+=1\n print(word)\n else:\n for i in range(1,3):\n if i ==2 and L+i > len(n):\n return\n elif int(n[L:L+i]) == 0:\n return\n elif int(n[L:L+i]) <= 25 :\n word += res[int(n[L:L+i])]\n DFS(L+i)\n word = word[:-1]\n\n pass\n\n# 65 97 chr / ord\n# 65 ~ 90 A ~Z\n# res = [0] * 65\nif __name__ ==\"__main__\":\n n = input()\n word=\"\"\n cnt=0\n res=[None]\n for i in range(26):\n res.append(chr(65+i))\n\n DFS(0)\n print(cnt)\n\n\n\n# '''강의 풀이'''\n# def DFS(L,P):\n# global cnt\n# if L== n:\n# cnt+=1\n# for j in range(P):\n# print(chr(64+res[j]),end='')\n# print()\n# else:\n# for i in range(1,27):\n# if code[L]==i:\n# res[P]=i\n# DFS(L+1,P+1)\n# elif i>=10 and code[L]==i//10 and code[L+1] == i%10:\n# res[P] = i\n# DFS(L+2,P+1)\n#\n#\n#\n# if __name__ == \"__main__\":\n# code = list(map(int,input()))\n# n = len(code)\n# code.insert(n,-1)\n# res = [0]*(n+3)\n# cnt = 0\n# DFS(0,0)\n# print(cnt)","repo_name":"jonghae5/CodingTest","sub_path":"섹션 7/6. 알파코드/AA.py","file_name":"AA.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"7381377408","text":"import numpy as np\r\nimport cv2\r\n\r\ndef get_b_img(img):\r\n b_img = np.copy(img)\r\n b_img[:,:,(1)] = 0\r\n b_img[:,:,(2)] = 0\r\n return b_img\r\n\r\ndef get_g_img(img):\r\n g_img = np.copy(img)\r\n g_img[:,:,(0)] = 0\r\n g_img[:,:,(2)] = 0\r\n return g_img\r\n\r\ndef get_r_img(img):\r\n r_img = np.copy(img)\r\n r_img[:,:,(0)] = 0\r\n r_img[:,:,(1)] = 0\r\n return r_img\r\n\r\nimg_path = 'giraffe.jpg'\r\nimg = cv2.imread(img_path, 1)\r\nimg_b = get_b_img(img)\r\nimg_g = get_g_img(img)\r\nimg_r = get_r_img(img)\r\n\r\ncv2.imwrite(f'b_giraffe.jpg', img_b)\r\ncv2.imwrite(f'g_giraffe.jpg', img_g)\r\ncv2.imwrite(f'r_giraffe.jpg', img_r)","repo_name":"PythonZamurai/rgb_img","sub_path":"rgb_img.py","file_name":"rgb_img.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"2742165749","text":"\"\"\"\nComputation of Contributors’ individual raw scores\nbased on Continuous Bradley-Terry model (CBT)\nusing coordinate descent.\n\"\"\"\nimport random\n\nimport numpy as np\nimport pandas as pd\nfrom numba import njit\n\nfrom solidago.comparisons_to_scores.base import ComparisonsToScoresAlgorithm\nfrom solidago.solvers.optimize import brentq\n\n\nDEFAULT_ALPHA = 0.20 # Signal-to-noise hyperparameter\nEPSILON = 1e-5\n\n\n@njit\ndef contributor_loss_partial_derivative(theta_a, theta_b, r_ab, alpha):\n theta_ab = theta_a - theta_b\n return alpha * theta_a + np.sum(\n np.where(\n np.abs(theta_ab) < EPSILON,\n theta_ab / 3,\n 1 / np.tanh(theta_ab) - 1 / theta_ab,\n )\n + r_ab\n )\n\n\n@njit\ndef Delta_theta(theta_ab):\n return np.where(\n np.abs(theta_ab) < EPSILON,\n 1 / 3 - 1 / 15 * theta_ab**2,\n 1 - (1 / np.tanh(theta_ab)) ** 2 + 1 / theta_ab**2,\n ).sum() ** (-0.5)\n\n\n@njit\ndef coordinate_optimize(r_ab, theta_b, precision, alpha):\n return brentq(\n contributor_loss_partial_derivative,\n args=(theta_b, r_ab, alpha),\n xtol=precision,\n )\n\n\nclass ContinuousBradleyTerry(ComparisonsToScoresAlgorithm):\n def __init__(self, r_max, alpha=DEFAULT_ALPHA):\n \"\"\"\n Initialize Continous Bradley Terry (CBT) to compute individual scores\n\n Parameters\n ----------\n r_max: Maximum absolute score of a comparison\n alpha: Regularization term\n \"\"\"\n self.alpha = alpha\n self.r_max = r_max\n\n def coordinate_descent(self, coord_to_subset, initial_scores):\n n_alternatives = len(coord_to_subset)\n unchanged = set()\n to_pick = []\n\n def pick_next_coordinate():\n nonlocal to_pick\n if len(to_pick) == 0:\n to_pick = list(range(n_alternatives))\n random.shuffle(to_pick)\n return to_pick.pop()\n\n theta = initial_scores\n while len(unchanged) < n_alternatives:\n coord = pick_next_coordinate()\n if coord in unchanged:\n continue\n indices, r_ab = coord_to_subset[coord]\n old_theta_a = theta[coord]\n theta_b = theta[indices]\n new_theta_a = coordinate_optimize(\n r_ab, theta_b, precision=EPSILON / 10, alpha=self.alpha\n )\n theta[coord] = new_theta_a\n if abs(new_theta_a - old_theta_a) < EPSILON:\n unchanged.add(coord)\n else:\n unchanged.clear()\n return theta\n\n def compute_individual_scores(self, scores: pd.DataFrame, initial_entity_scores=None):\n scores = scores[[\"entity_a\", \"entity_b\", \"score\"]]\n scores_sym = (\n pd.concat(\n [\n scores,\n pd.DataFrame(\n {\n \"entity_a\": scores.entity_b,\n \"entity_b\": scores.entity_a,\n \"score\": -1 * scores.score,\n }\n ),\n ]\n )\n .set_index([\"entity_a\", \"entity_b\"])\n .sort_index()\n )\n entities_index = scores_sym.index.get_level_values(\"entity_a\").unique()\n coord_to_subset = {}\n for (coord, (_a, group)) in enumerate(scores_sym.groupby(level=\"entity_a\", sort=False)):\n r_ab = group[\"score\"].to_numpy()\n indices = entities_index.get_indexer(group.index.get_level_values(\"entity_b\"))\n coord_to_subset[coord] = (indices, r_ab)\n\n if initial_entity_scores is None:\n initial_scores = np.zeros(len(entities_index))\n else:\n initial_scores = pd.Series(initial_entity_scores, index=entities_index)\n initial_scores.fillna(0.0, inplace=True)\n initial_scores = initial_scores.to_numpy()\n theta_star_numpy = self.coordinate_descent(coord_to_subset, initial_scores=initial_scores)\n delta_star_numpy = np.zeros(len(theta_star_numpy))\n for idx_a in range(len(theta_star_numpy)):\n indices_b, _r_ab = coord_to_subset[idx_a]\n delta_star_numpy[idx_a] = Delta_theta(theta_star_numpy[idx_a] - theta_star_numpy[indices_b])\n\n result = pd.DataFrame(\n {\n \"raw_score\": theta_star_numpy,\n \"raw_uncertainty\": delta_star_numpy,\n },\n index=entities_index,\n )\n result.index.name = \"entity_id\"\n return result\n\n def get_metadata(self) -> dict:\n return {\n \"algorithm_name\": \"continuous_bradley_terry\",\n \"parameters\": {\n \"R_MAX\": self.r_max,\n \"ALPHA\": self.alpha,\n },\n }\n","repo_name":"tournesol-app/tournesol","sub_path":"solidago/src/solidago/comparisons_to_scores/continuous_bradley_terry.py","file_name":"continuous_bradley_terry.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","stars":302,"dataset":"github-code","pt":"51"} +{"seq_id":"20827528066","text":"from functools import partial\n\nimport numpy as np\nimport pytest\nfrom anml.parameter.smoothmapping import Exp, Expit, Identity, Log, Logit\n\n\ndef ad_jacobian(fun, x, out_shape=(), eps=1e-10):\n c = x + 0j\n g = np.zeros((*out_shape, *x.shape))\n if len(out_shape) == 0:\n for i in np.ndindex(x.shape):\n c[i] += eps*1j\n g[i] = fun(c).imag/eps\n c[i] -= eps*1j\n else:\n for j in np.ndindex(out_shape):\n for i in np.ndindex(x.shape):\n c[i] += eps*1j\n g[j][i] = fun(c)[j].imag/eps\n c[i] -= eps*1j\n return g\n\n\nfuns = [\n Identity(),\n Exp(),\n Log(),\n Expit(),\n Logit(),\n]\n\n\n@pytest.fixture\ndef x():\n np.random.seed(123)\n return np.random.rand(5)\n\n\n@pytest.mark.parametrize(\"order\", [-1, 3])\n@pytest.mark.parametrize(\"fun\", funs)\ndef test_illegal_order(order, fun, x):\n with pytest.raises(ValueError):\n fun(x, order=order)\n\n\n@pytest.mark.parametrize(\"fun\", funs)\ndef test_first_order_derivative(fun, x):\n d = np.diag(ad_jacobian(fun, x, out_shape=(x.size,)))\n my_d = fun(x, order=1)\n assert np.allclose(my_d, d)\n\n\n@pytest.mark.parametrize(\"fun\", funs)\ndef test_second_order_derivative(fun, x):\n d2 = np.diag(ad_jacobian(partial(fun, order=1), x, out_shape=(x.size,)))\n my_d2 = fun(x, order=2)\n assert np.allclose(my_d2, d2)\n\n\n@pytest.mark.parametrize(\"fun\", funs)\ndef test_inverse(fun, x):\n assert np.allclose(x, fun(fun.inverse(x)))\n assert np.allclose(x, fun.inverse(fun(x)))\n\n\n@pytest.mark.parametrize(\"x\", [np.array([0.0]), np.array([-1.0])])\ndef test_log_illegal_input(x):\n log = Log()\n with pytest.raises(ValueError):\n log(x)\n\n\n@pytest.mark.parametrize(\"x\", [np.array([-1.0]),\n np.array([0.0]),\n np.array([1.0]),\n np.array([2.0])])\ndef test_logit_illegal_input(x):\n logit = Logit()\n with pytest.raises(ValueError):\n logit(x)\n","repo_name":"ihmeuw-msca/anml","sub_path":"tests/parameter/test_smoothmapping.py","file_name":"test_smoothmapping.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"51"} +{"seq_id":"40355956932","text":"import copy\r\nfrom Constraint import SumEquals, AllDifferent\r\nfrom Domain import Domain\r\nfrom EncryptVar import EncryptVar\r\n\r\n\r\nclass CryptarithmeticSolver:\r\n\r\n def __init__(self, first, second, result):\r\n self.first = first\r\n self.second = second\r\n self.result = result\r\n self.vars = self.getVars()\r\n self.assignments = {'0': 0}\r\n self.constraints = self.getConstraints()\r\n\r\n self.domainReduction()\r\n\r\n # Reducing the domain before the start of the run - with the help of mathematical rules\r\n def domainReduction(self):\r\n fLen, sLen, rLen = len(self.first), len(self.second), len(self.result)\r\n\r\n # If the length of the result is greater than the first and second numbers ->\r\n # the MSB of the result must be 1\r\n if rLen > fLen and rLen > sLen:\r\n self.assignments[self.result[0]] = 1\r\n self.assignments['x'+str(max(len(self.first), len(self.second)) - 1)] = 1\r\n self.updateDomains(self.result[0], 1)\r\n if fLen != sLen:\r\n # If the length of the first number is greater than the second number ->\r\n # the MSB of the first number must be 9 (to reach the length of the result)\r\n if fLen > sLen:\r\n self.assignments[self.first[0]] = 9\r\n self.updateDomains(self.first[0], 9)\r\n else:\r\n self.assignments[self.second[0]] = 9\r\n self.updateDomains(self.second[0], 9)\r\n\r\n # Return a dictionary of variables {variable: EncryptedVar}\r\n def getVars(self):\r\n vars = list(set(self.first + self.second + self.result))\r\n varsElements = {}\r\n for var in vars:\r\n domain = self.getDomain(var)\r\n varsElements[var] = EncryptVar(var, domain)\r\n return varsElements\r\n\r\n # Return an array of possible domain values for the variable given to the function\r\n def getDomain(self, var):\r\n firsts = [self.first[0], self.second[0], self.result[0]]\r\n # A number cannot start with the digit '0'\r\n if var in firsts:\r\n return Domain(list(range(1, 10)))\r\n # The carry digit can only be 0 or 1\r\n elif len(var) == 2:\r\n return Domain([0, 1])\r\n else:\r\n return Domain(list(range(0, 10)))\r\n\r\n # Return an array of constraints\r\n def getConstraints(self):\r\n constraints = []\r\n varsCopy = copy.deepcopy(list(self.vars.keys()))\r\n # Add a constraint of type AllDifferent\r\n constraints += [AllDifferent(varsCopy)]\r\n\r\n # padding the numbers with zeros.\r\n firstPaddingList = '0' * (len(self.result) - len(self.first))\r\n secondPaddingList = '0' * (len(self.result) - len(self.second))\r\n\r\n # Arrange the words in reverse to begin with the LSB digit\r\n firstRev = self.first[::-1] + firstPaddingList\r\n secondRev = self.second[::-1] + secondPaddingList\r\n resultRev = self.result[::-1]\r\n\r\n prevCarry = None\r\n\r\n # Initialize variables for carry numbers\r\n for index in range(len(self.result)):\r\n carry = 'x' + str(index)\r\n domain = self.getDomain(carry)\r\n self.vars[carry] = EncryptVar(carry, domain)\r\n\r\n # Add a constraint of type SumEquals\r\n if not prevCarry:\r\n constraints += [SumEquals([firstRev[index], secondRev[index]], resultRev[index], carry)]\r\n else:\r\n constraints += [SumEquals([firstRev[index], secondRev[index], prevCarry], resultRev[index], carry)]\r\n\r\n prevCarry = carry\r\n\r\n # last carry is out of result 'range'\r\n self.assignments[prevCarry] = 0\r\n return constraints\r\n\r\n # Checks if all assignments have been completed\r\n def isComplete(self, result):\r\n if not result:\r\n return False\r\n return len(result) == (len(self.vars) + 1)\r\n\r\n # Backtracking algorithm for finding the right assignment for the words entered\r\n def backtracking(self, assignments):\r\n if self.isComplete(assignments):\r\n return assignments\r\n\r\n # the main point: which var to choose?\r\n var = self.getUnassignedVar(assignments)\r\n\r\n # Check the possible assignments of the current character\r\n dom = copy.deepcopy(self.vars[var].getDomain().getDomainList())\r\n for value in dom:\r\n if self.checkConsistency(assignments, var, value):\r\n assignments[var] = value\r\n self.updateDomains(var, value)\r\n res = self.backtracking(assignments)\r\n if res != -1:\r\n return res\r\n assignments.pop(var)\r\n self.cancelDomains(var, value)\r\n return -1\r\n\r\n # Check whether the new assignment satisfies all the constraints\r\n def checkConsistency(self, ass, newVar, newValue):\r\n assCopy = dict(copy.deepcopy(ass))\r\n assCopy[newVar] = newValue\r\n for cons in self.constraints:\r\n if not cons.isConsist(assCopy):\r\n return False\r\n return True\r\n\r\n # Return a character that has not yet been assigned\r\n def getUnassignedVar(self, assignments):\r\n unassignedVars = list(filter(lambda x: x not in assignments, self.vars))\r\n return self.sortByMRV(unassignedVars)[0]\r\n\r\n # Sort the array of characters received according to the heuristic 'minimum remaining values'\r\n def sortByMRV(self, unassignedVars):\r\n sortedDomains = sorted(unassignedVars, key=lambda x: len(self.vars[x].domain.domain))\r\n return sortedDomains\r\n\r\n # Domains reduction for new assignment\r\n def updateDomains(self, var, value):\r\n for v in self.vars:\r\n if v != var and len(var) == 1 and len(v) == 1: # means var and v are not carry\r\n self.vars[v].getDomain().removeFromDomain(value)\r\n\r\n # Cancel domains reduction after canceling an inappropriate assignment\r\n def cancelDomains(self, var, value):\r\n for v in self.vars:\r\n if v != var and len(var) == 1 and len(v) == 1: # means var and v are not carry\r\n self.vars[v].getDomain().addToDomain(value)\r\n\r\n","repo_name":"PinhasZiv/CryptArithmetic-problem","sub_path":"Cryptarithmetic/CryptarithmeticSolver.py","file_name":"CryptarithmeticSolver.py","file_ext":"py","file_size_in_byte":6222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"19049193274","text":"# Simple python implementation of Euler Phi function\n# Math sourced from Elementary Number Theory by Kenneth H. Rosen\n# 2020 Dominic Hatch dhatch207 dmh207@gmail.com\n\nimport BruteforceFactorization\n\ndef EulerPhi(n):\n # does the math. takes number, returns value of euler phi function\n x = n\n for i in BruteforceFactorization.pfactor(n):\n x = x * (1 - (1/i))\n\n return int(x)\n\n\ndef main():\n print(\"Enter number:\")\n n = int(input())\n print(\"Euler Phi value:\")\n print(EulerPhi(n))\n\nif __name__ == \"__main__\":\n main()","repo_name":"dhatch207/PracticeCode","sub_path":"EulerPhi.py","file_name":"EulerPhi.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"29454054095","text":"import cv2\nimport numpy as np\nimport os\nimport time\nimport mediapipe as mp\nimport sys\nimport cv2\nimport numpy as np\nimport os\nimport time\nimport mediapipe as mp\nimport sys\n\n##############################################################\n##################### YOU MAY EDIT THIS ######################\n##############################################################\n# Path for exported data\nfolder_name = os.path.join(os.getcwd(), '../../../trash')\n\n# Names of gestures\ngestures = np.array(['luisteren'])\n#gestures = np.array(['vooruit', 'achteruit', 'links', 'rechts', 'stop'])\n\n# Number of videos per gesture\nno_sequences = 1\n\n# Do you want to draw everything?\ndraw_all = False\n\n# Key to go to next video\nstop_key = 'q'\n\n##############################################################\n\nfourcc = cv2.VideoWriter_fourcc(*'XVID') # Video writer\nmp_holistic = mp.solutions.holistic # Holistic model\nmp_drawing = mp.solutions.drawing_utils # Drawing utilities\n\n\ndef mediapipe_detection(image, model):\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # COLOR CONVERSION BGR 2 RGB\n image.flags.writeable = False # Image is no longer writeable\n results = model.process(image) # Make prediction\n image.flags.writeable = True # Image is now writeable\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # COLOR COVERSION RGB 2 BGR\n return image, results\n\n\ndef alleen_nodige_resultaten(results):\n right_handmarks = results.right_hand_landmarks\n if right_handmarks is None: return\n # Gehardcoded number of landmarks\n r = 21\n to_add = None\n for i in range(r):\n # Gehardcoded number of the landmark (20 - 8)\n if i == 12:\n to_add = right_handmarks.landmark.pop()\n continue\n right_handmarks.landmark.pop()\n right_handmarks.landmark.insert(0, to_add)\n results.right_hand_landmarks = right_handmarks\n return results\n\ndef draw_styled_landmarks(image, results, draw_all):\n if draw_all:\n # Draw face connections\n mp_drawing.draw_landmarks(image, results.face_landmarks, mp_holistic.FACEMESH_CONTOURS,\n mp_drawing.DrawingSpec(color=(80, 110, 10), thickness=1, circle_radius=1),\n mp_drawing.DrawingSpec(color=(80, 256, 121), thickness=1, circle_radius=1)\n )\n # Draw pose connections\n mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS,\n mp_drawing.DrawingSpec(color=(80, 22, 10), thickness=2, circle_radius=4),\n mp_drawing.DrawingSpec(color=(80, 44, 121), thickness=2, circle_radius=2)\n )\n # Draw left hand connections\n mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS,\n mp_drawing.DrawingSpec(color=(121, 22, 76), thickness=2, circle_radius=4),\n mp_drawing.DrawingSpec(color=(121, 44, 250), thickness=2, circle_radius=2)\n )\n # Draw right hand connections\n mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS,\n mp_drawing.DrawingSpec(color=(245, 117, 66), thickness=2, circle_radius=4),\n mp_drawing.DrawingSpec(color=(245, 66, 230), thickness=2, circle_radius=2)\n )\n else:\n results = alleen_nodige_resultaten(results)\n if results is None:\n print(None)\n return\n hand_connect = frozenset()\n mp_drawing.draw_landmarks(image, results.right_hand_landmarks, hand_connect,\n mp_drawing.DrawingSpec(color=(245, 117, 66), thickness=2, circle_radius=10),\n mp_drawing.DrawingSpec(color=(245, 66, 230), thickness=2, circle_radius=2)\n )\n print(results.right_hand_landmarks)\n\n\n# Collect\n# Keypoint\n# Values\n# for Training and Testing\n\ndef start_collection(folder_name, gestures, no_sequences, draw_all, stop_key):\n \"\"\"\n Collects gesture video's from the feed and saves to the given folder\n\n :param folder_name: relative folder path\n :param gestures: array of gesture names\n :param no_sequences: number of sequences per gesture\n :param draw_all: do you want to draw all landmarks?\n :param stop_key: char to go the next video recording\n \"\"\"\n\n OUTPUT_FOLDER = os.path.join(os.getcwd(), folder_name)\n\n # Set folders\n for gesture in gestures:\n try:\n os.makedirs(os.path.join(OUTPUT_FOLDER, gesture))\n except:\n pass\n cap = cv2.VideoCapture(0)\n # Set mediapipe model\n with mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic:\n # Loop through actions\n for gesture in gestures:\n # Loop through sequences aka videos\n for reeks in range(no_sequences):\n bool_record = True\n\n # Get number of files in the directory\n lst = os.listdir(os.path.join(OUTPUT_FOLDER, gesture))\n number_files = len(lst)\n\n # Create video file\n file_created = False\n file_duplicate_number = 0\n while not file_created:\n # Check if file with given name already exists\n if os.path.exists(os.path.join(OUTPUT_FOLDER, gesture, f'{gesture}{number_files}_{file_duplicate_number}.avi')):\n file_duplicate_number += 1\n else:\n out = cv2.VideoWriter(os.path.join(OUTPUT_FOLDER, gesture, f'{gesture}{number_files}_{file_duplicate_number}.avi'),\n fourcc, 20.0, (640, 480))\n file_created = True\n frame_num = 0\n while bool_record:\n\n # Read feed\n ret, frame = cap.read()\n\n # Make detections\n image, results = mediapipe_detection(frame, holistic)\n\n # Draw landmarks\n draw_styled_landmarks(image, results, draw_all)\n\n # Flip image\n image = cv2.flip(image, 1)\n frame = cv2.flip(frame, 1)\n\n out.write(frame)\n # Apply wait logic\n if frame_num == 0:\n cv2.putText(image, 'BEGIN VERZAMELEN', (120, 200),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 4, cv2.LINE_AA)\n cv2.putText(image, 'Verzamelen van frames voor gebaar {} video #{}'.format(gesture, reeks), (15, 12),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1, cv2.LINE_AA)\n # Show to screen\n cv2.imshow('Opname van gebaren', image)\n cv2.waitKey(2000)\n frame_num += 1\n else:\n cv2.putText(image, 'Verzamelen van frames voor gebaar {} video #{}'.format(gesture, reeks), (15, 12),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1, cv2.LINE_AA)\n # Show to screen\n cv2.imshow('Opname van gebaren', image)\n\n # Break\n if cv2.waitKey(10) & 0xFF == ord(stop_key):\n bool_record = False\n out.release()\n break\n\n cap.release()\n cv2.destroyAllWindows()\n\n cap.release()\n cv2.destroyAllWindows()\n# start_collection(folder_name, gestures, no_sequences, draw_all, stop_key)","repo_name":"SpeedyCodes/HMM-GestureRecognition","sub_path":"src/utils/collect_data.py","file_name":"collect_data.py","file_ext":"py","file_size_in_byte":7883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"32037099690","text":"\nfrom rmq_channel import rmq_channel\n\n# Define a callback function for handling received messages\ndef on_message_received(ch, method, properties, body):\n print(f\"Received new message: {body}\")\n\n# Establish a connection and create a channel using a helper function (rmq_channel)\nconnection, channel = rmq_channel()\n\n# Declare a queue named 'letterbox',if not exists then only will be create\nchannel.queue_declare(queue='letterbox')\n\n# Set up a basic consumer that listens to the 'letterbox' queue and invokes the\n# on_message_received callback function for each received message\nchannel.basic_consume(queue='letterbox', auto_ack=True, on_message_callback=on_message_received)\n\n# Indicate that the consumer is starting\nprint(\"Starting Consuming\")\n\n# Start the consumer, which will continuously listen for and process messages\nchannel.start_consuming()\n","repo_name":"hafizul16103123/python-rabbitmq-all-type-practise","sub_path":"1-First-RabbitMQ-App/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"23335334362","text":"# -*- coding: utf-8 -*-\n\"\"\"ANI-1, A data set of 20 million calculated off-equilibrium conformations\nfor organic molecules. (https://doi.org/10.6084/m9.figshare.c.3846712.v1)\n\nPlease cite the original paper when using this dataset.\n\nThe dataset is splitted by molecules while loading, \nmeaninig the same molecule shows up in only one of the splitted datasets.\nnote that this scheme is not identical to the original ANI-1 paper.\n\"\"\"\n\n\nimport h5py\nimport numpy as np\nimport tensorflow as tf\nfrom pinn.io.base import map_nested, split_list\n\n\ndef _ani_generator(sample_list):\n from ase.data import atomic_numbers as atomic_num\n for sample in sample_list:\n data = h5py.File(sample[0])[sample[1]]\n coord = data['coordinates'].value\n elems = data['species'].value\n elems = np.array([atomic_num[e.decode()] for e in elems])\n elems = np.tile(elems[np.newaxis, :], [coord.shape[0], 1])\n e_data = data['energies'].value\n yield {'coord': coord, 'elems': elems, 'e_data': e_data}\n\n\ndef load_ani(filelist, cycle_length=4, **kwargs):\n \"\"\"Loads the ANI-1 dataset\n\n Args:\n filelist (list): filenames of ANI-1 h5 files.\n cycle_length (int): number of parallel threads to read h5 file\n **kwargs: split options, see ``pinn.io.base.split_list``\n \"\"\"\n format_dict = {\n 'elems': {'dtype': tf.int32, 'shape': [None]},\n 'coord': {'dtype': tf.float32, 'shape': [None, 3]},\n 'e_data': {'dtype': tf.float32, 'shape': []}}\n dtypes = {k: v['dtype'] for k, v in format_dict.items()}\n shapes = {k: [None] + v['shape'] for k, v in format_dict.items()}\n # Load the list of samples\n sample_list = []\n for fname in filelist:\n store = h5py.File(fname)\n k1 = list(store.keys())[0]\n samples = store[k1]\n for k2 in samples.keys():\n sample_list.append((fname, '{}/{}'.format(k1, k2)))\n # Generate dataset from sample list\n\n def generator_fn(samplelist): return tf.data.Dataset.from_generator(\n lambda: _ani_generator(samplelist), dtypes, shapes).interleave(\n lambda x: tf.data.Dataset.from_tensor_slices(x),\n cycle_length=cycle_length)\n # Generate nested dataset\n subsets = split_list(sample_list, **kwargs)\n splitted = map_nested(generator_fn, subsets)\n return splitted\n","repo_name":"haydensoliver/PiNN","sub_path":"pinn/io/ani.py","file_name":"ani.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"51"} +{"seq_id":"5949880384","text":"import os\r\nimport shutil\r\nimport time\r\nimport logging\r\nimport threading\r\nimport joblib\r\nfrom pathlib import Path\r\nfrom scapy.all import *\r\nfrom datetime import datetime\r\nfrom schedule import Scheduler\r\n\r\n# Set up logging\r\nlogging.basicConfig(filename='nids.log', level=logging.INFO,\r\n format='%(asctime)s %(levelname)s: %(message)s')\r\n\r\nlog_file = \"nids.log\"\r\n\r\n# Load the trained model\r\nmodel = joblib.load('isolation_forest_model.pkl')\r\n\r\n# Function to get all available drives\r\ndef get_drives():\r\n drives = []\r\n for drive_letter in range(ord(\"C\"), ord(\"Z\") + 1):\r\n drive = f\"{chr(drive_letter)}:\"\r\n if os.path.exists(drive):\r\n drives.append(drive)\r\n return drives\r\n\r\n# Function to backup logs to all available drives\r\ndef backup_logs():\r\n drives = get_drives()\r\n for drive in drives:\r\n backup_folder = Path(drive) / \"Daily_NIDS_Data\"\r\n backup_folder.mkdir(exist_ok=True)\r\n shutil.copy2(log_file, backup_folder / os.path.basename(log_file))\r\n\r\n# Backup logs every 24 hours using a separate thread\r\ndef schedule_log_backup():\r\n scheduler = Scheduler()\r\n scheduler.every(24).hours.do(backup_logs)\r\n while True:\r\n scheduler.run_pending()\r\n time.sleep(1)\r\n\r\nbackup_thread = threading.Thread(target=schedule_log_backup)\r\nbackup_thread.start()\r\n\r\n# Prompt the user to set the network settings\r\nnetwork_type = input(\"Is this a business or home-based network? Enter 'B' for business or 'H' for home: \")\r\nif network_type.lower() == \"b\":\r\n monitored_ports = [22, 25, 80, 443]\r\nelse:\r\n monitored_ports = [22, 25, 80, 110, 143, 443]\r\n\r\n# Load the threat intelligence feed\r\nthreat_feed = set()\r\nwith open('threat_feed.txt', 'r') as f:\r\n for line in f:\r\n threat_feed.add(line.strip())\r\n\r\n# Define the packet callback function\r\ndef packet_callback(packet):\r\n if packet.haslayer(TCP) and packet.haslayer(IP):\r\n src_ip = packet[IP].src\r\n dst_ip = packet[IP].dst\r\n src_port = packet[TCP].sport\r\n dst_port = packet[TCP].dport\r\n payload = str(packet[TCP].payload)\r\n\r\n # Feature extraction for anomaly detection\r\n features = [src_port, dst_port, len(payload)]\r\n prediction = model.predict([features])\r\n\r\n if prediction[0] == -1:\r\n logging.warning(f\"Anomaly detected: {src_ip}:{src_port} -> {dst_ip}:{dst_port}, Payload: {payload}\")\r\n\r\n # Check for plaintext credentials in mail traffic\r\n if dst_port in [110, 143, 25]:\r\n if \"user\" in payload.lower() or \"pass\" in payload.lower():\r\n logging.warning(f\"Plaintext credentials detected: {src_ip}:{src_port} -> {dst_ip}:{dst_port}, Payload: {payload}\")\r\n\r\n # Check for SSH brute-force attacks\r\n elif dst_port == 22:\r\n if \"ssh\" in payload.lower() and \"invalid user\" in payload.lower():\r\n logging.warning(f\"SSH brute-force detected: {src_ip}:{src_port} -> {dst_ip}:{dst_port}, Payload: {payload}\")\r\n\r\n # Check for HTTP/HTTPS attacks\r\n elif dst_port in [80, 443]:\r\n if \"sql injection\" in payload.lower() or \"xss\" in payload.lower() or \"csrf\" in payload.lower():\r\n logging.warning(f\"Web attack detected: {src_ip}:{src_port} -> {dst_ip}:{dst_port}, Payload: {payload}\")\r\n\r\n # Check for known malicious IPs\r\n if src_ip in threat_feed or dst_ip in threat_feed:\r\n logging.warning(f\"Traffic from/to known malicious IP detected: {src_ip}:{src_port} -> {dst_ip}:{dst_port}\")\r\n\r\n# Start packet capture\r\nsniff(prn=packet_callback, filter=\"tcp\", store=0)\r\n","repo_name":"abtzpro/BlockerBoy","sub_path":"NIDSv2.py","file_name":"NIDSv2.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"30802884605","text":"import sys\nsys.path.append('类/')\nfrom PyQt5 import QtWidgets\n\nsys.path.append(\"view/\")\nsys.path.append(\"ui/\")\nfrom 知识与参数g import knowForm\nfrom 行为分析g import actForm\nfrom 认知建模g import conForm\nfrom mian import *\n\nclass MainForm(QtWidgets.QMainWindow, Ui_MainWindow):\n def __init__(self):\n super(MainForm, self).__init__()\n self.setupUi(self)\n\n self.child1 = knowForm() # self.child = children()生成子窗口实例self.child.\n self.toolButton_1.clicked.connect(self.child1Show) # 点击actionTst,子窗口就会显示在主窗口的MaingridLayout中\n\n self.child2 = actForm()\n self.toolButton_2.clicked.connect(self.child2Show)\n\n\n self.child3 = conForm()\n self.toolButton_3.clicked.connect(self.child3Show)\n\n\n def child1Show(self):\n self.child2.close()\n self.child3.close()\n self.gridLayout.addWidget(self.child1) # 添加子窗口\n self.child1.show()\n\n def child2Show(self):\n self.child1.close()\n self.child3.close()\n self.gridLayout.addWidget(self.child2) # 添加子窗口\n self.child2.show()\n\n # 参数传递\n for bar in self.child2.mmcondition[1:]:\n for Feature in self.child1.modelFeatureList:\n bar[3].addItem(Feature[0])\n for bar in self.child2.mmresult[1:]:\n for Feature in self.child1.modelFeatureList:\n bar[3].addItem(Feature[0])\n for bar in self.child2.vacondition[1:]:\n for Feature in self.child1.modelFeatureList:\n bar[3].addItem(Feature[0])\n for bar in self.child2.varesult[1:]:\n for Feature in self.child1.modelFeatureList:\n bar[3].addItem(Feature[0])\n\n\n\n def child3Show(self):\n self.child1.close()\n self.child2.close()\n self.gridLayout.addWidget(self.child3) # 添加子窗口\n self.child3.show()\n # 先判断lisp文件是否存在,再进行输出\n self.child3.textEdit.setText('''(clear-all)\\n\\n(define-model count\\n''' + self.child1.SYSTEMSTRING + \"\\n\\n\" + self.child1.SYSTEMCLASSFEATURE + self.child1.SYSTEMFEATURE)\n # 参数传递\n self.child3.systemFeatureList = self.child1.systemFeatureList\n self.child3.modelFeatureList = self.child1.modelFeatureList\n self.child3.stateClassFeatureList = self.child1.stateClassFeatureList\n self.child3.stateClassFeatureList = self.child1.stateClassFeatureList\n self.child3.stateFeatureList = self.child1.stateFeatureList\n\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n myshow = MainForm()\n myshow.show()\n sys.exit(app.exec_())","repo_name":"13385877395/HCI","sub_path":"mainfrom.py","file_name":"mainfrom.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"33964352760","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 24 16:59:34 2020\r\n\r\n@author: evule\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport xlrd\r\nimport numpy as np\r\nimport scipy.stats as sc\r\nimport math\r\n\r\nLibro=xlrd.open_workbook('Ajuste distribucion.xlsx')\r\nInputs=Libro.sheet_by_name('Inputs')\r\n\r\nFechaInicio=xlrd.xldate_as_datetime(Inputs.cell(0,1).value, datemode=0)\r\nFechaFin=xlrd.xldate_as_datetime(Inputs.cell(1,1).value, datemode=0)\r\n\r\nSerie=pd.read_excel('Ajuste distribucion.xlsx', sheet_name='Serie')\r\nSerie=Serie[(Serie['Fecha']>=FechaInicio) & (Serie['Fecha']<=FechaFin)]\r\n\r\n\r\nn=len(Serie)\r\nk=int(round(1+np.log10(n)/np.log10(2),0)) #Defino intervalos utilizando la regla de Sturges\r\nMinimo=min(Serie.Valores)\r\nMaximo=max(Serie.Valores)\r\nAmplitud=(Maximo-Minimo)/k\r\n\r\nIntervaloMax=pd.Series([(Minimo+Amplitud*k) for k in range(1,k+1)])\r\nIntervaloMax.reset_index(drop=True,inplace=True)\r\n\r\nIntervaloMin=pd.Series(Minimo).append(IntervaloMax.iloc[:-1])\r\nIntervaloMin.reset_index(drop=True,inplace=True)\r\n\r\nIntervalo=pd.concat([IntervaloMin,IntervaloMax], axis=1)\r\nIntervalo.columns=['Minimo','Maximo']\r\n\r\ndef Cuenta(y,z): #Para contar la cantidad de datos real en cada intervalo\r\n return (sum((Serie.Valores>=y)&(Serie.Valores<=z)))\r\n\r\nni=pd.Series([Cuenta(Intervalo.Minimo[i],Intervalo.Maximo[i]) for i in range(0,k)])\r\n\r\nCortar=sum(np.cumsum(ni.iloc[::-1])<=5)-1 #Cuando el ultimo intervalo tiene menos de 5 datos, los agrupo\r\nIntervalo=Intervalo.iloc[:-Cortar]\r\nIntervalo.iloc[-1]['Maximo']=Maximo\r\n\r\nni=pd.Series([Cuenta(Intervalo.Minimo[i],Intervalo.Maximo[i]) for i in range(0,len(Intervalo))])\r\nIntervalo=pd.concat([Intervalo,ni], axis=1)\r\nIntervalo.columns=['Minimo','Maximo','ni']\r\n\r\nIntervalo['Xi']=(Intervalo.Minimo+Intervalo.Maximo)/2 #Punto medio del intervalo\r\nIntervalo['Frec relativa']=Intervalo['ni']/n\r\n\r\nnint=len(Intervalo)\r\nAlpha=Inputs.cell(2,1).value\r\n\r\n#Test chi-cuadrado para distintas distribuciones:\r\nMuDistrNormal=Serie.Valores.mean()\r\nSigmaDistrNormal=Serie.Valores.std()\r\nIntervalo['ProbEsperadaDistrNormal']=sc.norm(MuDistrNormal,SigmaDistrNormal).cdf(Intervalo.Maximo)-sc.norm(MuDistrNormal,SigmaDistrNormal).cdf(Intervalo.Minimo)\r\nIntervalo.loc[0,'ProbEsperadaDistrNormal']=sc.norm(MuDistrNormal,SigmaDistrNormal).cdf(Intervalo.loc[0,'Maximo'])\r\nIntervalo.loc[Intervalo.index[-1],'ProbEsperadaDistrNormal']=1-sum(Intervalo['ProbEsperadaDistrNormal'][:-1]) #Ajusto por ley de cierre\r\nIntervalo['FrecEsperadaDistrNormal']=Intervalo['ProbEsperadaDistrNormal']*n\r\nIntervalo['AuxCostoDistrNormal']=((Intervalo['ni']-Intervalo['FrecEsperadaDistrNormal'])**2)/Intervalo['FrecEsperadaDistrNormal']\r\nCantParamDistrNormal=2\r\nGLDistrNormal=nint-CantParamDistrNormal-1 #Grados de libertad\r\nCriticoDistrNormal=sc.chi2.ppf(1-Alpha,GLDistrNormal)\r\nResultadoDistrNormal=sum(Intervalo['AuxCostoDistrNormal'])= u'\\u4e00' and s<=u'\\u9fa5':\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef cut(s,b):\n\traw=s.decode('utf-8')\n\ti,out=0,''\n\tfor a in raw:\n\t\tout+=a\n\t\tif(is_chinese(a)):\n\t\t\ti+=2\n\t\telif a=='\\n':\n\t\t\ti=0\n\t\telse:\n\t\t\ti+=1\n\t\tif i>2*(b-1):\n\t\t\tout+='\\n'\n\t\t\ti=0\n\treturn out.encode('gbk')\n\ndef printf(raw,top,left):\n\tfor num in range(len(raw)):\n\t\tcore.gotoxy((left,num+top))\n\t\tsys.stdout.write(raw[num])\n\nif __name__ == '__main__':\n\ttop,left=5,5\n\ti=0\n\tstring = '''Python的创始人为Guido van Rossum。1989年圣诞节期间,在阿姆斯特丹,Guido为了打发圣诞节的无趣,决心开发一个新的脚本解释程序,做为ABC 语言的一种继承。之所以选中Python(大蟒蛇的意思)作为该编程语言的名字,是因为他是一个叫Monty Python的喜剧团体的爱好者。\\n\n Python在设计上坚持了清晰划一的风格,这使得Python成为一门易读、易维护,并且被大量用户所欢迎的、用途广泛的语言。\\n\n 设计者开发时总的指导思想是,对于一个特定的问题,只要有一种最好的方法来解决就好了。这在由Tim Peters写的Python格言(称为The Zen of Python)里面表述为:There should be one-- and preferably only one --obvious way to do it. 这正好和Perl语言(另一种功能类似的高级动态语言)的中心思想TMTOWTDI(There's More Than One Way To Do It)完全相反。'''\n\ttmp = cut(string,15).split('\\n')\n\twhile 1:\n\t\top=msvcrt.getch()\n\t\tif op=='s':\n\t\t\tos.system('cls')\n\t\t\tprintf(tmp[i:i+8],top,left)\n\t\t\tif i!=len(tmp):\n\t\t\t\ti+=1\n\t\t\t\tcontinue\n\t\telif op=='w':\n\t\t\tos.system('cls')\n\t\t\tprintf(tmp[i:i+8],top,left)\n\t\t\tif i!=0:\n\t\t\t\ti-=1\n\t\t\t\tcontinue\n\t\telse:\n\t\t\tbreak\n","repo_name":"qq431169079/supreme-meme","sub_path":"cui.py/cut.py","file_name":"cut.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"71530168478","text":"\"\"\"\nThis page contains all the functions\n\"\"\"\nimport sys # needed to exit the running task\nimport matplotlib.pyplot as plt #import visuallizing library matplot.lib\nimport read_data as rd\n\n#####################################################################\n# 1\n# This function display some statistics\ndef display_statistics_func():\n students_count = 0\n students_fsw = 0\n students_fcs = 0\n fsw_22 = 0\n # Looping through outer_dict to count the students\n for key, value in rd.outer_dict.items(): # O(n)\n students_count += 1\n\n # Checking if the students are enrolled in FSW\n if (value[\"course_id\"])[0:3]==\"FSW\":\n students_fsw += 1\n # Checking the year of the students that are enrolled in FSW\n if (value[\"course_id\"])[0:5]==\"FSW22\":\n fsw_22 += 1\n # Checking if the students are enrolled in FCS\n if (value[\"course_id\"])[0:3]==\"FCS\":\n students_fcs += 1\n\n print()\n print(\"Total Number of FCS Students:\", students_fcs)\n print(\"Total Number of FSW Students:\", students_fsw)\n print(\"Students enrolled in FSW 2022\", fsw_22)\n print()\n\n # creating the dataset\n data = {\"students_fcs\": students_fcs, \"students_fsw\": students_fsw, \"fsw_22\": fsw_22}\n k = list(data.keys())\n v = list(data.values())\n\n fig = plt.figure(figsize = (5, 2.5))\n \n # creating the bar plot\n plt.bar(k, v, color ='maroon', width = 0.4)\n \n plt.xlabel('Token course')\n plt.ylabel('No. of students')\n plt.title('Students statistics')\n plt.show()\n\n#####################################################################\n# 2\nouter_list = []\n# This function is used to get the data from the dictionary\ndef choose_function(key, value):\n # Creating a list of three None items\n inner_list = [None]*3\n inner_list[0] = key[5:7]\n inner_list[1] = value.get(\"first_name\")\n inner_list[2] = value.get(\"last_name\")\n # Add the inner_list to the outer_list\n outer_list.append(inner_list)\n\n# This function is used to sort a list\ndef sort_list_function(outer_list):\n # Bubble sort algorithme (This algorithme was used in class)\n # Loop through elements from 0 to n\n for i in range(0,len(outer_list)): # O(n^2)\n #Fix the last i elements in place and loop through the remaining elements (j: 1 -> n-i)\n for j in range(1,len(outer_list)-i): # O(n)\n # Comparing the last_name in every list\n # If first>second\n if outer_list[j-1][2] > outer_list[j][2]:\n # Swap elements position\n outer_list[j-1], outer_list[j] = outer_list[j], outer_list[j-1]\n # Looping through the sorted list to print it\n for i in range(0,len(outer_list)): # O(n) \n print(\"Applied year: 20\" + outer_list[i][0] + \" First name: \" + outer_list[i][1] + \" Last name: \" + outer_list[i][2])\n \n# This function is used to display a list of all or specific students\ndef display_all_students_func():\n print()\n print(\"What do you want to list?\")\n print(\"1 - All the students\")\n print(\"2 - The students enrolled in FCS only\")\n print(\"3 - The students enrolled in FSW only\")\n print()\n choice2 = input(\"Enter your choice:\")\n print()\n\n # Checking the input choice of the user\n if choice2==\"1\":\n for key, value in rd.outer_dict.items(): # O(n)\n choose_function(key, value)\n sort_list_function(outer_list)\n outer_list.clear()\n\n elif choice2==\"2\":\n for key, value in rd.outer_dict.items(): # O(n)\n if value.get(\"course_id\")[0:3]==\"FCS\":\n choose_function(key, value)\n sort_list_function(outer_list)\n outer_list.clear()\n\n elif choice2==\"3\":\n for key, value in rd.outer_dict.items(): # O(n)\n if value.get(\"course_id\")[0:3]==\"FSW\":\n choose_function(key, value)\n sort_list_function(outer_list)\n outer_list.clear()\n\n else:\n print(\"Incorrect input\")\n \n#####################################################################\n# 3\n# This function add new student\ndef add_new_student_func():\n print(\"Adding new student\")\n student_id = input(\"Enter the student ID:\").upper()\n # Checking if the user didn't enter an ID\n if student_id ==\"\":\n print()\n print(\"You should enter an ID\")\n\n # Checking if this ID exist in the dictionary keys\n elif student_id in rd.outer_dict.keys(): # O(n)\n print()\n print(\"This student already exist\")\n \n # Adding the details to the inner_dict\n else:\n inner_dict = {\n \"first_name\" : input(\"Enter the student first name:\").lower().capitalize(),\n \"last_name\" : input(\"Enter the student last name:\").lower().capitalize(),\n \"course_id\" : \"N/A\"\n }\n # Adding the details and the student_id to the outer_dict\n rd.outer_dict.update({student_id : inner_dict})\n print(\"Student added successfully\")\n\n#####################################################################\n# 4\n# This function remove a student from the dictionary\ndef remove_student_func():\n print(\"Removing existing student\")\n student_id = input(\"Enter student ID:\").upper()\n\n # Check if the student does not exist\n if student_id not in rd.outer_dict: # O(n)\n print(\"Student not found\")\n else:\n rd.outer_dict.pop(student_id)\n print(\"Student deleted successfully\")\n\n#####################################################################\n# 5\n# This function is used to enroll students in courses\ndef enroll_existing_student_in_a_course_func():\n print(\"Enroll Student in course\")\n student_id = input(\"Enter student ID:\").upper()\n\n # Check if the student does not exist\n if student_id not in rd.outer_dict: # O(n)\n print(\"Student not found\")\n # Check if the student is not enrolled in a course\n elif rd.outer_dict.get(student_id).get(\"course_id\")[0:3] == \"N/A\":\n course_id = input(\"Enter the course you want to enroll it:\").upper()\n rd.outer_dict[student_id][\"course_id\"] = course_id\n print(\"Course enrolled successfully\")\n # Check if the student is enrolled in a course\n else:\n print(\"Student allready enrolled in a course\")\n\n#####################################################################\n# 6\n# This function is used to edit the details of students\ndef edit_student_func():\n print(\"Edit a Student details\")\n student_id = input(\"Enter student ID:\").upper()\n\n # Check if the student does not exist\n if student_id not in rd.outer_dict: # O(n)\n print(\"Student not found\")\n else:\n print()\n print(\"Enter the new details:\")\n print(\"If you leave it empty, the old value will not change\")\n\n new_first_name = input(\"Enter the new first name:\").lower().capitalize()\n if new_first_name != \"\":\n rd.outer_dict[student_id][\"first_name\"] = new_first_name\n\n new_last_name = input(\"Enter the new last name:\").lower().capitalize()\n if new_last_name != \"\":\n rd.outer_dict[student_id][\"last_name\"] = new_last_name\n\n new_course_id = input(\"Enter the new course ID:\").upper()\n if new_course_id != \"\":\n rd.outer_dict[student_id][\"course_id\"] = new_course_id\n\n new_student_id = input(\"Enter the new student ID:\").upper()\n if new_student_id != \"\": \n rd.outer_dict[new_student_id] = rd.outer_dict.pop(student_id)\n\n#####################################################################\n# 7\n# This function display specific student and there informations\ndef display_student_func():\n print(\"Displaying students details:\")\n info = input(\"Enter student ID or name:\")\n\n # Checking if the user entered a name or ID \n if info[0:5]==\"SEFST\":\n # info in this case is the student_id\n if info in rd.outer_dict: # O(n)\n print()\n print(\"Student ID:\", info)\n print(\"First name:\", rd.outer_dict[info][\"first_name\"])\n print(\"Last name:\", rd.outer_dict[info][\"last_name\"])\n print(\"Course ID:\", rd.outer_dict[info][\"course_id\"])\n else:\n print(\"Student not found\")\n else:\n # info in this case is the first_name\n\n # this value will become True if we found at least one user having the input name\n found = False\n\n # Looping through outer_dict\n for key, value in rd.outer_dict.items(): # O(n)\n if value[\"first_name\"]==info:\n print()\n print(\"Student ID:\", key)\n print(\"First name:\", value[\"first_name\"])\n print(\"Last name:\", value[\"last_name\"])\n print(\"Course ID:\", value[\"course_id\"])\n found = True\n if found==False:\n print(\"Student not found\")\n\n#####################################################################\n# 8\n# This function exit the running task\ndef exit_func():\n print()\n print(\"Do you want to save your changes?\")\n print(\"If YES press: y\")\n print(\"If NO press any key\")\n pressed_key = input()\n print()\n # This condition is used to check if the user want to save his changes or no\n if pressed_key==\"y\":\n # Updating the edited dictionary in the database\n file = open(\"database.txt\", \"w\")\n my_str = \"\"\n for key, value in rd.outer_dict.items(): # O(n)\n # Concatenate the data to get the original form in my_str\n my_str += key + \": \" + value[\"first_name\"] + \", \" + value[\"last_name\"] + \", \" + value[\"course_id\"] + \"\\n\"\n # Writting my_str to the text document without the last \\n\n file.write(my_str[:-1])\n file.close()\n print(\"You have logged out\")\n print(\"you have saved your changes\")\n\n else:\n print(\"You have logged out\")\n print(\"You haven't change anything\")\n\n sys.exit() # exit the running task","repo_name":"hicham-hachem/student-management-system","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":9926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"24956454796","text":"'''\n---------------------------------------------------------------\n Code to improve SVM\n Authors: A. Ramirez-Morales and J. Salmon-Gamboa\n ---------------------------------------------------------------\n'''\n\n# model comparison module\n\nimport pandas as pd\nimport datetime\nimport numpy as np\n# sklearn\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\n# framework includes\nimport data_utils as du\n\n\n# perform the ml algos and generate report (fit , predict and metrics)\ndef comparison(sample, X_train, Y_train, Y_test, X_test):\n # initialise list to store process times\n times_list = ['Time']\n\n # creating the dataframe containing the output metrics\n metrics_list = ['Cross Validation', 'Accuracy', 'Precision', 'Recall', 'F1 Score']\n metrics_df = pd.DataFrame({'Metric': metrics_list})\n\n # support vector machine (single case)\n weights= np.ones(len(Y_train))/len(Y_train)\n svc = SVC(C=150.0, kernel='rbf', gamma=1/(2*(10**2)), shrinking = True, probability = True, tol = 0.001)\n start = datetime.datetime.now()\n svc.fit(X_train, Y_train, weights)\n end = datetime.datetime.now()\n times_list.append(end - start)\n Y_pred = svc.predict(X_test)\n temp_list = du.metrics(sample, 'SVC', svc, X_train, Y_train, Y_test, X_test, Y_pred)\n temp_df = pd.DataFrame({'SVC': temp_list})\n metrics_df = pd.concat([metrics_df, temp_df], axis = 1)\n\n # RANDOM forest classifier\n random_forest = RandomForestClassifier(n_estimators=100)\n start = datetime.datetime.now()\n random_forest.fit(X_train, Y_train)\n end = datetime.datetime.now()\n times_list.append(end - start)\n Y_pred = random_forest.predict(X_test)\n temp_list = du.metrics(sample, 'rForest',random_forest, X_train, Y_train, Y_test, X_test, Y_pred)\n temp_df = pd.DataFrame({'Random Forest': temp_list})\n metrics_df = pd.concat([metrics_df, temp_df], axis = 1)\n\n # AdaBoost-SAMME: Zhu, H. Zou, S. Rosset, T. Hastie, “Multi-class AdaBoost”, 2009.\n AdaBoost = AdaBoostClassifier(n_estimators=100, random_state=0)\n start = datetime.datetime.now()\n AdaBoost.fit(X_train, Y_train)\n end = datetime.datetime.now()\n times_list.append(end - start)\n Y_pred = AdaBoost.predict(X_test)\n temp_list = du.metrics(sample, 'AdaBoost-SAMME', AdaBoost, X_train, Y_train, Y_test, X_test, Y_pred)\n temp_df = pd.DataFrame({'AdaBoost': temp_list})\n metrics_df = pd.concat([metrics_df, temp_df], axis = 1)\n\n # Neural Network Multi Layer Perceptron classifier\n NeuralNet = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(2, 2), random_state=1)\n start = datetime.datetime.now()\n NeuralNet.fit(X_train, Y_train)\n end = datetime.datetime.now()\n times_list.append(end - start)\n Y_pred = NeuralNet.predict(X_test)\n temp_list = du.metrics(sample, 'NeuralNet', NeuralNet, X_train, Y_train, Y_test, X_test, Y_pred)\n temp_df = pd.DataFrame({'NeuralNet': temp_list})\n metrics_df = pd.concat([metrics_df, temp_df], axis = 1)\n\n # Gradient Boost Classifier XGBoost\n model_GBC = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0, max_depth=1, random_state=0)\n start = datetime.datetime.now()\n model_GBC.fit(X_train, Y_train)\n end = datetime.datetime.now()\n times_list.append(end - start)\n Y_pred=model_GBC.predict(X_test)\n temp_list = du.metrics(sample, 'XGBoost', model_GBC, X_train, Y_train, Y_test, X_test, Y_pred)\n temp_df = pd.DataFrame({'XGBoost': temp_list})\n metrics_df = pd.concat([metrics_df, temp_df], axis = 1)\n\n # K neighbors classifier. n_neighbors=3 because there are 2 classes\n knn = KNeighborsClassifier(n_neighbors=3)\n start = datetime.datetime.now()\n knn.fit(X_train, Y_train)\n end = datetime.datetime.now()\n times_list.append(end - start)\n Y_pred = knn.predict(X_test)\n temp_list = du.metrics(sample, 'KNN', knn, X_train, Y_train, Y_test, X_test, Y_pred)\n temp_df = pd.DataFrame({'KNN': temp_list})\n metrics_df = pd.concat([metrics_df, temp_df], axis = 1)\n metrics_df.loc[6] = times_list\n #print(times_list)\n\n metrics_df.to_csv('output/{}/metrics_report.csv'.format(sample), index=False)\n","repo_name":"andrex-naranjas/boosting","sub_path":"model_comparison.py","file_name":"model_comparison.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"51"} +{"seq_id":"13757064809","text":"import torch\nfrom gpytorch import models\nfrom gpytorch import means, kernels, distributions, likelihoods, mlls, settings\nfrom gpytorch.utils.grid import choose_grid_size\nimport numpy as np\nimport pods\nimport time\nfrom visualization import plot_gp\n\n\n#SKI (or KISS-GP) is a great way to scale a GP up to very large datasets (100,000+ data points).\n# Kernel interpolation for scalable structured Gaussian processes (KISS-GP)\n# was introduced in this paper: http://proceedings.mlr.press/v37/wilson15.pdf\n\n# SKI is asymptotically very fast (nearly linear), very precise (error decays cubically)\n\nclass StructredKernelGaussianProcess(models.ExactGP):\n\n def __init__(self, x_train, y_train, likelihood):\n super().__init__(x_train, y_train, likelihood)\n # SKI requires a grid size hyperparameter. This util can help with that.\n # Here we are using a grid that has the same number of points as the training data (a ratio of 1.0).\n # Performance can be sensitive to this parameter, so you may want to adjust it for your own problem on a validation set\n grid_size = choose_grid_size(x_train, ratio=1.0)\n self.mean_module = means.ConstantMean()\n self.covar_module = kernels.ScaleKernel(kernels.GridInterpolationKernel(kernels.RBFKernel(),\n grid_size=grid_size,\n num_dims=1))\n\n def forward(self, x):\n mean_x = self.mean_module(x)\n covar_x = self.covar_module(x)\n return distributions.MultivariateNormal(mean_x, covar_x)\n\n\ndata = pods.datasets.olympic_marathon_men()\nx_train = torch.from_numpy(data[\"X\"]).squeeze(-1).type(torch.float32)\ny_train = torch.from_numpy(data[\"Y\"]).squeeze(-1).type(torch.float32)# + torch.randn(train_x.size()) * np.sqrt(0.04)\n\n\nlikelihood = likelihoods.GaussianLikelihood()\nmodel = StructredKernelGaussianProcess(x_train, y_train, likelihood)\n\nx_train = x_train.cuda()\ny_train = y_train.cuda()\nmodel = model.cuda()\nlikelihood = likelihood.cuda()\n\n\nmodel.train()\nlikelihood.train()\n\n\noptimizer = torch.optim.Adam([{'params': model.parameters()}], lr=0.1)\n\n##loss for gp\nmarginal_loglikelihood = mlls.ExactMarginalLogLikelihood(likelihood, model)\n\ntraining_iter = 1000\nfor i in range(training_iter):\n optimizer.zero_grad()\n\n output = model(x_train)\n\n loss = -marginal_loglikelihood(output, y_train) # this gives the marginal loglikelihood log(p(y|X))\n loss.backward()\n\n print(f'Iter {i + 1} - Loss: {loss.item()} noise: {model.likelihood.noise.item()}')\n\n optimizer.step()\n\n\nmodel.eval()\nlikelihood.eval()\n\n\nwith torch.no_grad(), settings.fast_pred_var(), settings.max_root_decomposition_size(25):\n x_test = torch.from_numpy(np.linspace(1870, 2030, 200)[:, np.newaxis]).type(torch.float32)\n x_test = x_test.cuda()\n f_preds = model(x_test)\n y_pred = likelihood(f_preds)\n\n# plot\nwith torch.no_grad():\n mean = y_pred.mean.cpu().numpy()\n var = y_pred.variance.cpu().numpy()\n samples = y_pred.sample().cpu().numpy()\n plot_gp(mean, var, x_test.cpu().numpy(), X_train=x_train.cpu().numpy(), Y_train=y_train.cpu().numpy(), samples=samples)\n\n\n","repo_name":"roholazandie/gaussian_process_tutorial","sub_path":"gpytorch_examples/scalable_gps/structured_kernel_interpolation.py","file_name":"structured_kernel_interpolation.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"30159431148","text":"from collections import namedtuple\nimport dataclasses as dc\nfrom enum import Enum\n\nclass ShipMoveMode(Enum):\n SHIP = 1\n WAYPOINT = 2\n\nclass Position(): \n def __init__(self,x,y):\n self._x = x\n self._y = y\n\n @property \n def x(self):\n return self._x\n\n @property \n def y(self):\n return self._y\n \n @x.setter\n def x(self,val):\n self._x = val \n\n @y.setter\n def y(self,val):\n self._y = val \n\nclass Nav:\n def __init__(self,instruction):\n self._instruction = instruction[0]\n self._units = int(instruction[1:])\n\n @property\n def instruction(self):\n return self._instruction\n\n @property\n def units(self):\n return self._units\n\nclass Ship():\n def __init__(self,file_name):\n with open(file_name,'r') as nav_data:\n self._nav_instructs = [Nav(line.strip('\\n')) for line in nav_data]\n self.reset()\n\n def reset(self):\n self._facing = 90 \n self._position = Position(0,0)\n self._waypoint_position = Position(10,1)\n \n def navigate(self,mode=ShipMoveMode.SHIP):\n '''\n Run navigation instructions and calculate Manhattan distance travelled\n '''\n if mode == ShipMoveMode.SHIP:\n # Ship move mode - Part 1\n for nav in self._nav_instructs:\n if nav.instruction == 'E':\n self._position.x += nav.units \n elif nav.instruction == 'W':\n self._position.x -= nav.units \n elif nav.instruction == 'N':\n self._position.y += nav.units \n elif nav.instruction == 'S':\n self._position.y -= nav.units \n elif nav.instruction == 'L':\n self._facing = self._facing - nav.units\n if self._facing < 0:\n self._facing = 360 + self._facing\n elif nav.instruction == 'R':\n self._facing = (self._facing + nav.units) % 360\n elif nav.instruction == 'F':\n if self._facing == 0:\n self._position.y += nav.units\n elif self._facing == 90:\n self._position.x += nav.units \n elif self._facing == 180:\n self._position.y -= nav.units \n elif self._facing == 270:\n self._position.x -= nav.units\n else: \n # Wapoint mode - Part 2\n for nav in self._nav_instructs:\n if nav.instruction == 'E':\n self._waypoint_position.x += nav.units \n elif nav.instruction == 'W':\n self._waypoint_position.x -= nav.units \n elif nav.instruction == 'N':\n self._waypoint_position.y += nav.units \n elif nav.instruction == 'S':\n self._waypoint_position.y -= nav.units \n elif nav.instruction in ('L','R'):\n self.rotate_waypoint(nav.instruction,nav.units)\n elif nav.instruction == 'F':\n # move ship\n self._position.x += nav.units * self._waypoint_position.x\n self._position.y += nav.units * self._waypoint_position.y\n\n return abs(self._position.x) + abs(self._position.y)\n \n \n def rotate_waypoint(self,direction,rotate_by):\n for r in range(0,rotate_by // 90):\n if direction == \"L\": # counterclockwise\n new_x = self._waypoint_position.y * -1\n self._waypoint_position.y = self._waypoint_position.x\n self._waypoint_position.x = new_x\n else: # clockwise\n new_x = self._waypoint_position.y\n self._waypoint_position.y = self._waypoint_position.x * -1\n self._waypoint_position.x = new_x","repo_name":"dh256/adventofcode","sub_path":"2020/Day12/Ship.py","file_name":"Ship.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"6720118924","text":"file =open('17.2.txt')\ns = 0\ni = 0\nfor n in file:\n n = int(n)\n if n % 2 != 0:\n s += n\n i += 1\nsrarf = s // i\n\nfile = open('17.2.txt')\ncount = 0\nmaxsumm = 0\nlast = int(file.readline())\nfor n in file:\n n = int(n)\n if (last % 5 == 0 and n < srarf) or (n % 5 == 0 and last < srarf):\n count += 1\n maxsumm = max(maxsumm, last + n)\n last = n\nprint(count, maxsumm)","repo_name":"gmrvl/python_ege_2223","sub_path":"sonya/12825781/17.2.py","file_name":"17.2.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"41573668743","text":"import os\nimport sys\nfrom tkinter import Tcl\nimport numpy as np\nfrom tqdm import tqdm\n\n\ndef fns(data_dir):\n fnsu = [\n fn\n for fn in os.listdir(data_dir)\n if fn.startswith(f\"u\") and fn.endswith(f\".npy\")\n ]\n fnsu = Tcl().call(\"lsort\", \"-dict\", fnsu)\n fnsv = [\n fn\n for fn in os.listdir(data_dir)\n if fn.startswith(f\"v\") and fn.endswith(f\".npy\")\n ]\n fnsv = Tcl().call(\"lsort\", \"-dict\", fnsv)\n fnsp = [\n fn\n for fn in os.listdir(data_dir)\n if fn.startswith(f\"p\") and fn.endswith(f\".npy\")\n ]\n fnsp = Tcl().call(\"lsort\", \"-dict\", fnsp)\n return fnsu, fnsv, fnsp\n\n\ndef collect_data(data_dir):\n data_u, data_v, data_p = [], [], []\n diffs = []\n\n fnsu, fnsv, fnsp = fns(data_dir)\n for idx, (fnu, fnv, fnp) in tqdm(\n enumerate(zip(fnsu, fnsv, fnsp)), total=len(fnsp)\n ):\n u = np.load(os.path.join(data_dir, fnu)).squeeze()\n v = np.load(os.path.join(data_dir, fnv)).squeeze()\n p = np.load(os.path.join(data_dir, fnp)).squeeze()\n\n if idx > 0:\n diff = np.linalg.norm(u - data_u[-1])\n diffs.append(diff)\n\n data_u.append(u)\n data_v.append(v)\n data_p.append(p)\n\n os.remove(f\"{data_dir}/{fnu}\")\n os.remove(f\"{data_dir}/{fnv}\")\n os.remove(f\"{data_dir}/{fnp}\")\n\n # Calculate average difference\n avg_diff = np.mean(diffs)\n\n processed_data_u, processed_data_v, processed_data_p = (\n [data_u[0]],\n [data_v[0]],\n [data_p[0]],\n )\n for idx, diff in enumerate(diffs):\n if diff < 0.4 * avg_diff:\n # Too similar, drop the next data point\n print(f\"Diff : {diff}, dropped idx {idx}\")\n continue\n elif diff > 1.5 * avg_diff:\n # Too different, interpolate between data[idx] and data[idx+1]\n print(f\"Diff : {diff}, interped idx {idx}\")\n interpolated = 0.5 * (data_u[idx] + data_u[idx + 1])\n processed_data_u.append(interpolated)\n interpolated = 0.5 * (data_v[idx] + data_v[idx + 1])\n processed_data_v.append(interpolated)\n interpolated = 0.5 * (data_p[idx] + data_p[idx + 1])\n processed_data_p.append(interpolated)\n\n processed_data_u.append(data_u[idx + 1])\n processed_data_v.append(data_v[idx + 1])\n processed_data_p.append(data_p[idx + 1])\n\n uvp = np.stack(\n [\n np.array(processed_data_u),\n np.array(processed_data_v),\n np.array(processed_data_p),\n ],\n axis=0,\n )\n return np.transpose(uvp, (0, 3, 2, 1))\n\n\nif __name__ == \"__main__\":\n case = sys.argv[1]\n data_dir = f\"{os.getcwd()}/{case}/unmasked\"\n uvp = collect_data(data_dir)\n np.save(f\"{data_dir}/uvp.npy\", uvp)\n","repo_name":"J-Massey/BumpStab","sub_path":"data/collect_save.py","file_name":"collect_save.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"16238121752","text":"from DAL.Local_DAL.receiptHeader_dal import Receipt_header_DAL\nimport datetime\n\n\nclass Receipt_header_BL:\n def __init__(self):\n self.receipt_header_dal = Receipt_header_DAL()\n self.monthToNum = {\n 'Jan': 1,\n 'Feb': 2,\n 'Mar': 3,\n 'Apr': 4,\n 'May': 5,\n 'Jun': 6,\n 'Jul': 7,\n 'Aug': 8,\n 'Sep': 9,\n 'Oct': 10,\n 'Nov': 11,\n 'Dec': 12\n }\n\n def get_receipt_headers(self, filteredSeason):\n receipts = self.receipt_header_dal.get_all_receipt_headers(\n filteredSeason)\n receipts_list = []\n for i in receipts:\n if i.receiptRemarks == None:\n i.receiptRemarks = ''\n d = {}\n d['id'] = i.id\n d['season'] = i.season\n d['receiptNum'] = i.receiptNum\n d['receiptDate'] = i.receiptDate\n d['invoiceHeaderID'] = i.invoiceHeaderID\n d['invoiceNum'] = i.invoice_header.invoiceNum\n d['receiptRemarks'] = i.receiptRemarks\n d['invoiceStatus'] = i.invoice_header.invoiceStatus\n\n receipts_list.append(d)\n\n return receipts_list\n\n def add_receipt_header(self, data):\n if \"month\" not in data:\n # data['receiptDate'] ='Thu, 01 Sep 2022 00:00:00 GMT'\n data['day'] = int(data['receiptDate'][5:7])\n data['month'] = self.monthToNum[(data['receiptDate'][8:11])]\n data['year'] = int(data['receiptDate'][12:16])\n data['receiptDate'] = datetime.datetime(\n data['year'], data['month'], data['day'])\n\n new_record = self.receipt_header_dal.add_receipt_header(data)\n return new_record\n\n def delete_receipt_header(self, id):\n deletedrecrod = self.receipt_header_dal.delete_receipt_header(id)\n return deletedrecrod\n\n def update_receipt_header(self, id, data):\n if \"month\" not in data:\n # data['receiptDate'] ='Thu, 01 Sep 2022 00:00:00 GMT'\n data['day'] = int(data['receiptDate'][5:7])\n data['month'] = self.monthToNum[(data['receiptDate'][8:11])]\n data['year'] = int(data['receiptDate'][12:16])\n\n status = self.receipt_header_dal.update_receipt_header(id, data)\n return status\n","repo_name":"MayanAsifLevy/Aitan_Server_Almagor","sub_path":"BL/Local_BL/receiptHeader_bl.py","file_name":"receiptHeader_bl.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"34290251636","text":"import requests\nfrom . import utils\nfrom formanceapi.models import operations, shared\nfrom typing import Optional\n\nclass Script:\n _client: requests.Session\n _security_client: requests.Session\n _server_url: str\n _language: str\n _sdk_version: str\n _gen_version: str\n\n def __init__(self, client: requests.Session, security_client: requests.Session, server_url: str, language: str, sdk_version: str, gen_version: str) -> None:\n self._client = client\n self._security_client = security_client\n self._server_url = server_url\n self._language = language\n self._sdk_version = sdk_version\n self._gen_version = gen_version\n\n \n def run_script(self, request: operations.RunScriptRequest) -> operations.RunScriptResponse:\n r\"\"\"Execute a Numscript\n This route is deprecated, and has been merged into `POST /{ledger}/transactions`.\n \n \"\"\"\n \n base_url = self._server_url\n \n url = utils.generate_url(base_url, \"/api/ledger/{ledger}/script\", request.path_params)\n \n headers = {}\n req_content_type, data, json, files = utils.serialize_request_body(request)\n if req_content_type != \"multipart/form-data\" and req_content_type != \"multipart/mixed\":\n headers[\"content-type\"] = req_content_type\n if data is None and json is None:\n raise Exception('request body is required')\n query_params = utils.get_query_params(request.query_params)\n \n client = self._security_client\n \n r = client.request(\"POST\", url, params=query_params, data=data, json=json, files=files, headers=headers)\n content_type = r.headers.get(\"Content-Type\")\n\n res = operations.RunScriptResponse(status_code=r.status_code, content_type=content_type)\n \n if r.status_code == 200:\n if utils.match_content_type(content_type, \"application/json\"):\n out = utils.unmarshal_json(r.text, Optional[shared.ScriptResponse])\n res.script_response = out\n\n return res\n\n ","repo_name":"speakeasy-sdks/formance-sdks","sub_path":"python-sdk/src/formanceapi/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"41864756328","text":"#!/usr/bin/env python\nimport gzip\nimport math\n\n\n# Class to store word freqences. Word frequences are read from a tab-sepparated file containing two fields: freqences\n# first and words second. Words must be lowercased. The file must be gzipped. Such files can be easyly produced from\n# monolingual text running a command like this:\n# cat monolingual.txt | tokenizer.sh | tr ' ' '\\n' | tr '[:upper:]' '[:lower:]' | sort | uniq -c > wordfreq.txt\nclass WordZipfFreqDist(object):\n\n # Constructor\n def __init__(self, file_with_freq):\n self.word_freqs = dict()\n fname = file_with_freq if not hasattr(file_with_freq, 'name') else file_with_freq.name\n word_ocss = dict()\n with gzip.open(fname, \"r\") as reader:\n for line in reader:\n line = line.decode().strip()\n parts = line.split()\n word = parts[-1]\n occs = int(parts[0])\n word_ocss[word] = occs\n self.total_words = sum(word_ocss.values())\n for word, occs in word_ocss.items():\n self.word_freqs[word] = int(math.log(float(occs)/float(self.total_words))*100)\n self.min_freq = int(math.log(1.0/float(self.total_words))*100)\n max_val = max(self.word_freqs.values())\n min_max_diff = abs(max_val)-abs(self.min_freq)\n self.q1limit = self.min_freq-min_max_diff\n self.q2limit = self.min_freq-(2*min_max_diff)\n self.q3limit = self.min_freq-(3*min_max_diff)\n\n def split_sentence_by_freq(self, sentence):\n word_splits = dict()\n for i in range(0, 4):\n word_splits[i] = set()\n\n for w in sentence:\n word_splits[self.get_word_quartile(w)-1].add(w)\n\n return word_splits\n\n def get_word_quartile(self, word):\n if word in self.word_freqs:\n val_word = self.word_freqs[word]\n if val_word <= self.q1limit:\n return 1\n elif val_word <= self.q2limit:\n return 2\n elif val_word <= self.q3limit:\n return 3\n else:\n return 4\n else:\n return 4\n\n def word_is_in_q1(self, word):\n if word in self.word_freqs:\n val_word = self.word_freqs[word]\n return val_word <= self.q1limit\n else:\n return False\n\n def word_is_in_q2(self, word):\n if word in self.word_freqs:\n val_word = self.word_freqs[word]\n return val_word <= self.q2limit\n else:\n return False\n\n def word_is_in_q3(self, word):\n if word in self.word_freqs:\n val_word = self.word_freqs[word]\n return val_word <= self.q3limit\n else:\n return False\n\n def word_is_in_q4(self, word):\n if word in self.word_freqs:\n val_word = self.word_freqs[word]\n return val_word > self.q3limit\n else:\n return True\n\n def get_word_freq(self, word):\n word = word.lower()\n if word in self.word_freqs:\n return self.word_freqs[word]\n else:\n return self.min_freq\n","repo_name":"bitextor/bicleaner","sub_path":"src/bicleaner/word_freqs_zipf.py","file_name":"word_freqs_zipf.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","stars":134,"dataset":"github-code","pt":"51"} +{"seq_id":"9875459248","text":"from flask_restx import fields\nfrom shop.fauna.serializers import FaunaRef, faunaPagination\nfrom shop.restplus import api\n\ncategory = api.model('Category', {\n 'ref': FaunaRef(readOnly=True, description='The unique identifier product'), #TBD\n 'name': fields.String(attribute='data.name', required=True, description='Product name'),\n})\n\ncategories_list = api.inherit('Categories lists', faunaPagination, {\n 'data': fields.List(fields.Nested(category))\n})\n","repo_name":"fauna-labs/fauna-shopapp-flask","sub_path":"shop/categories/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"51"} +{"seq_id":"40966818188","text":"import torch.nn.functional as F\r\nimport torch.nn as nn\r\n\r\nfrom models.unet_blocks import *\r\n\r\nclass metaCLF(nn.Module):\r\n \r\n def __init__(self, dis_cs, in_cs):\r\n\r\n super(metaCLF, self).__init__()\r\n \r\n self.encode_coords = nn.Sequential(\r\n nn.Conv3d(2, 16, 1, bias=False),\r\n nn.ReLU(inplace=True),\r\n nn.Conv3d(16, 3, 1, bias=False),\r\n )\r\n \r\n self.generate_filters = nn.Sequential(\r\n nn.Conv3d(27, in_cs, 1, bias=False),\r\n nn.ReLU(inplace=True),\r\n nn.Conv3d(in_cs, in_cs*2, 1, bias=False),\r\n nn.ReLU(inplace=True),\r\n nn.Conv3d(in_cs*2, in_cs, 1, bias=False),\r\n )\r\n \r\n def kroneckerProduct(self, x, y):\r\n \r\n bs, c1, h, w, d = x.shape \r\n bs, c2, h, w, d = y.shape \r\n \r\n x = x.view(bs,c1,h*w*d,1).permute(0,2,1,3)\r\n y = y.view(bs,c2,h*w*d,1).permute(0,2,3,1)\r\n \r\n out = torch.matmul(x,y)\r\n out = out.permute(0,2,3,1)\r\n out = out.view(bs,c1*c2,h,w,d)\r\n \r\n return out \r\n \r\n def forward(self, x, d_all):\r\n \r\n x_x = self.encode_coords(d_all[:,0:2,:,:,:])\r\n y_y = self.encode_coords(d_all[:,2:4,:,:,:])\r\n z_z = self.encode_coords(d_all[:,4:6,:,:,:])\r\n \r\n enced_coords = self.kroneckerProduct(x_x, y_y)\r\n enced_coords = self.kroneckerProduct(enced_coords, z_z)\r\n \r\n filters = self.generate_filters(enced_coords)\r\n x = (x * filters).sum(dim=1, keepdim=True)\r\n\r\n return x \r\n\r\nclass unetVggBNNAR1CLFEnc(nn.Module):\r\n def __init__(\r\n self,\r\n input_channels,\r\n output_channels,\r\n num_filters,\r\n use_deconv=0,\r\n use_bn=2\r\n ):\r\n super(unetVggBNNAR1CLFEnc, self).__init__()\r\n self.input_channels = input_channels\r\n self.output_channels = output_channels\r\n self.num_filters = num_filters\r\n self.downsampling_path = nn.ModuleList()\r\n self.upsampling_path = nn.ModuleList()\r\n\r\n # down-sampling\r\n for i in range(len(self.num_filters)):\r\n input_dim = self.input_channels if i == 0 else output_dim\r\n output_dim = self.num_filters[i]\r\n if i == 0:\r\n pool = False\r\n else:\r\n pool = True\r\n self.downsampling_path.append(DownConvBlock(input_dim, output_dim, use_bn=use_bn, pool=pool))\r\n # up-sampling\r\n for i in range(len(self.num_filters)-2, -1, -1):\r\n input_dim = self.num_filters[i+1]\r\n output_dim = self.num_filters[i]\r\n self.upsampling_path.append(UpConvBlock(input_dim, output_dim, use_bn=use_bn, use_deconv=use_deconv))\r\n\r\n # final conv (without any concat)\r\n self.final = metaCLF(dis_cs=6, in_cs=self.num_filters[0]) \r\n\r\n def generateCoordsToBoundary(self, x):\r\n \r\n bs, c, h, w, d = x.size()\r\n ycds, xcds, zcds = np.meshgrid(range(w),range(h),range(d))\r\n \r\n d1 = torch.from_numpy(xcds).float().to(x.device) \r\n d2 = torch.from_numpy(h-xcds).float().to(x.device)\r\n d3 = torch.from_numpy(ycds).float().to(x.device)\r\n d4 = torch.from_numpy(w-ycds).float().to(x.device)\r\n d5 = torch.from_numpy(zcds).float().to(x.device)\r\n d6 = torch.from_numpy(d-zcds).float().to(x.device) \r\n\r\n d_all = torch.stack([d1,d2,d3,d4,d5,d6])\r\n\r\n return d_all.expand(bs, 6, h, w, d)\r\n \r\n def forward(self, x):\r\n\r\n distance_tensor = self.generateCoordsToBoundary(x)\r\n\r\n blocks = []\r\n for idx, down in enumerate(self.downsampling_path):\r\n x = down(x)\r\n if idx != len(self.downsampling_path)-1:\r\n blocks.append(x)\r\n\r\n for idx, up in enumerate(self.upsampling_path):\r\n x = up(x, blocks[-idx-1])\r\n\r\n x = self.final(x, distance_tensor)\r\n return x","repo_name":"Jinwei1209/Bayesian_QSM","sub_path":"models/unetVggBNNAR1CLFEnc.py","file_name":"unetVggBNNAR1CLFEnc.py","file_ext":"py","file_size_in_byte":3943,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"51"} +{"seq_id":"43345084852","text":"\n\n# Number 2\nf_name = input(\"First name : \")\ns_name = input(\"Surname : \")\n\nprint(\"Hello,\", s_name, f_name)\n\n#umber 3\n\nprint(\"What do you call bla bla bla? \\nA gummy bear \")\n\n# 4\na = input(\"Input a number : \")\nb = input(\"Input another number : \")\nprint(int(a) + int(b))\n\n\n#5\n\na = int(input(\"A : \")) \nb = int(input(\"B : \")) \nc = int(input(\"C : \")) \n\nd = (a+b)/c\n\nprint(d)\n\n#6\n\npizza_start = int(input(\"What number of slices did you start with? : \"))\npizza_left = int(input(\"What number of slices do you have left? : \")) \n\ndiff = pizza_start - pizza_left\n\nprint(f\"You have {diff} slices of pizza left \")\nprint(\"You have\", diff, \"slices of pizza left\")\n\n#7\n\nname = input(\"Name : \")\nage = int(input(\"Age : \")) \n\nprint(f\"{name} next birthday, you will be {age + 1}\")\n\n#8\n\n\n\nprice = int(input(\"Total price(USD) : \")) \ndinner = int(input(\"Number of dinners(USD) : \"))\nppd = price/dinner\nprint(f\"Each dinner pays {ppd} USD\")\n\n\"\"\"\n\n#9\ndays = int(input(\"Input the number of days : \"))\nhours = 24*days\nminutes = 60*hours\nseconds = 60*minutes\n\nprint(f\"{hours} hours\")\nprint(f\"{minutes} minutes\")\nprint(f\"{seconds} seconds\")\n#10\n\n\"\"\"\nweight_kg = int(input(\"Input weight in kilograms : \")) \n\nweight_pounds = weight_kg*2204\nprint(f\"{weight_kg} kilograms is equal to {weight_pounds} pounds\")\n\n#11\n\n\nover100 = int(input(\"Input a number over 100 : \"))\nunder10 = int(input(\"Input a number under 10 : \"))\ndivide = over100 % under10\n\nprint(f\"{over100} can be divided by {under10} {divide}times without remainder\")\n","repo_name":"dapoadedire/Python-Beginner-Codes","sub_path":"My Codes/judah.py","file_name":"judah.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"5316503866","text":"import tensorflow as tf\nfrom tensorflow.python.keras.models import Model\nfrom tensorflow.python.keras.layers import (LSTM, Input, Dense, Embedding)\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\ntfconfig = tf.compat.v1.ConfigProto()\ntfconfig.gpu_options.allow_growth = True\n\ninput = Input(shape=(100,), dtype='int32', name='input')\nx = Embedding(\n output_dim=512, input_dim=10000, input_length=100)(input)\nx = LSTM(32)(x)\nx = Dense(64, activation='relu')(x)\nx = Dense(64, activation='relu')(x)\nx = Dense(64, activation='relu')(x)\noutput = Dense(1, activation='sigmoid', name='output')(x)\nmodel = Model(inputs=[input], outputs=[output])\ndot_img_file = '/tmp/model_1.png'\ntf.keras.utils.plot_model(model, to_file=dot_img_file, show_shapes=True)","repo_name":"Lubayna/DSIN_model","sub_path":"code/train_din.py","file_name":"train_din.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"7351341004","text":"try:\n import gym\n import gym_chrome_dino\n from gym_chrome_dino.utils.wrappers import make_dino\n import random\n import numpy as np\n from collections import deque\n import tensorflow as tf\n from keras.models import Sequential\n from keras.layers import InputLayer, Dense, Activation, Flatten, Conv2D, MaxPooling2D\n from keras.optimizers import Adam\n import os\n import datetime\n import cv2\n import display\n import argparse\n import sys\nexcept:\n import install_requirements # install packages\n import gym\n import gym_chrome_dino\n from gym_chrome_dino.utils.wrappers import make_dino\n import random\n import numpy as np\n from collections import deque\n import tensorflow as tf\n from keras.models import Sequential\n from keras.layers import InputLayer, Dense, Activation, Flatten, Conv2D, MaxPooling2D\n from keras.optimizers import Adam\n import os\n import datetime\n import argparse\n import sys\n\n\nclass DQN_Agent:\n #\n # Initialize attributes and construct CNN train_model and target_model\n #\n def __init__(self, state_shape, action_size, gamma, epsilon, min_epsilon, decay, lr, update_rate, max_experiences, min_experiences):\n self.state_shape = state_shape\n self.action_size = action_size\n self.min_experiences = min_experiences\n self.max_experiences = max_experiences\n self.memory = deque(maxlen=self.max_experiences)\n\n # Hyperparameters\n self.gamma = gamma # Discount rate\n self.epsilon = epsilon # Exploration rate\n self.min_epsilon = min_epsilon # Minimal exploration rate (epsilon-greedy)\n self.decay = decay # Decay rate for epsilon\n self.lr = lr # LEarning rate\n self.update_rate = update_rate # Number of steps until updating the target network\n\n # Construct DQN models\n self.train_model = self._build_model()\n self.target_model = self._build_model()\n self.target_model.set_weights(self.train_model.get_weights())\n self.train_model.summary()\n\n #\n # Constructs model\n #\n def _build_model(self):\n\n model = Sequential()\n\n # Convolutional layers\n\n model.add(Conv2D(16, (8, 8), strides=4, padding='same', input_shape=self.state_shape))\n model.add(Activation('relu'))\n\n model.add(Conv2D(32, (4, 4), strides=2, padding='same'))\n model.add(Activation('relu'))\n\n model.add(Conv2D(32, (3, 3), strides=1, padding='same'))\n model.add(Activation('relu'))\n model.add(Flatten())\n\n # FC Layers\n model.add(Dense(self.action_size, activation='linear'))\n\n model.compile(loss='mse', optimizer=Adam(learning_rate=self.lr))\n\n return model\n\n #\n # Stores experience in replay memory\n #\n def add_experience(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done))\n\n #\n # Chooses action based on epsilon-greedy policy\n #\n def get_action(self, state):\n # Random action\n if np.random.rand() <= self.epsilon:\n action = np.random.choice(self.action_size)\n return action\n\n # Exploit\n action_values = self.train_model.predict(state)\n # Max value is the action\n action = np.argmax(action_values[0])\n return action\n\n #\n # Trains model using a random batch of selected experiences in the memory\n #\n def train(self, batch_size):\n minibatch = random.sample(self.memory, batch_size)\n states, targets_f = [], []\n for state, action, reward, next_state, done in minibatch:\n target = reward\n if not done:\n target = (reward + self.gamma *\n np.amax(self.target_model.predict(next_state)[0]))\n target_f = self.target_model.predict(state)\n target_f[0][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.train_model.fit(np.array(states), np.array(targets_f), epochs=1, verbose=0)\n\n #\n # Set the target model parameters to the current model parameters\n #\n def update_target_model(self):\n self.target_model.set_weights(self.train_model.get_weights())\n\n #\n # Save parameters of the trained models\n #\n def save_network(self, name):\n self.train_model.save_weights(name)\n\n #\n # Load parametres of the trained model\n #\n def load_network(self, name):\n self.train_model.load_weights(name)\n\n\n# Preprocessing taken from github.com/ageron/tiny-dqn\ndef process_frame(obs):\n #display.display(obs, \"original\")\n img = obs[20::2, 20:180:2] # crop and downsize\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n (thresh, img) = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)\n #img = img.mean(axis=2) # to greyscale\n #img = (img - 128) / 128 - 1 # normalize from -1. to 1.\n #display.display(img, \"cropped\")\n return img.reshape(65, 80, 1)\n\ndef blend_images(images, blend):\n avg_image = np.expand_dims(np.zeros((65, 80, 1), np.float64), axis=0)\n\n for image in images:\n avg_image += image\n\n if len(images) < blend:\n return avg_image / len(images)\n else:\n return avg_image / blend\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description='Dino ML Agent')\n parser.add_argument(\"-train\", action='store_const', const='train', dest=\"argv\" ,help='Train an agent. Previous progress saved in folder \"models\"')\n parser.add_argument(\"-newTrain\", action='store_const', const='newTrain' ,dest=\"argv\", help='Train an new agent. Previous agent weights will be deleted.')\n parser.add_argument(\"-test\", action='store_const', const='test' ,dest=\"argv\", help='Use the weights saved in the folder \"models\" for the agent.')\n\n args = parser.parse_args()\n\n # check args\n if args.argv==\"train\" or args.argv==\"test\":\n pass\n elif args.argv==\"newTrain\":\n os.system('rm -r models')\n os.system('rm logs.txt')\n else:\n print(\"usage: dino.py [-h] [-train] [-newTrain] [-test]\")\n sys.exit()\n\n env = gym.make('ChromeDino-v0')\n state = env.reset()\n\n state_shape = env.observation_space.shape # (150, 600, 3)\n state_shape = (65, 80, 1) # downsample of the original state size\n num_actions = env.action_space.n # 2\n\n gamma = 0.99 # decay rate of past observations original 0.99\n update_rate = 1000\n train_rate = 500\n\n max_experiences = 15000\n min_experiences = 1000\n\n epsilon = 0.99 # starting value of epsilon\n min_epsilon = 0.1 # final value for epsilon\n decay = 0.99 # epsilon decay rate\n\n # if its testing the epsilon must be 0 \n if args.argv==\"test\":\n epsilon = 0 \n min_epsilon = 0\n\n lr = 1e-2 # learning rate\n\n episodes = 10000\n batch_size = 32\n blend = 4 # Number of images to blend\n\n total_steps = 0\n\n\n\n agent = DQN_Agent(state_shape, num_actions, gamma, epsilon, min_epsilon, decay, lr, update_rate, max_experiences, min_experiences)\n\n if args.argv==\"test\":\n agent.load_network(\"models/agent\")\n\n for ep in range(episodes):\n\n iter = 0\n state = process_frame(env.reset())\n images = deque(maxlen=blend) # Array of images to be blended\n images.append(state)\n next_state, reward, done, info = env.step(1)\n\n rewards = 0\n done = False\n\n while True:\n iter += 1\n total_steps += 1\n reward = 0\n\n # Every update_rate timesteps we update the target network parameters\n if total_steps % agent.update_rate == 0:\n agent.update_target_model()\n\n # Return the average of the last 4 frames\n state = blend_images(images, blend)\n\n # Transitions from one state to the next through the chosen action\n if iter < 40:\n action = 0\n else:\n action = agent.get_action(state)\n\n next_state, reward, done, info = env.step(action)\n\n # Return the avg of the last 4 frames\n next_state = process_frame(next_state)\n images.append(next_state)\n next_state = blend_images(images, blend)\n\n if done:\n rewards = env.unwrapped.game.get_score()\n if args.argv==\"test\":\n agent.epsilon = 0\n print(\"episode: \", ep,\n \"iteration: \", total_steps,\n \"total reward: \", rewards)\n if args.argv==\"train\" or args.argv==\"newTrain\":\n agent.epsilon = max(agent.min_epsilon, agent.epsilon * agent.decay)\n print(\"episode: \", ep,\n \"iteration: \", total_steps,\n \"total reward: \", rewards,\n \"epsilon: \", agent.epsilon,\n \"experiences:\", len(agent.memory))\n f = open(\"logs.txt\", \"a\")\n L = \"%d %d %d %f\\n\" % (ep+1, rewards, total_steps, agent.epsilon)\n f.writelines(L)\n f.close()\n if len(agent.memory) > batch_size:\n print(\"Training...\")\n agent.train(batch_size)\n agent.save_network(\"models/agent\")\n\n break\n\n #reward += env.unwrapped.game.get_score()\n\n # Store sequence in replay memory\n if args.argv==\"train\" or args.argv==\"newTrain\":\n agent.add_experience(state, action, reward, next_state, done)\n\n state = next_state\n","repo_name":"vitalinarh/Dino-RL","sub_path":"dino.py","file_name":"dino.py","file_ext":"py","file_size_in_byte":9875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"72625484651","text":"from collections import deque\n\ndef solution(begin, target, words):\n dq = deque([(begin, 0)])\n visited = [False] * len(words)\n while dq:\n word, cnt = dq.popleft()\n if word == target:\n return cnt \n for i in range(len(words)):\n if not visited[i]:\n tmp = 0\n for j in range(len(word)):\n if words[i][j] != word[j]:\n tmp += 1\n if tmp == 1:\n dq.append([words[i], cnt+1])\n visited[i] = True\n \n return 0\n\n","repo_name":"Hello-Hyuk/coding-test","sub_path":"프로그래머스/lv3/43163. 단어 변환/단어 변환.py","file_name":"단어 변환.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"11683201330","text":"from PyMca import PyMcaQt as qt\n\nicon_first = [\"22 22 2 1\",\n \". c None\",\n \"# c #000000\",\n \"......................\",\n \"......................\",\n \".#.................##.\",\n \".#...............####.\",\n \".#.............######.\",\n \".#...........########.\",\n \".#.........##########.\",\n \".#.......############.\",\n \".#.....##############.\",\n \".#...################.\",\n \".#.##################.\",\n \".#.##################.\",\n \".#...################.\",\n \".#.....##############.\",\n \".#.......############.\",\n \".#.........##########.\",\n \".#...........########.\",\n \".#.............######.\",\n \".#...............####.\",\n \".#.................##.\",\n \"......................\",\n \"......................\"]\n\nicon_previous = [\"22 22 2 1\",\n \". c None\",\n \"# c #000000\",\n \"......................\",\n \"......................\",\n \"...................##.\",\n \".................####.\",\n \"...............######.\",\n \".............########.\",\n \"...........##########.\",\n \".........############.\",\n \".......##############.\",\n \".....################.\",\n \"...##################.\",\n \"...##################.\",\n \".....################.\",\n \".......##############.\",\n \".........############.\",\n \"...........##########.\",\n \".............########.\",\n \"...............######.\",\n \".................####.\",\n \"...................##.\",\n \"......................\",\n \"......................\"]\n\nicon_next = [\"22 22 2 1\",\n \". c None\",\n \"# c #000000\",\n \"......................\",\n \"......................\",\n \".##...................\",\n \".####.................\",\n \".######...............\",\n \".########.............\",\n \".##########...........\",\n \".############.........\",\n \".##############.......\",\n \".################.....\",\n \".##################...\",\n \".##################...\",\n \".################.....\",\n \".##############.......\",\n \".############.........\",\n \".##########...........\",\n \".########.............\",\n \".######...............\",\n \".####.................\",\n \".##...................\",\n \"......................\",\n \"......................\"]\n\nicon_last = [\"22 22 2 1\",\n \". c None\",\n \"# c #000000\",\n \"......................\",\n \"......................\",\n \".##.................#.\",\n \".####...............#.\",\n \".######.............#.\",\n \".########...........#.\",\n \".##########.........#.\",\n \".############.......#.\",\n \".##############.....#.\",\n \".################...#.\",\n \".##################.#.\",\n \".##################.#.\",\n \".################...#.\",\n \".##############.....#.\",\n \".############.......#.\",\n \".##########.........#.\",\n \".########...........#.\",\n \".######.............#.\",\n \".####...............#.\",\n \".##.................#.\",\n \"......................\",\n \"......................\"]\n\n\nclass FrameBrowser(qt.QWidget):\n def __init__(self, parent=None, n=1):\n qt.QWidget.__init__(self, parent)\n self.mainLayout=qt.QHBoxLayout(self)\n self.mainLayout.setMargin(0)\n self.mainLayout.setSpacing(0)\n self.firstButton = qt.QPushButton(self)\n self.firstButton.setIcon(qt.QIcon(qt.QPixmap(icon_first)))\n self.previousButton = qt.QPushButton(self)\n self.previousButton.setIcon(qt.QIcon(qt.QPixmap(icon_previous)))\n self.lineEdit = qt.QLineEdit(self)\n self.lineEdit.setFixedWidth(self.lineEdit.fontMetrics().width('%05d' % n)) \n validator = qt.QIntValidator(1, n, self.lineEdit)\n self.lineEdit.setText(\"1\")\n self._oldIndex = 0\n self.lineEdit.setValidator(validator)\n self.label = qt.QLabel(self)\n self.label.setText(\"of %d\" % n)\n self.nextButton = qt.QPushButton(self)\n self.nextButton.setIcon(qt.QIcon(qt.QPixmap(icon_next)))\n self.lastButton = qt.QPushButton(self)\n self.lastButton.setIcon(qt.QIcon(qt.QPixmap(icon_last)))\n\n self.mainLayout.addWidget(qt.HorizontalSpacer(self))\n self.mainLayout.addWidget(self.firstButton)\n self.mainLayout.addWidget(self.previousButton)\n self.mainLayout.addWidget(self.lineEdit)\n self.mainLayout.addWidget(self.label)\n self.mainLayout.addWidget(self.nextButton)\n self.mainLayout.addWidget(self.lastButton)\n self.mainLayout.addWidget(qt.HorizontalSpacer(self))\n\n self.connect(self.firstButton,\n qt.SIGNAL(\"clicked()\"),\n self._firstClicked)\n\n self.connect(self.previousButton,\n qt.SIGNAL(\"clicked()\"),\n self._previousClicked)\n\n self.connect(self.nextButton,\n qt.SIGNAL(\"clicked()\"),\n self._nextClicked)\n\n\n self.connect(self.lastButton,\n qt.SIGNAL(\"clicked()\"),\n self._lastClicked)\n\n self.connect(self.lineEdit,\n qt.SIGNAL(\"editingFinished()\"),\n self._textChangedSlot)\n\n def _firstClicked(self):\n self.lineEdit.setText(\"%d\" % self.lineEdit.validator().bottom())\n self._textChangedSlot()\n\n def _previousClicked(self):\n if self._oldIndex >= self.lineEdit.validator().bottom():\n self.lineEdit.setText(\"%d\" % (self._oldIndex)) \n self._textChangedSlot()\n\n def _nextClicked(self):\n if self._oldIndex < (self.lineEdit.validator().top()-1):\n self.lineEdit.setText(\"%d\" % (self._oldIndex+2)) \n self._textChangedSlot()\n\n def _lastClicked(self):\n self.lineEdit.setText(\"%d\" % self.lineEdit.validator().top())\n self._textChangedSlot()\n\n def _textChangedSlot(self):\n txt = str(self.lineEdit.text())\n if not len(txt):\n self.lineEdit.setText(\"%d\" % (self._oldIndex+1))\n return\n newValue = int(txt) - 1\n if newValue == self._oldIndex:\n return\n ddict = {}\n ddict[\"event\"] = \"indexChanged\"\n ddict[\"old\"] = self._oldIndex + 1\n self._oldIndex = newValue\n ddict[\"new\"] = self._oldIndex + 1\n self.emit(qt.SIGNAL(\"indexChanged\"), ddict)\n\n def setRange(self, first, last):\n return self.setLimits(first, last)\n\n def setLimits(self, first, last):\n bottom = min(first, last)\n top = max(first, last)\n self.lineEdit.validator().setTop(top)\n self.lineEdit.validator().setBottom(bottom)\n self._oldIndex = bottom - 1\n self.lineEdit.setText(\"%d\" % (self._oldIndex + 1))\n self.label.setText(\" limits = %d, %d\" % (bottom, top))\n\n\n def setNFrames(self, nframes):\n bottom = 1\n top = nframes\n self.lineEdit.validator().setTop(top)\n self.lineEdit.validator().setBottom(bottom)\n self._oldIndex = bottom - 1\n self.lineEdit.setText(\"%d\" % (self._oldIndex + 1))\n self.label.setText(\" of %d\" % (top))\n\n def getCurrentIndex(self):\n return self._oldIndex + 1\n\n def setValue(self, value):\n self.lineEdit.setText(\"%d\" % value)\n self._textChangedSlot()\n\nclass HorizontalSliderWithBrowser(qt.QAbstractSlider):\n def __init__(self, *var):\n qt.QAbstractSlider.__init__(self, *var)\n self.setOrientation(qt.Qt.Horizontal)\n self.mainLayout = qt.QHBoxLayout(self)\n self.mainLayout.setMargin(0)\n self.mainLayout.setSpacing(2)\n self._slider = qt.QSlider(self)\n self._slider.setOrientation(qt.Qt.Horizontal)\n self._browser = FrameBrowser(self)\n self.mainLayout.addWidget(self._slider)\n self.mainLayout.addWidget(self._browser)\n self.connect(self._slider,\n qt.SIGNAL(\"valueChanged(int)\"),\n self._sliderSlot)\n self.connect(self._browser,\n qt.SIGNAL(\"indexChanged\"),\n self._browserSlot)\n\n\n def setMinimum(self, value):\n self._slider.setMinimum(value)\n maximum = self._slider.maximum()\n if value == 1:\n self._browser.setNFrames(maximum)\n else:\n self._browser.setRange(value, maximum)\n\n def setMaximum(self, value):\n self._slider.setMaximum(value)\n minimum = self._slider.minimum()\n if minimum == 1:\n self._browser.setNFrames(value)\n else:\n self._browser.setRange(minimum, value)\n\n def setRange(self, *var):\n self._slider.setRange(*var)\n self._browser.setRange(*var)\n\n def _sliderSlot(self, value):\n self._browser.setValue(value)\n self.emit(qt.SIGNAL(\"valueChanged(int)\"), value)\n\n def _browserSlot(self, ddict):\n self._slider.setValue(ddict['new'])\n\n def setValue(self, value):\n self._slider.setValue(value)\n self._browser.setValue(value)\n\n def value(self):\n return self._slider.value()\n \ndef test1(args):\n app=qt.QApplication(args)\n w=HorizontalSliderWithBrowser()\n def slot(ddict):\n print(ddict)\n qt.QObject.connect(w,\n qt.SIGNAL(\"valueChanged(int)\"),\n slot)\n w.setRange(8, 20)\n w.show()\n app.exec_()\n\n\ndef test2(args):\n app=qt.QApplication(args)\n w=FrameBrowser()\n def slot(ddict):\n print(ddict)\n qt.QObject.connect(w,\n qt.SIGNAL(\"indexChanged\"),\n slot)\n if len(args) > 1:\n w.setLimits(8, 20)\n w.show()\n app.exec_()\n \n\nif __name__==\"__main__\":\n import sys\n test1(sys.argv)\n \n","repo_name":"tonnrueter/pymca_devel","sub_path":"PyMca/FrameBrowser.py","file_name":"FrameBrowser.py","file_ext":"py","file_size_in_byte":10562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"11127377397","text":"from random import*\nfrom time import*\nfrom os import*\ndef c():\n print(\"------------------------------------------------\")\nprint(\"pY-DOS Boot Loader Version 2.21:\")\nc()\nprint(\"1.Start DOS Normally\")\nc()\nprint('2.DOS Boot Manager')\nc()\nboot1 = int(input(\"Lc:>\"))\ndef dos():\n while 1:\n c()\n data1 = \"\"\"\n |-------------------------|\n | pY-DOS |\n | Version 4.0.2 |\n | 22H1 |\n |-------------------------|\n \"\"\"\n print(data1)\n cmd01 = input(\"APPs(app) Turn off(off)\")\n c()\n if cmd01 == \"app\" or \"APP\" or \"App\":\n cmd2 = input(\"Calculator(cal) Guessing Numbers(guess) Back(back)\")\n if cmd2 ==\"cal\" or \"Cal\":\n Caldata = \"\"\"\n |-------------------------|\n | Calculator |\n | for the |\n | pY-DOS |\n | Version22H1 |\n |-------------------------|\n \"\"\"\n c()\n print(Caldata)\n c()\n print(\"1=+ 2=- 3=* 4=/\")\n u = int(input())\n \n c()\n num1 = int(input(\"The first number:\"))\n num2 = int(input(\"The second number:\"))\n ans = 0\n if u == 1:\n ans = ans + num1 + num2\n elif u == 2:\n ans = ans + num1 - num2\n elif u == 3:\n ans = ans + num1 * num2\n else:\n ans = ans + num1 / num2\n print(ans)\n elif cmd2 == \"guess\":\n c()\n print(\"The number is between 1 and 100.\")\n number = int(input())\n NUM = randint(1,100)\n if number < NUM:\n \n print(\"It is small.\")\n elif number > NUM:\n print(\"It is big.\")\n else:\n print(\"You are right!\")\n elif cmd2 == \"back\":\n pass\n elif cmd01 == \"off\":\n break\nif boot1 == 2:\n c()\n print(\"DOS Boot Manager:(Version 2.21)\")\n print(\"1.Start DOS Normally\")\n print(\"2.Safe Mode\")\n boot3 = int(input(\"\"))\n if boot3 == 1:\n dos()\n elif boot3 == 2:\n c()\n print(\"DOS Loading files...\")\n print(\"1.DOS.py\")\n print(\"2.GuessingNum.py\")\n print(\"3.Set.py\")\n print(\"4.Cal.py\")\n sleep(0.75)\n dos()\nelif boot1 == 1:\n dos()\n","repo_name":"uysoftware/End-Support-Releases","sub_path":"pYDOS4.0.2.py","file_name":"pYDOS4.0.2.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"72855165610","text":"from fractions import Fraction\n\n\ndef sgn(i: float) -> int:\n return 0 if i == 0 else 1 if i > 0 else -1\n\n\ndef reciprocal(i: int) -> float:\n return 0 if i == 0 else 1 / i\n\n\ndef list_add(a: list[int], b: list[int]) -> list[int]:\n return [x + y for x, y in zip(a, b)]\n\n\ndef valid_permutations(m: int, n: int) -> list[list[int]]:\n result = []\n sum = [0] * (m + 1)\n quota = [n, *range(1, m + 1)]\n\n _valid_permutations_helper(m, n, result, [], sum, quota)\n\n return result\n\n\ndef _valid_permutations_helper(\n m: int,\n n: int,\n result: list[list[int]],\n seq: list[int],\n sum: list[int],\n quota: list[int],\n) -> None:\n level = len(seq)\n\n sign = 0\n for i in range(1, m + 1):\n if sum[i] != 0:\n sign = sgn(sum[i])\n break\n\n if level == m * (m + 1) / 2 + n:\n if sign == 1 and seq[level - 1] < 0:\n return\n if sign == -1 and seq[level - 1] > 0:\n return\n\n result.append(seq)\n return\n\n valid_moves: list[int] = []\n\n if sign == -1:\n if seq[level - 1] < 0:\n valid_moves = [*range(seq[level - 1], -m - 1, -1), 0, *range(m, 0, -1)]\n elif seq[level - 1] == 0:\n valid_moves = [0, *range(m, 0, -1)]\n else:\n valid_moves = [*range(seq[level - 1], 0, -1)]\n\n if sign == 0:\n valid_moves = [*range(-1, -m - 1, -1), 0, *range(m, 0, -1)]\n\n if sign == 1:\n if seq[level - 1] > 0:\n valid_moves = [*range(-1, -m - 1, -1), 0, *range(m, seq[level - 1] - 1, -1)]\n elif seq[level - 1] == 0:\n valid_moves = [*range(-1, -m - 1, -1), 0]\n else:\n valid_moves = [*range(-1, seq[level - 1] - 1, -1)]\n\n for i in valid_moves:\n absi = abs(i)\n if quota[absi] == 0:\n continue\n\n new_seq = seq + [i]\n quota[absi] -= 1\n sum[absi] += sgn(i)\n\n _valid_permutations_helper(m, n, result, new_seq, sum, quota)\n\n quota[absi] += 1\n sum[absi] -= sgn(i)\n\n\ndef binom(n: Fraction, k: int) -> Fraction:\n result = Fraction(1)\n for i in range(k):\n result *= Fraction(n - i, i + 1)\n\n return result\n\n\ndef factorial(n: int) -> int:\n result = 1\n for i in range(1, n + 1):\n result *= i\n\n return result\n\n\ndef v_coefficient(n: int, weights: dict[int, int]) -> Fraction:\n result = 0\n m = sum([weights[i] for i in range(-n, n + 1)])\n\n for seq in valid_permutations(m, n):\n aux = seq + [0] + [-x for x in reversed(seq)]\n aux = [x for x in aux if x >= 0]\n\n w = 1\n for i in range(1, m):\n t = 0\n for j in range(len(aux)):\n if aux[j] == i + 1:\n t += 1\n if aux[j] == i:\n w *= t\n t -= 1\n\n t = 0\n zero_index = 1 if n > 0 else 0\n for j in range(len(aux)):\n if aux[j] == 0:\n t += weights[zero_index]\n zero_index += (\n -n if zero_index == n or zero_index == 0 else zero_index + 1\n )\n if aux[j] == m:\n w *= t\n t -= 1\n\n if w == 0:\n continue\n\n u = u_coefficient(seq)\n # print(seq, w, u)\n result += w * u\n\n return result\n\n\ndef u_coefficient(seq: list[int]) -> Fraction:\n m = max(abs(x) for x in seq)\n\n sign = []\n convex = []\n\n sum = [0] * (m + 1)\n for i in range(len(seq)):\n sum[abs(seq[i])] += sgn(seq[i])\n\n new_sign = 0\n for j in range(1, m + 1):\n if sum[j] != 0:\n new_sign = sgn(sum[j])\n break\n sign.append(new_sign)\n\n if i == len(seq) - 1:\n convex.append(-sgn(seq[i]))\n else:\n convex.append(sgn(reciprocal(seq[i + 1]) - reciprocal(seq[i])))\n\n zero_places = [i + 1 for i in range(len(sign)) if sign[i] == 0]\n\n # all subsequences of zero_places\n subsequences = []\n for i in range(1 << len(zero_places)):\n subsequence = [0]\n for j in range(len(zero_places)):\n if i & (1 << j):\n subsequence.append(zero_places[j])\n subsequences.append(subsequence)\n\n result = Fraction(0)\n for subsequence in subsequences:\n subresult = Fraction(1)\n\n for i in range(len(subsequence) - 1):\n new_sign = sign[subsequence[i] : subsequence[i + 1]]\n new_convex = convex[subsequence[i] : subsequence[i + 1]]\n subresult *= s_coefficient(new_sign, new_convex)\n\n last_sign = sign[subsequence[-1] :]\n last_convex = convex[subsequence[-1] :]\n subresult *= s_coefficient(last_sign, last_convex, True)\n\n subresult *= binom(Fraction(-1, 2), len(subsequence) - 1)\n result += subresult\n\n return result\n\n\ndef s_coefficient(\n sign: list[int], convex: list[int], is_last: bool = False\n) -> Fraction:\n result = Fraction(1)\n n = len(sign)\n\n degen_pos = 0\n degen_neut = 0\n degen_neg = 0\n reset_degen = False\n\n for i in range(n - 1):\n if sign[i] > 0:\n if convex[i] > 0:\n return Fraction(0)\n\n result *= -1\n\n if convex[i] == 0:\n degen_pos += 1\n reset_degen = i == n - 2 or convex[i + 1] != 0\n\n if sign[i] == 0:\n if convex[i] < 0:\n return Fraction(0)\n\n if convex[i] == 0:\n degen_neut += 1\n reset_degen = i == n - 2 or convex[i + 1] != 0\n\n if sign[i] < 0:\n if convex[i] < 0:\n return Fraction(0)\n\n if convex[i] == 0:\n degen_neg += 1\n reset_degen = i == n - 2 or convex[i + 1] != 0\n\n if reset_degen:\n result *= Fraction(1, factorial(degen_pos + degen_neut + degen_neg + 1))\n\n if degen_neut > 0:\n result *= binom(degen_pos + degen_neut + degen_neg, degen_pos)\n\n degen_pos = 0\n degen_neut = 0\n degen_neg = 0\n\n if is_last:\n if sign[n - 1] > 0:\n if convex[n - 1] > 0:\n return Fraction(0)\n result *= -1\n\n if sign[n - 1] < 0 and convex[n - 1] < 0:\n return Fraction(0)\n\n last_flat = n - 1\n while last_flat >= 0 and convex[last_flat] == 0:\n last_flat -= 1\n\n result *= Fraction(1, 1 << (n - 1 - last_flat))\n\n return result\n","repo_name":"abccsss/flags","sub_path":"flags.py","file_name":"flags.py","file_ext":"py","file_size_in_byte":6459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"42181280836","text":"\"\"\"Constants for We Connect library.\"\"\"\n\nBASE_SESSION = \"https://msg.volkswagen.de\"\nBASE_AUTH = \"https://identity.vwgroup.io\"\nBRAND = \"VW\"\nCOUNTRY = \"DE\"\n\n# Data used in communication\nCLIENT = {\n \"Legacy\": {\n \"CLIENT_ID\": \"9496332b-ea03-4091-a224-8c746b885068@apps_vw-dilab_com\",\n # client id for VWG API, legacy Skoda Connect/MySkoda\n \"SCOPE\": \"openid mbb profile cars address email birthdate nickname phone\",\n # 'SCOPE': 'openid mbb profile cars address email birthdate badge phone driversLicense dealers profession vin',\n \"TOKEN_TYPES\": \"code id_token token\",\n },\n \"New\": {\n \"CLIENT_ID\": \"f9a2359a-b776-46d9-bd0c-db1904343117@apps_vw-dilab_com\",\n # Provides access to new API? tokentype=IDK_TECHNICAL..\n \"SCOPE\": \"openid mbb profile\",\n \"TOKEN_TYPES\": \"code id_token\",\n },\n \"Unknown\": {\n \"CLIENT_ID\": \"72f9d29d-aa2b-40c1-bebe-4c7683681d4c@apps_vw-dilab_com\", # gives tokentype=IDK_SMARTLINK ?\n \"SCOPE\": \"openid dealers profile email cars address\",\n \"TOKEN_TYPES\": \"code id_token\",\n },\n}\n\n\nXCLIENT_ID = \"c8fcb3bf-22d3-44b0-b6ce-30eae0a4986f\"\nXAPPVERSION = \"5.3.2\"\nXAPPNAME = \"We Connect\"\nUSER_AGENT = \"okhttp/3.14.7\"\nAPP_URI = \"carnet://identity-kit/login\"\n\n# Used when fetching data\nHEADERS_SESSION = {\n \"Connection\": \"keep-alive\",\n \"Content-Type\": \"application/json\",\n \"Accept-charset\": \"UTF-8\",\n \"Accept\": \"application/json\",\n \"X-Client-Id\": XCLIENT_ID,\n \"X-App-Version\": XAPPVERSION,\n \"X-App-Name\": XAPPNAME,\n \"User-Agent\": USER_AGENT,\n \"tokentype\": \"IDK_TECHNICAL\",\n}\n\n# Used for authentication\nHEADERS_AUTH = {\n \"Connection\": \"keep-alive\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"x-requested-with\": XAPPNAME,\n \"User-Agent\": USER_AGENT,\n \"X-App-Name\": XAPPNAME,\n}\n\nTEMP_CELSIUS: str = \"°C\"\nTEMP_FAHRENHEIT: str = \"°F\"\n\n\nclass VWStateClass:\n \"\"\"Supported state classes.\"\"\"\n\n MEASUREMENT = \"measurement\"\n TOTAL = \"total\"\n TOTAL_INCREASING = \"total_increasing\"\n\n\nclass VWDeviceClass:\n \"\"\"Supported sensor entity device classes.\"\"\"\n\n BATTERY = \"battery\"\n CONNECTIVITY = \"connectivity\"\n DOOR = \"door\"\n LIGHT = \"light\"\n LOCK = \"lock\"\n MOVING = \"moving\"\n PLUG = \"plug\"\n POWER = \"power\"\n TEMPERATURE = \"temperature\"\n WINDOW = \"window\"\n\n\nclass VehicleStatusParameter:\n \"\"\"Hex codes for vehicle status parameters.\"\"\"\n\n FRONT_LEFT_DOOR_LOCK = \"0x0301040001\"\n FRONT_RIGHT_DOOR_LOCK = \"0x0301040007\"\n REAR_LEFT_DOOR_LOCK = \"0x0301040004\"\n READ_RIGHT_DOOR_LOCK = \"0x030104000A\"\n\n FRONT_LEFT_DOOR_CLOSED = \"0x0301040002\"\n FRONT_RIGHT_DOOR_CLOSED = \"0x0301040008\"\n REAR_LEFT_DOOR_CLOSED = \"0x0301040005\"\n REAR_RIGHT_DOOR_CLOSED = \"0x030104000B\"\n\n HOOD_CLOSED = \"0x0301040011\"\n\n TRUNK_LOCK = \"0x030104000D\"\n TRUNK_CLOSED = \"0x030104000E\"\n\n FRONT_LEFT_WINDOW_CLOSED = \"0x0301050001\"\n FRONT_RIGHT_WINDOW_CLOSED = \"0x0301050005\"\n REAR_LEFT_WINDOW_CLOSED = \"0x0301050003\"\n REAR_RIGHT_WINDOW_CLOSED = \"0x0301050007\"\n SUNROOF_CLOSED = \"0x030105000B\"\n\n PRIMARY_RANGE = \"0x0301030006\"\n SECONDARY_RANGE = \"0x0301030008\"\n\n PRIMARY_DRIVE = \"0x0301030007\"\n SECONDARY_DRIVE = \"0x0301030009\"\n COMBINED_RANGE = \"0x0301030005\"\n FUEL_LEVEL = \"0x030103000A\"\n\n PARKING_LIGHT = \"0x0301010001\"\n\n ODOMETER = \"0x0101010002\"\n\n DAYS_TO_SERVICE_INSPECTION = \"0x0203010004\"\n DISTANCE_TO_SERVICE_INSPECTION = \"0x0203010003\"\n\n DAYS_TO_OIL_INSPECTION = \"0x0203010002\"\n DISTANCE_TO_OIL_INSPECTION = \"0x0203010001\"\n\n ADBLUE_LEVEL = \"0x02040C0001\"\n\n OUTSIDE_TEMPERATURE = \"0x0301020001\"\n","repo_name":"robinostlund/volkswagencarnet","sub_path":"volkswagencarnet/vw_const.py","file_name":"vw_const.py","file_ext":"py","file_size_in_byte":3837,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"55"} +{"seq_id":"6967163277","text":"def merge_two_list(a,b):\n combined_list = []\n begin_a = 0\n begin_b = 0\n while begin_a < len(a) and begin_b < len(b):\n if a[begin_a] < b[begin_b]:\n combined_list.append(a[begin_a])\n begin_a += 1\n else:\n combined_list.append(b[begin_b])\n begin_b += 1\n\n\n if begin_a < len(a):\n combined_list += a[begin_a:]\n if begin_b < len(b):\n combined_list += b[begin_b:]\n return combined_list\n\n\n\ndef merge_sort(s):\n if len(s) == 1:\n return s\n midle = len(s)//2\n left = merge_sort(s[:midle])\n right = merge_sort(s[midle:])\n return merge_two_list(left, right)\n\n\ns = [7, 5, 2, 3, 9, 8, 6]\nprint(merge_sort(s))\n\n","repo_name":"MikitaTsiarentsyeu/Md-PT1-51-22","sub_path":"Tasks/Nikifarau/Task7/task7merge.py","file_name":"task7merge.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"55"} +{"seq_id":"35621774894","text":"import torch\nimport numpy as np\nimport cv2\nfrom network import CCNN\nfrom torch.autograd import Variable\nimport os\nfrom tensorboardX import SummaryWriter\nfrom util.loss import similar_loss\nfrom torchvision import transforms\nimport util.data as utils\nimport argparse\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'true'\ntorch.cuda.set_device(0)\n\n\ndef feed_random_seed(seed=np.random.randint(1, 10000)):\n # feed random seed\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n\n\ndef get_latest_file_name(dir):\n lists = os.listdir(dir)\n if len(lists) > 0:\n lists.sort(key=lambda fn: os.path.getmtime(dir + \"/\" + fn))\n file_new = os.path.join(dir, lists[-1])\n return file_new\n return None\n\n\ndef get_model(model_name):\n if model_name == \"CCNN\":\n return CCNN.Net().cuda()\n\n\ndef get_lr(optimizer):\n for param_group in optimizer.param_groups:\n return param_group['lr']\n\n\ndef train(epoch, dataloader, net, optimizer, alpha, m=0):\n accum_loss = 0\n net.train()\n correct = torch.zeros(1).squeeze().cuda()\n total = torch.zeros(1).squeeze().cuda()\n\n for i, data in enumerate(dataloader):\n images, labels, _ = Variable(data['images']), Variable(\n data['labels']), data['paths']\n shape = list(images.size())\n images = images.reshape(shape[0] * shape[1], *shape[2:])\n labels = labels.reshape(-1)\n images, labels = images.cuda(), labels.cuda()\n b, fea = net(images)\n prediction = torch.argmax(b, 1)\n correct += (prediction == labels).sum().float()\n total += len(labels)\n loss = similar_loss(b, labels, fea, alpha, m)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n accum_loss += loss.data\n print(f'[{epoch}][{i}/{len(dataloader)}] loss: {loss.data:.4f} ',\n end=\"\\r\", flush=False)\n\n acc_str = ((correct/total).cpu().detach().data.numpy())\n return accum_loss/len(dataloader), acc_str\n\n\ndef test(epoch, dataloader, net, alpha, m=0):\n accum_loss = 0\n net.eval()\n correct = torch.zeros(1).squeeze().cuda()\n total = torch.zeros(1).squeeze().cuda()\n with torch.no_grad():\n for i, data in enumerate(dataloader):\n images, labels, _ = Variable(data['images']), Variable(\n data['labels']), data['paths']\n shape = list(images.size())\n images = images.reshape(shape[0] * shape[1], *shape[2:])\n labels = labels.reshape(-1)\n images, labels = images.cuda(), labels.cuda()\n b, fea = net(images)\n prediction = torch.argmax(b, 1)\n correct += (prediction == labels).sum().float()\n total += len(labels)\n loss = similar_loss(b, labels, fea, alpha, m)\n accum_loss += loss.data\n print(f'[{epoch}][{i}/{len(dataloader)}] test_loss: {loss.data:.4f} ',\n end=\"\\r\", flush=False)\n acc_str = ((correct/total).cpu().detach().data.numpy())\n return accum_loss / len(dataloader), acc_str\n\n\ndef main(args):\n resume_epoch = args.resume_epoch\n niter = args.niter\n model_checkpoints = args.model_checkpoints\n m = args.m\n alpha = args.alpha\n mode = args.mode\n\n output_root = \"output/\"+args.model_name+\"/A_S_256_0.4_pair/\"\n train_cover_dir = args.dataset+\"/train/cover\"\n train_stego_dir = args.dataset+\"/train/stego\"\n valid_cover_dir = args.dataset+\"/val/cover\"\n valid_stego_dir = args.dataset+\"/val/stego\"\n test_cover_dir = args.dataset+\"/test/cover\"\n test_stego_dir = args.dataset+\"/test/stego\"\n\n os.makedirs(output_root, exist_ok=True)\n feed_random_seed()\n train_transform = transforms.Compose([\n utils.ToTensor(),\n ])\n\n # load datasets\n train_loader = utils.DataLoaderStego(train_cover_dir, train_stego_dir,\n embedding_otf=False, shuffle=True,\n pair_constraint=True,\n batch_size=args.batch_size,\n transform=train_transform,\n )\n\n val_loader = utils.DataLoaderStego(valid_cover_dir, valid_stego_dir,\n embedding_otf=False, shuffle=False,\n pair_constraint=True,\n batch_size=args.batch_size,\n transform=train_transform,\n )\n test_loader = utils.DataLoaderStego(test_cover_dir, test_stego_dir,\n embedding_otf=False, shuffle=False,\n pair_constraint=True,\n batch_size=args.batch_size,\n transform=train_transform,\n )\n\n model = get_model(args.model_name)\n optimizer = torch.optim.Adadelta(model.parameters(), lr=args.learning_rate, rho=0.95, eps=1e-8,\n weight_decay=5e-4)\n scheduler = torch.optim.lr_scheduler.StepLR(\n optimizer, step_size=50, gamma=0.2)\n\n outf = os.path.join(output_root, \"model\")\n os.makedirs(outf, exist_ok=True)\n\n# setting file\n setting_str = f\"setup config:\\n\\tdataset:{args.dataset}\\n\\t\"\\\n f\"net :{args.model_name} \\n\\tniter:{niter} \\n\\tis_scheduler:{args.is_scheduler} \\n\\t\"\\\n f\"batch size:{args.batch_size}\\n\\tlearning rate:{args.learning_rate}\\n\\tis_logger:{args.is_logger}\\n\\t\"\\\n f\"alhpa:{alpha}\\n\\tmodel_checkpoint:{args.model_checkpoints}\\n\\t\"\\\n f\"auto_train:{args.auto_train}\\n\\toutput root:{output_root}\\n\\tm:{m}\\n\\t\"\n print(setting_str)\n\n with open(output_root+\"/setting.txt\", \"w\") as f:\n f.writelines(setting_str)\n\n if args.is_logger:\n logger = None\n\n if mode == \"test\":\n weights_file = output_root+\"/model/best_model.pth\"\n checkpoint = torch.load(weights_file, map_location='cuda:0')\n model.load_state_dict(checkpoint['net'])\n model.eval()\n elif args.auto_train and args.pretrained_model == \"\":\n weights_file = get_latest_file_name(output_root+\"/model\")\n if weights_file is not None:\n checkpoint = torch.load(weights_file, map_location='cuda:0')\n model.load_state_dict(checkpoint['net'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n # \t\tswtich optimizer coefficient to cuda type\n for state in optimizer.state.values():\n for k, v in state.items():\n if torch.is_tensor(v):\n state[k] = v.cuda()\n if args.is_scheduler is True:\n scheduler.load_state_dict(checkpoint['scheduler'])\n for state in optimizer.state.values():\n for k, v in state.items():\n if torch.is_tensor(v):\n state[k] = v.cuda()\n resume_epoch = checkpoint['epoch'] + 1\n print(\n f\"auto_weight:successfully find latest weight:{weights_file} and load,resume epoch changes to {resume_epoch}\")\n elif args.auto_train:\n ckpt = torch.load(args.pretrained_model)\n model.load_state_dict(ckpt['net'])\n\n best_acc = 0\n\n if mode == \"test\":\n test_loss, test_acc = test(0, test_loader, model, alpha, m)\n print(f'test loss:{test_loss:.4f}test_acc:{test_acc}')\n elif mode == \"train\":\n for epoch in range(resume_epoch, niter + 1):\n train_loss, train_acc = train(\n epoch, train_loader, model, optimizer, alpha, m)\n train_loss_list.append(train_loss)\n train_acc_list.append(train_acc)\n test_loss, test_acc = test(epoch, val_loader, model, alpha, m)\n test_loss_list.append(test_loss)\n test_acc_list.append(test_acc)\n learning_rate_list.append(get_lr(optimizer))\n if args.is_scheduler is True:\n scheduler.step(epoch=epoch)\n torch.cuda.empty_cache()\n if args.is_logger:\n if logger is None:\n logger_root = \"runs/\"\n if not output_root is None:\n logger_root = os.path.join(output_root, logger_root)\n logger = SummaryWriter(logger_root)\n if epoch % model_checkpoints == 0:\n check_loss, check_acc = test(\n epoch, test_loader, model, alpha)\n print(f'test loss:{check_loss:.4f} test_acc:{ check_acc}')\n logger.add_scalar('test_loss', check_loss, epoch + 1)\n logger.add_scalar('test_acc', check_acc, epoch + 1)\n # log out\n for inx in range(model_checkpoints):\n history_epoch = epoch - model_checkpoints + inx\n print(train_acc_list[inx])\n logger.add_scalar(\n 'train_loss', train_loss_list[inx], history_epoch + 1)\n logger.add_scalar(\n 'val_loss', test_loss_list[inx], history_epoch + 1)\n logger.add_scalar(\n 'learning rate', learning_rate_list[inx], history_epoch + 1)\n logger.add_scalar(\n 'train_acc', train_acc_list[inx], history_epoch + 1)\n logger.add_scalar(\n 'val_acc', test_acc_list[inx], history_epoch + 1)\n train_loss_list = []\n test_loss_list = []\n learning_rate_list = []\n train_acc_list = []\n test_acc_list = []\n if args.is_scheduler is True:\n state = {'net': model.state_dict(), 'optimizer': optimizer.state_dict(),\n 'scheduler': scheduler.state_dict(),\n 'epoch': epoch}\n else:\n state = {'net': model.state_dict(), 'optimizer': optimizer.state_dict(),\n 'epoch': epoch}\n torch.save(state, os.path.join(outf, f'{epoch:04d}.pth'))\n if check_acc > best_acc:\n torch.save(state, os.path.join(\n outf, f'best_model.pth'))\n best_acc = check_acc\n\n print(f'[{epoch}] train loss: {train_loss:.4f} val loss:{test_loss:.4f} lr:{get_lr(optimizer)} train_acc:{train_acc} val_acc:{test_acc}')\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--batch_size\",\n default=32,\n help=\"Model definition file.\"\n )\n\n parser.add_argument(\n \"--pretrained_model\",\n default='',\n help=\"Trained model weights file.\"\n )\n\n parser.add_argument(\n \"--model_name\",\n default=\"CCNN\",\n help=\"Choose which model to train.\"\n )\n\n parser.add_argument(\n \"--auto_train\",\n default=True,\n type=bool,\n help=\"Continue training.\"\n )\n\n parser.add_argument(\n \"--resume_epoch\",\n default=1,\n type=int,\n help=\"Resume epoch.\"\n )\n\n parser.add_argument(\n \"--niter\",\n default=400,\n type=int,\n help=\"The number of epochs.\"\n )\n\n parser.add_argument(\n \"--is_scheduler\",\n default=True,\n type=bool,\n help=\"Dynamic learning.\"\n )\n\n parser.add_argument(\n \"--is_logger\",\n default=True,\n type=bool,\n help=\"Log file.\"\n\n )\n\n parser.add_argument(\n \"--model_checkpoints\",\n type=int,\n default='10',\n help=\"Checkpoints.\"\n )\n\n parser.add_argument(\n \"--dataset\",\n default='dataset/A_S_256_0.4_pair',\n help=\"Data folder.\"\n )\n\n parser.add_argument(\n \"--learning_rate\",\n type=float,\n default='0.4',\n help=\"Initial learning rate.\"\n )\n\n parser.add_argument(\n \"--alpha\",\n type=float,\n default='0.05',\n help=\"The parameter of loss.\"\n )\n\n parser.add_argument(\n \"--m\",\n type=float,\n default='3',\n help=\"Distance of pair-wise.\"\n )\n\n parser.add_argument(\n \"--mode\",\n default='test',\n help=\"Train or test.\"\n )\n\n args = parser.parse_args()\n\n main(args)\n","repo_name":"MyRoe/deep_learning_detector","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":12592,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"55"} +{"seq_id":"74762880170","text":"from django.db import models\nfrom geopy.geocoders import Nominatim, ArcGIS\nfrom django_pandas.io import read_frame\nfrom geopy.extra.rate_limiter import RateLimiter\nimport datetime\n\n# Create your models here.\n\n\nclass AddMarker(models.Model):\n users_name = models.CharField(max_length=120)\n # Name_of_Event = models.CharField(max_length=200)\n location = models.CharField(max_length=500)\n # Date_time = models.DateField(default=datetime.datetime.today().strftime('%Y-%m-%d'), auto_now=False, auto_now_add=False, null=True)\n # Registration_Link = models.URLField(max_length=200)\n description = models.TextField(max_length=10000)\n lat = models.DecimalField(decimal_places=6, max_digits=20, null=True, default=32.076179)\n lon = models.DecimalField(decimal_places=6, max_digits=20, null=True, default=-81.088379)\n # Authorization_token = models.CharField(max_length=20)\n\n def set_coordinates(self):\n coordinates_updated = False\n Every_Event = read_frame(AddMarker.objects.filter(id=self.id), fieldnames=[ 'location', 'users_name', 'description'])\n geolocator = Nominatim(user_agent=\"HD GEM\")\n geocode = RateLimiter(geolocator.geocode, min_delay_seconds=0)\n location = Every_Event['location'].apply(geocode)\n point = location.apply(lambda loc: tuple(loc.point) if loc else None)\n point = point.tolist()\n if point == [None]:\n point = [(32.076179), (-81.088379), (0)]\n lat, lon, nop = point[0], point[1], point[-1]\n lat= str(lat).strip('()').strip(',')\n lat = float(lat)\n if lat and self.lat != lat:\n self.lat = lat\n coordinates_updated = True\n #lat = lat.split(\",\")\n # lat = list(lat)\n # lat = [float(i) for i in lat]\n # lat = { i : lat[i] for i in range(0, len(lat) ) }\n lon= str(lon).strip('()').strip(',')\n lon = float(lon)\n if lon and self.lon != lon:\n self.lon = lon\n coordinates_updated = True\n # lon = lon.split(\",\")\n # lon = list(lon)\n # lon = [float(i) for i in lon]\n # lon = { i : lon[i] for i in range(0, len(lon) ) }\n if coordinates_updated:\n self.save()\n\n else:\n lat, lon, nop = zip(*point)\n lat= str(lat).strip('()').strip(',')\n lat = float(lat)\n if lat and self.lat != lat:\n self.lat = lat\n coordinates_updated = True\n #lat = lat.split(\",\")\n # lat = list(lat)\n # lat = [float(i) for i in lat]\n # lat = { i : lat[i] for i in range(0, len(lat) ) }\n lon= str(lon).strip('()').strip(',')\n lon = float(lon)\n if lon and self.lon != lon:\n self.lon = lon\n coordinates_updated = True\n # lon = lon.split(\",\")\n # lon = list(lon)\n # lon = [float(i) for i in lon]\n # lon = { i : lon[i] for i in range(0, len(lon) ) }\n if coordinates_updated:\n self.save()\n\n return self.lat, self.lon\n\n def get_coordinates(self, force_reset=False):\n lat = self.lat\n lon = self.lon\n if not lat or not lon or force_reset:\n lat, lon = self.set_coordinates()\n\n return lat, lon","repo_name":"caseyh9438/floodsight_django","sub_path":"floodmap/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"71084598890","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass AMSoftmax(nn.Module):\n '''\n The am softmax as seen on https://arxiv.org/pdf/1801.05599.pdf,\n\n in_features: size of the embedding, eg. 512\n n_classes: number of classes on the classification task\n s: s parameter of loss, standard = 30.\n m: m parameter of loss, standard = 0.4, best between 0.35 and 0.4 according to paper.\n\n *inputs: tensor shaped (batch_size X embedding_size)\n output : tensor shaped (batch_size X n_classes) AM_softmax logits for NLL_loss.\n\n '''\n def __init__(self, in_features, n_classes, s=30, m=0.4):\n super(AMSoftmax, self).__init__()\n self.linear = nn.Linear(in_features, n_classes, bias=False)\n self.s = s\n self.m = m\n\n def forward(self, *inputs):\n x_vector = F.normalize(inputs[0], p=2, dim=-1)\n self.linear.weight.data = F.normalize(self.linear.weight.data, p=2, dim=-1)\n logits = self.linear(x_vector)\n scaled_logits = (logits - self.m)*self.s\n return scaled_logits - self._am_logsumexp(logits)\n\n def _am_logsumexp(self, logits):\n '''\n logsumexp designed for am_softmax, the computation is numerically stable\n\n '''\n max_x = torch.max(logits, dim=-1)[0].unsqueeze(-1)\n term1 = (self.s*(logits - (max_x + self.m))).exp()\n term2 = (self.s * (logits - max_x)).exp().sum(-1).unsqueeze(-1) \\\n - (self.s * (logits - max_x)).exp()\n return self.s*max_x + (term2 + term1).log()\n","repo_name":"dalisson/am_softmax","sub_path":"am_softmax.py","file_name":"am_softmax.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"55"} +{"seq_id":"30999983733","text":"import os\nimport shutil\nimport zipfile\n\nbuild_name = 'Prismatik-iRacing'\n\n# Set up common source and destination directories\ncurrent_dir = os.path.abspath(os.path.dirname(__file__))\nsrc_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))\nroot_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))\nplugins_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))\ntemp_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'release-temp'))\ntemp_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'release-temp', build_name))\n\n# Check that the script is in the right folder\nfile_check = current_dir[len(root_dir):]\nexpected_directory = \"\\src\\\\build\"\n\nif file_check != expected_directory:\n\traise UserWarning(\"Error: script not running from expected directory!\")\nelse:\n\tprint(\"Script running from expected directory\")\n\n\n# Copy helper class\nclass CopyPath:\n\tpaths = []\n\n\tdef __init__(self, source, destination, isdir=False):\n\t\tself.source = os.path.join(root_dir, source)\n\t\tself.destination = os.path.join(temp_dir, destination)\n\t\tself.directory = isdir\n\t\tself.paths.append(self)\n\n\tdef copy(self):\n\t\tif self.directory:\n\t\t\tshutil.copytree(self.source, self.destination)\n\t\telse:\n\t\t\tshutil.copyfile(self.source, self.destination)\n\n\tdef exists(self):\n\t\tif self.directory:\n\t\t\treturn os.path.isdir(self.source)\n\t\telse:\n\t\t\treturn os.path.isfile(self.source)\n\n\n# Create copy objects with source and destination paths\ndist = CopyPath(os.path.join('src', 'dist', build_name), 'dist', True)\nicon = CopyPath(os.path.join('icons', 'icon.png'), os.path.join('dist', 'icon.png'))\npresets = CopyPath('presets', 'presets', True)\nuser_config = CopyPath('config.ini', 'config.ini')\nplugin_config = CopyPath('Prismatik-iRacing-source.ini', build_name + '.ini')\n\n# Check existence of all required files\nfor item in CopyPath.paths:\n\tprint(\"Checking existence of\", item.source)\n\tif not item.exists():\n\t\traise UserWarning(\"Error! Path {} is missing\".format(item.source))\n\n# Create temporary directory\nif not os.path.isdir(temp_root):\n\tprint(\"Creating temporary folder...\")\n\tos.mkdir(temp_root)\n\tos.mkdir(temp_dir)\nelse:\n\traise UserWarning(\"Error! Temporary folder already exists! Remove it before continuing\")\n\n# Just a little hype :)\nprint(\" ----- All systems go. LET'S DO IT!\")\n\n# Copy build\ndist.copy()\nprint(\"Copied application files...\")\n\n# Copy configurations\nuser_config.copy()\nprint(\"Copied cfg.ini...\")\npresets.copy()\nprint(\"Copied presets folder...\")\nos.remove(os.path.join(presets.destination, \"README.md\"))\nprint(\"Removed preset markdown file...\")\n\n# Modify and write new plugin configuration\nf = open(plugin_config.source, 'r')\nline_list = f.readlines()\nf.close()\n\nversion_num = \"\"\nwith open(plugin_config.destination, 'w') as f_new:\n\tfor line_num, line in enumerate(line_list):\n\t\tif line == \"[Main]\\n\":\n\t\t\tline_list[line_num + 1] = \"Name=iRacing Integration\" + '\\n'\n\t\t\tline_list[line_num + 2] = \"Execute=dist/\" + build_name + \".exe\" + '\\n'\n\t\t\tline_list[line_num + 3] = \"Icon=dist/icon.png\" + '\\n'\n\t\tif \"Version=\" in line:\n\t\t\tversion_num = line.split('=', 1)[1].rstrip() # Pull out version number for zip title\n\t\tf_new.write(line)\nf_new.close()\nprint(\"Copied and modified \" + build_name + \".ini\")\n\n# Copy icon image\nicon.copy()\nprint(\"Copied plugin icon...\")\n\n\n# Zip files for distribution\ndef zip(src, dst, name):\n\tzip_path = os.path.abspath(os.path.join(dst, name + \".zip\"))\n\tzf = zipfile.ZipFile(zip_path, \"w\", zipfile.ZIP_DEFLATED)\n\tabs_src = os.path.abspath(src)\n\tfor dirname, subdirs, files in os.walk(abs_src):\n\t\tfor filename in files:\n\t\t\tabsname = os.path.abspath(os.path.join(dirname, filename))\n\t\t\tarcname = absname[len(abs_src) + 1:]\n\t\t\tprint('Zipping %s as %s' % (os.path.join(dirname, filename),\n\t\t\t\t\t\t\t\t\t\tarcname))\n\t\t\tzf.write(absname, arcname)\n\tzf.close()\n\n\nzip_name = build_name + '-' + version_num + '-' + \"Plugin\"\nzip(temp_root, current_dir, zip_name)\n\n# Clean up\nprint(\"Removing temporary files...\")\nshutil.rmtree(temp_root)\n\n# Success!\nprint(\" -----\")\nprint(\"Release successfully created!\")\n","repo_name":"dmadison/Prismatik-iRacing","sub_path":"src/build/release_assembler.py","file_name":"release_assembler.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"55"} +{"seq_id":"26826206637","text":"from itertools import permutations as per\ndef calc(l,r):\n res=0\n for i in range(l,r+1):\n res=10*res+int(p[i])\n return res\n \nn=int(input())\ncnt=0\nfor p in per(\"123456789\"):\n a,b,c=0,0,0\n for i in range(7):\n for j in range(i+1,8):\n a,b,c=calc(0,i),calc(i+1,j),calc(j+1,8)\n if a*c+b==n*c: cnt+=1\nprint(cnt)\n\n \n","repo_name":"Eureka-JTX/Blue","sub_path":"AcWing/1209. 带分数.py","file_name":"1209. 带分数.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"6617183448","text":"def mastermind(g1, g2, g3, c1, c2, c3):\n soma = 0\n if g1==c1:\n soma +=3\n elif g1==c2 or g1==c3:\n soma +=1\n if g2==c2:\n soma +=3\n elif g2==c1 or g2==c3:\n soma +=1\n if g3==c3:\n soma +=3\n elif g3==c1 or g3==c2:\n soma +=1\n return soma\nprint(mastermind('b', 'w', 'y', 'b', 'b', 'b'))","repo_name":"NunationFL/FPRO","sub_path":"mastermind.py","file_name":"mastermind.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"31580878536","text":"import numpy as np\n\ndef compute_velocity_interaction(path, neigh_path, obs_len=9, stride=3):\n ## Computes the angle between velocity of neighbours and velocity of pp\n\n prim_vel = path[obs_len:] - path[obs_len-stride:-stride]\n theta1 = np.arctan2(prim_vel[:, 1], prim_vel[:, 0])\n neigh_vel = neigh_path[obs_len:] - neigh_path[obs_len-stride:-stride]\n vel_interaction = np.zeros(neigh_vel.shape[0:2])\n sign_interaction = np.zeros(neigh_vel.shape[0:2])\n\n for n in range(neigh_vel.shape[1]):\n theta2 = np.arctan2(neigh_vel[:, n, 1], neigh_vel[:, n, 0])\n theta_diff = (theta2 - theta1) * 180 / np.pi\n theta_diff = theta_diff % 360\n theta_sign = theta_diff > 180\n sign_interaction[:, n] = theta_sign\n vel_interaction[:, n] = theta_diff\n return vel_interaction, sign_interaction\n\n\ndef compute_theta_interaction(path, neigh_path, obs_len=9, stride=3):\n ## Computes the angle between line joining pp to neighbours and velocity of pp\n\n prim_vel = path[obs_len:] - path[obs_len-stride:-stride]\n theta1 = np.arctan2(prim_vel[:, 1], prim_vel[:, 0])\n rel_dist = neigh_path[obs_len:] - path[obs_len:][:, np.newaxis, :]\n theta_interaction = np.zeros(rel_dist.shape[0:2])\n sign_interaction = np.zeros(rel_dist.shape[0:2])\n\n for n in range(rel_dist.shape[1]):\n theta2 = np.arctan2(rel_dist[:, n, 1], rel_dist[:, n, 0])\n theta_diff = (theta2 - theta1) * 180 / np.pi\n theta_diff = theta_diff % 360\n theta_sign = theta_diff > 180\n sign_interaction[:, n] = theta_sign\n theta_interaction[:, n] = theta_diff\n return theta_interaction, sign_interaction\n\ndef compute_dist_rel(path, neigh_path, obs_len=9):\n ## Distance between pp and neighbour\n\n dist_rel = np.linalg.norm((neigh_path[obs_len:] - path[obs_len:][:, np.newaxis, :]), axis=2)\n return dist_rel\n\n\ndef compute_interaction(theta_rel_orig, dist_rel, angle, dist_thresh, angle_range):\n ## Interaction is defined as\n ## 1. distance < threshold and\n ## 2. angle between velocity of pp and line joining pp to neighbours\n\n theta_rel = np.copy(theta_rel_orig)\n angle_low = (angle - angle_range)\n angle_high = (angle + angle_range)\n if (angle - angle_range) < 0:\n theta_rel[np.where(theta_rel > 180)] = theta_rel[np.where(theta_rel > 180)] - 360\n if (angle + angle_range) > 360:\n raise ValueError\n interaction_matrix = (angle_low < theta_rel) & (theta_rel <= angle_high) \\\n & (dist_rel < dist_thresh) & (theta_rel < 500) == 1\n return interaction_matrix\n\n\ndef get_interaction_matrix(rows, args, output='all'):\n ## Computes the angle between velocity of pp at t_obs and velocity of pp at t_pred\n\n path = rows[:, 0]\n neigh_path = rows[:, 1:]\n theta_interaction, sign_interaction = compute_theta_interaction(path, neigh_path)\n vel_interaction, sign_vel_interaction = compute_velocity_interaction(path, neigh_path)\n dist_rel = compute_dist_rel(path, neigh_path)\n\n ## str choice\n if args.choice == 'pos':\n interaction_matrix = compute_interaction(theta_interaction, dist_rel, \\\n args.pos_angle, args.dist_thresh, args.pos_range)\n chosen_interaction = theta_interaction\n\n elif args.choice == 'vel':\n interaction_matrix = compute_interaction(vel_interaction, dist_rel, \\\n args.vel_angle, args.dist_thresh, args.vel_range)\n chosen_interaction = vel_interaction\n sign_interaction = sign_vel_interaction\n\n elif args.choice == 'bothpos':\n pos_matrix = compute_interaction(theta_interaction, dist_rel, \\\n args.pos_angle, args.dist_thresh, args.pos_range)\n vel_matrix = compute_interaction(vel_interaction, dist_rel, \\\n args.vel_angle, args.dist_thresh, args.vel_range)\n interaction_matrix = pos_matrix & vel_matrix\n chosen_interaction = theta_interaction\n\n elif args.choice == 'bothvel':\n pos_matrix = compute_interaction(theta_interaction, dist_rel, \\\n args.pos_angle, args.dist_thresh, args.pos_range)\n vel_matrix = compute_interaction(vel_interaction, dist_rel, \\\n args.vel_angle, args.dist_thresh, args.vel_range)\n interaction_matrix = pos_matrix & vel_matrix\n chosen_interaction = vel_interaction\n sign_interaction = sign_vel_interaction\n else:\n raise NotImplementedError\n\n chosen_true = chosen_interaction[interaction_matrix]\n sign_true = sign_interaction[interaction_matrix]\n dist_true = dist_rel[interaction_matrix]\n\n ## output choice\n if output == 'matrix':\n return interaction_matrix\n if output == 'all':\n return interaction_matrix, chosen_true, sign_true, dist_true\n raise NotImplementedError\n\ndef check_group(rows, args, dist_thresh=0.8, std_thresh=0.2):\n ## Identify Groups\n ## dist_thresh: Distance threshold to be withinin a group\n ## std_thresh: Std deviation threshold for variation of distance\n\n path = rows[:, 0]\n neigh_path = rows[:, 1:]\n\n ## Horizontal Position\n args.pos_angle = 90\n interaction_matrix_1 = get_interaction_matrix(rows, args, output='matrix')\n args.pos_angle = 270\n interaction_matrix_2 = get_interaction_matrix(rows, args, output='matrix')\n neighs_side = np.any(interaction_matrix_1, axis=0) | np.any(interaction_matrix_2, axis=0)\n\n ## Distance Maintain\n dist_rel = np.linalg.norm((neigh_path - path[:, np.newaxis, :]), axis=2)\n mean_dist = np.mean(dist_rel, axis=0)\n std_dist = np.std(dist_rel, axis=0)\n\n group_matrix = (mean_dist < dist_thresh) & (std_dist < std_thresh) & neighs_side\n\n return group_matrix\n","repo_name":"Saleh-Gholam-Zadeh/Navigation","sub_path":"whole_model/trajnet/trajnettools/trajnettools/interactions.py","file_name":"interactions.py","file_ext":"py","file_size_in_byte":5851,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"55"} +{"seq_id":"38593875191","text":"from django.db.models import Q\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework import filters\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework_extensions.mixins import NestedViewSetMixin\nfrom rest_fuzzysearch.search import RankedFuzzySearchFilter\n\nfrom boundlexx.api.common.filters import (\n ColorFilterSet,\n DedupedFilter,\n WorldBlockColorFilterSet,\n)\nfrom boundlexx.api.common.viewsets import BoundlexxReadOnlyViewSet\nfrom boundlexx.api.schemas import DescriptiveAutoSchema\nfrom boundlexx.api.utils import get_base_url, get_list_example\nfrom boundlexx.api.v1.serializers import (\n PossibleItemSerializer,\n URLBlockColorSerializer,\n URLColorSerializer,\n)\nfrom boundlexx.boundless.models import Color, WorldBlockColor\n\nCOLOR_EXAMPLE = {\n \"url\": f\"{get_base_url()}/api/v1/colors/1/\",\n \"blocks_url\": f\"{get_base_url()}/api/v1/colors/1/blocks/\",\n \"game_id\": 1,\n \"base_color\": \"#1b1b1b\",\n \"gleam_color\": \"#1b1b1b\",\n \"localization\": [\n {\"lang\": \"english\", \"name\": \"Black\"},\n {\"lang\": \"french\", \"name\": \"Noir\"},\n {\"lang\": \"german\", \"name\": \"Schwarz\"},\n {\"lang\": \"italian\", \"name\": \"Nero\"},\n {\"lang\": \"spanish\", \"name\": \"Negro\"},\n ],\n}\n\nCOLOR_BLOCKS_EXAMPLE = {\n \"item\": {\n \"url\": f\"{get_base_url()}/api/v1/items/13/?format=json\",\n \"game_id\": 13,\n \"string_id\": \"ITEM_TYPE_GRASS_VERDANT_BASE\",\n },\n \"world\": {\"url\": None, \"id\": 2000000075, \"display_name\": \"Spination\"},\n \"is_new_color\": True,\n \"exist_on_perm\": True,\n \"exist_via_transform\": None,\n}\n\n\nclass ColorViewSet(BoundlexxReadOnlyViewSet):\n queryset = Color.objects.filter(active=True).prefetch_related(\n \"localizedname_set\", \"colorvalue_set\"\n )\n serializer_class = URLColorSerializer\n lookup_field = \"game_id\"\n filter_backends = [\n DjangoFilterBackend,\n RankedFuzzySearchFilter,\n filters.OrderingFilter,\n DedupedFilter,\n ]\n filterset_class = ColorFilterSet\n search_fields = [\"localizedname__name\", \"game_id\"]\n ordering = [\"-rank\", \"game_id\"]\n ordering_fields: list[str] = []\n\n def list(self, request, *args, **kwargs): # noqa A003\n \"\"\"\n Retrieves the list of colors avaiable in Boundless\n \"\"\"\n\n return super().list(request, *args, **kwargs) # pylint: disable=no-member\n\n list.example = {\"list\": {\"value\": get_list_example(COLOR_EXAMPLE)}} # type: ignore # noqa E501\n\n def retrieve(\n self,\n request,\n *args,\n **kwargs,\n ): # pylint: disable=arguments-differ\n \"\"\"\n Retrieves a color with a given ID\n \"\"\"\n return super().retrieve(request, *args, **kwargs) # pylint: disable=no-member\n\n retrieve.example = {\"retrieve\": {\"value\": COLOR_EXAMPLE}} # type: ignore # noqa E501\n\n @action(\n detail=True,\n methods=[\"get\"],\n serializer_class=PossibleItemSerializer,\n url_path=\"sovereign-blocks\",\n )\n def sovereign_blocks(\n self,\n request,\n game_id=None,\n ):\n \"\"\"\n Gets current Possible Sovereign Blocks choices for given color\n \"\"\"\n\n color = self.get_object()\n\n queryset = (\n WorldBlockColor.objects.filter(color=color, is_default=True)\n .filter(\n Q(world__isnull=True)\n | Q(world__end__isnull=True, world__is_creative=False)\n | Q(world__owner__isnull=False, world__is_creative=False)\n )\n .select_related(\"item\")\n .order_by(\"item__game_id\")\n .distinct(\"item__game_id\")\n )\n\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(queryset, many=True)\n\n return Response(serializer.data)\n\n sovereign_blocks.operation_id = \"listColorSovereignBlocks\" # noqa E501\n\n\nclass BlockColorViewSet(\n NestedViewSetMixin,\n BoundlexxReadOnlyViewSet,\n):\n schema = DescriptiveAutoSchema()\n queryset = (\n WorldBlockColor.objects.filter(world__is_creative=False)\n .select_related(\n \"item\",\n \"world\",\n \"item__item_subtitle\",\n )\n .prefetch_related(\n \"item__localizedname_set\",\n \"item__item_subtitle__localizedname_set\",\n )\n )\n\n serializer_class = URLBlockColorSerializer\n lookup_field = \"item__game_id\"\n filter_backends = [\n DjangoFilterBackend,\n RankedFuzzySearchFilter,\n filters.OrderingFilter,\n DedupedFilter,\n ]\n filterset_class = WorldBlockColorFilterSet\n search_fields = [\n \"item__string_id\",\n \"item__item_subtitle__localizedname__name\",\n \"item__localizedname__name\",\n \"world__name\",\n \"world__display_name\",\n ]\n ordering = [\"-rank\", \"item__game_id\", \"color__game_id\"]\n ordering_fields: list[str] = []\n\n def get_queryset(self):\n queryset = super().get_queryset()\n\n if not self.request.user.has_perm(\"boundless.can_view_private\"):\n queryset = queryset.filter(world__is_public=True)\n\n return queryset\n\n def list(self, request, *args, **kwargs): # noqa A003\n \"\"\"\n Retrieves the list of the items for a given color\n \"\"\"\n\n return super().list(request, *args, **kwargs) # pylint: disable=no-member\n\n list.example = {\"list\": {\"value\": get_list_example(COLOR_BLOCKS_EXAMPLE)}} # type: ignore # noqa E501\n list.operation_id = \"listColorBlocks\" # type: ignore # noqa E501\n\n def retrieve(\n self,\n request,\n *args,\n **kwargs,\n ): # pylint: disable=arguments-differ\n \"\"\"\n Retrieves the counts worlds for a given color/item combination\n \"\"\"\n return super().list(request, *args, **kwargs) # pylint: disable=no-member\n\n retrieve.example = {\"list\": {\"value\": get_list_example(COLOR_BLOCKS_EXAMPLE)}} # type: ignore # noqa E501\n retrieve.operation_id = \"retrieveColorBlock\" # type: ignore # noqa E501\n","repo_name":"AngellusMortis/boundlexx","sub_path":"boundlexx/api/v1/views/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":6237,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"55"} +{"seq_id":"4088032064","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom random import randint\n\ndict = {\n 1: 'Бесспорно',\n 2: 'Предрешено',\n 3: 'Никаких сомнений',\n 4: 'Определённо да',\n 5: 'Можешь быть уверен в этом',\n 6: 'Мне кажется — «да»',\n 7: 'Вероятнее всего',\n 8: 'Хорошие перспективы',\n 9: 'Знаки говорят — «да»',\n 10: 'Да',\n 11: 'Пока не ясно, попробуй снова',\n 12: 'Спроси позже',\n 13: 'Лучше не рассказывать',\n 14: 'Сейчас нельзя предсказать',\n 15: 'Сконцентрируйся и спроси опять',\n 16: 'Даже не думай',\n 17: 'Мой ответ — «нет»',\n 18: 'По моим данным — «нет»',\n 19: 'Перспективы не очень хорошие',\n 20: 'Весьма сомнительно'\n}\ndef select():\n key = randint(1, 20)\n result.set(dict[key])\n messagebox.showinfo(\"Ответ\", result.get())\n\nroot = Tk()\nroot.title(\"Магический шар\")\nroot.geometry(\"350x350\")\n\nresult = StringVar()\n\nheader = Label(text = \"Привет, я программа \\\"Магический шар\\\" \"\n \"\\nЗадай вопрос, нажми на кнопку \\\"Ответ\\\"\", padx=15, pady=15)\nheader.pack(side = TOP)\n\nbtn = Button(text = \"Ответ\", background=\"green\", foreground=\"black\", font=\"Verdana 13\",\n padx=5, pady=5, command=select)\nbtn.place(relx=.3, rely=.3, relheight=.3, relwidth=.3)\n\nroot.mainloop()","repo_name":"ramilabd/tasks_python","sub_path":"My_programs/magic_ball_grafic.py","file_name":"magic_ball_grafic.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"1093674644","text":"from __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport logging\nimport h5py\nimport numpy as np\nimport dxchange\nimport re\nimport os\nimport glob\n\n\nlogger = logging.getLogger(__name__)\n\n__author__ = [\"Rafael Vescovi\", \"Ming Du\"]\n__credits__ = \"Doga Gursoy\"\n__copyright__ = \"Copyright (c) 2015, UChicago Argonne, LLC.\"\n__docformat__ = 'restructuredtext en'\n__all__ = ['allocate_mpi_subsets',\n 'read_aps_32id_adaptive']\n\n\ndef allocate_mpi_subsets_cont_chunk(n_task, size, task_list=None):\n\n # TODO: chunk from beginning, not across the entire set\n if task_list is None:\n task_list = range(n_task)\n sets = []\n per_rank_floor = int(np.floor(n_task/size))\n remainder = n_task % size\n start = 0\n for i in range(size):\n length = per_rank_floor\n if remainder > 0:\n length += 1\n remainder -= 1\n sets.append(task_list[start:start+length])\n start = start + length\n return sets\n\n\ndef allocate_mpi_subsets(n_task, size, task_list=None):\n\n if task_list is None:\n task_list = range(n_task)\n sets = []\n for i in range(size):\n selection = range(i, n_task, size)\n sets.append(np.take(task_list, selection).tolist())\n return sets\n\n\ndef which_tile(shift_grid, file_grid, x_coord, y_coord):\n\n f = h5py.File(file_grid[0, 0])\n y_cam, x_cam = f['exchange/data'].shape[1:3]\n y_prev = 'none'\n x_prev = 'none'\n y = np.searchsorted(shift_grid[:, 0], y_coord) - 1\n if y != 0:\n if y < shift_grid[y-1, 0] + y_cam:\n y_prev = y - 1\n else:\n y_prev = y\n x = np.searchsorted(shift_grid[0, :], x_coord) - 1\n if x != 0:\n if x < shift_grid[0, x-1] + x_cam:\n x_prev = x - 1\n else:\n x_prev = x\n s = file_grid[y, x]\n if x_prev != x or y_prev != y:\n s = s + ' overlapped with ' + file_grid[y_prev, x_prev]\n return s\n\n\ndef entropy(img, range=(-0.002, 0.002)):\n\n hist, e = np.histogram(img, bins=1024, range=range)\n hist = hist.astype('float32') / img.size + 1e-12\n val = -np.dot(hist, np.log2(hist))\n return val\n\n\ndef minimum_entropy(folder, pattern='*.tiff', range=(-0.002, 0.002)):\n\n flist = glob.glob(os.path.join(folder, pattern))\n a = []\n s = []\n for fname in flist:\n img = dxchange.read_tiff(fname)\n s.append(entropy(img, range=range))\n a.append(fname)\n return a[np.argmin(s)]\n\n\ndef read_aps_32id_adaptive(fname, proj=None, sino=None):\n \"\"\"\n Adaptive data reading function that works with dxchange both below and beyond version 0.0.11.\n \"\"\"\n dxver = dxchange.__version__\n m = re.search(r'(\\d+)\\.(\\d+)\\.(\\d+)', dxver)\n ver = m.group(1, 2, 3)\n ver = map(int, ver)\n if ver[0] > 0 or ver[1] > 1 or ver[2] > 1:\n dat, flt, drk, _ = dxchange.read_aps_32id(fname, proj=proj, sino=sino)\n else:\n dat, flt, drk = dxchange.read_aps_32id(fname, proj=proj, sino=sino)\n\n return dat, flt, drk","repo_name":"ravescovi/tomosaic_old","sub_path":"tomosaic/misc/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"33887800889","text":"import unittest\nfrom unittest import mock\n\nfrom cluster import *\n\nfrom . import fake_network\n\nclass FakeRequest(object):\n def __init__(self, node, input_value, callback):\n self.node = node\n self.input_value = input_value\n self.callback = callback\n\n def start(self):\n self.callback(('ROTATED', self.node, self.input_value))\n\nclass TestMember(unittest.TestCase):\n def setUp(self):\n self.Node = mock.Mock(spec_set=Node)\n self.Bootstrap = mock.Mock(spec_set=Bootstrap)\n self.Seed = mock.Mock(spec_set=Seed)\n self.network = fake_network.FakeNetwork()\n self.state_machine = mock.Mock(name='state_machine')\n self.cls_args = {'bootstrap_cls': self.Bootstrap, 'seed_cls': self.Seed}\n\n def test_no_seed(self):\n sh = Member(self.state_machine, network=self.network, peers=['p1', 'p2'], **self.cls_args)\n self.assertFalse(self.Seed.called)\n self.Bootstrap.assert_called_with(self.network.node, execute_fn=self.state_machine, peers=['p1', 'p2'])\n\n def test_seed(self):\n sh = Member(self.state_machine, network=self.network, peers=['p1', 'p2'], seed=44, **self.cls_args)\n self.assertFalse(self.Bootstrap.called)\n self.Seed.assert_called_with(self.network.node, initial_state=44, peers=['p1', 'p2'], execute_fn=self.state_machine)\n\n def test_start(self):\n sh = Member(self.state_machine, network=self.network, peers=['p1', 'p2'], **self.cls_args)\n sh.start()\n sh.thread.join()\n sh.startup_role.start.assert_called_once_with()\n self.assertTrue(self.network.ran)\n\n def test_invoke(self):\n sh = Member(self.state_machine, network=self.network, peers=['p1', 'p2'], **self.cls_args)\n res = sh.invoke('ROTATE', request_cls=FakeRequest)\n self.assertEqual(sh.requester, None)\n self.assertEqual(res, ('ROTATED', sh.node, 'ROTATE'))\n","repo_name":"liuq901/500-lines","sub_path":"cluster/test/test_member.py","file_name":"test_member.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"36163129447","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.views.generic import ListView, DetailView, TemplateView, View\nfrom django.urls import reverse_lazy\nfrom django.http import JsonResponse\nfrom django.contrib.auth.views import LoginView \nfrom django.contrib.auth.forms import AuthenticationForm, UserCreationForm\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.template.loader import render_to_string\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom django.utils.encoding import force_bytes\nfrom django.core.mail import EmailMessage \nfrom django.contrib import messages\nfrom django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin, AccessMixin\nfrom django.contrib.auth.models import Group\nfrom django.utils.translation import gettext as _\nfrom django.utils.translation import gettext_lazy\n\nfrom .token import token_activacion\nfrom .models import Usuario, Municipio, Estado\nfrom .forms import UsuarioForm, UsuarioRegistroForm\n\nclass NuevoUsuario(PermissionRequiredMixin,CreateView):\n model = Usuario\n form_class = UsuarioForm\n permission_required = 'usuarios.add_usuario'\n extra_context = {'etiqueta' : gettext_lazy('Nuevo'),\n 'boton' : gettext_lazy('Agregar'),\n 'us_nuevo' : True} \n success_url = reverse_lazy('usuarios:lista')\n\n def form_valid(self, form):\n user = form.save(commit=False)\n user.is_active = False\n user.save()\n # Toma el dominio actual. Es muy util para produccion\n dominio = get_current_site(self.request)\n uid = urlsafe_base64_encode(force_bytes(user.id))\n token = token_activacion.make_token(user)\n # Le mandamos las variables requeridas en el formulario\n mensaje = render_to_string('confirmar_cuenta.html',\n {\n 'usuario' : user,\n 'dominio' : dominio,\n 'uid' : uid,\n 'token' : token\n }\n )\n asunto = _('Activar cuenta en el Sistema de Videojuegos')\n to = user.email\n # En el to se puede poner una lista de usuarios\n email = EmailMessage(\n asunto,\n mensaje,\n to=[to]\n )\n email.content_subtype = 'html'\n email.send()\n\n return super().form_valid(form)\n\nclass ActivarCuenta(TemplateView):\n def get(self, request, *args, **kwargs):\n try:\n uid = urlsafe_base64_decode(kwargs['uid64'])\n token = kwargs['token']\n user = Usuario.objects.get(id=uid)\n except:\n user = None\n\n if user and token_activacion.check_token(user,token):\n user.is_active = True\n user.save()\n messages.success(self.request,_('¡Cuenta activada con éxito!'))\n else:\n messages.error(self.request,_('Token inválido, contacta al administrador'))\n \n return redirect('usuarios:login')\n\n\ndef obtiene_municipios(request):\n # estado = get_object_or_404(Estado, id=id_estado)\n if request.method == 'GET':\n return JsonResponse({'error':_('Petición incorrecta')}, safe=False, status=403)\n id_estado = request.POST.get('id')\n municipios = Municipio.objects.filter(estado_id=id_estado)\n json = []\n if not municipios:\n json.append({'error' : _('No se encontraron municipios con ese estado')})\n for municipio in municipios:\n json.append({'id' : municipio.id,\n 'nombre' : municipio.nombre})\n return JsonResponse(json, safe=False)\n\nclass UsuarioList(PermissionRequiredMixin,ListView):\n paginate_by = 5\n model = Usuario\n permission_required = 'usuarios.view_usuario'\n lista_grupos = Group.objects.all()\n\n extra_context = {'us_lista' : True,\n 'lista_grupos': lista_grupos} \n template_name = 'usuarios:lista'\n\nclass UsuarioActualizar(PermissionRequiredMixin,UpdateView):\n model = Usuario\n permission_required = 'usuarios.change_usuario'\n form_class = UsuarioForm\n extra_context = {'etiqueta' : gettext_lazy('Editar'),\n 'boton' : gettext_lazy('Guardar')}\n success_url = reverse_lazy('usuarios:lista')\n\nclass UsuarioEliminar(PermissionRequiredMixin,DeleteView):\n model = Usuario\n permission_required = 'usuarios.delete_usuario'\n success_url = reverse_lazy('usuarios:lista')\n\nclass UsuarioDetalle(PermissionRequiredMixin,DetailView):\n model = Usuario\n permission_required = 'usuarios.view_usuario'\n\nclass LoginUsuario(LoginView):\n template_name = 'login.html'\n form_class = AuthenticationForm\n \n def get_success_url(self):\n self.request.session['articulos'] = {}\n self.request.session['total'] = 0.0\n return super().get_success_url()\n\nclass SignUpUsuario(CreateView):\n template_name = 'signup.html'\n form_class = UsuarioForm\n success_url = reverse_lazy('usuarios:login')\n\n def form_valid(self, form):\n user = form.save(commit=False)\n user.is_active = False\n user.save()\n # Toma el dominio actual. Es muy util para produccion\n dominio = get_current_site(self.request)\n uid = urlsafe_base64_encode(force_bytes(user.id))\n token = token_activacion.make_token(user)\n # Le mandamos las variables requeridas en el formulario\n mensaje = render_to_string('confirmar_cuenta.html',\n {\n 'usuario' : user,\n 'dominio' : dominio,\n 'uid' : uid,\n 'token' : token\n }\n )\n asunto = _('Activar cuenta en el Sistema de Videojuegos')\n to = user.email\n # En el to se puede poner una lista de usuarios\n email = EmailMessage(\n asunto,\n mensaje,\n to=[to]\n )\n email.content_subtype = 'html'\n email.send()\n\n return super().form_valid(form)\n\ndef logout(request):\n auth.logout(request)\n return redirect('usuarios:login')\n\ndef modificar_usuario_grupo(request,id):\n grupos = [grupo.id for grupo in Group.objects.all()]\n usuario = Usuario.objects.get(id=id)\n\n # El usuario tiene por lo menos un grupo asignado dado que en el arreglo\n # viene el token y algún grupo a asignar.\n if len(request.POST) > 1: \n usuario.groups.clear()\n for item in request.POST:\n if request.POST[item] == 'on':\n usuario.groups.add(Group.objects.get(id=int(item)))\n \n messages.success(request, gettext_lazy(f'Se agregó al usuario {usuario} a los usuarios'))\n # El usuario no tiene ningún grupo asignado\n else:\n messages.error(request, gettext_lazy('El usuario debe pertenecer a un grupo como mínimo'))\n \n return redirect('usuarios:lista')","repo_name":"juanca1499/is-frameworks-videojuegos","sub_path":"usuarios/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6846,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"24480047751","text":"class Auto:\n def __init__(self, rekisteri, huippunopeus, nopeus=0, matka=0):\n self.rekisteri = rekisteri\n self.huippunopeus = int(huippunopeus)\n self.nopeus = nopeus\n self.matka = matka\n return\n\n def kiihdyta(self, nopeuden_muutos):\n self.nopeus += nopeuden_muutos\n if self.nopeus < 0:\n self.nopeus = 0\n elif self.nopeus > self.huippunopeus:\n self.nopeus = self.huippunopeus\n return\n\n def kulje(self, tuntimaara):\n self.matka += self.nopeus * tuntimaara\n return\n\n\nabc_bil = Auto(\"ABC-123\", \"142\")\nprint(f\"Auton rekisterinumero: {abc_bil.rekisteri}\")\nprint(f\"Auton huippunopeus: {abc_bil.huippunopeus}\")\nabc_bil.kiihdyta(30)\nabc_bil.kiihdyta(70)\nabc_bil.kiihdyta(50)\nabc_bil.kiihdyta(-200)\n\nabc_bil.kulje(1.5)\nprint(f\"Auton nopeus nyt: {abc_bil.nopeus}km/h\")\nprint(f\"Auto on kulkenut matkan: {abc_bil.matka}km\")\n","repo_name":"SamuKauppi/Python-Koodit","sub_path":"9_Luokka_olio_alustaja/teht_3.py","file_name":"teht_3.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"1836956674","text":"# -*- coding: utf-8 -*-\nimport ast\nimport io\nimport re\n\nfrom setuptools import setup, find_packages\n\nwith io.open('README.md', 'rt', encoding=\"utf8\") as f:\n readme = f.read()\n\n_description_re = re.compile(r'description\\s+=\\s+(?P.*)')\n\nwith open('lektor_image_resize.py', 'rb') as f:\n description = str(ast.literal_eval(_description_re.search(\n f.read().decode('utf-8')).group(1)))\n\nsetup(\n author='L3D',\n author_email='l3d@c3woc.de',\n description=description,\n keywords='Lektor plugin generate webp jpg thumbnails images',\n license='MIT',\n long_description=readme,\n long_description_content_type='text/markdown',\n name='lektor-image-resize',\n packages=find_packages(),\n py_modules=['lektor_image_resize'],\n url='https://github.com/chaos-bodensee/lektor-image-resize.git',\n version='1.0.0',\n install_requires=[],\n classifiers=[\n 'Framework :: Lektor',\n 'Environment :: Plugins',\n ],\n entry_points={\n 'lektor.plugins': [\n 'image-resize = lektor_image_resize:ImageResizePlugin',\n ]\n }\n)\n","repo_name":"chaos-bodensee/lektor-image-resize","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"55"} +{"seq_id":"5780773685","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 4 21:56:48 2023\r\n\r\n@author: yutah\r\n\"\"\"\r\nimport os, sys\r\nimport numpy as np\r\nfrom codes.auxilary import load_X, load_y, preprocess_data\r\nfrom codes.constructOutpath import constructCCPpath\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.metrics import adjusted_rand_score, normalized_mutual_info_score, silhouette_score\r\nfrom sklearn.preprocessing import StandardScaler\r\ndef makeFolder(outpath):\r\n try:\r\n os.makedirs(outpath)\r\n except:\r\n return\r\n return\r\n\r\ndef KM_raw(X_ccp, y, outfile):\r\n ari = np.zeros(30)\r\n nmi = np.zeros(30)\r\n sil = np.zeros(30)\r\n labels = np.zeros([30, X_ccp.shape[0]])\r\n for idx in range(30):\r\n myKM = KMeans(n_clusters = np.unique(y).shape[0], random_state = idx)\r\n myKM.fit(X_ccp)\r\n l = myKM.labels_\r\n ari[idx] = adjusted_rand_score(y, l)\r\n nmi[idx] = normalized_mutual_info_score(y, l)\r\n sil[idx] = silhouette_score(X_ccp, l)\r\n labels[idx, :] = l\r\n np.save(outfile + '_raw_labels.npy', labels)\r\n np.save(outfile + '_raw_ari.npy', ari)\r\n np.save(outfile + '_raw_nmi.npy', nmi)\r\n np.save(outfile + '_raw_sil.npy', sil)\r\n print('raw', np.mean(ari))\r\n \r\n \r\ndef KM_standard(X_ccp, y, outfile):\r\n X_ccp_scaled = StandardScaler().fit_transform(X_ccp)\r\n ari = np.zeros(30)\r\n nmi = np.zeros(30)\r\n sil = np.zeros(30)\r\n labels = np.zeros([30, X_ccp.shape[0]])\r\n for idx in range(30):\r\n myKM = KMeans(n_clusters = np.unique(y).shape[0], random_state = idx)\r\n myKM.fit(X_ccp_scaled)\r\n l = myKM.labels_\r\n ari[idx] = adjusted_rand_score(y, l)\r\n nmi[idx] = normalized_mutual_info_score(y, l)\r\n sil[idx] = silhouette_score(X_ccp_scaled, l)\r\n labels[idx, :] = l\r\n np.save(outfile + '_std_labels.npy', labels)\r\n np.save(outfile + '_std_ari.npy', ari)\r\n np.save(outfile + '_std_nmi.npy', nmi)\r\n np.save(outfile + '_std_sil.npy', sil)\r\n print('std', np.mean(ari))\r\n \r\ndef KM_sum(X_ccp, y, outfile):\r\n X_ccp_scaled = X_ccp / (np.sum(X_ccp, axis = 1)[:, None])\r\n ari = np.zeros(30)\r\n nmi = np.zeros(30)\r\n sil = np.zeros(30)\r\n labels = np.zeros([30, X_ccp.shape[0]])\r\n for idx in range(30):\r\n myKM = KMeans(n_clusters = np.unique(y).shape[0], random_state = idx)\r\n myKM.fit(X_ccp_scaled)\r\n l = myKM.labels_\r\n ari[idx] = adjusted_rand_score(y, l)\r\n nmi[idx] = normalized_mutual_info_score(y, l)\r\n sil[idx] = silhouette_score(X_ccp_scaled, l)\r\n labels[idx, :] = l\r\n np.save(outfile + '_sum_labels.npy', labels)\r\n np.save(outfile + '_sum_ari.npy', ari)\r\n np.save(outfile + '_sum_nmi.npy', nmi)\r\n np.save(outfile + '_sum_sil.npy', sil)\r\n print('sum', np.mean(ari))\r\n\r\ndata = sys.argv[1]\r\nmax_state = 20\r\n#data = 'GSE45719'\r\n#data = 'GSE67835'\r\n#data = 'GSE75748cell'\r\n#data = 'GSE75748time'\r\n#data = 'GSE82187'\r\n#data = 'GSE84133human1'\r\n#data = 'GSE84133human2'\r\n#data = 'GSE84133human3'\r\n#data = 'GSE84133human4'\r\n#data = 'GSE84133mouse1'\r\n#data = 'GSE84133mouse2'\r\n#data = 'GSE89232'\r\n#data = 'GSE94820'\r\n#data = 'GSE59114'\r\nn_components_vec = [25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300]\r\n#max_state = 20\r\nn_components_vec = [int(sys.argv[2])]\r\ny = load_y(data)\r\n\r\n\r\n\r\n\r\n#CCP\r\noutpath_ccp = constructCCPpath(data)\r\noutpath_ccp_results = './rawResults_test/%s_rawResults_test/'%(data); makeFolder(outpath_ccp_results)\r\nfor n_components in n_components_vec:\r\n for state in range(1, max_state + 1):\r\n infile = '%s_ccp_n%d_state%d'%(data, n_components, state)\r\n X_ccp = np.load(outpath_ccp + infile + '.npy')\r\n \r\n outfile = outpath_ccp_results + infile\r\n KM_raw(X_ccp, y, outfile)\r\n KM_standard(X_ccp, y, outfile)\r\n KM_sum(X_ccp, y, outfile)","repo_name":"hozumiyu/CCP-for-Single-Cell-RNA-Sequencing","sub_path":"clustering_test.py","file_name":"clustering_test.py","file_ext":"py","file_size_in_byte":3831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"15695395455","text":"import bisect\nimport hashlib\nfrom typing import Dict, Iterable, Iterator, List, Optional, Tuple\n\n\nclass HashRing:\n nodes: List[str] = []\n\n def __init__(self, nodes: Iterable[str] = (), replicas: int = 128) -> None:\n self.replicas: int = replicas\n self.ring: Dict[str, str] = {}\n self.sorted_keys: List[str] = []\n\n for node in nodes:\n self.add_node(node)\n\n def add_node(self, node: str) -> None:\n self.nodes.append(node)\n\n for x in range(self.replicas):\n _key = f\"{node}:{x}\"\n _hash = hashlib.sha256(_key.encode()).hexdigest()\n\n self.ring[_hash] = node\n self.sorted_keys.append(_hash)\n\n self.sorted_keys.sort()\n\n def remove_node(self, node: str) -> None:\n self.nodes.remove(node)\n for x in range(self.replicas):\n _hash = hashlib.sha256(f\"{node}:{x}\".encode()).hexdigest()\n del self.ring[_hash]\n self.sorted_keys.remove(_hash)\n\n def get_node(self, key: str) -> Optional[str]:\n n, i = self.get_node_pos(key)\n return n\n\n def get_node_pos(self, key: str) -> Tuple[Optional[str], Optional[int]]:\n if len(self.ring) == 0:\n return None, None\n\n _hash = hashlib.sha256(key.encode()).hexdigest()\n idx = bisect.bisect(self.sorted_keys, _hash)\n idx = min(idx - 1, (self.replicas * len(self.nodes)) - 1)\n return self.ring[self.sorted_keys[idx]], idx\n\n def iter_nodes(self, key: str) -> Iterator[Tuple[Optional[str], Optional[str]]]:\n if len(self.ring) == 0:\n yield None, None\n\n node, pos = self.get_node_pos(key)\n for k in self.sorted_keys[pos:]:\n yield k, self.ring[k]\n\n def __call__(self, key: str) -> Optional[str]:\n return self.get_node(key)\n","repo_name":"jazzband/django-redis","sub_path":"django_redis/hash_ring.py","file_name":"hash_ring.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","stars":2715,"dataset":"github-code","pt":"55"} +{"seq_id":"39221261196","text":"# coding=utf-8\n\n__author__ = 'M'\n\nimport math\n\nfrom game_logic.match_builder import MatchBuilder\nfrom game_logic.model.player import Player\n\nif __name__ == '__main__':\n player1 = Player('A',None)\n player2 = Player('B',None)\n\n testMatch = MatchBuilder.get_match([player1, player2])\n print(testMatch)\n for i in xrange(5):\n angle = math.pi / 4\n speed = 200\n flugbahn = testMatch.calc_flugbahn(player1, angle, speed)\n print('letzter Punkt: ' + flugbahn.time_points[len(flugbahn.time_points)-1].__str__())\n print('Schusshöhe: {:.2f}'.format(flugbahn.max_y_point.y))\n for hit in flugbahn.hits:\n print('Treffer: ' + hit.__str__())\n print('')","repo_name":"TankCommander/pythonCode","sub_path":"startGameTest.py","file_name":"startGameTest.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"11382895052","text":"########################################\n# --- Day 7: Amplification Circuit --- #\n########################################\n\nimport AOCUtils\nfrom intcodeVM import VM\nfrom itertools import permutations\n\n########################################\n\nraw_program = AOCUtils.load_input(7)\nmemory = list(map(int, raw_program.split(',')))\n\nthruster_signals = dict()\nfor phase in permutations([0, 1, 2, 3, 4]):\n signal = 0\n for i in range(5):\n vm = VM(memory)\n vm.run([phase[i], signal])\n signal = vm.output[0]\n\n thruster_signals[phase] = signal\n\nAOCUtils.print_answer(1, max(thruster_signals.values()))\n\nthruster_signals = dict()\nfor phase in permutations([5, 6, 7, 8, 9]):\n vms = [VM(memory) for _ in range(5)]\n vm_outputs = [0 for _ in range(5)]\n\n for i in range(5): # Send phase setting, does not expect any output\n vms[i].run(phase[i])\n\n while not any(vm.halted for vm in vms):\n for i in range(5): # Run each of the amps in order\n vms[i].run(vm_outputs[(i-1)%5])\n signal = vms[i].output[-1]\n vm_outputs[i] = signal\n\n thruster_signals[phase] = signal\n\nAOCUtils.print_answer(2, max(thruster_signals.values()))\n\nAOCUtils.print_time_taken()","repo_name":"KanegaeGabriel/advent-of-code","sub_path":"2019/07_amplification_circuit.py","file_name":"07_amplification_circuit.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"11514729327","text":"import unittest\nimport sys\nimport os\nimport shutil\n\np = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, p + \"/../\")\n\nfrom dmai.game.state import State\nfrom dmai.utils.output_builder import OutputBuilder\nfrom dmai.game.game import Game\nfrom dmai.planning.fast_downward_adapter import FastDownwardAdapter\nfrom dmai.utils.config import Config\n\n\nclass TestFastDownwardAdapter(unittest.TestCase):\n \"\"\"Test the FastDownwardAdapter class\"\"\"\n def _prepare_adapter(self, domain: str,\n problem: str) -> FastDownwardAdapter:\n output_builder = OutputBuilder()\n state = State(output_builder)\n state.session.set_session_id(\"test\")\n shutil.copy(\n os.path.join(Config.directory.planning_test,\n \"{d}.pddl\".format(d=domain)),\n os.path.join(Config.directory.planning,\n \"{u}.{d}.domain.pddl\".format(d=domain,\n u=\"test\")))\n shutil.copy(\n os.path.join(Config.directory.planning_test,\n \"{p}.pddl\".format(p=problem)),\n os.path.join(\n Config.directory.planning,\n \"{u}.{p}.problem.pddl\".format(p=problem, u=\"test\")))\n return FastDownwardAdapter(domain, problem, state, output_builder)\n\n def _cleanup(self, domain, problem) -> None:\n os.remove(\n os.path.join(\n Config.directory.planning,\n \"{u}.{d}.domain.pddl\".format(d=domain, u=\"test\")))\n os.remove(\n os.path.join(\n Config.directory.planning,\n \"{u}.{p}.problem.pddl\".format(p=problem, u=\"test\")))\n os.remove(\n os.path.join(\n Config.directory.planning,\n \"{u}.{d}-{p}.plan\".format(d=domain,\n p=problem,\n u=\"test\")))\n\n def test_build_plan_player(self) -> None:\n domain = \"player_domain\"\n problem = \"player_problem_fighter\"\n try:\n adapter = self._prepare_adapter(domain, problem)\n p = adapter.build_plan()\n except Exception:\n self._cleanup(domain, problem)\n self.assertEqual(p, True)\n self._cleanup(domain, problem)\n\n def test_build_plan_monster(self) -> None:\n domain = \"monster_domain\"\n problem = \"monster_problem_inns_cellar\"\n try:\n adapter = self._prepare_adapter(domain, problem)\n m = adapter.build_plan()\n except Exception:\n self._cleanup(domain, problem)\n self.assertEqual(m, True)\n self._cleanup(domain, problem)\n\n\nclass TestPlanningMonster(unittest.TestCase):\n \"\"\"Test the PlanningMonster class\"\"\"\n def setUp(self) -> None:\n self.game = Game(\n char_class=\"fighter\",\n char_name=\"Xena\",\n adventure=\"the_tomb_of_baradin_stormfury\",\n session_id=\"test\"\n )\n self.game.load()\n Config.agent.set_player(\"planning\")\n Config.planner.set_player(\"fd\")\n monster_id = \"giant_rat_1\"\n self.game.state.set_current_room(\"player\", \"inns_cellar\")\n self.game.state.light_torch()\n self.game.state.set_target(monster_id)\n self.monster = self.game.state.get_entity(monster_id)\n self.monster.agent.prepare_next_move()\n \n def tearDown(self) -> None:\n shutil.rmtree(Config.directory.planning)\n \n def test_giant_rat_plan(self) -> None:\n self.assertEqual(\"declare_attack_against_player giant_rat_1 player inns_cellar\", self.monster.agent.get_next_move())\n \n def test_build_domain(self) -> None:\n file_path = os.path.join(\n Config.directory.planning,\n \"{u}.{d}.domain.pddl\".format(u=\"test\", d=self.monster.agent.domain)\n )\n self.assertTrue(os.path.exists(file_path))\n \n def test_build_problem(self) -> None:\n file_path = os.path.join(\n Config.directory.planning,\n \"{u}.{p}.problem.pddl\".format(u=\"test\", p=self.monster.agent.problem)\n )\n self.assertTrue(os.path.exists(file_path))\n\n\nclass TestPlanningPlayer(unittest.TestCase):\n \"\"\"Test the PlanningPlayer class\"\"\"\n def setUp(self) -> None:\n self.game = Game(\n char_class=\"fighter\",\n char_name=\"Xena\",\n adventure=\"the_tomb_of_baradin_stormfury\",\n session_id=\"test\"\n )\n self.game.load()\n Config.agent.set_player(\"planning\")\n Config.planner.set_player(\"fd\")\n monster_id = \"giant_rat_1\"\n self.game.state.set_current_room(\"player\", \"inns_cellar\")\n self.game.state.set_current_goal([[\"not\", \"alive\", \"giant_rat_1\"]])\n self.game.state.quest()\n self.game.state.light_torch()\n self.game.state.set_target(monster_id)\n self.player = self.game.state.get_player()\n self.player.agent.prepare_next_move()\n \n def tearDown(self) -> None:\n shutil.rmtree(Config.directory.planning)\n \n def test_player_plan(self) -> None:\n self.assertEqual(\"Maybe you should attack Giant Rat 1.\", self.player.agent.get_next_move())\n \n def test_build_domain(self) -> None:\n file_path = os.path.join(\n Config.directory.planning,\n \"{u}.{d}.domain.pddl\".format(u=\"test\", d=self.player.agent.domain)\n )\n self.assertTrue(os.path.exists(file_path))\n \n def test_build_problem(self) -> None:\n file_path = os.path.join(\n Config.directory.planning,\n \"{u}.{p}.problem.pddl\".format(u=\"test\", p=self.player.agent.problem)\n )\n self.assertTrue(os.path.exists(file_path))\n \n \nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"katie-codes-io/dungeon-master-ai","sub_path":"tests/test_planning.py","file_name":"test_planning.py","file_ext":"py","file_size_in_byte":5883,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"71868113133","text":"import threading\n\nMAX9744_ADDRESS = 0x4B\n\nclass MAX9744(object):\n MAX_VOLUME = 0x3F\n\n def __init__(self, address=MAX9744_ADDRESS, i2c=None, **kwargs):\n if i2c is None:\n import Adafruit_GPIO.I2C as I2C\n i2c = I2C\n\n self._device = i2c.get_i2c_device(address, **kwargs)\n self._volume_lock = threading.Lock()\n self.set_volume(0)\n\n def set_volume(self, volume):\n if volume < 0:\n volume = 0\n elif volume > self.MAX_VOLUME:\n volume = self.MAX_VOLUME\n\n with self._volume_lock:\n self._device.writeRaw8(volume & self.MAX_VOLUME)\n self._volume = volume\n\n def get_volume(self):\n with self._volume_lock:\n return self._volume\n\n","repo_name":"gnoddep/nerdhome","sub_path":"Nerdman/MAX9744.py","file_name":"MAX9744.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"28715974607","text":"import math\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nfrom sklearn.metrics import mean_squared_error as mse\nfrom sklearn.metrics import mean_absolute_percentage_error as mape\nimport numpy as np\nimport pandas as pd\n\n\ndef four_hour_prediction(model, X, y, title, start, end):\n predictions = []\n sequence = []\n input_values = X[start:start + 1]\n\n actual = y[start:end]\n # [[[5, 2, 4, 1, 6]\n # [2, 4, 1, 6, 5]\n # [4, 1, 6, 5, 3]\n # [1, 6, 5, 3, 4]\n # [6, 5, 3, 4, 5]\n # ]]]\n sequence.append(input_values[0])\n\n for i in range(0, end - start - 1):\n l = model.predict(input_values).flatten()\n\n wind_speed = math.ceil(l[0])\n\n new_l = np.expand_dims(np.array([wind_speed]), axis=1)\n\n input_values = np.array(np.append(input_values[0][1:], new_l, axis=0))\n\n sequence.append(input_values)\n input_values = np.expand_dims(input_values, axis=0)\n\n predictions.append(l)\n\n final_sequence = np.array(sequence)\n final_predictions = model.predict(final_sequence).flatten()\n\n final_predictions_m_per_s = [i * 0.511111 for i in final_predictions]\n actual_m_per_s = [i * 0.511111 for i in actual]\n\n df = pd.DataFrame(data={'Prediction': final_predictions_m_per_s, 'Actual': actual_m_per_s})\n df.index = np.arange(1, len(df) + 1)\n\n plt.plot(df['Prediction'], color='r')\n plt.plot(df['Actual'], color='g')\n plt.title(title)\n plt.legend(handles=[mpatches.Patch(color='g', label='Actual'), mpatches.Patch(color='r', label='Prediction')])\n plt.ylabel('Wind Speed(m/s)')\n plt.xlabel('Hours Ahead')\n plt.show()\n\n md_mape = mape(y[start:end], final_predictions) * 100\n md_rmse = mse(y[start:end], final_predictions, squared=True)\n md_mse = mse(y[start:end], final_predictions, squared=False)\n\n return md_mape, md_rmse, md_mse\n\n\ndef plot_predictions(model_lstm, model_cnn, model_gru, X, y, title='#####', start=0, end=100):\n try:\n\n lstm_predictions = model_lstm.predict(X[start:end]).flatten()\n cnn_predictions = model_cnn.predict(X[start:end]).flatten()\n gru_predictions = model_gru.predict(X[start:end]).flatten()\n\n actual = y[start - 1:end - 1]\n\n df = pd.DataFrame(data={'LSTM Prediction': lstm_predictions, 'CNN Prediction': cnn_predictions,\n 'GRU Prediction': gru_predictions, 'Actual': actual})\n\n plt.plot(df['LSTM Prediction'], color='r')\n plt.plot(df['CNN Prediction'], color='b')\n plt.plot(df['GRU Prediction'], color='orange')\n plt.plot(df['Actual'], color='g')\n plt.title(title)\n plt.legend(\n handles=[mpatches.Patch(color='g', label='Actual'), mpatches.Patch(color='r', label='LSTM Prediction'),\n mpatches.Patch(color='b', label='CNN Prediction'),\n mpatches.Patch(color='orange', label='GRU Prediction')])\n plt.ylabel('Wind Speed(m/s)')\n plt.xlabel('Hours Ahead')\n plt.show()\n return mse(y[start:end], lstm_predictions), mse(y[start:end], cnn_predictions), mse(y[start:end],\n gru_predictions)\n except Exception as e:\n print(\"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\")\n print(e)\n","repo_name":"MaksymMysak2000/wind-predictions","sub_path":"model_train/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"7215756869","text":"import matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom matplotlib import rc\n\nrc('text', usetex=True)\nplt.rcParams.update({'font.size': 10})\nimport os\n\nimport librosa\nimport numpy as np\nimport scipy.signal as signal\nimport argparse\n# seg_len_mic = 640\n# overlap_mic = 320\n# seg_len_imu = 64\n# overlap_imu = 32\n\nseg_len_mic = 2560\noverlap_mic = 2240\nseg_len_imu = 256\noverlap_imu = 224\n\nrate_mic = 16000\nrate_imu = 1600\nT = 5\nfreq_bin_high = int(rate_imu / rate_mic * int(seg_len_mic / 2)) + 1\nfreq_bin_low = int(200 / rate_mic * int(seg_len_mic / 2)) + 1\nfreq_bin_limit = int(rate_imu / rate_mic * int(seg_len_mic / 2)) + 1\ntime_bin = int(T*rate_mic/(seg_len_mic-overlap_mic)) + 1\n\ndef synchronize(x, x_t, y_t):\n x_t = np.sum(x_t, axis=0)\n y_t = np.sum(y_t, axis=0)\n corr = signal.correlate(y_t, x_t, 'full')\n shift = np.argmax(corr) - np.shape(x_t)\n x = np.roll(x, shift, axis=1)\n\n return x\ndef data_extract(path, files_mic1, files_mic2, files_imu1, files_imu2):\n wave_1 = librosa.load(os.path.join(path, files_mic1), sr=rate_mic)[0]\n wave_2 = librosa.load(os.path.join(path, files_mic2), sr=rate_mic)[0]\n\n # b, a = signal.butter(4, 100, 'highpass', fs=16000)\n # wave_1 = signal.filtfilt(b, a, wave_1)\n # wave_2 = signal.filtfilt(b, a, wave_2)\n\n Zxx1 = np.abs(signal.stft(wave_1, nperseg=seg_len_mic, noverlap=overlap_mic, fs=rate_mic)[-1])\n Zxx2 = np.abs(signal.stft(wave_2, nperseg=seg_len_mic, noverlap=overlap_mic, fs=rate_mic)[-1])\n\n data1, imu1 = imuplot.read_data(os.path.join(path, files_imu1), seg_len_imu, overlap_imu, rate_imu, filter=False)\n data2, imu2 = imuplot.read_data(os.path.join(path, files_imu2), seg_len_imu, overlap_imu, rate_imu, filter=False)\n imu1 = np.pad(imu1, ((0, freq_bin_high), (0, 0)))\n imu2 = np.pad(imu2, ((0, freq_bin_high), (0, 0)))\n return Zxx1, Zxx2, imu1, imu2\ndef draw_2(spectrogram1, spectrogram2, axs, start, stop, vmax):\n\n\n\n axs[0].locator_params(axis='x', nbins=1)\n axs[0].tick_params(axis='both', left=False, bottom=False, pad=-2)\n axs[0].set_yticks([0, 100, 400, 800, 1600])\n #axs[0].axline((0, 100), (2, 100), color='w')\n im1 = axs[0].imshow(spectrogram1, extent=[0, stop - start, 0, 1600],\n aspect='auto', origin='lower', vmin=0, vmax=vmax[0])\n\n axs[1].locator_params(axis='x', nbins=1)\n axs[1].tick_params(axis='both', left=False, bottom=False, pad=-2)\n axs[1].set_yticks([])\n #axs[1].axline((0, 100), (2, 100), color='w')\n im2 = axs[1].imshow(spectrogram2, extent=[0, stop - start, 0, 1600],\n aspect='auto', origin='lower', vmin=0, vmax=vmax[1])\n\n fig.text(0.3, 0.95, 'Mic', va='center')\n fig.text(0.7, 0.95, 'Acc', va='center')\n fig.text(0.2, 0.04, 'Time (S)', va='center')\n fig.text(0.65, 0.04, 'Time (S)', va='center')\n #fig.text(0.01, 0.50, 'Frequency(Hz)', va='center', rotation='vertical')\n\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--mode', action=\"store\", type=int, default=0, required=False,\n help='mode of processing, 0-WER, 1-spectrogram compare, 2-low, high frequency')\n args = parser.parse_args()\n if args.mode == 0:\n functions = os.listdir('transfer_function')\n collect1 = {}\n collect2 = {}\n for f in functions:\n r = np.load('transfer_function/' + f)['response']\n v = np.load('transfer_function/' + f)['variance']\n id = int(f.split('_')[0])\n if id not in collect1:\n collect1[id] = r\n collect2[id] = v\n else:\n collect1[id] = np.column_stack([collect1[id], r])\n collect2[id] = np.column_stack([collect2[id], r])\n\n fig, axs = plt.subplots(1, figsize=(2, 2))\n plt.subplots_adjust(left=0.2, bottom=0.16, right=0.98, top=0.98)\n response = np.mean(collect1[0], axis=1)\n variance = np.mean(collect2[0], axis=1)\n plt.errorbar(range(33), response, yerr=variance/2, fmt='--', color='b', elinewidth=1, capsize=1.5, label='User'+str(0))\n response = np.mean(collect1[1], axis=1)\n variance = np.mean(collect2[1], axis=1)\n plt.errorbar(range(33), response, yerr=variance / 2, fmt='', color='r', elinewidth=1, capsize=1.5,\n label='User' + str(1))\n plt.xticks([0, 7, 15, 23, 31], [0, 200, 400, 600, 800])\n plt.legend()\n\n fig.text(0.4, 0.03, 'Frequency (Hz)', va='center')\n fig.text(0.02, 0.575, '${S_Acc}/{S_Mic}$', va='center', rotation='vertical')\n plt.savefig('transfer_variance.pdf', dpi=600)\n plt.show()\n\n elif args.mode == 1:\n path = os.path.join('dataset/measurement/')\n files = os.listdir(path)\n N = int(len(files) / 4)\n files_imu1 = files[:N]\n files_imu2 = files[N:2 * N]\n files_mic1 = files[2 * N:3 * N]\n files_mic2 = files[3 * N:]\n files_mic2.sort(key=lambda x: int(x[4:-4]))\n crop = [[0.5, 2.5], [1.5, 3.5], [0.5, 2.5], [1, 3]]\n name = ['clean', 'noise', 'move', 'notalk']\n #vmax = [[[0.05, 0.0008], [0.02, 0.02]], [[0.05, 0.0008], [0.02, 0.02]], [[0.05, 0.0008], [0.02, 0.02]], [[0.05, 0.0008], [0.02, 0.02]]]\n vmax = [[0.05, 0.02], [0.05, 0.02], [0.05, 0.02], [0.05, 0.02]]\n select = [1, 5, 6, 13]\n for i in [3]:\n v = vmax[i]\n start = crop[i][0]\n stop = crop[i][1]\n n = name[i]\n\n Zxx1, Zxx2, imu1, imu2 = data_extract(path, files_mic1[select[i]], files_mic2[select[i]],\n files_imu1[select[i]], files_imu2[select[i]])\n\n fig, axs = plt.subplots(1, 2, figsize=(2, 2))\n plt.subplots_adjust(left=0.16, bottom=0.12, right=0.95, top=0.92, wspace=0.1, hspace=0)\n spectrogram1 = Zxx2[: 2 * freq_bin_high, int(start * 50): int(stop * 50)]\n spectrogram2 = imu1[: 2 * freq_bin_high, int(start * 50): int(stop * 50)]\n draw_2(spectrogram1, spectrogram2, axs, start, stop, v)\n # axs[0].axline((0, 100), (2, 100), color='w')\n # axs[1].axline((0, 100), (2, 100), color='w')\n if i == 1:\n print('add white box')\n rect = patches.Rectangle((1.05, 200), 0.7, 550, linewidth=1, edgecolor='w', facecolor='none')\n axs[0].add_patch(rect)\n if i == 3:\n print('add zoom-in')\n rect = patches.Rectangle((0.3, 0), 0.3, 100, linewidth=1, edgecolor='lime', facecolor='none')\n axs[0].add_patch(rect)\n rect = patches.Rectangle((0.3, 0), 0.3, 100, linewidth=1, edgecolor='lime', facecolor='none')\n axs[1].add_patch(rect)\n\n axs[0].arrow(0.6, 100, 0.8, 600, color='lime')\n axs[0].arrow(0.3, 100, 0.15, 600, color='lime')\n\n axs[1].arrow(0.6, 100, 0.8, 600, color='lime')\n axs[1].arrow(0.3, 100, 0.15, 600, color='lime')\n\n axs[0].text(0.35, 1200, 'Zoom-in', color='white')\n axs[1].text(0.35, 1200, 'Zoom-in', color='white')\n axins = axs[0].inset_axes([0.2, 0.3, 0.5, 0.5])\n axins.imshow(spectrogram1, origin=\"lower\", vmin=0, vmax=0.02)\n axins.spines['bottom'].set_color('lime')\n axins.spines['top'].set_color('lime')\n axins.spines['right'].set_color('lime')\n axins.spines['left'].set_color('lime')\n # sub region of the original image\n x1, x2, y1, y2 = 35, 60, 0, 30\n axins.set_xlim(x1, x2)\n axins.set_ylim(y1, y2)\n axins.set_xticklabels([])\n axins.set_yticklabels([])\n axins.tick_params(axis='both', left=False, bottom=False)\n\n\n axins = axs[1].inset_axes([0.2, 0.3, 0.5, 0.5])\n axins.imshow(spectrogram2, origin=\"lower\", vmin=0, vmax=0.02)\n axins.spines['bottom'].set_color('lime')\n axins.spines['top'].set_color('lime')\n axins.spines['right'].set_color('lime')\n axins.spines['left'].set_color('lime')\n # sub region of the original image\n x1, x2, y1, y2 = 35, 60, 0, 30\n axins.set_xlim(x1, x2)\n axins.set_ylim(y1, y2)\n axins.set_xticklabels([])\n axins.set_yticklabels([])\n axins.tick_params(axis='both', left=False, bottom=False)\n #axs[1].indicate_inset_zoom(axins, edgecolor=\"white\")\n\n plt.savefig(n + '.pdf', dpi=600)\n plt.show()\n","repo_name":"lixinghe1999/audioproject","sub_path":"vibvoice/plot/measurement.py","file_name":"measurement.py","file_ext":"py","file_size_in_byte":8699,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"55"} +{"seq_id":"20526888309","text":"from datetime import datetime\n\nfrom bson import ObjectId\n\nfrom clockify.data import users, projects\nfrom mongo_connection import MongoDatabase\n\nmongo = MongoDatabase()\ndb = mongo.client.clockify_normalized\n\nusers_collection = db.users\nprojects_collection = db.projects\nreports_collection = db.reports\n\n\ndef store_one():\n \"\"\"Just run at the first run of the script\"\"\"\n if users_collection.count_documents({}) == 0:\n print(\"Save data in users collection\")\n users_collection.insert_many(users)\n if projects_collection.count_documents({}) == 0:\n print(\"Save data in projects collection\")\n projects_collection.insert_many(projects)\n\n\ndef save_record():\n hossein = users_collection.find_one({\"username\": \"hossein\"})\n shop = projects_collection.find_one({'name': \"Online Shop\"})\n\n report = reports_collection.insert_one(\n {\n \"user\": hossein.get(\"_id\"),\n \"project\": shop.get(\"_id\"),\n \"start_time\": datetime.now()\n }\n )\n return report\n\n\ndef set_end_time(object_id):\n query_filter = {\"_id\": ObjectId(object_id)}\n update = {\"$set\": {'end_time': datetime.now()}}\n reports_collection.update_one(\n filter=query_filter,\n update=update\n )\n\n\ndef show_reports():\n query_filter = users_collection.find_one({\"username\": \"hossein\"})\n pipeline = [\n {\"$match\": {\"user\": query_filter.get(\"_id\")}},\n {\"$lookup\": {\"from\": \"users\", \"localField\": \"user\", \"foreignField\": \"_id\", \"as\": \"user\"}},\n {\"$unwind\": \"$user\"},\n {\"$lookup\": {\"from\": \"projects\", \"localField\": \"project\", \"foreignField\": \"_id\", \"as\": \"project\"}},\n {\"$unwind\": \"$project\"},\n ]\n query = reports_collection.aggregate(pipeline=pipeline)\n\n for report in query:\n duration = (report.get('end_time') - report.get('start_time')).seconds\n\n print(f\"Username: {report.get('user').get('username')}\\n\"\n f\"Project: {report.get('project').get('name')}\\n\"\n f\"Duration: {duration} Seconds\")\n\n print(\"######################################\")\n\n query_filter = users_collection.find_one({\"username\": \"hossein\"}) # hint-1\n for report in reports_collection.find({\"user\": query_filter.get(\"_id\")}): # hint-2\n user = users_collection.find_one({\"_id\": ObjectId(report.get('user'))}) # hint-3\n project = projects_collection.find_one({\"_id\": ObjectId(report.get(\"project\"))}) # hint-4\n duration = (report.get('end_time') - report.get('start_time')).seconds\n\n print(f\"Username: {user.get('username')}\\n\"\n f\"Project: {project.get('name')}\\n\"\n f\"Duration: {duration} Seconds\")\n\n\nif __name__ == '__main__':\n # store_one()\n # save_record()\n # set_end_time(object_id=\"6223c4bb7fa9d10dacb85f41\")\n show_reports()\n","repo_name":"mohsen-az/Redis-Mongo-Rabbitmq-Celery","sub_path":"m-mongo/src/clockify/clockify_normalized.py","file_name":"clockify_normalized.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"71480763693","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.nn import init\n\nfrom hgp.misc.constraint_utils import invsoftplus, softplus\n\n\nclass Gaussian(nn.Module):\n \"\"\"\n Gaussian likelihood\n \"\"\"\n\n def __init__(self, ndim=1, init_val=0.01):\n super(Gaussian, self).__init__()\n self.unconstrained_variance = torch.nn.Parameter(\n torch.ones(ndim), requires_grad=True\n )\n self._initialize(init_val)\n\n def _initialize(self, x):\n init.constant_(self.unconstrained_variance, invsoftplus(torch.tensor(x)).item())\n\n @property\n def variance(self):\n return softplus(self.unconstrained_variance)\n\n @variance.setter\n def variance(self, value):\n self.unconstrained_variance = nn.Parameter(\n invsoftplus(value), requires_grad=True\n )\n\n def log_prob(self, F, Y):\n return -0.5 * (\n np.log(2.0 * np.pi)\n + torch.log(self.variance)\n + torch.pow(F - Y, 2) / self.variance\n )\n","repo_name":"magnusross/hgp","sub_path":"hgp/core/observation_likelihoods.py","file_name":"observation_likelihoods.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"37194857423","text":"import os\nimport tempfile\nfrom typing import Dict, Literal\n\nimport structlog\n\nfrom toolbelt.config import config\nfrom toolbelt.constants import WIN\nfrom toolbelt.tools.esigner import Esigner\nfrom toolbelt.types import Platforms\nfrom toolbelt.utils.zip import compress, extract\n\nlogger = structlog.get_logger(__name__)\n\n\nclass CopyMachine:\n def __init__(self, app: Literal[\"player\", \"launcher\"]) -> None:\n self.app = app\n self.dir_map: Dict[str, str] = {}\n\n def run(\n self,\n platform: Platforms,\n commit_hash: str,\n target_s3_dir: str,\n version: int,\n run_id: str,\n *,\n dry_run: bool = False,\n signing: bool = False,\n ):\n with tempfile.TemporaryDirectory() as tmp_path:\n self.base_dir = tmp_path\n\n self.download(platform, commit_hash, run_id)\n self.preprocessing(platform, commit_hash, version)\n if signing:\n if platform == WIN:\n signing_for_windows(\n Esigner(),\n self.dir_map[\"binary\"],\n self.base_dir,\n self.app,\n )\n logger.info(\"Finish signing\", os=platform, app=self.app)\n if not dry_run:\n self.upload(platform, target_s3_dir)\n\n def download(self, platform: str, commit_hash: str, run_id: str):\n raise NotImplementedError\n\n def preprocessing(\n self,\n platform: str,\n commit_hash: str,\n version: int,\n ):\n raise NotImplementedError\n\n def upload(self, platform: str, target_s3_dir: str):\n raise NotImplementedError\n\n\ndef signing_for_windows(\n esigner: Esigner,\n binary_path: str,\n dir: str,\n target_app: Literal[\"player\", \"launcher\"],\n):\n # 1. Extract binary\n extract_path = extract(os.path.join(dir, \"for_signing\"), binary_path, use7z=False)\n\n # 2. Move exe files\n input_dir = os.path.join(dir, \"temp_input\")\n os.mkdir(input_dir)\n if target_app == \"player\":\n os.rename(\n os.path.join(extract_path, \"NineChronicles.exe\"),\n os.path.join(input_dir, \"NineChronicles.exe\"),\n )\n elif target_app == \"launcher\":\n os.rename(\n os.path.join(extract_path, \"Nine Chronicles.exe\"),\n os.path.join(input_dir, \"Nine Chronicles.exe\"),\n )\n else:\n raise ValueError()\n\n # 3. signing\n output_dir = os.path.join(dir, \"temp_output\")\n os.mkdir(output_dir)\n result = esigner.sign(\n **config.signing_secrets,\n input_dir_path=input_dir,\n output_dir_path=output_dir,\n )\n logger.debug(\"Signed\", output=result.stdout)\n\n # 4. Re move exe files\n if target_app == \"player\":\n os.rename(\n os.path.join(output_dir, \"NineChronicles.exe\"),\n os.path.join(extract_path, \"NineChronicles.exe\"),\n )\n elif target_app == \"launcher\":\n os.rename(\n os.path.join(output_dir, \"Nine Chronicles.exe\"),\n os.path.join(extract_path, \"Nine Chronicles.exe\"),\n )\n\n # 5. Compress\n result_path = compress(dir, extract_path, binary_path, use7z=False)\n logger.debug(\"Signed path\", path=result_path)\n","repo_name":"planetarium/9c-toolbelt","sub_path":"toolbelt/apps/release/copy_machine.py","file_name":"copy_machine.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"70452423533","text":"import argparse\nimport gym\nfrom gym import wrappers\nimport os.path as osp\nimport random\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.contrib.layers as layers\n\nimport dqn\nfrom dqn_utils import *\nfrom atari_wrappers import *\n\n\ndef atari_model(ram_in, num_actions, scope, reuse=False):\n with tf.variable_scope(scope, reuse=reuse):\n out = ram_in\n #out = tf.concat(1,(ram_in[:,4:5],ram_in[:,8:9],ram_in[:,11:13],ram_in[:,21:22],ram_in[:,50:51], ram_in[:,60:61],ram_in[:,64:65]))\n with tf.variable_scope(\"action_value\"):\n out = layers.fully_connected(out, num_outputs=256, activation_fn=tf.nn.relu)\n out = layers.fully_connected(out, num_outputs=128, activation_fn=tf.nn.relu)\n out = layers.fully_connected(out, num_outputs=64, activation_fn=tf.nn.relu)\n out = layers.fully_connected(out, num_outputs=num_actions, activation_fn=None)\n\n return out\n\ndef atari_learn(env,\n session,\n num_timesteps):\n # This is just a rough estimate\n num_iterations = float(num_timesteps) / 4.0\n\n lr_multiplier = 1.0\n lr_schedule = PiecewiseSchedule([\n (0, 1e-4 * lr_multiplier),\n (num_iterations / 10, 1e-4 * lr_multiplier),\n (num_iterations / 2, 5e-5 * lr_multiplier),\n ],\n outside_value=5e-5 * lr_multiplier)\n optimizer = dqn.OptimizerSpec(\n constructor=tf.train.AdamOptimizer,\n kwargs=dict(epsilon=1e-4),\n lr_schedule=lr_schedule\n )\n\n def stopping_criterion(env, t):\n # notice that here t is the number of steps of the wrapped env,\n # which is different from the number of steps in the underlying env\n return get_wrapper_by_name(env, \"Monitor\").get_total_steps() >= num_timesteps\n\n exploration_schedule = PiecewiseSchedule(\n [\n (0, 0.2),\n (1e6, 0.1),\n (num_iterations / 2, 0.01),\n ], outside_value=0.01\n )\n\n dqn.learn(\n env,\n q_func=atari_model,\n optimizer_spec=optimizer,\n session=session,\n exploration=exploration_schedule,\n stopping_criterion=stopping_criterion,\n replay_buffer_size=1000000,\n batch_size=32,\n gamma=0.99,\n learning_starts=50000,\n learning_freq=4,\n frame_history_len=1,\n target_update_freq=10000,\n grad_norm_clipping=10\n )\n env.close()\n\ndef get_available_gpus():\n from tensorflow.python.client import device_lib\n local_device_protos = device_lib.list_local_devices()\n return [x.physical_device_desc for x in local_device_protos if x.device_type == 'GPU']\n\ndef set_global_seeds(i):\n try:\n import tensorflow as tf\n except ImportError:\n pass\n else:\n tf.set_random_seed(i)\n np.random.seed(i)\n random.seed(i)\n\ndef get_session():\n tf.reset_default_graph()\n tf_config = tf.ConfigProto(\n inter_op_parallelism_threads=1,\n intra_op_parallelism_threads=1)\n session = tf.Session(config=tf_config)\n print(\"AVAILABLE GPUS: \", get_available_gpus())\n return session\n\ndef get_env(seed):\n env = gym.make('Pong-ram-v0')\n\n set_global_seeds(seed)\n env.seed(seed)\n\n expt_dir = '/tmp/hw3_vid_dir/'\n env = wrappers.Monitor(env, osp.join(expt_dir, \"gym\"), force=True)\n env = wrap_deepmind_ram(env)\n\n return env\n\ndef main():\n # Run training\n seed = 0 # Use a seed of zero (you may want to randomize the seed!)\n env = get_env(seed)\n session = get_session()\n atari_learn(env, session, num_timesteps=int(4e7))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"berkeleydeeprlcourse/homework","sub_path":"hw3/run_dqn_ram.py","file_name":"run_dqn_ram.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","stars":1514,"dataset":"github-code","pt":"55"} +{"seq_id":"31665239630","text":"\ndoors = [\"A\", \"B\", \"C\"]\n\nwinning_door = \"A\"\nwinning_door\n# out: 'A'\n\nchosen_door = input(\"Choose a door from 'A', 'B', or 'C': \").upper()\n# in: A\n# out: Choose a door from 'A', 'B', or 'C': A\nchosen_door\n# out: 'A'\n\nwrong_door = \"B\"\nwrong_door\n# out: 'B'\n\nprint(f\"Door '{wrong_door}' is not the winning door\")\n# out: Door 'B' is not the winning door\nswitch_choice = input(\"Would you like to switch your choice [y/n]\").lower()\n# in: n\n# out: Would you like to switch your choice [y/n]n\nswitch_choice\n# out: 'n'\n\nif switch_choice == \"y\":\n\tchosen_door, = [d for d in doors if d not in [wrong_door, chosen_door]]\nchosen_door\n# out: 'A'\n\nif chosen_door == winning_door:\n\tprint(\"Congrats, you won!\", end=\"\")\nelse:\n\tprint(\"Too bad! better luck next time!\", end=\"\")\n# out: Congrats, you won!\n# info: missing trailing newline\n","repo_name":"07734willy/PyRepl","sub_path":"tests/data/samples/demo1/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"55"} +{"seq_id":"12164084628","text":"import os\nimport time\nimport uuid\nimport contextlib\n\nfrom TextToSpeech.TTSInterface import TTSInterface\nfrom gtts import gTTS\nfrom gtts.tokenizer.pre_processors import abbreviations, end_of_line\nwith contextlib.redirect_stdout(None):\n from pygame import mixer\n\nfrom mutagen.mp3 import MP3\n\nclass GTTS(TTSInterface):\n def __init__(self, language='en', speed=False):\n self.language = language\n self.speed = speed\n self.audio = None\n\n def get_tts_audio(self, text):\n # slow=False. Tells the module that the converted audio should have a high speed\n tts_audio = gTTS(text, lang=self.language, slow=self.speed, pre_processor_funcs = [abbreviations, end_of_line])\n \n self.audio = tts_audio\n\n ct = f'{uuid.uuid4()}.mp3'\n tts_audio.save(ct)\n\n self.play_audio(ct)\n \n os.remove(ct)\n\n def save_tts(self):\n # Should prob open file explorer to select a destination instead.\n self.audio.save(f'{uuid.uuid4()}.mp3')\n \n def play_audio(self, file_path):\n mixer.init()\n mixer.music.load(file_path)\n mixer.music.play()\n\n # Wait for the audio to be played\n time.sleep(MP3(file_path).info.length)\n\n mixer.quit()\n","repo_name":"seelk89/Chatbot","sub_path":"TextToSpeech/gTTS.py","file_name":"gTTS.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"27628813928","text":"import torch\nfrom torch.utils.data import DataLoader\nimport os\nfrom functools import reduce\nimport numpy as np\nimport pandas as pd\n\n\nclass AutoencoderDataset:\n def __init__(self, folder_path, use_dataloaders, device, filter_feats, batch_size=None):\n self.folder_path = folder_path\n self.use_dataloaders = use_dataloaders\n self.batch_size = batch_size\n self.device = device\n self.filter_feats = filter_feats\n self.dataset = self.__load_dataset()\n\n def get_dataloaders(self, datasets):\n loaders = []\n filter_feats = [self.filter_feats] if not isinstance(self.filter_feats, list) else self.filter_feats\n for dataset in datasets:\n cols = [c for feat in filter_feats for c in dataset.columns if not c.startswith(feat)]\n dataset.drop(columns=cols, inplace=True)\n tensor_dataset = [torch.tensor(t, device=self.device) for _,t in dataset.iterrows()]\n loader = DataLoader(tensor_dataset, batch_size=self.batch_size, num_workers=0)\n loaders.append(loader)\n return loaders\n\n def __load_dataset(self):\n # Load ae\n filenames = [os.path.join(self.folder_path, filename) for filename in os.listdir(self.folder_path) if\n filename.endswith('.csv')]\n datasets = [pd.read_csv(filename) for filename in filenames]\n\n # Drop infinities if they exist\n for dataset in datasets:\n dataset.replace([np.inf, -np.inf], np.nan, inplace=True)\n dataset.dropna(inplace=True)\n dataset.reset_index(drop=True, inplace=True)\n\n cols = [c for c in dataset.columns if c.lower().startswith('unnamed') or c.lower().startswith('ae')] # Remove columns\n dataset.drop(columns=cols, inplace=True)\n\n # Combine ae\n full_dataset = reduce(lambda df1, df2: pd.concat((df1, df2), axis=0), datasets)\n full_dataset.sort_values(['date'], ascending=[True], inplace=True)\n full_dataset.reset_index(drop=True, inplace=True)\n\n return full_dataset\n\n","repo_name":"brunogreen25/Deep-Pocket-for-Portfolio-Management","sub_path":"datasets/ae/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"41080266398","text":"from collections import defaultdict\ns=defaultdict(list)\nlist1=[]\nm,n=map(int,input().split())\nfor i in range(m):\n a=input()\n s[a].append(i+1)\nfor i in range(n):\n b=input()\n list1=list1+[b]\nfor i in list1:\n if i in s:\n print(' '.join(map(str,s[i])))\n else:\n print(-1) ","repo_name":"ankitafzl/PythonPractice","sub_path":"defaultdictTutorial.py","file_name":"defaultdictTutorial.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"567607547","text":"import cv2 as cv2\nimport numpy as np\nfrom . import c4d_uc5_settings as sett\n\ndef ResizeAndPad(image, inputSize):\n canH = image.shape[0]\n canW = image.shape[1]\n\n # Create new image canvas\n new_image_width = max(canW, canH)\n new_image_height = max(canW, canH)\n color = (0, 0, 0)\n frame = np.full((new_image_height, new_image_width, 3), color, dtype=np.uint8)\n x_center = (new_image_width - canW) // 2\n y_center = (new_image_height - canH) // 2\n\n frame[y_center:y_center + canH, x_center:x_center + canW] = image\n\n # Normalize\n frame = frame / 255.0\n # Resize\n frame = cv2.resize(frame, inputSize)\n\n return frame # return padded and resized 640x640 image\n\n\n## Bundle function of frame spatial specifications ##\ndef frameSpecs(frame, inputSize):\n canH = frame.shape[0]\n canW = frame.shape[1]\n\n scaleW = canW / max(canW, canH)\n scaleH = canH / max(canW, canH)\n padFactor = (abs(canW - canH) / 2) / max(canW, canH) * inputSize[0]\n return (canH, canW, scaleW, scaleH, padFactor)\n\n\ndef inputPreprocess(frame, inputSize):\n # convert to RGB\n image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\n # create letterbox image and resize 640x640 (as the examples in the mail)\n img = ResizeAndPad(image, inputSize)\n image = img\n # Reshape and type float16\n img = np.expand_dims(img.transpose(2, 0, 1), axis=0)\n img = img.astype(np.float16)\n return np.array(img)\n\n\n## Convert raw output to list of (xmin, ymin, w, h) entries for bounding boxes ##\ndef outputPreprocess(result_0, mOutputRow, mOutputColumn, frame):\n # flattening the output [][][] -> []\n outputs = []\n (canH, canW, scaleW, scaleH, padFactor) = frameSpecs(frame, (640,640))\n\n for i in range(mOutputRow):\n for j in range(mOutputColumn):\n outputs.append(result_0[0][i][j])\n\n # process the output and convert boxes to xmin, ymin, w, h\n boxes = []\n for i in range(mOutputRow):\n conf = outputs[i * mOutputColumn + 4]\n if conf > 0.25:\n # extract box coordinates and compensate the added padding\n if canW > canH:\n xc = (outputs[i * mOutputColumn]) / (640 * scaleW)\n yc = (outputs[i * mOutputColumn + 1] - padFactor) / (640 * scaleH)\n else:\n xc = (outputs[i * mOutputColumn] - padFactor) / (640 * scaleW)\n yc = (outputs[i * mOutputColumn + 1]) / (640 * scaleH)\n # convert boxes to xmin, ymin, w, h\n w = outputs[i * mOutputColumn + 2] / (640 * scaleW)\n h = outputs[i * mOutputColumn + 3] / (640 * scaleH)\n x = xc - w / 2\n y = yc - h / 2\n\n # this step is only needed when the model has multiple classes\n boxes.append([x, y, w, h, conf])\n return boxes\n\n\ndef bb_intersection_over_union(boxA, boxB):\n IOU = 0\n AW = boxA[2]\n AH = boxA[3]\n Bx = boxB[0] - boxA[0]\n By = boxB[1] - boxA[1]\n BW = Bx + boxB[2]\n BH = By + boxB[3]\n\n # X overlap Calc\n if Bx < 0 and BW > 0:\n ovlpX = min(BW, AW)\n elif Bx > 0 and Bx < AW:\n ovlpX = min(BW, AW) - Bx\n elif Bx == 0:\n ovlpX = min(AW, BW)\n else:\n ovlpX = 0\n\n # Y overlap Calc\n if By < 0 and BH > 0:\n ovlpY = min(BH, AH)\n elif By > 0 and By < AH:\n ovlpY = min(BH, AH) - Bx\n elif By == 0:\n ovlpY = min(AH, BH)\n else:\n ovlpY = 0\n # Calculate Intersection over Union\n upp = ovlpX * ovlpY\n dwnn = AW * AH + BW * BH - upp\n if dwnn == 0.0:\n IOU = 255\n else:\n IOU = upp / dwnn\n return IOU\n\n\ndef FilterBoxesNMS(sorted_Boxes, iou_threshold):\n sorted_Boxes = sorted_Boxes.tolist()\n bbox_list = []\n stSize = len(sorted_Boxes)\n\n while stSize - len(bbox_list) != 0:\n bbox_list = []\n stSize = len(sorted_Boxes)\n while len(sorted_Boxes) > 0:\n current_box = sorted_Boxes.pop(0)\n bbox_list.append(current_box)\n list(bbox_list)\n for box in sorted_Boxes:\n iou = bb_intersection_over_union(current_box, box)\n if iou > iou_threshold:\n sorted_Boxes.remove(box)\n sorted_Boxes = bbox_list\n return bbox_list\n\n\ndef printBBoxes(frame, rem_bbox):\n (canH, canW, scaleW, scaleH, padFactor) = frameSpecs(frame, (640,640))\n\n for i in range(0, rem_bbox.shape[0]):\n boxYX = (int((rem_bbox[i, 0]) * canW),\n int((rem_bbox[i, 1]) * canH))\n boxYrXr = (int((rem_bbox[i, 0] + rem_bbox[i, 2]) * canW),\n int((rem_bbox[i, 1] + rem_bbox[i, 3]) * canH))\n\n box_rect = cv2.rectangle(frame, boxYX, boxYrXr, (0, 0, 180), 3)\n return frame\n\n","repo_name":"Di-O-Sotirop/c4d-companion-demo","sub_path":"modules/c4d_uc5_onnx_helper.py","file_name":"c4d_uc5_onnx_helper.py","file_ext":"py","file_size_in_byte":4707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"29178520041","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 14 19:16:33 2021\n\n@author: nd7896\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport re\nimport os\nimport sys\n\ndef read_file(filename):\n print(\"filename:\", filename)\n num_methods, capacity, item_dataset = None, None, None\n specification_regex = re.compile(\"knapsack problem specification \\(1 knapsacks, [0-9]* items\\)\")\n numbers = re.compile(\"\\ *[0-9]* items\")\n capacity_regex = re.compile(\"capacity: \\+[0-9]*.[0-9]*\")\n weight_regex = re.compile(\"weight: \\+[0-9]+\")\n profit_regex = re.compile(\"profit: \\+[0-9]*.[0-9]*\")\n item_regex = re.compile(\"item: [0-9]+\")\n #item dataset must be a pandas datatype\n with open(filename) as file:\n lines = file.readlines()\n for i in range(0, len(lines)):\n # print(lines[i])\n line = lines[i].strip(\"\\n\")\n proc_line = line.rstrip()\n proc_line = proc_line.lstrip()\n if specification_regex.search(proc_line):\n num_methods = int(numbers.findall(proc_line)[0].strip(\" items\"))\n item_dataset = pd.DataFrame(data=np.zeros(shape=(num_methods,2)), columns=[\"Fitness\", \"Weight\"])\n if capacity_regex.search(proc_line):\n capacity = int(capacity_regex.search(proc_line)[0].strip(\"capacity:\\ *\"))\n if item_regex.search(proc_line):\n item_line = item_regex.search(proc_line)\n item_idx = int(item_line[0].strip(\"item:\\ *\"))\n \n item_weight_line = lines[i+1].rstrip().lstrip()\n item_profit_line = lines[i+2].rstrip().lstrip()\n item_weight = weight_regex.search(item_weight_line)[0].strip(\"weight:\\ *\")\n item_fitness = profit_regex.search(item_profit_line)[0].strip(\"profit:\\ *\")\n \n item_dataset[\"Fitness\"].iloc[item_idx-1] = float(item_fitness)\n item_dataset[\"Weight\"].iloc[item_idx-1] = float(item_weight)\n \n \n return num_methods, capacity, item_dataset\n\ndef bit_flip(idx, solution):\n if solution[idx] == 0:\n solution[idx] = 1\n elif solution[idx] == 1:\n solution[idx] = 0\n return solution\n\n\ndef get_fitness(dataset, solution):\n fitness = 0\n \n for i in range(0, len(solution)):\n if solution[i] == 1:\n fitness = fitness + dataset[\"Fitness\"].iloc[i]\n \n return fitness\n\ndef hill_climbing(start_solution, num_methods, capacity, dataset):\n best_solution = start_solution\n best_fitness = float('-inf')\n for i in range(0, len(start_solution)):\n \n curr_solution = np.asarray(bit_flip(i, start_solution))\n curr_fitness = get_fitness(dataset, curr_solution)\n curr_weight = len(np.where(curr_solution==1)[0])\n if curr_weight <= capacity:\n if curr_fitness > best_fitness:\n best_solution = curr_solution\n best_fitness = curr_fitness\n \n return best_solution\n\ndef main():\n \n \n \n filename = str(sys.argv[1])\n output_run_path = str(sys.argv[2])\n num_iterations = int(sys.argv[3])\n num_methods, capacity, dataset = read_file(filename)\n \n start_solution = np.zeros(shape=(len(dataset)))\n ones_idx = np.random.choice(np.arange(0, len(dataset)), np.random.choice(len(dataset)))\n for each_idx in ones_idx:\n start_solution[each_idx] = 1\n \n solution = start_solution\n for i in range(0, num_iterations):\n \n solution = hill_climbing(solution, num_methods, capacity, dataset)\n \n output_filename = output_run_path+\"/results.txt\"\n #Write solution to file\n fo = open(output_filename, \"w+\")\n fo.write(\"Binary String:\")\n # print(solution.tolist())\n fo.write(str(solution.tolist()))\n fo.close()\n \n\n\nif __name__==\"__main__\":\n main()\n","repo_name":"niranjanadeshpande/search-based-api-migration","sub_path":"files/hill_climbing.py","file_name":"hill_climbing.py","file_ext":"py","file_size_in_byte":3904,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"27627939483","text":"import time\nfrom typing import Union\n\nimport settings\n\n\nclass Informer:\n \"\"\"\n The class is used to display the necessary current\n information about the events and processes of the game.\n \"\"\"\n\n @staticmethod\n def greeting() -> None:\n \"\"\"\n Displaying of game greeting.\n \"\"\"\n for line in settings.signboard:\n print(line)\n time.sleep(0.5)\n\n time.sleep(0.5)\n\n def game_over_message(self) -> None:\n \"\"\"\n Displaying of the game over message.\n \"\"\"\n self.text_into_frame(\n [f'\\n{settings.game_over_text}\\n'],\n need_printing=True\n )\n\n def player_registration_intro(self) -> None:\n \"\"\"\n Displaying of rules for registration of players.\n \"\"\"\n self.text_into_frame(\n [\n settings.player_registration_text.upper(),\n settings.allowed_name_notice\n ],\n need_printing=True\n )\n\n @staticmethod\n def player_greeting(\n player_number: str,\n player_name: str\n ) -> None:\n \"\"\"\n Displaying of greeting of the new player.\n \"\"\"\n pgt1, pgt2, pgt3 = settings.player_greeting_text_array.copy()\n print(f'{pgt1} {player_name.upper()}! {pgt2} {player_number}, {pgt3}\\n')\n\n def end_registration_message(\n self,\n player_count: int\n ) -> None:\n \"\"\"\n The succesful registration message.\n \"\"\"\n first, second = settings.players_registered_text\n self.text_into_frame([f'{first} {player_count} {second}'])\n\n def show_rules(self) -> None:\n \"\"\"\n Display the game rules.\n \"\"\"\n self.text_into_frame(settings.rule_text)\n\n @staticmethod\n def tap_to_game_starting() -> str:\n \"\"\"\n Returns user's any input to start the game.\n \"\"\"\n return input(f'{settings.tap_to_game_starting_text}: ')\n\n @staticmethod\n def text_into_frame(\n array_of_text_strings: Union[tuple, list],\n double_border: bool = True,\n need_printing: bool = True\n ) -> Union[str, None]:\n \"\"\"\n Places an array of strings into a double or single frame.\n \"\"\"\n spl_text = []\n\n for string in array_of_text_strings:\n # It separates text by a line break and placed\n # as separate elements in a special dictionary.\n for sub_string in string.split('\\n'):\n spl_text.append(sub_string)\n\n # The length of resulting frame by the longest string of all strings.\n frame_length = len(sorted(spl_text, key=len)[-1])\n\n # Variables of frame elements.\n tl, tr, bl, br, st = ('╔', '╗', '╚', '╝', '═') if double_border else ('┌', '┐', '└', '┘', '─')\n lf_fr, rt_fr = ('║ ', ' ║') if double_border else ('│ ', ' │')\n\n # The length of space between a side border\n # of the frame and the beginning of strings.\n brd_space = 2\n\n # Form the top and bottom lines of the frame.\n top_frame = tl + st * (frame_length + brd_space) + tr\n bottom_frame = bl + st * (frame_length + brd_space) + br\n\n # Adding to each row side borders.\n frame_content = (lf_fr + txt.ljust(frame_length) + rt_fr for txt in spl_text)\n\n # We place all the lines in the array between the upper\n # and lower borders of the frame, gluing them together,\n # as well as all the lines in the array between each other\n # with a line break.\n framed_text = '\\n'.join((top_frame, *frame_content, bottom_frame))\n\n if need_printing:\n # If necessary, print the result string.\n print(framed_text)\n return\n\n # Return the result string if it doesn't need to be printed.\n return framed_text\n\n def show_table_by_array(\n self,\n title_array: list,\n content_array: list,\n double_border: bool = True,\n need_printing: bool = True\n ) -> Union[str, None]:\n \"\"\"\n The function takes an array of strings, each of which is\n the header of a separate table column. The second array\n the function receives contains arrays that contain rows\n for each column of a particular row. The function calculates\n the necessary sizes and intervals for correct printing\n of received data in table format.\n \"\"\"\n\n # Merge a header array with a content array.\n common_array = [title_array] + content_array\n\n # Calculate the length of common array.\n common_array_size = len(common_array)\n\n # Get the table columns count which equal to length of title array.\n col_count = len(title_array)\n\n # Set the left, right and total indent for each column as well a column separator.\n left_indent = 1\n right_indent = 4\n ind = left_indent + right_indent\n column_separator = ' '\n\n # Forms a copy of the content array, in which each string\n # is replaced with a number equal to the length of this string.\n lengths = list(map(lambda x: list(map(len, x)), common_array))\n\n # Among the lengths of all the rows of each column, we find the\n # largest length value and adding to it the size of the total\n # indent, we thus obtain the width of this column.\n max_lengths = list(map(lambda i: max(map(lambda x: x[i], lengths)) + ind, range(col_count)))\n\n table_content = []\n\n for row_ind, row in enumerate(common_array):\n\n indented_row = []\n\n for col_ind, col_text in enumerate(row):\n\n # Format the ij(-row_ind-, -col_ind-) table cell\n # with the indent by the width of this column.\n text = col_text.ljust(max_lengths[col_ind])\n\n # Add left and right indents to this formatted\n # line and append it to the corresponding array.\n indented_row.append(' ' * left_indent + text + ' ' * right_indent)\n\n # Join all strings of the current column with the column separator.\n row_content = column_separator.join(indented_row)\n\n # Put the resulting string into the table row array.\n table_content.append(row_content)\n\n if row_ind != common_array_size - 1:\n # If the string is not the last one, then the bottom dividing\n # line is added to it. This line is double for the string of\n # titles (zero index) and single for all others.\n table_content.append({True: '═', False: '─'}[row_ind == 0] * len(row_content))\n\n # All lines of data received by the function are separated\n # by horizontal lines, and columns are separated by a column\n # separator. The outer frame is formed by the function below.\n #\n # The -return- operator is needed in case the table does not\n # need to be printed, but only formed.\n return self.text_into_frame(\n table_content,\n double_border=double_border,\n need_printing=need_printing\n )\n\n @staticmethod\n def show_guessable_track_titles(track_titles: list) -> None:\n \"\"\"\n Displaying the list of guessable tracks with their numbers.\n \"\"\"\n for i, title in enumerate(track_titles):\n print(i + 1, title)\n\n def show_positive_scores(\n self,\n positive_scores: list\n ) -> None:\n \"\"\"\n Displaying none-zero scores of players.\n \"\"\"\n if not positive_scores:\n # If nobody has non-zero scores then display the corresponding message.\n\n self.text_into_frame(\n [settings.players_have_0_text],\n need_printing=True\n )\n\n else:\n # Sort players data at first by name and then by scores.\n ps_srt_by_name = sorted(positive_scores, key=lambda x: x[1])\n ps_srt_by_scores = sorted(ps_srt_by_name, key=lambda x: x[2], reverse=True)\n\n # Display players scores information using a table.\n self.show_table_by_array(\n title_array=settings.positive_scores_title,\n content_array=list(map(lambda tpl: list(map(str, tpl)), ps_srt_by_scores))\n )\n\n def show_excluded_tracks_players(\n self,\n excluded_tracks: list,\n excluded_players: list\n ) -> None:\n \"\"\"\n Displaying excluded players and tracks in table form.\n \"\"\"\n if not excluded_tracks:\n return\n\n # The array for a table content.\n exclusion_information = []\n\n for ex_track, ex_player in zip(excluded_tracks, excluded_players):\n # Pair the names of melodys and players from the corresponding arrays.\n\n # Add the taken ifromation to the corresponding array.\n exclusion_information.append(\n [\n f'[x] {ex_track[0]}. {ex_track[1]}',\n f'[x] {ex_player[0]}. {ex_player[1]}'\n ]\n )\n\n self.show_table_by_array(\n title_array=settings.exclusion_title,\n content_array=exclusion_information\n )\n\n @staticmethod\n def guess_result_message(\n player_name: str,\n is_guessed: bool\n ) -> None:\n \"\"\"\n Informing whether a given answer is correct or incorrect.\n \"\"\"\n # Receive and unpack an array of text depending\n # on the correctness of the results.\n first, second = {\n True: settings.congratulation_text,\n False: settings.not_guessed_text\n }[is_guessed]\n\n print(f'{first} {player_name}, {second}\\n')\n\n def win_message(\n self,\n winner_name: str\n ) -> None:\n \"\"\"\n Displaying the message of a winner.\n \"\"\"\n self.text_into_frame(\n ['', f'{winner_name.upper()} {settings.win_message}', '']\n )\n\n def round_over_message(self, round_number: int) -> None:\n \"\"\"\n Displaying a message of the round ending with its number.\n \"\"\"\n text = settings.this_round_over_text.copy()\n text[1] = f'The {round_number} {text[1]}'\n self.text_into_frame(text)\n\n\ndef format_key_text(text: str) -> str:\n \"\"\"\n It clears a string of leading and trailing\n spaces and quotes as well converts the text\n to lower case.\n \"\"\"\n return text.strip(\" '\\\"\").lower()\n","repo_name":"Belingood/guess-the-melody-game","sub_path":"informer.py","file_name":"informer.py","file_ext":"py","file_size_in_byte":10608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"4080497166","text":"# Copyright (c) 2019, NVIDIA Corporation. All rights reserved.\r\n#\r\n# This work is made available under the Nvidia Source Code License-NC.\r\n# To view a copy of this license, visit\r\n# https://nvlabs.github.io/stylegan2/license.html\r\n\r\n# Taken from NVIDIA at https://github.com/NVlabs/stylegan2/blob/master/metrics/perceptual_path_length.py\r\n\r\n\"\"\"Perceptual Path Length (PPL).\"\"\"\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\n\r\n# ----------------------------------------------------------------------------\r\n\r\n# Normalize batch of vectors.\r\ndef normalize(v):\r\n return v / tf.sqrt(tf.reduce_sum(tf.square(v), axis=-1, keepdims=True))\r\n\r\n\r\n# Spherical interpolation of a batch of vectors.\r\ndef slerp(a, b, t):\r\n a = normalize(a)\r\n b = normalize(b)\r\n d = tf.reduce_sum(a * b, axis=-1, keepdims=True)\r\n p = tf.reshape(t, [-1, 1,1,1]) * tf.math.acos(d)\r\n c = normalize(b - d * a)\r\n d = a * tf.math.cos(p) + c * tf.math.sin(p)\r\n return normalize(d)\r\n\r\n\r\n# ----------------------------------------------------------------------------\r\n\r\n\r\ndef evaluate(act1, act2, epsilon=1e-4):\r\n distances = tf.linalg.norm(act1 - act2, axis=0)\r\n distances = distances * (1 / epsilon ** 2)\r\n # Reject outliers.\r\n lo = np.percentile(distances, 1, interpolation=\"lower\")\r\n hi = np.percentile(distances, 99, interpolation=\"higher\")\r\n filtered_distances = np.extract(\r\n np.logical_and(lo <= distances, distances <= hi), distances\r\n )\r\n return tf.reduce_mean(filtered_distances)\r\n\r\n\r\n# ----------------------------------------------------------------------------\r\n","repo_name":"stevensdavid/nvae-tf","sub_path":"perceptual_path_length.py","file_name":"perceptual_path_length.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"51"} +{"seq_id":"8182392156","text":"#!/usr/bin/env python3\n\nimport copy\nimport datetime\nimport json\nimport logging\nimport os.path\nimport sys\n\nimport boto3\nfrom fbprophet import Prophet\nimport requests\nimport pandas as pd\n\nfrom data import states_table\n\nlogging.getLogger('fbprophet').setLevel(logging.WARNING)\n\nclass State:\n roc_metrics = ['death', 'hospitalizedCurrently', 'inIcuCurrently', \n 'positiveIncrease']\n def __init__(self, name):\n self.name = name\n self.days = {}\n self.projected_days = {}\n self.rocdeath = 0\n self.totaldeath = 0\n self.newdeath = 0\n\n def add_day(self, date, name, data=None):\n if date in self.days.keys():\n raise ValueError('Already exists')\n day = Day(date)\n if not data:\n data = get_data(date=date, state=name)\n error = data.get('error')\n if error and error == True:\n raise IOError(data.get('message'))\n for k, v in data.items():\n if v is not None:\n setattr(day, k, v)\n day.calculate_positive_percentage()\n self.days[date] = day\n for metric in self.roc_metrics:\n if metric in data.keys():\n self.rate_of_change(date, metric)\n if date == max(self.days.keys()):\n if hasattr(self.days[date], 'roc_death'):\n self.roc_death = self.days[date].roc_death\n self.totaldeath = self.days[date].death\n self.newdeath = self.days[date].deathIncrease\n\n def add_today(self):\n today = datetime.datetime.today().strftime('%Y%m%d')\n if today in self.days.keys():\n raise ValueError('Already exists')\n self.add_day(today, self.name)\n\n def rate_of_change(self, day, metric):\n this_day = self.days[day]\n roc_name = 'roc_' + metric\n if hasattr(this_day, roc_name):\n raise ValueError('Already exists')\n previous_day = self.days.get(day - 1)\n todays_metric = getattr(this_day, metric)\n if previous_day and hasattr(previous_day, metric) and todays_metric:\n previous_metric = getattr(previous_day, metric)\n if previous_metric:\n setattr(this_day, roc_name, (\n (todays_metric - previous_metric) / previous_metric))\n else:\n setattr(this_day, roc_name, 0.0)\n else:\n setattr(this_day, roc_name, 0.0)\n\n\nclass Day:\n def __init__(self, date, state=None, positive=None, negative=None,\n pending=None, hospitalizedCurrently=None, \n hospitalizedCumulative=None, inIcuCurrently=None,\n inIcuCumulative=None, onVentilatorCurrently=None, \n onVentilatorCumulative=None, recovered=None, hash=None, \n dateChecked=None, death=None, hospitalized=None, total=None, \n totalTestResults=None, posNeg=None, fips=None, \n deathIncrease=None, hospitalizedIncrease=None, \n negativeIncrease=None, positiveIncrease=None, \n totalTestResultsIncrease=None, \n model_hospitalizedCurrently=None,\n model_hospitalizedCurrently_pct05=None,\n model_hospitalizedCurrently_pct95=None,\n model_inIcuCurrently=None,\n model_inIcuCurrently_pct05=None,\n model_inIcuCurrently_pct95=None,\n model_death=None, model_death_pct05=None, \n model_death_pct95=None, model_deathIncrease=None, \n model_deathIncrease_pct05=None, model_deathIncrease_pct95=None):\n self.date = date\n self.state = state\n self.positive = positive\n self.negative = negative\n self.pending = pending\n self.hospitalizedCurrently = hospitalizedCurrently\n self.hospitalizedCumulative = hospitalizedCumulative\n self.inIcuCurrently = inIcuCurrently\n self.inIcuCumulative = inIcuCumulative\n self.onVentilatorCurrently = onVentilatorCurrently\n self.onVentilatorCumulative = onVentilatorCumulative\n self.recovered = recovered\n self.hash = hash\n self.dateChecked = dateChecked\n self.death = death\n self.hospitalized = hospitalized\n self.total = total\n self.totalTestResults = totalTestResults\n self.posNeg = posNeg\n self.fips = fips\n self.deathIncrease = deathIncrease\n self.hospitalizedIncrease = hospitalizedIncrease\n self.negativeIncrease = negativeIncrease\n self.positiveIncrease = positiveIncrease\n self.totalTestResultsIncrease = totalTestResultsIncrease\n self.model_hospitalizedCurrently=model_hospitalizedCurrently\n self.model_hospitalizedCurrently_pct05=model_hospitalizedCurrently_pct05\n self.model_hospitalizedCurrently_pct95=model_hospitalizedCurrently_pct95\n self.model_inIcuCurrently=model_inIcuCurrently\n self.model_inIcuCurrently_pct05=model_inIcuCurrently_pct05\n self.model_inIcuCurrently_pct95=model_inIcuCurrently_pct95\n self.model_death=model_death\n self.model_death_pct05=model_death_pct05\n self.model_death_pct95=model_death_pct95\n self.model_deathIncrease=model_deathIncrease\n self.model_deathIncrease_pct05=model_deathIncrease_pct05\n self.model_deathIncrease_pct95=model_deathIncrease_pct95\n \n def calculate_positive_percentage(self):\n if self.positiveIncrease and self.totalTestResultsIncrease:\n positive_percentage = (\n self.positiveIncrease / self.totalTestResultsIncrease) * 100\n # Throw out days where testing oversamples positives\n if positive_percentage < 50:\n self.positive_percentage = positive_percentage\n else:\n self.positive_percentage = 0\n else:\n self.positive_percentage = 0\n\n\ndef get_data(state='all', date='daily'):\n if state == 'all':\n state_path = ''\n else: \n state_path = '{}/'.format(state.lower())\n r = requests.get(url='https://covidtracking.com/api/v1/states/{}{}.json'.format(\n state_path, date))\n return r.json()\n\n\ndef train(model_name, df, state_name, states, periods=30, frequency='D',\n history=True, plot=False):\n model = Prophet(weekly_seasonality=True, interval_width=0.95,\n changepoint_prior_scale=.1)\n train_df = df.rename(columns={model_name:'y'})\n train_df[\"ds\"] = train_df.index\n model.fit(train_df)\n\n pd.plotting.register_matplotlib_converters()\n future = model.make_future_dataframe(\n periods=periods, freq=frequency,\n include_history=history)\n forecast = model.predict(future)\n\n if plot:\n fig = model.plot(forecast)\n axes = fig.get_axes()\n axes[0].set_title('{} - {}'.format(state_name, model_name), size=20)\n axes[0].set_xlabel('Date')\n axes[0].set_ylabel(model_name)\n\n model_records = forecast.to_dict('records')\n for record in model_records:\n record_date = int(record['ds'].strftime('%Y%m%d'))\n if record_date not in states[state_name].days.keys():\n states[state_name].days[record_date] = Day(\n date=record_date, state=state_name)\n setattr(states[state_name].days[record_date], \n 'model_{}'.format(model_name),\n record.get('yhat'))\n setattr(states[state_name].days[record_date], \n 'model_{}_pct05'.format(model_name),\n record.get('yhat_lower'))\n setattr(states[state_name].days[record_date], \n 'model_{}_pct95'.format(model_name),\n record.get('yhat_upper'))\n for day in states[state_name].days.keys():\n if not hasattr(states[state_name].days[day],\n 'model_{}'.format(model_name)):\n setattr(states[state_name].days[day],\n 'model_{}'.format(model_name),\n None)\n setattr(states[state_name].days[day],\n 'model_{}_pct05'.format(model_name),\n None)\n setattr(states[state_name].days[day],\n 'model_{}_pct95'.format(model_name),\n None)\n\n\ndef full_update(ignore_history=False, plot=False, export=True, export_type='s3',\n state='all', date='daily', s3_bucket='cv19.report'):\n if not ignore_history and not is_updated():\n return\n\n selected_models = ['death', 'deathIncrease', 'inIcuCurrently', \n 'hospitalizedCurrently', 'positiveIncrease',\n 'positive_percentage']\n agg_models = []\n for model in selected_models:\n agg_models += ['model_{}'.format(model), \n 'model_{}_pct05'.format(model),\n 'model_{}_pct95'.format(model)]\n metrics = selected_models + agg_models\n states = {}\n data_set = get_data(state=state, date=date)\n data_set.reverse()\n for data in data_set:\n if data['state'] not in states.keys():\n states[data['state']] = State(data['state'])\n states[data['state']].add_day(\n date=data['date'], name=data['state'], data=data)\n sorted_states = sorted(\n states.values(), key=lambda state: state.newdeath, reverse=True)\n\n for state in sorted_states:\n df = pd.DataFrame(\n [{'date': pd.to_datetime(\n day.date, format='%Y%m%d', errors='ignore'),\n 'death': day.death,\n 'deathIncrease': day.deathIncrease,\n 'inIcuCurrently': day.inIcuCurrently,\n 'hospitalizedCurrently': day.hospitalizedCurrently,\n 'positiveIncrease': day.positiveIncrease,\n 'positive_percentage': day.positive_percentage,\n } for day in state.days.values() if hasattr(day, 'death')])\n df.date = pd.to_datetime(df.date)\n df.set_index('date', inplace=True)\n \n for model_name in selected_models:\n if getattr(df, model_name).count() > 5:\n train(model_name=model_name, df=df, state_name=state.name, \n states=states, plot=True)\n\n # There is too much delta between different hospitalization reporting to\n # generate meaningful trends ATM...\n us_metrics = []\n for metric in metrics:\n if metric.startswith('model_hospitalizedCurrently'):\n pass\n elif metric.startswith('model_inIcuCurrently'):\n pass\n else:\n us_metrics.append(metric)\n combined = prepare_combined(states=states, metrics=us_metrics, plot=plot)\n\n if export:\n export_data(states=states, metrics=metrics, combined=combined,\n export_type=export_type, s3_bucket=s3_bucket)\n\n\ndef export_data(states, metrics, combined=None, export_type='s3', \n s3_bucket='cv19.report'):\n if export_type == 's3':\n export_func = write_json_s3\n elif export_type == 'file':\n export_func = write_file\n else:\n raise ValueError\n\n # Export states\n state_codes = ['US']\n for state_name, state in states.items():\n if state.totaldeath:\n state_codes.append(state_name)\n export = []\n for day in state.days.values():\n datestr = str(day.date)\n record = {\n 'date': '{}-{}-{}'.format(datestr[:4], \n datestr[4:6], \n datestr[6:])}\n for metric_name in metrics:\n if hasattr(day, metric_name):\n record[metric_name] = getattr(day, metric_name)\n export.append(record)\n\n export_func(filename='{}.json'.format(state_name.lower()),\n json_data=export, s3_bucket=s3_bucket)\n\n # Export Combined\n if combined:\n export = []\n for day in combined:\n record = {'date': day['date'].strftime('%Y-%m-%d')}\n for metric_name in metrics:\n metric = day.get(metric_name)\n record[metric_name] = metric\n export.append(record)\n export.sort(key=lambda d: d['date'])\n export_func(filename='us.json', json_data=export, s3_bucket=s3_bucket)\n\n state_code_table = [state for state in states_table if state['value'] in state_codes]\n export_func(filename='states.json', json_data=state_code_table, \n s3_bucket=s3_bucket)\n\n\ndef prepare_combined(states, metrics, plot=False):\n dates = set()\n for state in states.values():\n for date in state.days.keys():\n dates.add(date)\n combined = []\n future_limit = int(\n (datetime.datetime.today() + \n datetime.timedelta(days=30)).strftime('%Y%m%d'))\n for date in dates:\n if date > 20200225 and date <= future_limit:\n day = {\n 'date': pd.to_datetime(date, format='%Y%m%d')\n }\n\n for model in metrics:\n points = [getattr(state.days[date], model) for\n state in states.values() if\n state.days.get(date) and \n hasattr(state.days[date], model) and\n getattr(state.days[date], model) is not None]\n total = sum(points)\n if total:\n if 'positive_percentage' in model:\n day[model] = total / len(points)\n else:\n day[model] = total\n else:\n day[model] = None\n\n combined.append(day)\n df = pd.DataFrame(combined)\n df.set_index('date', inplace=True)\n\n # Needed to compute rolling avg\n df.sort_values(by=['date'], inplace=True, ascending=True)\n\n if plot:\n import matplotlib.pyplot as plt\n fig, ax1 = plt.subplots(1,1, figsize=(15,10))\n ax1.title.set_text('Combined - {} deaths'.format(int(df.death.max())))\n df.model_death.plot(color='red', label='Model', linestyle=\":\")\n df.death.plot(ax=ax1, color='blue', label='Actual')\n ax1.set_ylabel('Deaths')\n ax1.legend(loc=2)\n ax2 = ax1.twinx()\n df.deathIncrease.plot(ax=ax2, color='lightgreen', label='Daily')\n ax2.set_ylabel('Daily')\n ax2.legend(loc=0)\n df['DailyMA'] = df.deathIncrease.rolling(7).mean()\n pd.set_option('display.max_rows', None)\n df.DailyMA.plot(ax=ax2, color='green', label='DailyMA')\n ax2.set_ylabel('DailyMA')\n ax2.legend(loc=1)\n plt.show()\n\n return combined\n\n\ndef write_json_s3(filename, json_data, path='api/', s3_bucket='cv19.report'):\n s3 = boto3.resource('s3')\n s3object = s3.Object(s3_bucket, '{}{}'.format(\n path, filename))\n s3object.put(\n Body=(bytes(json.dumps(json_data).encode('UTF-8'))),\n ContentType='application/json')\n\n\ndef write_file(filename, json_data, path=None, s3_bucket=None):\n with open(filename, 'w') as f:\n json.dump(json_data, f)\n\n\ndef is_updated():\n r = requests.get(url='https://cv19.report/api/us.json')\n if r.status_code != 200:\n return True\n else:\n data = r.json()\n dates = [event['date'] for event in data if event.get('death')]\n last_date_local = int(dates[-1].replace('-', ''))\n r = requests.get(url='https://covidtracking.com/api/v1/us/current.json')\n last_date_remote = r.json()[0]['date']\n print(last_date_local, last_date_remote)\n if last_date_remote > last_date_local:\n return True\n\nif __name__ == '__main__':\n print(sys.argv)\n if len(sys.argv) > 1:\n full_update(ignore_history=sys.argv[1])\n else:\n full_update()\n","repo_name":"alexanderyoung/cv19-report","sub_path":"covid.py","file_name":"covid.py","file_ext":"py","file_size_in_byte":15888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"74390993117","text":"import random\nimport keyboard\nimport time\nimport csv\nimport datetime\nimport os\n\ndef main():\n key_mapping = {1: '1', 2: '2', 3: '3'}\n score = 0\n highest_score = get_highest_score()\n\n if not os.path.isfile('scores.csv'):\n create_scores_file()\n\n while True:\n target_number = random.randint(1, 3)\n print(\"Target Number:\", target_number)\n print(\"Score:\", score)\n\n try:\n pressed_key = keyboard.read_event().name\n if pressed_key == key_mapping[target_number]:\n score += 100\n print(\"Correct! You scored 100 points.\")\n else:\n print(\"Wrong key! Game over.\")\n if score > highest_score:\n highest_score = score\n print(\"(Best)\")\n save_score(score)\n score = 0\n print(f\"Highest Score: {highest_score}\")\n print(\"Press Space to reset...\")\n keyboard.wait('space')\n except KeyboardInterrupt:\n break\n time.sleep(1)\n\ndef save_score(score):\n now = datetime.datetime.now()\n date_time = now.strftime(\"%d/%m/%Y %H:%M\")\n with open('scores.csv', mode='a', newline='') as file:\n writer = csv.writer(file)\n writer.writerow([date_time, score])\n\ndef get_highest_score():\n try:\n with open('scores.csv', mode='r') as file:\n reader = csv.reader(file)\n next(reader) # Skip the header row\n scores = [(int(score), date) for date, score in reader]\n if scores:\n highest = max(scores, key=lambda x: x[0])\n return highest[0]\n except FileNotFoundError:\n pass\n return 0\n\ndef create_scores_file():\n with open('scores.csv', mode='w', newline='') as file:\n writer = csv.writer(file)\n writer.writerow([\"Date/Time\", \"Score\"])\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"xtianbong/roger_game","sub_path":"cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"24345988757","text":"from tkinter import *\r\nfrom tkinter.scrolledtext import ScrolledText\r\nimport paramiko\r\nimport time\r\nimport os\r\nimport sys\r\nfrom openpyxl.styles.borders import Side\r\n\r\nfields = 'IP Address :','Login :', 'Password :', 'Command :'\r\ndef Login(entries,root):\r\n text=[]\r\n for entry in entries:\r\n text.append(entry[1].get())\r\n print(text)\r\n ssh = paramiko.SSHClient()\r\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n ssh.connect(text[0], username=text[1], password=text[2])\r\n stdin, stdout, stderr = ssh.exec_command(text[3])\r\n u=stdout.readlines()\r\n output = ''.join(u)\r\n sc=ScrolledText(root)\r\n sc.pack(side=LEFT)\r\n sc.insert(END, output)\r\n \r\n \r\ndef makeform(root, fields):\r\n entries = []\r\n for field in fields:\r\n row = Frame(root)\r\n lab = Label(row, width=15, text=field, anchor='w')\r\n ent = Entry(row)\r\n row.pack(side=TOP, fill=X, padx=5, pady=5)\r\n lab.pack(side=LEFT)\r\n ent.pack(side=LEFT, expand=NO, fill=X)\r\n entries.append((field, ent))\r\n la = Label(root, width=15, text=\"Output :\", anchor='w')\r\n la.pack(side=LEFT)\r\n return entries\r\n\r\nif __name__ == '__main__':\r\n root = Tk()\r\n root.title(\"SSH Login Application\")\r\n ents = makeform(root, fields)\r\n root.bind('', (lambda event, e=ents: Login(e))) \r\n b1 = Button(root, text='Login',command=(lambda e=ents:Login(e,root)))\r\n b1.pack(side=LEFT, padx=5, pady=5)\r\n b2 = Button(root, text='Quit', command=root.quit)\r\n b2.pack(side=LEFT, padx=5, pady=5)\r\n root.mainloop()","repo_name":"II-VSB-II/GUI-SSH","sub_path":"GUI-SSH.py","file_name":"GUI-SSH.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"73554583517","text":"#For refrence https://wiki.agiloft.com/display/HELP/Sample+Python+Scripts\r\n\r\nimport sys\r\nfrom ALget import ALget\r\nfrom ALset import ALset\r\ndef action(inputXMLFile, outputXMLFile):\r\n input = ALget(inputXMLFile)\r\n out = ALset(outputXMLFile)\r\n groups = input.globalVariable('my_groups')\r\n groupAllowedToClose = \"QA\"\r\n if groupAllowedToClose not in groups.split(\",\") and input.value(\"wfstate\") == \"Closed\" and input.value(\"wfstate\", input.oldRecordsNamesList()[0]) != \"Closed\":\r\n # Set a field value. In this case, we set the status field\r\n # to its old value\r\n out.recordField(\"wfstate\", input.value(\"wfstate\", input.oldRecordsNamesList()[0]))\r\n print(\"Restore state\")\r\n out.exitAction(ALset.ACCEPT)\r\n out.save()\r\n action(sys.argv[1], sys.argv[2])","repo_name":"Aanjul/python_projects","sub_path":"Script_checks_if_user belongs_to_QA_group_&_blocks_non-QA_users_from_closing_ticket.py","file_name":"Script_checks_if_user belongs_to_QA_group_&_blocks_non-QA_users_from_closing_ticket.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"51"} +{"seq_id":"45437999121","text":"import numpy as np\nfrom matplotlib.lines import Line2D\n\nfrom project1.bezier_builder import BezierBuilder2D\nfrom project1.deboor import deboor_to_bezier\n\n\nclass DeboorBuilder2D(BezierBuilder2D):\n def __init__(self, ax_2d):\n super(DeboorBuilder2D, self).__init__(ax_2d)\n\n # curves and their corresponding control points\n self.segments = []\n self.line_bezier_points_2d = []\n self.line_bezier_curve_2d = []\n self.bezier_points_style = {'linestyle': '--', 'marker': 'o'}\n\n self.last_point = False\n\n def create_curve(self, *args):\n \"\"\"\n Given control points, build Bezier curve\n :param args: control points [x, y, z, ...]\n :return: Bezier curve\n \"\"\"\n curve = self.bezier.create_curve(list(zip(*args)))\n return np.transpose(curve)\n\n def update_points_and_curve_2d(self):\n # Update de Boor control points\n self.line_points_2d.set_data(self.points_x, self.points_y)\n\n # Simply do nothing when segments is empty\n if len(self.segments) == 0:\n return\n\n # Update each segments\n for i, points in enumerate(self.line_bezier_points_2d):\n seg = self.segments[i]\n curve = self.line_bezier_curve_2d[i]\n points.set_data(seg[:, 0], seg[:, 1])\n curve.set_data(*self.create_curve(seg[:, 0], seg[:, 1]))\n\n # Create new segment when it is not the last point\n if not self.last_point:\n seg = self.segments[-1]\n bezier_points_2d = Line2D(seg[:, 0], seg[:, 1],\n **self.bezier_points_style)\n curve = self.create_curve(seg[:, 0], seg[:, 1])\n bezier_curve_2d = Line2D(curve[0], curve[1],\n **self.bezier_curve_style)\n self.line_bezier_curve_2d.append(\n self.ax_2d.add_line(bezier_curve_2d))\n self.line_bezier_points_2d.append(\n self.ax_2d.add_line(bezier_points_2d))\n\n def on_button_press(self, event):\n if event.inaxes != self.ax_2d:\n return\n if self.last_point:\n return\n\n # Add control point\n self.points_x.append(event.xdata)\n self.points_y.append(event.ydata)\n\n # Update segments, usually the last two are modified\n self.segments = deboor_to_bezier(\n list(zip(self.points_x, self.points_y)))\n self.update_points_and_curve_2d()\n \n self.canvas.draw()\n\n def on_key_press(self, event):\n \"\"\"\n :param event:\n :return:\n \"\"\"\n if event.key == ' ':\n self.last_point = True\n # TODO: maybe deboor stuff should be put into a class, since last\n # point only modifies the last two segments, we don't need to\n # calculate all the previous segments again\n self.segments = deboor_to_bezier(\n list(zip(self.points_x, self.points_y)), True)\n self.update_points_and_curve_2d()\n elif event.key == 'r':\n self.reset()\n\n self.canvas.draw()\n\n def reset(self):\n self.points_x = []\n self.points_y = []\n self.line_points_2d.set_data([], [])\n for points in self.line_bezier_points_2d:\n points.remove()\n for curve in self.line_bezier_curve_2d:\n curve.remove()\n self.line_bezier_curve_2d = []\n self.line_bezier_points_2d = []\n self.last_point = False\n","repo_name":"versatran01/cis515","sub_path":"project1/deboor_builder.py","file_name":"deboor_builder.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"19041803724","text":"#Dhaniston R\r\n\r\nimport sys\r\n\r\ncontacts = { }\r\n\r\ndef menu():\r\n print(\"***************** MENU *******************\")\r\n print(\"press 1 to add a new contact to the contact book.\")\r\n print(\"press 2 to display all contacts\")\r\n print(\"press 3 to delete an existing contact\")\r\n print(\"press 4 if you want to Exit Contact Book.\")\r\n \r\n print(\"press any number from 6-9 to display Menu\")\r\n print(\"----------------------------------------------\")\r\n print(\" CONTACT BOOK \")\r\nmenu()\r\ndef display():\r\n for key, value1 in contacts.items():\r\n print(key, \":\", value1)\r\n\r\ndef checkAlreadyExist(number,email):\r\n for value1 in contacts.values():\r\n if number in value1:\r\n return 1\r\n if email in value1:\r\n return 2 \r\n return 0\r\n\r\ndef displayLastUpdatedPerson(name):\r\n lastPerson=contacts.get(name)\r\n print(name, \":\",lastPerson) \r\nwhile True:\r\n\r\n try:\r\n choice = int(input(\"Please enter your choice:\"))\r\n \r\n if choice == 1:\r\n Name = input(\"Enter Name:\").upper()\r\n Number = (input(\"Enter 10 digit mobile number: \"))\r\n Email = input(\"Enter e-mail address:\")\r\n if checkAlreadyExist(Number,Email)==1:\r\n print(\"Number already exist\")\r\n elif checkAlreadyExist(Number,Email)==2:\r\n print(\"Email already exist\") \r\n\r\n else :\r\n if len(Number) == 10:\r\n contacts.update({Name:[\"Number\",Number,\"Email\",Email]})\r\n print(\" CONTACT\")\r\n displayLastUpdatedPerson(Name)\r\n else:\r\n print(\"Number is invalid.Please try again.\")\r\n\r\n \r\n elif choice == 3:\r\n delete = input(\"Please enter the name of the contact you wish to remove:\")\r\n del contacts[delete]\r\n print(\" CONTACTS\")\r\n display()\r\n elif choice == 4:\r\n print(\"Thank you for using the Contact Book!\")\r\n break\r\n elif choice == 2:\r\n print(\" CONTACTS\")\r\n display()\r\n else:\r\n menu()\r\n except :\r\n \r\n \r\n print(\"Invalid Command\") \r\n \r\n ","repo_name":"dhanishton/python-assignment","sub_path":"assignment1.py","file_name":"assignment1.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"22392812037","text":"'''\n\t4. Partition\n\t\t\tWrite code to partition a linked list around a value x, such \n\t\t\tthat all nodes less than x come before all nodes greater than \n\t\t\tor equal to x. IF x is contained within the list, the values \n\t\t\tof x only need to be after the elements less than x. The \n\t\t\tpartition element x can appear anywhere in the `right partition`; \n\t\t\tIt does not need to appear between the left and right partitions.\n\t\t\tExample:\n\t\t\t\tI: 3-> 5-> 8-> 5 ->10-> 2-> 1\n\t\t\t\tO: 3-> 1-> 2-> 10-> 5-> 5-> 8\n\n\tThoughts:\n\t\tWe can just bump all of the items that are greater than k to the tail.\n\t\tThis will take us just the time to traverse the list.\n\n\n'''\nimport sys\nsys.path.append('/Users/tannerleewoody/Workspace/google/CtCI/2_linkedLists/')\nfrom LinkedList import LinkedList\n\ndef partitionLL(ll, k):\n\t''' Partition linkedlist around value k '''\n\tcur = ll.head\n\tcnt = 0\n\ti = 0\n\tl = len(ll)\n\twhile i= 15 or b >= 15) and (abs(b - a >= 2))\n y = a == 15 or b == 15 or (a == 7 and b == 0) or (b == 7 and a == 0)\n while a != 15 and b != 15:\n a = a + 1\n b = b + 1\n print(a,b)\n\n\n\nbooleans()\n","repo_name":"jorian/Zelle","sub_path":"Exercises 8/8.0.3.py","file_name":"8.0.3.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"3437931479","text":"from .utils.cmd_types import CmdTypes\n\n\nclass Parser:\n \"\"\"Handles the parsing of a single .vmfile.\n\n Encapsulates access to the input code. It reads VM commands, parses\n them, and provides convenient access to their components. In\n addition, it removes all white space and comments.\n \"\"\"\n\n def __init__(self, file):\n \"\"\"Opens the input stream and gets ready to parse it.\"\"\"\n\n self.file = file\n self.cmd = None\n self.eof = False\n self.cmd_type = None\n self.cmd_arg1 = None\n self.cmd_arg2 = None\n self.__enter__() # might be a bad idea\n\n def __enter__(self):\n \"\"\"Allows usage of with Parser(file) as p:\n\n Enters context.\n \"\"\"\n self.fd = open(self.file)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"Allows usage of with Parser(file) as p:\n\n Auto-closes file.\n \"\"\"\n self.fd.close()\n\n def __iter__(self):\n for line in self.fd:\n self.cmd_type = None # reset initial values ..\n self.cmd_arg1 = None\n self.cmd_arg2 = None\n self.cmd = line\n self.clean()\n if self.cmd == '':\n continue # only yield lines with actual code ..\n yield self.cmd\n else:\n self.eof = True\n self.__exit__(None, None, None) # might be a bad idea\n\n def clean(self):\n \"\"\"Remove all whitespace and comments from current line.\"\"\"\n\n self.cmd = self.cmd.split(\"//\")[0]\n # self.cmd = ''.join(self.cmd.split())\n self.cmd = self.cmd.strip() # remove outer whitespace only.\n\n def has_more_commands(self):\n \"\"\"Are there more commands in the input?\n\n :returns: boolean\n \"\"\"\n return not self.eof\n\n def advance(self):\n \"\"\"Reads the next command from the input.\n\n Makes it the current command. Should be called only if\n 'has_more_commands()' is True. Initially there is no current\n command.\n Usage:\n\n while p.has_more_commands():\n p.advance()\n \"\"\"\n\n try: # kind of hacky ... use for loop instead!\n self.cmd = next(self.__iter__())\n except StopIteration:\n pass\n\n def command_type(self):\n \"\"\"Returns the type of the current VM command.\n\n C_ARITHMETIC is returned for all the arithmetic\n commands.\n\n :returns: C_ARITHMETIC, C_PUSH, C_POP, C_LABEL, C_GOTO, C_IF, C_FUNCTION, C_RETURN, C_CALL\n\n Note: sets cmd_type, cmd_arg1, cmd_arg2\n Note: modifies self.cmd\n \"\"\"\n if self.cmd_type is not None:\n return self.cmd_type # should be true only after first run ..\n\n if any([self.cmd == c for c in (\"add\", \"sub\", \"neg\", \"eq\", \"gt\", \"lt\", \"and\", \"or\", \"not\")]):\n self.cmd_type = CmdTypes.C_ARITHMETIC\n self.arg1() # sets cmd_arg1\n return self.cmd_type\n elif self.cmd[0:4] == \"push\":\n self.cmd_type = CmdTypes.C_PUSH\n self.arg2() # sets cmd_arg1, cmd_arg2\n return self.cmd_type\n elif self.cmd[0:3] == \"pop\":\n self.cmd_type = CmdTypes.C_POP\n self.arg2() # sets cmd_arg1, cmd_arg2\n return self.cmd_type\n elif self.cmd[0:5] == \"label\":\n self.cmd_type = CmdTypes.C_LABEL\n self.arg1()\n return self.cmd_type\n elif self.cmd[0:4] == \"goto\":\n self.cmd_type = CmdTypes.C_GOTO\n self.arg1()\n return self.cmd_type\n elif self.cmd[0:7] == \"if-goto\":\n self.cmd_type = CmdTypes.C_IF\n self.arg1()\n return self.cmd_type\n elif self.cmd[0:8] == \"function\":\n self.cmd_type = CmdTypes.C_FUNCTION\n self.arg2()\n return self.cmd_type\n elif self.cmd[0:6] == \"return\":\n self.cmd_type = CmdTypes.C_RETURN\n return self.cmd_type\n elif self.cmd[0:4] == \"call\":\n self.cmd_type = CmdTypes.C_CALL\n self.arg2()\n return self.cmd_type\n return None\n\n def arg1(self):\n \"\"\"Returns the first arg. of the current command.\n\n In the case of C_ARITHMETIC, the command itself (add, sub, etc.)\n is returned. Should not be called if the current command is\n C_RETURN.\n\n :returns: string\n\n As self.cmd_arg1 is reset each iteration I should be able\n to return it if it exits.\n If there is no self.cmd_type ... I should be able to call it\n and have it only run once.\n\n Note: sets cmd_type, cmd_arg1, cmd_arg2\n Note: modifies self.cmd\n \"\"\"\n\n if self.cmd_arg1 is not None:\n return self.cmd_arg1\n if self.cmd_type is None:\n self.command_type() # should only run once ...\n\n if self.cmd_type == CmdTypes.C_ARITHMETIC:\n self.cmd_arg1 = self.cmd\n return self.cmd_arg1\n elif any([self.cmd_type == c for c in (CmdTypes.C_PUSH, CmdTypes.C_POP, CmdTypes.C_FUNCTION, CmdTypes.C_CALL)]):\n self.arg2() # sets cmd_arg1, cmd_arg2\n return self.cmd_arg1\n elif any([self.cmd_type == c for c in (CmdTypes.C_LABEL, CmdTypes.C_GOTO, CmdTypes.C_IF)]):\n self.cmd, self.cmd_arg1 = self.cmd.split()\n return self.cmd_arg1\n return None\n\n def arg2(self):\n \"\"\"Returns the second argument of the current command.\n\n Should be called only if the current command is C_PUSH, C_POP,\n C_FUNCTION, or C_CALL.\n\n :returns: int\n Note: sets cmd_type, cmd_arg1, cmd_arg2\n Note: modifies self.cmd\n \"\"\"\n\n if self.cmd_arg2 is not None:\n return self.cmd_arg2\n if self.cmd_type is None:\n self.command_type() # should only run once ...\n\n if any([self.cmd_type == c for c in (CmdTypes.C_PUSH, CmdTypes.C_POP, CmdTypes.C_FUNCTION, CmdTypes.C_CALL)]):\n self.cmd, self.cmd_arg1, self.cmd_arg2 = self.cmd.split()\n self.cmd_arg2 = int(self.cmd_arg2)\n return self.cmd_arg2\n return None\n","repo_name":"klondikemarlen/VMTranslator","sub_path":"vm_translator/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":6159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"70169379360","text":"import asyncio\nimport time\nfrom dotenv import load_dotenv\nimport os\nimport discord\nfrom discord.commands import Option\nfrom echo import Echo\n\nload_dotenv()\ntoken = os.getenv('DISCORD_TOKEN')\nbot = discord.Bot()\necho = Echo()\n\n\n# makes sure that the bot is fully ready before accepting any slash commands\n@bot.event\nasync def on_ready():\n print(f\"logged in as {bot.user}\")\n\n\n@bot.slash_command()\nasync def pull_server(ctx,\n location=Option(str,\n description=\"Choose location of server, options are in the bot's description\",\n required=True),\n hold_time=Option(int,\n description=\"How long should the bot stay in the server?, max of 300 seconds\",\n required=False,\n default=120,\n min_value=60,\n max_value=300)\n ):\n\n # type hints to make using some methods easier later in the function\n hold_time: int\n location: str\n\n try:\n hold_time = int(hold_time)\n except TypeError:\n # user didn't define a set amount of seconds\n hold_time = 120\n\n location = location.strip().lower()\n\n if hold_time > 300:\n await ctx.respond(\"Cannot hold server for more than 300 seconds at a time\")\n else:\n if location not in echo.server_dict.keys():\n await ctx.respond(f\"Invalid server location, valid locations are {', '.join(list(echo.server_dict.keys()))}\")\n else:\n echo.open_temp_server(location=echo.server_dict[location])\n await ctx.respond(f\"Opening {location} server...\")\n # sleep to allow server to spin up and give local api access\n await asyncio.sleep(45)\n await ctx.send(echo.create_spark_link())\n # hold time is there to allow the players to get into the lobby themselves\n # means the bot doesn't have to stay there forever and allow it to create other servers\n time.sleep(hold_time)\n os.system(\"TASKKILL /F /IM echovr.exe\") # closes echovr.exe\n\n\nbot.run(token)\n","repo_name":"OneillWillam17/echo-server-slash-commands","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"9331140439","text":"from rest_framework import serializers\n\nfrom apps.comment.models import Comment, Children\n\n\nclass ChildrenSerializer(serializers.ModelSerializer):\n owner = serializers.HiddenField(default=serializers.CurrentUserDefault())\n\n class Meta:\n model = Children\n read_only_fields = ('id', 'owner')\n fields = (\n 'id',\n 'title',\n 'parent',\n 'create_at'\n )\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Comment\n read_only_fields = ('id', 'owner')\n fields = (\n 'id',\n 'comment',\n 'star',\n 'create_at',\n 'product',\n )","repo_name":"Saidulloh/Shop-API","sub_path":"apps/comment/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"10385687768","text":"#!/usr/bin/env python\n#file navigation tools\nfrom glob import glob\nimport os\n#image analysis library\nfrom skimage import io\n#jupyter notebook img display\n#import stackview\n#The fundamental package for scientific computing with Python\nimport numpy as np\n#python image viewer\nimport napari\n#excel for python\nimport pandas as pd\n\nimport csv\n#file navigation tools\nfrom glob import glob\nimport time\nfrom scipy.ndimage import shift\n\nimport pprint\nimport textwrap\n\nimport bigfish\nimport bigfish.stack as stack\nimport bigfish.detection as detection\nimport bigfish.multistack as multistack\nimport bigfish.plot as plot\nimport bigfish.classification as classification\nfrom skimage.measure import regionprops\nfrom cellpose.io import imread\nfrom cellpose import core, utils, io, models, metrics\n\nimport cv2 as cv\nfrom typing import List\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport shapely\nfrom shapely import Point, Polygon\nfrom shapely import intersection\n\nimport time\n\ndef print_info(msg):\n print('\\n')\n print(''.center(70, '-'))\n print(textwrap.fill(msg, 70))\n print(''.center(70, '-'))\n\n\n# =============================================================================\n# This function allows you to ask a yes or no question which either returns a\n# counter 'y' or 'n'. I use this in other functions when deciding to interact\n# with the user. I have usually used this to exit a while True: loop\n# =============================================================================\ndef yes_or_no(question):\n counter = ''\n while counter == '':\n #The user is asked a yes or no question.\n user = input('\\n\\n!!!\\n'+question+'(y/n)\\n!!!\\n')\n #If they don't either input yes or no in the accepted format the while loop is not broken.\n if user.lower() in ['yes', 'y']:\n counter += 'y'\n #While loop broken and programme run can continue.\n return counter\n elif user.lower() in ['no', 'n']:\n counter+='n'\n #While loop broken and programme run can continue.\n return counter\n else:\n print_info('I\\'m sorry I don\\'t understand... Please enter (y\\\\n) in the accepted format')\n\n\n# =============================================================================\n# This function takes the path of a z-stack tif file and splits the stack\n# in this case into 4 channels with 41 slices in each.\n# =============================================================================\ndef read_stack(path_array, number_of_slices_per_channel, channels):\n img = io.imread(path_array[0])\n img = np.expand_dims(img,1)\n img = np.reshape(img,(len(channels),number_of_slices_per_channel,2304,2304))\n return path_array, img\n\n# =============================================================================\n# This function calculates the Laplacian variance of an image.\n# =============================================================================\ndef calulating_laplacian_variance(img):\n return np.var(cv.Laplacian(img, cv.CV_64F, ksize=21))\n\n# =============================================================================\n# This function uses the calulating_laplacian_variance function to calulcate\n# the Laplacian variance for each image in a channel image stack and returns\n# a list of the Laplacian variance of each slice in a channel in a list.\n# =============================================================================\ndef focus_metric_of_each_z_slice(channel_stack):\n lap_var_of_each_z_slice = []\n # for each image in the stack of one fluorescent channel\n for img in channel_stack:\n # calculate the Laplacian variance and append to a list\n lap_var_of_each_z_slice.append(calulating_laplacian_variance(img))\n return lap_var_of_each_z_slice\n\n# =============================================================================\n# This function returns a list of \"x\" indices of the most in focus slices in a\n# channel stack using the top_x_slices function.\n# =============================================================================\ndef choosing_in_focus_slices(channel_stack, number_of_slices):\n # list of the Laplacian focus metric for each image in a channel stack\n focus_list_all = focus_metric_of_each_z_slice(channel_stack)\n # return list of \"x\" indices of slices with the highest scoring focus metric\n top_in_focus_slices = top_x_slices(focus_list_all, number_of_slices)\n return top_in_focus_slices\n# =============================================================================\n# This function returns the \"x\" indices of the most in focus slices\n# in terms of a list of image focus scores.\n# =============================================================================\ndef top_x_slices(focus_list_all, x):\n top_in_focus_slices = []\n # until the number of \"x\" in focus slices has been reached this loop continues\n while len(top_in_focus_slices)<=x:\n # the index of the highest scoring Laplacian focus metric is saved\n max_index = focus_list_all.index(max(focus_list_all))\n # this index is appended to a list\n top_in_focus_slices.append(max_index)\n # this maximum is removed from the original list without changing the\n # indices of the remaning focus scores.\n focus_list_all[max_index] = 0\n # the list of the indices of the top scoring slices is sorted so they are in\n # ascending order\n top_in_focus_slices.sort()\n return top_in_focus_slices\n\n# =============================================================================\n# This function computes the maximum intensity projection using the 'most in-fo\n# cus' slices. These focussed slices can be input manually or using the\n# Laplacian variance.\n# =============================================================================\ndef generating_maximum_projection(channel_array, focus):\n # at each position in the image choose the maximum value of all the slices\n return np.amax(channel_array[focus],axis=0,keepdims=False)\n\n# =============================================================================\n# This function is a simple wrapper for a bigfish function removing the\n# background of an image - currently unused in the script.\n# =============================================================================\ndef projection_filter(channel_projection):\n return stack.remove_background_gaussian(channel_projection, sigma=3)\n\n# =============================================================================\n# This function creates a dictionary of the channels and their corresponding\n# image stacks.\n# =============================================================================\ndef split_stack(image, channels, colors):\n image_dictionary = {}\n for i in range(0,len(image)):\n image_dictionary[channels[i]] = (colors[i], image[i])\n return image_dictionary\n\n# =============================================================================\n# This function adds to the napari viewer with the Maximum Intensity Projections\n# (MIP) of the channels.\n# =============================================================================\ndef napari_view(files, zproject, channels, colors, scale=(0.0648, 0.0648)):\n # add the DIC image to the napari viewer\n viewer.add_image(io.imread(files[1]), name='DIC', opacity=0.3, blending='opaque', scale=scale)\n # add each MIP using the channel names to identify each one within the viewer\n for i in range(zproject.shape[0]):\n viewer.add_image(zproject[i,...],name=channels[i],colormap=colors[i],opacity=1, blending='additive', scale=scale)\n\n# =============================================================================\n# This function adds to the napari viewer with the MIPs with the corresponding\n# spots for each channel.\n# =============================================================================\ndef napari_view_spots(files, zproject, spots, channels, colors, scale):\n # for each spot channel (i.e. not DAPI) add the detected spot coordinates\n # to the napari viewer\n for i in range(len(channels)):\n if channels[i] != 'DAPI':\n # use the names of each channel to identify each layer of detected spots\n coordinates_2d = spots[channels[i]][:, 1:]\n viewer.add_points(coordinates_2d, name=str(channels[i])+' spot', opacity=1, edge_color='red', face_color='transparent', scale=scale)\n\n# =============================================================================\n# This function adds to the napari viewer with cell masks generated by the\n# segmentation model.\n# =============================================================================\ndef napari_view_masks(masks, scale, name, mask_colors=['pink']):\n # add the masks parsed in as a shape layer\n viewer.add_shapes(masks, shape_type='polygon', edge_width=2, edge_color=colors[0], face_color='transparent', scale=scale, name=name)\n\n# =============================================================================\n# This function adds to the napari viewer with cell masks generated by the\n# segmentation model.\n# =============================================================================\ndef napari_check_and_edit_masks(masks, dic_image, mask_type):\n viewer = napari.Viewer()\n viewer.add_image(io.imread(dic_image), name='DIC', opacity=1, blending='opaque')\n # check whether the masks need to be loaded first\n if type(masks) == str:\n masks = io.imread(masks)\n\n viewer.add_labels(masks, name='Segmentation '+mask_type)\n\n# =============================================================================\n# This function adds to the napari viewer with cell masks generated by the\n# segmentation model.\n# =============================================================================\ndef loading_corrected_masks(masks, corrected_mask_path):\n from skimage import io\n if corrected_mask_path != None:\n masks_to_continue_with = io.imread(corrected_mask_path)\n if masks_to_continue_with.dtype == 'uint32':\n masks_to_continue_with = masks_to_continue_with.view('int32')\n else:\n masks_to_continue_with = masks\n return masks_to_continue_with\n\n# =============================================================================\n# This function creates a dictionary of the channels and their corresponding\n# MIPs. These are named by adding a \"P\" (for projection) to all channels\n# except the first due to specific naming customs of bigfish. Channel names can't\n# be repeated.\n# =============================================================================\ndef create_mip_projection_dict(fluor_channels, mip_projection):\n projection_dictionary={}\n # for the index of each channel\n for i in range(len(fluor_channels)):\n # if it is the first channel\n if i == 0:\n # then in the dictionary this can simply be the channel name\n projection_dictionary[str(fluor_channels[i])] = mip_projection[i]\n else:\n # but if this is a subsequent channel this name will already appear\n # in a bigfish dictionary of results and therefore a \"P\" is added\n projection_dictionary[fluor_channels[i]+'P'] = mip_projection[i]\n return projection_dictionary\n\n# =============================================================================\n# This function uses the bigfish detection.detect_spots to compute the coordinates\n# of RNA spots for each of the channels omitting the DAPI channel.\n# Returns a dictionary of each of the channels and the spot coordinates.\n# =============================================================================\ndef detecting_mRNA_spots(stack, voxel_size=(200, 64.5, 64.5), spot_radius=(200, 70, 70), channels=['CY5', 'CY3', 'CY3.5', 'DAPI']):\n coordinate_dict = {}\n for i in range(len(stack)):\n if channels[i] != 'DAPI':\n # if the channel isn't DAPI detect spots by detection and decomposition\n spots, threshold = detection.detect_spots(images=stack[i], return_threshold=True,\n voxel_size=voxel_size, spot_radius=spot_radius)\n spots_post_decomposition, dense_regions, reference_spot = detection.decompose_dense(image=stack[i],\n spots=spots, voxel_size=voxel_size, spot_radius=spot_radius,\n alpha=0.7, # alpha impacts the number of spots per candidate region\n beta=1, # beta impacts the number of candidate regions to decompose\n gamma=5) # gamma the filtering step to denoise the image\n # add spot coordinates to a dictionary of spots where the key is the channel name\n coordinate_dict[channels[i]] = spots_post_decomposition\n return coordinate_dict\n\n\n# =============================================================================\n# This function\n#\n# =============================================================================\ndef saving_spot_dict_in_df(spot_dict):\n spot_list = []\n for i in spot_dict.keys():\n spot_list.append(spot_dict[i])\n spots_df = pd.DataFrame(spot_list, columns=['Spots'], index=list(spot_dict.keys()))\n spots_df = spots_df.explode('Spots')\n return spots_df\n# =============================================================================\n# This function assigns the dictionary of spot coordinates to each of the cells\n# defined by the cell masks.\n# =============================================================================\ndef extracting_spots_per_cell(coordinate_dict, mask_path, mip_dict):\n # formatting the channel names for bigfish function\n first_channel = list(coordinate_dict.keys())[0]\n coordinate_dict_other = {key: coordinate_dict[key] for key in coordinate_dict if key != first_channel}\n # if mask is a file path (i.e. segmentation has happened outside of the pipeline)\n # the mask file is read\n if type(mask_path) == str:\n cell_label = io.imread(mask_path)\n # if the masks have been generated via the pipeline they are simply assigned\n else:\n cell_label=mask_path\n # bigfish function is used to extract the mRNA spots per cell\n percell_results = multistack.extract_cell(cell_label=cell_label,\n ndim=3, nuc_label=None, rna_coord=coordinate_dict[first_channel],\n others_coord=coordinate_dict_other,\n image=mip_dict[first_channel],\n others_image=mip_dict)\n # the data is returned as a dictionary\n return percell_results\n\n# =============================================================================\n# This function returns the mask coordinates so that they can be mapped onto\n# the DIC and the MIPs. If two Cellpose models are used to identify mother and\n# bud cells this function is used to map cell masks from the two different\n# models onto each other.\n# =============================================================================\ndef mapping_mask_coordinates(shifted_fov_results):\n cell_coords = []\n # for each cell in extracted cell dictionary\n for i, cell_results in enumerate(shifted_fov_results):\n #(min_y, min_x, max_y, max_x)\n # to each y coordinate in the \"cell_coord\" array add on the minimum y value stored a \"bbox\" tuple\n y = shifted_fov_results[i]['cell_coord'][:, 0] + shifted_fov_results[i]['bbox'][0]\n # to each x coordinate in the \"cell_coord\" array add on the minimum x value stored a \"bbox\" tuple\n x = shifted_fov_results[i]['cell_coord'][:, -1] + shifted_fov_results[i]['bbox'][1]\n # add all the cell arrays to a list\n cell_coords.append(np.dstack((y, x))[0])\n # return list of mapped cell masks\n return cell_coords\n\n# =============================================================================\n# This function computes the centroids of each segemented cell from the\n# separate Cellpose model and returns a dictionary of the index of the mask\n# and the centroids.\n# =============================================================================\ndef mask_centroids(separate_mask_coordinates):\n centroids = {}\n # using index as the cell ID anf key in the centroids dictionary\n for i in range(len(separate_mask_coordinates)):\n # use Shapely functionality to calculate the centroids of each cell mask shape\n centroids[i] = [float(x) for x in Polygon(separate_mask_coordinates[i]).centroid.wkt[7:-2].split(' ')]\n return centroids\n\n# =============================================================================\n# This function uses the centroids for each of the separate masks and isolates\n# masks from the \"whole\" Cellpose model containing two centroids\n# as those two mask fragments are related. These relationships are returned\n# in a 2d-array of related masks.\n# =============================================================================\ndef mother_bud_reunion(whole_mask_coordinates, centroids):\n mother_bud_sep = []\n mother_bud_whole = []\n # for each mask generated from the \"whole\" Cellpose model\n for i in whole_mask_coordinates:\n # initiate a counter\n counter_dict = {}\n # for the centroids in the centroid dictionary\n for j in centroids.values():\n counter = shapely.contains_xy(Polygon(i), j[0], j[1])\n # if the centroid is contained within the mask generated from the \"whole\" Cellpose model\n # it is added to the counter dictionary - with the ID of the \"separate\" mask as a key\n if counter == True:\n counter_dict[list(centroids.keys())[list(centroids.values()).index(j)]] = counter\n # if the counter dictionary has more than 1 value\n if len(counter_dict.values()) > 1:\n # then the ID of the \"separate\" mask is appended to a list\n mother_bud_sep.append(list(counter_dict.keys()))\n mother_bud_whole.append(i)\n # this list is returned after all masks generated from the \"whole\" Cellpose model\n # have been iterated through\n return mother_bud_sep\n\n# =============================================================================\n# This function calculates the area for each mask in the related pair of masks\n# and based on the area - each masks is either assigned the label of 'mother' or\n# 'bud' (with smaller area being 'bud' and larger area 'mother').\n# =============================================================================\ndef mother_or_bud(maskpairs, fov_sep):\n mother_bud_dict = {}\n for i in range(len(maskpairs)):\n # calculate the area of each related mask\n area1 = Polygon(fov_sep[maskpairs[i][0]]['cell_coord']).area\n area2 = Polygon(fov_sep[maskpairs[i][1]]['cell_coord']).area\n # if area1 is bigger than area2\n if area1 > area2:\n # then the mask from which area1 was calculated from is assigned 'mother'\n mother_bud_dict[maskpairs[i][0]] = ('mother', 'corresponding bud: '+str(maskpairs[i][1]))\n mother_bud_dict[maskpairs[i][1]] = ('bud', 'corresponding mother: '+str(maskpairs[i][0]))\n else:\n # else the mask from which area2 was calculated is assigned 'mother'\n mother_bud_dict[maskpairs[i][0]] = ('bud', 'corresponding mother: '+str(maskpairs[i][1]))\n mother_bud_dict[maskpairs[i][1]] = ('mother', 'corresponding bud: '+str(maskpairs[i][0]))\n # the ID of the corresponding cell fragment is also added to a dictionary which is returned\n return mother_bud_dict\n\n# =============================================================================\n# This function calculates the total proportion of the number of spots in each cell\n# vs the number of spots outside of cell boundaries for each channel per image.\n# =============================================================================\ndef counting_spots_in_cells(spots, spots_in_cells, channels=['rna_coord', 'CY3', 'CY3.5']):\n # calculate the total number of spots detected\n spot_num = 0\n for key in list(spots.keys()):\n spot_num += len(spots[key])\n\n # calculate the total number of spots assigned to cells\n spot_in_cell_num = 0\n for i in spots_in_cells:\n for j in channels:\n spot_in_cell_num += len(i[j])\n\n # use these two figures to calculate the proportion of sopts in cells\n proportion = (spot_in_cell_num/spot_num)*100\n return proportion, spot_in_cell_num, spot_num\n\n# =============================================================================\n# BRUTE FORCE SHIFT CORRECTION APPROACH - currently unused in script\n# This function iterates through different shifts and calculates the proportion\n# of the mRNA spots that are in cells vs outside of them and returns the max\n# proportion along with the corresponding coordinates.\n# =============================================================================\ndef dic_shift_coords(original_fov_whole, original_mask, original_proportion, spot_dict, shift_range=[-15,15]):\n prop_max = original_proportion\n results = []\n for x in range(shift_range[0],shift_range[1],1):\n for y in range(shift_range[0],shift_range[1],1):\n # for each combination of x and y coordinate shift the masks\n mask_whole_shifted = shift(original_mask, [x, y])\n # calculate the new proportion of spots in cells\n fov_whole_shifted = extracting_spots_per_cell(spot_dict, mask_whole_shifted, projection_dict)\n prop, cells_shifted, total = counting_spots_in_cells(spot_dict, fov_whole_shifted)\n # if the porportion is higher than the current maximum save this along with the\n # coordinates that have generated this maximum\n if prop > prop_max:\n prop_max = prop\n results = [prop_max, x, y, fov_whole_shifted]\n # after all coordinate combinations have been iterated through the maximum proportion\n # and corresponding coordinates are returned\n return results\n\n# =============================================================================\n# This function shifts the masks and calculates the new proportion of spots\n# within cells with this shift and the new proportion is returned.\n# =============================================================================\ndef shifting_and_counting(original_mask, spot_dict, x, y, projection_dict):\n # shift the mask\n mask_whole_shifted = shift(original_mask, [x, y])\n # use the shifted mask to extract spots in cells\n fov_whole_shifted = extracting_spots_per_cell(spot_dict, mask_whole_shifted, projection_dict)\n # use the new number of spots in cells to calculate the new proportion\n prop, cells_shifted, total = counting_spots_in_cells(spot_dict, fov_whole_shifted)\n return prop\n\n# =============================================================================\n# This function avoids the calulcation of proportion values for coordinate\n# combinations which have already been calculated.\n# =============================================================================\ndef checking_shift_dictionary(shift_coord, proportion_dictionary, spot_dict, original_mask, projection_dictionary):\n # if the coordinates that need to be checked are already in the proportion dictionary\n if str(shift_coord) in proportion_dictionary:\n # the proportion is simply the previously calculated proportion value in the dictionary\n proportion = proportion_dictionary[str(shift_coord)]\n else:\n # otherwise the shifting_and_counting function is used to calculate the new proportion\n proportion = shifting_and_counting(original_mask, spot_dict, shift_coord[0], shift_coord[1], projection_dictionary)\n proportion_dictionary[str(shift_coord)] = proportion\n # this proportion is returned\n return proportion\n\n# =============================================================================\n# This function defines all the neighbours around a point and returns the\n# neighbours as a list.\n# =============================================================================\ndef defining_neighbours(x, y, proportion_dictionary, spot_dict, original_mask):\n # centre coordinate\n start = [x, y]\n # neighbours\n up_shift = [x, y+1]\n upleft_shift = [x-1, y+1]\n upright_shift = [x+1, y+1]\n down_shift = [x, y-1]\n downleft_shift = [x-1, y-1]\n downright_shift = [x+1, y-1]\n left_shift = [x-1, y]\n right_shift = [x+1, y]\n # all the neighbours are placed in a list\n shift_neighbours = [start, up_shift, upleft_shift, upright_shift,down_shift, downleft_shift, downright_shift,left_shift, right_shift]\n # this list is returned\n return shift_neighbours\n\n# =============================================================================\n# This function calculates the proportions of spots in cells when the masks are\n# shifted around the centre i.e. all the proportions of neighbour shifts\n# are calculated. Calculating the same proportion twice is prevented by\n# checking the proportion dictionary.\n# =============================================================================\ndef calculating_neighbour_proportions(prev_max_prop, shift_neightbours_list, proportion_dictionary, spot_dict, original_mask, projection_dictionary):\n prop_max = [prev_max_prop, [0, 0]]\n # for each of the neighbours in the list\n for i in shift_neightbours_list:\n # check the dictionary or calculate the proportion for each neighbour shift\n prop = checking_shift_dictionary(i, proportion_dictionary, spot_dict, original_mask, projection_dictionary)\n # if the proportion calculated is higher than the previous maximum proportion\n if prop > prop_max[0]:\n # this value along with the corresponding coordinates are saved\n prop_max = [prop, i]\n # when all neighbours have been checked the maximum proportion and coordinates of these neighbours are returned\n return prop_max\n\n# =============================================================================\n# This function finds the shift with the maximum proportion of spots within\n# cells.\n# =============================================================================\ndef finding_max_proportion_of_image(prev_max_prop, x, y, proportion_dictionary, spot_dict, original_mask, projection_dictionary):\n # neighbours are defined for the starting point\n neighbour_list = defining_neighbours(x, y, proportion_dictionary, spot_dict, original_mask)\n # proportions for all the neighbouring shifts are calculated\n maximum_neighbour_proportion = calculating_neighbour_proportions(prev_max_prop, neighbour_list, proportion_dictionary, spot_dict, original_mask, projection_dictionary)\n # if the maximum proportion of the neighbours is larger than the previous maximum\n if maximum_neighbour_proportion[0] > prev_max_prop:\n # print the current shift information and rerun this function using this maximum and the coordinates that generated them as the starting point\n print(f'Current maximum proportion {maximum_neighbour_proportion[0]:.2f} and the cooresponding coordinates: {maximum_neighbour_proportion[1]}')\n return finding_max_proportion_of_image(maximum_neighbour_proportion[0], maximum_neighbour_proportion[1][0], maximum_neighbour_proportion[1][1], proportion_dictionary, spot_dict, original_mask, projection_dictionary)\n else:\n # otherwise, if none of the neighbours are bigger, the maximum of the image has been found and the proportion and the coordinates are returned\n return [prev_max_prop, [x, y]]\n\n# =============================================================================\n# This function calculates mRNA localisation metrics of each cell using\n# adapted bigfish functions.\n# =============================================================================\ndef calculating_bigfish_metrics_per_channel(cell_mask, rna_coord, smfish, ndim, channel, voxel_size_yx=103, foci_coord=None):\n # calculate distance metrics\n distance, distance_names = features_distance(rna_coord, _get_distance_cell(cell_mask), cell_mask, ndim, channel)\n # calculate protrusion metrics\n #protrusion, protrusion_names = features_protrusion(rna_coord, cell_mask, ndim, voxel_size_yx, channel)\n # calculate dispersion metrics\n dispersion, dispersion_names = features_dispersion(smfish, rna_coord, _get_centroid_rna(rna_coord, 2), cell_mask, _get_centroid_surface(cell_mask), ndim, channel, False)\n #features_foci(rna_coord, foci_coord, ndim)\n # combine all metrics into a numpy array\n features = np.concatenate((distance, dispersion), axis=0)\n feature_names = distance_names + dispersion_names\n\n #features = np.concatenate((distance, protrusion, dispersion), axis=0)\n #feature_names = distance_names + protrusion_names + dispersion_names\n # return the array of features\n return np.column_stack((features, feature_names))\n\n# =============================================================================\n# This function calculates the area of each cell using a bigfish function.\n# =============================================================================\ndef calculating_bigfish_area(cell_mask, pixel_size):\n # area is calculated\n area, area_names = features_area(cell_mask)\n area = float(area[0]) * (float(pixel_size[0])*float(pixel_size[1]))\n # area features returned as an array\n return [area, area_names[0]+str(\" (\\u03BCm\\u00b2)\")]\n\n# =============================================================================\n# This function is a bigfish function which is required for the adapted bigfish\n# functions to run. It caluclates the centroid coordinates of a 2-d binary surface.\n# =============================================================================\ndef _get_centroid_surface(mask):\n \"\"\"Get centroid coordinates of a 2-d binary surface.\n\n Parameters\n ----------\n mask : np.ndarray, bool\n Binary surface with shape (y, x).\n\n Returns\n -------\n centroid : np.ndarray, np.int\n Coordinates of the centroid with shape (2,).\n\n \"\"\"\n # get centroid\n region = regionprops(mask.astype(np.uint8))[0]\n centroid = np.array(region.centroid, dtype=np.int64)\n\n return centroid\n\n# =============================================================================\n# This function uses the dictionary containing the mask IDs and their label\n# (i.e. whether they are a mother or a bud) to add this information to the array\n# of calculated feature metrics.\n# =============================================================================\ndef assigning_cell_type_DataFrame(cell_id, celltype_dictionary):\n # if the ID of the cell is in the dictionary the value of the dictionary is\n # returned (either 'mother' or 'bud')\n if cell_id in celltype_dictionary.keys():\n return [celltype_dictionary[cell_id], 'cell_type']\n else:\n # otherwise the cell is not a 'mother' or 'bud' segment and is therefore\n # denoted as a 'single cell'\n return ['single cell', 'cell_type']\n\n# =============================================================================\n# This function uses the functions calculating_bigfish_metrics_per_channel,\n# calculating_bigfish_area and assigning_cell_type_DataFrame to calculate\n# the metrics for each channel in the image and return the information in a DataFrame.\n# =============================================================================\ndef writing_metrics_to_DataFrame(fov, channels, im_channels, celltype_dictionary, pixel_size, dic_shift):\n one_cell = []\n listDict = []\n # for each cell\n for i in range(len(fov)):\n # for each channel\n for j in range(len(channels)):\n # calculate the bigfish metrics\n one_cell.append(calculating_bigfish_metrics_per_channel(fov[i][\"cell_mask\"], fov[i][channels[j]], fov[i][im_channels[j]], 3, channels[j]))\n # count the number of mRNA molecules\n one_cell.append([[len(fov[i][channels[j]]), 'number_of_mRNA_'+channels[j]]])\n # calulate the area for each cell\n one_cell.append([calculating_bigfish_area(fov[i][\"cell_mask\"], pixel_size)])\n #print(calculating_bigfish_area(fov[i][\"cell_mask\"]))\n one_cell.append([[mapping_mask_coordinates(fov)[i], 'Mask Coordinates']])\n # if a celltype_dictionary has been created\n if celltype_dictionary != None:\n # then celltypes are added to the list of cell information\n one_cell.append([assigning_cell_type_DataFrame(i, celltype_dictionary)])\n # create a dictionary from the array which contains the metrics and the name of the metric calculated\n # append each cell dictionary in a list\n listDict.append(dict(zip(np.concatenate(one_cell)[:,-1],np.concatenate(one_cell)[:,0])))\n # use the list of dictionaries containing the metrics of each cell to create a DataFrame\n df = pd.DataFrame(listDict)\n df['DIC SHIFT (to shift dic to fluorescent channels): ' +str(dic_shift[1])] = np.nan\n return df\n\n# =============================================================================\n# This function saves the DataFrame created in an excel document to the output path\n# specified by the user. If the \"separate\" Cellpose model has been used as well\n# as the \"whole\" cell model both of these DataFrames are output on different sheets.\n# =============================================================================\ndef writing_dataframe_to_excel(output_path, whole_df_output, sep_df_output, spot_coord_dict_output):\n with pd.ExcelWriter(output_path, engine='xlsxwriter', engine_kwargs={'options': {'strings_to_numbers': True}}) as writer:\n whole_df_output.to_excel(writer, sheet_name='whole_cells')\n # If there is a separate DataFrame this is output on a different sheet\n if sep_df_output is not None:\n sep_df_output.to_excel(writer, sheet_name='mother_buds_separate')\n spot_coord_dict_output.to_excel(writer, sheet_name='Detected Spots')\n","repo_name":"carlottacode/smFISHImagePipeline","sub_path":"scripts/functions_edit.py","file_name":"functions_edit.py","file_ext":"py","file_size_in_byte":33931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"2688209730","text":"# pylint: disable=too-many-public-methods, too-few-public-methods, no-self-use, too-many-arguments\r\n\"\"\"Cron Update Progress\"\"\"\r\nfrom library.postgresql_queries import PostgreSQL\r\nfrom library.common import Common\r\nfrom library.sha_security import ShaSecurity\r\nfrom library.progress import Progress\r\nclass UpdateProgress(Common):\r\n \"\"\"Class for UpdateProgress\"\"\"\r\n\r\n # INITIALIZE\r\n def __init__(self):\r\n \"\"\"The Constructor for UpdateProgress class\"\"\"\r\n\r\n self.postgres = PostgreSQL()\r\n self.progress = Progress()\r\n self.sha_security = ShaSecurity()\r\n super(UpdateProgress, self).__init__()\r\n\r\n\r\n def update_student_progress(self):\r\n \"\"\"Update Progress\"\"\"\r\n\r\n sql_str = \"SELECT * FROM student_course sc\"\r\n sql_str += \" LEFT JOIN student_exercise se ON sc.course_id = se.course_id\"\r\n sql_str += \" WHERE sc.percent_score is NULL AND se.progress = '100'\"\r\n sql_str += \" AND se.status is True AND se.account_id = sc.account_id\"\r\n result = self.postgres.query_fetch_all(sql_str)\r\n \r\n if result:\r\n\r\n for res in result:\r\n userid = res['account_id']\r\n exercise_id = res['exercise_id']\r\n\r\n # UPDATE PROGRESS\r\n self.progress.update_course_progress(userid, exercise_id, \"student\")\r\n self.progress.update_section_progress(userid, exercise_id, \"student\")\r\n self.progress.update_subsection_progress(userid, exercise_id, \"student\")\r\n\r\n return 1\r\n","repo_name":"GithubJerome/nmi-api","sub_path":"controllers/cron/cron_update_progress.py","file_name":"cron_update_progress.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"16383034703","text":"import socket\nimport pygame as pg\nimport time\nimport json\n\n\nPLAYER_SPEED = 5\nLASER_SPEED = 6\nBUFFER_SIZE = 204800\n\n\ndef Main():\n\tclock = pg.time.Clock()\n\tfps = 60\n\n\thost = ''\n\tp1Port = 9002\n\tp2Port = 9003\n\n\tp1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\tp2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n\tp1.bind((host,p1Port))\n\tp2.bind((host,p2Port))\n\n\n\tp1.listen(1)\n\tp2.listen(1)\n\tprint(\"Waiting for P1 on:\", host, p1Port)\n\tprint(\"Waiting for P2 on:\", host, p2Port)\n\tconnP1, addrP1 = p1.accept()\n\tprint(\"Connection from P1 at: \" + str(addrP1))\n\tconnP2, addrP2 = p2.accept()\n\tprint(\"Connection from P2 at: \" + str(addrP2))\n\n\twhile True:\n\t\tp1Data = connP1.recv(BUFFER_SIZE).decode()\n\t\tp2Data = connP2.recv(BUFFER_SIZE).decode()\n\t\tif not (p1Data or p2Data):\n\t\t\tbreak\n\t\tp1Data = eval(p1Data)\n\t\tp2Data = eval(p2Data)\n\n\n\t\tif p1Data['R']:\n\t\t\tp1Data['xpos']+=PLAYER_SPEED\n\t\tif p1Data['L']:\n\t\t\tp1Data['xpos']-=PLAYER_SPEED\n\t\tif p1Data['U']: \n\t\t\tp1Data['ypos']-=PLAYER_SPEED\n\t\tif p1Data['D']:\n\t\t\tp1Data['ypos']+=PLAYER_SPEED\n\n\t\tif p2Data['R']:\n\t\t\tp2Data['xpos']+=PLAYER_SPEED\n\t\tif p2Data['L']:\n\t\t\tp2Data['xpos']-=PLAYER_SPEED\n\t\tif p2Data['U']: \n\t\t\tp2Data['ypos']-=PLAYER_SPEED\n\t\tif p2Data['D']:\n\t\t\tp2Data['ypos']+=PLAYER_SPEED\n\n\t\tp1Data['xposP2']=p2Data['xpos']\n\t\tp1Data['yposP2']=p2Data['ypos']\n\t\tp1Data['centerP2']=p2Data['center']\n\t\tp1Data['angleP2']=p2Data['angle']\n\t\tp1Data['fireP2']=p2Data['fire']\n\n\t\tp2Data['xposP1']=p1Data['xpos']\n\t\tp2Data['yposP1']=p1Data['ypos']\n\t\tp2Data['centerP1']=p1Data['center']\n\t\tp2Data['angleP1']=p1Data['angle']\n\t\tp2Data['fireP1']=p1Data['fire']\n\n\t\t#print(p1Data)\n\n\t\tFPS = clock.get_fps()\n\t\tp1Data['FPS'] = FPS\n\t\tp2Data['FPS'] = FPS\n\n\t\tconnP1.send(str(p1Data).encode())\n\t\tconnP2.send(str(p2Data).encode())\n\t\tclock.tick(fps)\n\t\t#print(clock.get_fps(), end='\\r')\n\n\tconnP1.close()\n\tconnP2.close()\n\nif __name__ == '__main__':\n\tMain()\n\n","repo_name":"Ezooon/myProjects","sub_path":"multiplayerShooter/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"28641776265","text":"from listpy import listpy\nfrom unittest import TestCase, skip\nfrom collections.abc import MutableSequence\n\n\nclass TestListpy(TestCase):\n def test_setitem_and_getitem(self):\n obj = listpy()\n obj[0] = 10\n self.assertEqual(obj[0], 10)\n\n def test_setitem_and_getitem_two_items(self):\n obj = listpy()\n obj[0] = 1\n obj[1] = 10\n self.assertEqual(obj[0], 1)\n self.assertEqual(obj[1], 10)\n\n def test_setitem_to_exists(self):\n obj = listpy()\n obj[0] = 1\n obj[1] = 10\n obj[0] = 5\n self.assertEqual(obj[0], 5)\n self.assertEqual(obj[1], 10)\n\n def test_getitem_out_of_range(self):\n obj = listpy()\n with self.assertRaises(IndexError):\n obj[0]\n\n def test_setitem_out_of_range(self):\n obj = listpy()\n with self.assertRaises(IndexError):\n obj[42] = 0\n\n def test_len_empty(self):\n obj = listpy()\n self.assertEqual(len(obj), 0)\n\n def test_len_one(self):\n obj = listpy()\n obj[0] = 42\n self.assertEqual(len(obj), 1)\n\n def test_len_overwrite(self):\n obj = listpy()\n obj[0] = 42\n self.assertEqual(len(obj), 1)\n\n def test_list_conversion(self):\n obj = listpy()\n obj[0] = 0\n obj[1] = 1\n obj[2] = 2\n obj[3] = 3\n obj[1] = 42\n self.assertListEqual(list(obj), [0, 42, 2, 3])\n\n def test_delitem(self):\n obj = listpy()\n obj[0] = 0\n del obj[0]\n self.assertSequenceEqual(obj, [])\n\n obj = listpy()\n obj[0] = 0\n obj[1] = 1\n obj[2] = 2\n del obj[1]\n self.assertSequenceEqual(obj, [0, 2])\n\n def test_delitem_out_of_range(self):\n obj = listpy()\n with self.assertRaises(IndexError):\n del obj[0]\n with self.assertRaises(IndexError):\n del obj[10]\n\n obj[0] = 42\n with self.assertRaises(IndexError):\n del obj[1]\n with self.assertRaises(IndexError):\n del obj[10]\n\n def test_insert(self):\n obj = listpy()\n obj.insert(0, 10)\n self.assertSequenceEqual(obj, [10])\n obj.insert(0, 5)\n self.assertSequenceEqual(obj, [5, 10])\n obj.insert(2, 9)\n self.assertSequenceEqual(obj, [5, 10, 9])\n obj.insert(1, 7)\n self.assertSequenceEqual(obj, [5, 7, 10, 9])\n\n def test_setitem_slice(self):\n obj = listpy()\n obj[:] = [10, 10]\n self.assertSequenceEqual(obj, [10, 10])\n obj[0:2] = [10, 10]\n self.assertSequenceEqual(obj, [10, 10])\n obj[1:2] = [10, 10]\n self.assertSequenceEqual(obj, [10, 10, 10])\n obj[3:10] = [10, 10]\n self.assertSequenceEqual(obj, [10, 10, 10, 10, 10])\n obj[5:10] = [0, 0]\n self.assertSequenceEqual(obj, [10, 10, 10, 10, 10, 0, 0])\n\n def test_getitem_slice(self):\n obj = listpy()\n obj[0:0] = [10, 20, 30, 40, 50]\n\n def test_listpy_should_be_MutableSequence(self):\n self.assertIsInstance(listpy(), MutableSequence)\n self.assertTrue(issubclass(listpy, MutableSequence))\n\n def test_listpy_should_have_mixins(self):\n obj = listpy()\n obj.append(0)\n obj.extend((1, 2, 3, 4))\n self.assertEqual(len(obj), 5)\n self.assertEqual(obj[3], 3)\n obj.reverse()\n self.assertEqual(obj[3], 1)\n obj.pop()\n self.assertEqual(len(obj), 4)\n obj.remove(3)\n self.assertEqual(len(obj), 3)\n obj += (10, 20, 30)\n self.assertEqual(len(obj), 6)\n self.assertEqual(obj[5], 30)\n # self.assertEqual(obj[-1], 30)\n obj.clear()\n self.assertEqual(len(obj), 0)\n\n '''\n # issue 34427\n # extending self should not cause infinite loop\n items = [1, 2, 3, 4]\n obj2 = listpy()\n obj2.extend(items + items)\n obj.clear()\n obj.extend(items)\n obj.extend(obj)\n self.assertEqual(len(obj), len(obj2))\n self.assertEqual(list(obj), list(obj2))\n '''\n\n def test_listpy_iterable_initialize(self):\n obj = listpy((1, 2, 3, 4))\n self.assertSequenceEqual(obj, (1, 2, 3, 4))\n","repo_name":"Tetramad/CIS3001","sub_path":"listpy_test.py","file_name":"listpy_test.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"15706020883","text":"from tkinter import *\r\nimport imageio\r\nfrom PIL import Image, ImageTk\r\ndef stream():\r\n try:\r\n image = video.get_next_data()\r\n frame_image = Image.fromarray(image)\r\n frame_image=ImageTk.PhotoImage(frame_image)\r\n l1.config(image=frame_image)\r\n l1.image = frame_image\r\n l1.after(delay, lambda: stream())\r\n except:\r\n video.close()\r\n return\r\n########### Main Program ############\r\nroot = Tk()\r\nroot.title('Video in a Frame')\r\nf1=Frame()\r\nl1 = Label(f1)\r\nl1.pack()\r\nf1.pack()\r\nvideo_name = \"D:\\mark.mp4\" #Image-path\r\nvideo = imageio.get_reader(video_name)\r\ndelay = int(1000 / video.get_meta_data()['fps'])\r\nstream()\r\nroot.mainloop()","repo_name":"harshyp47/Hydro-Infinity","sub_path":"VideoTkDemo.py","file_name":"VideoTkDemo.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"51"} +{"seq_id":"5241842913","text":"from Seq0 import *\n\nGenes = [\"ADA\", \"FRAT1\", \"FXN\", \"U5\", \"RNU6_269P\"]\nFolder = \"../Session-04/\"\nend = \".txt\"\n\nfor element in Genes:\n filename = Folder + element + end\n sequence = seq_read_fasta(filename)\n length = seq_len(sequence)\n print(\"Gene \", element, \"---> Length: \", length)","repo_name":"mjlozanob/-2019-2020-PNE-Practices","sub_path":"P0/Ex3.py","file_name":"Ex3.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"14090764567","text":"\"\"\"\n@brief Compute detector response vs incident flux for pairs of flats.\nThese data are to be used for linearity measurments.\n\n@author J. Chiang \n\"\"\"\nfrom __future__ import absolute_import\nimport os\nimport numpy as np\nimport astropy.io.fits as fits\nfrom lsst.eotest.fitsTools import fitsTableFactory, fitsWriteto\nimport lsst.eotest.image_utils as imutils\nfrom .MaskedCCD import MaskedCCD\nfrom .EOTestResults import EOTestResults\nfrom .DetectorResponse import DetectorResponse\n\nimport lsst.pex.config as pexConfig\nimport lsst.pipe.base as pipeBase\nfrom lsst.utils.timer import timeMethod\nfrom .flatPairTask import pair_mean, find_flat2\n\n\nclass LinearityConfig(pexConfig.Config):\n \"\"\"Configuration for flat pair task\"\"\"\n output_dir = pexConfig.Field(\"Output directory\", str, default='.')\n eotest_results_file = pexConfig.Field(\"EO test results filename\",\n str, default=None)\n verbose = pexConfig.Field(\"Turn verbosity on\", bool, default=True)\n\n\nclass LinearityTask(pipeBase.Task):\n \"\"\"Task to compute detector response vs incident flux from\n flat pair dataset.\"\"\"\n ConfigClass = LinearityConfig\n _DefaultName = \"LinearityTask\"\n\n @timeMethod\n def run(self, sensor_id, infiles, mask_files, gains, detrespfile=None,\n bias_frame=None, linearity_correction=None):\n self.sensor_id = sensor_id\n self.infiles = infiles\n self.mask_files = mask_files\n self.gains = gains\n self.bias_frame = bias_frame\n self.linearity_correction = linearity_correction\n if detrespfile is None:\n #\n # Compute detector response from flat pair files.\n #\n detrespfile = self.extract_det_response()\n #\n # Perform linearity analyses.\n #\n detresp = DetectorResponse(detrespfile)\n\n outfile = self.config.eotest_results_file\n if outfile is None:\n outfile = os.path.join(self.config.output_dir,\n '%s_eotest_results.fits' % self.sensor_id)\n all_amps = imutils.allAmps(detrespfile)\n output = EOTestResults(outfile, namps=len(all_amps))\n if self.config.verbose:\n self.log.info(\"Amp max. frac. dev.\")\n for amp in all_amps:\n try:\n results = detresp.linearity(amp)\n maxdev, fit_pars, Ne, flux = results[:4]\n except:\n maxdev = None\n if self.config.verbose:\n self.log.info('%2i %s' % (amp, maxdev))\n if maxdev is not None:\n output.add_seg_result(amp, 'MAX_FRAC_DEV', float(maxdev))\n output.write()\n\n def _create_detresp_fits_output(self, nrows, infile):\n self.output = fits.HDUList()\n self.output.append(fits.PrimaryHDU())\n all_amps = imutils.allAmps(infile)\n colnames = ['flux'] + ['AMP%02i_SIGNAL' % i for i in all_amps]\n formats = 'E'*len(colnames)\n units = ['None'] + ['e-']*len(all_amps)\n columns = [np.zeros(nrows, dtype=float) for fmt in formats]\n fits_cols = [fits.Column(name=colnames[i], format=formats[i],\n unit=units[i], array=columns[i])\n for i in range(len(units))]\n hdu = fitsTableFactory(fits_cols)\n hdu.name = 'DETECTOR_RESPONSE'\n self.output.append(hdu)\n\n def extract_det_response(self):\n outfile = os.path.join(self.config.output_dir,\n '%s_det_response_linearity.fits' % self.sensor_id)\n file1s = sorted([item for item in self.infiles\n if item.find('flat1') != -1 or\n item.find('linearity_flat') != -1])\n if self.config.verbose:\n self.log.info(\"writing to %s\" % outfile)\n self._create_detresp_fits_output(len(file1s), files1[0])\n for row, file1 in enumerate(file1s):\n if self.config.verbose:\n self.log.info(\"processing %s\" % file1)\n try:\n file2 = find_flat2(file1)\n except IndexError:\n # Just use flat1 again since only average is taken and\n # FPN subtraction isn't needed.\n file2 = file1\n\n flat1 = MaskedCCD(file1, mask_files=self.mask_files,\n bias_frame=self.bias_frame,\n linearity_correction=self.linearity_correction)\n flat2 = MaskedCCD(file2, mask_files=self.mask_files,\n bias_frame=self.bias_frame,\n linearity_correction=self.linearity_correction)\n\n if flat1.md.get('EXPTIME') != flat2.md.get('EXPTIME'):\n raise RuntimeError(\"Exposure times do not match for:\\n%s\\n%s\\n\"\n % (file1, file2))\n\n if (flat1.md.get('MONDIODE') != 0 and\n flat2.md.get('MONDIODE') != 0):\n flux = abs(flat1.md.get('EXPTIME')*flat1.md.get('MONDIODE') +\n flat2.md.get('EXPTIME')*flat2.md.get('MONDIODE'))/2.\n else:\n flux = flat1.md.get('EXPTIME')\n\n self.output[-1].data.field('FLUX')[row] = flux\n for amp in flat1:\n # Convert to e- and write out for each segment.\n signal = pair_mean(flat1, flat2, amp)*self.gains[amp]\n self.output[-1].data.field('AMP%02i_SIGNAL' % amp)[row] = signal\n self.output[0].header['NAMPS'] = len(flat1)\n fitsWriteto(self.output, outfile, overwrite=True)\n return outfile\n\n\nif __name__ == '__main__':\n parser = TaskParser('Compute detector response vs incident flux')\n parser.add_argument('-f', '--flats', type=str,\n help='flat pairs file pattern')\n parser.add_argument('-F', '--flats_file_list', type=str,\n help='list of flat pairs')\n args = parser.parse_args()\n sensor = args.sensor()\n sensor_id = args.sensor_id\n","repo_name":"lsst-camera-dh/eotest","sub_path":"python/lsst/eotest/sensor/linearityTask.py","file_name":"linearityTask.py","file_ext":"py","file_size_in_byte":6078,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"51"} +{"seq_id":"2739933049","text":"\"\"\"\nCreate and save a public dataset archive on the disk.\n\"\"\"\nimport zipfile\nfrom io import StringIO\nfrom os.path import getctime\nfrom pathlib import Path\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom django.utils import timezone\n\nfrom core.utils.time import time_ago\nfrom tournesol.lib.public_dataset import (\n write_collective_criteria_scores_file,\n write_comparisons_file,\n write_individual_criteria_scores_file,\n write_metadata_file,\n write_users_file,\n)\nfrom tournesol.models.poll import Poll\n\n\nclass Command(BaseCommand):\n help = \"Create and save a public dataset archive on the disk, then delete old datasets.\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--keep-only\",\n type=int,\n default=10,\n help=\"The number of archives to keep on the disk (default 10).\"\n \" The oldest archives will be deleted. No effect when --keep-all is set.\",\n )\n parser.add_argument(\n \"--keep-all\",\n action=\"store_true\",\n default=False,\n help=\"Do not remove old archives from the disk.\"\n \" Ignore the value defined by --keep-only.\",\n )\n\n def handle(self, *args, **options):\n \"\"\"\n Create a public dataset archive with fresh data retrieved from the\n database.\n\n The archive is created on the disk at:\n `MEDIA_ROOT/APP_TOURNESOL[\"DATASETS_BUILD_DIR\"]`\n \"\"\"\n self.stdout.write(f\"start command: {__name__}\")\n\n # Display the configuration if more verbosity is asked.\n if options.get(\"verbosity\", 1) > 1:\n self.stdout.write(f\"MEDIA_ROOT: {settings.MEDIA_ROOT}\")\n self.stdout.write(\n \"APP_TOURNESOL['DATASET_BASE_NAME']:\"\n f\" {settings.APP_TOURNESOL['DATASET_BASE_NAME']}\"\n )\n self.stdout.write(\n \"APP_TOURNESOL['DATASETS_BUILD_DIR']:\"\n f\" {settings.APP_TOURNESOL['DATASETS_BUILD_DIR']}\"\n )\n\n dataset_base_name = settings.APP_TOURNESOL[\"DATASET_BASE_NAME\"]\n datasets_build_dir = Path(settings.MEDIA_ROOT).joinpath(\n settings.APP_TOURNESOL[\"DATASETS_BUILD_DIR\"]\n )\n datasets_build_dir.mkdir(parents=True, exist_ok=True)\n\n # Only the default poll is exported for the moment.\n poll_name = Poll.default_poll().name\n\n archive_abs_path = datasets_build_dir.joinpath(dataset_base_name).with_suffix(\".zip\")\n\n readme_path = Path(\"tournesol/resources/export_readme.txt\")\n license_path = Path(\"tournesol/resources/export_odc_by_1.0_public_text.txt\")\n\n first_day_of_week = time_ago(days=timezone.now().weekday()).date()\n\n # BUILDING phase\n with zipfile.ZipFile(archive_abs_path, \"w\", compression=zipfile.ZIP_DEFLATED) as zip_file:\n with open(readme_path, \"r\", encoding=\"utf-8\") as readme:\n zip_file.writestr(\"README.txt\", readme.read())\n\n with open(license_path, \"r\", encoding=\"utf-8\") as license_:\n zip_file.writestr(\"LICENSE.txt\", license_.read())\n\n with StringIO() as output:\n self.stdout.write(\"building tournesol metadata...\")\n write_metadata_file(output, data_until=first_day_of_week)\n zip_file.writestr(\"metadata.json\", output.getvalue())\n self.stdout.write(\"- metadata.json written.\")\n\n with StringIO() as output:\n self.stdout.write(\"retrieving users' data...\")\n write_users_file(poll_name, output)\n zip_file.writestr(\"users.csv\", output.getvalue())\n self.stdout.write(\"- users.csv written.\")\n\n with StringIO() as output:\n self.stdout.write(\"retrieving comparisons' data...\")\n write_comparisons_file(poll_name, output, until_=first_day_of_week)\n zip_file.writestr(\"comparisons.csv\", output.getvalue())\n self.stdout.write(\"- comparisons.csv written.\")\n\n with StringIO() as output:\n self.stdout.write(\"retrieving individual criteria scores' data...\")\n write_individual_criteria_scores_file(poll_name, output)\n zip_file.writestr(\"individual_criteria_scores.csv\", output.getvalue())\n self.stdout.write(\"- individual_criteria_scores.csv written.\")\n\n with StringIO() as output:\n self.stdout.write(\"retrieving collective criteria scores' data...\")\n write_collective_criteria_scores_file(poll_name, output)\n zip_file.writestr(\"collective_criteria_scores.csv\", output.getvalue())\n self.stdout.write(\"- collective_criteria_scores.csv written.\")\n\n self.stdout.write(self.style.SUCCESS(f\"archive created at {archive_abs_path}\"))\n\n # CLEANING phase\n if options[\"keep_all\"]:\n self.stdout.write(\"the option --keep-all is set, old datasets won't be deleted\")\n else:\n all_datasets = list(datasets_build_dir.glob(f\"{dataset_base_name}*\"))\n all_datasets.sort(key=getctime, reverse=True)\n\n for old_dataset in all_datasets[options[\"keep_only\"]:]:\n old_dataset.unlink()\n self.stdout.write(f\"deleted old {old_dataset}\")\n\n self.stdout.write(self.style.SUCCESS(\"success\"))\n self.stdout.write(\"end\")\n","repo_name":"tournesol-app/tournesol","sub_path":"backend/tournesol/management/commands/create_dataset.py","file_name":"create_dataset.py","file_ext":"py","file_size_in_byte":5466,"program_lang":"python","lang":"en","doc_type":"code","stars":302,"dataset":"github-code","pt":"51"} +{"seq_id":"20945844898","text":"from interface_adapters.dtos.base_response import BaseResponse\nfrom infrastructure.configs.message import MESSAGES\nfrom modules.language_detection_request.commands.create_plain_text_language_detection_request.command import CreatePlainTextLanguageDetectionRequestCommand\n\nfrom sanic import response\nfrom modules.language_detection_request.commands.create_plain_text_language_detection_request.request_dto import CreatePlainTextLanguageDetectionRequestDto\nfrom infrastructure.configs.main import StatusCodeEnum, GlobalConfig, get_cnf\n\nfrom sanic_openapi import doc\nfrom sanic.views import HTTPMethodView\nfrom modules.language_detection_request.dtos.language_detection_response import PlainTextLanguageDetectionRequestResponse\n\nconfig: GlobalConfig = get_cnf()\nAPP_CONFIG = config.APP_CONFIG\n\nclass CreatePlainTextLanguageDetectionRequest(HTTPMethodView):\n\n def __init__(self) -> None:\n super().__init__()\n\n from modules.language_detection_request.commands.create_plain_text_language_detection_request.service import CreatePlainTextLanguageDetectionRequestService\n\n self.__create_plain_text_language_detection_request_service = CreatePlainTextLanguageDetectionRequestService()\n\n @doc.summary(APP_CONFIG.ROUTES['language_detection_request.text_language_detection.create']['summary'])\n @doc.description(APP_CONFIG.ROUTES['language_detection_request.text_language_detection.create']['desc'])\n @doc.consumes(CreatePlainTextLanguageDetectionRequestDto, location=\"body\", required=True)\n @doc.produces(PlainTextLanguageDetectionRequestResponse)\n\n async def post(self, request):\n \n data = request.json\n\n command = CreatePlainTextLanguageDetectionRequestCommand(\n source_text=data['sourceText']\n )\n\n new_task, new_language_detection_record = await self.__create_plain_text_language_detection_request_service.create_request(command)\n\n return response.json(BaseResponse(**{\n 'code': StatusCodeEnum.success.value,\n 'data': {\n 'taskId': new_task.id.value,\n 'taskName': new_task.props.task_name,\n 'languageDetectionHistoryId': new_language_detection_record.id.value\n },\n 'message': MESSAGES['success']\n }).dict())\n","repo_name":"distardao/translation-backend","sub_path":"backend/src/modules/language_detection_request/commands/create_plain_text_language_detection_request/http_controller.py","file_name":"http_controller.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"161395933","text":"import json\nimport requests\nfrom finglish import f2p\n\nbase_url = 'http://127.0.0.1:8000/seeder'\n\ndef divide_chunks(l, n):\n\n # looping till length l\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\ndef seedArtist():\n with open(\"artists_details.json\", \"r\") as f:\n artists = json.load(f)\n \n # for i in range(len(artists)):\n # artists[i]['faName'] = f2p(artists[i]['name'])\n \n # with open(\"artists_details.json\", \"w\") as f:\n # json.dump(artists,f)\n \n chunked_artists = list(divide_chunks(artists, 20))\n # print(chunked_artists[1])\n # for i in chunked_artists:\n # print(i)\n for artist in chunked_artists:\n # print(artist)\n res = requests.post(base_url+'/artists', json=artist)\n print(res.status_code)\n \ndef seedMusic():\n with open(\"processed_songs_465.local.json\", \"r\") as f:\n musics = json.load(f)\n \n # for i in range(len(musics)):\n # musics[i]['faName'] = f2p(musics[i]['name'])\n # musics[i]['faTitle'] = f2p(musics[i]['title'])\n \n # with open(\"processed_songs_465.local.json\", \"w\") as f:\n # json.dump(musics, f)\n \n chunked_musics = list(divide_chunks(musics, 10))\n # print(chunked_musics[1])\n # return\n # for i in chunked_artists:\n # print(i)\n for music in chunked_musics:\n # print(artist)\n res = requests.post(base_url+'/songs', json=music)\n print(res.status_code)\n if res.status_code != 201:\n ch_mus = list(divide_chunks(music, 5))\n for mu in ch_mus:\n res = requests.post(base_url+'/songs', json=mu)\n print('nested:',res.status_code)\n\nif __name__ == '__main__':\n seedArtist()\n seedMusic()\n","repo_name":"mdhi2000/dmp-analysis","sub_path":"seeder.py","file_name":"seeder.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"41669362803","text":"### Based on Corey Schafer's tutorial: https://www.youtube.com/watch?v=K8L6KVGG-7o&t=1561s\nimport re\n\n# -------- BEGIN: simple data -------- #\n\ntext_to_search = '''\nabcdefghijklmnopqurtuvwxyz\nABCDEFGHIJKLMNOPQRSTUVWXYZ\n1234567890\n\nHa HaHa\n\nMetaCharacters (Need to be escaped):\n. ^ $ * + ? { } [ ] \\ | ( )\n\ncoreyms.com\n\n321-555-4321\n123.555.1234\n123*555*1234\n800-555-1234\n900-555-1234\n\nMr. Schafer\nMr Smith\nMs Davis\nMrs. Robinson\nMr. T\n'''\n\nstringx = 'Start a sentence and then bring it to an end'\n\n# -------- END: simple data -------- #\n\npattern = re.compile(r'\\[')\n\nmatches = pattern.finditer(text_to_search)\n\nfor match in matches:\n print(\"matched at {}; match is: {}\".format(match.regs[0], text_to_search[match.regs[0][0]:match.regs[0][1]]))\n\n\n\n## SUMMARY\n# 1. When buiding the pattern, pay attention to what you are search: raw data (r'xxx') match or not.\n# 2. The \"__str__\" is a special built-in method can be overridden. \n# 3. When calling a method, do not forget \"()\" at the end","repo_name":"Tandysony/python-knowledge","sub_path":"regex/regex.py","file_name":"regex.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"6368188905","text":"from random import randint\n\nimport pytest\nfrom playwright.sync_api import ElementHandle, Page, Playwright\n\n\n@pytest.fixture(scope='function', autouse=True)\ndef setup(page: Page):\n page.goto('https://google.com')\n page.wait_for_load_state('domcontentloaded')\n\n input = page.query_selector('input[name=\"q\"]')\n page.wait_for_timeout(100)\n input.fill('Aid for Aids')\n\n btn = page.query_selector('input[name=\"btnK\"]')\n btn.click()\n\n page.wait_for_load_state('domcontentloaded')\n\n\n@pytest.fixture\ndef afa_nodes(page:Page):\n return page.query_selector_all('a[href^=\"https://aidforaids.org\"]')\n\ndef test_validate_results_number(afa_nodes):\n assert len(afa_nodes) > 0\n\ndef test_validate_links(\n afa_nodes: list[ElementHandle], \n playwright: Playwright\n):\n browser = playwright.chromium.launch()\n for node in afa_nodes:\n url = node.get_attribute('href')\n assert url != None\n\n ctx = browser.new_context()\n ctx.set_default_timeout(60000)\n\n page = ctx.new_page()\n page.goto(url)\n page.wait_for_load_state('networkidle', timeout=None)\n\n assert page.title() != None\n\n menu_items = page.query_selector_all('#primary-menu > li > a[href^=https]')\n item = menu_items[randint(0, len(menu_items) - 1)]\n\n item_link = item.get_attribute('href')\n assert item_link != None\n\n res = page.goto(item_link)\n page.wait_for_load_state('networkidle')\n\n assert res.status < 300\n\n page.screenshot(path=f'tmp/{page.title()}.png', full_page=True)\n\n ctx.close()\n browser.close()","repo_name":"dnevb/afa-qa-role","sub_path":"test_afa_search_results.py","file_name":"test_afa_search_results.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"12275999191","text":"import argparse\nimport serial\nimport time\nimport datetime\nfrom nabu_pak import NabuSegment, NabuPack\nfrom crccheck.crc import Crc16Genibus\nimport asyncio\nimport serial_asyncio\n\nNABU_STATE_AWAITING_REQ = 0\nNABU_STATE_PROCESSING_REQ = 1\nMAX_READ=65535\n\n# request type\n# Others (from http://dunfield.classiccmp.org/nabu/nabutech.pdf,\n# Segment Routines Page 9 - 3\n#\n# $80 Reset Segment Handler (Resets Adaptor to known state)\n# (also see Page 2 - 14)\n# $81 Reset (?)\n# $82 Get adaptor status\n# $83 Set adaptor status\n# $84 Download segment\n# $85 Set channel code\n\n# Others (from http://dunfield.classiccmp.org/nabu/nabutech.pdf,\n# $87 SEG$CST ZBase Address - return control status block\n# $88 Directory Search\n# $8f Unknown\n# $96 Load XIOS Module\n# $97 Unload XIOS Module\n# $99 Resolve Global Reference\n\nclass NabuAdaptor():\n segments = {}\n\n def __init__(self, reader, writer):\n print(\"Called NabuAdaptor::__init__\")\n self.reader=reader\n self.writer=writer\n self.segment = None\n\n # Loads pak from file, assumes file names are all upper case with a lower case .pak extension\n # Assumes all pak files are in a directory called paks/\n # 000001.pak from cycle 2 needs to have the last 16 bytes of 1A's stripped off\n # 000001.pak from cycle 1 is horribly corrupt and dosen't work\n def loadpak(self, filename):\n file = filename.upper()\n print(\"* Loading NABU Segments into memory\")\n segment = NabuSegment()\n segment.ingest_from_file( \"paks/\"+ file + \".pak\")\n NabuAdaptor.segments[filename] = segment\n\n async def run_NabuSession(self):\n connected = True\n while connected:\n try:\n data = await self.recvBytesExactLen(1)\n if len(data) > 0:\n req_type = data[0]\n if req_type == 0x03:\n print(\"* 0x03 request\")\n await self.handle_0x03_request(data)\n elif req_type == 0x05:\n print(\"* 0x05 request\")\n await self.handle_0x05_request(data)\n elif req_type == 0x06:\n print(\"* 0x06 request\")\n await self.handle_0x06_request(data)\n elif req_type == 0x0f:\n print(\"* 0x0f request\")\n await self.handle_0x0f_request(data)\n elif req_type == 0xf0:\n print(\"* 0xf0 request\")\n self.andle_0xf0_request(data)\n elif req_type == 0x80:\n print(\"* Reset segment handler\")\n await self.handle_reset_segment_handler(data)\n elif req_type == 0x81:\n print(\"* Reset\")\n await self.handle_reset(data)\n elif req_type == 0x82:\n print(\"* Get Status\")\n await self.handle_get_status(data)\n elif req_type == 0x83:\n print(\"* Set Status\")\n await self.handle_set_status(data)\n elif req_type == 0x84:\n print(\"* Download Segment Request\")\n await self.handle_download_segment(data)\n elif req_type == 0x85:\n print(\"* Set Channel Code\")\n await self.handle_set_channel_code(data)\n print(\"* Channel code is now \" + channelCode)\n elif req_type == 0x8f:\n print(\"* Handle 0x8f\")\n await self.handle_0x8f_req(data)\n elif req_type == 0x10:\n print(\"got request type 10, sending time\")\n await self.send_time()\n await self.sendBytes(bytes([0x10, 0xe1]))\n \n else:\n print(\"* Req type {} is Unimplemented :(\".format(data[0]))\n await self.handle_unimplemented_req(data)\n except asyncio.exceptions.IncompleteReadError:\n connected = False\n print(\"Incomplete read error.\")\n except ConnectionResetError:\n connected = False\n print(\"Connection reset by peer.\")\n\n print(\"Closing session.\")\n\n\n async def send_ack(self):\n await self.sendBytes(bytes([0x10, 0x06]))\n\n # Pre-formed time packet, sends Jan 1 1984 at 00:00:00\n # Todo - add proper time packet generation and CRC\n\n def get_time_bytes(self):\n data = bytearray([0x7f, 0xff, 0xff, 0x00, 0x01, 0x7f, 0xff, 0xff, 0xff, 0x7f, 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02])\n now = time.localtime()\n data.append(now.tm_wday + 2) # 2 seems to be the correct offset, if 1=Sun, 2=Mon, 3=Tue, etc...\n data.append(0x54) # This is 1984, forever\n data.append(now.tm_mon)\n data.append(now.tm_mday)\n data.append(now.tm_hour)\n data.append(now.tm_min)\n data.append(now.tm_sec)\n crc = Crc16Genibus.calc(data) # Empirically gives us the right CRC\n data.append(crc >> 8 & 0xff)\n data.append(crc & 0xff)\n return bytes(data)\n\n async def send_time(self):\n time_bytes = self.get_time_bytes()\n escaped_time_bytes = self.escapeUploadBytes(time_bytes)\n await self.sendBytes(escaped_time_bytes)\n\n # TODO: We can probably get rid of handle_0xf0_request, handle_0x0f_request and handle_0x03_request\n # TODO: as these bytes may have been from RS-422 buffer overruns / other errors\n\n async def handle_0xf0_request(self, data):\n await self.send_ack()\n\n async def handle_0x05_request(self, data):\n await self.send_ack()\n\n async def handle_0x06_request(self, data):\n await self.send_ack()\n\n async def handle_0x0f_request(self, data):\n await self.send_ack()\n\n async def handle_0x03_request(self, data):\n await self.send_ack()\n\n async def handle_reset_segment_handler(self, data):\n await self.sendBytes(bytes([0x10, 0x06, 0xe4]))\n\n async def handle_reset(self, data):\n await self.send_ack()\n\n async def handle_get_status(self, data):\n global channelCode\n await self.send_ack()\n response = await self.recvBytes()\n print(\"Response is of type {}\".format(type(response)))\n print(\"Len(response) = {}\".format(len(response)))\n print(\"Sent ack\")\n if channelCode is None:\n print(\"* Channel Code is not set yet.\")\n # Ask NPC to set channel code\n await self.sendBytes(bytes([0x9f, 0x10, 0xe1]))\n else:\n print(\"* Channel code is set to \" + channelCode)\n # Report that channel code is already set\n await self.sendBytes(bytes([0x1f, 0x10, 0xe1]))\n\n async def handle_set_status(self, data):\n await self.sendBytes(bytes([0x10, 0x06, 0xe4]))\n\n async def handle_download_segment(self, data):\n # ; segment load request\n # [11] NPC $84\n # NA $10 06\n await self.send_ack()\n data=await self.recvBytesExactLen(4)\n packetNumber=data[0]\n segmentNumber=bytes(reversed(data[1:4]))\n segmentId=str(segmentNumber.hex())\n print(\"* Requested Segment ID: \" + segmentId)\n print(\"* Requested PacketNumber: \" + str(packetNumber))\n if segmentId == \"7fffff\":\n print(\"Time packet requested\")\n await self.sendBytes(bytes([0xe4, 0x91]))\n segmentId == \"\"\n response = await self.recvBytesExactLen(2)\n print(\"* Response from NPC: \" + response.hex(\" \"))\n print(\"segmentId\", segmentId)\n print(\"packetnumber\", packetNumber)\n print(\"segments\", NabuAdaptor.segments)\n await self.send_time()\n await self.sendBytes(bytes([0x10, 0xe1]))\n else:\n await self.sendBytes(bytes([0xe4, 0x91]))\n response = await self.recvBytesExactLen(2)\n print(\"* Response from NPC: \" + response.hex(\" \"))\n print(\"segmentId\", segmentId)\n print(\"packetnumber\", packetNumber)\n print(\"segments\", NabuAdaptor.segments)\n\n # Get Segment from internal segment store\n if segmentId not in NabuAdaptor.segments:\n self.loadpak(segmentId)\n segment = NabuAdaptor.segments[segmentId]\n\n # Get requested pack from that segment\n pack_data = segment.get_pack(packetNumber)\n\n # Dump information about pack. 'pack' is otherwise unused\n pack = NabuPack()\n pack.ingest_bytes(pack_data)\n print(\"* Pack to send: \" + pack_data.hex(' '))\n print(\"* pack_segment_id: \"+ pack.pack_segment_id.hex())\n print(\"* pack_packnum: \" + pack.pack_packnum.hex())\n print(\"* segment_owner: \" + pack.segment_owner.hex())\n print(\"* segment_tier: \" + pack.segment_tier.hex())\n print(\"* segment_mystery_bytes: \" + pack.segment_mystery_bytes.hex())\n print(\"* pack type: \" + pack.pack_type.hex())\n print(\"* pack_number: \" + pack.pack_number.hex())\n print(\"* pack_offset: \" + pack.pack_offset.hex())\n print(\"* pack_crc: \" + pack.pack_crc.hex())\n print(\"* pack length: {}\".format(len(pack_data)))\n\n # escape pack data (0x10 bytes should be escaped maybe?)\n escaped_pack_data = self.escapeUploadBytes(pack_data)\n await self.sendBytes(escaped_pack_data)\n await self.sendBytes(bytes([0x10, 0xe1]))\n\n async def handle_set_channel_code(self, data):\n global channelCode\n await self.send_ack()\n data = await self.recvBytesExactLen(2)\n while len(data) < 2:\n remaining = 2 - len(data)\n print(\"Waiting for channel code\")\n print(data.hex(' '))\n if(remaining > 0):\n data = data + await self.recvBytesExactLen(remaining)\n\n print(\"* Received Channel code bytes: \" + data.hex())\n channelCode = bytes(reversed(data)).hex()\n print(\"* Channel code: \" + channelCode)\n await self.sendBytes(bytes([0xe4]))\n\n async def handle_0x8f_req(self, data):\n print(\"* 0x8f request\")\n if len(data) < 2:\n print(\"Waiting for throwaway data\")\n data = await self.recvBytesExactLen(1)\n await self.sendBytes(bytes([0xe4]))\n\n def handle_unimplemented_req(self, data):\n print(\"* ??? Unimplemented request\")\n print(\"* \" + data.hex(' '))\n\n def escapeUploadBytes(self, data):\n escapedBytes = bytearray()\n\n for idx in range(len(data)):\n byte=data[idx]\n if(byte == 0x10):\n escapedBytes.append(byte)\n escapedBytes.append(byte)\n else:\n escapedBytes.append(byte)\n\n return escapedBytes\n\n async def sendBytes(self, data):\n chunk_size=2000\n index=0\n end=len(data)\n\n while index + chunk_size < end:\n self.writer.write(data[index:index+chunk_size])\n print(\"NA-->NPC: \" + data[index:index+chunk_size].hex(' '))\n index += chunk_size\n\n if index != end:\n print(\"NA-->NPC: \" + data[index:end].hex(' '))\n self.writer.write(data[index:end])\n\n # await self.writer.drain()\n # print(\"Drained.\")\n\n\n async def recvBytesExactLen(self, length=None):\n if(length is None):\n return None\n data = await self.reader.readexactly(length)\n print(\"NPC-->NA: \" + data.hex(' '))\n return data\n\n\n async def recvBytes(self, length = None):\n if(length is None):\n length = MAX_READ\n data = await self.reader.read(length)\n\n if(len(data) > 0):\n print(\"NPC-->NA: \" + data.hex(' '))\n else:\n print(\"NBC->NA: Zero data. Disconnected??\")\n return data\n\n\n###### Begin main code here\n\nDEFAULT_BAUDRATE=111863\n# channelCode = None\nchannelCode = '0000'\n\nparser = argparse.ArgumentParser()\n# Positional argument for ttyname - required\nparser.add_argument(\"-t\", \"--ttyname\",\n help=\"Set serial device (e.g. /dev/ttyUSB0)\")\n# Optional argument for baudrate\nparser.add_argument(\"-b\", \"--baudrate\",\n type=int,\n help=\"Set serial baud rate (default: {} BPS)\".format(DEFAULT_BAUDRATE),\n default=DEFAULT_BAUDRATE)\nargs = parser.parse_args()\n\n# TODO: We should change this to handle .nabu files instead, which have not yet been split into packets with headers and checksums\n\nasync def handle_connection(reader, writer):\n nabu_session = NabuAdaptor(reader,writer)\n await nabu_session.run_NabuSession()\n\nasync def start_tcp_server():\n server = await asyncio.start_server(\n handle_connection, '0.0.0.0', 5816)\n addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets)\n print(f'Serving TCP on {addrs}')\n return server\n\n\nasync def start_serial_session(ttyname, baudrate):\n print(f'Starting serial session on {ttyname} at {baudrate} bps')\n reader, writer = await serial_asyncio.open_serial_connection(url=ttyname, baudrate=args.baudrate, stopbits=serial.STOPBITS_TWO, timeout=0.5)\n await handle_connection(reader, writer)\n\nasync def main(args):\n\n sessions = []\n\n # setup TCP session\n server = await start_tcp_server()\n sessions.append(server.serve_forever())\n\n # Serial session if enabled\n if args.ttyname is not None:\n serial_session = await start_serial_session(args.ttyname, args.baudrate)\n sessions.append(serial_session)\n else:\n print(\"No serial connection configured.\")\n\n await asyncio.gather(\n *sessions\n )\n\nprint (\"Started...\")\nasyncio.run(main(args))\n\n","repo_name":"mdebreceni/nabu-pc-playground","sub_path":"nabu-adaptor-emu/nabu-adaptor-emu.py","file_name":"nabu-adaptor-emu.py","file_ext":"py","file_size_in_byte":13930,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"51"} +{"seq_id":"4452879318","text":"import requests, json\r\nimport csv\r\n\r\nf= open(\"D:\\Covid 19\\crawl so lieu nhiem covid thoi diem chon\\output.csv\", \"w\", encoding='UTF8')\r\nwriter = csv.writer(f,lineterminator='\\n') \r\n\r\nres_api = requests.get('https://static.pipezero.com/covid/data.json')\r\ndata_js = res_api.text\r\ndt_js = json.loads(data_js)\r\n\r\nheader = [\"Thành phố\", \"Số ca chết\", \"Số ca đang điều trị\", \"Số ca nhiễm\", \"Số ca phục hồi\", \"Số ca nhiễm trong ngày\"]\r\nwriter.writerow(header)\r\nfor i in range(63):\r\n\r\n print('counter',i)\r\n name = dt_js['locations'][i]['name']\r\n death = dt_js['locations'][i]['death']\r\n treating = dt_js['locations'][i]['treating']\r\n cases = dt_js['locations'][i]['cases']\r\n recoverd = dt_js['locations'][i]['recovered']\r\n casesToday = dt_js['locations'][i]['casesToday']\r\n str1 = [name, death, treating, cases, recoverd, casesToday]\r\n \r\n writer.writerow(str1)\r\n\r\nf.close()\r\n ","repo_name":"Mioson819/Craw-data-covid-19-vn","sub_path":"Covid 19/crawl so lieu nhiem covid thoi diem chon/craw.py","file_name":"craw.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"29577054218","text":"# Inspired by: https://github.com/ChawDoe/LeNet5-MNIST-PyTorch\n# LeNet paper: \"Gradient-based learning applied to document recognition\"\nfrom torch.nn import Module\nfrom torch import nn\n\n\nclass FMCGNet(Module):\n def __init__(self):\n super(FMCGNet, self).__init__()\n self.conv1 = nn.Conv2d(1, 6, 5)\n self.relu1 = nn.ReLU()\n self.pool1 = nn.MaxPool2d(2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.relu2 = nn.ReLU()\n self.pool2 = nn.MaxPool2d(2)\n self.fc1 = nn.Linear(256, 120)\n self.relu3 = nn.ReLU()\n self.fc2 = nn.Linear(120, 84)\n self.relu4 = nn.ReLU()\n self.fc3 = nn.Linear(84, 10)\n self.relu5 = nn.ReLU()\n\n def forward(self, x):\n y = self.conv1(x)\n y = self.relu1(y)\n y = self.pool1(y)\n y = self.conv2(y)\n y = self.relu2(y)\n y = self.pool2(y)\n y = y.view(y.shape[0], -1)\n y = self.fc1(y)\n y = self.relu3(y)\n y = self.fc2(y)\n y = self.relu4(y)\n y = self.fc3(y)\n y = self.relu5(y)\n return y\n","repo_name":"Redcof/FMCGNet","sub_path":"model/fmcgnet.py","file_name":"fmcgnet.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"71926237917","text":"from django.urls import path\n\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\nfrom apps.chessgames.views import (\n AnonymousChessGameViewSet,\n ChessGameViewSet,\n)\n\n\nchessgame_list = ChessGameViewSet.as_view({\n 'get': 'list',\n 'post': 'create'\n})\nchessgame_detail = ChessGameViewSet.as_view({\n 'get': 'retrieve',\n 'delete': 'destroy'\n})\nchessgame_move = ChessGameViewSet.as_view({\n 'post': 'move'\n})\nchessgame_legal_moves = ChessGameViewSet.as_view({\n 'get': 'legal_moves'\n})\nanon_chessgame_list = AnonymousChessGameViewSet.as_view({\n 'get': 'list',\n 'post': 'create',\n})\nanon_chessgame_detail = AnonymousChessGameViewSet.as_view({\n 'get': 'retrieve',\n 'delete': 'destroy',\n})\n\nurlpatterns = format_suffix_patterns([\n path('chessgames/', chessgame_list),\n path('chessgames//', chessgame_detail),\n path('chessgames//legal-moves/', chessgame_legal_moves),\n path('chessgames//legal-moves//', chessgame_legal_moves),\n path('chessgames//move///', chessgame_move),\n path('chessgames/anonymous/', anon_chessgame_list),\n path('chessgames/anonymous//', anon_chessgame_detail),\n])\n","repo_name":"danhalv/play_chess","sub_path":"apps/chessgames/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"74467323037","text":"# Write a Python program to calculate the product of the unique numbers in a given list.\ndef unique_product(lst):\n unique_number=set(lst)\n p=1\n for i in unique_number:\n p*=i\n return p\nlst= [10, 20, 30, 40, 20, 50, 60, 40]\np=unique_product(lst)\nprint(p)\n","repo_name":"GABBAR-AMIT/code","sub_path":"List/list_125.py","file_name":"list_125.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"26593577910","text":"# -*- coding: utf-8 -*-\n\"\"\"The storage merge reader.\"\"\"\n\nfrom plaso.containers import event_sources\nfrom plaso.containers import events\nfrom plaso.containers import reports\nfrom plaso.containers import tasks\nfrom plaso.containers import warnings\nfrom plaso.storage import logger\n\n\nclass StorageMergeReader(object):\n \"\"\"Storage reader for merging.\n\n Attributes:\n number_of_containers (int): number of containers merged in last call to\n MergeAttributeContainers.\n \"\"\"\n\n _CONTAINER_TYPE_ANALYSIS_REPORT = reports.AnalysisReport.CONTAINER_TYPE\n _CONTAINER_TYPE_ANALYSIS_WARNING = warnings.AnalysisWarning.CONTAINER_TYPE\n _CONTAINER_TYPE_EVENT = events.EventObject.CONTAINER_TYPE\n _CONTAINER_TYPE_EVENT_DATA = events.EventData.CONTAINER_TYPE\n _CONTAINER_TYPE_EVENT_DATA_STREAM = events.EventDataStream.CONTAINER_TYPE\n _CONTAINER_TYPE_EVENT_SOURCE = event_sources.EventSource.CONTAINER_TYPE\n _CONTAINER_TYPE_EVENT_TAG = events.EventTag.CONTAINER_TYPE\n _CONTAINER_TYPE_EXTRACTION_WARNING = warnings.ExtractionWarning.CONTAINER_TYPE\n _CONTAINER_TYPE_PREPROCESSING_WARNING = (\n warnings.PreprocessingWarning.CONTAINER_TYPE)\n _CONTAINER_TYPE_RECOVERY_WARNING = warnings.RecoveryWarning.CONTAINER_TYPE\n _CONTAINER_TYPE_TASK_COMPLETION = tasks.TaskCompletion.CONTAINER_TYPE\n _CONTAINER_TYPE_TASK_START = tasks.TaskStart.CONTAINER_TYPE\n\n # Some container types reference other container types, such as event\n # referencing event_data. Container types in this tuple must be ordered after\n # all the container types they reference.\n _CONTAINER_TYPES = (\n _CONTAINER_TYPE_EVENT_SOURCE,\n _CONTAINER_TYPE_EVENT_DATA_STREAM,\n _CONTAINER_TYPE_EVENT_DATA,\n _CONTAINER_TYPE_EVENT,\n _CONTAINER_TYPE_EVENT_TAG,\n _CONTAINER_TYPE_EXTRACTION_WARNING,\n _CONTAINER_TYPE_RECOVERY_WARNING,\n _CONTAINER_TYPE_ANALYSIS_REPORT,\n _CONTAINER_TYPE_ANALYSIS_WARNING)\n\n def __init__(self, session, storage_writer, task_storage_reader):\n \"\"\"Initializes a storage merge reader.\n\n Args:\n session (Session): session the task is part of.\n storage_writer (StorageWriter): storage writer.\n task_storage_reader (StorageReader): task storage reader.\n \"\"\"\n super(StorageMergeReader, self).__init__()\n self._active_container_type = None\n self._active_generator = None\n self._container_types = []\n self._event_data_identifier_mappings = {}\n self._event_data_parser_mappings = {}\n self._event_data_stream_identifier_mappings = {}\n self._session = session\n self._storage_writer = storage_writer\n self._task_storage_reader = task_storage_reader\n\n self.number_of_containers = 0\n\n def Close(self):\n \"\"\"Closes the merge reader.\"\"\"\n self._task_storage_reader.Close()\n self._task_storage_reader = None\n\n def AddAttributeContainer(self, container):\n \"\"\"Adds an attribute container.\n\n Args:\n container (AttributeContainer): attribute container.\n \"\"\"\n if container.CONTAINER_TYPE == self._CONTAINER_TYPE_EVENT:\n event_data_identifier = container.GetEventDataIdentifier()\n event_data_lookup_key = event_data_identifier.CopyToString()\n\n event_data_identifier = self._event_data_identifier_mappings.get(\n event_data_lookup_key, None)\n\n if event_data_identifier:\n container.SetEventDataIdentifier(event_data_identifier)\n else:\n identifier = container.GetIdentifier()\n identifier_string = identifier.CopyToString()\n\n # TODO: store this as a merge warning so this is preserved\n # in the storage file.\n logger.error((\n 'Unable to merge event attribute container: {0:s} since '\n 'corresponding event data: {1:s} could not be found.').format(\n identifier_string, event_data_lookup_key))\n return\n\n elif container.CONTAINER_TYPE == self._CONTAINER_TYPE_EVENT_DATA:\n event_data_stream_identifier = container.GetEventDataStreamIdentifier()\n event_data_stream_lookup_key = None\n if event_data_stream_identifier:\n event_data_stream_lookup_key = (\n event_data_stream_identifier.CopyToString())\n\n event_data_stream_identifier = (\n self._event_data_stream_identifier_mappings.get(\n event_data_stream_lookup_key, None))\n\n if event_data_stream_identifier:\n container.SetEventDataStreamIdentifier(event_data_stream_identifier)\n elif event_data_stream_lookup_key:\n identifier = container.GetIdentifier()\n identifier_string = identifier.CopyToString()\n\n # TODO: store this as a merge warning so this is preserved\n # in the storage file.\n logger.error((\n 'Unable to merge event data attribute container: {0:s} since '\n 'corresponding event data stream: {1:s} could not be '\n 'found.').format(identifier_string, event_data_stream_lookup_key))\n return\n\n if container.CONTAINER_TYPE in (\n self._CONTAINER_TYPE_EVENT_DATA,\n self._CONTAINER_TYPE_EVENT_DATA_STREAM):\n # Preserve the lookup key before adding it to the attribute container\n # store.\n identifier = container.GetIdentifier()\n lookup_key = identifier.CopyToString()\n\n if container.CONTAINER_TYPE == self._CONTAINER_TYPE_EVENT_TAG:\n self._storage_writer.AddOrUpdateEventTag(container)\n else:\n self._storage_writer.AddAttributeContainer(container)\n\n if container.CONTAINER_TYPE == self._CONTAINER_TYPE_EVENT:\n parser_name = self._event_data_parser_mappings.get(\n event_data_lookup_key, 'N/A')\n self._session.parsers_counter[parser_name] += 1\n self._session.parsers_counter['total'] += 1\n\n elif container.CONTAINER_TYPE == self._CONTAINER_TYPE_EVENT_DATA:\n identifier = container.GetIdentifier()\n self._event_data_identifier_mappings[lookup_key] = identifier\n\n parser_name = container.parser.split('/')[-1]\n self._event_data_parser_mappings[lookup_key] = parser_name\n\n elif container.CONTAINER_TYPE == self._CONTAINER_TYPE_EVENT_DATA_STREAM:\n identifier = container.GetIdentifier()\n self._event_data_stream_identifier_mappings[lookup_key] = identifier\n\n def MergeAttributeContainers(self, maximum_number_of_containers=0):\n \"\"\"Reads attribute containers from a task store into the writer.\n\n Args:\n maximum_number_of_containers (Optional[int]): maximum number of\n containers to merge, where 0 represent no limit.\n\n Returns:\n bool: True if the entire task storage file has been merged.\n \"\"\"\n if not self._container_types:\n self._container_types = list(self._CONTAINER_TYPES)\n\n if not self._active_container_type:\n logger.debug('Starting merge')\n else:\n logger.debug('Continuing merge of: {0:s}'.format(\n self._active_container_type))\n\n self.number_of_containers = 0\n\n while self._active_generator or self._container_types:\n if not self._active_generator:\n self._active_container_type = self._container_types.pop(0)\n self._active_generator = (\n self._task_storage_reader.GetAttributeContainers(\n self._active_container_type))\n\n try:\n container = next(self._active_generator)\n self.number_of_containers += 1\n except StopIteration:\n container = None\n self._active_generator = None\n\n if container:\n self.AddAttributeContainer(container)\n\n if 0 < maximum_number_of_containers <= self.number_of_containers:\n break\n\n merge_completed = not self._active_generator and not self._container_types\n\n logger.debug('Merged {0:d} containers'.format(self.number_of_containers))\n\n return merge_completed\n","repo_name":"RobinsonShai/plaso","sub_path":"plaso/storage/merge_reader.py","file_name":"merge_reader.py","file_ext":"py","file_size_in_byte":7698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"51"} +{"seq_id":"39870516882","text":"\"\"\"\nBuilds the portfolio page by interpolating YAML data into the template files\n\"\"\"\n\nfrom global_vars import *\nimport yaml\n\n# read data and template files\nwith open(PortfolioDataPath, 'r') as fin:\n p_data = yaml.load(fin.read())\nwith open(PortfolioTemplatePath, 'r') as fin:\n p_template = fin.read()\nwith open(PortfolioItemTemplatePath, 'r') as fin:\n p_item_template = fin.read()\nwith open(MasterTemplatePath, 'r') as fin:\n m_template = fin.read()\n\n# inline short template strings that we don't bother to put into separate files\nnav_category_template = '
  • \\\n \\\n
    \">\\\n \\\n
    \\\n
  • '\nnav_item_template = '\" class=\"nav-link\" href=\"#\">'\naction_button_template = '\" target=\"\" class=\"btn btn-primary\" data-toggle=\"tooltip\" title=\"\">\\\n\" aria-hidden=\"true\">'\nimage_slide_template = '
    \">\\\n \" alt=\"image slide\">\\\n
    '\nyoutube_slide_template = '
    \">\\\n \\\n
    '\n\nfa_icons = {\n 'github': 'fa-github',\n 'external': 'fa-external-link',\n 'download': 'fa-download',\n 'play': 'fa-gamepad'\n}\ntooltip_defaults = {\n 'github': 'Fork on GitHub',\n 'external': 'View Site',\n 'download': 'Download Project',\n 'play': 'Play Game'\n}\n\n# initialize navigation links\nnav_snippets = {}\nfor category in p_data['categories']:\n nav_snippets[category['id']] = []\n\n# iterate through each portfolio item and generate snippets for each\nitem_counter = 0\nitems = []\nfor item in p_data['items']:\n # create the navigation link\n nav_item = templateSubN({\n 'item_title': item['title'],\n 'item_id': item_counter\n }, nav_item_template)\n nav_snippets[item['category']].append(nav_item)\n\n # action buttons\n action_buttons = []\n for action in item['resources']:\n if action['type'] in list(fa_icons.keys()):\n action_buttons.append(templateSubN({\n 'button_icon': fa_icons[action['type']],\n 'button_link': action['link'],\n 'button_target': '_blank' if action['type'] not in ['download', 'play'] else '_self',\n 'button_tooltip': action['tooltip'] if 'tooltip' in action else tooltip_defaults[action['type']]\n }, action_button_template))\n\n # carousel slides\n carousel_slides = []\n player_count = 0\n for slide in item['resources']:\n slide_active = 'active' if len(carousel_slides) == 0 else ''\n if slide['type'] == 'image':\n carousel_slides.append(templateSubN({\n 'slide_src': slide['link'],\n 'slide_active': slide_active\n }, image_slide_template))\n elif slide['type'] == 'youtube':\n carousel_slides.append(templateSubN({\n 'slide_src': slide['link'],\n 'slide_active': slide_active,\n 'item_id': item_counter,\n 'player_num': player_count\n }, youtube_slide_template))\n player_count += 1\n\n # create the portfolio item\n p_item = templateSubN({\n 'item_carousel_slides': '\\n'.join(carousel_slides),\n 'item_buttons': '\\n'.join(action_buttons),\n 'item_description': item['description'],\n 'item_subtitle': item['subtitle'],\n 'item_title': item['title'],\n 'item_id': item_counter\n }, p_item_template)\n\n # save snippet and inc id counter\n items.append(p_item)\n item_counter += 1\n\n# construct nav\nnav = ''\ncategory_counter = 0\nfor category in p_data['categories']:\n nav_list = '\\n'.join(nav_snippets[category['id']])\n nav += templateSubN({\n 'category_items': nav_list,\n 'category_name': category['name'],\n 'category_dropdown_type': 'dropdown-menu-right' if category_counter == len(p_data['categories']) - 1 else ''\n }, nav_category_template) + '\\n'\n category_counter += 1\n\n# build whole page\np = templateSubN({\n 'portfolio_items': '\\n'.join(items),\n 'nav_links': nav\n}, p_template)\nm = templateSubN({\n 'body': p,\n 'portfolio_active': 'active',\n 'cv_active': '',\n 'path_prefix': '',\n 'title': 'Portfolio'\n}, m_template)\n\n# write to file\nwith open(PortfolioOutputPath, 'w') as fout:\n fout.write(m)\n","repo_name":"SebastianJay/SebastianJay.github.io","sub_path":"scripts/make_portfolio.py","file_name":"make_portfolio.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"19731388035","text":"import sys\r\nfrom PyQt5.uic import loadUi\r\nfrom PyQt5 import QtWidgets\r\nfrom PyQt5.QtWidgets import QDialog, QApplication, QWidget, QMainWindow, QStyle\r\nfrom PyQt5.QtGui import QPixmap, QIcon\r\nimport sqlite3\r\n##################################################################################\r\n#Homepage Window Loading\r\n###################################################################################\r\nclass Homepage(QMainWindow):\r\n def __init__(self):\r\n super(Homepage,self).__init__()\r\n loadUi(\"Homepage.ui\",self)\r\n logobg=QPixmap('WhatsApp Image 2022-03-22 at 5.44.11 PM.jpeg')\r\n self.label_4.setPixmap(logobg)\r\n homimg=QPixmap('WhatsApp Image 2022-03-22 at 5.44.09 PM.jpeg')\r\n self.label_2.setPixmap(homimg)\r\n loginimg=QIcon('WhatsApp Image 2022-03-16 at 3.47.24 PM.jpeg')\r\n self.LoginButton.setIcon(loginimg)\r\n infoimg=QPixmap('WhatsApp Image 2022-03-22 at 5.44.10 PM.jpeg')\r\n self.label_3.setPixmap(infoimg)\r\n self.AdminLogin.clicked.connect(self.gotoadminlogin)\r\n self.LoginButton.clicked.connect(self.gotouserlogin)\r\n self.Register.clicked.connect(self.gotouserreg)\r\n def gotoadminlogin(self):\r\n adlogin=AdminLogin()\r\n widget.addWidget(adlogin)\r\n widget.setCurrentIndex(widget.currentIndex()+1)\r\n def gotouserlogin(self):\r\n uslogin = Userlogin()\r\n widget.addWidget(uslogin)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n def gotouserreg(self):\r\n usreg = userregister()\r\n widget.addWidget(usreg)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n#####################################################################\r\n#Admin Login Window Loading\r\n######################################################################\r\nclass AdminLogin(QMainWindow):\r\n def __init__(self):\r\n super(AdminLogin,self).__init__()\r\n loadUi(\"FinalAdminLogin.ui\",self)\r\n Adminphoto=QPixmap('1.jpg')\r\n self.label_2.setPixmap(Adminphoto)\r\n self.LoginButton.clicked.connect(self.gotoadmindashboard)\r\n self.BackButton.clicked.connect(self.gotohomepage)\r\n def gotohomepage(self):\r\n gohom=Homepage()\r\n widget.addWidget(gohom)\r\n widget.setCurrentIndex(widget.currentIndex()+1)\r\n def gotoadmindashboard(self):\r\n user=self.usernamefield.text()\r\n password=self.passfield.text()\r\n if len(user)==0 or len(password)==0:\r\n self.label_3.setText(\"Please input all the fields\")\r\n else:\r\n connection = sqlite3.connect(\"ADMINLOGIN1.db\")\r\n result = connection.execute(\"SELECT * FROM admintable WHERE Username =? AND Password =? \",(user, password))\r\n if(len(result.fetchall())>0):\r\n print(\"Succesfully logined\")\r\n self.label_3.setText(\"\")\r\n admindash=AdminDashboard()\r\n widget.addWidget(admindash)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n else:\r\n self.label_3.setText(\"Invalid Username or Password\")\r\n##################################################################################\r\n#Admin Dashboard Window Loading\r\n##################################################################################\r\nclass AdminDashboard(QMainWindow):\r\n def __init__(self):\r\n super(AdminDashboard,self).__init__()\r\n loadUi(\"FinalDashboard.ui\",self)\r\n logobg1 = QPixmap('WhatsApp Image 2022-03-22 at 5.44.11 PM.jpeg')\r\n self.label_22.setPixmap(logobg1)\r\n dashicon = QIcon('WhatsApp Image 2022-03-16 at 3.47.21 PM.jpeg')\r\n self.pushButton.setIcon(dashicon)\r\n searchlogo = QPixmap('WhatsApp Image 2022-03-16 at 3.47.20 PM.jpeg')\r\n self.label_2.setPixmap(searchlogo)\r\n heartbg = QPixmap('WhatsApp Image 2022-03-16 at 3.47.13 PM.jpeg')\r\n self.label_5.setPixmap(heartbg)\r\n bedlogobg = QPixmap('WhatsApp Image 2022-03-16 at 3.47.18 PM.jpeg')\r\n self.label_8.setPixmap(bedlogobg)\r\n ventlogobg = QPixmap('WhatsApp Image 2022-03-16 at 3.47.23 PM.jpeg')\r\n self.label_11.setPixmap(ventlogobg)\r\n revlogobg = QPixmap('WhatsApp Image 2022-03-16 at 3.47.20 PM (1).jpeg')\r\n self.label_14.setPixmap(revlogobg)\r\n declogobg = QPixmap('WhatsApp Image 2022-03-16 at 3.47.15 PM.jpeg')\r\n self.label_16.setPixmap(declogobg)\r\n addlogobg = QPixmap('WhatsApp Image 2022-03-16 at 3.47.12 PM.jpeg')\r\n self.label_20.setPixmap(addlogobg)\r\n self.pushButton_4.clicked.connect(self.gotoho)\r\n self.pushButton_3.clicked.connect(self.gotot)\r\n self.pushButton_6.clicked.connect(self.gotoht)\r\n def gotoht(self):\r\n gotoht = hostable()\r\n widget.addWidget(gotoht)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n def gotoho(self):\r\n gohom = Homepage()\r\n widget.addWidget(gohom)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n def gotot(self):\r\n gotot=patable()\r\n widget.addWidget(gotot)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n#########################################################################\r\n#User Login Window Loading\r\n##########################################################################\r\nclass Userlogin(QMainWindow):\r\n def __init__(self):\r\n super(Userlogin,self).__init__()\r\n loadUi(\"FinalLogin.ui\",self)\r\n loginphoto=QPixmap('1.jpg')\r\n self.label_2.setPixmap(loginphoto)\r\n self.backButton.clicked.connect(self.gotohomepage1)\r\n self.LoginButton1.clicked.connect(self.gotouserdashboard)\r\n self.createbutton.clicked.connect(self.gotoregis)\r\n def gotohomepage1(self):\r\n gohom=Homepage()\r\n widget.addWidget(gohom)\r\n widget.setCurrentIndex(widget.currentIndex()+1)\r\n def gotouserdashboard(self):\r\n user = self.lineEdit.text()\r\n password = self.lineEdit_2.text()\r\n if len(user) == 0 or len(password) == 0:\r\n self.label_3.setText(\"Please input all the fields\")\r\n else:\r\n connection = sqlite3.connect(\"userdata1.db\")\r\n result = connection.execute(\"SELECT * FROM logintable WHERE username =? AND password =? \",(user, password))\r\n if (len(result.fetchall()) > 0):\r\n print(\"Succesfully logined\")\r\n self.label_3.setText(\"\")\r\n userdash = Userdashboard()\r\n widget.addWidget(userdash)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n else:\r\n self.label_3.setText(\"Invalid Username or Password\")\r\n def gotoregis(self):\r\n usregis = userregister()\r\n widget.addWidget(usregis)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n####################################################################################################\r\n#User Registeratiion Login Window\r\n#####################################################################################################\r\nclass userregister(QMainWindow):\r\n def __init__(self):\r\n super(userregister,self).__init__()\r\n loadUi(\"FinalRegister.ui\",self)\r\n regphoto=QPixmap('1.jpg')\r\n self.label_2.setPixmap(regphoto)\r\n self.bacButton.clicked.connect(self.gotohomepage2)\r\n self.SubmitButton.clicked.connect(self.userregdone)\r\n self.GotoLogin.clicked.connect(self.gotouslogin)\r\n def gotohomepage2(self):\r\n gohom=Homepage()\r\n widget.addWidget(gohom)\r\n widget.setCurrentIndex(widget.currentIndex()+1)\r\n def userregdone(self):\r\n firstandlastname=self.lineEdit_fname.text()\r\n username=self.lineEdit_username.text()\r\n middlename=self.lineEdit_Mname.text()\r\n email=self.lineEdit_Email.text()\r\n mobile=self.lineEdit_Mobile.text()\r\n password=self.lineEdit_pass.text()\r\n gender=self.lineEdit_Gender.text()\r\n confirmpass=self.lineEdit_8.text()\r\n if len(firstandlastname) == 0 or len(username) == 0 or len(middlename) == 0 or len(email)==0 or len(mobile)==0 or len(password)==0 or len(gender)==0 or len(confirmpass)==0:\r\n self.label_3.setText(\"Please fill in all inputs.\")\r\n elif password != confirmpass:\r\n self.label_3.setText(\"Passwords do not match.\")\r\n else:\r\n con = sqlite3.connect(\"userdata1.db\")\r\n query = \"insert into userdata(firstandlastname,username,middlename,email,mobile,password,gender,confirmpass) values ('\" + firstandlastname + \"','\" + username + \"','\" + middlename + \"','\" + email + \"','\" + mobile + \"','\" + password + \"','\" + gender + \"','\" + confirmpass + \"' )\"\r\n query1 = \"insert into logintable(username,password) values ('\" + username + \"','\" + password + \"')\"\r\n con.execute(query)\r\n con.execute(query1)\r\n con.commit()\r\n con.close()\r\n print(\"register successfully\")\r\n self.label_3.setText(\"\")\r\n userlogin=Userlogin()\r\n widget.addWidget(userlogin)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n def gotouslogin(self):\r\n uselogin = Userlogin()\r\n widget.addWidget(uselogin)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n################################################################################################\r\n#UserDashboard Window Loading\r\n################################################################################################\r\nclass Userdashboard(QMainWindow):\r\n def __init__(self):\r\n super(Userdashboard,self).__init__()\r\n loadUi(\"FinalUserdashboard.ui\",self)\r\n logobg12 = QPixmap('WhatsApp Image 2022-03-22 at 5.44.11 PM.jpeg')\r\n self.label_22.setPixmap(logobg12)\r\n dashicon = QIcon('WhatsApp Image 2022-03-16 at 3.47.21 PM.jpeg')\r\n self.pushButton.setIcon(dashicon)\r\n searchlogo = QPixmap('WhatsApp Image 2022-03-16 at 3.47.20 PM.jpeg')\r\n self.label_2.setPixmap(searchlogo)\r\n heartbg = QPixmap('WhatsApp Image 2022-03-16 at 3.47.13 PM.jpeg')\r\n self.label_5.setPixmap(heartbg)\r\n bedlogobg = QPixmap('WhatsApp Image 2022-03-16 at 3.47.18 PM.jpeg')\r\n self.label_8.setPixmap(bedlogobg)\r\n ventlogobg = QPixmap('WhatsApp Image 2022-03-16 at 3.47.23 PM.jpeg')\r\n self.label_11.setPixmap(ventlogobg)\r\n revlogobg = QPixmap('WhatsApp Image 2022-03-16 at 3.47.20 PM (1).jpeg')\r\n self.label_14.setPixmap(revlogobg)\r\n declogobg = QPixmap('WhatsApp Image 2022-03-16 at 3.47.15 PM.jpeg')\r\n self.label_16.setPixmap(declogobg)\r\n addlogobg = QPixmap('WhatsApp Image 2022-03-16 at 3.47.12 PM.jpeg')\r\n self.label_20.setPixmap(addlogobg)\r\n self.pushButton_4.clicked.connect(self.gotoho)\r\n self.pushButton_5.clicked.connect(self.gotobed)\r\n self.pushButton_3.clicked.connect(self.bedavail)\r\n def gotoho(self):\r\n gohom = Homepage()\r\n widget.addWidget(gohom)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n def gotobed(self):\r\n gotobed = Bookbed()\r\n widget.addWidget(gotobed)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n def bedavail(self):\r\n gotoavail = bedavail()\r\n widget.addWidget(gotoavail)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n############################################################\r\n####Book Bed Window Loading\r\n#############################################################\r\nclass Bookbed(QMainWindow):\r\n def __init__(self):\r\n super(Bookbed, self).__init__()\r\n loadUi(\"bb.ui\", self)\r\n logodoc12 = QPixmap('Doctor.jpeg')\r\n self.label_2.setPixmap(logodoc12)\r\n self.pushButton_2.clicked.connect(self.gtodash)\r\n self.pushButton.clicked.connect(self.confirm)\r\n def gtodash(self):\r\n gotdash = Userdashboard()\r\n widget.addWidget(gotdash)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n def confirm(self):\r\n name=self.lineEdit.text()\r\n email = self.lineEdit_2.text()\r\n date =self.lineEdit_3.text()\r\n gender = self.lineEdit_5.text()\r\n mobile = self.lineEdit_6.text()\r\n bed=self.lineEdit_4.text()\r\n if len(name) == 0 or len(email) == 0 or len(date) == 0 or len(gender) == 0 or len(mobile) == 0 or len(bed) == 0:\r\n self.label_9.setText(\"Please fill in all inputs.\")\r\n else:\r\n con = sqlite3.connect(\"ADMINLOGIN1.db\")\r\n query = \"insert into confrim(name,email,date,gender,mobile,bed) values ('\" + name + \"','\" + email + \"','\" + date + \"','\" + gender + \"','\" + mobile + \"','\" + bed + \"' )\"\r\n con.execute(query)\r\n con.commit()\r\n con.close()\r\n print(\"bed confirm successfully\")\r\n self.label_9.setText(\"Your Bed is Succesfully booked\")\r\n conmess = success()\r\n widget.addWidget(conmess)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n######################################################\r\n#Bed Booking Confqrimation Window\r\n######################################################\r\nclass success(QMainWindow):\r\n def __init__(self):\r\n super(success, self).__init__()\r\n loadUi(\"success.ui\", self)\r\n logodoc12 = QPixmap('WhatsApp Image 2022-03-22 at 5.44.11 PM.jpeg')\r\n self.label.setPixmap(logodoc12)\r\n logodoc123= QPixmap('WhatsApp Image 2022-04-07 at 7.30.21 PM.jpeg')\r\n self.label_2.setPixmap(logodoc123)\r\n self.pushButton.clicked.connect(self.gotous)\r\n def gotous(self):\r\n gotdash = Userdashboard()\r\n widget.addWidget(gotdash)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n############################################################\r\n#Loading patient list\r\n############################################################\r\nclass patable(QDialog):\r\n def __init__(self):\r\n super(patable, self).__init__()\r\n loadUi(\"tabletutorial.ui\", self)\r\n self.tableWidget.setColumnWidth(0, 350)\r\n self.tableWidget.setColumnWidth(1, 350)\r\n self.tableWidget.setColumnWidth(2, 350)\r\n self.tableWidget.setColumnWidth(3, 350)\r\n self.tableWidget.setColumnWidth(4, 350)\r\n self.tableWidget.setColumnWidth(5, 350)\r\n self.tableWidget.setHorizontalHeaderLabels([\"Name\", \"Email\", \"Date\", \"Gender\", \"Mobile\", \"Bed\"])\r\n self.pushButton.clicked.connect(self.gotodash)\r\n self.loaddata()\r\n def loaddata(self):\r\n connection = sqlite3.connect('ADMINLOGIN1.db')\r\n cur = connection.cursor()\r\n sqlstr = 'SELECT * FROM confrim LIMIT 40'\r\n tablerow = 0\r\n results = cur.execute(sqlstr)\r\n self.tableWidget.setRowCount(40)\r\n for row in results:\r\n self.tableWidget.setItem(tablerow, 0, QtWidgets.QTableWidgetItem(row[0]))\r\n self.tableWidget.setItem(tablerow, 1, QtWidgets.QTableWidgetItem(row[1]))\r\n self.tableWidget.setItem(tablerow, 2, QtWidgets.QTableWidgetItem(row[2]))\r\n self.tableWidget.setItem(tablerow, 3, QtWidgets.QTableWidgetItem(row[3]))\r\n self.tableWidget.setItem(tablerow, 4, QtWidgets.QTableWidgetItem(row[4]))\r\n self.tableWidget.setItem(tablerow, 5, QtWidgets.QTableWidgetItem(row[5]))\r\n tablerow += 1\r\n def gotodash(self):\r\n admindash = AdminDashboard()\r\n widget.addWidget(admindash)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n######################################################\r\n#Loading haspital adding table\r\n###########################################################\r\nclass hostable(QDialog):\r\n def __init__(self):\r\n super(hostable, self).__init__()\r\n loadUi(\"Hopitaltable.ui\", self)\r\n self.tableWidget.setColumnWidth(0, 250)\r\n self.tableWidget.setColumnWidth(1, 250)\r\n self.tableWidget.setColumnWidth(2, 500)\r\n self.tableWidget.setColumnWidth(3, 500)\r\n self.tableWidget.setHorizontalHeaderLabels([\"Hospital Name\", \"Address\", \"Count of the Single Beds\", \"Count of the ICU Beds\"])\r\n self.pushButton_2.clicked.connect(self.addhos)\r\n self.pushButton_4.clicked.connect(self.loadda)\r\n self.pushButton.clicked.connect(self.gotoadmindashboarded)\r\n def addhos(self):\r\n name = self.lineEdit.text()\r\n address = self.lineEdit_2.text()\r\n sbeds = self.lineEdit_3.text()\r\n ibeds = self.lineEdit_4.text()\r\n if len(name) == 0 or len(address) == 0 or len(sbeds) == 0 or len(ibeds) == 0:\r\n self.label_2.setText(\"Please fill in all inputs.\")\r\n else:\r\n con = sqlite3.connect(\"ADMINLOGIN1.db\")\r\n query = \"insert into hosdata (name,address,sbeds,ibeds) values ('\" + name + \"','\" + address + \"','\" + sbeds + \"','\" + ibeds + \"')\"\r\n con.execute(query)\r\n con.commit()\r\n con.close()\r\n print(\"Hopital added succesfully\")\r\n self.label_3.setText(\"Hopital added succesfully\")\r\n def loadda(self):\r\n connection = sqlite3.connect('ADMINLOGIN1.db')\r\n cur = connection.cursor()\r\n sqlstr = 'SELECT * FROM hosdata LIMIT 100'\r\n tablerow = 0\r\n results = cur.execute(sqlstr)\r\n self.tableWidget.setRowCount(100)\r\n for row in results:\r\n self.tableWidget.setItem(tablerow, 0, QtWidgets.QTableWidgetItem(row[0]))\r\n self.tableWidget.setItem(tablerow, 1, QtWidgets.QTableWidgetItem(row[1]))\r\n self.tableWidget.setItem(tablerow, 2, QtWidgets.QTableWidgetItem(row[2]))\r\n self.tableWidget.setItem(tablerow, 3, QtWidgets.QTableWidgetItem(row[3]))\r\n tablerow += 1\r\n def gotoadmindashboarded(self):\r\n addash = AdminDashboard()\r\n widget.addWidget(addash)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n########################################################\r\n#Loading bed availablity window\r\n#########################################################\r\nclass bedavail(QDialog):\r\n def __init__(self):\r\n super(bedavail, self).__init__()\r\n loadUi(\"bedavail.ui\", self)\r\n self.tableWidget.setColumnWidth(0, 250)\r\n self.tableWidget.setColumnWidth(1, 250)\r\n self.tableWidget.setColumnWidth(2, 500)\r\n self.tableWidget.setColumnWidth(3, 500)\r\n self.tableWidget.setHorizontalHeaderLabels([\"Hospital Name\", \"Address\", \"Count of the Single Beds\", \"Count of the ICU Beds\"])\r\n self.pushButton.clicked.connect(self.gotouserdash)\r\n self.loadbed()\r\n def loadbed(self):\r\n connection = sqlite3.connect('ADMINLOGIN1.db')\r\n cur = connection.cursor()\r\n sqlstr = 'SELECT * FROM hosdata LIMIT 100'\r\n tablerow = 0\r\n results = cur.execute(sqlstr)\r\n self.tableWidget.setRowCount(100)\r\n for row in results:\r\n self.tableWidget.setItem(tablerow, 0, QtWidgets.QTableWidgetItem(row[0]))\r\n self.tableWidget.setItem(tablerow, 1, QtWidgets.QTableWidgetItem(row[1]))\r\n self.tableWidget.setItem(tablerow, 2, QtWidgets.QTableWidgetItem(row[2]))\r\n self.tableWidget.setItem(tablerow, 3, QtWidgets.QTableWidgetItem(row[3]))\r\n tablerow += 1\r\n def gotouserdash(self):\r\n userdash = Userdashboard()\r\n widget.addWidget(userdash)\r\n widget.setCurrentIndex(widget.currentIndex() + 1)\r\n################################################################\r\n#loading and exiting the window\r\n#main\r\napp=QApplication(sys.argv)\r\nHomepag=Homepage()\r\nwidget = QtWidgets.QStackedWidget()\r\nwidget.addWidget(Homepag)\r\nwidget.show()\r\nwidget.setFixedWidth(1150)\r\nwidget.setFixedHeight(700)\r\ntry:\r\n sys.exit(app.exec())\r\nexcept:\r\n print(\"Exiting\")","repo_name":"RJ2601/Patient-And-Bed-Management-System","sub_path":"Patient And Bed Management System/Final Miniproject/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":19775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"43839259450","text":"import pygame\nfrom ecs.ECS import set_handler\nfrom ecs.ECS import dispatch_event\nfrom screen import Screen\nfrom settings import settings\nfrom Systems.Game import Game\nfrom Systems.Menu import Menu\nimport pygame, sys, threading\n\nclass GameController:\n def __init__(self):\n pygame.init()\n\n self.screen = Screen(settings.scr_width,\n settings.scr_height,\n settings.scr_caption,\n settings.scr_image)\n self._game = Game(self.screen)\n self._menu = Menu(self.screen)\n\n set_handler(\"menu\", self.menu)\n set_handler(\"game\", self.game)\n set_handler(\"exit\", self.exit)\n self.menu()\n\n def menu(self):\n dispatch_event(\"scripts_asyncs\", False)\n self._menu.run()\n\n def game(self):\n dispatch_event(\"scripts_asyncs\", True)\n self._game.run()\n\n def exit(self):\n dispatch_event(\"scripts_asyncs\", False)\n cur_th = threading.current_thread()\n for th in threading.enumerate():\n if cur_th != th:\n th.join()\n pygame.quit()\n sys.exit()\n","repo_name":"Proklink/SpaceAdventure","sub_path":"Systems/GameController.py","file_name":"GameController.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"30250700235","text":"\"\"\"Point here is to create a utility function to create the baba dataframe.\"\"\"\n# %%\nfrom thesisutils import utils\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\n\nimport logging\n# %%\ndef dfprep(pub: utils.Publication, filter=False):\n \"\"\"gets df-date merged and filters for scmp and hkfp for \n alibaba containing articles.\n \n :param filter: True for HKFP and SCMP where no specific \n baba dataset. \n \"\"\"\n print(pub.name)\n if pub.name in (\"nyt\", \"chinadaily\", \"globaltimes\"):\n args = [\"baba\", f\"{pub.name}_full.csv\"]\n else:\n args = [f\"{pub.name}_full.csv\"]\n df = utils.main_date_load(pub, True, *args)\n if filter:\n mask = df.Textcol.str.lower().str.contains(\"alibaba\")\n print(\"fitering...\")\n print(mask.value_counts(dropna=False))\n df = df[mask]\n return df\n\n\n\n# %%\ncd = dfprep(utils.publications[\"chinadaily\"], True)\ncd.Year.value_counts().sort_index()\n# %%\nnyt = dfprep(utils.publications[\"nyt\"], True)\nnyt.Year.value_counts().sort_index()\n# %%\nscmp = dfprep(utils.publications[\"scmp\"], True)\nscmp.Year.value_counts().sort_index()\n# %% \nglobaltimes = dfprep(utils.publications[\"globaltimes\"], True)\nglobaltimes.Year.value_counts().sort_index()\n# %%\nhkfp = dfprep(utils.publications[\"hkfp\"], True)\nhkfp.Year.value_counts().sort_index()\nval_cnts = scmp.Year.value_counts()#.plot()\nval_cnts.sort_index().plot()\n\n# months starting with 1/2011 as first month and 12/2021 as 132. \n# 61 is our rough starting point of 1/2016\n# scmp[\"monthid\"] = (scmp.Year - 2011)*12 + scmp.Month\n# max(scmp.monthid)\n\n# monthgrouped = scmp.groupby(\"monthid\").size()\n# for i in range(0, 133):\n# if i not in monthgrouped.index:\n# monthgrouped.loc[i] = 0\n# monthgrouped = monthgrouped.sort_index()\n\nmaindf = pd.concat([nyt, cd, scmp, globaltimes, hkfp] )\nmaindf = maindf[maindf.Year.ge(2011)]\nutils.just_letters()\nmaindf['headlow'] = maindf.Headline.str.lower().apply(utils.justletters)\n# drop duplicate headlines from same year. \nmaindf = maindf.drop_duplicates(subset=['headlow', 'Year'])\nmaindf.head()\nmaindf.Year.value_counts(dropna=False)\nmaindf['cnt'] = 1\nmaindfgrouped = maindf.groupby([\"Publication\", \"Year\"]).size().rename(\"Alibaba mentions\")\nmaindfgrouped\n# gotta clean up this code\n# %%\n# plotting yearly alibaba mentions by each publication\nax = sns.lineplot(x=\"Year\", y=\"Alibaba mentions\", hue=\"Publication\", data=maindfgrouped.reset_index()) \nax.set_title(\"Figure _._: Mentions of Alibaba per Year\")\nax\n\n# %%\ndef meanb4after(df):\n \"\"\"Gets average mentions before and after 2016\"\"\"\n cutoff = 2015\n val_cnts = df.Year.value_counts()\n # if missing year, fill with zero. \n for i in range(2011, 2022):\n if i not in val_cnts.index:\n val_cnts.loc[i] = 0\n val_cnts = val_cnts.sort_index()\n pre16 = val_cnts.loc[2011:cutoff]\n post16 = val_cnts.loc[cutoff+1:2022]\n before = pre16.mean()\n after = post16.mean()\n print(\"percent change = \", 100*(after-before)/before)\n return before, after\n# %%\nny = meanb4after(nyt)\n# %% \nsc = meanb4after(scmp)\n# %\ngt = meanb4after(globaltimes)\n# %%\nc = meanb4after(cd)\n# %%\nhk = meanb4after(hkfp)\n\n# %%\n# Run for table with before and after\n\ntabledf = pd.DataFrame(np.array([ny, hk, gt, c, sc]),\n index=[\"NYT\", \"HKFP\", \"Global Times\", \"China Daily\", \"SCMP\"],\n columns = [\"pre-2016\", \"post-2016\"]\n )\ntabledf[\"% increase\"] = 100*(tabledf[\"post-2016\"] - tabledf[\"pre-2016\"])/ tabledf[\"pre-2016\"]\npd.options.display.precision = 0\ndisplay(tabledf)\npd.options.display.precision = 5\n\n\n# COMPETITOR ANALYSIS #########################\n# %%\npub = utils.publications[\"scmp\"]\nargs = [f\"{pub.name}_full.csv\"]\n\nscmpfull = utils.main_date_load(pub, True, *args)\nscmpfull['textcollower'] = scmpfull.Textcol.str.lower()\n # %% \n \ndef searchterm(term,df = scmpfull):\n \"\"\"Looks up a term in df.textcollower\"\"\"\n term = term.lower()\n mask = df.textcollower.str.contains(term)\n print(\"fitering...\")\n print(mask.value_counts(dropna=False))\n return df[mask]\n\n# %%\ntencent = searchterm(\"tencent\")\nten = meanb4after(tencent)\nbaidu = searchterm(\"baidu\")\nbai = meanb4after(baidu)\njd = searchterm(\"jd.com\")\nj = meanb4after(jd)\ntaobao = searchterm(\"taobao\")\ntb = meanb4after(taobao)\nwechat = searchterm(\"wechat\")\nwc = meanb4after(wechat)\npingduoduo = searchterm(\"pingduoduo\")\npdd = meanb4after(pingduoduo)\ndidi = searchterm(\"didi\")\ndd = meanb4after(didi)\nbytedance = searchterm(\"bytedance\")\nbd = meanb4after(bytedance)\n\n# %%\ntabledf = pd.DataFrame(np.array([sc, ten, bai, j, tb, wc]),\n index=[\"Alibaba\", \"Tencent\", \"Baidu\", \"JD.com\", \"Taobao\", \"WeChat\"],\n columns = [\"pre-2016\", \"post-2016\"]\n )\ntabledf[\"% increase\"] = 100*(tabledf[\"post-2016\"] - tabledf[\"pre-2016\"])/ tabledf[\"pre-2016\"]\npd.options.display.precision = 0\ndisplay(tabledf)\npd.options.display.precision = 5\n\n\n# %%\n# old analysis ignore.\npub = utils.publications['scmp']\nscmp = utils.get_df(pub)\nsections = utils.get_df(pub, \"sections\", \"sections.csv\")\ndatedf = utils.get_df(pub, \"date\", \"date.csv\")\nscmp = scmp.merge(sections, on=\"Index\")\nscmp = scmp.merge(datedf, on=\"Index\")\n# \nscmp['textcol'] = scmp.Headline + scmp.Body\nmask = scmp.Body.isna()\n\n\nnas = scmp[mask]\nnas.section0.value_counts()\nlen(nas)\n# 12267 nans bodys; but 11,000 are sport or yp so not a big deal'=;\n# %%\nscmp.textcol.str.contains(\"Alibaba\").value_counts()\n# 5000 baba stories\n# %%\nscmp.textcol.str.lower().str.contains(\"alibaba\").value_counts()\n# 5008\n# %%\npub = utils.publications['hkfp']\nhkfp = utils.get_df(pub)\nhkfp['textcol'] = hkfp[pub.headline] + hkfp[pub.textcol]\nhkfp.textcol.str.contains(\"Alibaba\").value_counts()\nhkfp.textcol.str.lower().str.contains(\"alibaba\").value_counts()\n# 178 hkfp\n# %%\npub = utils.publications['nyt']\nnyt = utils.get_df(pub, \"baba\", \"nyt_full.csv\")\nnyt\n# 1048 articles\n# %%\npub = utils.publications['globaltimes']\ngt = utils.get_df(pub, \"baba\", f\"{pub.name}_full.csv\")\n\n# 4688 articles\n# %%\npub = utils.publications['chinadaily']\ncd = utils.get_df(pub, \"baba\", f\"{pub.name}_full.csv\")\n# 7547 articles\n# %% \n","repo_name":"tlebryk/exploration_and_processing","sub_path":"edas/baba_poc.py","file_name":"baba_poc.py","file_ext":"py","file_size_in_byte":6078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"74541115999","text":"from . import enums\r\n\r\n# Most of these constants are deprecated, use the enum mentioned instead. (Or\r\n# whatever is after the '=', even if its not an enum.)\r\n\r\nkvmOK = 0\r\nkvmFail = enums.Error.FAIL\r\nkvmERR_PARAM = enums.Error.PARAM\r\nkvmERR_LOGFILEOPEN = enums.Error.LOGFILEOPEN\r\nkvmERR_NOSTARTTIME = enums.Error.NOSTARTTIME\r\nkvmERR_NOLOGMSG = enums.Error.NOLOGMSG\r\nkvmERR_LOGFILEWRITE = enums.Error.LOGFILEWRITE\r\nkvmEOF = enums.Error.FAIL\r\nkvmERR_NO_DISK = enums.Error.NO_DISK\r\nkvmERR_LOGFILEREAD = enums.Error.LOGFILEREAD\r\n\r\nkvmERR_QUEUE_FULL = enums.Error.QUEUE_FULL\r\nkvmERR_CRC_ERROR = enums.Error.CRC_ERROR\r\nkvmERR_SECTOR_ERASED = enums.Error.SECTOR_ERASED\r\nkvmERR_FILE_ERROR = enums.Error.FILE_ERROR\r\nkvmERR_DISK_ERROR = enums.Error.DISK_ERROR\r\nkvmERR_DISKFULL_DIR = enums.Error.DISKFULL_DIR\r\nkvmERR_DISKFULL_DATA = enums.Error.DISKFULL_DATA\r\nkvmERR_SEQ_ERROR = enums.Error.SEQ_ERROR\r\nkvmERR_FILE_SYSTEM_CORRUPT = enums.Error.FILE_SYSTEM_CORRUPT\r\nkvmERR_UNSUPPORTED_VERSION = enums.Error.UNSUPPORTED_VERSION\r\nkvmERR_NOT_IMPLEMENTED = enums.Error.NOT_IMPLEMENTED\r\nkvmERR_FATAL_ERROR = enums.Error.FATAL_ERROR\r\nkvmERR_ILLEGAL_REQUEST = enums.Error.ILLEGAL_REQUEST\r\nkvmERR_FILE_NOT_FOUND = enums.Error.FILE_NOT_FOUND\r\nkvmERR_NOT_FORMATTED = enums.Error.NOT_FORMATTED\r\nkvmERR_WRONG_DISK_TYPE = enums.Error.WRONG_DISK_TYPE\r\nkvmERR_TIMEOUT = enums.Error.TIMEOUT\r\nkvmERR_DEVICE_COMM_ERROR = enums.Error.DEVICE_COMM_ERROR\r\nkvmERR_OCCUPIED = enums.Error.OCCUPIED\r\nkvmERR_USER_CANCEL = enums.Error.USER_CANCEL\r\nkvmERR_FIRMWARE = enums.Error.FIRMWARE\r\nkvmERR_CONFIG_ERROR = enums.Error.CONFIG_ERROR\r\nkvmERR_WRITE_PROT = enums.Error.WRITE_PROT\r\n\r\nkvmDEVICE_MHYDRA = enums.Device.MHYDRA\r\nkvmDEVICE_MHYDRA_EXT = enums.Device.MHYDRA_EXT\r\n\r\nkvmFILE_KME24 = enums.FileType.KME24\r\nkvmFILE_KME25 = enums.FileType.KME25\r\nkvmFILE_KME40 = enums.FileType.KME40\r\nkvmFILE_KME50 = enums.FileType.KME50\r\n\r\nkvmLDF_MAJOR_CAN = enums.LoggerDataFormat.MAJOR_CAN # Used in Kvaser Memorator\r\n# (2nd generation)\r\nkvmLDF_MAJOR_CAN64 = enums.LoggerDataFormat.MAJOR_CAN64 # Used in Kvaser\r\n# Memorator (2nd generation) with extended data capabilities.\r\n","repo_name":"Kvaser/pycanlib","sub_path":"canlib/kvmlib/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"51"} +{"seq_id":"26634022183","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io\nimport h5py\n\nplt.rcParams['text.latex.preamble']=r\"\\usepackage{lmodern}\"\nparams = {'text.usetex' : True,'font.family' : 'lmodern','svg.fonttype':'none'}\nplt.rcParams.update(params)\n\n\n## ============================================================================\n## THEORETICAL ANALYSIS ##\n## ##\n## LOCALIZATION LENGTH OVER A RANDOM 1D BOTTOM ##\n## ##\n## ============================================================================\n\n\n############################ SETUP ############################\n\nN = 2048\n\nL = 4\n\nx = np.linspace(0,L,N)\ndx = L/N\n\nf = np.linspace(0.5,1.8,50)\n\nf7 = np.linspace(0.5,1.8,70)\n\n\n############################ LENGTH ############################\n\n\ndata_1 = h5py.File('/data/topo/exp/Xi_f_Sweep_Aff105_Rand25.mat','r')\n\ndata_4 = h5py.File('/data/topo/exp/Xi_f_Sweep_Aff30_Rand25.mat','r')\n\ntheo = scipy.io.loadmat('/data/topo/exp/zeta_th_L25_N9.mat')\n\nf_t = np.linspace(0,2.1,2000)\ng = np.load(\"/data/topo/exp/random.npy\",allow_pickle=True)\n\nxs_01 = np.load(\"/data/topo/data_A01_4096/loc_len.npy\",allow_pickle=True)\n\nxs_03 = np.load(\"/data/topo/random_1024/A_03/loc_len.npy\",allow_pickle=True)\nxs_1 = np.load(\"/data/topo/random_1024/A_1/loc_len.npy\",allow_pickle=True)\nxs_15 = np.load(\"/data/topo/random_1024/A_15/loc_len.npy\",allow_pickle=True)\nxs_4 = np.load(\"/data/topo/random_1024/A_4/loc_len.npy\",allow_pickle=True)\n\n\nfe_1 = data_1[\"freq\"]\nze_1 = np.array(data_1[\"zeta\"])\n\nfe_4 = data_4[\"freq\"]\nze_4 = np.array(data_4[\"zeta\"])\n\n\n############################ PLOT ############################\n\n\nfig, ax = plt.subplots(figsize=[12,9]) \n\n\n#plt.plot(f7,-1/xs_01,\"o\",color=\"y\",label=\"$\\epsilon=0.001$\")\n#plt.plot(f,-1/xs_1,\"--\",color=\"b\",label=\"$\\epsilon=0.001$\")\nplt.plot(f,-1/xs_15,\"--\",color=\"g\",label=\"$\\epsilon=0.01$\")\nplt.plot(f,-1/xs_4,\"--\",color=\"r\",label=\"$\\epsilon=0.04$\")\n\nplt.scatter(fe_1[:-1],ze_1[:-1]/100,color='g')\nplt.scatter(fe_4[:-1],ze_4[:-1]/100,color='r')\n\nplt.plot(f_t,0.01*g,color=\"k\")\n\nplt.ylim([-0.1,7])\n\n# plt.plot(x,y)\n# plt.plot(x,np.exp(a*x+b))\n\n# plt.semilogy()\n\nplt.ylim([-0.1,7])\nplt.xlim([0.3,1.85])\n\nplt.xlabel(\"$f$ [Hz]\",fontsize=25)\nplt.ylabel(\"$x_0$ [m]\",fontsize=25)\n\nax.tick_params(labelsize=20,direction=\"in\")\n\nmdic = {\"z15\": -1/xs_15, \"z4\": -1/xs_4, \"f\": f}\n\nscipy.io.savemat(\"simu_z_R.mat\", mdic)\n\n\nplt.savefig(\"random.pdf\")\n\n\n\nplt.show()\n","repo_name":"nofko/phy-code","sub_path":"waves/topological/basilisk/random_plot.py","file_name":"random_plot.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"36601768640","text":"import os\n\nfrom utils import log_trajectory_statistics\nfrom envs.envs import (ExpertInvertedPendulumEnv, AgentInvertedPendulumEnv, ExpertInvertedDoublePendulumEnv,\n AgentInvertedDoublePendulumEnv, ReacherEasyEnv, TiltedReacherEasyEnv, ThreeReacherEasyEnv,\n Tilted3ReacherEasyEnv, ExpertHalfCheetahEnv, LockedLegsHalfCheetahEnv, HopperEnv,\n HopperFlexibleEnv)\nfrom envs.manipulation_envs import PusherEnv, PusherHumanSimEnv, StrikerEnv, StrikerHumanSimEnv\nfrom samplers import Sampler\nfrom utils import save_expert_trajectories\n\n\ndef collect_prior_data(realm_name, max_timesteps=40000, prior_samples_location='prior_data'):\n \"\"\"Collect and save prior visual observations for an environment realm.\n\n Parameters\n ----------\n realm_name : Environment realm to collect the visual observations.\n max_timesteps : Maximum number of visual observations to collect, default is 40000.\n prior_samples_location : Folder to save the prior visual observations collected.\n \"\"\"\n if realm_name == 'InvertedPendulum' or realm_name == 'Inverted Pendulum':\n prior_envs = [ExpertInvertedPendulumEnv(), AgentInvertedPendulumEnv(),\n ExpertInvertedDoublePendulumEnv(), AgentInvertedDoublePendulumEnv()]\n prior_env_names = ['ExpertInvertedPendulum-v2', 'AgentInvertedPendulum-v2',\n 'ExpertInvertedDoublePendulum-v2', 'AgentInvertedDoublePendulum-v2']\n episode_limit = 50\n elif realm_name == 'Reacher':\n prior_envs = [ReacherEasyEnv(), TiltedReacherEasyEnv(),\n ThreeReacherEasyEnv(), Tilted3ReacherEasyEnv()]\n prior_env_names = ['ExpertReacherEasy-v2', 'AgentReacherEasy-v2',\n 'ExpertThreeReacherEasy-v2', 'AgentThreeReacherEasy-v2']\n episode_limit = 50\n elif realm_name == 'Hopper':\n prior_envs = [HopperEnv(), HopperFlexibleEnv()]\n prior_env_names = ['Hopper-v2', 'HopperFlexible-v2']\n episode_limit = 200\n elif realm_name == 'HalfCheetah' or realm_name == 'Half-Cheetah':\n prior_envs = [ExpertHalfCheetahEnv(), LockedLegsHalfCheetahEnv()]\n prior_env_names = ['HalfCheetah-v2', 'LockedLegsHalfCheetah-v2']\n episode_limit = 200\n elif realm_name == 'Pusher' or realm_name == '7DOF-Pusher':\n prior_envs = [PusherEnv(), PusherHumanSimEnv()]\n prior_env_names = ['Pusher-v2', 'PusherHumanSim-v2']\n episode_limit = 200\n elif realm_name == 'Striker' or realm_name == '7DOF-Striker':\n prior_envs = [StrikerEnv(), StrikerHumanSimEnv()]\n prior_env_names = ['Striker-v2', 'StrikerHumanSim-v2']\n episode_limit = 200\n else:\n print('Please select one of the implemented realms:'\n '(InvertedPendulum/Inverted Pendulum, Reacher, '\n 'Hopper, HalfCheetah/Half-Cheetah, '\n 'Striker/7DOF-Striker, Pusher/7DOF-Pusher')\n raise NotImplementedError\n\n episodes_n = int(max_timesteps // episode_limit)\n\n for env, env_name in zip(prior_envs, prior_env_names):\n saver_sampler = Sampler(env, episode_limit=episode_limit,\n init_random_samples=0, visual_env=True)\n traj = saver_sampler.sample_test_trajectories(None, 0.0, episodes_n, False)\n log_trajectory_statistics(traj['ret'])\n os.makedirs(prior_samples_location + '/' + env_name, exist_ok=True)\n save_expert_trajectories(traj, env_name, prior_samples_location,\n visual_data=True)\n print('Prior trajectories successfully saved.')\n","repo_name":"Aladoro/domain-robust-visual-il","sub_path":"collect_prior_data.py","file_name":"collect_prior_data.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"51"} +{"seq_id":"7380895946","text":"#!/data/software/conda/bin/python3.7\nimport os,sys\nimport time\nimport parasail\nfrom collections import deque\nimport re\n\"\"\"\nUsage:\n./MEAT.py $file.faa(prot) $file.pfam $blast_taget.txt [window=$int(bp)](optional, default=50000) [pfam_domain_similarity=$(float)](optional,default=0.0)\npfam annotations are generated by pfam_scan.pl\n#############################################################\n#********Mycology Exploring Annotation Tool*****************#\n#********************MEAT by ZHANG W************************#\n#******zhangww@big.ac.cn Wechat&TEL:18210123493**********#\n#***********Beijing Institute of Genomics, CAS, CN**********#\n#***********************************************************#\n#############################################################\n\n\"\"\"\n\n#********extract path*********#\n#print (os.path.abspath('genbank'))\ndef read_fasta(name):\n\tt=[]\n\twith open(name) as rawdata:\n\t\tfor line in rawdata:\n\t\t\tif line=='' or line=='\\n':\n\t\t\t\tcontinue\n\t\t\tif line[0]=='>':\n\t\t\t\tt.append(line.split()[0])\n\t\t\t\tt.append('')\n\t\t\tif line[0]!='>':\n\t\t\t\tt[-1]+=line.strip()\n\treturn t\n#print(read_fasta('test.faa'))\ndef get_gene_location(genename,gfflocations,gtflocations):\n\tchro,start,end='',0,0\n\tif gtflocations.split('.')[-1]=='gtf':\n#\t\tprint('GTF')\n\t\twith open(gtflocations) as los:\n\t\t\tfor lo in los:\n\t\t\t\tif len(lo.split('\\t'))<4:\n\t\t\t\t\tcontinue\n\t\t\t\tif lo.split('\\t')[2]=='CDS':\n#\t\t\t\t\tprint(lo.split('\\t')[-1].split(';')[0].split('\"')[-2])\n\t\t\t\t\tif lo.split('\\t')[-1].split(';')[0].split('\"')[-2]==genename:\n\t\t\t\t\t\tchro,start,end=lo.split('\\t')[0],min(int(lo.split('\\t')[3]),int(lo.split('\\t')[4])),max(int(lo.split('\\t')[3]),int(lo.split('\\t')[4]))\n\tif gfflocations.split('.')[-1]=='gff':\n\t\twith open(gfflocations) as los:\n\t\t\tfor lo in los:\n\t\t\t\tif len(lo.split('\\t'))<4:\n\t\t\t\t\tcontinue\n\t\t\t\tif lo.split('\\t')[2]=='CDS':\n#\t\t\t\t\tprint(lo.split('\\t')[-1].split(';')[0].split('XP_')[-1])\n\t\t\t\t\tif lo.split('\\t')[-1].split(';')[0].split('XP_')[-1]==genename.split('XP_')[-1]:\n\t\t\t\t\t\tchro,start,end=lo.split('\\t')[0],min(int(lo.split('\\t')[3]),int(lo.split('\\t')[4])),max(int(lo.split('\\t')[3]),int(lo.split('\\t')[4]))\n\treturn chro,start,end\ndef get_domain_sequence(protein_fasta,proteinID,pfamstart,pfamend):\n\tfor n in range(0,int(len(protein_fasta)/2)):\n\t\tif protein_fasta[2*n].split()[0][1:]==proteinID:\n\t\t\treturn protein_fasta[2*n+1][pfamstart-1:pfamend]\n\t\t\tbreak\ndef get_protein_sequence(protein_fasta,proteinID):\n\tfor n in range(0,int(len(protein_fasta)/2)):\n\t\tif protein_fasta[2*n].split()[0][1:]==proteinID:\n\t\t\treturn protein_fasta[2*n+1].strip()\n\t\t\tbreak\ndef get_gdna_sequence(genome_fasta,chroID,seqstart,seqend):\n\tfor n in range(0,int(len(genome_fasta)/2)):\n\t\tif genome_fasta[2*n].split()[0][1:]==chroID:\n\t\t\treturn genome_fasta[2*n+1][max([0,seqstart-1]):min([seqend,len(genome_fasta[2*n+1])-2])]\ndef protein_domain_similarity(sequence1,sequence2):\n\taaset=''.join([i for i in list(set(sequence1+sequence2))])\n\taamatrix=parasail.matrix_create(aaset,2,-2)\n\tparasail_result=parasail.sg_trace_scan_16(sequence1,sequence2,5,1,aamatrix)\n\tparasail_cigar=str(parasail_result.cigar.decode,'utf-8')\n\tt=[]\n\tz=''\n\tfor w in parasail_cigar:\n\t\tif ord(w)>=ord('0') and ord(w)<=ord('9'):\n\t\t\tz+=w\n\t\telse:\n\t\t\tif w=='=':\n\t\t\t\tt.append(int(z))\n\t\t\t\tz=''\n\t\t\telse:\n\t\t\t\tz=''\n#\tprint(parasail_cigar)\n\treturn sum(t)*2/(len(sequence1)+len(sequence2))\n\t\ndef main(query_protein,pfam_query,blast_query,window,similarity):\n\tsequence_containing_domains,pfam_annotation,query_annots=[],[],[]#1. get pfam domains and the corresponding genes\n\tfor p in pfam_query:\n\t\tif p[0]=='#' or p=='\\n':\n\t\t\tcontinue\n\t\tif len(p.split())==1:\n\t\t\tpfam_annotation.append(p.strip())\n\t\tif len(p.split())>6:\n\t\t\tquery_annots.append(p)\n\t\t\tpfam_annotation.append(p.split()[6])\n\tpfam_annotation =list(set(pfam_annotation))\n\tpfam_query=query_annots\n\tblast_annotation=list(set([annot.split()[1] for annot in blast_query]))#2. get blast genes and the annotations\n\tblast_index,blast_genes,blast_identity={annot.split()[0]:annot.split()[1] for annot in blast_query},[annot.split()[0] for annot in blast_query],{annot.split()[0]:float(annot.split()[2]) for annot in blast_query}\n\tblast_query_sequence=[''.join(('>',protein,'\\n',get_protein_sequence(query_protein,protein),'\\n')) for protein in blast_genes]\n\tprotein_query_sequence_output=open('{}_for_blast.fasta'.format(sys.argv[3].split('.')[0]),'w')\n\tprotein_query_sequence_output.writelines(blast_query_sequence)\n\tprotein_query_sequence_output.close()\t\n\tfilepaths={}#3. scan the genome paths\n\twith open('refseq_dic.txt') as refseqs:\n\t\tfor line in refseqs:\n\t\t\tfilepaths[line.split()[-1]]=''.join((os.path.abspath('refseq'),'/fungi/',line.split()[-1]))\n\twith open('genbank_dic.txt') as genbanks:\n\t\tfor line in genbanks:\n\t\t\ttry:\n\t\t\t\thave_dic_or_not=filepaths[line.split()[-1]]\n\t\t\texcept:\n\t\t\t\tfilepaths[line.split()[-1]]=''.join((os.path.abspath('genbank'),'/fungi/',line.split()[-1]))\n#*********get file names********#\n\tfor i,access in enumerate(filepaths):\n\t#\tif i>30:\n\t#\t\tbreak\n#\t\tif i<457:\n#\t\t\tcontinue\n\t\tprint(i,access,filepaths[access])\n\t\tfiledirs=os.listdir(filepaths[access])\n\t\tproteinname,dnaname,gffname,gtfname,pfamname='','','','',''\n\t\tfor filename in filedirs:#4. get the files in the folder\n\t\t\tif filename==access+'.fasta':\n\t\t\t\tdnaname=filename\n\t\t\tif filename==access+'.faa':\n\t\t\t\tproteinname=filename\n\t\t\tif filename==access+'.gff':\n\t\t\t\tgffname=filename\n\t\t\tif filename==access+'.gtf':\n\t\t\t\tgtfname=filename\n\t\t\tif filename==access+'.pfam':\n\t\t\t\tpfamname=filename\n\t\tprint (proteinname,dnaname,gffname,gtfname,pfamname)\n\t\tif not pfamname or not dnaname or not (gffname or gtfname) or not proteinname:\n\t\t\tcontinue\n\t\tprotein_sequence=read_fasta(''.join((filepaths[access],'/',proteinname)))\n\t\tgenome_sequence=read_fasta(''.join((filepaths[access],'/',dnaname)))\n\t\tgene_al={pfam:[] for pfam in pfam_annotation}#5. *******get pfam sequences\n\t\twith open(''.join((filepaths[access],'/',access,'.pfam'))) as all_pfams:\n\t\t\tfor pfam_annot in all_pfams:\n\t\t\t\tif pfam_annot[0]!='#' and pfam_annot!='\\n' and pfam_annot.split()[6] in pfam_annotation:\n\t\t\t\t\tgene_al[pfam_annot.split()[6]].append((pfam_annot.split()[6],pfam_annot.split()[0],get_gene_location(pfam_annot.split()[0],''.join((filepaths[access],'/',gffname)),''.join((filepaths[access],'/',gtfname))),int(pfam_annot.split()[1]),int(pfam_annot.split()[2])))\n#6. ***********get blast sequences\n\t\tos.system(\"blastp -db {0} -query '{1}_for_blast.fasta' -out {1}_blast.out -evalue 0.5 -outfmt 6\".format(''.join((filepaths[access],'/protein_blast')),sys.argv[3].split('.')[0]))\n\t\tblast_results={blast:[] for blast in blast_annotation}\n\t\twith open('{}_blast.out'.format(sys.argv[3].split('.')[0])) as query_sequence_blast_results:\n\t\t\tfor blast_result in query_sequence_blast_results:\n\t\t\t\tif 100*float(blast_result.split()[2])>blast_identity[blast_result.split()[0]]:\n\t\t\t\t\tblast_gene_location=(blast_index[blast_result.split()[0]],blast_result.split()[1],get_gene_location(blast_result.split()[1],''.join((filepaths[access],'/',gffname)),''.join((filepaths[access],'/',gtfname))),'Blast','-results')\n\t\t\t\t\tif blast_gene_location not in blast_results[blast_index[blast_result.split()[0]]]:\n\t\t\t\t\t\tblast_results[blast_index[blast_result.split()[0]]].append(blast_gene_location)\n\t\tgene_array=[]#7. put all the genes together and sort \n\t\tfor i,j in enumerate(gene_al):\n\t\t\tfor pfam,gene,(chro,start,end),pfamstart,pfamend in gene_al[j]:\n\t\t\t\tif chro and start:\n\t\t\t\t\tgene_array.append((pfam,gene,chro,start,end,pfamstart,pfamend))\n\t\tfor i,j in enumerate(blast_results):\n\t\t\tfor pfam,gene,(chro,start,end),pfamstart,pfamend in blast_results[j]:\n\t\t\t\tif chro and start:\n\t\t\t\t\tgene_array.append((pfam,gene,chro,start,end,pfamstart,pfamend))\n\t\t\n\t\tgene_array.sort(key=lambda x: x[3])\n\t\tgene_array.sort(key=lambda x: x[2])\n#\t\tprint(gene_array)\n\t\tif not gene_array:\n\t\t\tcontinue\n\t\tgenemer=[(gene_array[0])]#define initial windows\n\t\tgenemer=deque(genemer)\n\t\tfor gene in gene_array:#8. check if the window fullfil blast and pfam results\n\t\t\tsumpfam,sumblast,boolblast,boolpfam=1,1,{blast:False for blast in blast_annotation},{pfam:False for pfam in pfam_annotation}\n\t\t\tgenemer.append((gene))\n\t\t\twhile genemer[-1][2]!=genemer[0][2] or max(genemer[-1][3],genemer[-1][4])-min(genemer[0][4],genemer[0][3])>window:\n\t\t\t\tif len(genemer)==1:\n\t\t\t\t\tbreak\n\t\t\t\tt=genemer.popleft()\n#\t\t\tprint('after remove', genemer)\n\t\t\tfor gene in genemer:#8.1. blast check\n\t\t\t\tboolblast[gene[0]]=True\n\t\t\tfor _,i in enumerate(boolblast):\n\t\t\t\tsumblast*=boolblast[i]\n\t\t\tif not sumblast:\n\t\t\t\tcontinue\n\t\t\tfor gene in genemer:#8.2. domain check\n\t\t\t\tboolpfam[gene[0]]=True\n\t\t\t\n\t\t\tfor _,i in enumerate(boolpfam):\n\t\t\t\tsumpfam*=boolpfam[i] \n\t\t\tif sumpfam:\n#\t\t\t\tprint('Yes domain',genemer)\n\t\t\t\tsimlaritypfam=1\n\t\t\t\tsimpfam={pfam:False for pfam in pfam_annotation}\t\n\t\t\t\tquery_informations=deque((line.split()[6],line.split()[0],int(line.split()[1]),int(line.split()[2])) for line in pfam_query)\t\n\t\t\t\tfor q in query_informations:\n\t\t\t\t\tfor r in genemer:\n\t\t\t\t\t\tif q[0]==r[0]:\n\t\t\t\t\t\t\tif not get_domain_sequence(protein_sequence,r[1],r[5],r[6]):\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t#\t\t\tprint('domainq',get_domain_sequence(query_protein,q[1],q[2],q[3]),'domainr',get_domain_sequence(protein_sequence,r[1],r[5],r[6]))\n\t\t\t\t\t\t\tprint(protein_domain_similarity(get_domain_sequence(query_protein,q[1],q[2],q[3]),get_domain_sequence(protein_sequence,r[1],r[5],r[6])))\n\t\t\t\t\t\t\tif protein_domain_similarity(get_domain_sequence(query_protein,q[1],q[2],q[3]),get_domain_sequence(protein_sequence,r[1],r[5],r[6]))>similarity:\n\t\t\t\t\t\t\t\tsimpfam[q[0]]=True\n\t\t\t\tfor _,i in enumerate(simpfam):\n\t\t\t\t\tsimlaritypfam*=simpfam[i]\n\t\t\t\tif simlaritypfam:\n\t\t\t\t\tprint('All domain and genes present and similarities are OK',genemer)\n\t\t\t\t\tidentified_sequence=get_gdna_sequence(genome_sequence,genemer[0][2],genemer[0][3]-int(window),genemer[-1][4]+int(window))\n\t\t\t\t\tsequence_containing_domains.append((dnaname,identified_sequence,list(genemer)))\n\treturn sequence_containing_domains\n\t\t\t\t\t\t\t\t\t\n\n\n\n\n\n\t\n\t\t\t\t\n\nif __name__ =='__main__':\n\twindow=50000\n\tsimilarity=0.0\n\ttry:\n\t\twindow=int(sys.argv[4])\n\t\tsimilarity=float(sys.argv[4])\n\texcept:\n\t\tprint('Use default w=50000')\n\ttry:\n\t\tsimilarity=float(sys.argv[5])\n\texcept:\n\t\ta=0\n\tif similarity>1:\n\t\tsimilarity=0.0\n\tprint('Use similarity=',similarity,';\\tUse window=',window)\n\tquery_sequences=''\n\ttry:\n\t\tpfam_query=open(sys.argv[2]).readlines()\n\texcept:\n\t\tprint('Usage: ./MEAT.py $file.faa(prot) $file.pfam $blast_taget.txt [window=$int(bp)](optional, default=50000) [pfam_domain_similarity=$(float)](optional,default=0.0)\\ne.g.: ./MEAT.py query_sequence.fasta query_pfam.pfam blast_proteins.txt 50000 0.3')\n\t\tsys.exit()\n\tquery_sequence=read_fasta(sys.argv[1])\n\ttry:\n\t\tblast_query=open(sys.argv[3]).readlines()\n\texcept:\n\t\tprint('Usage: ./MEAT.py $file.faa(prot) $file.pfam $blast_taget.txt [window=$int(bp)](optional, default=50000) [pfam_domain_similarity=$(float)](optional,default=0.0)')\n\t\tsys.exit()\n\tsequence_containing_domains=main(query_sequence,pfam_query,blast_query,window,similarity)\n\toutputfile=open('meat_result{}.fasta'.format(time.time()),'w')\n\tfor s in sequence_containing_domains:\n\t\tif len(s[1])>window*10:\n\t\t\tcontinue\n#\t\tprint(s[2])\n\t\tannotation=''\n\t\tfor (domain,gene,chro,start,end,pfamstart,pfamend) in s[2]:\n\t\t\t\t annotation+='{0}:{1}-{2}|{3}:{4}-{5}//'.format(gene,start-s[2][0][3]+int(window),end-s[2][0][3]+int(window),domain,pfamstart,pfamend)\t\n\t\toutputfile.writelines('>{0} {1}\\n{2}\\n'.format(s[0],annotation,s[1]))\n\tos.system(\"mv {0}_for_blast.fasta bak/{0}_for_blast{1}.fasta\".format(sys.argv[3].split('.')[0],str(time.time())))\n\tos.system(\"mv {0}_blast.out bak/{0}_blast{1}.out\".format(sys.argv[3].split('.')[0],str(time.time())))\n","repo_name":"WarchiefZhangW/MEAT","sub_path":"MEAT.py","file_name":"MEAT.py","file_ext":"py","file_size_in_byte":11613,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"51"} +{"seq_id":"35256884429","text":"####\r\n# Each team's file must define four tokens:\r\n# team_name: a string\r\n# strategy_name: a string\r\n# strategy_description: a string\r\n# move: A function that returns 'c' or 'b'\r\n####\r\n\r\nteam_name = 'Win' # Only 10 chars displayed.\r\nstrategy_name = 'innocent till proven guilty'\r\nstrategy_description = 'If our teams score is a negative number then we will betray, if we have a positive number or a zero then we will collude'\r\n \r\ndef move(my_history, their_history, my_score, their_score):\r\n ''' Arguments accepted: my_history, their_history are strings.\r\n my_score, their_score are ints.\r\n \r\n Make my move.\r\n Returns 'c' or 'b'. \r\n '''\r\n\r\n if len(my_score)<0:\r\n return 'b'\r\n elif len(my_score)==0:\r\n return 'c'\r\n else:\r\n return 'c'","repo_name":"CSP-ArkCityHS-gregbuckbee/iterative-prisoners-dilemma-2p","sub_path":"team11.py","file_name":"team11.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"74194920477","text":"#!/usr/bin/env python2.7\n\nfrom __future__ import print_function, division\nimport matplotlib\nimport os\n#checks if there is a display to use.\nif os.environ.get('DISPLAY') is None:\n matplotlib.use('Agg')\n\nfrom matplotlib import rc\n# rc('font',**{'family': 'serif',\n# 'serif': ['DejaVu'],\n# 'size': 15})\nrc('text', usetex=True)\nrc('font', **{'family':'serif', 'serif':['Computer Modern Roman'], })\nrc('font', size=18)\n\nimport dtk\nimport sys\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport matplotlib.ticker as ticker\nimport matplotlib.patches as mpatches\nimport numpy as np\n\nfrom zmr import ZMR\n\n\ndef load_zmr(param_fname, sdss=False):\n if not sdss:\n fname = \"output/\"+param_fname+\"/zmr_lkhd_cores.param\"\n if sdss:\n fname = \"output/\"+param_fname+\"/zmr_sdss.param\"\n return ZMR(fname)\n \ndef plot_multiple_model_profiles_one_mass(sdss_zmr, model_zmrs, model_names, mass_i, spider_zmr=None):\n plt.figure()\n model_size = len(model_zmrs)\n colors = ['tab:blue', 'tab:orange', 'tab:green', 'tab:purple']\n for i in range(0, model_size):\n gal_density = model_zmrs[i].zmr_gal_density[0, mass_i, :]\n gal_density_err = model_zmrs[i].zmr_gal_density_err[0, mass_i, :]\n r_bins_cen = dtk.bins_avg(model_zmrs[i].r_bins)\n plt.plot(r_bins_cen, gal_density, label=model_names[i], color=colors[i], lw=2)\n plt.fill_between(r_bins_cen, gal_density-gal_density_err, gal_density+gal_density_err, color=colors[i], alpha=0.2)\n\n sdss_gal = sdss_zmr.zmr_gal_density[0, mass_i, :]\n sdss_gal_err = sdss_zmr.zmr_gal_density_err[0, mass_i, :]\n # plt.plot(r_bins_cen, sdss_zmr.zmr_gal_density[0, mass_i, :], 'k', label='SDSS', lw=2)\n # plt.fill_between(r_bins_cen, sdss_gal-sdss_gal_err, sdss_gal+sdss_gal_err, color='k', alpha=0.2)\n\n #offset for sdss vs spiders\n if spider_zmr is None: \n offset = 0\n else:\n offset = .005\n plt.errorbar(r_bins_cen-offset, sdss_gal, yerr=+sdss_gal_err, fmt='o',\n label='redMaPPer clusters', lw=2, color='k', capsize=0,\n )\n if spider_zmr is not None:\n spider_gal = spider_zmr.zmr_gal_density[0, mass_i, :]\n spider_gal_err = spider_zmr.zmr_gal_density_err[0, mass_i, :]\n plt.errorbar(r_bins_cen+offset, spider_gal, yerr=+spider_gal_err, fmt='o',\n label='SPIDERS clusters', lw=1, color='k', capsize=0, markerfacecolor='None')\n \n plt.yscale('log')\n plt.legend(loc='best', framealpha=0.0, ncol=2)\n title = r\"{:.2f}$<$log$_{{10}}$(M$_{{200m}}$)$<${:.2f}\".format(np.log10(sdss_zmr.m_bins[mass_i]), np.log10(sdss_zmr.m_bins[mass_i+1]))\n # plt.title(title)\n plt.text(0.05, 0.05, title, transform=plt.gca().transAxes)\n plt.xlabel(r'r/R$_{200}$')\n plt.ylabel(r\"Galaxy Surface Density\")\n plt.tight_layout()\n\ndef plot_profiles_mstar(param_base, mstar):\n # param_base = \"params/cfn/simet/mstar0/mean/a3_@model@.param\"\n # param_base = \"params/rmba/auto/make_all_OR.McClintock.high_richness.low_rez.min20.sh/crit/mstar0/OR_@model@.param\"\n param_base = param_base.replace(\"@mstar@\", mstar)\n models = [\"mi\", \"rd\", \"rm\", \"rd_rm\",]\n model_names = [\"Mi\", \"Rd\", \"Rm\", \"RdRm\",]\n param_fnames = [param_base.replace(\"@model@\", model) for model in models]\n model_zmrs = [load_zmr(param_fname) for param_fname in param_fnames]\n sdss_zmr = load_zmr(param_fnames[0], sdss=True) \n # spider_zmr = load_zmr(\"params/cfn/spider/mstar0/mean/bcg.xray_mass.rd.param\", sdss=True)\n plot_multiple_model_profiles_one_mass(sdss_zmr, model_zmrs, model_names, 0,)\n plot_multiple_model_profiles_one_mass(sdss_zmr, model_zmrs, model_names, 1,)\n plot_multiple_model_profiles_one_mass(sdss_zmr, model_zmrs, model_names, 2,)\n plot_multiple_model_profiles_one_mass(sdss_zmr, model_zmrs, model_names, 3,)\n # plot_multiple_model_profiles_one_mass(sdss_zmr, model_zmrs, model_names, 4,)\n # plot_multiple_model_profiles_one_mass(sdss_zmr, model_zmrs, model_names, 5,)\n\ndef plot_multiple_model_profiles(param_base, fig_dir):\n mstars = ['-1', '-0.5', '0', '0.5', '1']\n for mstar in mstars:\n plot_profiles_mstar(param_base, mstar)\n dtk.save_figs(fig_dir+\"/mstar\"+mstar+\"/\", extension=\".pdf\", reset_count=True)\n dtk.save_figs(fig_dir+\"/mstar\"+mstar+\"/\", extension=\".png\")\n plt.show()\n plt.close('all')\n\nif __name__ == \"__main__\":\n param_bases = {\"OR_McClintock\":\"params/rmba/auto/make_all_OR.McClintock.high_richness.low_rez.min20.sh/crit/mstar@mstar@/OR_@model@.param\",\n \"OR_Simet\": \"params/rmba/auto/make_all_OR.high_richness.low_rez.min20.sh/crit/mstar@mstar@/OR_@model@.param\",\n \"OR_Baxter\": \"params/rmba/auto/make_all_OR.Baxter.high_richness.low_rez.min20.sh/crit/mstar@mstar@/OR_@model@.param\",\n \"OR_Farahi\": \"params/rmba/auto/make_all_OR.Farahi.high_richness.low_rez.min20.sh/crit/mstar@mstar@/OR_@model@.param\"}\n\n if len(sys.argv) >= 2:\n plot_names = syst.argv[1:]\n else:\n plot_names = list(param_bases.keys())\n \n for plot_name in plot_names: \n plot_multiple_model_profiles(param_bases[plot_name], \"figs/\"+__file__+\"/\"+plot_name+\"/\") \n plt.show()\n","repo_name":"dkorytov/core_analysis","sub_path":"plot_multiple_model_profiles.py","file_name":"plot_multiple_model_profiles.py","file_ext":"py","file_size_in_byte":5276,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"13188264270","text":"from flask import Blueprint, jsonify, request\n\nimport requests\n\n\napi = Blueprint('api', __name__)\n\nORDER_DEPTH_URI = 'http://data.mtgox.com/api/1/BTCUSD/depth/fetch'\n\n\ndef get_rate(amount, type='asks'):\n data = requests.get(ORDER_DEPTH_URI).json()['return'][type]\n data = sorted(data, key=lambda d: d['price'], reverse=(type == 'bids'))\n\n sum_amounts = 0\n amounts = []\n prices = []\n for o in data:\n amounts.append(o['amount'])\n prices.append(o['price'])\n sum_amounts += amounts[-1]\n if sum_amounts >= amount:\n break\n\n return sum(o[0] * o[1] for o in zip(prices, amounts)) / sum(amounts)\n\n\n@api.route('/rate', methods=['POST'])\ndef rate():\n type = request.form.get('type')\n amount = request.form.get('amount', type=float)\n\n if None in (type, amount):\n return jsonify({'error': 'missing param'})\n\n if type not in ('bids', 'asks'):\n return jsonify({'error': 'type must be one of `asks`, `bids`'})\n\n rate = get_rate(amount, type=type)\n if rate is None:\n return jsonify({'error': 'error calculating exchange rate'})\n\n amount = amount * rate if type == 'bids' else amount / rate\n return jsonify({'rate': rate, 'amount': amount})\n","repo_name":"maxcountryman/rate","sub_path":"rate/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"27502754949","text":"import gym\nimport numpy as np\nfrom reinforce.agents import BaseAgent\nfrom typing import Optional\n\n\nclass Core:\n def __init__(self, agent: BaseAgent, env: gym.Env):\n self.agent = agent\n self.env = env\n\n def learn(self, n_episodes: Optional[int] = 1000) -> np.ndarray:\n rewards = np.zeros(n_episodes)\n for i in range(n_episodes):\n s, _ = self.env.reset()\n done = False\n print(i, self.agent.epsilon)\n while not done:\n a = self.agent.select_action(s)\n s_, r, done, _, _ = self.env.step(a)\n self.agent.update(s, a, s_, r, done)\n s = s_\n rewards[i] += r\n return rewards\n","repo_name":"jws-1/reinforce","sub_path":"reinforce/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"10538743309","text":"import cv2\nimport numpy as np\n\ncar_cascade = cv2.CascadeClassifier('cars.xml')\ncap = cv2.VideoCapture(0)\n\nwhile True:\n ret, frame = cap.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n cars = car_cascade.detectMultiScale(gray, 1.3, 5)\n for (x,y,w,h) in cars:\n cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)\n cv2.imshow('video', frame)\n if cv2.waitKey(5) == 27:\n break\n\ncv2.destroyAllWindows()\n\n","repo_name":"tunadurnal/dev","sub_path":"development/OpenCV/vehicle_detection.py","file_name":"vehicle_detection.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"16238100232","text":"from DAL.Local_DAL.fruitSize_dal import FruitSize_DAL\n\n\nclass FruitSize_BL:\n def __init__(self):\n self.fruitSize_dal = FruitSize_DAL()\n\n def get_fruitSize(self):\n fruitSize = self.fruitSize_dal.get_all_fruitSize()\n fruitSize_list = []\n for fSize in fruitSize:\n d = {}\n d['id'] = fSize.id\n d['size'] = fSize.size\n d['isActive'] = fSize.isActive\n fruitSize_list.append(d)\n\n return fruitSize_list\n\n def add_fruitSize(self, data):\n record = {'size': data['size'], 'isActive': data['isActive']}\n\n if (record['isActive'] == ''):\n record['isActive'] = False\n new_record = self.fruitSize_dal.add_fruitSize(record)\n return new_record\n\n def delete_fruitSize(self, id):\n status = self.fruitSize_dal.delete_fruitSize(id)\n return status\n\n def update_fruitSize(self, id, data):\n status = self.fruitSize_dal.update_fruitSize(id, data)\n return status\n","repo_name":"MayanAsifLevy/Aitan_Server_Almagor","sub_path":"BL/Local_BL/fruitSize_bl.py","file_name":"fruitSize_bl.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"22331321454","text":"# -*- coding:utf-8 -*-\n\"\"\"\nReference: https://github.com/auth0-samples/auth0-python-api-samples/tree/master/00-Starter-Seed\n\"\"\"\n\nimport json\n\nfrom six.moves.urllib.request import urlopen\nfrom jose import jwt\n\n\noptions = {\n \"verify_aud\": False,\n \"verify_exp\": True,\n \"verify_iss\": True\n}\n\nclass TokenExpiredException(Exception):\n message = 'token is expired'\n def __init__(self):\n super(TokenExpiredException, self).__init__(self.message)\n\nclass Auth0Connector(object):\n \"\"\"A connector between auth0 and current requests\"\"\"\n def __init__(\n self,\n domain,\n api_identifier,\n algorithms=None,\n jwks_cache_timeout=0,\n **kwargs\n ):\n self.cache = None\n self.domain = domain\n self.api_identifier = api_identifier\n self.algorithms = algorithms or ['RS256']\n self.jwks_cache_timeout = jwks_cache_timeout\n self.jwks_cache_key = 'https://{}/.well-known/jwks.json'.format(self.domain)\n\n def set_cache(self, cache):\n \"\"\"Set a cache object, which has get(key)/set(key, value, timeout) interface\"\"\"\n self.cache = cache\n\n def is_cache_enabled(self):\n return self.jwks_cache_timeout > 0 and self.cache\n\n def fetch_jwks(self):\n cache_enabled = self.is_cache_enabled()\n\n if cache_enabled:\n jwks = self.cache.get(self.jwks_cache_key)\n if jwks:\n return jwks\n\n jsonurl = urlopen('https://{}/.well-known/jwks.json'.format(self.domain))\n jwks = json.loads(jsonurl.read())\n\n if cache_enabled:\n self.cache.set(self.jwks_cache_key, jwks, self.jwks_cache_timeout)\n\n return jwks\n\n def verify_with_access_token(self, auth):\n \"\"\"Get valid access token from the Authorization header\"\"\"\n # g.user = None\n\n # auth = request.headers.get('Authorization', None)\n # if not auth:\n # return None\n\n auth = auth.split()\n if not (auth and auth[0].lower() == 'bearer'):\n return None\n\n if len(auth) == 1 or len(auth) > 2:\n raise Exception('Invalid token header.')\n\n raw_token = auth[1]\n\n try:\n unverified_header = jwt.get_unverified_header(raw_token)\n except jwt.JWTError:\n raise Exception('Invalid header. Use an RS256 signed JWT Access Token')\n if unverified_header['alg'] == 'HS256':\n raise Exception('Invalid header. Use an RS256 signed JWT Access Token')\n\n jwks = self.fetch_jwks()\n rsa_key = None\n\n for key in jwks[\"keys\"]:\n if key[\"kid\"] == unverified_header[\"kid\"]:\n rsa_key = {\n \"kty\": key[\"kty\"],\n \"kid\": key[\"kid\"],\n \"use\": key[\"use\"],\n \"n\": key[\"n\"],\n \"e\": key[\"e\"]\n }\n if rsa_key:\n try:\n payload = jwt.decode(\n raw_token,\n rsa_key,\n algorithms=self.algorithms,\n options=options,\n issuer=\"https://{0}/\".format(self.domain)\n )\n xtp_attrs = payload['https://auth.xtalpi.com/Metadata']\n appmeta = xtp_attrs.get('app_metadata', dict())\n authorization_data = appmeta.get('authorization', dict())\n except jwt.ExpiredSignatureError:\n raise TokenExpiredException()\n except jwt.JWTClaimsError:\n raise Exception(\"incorrect claims, please check the audience and issuer\")\n except Exception:\n raise Exception(\"Unable to parse authentication token.\")\n\n\n return dict(\n is_authenticated=True,\n id=payload['sub'],\n name=xtp_attrs.get('userPrincipalName', None),\n email=xtp_attrs.get('userPrincipalName', None),\n groups=authorization_data.get('groups', []),\n roles=authorization_data.get('roles', []),\n is_active=True,\n )\n # g.auth0_access_token = raw_token\n # g.auth0_access_token_payload = payload\n # g.user = User(\n # is_authenticated=True,\n # id=payload['sub'],\n # name=xtp_attrs['userPrincipalName'],\n # email=xtp_attrs['userPrincipalName'],\n # groups=appmeta['authorization']['groups'],\n # roles=appmeta['authorization']['roles'],\n # is_active=True,\n # )\n\n def hook_auth_on_each_request(self, app):\n \"\"\"should be called only once for a single flask app\"\"\"\n app.before_request(self.verify_with_access_token)\n","repo_name":"qq7987590/coral","sub_path":"coral/libs/auth0.py","file_name":"auth0.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"36456393051","text":"\nclass Solution:\n def minMoves2(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 0:\n return 0\n\n nums.sort()\n mid = nums[len(nums) // 2]\n\n diffs = 0\n for i in nums:\n diffs += abs(mid - i)\n\n return diffs\n\n","repo_name":"tiaotiao/leetcode","sub_path":"462-minimum-moves-to-equal-array-elements-ii.py","file_name":"462-minimum-moves-to-equal-array-elements-ii.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"38412676763","text":"import sys\nsys.stdin = open('input.txt')\n\nfrom collections import deque\n\ndi = [-1, 1, 0, 0]\ndj = [0, 0, -1, 1]\n\nT = int(input())\n\nfor tc in range(1, T+1):\n N, M = map(int, input().split())\n arr = [input() for _ in range(N)]\n\n dist = [[987654321]*M for _ in range(N)]\n\n Q = deque()\n\n # 시작점인 물 위치\n for i in range(N):\n for j in range(M):\n if arr[i][j] == 'W':\n Q.append((i, j))\n dist[i][j] = 0\n\n while Q:\n i, j = Q.popleft()\n for d in range(4):\n next_i = i + di[d]\n next_j = j + dj[d]\n\n if next_i < 0 or next_i >= N or next_j < 0 or next_j >= M:\n continue\n\n if arr[next_i][next_j] == 'L' and dist[next_i][next_j] == 987654321:\n dist[next_i][next_j] = dist[i][j] + 1\n Q.append((next_i, next_j))\n\n ans = 0\n\n for i in dist:\n ans += sum(i)\n\n print('#{} {}'.format(tc, ans))","repo_name":"Hyojeong721/TIL","sub_path":"algorithm/SWA/date/0924/chlrhkdgh624/10966_물놀이를가자/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"2054295016","text":"import itertools\nimport math\nfrom icecream import ic\nimport copy\n\nimport numpy as np\n\nl = [(29, 'mengenyangkan', 0.0014),\n (8, 'terkenal', 0.0003),\n (16, 'pesan', 0.0002),\n (26, 'porsi', 0.0002),\n (0, 'lokasi', 0.0002),\n (13, 'gule', 0.0002),\n (5, 'padang', 0.0002),\n (17, 'nasi', 0.0002),\n (21, 'rendang', 0.0002),\n (19, 'padang', 0.0002),\n (12, 'kakap', 0.0002),\n (2, 'alun', 0.0001),\n (11, 'ikan', 0.0001),\n (4, 'masakan', 0.0001),\n (18, 'bungkus', 0.0001),\n (23, 'pop', 0.0001),\n (10, 'kepala', 0.0001),\n (3, 'alun', 0.0001),\n (25, 'perkedel', 0.0001),\n (22, 'ayam', 9.3827e-05),\n (20, 'berisikan', 7.0279e-05)]\n\ndef findsubsets(s, n):\n return list(itertools.combinations(s, n))\n\ndef intersection(lst1, lst2):\n return set(lst1).intersection(lst2)\n\n# def least_important_words(words):\n# print(words[2])\n\n# Driver Code\n# s = {1, 2, 3}\nn = int(math.floor(len(l) * 0.4))\nwords_perturb = l[:n]\n\nprint(words_perturb)\n\nprint(n)\n\n# print(min(words_perturb, key = lambda t: t[2]))\ndef get_minimums(word_tups):\n arr = []\n for wt in word_tups:\n if wt[2] == min(words_perturb, key = lambda t: t[2])[2]:\n arr.append(wt)\n return arr\n\n\n# minimum_import = get_minimums(words_perturb)\n# print(minimum_import)\n# # for a in findsubsets(l, n):\n# # if len(intersection(words_perturb, a)) <= n:\n# # print(a)\n\n# def swap(A,B,i,j):\n# A[i] = B[j]\n# return A\n\ndef swap_minimum(l, words_perturb):\n def get_minimums(word_tups):\n arr = []\n for wt in word_tups:\n if wt[2] == min(words_perturb, key = lambda t: t[2])[2]:\n arr.append(wt)\n return arr\n minimum_import = get_minimums(words_perturb)\n unlisted = list(set(l).symmetric_difference(set(words_perturb)))\n\n len_wp = len(words_perturb)\n len_ul = len(unlisted)\n # ic(swap(words_perturb, unlisted, -1, 0))\n res = []\n for i in range(len_wp):\n if words_perturb[i] in minimum_import:\n temp_wp = list(copy.deepcopy(words_perturb))\n temp_wp.pop(i)\n swapped_wp = np.array([temp_wp for i in range(len_ul)])\n for j in range(len(swapped_wp)):\n temp_sm = np.append(swapped_wp[j], unlisted[j])\n res.append(temp_sm)\n # ic(unlisted[j])\n # swapped_wp.append(unlisted[j])\n return res\n\nic(words_perturb)\nic(len(swap_minimum(l, words_perturb)))\n\n# f = [[1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]]\n# f[1].append(99)\n# print(f)\n\n# a = [1,2,3,4,5]\n# b = [4,5]\n# c = [7,8,9]\n# r = []\n# res = []\n# for i in range(len(a)):\n# if a[i] in b:\n# temp_a = copy.deepcopy(a)\n# temp_a.pop(i)\n# swapped_matrix = np.array([temp_a for i in range(len(c))])\n# for j in range(len(swapped_matrix)):\n# temp_sm = np.append(swapped_matrix[j], c[j])\n# res.append(temp_sm)\n\n# ic(res)","repo_name":"faridlazuarda/indorobusta","sub_path":"viz/advanced/misc/permutation_ta.py","file_name":"permutation_ta.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"23432211975","text":"\n#%%\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup as bs\nimport time\nimport pandas as pd\nimport pymongo\n\n\n#%%\ndef init_browser():\n executable_path = {\"executable_path\": \"chromedriver\"}\n return Browser(\"chrome\", **executable_path, headless=False)\n\n\n#%%\nbrowser = init_browser()\n\n#set url\nurl = \"https://nodata.tv/blog\"\nbrowser.visit(url)\n\ntime.sleep(1)\n\n#scrape page into Soup\nhtml = browser.html\nsoup = bs(html, \"html.parser\")\n\n\n#%%\nlinks = []\n\nboxes = soup.find_all(\"article\", class_=\"project-box\")\n\nfor box in boxes:\n link = box.find(\"a\", class_=\"title\")[\"href\"]\n links.append(link)\n\nprint(links)\n\n\n#%%\nundergroundMusic = []\nfor link in links:\n browser.visit(link)\n\n time.sleep(3)\n\n #scrape page into Soup\n html = browser.html\n soup = bs(html, \"html.parser\")\n \n #find main div\n main = soup.find(\"div\", {\"id\": \"main\"})\n \n #find artist, album, year\n title = main.find(\"h4\").text\n artist = title.split(\"/\")[0]\n album = title.split(\"/ \")[1].split(\"[\")[0]\n year = title.split(\"[\")[1].split(\"]\")[0]\n print(artist, album, year)\n \n #find genre tags in metadata\n metadata = main.find(\"ul\", class_=\"meta\")\n date = metadata.find_all(\"li\")[1].text\n tags = metadata.find_all(\"li\")[2]\n tags = tags.find_all(\"a\")\n #add tags to genres list\n genres = []\n for tag in tags:\n genre = tag.text\n genres.append(genre)\n print(date)\n print(genres)\n \n #find cover img url\n cover_link = main.find(\"img\")[\"src\"]\n print(cover_link)\n \n #find label and catalog number\n label = main.find(\"section\", class_=\"post\").text\n split = label.split(\"[\")\n labeldata = split[1].split(\"]\")[0]\n label = labeldata.split(\": \")[1].split(\" |\")[0]\n catalog = labeldata.split(\": \")[2]\n print(label, catalog)\n\n #compile album info into dict\n albumInfo = {\n \"url\": link,\n \"artist\": artist,\n \"album\": album,\n \"year\": year,\n \"date\": date,\n \"genres\": genres,\n \"cover\": cover_link,\n \"label\": label,\n \"catalog\": catalog\n }\n print(albumInfo)\n \n #add dict to underground music list\n undergroundMusic.append(albumInfo)\n\n\n#%%\nbrowser.quit()\nundergroundMusic\n\n\n#%%\nconn = 'mongodb://localhost:27017/nodata_dev'\nclient = pymongo.MongoClient(conn)\n\n# Declare the database\ndb = client[\"underground_music_db\"]\n\ndb[\"nodata_db\"].drop()\n\n# Declare the collection\ncollection = db[\"nodata_db\"]\n\n\n#%%\nundergroundMusic\n\n\n#%%\ncollection.insert_many(undergroundMusic)\n\n\n#%%\nresults = db.nodata_db.find()\nfor result in results:\n print(result)\n\n\n","repo_name":"ambientstl/Underground-Music-Project","sub_path":"nodata-proj-development/scrape&createdb.py","file_name":"scrape&createdb.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"5599728458","text":"from abc import ABC\n\n\nclass Player(ABC):\n def challenge(self, player) -> (bool, str):\n pass\n\n\nclass Rock(Player):\n def challenge(self, player: Player) -> (bool, str):\n if isinstance(player, Lizzard):\n return True, \"Rock Crushes Lizzard\"\n\n if isinstance(player, Scissors):\n return True, \"Rock Crushes Scissors\"\n\n return False, \"\"\n\nclass Scissors(Player):\n def challenge(self, player: Player) -> (bool, str):\n if isinstance(player, Paper):\n return True, \"Scissors cuts paper\"\n\n if isinstance(player, Lizzard):\n return True, \"Scissors decapitates lizard\"\n\n return False, \"\"\n\nclass Paper(Player):\n def challenge(self, player: Player) -> (bool, str):\n if isinstance(player, Rock):\n return True, \"Paper covers rock\"\n\n if isinstance(player, Spock):\n return True, \"Paper disproves spock\"\n\n return False, \"\"\n\nclass Lizzard(Player):\n def challenge(self, player: Player) -> (bool, str):\n if isinstance(player, Spock):\n return True, \"Lizard poisons spock\"\n\n if isinstance(player, Paper):\n return True, \"Lizard eats paper\"\n\n return False, \"\"\n\n\nclass Spock(Player):\n def challenge(self, player: Player) -> (bool, str):\n if isinstance(player, Rock):\n return True, \"Spock vaporizes rock\"\n\n if isinstance(player, Scissors):\n return True, \"Spock smashes scissors\"\n\n return False, \"\"\n\n\ndef build_player(player_type):\n type_map = {\n \"spock\": Spock,\n \"scissor\": Scissors,\n \"rock\": Rock,\n \"lizard\": Lizzard,\n \"paper\": Paper,\n }\n _player = type_map.get(player_type)\n if _player:\n return _player()\n else:\n return None\n\n\n\ndef result(p1: str, p2: str):\n # your excellent code here\n _p1 = build_player(p1.lower())\n _p2 = build_player(p2.lower())\n if _p1 is None or _p2 is None:\n return \"Oh, Unknown Thing\"\n\n if type(_p1) == type(_p2):\n return \"Draw!\"\n\n results, msg = _p1.challenge(_p2)\n if results:\n return \"Player 1 won!\"\n else:\n return \"Player 2 won!\"\n\n\nprint(result(\"Spock\", \"Rock\"))\nprint(result(\"r0ck\", \"Paper\"))","repo_name":"byt3-m3/python_code_practice","sub_path":"code_wars/rock_paper_scissors_lizzard_spock.py","file_name":"rock_paper_scissors_lizzard_spock.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"41654887914","text":"import sys\nimport re\n\ntagPtn = re.compile(\"\\((\\S+)\")\n\ndef main(fileName):\n\ttagSet = set()\n\twith open(fileName, \"r\", encoding=\"utf8\") as fp:\n\t\tcontent = fp.read()\n\tfor match in tagPtn.finditer(content):\n\t\ttag = match.group(1)\n\t\tif tag not in tagSet:\n\t\t\ttagSet.add(tag)\n\tprint(tagSet)\n\treturn tagSet\n\nif __name__ == \"__main__\":\n\tmain(sys.argv[1])","repo_name":"mrguenther/NLP_Final_Project","sub_path":"getTagSet.py","file_name":"getTagSet.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"3987517312","text":"FETCH_INTERVAL = 500\n\n# This is the only valid reason to go to an MVC location\nAPPOINTMENT_ID = 12\n\n# More MVC locations exist, but these are the only ones I'm interested in\nLOCATIONS = {\n \"Bayonne\": 125,\n \"Lodi\": 136,\n \"Newark\": 138,\n \"North Bergen\": 139,\n \"Oakland\": 141,\n \"Paterson\": 142,\n \"Wayne\": 140\n}","repo_name":"mooey5775/njmvc-text-bot","sub_path":"njmvc/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"39599103910","text":"import socketio\r\nfrom flask_socketio import SocketIOTestClient\r\nsio = socketio.Client()\r\n\r\n\r\n@sio.event\r\ndef connect():\r\n print('connection established')\r\n\r\n@sio.event\r\ndef disconnect():\r\n print('disconnected from server')\r\n return 1\r\n\r\n#SocketIOTestClient.connect('http://localhost:5000')\r\n#SocketIOTestClient.emit(\"teste\", \"EV_276\")\r\n\r\nsio.connect('http://localhost:7877')\r\nsio.emit(\"teste\", \"EV_276\")\r\nsio.wait()\r\n\r\nsio.disconnect()\r\n","repo_name":"giovaniandrerizzardi/msservice","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"70310947360","text":"from patterns.fabric_pattern.MilkFabric import CheeseFabric, SourCreameFabric\nfrom patterns.fabric_pattern.Product import Cheese, SourCreame\n\n\ndef get_cheese_list():\n cheese_list = [Cheese(), Cheese(), Cheese()]\n return cheese_list\n\n\ndef test_fabric(monkeypatch):\n cheesefabric = CheeseFabric()\n monkeypatch.setattr(cheesefabric, \"deliver\", get_cheese_list)\n assert len(cheesefabric.deliver()) == 3\n sourcreamefabric = SourCreameFabric()\n assert type(sourcreamefabric.deliver(2)) == list\n assert len(sourcreamefabric.deliver(2)) == 2\n assert type(sourcreamefabric.deliver(2)[0]) == SourCreame\n\n\n","repo_name":"Enjoy4e/DIA-labs","sub_path":"lab4/tests/test_fabric_pattern.py","file_name":"test_fabric_pattern.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"18066103141","text":"# 한글은 2번 돌려야함\nimport matplotlib.pyplot as plt\nplt.title('마커')\nplt.plot([10,20,30,40],'r.--',label='원')\nplt.plot([40,30,20,10],'g^-',label='삼각형')\nplt.legend(loc=5)\nplt.rc('font',family='Malgun Gothic')\nplt.show()\n\n\n\nimport matplotlib.pyplot as plt \nimport csv\nf=open('seoul_csv.csv', encoding='cp949')\ndata=csv.reader(f)\nnext(data) #읽어들인것에서 날짜 주기 이런것들을 날림\nresult=[] #빈 리스트 초기화\n\nfor row in data:\n if row[-1]!='':\n result.append(float(row[-1]))\nprint(result)\nplt.plot(result,'r')\nplt.show()","repo_name":"seungje1217/2023-study","sub_path":"PYTHON/TUK/9.21.py","file_name":"9.21.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"32030226745","text":"# 6. Leer una matriz 4x4 entera y calcular el promedio de los números mayores de cada fila.\n\ntry:\n matriz = [[int(input(\"Ingresar numero\")) for i in range(4)] for i in range(4)]\n mayor_1 = 0\n mayor_2 = 0\n mayor_3 = 0\n mayor_4 = 0\n \n for i in range(len(matriz)):\n for j in range(len(matriz[i][:])):\n if i==0:\n if matriz[i][j]>mayor_1:\n mayor_1=matriz[i][j]\n elif i==1:\n if matriz[i][j]>mayor_2:\n mayor_2=matriz[i][j]\n elif i==2:\n if matriz[i][j]>mayor_3:\n mayor_3=matriz[i][j]\n else:\n if matriz[i][j]>mayor_4:\n mayor_4=matriz[i][j]\n promedio = (mayor_1+mayor_2+mayor_3+mayor_4)/4\n print(\"El numero mayor de la fila 1 es: \",mayor_1)\n print(\"El numero mayor de la fila 2 es: \",mayor_2)\n print(\"El numero mayor de la fila 3 es: \",mayor_3)\n print(\"El numero mayor de la fila 4 es: \",mayor_4)\n print(\"El promedio de los numeros mayores de cada fila es: \", promedio)\nexcept ValueError: print(\"Error\")","repo_name":"miguelparra2020/YulyRepo","sub_path":"Matrices/ejercicio_6.py","file_name":"ejercicio_6.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"es","doc_type":"code","dataset":"github-code","pt":"51"} +{"seq_id":"31713145562","text":"OPERATOR = {\n '+': lambda a, b: a + b,\n '-': lambda a, b: a - b,\n '*': lambda a, b: a * b,\n '/': lambda a, b: int(a / b),\n}\n\n\nclass Solution:\n def evalRPN(self, tokens):\n stack = []\n for token in tokens:\n if len(token) > 1 or token.isdigit():\n stack.append(int(token))\n else:\n op1 = stack.pop(-1)\n op2 = stack.pop(-1)\n stack.append(OPERATOR[token](op2, op1))\n return stack[0]\n\n\nif __name__ == '__main__':\n print(Solution().evalRPN([\"10\", \"6\", \"9\", \"3\", \"+\", \"-11\", \"*\", \"/\", \"*\", \"17\", \"+\", \"5\", \"+\"]))\n","repo_name":"stupidchen/leetcode","sub_path":"src/leetcode/P150.py","file_name":"P150.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"14573592671","text":"from .base import QuickbooksBaseObject, Ref, QuickbooksManagedObject, QuickbooksTransactionEntity, \\\n LinkedTxnMixin\nfrom .tax import TxnTaxDetail\nfrom .detailline import DetailLine, DescriptionOnlyLine\nfrom ..mixins import DeleteMixin\n\n\nclass Entity(QuickbooksBaseObject):\n class_dict = {\n \"EntityRef\": Ref\n }\n\n def __init__(self):\n super(Entity, self).__init__()\n self.Type = \"\"\n self.EntityRef = None\n\n\nclass JournalEntryLineDetail(QuickbooksBaseObject):\n class_dict = {\n \"Entity\": Entity,\n \"AccountRef\": Ref,\n \"ClassRef\": Ref,\n \"DepartmentRef\": Ref,\n \"TaxCodeRef\": Ref,\n }\n\n def __init__(self):\n super(JournalEntryLineDetail, self).__init__()\n self.PostingType = \"\"\n self.TaxApplicableOn = \"Sales\"\n self.TaxAmount = 0\n\n self.BillableStatus = None\n self.Entity = None\n self.AccountRef = None\n self.ClassRef = None\n self.DepartmentRef = None\n self.TaxCodeRef = None\n\n\nclass JournalEntryLine(DetailLine):\n class_dict = {\n \"JournalEntryLineDetail\": JournalEntryLineDetail\n }\n\n def __init__(self):\n super(JournalEntryLine, self).__init__()\n self.DetailType = \"JournalEntryLineDetail\"\n self.JournalEntryLineDetail = None\n\n\nclass JournalEntry(DeleteMixin, QuickbooksManagedObject, QuickbooksTransactionEntity, LinkedTxnMixin):\n \"\"\"\n QBO definition: Journal Entry is a transaction in which:\n - There are at least two parts - a Debit and a Credit - called distribution lines.\n - Each distribution line has an account from the Chart of Accounts.\n - The total of the Debit column equals the total of the Credit column.\n\n When you record a transaction with Journal Entry, the QBO UI labels the transaction as JRNL in a\n register and General Journal on reports that list transactions.\n \"\"\"\n\n class_dict = {\n \"TxnTaxDetail\": TxnTaxDetail,\n \"CurrencyRef\": Ref,\n }\n\n list_dict = {\n \"Line\": DetailLine\n }\n\n detail_dict = {\n \"DescriptionOnly\": DescriptionOnlyLine,\n \"JournalEntryLineDetail\": JournalEntryLine\n }\n\n qbo_object_name = \"JournalEntry\"\n\n def __init__(self):\n super(JournalEntry, self).__init__()\n self.Adjustment = False\n self.TxnDate = \"\"\n # self.TxnSource = \"\"\n self.DocNumber = \"\"\n self.PrivateNote = \"\"\n self.TotalAmt = 0\n self.ExchangeRate = 1\n self.Line = []\n self.TxnTaxDetail = None\n\n self.CurrencyRef = None\n\n def __str__(self):\n return str(self.TotalAmt)\n","repo_name":"ej2/python-quickbooks","sub_path":"quickbooks/objects/journalentry.py","file_name":"journalentry.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","stars":353,"dataset":"github-code","pt":"51"} +{"seq_id":"37359910294","text":"# pylint: disable=too-many-lines,invalid-name\n\nimport sqlite3\n\nfrom parsimonious import Grammar\n\nfrom allennlp.common.testing import AllenNlpTestCase\nfrom allennlp.semparse.worlds.text2sql_world import Text2SqlWorld\nfrom allennlp.semparse.contexts.sql_context_utils import format_grammar_string\nfrom allennlp.semparse.contexts.sql_context_utils import SqlVisitor\n\n\nclass TestText2SqlWorld(AllenNlpTestCase):\n def setUp(self):\n super().setUp()\n self.schema = str(self.FIXTURES_ROOT / 'data' / 'text2sql' / 'restaurants-schema.csv')\n self.database_path = str(self.FIXTURES_ROOT / \"data\" / \"text2sql\" / \"restaurants.db\")\n\n\n def test_world_modifies_unconstrained_grammar_correctly(self):\n world = Text2SqlWorld(self.schema)\n grammar_dictionary = world.base_grammar_dictionary\n assert grammar_dictionary[\"table_name\"] == ['\"RESTAURANT\"', '\"LOCATION\"', '\"GEOGRAPHIC\"']\n assert grammar_dictionary[\"column_name\"] == ['\"STREET_NAME\"', '\"RESTAURANT_ID\"', '\"REGION\"',\n '\"RATING\"', '\"NAME\"', '\"HOUSE_NUMBER\"',\n '\"FOOD_TYPE\"', '\"COUNTY\"', '\"CITY_NAME\"']\n\n def test_grammar_from_world_can_parse_statements(self):\n world = Text2SqlWorld(self.schema)\n sql = ['SELECT', 'COUNT', '(', '*', ')', 'FROM', 'LOCATION', ',',\n 'RESTAURANT', 'WHERE', 'LOCATION', '.', 'CITY_NAME', '=',\n \"'city_name0'\", 'AND', 'RESTAURANT', '.', 'NAME', '=', 'LOCATION',\n '.', 'RESTAURANT_ID', 'AND', 'RESTAURANT', '.', 'NAME', '=', \"'name0'\", ';']\n\n grammar = Grammar(format_grammar_string(world.base_grammar_dictionary))\n sql_visitor = SqlVisitor(grammar)\n sql_visitor.parse(\" \".join(sql))\n\n def test_world_identifies_non_global_rules(self):\n world = Text2SqlWorld(self.schema)\n assert not world.is_global_rule('value -> [\"\\'food_type0\\'\"]')\n\n def test_grammar_from_world_can_produce_entities_as_values(self):\n world = Text2SqlWorld(self.schema)\n sql = ['SELECT', 'COUNT', '(', '*', ')', 'FROM', 'LOCATION', ',',\n 'RESTAURANT', 'WHERE', 'LOCATION', '.', 'CITY_NAME', '=',\n \"'city_name0'\", 'AND', 'RESTAURANT', '.', 'NAME', '=', 'LOCATION',\n '.', 'RESTAURANT_ID', 'AND', 'RESTAURANT', '.', 'NAME', '=', \"'name0'\", ';']\n\n entities = {\"city_name0\": \"San fran\", \"name0\": \"Matt Gardinios Pizza\"}\n action_sequence, actions = world.get_action_sequence_and_all_actions(sql, entities)\n\n assert 'value -> [\"\\'city_name0\\'\"]' in action_sequence\n assert 'value -> [\"\\'name0\\'\"]' in action_sequence\n assert 'value -> [\"\\'city_name0\\'\"]' in actions\n assert 'value -> [\"\\'name0\\'\"]' in actions\n\n def test_world_adds_values_from_tables(self):\n connection = sqlite3.connect(self.database_path)\n cursor = connection.cursor()\n world = Text2SqlWorld(self.schema, cursor=cursor, use_prelinked_entities=False)\n assert world.base_grammar_dictionary[\"number\"] == ['\"229\"', '\"228\"', '\"227\"', '\"226\"',\n '\"225\"', '\"5\"', '\"4\"', '\"3\"', '\"2\"',\n '\"1\"', '\"833\"', '\"430\"', '\"242\"',\n '\"135\"', '\"1103\"']\n\n assert world.base_grammar_dictionary[\"string\"] == ['\"tommy\\'s\"', '\"rod\\'s hickory pit restaurant\"',\n '\"lyons restaurant\"', '\"jamerican cuisine\"',\n '\"denny\\'s restaurant\"', '\"american\"', '\"vallejo\"',\n '\"w. el camino real\"', '\"el camino real\"',\n '\"e. el camino real\"', '\"church st\"',\n '\"broadway\"', '\"sunnyvale\"', '\"san francisco\"',\n '\"san carlos\"', '\"american canyon\"', '\"alviso\"',\n '\"albany\"', '\"alamo\"', '\"alameda\"', '\"unknown\"',\n '\"santa clara county\"', '\"contra costa county\"',\n '\"alameda county\"', '\"bay area\"']\n","repo_name":"MrMao/allennlp","sub_path":"allennlp/tests/semparse/worlds/text2sql_world_test.py","file_name":"text2sql_world_test.py","file_ext":"py","file_size_in_byte":4438,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"38639322587","text":"import gzip\nimport json\nimport os\nimport pickle\n\n\ndef create_dir(path):\n if not os.path.exists(path):\n os.mkdir(path)\n\n\ndef load_dataset(path, encoding):\n with gzip.open(path , \"rt\", encoding=encoding) as file:\n dataset = json.load(file)\n return dataset\n\n\ndef load_delimited_data(path, encoding, delimiter):\n with open(path, \"rt\", encoding=encoding) as file:\n data = tuple( tuple(data_item.strip() for data_item in line.strip().split(delimiter)) for line in file ) \n return data\n\n\ndef load_indexing_periods(filepath, encoding, is_fully_indexed):\n periods = {}\n with open(filepath, \"rt\", encoding=encoding) as file:\n for line in file:\n split = line.split(\",\")\n\n nlm_id = split[0].strip()\n citation_subset = split[1].strip()\n start_year = int(split[2].strip())\n end_year = int(split[3].strip())\n \n if start_year < 0:\n continue\n if end_year < 0:\n end_year = None\n\n period = { \"citation_subset\": citation_subset, \"is_fully_indexed\": is_fully_indexed, \"start_year\": start_year, \"end_year\": end_year }\n if nlm_id in periods:\n periods[nlm_id].append(period)\n else:\n periods[nlm_id] = [period]\n return periods\n\n\ndef load_pickled_object(path):\n loaded_object = pickle.load(open(path, \"rb\"))\n return loaded_object\n\n\ndef preprocess_voting_model_data(data, year_filter=None):\n training_data = { \"titles\" : [], \"abstract\" : [], \"author_list\" : [], \"labels\": [] }\n for article in data:\n if year_filter and article['pub_year'] != year_filter:\n continue\n training_data[\"titles\"].append(article[\"title\"])\n training_data[\"abstract\"].append(article[\"abstract\"])\n training_data[\"author_list\"].append(article[\"affiliations\"])\n training_data[\"labels\"].append(not article[\"is_indexed\"])\n return training_data\n\n\ndef save_delimited_data(path, encoding, delimiter, data):\n with open(path, \"wt\", encoding=encoding) as file:\n for data_row in data:\n line = delimiter.join([str(data_item) for data_item in data_row]) + \"\\n\"\n file.write(line)","repo_name":"Global19/biomedical-citation-selector-trainer","sub_path":"BmCS/retrain/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"51"} +{"seq_id":"40633979190","text":"import faiss\nimport numpy as np\nfrom tqdm import tqdm\nfrom numpy.linalg import norm\nfrom sklearn.decomposition import PCA\n\nclass Embedding:\n def __init__(self, embed_path = \"data/embedding.txt\"):\n self.word_idx = {}\n self.idx_word = {}\n self.data = []\n self.embedding = None\n \n with open(embed_path,'r',encoding='utf-8') as f:\n for i, line in tqdm(enumerate(f)):\n line = line.strip().split(\" \", 1)\n #print(line)\n word, vec = line\n vec = np.fromstring(vec, sep=' ')\n self.data.append(vec / norm(vec))\n self.word_idx[word] = i\n self.idx_word[i] = word\n self.data = np.asarray(self.data).astype('float32')\n\n self.nb, self.d = self.data.shape\n self.xb = np.ascontiguousarray(self.data[:,:self.d])\n self.index = faiss.IndexFlatIP(self.d)\n self.index.add(self.xb)\n\n def set_embed_function(self, func):\n self.embedding = func\n\n def get_emb(self, word):\n start_idx = 0\n if word in self.word_idx:\n emb = self.data[self.word_idx[word],:self.d] \n start_idx = 1\n else:\n emb = self.embedding(word)[:self.d]\n emb = emb / norm(emb)\n return emb, start_idx\n\n def get_sim_words(self, word, domain=None, k=15):\n if domain is not None:\n d_words = {}\n d_idx_word = {}\n word_emb_list = []\n for i, dw in enumerate(domain):\n if dw in d_words: # or dw == word:\n continue\n d_words[dw] = True\n d_idx_word[len(d_idx_word)] = dw\n word_emb_list.append(self.get_emb(dw)[0])\n word_emb_list = np.asarray(word_emb_list)\n d_index = faiss.IndexFlatIP(self.d)\n d_index.add(word_emb_list)\n else:\n word_emb_list = self.xb\n d_idx_word = self.idx_word\n d_index = self.index\n\n emb, start_idx = self.get_emb(word)\n emb = np.expand_dims(emb, axis=0)\n D, I = d_index.search(emb, k+start_idx)\n D, I = D[0], I[0]\n W = [d_idx_word[v] for v in I]\n\n word_list = W[start_idx:][:k]\n dist_list = D[start_idx:].tolist()[:k]\n\n label_list = W if start_idx == 1 else [word] + W\n _vec_sub = np.array([word_emb_list[v] for v in I])\n vector_list = _vec_sub if start_idx == 1 else np.concatenate((emb, _vec_sub), axis=0)\n vector_list = np.array(vector_list)\n\n pca = PCA(n_components=2)\n reduced = pca.fit_transform(vector_list).tolist()\n pca_result = {}\n pca_result[\"label\"] = label_list\n pca_result[\"plot\"] = reduced\n\n return {\"word_list\": word_list, \"dist_list\": dist_list, \"pca_result\": pca_result}\n\n def get_sim_words_extra(self, word, word2, domain=None, k=15):\n if domain is not None:\n d_words = {}\n d_idx_word = {}\n word_emb_list = []\n for i, dw in enumerate(domain):\n if dw in d_words: # or dw == word or dw == word2:\n continue\n d_words[dw] = True\n d_idx_word[len(d_idx_word)] = dw\n word_emb_list.append(get_emb(dw)[0])\n word_emb_list = np.asarray(word_emb_list)\n d_index = faiss.IndexFlatIP(self.d)\n d_index.add(word_emb_list)\n else:\n word_emb_list = self.xb\n d_idx_word = self.idx_word\n d_index = self.index\n\n start_idx = 0\n emb, start_idx = self.get_emb(word)\n emb2, _ = self.get_emb(word2)\n\n emb = np.expand_dims(emb, axis=0)\n emb2 = np.expand_dims(emb2, axis=0)\n D, I = d_index.search(emb, k+start_idx)\n D, I = D[0], I[0]\n W = [d_idx_word[v] for v in I]\n\n word_list = W[start_idx:][:k]\n dist_list = D[start_idx:].tolist()[:k]\n\n pca = PCA(n_components=2)\n\n is_included = word2 in word_list\n _vec_sub = np.array([word_emb_list[v] for v in I])\n label_list = W if start_idx == 1 else [word] + W\n if not is_included:\n _vec_sub = np.concatenate((emb2, _vec_sub), axis=0)\n label_list = [word2] + label_list\n\n vector_list = _vec_sub if start_idx == 1 else np.concatenate((emb, _vec_sub), axis=0)\n vector_list = np.array(vector_list)\n\n pca = PCA(n_components=2)\n reduced = pca.fit_transform(vector_list).tolist()\n pca_result = {}\n pca_result[\"label\"] = label_list\n pca_result[\"plot\"] = reduced\n\n return {\"pca_result\": pca_result}\n\n def get_embedding(self, word):\n if word in self.word_idx:\n emb = self.data[self.word_idx[word],:self.d]\n else:\n emb = self.embedding(word)[:self.d]\n return emb\n\n def cosine_sim(self, a, b):\n return np.dot(a, b)/(norm(a)*norm(b))\n\n def get_word_info(self, word, domain=None, K=15):\n emb = self.get_embedding(word).tolist()\n sim_words = self.get_sim_words(word, domain, K)\n result = sim_words\n result[\"word\"] = [word]\n result[\"embed\"] = [emb]\n return result\n\n def get_pair_info(self, word1, word2, domain=None, K=15):\n emb1 = self.get_embedding(word1).tolist()\n emb2 = self.get_embedding(word2).tolist()\n \n result = self.get_sim_words_extra(word1, word2, domain, K)\n result[\"word\"] = [word1, word2]\n result[\"embed\"] = [emb1, emb2]\n result[\"sim\"] = self.cosine_sim(emb1, emb2)\n return result\n\n\nif __name__ == \"__main__\":\n ev = EmbeddingVector()\n print(ev.d, ev.nb)\n result = ev.get_pair_info(\"!!\", \"4!\", 15)\n print(result)\n\n exit()\n\n","repo_name":"naver/qadiver","sub_path":"tools/emb_faiss.py","file_name":"emb_faiss.py","file_ext":"py","file_size_in_byte":5778,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"51"} +{"seq_id":"13466539429","text":"# Use modern Python\nfrom __future__ import unicode_literals, absolute_import, print_function\n\n# Django imports\nimport json\n\nfrom django.contrib import admin\nfrom django import forms\nfrom django.core import urlresolvers\n\n\n# Local imports\nimport django_prbac.csv\nfrom django_prbac.models import *\nfrom django_prbac.forms import StringSetInput\n\n__all__ = [\n 'RoleAdmin',\n 'RoleAdminForm',\n 'GrantAdmin',\n]\n\nclass RoleAdminForm(forms.ModelForm):\n class Meta:\n model = Role\n widgets = {\n 'parameters': StringSetInput\n }\n exclude = []\n\n\nclass RoleAdmin(admin.ModelAdmin):\n\n model = Role\n form = RoleAdminForm\n\n def parameters__csv(self, instance):\n return django_prbac.csv.line_to_string(sorted(list(instance.parameters)))\n parameters__csv.short_description = 'Parameters'\n parameters__csv.admin_order_field = 'parameters'\n\n list_display = [\n 'slug',\n 'name',\n 'parameters__csv',\n 'description',\n ]\n\n search_fields = [\n 'slug',\n 'name',\n 'parameters',\n 'description',\n ]\n\nclass GrantAdmin(admin.ModelAdmin):\n\n model = Grant\n\n def edit_link(self, instance):\n if instance.id:\n return '(edit)' % urlresolvers.reverse('admin:django_prbac_grant_change',\n args=[instance.id])\n else:\n return ''\n edit_link.allow_tags = True\n edit_link.short_description = ''\n\n def assignment__dumps(self, instance):\n return json.dumps(instance.assignment)\n assignment__dumps.short_description = 'Assignment'\n\n list_display = [\n 'edit_link',\n 'from_role',\n 'to_role',\n 'assignment__dumps',\n ]\n\n search_fields = [\n 'from_role__name',\n 'from_role__description',\n 'to_role__name',\n 'to_role__description',\n ]\n\n def get_queryset(self, request):\n return Grant.objects.select_related('to_role', 'from_role')\n\nadmin.site.register(Role, RoleAdmin)\nadmin.site.register(Grant, GrantAdmin)\n\n","repo_name":"mesemus/django-prbac","sub_path":"django_prbac/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"51"} +{"seq_id":"4208460540","text":"#!/usr/bin/python\n\nimport sys\nimport socket\nimport struct\nimport time\n\nlocal_port = 5006\n\nif len(sys.argv) == 1:\n\tfamily = socket.AF_INET\n\tconnect_tuple = ( 'localhost', local_port )\nelse:\n\tdetails = socket.getaddrinfo( sys.argv[1], local_port, socket.AF_UNSPEC, socket.SOCK_DGRAM)\n\tfamily = details[0][0]\n\tif family == socket.AF_INET6:\n\t\tconnect_tuple = ( sys.argv[1], local_port, 0, 0)\n\telse:\n\t\tconnect_tuple = ( sys.argv[1], local_port)\n\ns = socket.socket( family, socket.SOCK_DGRAM )\ns.setblocking(0)\ns.connect( connect_tuple )\n\n# Control Change\nbytes = struct.pack( \"BBB\", 0xB6, 0x3c, 0x7f )\ns.send( bytes )\nbytes = struct.pack( \"BBB\", 0xB6, 0x3e, 0x7f )\ns.send( bytes )\n\ns.close()\n","repo_name":"ravelox/pimidi","sub_path":"python/control_send.py","file_name":"control_send.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":151,"dataset":"github-code","pt":"51"} +{"seq_id":"8210701639","text":"from pandas import DataFrame\r\nimport pandas as pd\r\n\r\ndfH = DataFrame.from_csv('C:\\\\Users\\\\DELL\\\\PycharmProjects\\\\rdf-datatype-detection\\\\geneData\\\\hgnccomWithoutNull.csv',index_col=None) #hgnc\r\ndfg = DataFrame.from_csv('C:\\\\Users\\\\DELL\\\\PycharmProjects\\\\rdf-datatype-detection\\\\geneData\\\\genes.tsv', sep='\\t') #pharmgkb\r\ndfC3 = DataFrame.from_csv('ctd3.csv', sep=',',index_col=0) #ctd\r\ndfC1 = DataFrame.from_csv('ctd1.csv', sep=',',index_col=0) #ctd\r\n\r\n\r\n#create new data file\r\n# new_df=DataFrame()\r\n# #hgnc_id\r\n# Hhi=dfH['hgnc_id_n'].tolist()\r\n# Ghi=dfg['HGNC ID'].tolist()\r\n# Chi3=dfC3['hgnc_id'].tolist()\r\n# Chi1=dfC1['hgnc_id'].tolist()\r\n# newchi=Hhi+Ghi+Chi1+Chi3\r\n#\r\n# se1 = pd.Series(newchi)\r\n# #\r\n# new_df['hgnc_id'] = se1.values\r\n# # dfH.to_csv('C:\\\\Users\\\\DELL\\\\PycharmProjects\\\\rdf-datatype-detection\\\\geneData\\\\hgnccom.csv')\r\n#\r\n# #ncbi_id\r\n# Hni=dfH['ncbi_id'].tolist()\r\n# Gni=dfg['NCBI Gene ID'].tolist()\r\n# Cni3=dfC3['Gene ID'].tolist()\r\n# Cni1=dfC1['Gene ID'].tolist()\r\n# newcni=Hni+Gni+Cni1+Cni3\r\n# se2 = pd.Series(newcni)\r\n# #\r\n# new_df['ncbi_id'] = se2.values\r\n# # dfH.to_csv('C:\\\\Users\\\\DELL\\\\PycharmProjects\\\\rdf-datatype-detection\\\\geneData\\\\hgnccom.csv')\r\n#\r\n#\r\n# #symbol\r\n# Hs=dfH['symbol'].tolist()\r\n# Gs=dfg['Symbol'].tolist()\r\n# Cs3=dfC3['Gene Symbol'].tolist()\r\n# Cs1=dfC1['Gene Symbol'].tolist()\r\n# newcs=Hs+Gs+Cs1+Cs3\r\n# se3 = pd.Series(newcs)\r\n# #\r\n# new_df['symbol'] = se3.values\r\n# # dfH.to_csv('C:\\\\Users\\\\DELL\\\\PycharmProjects\\\\rdf-datatype-detection\\\\geneData\\\\hgnccom.csv')\r\n#\r\n# new_df.to_csv('datacomplete.csv')\r\ndf = DataFrame.from_csv('datacomplete.csv', sep=',',index_col=0) #ctd","repo_name":"MaastrichtU-IDS/semantic-enhancement","sub_path":"NewData.py","file_name":"NewData.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"21082881696","text":"import serial\nimport adafruit_dht\n\n\n\nlocations=['COM5'] \nfor device in locations: \n try: \n print (\"Conectado a Arduino en: \",device )\n arduino = serial.Serial('COM5', 9600,timeout=10) \n break \n except: \n print (\"Fallo la conexion a: \",device )\n#from board import ()\ndht_device = adafruit_dht . DHT11(4)\ntemperature = dht_device . temperature\nhumidity = dht_device . humidity\n","repo_name":"loscapitos2018/HomeSmartHome","sub_path":"Python/prueba_TH.py","file_name":"prueba_TH.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"51"} +{"seq_id":"41169307943","text":"\"\"\"\nTests for dbbackup command.\n\"\"\"\nimport os\n\nfrom django.test import TestCase\nfrom mock import patch\n\nfrom dbbackup.db.base import get_connector\nfrom dbbackup.management.commands.dbbackup import Command as DbbackupCommand\nfrom dbbackup.storage import get_storage\nfrom dbbackup.tests.utils import DEV_NULL, TEST_DATABASE, add_public_gpg, clean_gpg_keys\n\n\n@patch(\"dbbackup.settings.GPG_RECIPIENT\", \"test@test\")\n@patch(\"sys.stdout\", DEV_NULL)\nclass DbbackupCommandSaveNewBackupTest(TestCase):\n def setUp(self):\n self.command = DbbackupCommand()\n self.command.servername = \"foo-server\"\n self.command.encrypt = False\n self.command.compress = False\n self.command.database = TEST_DATABASE[\"NAME\"]\n self.command.storage = get_storage()\n self.command.connector = get_connector()\n self.command.stdout = DEV_NULL\n self.command.filename = None\n self.command.path = None\n\n def tearDown(self):\n clean_gpg_keys()\n\n def test_func(self):\n self.command._save_new_backup(TEST_DATABASE)\n\n def test_compress(self):\n self.command.compress = True\n self.command._save_new_backup(TEST_DATABASE)\n\n def test_encrypt(self):\n add_public_gpg()\n self.command.encrypt = True\n self.command._save_new_backup(TEST_DATABASE)\n\n def test_path(self):\n self.command.path = \"/tmp/foo.bak\"\n self.command._save_new_backup(TEST_DATABASE)\n self.assertTrue(os.path.exists(self.command.path))\n # tearDown\n os.remove(self.command.path)\n\n\n@patch(\"dbbackup.settings.GPG_RECIPIENT\", \"test@test\")\n@patch(\"sys.stdout\", DEV_NULL)\n@patch(\"dbbackup.db.sqlite.SqliteConnector.create_dump\")\n@patch(\"dbbackup.utils.handle_size\", returned_value=4.2)\nclass DbbackupCommandSaveNewMongoBackupTest(TestCase):\n def setUp(self):\n self.command = DbbackupCommand()\n self.command.servername = \"foo-server\"\n self.command.encrypt = False\n self.command.compress = False\n self.command.storage = get_storage()\n self.command.stdout = DEV_NULL\n self.command.filename = None\n self.command.path = None\n self.command.connector = get_connector(\"default\")\n\n def tearDown(self):\n clean_gpg_keys()\n\n def test_func(self, mock_run_commands, mock_handle_size):\n self.command._save_new_backup(TEST_DATABASE)\n self.assertTrue(mock_run_commands.called)\n","repo_name":"jazzband/django-dbbackup","sub_path":"dbbackup/tests/commands/test_dbbackup.py","file_name":"test_dbbackup.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","stars":811,"dataset":"github-code","pt":"51"} +{"seq_id":"33454164794","text":"import logging\nimport os\nimport sys\n\n# backend constants\nWX = \"wx\"\nPYQT5 = \"pyqt5\"\nPYSIDE2 = \"pyside2\"\nPYQT6 = \"pyqt6\"\nPYSIDE6 = \"pyside6\"\nTK = \"tk\"\n\n# backend module\nHAVE_PYQT5, HAVE_PYSIDE2, HAVE_PYQT6, HAVE_PYSIDE6, HAVE_WX = (\n False,\n False,\n False,\n False,\n False,\n)\n\n# is any backend imported?\nHAVE_BACKEND = False\nBACKEND_MODULE = \"No backend loaded\"\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\n\n\ndef qt6_force_xcb_on_linux():\n \"\"\"Force QT_QPA_PLATFORM to 'xcb' on Linux for Qt6. wayland implementation\n prevents winId to provide with the correct x11 windows id\"\"\"\n if sys.platform == \"linux\" and \"XDG_SESSION_TYPE\" in os.environ:\n if os.environ[\"XDG_SESSION_TYPE\"] == \"wayland\":\n os.environ[\"QT_QPA_PLATFORM\"] = \"xcb\"\n\n\ndef load_pyqt5():\n \"\"\"Return True is PyQt5 found, else False\"\"\"\n global HAVE_PYQT5, QtCore, QtGui, QtWidgets, QtOpenGL\n\n # backend already loaded, dont load another one\n if loaded_backend():\n return False\n try:\n from PyQt5 import QtCore, QtGui, QtOpenGL, QtWidgets\n\n HAVE_PYQT5 = True\n except ImportError:\n HAVE_PYQT5 = False\n return HAVE_PYQT5\n\n\ndef load_pyside2():\n \"\"\"Return True is PySide2 found, else False\"\"\"\n global HAVE_PYSIDE2, QtCore, QtGui, QtWidgets, QtOpenGL\n\n # backend already loaded, dont load another one\n if loaded_backend():\n return False\n try:\n from PySide2 import QtCore, QtGui, QtOpenGL, QtWidgets\n\n HAVE_PYSIDE2 = True\n except ImportError:\n HAVE_PYSIDE2 = False\n return HAVE_PYSIDE2\n\n\ndef load_pyqt6():\n \"\"\"Return True is PyQt5 found, else False\"\"\"\n global HAVE_PYQT6, QtCore, QtGui, QtWidgets, QtOpenGL\n\n # backend already loaded, dont load another one\n if loaded_backend():\n return False\n try:\n qt6_force_xcb_on_linux()\n from PyQt6 import QtCore, QtGui, QtOpenGL, QtWidgets\n\n HAVE_PYQT6 = True\n except ImportError:\n HAVE_PYQT6 = False\n return HAVE_PYQT6\n\n\ndef load_pyside6():\n \"\"\"Return True is PyQt5 found, else False\"\"\"\n global HAVE_PYSIDE6, QtCore, QtGui, QtWidgets, QtOpenGL\n\n # backend already loaded, dont load another one\n if loaded_backend():\n return False\n try:\n qt6_force_xcb_on_linux()\n from PySide6 import QtCore, QtGui, QtOpenGL, QtWidgets\n\n HAVE_PYSIDE6 = True\n except ImportError:\n HAVE_PYSIDE6 = False\n return HAVE_PYSIDE6\n\n\ndef load_wx():\n \"\"\"Return True is wxPython found, else False\"\"\"\n\n # backend already loaded, dont load another one\n if loaded_backend():\n return False\n global HAVE_WX\n try:\n import wx\n\n HAVE_WX = True\n except ImportError:\n HAVE_WX = False\n return HAVE_WX\n\n\ndef loaded_backend():\n return HAVE_BACKEND\n\n\ndef get_loaded_backend():\n return BACKEND_MODULE\n\n\ndef load_any_qt_backend():\n \"\"\"Load any qt based backend. First try to load\n PyQt5, then PyQt6. Raise an exception if none of them are available\n \"\"\"\n pyqt5_loaded = False\n # by default, load PyQt5\n pyqt5_loaded = load_backend(PYQT5)\n if not pyqt5_loaded:\n pyqt6_loaded = load_backend(PYQT6)\n if not (pyqt5_loaded or pyqt6_loaded):\n raise AssertionError(\"None of the PyQt5 or PyQt6 can be loaded\")\n return True\n\n\ndef load_backend(backend_str=None):\n \"\"\"Load a GUI backend\n\n If no Qt backend is found (PyQt5 or PySide), wx is loaded\n\n The search order for pythonocc compatible gui modules is:\n PyQt5, PySide2, PyQt6, PySide6, wx\n\n Note\n ----\n wx is imported when no Qt backend is found.\n\n Parameters\n ----------\n backend_str : str\n\n specifies which backend to load\n\n backend_str is one of ( \"pyqt5\", \"pyqt6\", \"pyside2\", \"pyside6\", \"wx\" )\n\n if no value has been set, load the first module in gui module search\n order\n\n Returns\n -------\n str\n the name of the loaded backend\n one of ( \"pyqt5\", \"pyqt6\", \"pyside2\", \"pyside6\", \"wx\" )\n\n Raises\n ------\n\n ValueError\n * when a backend is already loaded\n * when an invalid backend_str is specified\n\n ImportError\n when the backend specified in ``backend_str`` could not be imported\n\n \"\"\"\n global HAVE_BACKEND, BACKEND_MODULE\n\n if HAVE_BACKEND:\n msg = (\n \"The %s backend is already loaded...\"\n \"``load_backend`` can only be called once per session\"\n )\n log.info(msg, BACKEND_MODULE)\n return BACKEND_MODULE\n\n if backend_str is not None:\n compatible_backends = (PYQT5, PYQT6, PYSIDE2, PYSIDE6, WX, TK)\n if backend_str not in compatible_backends:\n msg = (\n f\"incompatible backend_str specified: {backend_str}\\n\"\n f\"backend is one of : {compatible_backends}\"\n )\n log.critical(msg)\n raise ValueError(msg)\n\n if backend_str == PYQT5 or backend_str is None:\n if load_pyqt5():\n HAVE_BACKEND = True\n BACKEND_MODULE = \"pyqt5\"\n log.info(\"backend loaded: %s\", BACKEND_MODULE)\n return BACKEND_MODULE\n if backend_str == PYQT5 and not HAVE_BACKEND:\n msg = f\"{backend_str} backend could not be loaded\"\n log.exception(msg)\n raise ValueError(msg)\n\n if backend_str == PYSIDE2 or (backend_str is None and not HAVE_BACKEND):\n if load_pyside2():\n HAVE_BACKEND = True\n BACKEND_MODULE = \"pyside2\"\n log.info(\"backend loaded: %s\", BACKEND_MODULE)\n return BACKEND_MODULE\n elif backend_str == PYSIDE2 and not HAVE_BACKEND:\n msg = f\"{backend_str} could not be loaded\"\n log.exception(msg)\n raise ValueError(msg)\n\n if backend_str == PYQT6 or backend_str is None:\n if load_pyqt6():\n HAVE_BACKEND = True\n BACKEND_MODULE = \"pyqt6\"\n log.info(\"backend loaded: %s\", BACKEND_MODULE)\n return BACKEND_MODULE\n if backend_str == PYQT6 and not HAVE_BACKEND:\n msg = f\"{backend_str} backend could not be loaded\"\n log.exception(msg)\n raise ValueError(msg)\n\n if backend_str == PYSIDE6 or backend_str is None:\n if load_pyside6():\n HAVE_BACKEND = True\n BACKEND_MODULE = \"pyside6\"\n log.info(\"backend loaded: %s\", BACKEND_MODULE)\n return BACKEND_MODULE\n if backend_str == PYSIDE6 and not HAVE_BACKEND:\n msg = f\"{backend_str} backend could not be loaded\"\n log.exception(msg)\n raise ValueError(msg)\n\n if backend_str == WX or (backend_str is None and not HAVE_BACKEND):\n if load_wx():\n HAVE_BACKEND = True\n BACKEND_MODULE = \"wx\"\n log.info(\"backend loaded: %s\", BACKEND_MODULE)\n return BACKEND_MODULE\n elif backend_str == WX and not HAVE_BACKEND:\n msg = f\"{backend_str} backend could not be loaded\"\n log.exception(\"%s backend could not be loaded\", backend_str)\n raise ValueError(msg)\n\n # finally, return a tk backend, available on all machines\n return \"tk\"\n\n\ndef get_qt_modules():\n \"\"\"\n\n Returns\n -------\n tuple : ( QtCore, QtGui, QtWidgets, QtOpenGL )\n here QtWidgets shadows QtGui when a PySide module is loaded\n this is the most coherent way to get PyQt5 compliant code\n\n Raises\n ------\n\n ValueError\n when no Qt backend has been yet loaded\n informs the user to call `load_backend` or that no Qt python module\n (PyQt5, PySide) is found\n\n \"\"\"\n if not HAVE_BACKEND:\n raise ValueError(\n \"no backend has been imported yet with \" \"``load_backend``... \"\n )\n if HAVE_PYQT5 or HAVE_PYQT6 or HAVE_PYSIDE2 or HAVE_PYSIDE6:\n return QtCore, QtGui, QtWidgets, QtOpenGL\n if HAVE_WX:\n raise ValueError(\"the wx backend is already loaded\")\n msg = (\n \"no Qt backend is loaded, hence cannot return any modules\\n\"\n \"either you haven't got PyQt5, PyQt6, PySide2 or PySide6 installed\\n\"\n \"or you haven't yet loaded a backend with the \"\n \"`OCC.Display.backend.load_backend` function\"\n )\n raise ValueError(msg)\n","repo_name":"tpaviot/pythonocc-core","sub_path":"src/Display/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":8225,"program_lang":"python","lang":"en","doc_type":"code","stars":1117,"dataset":"github-code","pt":"51"} +{"seq_id":"29657307676","text":"import os\nimport glob\nimport time\nimport requests, json\nimport RPi.GPIO as GPIO\n\nGPIO.setmode(GPIO.BOARD)\nmode=GPIO.getmode()\nGPIO.setup(11,GPIO.OUT)\nGPIO.setup(13,GPIO.OUT)\nos.system('modprobe w1-gpio')\nos.system('modprobe w1-therm')\nbase_dir = '/sys/bus/w1/devices/'\ndevice_folder = glob.glob(base_dir + '28*')[0]\ndevice_file = device_folder + '/w1_slave'\ndef read_temp_raw():\n f = open(device_file, 'r')\n lines = f.readlines()\n f.close()\n return lines\ndef read_temp():\n lines = read_temp_raw()\n while lines[0].strip()[-3:] != 'YES':\n time.sleep(0.2)\n lines = read_temp_raw()\n equals_pos = lines[1].find('t=')\n if equals_pos != -1:\n temp_string = lines[1][equals_pos+2:]\n temp_c = float(temp_string) / 1000.0\n temp_f = temp_c * 9.0 / 5.0 + 32.0\n return temp_c\nwhile True:\n print(read_temp()) \n temper=read_temp()\n if int(temper)==28:\n GPIO.output(11,GPIO.HIGH)\n GPIO.output(13,GPIO.LOW)\n elif int(temper)==24:\n GPIO.output(11,GPIO.LOW)\n GPIO.output(13,GPIO.HIGH)\n else:\n GPIO.output(11,GPIO.LOW)\n GPIO.output(13,GPIO.LOW)\n time.sleep(1)\n\n","repo_name":"junhyoung/systemNewTech","sub_path":"temperControllLED.py","file_name":"temperControllLED.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"27970900955","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 11 09:46:34 2019\n\n@author: sanja\n\"\"\"\n\n\nimport numpy as np\nimport scipy.linalg as la\nimport ODEs\n\nNo_mach = 4;\nNo_turb = 4;\nNo_states_mach = 4;\nNo_states_turb = 11;\nR_L = 5;\nX_L = 0.5;\n\n\ndef MatrixArrange(a,b,c):\n \"\"\"\n \n More often than not in Power Systems, we need this matrix representation\n (Recall Rotational Matrices)\n \n D = [a -b;\n c a]\n \n \"\"\"\n\n left = np.vstack((a, c))\n right = np.vstack((-b, a))\n \n return np.hstack((left, right))\n\n\n###############################################################################\n \ndef TurbineCurrentsInGlobal(t,x):\n \n # These are the currents available at the turbine\n i_s_q = x[0::No_states_turb];\n i_s_d = x[1::No_states_turb];\n \n #### ? ? ###### Add the rotor currents, although its small ########\n\n # The idea is to add turbine only where it is located\n Iturb = np.zeros(2*No_mach);\n Iturb[No_mach -1] = np.sum(i_s_d)\n Iturb[-1] = np.sum(i_s_q)\n \n return Iturb\n \n \n \n############################################################################### \ndef GridInterconnection(Ybus,x_sync,Iturb):\n \"\"\"\n \n This function computes voltages of various nodes using the admittance \n matrices following a number of numerical calculations\n \n Inputs:\n Ybus := Admittance matrix\n Outputs:\n Voltages of every bus\n \n \n \"\"\"\n \n # Details of the network\n # load_idx = [6, 8]; # Indices where loads are present\n # Ybus[load_idx,load_idx] = Ybus[load_idx,load_idx] \\\n # + complex(R_L,X_L)/(R_L*complex(0,X_L)); \n \n Y_gg = Ybus[:No_mach,:No_mach];\n Y_gl = Ybus[:No_mach,No_mach:];\n Y_ll = Ybus[No_mach:,No_mach:];\n\n Y_kr = Y_gg - np.dot(np.dot(Y_gl,la.inv(Y_ll)),np.transpose(Y_gl))\n\n Y_kr_pr = MatrixArrange(Y_kr.real, Y_kr.imag, Y_kr.imag)\n # Parameters of the synchronous machine\n X_d_pr = 0.031;\n X_q_pr = X_d_pr;\n R_s = 0;\n\n # Machine impedance matrix\n Z_S = MatrixArrange(R_s,X_q_pr, X_d_pr)\n Z_S_aug = la.block_diag(Z_S, Z_S, Z_S, Z_S) # Coz there are 4 machines\n \n # Transformation matrix\n T = []\n for i in range (No_mach):\n theta = x_sync[i*No_states_mach + 2]\n T_cur = MatrixArrange(np.sin(theta), np.cos(theta),np.cos(theta))\n T.append(T_cur)\n T_aug = la.block_diag(*T)\n \n # Arrange as DDQQ instead of DQDQ\n even = np.arange(0,len(Z_S_aug),2)\n odd = np.arange(1,len(Z_S_aug),2)\n new_order = np.hstack((even, odd))\n s = Z_S_aug[:,new_order]\n Z_S_DQ = s[new_order,:];\n \n T_bleh = T_aug[:,new_order] # Transformation matrix rearranged\n T_DQ = T_bleh[new_order,:]\n \n # Terminal voltages of the synchronus machine\n Ed = x_sync[0::4] # Collect d-voltages of all the machines\n Eq = x_sync[1::4] # Collect q-voltages of all the machines\n Edq = np.transpose(np.hstack((Ed,Eq)))\n \n # Compute currents with this info:\n bleh = np.dot(np.dot(T_DQ,la.inv(Y_kr_pr)),np.transpose(T_DQ))\n bleh1 = la.inv(Z_S_DQ + bleh)\n bleh2 = Edq - np.dot(np.dot(T_DQ,la.inv(Y_kr_pr)), Iturb)\n I_DQ = np.dot(bleh1,bleh2)\n Id = I_DQ[:No_mach];\n Iq = I_DQ[No_mach:];\n \n \n # Terminal voltages:\n Vdq = Edq - np.dot(Z_S_DQ,I_DQ)\n Vd = Vdq[:No_mach]\n Vq = Vdq[No_mach:]\n\n \n return Vd, Vq, Id, Iq\n \n\n############################################################################### \n \n\n\n \ndef NonLinSystem(t,x, power_yaw, Ybus):\n \"\"\"\n \n Objective: \n Describes the system of equations for a coupled machine-turbine system\n dictated by a given network. We use the Kundur 2-area system as a \n test-case\n \n Inputs:\n x := state vector\n t := time\n fi := struct containing flow info\n Ybus := Admittance matrix\n \n Outputs:\n F := d/dts\n \n Note:\n In this function, we will work with 2 systems\n 1) Turbine := No_mach*No_states_mach : No_mach*No_states_mach + 11\n 2) Synchronous Machines := 0:No_mach*No_states_mach\n \n The network gives us voltage info of the buses and we use this to\n simulate the dynamics of turbine and synch mach\n \n \"\"\"\n\n # So now we have things written in different functions \n # This is sorta the main function where we get the ODEs\n \n # Initialization:\n Nfull = No_mach*No_states_mach + No_states_turb*No_turb\n \n #==========================================================================\n # 0) Get the currents from the turbine to feed into the grid\n \n Iturb = TurbineCurrentsInGlobal(t,x[No_mach*No_states_mach:])\n \n #==========================================================================\n # 1) Get voltage from the network\n \n Vd, Vq, Id, Iq = GridInterconnection(Ybus,x[:No_mach*No_states_mach], Iturb)\n #==========================================================================\n # 2) Use this voltage to simulate SM\n \n omega_slack = x[3]\n DXsyncDT = np.zeros(No_mach*No_states_mach)\n \n # Loop over machines\n l = 0;\n for mach in range(No_mach):\n if mach == 0:\n omega_slack_1 = 377;\n else:\n omega_slack_1 = x[3];\n \n mach_dyn = ODEs.SyncMachineEqns(t, x[:No_mach*No_states_mach],\\\n omega_slack, omega_slack_1,\\\n Id[mach], Iq[mach]);\n DXsyncDT[l:l + No_states_mach] = mach_dyn\n l = l + No_states_mach\n #==========================================================================\n # 3) Use this voltage to simulate turbine\n \n DXturbDT =np.zeros(No_states_turb*No_turb)\n\n # Loop over turbines\n k = 0;\n for turb in range(No_turb):\n turb_dyn = ODEs.TurbineEqns(t, x[No_mach*No_states_mach:],\\\n power_yaw[turb]/5e6, Vd[-1],Vq[-1]);\n DXturbDT[k:k + No_states_turb] = turb_dyn\n k = k + No_states_turb\n #==========================================================================\n # 4) Stack 'em\n F = np.hstack((DXsyncDT,DXturbDT))\n \n return F","repo_name":"vijay092/FLORID","sub_path":"FLORIS+GRID/Grid.py","file_name":"Grid.py","file_ext":"py","file_size_in_byte":6243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"21339182083","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 30 15:07:45 2019\n\n@author: geoffreycideron\n\"\"\"\n\nimport numpy as np \n\nclass User:\n def __init__(self, profile, depar_loc, arr_loc, time_available, keep_point_interests=10, travel_speed=4) :\n self.profile = profile\n self.depar_loc = depar_loc #(lamb, phi) => longitude et latitude\n self.arr_loc = arr_loc\n # Calculate the mid point of the journey\n self.mid_point = self.get_mid_point(self.depar_loc, self.arr_loc)\n self.dist_mid_depar = self.distance(self.mid_point,self.depar_loc)\n self.time_available = time_available\n self.keep_point_interests = keep_point_interests\n self.travel_speed = travel_speed\n \n def distance(self, point_a, point_b):\n x = (point_a[0]-point_b[0])*np.cos((point_a[1]+point_b[1])/2)\n y = (point_a[1]-point_b[1])\n return np.sqrt(x**2 + y**2)*6.371\n \n def get_mid_point(self, depar_loc, arr_loc):\n \"\"\"\n Create the mid point of the journey\n \"\"\"\n \n delta_lambda = depar_loc[0] - arr_loc[0]\n B_x = np.cos(depar_loc[1]*np.cos(delta_lambda))\n B_y = np.sin(depar_loc[1]*np.cos(delta_lambda))\n \n mid_phi = np.arctan2(np.sin(arr_loc[1]) + np.sin(depar_loc[1]), np.sqrt((np.cos(arr_loc[1]) + B_x)**2 + B_y**2))\n mid_lamb = arr_loc[0] + np.arctan2(B_y, np.cos(arr_loc[1]) + B_x)\n \n return (mid_lamb, mid_phi)\n \n def distance_regularization(self, point_of_interest_dist):\n \"\"\"\n Penalisation of the score if the point of interest is farther than the distance\n between the departure point and the mid point\n \"\"\"\n if self.dist_mid_depar > point_of_interest_dist:\n return 1\n else:\n return np.exp(-(point_of_interest_dist - self.dist_mid_depar))\n \n def find_relevant_interest_points(self, points_of_interest):\n \"\"\"\n Return the importance of each point of interest for the user\n \"\"\"\n score = np.zeros(len(points_of_interest))\n for ind, point_of_interest in enumerate(points_of_interest):\n # Order by the profile\n score[ind] = np.dot(self.profile, point_of_interest.features)\n # Ponderate by the distance\n score[ind] *= self.distance_regularization(point_of_interest.dist(self.mid_point))\n best_pi = np.argsort(score)\n return best_pi[:self.keep_point_interests]\n \n \n \n","repo_name":"Oxydros/La-Belle-Balade","sub_path":"server/User.py","file_name":"User.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"35295348701","text":"\"\"\" Plotting for DSFE\n\"\"\"\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\n\ndef count_bar(arr, x_vals=None):\n \"\"\" Do bar plot of counts for integers in `arr`\n\n This function is a simple wrapper for ``np.bincount`` and ``plt.bar``.\n\n It assumes all the values in `arr` are all non-negative integers (such as\n counts), then counts how many times each integer occurs in `arr`, and makes\n a bar graph to display the counts.\n\n Parameters\n ----------\n arr : array-like\n A sequence that can be made into an array, such as an array or a list.\n The array must contain non-negative integers.\n x_vals : None or array-like, optional\n x values for bar plot. If None, use the obvious integer array from 0\n through the maximum value in `arr`. Otherwise, use `x_vals` as the x\n values, and select corresponding values from counts.\n\n Returns\n -------\n bc : BarContainer\n The Matplotlib container for a bar plot.\n \"\"\"\n # Convert arr to integers if necessary.\n to_count = np.asarray(arr).astype(int)\n if x_vals is None: # We didn't specify x_vals\n y_vals = np.bincount(to_count) # Count numbers of each integer.\n x_vals = np.arange(len(y_vals))\n else: # We specified x_vals\n # Make counts go up as far as we need for the x_vals indices.\n counts = np.bincount(to_count, minlength=np.max(x_vals) + 1)\n y_vals = counts[x_vals]\n out = plt.bar(x_vals, y_vals)\n plt.xticks(x_vals)\n return out\n","repo_name":"odsti/dsfe-package","sub_path":"dsfe/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"70379662238","text":"from __future__ import print_function, absolute_import, division\n\nimport subprocess\n\nimport os\nimport six\nfrom punch.vcs_repositories import git_repo as gr\nfrom punch.vcs_repositories.exceptions import (\n RepositoryStatusError,\n RepositorySystemError\n)\n\n\nclass GitFlowRepo(gr.GitRepo):\n\n def __init__(self, working_path, config_obj, files_to_commit=None):\n if six.PY2:\n super(GitFlowRepo, self).__init__(\n working_path, config_obj, files_to_commit)\n else:\n super().__init__(working_path, config_obj, files_to_commit)\n\n self.release_branch = \"release/{}\".format(\n self.config_obj.options['new_version']\n )\n\n def _set_command(self):\n self.commands = ['git', 'flow']\n self.command = 'git'\n\n def _check_system(self):\n # git flow -h returns 1 so the call fails\n\n p = subprocess.Popen(\n self.commands,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n\n stdout, stderr = p.communicate()\n\n if \"git flow \" not in stdout.decode('utf8'):\n raise RepositorySystemError(\"Cannot run {}\".format(self.commands))\n\n if not os.path.exists(os.path.join(self.working_path, '.git')):\n raise RepositorySystemError(\n \"The current directory {} is not a Git repository\".format(\n self.working_path))\n\n def pre_start_release(self):\n output = self._run([self.command, \"status\"])\n if \"Changes to be committed:\" in output:\n raise RepositoryStatusError(\n (\"Cannot start release while repository \"\n \"contains uncommitted changes\")\n )\n\n self._run([self.command, \"checkout\", \"develop\"])\n\n branch = self.get_current_branch()\n\n if branch != \"develop\":\n raise RepositoryStatusError(\n \"Current branch shall be develop but is {}\".format(branch))\n\n def start_release(self):\n self._run(\n self.commands + [\n \"release\",\n \"start\",\n self.config_obj.options['new_version']\n ])\n\n def finish_release(self):\n branch = self.get_current_branch()\n\n command = [self.command, \"add\"]\n\n if self.config_obj.include_all_files:\n command.append(\".\")\n else:\n command.extend(self.config_obj.include_files)\n command.extend(self.files_to_commit)\n self._run(command)\n\n output = self._run([self.command, \"status\"])\n if \"nothing to commit, working directory clean\" in output or \\\n \"nothing to commit, working tree clean\" in output:\n self._run([self.command, \"checkout\", \"develop\"])\n self._run([self.command, \"branch\", \"-d\", branch])\n return\n\n message = [\"-m\", self.config_obj.commit_message]\n\n command_line = [self.command, \"commit\"]\n command_line.extend(message)\n\n self._run(command_line)\n\n self._run(\n self.commands + [\n \"release\",\n \"finish\",\n \"-m\",\n branch,\n self.config_obj.options['new_version']\n ])\n\n def post_finish_release(self):\n pass\n\n def get_info(self):\n return [\n (\"Commit message\", self.config_obj.commit_message),\n (\"Release branch\", self.release_branch),\n ]\n","repo_name":"lgiordani/punch","sub_path":"punch/vcs_repositories/git_flow_repo.py","file_name":"git_flow_repo.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","stars":89,"dataset":"github-code","pt":"51"} +{"seq_id":"34839377482","text":"#Michael Solimano 2020\n#Practice implementing a stack with functions pop(), push(), peek() and isEmpty()\n#Problem Solved at Bottom of Program: Implement a function to sort a stack, without\n#placing nodes in an array / list\n\nclass Node():\n\t#A basic node to be put on a stack\n\n\tdef __init__(self, val=None):\n\t\t#Construct a simple node\n\t\tself.next = None\n\t\tself.data = val\n\t\tself.prev = None\n\n\nclass Stack():\n\t#A basic stack implementation\n\n\tdef __init__(self):\n\t\t#Initialize a stack object\n\t\tself.top = None\n\n\tdef push(self, val):\n\t\t#Push a new node onto the stack\n\t\tnew_node = Node(val)\n\n\t\t#Check for the stack is empty case\n\t\tif self.isEmpty() == True:\n\t\t\tself.top = new_node\n\t\t\treturn\n\t\telse:\n\t\t\tcurrent_top = self.top\n\t\t\tcurrent_top.next = new_node\n\t\t\tnew_node.prev = current_top\n\t\t\tself.top = new_node\n\n\tdef peek(self):\n\t\t#Return the value of the top\n\t\tif self.isEmpty() != True:\n\t\t\tcurrent_top = self.top\n\t\t\treturn current_top.data\n\n\tdef pop(self):\n\t\t#Return the current top of a stack\n\t\t#Reset the stack top\n\n\t\tcurrent_top = self.top\n\t\tone_back = current_top.prev\n\t\tself.top = one_back\n\t\tone_back.next = None\n\t\treturn current_top\n\n\n\tdef isEmpty(self):\n\t\t#Return a boolean, showing if the stack is empty.\n\n\t\tif self.top == None:\n\t\t\treturn True\n\n\t\telse:\n\t\t\treturn False\n\n\tdef printStack(self):\n\t\t#Print out the stack in order\n\n\t\tstack = []\n\t\tcurrent_node = self.top\n\n\t\t#Append stack values to the list top to bottom\n\t\twhile current_node != None:\n\t\t\tval = current_node.data\n\t\t\tstack.append(val)\n\t\t\tcurrent_node = current_node.prev\n\t\t\n\t\t#Now, reverse this list to get an in-order output of data\n\t\tin_order = []\n\t\tcounter = (len(stack) - 1)\n\t\twhile counter > -1:\n\t\t\tto_add = stack[counter]\n\t\t\tin_order.append(to_add)\n\t\t\tcounter = counter - 1\n\n\t\t#Now, print the in order stack values\n\t\tfor value in in_order:\n\t\t\tprint(value)\n\n\tdef sortQueue(self):\n\t\t#Sort the nodes in a queue (by data value) without using a separate array\n\n\t\tsort_stack = Queue()\n\t\tsort_stack.head = self.head\n\n\t\tpointer = self.head.next\n\n\t\twhile pointer != None:\n\t\t\tcompare = sort_stack.head\n\n\t\t\tif pointer.data > compare.data:\n\t\t\t\twhile pointer.data > compare.data and compare != None:\n\t\t\t\t\tcompare = compare.next\n\t\t\t\tcopy_node = Node(pointer.data)\n\t\t\t\tcopy_node.next = compare.next\n\t\t\t\tcompare.next = copy_node\n\t\t\telse:\n\t\t\t\tcopy_node = Node(pointer.data)\n\t\t\t\tcopy_node.next = compare\n\t\t\t\tsort_stack.head = copy_node\n\n\t\t\tpointer = pointer.next\n\n\t\treturn sort_stack\n\n\n\n\n\n","repo_name":"michaelsolimano16/stacks-and-queues","sub_path":"ms_stack.py","file_name":"ms_stack.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"18049807119","text":"#!/usr/bin/python2\n\nimport asyncore\nimport logging\n\nimport kivy\nkivy.require('1.9.0')\n\nfrom kivy.app import App\nfrom kivy.logger import Logger\n# from kivy.uix.widget import Widget\nfrom kivy.uix.floatlayout import FloatLayout\n# from kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.properties import (ObjectProperty, NumericProperty,\n StringProperty, BooleanProperty, ListProperty, OptionProperty)\n\nfrom kivy.core.window import Window\nfrom kivy.clock import Clock\nfrom kivy.uix.listview import ListView, ListItemLabel\nfrom kivy.adapters.listadapter import ListAdapter\n\nfrom kivy.config import ConfigParser\n\nconfig = ConfigParser()\nconfig.read(\"manachat.ini\")\n\nimport monsterdb\nimport net\nimport net.mapserv as mapserv\nimport gui.handlers as handlers\nimport plugins\nfrom commands import process_line\nfrom net.onlineusers import OnlineUsers\nfrom loggers import netlog, debuglog\n\n\nclass DebugLogHandler(logging.Handler):\n\n def __init__(self, app, **kwargs):\n self.app = app\n super(self.__class__, self).__init__(**kwargs)\n\n def emit(self, record):\n msg = self.format(record)\n self.app.root.messages_log.append_message(msg)\n\n\nclass MessagesLog(BoxLayout):\n\n def append_message(self, msg):\n if not msg.endswith(\"\\n\"):\n msg += \"\\n\"\n self.msg_log_label.text += msg\n self.msg_log_label.parent.scroll_y = 0.0\n\n\nclass PlayersListItem(BoxLayout, ListItemLabel):\n nick = StringProperty(allow_none=False)\n\n def on_touch_down(self, touch):\n if not self.collide_point(*touch.pos):\n return False\n touch.grab(self)\n return True\n\n def on_touch_up(self, touch):\n if not self.collide_point(*touch.pos):\n return False\n if touch.grab_current is self:\n app = App.get_running_app()\n app.root.chat_input.text = '/w \"{}\" '.format(self.nick)\n app.root.chat_input.focus = True\n touch.ungrab(self)\n return True\n\n\nclass PlayersList(FloatLayout):\n items = ListProperty([])\n\n def __init__(self, **kwargs):\n super(PlayersList, self).__init__(**kwargs)\n\n player_args_coverter = lambda row_index, nick: {\"nick\" : nick,\n \"size_hint_y\": None, \"height\": \"30dp\", \"pos_hint_y\": 0.9 }\n\n list_adapter = ListAdapter(\n data=[\"Ginaria\", \"Celestia\"],\n args_converter=player_args_coverter,\n selection_mode='single',\n allow_empty_selection=True,\n cls=PlayersListItem)\n\n list_view = ListView(adapter=list_adapter,\n size_hint=(1.0, 1.0),\n pos_hint={'center_x': 0.5})\n\n def data_changed(instance, value):\n list_adapter.data = value\n\n self.bind(items=data_changed)\n\n self.add_widget(list_view)\n\n\nclass RootWidget(FloatLayout):\n\n def _focus_chat_input(self, dt):\n self.chat_input.focus = True\n\n def on_command_enter(self, *args):\n process_line(self.chat_input.text)\n self.chat_input.text = ''\n Clock.schedule_once(self._focus_chat_input, 0.1) # dirty hack :^)\n\n\nclass RootWidgetMobile(RootWidget):\n pass\n\n\nclass ManaGuiApp(App):\n use_kivy_settings = BooleanProperty(False)\n\n def update_online_list(self, *l):\n self.root.players_list.items = OnlineUsers.dl_online_list(\n config.get('Other', 'online_txt_url'))\n\n def move_player(self, sender, touch):\n gx, gy = self.root.map_w.to_game_coords(touch.pos)\n Logger.info(\"move_player (%s, %s)\", gx, gy)\n mapserv.cmsg_player_change_dest(gx, gy)\n\n def hook_keyboard(self, window, key, *largs):\n if key == 27:\n self.stop()\n return True\n return False\n\n def on_start(self):\n if config.getboolean('Other', 'log_network_packets'):\n import os\n import tempfile\n\n logfile = os.path.join(tempfile.gettempdir(), \"netlog.txt\")\n netlog.setLevel(logging.INFO)\n fh = logging.FileHandler(logfile, mode=\"w\")\n fmt = logging.Formatter(\"[%(asctime)s] %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\")\n fh.setFormatter(fmt)\n netlog.addHandler(fh)\n\n monsterdb.read_monster_db()\n\n dbgh = DebugLogHandler(self)\n dbgh.setFormatter(logging.Formatter(\"[%(asctime)s] %(message)s\",\n datefmt=\"%H:%M\"))\n debuglog.addHandler(dbgh)\n debuglog.setLevel(logging.INFO)\n\n plugins.load_plugins(config, 'chatlogfile')\n\n handlers.app = self\n\n net.login(host=config.get('Server', 'host'),\n port=config.getint('Server', 'port'),\n username=config.get('Player', 'username'),\n password=config.get('Player', 'password'),\n charname=config.get('Player', 'charname'))\n\n self.root.map_w.tile_size = config.getint('GUI', 'tile_size')\n\n Clock.schedule_once(self.update_online_list, 0.2)\n Clock.schedule_interval(self.update_online_list, 35)\n Clock.schedule_interval(self.update_loop, 0)\n\n def build(self):\n Window.bind(on_keyboard=self.hook_keyboard)\n\n use_mobile = config.getboolean('GUI', 'use_mobile_interface')\n if use_mobile:\n return RootWidgetMobile()\n else:\n return RootWidget()\n\n def build_settings(self, settings):\n settings.add_json_panel('ManaChat', config,\n filename='manachat.json')\n\n def update_loop(self, *l):\n asyncore.loop(timeout=0, count=10)\n\n def on_pause(self):\n return True\n\n def on_stop(self):\n Clock.unschedule(self.update_loop)\n Clock.unschedule(self.update_online_list)\n mapserv.cleanup()\n\n\nif __name__ == \"__main__\":\n ManaGuiApp().run()\n","repo_name":"Tezer123/manachat","sub_path":"gui/managui.py","file_name":"managui.py","file_ext":"py","file_size_in_byte":5912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"7771209441","text":"from circuit import QuantumCircuit\r\nfrom gates import X_GATE, H_GATE, Y_GATE, Z_GATE\r\n\r\n\r\ndef main():\r\n print(\"Welcome to the Quantum Simulator!\\n\")\r\n\r\n # Ask user for number of qubits\r\n num_qubits = int(input(\"Enter the number of qubits: \"))\r\n\r\n # Create a quantum circuit\r\n circuit = QuantumCircuit(num_qubits)\r\n\r\n # Gate selection menu\r\n gates = {\r\n 'X': X_GATE,\r\n 'H': H_GATE,\r\n 'Y': Y_GATE,\r\n 'Z': Z_GATE\r\n }\r\n \r\n print(\"\\nAvailable gates: X, Y, Z, H\")\r\n \r\n while True:\r\n # Ask user for gate and target qubit\r\n user_input = input(\"Enter gate and target qubit index (e.g. 'H 0') or 'run' to execute: \")\r\n \r\n # Check if user wants to execute the circuit\r\n if user_input.lower() == 'run':\r\n break\r\n \r\n # Parse user input and add gate to circuit\r\n try:\r\n gate_name, target_qubit = user_input.split()\r\n target_qubit = int(target_qubit)\r\n if gate_name in gates:\r\n circuit.add_gate(gates[gate_name], target_qubit)\r\n else:\r\n print(\"Invalid gate name.\")\r\n except ValueError:\r\n print(\"Invalid input format. Please enter gate and target qubit index.\")\r\n\r\n # Execute the circuit\r\n circuit.execute()\r\n\r\n # Print the state of each qubit\r\n for i in range(num_qubits):\r\n print(f\"State of qubit {i}:\", circuit.get_state(i))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"mrussotti/Quantum_Projects","sub_path":"QuantumSimulator/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"72982031837","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\n\r\n#--------------FUNCIONES\r\ndef infoAdicional():\r\n messagebox.showinfo(\"Procesador de Cristhian\",\"Procesador de texto 2019\")\r\n # messagebox.showerror(\"procesador de texto\",\"Procesador de texto\")\r\n #messagebox.showwarning(\"procesador de texto\",\"Procesador de texto\")\r\ndef avisoLicencia():\r\n messagebox.showwarning(\"Licencia\",\"Procesador de texto licencia expiro\")\r\ndef salir():\r\n # valor = messagebox.askquestion(\"Salir\",\"Deseas salir\")#ventana emergente de pregunta si o no\r\n\r\n valor = messagebox.askokcancel(\"Salir\",\"Deseas salir\")\r\n\r\n # if valor==\"yes\":\r\n # root.destroy()\r\n if valor==True:\r\n root.destroy()\r\ndef cerrarDoc():\r\n valor = messagebox.askretrycancel(\"Reintentar\",\"No es posible cerrar el docuemnto\")\r\n if valor ==False:\r\n root.destroy()\r\n#-------------------DISEÑP\r\nroot =Tk()\r\nbarraMenu = Menu(root)\r\n\r\nroot.config(menu=barraMenu,width=700,height=300)\r\nroot.resizable(0,0)\r\n\r\n#-----------crea la opcion de menu\r\narchivoMenu= Menu(barraMenu,tearoff=0)\r\n#-------------las opciones de menu archivo\r\narchivoMenu.add_command(label=\"Nuevo\")\r\narchivoMenu.add_command(label=\"Guardar\")\r\narchivoMenu.add_command(label=\"Guardar como ...\")\r\narchivoMenu.add_separator()#agrega un separador\r\narchivoMenu.add_command(label=\"Cerrar\",command=cerrarDoc)\r\narchivoMenu.add_command(label=\"Salir\",command=salir)\r\n\r\neditarMenu= Menu(barraMenu,tearoff=0)\r\n\r\neditarMenu.add_command(label=\"Copiar\")\r\neditarMenu.add_command(label=\"Cortar\")\r\neditarMenu.add_command(label=\"Pegar\")\r\n\r\n\r\nherramientasMenu= Menu(barraMenu,tearoff=0)\r\nayudaMenu= Menu(barraMenu,tearoff=0)\r\nayudaMenu.add_command(label=\"Licencia\",command=avisoLicencia)\r\nayudaMenu.add_command(label=\"Acerca de...\",command=infoAdicional)\r\n\r\n#---------------ponemos en la ventana los menus\r\nbarraMenu.add_cascade(label=\"Archivo\",menu=archivoMenu)\r\nbarraMenu.add_cascade(label=\"Editar\",menu=editarMenu)\r\nbarraMenu.add_cascade(label=\"Herramientas\",menu=herramientasMenu)\r\nbarraMenu.add_cascade(label=\"Ayuda\",menu=ayudaMenu)\r\n\r\n\r\n\r\nroot.mainloop()","repo_name":"Crisfon6/Python-Review","sub_path":"graficos/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"18108497462","text":"\"\"\"\nA reffer from https://www.protechtraining.com/blog/post/tutorial-the-observer-pattern-in-python-879\n\"\"\"\nfrom publisher import Publisher\nfrom subscriber import Subscriber\n\n\nif __name__ == \"__main__\":\n pub = Publisher(['lunch', 'dinner'])\n bob = Subscriber('Bob')\n alice = Subscriber('Alice')\n john = Subscriber('John')\n\n pub.register(\"lunch\", bob)\n pub.register(\"dinner\", alice)\n pub.register(\"lunch\", john)\n pub.register(\"dinner\", john)\n\n pub.dispatch(\"lunch\", \"It's lunchtime!\")\n pub.dispatch(\"dinner\", \"Dinner is served\")","repo_name":"dtleal/design-patterns","sub_path":"observer/example2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"13888829081","text":"#!/usr/bin/python3\n\nimport json, requests, itertools, argparse\nfrom operator import itemgetter\n\n\nparser = argparse.ArgumentParser(description='Cardano Descentralization')\nparser.add_argument('-n', '--network', dest='network', type=str, help='testnet or mainnet', required=True)\nparser.add_argument('-f', '--filter', dest='filter', type=str, help='state or continent', required=True)\n\nargs = parser.parse_args()\n\nif (args.network not in [\"mainnet\",\"testnet\"]):\n raise ValueError(\"use testnet or mainnet\")\n\nif (args.filter not in [\"state\",\"continent\"]):\n raise ValueError(\"use state or continent\")\n\n\n#VARIABLES\nif args.network == \"mainnet\":\n url = \"https://explorer.mainnet.cardano.org/relays/topology.json\"\n topology = requests.get(url)\n data = topology.json()\nelse:\n url = \"https://explorer.cardano-testnet.iohkdev.io/relays/topology.json\"\n topology = requests.get(url)\n data = topology.json()\n\n#EXEC\nif args.filter == \"continent\":\n relays_continent = sorted(data[\"Producers\"], key=itemgetter(\"continent\"))\n total=len(list(relays_continent))\n for country, continent in itertools.groupby(relays_continent, key=itemgetter(\"continent\")):\n print(country, round((len(list(continent))/total*100),5), sep=\"|\")\nelse:\n relays_state = sorted(data[\"Producers\"], key=itemgetter(\"state\"))\n total=len(list(relays_state))\n for country, state in itertools.groupby(relays_state, key=itemgetter(\"state\")):\n print(country, round((len(list(state))/total*100),5), sep=\"|\")\n\n","repo_name":"MurphyStakePool/cardanoDecentralization","sub_path":"decentralization.py","file_name":"decentralization.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"11991026011","text":"#!/usr/bin/python\n# -*- encoding: utf-8 -*-\n\nimport os\nimport sys\nimport pdb\nimport robotexclusionrulesparser\nimport line_escape\nimport urlparse\nimport urllib\n\ndef LoadRobots (content, rp):\n dest = line_escape.unescape(content)\n# rp.parse(dest)\n arr = dest.split('\\n')\n for i, item in enumerate(arr):\n if item.strip() == 'Allow:':\n arr[i] = \"Allow: /\"\n if arr[i].find('**') != -1:\n b = arr[i].split('*')\n l = len(b)\n arr[i] = '*'.join([elem for j,elem in enumerate(b) if j == 0 or j == l-1 or elem != \"\"])\n\n rp.parse('\\n'.join(arr))\n\ndef CanFetch (url, rp):\n flds = url.split(\"/\")\n relative = ''\n if len(flds) == 3:\n relative = '/'\n else:\n relative = '/' + '/'.join(flds[3:])\n\n someotherspider_allowed = False\n oneboxspider_allowed = False\n can_fetch = True \n #pdb.set_trace()\n if True == rp.is_allowed('360Spider', relative):\n can_fetch = True\n oneboxspider_allowed = True\n someotherspider_allowed = True\n else:\n can_fetch = False\n if can_fetch == False:\n if True == rp.is_allowed('Baiduspider', relative) or \\\n True == rp.is_allowed('Googlebot', relative):\n can_fetch = True\n someotherspider_allowed = True\n return (can_fetch, oneboxspider_allowed, someotherspider_allowed)\n\ndef ReadSequential (url_field, robots_level_field, spider_type, output_can_fetch):\n rp = robotexclusionrulesparser.RobotExclusionRulesParser()\n\n robots_host = ''\n robots_loaded = False\n robots_raw_content = ''\n\n every_n_idx = 0\n every_n = 100000\n\n for line in sys.stdin:\n # for line in open('test/samples.test'):\n #pdb.set_trace()\n array = line.strip('\\n').split('\\t')\n cur_host = array[0]\n tag = array[1]\n url = ''\n if tag is 'A':\n robots_host = cur_host\n robots_loaded = False\n robots_raw_content = array[2]\n continue\n else:\n url = urllib.quote(array[url_field], safe='/@#?:')\n\n #pdb.set_trace()\n can_fetch = True\n oneboxspider_allowed = False\n someotherspider_allowed = False\n has_robots_txt = False\n if cur_host == robots_host:\n if robots_loaded == False:\n LoadRobots(robots_raw_content, rp)\n robots_loaded = True\n has_robots_txt = True\n (can_fetch, oneboxspider_allowed, someotherspider_allowed) = CanFetch(url, rp)\n\n robots_level = 0\n if can_fetch == False:\n robots_level = 0\n elif has_robots_txt == False:\n robots_level = 1\n elif oneboxspider_allowed == False and someotherspider_allowed == True:\n robots_level = 2\n elif oneboxspider_allowed == True:\n robots_level = 3\n else:\n sys.stderr.write(\"invalid robots_level\")\n sys.exit(1)\n\n if spider_type == 3:\n can_fetch = True\n elif spider_type ==1 and can_fetch == True and has_robots_txt == True and oneboxspider_allowed == False:\n can_fetch = False\n\n if can_fetch == output_can_fetch:\n if robots_level_field > 0:\n array.insert(robots_level_field, str(robots_level))\n output_line = \"\\t\".join(array[2:])\n sys.stdout.write('%s\\n' % (output_line))\n else:\n# 打印到标准错误的日志\n if robots_level_field > 0:\n array.insert(robots_level_field, str(robots_level))\n output_line = \"\\t\".join(array[2:])\n if every_n_idx % every_n == 0:\n sys.stderr.write('%s\\n' % (output_line))\n every_n_idx = 0\n every_n_idx += 1\n\nif __name__ == '__main__':\n if len(sys.argv) < 5:\n sys.stderr.write(\"4 cmd paras expected\\n\")\n sys.exit(1)\n\n url_field = int(sys.argv[1])\n url_field += 2\n\n# general_spider: I am transformer of any spider, eg. Baiduspider, GoogleBot..\n# 360 Spider, I am 360Spider\n# RushSpider, I am rushing, what is robots.txt?\n spider = sys.argv[2]\n if spider != 'GeneralSpider' and \\\n spider != '360Spider' and \\\n spider != 'RushSpider':\n sys.stderr.write('Invalid input, spider')\n sys.exit(1)\n\n spider_type = 1\n if spider == '360Spider':\n spider_type = 1\n elif spider == 'GeneralSpider':\n spider_type = 2\n else:\n spider_type = 3\n\n robots_level_field = int(sys.argv[3])\n robots_level_field += 2\n# 1, 输出 can fetch\n# 其他, 输出 cannot fetch\n output_type = int(sys.argv[4])\n if output_type == 1:\n output_can_fetch = True\n else:\n output_can_fetch = False\n\n ReadSequential(url_field, robots_level_field, spider_type, output_can_fetch)\n\n\n","repo_name":"pengdan01/spider","sub_path":"crawler/crawler/control/robots/robots_parser_mapper.py","file_name":"robots_parser_mapper.py","file_ext":"py","file_size_in_byte":4332,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"14828575160","text":"class Solution:\n def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:\n area1 = (ax2 - ax1) * (ay2 - ay1)\n area2 = (bx2 - bx1) * (by2 - by1)\n if ax2 <= bx1 or bx2 <= ax1 or by2 <= ay1 or ay2 <= by1:\n dup = 0\n else:\n x = [ax1, ax2, bx1, bx2]\n x.sort()\n y = [ay1, ay2, by1, by2]\n y.sort()\n dup = (x[2] - x[1]) * (y[2] - y[1])\n return area1 + area2 - dup\n","repo_name":"xinyi-han/leetcode","sub_path":"algorithms/223-Rectangle-Area.py","file_name":"223-Rectangle-Area.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"26913330223","text":"from functools import reduce\r\nimport math\r\nclass Perceptron(object):\r\n def __init__(self, input_num, activator): # 1.初始化函数2.预测函数3.多轮训练函数4.更新函数5单轮训练函数\r\n '''\r\n 初始化感知器,设置输入参数的个数,以及激活函数。\r\n 激活函数的类型为double -> double\r\n '''\r\n self.activator = activator # 这里输入的是感知器的激活函数\r\n # 权重向量初始化为0\r\n self.weights = [0.0 for _ in range(input_num)] # 权重都初始画为0,input_num=2,权重值也是list[0.0,0.0]\r\n # 偏置项初始化为0\r\n self.bias = 0.0\r\n\r\n def __str__(self): # 这个函数是被print()调用的\r\n '''\r\n 打印学习到的权重、偏置项\r\n '''\r\n return 'weights\\t:%s\\nbias\\t:%f\\n' % (self.weights, self.bias)\r\n\r\n def predict(self, input_vec):\r\n '''\r\n 输入向量,输出感知器的计算结果\r\n '''\r\n # 把input_vec[x1,x2,x3...]和weights[w1,w2,w3,...]打包在一起\r\n # 变成[(x1,w1),(x2,w2),(x3,w3),...]\r\n # 然后利用map函数计算[x1*w1, x2*w2, x3*w3]\r\n # 最后利用reduce求和\r\n return self.activator(\r\n reduce(lambda a, b: a + b, # reduce的第一个参数为求和函数,第二个参数是map函数处理后的新list\r\n list(map(lambda x, w: x * w, # map的第一个参数是两个数的乘积\r\n input_vec, self.weights)) # map的第二个参数是输入向量和权值向量打包后的list\r\n , 0.0) + self.bias) #最后返回的是调用了激活函数的返回值1或0\r\n\r\n def train(self, input_vecs, labels, iteration, rate):\r\n '''\r\n 输入训练数据:一组向量、与每个向量对应的label;以及训练轮数、学习率\r\n '''\r\n for i in range(iteration):\r\n self._one_iteration(input_vecs, labels, rate)\r\n\r\n def _one_iteration(self, input_vecs, labels, rate):\r\n '''\r\n 一次迭代,把所有的训练数据过一遍\r\n '''\r\n # 把输入和输出打包在一起,成为样本的列表[(input_vec, label), ...]\r\n # 而每个训练样本是(input_vec, label)\r\n samples = list(zip(input_vecs, labels))\r\n loss=0\r\n i=0\r\n # 对每个样本,按照感知器规则更新权重\r\n for (input_vec, label) in samples: # 此时input_vec是一个样本,label是其标签如:[1, 1] 1\r\n # 计算感知器在当前权重下的输出\r\n output = self.predict(input_vec) # 返回预测标签\r\n # 更新权重\r\n loss+=self._update_weights(input_vec, output, label, rate) # 输入此时的样本,预测值,真实标签,学习率\r\n i=i+1\r\n print('loss:',loss/i)\r\n def _update_weights(self, input_vec, output, label, rate):\r\n '''\r\n 按照感知器规则更新权重\r\n '''\r\n # 把input_vec[x1,x2,x3,...]和weights[w1,w2,w3,...]打包在一起\r\n # 变成[(x1,w1),(x2,w2),(x3,w3),...]\r\n # 然后利用感知器规则更新权重\r\n delta = label - output\r\n #print(delta)\r\n self.weights = list(map(\r\n lambda x, w: w + rate * delta * x,\r\n input_vec, self.weights))\r\n # 更新bias\r\n self.bias += rate * delta\r\n return(delta**2)\r\n\r\n\r\n\r\nclass LinearUnit(Perceptron): # 继承了Perceptronf\r\n def __init__(self, input_num,func):\r\n '''初始化线性单元,设置输入参数的个数'''\r\n self.func=func\r\n Perceptron.__init__(self, input_num, self.func) # f定义在前面可以直接写?原来代码跟我不一样,看一下原来代码思路\r\ndef get_training_dataset():\r\n '''\r\n 捏造5个人的收入数据\r\n '''\r\n # 构建训练数据\r\n # 输入向量列表,每一项是工作年限,第二项是职位1,2,3\r\n input_vecs =[ [0.29542801],[0.27334914],[0.48793942],[0.34162864],[0.68219209],[0.60673505],\r\n [0.40210965],[0.23888192],[0.948605],[0.0495657],[0.57764995],[0.83816797],\r\n [0.48592442],[0.51871407],[0.73516047],[0.69514716],[0.283856],[0.55346227]]\r\n # 期望的输出列表,月薪,注意要与输入一一对应\r\n labels = [0.32954282, 0.32733494,0.34879395,0.33416289,0.36821923,0.36067352,0.34021097,0.32388821,0.39486051,0.30495659,0.35776502,0.38381681,0.34859246,0.35187143,0.37351605,0.36951473,0.32838562,0.35534623]\r\n return input_vecs, labels\r\ndef f(x):\r\n return x\r\ndef train_linear_unit():\r\n '''\r\n 使用数据训练线性单元\r\n '''\r\n # 创建感知器,输入参数的特征数为1(工作年限)\r\n lu = LinearUnit(2,f)\r\n # 训练,迭代10轮, 学习速率为0.01\r\n input_vecs, labels = get_training_dataset()\r\n lu.train(input_vecs, labels, 1000, 0.5)\r\n #返回训练好的线性单元\r\n return lu\r\nif __name__ == '__main__':\r\n '''训练线性单元'''\r\n linear_unit = train_linear_unit()\r\n # 打印训练获得的权重\r\n print(linear_unit)\r\n # 测试\r\n print('[0.29542801]测试值:{}'.format(linear_unit.predict([0.29542801])))\r\n print('[0.48793942]测试值:{}'.format(linear_unit.predict([0.48793942])))\r\n print('[0.27334914]测试值:{}'.format(linear_unit.predict([0.27334914])))\r\n print('[0.34162864]测试值:{}'.format(linear_unit.predict([0.34162864])))","repo_name":"AIMarkov/tensorflow","sub_path":"线性单元(手工).py","file_name":"线性单元(手工).py","file_ext":"py","file_size_in_byte":5461,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"10523647153","text":"from nltk.corpus import wordnet as wn\n\ndef isantonym(word1, word2):\n \"\"\"\n judge whether two word are antonym\n \"\"\"\n\n w1_lemma = [lemma for lemma in wn.lemmas(word1)]\n w1_antonyms = set()\n for lemma in w1_lemma:\n for antonym in lemma.antonyms():\n w1_antonyms.add(antonym.name)\n\n if word2 in w1_antonyms:\n return True\n else:\n return False\n\ndef antonyms(word):\n \"\"\"\n return all antonyms of word\n \"\"\"\n\n lemmas = [lemma for lemma in wn.lemmas(word)]\n antonyms = set()\n for lemma in lemmas:\n for antonym in lemma.antonyms():\n antonyms.add(antonym.name)\n return antonyms\n","repo_name":"dx88968/SRA","sub_path":"antonym.py","file_name":"antonym.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"18563586447","text":"import os, stat\nimport threading\nimport sqlite3 as sql\nimport re\n\nimport telegram\nimport discord\n\ndef validateName( name ):\n\n if re.match('^[a-zA-Z0-9.,#-]{1,20}$',name):\n return name\n\n return None\n\ndef validateIp( ip ):\n\n if re.match('^(?:(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])(\\.(?!$)|$)){3}(?:(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])(\\.(?!$)|$|:9678)){1}$',ip):\n return ip.replace(':9678','')\n\n return None\n\ndef isInt(s):\n try:\n int(s)\n return True\n except:\n return False\n\ndef pathIsWritable(path):\n mode = os.lstat(path)[stat.ST_MODE]\n return True if mode & stat.S_IWUSR else False\n\ndef secondsToText(secs):\n days = secs//86400\n hours = (secs - days*86400)//3600\n minutes = (secs - days*86400 - hours*3600)//60\n seconds = secs - days*86400 - hours*3600 - minutes*60\n\n if days:\n seconds = -1\n minutes = -1\n\n result = (\"{0} day{1}, \".format(days, \"s\" if days!=1 else \"\") if days else \"\")\n result += (\"{0} hour{1}{2} \".format(hours, \"s\" if hours!=1 else \"\", \",\" if minutes and not days else \"\") if hours else \"\")\n result += (\"{0} minute{1}{2} \".format(minutes, \"s\" if minutes!=1 else \"\", \",\" if seconds and not minutes else \"\") if minutes and not days else \"\")\n result += (\"{0} second{1} \".format(seconds, \"s\" if seconds!=1 else \"\") if seconds and not minutes else \"\")\n return result if result != \"\" else \"Now\"\n\ndef crossMessengerSplit(obj):\n\n result = {'user': None, 'name': None, 'chat':None, 'public':False}\n\n if isinstance(obj, telegram.update.Update):\n #Telegram\n result['user'] = obj.message.from_user.id\n result['name'] = obj.message.from_user.name\n result['chat'] = obj.message.chat_id\n elif isinstance(obj, discord.Member) or \\\n isinstance(obj, discord.User):\n result['user'] = obj.id\n result['name'] = obj.name\n elif isinstance(obj.author, discord.Member) or \\\n isinstance(obj.author, discord.User):\n #Discord public/private message\n result['user'] = obj.author.id\n result['name'] = obj.author.name\n result['chat'] = obj.channel.id\n result['public'] = isinstance(obj.author, discord.Member)\n\n return result\n\ndef memcmp ( str1, str2, count):\n\n while count > 0:\n count -= 1\n\n if str1[count] != str2[count]:\n return -1 if str1[count] < str2[count] else 1\n\n return 0\n","repo_name":"xdustinface/SmartNodeMonitorBot","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"57"} +{"seq_id":"3913262717","text":"class Solution(object):\n def minimumJumps(self, forbidden, a, b, x):\n \"\"\"\n :type forbidden: List[int]\n :type a: int\n :type b: int\n :type x: int\n :rtype: int\n \"\"\"\n\n # parameters\n jumps = -1\n possibleJumps = []\n\n # start computing\n possibleJumps.append([0, True])\n while possibleJumps:\n jumps += 1\n pP_size = len(possibleJumps)\n\n for i in range(pP_size):\n [currP, backC] = possibleJumps.pop(0)\n\n if (currP == x):\n return jumps\n elif (currP in forbidden):\n continue\n else:\n \n # backward (check if it backwarded once, also for the negative position)\n if (backC and (0 <= currP-b)):\n possibleJumps.append([currP-b, False])\n \n # forward (check if it is going to jump redundandly)\n if (currP-b <= 2000):\n possibleJumps.append([currP+a, True])\n \n forbidden.append(currP)\n\n return -1\n","repo_name":"Koyama-Tsubasa/LeetCode","sub_path":"Problems/No.1654_Minimum_Jumps_to_Reach_Home/minimum_jumps_to_reach_home.py","file_name":"minimum_jumps_to_reach_home.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"57"} +{"seq_id":"8217249330","text":"import matplotlib.pyplot as plt\nfrom pylab import *\n\ndef plot_reward(file_name):\n with open(file_name, 'r') as ip:\n lines = ip.readlines()\n step = []\n reward = []\n for idx, line in enumerate(lines):\n line = line.split(':')[-1]\n line = line.split(',')\n step.append(int(line[0]))\n reward.append(float(line[1]))\n plot(step, reward, label=file_name.split('.')[0])\n\n\nplot_reward('dqn_reward.log')\nplot_reward('double_reward.log')\nplot_reward('dueling_reward.log')\nplt.legend(loc='upper right')\nplt.savefig('improvement.png')\n","repo_name":"PierreSue/Play-Atari-games-using-Deep-Reinforcement-Learning","sub_path":"plot/improvement_plot.py","file_name":"improvement_plot.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"41350646520","text":"import io, os, sys, shutil\nfrom Bio import SeqIO\n\nif len(sys.argv) != 3:\n print('Usage: parition_pear.py ')\nelse:\n pearfile = sys.argv[1]\n nump = eval(sys.argv[2])\n dirname = '/'.join(pearfile.split('/')[:-1])\n pearsuffix = pearfile.split('/')[-1]\n\n for filename in os.listdir(dirname):\n if filename[:len(pearfile)+1] == ('%s_' % pearsuffix):\n os.remove(dirname + '/' + filename)\n\n fouts = []\n for i in range(nump):\n fouts.append(io.open(pearfile[:-5] + '_%d.' % i + pearfile[-5:],'w'))\n\n i, j = 0,0\n f = io.open(pearfile)\n for line in f:\n fouts[i%nump].write(line)\n j += 1\n i += (j%4 == 0)\n f.close()\n for i in range(nump):\n fouts[i].close()\t\t\n\n \n","repo_name":"felicityallen/SelfTarget","sub_path":"indel_analysis/compute_indels/partition_pear.py","file_name":"partition_pear.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"57"} +{"seq_id":"21775064536","text":"def solution(word):\n alph = 'AEIOU'\n li = []\n\n def dfs(path):\n if len(path) > 5: return\n li.append(path)\n\n for i in alph:\n s = path + i\n dfs(s)\n\n for i in alph:\n dfs(i)\n\n answer = li.index(word) + 1\n\n return answer","repo_name":"imji0319/new_python","sub_path":"PythonInterview/CodingStudy/weekly/5주차.py","file_name":"5주차.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"43743638243","text":"from tkinter import *\nfrom tkinter import ttk\nfrom PIL import Image, ImageTk\nimport os\n\n## Gui class using TKinter module\n##\n## Gui for selecting start and destinations \n## and calculating shortest route to display\n\n## displays a graph representation of the stations, \n## defines the layout and look of the GUI\nclass Gui(Frame):\n## this function sets up the appearance of the GUI, such as the buttons,\n# labels and drop downs\n def __init__(self, master=None):\n \n Frame.__init__(self, master)\n #display of app\n self.master.title(\"TrainApp\")\n \n self.canvas_frame = Frame(self.master, width=400, height=300)\n self.hbar = Scrollbar(self.canvas_frame, orient=HORIZONTAL)\n self.vbar = Scrollbar(self.canvas_frame, orient=VERTICAL)\n\n\n #add some labels\n self.from_station_label = ttk.Label(self.master, text=\"Station From:\")\n self.to_station_label = ttk.Label(self.master, text=\"Station To:\")\n \n self.from_station_label.pack() #grid(column = 0, row = 0)\n # Add a combobox widget\n self.station_from_combo = ttk.Combobox(self.master)\n #combo['values'] = (1,2,3,4,5, \"Text\")\n self.station_from_combo.pack() #.grid(column = 1, row = 0)\n \n self.to_station_label.pack() #grid(column=2, row = 0)\n self.station_to_combo = ttk.Combobox(self.master)\n \n #combo2['values'] = (1,2,3,4,5, \"Text\")\n self.station_to_combo.pack() #grid(column = 3, row = 0)\n self.find_route_button = ttk.Button(self.master)\n self.find_route_button.pack() #grid(column = 4, row = 0)\n \n self.route_text_frame = Frame(self.master)\n self.route_text_box = Text(self.route_text_frame, height =3, width =50)\n self.route_text_scroll_bar = Scrollbar(self.route_text_frame)\n self.route_text_scroll_bar.config(command=self.route_text_box.yview)\n self.route_text_box.config(yscrollcommand=self.route_text_scroll_bar.set)\n self.route_text_box.configure(state='disabled')\n self.route_text_scroll_bar.pack(side=RIGHT, fill=BOTH)\n self.route_text_box.pack()\n self.route_text_frame.pack(expand=True)\n image_path = os.path.join(os.path.abspath(os.getcwd()), \"LondonNetwork.gif\")\n\n self.graph_image = ImageTk.PhotoImage(Image.open(image_path))\n self.canvas = Canvas(self.canvas_frame, xscrollcommand=self.hbar.set,\n yscrollcommand=self.vbar.set,\n width=300,\n height=200,\n bg='white')\n self.canvas.create_image(self.graph_image.width(),self.graph_image.height(), image=self.graph_image)\n self.hbar[\"command\"] = self.canvas.xview\n self.vbar[\"command\"] = self.canvas.yview\n self.canvas.config(scrollregion=self.canvas.bbox(\"all\"))\n self.vbar.pack(side=RIGHT, fill=Y)\n self.hbar.pack(side=BOTTOM, fill=X)\n self.canvas.pack(side=LEFT, expand=True, fill=BOTH)#grid(column=0, row=1)\n self.canvas_frame.pack(expand=True, fill=BOTH)\n \n \n \n \n## This sets the text in the textbox\n def set_route_text_box_text(self, text):\n #self.route_text_box[\"text\"] = text\n self.route_text_box.configure(state='normal')\n self.route_text_box.delete(0.0,END)\n self.route_text_box.insert(0.0, text)\n self.route_text_box.configure(state='disabled')\n\n## This sets the to and from station names for combo boxes\n def set_station_names_combo(self, from_stations, to_stations):\n self.station_from_combo[\"values\"] = from_stations\n self.station_to_combo[\"values\"] = to_stations\n\n## This sets the function to call when the find route button is pressed \n def set_button_function(self, function):\n self.find_route_button[\"command\"] = function\n\n## This sets 'find route' text on the button\n def set_button_text(self, text):\n self.find_route_button[\"text\"] = text\n\n## This gets the text from the combo box \n def get_from_station_name(self):\n return self.station_from_combo.get()\n\n## This gets the text from the combo box \n def get_to_station_name(self):\n return self.station_to_combo.get()\n\n## This starts the GUI\n def start_main_loop(self):\n self.mainloop()\n \n\n\n\n\n","repo_name":"JessicaFarrell/trainapp","sub_path":"view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":4352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"19264885648","text":"def love_meet(amant1, amant2):\n rencontre = []\n for i in amant1:\n for j in amant2:\n if i == j:\n rencontre.append(i)\n rencontre = set(rencontre)\n return(rencontre)\n\n\ndef affair_meet(amant1, amant2, amant3):\n dispute = set(amant2) & set(amant1)\n amour = set(amant2) & set(amant3)\n rencontre = amour - dispute\n return(rencontre)\n","repo_name":"Ninanouchka/hackinscience","sub_path":"exercises/097/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"72935950899","text":"def solution(scores):\n n = len(scores)\n ans = []\n for j in range(n):\n me = scores[j][j]\n s = 0\n cnt = n\n min_val = 100\n max_val = 0\n tmp = []\n\n for i in range(n):\n tmp.append(scores[i][j])\n s += scores[i][j]\n max_val = max(max_val, scores[i][j])\n min_val = min(min_val, scores[i][j])\n\n if me == min_val and tmp.count(min_val) == 1:\n s -= me\n cnt -= 1\n if me == max_val and tmp.count(max_val) == 1:\n s -= me\n cnt -= 1\n\n ans.append(s / cnt)\n\n res = \"\"\n for x in ans:\n if x >= 90:\n res += \"A\"\n elif x >= 80:\n res += \"B\"\n elif x >= 70:\n res += \"C\"\n elif x >= 50:\n res += \"D\"\n else:\n res += \"F\"\n return res\n\nsolution([[100,90,98,88,65],[50,45,99,85,77],[47,88,95,80,67],[61,57,100,80,65],[24,90,94,75,65]])","repo_name":"hahyuning/CodingTest-Study","sub_path":"programmers/위클리 챌린지/2주차.py","file_name":"2주차.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"22813052210","text":"# Made by @o_s_h_o_r_a_j\n# Change credit and you gay.\n\n\nfrom ..core.managers import edit_delete\nfrom ..helpers.utils import reply_id\nfrom . import catub\n\nplugin_category = \"extra\"\n\n\n@catub.cat_cmd(\n pattern=\"ilyrics ?(.*)\",\n command=(\"ilyrics\", plugin_category),\n info={\n \"header\": \"Sends lyrics [inline] of a song along with Spotify & Youtube links\\n•Add artist name if you getting different lyrics\\n•you can also type a line of a song to search\",\n \"usage\": [\n \"{tr}ilyrics \",\n \"{tr}ilyrics \",\n ],\n },\n)\nasync def GayIfUChangeCredit(event):\n \"Lyrics Time\"\n if event.fwd_from:\n return\n bot = \"@ilyricsbot\"\n song = event.pattern_match.group(1)\n reply_to_id = await reply_id(event)\n if not song:\n return await edit_delete(event, \"`Gimme a song u baka!`\", 15)\n await event.delete()\n results = await event.client.inline_query(bot, song)\n await results[0].click(event.chat_id, reply_to=reply_to_id)\n","repo_name":"BusyDragon-1237/pepecat","sub_path":"userbot/plugins/ilyrics.py","file_name":"ilyrics.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"57"} +{"seq_id":"18888869381","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom urllib.parse import urljoin\n\nfrom .base_parser import BaseParser\n\n\nclass KrarmymilParser(BaseParser):\n name = 'krarmymil'\n \n # 站点id\n site_id = \"eb288286-36ce-431d-a5af-4027024a1754\"\n # 站点名\n site_name = \"韩国陆军\"\n # 板块信息\n channel = [\n {\n # 板块默认字段(站点id, 站点名, 站点地区)\n **{\"site_id\": \"eb288286-36ce-431d-a5af-4027024a1754\", \"source_name\": \"韩国陆军\", \"direction\": \"usa\", \"if_front_position\": False}, \n # (板块id, 板块名, 板块URL, 板块类型)\n **{\"board_id\": board_id, \"site_board_name\": board_name, \"url\": board_url, \"board_theme\": board_theme}\n }\n for board_id, board_name, board_url, board_theme in [\n (\"d7d98134-a346-433c-9651-3aee04db6c86\", \"新闻稿\", \"https://www.army.mil.kr/webapp/user/indexSub.do?codyMenuSeq=20360841&siteId=army\", \"政治\"),\n (\"8197f17a-de1c-463a-be4f-5b9095aefeea\", \"陆军新闻\", \"https://www.army.mil.kr/webapp/user/indexSub.do?codyMenuSeq=213347&siteId=army\", \"政治\"),\n ]\n ]\n \n def __init__(self):\n BaseParser.__init__(self)\n\n def parse_list(self, response) -> list:\n if response.url.startswith('https://www.army.mil.kr/webapp/user/indexSub.do?codyMenuSeq=20360841&siteId=army'):\n urls = response.xpath('//td[@class=\"title\"]/a/@href').extract() or \"\"\n for url in urls:\n yield urljoin(response.url, url)\n js_code = response.xpath('//div[@class=\"thumb\"]/a/@onclick').extract() or \"\"\n for item in js_code:\n item = eval(item.replace('javascript:jf_view', '').replace(';', ''))\n boardId, boardSeq = item[1], item[2]\n news_url = response.url + f'&dum=dum&boardId={boardId}&page=1&command=albumView&boardSeq={boardSeq}&chkBoxSeq=&categoryId=&categoryDepth='\n yield news_url\n\n def get_title(self, response) -> str:\n title = response.xpath('//dl[@class=\"viewdata\"]/dt/text()').extract_first(default=\"\") or \"\"\n news_issue_title = title.strip().replace('\\n', '').replace('\\t', '')\n return news_issue_title or \"\"\n\n def get_author(self, response) -> list:\n return []\n\n def get_pub_time(self, response) -> str:\n # Posted at: Apr 21 2021 3:15PM\n time_ = response.xpath('//div[@class=\"id\"]/dl/dt[contains(text(), \"작성일\")]/following-sibling::dd[1]/text()|'\n '//div[@class=\"id\"]/dl/dt[contains(text(), \"일 자\")]/following-sibling::dd[1]/text()').extract_first() or \"\"\n if time_:\n return str(datetime.strptime('20' + time_, \"%Y.%m.%d %H:%M:%S\"))\n else:\n return \"9999-01-01 00:00:00\"\n\n def get_tags(self, response) -> list:\n return []\n\n def get_content_media(self, response) -> list:\n content = []\n news_tags = response.xpath('//div[@id=\"divView\"]|'\n '//div[@id=\"divView\"]//img|'\n '//dl[@class=\"viewdata\"]//dd[@class=\"file\"]')\n if news_tags:\n for news_tag in news_tags:\n if news_tag.root.tag == \"img\":\n img_dict = self.parse_img(response, news_tag)\n content.append(img_dict)\n elif news_tag.root.tag in [\"h2\", \"h3\", \"h4\", \"strong\", \"p\", \"li\", \"div\"]:\n text_dict = self.parse_text(news_tag)\n if text_dict:\n content.append(text_dict)\n elif news_tag.root.tag == 'dd':\n file_dict = self.parse_file(response, news_tag)\n if file_dict:\n content.append(file_dict)\n return content\n\n def get_detected_lang(self, response) -> str:\n return \"zh\"\n\n def parse_text(self, news_tag):\n dic = {}\n cons = news_tag.xpath('.//text()').extract() or \"\"\n new_cons = []\n if cons:\n for x in cons:\n if x.strip():\n new_cons.append(x.strip())\n new_cons = ''.join([c for c in new_cons if c != \"\"])\n dic['data'] = new_cons\n dic['type'] = 'text'\n return dic\n\n def parse_img(self, response, news_tag):\n img_url = urljoin(response.url, news_tag.attrib.get('src'))\n dic = {\"type\": \"image\",\n \"name\": news_tag.attrib.get('title'),\n \"md5src\": self.get_md5_value(img_url) + '.jpg',\n \"description\": news_tag.attrib.get('alt'),\n \"src\": urljoin(response.url, news_tag.attrib.get('src'))}\n return dic\n\n def parse_file(self, response, news_tag):\n file_src = urljoin('https://www.army.mil.kr/', news_tag.xpath(\".//a/@href\").extract_first())\n file_dic = {\n \"type\": \"file\",\n \"src\": file_src,\n \"name\": None,\n \"description\": None,\n \"md5src\": self.get_md5_value(file_src) + \".pdf\"\n }\n return file_dic\n\n def parse_media(self, response, news_tag):\n video_src = urljoin(response.url, news_tag.xpath(\"\").extract_first())\n video_dic = {\n \"type\": \"video\",\n \"src\": video_src,\n \"name\": None,\n \"description\": None,\n \"md5src\": self.get_md5_value(video_src) + \".mp4\"\n }\n return video_dic\n\n def get_like_count(self, response) -> int:\n return 0\n\n def get_comment_count(self, response) -> int:\n return 0\n\n def get_forward_count(self, response) -> int:\n return 0\n\n def get_read_count(self, response) -> int:\n return 0\n\n def get_if_repost(self, response) -> bool:\n return False\n\n def get_repost_source(self, response) -> str:\n return \"\"\n","repo_name":"data-source-manager/site_crawl","sub_path":"site_crawl/spiders/parser/kr_armymil.py","file_name":"kr_armymil.py","file_ext":"py","file_size_in_byte":5830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"30130718317","text":"#Quick sort\n \nimport random\ndef quick_sort(nums):\n n = len(nums)\n\n def quick_sort(start,end):\n #print(f\"s = {start}, e = {end}\")\n if end-start < 1:\n return\n pivotpos = random.randint(start, end)\n temp = nums[start]\n nums[start]=nums[pivotpos]\n nums[pivotpos]=temp\n pivot = nums[start]\n #print(f\"pivotpos {pivotpos}, pivot {pivot}\")\n #print(nums)\n #move pivot to so that everything to left of pivot <= pivot\n #and everything to the right of pivot > pivot\n dividing_pointer = start+1\n for to_do_pointer in range(start+1,end+1):\n if nums[to_do_pointer] <= pivot:\n temp = nums[to_do_pointer]\n nums[to_do_pointer] = nums[dividing_pointer]\n nums[dividing_pointer] = temp\n dividing_pointer += 1\n #print(nums)\n nums[start]=nums[dividing_pointer-1]\n nums[dividing_pointer-1] = pivot\n #print(nums)\n #print(\"*****\")\n \n\n \n \n quick_sort(start,dividing_pointer-1)\n quick_sort(dividing_pointer,end)\n quick_sort(0,n-1)\n print(nums)\n \n \n\n \n\nquick_sort([1,3,2,7,0,14])\n\n\n \n\n\n","repo_name":"nivbhaskhar/algorithms_and_datastructures","sub_path":"Algorithms/Sorting/Quick_sort.py","file_name":"Quick_sort.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"33925052031","text":"from django.shortcuts import render, redirect\r\nfrom django.contrib import messages\r\nfrom .forms import UserRegisterForm\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm\r\n# Create your views here.\r\ndef register(request):\r\n if request.method == 'POST': # POST is the data from the form\r\n form = UserRegisterForm(request.POST)\r\n if form.is_valid():\r\n form.save()\r\n username = form.cleaned_data.get('username')\r\n messages.success(request, f'Your account has been created. You can now log in!')\r\n return redirect('login')\r\n else:\r\n # a user creation form with captcha and shit already exists within DJANGO!!!\r\n form = UserRegisterForm() # all it takes is making an instance of it\r\n return render(request, 'users/register.html', {'form':form}) # rendering the html n giving it content/context\r\n\r\n# luckily its super ez to add instances of objects to forms \r\n@login_required\r\ndef profile(request):\r\n if request.method == 'POST': # this basically asks the computer \"are u talking to sqlite rn?\" and gets run after the form is submitted\r\n\r\n # Added after forms/signals addon\r\n u_form = UserUpdateForm(request.POST, instance=request.user) # u jus set it as a variable and it adds it to the model form\r\n p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) # but remember the syntax is that of sqlite\r\n if u_form.is_valid() and p_form.is_valid(): # basically requiring both forms to be valid in order to update\r\n u_form.save()\r\n p_form.save()\r\n messages.success(request, f'Your account has been updated!')\r\n return redirect('profile')\r\n \r\n else:\r\n u_form = UserUpdateForm(instance=request.user) # u jus set it as a variable and it adds it to the model form\r\n p_form = ProfileUpdateForm(instance=request.user.profile) # but remember the syntax is that of sqlite\r\n # context is like the content of the actual website, which is defined as a dictionary, like in the blog/views.py\r\n context = {\r\n 'u_form': u_form,\r\n 'p_form': p_form,\r\n }\r\n\r\n return render(request, 'users/profile.html', context)","repo_name":"DunkJFunk/Y-Django","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"57"} +{"seq_id":"70138341300","text":"from django.db import models\n\n\"\"\"\nClass Tweet\nThis holds information for the Tweets received.\n\"\"\"\nclass Tweet:\n def __init__(self, url, user_name, text, created_at, hashtags, retweet_count=0, favorite_count=0):\n try:\n self.url = url\n except TypeError:\n TweetCreationException(TypeError)\n try:\n self.hashtags = hashtags\n except TypeError:\n TweetCreationException(TypeError)\n try:\n self.user_name = user_name\n except TypeError:\n TweetCreationException(TypeError)\n try:\n self.text = text\n except TypeError:\n TweetCreationException(TypeError)\n try:\n self.created_at = created_at\n except TypeError:\n TweetCreationException(TypeError)\n self.retweet_count = retweet_count\n self.favorite_count = favorite_count\n\n def __str__(self):\n return 'Tweet from User: ' + str(self.user_name) + ' - Said: \\\"' + str(self.text) + '\\\" - Created at: ' + str(self.created_at) + ' - Favorite Count: ' + str(self.favorite_count) + ' - Retweet Count: ' + str(self.retweet_count) + ' - Hashtags: ' + str(self.hashtags)\n\n def __repr__(self):\n return 'Tweet from user_name: ' + str(self.user_name) + '\\ntext: \\\"' + str(self.text) + '\\\"\\ncreated_at: ' + str(self.created_at) + '\\nfavorite_count: ' + str(self.favorite_count) + '\\nretweet_count: ' + str(self.retweet_count) + '\\nhashtags: ' + str(self.hashtags)\n\n def display(self):\n return 'Tweet from User: ' + str(self.user_name) + ' - Said: \\\"' + str(self.text) + '\\\" - Created at: ' + str(self.created_at) + ' - Favorite Count: ' + str(self.favorite_count) + ' - Retweet Count: ' + str(self.retweet_count) + ' - Hashtags: ' + str(self.hashtags)\n\n\ndef TweetCreationException(TypeError):\n print(\"Big error\" + TypeError)\n pass\n\n\"\"\"class defined for database model\"\"\"\n# class Tweets(models.Model):\n# hashtags = models.CharField(max_length=250)\n# retweet_count = models.IntegerField(default=0)\n# favorite_count = models.IntegerField(default=0)\n# user_name = models.CharField(max_length=50)\n# text = models.CharField(max_length=250)\n# created_at = models.DateTimeField('date picked')\n#\n# def __str__(self):\n# return 'Tweet from User: ' + str(self.user_name) + ' - Said: \\\"' + str(self.text) + '\\\" - Created at: ' + str(self.created_at) + ' - Favorite Count: ' + str(self.favorite_count) + ' - Retweet Count: ' + str(self.retweet_count) + ' - Hashtags: ' + str(self.hashtags)\n#\n# def __repr__(self):\n# return 'Tweet from user_name: ' + str(self.user_name) + '\\ntext: \\\"' + str(self.text) + '\\\"\\ncreated_at: ' + str(self.created_at) + '\\nfavorite_count: ' + str(self.favorite_count) + '\\nretweet_count: ' + str(self.retweet_count) + '\\nhashtags: ' + str(self.hashtags)\n#\n# def display(self):\n# return 'Tweet from User: ' + str(self.user_name) + ' - Said: \\\"' + str(self.text) + '\\\" - Created at: ' + str(self.created_at) + ' - Favorite Count: ' + str(self.favorite_count) + ' - Retweet Count: ' + str(self.retweet_count) + ' - Hashtags: ' + str(self.hashtags)\n","repo_name":"carl-phillips/TwitterProject","sub_path":"mysite/polls/tweet.py","file_name":"tweet.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"42520772308","text":"#!/usr/bin/python3\n\nfrom random import randint, shuffle, choice\nfrom PyPDF2 import PdfFileReader, PdfFileWriter\nfrom reportlab.pdfgen import canvas\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.ttfonts import TTFont\n\nSTAT_COLOR = (.0, .4, .7)\nTEXT_COLOR = (.0, .4, .7)\nDEFAULT_FONT = 'FellEnglish-Bold'\npdfmetrics.registerFont(\n TTFont('FellEnglish-Bold', 'data/FellEnglish-Bold.ttf'))\n\nwith open('data/male.txt') as f:\n males = f.read().splitlines()\n\nwith open('data/female.txt') as f:\n females = f.read().splitlines()\n\nwith open('data/surnames.txt') as f:\n surnames = f.read().splitlines()\n\nwith open('data/towns1920.txt') as f:\n towns = f.read().splitlines()\n\n\ndef male_name():\n return choice(males) + ' ' + choice(surnames)\n\n\ndef female_name():\n return choice(females) + ' ' + choice(surnames)\n\n\nclass Character(object):\n\n def d6(self, count=1):\n sum = 0\n for x in range(count):\n sum += randint(1, 6)\n return sum\n\n def improvement_check(self, count):\n for x in range(count):\n improv = randint(1, 100)\n if improv > self.education:\n self.education += randint(1, 10)\n\n if self.education > 99:\n self.education = 99\n\n def deduct(self, point_list):\n shuffle(point_list)\n self.strength -= point_list[0]\n self.constitution -= point_list[1]\n self.dexterity -= point_list[2]\n\n def sex(self, sex):\n self.sex = sex\n\n def name(self, name):\n self.name = name\n\n\nclass Character1920(Character):\n\n def __init__(self):\n\n self.birthplace = choice(towns)\n self.strength = self.d6(3) * 5\n self.size = (self.d6(2) + 6) * 5\n self.dexterity = self.d6(3) * 5\n self.appearance = self.d6(3) * 5\n self.constitution = self.d6(3) * 5\n self.intelligence = (self.d6(2) + 6) * 5\n self.education = (self.d6(2) + 6) * 5\n self.power = self.d6(3) * 5\n self.luck = (self.d6(2) + 6) * 5\n self.age = 15 + randint(0, 64)\n\n if self.age >= 15 and self.age <= 19:\n self.education -= 5\n l1 = randint(1, 5)\n l2 = 5 - l1\n self.strength -= l1\n self.size -= l2\n luck2 = (self.d6(2) + 6) * 5\n if self.luck < luck2:\n self.luck = luck2\n\n elif self.age >= 20 and self.age <= 39:\n self.improvement_check(1)\n\n elif self.age >= 40 and self.age <= 49:\n self.improvement_check(2)\n self.deduct([1, 2, 2])\n self.appearance -= 5\n\n elif self.age >= 50 and self.age <= 59:\n self.improvement_check(3)\n self.deduct([3, 3, 4])\n self.appearance -= 10\n\n elif self.age >= 60 and self.age <= 69:\n self.improvement_check(4)\n self.deduct([6, 7, 7])\n self.appearance -= 15\n\n elif self.age >= 70 and self.age <= 79:\n self.improvement_check(4)\n self.deduct([13, 13, 14])\n self.appearance -= 20\n\n elif self.age >= 80:\n self.improvement_check(4)\n self.deduct([26, 27, 27])\n self.appearance -= 25\n\n self.hitpoints = int((self.size + self.constitution) / 10)\n\n if self.dexterity < self.size and self.strength < self.size:\n self.movement = 7\n\n if self.strength >= self.size or self.dexterity >= self.size:\n self.movement = 8\n\n if self.strength > self.size and self.dexterity > self.size:\n self.movement = 9\n\n if self.age >= 40 and self.age <= 49:\n self.movement -= 1\n elif self.age >= 50 and self.age <= 59:\n self.movement -= 2\n elif self.age >= 60 and self.age <= 69:\n self.movement -= 3\n elif self.age >= 70 and self.age <= 79:\n self.movement -= 4\n elif self.age >= 80:\n self.movement -= 5\n\n\nclass PDF1920(object):\n\n def __init__(self, width=612, height=792):\n self.c = canvas.Canvas('sample.pdf')\n self.c.setPageSize((width, height))\n\n def save_pdf(self):\n self.c.save()\n\n def font_size(self, size):\n self.c.setFontSize(size)\n\n def font_color(self, r, g, b):\n self.c.setFillColorRGB(r, g, b)\n\n def draw_string(self, x, y, text):\n self.c.drawString(x, y, str(text))\n\n def _add_stat(self, x, y, value):\n self.font_color(*STAT_COLOR)\n self.font_size(13)\n self.draw_string(x, y, value)\n one_half = str(int(value / 2))\n one_fifth = str(int(value / 5))\n self.font_size(9)\n self.draw_string(x+26, y+8, one_half)\n self.draw_string(x+26, y-6, one_fifth)\n\n def _add_text(self, x, y, text):\n self.font_size(12)\n self.font_color(*TEXT_COLOR)\n self.draw_string(x, y, str(text))\n\n def name(self, text):\n self._add_text(142, 739, text)\n\n def player(self, text):\n self._add_text(142, 719, text)\n\n def occupation(self, text):\n self._add_text(164, 699, text)\n\n def age(self, text):\n self._add_text(136, 680, text)\n\n def sex(self, text):\n self._add_text(220, 680, text)\n\n def residence(self, text):\n self._add_text(155, 658, text)\n\n def birthplace(self, text):\n self._add_text(155, 639, text)\n\n def str(self, value):\n self._add_stat(332, 710, value)\n\n def dex(self, value):\n self._add_stat(419, 710, value)\n\n def int(self, value):\n self._add_stat(511, 710, value)\n\n def con(self, value):\n self._add_stat(332, 678, value)\n\n def app(self, value):\n self._add_stat(419, 678, value)\n\n def pow(self, value):\n self._add_stat(511, 678, value)\n\n def siz(self, value):\n self._add_stat(332, 647, value)\n\n def edu(self, value):\n self._add_stat(419, 647, value)\n\n def mov(self, value):\n self.font_color(*STAT_COLOR)\n self.font_size(13)\n self.draw_string(511, 647, value)\n\n def hp(self, value):\n self.font_color(*STAT_COLOR)\n self.font_size(13)\n self.draw_string(100, 582, value)\n\n def luck(self, value):\n self.font_color(*STAT_COLOR)\n self.font_size(13)\n self.draw_string(100, 510, value)\n\n def sanity(self, value):\n self.font_color(*STAT_COLOR)\n self.font_size(13)\n self.draw_string(480, 582, value)\n\n def magic(self, value):\n self.font_color(*STAT_COLOR)\n self.font_size(13)\n self.draw_string(480, 510, value)\n\n def add_character(self, char):\n\n self.c.drawImage('data/1920blank.png', 0, 0, 612, 792)\n self.c.setFont(DEFAULT_FONT, 12)\n self.name(char.name)\n self.age(char.age)\n self.sex(char.sex)\n #o.player('Henry Armitage')\n # o.occupation('Librarian')\n #o.residence('Arkham, MA')\n self.birthplace(char.birthplace)\n self.str(char.strength)\n self.dex(char.dexterity)\n self.int(char.intelligence)\n self.con(char.constitution)\n self.app(char.appearance)\n self.pow(char.power)\n self.sanity(char.power)\n self.magic(int(char.power / 5))\n self.siz(char.size)\n self.edu(char.education)\n self.mov(char.movement)\n self.hp(char.hitpoints)\n self.luck(char.luck)\n self.c.showPage()\n\n\np = PDF1920()\n\nfor x in range(200):\n\n c = Character1920()\n c.sex('Male')\n c.name(male_name())\n p.add_character(c)\n\n c = Character1920()\n c.sex('Female')\n c.name(female_name())\n p.add_character(c)\n\np.save_pdf()\n","repo_name":"jimstorch/1920Gen","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":7615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"23879766333","text":"'''\nto estimate the memory needed for a model\n'''\nimport os\nimport sys\nsys.path.append(\"../\")\nimport numpy as np\nfrom utils.loss import loss_qu, loss_disorientation\nfrom keras.models import Sequential, load_model\nimport h5py\n\n# assign gpu to use\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\ndef get_model_memory_usage(batch_size, model):\n import numpy as np\n from keras import backend as K\n\n shapes_mem_count = 0\n for l in model.layers:\n single_layer_mem = 1\n for s in l.output_shape:\n if s is None:\n continue\n single_layer_mem *= s\n shapes_mem_count += single_layer_mem\n\n trainable_count = np.sum([K.count_params(p) for p in set(model.trainable_weights)])\n non_trainable_count = np.sum([K.count_params(p) for p in set(model.non_trainable_weights)])\n\n number_size = 4.0\n if K.floatx() == 'float16':\n number_size = 2.0\n if K.floatx() == 'float64':\n number_size = 8.0\n\n total_memory = number_size*(batch_size*shapes_mem_count + trainable_count + non_trainable_count)\n gbytes = np.round(total_memory / (1024.0 ** 3), 3)\n return gbytes\n\nif __name__ == '__main__':\n h5 = h5py.File('dir/to/EBSD_CNN_model.h5','r')\n model = load_model(h5, custom_objects={'loss_qu': loss_qu, 'loss_disorientation': loss_disorientation})\n print(get_model_memory_usage(16, model))","repo_name":"Darkhunter9/EBSD_CNN_Public","sub_path":"utils/modelsize.py","file_name":"modelsize.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"17174933188","text":"# coding:utf-8\r\nimport pyrealsense2 as rs\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport glob\r\nimport os\r\nimport cv2\r\nimport shutil\r\nimport time\r\nimport seaborn as sns\r\nimport sys\r\n\r\nwidth = 1280\r\nheight = 720\r\nframerate = 30\r\n\r\ntarget_dir = sys.argv[1]\r\nsaved_dir = sys.argv[2]\r\n\r\ndef Save_data(filename):\r\n target_file_saved_dir = '{}{}/'.format(saved_dir, filename.split(\"/\")[-1].split(\".\")[0])\r\n if(os.path.isdir(target_file_saved_dir) == True):\r\n shutil.rmtree(target_file_saved_dir)\r\n os.mkdir(target_file_saved_dir)\r\n # Configure depth and color streams\r\n config = rs.config()\r\n config.enable_device_from_file(filename, repeat_playback=False)\r\n config.enable_stream(rs.stream.infrared, 1, width, height, rs.format.y8, framerate)\r\n config.enable_stream(rs.stream.infrared, 2, width, height, rs.format.y8, framerate)\r\n config.enable_stream(rs.stream.depth, width, height, rs.format.z16, framerate)\r\n config.enable_stream(rs.stream.color, width, height, rs.format.bgr8, framerate)\r\n\r\n count = 0\r\n # Start streaming\r\n pipeline = rs.pipeline()\r\n profile = pipeline.start(config)\r\n\r\n start = time.time()\r\n try:\r\n while True:\r\n # Wait for a coherent pair of frames: depth and color\r\n flag,frames = pipeline.try_wait_for_frames()\r\n if flag == False: break\r\n depth_frame = frames.get_depth_frame()\r\n color_frame = frames.get_color_frame()\r\n ir1_frame = frames.get_infrared_frame(1)\r\n ir2_frame = frames.get_infrared_frame(2)\r\n if not depth_frame or not color_frame or not ir1_frame or not ir2_frame:\r\n continue\r\n\r\n depth_map = np.zeros((height,width))\r\n for w in range(width):\r\n for h in range(height):\r\n dist = depth_frame.get_distance(w,h)\r\n depth_map[h,w] = dist\r\n np.savetxt('{}Depth_map_{}.csv'.format(target_file_saved_dir,count), depth_map, delimiter=',', fmt='%.3f')\r\n fig, ax = plt.subplots()\r\n ax = sns.heatmap(depth_map)\r\n ax.set_aspect('equal')\r\n fig.savefig('{}Depth_map_color_{}.png'.format(target_file_saved_dir,count))\r\n\r\n # Convert images to numpy arrays\r\n depth_image = np.asanyarray(depth_frame.get_data())\r\n color_image = np.asanyarray(color_frame.get_data())\r\n ir1_image = np.asanyarray(ir1_frame.get_data())\r\n ir2_image = np.asanyarray(ir2_frame.get_data())\r\n \r\n depth_color_image = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.08), cv2.COLORMAP_JET) \r\n \r\n # Show images\r\n cv2.imwrite(\"{}Depth_{}.png\".format(target_file_saved_dir,count), depth_image)\r\n cv2.imwrite(\"{}Color_{}.png\".format(target_file_saved_dir,count), color_image)\r\n cv2.imwrite(\"{}IR_Left_{}.png\".format(target_file_saved_dir,count), ir1_image)\r\n cv2.imwrite(\"{}IR_Right_{}.png\".format(target_file_saved_dir,count), ir2_image)\r\n cv2.imwrite(\"{}Depth_Color_{}.png\".format(target_file_saved_dir,count), depth_color_image)\r\n count += 1\r\n finally:\r\n # Stop streaming\r\n pipeline.stop()\r\n\r\nfilenames = glob.glob('{}*.bag'.format(target_dir))\r\nfor filename in filenames:\r\n filename = filename.replace(\"\\\\\",\"/\")\r\n print(filename)\r\n Save_data(filename)","repo_name":"yu10kami/rec-bagfile-realsense","sub_path":"Restoration_bagfile.py","file_name":"Restoration_bagfile.py","file_ext":"py","file_size_in_byte":3452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"7043099304","text":"# 백준 1743 음식물 피하기\n\nimport sys\nfrom collections import deque\ninput = sys.stdin.readline\nn, m, k = map(int, input().split())\narr, check = [[0]*m for _ in range(n)], [[0]*m for _ in range(n)]\nfor _ in range(k):\n y, x = map(int, input().split())\n arr[y-1][x-1] = 1\nans = 0\ndef abc(y, x):\n global ans\n q = deque()\n q.append([y, x])\n rst = 1\n while q:\n nowy, nowx = q.popleft()\n directy = [0, 0, -1, 1]\n directx = [-1, 1, 0, 0]\n for z in range(4):\n dy = nowy + directy[z]\n dx = nowx + directx[z]\n if dy < 0 or dx < 0 or dy >= n or dx >= m:\n continue\n if arr[dy][dx] == 1 and check[dy][dx] == 0:\n check[dy][dx] = 1\n rst += 1\n q.append([dy, dx])\n if rst > ans:\n ans = rst\nfor i in range(n):\n for j in range(m):\n if arr[i][j] == 1 and check[i][j] == 0:\n check[i][j] = 1\n abc(i, j)\nprint(ans)","repo_name":"yeolsim2hajo/Team_hard","sub_path":"hanpark/solved ac/tony9402/tony9402_0723_1743.py","file_name":"tony9402_0723_1743.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"57"} +{"seq_id":"72629929139","text":"# Input: [1,2,4,7,7,5]\n# Output: Second Smallest : 2\n# \tSecond Largest : 5\n# Explanation: The elements are as follows 1,2,3,5,7,7 and hence second largest of these is 5 and second smallest is 2\ndef secondElement(arr):\n mini = 999999\n maxi = -999999\n secMini = 0\n secMax = 0\n for x in arr:\n if x > maxi:\n secMax = maxi\n maxi = x\n elif x > secMax and x != maxi:\n secMax = x\n if x < mini:\n secMini = mini\n mini = x\n elif x < secMini and x != mini:\n secMini = x\n print('secMax', secMax, 'max', maxi)\n print('secMini', secMini, 'mini', mini)\n\n\nx = int(input('Enter number '))\narr = [int(x) for x in input('Enter arr ').split()]\n\nsecondElement(arr)\n","repo_name":"Tapendrakmr/SDE_SHEET_CHALLENGE","sub_path":"3.array/3.1easy/secondLargest.py","file_name":"secondLargest.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"21524092847","text":"\"\"\"\nnetpyne_model_interpreter.py\nModel interpreter for NWB. This class creates a geppetto type\n\"\"\"\nimport importlib\nimport json\nimport uuid\nfrom os import listdir, path\n\nimport holoviews as hv\nimport seaborn as sns\n\nfrom nwb_explorer.nwb_model_interpreter.nwb_reader import NWBReader\n\nhv.extension('bokeh')\nsns.set_style('whitegrid')\n\n\nclass PlotManager: # pytest: no cover\n holoviews_plots_path = \"webapp/holoviews_plots/\"\n public_plots_path = \"nwb_explorer/public/plots\"\n public_plots_dict = {}\n\n def __init__(self, geppetto_model=None):\n self.geppetto_model = geppetto_model\n self.plots = self._get_public_plots()\n\n # def get_nearest_frame(self, timepoint, timestamps):\n # return None # int(np.nanargmin(abs(timestamps - timepoint)))\n #\n # def get_trace_around_timepoint(self, timepoint, trace, timestamps, window=1, frame_rate=30):\n # frame_for_timepoint = self.get_nearest_frame(timepoint, timestamps)\n # lower_frame = frame_for_timepoint - (window * frame_rate)\n # upper_frame = frame_for_timepoint + (window * frame_rate)\n # trace = trace[lower_frame:upper_frame]\n # timepoints = timestamps[lower_frame:upper_frame]\n # return trace, timepoints\n #\n # def get_xticks_xticklabels(self, trace, interval_sec=1):\n # interval_frames = interval_sec * 30\n # n_frames = len(trace)\n # n_sec = n_frames / 30\n # xticks = np.arange(0, n_frames + 1, interval_frames)\n # xticklabels = np.arange(0, n_sec + 0.1, interval_sec)\n # xticklabels = xticklabels - n_sec / 2\n # return xticks, xticklabels\n #\n # def plot_mean_trace(self, traces, label=None, color='k', interval_sec=1, ax=None):\n # if ax is None:\n # fig, ax = plt.subplots()\n # if len(traces) > 0:\n # trace = np.mean(traces, axis=0)\n # times = np.arange(0, len(trace), 1)\n # sem = (traces.std()) / np.sqrt(float(len(traces)))\n # ax.plot(trace, label=label, linewidth=3, color=color)\n # ax.fill_between(times, trace + sem, trace - sem, alpha=0.5, color=color)\n #\n # xticks, xticklabels = self.get_xticks_xticklabels(trace, interval_sec)\n # ax.set_xticks([int(x) for x in xticks])\n # ax.set_xticklabels([int(x) for x in xticklabels])\n # ax.set_xlabel('time after change (s)')\n # ax.set_ylabel('dF/F')\n # sns.despine(ax=ax)\n # return ax\n #\n # def plot_mean(self):\n # cell = 17\n # cell_trace = dataset.dff_traces[cell]\n # timestamps = dataset.timestamps_2p\n # flashes = dataset.flashes[:-1] # avoid issues with truncated last flash\n #\n # fig, ax = plt.subplots()\n # colors = sns.color_palette('hls', 8)\n # for i, image_name in enumerate(np.sort(flashes.image_name.unique())):\n # flash_times = flashes[flashes.image_name == image_name].master_time\n #\n # traces = []\n # window = 1 # seconds around flash time to take trace snippet\n # for flash_time in flash_times:\n # trace, timepoints = self.get_trace_around_timepoint(flash_time, cell_trace, timestamps, window)\n # traces.append(trace)\n # traces = np.asarray(traces)\n #\n # self.plot_mean_trace(traces, label=image_name, color=colors[i], interval_sec=1, ax=ax)\n # ax.set_title('roi ' + str(cell))\n #\n # plt.legend(bbox_to_anchor=(1., 1))\n # return plt\n\n def plot(self, plot_id, nwbfile_path):\n \"\"\"Given a valid plot_id dynamically imports the module and calls the method responsible for plotting \"\"\"\n try:\n nwb_utils = NWBReader(nwbfile_path)\n except ValueError:\n raise ValueError(\"File not found\")\n try:\n plot_data = self.public_plots_dict[plot_id]\n except KeyError:\n raise KeyError(\"Invalid plot id\")\n plot_path = plot_data['path']\n try:\n imported_module = importlib.import_module(plot_path)\n method_to_call = getattr(imported_module, 'plot')\n plot = method_to_call(nwb_utils.get_nwbfile())\n except ImportError:\n raise ImportError\n\n # TODO we should return the file content here, not the url at some point\n data = self.get_url(plot, self.holoviews_plots_path)\n return json.dumps(data)\n\n def get_available_plots(self, nwbfile_path):\n \"\"\"Given a nwbfile looks under public_plots_path to verify which plots can be draw \"\"\"\n try:\n nwb_utils = NWBReader(nwbfile_path)\n except ValueError:\n raise ValueError(\"Invalid nwbfile\")\n available_plots = [{'name': plot['name'], 'id': plot['id']} for plot in self.plots if\n nwb_utils.has_all_requirements(plot[\"requirements\"])]\n return json.dumps(available_plots)\n\n def _get_public_plots(\n self):\n \"\"\"Looks under public_plots_path and expects to find folders containing each one\n 2 files with the same base name as the first; one a json file containing name, id and requirements as fields\n and other a python module where the method's name responsible to return the plot should be the same\n as the id in the json file \"\"\"\n plots = []\n for folder in listdir(\n self.public_plots_path):\n json_filepath = self.public_plots_path + \"/\" + folder + \"/\" + folder + \".json\"\n python_filepath = self.public_plots_path.replace('/', '.') + \".\" + folder + \".\" + folder\n if path.isfile(json_filepath):\n with open(json_filepath) as file:\n data = json.load(file)\n self.public_plots_dict[data[\"id\"]] = {'path': python_filepath, 'requirements': data[\"requirements\"]}\n plots.append(data)\n return plots\n\n @staticmethod\n def get_url(obj, path_):\n \"\"\"Saves obj in path and returns an object with the url.\"\"\"\n uuid_plot = path_ + str(uuid.uuid4())\n try:\n hv.renderer('bokeh').save(obj, uuid_plot)\n plot_path = '/geppetto/{}.html'.format(uuid_plot.split('webapp/')[1])\n return {'url': plot_path}\n except Exception as e:\n e.args = [\"Error saving plot\"] + list(e.args)\n raise e\n","repo_name":"MetaCell/nwb-explorer","sub_path":"nwb_explorer/plots_manager.py","file_name":"plots_manager.py","file_ext":"py","file_size_in_byte":6393,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"57"} +{"seq_id":"74898303856","text":"import csv\n\nfrom src import constants\nfrom src.BNXFile.BNXFileReader import BNXFileReader\nfrom src.Exception.EndOfBNXFileException import EndOfBNXFileException\nfrom src.Filesystem.BNXFilesystem import BNXFilesystem\nfrom src.Filesystem.ImageFilesystem import ImageFilesystem\nfrom src.ImageAnalysis.FluorescentMarkImageAnalyzer import FluorescentMarkImageAnalyzer\nimport numpy as np\n\n\ndef getCenterOfMass(values, surroundingsSize=1):\n vals = np.array(values)\n center = (vals * np.mgrid[0:vals.shape[0], 0:vals.shape[1]]).sum(1).sum(1) / vals.sum()\n nucleotidePosition = [\n constants.PIXEL_TO_NUCLEOTIDE_RATIO * point - constants.PIXEL_TO_NUCLEOTIDE_RATIO * (surroundingsSize - 0.5)\n for point in center\n ]\n return nucleotidePosition\n\n\ndef getCountOfNotCentered(nucleotidePositions):\n count = 0\n for position in nucleotidePositions:\n if position[0] > constants.PIXEL_TO_NUCLEOTIDE_RATIO or \\\n position[1] > constants.PIXEL_TO_NUCLEOTIDE_RATIO or \\\n position[0] < 0 or \\\n position[1] < 0:\n count += 1\n\n return count\n\ndef getPositionsForScan(scan):\n fileReader = BNXFileReader(BNXFilesystem.getBNXByScan(scan))\n fileReader.open()\n filename = ''\n results = ['calculatedY', 'expectedY', 'calculatedX', 'shape']\n\n c = 0\n while True:\n try:\n molecule = fileReader.getNextMolecule(\n False)\n except EndOfBNXFileException:\n break\n c += 1\n if c % 1000 != 0:\n continue\n print(c)\n\n currentFilename = ImageFilesystem.getImageByScanAndRunAndColumn(scan, molecule.runId, molecule.column)\n if currentFilename != filename:\n filename = currentFilename\n ia = FluorescentMarkImageAnalyzer(filename)\n\n for mark in molecule.fluorescentMarks:\n surroundingValues = ia.getSurroundingValues(mark.posX, mark.posY, 1, shape='c')\n centerOfMass = getCenterOfMass(surroundingValues, 1)\n results.append([centerOfMass[0], mark.nucleotideDistance, centerOfMass[1], 'c'])\n surroundingValues = ia.getSurroundingValues(mark.posX, mark.posY, 1, shape='s')\n centerOfMass = getCenterOfMass(surroundingValues, 1)\n results.append([centerOfMass[0], mark.nucleotideDistance, centerOfMass[1], 's'])\n with open('results/centerOfMass_full_scan_1.csv', 'a') as file:\n wr = csv.writer(file)\n for row in results:\n wr.writerow(row)\n return results\n\n\nif __name__ == '__main__':\n getPositionsForScan(1)\n print(getCenterOfMass([[0,0,0],[0,0,1],[0,0,0]]))\n # porovnat maxima molekul s ch1 souborem\n # udelat na x symetrickou masku a udelat z toho filtr ktery se pak da aplikovat na najiti posunu\n","repo_name":"bchamradova/BNXproject","sub_path":"src/Experiments/NucleotideMarkPosition/nucleotidePositionAnalyzer.py","file_name":"nucleotidePositionAnalyzer.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"29814056902","text":"#!/usr/bin/env python3\n\nimport multiprocessing as mp\n\n\ndef createSNPDict(snplist):\n\t'''\n\tCreates a set with all SNPs in the form tuple(CHR, POS, ALT),\n\te.g. tuple(chr18, 3000528, T), given a list with SNPs formatted as in \"the file\".\n\t'''\n\n\tsnpdict = {}\n\tfor elem in snplist:\n\t\tl = elem.split('\\t')\n\t\t# CHR POS ALT\n\t\tsnpdict[tuple((l[0], l[1], l[4]))] = elem\n\n\treturn snpdict\n\n\ndef getSNPs(workpackage):\n\t'''\n\tReturns a set with SNPs that are in sbjct but not in ctrl. sbjct and ctrl\n\tmust be file names.\n\t'''\n\n\tctrllist, sbjctlist = workpackage\n\n\tctrldict = createSNPDict(ctrllist)\n\tsbjctdict = createSNPDict(sbjctlist)\n\n\t# This returns dict keys that are in sbjctdict but not in ctrldict\n\tsnps = set(sbjctdict).difference(set(ctrldict))\n\n\treturn [sbjctdict[snp] for snp in snps]\n\n\ndef readSNPfile(fname):\n\t'''\n\tReads a SNP file, discards the commented lines and returns all other lines\n\tas a list (suitable for createSNPSet()).\n\t'''\n\n\tsnplists = []\n\tcurrent = None\n\twith open(fname, 'r') as f:\n\t\tfor line in f:\n\t\t\tif line.startswith('#'):\n\t\t\t\tcontinue\n\t\t\tif line[:5] != current:\n\t\t\t\tsnplists.append([])\n\t\t\t\tcurrent = line[:5]\n\t\t\tsnplists[-1].append(line)\n\n\treturn snplists\n\n\ndef prepareParallel(ctrlfile, sbjctfile):\n\tctrllists = readSNPfile(ctrlfile)\n\tsbjctlists = readSNPfile(sbjctfile)\n\n\tif len(ctrllists) != len(sbjctlists):\n\t\traise ValueError('Length of the two lists are not the same ({} vs {})'.format(len(ctrllists), len(sbjctlists)))\n\n\treturn zip(ctrllists, sbjctlists)\n\n\nif __name__ == '__main__':\n\tctrlfile = 'MMR_664_control.raw.snps_filtered.vcf'\n\tsbjctfile = 'MMR_1370_subject.raw.snps_filtered.vcf'\n\n\tworkpackages = prepareParallel(ctrlfile, sbjctfile)\n\n\tpool = mp.Pool(4)\n\n\tresult = pool.map(getSNPs, workpackages)\n\n\twith open('result.vcf', 'w') as out:\n\t\ttotalLength = 0\n\t\tfor chromosome in result:\n\t\t\ttotalLength += len(chromosome)\n\t\t\tfor snp in chromosome:\n\t\t\t\tout.write(snp)\n\n\tprint('number of SNPs found:', totalLength)\n\n\n","repo_name":"mathiasbockwoldt/inf9380exam","sub_path":"python-part/snp_finder_parallel.py","file_name":"snp_finder_parallel.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"16161004875","text":"# require python3\n# -*- coding: utf-8 -*-\n\nfrom automato.core import test\nfrom automato.core import system\n\n# TODO test presence_connection_after_disconnect > 0\n\ndef test_init():\n test.add_node_config({\n \"entries\": [\n { \n \"module\": \"presence\",\n \"config\": {\n \"presence_home_location\": { \"latitude\": 45.123, \"longitude\": 12.123, \"radius\": 500 },\n \"presence_home_regions\": [ \"home\", \"Region\" ],\n \"presence_location_session_duration\": 30,\n \"presence_connection_after_disconnect\": 0,\n },\n \"publish\": {\n './presence': {\n 'run_interval': 2,\n }\n },\n \"events_listen\": [\".presence-out\", \".presence-in\", \"*.clock\"],\n },\n {\n \"module\": \"net_sniffer_scapy\",\n \"config\": {\n \"momentary_flood_time\": 30,\n \"connection_time\": 30,\n }\n },\n { \"module\": \"location_owntracks\" },\n\n {\n \"caption\": \"Device1\",\n \"device\": \"device1\",\n \"mac_address\": \"01:02:03:04:05\",\n \"owntracks_id\": \"xxx\",\n \"presence_detect\": \"mary\",\n },\n {\n \"caption\": \"Device2\",\n \"device\": \"device2\",\n \"mac_address\": \"0A:0B:0C:0D:0E\",\n \"presence_detect\": \"john\",\n },\n ]\n }) \n\ndef test_run(entries):\n #print(\"DIST: \" + str(entries['presence@TEST'].module.locations_distance((45.123,12.123), (45.127,12.123))))\n \n # Mary enters via device\n t1 = system.time()\n test.assertx('t1', \n assertSubscribeSomePayload = {\n 'home/presence/in': {'name': 'mary', 'before_someone_inside': False, 'time': ('d', t1)},\n 'home/presence': {'occupants': {'mary': {\"firstseen\": ('d', t1), \"lastseen\": ('d', t1), \"methods\": [\"connected/device1@TEST\"]}}, \"time\": ('d', t1)}, },\n assertNotification = ['info', 'mary has entered', 'home/presence/in' ],\n # ['debug', ('re', 'People detected:.*mary.*'), 'home/presence' ],\n assertEventsTopic = 'home/presence/in', assertEvents = {\n 'presence-in': {'who': 'mary', 'before_someone_inside': False, 'region': 'home' }, \n 'clock': {'value': ('d', t1)}},\n assertExports = {'presence_someone_inside': True, 'presence_no_one_inside': False},\n wait = False)\n entries['net_sniffer_scapy@TEST'].module.sniff_callback(entries['net_sniffer_scapy@TEST'], '01:02:03:04:05')\n test.waitRunning()\n\n # ... via location region\n t2 = system.time()\n test.assertPublish('t2a', 'owntracks/device/xxx', '{\"_type\":\"location\",\"acc\":78,\"alt\":0,\"batt\":86,\"conn\":\"w\",\"inregions\":[\"Region\"],\"lat\":35.123,\"lon\":22.123,\"tid\":\"ic\",\"tst\":1546871086,\"vac\":0,\"vel\":0}', \n assertEvents = {\n 'location': {'latitude': 35.123, 'longitude': 22.123, 'altitude': 0, 'radius': 78, 'radius:unit': 'm', 'regions': ['Region'], 'source': 'owntracks'},\n 'clock': {'value': 1546871086}\n },\n assertSubscribeNotReceive = ['home/presence/in'])\n\n test.assertx('t2b', \n assertSubscribeSomePayload = {\n 'home/presence': {'occupants': {'mary': {\"firstseen\": ('d', t1), \"lastseen\": ('d', t2), \"methods\": [\"connected/device1@TEST\", \"location_region/owntracks\"]}}, \"time\": ('d', system.time())}, },\n assertNotification = [ 'debug', ('re', 'People detected:.*mary.*'), 'home/presence' ],\n assertSubscribeNotReceive = ['home/presence/in'],\n wait = False)\n entries['presence@TEST'].module.publish(entries['presence@TEST'], 'home/presence', entries['presence@TEST'].definition['publish']['home/presence'])\n test.waitRunning()\n \n # ... via location position\n t3 = system.time()\n test.assertPublish('t3a', 'owntracks/device/xxx', '{\"_type\":\"location\",\"acc\":78,\"alt\":0,\"batt\":86,\"conn\":\"w\",\"inregions\":[\"Out\"],\"lat\":45.127,\"lon\":12.123,\"tid\":\"ic\",\"tst\":1546871086,\"vac\":0,\"vel\":0}', \n assertSubscribeNotReceive = ['home/presence/in'])\n\n test.assertx('t3b', \n assertSubscribeSomePayload = {\n 'home/presence': {'occupants': {'mary': {\"firstseen\": ('d', t1), \"lastseen\": ('d', t3), \"methods\": [\"connected/device1@TEST\", \"location_region/owntracks\", \"location/owntracks\"]}}, \"time\": ('d', system.time())}, },\n assertNotification = [ 'debug', ('re', 'People detected:.*mary.*'), 'home/presence' ],\n assertSubscribeNotReceive = ['home/presence/in'],\n wait = False)\n entries['presence@TEST'].module.publish(entries['presence@TEST'], 'home/presence', entries['presence@TEST'].definition['publish']['home/presence'])\n test.waitRunning()\n \n # Also John enters via device\n t4 = system.time()\n test.assertx('t4', \n assertSubscribeSomePayload = {\n 'home/presence/in': {'name': 'john', 'before_someone_inside': True, 'time': ('d', t4)},\n 'home/presence': {'occupants': {'mary': {\"firstseen\": ('d', t1), \"lastseen\": ('d', t3), \"methods\": [\"connected/device1@TEST\", \"location_region/owntracks\", \"location/owntracks\"]}, \"john\": {\"firstseen\": ('d', t4), \"lastseen\": ('d', t4), \"methods\": [\"connected/device2@TEST\"]}}, \"time\": ('d', t4)}, },\n assertNotification = [ 'info', 'john has entered', 'home/presence/in' ],\n # 'debug', ('re', 'People detected:.*mary.*john.*'), 'home/presence'\n assertEventsTopic = 'home/presence/in', assertEvents = {\n 'presence-in': {'who': 'john', 'before_someone_inside': True, 'region': 'home' }, \n 'clock': {'value': ('d', t4)}},\n assertExports = {'presence_someone_inside': True, 'presence_no_one_inside': False},\n wait = False)\n entries['net_sniffer_scapy@TEST'].module.sniff_callback(entries['net_sniffer_scapy@TEST'], '0A:0B:0C:0D:0E')\n test.waitRunning()\n \n # Mary should exit if we wait connection_time/presence_location_session_duration\n system.time_offset(40)\n t5 = system.time()\n test.assertx('t5', \n assertSubscribeSomePayload = {\n 'home/presence/out': {'name': 'mary', 'after_someone_inside': True, 'time': ('d', t5)},\n 'home/presence': {'occupants': {\"john\": {\"firstseen\": ('d', t4), \"lastseen\": ('d', t4), \"methods\": [\"connected/device2@TEST\"]}}, \"time\": ('d', t5)}, },\n assertNotification = [ 'info', 'mary has gone away', 'home/presence/out' ],\n # 'debug', ('re', 'People detected:.*john.*'), 'home/presence'\n assertEventsTopic = 'home/presence/out', assertEvents = {\n 'presence-out': {'who': 'mary', 'after_someone_inside': True, 'region': 'home' }, \n 'clock': {'value': ('d', t5)}},\n wait = False)\n entries['net_sniffer_scapy@TEST'].module.sniff_callback(entries['net_sniffer_scapy@TEST'], '0A:0B:0C:0D:0E') # John should stay there\n entries['net_sniffer_scapy@TEST'].module.status_check(entries['net_sniffer_scapy@TEST'])\n system.sleep(1) # To ensure the execution of events callbacks\n entries['presence@TEST'].module.publish(entries['presence@TEST'], 'home/presence', entries['presence@TEST'].definition['publish']['home/presence'])\n test.waitRunning()\n\n # And now its time for John to exit too\n system.time_offset(40)\n t6 = system.time()\n test.assertx('t6', \n assertSubscribeSomePayload = {\n 'home/presence/out': {'name': 'john', 'after_someone_inside': False, 'time': ('d', t6)},\n 'home/presence': {'occupants': {}, \"time\": ('d', t6)}, },\n assertNotification = [ 'info', 'john has gone away', 'home/presence/out' ],\n # 'debug', 'No people detected', 'home/presence'\n assertEventsTopic = 'home/presence/out', assertEvents = {\n 'presence-out': {'who': 'john', 'after_someone_inside': False, 'region': 'home' }, \n 'clock': {'value': ('d', t6)}},\n assertExports = {'presence_someone_inside': False, 'presence_no_one_inside': True},\n wait = False)\n entries['net_sniffer_scapy@TEST'].module.status_check(entries['net_sniffer_scapy@TEST'])\n system.sleep(1) # To ensure the execution of events callbacks\n entries['presence@TEST'].module.publish(entries['presence@TEST'], 'home/presence', entries['presence@TEST'].definition['publish']['home/presence'])\n test.waitRunning()\n","repo_name":"eric-void/automato-node-py","sub_path":"src/automato/modules/presence_test.py","file_name":"presence_test.py","file_ext":"py","file_size_in_byte":7810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"35750765852","text":"from numpy import *\n\n\n\ndef loadDataset():#设置样本集和分类 0好1坏(啊这\n eglist = [['你','真','是','一个','好人','啊','宝'],\n ['我的','宝','长得','真的','好像','你','母猪','啊'],\n ['我','对','他','没有','坏','的','感觉'],\n ['你','好','普信','我','觉得','老','母猪','没有','你','一半','肥'],\n ['你','好','坏','我','好','喜欢','你','这种','普信'],\n ['我','是','迪士尼','在逃','普信','绝绝子','暴风吸入','yyds']\n ]\n classvec = [0,1,0,1,0,1]\n return eglist,classvec\n\ndef createVocallist(dataset):#整体返回一个字列表 自动去重\n vocalset = set([])\n for doc in dataset:\n vocalset = vocalset | set(doc)\n return list(vocalset)\n\ndef setofwords2vec(vocallist, inputset):#判断字典文档里每一个字 在输入文档中是否出现\n returnvec = [0] * len(vocallist)\n for word in inputset:\n if word in vocallist:\n returnvec[vocallist.index(word)] = 1\n else: print(\"%s 找不到啊\" %word)\n return returnvec\n\ndef trainNB0(trainmatrix, traincategory): #通过计算条件概率\n numtraindocs = len(trainmatrix)\n numwords = len(trainmatrix[0])\n p_class = sum(traincategory)/float(numtraindocs)\n p0denom = 0.0\n p1denom = 0.0\n p0 = zeros(numwords)\n p1 = zeros(numwords)\n # 防止其中一个概率为0\n # p0denom = 2.0\n # p1denom = 2.0\n # p0 = ones(numwords)\n # p1 = ones(numwords)\n\n for i in range(numtraindocs):\n if traincategory[i] == 1:\n p1 += trainmatrix[i]\n p1denom += sum(trainmatrix[i])\n\n else:\n p0 += trainmatrix[i]\n p0denom += sum(trainmatrix[i])\n p0vec = p0 / p0denom\n p1vec = p1 / p1denom\n # 防止太多很小的数向下溢出\n # p0vec = log(p0 / p0denom)\n # p1vec = log(p1 / p1denom)\n return p0vec,p1vec,p_class\n\ndef classifyNB(vec2classify, p0vec, p1vec, pclass1):#条件概率分类\n p1 = sum(vec2classify * p1vec) + log(pclass1)\n p0 = sum(vec2classify * p0vec) + log(1.0 - pclass1)\n if p1>p0:\n return 1\n else: return 0\n\ndef testNB():\n post,classes=loadDataset()\n # print(post)\n vocallist = createVocallist(post)\n # print(vocallist)\n # retrieve1 = setofwords2vec(vocallist, post[0])\n # print(retrieve1)\n trainmat = []\n for doc in post:\n trainmat.append(setofwords2vec(vocallist, doc))\n # print(trainmat)\n p0v, p1v, p_sum = trainNB0(trainmat, classes)\n # print(p0v)\n # print(p1v)\n test = ['yyds', '绝绝子', '母猪']\n this = array(setofwords2vec(vocallist, test))\n print (test ,\"属于:\", classifyNB(this,p0v,p1v,p_sum))\n\nif __name__ == '__main__':\n testNB()","repo_name":"girlsdontget341/machine_learning","sub_path":"book/Naive_BayesianModel/bayes.py","file_name":"bayes.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"72808838579","text":"##\n# Change radius of white ball centered on canvas in response to up and down keypresses.\n# pygame\n#\nfrom time import sleep\nimport pygame as pg\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nRADIUS_INCREMENT = 1\nradius = 20\n\n# Initialize pygame\npg.init()\n\n# Create window\nscreen = pg.display.set_mode((500, 500))\n\nwhile True:\n # To get rid of the previously drawn circle you either have to draw over it (screen.fill) or\n # you need to create a new screen object each time by putting the screen assignment in the\n # while loop.\n screen.fill(BLACK)\n pg.draw.circle(screen, WHITE, (250, 250), radius)\n pg.display.update()\n # Use key.get_pressed() for key holding behavior\n keys = pg.key.get_pressed()\n if keys[pg.K_DOWN] and radius > RADIUS_INCREMENT:\n radius -= RADIUS_INCREMENT\n elif keys[pg.K_UP]:\n radius += RADIUS_INCREMENT\n\n # Pass/process any other events\n for event in pg.event.get():\n if event.type == pg.QUIT:\n pg.quit()\n quit()\n else:\n pass\n\n # Run loop at 60 FPS\n sleep(1 / 60)\n","repo_name":"nmoore32/coursera-fundamentals-of-computing-work","sub_path":"1 An Introduction to Interactive Programming in Python/Week 4/2 Keyboard Control/exercise-2a.py","file_name":"exercise-2a.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"22076406404","text":"# -*- coding: utf-8 -*-\n\"\"\"Detects text in the file.\"\"\"\nfrom google.cloud import vision\nimport io\nimport os\n\nos.environ.setdefault('GOOGLE_APPLICATION_CREDENTIALS', '/home/ec2-user/capstone/capstoneProject/visionAPI/My_First_Project-51cda441fdd3.json')\n\nclient = vision.ImageAnnotatorClient()\n#path = '/home/ec2-user/capstone/capstoneProject/visionAPI/image/t.png'\ndef imagedetection():\n path = \"/home/ec2-user/capstone/capstoneProject/visionAPI/drug_image.jpg\"\n with io.open(path, 'rb') as image_file:\n content = image_file.read()\n\n image = vision.Image(content=content)\n\n price_candidate = []\n card_number_candidate = []\n date_candidate = []\n detectedText = []\n response = client.text_detection(image=image)\n texts = response.text_annotations\n #print('Texts:')\n\n for text in texts:\n content = text.description\n content = content.replace(',','')\n print('\\n\"{}\"'.format(content))\n detectedText.append(content)\n\n if response.error.message:\n raise Exception(\n '{}\\nFor more info on error messages, check: '\n 'https://cloud.google.com/apis/design/errors'.format(\n response.error.message))\n return detectedText[0]\n\n","repo_name":"so-hko/capstone","sub_path":"capstoneProject/visionAPI/imageDetectionAPI.py","file_name":"imageDetectionAPI.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"57"} +{"seq_id":"9909843063","text":"#MySQLdb套件\r\nimport MySQLdb\r\nconn = MySQLdb.connect(host=\"db-testing.csvceebtmmcx.ap-northeast-1.rds.amazonaws.com\",\r\n user=\"admin\",\r\n passwd=\"321password\",\r\n db=\"activity\",\r\n charset=\"utf8\")\r\n\r\n\r\ndef insertIntoDatabase(table, dataDic):\r\n \"\"\"\r\n 將資料輸入到指定的table裡\r\n 輸入要新增資料的table跟字典型態的輸入資料\r\n 會直接新增資料至table中\r\n \"\"\"\r\n # 欲查詢的 query 指令\r\n query = \"Insert into \" + table + \" (\"\r\n for colunm in dataDic.keys():\r\n query += colunm\r\n query += \", \"\r\n query = query[:-2]\r\n query += \") values (\"\r\n val = []\r\n for colunm in dataDic.values():\r\n if colunm != \"number\" and colunm != \"price\":\r\n val.append(colunm)\r\n query += \"%s, \"\r\n else:\r\n val.append(colunm)\r\n query += \"%d, \"\r\n query = query[:-2]\r\n query += \");\"\r\n print(query) # 字串 = %s 數字 = %d\r\n print(val)\r\n # 執行查詢\r\n cursor = conn.cursor()\r\n cursor.execute(query, tuple(val))\r\n\r\n\r\n #印出結果\r\n print(cursor.rowcount, \"record inserted.\")\r\n\r\n\r\ndef select(table):\r\n \"\"\"印出table裡的所有資料\"\"\"\r\n # 欲查詢的 query 指令\r\n query = \"SELECT * FROM \" + table\r\n # 執行查詢\r\n cursor = conn.cursor()\r\n cursor.execute(query)\r\n result = cursor.fetchall()\r\n #print(type(result))\r\n #print(result)\r\n return result\r\n# id目前的使用狀況,要用前記得+=1\r\n\r\n\r\ndef insertdata(push_main, push_add, push_book):\r\n push_main['activityID'] = check_main(push_main)\r\n push_add['addressID'] = check_add(push_add)\r\n push_main['addressID'] = push_add.get('addressID')\r\n push_book['bookingID'] = check_booking(push_book)\r\n push_main['bookingID'] = push_book.get('bookingID')\r\n\r\n if final_check('Address', push_main.get('addressID')):\r\n push_add['addressID'] = str(check_add(push_add))\r\n insertIntoDatabase(\"Address\", push_add)\r\n if final_check('Booking', push_main.get('bookingID')):\r\n push_book['bookingID'] = str(check_booking(push_book))\r\n insertIntoDatabase(\"Booking\", push_book)\r\n if final_check('ActivityMain', push_main.get('activityID')):\r\n push_main['activityID'] = str(push_main.get('activityID'))\r\n push_main['addressID'] = str(push_add.get('addressID'))\r\n push_main['bookingID'] = str(push_book.get('bookingID'))\r\n insertIntoDatabase(\"ActivityMain\", push_main)\r\n\r\n # 確認執行\r\n conn.commit()\r\n\r\n\r\ndef check_main(push):\r\n listd = select(\"ActivityMain\")\r\n #print(\"ActivityMain\")\r\n #print(len(listd))\r\n #print(listd)\r\n for i in listd:\r\n if i[1] == push.get('name'):\r\n #print(\"same event\")\r\n return i[0]\r\n return len(listd)+1\r\n\r\n\r\ndef check_add(push):\r\n lista = select(\"Address\")\r\n #print(\"Address\")\r\n #print(len(lista))\r\n for i in lista:\r\n if i[5] == push.get('fullAddress'):\r\n #print(\"same address\")\r\n return i[0]\r\n return len(lista)+1\r\n\r\n\r\ndef check_booking(push):\r\n listb = select(\"Booking\")\r\n #print(\"Booking\")\r\n #print(len(listb))\r\n for i in listb:\r\n if i[1] == push.get('bookingURL'):\r\n #print(\"same url\")\r\n return i[0]\r\n return len(listb)+1\r\n\r\n\r\ndef final_check(table, uid):\r\n listd = select(table)\r\n print(type(uid))\r\n print(uid)\r\n uuid = int(uid)\r\n if uuid <= len(listd):\r\n return False\r\n else:\r\n return True\r\n","repo_name":"tony148565/event_get","sub_path":"SQL_connect.py","file_name":"SQL_connect.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"70636669938","text":"#!/usr/bin/env python3\r\nfrom tdm import tdm\r\nimport numpy as np\r\nimport random\r\n\r\ndef lsClassifier(traindata, trainlabel, testdata, testlabel, _lambda):\r\n\tx = traindata\r\n\ty = trainlabel\r\n\r\n\tz = x.T * x\r\n\r\n\tomega = (z + _lambda*np.eye(z.shape[0])).I * x.T * y.T\r\n\tpredicty = testdata * omega\r\n\t\r\n\t\r\n\tp = [i[0] for i in predicty]\r\n\tp1 = p[:100]\r\n\tp2 = p[100:]\r\n\tp1.sort()\r\n\tmf = 100\r\n\tmt = 0\r\n\tfor i in range(len(p1)):\r\n\t\tm2 = 0\r\n\t\tfor j in p2:\r\n\t\t\tif j > p1[i]:\r\n\t\t\t\tm2 += 1\r\n\t\tf = (100 + m2)/(100 - i + 1)\r\n\t\tif f < mf:\r\n\t\t\tmf = f\r\n\t\t\tmt = p1[i]\r\n\t\r\n\tnp2p = 0\r\n\tnn2p = 0\r\n\typred = []\r\n\tfor i in range(len(p)):\r\n\t\tif p[i] > mt:\r\n\t\t\typred.append(1)\r\n\t\t\tif testlabel[0, i]:\r\n\t\t\t\tnp2p += 1\r\n\t\t\telse:\r\n\t\t\t\tnn2p += 1\r\n\t\telse:\r\n\t\t\typred.append(0)\r\n\t#print(nn2p, np2p)\r\n\tSP = np2p / (np2p + nn2p) \r\n\tSR = np2p / 100\r\n\tF = SP * SR * 2 / (SP + SR)\r\n\treturn ypred, SP, SR, F\r\n\t\r\n\r\nsn, hn, M = tdm()\r\n\r\nx = list(range(500))\r\nrandom.shuffle(x)\r\ny = list(range(2500))\r\nrandom.shuffle(y)\r\n\r\n# 5 cross validation\r\nf = []\r\nfor idx in range(5):\r\n\r\n\ttraindata = []\r\n\ttrainlabel = []\r\n\ttestdata = []\r\n\ttestlabel = []\r\n\r\n\tfor i in range(400):\r\n\t\ttraindata.append([0 for j in range(M)])\r\n\t\tfor j in sn[x[i]]:\r\n\t\t\ttraindata[-1][j[0]] = j[1]\r\n\tfor i in range(100):\r\n\t\ttestdata.append([0 for j in range(M)])\r\n\t\tfor j in sn[x[i + 400]]:\r\n\t\t\ttestdata[-1][j[0]] = j[1]\r\n\r\n\tfor i in range(2000):\r\n\t\ttraindata.append([0 for j in range(M)])\r\n\t\tfor j in hn[y[i]]:\r\n\t\t\ttraindata[-1][j[0]] = j[1]\r\n\tfor i in range(500):\r\n\t\ttestdata.append([0 for j in range(M)])\r\n\t\tfor j in hn[y[i + 2000]]:\r\n\t\t\ttestdata[-1][j[0]] = j[1]\r\n\r\n\ttraindata = np.mat(traindata)\r\n\ttestdata = np.mat(testdata)\r\n\ttrainlabel = np.mat([1 for i in range(400)] + [0 for i in range(2000)])\r\n\ttestlabel = np.mat([1 for i in range(100)] + [0 for i in range(500)])\r\n\r\n\r\n\tf.append(lsClassifier(traindata, trainlabel, testdata, testlabel,1000)[3])\r\n\tx = x[100:] + x[:100]\r\n\ty = y[500:] + y[:500]\r\nprint(f)\r\nprint(sum(f)/len(f))\r\n\r\n\r\n","repo_name":"cyh-ustc/aiexp2","sub_path":"1/lsclassifier.py","file_name":"lsclassifier.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"57"} +{"seq_id":"6040307719","text":"import pickle\n\nfrom lib.utils_cv.similarity.metrics import compute_distances\n\nfrom feature_vector import extract_feature\nfrom services.db import product_data\n\ndnn_features = {}\nfor prod in list(product_data.find({'featureVector': {'$type': 'binData'}})):\n dnn_features[prod['productId']] = pickle.loads(prod['featureVector'])\n\n\ndef query_image():\n query_feature = list(extract_feature('query').values())[0]\n\n distances = compute_distances(query_feature, dnn_features)\n\n distances.sort(key=lambda x: x[1])\n id_list = [prod[0] for prod in distances]\n\n return id_list\n\n\nif __name__ == '__main__':\n print(query_image())\n","repo_name":"tdd75/cbir","sub_path":"search-engine-module/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"19687142958","text":"import numpy as np\nfrom skimage import transform\n\n\nclass TransformSuite:\n \"\"\"Benchmark for transform routines in scikit-image.\"\"\"\n\n def setup(self):\n self.image = np.zeros((2000, 2000))\n idx = np.arange(500, 1500)\n self.image[idx[::-1], idx] = 255\n self.image[idx, idx] = 255\n\n def time_hough_line(self):\n result1, result2, result3 = transform.hough_line(self.image)\n","repo_name":"scikit-image/scikit-image","sub_path":"benchmarks/benchmark_transform.py","file_name":"benchmark_transform.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":5678,"dataset":"github-code","pt":"57"} +{"seq_id":"28325082725","text":"from cs50 import get_string\nimport re\n\n\n# letters count logic\ndef count_letters(text):\n count = 0\n for letter in text:\n if letter.isupper() or letter.islower():\n count = count + 1\n return count\n\n# words count logic\n\n\ndef count_words(text):\n word_count = 0\n for word in text.rsplit(\" \"):\n # print(word)\n word_count = word_count + 1\n return word_count\n\n# sentence count logic\n\n\ndef count_sentence(text):\n\n pattern = \"[\\.?!]\"\n\n splitstring = re.split(pattern, text)\n sentence_count = len(splitstring) - 1\n return sentence_count\n\n\ndef grade(letters_count, words_count, sentence_count):\n\n L = (float(letters_count) / float(words_count)) * 100\n S = (float(sentence_count) / float(words_count)) * 100\n index = round((0.0588 * L) - (0.296 * S) - 15.8)\n return index\n\n\ndef main():\n\n text = get_string(\"Text: \")\n\n # print(f\"Text: {text}\")\n\n letters_count = count_letters(text)\n # print(letters_count)\n\n words_count = count_words(text)\n # print(words_count)\n\n sentence_count = count_sentence(text)\n # print(f\"sentence :{sentence_count}\")\n\n index = grade(letters_count, words_count, sentence_count)\n # print(f\"index: {index}\")\n\n if index > 16:\n print(\"Grade 16+\")\n\n elif index < 1:\n print(\"Before Grade 1\")\n else:\n print(f\"Grade {index}\")\n\n\nmain()","repo_name":"sarannetworkprogammer/CS50_2022-Harvard","sub_path":"week6/sentimental-readability/readability.py","file_name":"readability.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"1310190203","text":"from utils import timer\n\n\ndef sim(boss, actions, part):\n boss_hp, boss_dmg = boss[\"HP\"], boss[\"Damage\"]\n hp, mana, armor = 50, 500, 0\n turn, turn_c = 0, 0\n mana_spent = 0\n poison_left, shield_left, recharge_left = 0, 0, 0\n my_turn = True\n spell_cost = {\"M\": 53, \"D\": 73, \"S\": 113, \"P\": 173, \"R\": 229}\n\n while True:\n if len(actions) <= turn_c:\n return\n if poison_left:\n poison_left -= 1\n boss_hp -= 3\n if shield_left:\n shield_left -= 1\n armor = 7\n else:\n armor = 0\n if recharge_left:\n recharge_left -= 1\n mana += 101\n if my_turn:\n if part == 2:\n hp -= 1\n if hp <= 0:\n return\n action = actions[turn_c]\n mana -= spell_cost[action]\n mana_spent += spell_cost[action]\n if action == \"M\":\n boss_hp -= 4\n elif action == \"D\":\n boss_hp -= 2\n hp += 2\n elif action == \"S\":\n if shield_left:\n return\n shield_left = 6\n elif action == \"P\":\n if poison_left:\n return\n poison_left = 6\n elif action == \"R\":\n if recharge_left:\n return\n recharge_left = 5\n if mana < 0:\n return\n if boss_hp <= 0:\n return mana_spent\n if not my_turn:\n hp -= max(boss_dmg - armor, 1)\n if hp <= 0:\n return\n if my_turn:\n turn_c += 1\n my_turn = not my_turn\n turn += 1\n\n\ndef iterate_actions(actions, pos):\n actions[pos] = \"DSPRM\"[\"MDSPR\".index(actions[pos])]\n if actions[pos] == \"M\":\n if pos + 1 <= len(actions):\n iterate_actions(actions, pos + 1)\n\n\ndef solve(boss, part):\n actions = [\"M\"] * 10\n min_spent = 10000\n\n for i in range(100000):\n iterate_actions(actions, 0)\n result = sim(boss, actions, part)\n if result:\n min_spent = min(result, min_spent)\n return min_spent\n\n\n@timer\ndef main():\n boss = {\n \"HP\": 58,\n \"Damage\": 9\n }\n\n print(solve(boss, 1))\n print(solve(boss, 2))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jmcarter17/aoc2015","sub_path":"day22.py","file_name":"day22.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"10719592238","text":"import unittest\r\nimport os\r\nfrom src.data_ingestion import ingest_data, convert_to_decimal_degrees\r\n\r\n\r\nclass TestDataIngestion(unittest.TestCase):\r\n def test_ingest_data(self):\r\n # Test input files\r\n raw_data_file1 = \"data/raw/raw_data_folder/raw_data_file1.json\"\r\n raw_data_file2 = \"data/raw/raw_data_folder/raw_data_file2.json\"\r\n\r\n # Test expected output files\r\n intermediate_data_file1 = (\r\n \"data/intermediate/intermediate_data_folder/intermediate_data_file1.json\"\r\n )\r\n intermediate_data_file2 = (\r\n \"data/intermediate/intermediate_data_folder/intermediate_data_file2.json\"\r\n )\r\n\r\n # Test if the function can correctly ingest data\r\n ingest_data(\r\n raw_data_file1,\r\n raw_data_file2,\r\n intermediate_data_file1,\r\n intermediate_data_file2,\r\n )\r\n self.assertTrue(os.path.exists(intermediate_data_file1))\r\n self.assertTrue(os.path.exists(intermediate_data_file2))\r\n\r\n def test_convert_to_decimal_degrees(self):\r\n # Test input coordinates in different\r\n coord1 = \"40.785091, -73.968285\" # Decimal Degrees\r\n coord2 = \"40° 47' 6.32752'' N, 73° 58' 5.82680'' W\" # Degrees, Minutes, Seconds\r\n coord3 = \"40° 47.10546' N, 73° 58.09788' W\" # Degrees, Decimal Minutes\r\n coord4 = \"40.785091 N, 73.968285 W\" # x y\r\n coord_type = \"longitude\"\r\n\r\n # Test expected output coordinates in decimal degrees\r\n expected_coord1 = \"40.785091, -73.968285\"\r\n expected_coord2 = \"40.785091, -73.968285\"\r\n expected_coord3 = \"40.785091, -73.968285\"\r\n expected_coord4 = \"40.785091, -73.968285\"\r\n\r\n # Test if the function can correctly convert the input coordinates to decimal\r\n self.assertEqual(\r\n convert_to_decimal_degrees(coord1, coord_type), expected_coord1\r\n )\r\n self.assertEqual(\r\n convert_to_decimal_degrees(coord2, coord_type), expected_coord2\r\n )\r\n self.assertEqual(\r\n convert_to_decimal_degrees(coord3, coord_type), expected_coord3\r\n )\r\n self.assertEqual(\r\n convert_to_decimal_degrees(coord4, coord_type), expected_coord4\r\n )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n","repo_name":"Vleyked/data-engineering-sample","sub_path":"etl-gcp-json-bigquery/test/data_ingestion_test.py","file_name":"data_ingestion_test.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"20660888049","text":"import bpy\nimport blf\nimport bgl\nfrom time import time\nfrom ..addon import prefs, is_28\n\n\ndef blf_color(r, g, b, a):\n if is_28():\n blf.color(0, r, g, b, a)\n else:\n bgl.glColor4f(r, g, b, a)\n\n\nclass Timer:\n def __init__(self, t):\n self.reset(t)\n\n def update(self):\n t1 = time()\n self.t -= t1 - self.t0\n self.t0 = t1\n\n return self.t <= 0\n\n def reset(self, t):\n self.t = t\n self.t0 = time()\n\n def finished(self):\n return self.t <= 0\n\n\nclass SpaceGroup:\n def __init__(self, bl_type):\n self.type = bl_type\n self.handler = None\n self.bl_timer = None\n self.timer = Timer(1)\n self.text = None\n self.alignment = 'TOP'\n self.offset_x = 10\n self.offset_y = 10\n self.shadow = True\n\n\nspace_groups = dict()\n\n\ndef add_space_group(id, tp_name):\n tp = getattr(bpy.types, tp_name, None)\n if not tp:\n return\n\n space_groups[id] = SpaceGroup(tp)\n\n\nadd_space_group(\"CLIP_EDITOR\", \"SpaceClipEditor\")\nadd_space_group(\"CONSOLE\", \"SpaceConsole\")\nadd_space_group(\"DOPESHEET_EDITOR\", \"SpaceDopeSheetEditor\")\nadd_space_group(\"FILE_BROWSER\", \"SpaceFileBrowser\")\nadd_space_group(\"GRAPH_EDITOR\", \"SpaceGraphEditor\")\nadd_space_group(\"IMAGE_EDITOR\", \"SpaceImageEditor\")\nadd_space_group(\"INFO\", \"SpaceInfo\")\nadd_space_group(\"LOGIC_EDITOR\", \"SpaceLogicEditor\")\nadd_space_group(\"NLA_EDITOR\", \"SpaceNLA\")\nadd_space_group(\"NODE_EDITOR\", \"SpaceNodeEditor\")\nadd_space_group(\"OUTLINER\", \"SpaceOutliner\")\nadd_space_group(\"PROPERTIES\", \"SpaceProperties\")\nadd_space_group(\"SEQUENCE_EDITOR\", \"SpaceSequenceEditor\")\nadd_space_group(\"TEXT_EDITOR\", \"SpaceTextEditor\")\nadd_space_group(\"TIMELINE\", \"SpaceTimeline\")\nadd_space_group(\"USER_PREFERENCES\", \"SpaceUserPreferences\")\nadd_space_group(\"VIEW_3D\", \"SpaceView3D\")\n\ndel add_space_group\n\n\nclass Overlay(bpy.types.PropertyGroup):\n overlay: bpy.props.BoolProperty(\n name=\"Use Text Overlay\", description=\"Use text overlay\", default=True)\n size: bpy.props.IntProperty(\n name=\"Font Size\", description=\"Font size\",\n default=18, min=10, max=50, options={'SKIP_SAVE'})\n color: bpy.props.FloatVectorProperty(\n name=\"Color\", description=\"Color\",\n default=(1, 1, 1, 1), subtype='COLOR', size=4, min=0, max=1)\n color2: bpy.props.FloatVectorProperty(\n name=\"Color\", description=\"Secondary color\",\n default=(1, 1, 0, 1), subtype='COLOR', size=4, min=0, max=1)\n alignment: bpy.props.EnumProperty(\n name=\"Alignment\",\n description=\"Alignment\",\n items=(\n ('TOP', \"Top\", \"\"),\n ('TOP_LEFT', \"Top Left\", \"\"),\n ('TOP_RIGHT', \"Top Right\", \"\"),\n ('BOTTOM', \"Bottom\", \"\"),\n ('BOTTOM_LEFT', \"Bottom Left\", \"\"),\n ('BOTTOM_RIGHT', \"Bottom Right\", \"\"),\n ),\n default='BOTTOM')\n duration: bpy.props.FloatProperty(\n name=\"Duration (sec)\", description=\"Duration (sec)\",\n subtype='TIME', min=1, max=10, default=2, step=10)\n offset_x: bpy.props.IntProperty(\n name=\"Offset X\", description=\"Offset X\",\n subtype='PIXEL', default=10)\n offset_y: bpy.props.IntProperty(\n name=\"Offset Y\", description=\"Offset Y\",\n subtype='PIXEL', default=30)\n shadow: bpy.props.BoolProperty(\n name=\"Shadow\", description=\"Use shadow\", default=True)\n\n def draw(self, layout):\n layout.prop(self, \"overlay\")\n\n layout = layout.column()\n if not self.overlay:\n layout.active = False\n\n col = layout.column(align=True)\n col.prop(self, \"alignment\", text=\"\")\n\n row = col.row(align=True)\n row.prop(self, \"color\", text=\"\")\n row.prop(self, \"color2\", text=\"\")\n row.prop(self, \"shadow\", text=\"\", icon='META_BALL')\n\n col.prop(self, \"size\")\n col.prop(self, \"duration\")\n col.prop(self, \"offset_x\")\n col.prop(self, \"offset_y\")\n\n\nclass Table:\n def __init__(self):\n self.text = None\n\n def update(self, space):\n text = space.text\n if self.text == text:\n return\n\n self.text = text\n\n self.width = 0\n self.height = 0\n self.data = data = []\n self.border_x = 10\n self.border_y = 8\n\n rows = text.split(\"\\n\")\n\n for i, row in enumerate(rows):\n blf.size(0, round(space.size * (1 if i == 0 else 1.3)), 72)\n row_w, row_h = 0, 0\n data.append([0, 0, 0])\n cells = row.split(\"\\t\")\n cell_x = 0\n _, row_h = blf.dimensions(0, \"Yy\")\n for j, cell in enumerate(cells):\n w, _ = blf.dimensions(0, cell)\n row_w += w\n data[i].append(cell)\n data[i].append(w)\n data[i].append(cell_x)\n cell_x += w\n if j > 0:\n cell_x += self.border_x\n row_w += self.border_x\n\n data[i][0] = row_w\n data[i][1] = row_h\n data[i][2] = (0 if \"BOTTOM\" in space.alignment else row_h) \\\n if i == 0 else data[i - 1][2] + data[i - 1][1] + self.border_y\n\n self.width = max(self.width, row_w)\n self.height += row_h\n if i > 0:\n self.height += self.border_y\n\n def size(self, i, j):\n return self.data[i][3 * j + 4]\n\n def cell(self, i, j):\n return self.data[i][3 * j + 3]\n\n def num_cols(self, i):\n return (len(self.data[i]) - 3) // 3\n\n def num_rows(self):\n return len(self.data)\n\n def row_y(self, i):\n return self.data[i][2]\n\n def col_x(self, i, j):\n row = self.data[i]\n num_cols = self.num_cols(i)\n if num_cols == 1:\n return (self.width - row[3 + 3 * j + 1]) // 2\n elif j == num_cols - 1:\n return self.width - row[3 + 3 * j + 1]\n return row[3 + 3 * j + 2]\n\n\ntable = Table()\n\n\ndef _draw_table(space, table, i, j, r, g, b, a):\n ctx = bpy.context\n\n if \"LEFT\" in space.alignment:\n x = space.offset_x + table.col_x(i, j)\n elif \"RIGHT\" in space.alignment:\n x = ctx.region.width - table.width - space.offset_x + table.col_x(i, j)\n else:\n x = 0.5 * ctx.region.width - 0.5 * table.width + table.col_x(i, j)\n\n if \"TOP\" in space.alignment:\n y = ctx.region.height - space.offset_y - table.row_y(i)\n else:\n y = space.offset_y + table.row_y(i)\n\n blf.position(0, x, y, 0)\n blf.size(0, round(space.size * (1 if i == 0 else 1.3)), 72)\n blf_color(r, g, b, a)\n blf.draw(0, table.cell(i, j))\n\n\ndef _draw_text(space):\n p = 1 if space.timer.t >= 0.3 else space.timer.t / 0.3\n\n if space.shadow:\n blf.enable(0, blf.SHADOW)\n blf.shadow_offset(0, 1, -1)\n\n if space.text:\n table.update(space)\n\n for i in range(0, table.num_rows()):\n for j in range(0, table.num_cols(i)):\n r, g, b, a = space.color if j % 2 == 0 else space.color2\n if i == 0:\n a *= 0.8\n if space.shadow:\n blf.shadow(0, 5, 0.0, 0.0, 0.0, a * 0.4 * p)\n _draw_table(space, table, i, j, r, g, b, a * p)\n\n blf.disable(0, blf.SHADOW)\n\n\nclass RL_OT_overlay(bpy.types.Operator):\n bl_idname = \"rl.overlay\"\n bl_label = \"\"\n bl_options = {'INTERNAL'}\n\n is_running = False\n\n text: bpy.props.StringProperty(options={'SKIP_SAVE'}, maxlen=1024)\n duration: bpy.props.FloatProperty(options={'SKIP_SAVE'})\n\n def modal(self, context, event):\n if event.type == 'TIMER':\n num_handlers = 0\n active_areas = set()\n for name, space in space_groups.items():\n if not space.handler:\n continue\n\n active_areas.add(name)\n\n if space.timer.update():\n space.type.draw_handler_remove(\n space.handler, 'WINDOW')\n space.handler = None\n else:\n num_handlers += 1\n\n for area in context.screen.areas:\n if area.type in active_areas:\n area.tag_redraw()\n\n if not num_handlers:\n context.window_manager.event_timer_remove(self.timer)\n self.timer = None\n RL_OT_overlay.is_running = False\n return {'FINISHED'}\n\n return {'PASS_THROUGH'}\n\n def execute(self, context):\n if context.area.type not in space_groups:\n return {'CANCELLED'}\n\n pr = prefs()\n\n if not pr.overlay.overlay:\n return {'CANCELLED'}\n\n space = space_groups[context.area.type]\n space.timer.reset(self.duration or pr.overlay.duration)\n space.text = self.text\n space.size = pr.overlay.size\n space.alignment = pr.overlay.alignment\n space.offset_x = pr.overlay.offset_x\n space.offset_y = pr.overlay.offset_y\n space.shadow = pr.overlay.shadow\n space.color = list(pr.overlay.color)\n space.color2 = list(pr.overlay.color2)\n\n if space.handler:\n return {'CANCELLED'}\n\n space.handler = space.type.draw_handler_add(\n _draw_text, (space,), 'WINDOW', 'POST_PIXEL')\n\n if not RL_OT_overlay.is_running:\n RL_OT_overlay.is_running = True\n context.window_manager.modal_handler_add(self)\n self.timer = context.window_manager.event_timer_add(\n 0.1, window=bpy.context.window)\n\n return {'RUNNING_MODAL'}\n","repo_name":"huggaida/scripts","sub_path":"blender/addons/re-last/utils/overlay.py","file_name":"overlay.py","file_ext":"py","file_size_in_byte":9583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"21724167045","text":"import PCA9685\nimport time\npca=PCA9685.PCA9685()\npca.setPWMFreq(50)\nclass Servo():\n\tdef __init__(self,chan=0,centerVal=1457):\n\t\tself.pca=pca\n\t\tself.pca.setPWMFreq(50)\n\t\tself.channel=chan\n\t\tself.centerVal=centerVal\n\t\tself.currentVal=0\n\t\tself.center()\n\tdef center(self):\n\t\tself.pca.setServoPulse(self.channel,self.centerVal)\n\t\tself.currentVal=self.centerVal\n\tdef checkPosition(self):\n\t\tif self.currentVal <=500:\n\t\t\t\tself.currentVal=500\n\t\telif self.currentVal >=2500:\n\t\t\t\tself.currentVal=2500\n\tdef move(self,val):\n\t\tself.currentVal-=val\n\t\tself.checkPosition()\n\t\tself.pca.setServoPulse(self.channel,self.currentVal)\n\tdef setPosition(self,pos):\n\t\tself.currentVal=pos\n\t\tself.checkPosition()\n\t\tself.pca.setServoPulse(self.channel,self.currentVal)\n\tdef setPositionDegrees(self,deg):\n\t\tif deg<(-90):\n\t\t\tdeg=-90\n\t\tif deg>90:\n\t\t\tdeg=90\n\t\tif deg>=0:\n\t\t\tself.currentVal=self.centerVal+( deg*(2500-self.centerVal)/90 )\n\t\telse:\n\t\t\tself.currentVal=self.centerVal+( deg*(self.centerVal-500)/90)\n\t\t\tself.checkPosition()\n\t\t\tself.pca.setServoPulse(self.channel,self.currentVal)\n\tdef stop(self):\n\t\t\tself.pca.setPWM(self.channel,0,0)\n\t\t\nif __name__ =='__main__':\n\tprint(\"main\")\n\tservo=Servo()\n\tservo.center()\n\ttime.sleep(3)\n\tservo.setPositionDegrees(-45)\n\ttime.sleep(1)\n\tservo.setPositionDegrees(45)\n\ttime.sleep(1)\n\tservo.setPositionDegrees(90)\n\ttime.sleep(1)\n\tservo.setPositionDegrees(-90)\n\ttime.sleep(1)\n\tservo.stop()\n\ttime.sleep(1) \n\tservo2=Servo(chan=1,centerVal=1800)\n\tservo2.center()\n\ttime.sleep(1)\n\tservo2.stop()\n \n \n","repo_name":"xbubus/AlphaBot2-object-tracking-rpi","sub_path":"servos.py","file_name":"servos.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"57"} +{"seq_id":"28283912209","text":"'''\nTool to build a transliteration table for ASCII characters.\n \nThe strategy used is to create a set of all valid Unicode codepoints and\nremove things like combining characters, tags, and non-English language\ncodepoints. A decomposition from the Unicode Character Database (see\nucd.py) is used if it exists; these usually translate characters with\naccents or other modifiers. Then the Unicode string descriptions of\neach character are searched for key words to select the set of\ncharacters wanted for each of the above ASCII characters. The result is\na dictionary named keep that contains each ASCII character as a key and\nthe set of Unicode characters that should be transliterated to that\nASCII character.\n \nA guiding factor in my selection of the characters to transliterate is\nthat they must look like the corresponding ASCII character, regardless\nof the semantic content. Thus, U+01c3 looks like an exclamation mark,\nbut has the name of \"LATIN LETTER RETROFLEX CLICK\". The alternate name\nis \"LATIN LETTER EXCLAMATION MARK\", so it is reasonable that it be\ntranslated to !, U+0021. In other words, syntax and not semantic\ncontent is the driving force behind this transliteration, primarily\nbecause I am not a linguist.\n'''\n#∞test∞# ignore #∞test∞#\nimport unicodedata as U\nimport re\nimport pickle\nimport string\nimport sys\nimport time\nimport getopt\nimport os\nfrom ucd import ucd\nfrom textwrap import dedent\nfrom itertools import combinations, chain\nfrom columnize import Columnize\nfrom pprint import pprint as pp\nfrom collections import defaultdict\nfrom pdb import set_trace as xx \nif 0:\n import debug\n debug.SetDebugger()\n\ndef ShowAll(cpset, arg=\"all\"):\n '''Print all codepoints in cpset to stdout that contain the regular\n expression arg. Use \"all\" for arg to print all characters.\n '''\n r = re.compile(arg, re.I)\n for cp in sorted(cpset, reverse=True):\n descr = U.name(chr(cp))\n if arg == \"all\" or r.search(descr):\n print(f\"{cp:06x} {chr(cp)} {descr}\")\n\ndef PrintCP(cp, indent=\"\"):\n c = chr(cp)\n print(f\"{indent}{cp:05X} {chr(cp):^3s} {U.name(c)}\", file=stream)\n\ndef GetWorkingSet(file=\"asciify_make.pickle\", build=False):\n '''Return (cpset, keep) where cpset is the working set of Unicode\n codepoints and keep is a defaultdict of lists.\n \n It takes about 1.6 s to build the set and about half of this time to\n read it in from disk. Thus, we pickle the data to disk. The file\n is only built if the pickled data cannot be read or build is True.\n '''\n def RemoveInvalid(cpset):\n 'Remove codepoint values that cause an exception'\n remove = set()\n for cp in cpset:\n try:\n U.name(chr(cp))\n except ValueError:\n remove.add(cp)\n Debug(fmt.format(\" Invalid codepoints\", -len(remove)))\n cpset -= remove\n def RemoveMisc(cpset):\n 'Remove TAG and COMBINING characters'\n remove = set()\n cpset -= set(range(0xe0020, 0xe007f)) # Remove TAGS\n cpset -= set((0x0fdfc,)) # Special character\n combine = re.compile(r\"^COMBINING\\b|\\bCOMBINING\\b\")\n for cp in cpset:\n descr = U.name(chr(cp))\n if combine.search(descr):\n remove.add(cp)\n Debug(fmt.format(\" Tag, combining\", -len(remove)))\n cpset -= remove\n def RemoveNotEnglish(cpset):\n '''Remove the codepoints from cpset whose Unicode\n description string contains one of the following languages,\n as they don't share symbols with English.\n '''\n languages = set('''\n adlam admetos aegean afghani ahom anatolian arabian\n arabic armenian avestan balinese bamum bassa batak\n bengali bhaiksuki bopomofo brahmi buginese buhid\n byzantine canadian carian caucasian chakma cham cherokee\n cjk coptic cuneiform cypriot cyrillic deseret devanagari\n dogra duployan egyptian egyptological elbasan ethiopic\n ewa functional georgian geta glagolitic grantha greek\n gujarati gunjala gurmukhi halfwidth hangul hangzhou\n hanifi hanunoo hatran hebrew hentaigana hexagram\n hieroglyph hiragana hom hungarian ideogram ideograph\n ideographic imperial indic inscriptional interlinear\n japanese javanese kaithi kangxi kannada katakana kayah\n kharoshthi khmer khojki khudawadi korean lao lepcha\n limbu linear lisu lycian lydian mahajani mahjong makasar\n malayalam mandaic manichaean marchen masaram mayan\n medefaidrin meetei mende meroitic miao modi mongolian\n mro multani myanmar nabataean nandinagari newa nko\n nomisma nushu nyiakeng object ogham ogonek ol oriya\n osage osmanya pahawh pahlavi palmyrene parthian pau\n permic persian phags-pa phaistos philippine phoenician\n psalter rejang rumi runic samaritan saurashtra sesame\n shakti sharada shavian siddham sinhala slavonic sogdian\n sora soyombo sundanese svasti syloti syriac tagalog\n tagbanwa tai takri tamil tangut telugu tetragram thaana\n thai tibetan tifinagh tirhuta turkic ugaritic vai vedic\n wancho warang xiangqi yi zanabazar\n \n alchemical astrological bottom dentistry digram domino\n element emoji face input integral person recycling\n shorthand sideways signwriting symbol\n '''.upper().split())\n L = [rf\"\\b{i}\\b\" for i in languages] # Add word boundaries\n ignore = re.compile('|'.join(L))\n remove = set()\n # Japanese special characters\n remove.update(set(range(0x3300, 0x3358)))\n remove.update(range(0x337b, 0x3380))\n for cp in cpset:\n descr = U.name(chr(cp))\n if ignore.search(descr):\n remove.add(cp)\n Debug(fmt.format(\" Non-English codepoints\", -len(remove)))\n cpset -= remove\n def RemoveGroups(cpset):\n '''Remove general categories (ucd calls them groups) that\n are known to not contain characters we want.\n \n Cf = TAG, format control characters\n Lo = Other letters from foreign languages\n Mn = Combining, etc.\n Ps = Open punctuation\n '''\n gc_to_ignore = \"Cf Lo Mn Ps\"\n ignore = set(gc_to_ignore.split())\n remove = set()\n for cp in cpset:\n try:\n group, data = ucd[\"chars\"][cp]\n g = ucd[\"groups\"][group]\n gc = g[\"gc\"] # General category\n if gc in ignore:\n remove.add(cp)\n except KeyError:\n continue\n Debug(fmt.format(f\" Remove gc '{gc_to_ignore}'\", -len(remove)))\n cpset -= remove\n try:\n if build or d[\"-f\"]:\n raise Exception()\n # Read in the pickled data\n f = open(file, \"rb\")\n cpset = pickle.load(f)\n except Exception:\n # Construct the pickle file\n cpset = set(range(0x110000)) # 1114112 codepoints\n Debug(f\"Started with {len(cpset)} codepoints\")\n RemoveInvalid(cpset)\n RemoveGroups(cpset)\n RemoveMisc(cpset)\n RemoveNotEnglish(cpset)\n f = open(file, \"wb\")\n pickle.dump(cpset, f)\n Debug(f\"Left with {len(cpset)} valid codepoints\")\n return cpset, defaultdict(set)\n\nif 1: # Utility\n def Debug(*p, **kw):\n print(*p, **kw, file=sys.stderr)\n def IsASCII(s):\n '''Return True if string s is composed of all ASCII characters.\n Note it returns True for the empty string.\n '''\n return all(ord(i) < 0x80 for i in s)\n def flatten(listOfLists):\n \"Flatten one level of nesting\"\n return chain.from_iterable(listOfLists)\n def Usage(d, status=1):\n name = sys.argv[0]\n print(dedent(f'''\n Usage: {name} [options] [output_file]\n \n -d dbg Debug level\n -f Force a rebuild\n -s Set select to True\n '''[1:-1]))\n exit(status)\n def ParseCommandLine(d):\n d[\"-d\"] = 0\n d[\"-f\"] = False\n d[\"-s\"] = False\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"d:fhs\")\n except getopt.GetoptError as e:\n print(str(e))\n exit(1)\n for o, a in opts:\n if o[1] in list(\"fs\"):\n d[o] = not d[o]\n if o == \"-d\":\n d[o] = int(a)\n elif o == \"-h\":\n Usage(d)\n return args\nif 1: # Handling the codepoints\n def Quotes(cpset, keep):\n def GetDoubleQuotes():\n get = [\"quot\", \"prime\"]\n remove = [\n \"single\",\n \"syllable\",\n r\"\\bapl\\b\",\n \"^prime$\",\n \"^reversed prime$\",\n \"^modifier letter prime$\",\n \"^heavy left-pointing angle\",\n \"^heavy right-pointing angle\",\n ]\n Extract(cpset, keep, get, remove, '\"', verbose=\"Double quotes\")\n def GetSingleQuotes():\n get = [\"quot\", \"prime\"]\n remove = [\n \"double\",\n \"syllable\",\n \"triple\",\n \"quadruple\",\n r\"\\bapl\\b\",\n \"^quotation mark$\",\n \"^fullwidth quotation mark$\",\n \"^heavy left-pointing angle\",\n \"^heavy right-pointing angle\",\n ]\n Extract(cpset, keep, get, remove, \"'\", verbose=\"Single quotes\")\n def GetBackQuote():\n get = [\"grave accent\", \"reversed.*prime\"]\n remove = [\"letter\", \"quotation\"]\n Extract(cpset, keep, get, remove, \"`\", verbose=\"Back quote\")\n if not select:\n GetSingleQuotes()\n GetDoubleQuotes()\n GetBackQuote()\n def Brackets(cpset, keep):\n def GetLeftParenthesis():\n get = [\"parenthesis\"]\n remove = [\"right\", \"hook\", \"extension\", \"top\", \"vertical\"]\n Extract(cpset, keep, get, remove, \"(\", verbose=\"Left parenthesis\")\n def GetRightParenthesis():\n get = [\"parenthesis\"]\n remove = [\"left\", \"hook\", \"extension\", \"top\", \"vertical\"]\n Extract(cpset, keep, get, remove, \")\", verbose=\"Right parenthesis\")\n def GetLessThan():\n get = [\"less-than\"]\n remove = [\"equal\", \"with\", \"and\", \"or\", \"not\", \"above\",\n \"nested\", \"arc\", \"closed\", \"lap\", \"double\", \"beside\", \"arrow\"]\n Extract(cpset, keep, get, remove, \"<\", verbose=\"Less-than\")\n def GetGreaterThan():\n get = [\"greater-than\"]\n remove = [\"equal\", \"with\", \"and\", \"or\", \"not\", \"above\",\n \"nested\", \"arc\", \"closed\", \"lap\", \"double\", \"beside\", \"arrow\"]\n Extract(cpset, keep, get, remove, \">\", verbose=\"Greater-than\")\n def GetLeftBracket():\n get = [\"bracket\"]\n remove = [\"right\", \"curly\", \"hook\", \"extension\", \"top\",\n \"vertical\", \"paraphrase\", \"angle\", \"substitution\",\n \"transposition\", \"omission\", \"letter\", \"arc\", \"z notation\"]\n Extract(cpset, keep, get, remove, \"[\", verbose=\"Left bracket\")\n def GetRightBracket():\n get = [\"bracket\"]\n remove = [\"left\", \"curly\", \"hook\", \"extension\", \"top\",\n \"vertical\", \"paraphrase\", \"angle\", \"substitution\",\n \"transposition\", \"omission\", \"letter\", \"arc\", \"z notation\"]\n Extract(cpset, keep, get, remove, \"]\", verbose=\"Right bracket\")\n def GetLeftCurly():\n get = [\"curly\"]\n remove = [\"right\", \"square\", \"hook\", \"middle\", \"loop\",\n \"extension\", \"logical\", \"vertical\", \"top\"]\n Extract(cpset, keep, get, remove, \"{\", verbose=\"Left curly bracket\")\n def GetRightCurly():\n get = [\"curly\"]\n remove = [\"left\", \"square\", \"hook\", \"middle\", \"loop\",\n \"extension\", \"logical\", \"vertical\", \"top\"]\n Extract(cpset, keep, get, remove, \"}\", verbose=\"Right curly bracket\")\n if not select:\n GetLeftParenthesis()\n GetRightParenthesis()\n GetLessThan()\n GetGreaterThan()\n GetLeftBracket()\n GetRightBracket()\n GetLeftCurly()\n GetRightCurly()\n def Punctuation(cpset, keep):\n def GetApostrophe():\n get = [\"apostrophe\", \"prime\"]\n remove = [\"reversed\", \"double\", \"triple\", \"quadruple\", \"letter\"]\n Extract(cpset, keep, get, remove, \"'\", verbose=\"Apostrophe\")\n def GetExclamation():\n get = [\"exclamation\"]\n remove = \"question squared arrow\".split()\n Extract(cpset, keep, get, remove, \"!\", verbose=\"Exclamation\")\n def GetComma():\n get = [\"comma\"]\n remove = [\"digit\", \"double\", \"letter\", \"quotation\"]\n Extract(cpset, keep, get, remove, \",\", verbose=\"Comma\")\n def GetDash():\n get = [\"hyphen\", \"dash\"]\n remove = [\"triangle\", \"harpoon\", \"vertical\", \"arrow\",\n \"overline\", \"low line\", \"logical\", \"oblique\", \"diaeresis\",\n \"subset\"]\n Extract(cpset, keep, get, remove, \"-\", verbose=\"Hyphen, dash\")\n def GetPeriod():\n get = [\"stop\"]\n remove = [\"digit\", \"number\", \"glottal\", \"watch\", \"bus\",\n \"square\", ]\n Extract(cpset, keep, get, remove, \".\", verbose=\"Period\")\n def GetSemicolon():\n get = [\"semicolon\"]\n remove = []\n Extract(cpset, keep, get, remove, \";\", verbose=\"Semicolon\")\n def GetColon():\n get = [\"colon\"]\n remove = [\"semicolon\", \"sign\", \"equal\", \"tri\"]\n Extract(cpset, keep, get, remove, \":\", verbose=\"Colon\")\n def GetQuestion():\n get = [\"question\"]\n remove = [\"than\", \"equal\", \"double\", \"exclamation\"]\n Extract(cpset, keep, get, remove, \"?\", verbose=\"Question\")\n def GetSpace():\n get = [\"space\"]\n remove = [\"monospace\"]\n Extract(cpset, keep, get, remove, \" \", verbose=\"Space\")\n if not select:\n GetApostrophe()\n GetComma()\n GetDash()\n GetPeriod()\n GetSemicolon()\n GetColon()\n GetQuestion()\n GetSpace()\n GetExclamation()\n def Slash_bar(cpset, keep):\n def GetSlash():\n get = [\"solidus\", \"slash\"]\n remove = [\"reverse\", \"back\", \"falling\", \"set\", \"letter\"]\n Extract(cpset, keep, get, remove, \"/\", verbose=\"Slash\")\n def GetBackslash():\n get = [\"reverse solidus\", \"backslash\"]\n remove = [\"set\"]\n Extract(cpset, keep, get, remove, \"\\\\\", verbose=\"Backslash\")\n def GetVerticalLine():\n get = [\"vertical line\"]\n remove = []\n Extract(cpset, keep, get, remove, \"|\", verbose=\"Vertical line\")\n if not select:\n GetSlash()\n GetBackslash()\n GetVerticalLine()\n def OtherCharacters(cpset, keep):\n def GetNumberSign():\n get = [\"number sign\"]\n remove = []\n Extract(cpset, keep, get, remove, \"#\", verbose=\"Number sign\")\n def GetDollarSign():\n get = [\"dollar sign\"]\n remove = []\n Extract(cpset, keep, get, remove, \"$\", verbose=\"Dollar sign\")\n def GetPercentSign():\n get = [\"percent sign\"]\n remove = []\n Extract(cpset, keep, get, remove, \"%\", verbose=\"Percent sign\")\n def GetAmpersand():\n get = [\"ampersand\"]\n remove = []\n Extract(cpset, keep, get, remove, \"&\", verbose=\"Ampersand\")\n def GetAsterisk():\n get = [\"asterisk\"]\n remove = [\"two\", \"equal\"]\n Extract(cpset, keep, get, remove, \"*\", verbose=\"Asterisk\")\n def GetPlusSign():\n get = [\"plus sign\"]\n remove = [\"with\", \"or\", \"equal\", \"set\", \"circle\", \"triangle\"]\n Extract(cpset, keep, get, remove, \"+\", verbose=\"Plus sign\")\n def GetEqualSign():\n get = [\"equals sign\"]\n remove = [\"above\", \"parallel\", \"dot\", \"infinity\"]\n Extract(cpset, keep, get, remove, \"=\", verbose=\"Equal sign\")\n def GetAtSign():\n get = [\"commercial at\"]\n remove = []\n Extract(cpset, keep, get, remove, \"@\", verbose=\"At sign\")\n def GetCircumflex():\n get = [\"circumflex\"]\n remove = [\"letter\", \"with\"]\n Extract(cpset, keep, get, remove, \"^\", verbose=\"Circumflex\")\n def GetUnderscore():\n get = [\"low line\"]\n remove = [\"vertical\"]\n Extract(cpset, keep, get, remove, \"_\", verbose=\"Underscore\")\n def GetTilde():\n get = [\"tilde\"]\n remove = \"letter with vertical equal set arrow not minus\".split()\n Extract(cpset, keep, get, remove, \"~\", verbose=\"Tilde\")\n if not select:\n GetNumberSign()\n GetDollarSign()\n GetPercentSign()\n GetAmpersand()\n GetAsterisk()\n GetPlusSign()\n GetEqualSign()\n GetAtSign()\n GetCircumflex()\n GetUnderscore()\n GetTilde()\n def Digits(cpset, keep):\n if not select:\n for n, s in (\n (\"0\", \"Zero\"),\n (\"1\", \"One\"),\n (\"2\", \"Two\"),\n (\"3\", \"Three\"),\n (\"4\", \"Four\"),\n (\"5\", \"Five\"),\n (\"6\", \"Six\"),\n (\"7\", \"Seven\"),\n (\"8\", \"Eight\"),\n (\"9\", \"Nine\")):\n get = [f\"digit {s}\", f\"superscript {s}\", f\"subscript {s}\",\n f\"double-struck digit {s}\"]\n remove = \"rod fraction\".split()\n Extract(cpset, keep, get, remove, n, verbose=f\"{s}\")\n def Letters(cpset, keep):\n d = \"double-struck\"\n # Dict for superscripts & subscripts\n s = \"I:ⁱᵢ N:ⁿₙ J:ⱼ T:ₜ S:ₛ P:ₚ M:ₘ L:ₗ K:ₖ H:ₕ X:ₓ O:ₒ E:ₑ A:ₐ V:ᵥ U:ᵤ R:ᵣ\"\n ss = dict([i.split(\":\") for i in s.split()])\n if not select:\n for i in string.ascii_uppercase:\n get = [f\"letter {i}$|letter {i} \", \n f\"{d} .* {i} |{d} .* {i}$\"]\n # Upper case\n remove = \"small schwa\".split()\n Extract(cpset, keep, get, remove, i, verbose=f\"{i}\")\n # Lower case\n other = set([ord(j) for j in ss[i]]) if i in ss else None\n remove = \"capital schwa\".split()\n Extract(cpset, keep, get, remove, i.lower(),\n verbose=f\"{i.lower()}\", other=other)\n def Miscellaneous(cpset, keep):\n # Note: set show_orig to True to print out the characters extracted\n # using regexps. \n show_orig = True\n show_orig = False\n def Ligatures():\n if show_orig:\n get = [\"ligature\"]\n remove = []\n Extract(cpset, keep, get, remove, \"xxLigatures\", verbose=\"Ligatures\")\n for cp in keep[\"xxLigatures\"]:\n print(cp, chr(cp), U.name(chr(cp)))\n else:\n keep[\"oe\"] = set((0xa7f9,))\n # I've chosen to ignore the ligatures 128624 to 128627\n def MultipleLetters():\n if show_orig:\n get = [\"letter [A-Z]{2,2} |letter [A-Z]{2,2}$\", \"digraph\"]\n remove = [\"old italic\"]\n Extract(cpset, keep, get, remove, \"xxMultiple_letters\", verbose=\"Multiple letters\")\n else:\n s = '''\n Ȣ:OU ȣ:ou Ꜩ:TZ ʪ:ls ʫ:lz ꜩ:tz Ꜳ:AA ꜳ:aa Ꜵ:AO ꜵ:ao Ꜷ:AU\n ꜷ:au ȸ:db ꜹ:av ȹ:qp Ꜹ:AV Ꜻ:AV ꜻ:av Ꜽ:AY ꜽ:ay Ꝏ:OO ꝏ:oo\n ꭐ:ui Ꝡ:VY ꝡ:vy ꭣ:uo ᵫ:ue Ꝭ:IS ꝭ:is ꝸ:um ᵺ:th Ǽ:AE ǽ:ae\n '''\n for i in s.split():\n c, e = i.split(\":\")\n keep[e].update([ord(c)])\n def DigitStop():\n get = [\"digit.*stop\"]\n remove = []\n Extract(cpset, keep, get, remove, \"xxDigit_stop\", verbose=\"Digit stop\")\n def DigitComma():\n get = [\"digit.*comma\"]\n remove = []\n Extract(cpset, keep, get, remove, \"xxDigit_comma\", verbose=\"Digit comma\")\n def QuestionExcl():\n get = [\"question exclamation\", \"exclamation question\"]\n remove = []\n Extract(cpset, keep, get, remove, \"xx?!\", verbose=\"Quest. Excl.\")\n def Fraction():\n get = [\"fraction\"]\n remove = [\"slash\"]\n Extract(cpset, keep, get, remove, \"xxFraction\", verbose=\"Fraction\")\n def Ring():\n other = set((0xB0, 0x2DA, 0x1424, 0x18DE, 0x2218))\n if show_orig:\n get = [\"ring operator\", \"ring point\"]\n remove = []\n Extract(cpset, keep, get, remove, \"xxRing\", verbose=\"Ring\", other=other)\n else:\n for cp in other:\n keep[\"deg\"].add(cp)\n keep[\".\"].add(0x2e30)\n def Interrobang():\n if show_orig:\n get = [\"interrobang\"]\n remove = []\n Extract(cpset, keep, get, remove, \"xxInterrobang\", verbose=\"Interrobang\")\n else:\n for cp in (8253, 11800, 128633, 128634, 128635):\n keep[\"?!\"].add(cp)\n def Plus():\n get = []\n remove = []\n other = set((\n 0x016ED, 0x0271A, 0x0271B, 0x0271C, 0x1F540, 0x1F541,\n 0x1F542, 0x1F7A1, 0x1F7A2, 0x1F7A3, 0x1F7A4, 0x1F7A5,\n 0x1F7A6, 0x1F7A7, 0x002D6, 0x01429, 0x02064, 0x0207A,\n 0x0208A, 0x02214, 0x02295, 0x0229E, 0x02795, 0x02A01,\n 0x02A25, 0x02A28, 0x02A2D, 0x02A2E, 0x02A39, 0x0FE62,\n 0x0FF0B))\n Extract(cpset, keep, get, remove, \"+\", verbose=\"Plus\", other=other)\n keep[\"++\"].add(0x29fa)\n keep[\"+++\"].add(0x29fb)\n def Cross():\n get = []\n remove = []\n other = set((\n 0x002DF, 0x02573, 0x26CC, 0x02694, 0x02720, 0x0274C, 0x0274E,\n 0x0292B, 0x0292C, 0x02A2F))\n Extract(cpset, keep, get, remove, \"x\", verbose=\"Cross\", other=other)\n def Precedes():\n if show_orig:\n get = [\"precedes\", \"succeeds\"]\n remove = [\"above\", \"or\", \"not\", \"relation\"]\n Extract(cpset, keep, get, remove, \"xxPrecedes\", verbose=\"Precedes\")\n else:\n for i in \"≻:> ≺:< ⪻:<< ⪼:>>\".split():\n c, e = i.split(\":\")\n keep[e].update([ord(c)])\n def Square():\n s = '''\n ㏿:gal ㏟:A/m ㏞:V/m ㏝:Wb ㏜:Sv ㏛:sr ㏙:ppm ㏘:p.m. ㏗:pH\n ㏖:mol ㏕:mil ㏔:mb ㏓:lx ㏒:log ㏑:ln ㏐:lm ㏏:kt ㏌:in\n ㏋:HP ㏊:ha ㏉:GY ㏈:dB ㏇:Co. ㏆:C/kg ㏅:cd ㏄:cc ㏃:Bq\n ㏂:a.m. ㏁:Mohm ㏀:kohm ㎿:MW ㎾:kW ㎽:mW ㎼:uW ㎻:nW ㎺:pW\n ㎹:MV ㎸:kV ㎷:mV ㎶:uV ㎵:nV ㎴:pV ㎳:ms ㎲:us ㎱:ns ㎰:ps\n ㎯:rad/s^2 ㎮:rad/s ㎭:rad ㎬:GPa ㎫:MPa ㎪:kPa ㎩:Pa\n ㎨:m/s^2 ㎧:m/s ㎦:km^3 ㎥:m^3 ㎤:cm^3 ㎣:mm^3 ㎢:km^2\n ㎡:m^2 ㎠:cm^2 ㎟:mm^2 ㎞:km ㎝:cm ㎜:mm ㎛:um ㎚:nm ㎙:fm\n ㎘:kL ㎗:dL ㎖:mL ㎕:uL ㎔:THz ㎓:GHz ㎒:MHz ㎑:kHz ㎐:Hz\n ㎏:kg ㎎:mg ㎍:ug ㎌:uF ㎋:nF ㎊:pF ㎉:kcal ㎈:cal ㎇:GB\n ㎆:MB ㎅:kB ㎄:kA ㎃:mA ㎂:uA ㎁:nA ㎀:pA ㍹:dm^3 ㍸:dm^2\n ㍷:dm ㍶:pc ㍵:oV ㍴:bar ㍳:AU ㍲:da ㍱:hPa\n '''\n for i in s.split():\n c, t = i.split(\":\")\n keep[t].add(ord(c))\n def Other():\n keep[\"||\"].add(0x23f8)\n keep[\"c/o\"].add(0x2105)\n keep[\"c/u\"].add(0x2106)\n keep[\"K\"].add(0x212a)\n keep[\"degF\"].add(ord(\"℉\"))\n keep[\"degC\"].add(ord(\"℃\"))\n keep[\"(C)\"].add(ord(\"©\"))\n keep[\"(R)\"].add(ord(\"®\"))\n keep[\"+/-\"].add(ord(\"±\"))\n keep[\"-/+\"].add(ord(\"∓\"))\n # Superscripts & subscripts\n keep[\"+\"].update((ord(\"⁺\"), ord(\"₊\")))\n keep[\"-\"].update((ord(\"⁻\"), ord(\"₋\")))\n keep[\"=\"].update((ord(\"⁼\"), ord(\"₌\")))\n keep[\"(\"].update((ord(\"⁽\"), ord(\"₍\")))\n keep[\")\"].update((ord(\"⁾\"), ord(\"₎\")))\n # Math symbols\n keep[\"::\"].add(ord(\"∷\"))\n keep[\":\"].add(ord(\"∶\"))\n keep[\"-:\"].add(ord(\"∹\"))\n s = '''⊘:/ ⊗:x ⊖:- ⊕:+ ⊛:* ⊠:x ⊟:- ⊞:+ ⊝:- ⊜:= ∿:~ ∾:~ ∽:~ ∼:~\n ∞:oo ∗:* ∖:\\\\ ∕:/ ∓:-/+ −:- ∣:| ≫:>> ≪:<< ⋙:>>> ⋘:<<<'''\n for i in s.split():\n c, t = i.split(\":\")\n keep[t].add(ord(c))\n # Currency\n s = '''\n ₡: ₢: ₣: ₤: ₧:\n ₨: €: ₯: ₱: ₹: ₽:\n ₿:'''\n for i in s.split():\n c, t = i.split(\":\")\n keep[t].add(ord(c))\n # Modifiers\n s = '''\n ʰ:h ʱ:h ʲ:j ʳ:r ʴ:r ʵ:r ʶ:R ʷ:w ʸ:y ʹ:' ʺ:\" ʻ:' ʼ:' ʽ:' ˂:<\n ˃:> ˄:^ ˅:v ˆ:^ ˈ:| ˊ:' ˋ:` ˌ:| ˍ:_ ˎ:' ˏ:` ˖:+ ˗:- ˜:~ ˝:\"\n ˟:x ˡ:l ˢ:s ˣ:x ˮ:\" ˴:` ˵:`` ˶:\" ˷:~ ꜝ:! ꜞ:! ꜟ:!'''\n for i in s.split():\n c, t = i.split(\":\")\n keep[t].add(ord(c))\n keep[\":\"].add(ord(\"ː\"))\n keep[\":\"].add(ord(\"˸\"))\n if not select:\n Ligatures()\n MultipleLetters()\n DigitStop()\n DigitComma()\n QuestionExcl()\n Fraction()\n Ring()\n Interrobang()\n Plus()\n Cross()\n Precedes()\n Square()\n Other()\nif 1: # Core functions\n def Check(cpset, keep):\n '''Verify there's no overlap between the sets in keep.\n '''\n for a, b in combinations(keep, 2):\n setA, setB = keep[a], keep[b]\n assert(not (setA & setB))\n assert(not (cpset & setA))\n assert(not (cpset & setB))\n def GetAliases(cp):\n '''Return a list of the aliases of the indicated codepoint.\n '''\n if not ucd:\n return []\n try:\n group, data = ucd[\"chars\"][cp]\n except KeyError:\n return []\n aliases = []\n if \"na1\" in data:\n aliases.append(data[\"na1\"])\n if cp in ucd[\"aliases\"]:\n for a in ucd[\"aliases\"][cp]:\n aliases.append(a[\"alias\"])\n return aliases\n def Get(cpset, build, remove, other=None):\n '''Return (local, remove_set) where local is the set of characters\n described by the sequence of regular expressions in build and\n remove_set is the set of characters in local that were removed\n because they matched the regular expressions in the sequence remove.\n Any characters in local must not be in the dictionary decomp because\n they have already been handled.\n '''\n assert(isinstance(cpset, set))\n assert(isinstance(build, (list, tuple)))\n assert(isinstance(remove, (list, tuple)))\n if other is not None:\n assert(isinstance(other, set))\n # Compile regular expressions\n bld = [re.compile(i, re.I) for i in build]\n rem = [re.compile(i, re.I) for i in remove]\n # Build our local maximal set (cache descr for later loop)\n local = []\n for cp in cpset:\n if cp in decomp: # It's already been handled\n continue\n c = chr(cp)\n # Check the U database's description\n descr = U.name(c)\n for b in bld:\n if b.search(descr):\n local.append((cp, descr))\n # Check aliases\n for alias in GetAliases(cp):\n for b in bld:\n if b.search(alias):\n local.append((cp, alias))\n # Remove the indicated chars\n remove_set = set()\n for cp, descr in local:\n for r in rem:\n if r.search(descr):\n remove_set.add(cp)\n # Change local to a set of cp and don't keep any ASCII characters\n local = set(i[0] for i in local if i[0] >= 0x80)\n if other:\n local.update(other)\n local -= remove_set\n return local, remove_set\n def Extract(cpset, keep, build, remove, key, verbose=\"\", other=None):\n '''For the set of codepoints cpset, put the subset defined by build\n and remove into the keep dictionary under the indicated key.\n cpset set of codepoints\n keep dict{key:set(equivalent_codepoints)}\n build list[regex]: extract these matches from cpset\n remove list[regex]: remove these matches from build\n key single character\n keep[key] = build - remove \n \n other is a set of characters that should be kept but aren't easy to\n find with regex searches.\n \n If verbose is not the empty string and dbg is True, it is printed\n out as a header, then the removed and kept sets are printed, along\n with keep: keep[key]. This lets you see what's kept & not.\n '''\n assert(isinstance(key, str))\n assert(isinstance(verbose, str))\n local, remove_set = Get(cpset, build, remove, other=other)\n # Update sets\n if local:\n keep[key].update(local)\n cpset -= local\n # Show the results\n if dbg and verbose:\n # dbg == 1: only print ASCII_char tab codepoints\n # dbg == 2: Print all data\n if dbg > 1:\n print(verbose, file=stream)\n print(\" Characters removed:\", file=stream)\n for cp in sorted(remove_set, reverse=True):\n PrintCP(cp, indent=\" \"*4)\n print(\" Characters kept:\", file=stream)\n for cp in sorted(local, reverse=True):\n PrintCP(cp, indent=\" \"*4)\n print(\" Result:\", file=stream)\n c = ''.join(chr(i) for i in sorted(local))\n if dbg == 1:\n print(f\"{key}\\t{c}\", file=stream)\n else:\n print(f\" {key}\\t{c}\", file=stream)\n if dbg > 1:\n n = ', '.join(f\"0x{i:x}\" for i in sorted(local))\n print(f\" {key}\\t[{n}]\", file=stream)\n print(file=stream)\n def Decompose(char):\n '''Return the decomposed string or '' if there is no suitable one.\n '''\n # Make a dictionary to translate some of the strings like \"⁄\"\n T = {\n 0x2044: \"/\",\n 0x2215: \"/\",\n 0x03A9: \"ohm\",\n 0x0301: \"'\",\n 0x0327: \",\",\n }\n for cp in range(768, 880): # Remove combining characters\n T[cp] = None\n s = char\n while s and not IsASCII(s):\n t = []\n for c in s:\n if IsASCII(c):\n t.append(c)\n else:\n d = U.decomposition(c)\n if not d:\n continue\n f = d.split()\n if f[0].startswith(\"<\"):\n f = f[1:]\n t.append(chr(int(i, 16)).translate(T) for i in f)\n s = ''.join(flatten(t))\n # Manual fixes: there are some characters that should have ''\n # returned because the above routine returns e.g. ' ' for them, but\n # they are not space-like characters.\n not_ok = set((\n 0x203e, 0x2017, 0x2dd, 0x2dc, 0x2da, 0x2d9, 0x2d8, 0xb8, 0xb4,\n 0xaf, 0xa8\n ))\n if s == \" \" and ord(char) in not_ok: \n return \"\"\n elif char in set(\"℉℃₨\"):\n return \"\"\n return s\n def Decomp(cpset, decomp):\n '''Use decomposition to construct conversions. decomp is a\n dictionary to store the codepoints and their conversions in.\n \n Example: '🆐' (0x1f190) decomposes to 'DJ'\n '''\n remove = set()\n for cp in sorted(cpset, reverse=1):\n if cp < 0x80:\n continue\n t = Decompose(chr(cp))\n if t:\n decomp[cp] = t\n remove.add(cp)\n cpset -= remove\n def GetTranslations():\n cpset, keep = GetWorkingSet()\n Decomp(cpset, decomp)\n # Build keep dictionary\n Quotes(cpset, keep)\n Brackets(cpset, keep)\n Punctuation(cpset, keep)\n Slash_bar(cpset, keep)\n OtherCharacters(cpset, keep)\n Digits(cpset, keep)\n Letters(cpset, keep)\n Miscellaneous(cpset, keep)\n # Make sure all items in keep are sets\n for i in keep:\n assert(isinstance(keep[i], set))\n # Output data\n MakeScript(\"asciify.script\", keep)\n MakeTestFile(\"asciify.test\", keep)\nif 1: # Make the files\n def MakeScript(file, keep):\n '''Write the kept data in a form suitable for a python script's \n str.translate use.\n '''\n f = open(file, \"w\")\n print(dedent(f'''\n # Constructed {time.asctime()} by {sys.argv[0]}\n \n # This dictionary can be used by str.translate to \"asciify\" Unicode\n # text by converting non-7-bit Unicode characters to their (rough)\n # ASCII equivalents.\n \n ascii_translate = {{'''[1:]), file=f)\n s = []\n for c in keep:\n for cp in keep[c]:\n s.append((cp, repr(c)))\n for cp in decomp:\n s.append((cp, repr(decomp[cp])))\n for cp, c in sorted(s):\n print(f\" 0x{cp:x}: {c},\", file=f)\n print(dedent(f'''\n }}\n if __name__ == \"__main__\": \n import sys\n s = sys.stdin.read()\n print(s.translate(ascii_translate))\n '''[1:]), file=f)\n print(f\"Wrote '{file}'\", file=sys.stderr)\n def MakeTestFile(file, keep):\n '''This function writes the data in keep to file, which can be used\n to test the transliteration facilities. The output format is the\n key ASCII character, followed by a tab, followed by the Unicode\n characters that should be mapped to it. After the transliteration,\n the line should contain all the same characters with one tab\n character.\n '''\n f = open(file, \"w\")\n for key in decomp:\n keep[decomp[key]].add(key)\n for key in keep:\n u = ''.join([chr(i) for i in keep[key]])\n print(f\"{key}\\t{u}\", file=f)\n print(f\"Wrote '{file}'\", file=sys.stderr)\n\nif __name__ == \"__main__\": \n d = {} # Options dictionary\n args = ParseCommandLine(d)\n decomp = {} # Codepoints that could be decomposed\n trans = {} # Contains the final translate dictionary\n fmt = \" {:30s} {:8d}\" # Used for debug printing to stderr\n # If select is True, only do the tasks currently being worked on\n select = True if d[\"-s\"] else False\n # Set to 0 for no debug output, 1 for only title & result, 2 for all\n dbg = d[\"-d\"]\n stream = sys.stdout\n GetTranslations()\n","repo_name":"someonesdad1/plib","sub_path":"asciify_make.py","file_name":"asciify_make.py","file_ext":"py","file_size_in_byte":36172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"43357609656","text":"import random\n\n\ndef tester_premier(nombre: int):\n \"\"\"Retourner si un nombre est premier ou pas\n\n Args:\n nombre (int): nombre a verifier\n\n Returns:\n _type_: True or False\n \"\"\"\n premier = True\n if nombre == 1:\n premier = False\n else:\n i = 2\n while i < nombre and premier == True:\n if nombre % i == 0:\n premier = False\n i += 1\n else:\n i += 1\n return premier\n\n\ndef afficher_premier(liste: list):\n \"\"\"Afficher la liste des nombres premiers d'une liste\n\n Args:\n liste (list): liste des nombres a verifier\n\n Returns:\n _type_: liste des nombres premiers\n \"\"\"\n result = []\n for value in liste:\n if tester_premier(value) == True:\n result.append(value)\n return result\n\n\nif __name__ == '__main__':\n \"\"\"Create a random list and print \"nombres premiers\"\n \"\"\"\n random_list = [random.randint(1, 100) for _ in range(10)]\n print(\"Random liste: \", random_list)\n result = afficher_premier(random_list)\n print(\"Liste des nombres premier: \", result)\n","repo_name":"mbayedione10/PythonCodingChallenge","sub_path":"tester_premier.py","file_name":"tester_premier.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"57"} +{"seq_id":"24923273822","text":"'''парсинг еис\nскачивание номеров контрактов\n'''\nimport time\nfrom selenium import webdriver\nimport pickle\n\npage = 'https://zakupki.gov.ru/epz/contract/search/results.html'\n\n\ndriver = webdriver.Chrome()\ndriver.implicitly_wait(100) # ждем столько, если не справился заканчиваем?\n\ndriver.get(page)\n\ndef first_setting():\n # Настройка параметров поиска\n # Клики по \"квадратикам\"\n # Настройка на количество страниц 50 шт.\n param_list = ['//*[@id=\"contractStageListTag\"]/div/div[2]/div[4]/label',\n '//*[@id=\"contractStageListTag\"]/div/div[2]/div[1]/label',\n '//*[@id=\"contractStageListTag\"]/div/div[2]/div[3]/label',\n '//*[@id=\"quickSearchForm_header\"]/section[2]/div/div/div[1]/div[4]/div/div[2]/div/div[2]/div[1]/span',\n '//*[@id=\"_50\"]']\n\n [driver.find_element_by_xpath(el).click() for el in param_list]\n\n\n # Выбор Города\n citi_chose = '//*[@id=\"customerPlaceAnchor\"]'\n driver.find_element_by_xpath(citi_chose).click()\n print('Два *')\n citi_input = '//*[@id=\"goodssearch\"]'\n driver.find_element_by_xpath(citi_input).send_keys('Санкт-Петербург')\n aply_btn = '//*[@id=\"btn-floating\"]/button'\n print('вставили спб *')\n time.sleep(1) # Нужно подождать пока найдет СПБ\n spb_cell = '//*[@id=\"mCSB_2_container\"]/ul/li[2]/span'\n driver.find_element_by_xpath(spb_cell).click()\n print('кликнули спб *')\n aply_btn = '//*[@id=\"modal-okdp-okved\"]/div/div[4]/div/div/button[2]'\n driver.find_element_by_xpath(aply_btn).click()\n print('Применили')\n\ndef clear_dateform():\n # очистка формы даты (нажать на кнопу \"до\" и пустую часть)\n date_form = '//*[@id=\"contractDateTag\"]/div/div/div'\n driver.find_element_by_xpath(date_form).click()\n date_set_to = '//*[@id=\"calendarDays\"]/div[1]/button[2]'\n driver.find_element_by_xpath(date_set_to).click()\n driver.find_element_by_xpath(\"//html\").click()\n\ndef clear_dateform2():\n # очистка формы даты (нажать на кнопу \"от\" и пустую часть)\n date_form = '//*[@id=\"contractDateTag\"]/div/div/div'\n driver.find_element_by_xpath(date_form).click()\n date_set_to = '//*[@id=\"calendarDays\"]/div[1]/button[1]'\n driver.find_element_by_xpath(date_set_to).click()\n driver.find_element_by_xpath(\"//html\").click()\n\ndef date_input(d_from, d_to):\n # Выбор даты\n date_form = '//*[@id=\"contractDateTag\"]/div/div/div'\n driver.find_element_by_xpath(date_form).click()\n driver.find_element_by_xpath(date_form).click()\n date_set_to = '//*[@id=\"calendarDays\"]/div[1]/button[2]'\n driver.find_element_by_xpath(date_set_to).click()\n date_from = '//*[@id=\"contractDateTag\"]/div/div/div/div[1]/input'\n driver.find_element_by_xpath(date_from).send_keys(d_from)\n date_to = '//*[@id=\"contractDateTag\"]/div/div/div/div[2]/input'\n driver.find_element_by_xpath(date_to).send_keys(d_to)\n driver.find_element_by_xpath(date_form).click()\n driver.find_element_by_xpath(\"//html\").click()\n aply_btn = '//*[@id=\"btn-floating\"]/button'\n driver.find_element_by_xpath(aply_btn).click()\n\ndef read_amount():\n # Смотрим, сколько вариантов нашлось\n found_list = []\n result = '//*[@id=\"quickSearchForm_header\"]/section[2]/div/div/div[1]/div[1]/div[2]'\n result = driver.find_element_by_xpath(result)\n found_list = [el for el in result.text if el in {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}]\n #print(int(\"\".join(found_list)))\n return int(\"\".join(found_list))\n\ndef page_data_save(file_name):\n # Чтение и запись номеров контрактов\n # считываем все номера со страницы\n cells = '//div[@class=\"registry-entry__header-mid__number\"]'\n numbers = driver.find_elements_by_xpath(cells)\n # записываем все \"чистые\" номера во множество\n numersss = set()\n for el in numbers:\n split_el = str(el.text.split(\" \")[1])\n numersss.add(split_el)\n # Пытаемся открыть файл .pkl если есть\n pickle_set = {}\n try:\n with open(file_name, 'rb') as f:\n pickle_set = pickle.load(f)\n numersss |= pickle_set\n except:\n print('no file')\n\n # добавляем в файл pkl\n with open(file_name, 'wb') as f:\n pickle.dump(numersss, f, pickle.HIGHEST_PROTOCOL)\n print(f'Всего в файле: {len(numersss)} номеров')\n #print(numersss)\n\n###\n### Рабочая часть\n###\n# Формируем список из дат (365 дней) = days_list\nmax_days_list = [31, 27, 31, 30, 31, 30, 31, 31, 30] # до сент., 31, 30, 31 #\n# на сайте нет 28 февраля!!\nmounth_count = 2\nyear_str = '2021'\ndays_list = []\nfor month in max_days_list:\n # добавляем '0' к месяцу\n if len(str(mounth_count)) >= 2:\n monthe = str(mounth_count)\n else:\n monthe = '0' + str(mounth_count)\n mounth_count += 1\n for day in range(month):\n # добавляем '0' к дню\n if len(str(day + 1)) >= 2:\n day_str = str(day + 1)\n else:\n day_str = '0' + str(day + 1)\n days_list.append(f'{day_str}.{monthe}.{year_str}')\n\n\nfirst_setting()\n#a = input('Проверьте настройки и введите, что нибудь для продолжения')\n\n# Выводит нужные даты если не подходит, то \"до\" уменьшается на 1 день\nfirst_value = 5 # стандартная разница между датами (от 01 до 05)\nstep = first_value\nday_index = 101 # начинаем с **.**.2021\nperiod = 0\nerror_date = []\n\nsum_kontrakts = 0\npkl_name_part = 9\n\n# перебор всех дат\nwhile day_index < len(days_list):\n pre_index = day_index # что бы переписать даты\n day_from = days_list[day_index]\n day_index += step\n if day_index >= len(days_list):\n day_index = len(days_list) - 1\n day_to = days_list[day_index]\n day_index += 1\n period = day_index - pre_index\n # вставляем даты в поисковик\n date_input(day_from, day_to)\n some_text = read_amount()\n print(f'от: {day_from} до: {day_to}, контрактов: {some_text}')\n # Проверяем, что бы значений было меньше\n if some_text > 999 and period > 1:\n day_index = pre_index\n step -= 1\n clear_dateform()\n else:\n if period < 2 and some_text > 999:\n error_date.append([day_from, day_to])\n print('--- Период = 1, контрактов больше 999!!')\n ## Начинаем цикл с перелистыванием и парсингом\n pars_pages_stat = 0\n page_number = 0\n print(f'Записываем в файл № {pkl_name_part}')\n print(f'Кол-во контрактов: {some_text}')\n while pars_pages_stat == 0:\n # Перелистывание страницы\n page_data_save('contra/pkl_' + str(pkl_name_part) + '.pkl')\n xp_pg_nums = '//*[@id=\"quickSearchForm_header\"]/section[2]/div/div/div[1]/div[4]/div/div[1]/ul/a'\n pg_num = driver.find_elements_by_xpath(xp_pg_nums)\n # ловим стрелку перемотки\n if page_number != 0:\n # если это не первая страница - в списке две стрелки\n if len(pg_num) == 2:\n pg_num[1].click()\n page_number += 1\n else:\n # в списке одна стрелка и стр. не №1 = последняя стр.\n print('Закончили перелистывать')\n pkl_name_part += 1\n pars_pages_stat = 1\n else:\n # если это первая страница - в списке одна стрелка - сслыка\n pg_num[0].click()\n page_number += 1\n #\n\n print(f'Скачали: {some_text} шт. за период {period} дн.')\n sum_kontrakts += some_text\n print(f'Всего скачано: {sum_kontrakts} шт.')\n step = first_value\n if period == 1:\n clear_dateform2()\n else:\n clear_dateform()\n\n ##\n #pkl_name_part += 1\n\n\n\nprint(error_date)\n","repo_name":"Griga178/gitdev","sub_path":"old/sql/eis_parse.py","file_name":"eis_parse.py","file_ext":"py","file_size_in_byte":8831,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"12775567250","text":"import unittest\nfrom ical.utilities import Ical\n\nTEST_FILE = \"tests/binfeed.ical\"\nTEST_URL = \"https://s3-eu-west-1.amazonaws.com/fs-downloads/GM/binfeed.ical\"\n\nclass TestIcal(unittest.TestCase):\n def test_file_loading(self):\n \"\"\"Test if the load from disk.\n \"\"\"\n try:\n cal = Ical(TEST_FILE)\n except:\n self.assertTrue(False)\n\n def test_url_loading(self):\n \"\"\"Test the load from url.\n \"\"\"\n try:\n cal = Ical(TEST_URL)\n except:\n self.assertTrue(False)\n\n def test_no_solution(self):\n \"\"\"Test when there is no solutions.\n \"\"\"\n calendar = Ical(TEST_FILE)\n events = calendar.get_next_bin(2020, 12, 25)\n self.assertTrue(not events)\n\n def test_one_bin(self):\n \"\"\"Test when there is just one solution.\n \"\"\"\n calendar = Ical(TEST_FILE)\n events = calendar.get_next_bin(2018, 1, 16)\n self.assertFalse(not events)\n self.assertEqual(1, len(events))\n\n def test_two_bin(self):\n \"\"\"Test when there are two solutions.\n \"\"\"\n calendar = Ical(TEST_FILE)\n events = calendar.get_next_bin(2018, 5, 28)\n self.assertFalse(not events)\n self.assertEqual(2, len(events))\n\n def test_regularity(self):\n uids = [\"20180103T190905GMT-4437IlTejd@192.124.249.105\",\n \"20180103T190905GMT-4463fruaVC@192.124.249.105\"]\n calendar = Ical(TEST_FILE)\n events = calendar.get_next_bin(2018, 5, 28)\n for e in events:\n uid = e.get(\"UID\").to_ical().decode(\"utf-8\")\n self.assertTrue(uid in uids)\n","repo_name":"AlEmerich/ical","sub_path":"tests/test_sample.py","file_name":"test_sample.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"7903264534","text":"from django.contrib import admin\nfrom django.contrib.auth.views import LoginView, LogoutView\nfrom django.urls import path, include\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', include('generator.urls')),\n path('login/', LoginView.as_view(template_name='login.html'), name='login'),\n path('login/github_callback/', include('userprofile.urls')),\n path('logout/', LogoutView.as_view(), name='logout'),\n \n]\n","repo_name":"soil7800/keygen-demo","sub_path":"keygen/keygen/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"9348832874","text":"from django.http import JsonResponse\nfrom django.shortcuts import render\n\nfrom .convert import xml_to_dict\nfrom .forms import SubmissionForm\n\n\ndef upload_page(request):\n if request.method == 'POST':\n form = SubmissionForm(request.POST, request.FILES)\n if form.is_valid():\n submission = request.FILES.get('file')\n response = xml_to_dict(submission)\n if response:\n return JsonResponse(response, content_type='application/json')\n else:\n return JsonResponse({}, status=400, content_type='application/json')\n\n\n form = SubmissionForm()\n return render(request, \"upload_page.html\", {'form': form})\n","repo_name":"ignacio-sanchez-dev/calandria","sub_path":"xml_converter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"26686286237","text":"from pycinema import Filter\n\nfrom .FilterView import FilterView\n\nfrom PySide6 import QtCore, QtWidgets\n\nimport numpy\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as pp\n\nclass ColorMappingView(Filter, FilterView):\n\n def __init__(self):\n FilterView.__init__(\n self,\n filter=self,\n delete_filter_on_close = True\n )\n\n Filter.__init__(\n self,\n inputs={\n 'images': [],\n 'channel': 'rgba',\n 'map': 'plasma',\n 'range': (0,1),\n 'nan': (1,1,1,1),\n 'composition_id': -1\n },\n outputs={\n 'images': []\n }\n )\n\n def generateWidgets(self):\n self.widgetsDict = {}\n self.widgets = QtWidgets.QFrame()\n l = QtWidgets.QGridLayout()\n l.setAlignment(QtCore.Qt.AlignTop)\n l.setSpacing(0)\n l.setContentsMargins(0,0,0,0)\n self.widgets.setLayout(l)\n\n self.content.layout().addWidget(self.widgets)\n\n gridL = self.widgets.layout()\n row = 0\n\n w = QtWidgets.QComboBox()\n self.widgetsDict['channel'] = w\n w.channels = []\n gridL.addWidget(QtWidgets.QLabel(\"Channel\"),row,0)\n gridL.addWidget(w,row,1)\n w.on_text_changed = lambda v: self.inputs.channel.set(v)\n w.currentTextChanged.connect( w.on_text_changed )\n row += 1\n\n w = QtWidgets.QComboBox()\n self.widgetsDict['map'] = w\n gridL.addWidget(QtWidgets.QLabel(\"Color Map\"),row,0)\n gridL.addWidget(w,row,1)\n maps = [map for map in pp.colormaps() if not map.endswith('_r')]\n maps.sort(key=lambda x: x.lower())\n w.addItems(\n maps\n )\n w.currentTextChanged.connect( lambda v: self.inputs.map.set(v) )\n row += 1\n\n # RANGE\n f = QtWidgets.QFrame()\n f.setLayout( QtWidgets.QHBoxLayout())\n gridL.addWidget(QtWidgets.QLabel(\"Range\"),row,0)\n gridL.addWidget(f,row,1)\n\n w0 = QtWidgets.QLineEdit()\n w1 = QtWidgets.QLineEdit()\n self.widgetsDict['range'] = [w0,w1]\n l = lambda v: self.inputs.range.set( (float(w0.text()), float(w1.text())) )\n w0.textEdited.connect(l)\n w1.textEdited.connect(l)\n f.layout().addWidget(w0)\n f.layout().addWidget(w1)\n row+=1\n\n # NAN COLOR\n def select_color():\n w = self.widgetsDict['nan']\n clrpick = QtWidgets.QColorDialog()\n clrpick.setOption(QtWidgets.QColorDialog.DontUseNativeDialog)\n color = clrpick.getColor()\n color = (w.format(color.redF()),w.format(color.greenF()),w.format(color.blueF()),w.format(color.alphaF()))\n w.setText(str(color))\n self.inputs.nan.set(color)\n\n w = QtWidgets.QPushButton()\n w.clicked.connect(select_color)\n w.format = lambda v: float(\"{:.3f}\".format(v))\n self.widgetsDict['nan'] = w\n gridL.addWidget(QtWidgets.QLabel(\"NAN Color\"),row,0)\n gridL.addWidget(w,row,1)\n row += 1\n\n def update_widgets(self,images):\n self.widgetsDict['map'].setCurrentText(self.inputs.map.get())\n self.widgetsDict['range'][0].setText(str(self.inputs.range.get()[0]))\n self.widgetsDict['range'][1].setText(str(self.inputs.range.get()[1]))\n self.widgetsDict['nan'].setText(str(self.inputs.nan.get()))\n\n # channels\n channels = set({})\n for i in images:\n for c in i.channels:\n channels.add(c)\n new_channels = list(channels)\n new_channels.sort()\n\n w = self.widgetsDict['channel']\n w.currentTextChanged.disconnect( w.on_text_changed )\n w.clear()\n for c in new_channels:\n w.addItem(c)\n w.channels = new_channels\n w.currentTextChanged.connect( w.on_text_changed )\n channel = self.inputs.channel.get()\n if channel in new_channels:\n w.setCurrentText( channel )\n else:\n self.inputs.channel.set(new_channels[0])\n w.setCurrentText( new_channels[0] )\n\n def _update(self):\n i_images = self.inputs.images.get()\n if len(i_images)<1:\n self.outputs.images.set([])\n return 1\n\n self.update_widgets(i_images)\n\n i_channel = self.inputs.channel.get()\n i_map = self.inputs.map.get()\n i_nan = self.inputs.nan.get()\n i_composition_id = self.inputs.composition_id.get()\n\n nanColor = numpy.array(tuple([f * 255 for f in i_nan]),dtype=numpy.uint8)\n\n cmap = cm.get_cmap( i_map )\n cmap.set_bad(color=i_nan )\n i_range = self.inputs.range.get()\n d = i_range[1]-i_range[0]\n\n o_images = []\n for i_image in i_images:\n if not i_channel in i_image.channels or i_channel=='rgba':\n o_images.append(i_image)\n continue\n\n normalized = (i_image.channels[ i_channel ]-i_range[0])/d\n if i_channel == 'depth':\n normalized[i_image.channels[i_channel]==1] = numpy.nan\n\n o_image = i_image.copy()\n if i_composition_id>=0 and 'composition_mask' in o_image.channels:\n rgba = None\n if 'rgba' not in o_image.channels:\n rgba = numpy.full((o_image.shape[0],o_image.shape[1],4), nanColor, dtype=numpy.uint8)\n o_image.channels['rgba'] = rgba\n else:\n rgba = o_image.channels['rgba']\n\n mask = o_image.channels['composition_mask']==i_composition_id\n rgba[mask] = cmap(normalized[mask], bytes=True)\n else:\n o_image.channels[\"rgba\"] = cmap(normalized, bytes=True)\n\n o_images.append(o_image)\n\n self.outputs.images.set(o_images)\n\n return 1\n","repo_name":"cinemascience/pycinema","sub_path":"pycinema/theater/views/ColorMappingView.py","file_name":"ColorMappingView.py","file_ext":"py","file_size_in_byte":5837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"57"} +{"seq_id":"17718531082","text":"# 练习:累加10 -- 60 之间,个位不是3/5/8的整数和。\nsum=0\nfor item in range(10,61):\n number=item%10\n if number==3 or number==5 or number==8:\n continue\n else:\n sum+=number\n print(sum)\n'''sum = 0\nfor item in range(10, 61):\n value = item % 10\n # 如果个位是3或者5或者8则跳过\n if value == 3 or value == 5 or value == 8:\n continue\n sum += item\nprint(sum)'''\n","repo_name":"singerdo/songers","sub_path":"第一阶段/课上实例练习/day04/exercise04.py","file_name":"exercise04.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"38627077878","text":"#Question 2.a\nn=int(input(\"Enter the size of the list\"))\nl=[]\na=0\nprint(\"Enter the elements of the list \")\nfor i in range(0,n):\n a=int(input())\n l.append(a)\nmax1=l[0]\nfor i in range(0,n):\n if(l[i]>max1):\n max1=l[i]\nprint(\"maximum number Without using standard function\",max1)\n\nprint(\"maximum number Using standard function:\",max(l))\n","repo_name":"sanyukta001/pythonprogs","sub_path":"pracexamq2a.py","file_name":"pracexamq2a.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"12301115812","text":"def goldMining(n, w, g, p):\n\tresults = []\t\t\t\t\t#保存返回结果的数组\n\tpreResults = []\t\t\t\t#保存上一行结果的数组\n\tfor i in range(0,w):\t\t\t#填充边界格子的值,从左向��填充表格第一行的内容\n\t\tresults.append(0)\t\t#初始化结果数组\n\t\tif i < p[0]:\t\n\t\t\tpreResults.append(0)\t#若人数少于第一个金矿所需人数,黄金量为0\n\t\telse:\n\t\t\tpreResults.append(g[0])\t#若人数不少于第一个金矿所需人数,黄金量为g[0]\n\n\tfor i in range(0,n):\t\t\t#外层循环为金矿数量\n\t\tfor j in range(0,w):\t\t#外层循环为矿工数量\n\t\t\tif j < p[i]:\n\t\t\t\tresults[j] = preResults[j]\n\t\t\telse:\n\t\t\t\tresults[j] = Math.max(preResults[j], preResults[j-p[i]] + g[i])\n\t\tpreResults = results\n\treturn results","repo_name":"sure0328/pythonAlgorithm","sub_path":"code/第八章/8-2.py","file_name":"8-2.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"zh","doc_type":"code","stars":5,"dataset":"github-code","pt":"57"} +{"seq_id":"5500327884","text":"import os\nos.chdir('../')\n\nimport sys\nsys.path.append('/home/njr61/rds/hpc-work/spurious-concepts/ConceptBottleneck')\nsys.path.append('/home/njr61/rds/hpc-work/spurious-concepts')\n\nimport torch\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.neural_network import MLPClassifier\nimport torch.nn as nn\nimport torch.optim as optim\nimport pickle\nimport matplotlib.pyplot as plt\nimport torch.nn.functional as F\nfrom PIL import Image\nfrom captum.attr import visualization as viz\nfrom matplotlib.colors import LinearSegmentedColormap\nimport cv2\nfrom copy import copy \nimport itertools\nimport json\nimport argparse\n\nfrom ConceptBottleneck.CUB.models import ModelXtoC, ModelOracleCtoY\n\nfrom src.images import *\nfrom src.util import *\nfrom src.models import *\nfrom src.plot import *\n\n# ## General Setup\n\nnoisy=False\nweight_decay = 0.0004\noptimizer = 'sgd'\n\nparser = argparse.ArgumentParser(description=\"Your script description here\")\n\n# Add command-line arguments\nparser.add_argument('--num_objects', type=int, default=2, help='Number of objects')\nparser.add_argument('--seed', type=int, default=42, help='Random seed')\n\n# Parse the command-line arguments\nargs = parser.parse_args()\n\n# Now you can access the variables using args.num_objects, args.noisy, etc.\nnum_objects = args.num_objects\nseed = args.seed\n\nnp.random.seed(seed)\ntorch.manual_seed(seed)\n\n# +\nresults_folder = \"results/explanations/objects={}_seed={}\".format(\n num_objects,seed\n)\n\nif not os.path.exists(results_folder):\n os.makedirs(results_folder)\n# -\n\n# ## Compare methods\n\n# +\nclean_intensities = {}\ndirty_intensities = {}\ndistances = {}\nconcept_num = 0\n\ntrain_loader, val_loader, train_pkl, val_pkl = get_data(num_objects, noisy)\nval_images, val_y, val_c = unroll_data(val_loader)\n\ndata_points = []\nbinary_combos = list(itertools.product([0, 1], repeat=num_objects))\nfor combo in binary_combos:\n as_tensor = []\n\n for k in combo:\n as_tensor.append(k)\n as_tensor.append(1-k)\n\n data_points.append(torch.where(torch.all(val_c == torch.Tensor(as_tensor), dim=1))[0][0].item())\n\njoint_model_small = get_synthetic_model(num_objects,'small3',noisy,weight_decay,optimizer,seed)\njoint_model_large = get_synthetic_model(num_objects,'small7',noisy,weight_decay,optimizer,seed)\n\nfor method in [plot_saliency,plot_gradcam,plot_integrated_gradients]:\n str_method = {plot_integrated_gradients: 'integrated gradients', plot_gradcam: 'gradcam',plot_saliency: 'saliency'}[method]\n clean_intensities['{}'.format(str_method)] = []\n dirty_intensities['{}'.format(str_method)] = []\n distances['{}'.format(str_method)] = []\n\n for i in data_points:\n gradcam_intensities_clean = method(joint_model_small,run_joint_model,concept_num,val_images,i,val_pkl,plot=False)\n gradcam_intensities_clean -= np.min(gradcam_intensities_clean)\n gradcam_intensities_clean = gradcam_intensities_clean/np.max(gradcam_intensities_clean)\n clean_patches = get_patches(gradcam_intensities_clean,64)\n\n\n gradcam_intensities_dirty = method(joint_model_large,run_joint_model,concept_num,val_images,i,val_pkl,plot=False)\n gradcam_intensities_dirty -= np.min(gradcam_intensities_dirty)\n gradcam_intensities_dirty = gradcam_intensities_dirty/np.max(gradcam_intensities_dirty)\n dirty_patches = get_patches(gradcam_intensities_dirty,64) \n\n clean_intensities['{}'.format(str_method)].append(np.sum(clean_patches[:,:2])/(np.sum(clean_patches)))\n dirty_intensities['{}'.format(str_method)].append(np.sum(dirty_patches[:,:2])/(np.sum(dirty_patches)))\n\n distances['{}'.format(str_method)].append(compute_wasserstein_distance(clean_patches,dirty_patches))\n# -\n\ngradcam_intensities_clean=gradcam_intensities_clean/np.max(gradcam_intensities_clean )\n\njson.dump({\n 'distances': distances, \n 'small_intensities': clean_intensities, \n 'large_intensities': dirty_intensities, \n}, open(\"{}/{}.json\".format(results_folder,'evaluation'),\"w\"))\n\n\n","repo_name":"naveenr414/Spurious-Concepts","sub_path":"scripts/analyze_explanations.py","file_name":"analyze_explanations.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"16558597643","text":"from django.shortcuts import render\nfrom .forms import StudentForm\nfrom .models import Student\n# Create your views here.\n\ndef home_page_view(request) :\n form=StudentForm()\n if request.method=='POST' :\n form=StudentForm(request.POST)\n if form.is_valid() :\n form.save(commit=True)\n form=StudentForm()\n return render(request,'ModelApp/home.html',{'form':form})\n\ndef list_view(request) :\n list_obj=Student.objects.all()\n return render(request,'ModelApp/list.html',{'list_obj':list_obj})\n","repo_name":"supriya-adik/StudentModelForm_project","sub_path":"ModelFormProject/ModelApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"72043640177","text":"import argparse\nfrom pathlib import Path\n\n\nbakery_path = Path().resolve().joinpath('data/task_4/bakery.csv')\n\nparser = argparse.ArgumentParser(description='Записывает сумму продаж в базу.')\nparser.add_argument('sum', help='Сумма продаж')\n\nargs = parser.parse_args()\n\nwith open(bakery_path, mode='at', encoding='UTF-8') as bakery_file:\n bakery_file.write(args.sum + '\\n')\n\n","repo_name":"k33p3r-78/course-1","sub_path":"lesson_6/task_4_add_sale.py","file_name":"task_4_add_sale.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"21449165593","text":"import discord\r\nfrom discord import *\r\nfrom discord.ext import commands\r\nimport requests\r\n\r\nbot = commands.Bot(command_prefix=\"dss/\", intents = discord.Intents.all())\r\n\r\n@bot.event\r\nasync def on_ready():\r\n await bot.change_presence( status = discord.Status.idle, activity = discord.Game('Bot started'))\r\n print(f'Bot: {bot.user.name} connected!')\r\n\r\n@bot.command()\r\nasync def status(ctx):\r\n sql_status_url = 'http://dragonfire.7m.pl/api/checkSqlStatus.php'\r\n webserver_status_url = 'http://dragonfire.7m.pl/api/checkWebServer.php'\r\n\r\n sql_status_check = requests.get(sql_status_url)\r\n webserver_status_check = requests.get(webserver_status_url)\r\n\r\n embed = discord.Embed(\r\n title = 'DragonFire servers status',\r\n description = f'SQL Status (dragonfire.7m.pl): { sql_status_check.status_code }\\n Webserver status (dragonfire.7m.pl): { webserver_status_check.status_code }',\r\n colour = discord.Colour.from_rgb(139, 0, 0)\r\n )\r\n await ctx.send(embed=embed)\r\n \r\nbot.run(f'ODg4Nzg4MjE2MTg5MTY1NjIw.YUXyhw.IIjh08UbkqfOYc31C_ZXlys0J2k')\r\n","repo_name":"CNORIX/dragon-cnorix.bot","sub_path":"src/DragonServerStatus.py","file_name":"DragonServerStatus.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"29138589772","text":"#!/usr/bin/env python\n\"\"\"Test Selenium tests JS errors detection logic.\"\"\"\n\nfrom absl import app\n\nfrom grr_response_server.gui import gui_test_lib\nfrom grr.test_lib import test_lib\n\n\nclass JavascriptErrorTest(gui_test_lib.GRRSeleniumTest):\n \"\"\"Tests that Javascript errors are caught in Selenium tests.\"\"\"\n\n def testJavascriptErrorTriggersPythonException(self):\n self.Open(\"/legacy\")\n\n # Erase global Angular object.\n # Things are guaranteed to stop working correctly after this.\n self.GetJavaScriptValue(\"window.angular = undefined;\")\n\n with self.assertRaisesRegex(self.failureException,\n \"Javascript error encountered\"):\n # Note that self.Click(), can, on rare occasions, trigger a\n # Javascript error, because of tickers that are running on the page.\n self.Click(\"client_query_submit\")\n self.WaitUntil(self.IsElementPresent, \"css=grr-clients-list\")\n\n # The page has some tickers running that also use Angular so there\n # is a race that they can cause more js errors after the test has\n # already finished. By navigating to the main page, we make sure\n # the Angular object is valid again which means no more errors and\n # also clear the list of recorded errors in case there have been\n # any in the meantime.\n self.Open(\"/legacy\")\n\n\nif __name__ == \"__main__\":\n app.run(test_lib.main)\n","repo_name":"google/grr","sub_path":"grr/server/grr_response_server/gui/selenium_tests/js_error_test.py","file_name":"js_error_test.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":4531,"dataset":"github-code","pt":"57"} +{"seq_id":"30664769468","text":"# Use 'ISO-8859-1' instead of \"utf-8\" for decoding\nimport json\nimport logging\nimport os\nimport time\nimport csv\nimport datetime\nimport uuid\nimport requests\nfrom key_handler import KeyHandler\nimport sqlite3\nfrom sqlite3 import Error\n\nimport jsonschema\nfrom jsonschema import validate\n\nimport pandas as pd\n\nglobal logger\n\n\ntimerecord = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')\nsubscriptionId = \"2d622ff4-5c89-41e7-890a-eaf62c787df6\" \n\naccentedCharacters = \"àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇߨøÅ寿œ\"\nfilterPatterns =\"^([.,#A-Za-z \" + accentedCharacters + \"0-9 _-]+)$\" \nstate = \"^([A-Za-z]+)$\"\nschema = {\n 'title': 'Eva WithPrivacyNotice V2',\n 'type': 'object',\n 'required': [\"privacyNotice\",\"employmentVerification\"],\n 'properties': {\n 'privacyNotice':{\n 'type': \"object\",\n 'required': ['fullName', 'address', 'acceptance', 'acceptanceDate'],\n 'properties': {\n 'fullName':{\n 'type': \"object\",\n 'required': ['firstName', 'firstSurname', 'secondSurname'],\n 'properties': {\n 'firstName':{ 'type': 'string',\"pattern\": \"^[A-Za-z \" + accentedCharacters + \"0-9\\s]+$\", 'minLength': 1},\n 'middleName':{ 'type': ['string','null'],\"pattern\": \"^[A-Za-z \" + accentedCharacters + \"0-9\\s]+$\", 'minLength': 1},\n 'firstSurname':{'type': 'string',\"pattern\": \"^[A-Za-z \" + accentedCharacters + \"0-9\\s]+$\"},\n 'secondSurname':{ 'type': 'string',\"pattern\": \"^[A-Za-z \" + accentedCharacters + \"0-9\\s]+$\", 'minLength': 1},\n 'aditionalSurname':{'type': ['string','null'],\"pattern\": \"^[A-Za-z \" + accentedCharacters + \"0-9\\s]+$\"}\n }\n },\n 'address': {\n 'type': 'object',\n 'required': [\"streetAndNumber\",\"settlement\",\"county\",\"city\",\"state\",\"postalCode\"],\n 'properties': {\n 'streetAndNumber': {'type': \"string\",'pattern': filterPatterns, 'minLength':2, 'maxLength':40},\n 'settlement':{'type': \"string\",'pattern': filterPatterns, 'minLength':2, 'maxLength':60},\n 'county':{'type': \"string\",'pattern': filterPatterns, 'minLength':2, 'maxLength':60},\n 'city':{'type': \"string\",'pattern': filterPatterns, 'minLength':2, 'maxLength':40},\n 'state':{'type': \"string\",'pattern': state , 'minLength':2, 'maxLength':4},\n 'postalCode':{'type': \"string\",'pattern': '^\\\\d{5}$' , 'minLength':5, 'maxLength':10}\n }\n },\n 'acceptance':{'type':['string'], \"enum\":[\"Y\",\"N\"]},\n 'acceptanceDate': { 'type': ['string'], 'pattern': \"^[1-9]\\d{3}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{2}Z$\" }\n }\n },\n 'employmentVerification':{\n 'type': \"object\",\n 'required': ['employmentVerificationRequestId', 'subscriptionId', 'curp', 'email'],\n 'properties': {\n 'employmentVerificationRequestId': { 'type': ['string'], 'pattern': '^[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}$' },\n 'subscriptionId': { 'type': ['string'], 'pattern': '^[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}$' },\n 'curp': { 'type': ['string'], \"pattern\": '^[A-Z][AEIOUX][A-Z]{2}[0-9]{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])[MH]([ABCMTZ]S|[BCJMOT]C|[CNPST]L|[GNQ]T|[GQS]R|C[MH]|[MY]N|[DH]G|NE|VZ|DF|SP)[BCDFGHJ-NP-TV-Z]{3}[0-9A-Z][0-9]$'},\n 'nss': { 'type': ['string','null'], 'pattern': '^\\d{11}$' },\n 'email': { 'type': ['string'], 'maxLength':80,'minLength':3, \"pattern\": \"\"\"^(?:[a-z0-9!#$%&'*+/=?^_`{|}~]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$\"\"\" }\n }\n }\n }\n}\n\nglobal countError\ncountError=0\n\n\ndef csv_to_json(csvFilePath):\n\n logger.info(\"Read file %s init\" % (csvFilePath))\n jsonArray = []\n #read csv file\n with open(csvFilePath, encoding='UTF-8') as csvf: \n #load csv file data using csv library's dictionary reader\n #csvReader = csv.DictReader(csvf,delimiter='|', quoting=csv.QUOTE_NONE) \n csvReader = csv.DictReader(csvf) \n \n #convert each csv row into python dict\n for row in csvReader: \n #add this python dict to json array\n item={}\n for k, v in row.items():\n item[k.strip()]=v.strip()\n jsonArray.append(item)\n \n #convert python jsonArray to JSON String and write to file\n\n logger.info(\"Read file %s end\" % (csvFilePath))\n return (jsonArray)\n\n\n\ndef initialize_logger():\n global logger\n format_colors = '%(asctime)s %(levelname)7s %(process)5d %(filename)20s %(lineno)3d %(message)s'\n logging.basicConfig(filename=f'logs/depurar_{timerecord}.log', format=format_colors, filemode='w', level=logging.INFO)\n logger = logging.getLogger()\n\ndef validateJson(jsonData):\n global countError\n try:\n validate(instance=jsonData, schema=schema)\n except jsonschema.exceptions.ValidationError as err:\n print(err)\n \n countError = countError + 1\n logger.info(f'Error: {err}' )\n return False\n return True\n\ndef main():\n global logger\n global countError\n start_time = time.time()\n initialize_logger()\n \n\n array = csv_to_json(file_path)\n count = 0\n for item in array:\n #print(item)\n logger.info(\"\\n-------------------------------------------------------------------------------------------------------------------------------\")\n \n requestId=str(uuid.uuid4())\n\n logger.info(f'RequestId: {requestId}')\n \n logger.info(f'Orign: {item}')\n jsonObj ={\n \"privacyNotice\": {\n \"fullName\": {\n \"firstName\": item['primerNombre'],\n \"firstSurname\": item['apellidoPaterno'],\n \"secondSurname\": item['apellidoMaterno']\n },\n \"address\": {\n \"streetAndNumber\": item['calleNumero'],\n \"settlement\": item['colonia'],\n \"county\": \"MX\",\n \"city\": item['ciudad'],\n \"state\": item['estado'],\n \"postalCode\": item['codigoPostal'].zfill(5)\n },\n \"acceptanceDate\": item['fechaHoraAceptacion'],\n \"acceptance\": item['aceptacion']\n },\n \"employmentVerification\": {\n \"employmentVerificationRequestId\": requestId,\n \"subscriptionId\": subscriptionId,\n \"curp\": item['curp'],\n \"nss\": \"92919084431\",\n \"email\": item['email']\n }\n }\n isValid = validateJson(jsonObj)\n if isValid == False:\n logger.info(f'[{str(count)}] Request {isValid}: {jsonObj}' )\n count = count +1\n\n \n \n \n\n logger.info(f'Total Errores: {str(countError)} ')\n logger.info(\"Total %s seconds execution\" % (time.time() - start_time))\n\nif __name__ == '__main__':\n main()","repo_name":"dramon-z/test_0001","sub_path":"depurar.py","file_name":"depurar.py","file_ext":"py","file_size_in_byte":7542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"74204921138","text":"\"\"\"\n@author: Zsofia Koma, UvA\nAim: apply Random Forest for classifying segments into given vegetation classes\n\nInput: path of polygon with segment related features + label\nOutput: accuracy report, feature importance, classified shapefile \n\nExample usage (from command line): \n\nToDo: \n1. automatize feature_list definition\n\"\"\"\n\nimport sys\nimport argparse\n\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nfrom geopandas.tools import sjoin\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score,precision_score,recall_score\nfrom sklearn.metrics import classification_report\n\nfrom collections import Counter\nfrom imblearn.under_sampling import RandomUnderSampler\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef cohenkappa_calc(cm):\n \"\"\"\n Cohen Kappa calculator.\n\n Input: confusion_matrix function from sklearn results\n Output: cohen kappa\n \"\"\"\n\n import numpy as np\n sum_diag=sum(cm.diagonal())\n\n sum_rows=np.ones((1,len(cm)))\n sum_cols=np.ones((len(cm)+1,1))\n bychance=np.ones((1,len(cm)))\n\n for k in range(0,len(cm)):\n sum_rows[0,k]=sum(cm[:,k])\n\n for h in range(0,len(cm)):\n sum_cols[h,0]=sum(cm[h,:])\n\n sum_cols[len(cm),0]=sum(sum_cols)-1\n\n for j in range(0,len(cm)):\n bychance[0,j]=(sum_rows[0,j]/sum_cols[len(cm),0])*sum_cols[j,0]\n\n sum_bychance=sum(bychance[0,:])\n\n cohenkappa=(sum_diag-sum_bychance)/((sum_cols[len(cm),0])-sum_bychance)\n\n sumsum=np.concatenate((cm, sum_rows), axis=0)\n sumsum2=np.concatenate((sumsum, sum_cols), axis=1)\n\n return cohenkappa\n\nparser = argparse.ArgumentParser()\nparser.add_argument('path', help='where the files are located')\nparser.add_argument('segments', help='polygon shape file with features and classes')\nargs = parser.parse_args()\n\n# Import and define feature and label\n\nprint(\"------ Import data and re-organize------ \")\n\nsegments = gpd.GeoDataFrame.from_file(args.path+args.segments)\n#segments=segments[segments['Highestid']!='Open water']\n#segments=segments[segments['Highestid']!='Bos']\nsegments['Highestid']=segments['Highestid'].replace(['Landriet, structuurarm', 'Landriet, structuurrijk','Waterriet'], 'Riet')\n\nsegments['Highestid']=segments['Highestid'].replace(['Riet','Struweel','Grasland'], 'Non-water')\n\n\n# pre-organize the data\n\n#feature_list=['mean_echo_','mean_Plana','mean_Curva','mean_kurto','mean_sigma','mean_media','mean_Spher']\n#feature_list=['mean_echo_','mean_Plana','mean_Curva','mean_kurto','mean_sigma','mean_mean_','mean_media','std_echo_r','std_Planar','std_Curvat','std_kurto_','std_sigma_']\n#feature_list=['mean_Plana','mean_Curva','mean_kurto','mean_Spher']\nfeature_list=segments.columns[7:35]\n\nsegments_whighprob=segments[(segments['Prob']>0.4)&(segments['poly_area']>0)]\n\nfeature=segments_whighprob[feature_list].values\nfeature_all=segments[feature_list].values\n\nfea_list_forvis=np.array(feature_list)\n\nlabel=segments_whighprob['Highestid'].values\n\n# Under-sampling -- get equal number of samples per class + split training and testing\n\nrus = RandomUnderSampler(random_state=0)\nfeature_resampled, label_resampled = rus.fit_sample(feature, label)\n#print(sorted(Counter(label_resampled).items()))\n\nmytrain, mytest, mytrainlabel, mytestlabel = train_test_split(feature_resampled, label_resampled,train_size = 0.6)\n\n\n# Random Forest\n\nprint(\"------ Apply Random Forest ------ \")\n\nn_estimators=30\ncriterion='gini'\nmax_depth=30\nmin_samples_split=5\nmin_samples_leaf=5\nmax_features='auto'\nmax_leaf_nodes=None\nbootstrap=True\noob_score=True\nn_jobs=1\nrandom_state=None\nverbose=0\nclass_weight='balanced'\n\nforest = RandomForestClassifier(n_estimators=n_estimators, criterion=criterion, max_depth=max_depth,\n min_samples_split=min_samples_split, min_samples_leaf=min_samples_leaf,\n max_features=max_features, max_leaf_nodes=max_leaf_nodes, bootstrap=bootstrap, oob_score=oob_score,\n n_jobs=n_jobs, random_state=random_state, verbose=verbose,class_weight=class_weight)\n\nRF_classifier = forest.fit(mytrain, mytrainlabel)\n\n# Validation\n\nprint(\"------ Validation ------ \")\n\nmypredtest=RF_classifier.predict(mytest)\n\nprint(classification_report(mytestlabel, mypredtest)) \nprint(confusion_matrix(mytestlabel, mypredtest))\n\nmypred=RF_classifier.predict(feature_all)\n\nsegments['pred_class']=mypred\n\nsegments.to_file(args.path+args.segments+\"_RFclass.shp\", driver='ESRI Shapefile')\n\nimportances=RF_classifier.feature_importances_\nindices = np.argsort(importances)[::-1]\n\n# Plot the feature importances of the forest\n\nprint(\"------ Export ------ \")\n\nplt.figure()\nplt.title(\"Feature importances\")\nplt.bar(range(mytrain.shape[1]), importances[indices],\n color=\"r\", align=\"center\")\nplt.xticks(range(mytrain.shape[1]), fea_list_forvis[indices],rotation=45,horizontalalignment='right')\nplt.xlim([-1, mytrain.shape[1]])\nplt.tight_layout()\n#plt.show()\nplt.savefig(args.path+args.segments+\"_RFclass_feaimp.png\")\n\n# Export classification report\n\nwith open(args.path+args.segments+\"_RFclass_acc.txt\", 'w') as f:\n\tf.write(np.array2string(confusion_matrix(mytestlabel, mypredtest), separator=', '))\n\tf.write(classification_report(mytestlabel, mypredtest))\n\tf.write(np.array2string(cohenkappa_calc(confusion_matrix(mytestlabel, mypredtest))))\n\tf.write(np.array2string(importances[indices]))\n\tf.write(np.array2string(feature_list[indices]))\n","repo_name":"eEcoLiDAR/wetland_classification_from_lidar","sub_path":"analysis/randomforest_forsegments_wcolsel_wbalance.py","file_name":"randomforest_forsegments_wcolsel_wbalance.py","file_ext":"py","file_size_in_byte":5512,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"57"} +{"seq_id":"31236378181","text":"# 프로그래머스_알고리즘_2021-03-23, level01_최소공배수, 최대 공약수../by 정석진\n\nimport math\n\n\ndef solution(n, m):\n a = math.gcd(n, m)\n b = n*m//a\n answer = [a, b]\n return answer\n","repo_name":"strong1133/hh99_cpt2_Algorithm","sub_path":"altari/programmers/level01/최소공배수, 최대공약수.py","file_name":"최소공배수, 최대공약수.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"1549745437","text":"import parser.pycparser as pcp\n\nfrom collections import OrderedDict\n\nclass OffloadBuilder:\n\t\n\tdef __init__(self, kernel_id, kernel_node):\n\t\tself._k_id = kernel_id\n\t\tself._k_def = kernel_node\n\n\t\tself._match_arr = OrderedDict()\n\t\tself._match_arr['u64'] = ['*', 'unsiged long', 'uint64_t']\n\t\tself._match_arr['i64'] = ['long', 'int64_t']\n\t\tself._match_arr['u32'] = ['unsigned int', 'uint32_t']\n\t\tself._match_arr['i32'] = ['int', 'int32_t']\n\t\tself._match_arr['u16'] = ['unsigned short', 'uint16_t']\n\t\tself._match_arr['i16'] = ['short', 'int16_t']\n\t\tself._match_arr['u8'] = ['unsigned char', 'uint8_t']\n\t\tself._match_arr['i8'] = ['char', 'int8_t']\n\t\tself._match_arr['double'] = ['double']\n\t\tself._match_arr['float'] = ['float']\n\n\t\tself._args = self._map_args_veo(self._list_args_types())\n\n\tdef build_pe_offload_header(self, pg_size):\n\t\treturn self._func_decl(pg_size)\n\t\t\n\tdef build_pe_offload_code(self, pg_size):\n\t\t\n\t\t# get function to call\n\t\tif(pg_size is None):\n\t\t\tki_id = '%s__omp__' % self._k_id\n\t\telse:\n\t\t\tki_id = '%s__%d__omp__' % (self._k_id, pg_size)\n\n\t\t# start with an empty body\n\t\tki_body = []\n\n\t\t# declare req, retval\n\t\tki_body.append(\n\t\t\tpcp.c_ast.Decl(\n\t\t\t\t'req',\n\t\t\t\t[],\n\t\t\t\t[],\n\t\t\t\t[],\n\t\t\t\tpcp.c_ast.TypeDecl(\n\t\t\t\t\t'req',\n\t\t\t\t\t[],\n\t\t\t\t\tpcp.c_ast.IdentifierType(['uint64_t'])),\n\t\t\t\tNone,\n\t\t\t\tNone))\n\t\tki_body.append(\n\t\t\tpcp.c_ast.Decl(\n\t\t\t\t'retval',\n\t\t\t\t[],\n\t\t\t\t[],\n\t\t\t\t[],\n\t\t\t\tpcp.c_ast.TypeDecl(\n\t\t\t\t\t'retval',\n\t\t\t\t\t[],\n\t\t\t\t\tpcp.c_ast.IdentifierType(['uint64_t'])),\n\t\t\t\tNone,\n\t\t\t\tNone))\n\n\t\t# clear arguments\n\t\tki_body.append(\n\t\t\tpcp.c_ast.FuncCall(\n\t\t\t\tpcp.c_ast.ID('veo_args_clear'),\n\t\t\t\tpcp.c_ast.ExprList([\n\t\t\t\t\tpcp.c_ast.ID('_veo_inst.args')\n\t\t\t\t])))\n\n\t\t# add kernel arguments (pointers as uint64_t!)\n\t\tfor ix, item in enumerate(self._args):\n\t\t\tki_body.append(\n\t\t\t\tpcp.c_ast.FuncCall(\n\t\t\t\t\tpcp.c_ast.ID('veo_args_set_%s' % item[0]),\n\t\t\t\t\tpcp.c_ast.ExprList([\n\t\t\t\t\t\tpcp.c_ast.ID('_veo_inst.args'),\n\t\t\t\t\t\tpcp.c_ast.ID(str(ix)),\n\t\t\t\t\t\tpcp.c_ast.ID(item[2])\n\t\t\t\t\t])))\n\n\t\t# get symbol\n\t\tki_body.append(\n\t\t\tpcp.c_ast.Assignment(\n\t\t\t\t'=',\n\t\t\t\tpcp.c_ast.ID('_veo_inst.sym'),\n\t\t\t\tpcp.c_ast.FuncCall(\n\t\t\t\t\tpcp.c_ast.ID('veo_get_sym'),\n\t\t\t\t\tpcp.c_ast.ExprList([\n\t\t\t\t\t\tpcp.c_ast.ID('_veo_inst.hproc'),\n\t\t\t\t\t\tpcp.c_ast.Constant(\n\t\t\t\t\t\t\tpcp.c_ast.IdentifierType(['uint64_t']),\n\t\t\t\t\t\t\t'0'),\n\t\t\t\t\t\tpcp.c_ast.Constant(\n\t\t\t\t\t\t\tpcp.c_ast.IdentifierType(['const char *']),\n\t\t\t\t\t\t\t'\\\"%s\\\"' % ki_id)]))))\n\n\t\t# offload kernel call\n\t\tki_body.append(\n\t\t\tpcp.c_ast.Assignment(\n\t\t\t\t'=',\n\t\t\t\tpcp.c_ast.ID('req'),\n\t\t\t\tpcp.c_ast.FuncCall(\n\t\t\t\t\tpcp.c_ast.ID('veo_call_async'),\n\t\t\t\t\tpcp.c_ast.ExprList([\n\t\t\t\t\t\tpcp.c_ast.ID('_veo_inst.hctxt'),\n\t\t\t\t\t\tpcp.c_ast.ID('_veo_inst.sym'),\n\t\t\t\t\t\tpcp.c_ast.ID('_veo_inst.args')]))))\n\n\t\t# synchronize aurora device\n\t\tki_body.append(\n\t\t\tpcp.c_ast.FuncCall(\n\t\t\t\tpcp.c_ast.ID('veo_call_wait_result'),\n\t\t\t\tpcp.c_ast.ExprList([\n\t\t\t\t\tpcp.c_ast.ID('_veo_inst.hctxt'),\n\t\t\t\t\tpcp.c_ast.ID('req'),\n\t\t\t\t\tpcp.c_ast.ID('&retval')])))\n\n\t\t# return implementation\n\t\treturn pcp.c_ast.FuncDef(\n\t\t\tself._func_decl(pg_size),\n\t\t\tNone,\n\t\t\tpcp.c_ast.Compound(ki_body))\n\n\tdef _func_decl(self, pg_size):\n\t\t# kernel variant id includes the PG size\n\t\tif(pg_size is None):\n\t\t\tki_id = '%s__offload__' % self._k_id\n\t\telse:\n\t\t\tki_id = '%s__%d__offload__' % (self._k_id, pg_size)\n\n\t\t# copy param decls from definition + number of jobs parameter\n\t\tki_param_decl = pcp.c_ast.ParamList([])\n\t\tfor arg in self._args:\n\t\t\traw_type = self._match_arr[arg[0]][-1]\n\n\t\t\tki_param_decl.params.append(pcp.c_ast.Decl(\n\t\t\t\t\targ[2],\n\t\t\t\t\t[],\n\t\t\t\t\t[],\n\t\t\t\t\t[],\n\t\t\t\t\tpcp.c_ast.TypeDecl(\n\t\t\t\t\t\targ[2],\n\t\t\t\t\t\t[arg[1]] if len(arg[1]) > 0 else None,\n\t\t\t\t\t\tpcp.c_ast.IdentifierType([raw_type])),\n\t\t\t\t\tNone,\n\t\t\t\t\tNone))\n\n\t\treturn pcp.c_ast.Decl(\n\t\t\tki_id,\n\t\t\t[],\n\t\t\t[],\n\t\t\t[],\n\t\t\tpcp.c_ast.FuncDecl(\n\t\t\t\tki_param_decl,\n\t\t\t\tpcp.c_ast.TypeDecl(\n\t\t\t\t\tki_id,\n\t\t\t\t\t[],\n\t\t\t\t\tpcp.c_ast.IdentifierType(['void'])\n\t\t\t\t)\n\t\t\t),\n\t\t\tNone,\n\t\t\tNone)\n\n\tdef _list_args_types(self):\n\n\t\targs = []\n\n\t\tfor a_decl in self._k_def.decl.type.args.params:\n\n\t\t\t# flatten qualifier string\n\t\t\tquals = ''\n\t\t\tif(type(a_decl) == pcp.c_ast.PtrDecl):\n\t\t\t\tfor s in a_decl.type.type.quals:\n\t\t\t\t\tquals += s + ' '\n\t\t\telse:\n\t\t\t\tfor s in a_decl.type.quals:\n\t\t\t\t\tquals += s + ' '\n\n\t\t\tquals = quals.strip()\n\n\t\t\tif(type(a_decl.type) is pcp.c_ast.PtrDecl):\n\t\t\t\targs.append(('%s *' % a_decl.type.type.type.names[0], quals, a_decl.name))\n\t\t\telse:\n\t\t\t\targs.append(('int', quals, a_decl.name))\n\t\t\t\t\n\t\t# artificial 'num jobs' argument\n\t\targs.append(('int', 'const', '__num_pgs'))\n\n\t\treturn args\n\n\tdef _map_args_veo(self, args):\n\n\t\tdef map(arg):\n\t\t\tfor _sfx in self._match_arr:\n\t\t\t\tfor expr in self._match_arr[_sfx]:\n\t\t\t\t\tif(arg.find(expr) != -1):\n\t\t\t\t\t\treturn _sfx\n\t\t\t\n\t\t\treturn 'UNKNOWN'\n\n\t\treturn [(map(a[0]), a[1], a[2]) for a in args]\n\nclass OffloadFileBuilder:\n\n\tdef __init__(self):\n\t\tself._o_header = []\n\t\tself._o_code = []\n\n\tdef add_kernel_instance(self, kernel_id, kernel_node, pg_size):\n\t\tbob = OffloadBuilder(kernel_id, kernel_node)\n\n\t\tself._o_header.append(bob.build_pe_offload_header(pg_size))\n\t\tself._o_code.append(bob.build_pe_offload_code(pg_size))\n\n\tdef header_ast(self):\n\t\treturn pcp.c_ast.FileAST(\n\t\t\tpcp.c_ast.DeclList(self._o_header))\n\n\tdef src_ast(self):\n\t\treturn pcp.c_ast.FileAST(\n\t\t\tpcp.c_ast.DeclList(self._o_code))\n","repo_name":"dthuerck/aurora-runtime","sub_path":".runtime/src/build_offload.py","file_name":"build_offload.py","file_ext":"py","file_size_in_byte":5253,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"55"} +{"seq_id":"5184180159","text":"import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport urllib\nimport re\nimport wget\nimport pymysql\nfrom sqlalchemy import create_engine\nimport pandas as pd\nimport pickle\nfrom os import walk\nfrom datetime import datetime\n\nuser=\"\"\nhost=\"\"\npassword=\"\"\nport=1234\ndatabase=\"\"\n\n\n\nlink = 'https://info.bossa.pl/pub/intraday/mstock/daily/'\nf = requests.get(link)\nhtml = f.text\nsoup = BeautifulSoup(html, 'lxml')\n\nhref_tags = list(soup.find_all(href=True))\nhref_tags = [ str(x) for x in href_tags]\nfiles=[x for x in href_tags if re.match(r\".*\\d\\d\\d\\d-\\d\\d-\\d\\d.zip.*\",x)]\nfiles = [ x.split('\"') for x in files]\nfiles = [x[1] for x in files]\n\n\nengine = create_engine(\"mysql+pymysql://{user}:{pw}@{host}:{port}/{db}\"\n .format(user=user,\n pw=password,\n host=host,\n port = port,\n db=database))\n\nconnection = pymysql.connect(host=host,\n port = port,\n user=user,\n password=password,\n db=database)\nmy_cursor = connection.cursor()\n\nmy_cursor.execute(\"SELECT id_company,name FROM gpw.company\")\ncompany_ids = my_cursor.fetchall()\ncompany_ids = pd.DataFrame(company_ids, columns =['id', 'name']) \n\nsql = \"SELECT MAX(date) FROM gpw.historic_data\"\n\nmy_cursor.execute(sql)\n\ndate = my_cursor.fetchall()\n\ndate =date[0][0].strftime('%Y-%m-%d')\n\nid = files.index(f'{date}.zip')\nfiles = files[:id]\nfiles.reverse()\nprint(files)\nupdate=[]\nfor f in files:\n update.append(wget.download(f'https://info.bossa.pl/pub/intraday/mstock/daily/{f}',f'data/{f}'))\n\ndf=pd.DataFrame([])\nfor f in update:\n df2 = pd.read_csv(f'{f}',names=['name','0','date','hour','open','high','low','close','volume'],index_col=False)\n df2.drop('0', axis=1, inplace=True)\n \n df2['date'] = df2['date'].astype(str)\n df2['hour'] = df2['hour'].astype(str)\n df2['date'] = df2['date']+df2['hour']\n df2['date'] = pd.to_datetime(df2['date'], format='%Y%m%d%H%M%S')\n df2.drop('hour', axis=1, inplace=True)\n df2['date'] =df2['date'].astype(str)\n frames = [df2,df]\n df = pd.concat(frames)\ndf =pd.merge(df, company_ids, on='name')\ndf.drop('name', axis=1, inplace=True)\ndf = df[['id','date','open','high','low','close','volume']]\ndf.rename(columns={'id': 'id_company'}, inplace=True)\ndf.to_sql('historic_data', con = engine, if_exists = 'append', chunksize = 100000, index=False)","repo_name":"marcin-mulawa/GPW","sub_path":"pobierz.py","file_name":"pobierz.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"39170253478","text":"board_str = \"1 0 1 1 0 1 1\"\nstep_str = \"4 5 6 2 3 4 5 6\"\nboard = [int(x) for x in board_str.split(' ')]\nsteps = [int(x) for x in step_str.split(' ')]\n\ntile_num = len(board)\n\ndef mutate(board, idx):\n new = [0] * tile_num\n for i in range(tile_num):\n if i != idx:\n if board[i] == 1:\n if i - 1 >= 0:\n new[i - 1] = 1\n if i + 1 < tile_num:\n new[i + 1] = 1\n return new\n\nprint(board)\nfor step in steps:\n print(f'Click grid {step}')\n board = mutate(board, step - 1)\n print(board)\n","repo_name":"KennethOng02/NTNU-Artificial-Intelligence","sub_path":"hw2/simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"42387587565","text":"# You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. \n# You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order.\n\ndef minimumSwaps(arr):\n swaps = 0\n i = 0\n while i < len(arr): \n if arr[i] == i + 1: \n i += 1\n else: \n # swap the element that's out of place w/ the element\n # that's currently at the element's correct position\n # assumes that input array contains consecutive numbers starting from 1\n arr[arr[i]-1], arr[i] = arr[i], arr[arr[i]-1]\n swaps += 1\n return swaps\narr = [2, 3, 4, 1, 5]\nprint(minimumSwaps(arr) == 3)\n","repo_name":"abusharkhm/coding-challenges-and-review","sub_path":"searching and sorting/minimumSwaps.py","file_name":"minimumSwaps.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"34855671084","text":"cards = str(input()).split()\r\nnumber_of_shuffles = int(input())\r\n\r\ntop_card = cards[0]\r\nbottom_card = cards[-1]\r\n\r\nfor j in range(number_of_shuffles):\r\n\r\n left_cards = []\r\n right_cards = []\r\n if j == 0:\r\n shuffled_cards = top_card.split()\r\n half = len(cards) // 2\r\n\r\n for index in range(1, half):\r\n if j == 0:\r\n left_cards.append(cards[index])\r\n else:\r\n left_cards.append(shuffled_cards[index])\r\n\r\n for index in range(half, len(cards) - 1):\r\n if j == 0:\r\n right_cards.append(cards[index])\r\n else:\r\n right_cards.append(shuffled_cards[index])\r\n if j != 0:\r\n shuffled_cards = top_card.split()\r\n for index in range(len(right_cards)):\r\n shuffled_cards.append(right_cards[0])\r\n right_cards.pop(0)\r\n shuffled_cards.append(left_cards[0])\r\n left_cards.pop(0)\r\n\r\n shuffled_cards.append(bottom_card)\r\nprint(shuffled_cards)","repo_name":"iiZlatanov/SoftUni---Main-Course-PY","sub_path":"PY-Fundamentals/Homework/03. Lists Basics Exercise/05. Faro Shuffle.py","file_name":"05. Faro Shuffle.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"39805475403","text":"from infosystem.database import db\nfrom sqlalchemy import UniqueConstraint\nfrom infosystem.common.subsystem import entity\n\n\nclass Role(entity.Entity, db.Model):\n\n attributes = ['domain_id', 'name']\n attributes += entity.Entity.attributes\n\n domain_id = db.Column(\n db.CHAR(32), db.ForeignKey(\"domain.id\"), nullable=False)\n name = db.Column(db.String(80), nullable=False)\n\n __table_args__ = (\n UniqueConstraint('domain_id', 'name', name='role_name_uk'),)\n\n def __init__(self, id, domain_id, name,\n active=True, created_at=None, created_by=None,\n updated_at=None, updated_by=None, tag=None):\n super().__init__(id, active, created_at, created_by,\n updated_at, updated_by, tag)\n self.domain_id = domain_id\n self.name = name\n","repo_name":"samueldmq/infosystem","sub_path":"infosystem/subsystem/role/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"55"} +{"seq_id":"13793143117","text":"from unittest import TestCase\n\nfrom veritranspay.response import IndomaretChargeResponse\n\n\nclass IndomaretChargeResponseTests(TestCase):\n\n def setUp(self):\n # example response data from\n # http://docs.veritrans.co.id/en/vtdirect/integration_indomrt.html#response-transaction-indomrt\n self.response_json = {\n \"status_code\": \"201\",\n \"status_message\": \"Success, CSTORE transaction is successful\",\n \"transaction_id\": \"ff05337c-6c94-4f70-8e81-35acd89b688e\",\n \"order_id\": \"201404141421\",\n \"payment_type\": \"cstore\",\n \"transaction_time\": \"2014-04-14 16:03:51\",\n \"transaction_status\": \"pending\",\n \"payment_code\": \"498112345234\",\n \"gross_amount\": \"145000.00\"\n }\n\n self.parsed_response = IndomaretChargeResponse(**self.response_json)\n\n def test_status_code(self):\n self.assertEqual(201, self.parsed_response.status_code)\n\n def test_payment_type(self):\n self.assertEqual('cstore', self.parsed_response.payment_type)\n\n def test_payment_code(self):\n self.assertEqual('498112345234', self.parsed_response.payment_code)\n","repo_name":"gramedia-digital-nusantara/midtranspay","sub_path":"tests/response_indomaret_charge_tests.py","file_name":"response_indomaret_charge_tests.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"55"} +{"seq_id":"7150516365","text":"import json\nimport logging\nfrom inspect import isawaitable\nfrom typing import Callable\n\nfrom graphene import ResolveInfo\n\n\nclass BaseDebugMiddleware:\n def __init__(self, logger, level):\n self.logger = logger\n self.level = level\n\n async def resolve(self, next_, root, info: ResolveInfo, **args):\n if root is None:\n try:\n self.log(info)\n except Exception as e:\n ...\n\n result = next_(root, info, **args)\n if isawaitable(result):\n return await result\n\n return result\n\n def log(self, info: ResolveInfo):\n raise NotImplementedError()\n\n\nclass LogMiddleware(BaseDebugMiddleware):\n def __init__(\n self,\n logger: logging.Logger = logging.getLogger(\"gsc\"),\n level: int = logging.INFO,\n ):\n super().__init__(logger, level)\n\n def log(self, info):\n full_query = json.loads(info.context.request._body)\n if full_query.get(\"operationName\") != \"IntrospectionQuery\":\n text = json.dumps(full_query, ensure_ascii=False, sort_keys=True)\n self.logger.log(self.level, text)\n\n\nclass BreadcrumbMiddleware(BaseDebugMiddleware):\n logger: Callable\n\n def __init__(self, level: str = \"info\"):\n from sentry_sdk import add_breadcrumb\n\n super().__init__(add_breadcrumb, level)\n\n def log(self, info):\n full_query = json.loads(info.context.request._body)\n if full_query.get(\"operationName\") != \"IntrospectionQuery\":\n if full_query.get(\"query\"):\n self.logger(\n category=\"graphql\", message=full_query[\"query\"], level=\"info\"\n )\n if full_query.get(\"variables\"):\n self.logger(\n category=\"graphql\",\n message=json.dumps(full_query[\"variables\"]),\n level=\"info\",\n )\n","repo_name":"startupmillio/alchql","sub_path":"alchql/middlewares/debug_middleware.py","file_name":"debug_middleware.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"55"} +{"seq_id":"3627676158","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# based on \n\nfrom tkinter import *\nimport asyncio\nimport threading\nimport random\nimport queue\n\n\n# Fancy child of a thread that can send data to and from the tkinter stuff\n# Code works\n# Must be commented and reformatted to work within our program\nclass AsyncioThread(threading.Thread):\n \n # Constructor\n # Parameters: the queue that is storing the \"updates\", the maximum amount of data that can go in\n def __init__(self, the_queue, max_data):\n \n # SPECIAL\n # asyncio.get_event_loop() is a special object from the asyncio import\n self.asyncio_loop = asyncio.get_event_loop()\n \n # Initializes the class attributes\n self.the_queue = the_queue\n self.max_data = max_data\n\n # Calls the thread (parent class) constructor\n threading.Thread.__init__(self)\n\n\n # Method that is called when the thread is started\n # Ran on the command \"thread.start()\"\n def run(self):\n\n # run_until_complete is a method for \"asyncio.get_event_loop()\" objects\n self.asyncio_loop.run_until_complete(self.do_data())\n\n\n # This is an \"async def\" function \n # I don't know why it's special, but it is\n async def do_data(self):\n \"\"\" Creating and starting 'maxData' asyncio-tasks. \"\"\"\n\n # List of tasks that should be completed\n tasks = [\n self.create_dummy_data(key)\n for key in range(self.max_data)\n ]\n\n\n # Wait until this is done\n # I don't really know what this does\n await asyncio.wait(tasks)\n\n\n\n # Creates the random numbers that are shown as \"data\"\n # Randomly does tasks \n async def create_dummy_data(self, key):\n \"\"\" Create data and store it in the queue. \"\"\"\n \n \n sec = random.randint(1, 10)\n data = '{}:{}'.format(key, random.random())\n await asyncio.sleep(sec)\n\n self.the_queue.put((key, data))\n\n\n\n# Class that handles all of the tkinter stuff\n# Creates an AsyncioThread within\nclass TheWindow:\n\n # Constructor\n def __init__(self, max_data):\n # thread-safe data storage\n self.the_queue = queue.Queue()\n\n # the GUI main object\n self.root = Tk()\n\n # create the data variable\n self.data = []\n for key in range(max_data):\n self.data.append(StringVar())\n self.data[key].set('')\n\n # Button to start the asyncio tasks\n Button(master=self.root,\n text='Start Asyncio Tasks',\n command=lambda: self.do_asyncio()).pack()\n \n # Frames to display data from the asyncio tasks\n for key in range(max_data):\n Label(master=self.root, textvariable=self.data[key]).pack()\n \n # Button to check if the GUI is freezed\n Button(master=self.root,\n text='Freezed???',\n command=self.do_freezed).pack()\n\n\n # Recursive Method\n # Refreshes the data that will be put on the tkinter window\n def refresh_data(self):\n \"\"\"\n \"\"\"\n # do nothing if the aysyncio thread is dead\n # and no more data in the queue\n # Breaking statement of recursive loop\n if not self.thread.is_alive() and self.the_queue.empty():\n return\n\n # refresh the GUI with new data from the queue\n while not self.the_queue.empty():\n key, data = self.the_queue.get()\n self.data[key].set(data)\n\n print('RefreshData...')\n\n # timer to refresh the gui with data from the asyncio thread\n self.root.after(1000, self.refresh_data) # called only once!\n\n\n # What the \"Freeze???\" button does when clicked\n # Demonstrates that the GUI Window isn't frozen while the other data is parsed in\n def do_freezed(self):\n \"\"\" Button-Event-Handler to see if a button on GUI works.\n The GOAL of this example is to make this button clickable\n while the other thread/asyncio-tasks are working. \"\"\"\n print('Tkinter is reacting. Thread-ID: {}'\n .format(threading.get_ident()))\n\n\n # Method that is run when the button is clicked\n def do_asyncio(self):\n \"\"\"\n Button-Event-Handler starting the asyncio part in a separate\n thread.\n \"\"\"\n # create fancy thread object\n # Parameters: the queue that is storing the \"updates\", the maximum amount of data that can go in\n self.thread = AsyncioThread(self.the_queue, len(self.data))\n\n # timer to refresh the gui with data from the asyncio thread\n self.root.after(1000, self.refresh_data) # called only once!\n\n # start the thread\n self.thread.start()\n\n\n# Main Method\n# What logic is run when this file is ran from the terminal\nif __name__ == '__main__':\n\n # Creates the window\n # Parameter: number of labels to be filled with data\n window = TheWindow(10)\n\n # mainloop()\n window.root.mainloop()","repo_name":"bethel-physics/WagonTestGUI","sub_path":"PREV-VERSION/PrevBethelFiles/QueueAttempt.py","file_name":"QueueAttempt.py","file_ext":"py","file_size_in_byte":5042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"31623151756","text":"import foo\nfrom foo import Bar\nfrom foo import Foo\nfrom random import Random\nimport unittest\n\n\nclass FooTest(unittest.TestCase):\n def test_bar_get(self):\n self.assertIsInstance(\n Bar.bar_get(),\n foo.Bar\n )\n\n\n def test_foo(self):\n foo_instance = Foo()\n self.assertEqual(\n foo_instance.foo(x=32),\n 64\n )\n\n\n def test_foo_get(self):\n foo_instance = Foo()\n self.assertIsInstance(\n foo_instance.foo_get(),\n foo.Bar\n )\n\n\n def test_main(self):\n self.assertEqual(\n foo.main(),\n None\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"laffra/auger","sub_path":"sample/tests/test_Foo.py","file_name":"test_Foo.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":196,"dataset":"github-code","pt":"55"} +{"seq_id":"74232771691","text":"# -*- coding: utf-8 -*-\nfrom plone.app.vocabularies.catalog import SearchableTextSourceBinder\nfrom plone.portlets.interfaces import IPortletDataProvider\nfrom zope.i18nmessageid import MessageFactory\nfrom zope.interface import Interface\nfrom zope.lifecycleevent.interfaces import IObjectModifiedEvent\nfrom zope.schema import Int, List, Dict, Choice, Bool, Tuple, TextLine\n\n\n_ = MessageFactory('collective.vaporisation')\n\n\nclass ITreeUpdateEvent(IObjectModifiedEvent):\n \"\"\"This triggers the rebuilding of the whole tree\n \"\"\"\n\n\nclass ICustomizableCloud(IPortletDataProvider):\n \"\"\"Customizable parts of the cloud\n \"\"\"\n # Customization\n name = TextLine(\n title=_(u\"Name to display\"),\n description=_(u\"The name of the tagcloud. For display purposes.\"),\n required=True,\n default=u\"Tagcloud\"\n )\n\n steps = Int(\n title=_(u\"Number of different sizes\"),\n description=_(u\"This number will also determine the biggest size.\"),\n required=True,\n default=10\n )\n\n limit = Int(\n title=_(u\"Number of keywords to display\"),\n description=_(u\"Zero displays it all.\"),\n required=False,\n default=0\n )\n\n timeout = Int(title=_(u'Cloud reload timeout'),\n description=_(u'Time in minutes after which the cloud should be '\n u'reloaded.'),\n required=True,\n default=100)\n\n startpath = Choice(title=_(u\"Start path\"),\n description=_(u'Only the objects under this directory will be counted.'\n u' If empty, the portlet will search in all the site.'),\n required=False,\n source=SearchableTextSourceBinder({}, default_query='path:'))\n\n indexes_to_use = Tuple(\n title=_(u\"Indexes to use\"),\n description=_(u\"Select from the list the indexes to use for the \"\n u\"cloud\"),\n default=('Subject',),\n value_type=Choice(vocabulary='collective.vaporisation.indexes'),\n required=True)\n\n type = Tuple(\n title=_(u\"Type of contents\"),\n description=_(u\"Only the objects of this type will be counted.\"),\n value_type=Choice(vocabulary='plone.app.vocabularies.ReallyUserFriendlyTypes'),\n required=False,\n )\n\n joint = Bool(\n default=False,\n required=False,\n title=_(u\"Activate joint navigation\"),\n description=_(u\"Joint navigation puts keywords together\"\n u\" for associative searches.\")\n )\n\n white_list = Tuple(\n required=False,\n title=_(u\"Use only the keywords of this list\"),\n description=_(u\"List of keywords to use in the cloud\"),\n value_type=Choice(vocabulary='collective.vaporisation.keywords'),\n )\n\n restrict = Tuple(\n required=False,\n title=_(u\"Remove from keywords list\"),\n description=_(u\"Restrict the cloud keywords by removing these \"\n u\"keywords.\"\n u\"If there is something selected in the list over,\"\n u\" the values of that list will be ignored.\"),\n value_type=Choice(vocabulary='collective.vaporisation.keywords'),\n )\n\n mode_to_use = Choice(\n title=_(u\"Mode to use\"),\n description=_(u'Select one of the possible mode to use the cloud'),\n vocabulary='collective.vaporisation.use_mode',\n required=True,\n default=('default',),\n )\n\n sort = Bool(\n default=True,\n required=False,\n title=_(u\"Sort keywords\"),\n description=_(u\"If selected, the keywords will be sorted \"\n u\"alphabetically.\")\n )\n\n\nclass IVaporizedCloud(ICustomizableCloud):\n \"\"\"A cloudy bunch of keywords\n \"\"\"\n\n # storing the tags\n keywords = List(title=u\"The list of keywords\", default=[])\n all_keys = List(title=u\"The list of all the keywords\", default=[])\n tagsTree = Dict(title=u\"The full tree of tags\", default={})\n\n #informations about weights\n lowest = Int(title=u\"lowest weight\", default=10)\n highest = Int(title=u\"heighest weight\", default=20)\n\n\nclass ISteamer(Interface):\n \"\"\"\n The steamer releases the pression by letting the steam out.\n Here, the vaporisation is done !\n \"\"\"\n\n def getStepForTag(self, tag):\n \"\"\"\n This method will return a tuple that contains :\n - size of the tag to display, in %, for the template\n - The number of occurence of that tag\n The size of the tag is calculated into the inner function\n calculateTagSize, so it's easy to modify.\n If the occurence of the tags is even, they will all be displayed\n at 100%\n \"\"\"\n\n def getTagsFromTree(self, keywords):\n \"\"\"\n This method returns a list of dict.\n Each entry consits in a tag, with the keys :\n - name : the name of the keyword, the label\n - weight: the number of occurence of that keyword\n - size : the size in % of the tag to be displayed\n \"\"\"\n\n def getConnectionsFor(self, keywords):\n \"\"\"\n This is heart of the joint navigation.\n It returns a list of keywords.\n This list is computed from the connection keywords have\n between themselves.\n The joint navigation being cumulative, it sorts an eliminates\n keywords via an intersection.\n \"\"\"\n\n def getVaporizedCloudFor(self, subjects=None):\n \"\"\"\n This returns the keywords to display in the cloud.\n It takes in consideration the given list of keywords.\n \"\"\"\n\n def updateWitnessWeights(self, value):\n \"\"\"\n In order to calculate the sizes of the tags to be\n displayed, we have to keep track of the fatest and\n skinniest keywords.\n \"\"\"\n\n def updateTree(self, keywords, index):\n \"\"\"\n This is the main method to build the tags Tree.\n Although it is heavy duty done here, we do it only\n time to time. So, it's merciless.\n \"\"\"\n\n def restrictTree(self):\n \"\"\"\n This methods takes cares of removing the tags\n beyond the limit fixed by the user.\n To do so, it will build a complementary list\n that is the keywords, sorted by 'weight', the number\n of occurences. In order to sort the keywords, we need\n the already filled tree. It's not very optimal, but\n it is done only once.\n \"\"\"\n\n def setTree(self):\n \"\"\"\n Using the catalog, this method creates a blank tree.\n Taking care of keyword restrictions, it builds a full\n structure containing either the keywords and their\n properties, such as number of occurences.\n Keywords are stored as unicodes.\n \"\"\"\n\n\nclass ICloudRenderer(Interface):\n \"\"\"\n The cloud renderer provides the methods to display the cloud.\n It will adapt the cloud with a steamer to gets the things out.\n \"\"\"\n\n def Title(self):\n \"\"\"\n Returns the name of a tagcloud\n \"\"\"\n\n def update_tags_tree(self):\n \"\"\"\n This is the restricted access for a manager to handle his cloud.\n It will simply trigger the private method of the vaporized cloud.\n Once refreshed, it will display a message, acknowledging the change.\n \"\"\"\n\n def render(self):\n \"\"\"\n default render method\n \"\"\"\n\n def getVaporizedCloud(self):\n \"\"\"\n This method return as list of dictionnaries.\n A dict contains :\n - name : the name of the tag. (unicode)\n - weight : the weight of the tag. (int)\n - size : the size of the font, for the HTML rendering. (int)\n \"\"\"\n\n def isJointNavigation(self):\n \"\"\"\n This method is a simple public accessor for the attribute 'joint' that\n defines a cloud with the joint navigation activated. It returns a bool.\n \"\"\"\n\n def currentSubjects(self):\n \"\"\"\n This method return the list of keywords actually selected.\n The result is an iterable sequence of unicodes.\n \"\"\"\n\n def removableTags(self):\n \"\"\"\n This method return the list of keywords actually selected.\n The result is an iterable sequence of dictionaries :\n - name : the name of the tag. (unicode)\n - link : an http link that will be used in the template, for the tag.\n \"\"\"\n\n def getStartPath(self):\n \"\"\"\n This method return the complete start path\n \"\"\"\n\n def getLinkPath(self):\n \"\"\"\n This method calculates the link that will be used in the cloud HTML\n generation. It takes in consideration the currently selected keywords.\n This is an internal method. Never to be used outside the view itself.\n \"\"\"\n","repo_name":"collective/collective.vaporisation","sub_path":"collective/vaporisation/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":8769,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"31659776235","text":"from matplotlib import pyplot as plt\nimport numpy as np\n\nRESULTS_DIR = 'neural_results/'\n\ndef build_clustering_graph(save_name, all_scores):\n \"\"\"\n :param save_name: string\n :param all_scores: Dictionary mapping thresholds to tuples of (recall, precision, f1)\n :return:\n \"\"\"\n x = all_scores.keys()\n rpf1s = all_scores.values()\n recalls = [t[0] for t in rpf1s]\n precisions = [t[1] for t in rpf1s]\n f1s = [t[2] for t in rpf1s]\n\n f, axarr = plt.subplots(3, sharex=True) # sharing x axis\n axarr[0].set_title('Agglomerative clustering results from threshold tuning')\n\n axarr[0].plot(x, recalls, 'r-')\n axarr[0].set_ylabel('B3 recall')\n\n axarr[1].plot(x, precisions, 'b-')\n axarr[1].set_ylabel('B3 precision')\n\n axarr[2].plot(x, f1s, 'g-')\n axarr[2].set_ylabel('B3 F1')\n axarr[2].set_xlabel('Threshold')\n\n f.savefig(RESULTS_DIR + save_name + 'thresh_eval.png')\n plt.clf()\n\ndef build_results_graphs(save_name, epochs, train_loss, val_acc):\n bound = 0.2\n\n fig = plt.figure()\n axis1 = fig.add_subplot(211)\n plt.plot(epochs, train_loss, 'r-')\n plt.ylabel('Training loss')\n plt.axis([-1,max(epochs)+1, min(train_loss)-bound, max(train_loss)+bound])\n\n axis2 = fig.add_subplot(212)\n plt.plot(epochs, val_acc, 'b-')\n plt.xlabel('Epoch')\n plt.ylabel('Validation accuracy')\n plt.axis([-1,max(epochs)+1, min(val_acc)-bound, max(val_acc)+bound])\n\n fig.savefig(RESULTS_DIR + save_name + '.png')\n plt.clf()\n\nif __name__ == '__main__':\n fake_data = {i:[i, i**2, i**3] for i in map(lambda x: x/100., range(100))}\n build_clustering_graph('test_delete.png', fake_data)\n","repo_name":"kiankd/events","sub_path":"python/results_analysis.py","file_name":"results_analysis.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"55"} +{"seq_id":"2949088757","text":"import pybotters\n\nclass subaccountFTX:\n\n def __init__(self,ticker,asset,pair,client:pybotters.Client):\n self.client = client\n self.ticker = ticker\n self.asset = asset\n self.pair = pair\n\n ################## Subaccounts ################## \n\n\n async def get_all_subaccounts(self):\n \"\"\"get all subaccounts\"\"\"\n r = await self.client.get(\n \"/subaccounts\"\n )\n data = await r.json()\n return data[\"result\"]\n\n async def create_subaccount(self,subaccount):\n \"\"\"create subaccount\"\"\"\n r = await self.client.post(\n \"/subaccounts\",\n data={\"nickname\": subaccount}\n )\n data = await r.json()\n return data\n \n async def change_subaccount_name(self,nickname,newNickname):\n \"\"\"change subaccount name\"\"\"\n params = {\"nickname\": nickname, \"newNickname\": newNickname}\n r = await self.client.post(\n \"/subaccounts/update_name\",\n data=params\n )\n data = await r.json()\n return data\n\n async def delete_subaccount(self,nickname):\n \"\"\"delete subaccount\"\"\"\n params = {\"nickname\": nickname}\n r = await self.client.delete(\n \"/subaccounts\",\n data=params\n )\n data = await r.json()\n return data\n\n async def get_subaccount_balances(self,subaccount=None):\n \"\"\"get subaccount balances\"\"\"\n if subaccount == None: subaccount = self.subaccount\n r = await self.client.get(\n \"/subaccounts/{}/balances\".format(subaccount)\n )\n data = await r.json()\n return data[\"result\"]\n \n async def get_subaccount_balances_list(self,subaccount=None):\n \"\"\"get subaccount balances list\"\"\"\n data = await self.get_subaccount_balances(subaccount)\n balances = {}\n for i in range(len(data)):\n balances.setdefault(data[i][\"coin\"], data[i][\"free\"])\n return balances\n\n async def transfer_between_subaccounts(self,source, destination):\n \"\"\"transfer between subaccounts\"\"\"\n params = {\"source\": source, \"destination\": destination}\n r = await self.client.post(\n \"/subaccounts/transfer\",\n data=params\n )\n data = r.json()\n return data","repo_name":"shiohamu/pybottersWrap","sub_path":"pybottersWrap/pybottersFTX/subaccountFTX.py","file_name":"subaccountFTX.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"12764925720","text":"import socket\nimport time\n\n# Set up IP addresses and port\nSERVER_IP = '127.0.0.1' # replace with the IP address of the server (RPI)\n# CLIENT_IP = '10.154.60.204' # replace with the IP address of the client\n#CLIENT_IP = '10.153.14.30' # replace with the IP address of the client WILLIAMS\nCLIENT_IP = '192.168.1.224' # ip sending to\nPORT = 5501 # replace with any available port number\n\n# Create socket object\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # DGRAM MAKES IT UDP\n\n# Bind socket to client IP and port\n# s.bind((SERVER_IP, PORT))\n\n# Connect to server IP and port\n#s.connect((SERVER_IP, PORT))\n\n# Send message to server\nwhile True:\n message = 'Hello, server!'\n s.sendto(message.encode(), (CLIENT_IP, PORT))\n time.sleep(2) \n print(\"debug 🫡\")\n \n\n# Receive message from server\ndata = s.recv(1024)\nprint('Received from server:', data.decode())\n\n# Close socket connection\n#s.close()\n","repo_name":"MattPark965/ECE592AutoBoom","sub_path":"Working Directory/final-deliverables/TeamA22/src/rpi/socket_test.py","file_name":"socket_test.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"36439220222","text":"# Python classes and objects allow writing code in an object-oriented\n# way. To define a class, we use the \"class\" keyword, followed by a\n# block of statements. These statements are executed in a \"local\n# namespace\" associated to the class. Note: classes are themselves\n# objects. We can access class attributes with the dot \".\" operator\nfrom script import AClass as DClass\nfrom script import AClass as CClass\nfrom script import AClass as BClass\n\n\nclass AClass:\n x = 3\n\n def f(self):\n print(\"Hello World\")\n\n\nif __name__ == \"__main__\":\n print(AClass.x) # \"3\"\n print(AClass.f) # \"\" etc.\n\n# Class instances (called objects) can be created by “calling” the class\n# object. We'll use: \"from script import AClass as BClass\". We don't\n# have to use the \"as BClass\" part, but we had already defined a class\n# names AClass, so we won't want them to clash. Then:\nobj = BClass()\nprint(obj.x) # \"3\"\nprint(obj.f) # \"... \" etc.\nobj.f() # \"Hello World\"\n\n# The instantiated object allows for attribute look-up. Attributes can\n# be either \"data\" attributes (similar to variables, like \"x=3\" in our\n# example) or \"methods\" (like def \"f(self): print(\"Hello World\")\" in our\n# example). Similar to variables, data attributes are not declared, but\n# are created on assignment.\nobj = CClass()\nobj.z = 1\nprint(\"obj.z is\", obj.z)\nobj = DClass()\nobj.f() # Will print \"Hello World\"\nDClass.f(obj) # Will print \"Hello World\"\n\n# When a class is instantiated, its special method __init__ is invoked\n# (if not present, it’s inherited from the built-in ’object’ class). We\n# can use the method to initialize the object attributes:\n\n\nclass Point:\n name = \"2D Point\"\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n# Note: x and y are \"object\" attributes that are created on the new\n# object when it’s instantiated. Class attributes (e.g. name) are\n# \"shared\" by all instances. Class attributes are used in place of\n# object attributes whenever a given attribute is not found on an\n# object:\n\n\nclass A:\n x = 3\n\n def __init__(self, y):\n self.y = y\n\n\na = A(1)\nprint(a.x) # Will print 3\n\n# Note: Class attributes are shared among all instances of the class,\n# but can be masked by object attributes. In the example below, a.x = 4\n# creates a \"new\" attribute called x on the object a. (My further\n# explanation: \"so the object attribute of a (a.x) overrides the class\n# attribute of B (B.x). If we than change the attribute of B again\n# (B.x=5), a.x won't be affected, because as we've said before, a.x=4\n# created a 'new' attribute.\")\n\n\nclass B:\n x = 3\n\n\na = B()\nb = B()\nprint(a.x, b.x)\na.x = 4\nprint(a.x, b.x)\nB.x = 5\nprint(a.x, b.x)\n\n# However in the example below, doing \"c.z.append(4)\", not only modifies\n# c.z, but also modifies d.z too. This is because, in this case c.z is\n# not \"assigned\", but is \"accessed\". Since c has no attribute z, class C\n# is searched, and its z attribute is used. We then call a method of the\n# object \"C.z\". Its modifications are visible to all objects that do not\n# specify a local attribute z.\n\n\nclass C:\n z = [3]\n\n\nc = C()\nd = C()\nprint(c.z, d.z)\nc.z.append(4)\nprint(c.z, d.z)\n\n# Python classes can define \"special\" (or \"magic\") methods. These\n# methods, whose names start and end with a double underscore, allow\n# defining how the object should behave in particular cases, such as\n# when it appears in an expression. For example, the method \"__add__\"\n# allows defining how to compute the result of a sum (\"+\") of two\n# objects.\n\n\nclass PointClass:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n return PointClass(self.x+other.x, self.y+other.y)\n\n\np1 = PointClass(1, 2)\np2 = PointClass(5, 5)\np3 = p1+p2\nprint(p3.x, p3.y)\n\n# Other methods allow \"overriding\" different operators (arithmetic,\n# logical, slicing, getting and setting items, ...). For example, the\n# \"__str__\" method defines how an object is converted to a string:\n\n\nclass Point2:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __str__(self):\n return \"Point( % .2f, % .2f)\" % (self.x, self.y)\n\n\np = Point2(1, 2)\nprint(p)\n\n# Python allows a class to inherit from a different one. The syntax\n# requires specifying a comma-separated sequence of base classes:\n# class DerivedClass(Base1, Base2, Base3):\n# \n# Attribute look-up becomes more complex. For this course, we will\n# mainly use classes and objects to simulate C-style structures, i.e. as\n# containers of data. If you’re interested, you can learn more on Python\n# objected oriented programming on the Python tutorial and on the Python\n# documentation.\n","repo_name":"nogaykucuk/polito_2122_mlpr","sub_path":"14_ClassesObjects.py","file_name":"14_ClassesObjects.py","file_ext":"py","file_size_in_byte":4755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"37716305857","text":"import os\nfrom tkinter import *\nfrom tkinter.filedialog import askopenfilename\nfrom tkinter.scrolledtext import ScrolledText\nimport pyperclip as clip\nimport pymsgbox as pg\nimport requests\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n\ndef PlatformsToUpload(platforms=['Dev.to', 'Medium', \"CodeItDown\", \"All\"], title=\"Select the Platforms to Upload\", LabelText = None):\n if LabelText == None:\n LabelText = \"Select the Platforms to Upload\"\n root = Tk()\n root.geometry(\"500x500\")\n root.title(title)\n root.resizable(width=False, height=False)\n\n def MoveToNext():\n AllPlatformsSelected = \"\"\n for key, value in optionCheckBox.items():\n val = value.get()\n if val != 0:\n AllPlatformsSelected += f\"{key}+\"\n clip.copy(AllPlatformsSelected)\n root.destroy()\n\n InstalledApps = platforms\n\n optionCheckBox = {}\n\n if len(InstalledApps) == 0:\n pg.alert(\n \"No Videos/Blog Posts to Promote\", os.getenv(\"BotName\"))\n exit()\n else:\n for i in InstalledApps:\n optionCheckBox[f\"{i}\"] = IntVar()\n\n labl = Label(root, text=LabelText)\n labl.config(font=(\"Courier\", 12))\n labl.place(x=80, y=20)\n\n text = ScrolledText(root, width=60, height=15)\n text.place(x=8, y=60)\n for key, value in optionCheckBox.items():\n text.window_create('end', window=Checkbutton(text=key, variable=value))\n\n btn = Button(root, text=\"Post\", command=MoveToNext)\n btn.place(x=225, y=325)\n\n root.mainloop()\n\ndef getAllCateogarys():\n allCateogary = requests.get(f'{os.getenv(\"BlogDomain\")}/allCateogary/').json()\n licat = [x[\"Cateogary\"] for x in allCateogary]\n PlatformsToUpload(platforms=licat, title=\"Select The Cateogary's in which Blogs to be Uploaded\")\n\ndef getAllHashtags():\n allCateogary = requests.get(\n f'{os.getenv(\"BlogDomain\")}/hashtagall/').json()\n licat = [x[\"Hashtag\"] for x in allCateogary]\n PlatformsToUpload(platforms=licat, title=\"Select 4 Hashtags in which Blogs to be Uploaded\", LabelText=\"Select 4 Hashtags\")","repo_name":"coderaman7/Content-Manager","sub_path":"Manager/GraphicalComponents/OptionBox.py","file_name":"OptionBox.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"42536212819","text":"a = input()\na = {int(i) for i in a.split()}\n\nn = int(input())\n\nstrict_superset = True\nfor i in range(n):\n other_set = input()\n other_set = {int(j) for j in other_set.split()}\n \n if a.issuperset(other_set)==False:\n strict_superset = False\n \nprint(strict_superset)","repo_name":"satyamverma21/Practice_Python","sub_path":"py-check-strict-superset.py","file_name":"py-check-strict-superset.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"ceb","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"43411880454","text":"import pandas as pd\nfrom collections import Counter\nfrom utils.text import *\n\n\n########################################### Explore #################################################################\n\n# Occurence count of each column header\ndef get_column_labels_count(frame, duplicated_only=True):\n c = Counter(frame.columns)\n col_counts_df = pd.DataFrame.from_dict(dict(c.items()), orient='index')\n col_counts_df.columns = ['count']\n\n if duplicated_only:\n return col_counts_df[col_counts_df[\"count\"] > 1]\n\n return col_counts_df\n\n# Check whether there is a duplicated column or not\ndef has_duplicated_labels(frame, axis=1, verbose=False):\n has = get_duplicated_labels(frame, axis=axis).shape[0] > 0\n if has:\n print(get_duplicated_labels(frame))\n return has\n\n# return duplicated columns\ndef get_duplicated_labels(frame, axis=1):\n if axis == 1:\n return frame.columns[frame.columns.duplicated()]\n return frame.index[frame.index.duplicated()]\n\n\n########################################### Clean/edit #################################################################\n\n# Normalized column headers: Capital letter, remove special chars according to a provided map, replace\ndef get_clean_header_label(column_name, default_name='UNNAMED', char_map = None):\n if column_name is None or column_name.strip() == '':\n return default_name\n clean_label = remove_repetitive_chars(remove_special_chars(column_name), ' ').strip().replace(' ', '_').upper()\n if char_map:\n return replace_special_chars(clean_label, char_map)\n\n return char_map\n\n\ndef get_clean_header_labels(header, cleaner_lambda = lambda x : get_clean_header_label(x) ):\n if isinstance(header, pd.DataFrame):\n header.columns = get_clean_header_labels(header.columns, cleaner_lambda)\n return header\n\n return [cleaner_lambda(col) for col in header]\n\n\ndef merge_headers(frame, start_row, end_row, ffill=True, joiner_string=' '):\n '''\n Merge the rows from start_row to _end_row (inclusive) and set them as column header then drop those rows.\n This is for files where the header may be specified across several rows (category, name, unit) for example\n Category for example may be into a merged excel cells so a ffill may be needed first to not lose this info\n The label are concatenated using the joiner_string character.\n '''\n new_columns = frame.columns\n for i in range(start_row, end_row + 1):\n\n if ffill: # Treat multi-columns rows\n frame.iloc[i] = frame.iloc[i].fillna(method='ffill')\n\n if i == start_row:\n new_columns = frame.iloc[i].fillna('')\n else:\n new_columns += joiner_string + frame.iloc[i].fillna('')\n\n frame.columns = new_columns\n return frame.drop(range(start_row, end_row + 1))\n\n\ndef rename_duplicated_columns(frame, verbose=False):\n '''\n Add a _index suffix for duplicated columns starting at 1\n '''\n dup = get_column_labels_count(frame, True)\n\n if dup.shape[0] < 1:\n if verbose:\n print(\"No duplicated columns to rename\")\n return frame\n\n\n dup_columns_list = list(dup.index)\n\n dup_columns_counts = dict(zip(dup_columns_list, [0] * len(dup_columns_list)))\n\n new_columns = list(frame.columns)\n\n if verbose:\n print(\"Renaming: \", dup_columns_list)\n\n for ic, c in enumerate(frame.columns):\n if c in dup_columns_counts:\n new_columns[ic] = c + \"_\" + str(dup_columns_counts[c] + 1)\n dup_columns_counts[c] += 1\n\n frame.columns = new_columns\n\n return frame","repo_name":"ridhadev/MLToolbox","sub_path":"src/data/headers.py","file_name":"headers.py","file_ext":"py","file_size_in_byte":3583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"28924401186","text":"import time\nimport unittest\nfrom lbry.wallet.server.metrics import ServerLoadData, calculate_avg_percentiles\n\n\nclass TestPercentileCalculation(unittest.TestCase):\n\n def test_calculate_percentiles(self):\n self.assertEqual(calculate_avg_percentiles([]), (0, 0, 0, 0, 0, 0, 0, 0))\n self.assertEqual(calculate_avg_percentiles([1]), (1, 1, 1, 1, 1, 1, 1, 1))\n self.assertEqual(calculate_avg_percentiles([1, 2]), (1, 1, 1, 1, 1, 2, 2, 2))\n self.assertEqual(calculate_avg_percentiles([1, 2, 3]), (2, 1, 1, 1, 2, 3, 3, 3))\n self.assertEqual(calculate_avg_percentiles([4, 1, 2, 3]), (2, 1, 1, 1, 2, 3, 4, 4))\n self.assertEqual(calculate_avg_percentiles([1, 2, 3, 4, 5, 6]), (3, 1, 1, 2, 3, 5, 6, 6))\n self.assertEqual(calculate_avg_percentiles(\n list(range(1, 101))), (50, 1, 5, 25, 50, 75, 95, 100))\n\n\nclass TestCollectingMetrics(unittest.TestCase):\n\n def test_happy_path(self):\n self.maxDiff = None\n load = ServerLoadData()\n search = load.for_api('search')\n self.assertEqual(search.name, 'search')\n search.start()\n search.cache_response()\n search.cache_response()\n metrics = {\n 'search': [{'total': 40}],\n 'execute_query': [\n {'total': 20},\n {'total': 10}\n ]\n }\n for x in range(5):\n search.query_response(time.perf_counter() - 0.055 + 0.001*x, metrics)\n metrics['execute_query'][0]['total'] = 10\n metrics['execute_query'][0]['sql'] = \"select lots, of, stuff FROM claim where something=1\"\n search.query_interrupt(time.perf_counter() - 0.050, metrics)\n search.query_error(time.perf_counter() - 0.050, metrics)\n search.query_error(time.perf_counter() - 0.052, {})\n self.assertEqual(load.to_json_and_reset({}), {'status': {}, 'api': {'search': {\n \"receive_count\": 1,\n \"cache_response_count\": 2,\n \"query_response_count\": 5,\n \"intrp_response_count\": 1,\n \"error_response_count\": 2,\n \"response\": (53, 51, 51, 52, 53, 54, 55, 55),\n \"interrupt\": (50, 50, 50, 50, 50, 50, 50, 50),\n \"error\": (51, 50, 50, 50, 50, 52, 52, 52),\n \"python\": (12, 10, 10, 10, 10, 20, 20, 20),\n \"wait\": (12, 10, 10, 10, 12, 14, 15, 15),\n \"sql\": (27, 20, 20, 20, 30, 30, 30, 30),\n \"individual_sql\": (13, 10, 10, 10, 10, 20, 20, 20),\n \"individual_sql_count\": 14,\n \"errored_queries\": ['FROM claim where something=1'],\n \"interrupted_queries\": ['FROM claim where something=1'],\n }}})\n self.assertEqual(load.to_json_and_reset({}), {'status': {}, 'api': {}})\n","repo_name":"Astrotube-net/python-hub","sub_path":"tests/unit/wallet/server/test_metrics.py","file_name":"test_metrics.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"69960857132","text":"# IMPORTS #\nimport os\n\n\n# SOLUTIONS #\ndef solution_1(infile: str = 'year_2017/day_09/data.txt'):\n return Stream(_file_reader(infile)[0]).score()\n\n\ndef solution_2(infile: str = 'year_2017/day_09/data.txt'):\n return Stream(_file_reader(infile)[0]).count_garbage()\n\n\n# HELPERS #\ndef _file_reader(infile: str):\n if os.path.isfile(infile):\n with open(infile) as fin:\n return list(map(str.rstrip, fin.readlines()))\n else:\n raise ValueError(f'{infile} is not a file.')\n\n\n# GLOBALS #\n\n\n# EXCEPTIONS #\n\n\n# DECORATORS #\n\n\n# CLASSES #\nclass Stream:\n\n def __init__(self, stream: str):\n self.stream = stream\n\n def score(self):\n score = 0\n depth = 0\n i = 0\n garbage = False\n while i < len(self.stream):\n char = self.stream[i]\n if char == '{' and not garbage:\n depth += 1\n elif char == '}' and not garbage:\n score += depth\n depth -= 1\n elif char == '<' and not garbage:\n garbage = True\n elif char == '>':\n garbage = False\n elif char == '!':\n i += 1\n i += 1\n return score\n\n def count_garbage(self):\n i = 0\n garbage = False\n count = 0\n while i < len(self.stream):\n char = self.stream[i]\n if char == '<' and not garbage:\n garbage = True\n elif char == '!':\n i += 1\n elif char == '>':\n garbage = False\n elif garbage:\n count += 1\n i += 1\n return count\n\n\n# TESTS #\ndef test_cases_part_1():\n assert Stream('{}').score() == 1\n assert Stream('{{{}}}').score() == 6\n assert Stream('{{},{}}').score() == 5\n assert Stream('{{{},{},{{}}}}').score() == 16\n assert Stream('{,,,}').score() == 1\n assert Stream('{{},{},{},{}}').score() == 9\n assert Stream('{{},{},{},{}}').score() == 9\n assert Stream('{{},{},{},{}}').score() == 3\n print('Test successful.')\n\n\ndef test_cases_part_2():\n assert Stream('<>').count_garbage() == 0\n assert Stream('').count_garbage() == 17\n assert Stream('<<<<>').count_garbage() == 3\n assert Stream('<{!>}>').count_garbage() == 2\n assert Stream('').count_garbage() == 0\n assert Stream('>').count_garbage() == 0\n assert Stream('<{o\"i!a,<{i').count_garbage() == 10\n print('Test successful.')\n","repo_name":"enygma999/AdventOfCode","sub_path":"year_2017/day_09/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"38837188503","text":"import os, sys\nsys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))\n\nimport mechanize\nimport cookielib\nimport string\nimport random\nimport traceback\nimport requests\nimport urlparse\nfrom bs4 import BeautifulSoup\n\nfrom patterns import patterns, match_any_pattern\nimport extract\n\ndef get_form_index(br, form):\n index = 0\n for f in br.forms():\n equal = True\n form['class'] = form['clazz']\n for name, value in form.iteritems():\n if name in f.attrs:\n if str(f.attrs[name]).lower() != str(value).lower():\n equal = False\n break\n if equal:\n break\n index = index + 1\n return index\n\ndef submit_form(form, inputs, br = None):\n if br == None:\n br = mechanize.Browser()\n cj = cookielib.LWPCookieJar()\n br.set_cookiejar(cj)\n br.set_handle_robots(False)\n\n br.open(form['url'].encode(\"ascii\",\"ignore\"))\n br.select_form(nr=get_form_index(br, form))\n\n for input in form['inputs']:\n if input['name'] in inputs:\n try:\n if br.find_control(name = input['name'], type = input['type']) == None:\n continue\n if input['type'] == 'file':\n filename = inputs[input['name']]['filename']\n upload_filename = os.path.basename(filename)\n mime_type = inputs[input['name']]['mime_type']\n br.form.add_file(open(filename), mime_type, upload_filename, name = input['name'])\n br.form.set_all_readonly(False)\n elif input['type'] == 'checkbox':\n br.find_control(name = input['name'], type = input['type']).selected = inputs[input['name']]\n else:\n if br.find_control(name = input['name'], type = input['type']).readonly:\n continue\n if input['type'] == 'radio':\n continue\n br[input['name']] = inputs[input['name']]\n except:\n # traceback.print_exc()\n pass\n\n response = br.submit().code\n\n return response, br\n\ndef gen_random_value(chars = string.ascii_letters + string.digits, length = 0):\n if length == 0:\n length = random.choice(range(8, 21))\n return ''.join(random.choice(chars) for x in range(length))\n\ndef gen_random_true_false():\n return random.choice([True, False])\n\ndef gen_file(base_path, input):\n if input['name'] != '' and 'image' in input['name']:\n filename = os.path.join(os.path.dirname(__file__), os.pardir, \"files\", \"image.jpg\")\n mime_type = 'image/jpeg'\n else:\n filename = os.path.join(base_path, gen_random_value() + '.txt')\n with open(filename, 'w') as f:\n f.write(gen_random_value(length = 1000))\n f.close()\n mime_type = 'text/plain'\n return filename, mime_type\n\ndef fill_form(form, matched_patterns = {}, br = None):\n inputs = {}\n for input in form['inputs']:\n if input['value'] != '':\n continue\n for pattern_name in patterns:\n if input['type'] == 'hidden':\n continue\n pattern, value = patterns[pattern_name]\n if match_any_pattern(input['name'], pattern) or match_any_pattern(input['type'], pattern):\n if pattern_name in matched_patterns:\n inputs[input['name']] = matched_patterns[pattern_name]\n else:\n inputs[input['name']] = value[0]\n matched_patterns[pattern_name] = value[0]\n break\n elif input['type'] == 'checkbox':\n inputs[input['name']] = True\n else:\n inputs[input['name']] = gen_random_value()\n\n response, br = submit_form(form, inputs, br)\n\n return matched_patterns, inputs, response, br\n\ndef fill_form_random(form, br, base_path = '/tmp'):\n inputs = {}\n for input in form['inputs']:\n if input['value'] != '':\n continue\n if input['type'] == 'file':\n filename, mime_type = gen_file(base_path, input)\n inputs[input['name']] = {\n 'filename' : filename,\n 'mime_type': mime_type\n }\n elif input['type'] == 'checkbox':\n inputs[input['name']] = gen_random_true_false()\n else:\n inputs[input['name']] = gen_random_value()\n\n response, br = submit_form(form, inputs, br)\n\n return inputs\n\ndef submit_form_fast(form, inputs, files, session):\n new_url = urlparse.urljoin(form['url'], form['action'])\n if files == None:\n response = session.post(new_url, data = inputs)\n else:\n response = session.post(new_url, data = inputs, files = files)\n return response\n\ndef fill_form_random_fast(form, session, base_path = '/tmp'):\n inputs = {}\n files = None\n response = session.get(form['url'])\n soup = BeautifulSoup(response.text)\n for input in form['inputs']:\n if input['value'] != '':\n i = soup.find('input', {\"name\":input['name']})\n if i:\n inputs[input['name']] = i['value']\n continue\n if input['type'] == 'file':\n if files == None:\n files = {}\n filename, mime_type = gen_file(base_path, input)\n upload_filename = os.path.basename(filename)\n files[input['name']] = (upload_filename, open(filename), mime_type)\n elif input['type'] == 'checkbox':\n inputs[input['name']] = gen_random_true_false()\n else:\n inputs[input['name']] = gen_random_value()\n\n response = submit_form_fast(form, inputs, files, session)\n\n return inputs","repo_name":"cmu-db/cmdbac","sub_path":"core/drivers/submit/submit.py","file_name":"submit.py","file_ext":"py","file_size_in_byte":5778,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"55"} +{"seq_id":"10193619209","text":"import re\nfrom pathlib import Path\n\nfrom requirement_auditor import CONFIGURATION_MANAGER\n\nSTABLE_VERSION_REGEX = re.compile(r\"^(?P\\d+)\\.(?P\\d+)\\.?(?P\\d)?$\")\nFULLY_PINNED_REGEX = re.compile(r\"^(?P[\\w_\\-]+)==(?P[\\w.\\-]+)\\s*(?P#.*)?$\")\n\ntry:\n CONFIGURATION = CONFIGURATION_MANAGER.get_configuration()\n LOG_FOLDER = CONFIGURATION['logs']['folder']\n LOG_FILE = Path(f'{LOG_FOLDER}/{CONFIGURATION[\"logs\"][\"filename\"]}')\nexcept KeyError as e:\n error_message = f'Error getting logs configuration. Check the configuration file ' \\\n f'{CONFIGURATION_MANAGER.config_file}. Error {e}'\n LOG_FILE = CONFIGURATION_MANAGER.logs_folder / f'{CONFIGURATION_MANAGER.APP_NAME}.log'\n print(error_message)\n\nLOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": True,\n \"formatters\": {\n \"verbose\": {\n \"format\": \"%(levelname)s %(asctime)s %(module)s %(lineno)d \"\n \"%(process)d %(thread)d %(message)s\"\n }\n },\n \"handlers\": {\n \"console\": {\n \"level\": \"INFO\",\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"verbose\",\n },\n \"file\": {\n \"level\": \"DEBUG\",\n \"class\": \"logging.handlers.RotatingFileHandler\",\n \"formatter\": \"verbose\",\n \"filename\": str(LOG_FILE),\n \"maxBytes\": 1024 * 1024,\n \"backupCount\": 3\n }\n },\n \"loggers\": {\n 'requirement_auditor': {\n \"level\": \"INFO\",\n \"handlers\": ['console', 'file'],\n \"propagate\": False\n },\n 'johnnydep': {\n \"level\": \"INFO\",\n \"handlers\": ['console', 'file'],\n \"propagate\": False\n },\n },\n \"root\": {\"level\": \"INFO\", \"handlers\": [\"console\", ]},\n}\n","repo_name":"luiscberrocal/requirement-auditor","sub_path":"requirement_auditor/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"72505162091","text":"from datetime import datetime, timedelta\nfrom ci.models.spatial_reference import RAP_Spatial_Reference\nfrom ci.util.gdal_helper import find_band_num, get_band_metadata\nfrom ci.models.gdal_raster import GDALRaster\nfrom ci.ingest import config, logger, proj_helper, base_ingestor\n\n__author__ = 'ujjwal'\n\nvariables = {\n\n \"CAPE0\": {\n \"GRIB_ELEMENT\": \"CAPE\",\n \"GRIB_SHORT_NAME\": \"0-SFC\"\n },\n\n \"CAPE1\": {\n \"GRIB_ELEMENT\": \"CAPE\",\n \"GRIB_SHORT_NAME\": \"18000-0-SPDL\"\n },\n\n \"CAPE2\": {\n \"GRIB_ELEMENT\": \"CAPE\",\n \"GRIB_SHORT_NAME\": \"25500-0-SPDL\"\n },\n\n \"CAPE3\": {\n \"GRIB_ELEMENT\": \"CAPE\",\n \"GRIB_SHORT_NAME\": \"9000-0-SPDL\"\n },\n\n \"CIN0\": {\n \"GRIB_ELEMENT\": \"CIN\",\n \"GRIB_SHORT_NAME\": \"0-SFC\"\n },\n\n \"CIN1\": {\n \"GRIB_ELEMENT\": \"CIN\",\n \"GRIB_SHORT_NAME\": \"18000-0-SPDL\"\n },\n\n \"CIN2\": {\n \"GRIB_ELEMENT\": \"CIN\",\n \"GRIB_SHORT_NAME\": \"25500-0-SPDL\"\n },\n\n \"CIN3\": {\n \"GRIB_ELEMENT\": \"CIN\",\n \"GRIB_SHORT_NAME\": \"9000-0-SPDL\"\n },\n\n \"HTFL_HGT\": {\n \"GRIB_ELEMENT\": \"HGT\",\n \"GRIB_SHORT_NAME\": \"0-HTFL\"\n },\n\n \"HTFL_RH\": {\n \"GRIB_ELEMENT\": \"RH\",\n \"GRIB_SHORT_NAME\": \"0-HTFL\"\n },\n\n \"UGRD\": {\n \"GRIB_ELEMENT\": \"UGRD\",\n \"GRIB_SHORT_NAME\": \"10-HTGL\"\n },\n\n \"VGRD\": {\n \"GRIB_ELEMENT\": \"VGRD\",\n \"GRIB_SHORT_NAME\": \"10-HTGL\"\n },\n\n \"DEWPOINT\": {\n \"GRIB_ELEMENT\": \"DPT\",\n \"GRIB_SHORT_NAME\": \"2-HTGL\"\n },\n\n \"RAP_REFL\": {\n \"GRIB_ELEMENT\": \"REFC\",\n \"GRIB_SHORT_NAME\": \"0-EATM\"\n }\n}\n\n\ndef process_file(rap_file):\n provider_name = \"RAP\"\n srid = RAP_Spatial_Reference.epsg\n\n logger.info(\"Ingesting file %s\" % rap_file)\n for variable in variables:\n logger.info(\"Processing variable %s\" % variable)\n band_num = find_band_num(rap_file, filterr=variables[variable])\n\n if band_num is None:\n #raise Exception(\"Could not find band for %s\" % variable)\n logger.error(\"Could not find band for %s\" % variable)\n else:\n vars = [\"GRIB_REF_TIME\", \"GRIB_VALID_TIME\"]\n datevalues = get_band_metadata(rap_file, band_num, vars)\n startdate_utc_str = (datevalues[\"GRIB_REF_TIME\"].split())[0]\n enddate_utc_str = (datevalues[\"GRIB_VALID_TIME\"].split())[0]\n\n start_date = datetime.utcfromtimestamp(float(startdate_utc_str))\n #end_date = datetime.fromtimestamp(float(enddate_utc_str))\n end_date = start_date + timedelta(hours=1)\n\n block_size = (10, 10)\n ras = GDALRaster(rap_file, srid)\n ras.set_band_num(band_num)\n if variable == \"RAP_REFL\":\n ras.nodata_range = [-999, -9]\n\n level = int((variables[variable][\"GRIB_SHORT_NAME\"].split(\"-\"))[0])\n granule_name = \"%s_%s %s_%d\" % (provider_name, variable, start_date.strftime(\"%Y%m%d %H:%M\"), level)\n table_name = \"%s_%s_%s_%d\" % (provider_name, variable, start_date.strftime(\"%Y%m%d%H%M\"), level)\n bbox = proj_helper.get_bbox(srid)\n base_ingestor.ingest(ras=ras, provider_name=provider_name, variable_name=variable, granule_name=granule_name,\n table_name=granule_name, srid=srid, level=level, block_size=block_size, dynamic=False,\n start_time=start_date, end_time=end_date, subset_bbox=bbox, overwrite=True, threshold=None)\n\nif __name__ == \"__main__\":\n from multiprocessing import Pool\n\n df = config.datafiles[\"RAP\"]\n if isinstance(df[\"wildcard\"], list):\n files = []\n for wc in df[\"wildcard\"]:\n files += base_ingestor.get_ingest_files(df[\"folder\"], wc)\n else:\n files = base_ingestor.get_ingest_files(df[\"folder\"], df[\"wildcard\"])\n\n parallel = config.parallel\n if parallel:\n n_proc = config.nprocs\n pool_size = min(n_proc, len(files))\n\n p = Pool(pool_size)\n p.map(process_file, files)\n\n p.close()\n p.join()\n else:\n for file in files:\n process_file(file)\n","repo_name":"ujjwaln/cageo","sub_path":"ci/ingest/rap_ingestor.py","file_name":"rap_ingestor.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"26308604905","text":"import cv2\nimport os \ndef resize_images(input_folder, out_folder ,img_name , scale_percent):\n #scale_percent = percent of original size\n input_path = input_folder+'/'+img_name\n image = cv2.imread(input_path)\n width_new = int(image.shape[1] * scale_percent)\n height_new = int(image.shape[0] * scale_percent)\n dim = (width_new,height_new)\n resize_image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)\n\n # reset name\n img_name , img_type = img_name.split(\".\")\n out_path = out_folder+'/'+img_name + \".\" + img_type\n cv2.imwrite( out_path, resize_image )\n\nif __name__=='__main__':\n input_folder = r'datasets\\no_decoded\\raw_dataset_HR'\n out_folder = r'datasets\\no_decoded\\dataset_LR'\n files= os.listdir(input_folder)\n for idx in range(len(files)):\n resize_images( input_folder ,out_folder , files[idx] , (1/3))","repo_name":"elina20chihlingliu/2021-VRDL-HW4-Image-Super-Resolution","sub_path":"resize.py","file_name":"resize.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"7071228555","text":"import requests\nimport json\nimport pandas as pd\n\n#data of specific general time measurment used for getting channels ids.\ndata = [{\"id\": 1, \"name\": \"WSmax\", \"alias\": 0, \"value\": 2.1, \"status\": 2, \"valid\": False, \"description\": 0},\n {\"id\": 2, \"name\": \"WDmax\", \"alias\": 0, \"value\": 302.0, \"status\": 2, \"valid\": False, \"description\": 0}, \n {\"id\": 3, \"name\": \"WS\", \"alias\": 0, \"value\": 1.2, \"status\": 2, \"valid\": False, \"description\": 0}, \n {\"id\": 4, \"name\": \"WD\", \"alias\": 0, \"value\": 267.0, \"status\": 2, \"valid\": False, \"description\": 0}, \n {\"id\": 5, \"name\": \"STDwd\", \"alias\": 0, \"value\": 28.5, \"status\": 2, \"valid\": False, \"description\": 0}, \n {\"id\": 6, \"name\": \"TD\", \"alias\": 0, \"value\": 25.2, \"status\": 1, \"valid\": True, \"description\": 0}, \n {\"id\": 7, \"name\": \"RH\", \"alias\": 0, \"value\": 70.0, \"status\": 1, \"valid\": True, \"description\": 0}, \n {\"id\": 8, \"name\": \"TDmax\", \"alias\": 0, \"value\": 25.2, \"status\": 1, \"valid\": True, \"description\": 0}, \n {\"id\": 9, \"name\": \"TDmin\", \"alias\": 0, \"value\": 25.1, \"status\": 1, \"valid\": True, \"description\": 0}, \n {\"id\": 10, \"name\": \"Grad\", \"alias\": 0, \"value\": 0.0, \"status\": 1, \"valid\": True, \"description\": 0}, \n {\"id\": 11, \"name\": \"NIP\", \"alias\": 0, \"value\": 2.0, \"status\": 1, \"valid\": True, \"description\": 0}, \n {\"id\": 12, \"name\": \"DiffR\", \"alias\": 0, \"value\": 1.0, \"status\": 1, \"valid\": True, \"description\": 0}, \n {\"id\": 13, \"name\": \"WS1mm\", \"alias\": 0, \"value\": 1.6, \"status\": 2, \"valid\": False, \"description\": 0}, \n {\"id\": 15, \"name\": \"Ws10mm\", \"alias\": 0, \"value\": 1.8, \"status\": 2, \"valid\": False, \"description\": 0}, \n {\"id\": 16, \"name\": \"Time\", \"alias\": 0, \"value\": 2.0, \"status\": 2, \"valid\": False, \"description\": 0}, \n {\"id\": 20, \"name\": \"Rain\", \"alias\": 0, \"value\": 0.0, \"status\": 1, \"valid\": True, \"description\": 0}]\n\ndef getChannelIds():\n \"\"\"\n Iterating over data to return all castings between feature name and its id.\n :return: Dictionary of names as keys and ids as values.\n \"\"\"\n res = {}\n for row in data:\n res[row[\"name\"]] = row[\"id\"]\n return res\n\n","repo_name":"talperchuk/ProjectAI","sub_path":"GetChannels.py","file_name":"GetChannels.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"71648869290","text":"import sys\n\nN, K = map(int, sys.stdin.readline().split())\n\nnumber = list(map(str, sys.stdin.readline().rstrip()))\n\nstack = []\ncount = 0\nfor idx, num in enumerate(number):\n if len(stack) == 0:\n stack.append(num)\n continue\n if count == K:\n if idx <= len(number) - 1:\n while idx <= len(number)-1:\n stack.append(number[idx])\n idx += 1\n break\n if stack[-1] < num:\n stack.append(num)\n while len(stack) > 1:\n if count == K:\n break\n if stack[-2] < stack[-1]:\n temp = stack[-1]\n stack.pop(-1)\n stack.pop(-1)\n stack.append(temp)\n count += 1\n else:\n break\n else:\n stack.append(num)\n\nif count < K:\n stack = stack[:-(K-count)]\n\nprint(\"\".join(stack))\n","repo_name":"Zigje9/Algorithm_study","sub_path":"python/2812.py","file_name":"2812.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"73786120810","text":"from django.conf.urls import include, url,patterns\nfrom rest_framework import routers\nfrom .views import (Index,dinar_list,dinar_detail,DinarViewSet,ItemViewSet,DinarList,DinarItem,DinDetail,Detail,AddDin ,AddItem,DinExcept,DeleteList,\n DeleteItem)\n\nrouter = routers.DefaultRouter()\nrouter.register(r'dinar', DinarViewSet)\n#router.register(r'period', PeriodViewSet)\nrouter.register(r'itens', ItemViewSet)\n\nurlpatterns = patterns('apps.con.views',\n (r'^',include(router.urls)),\n (r'^index$',Index),\n (r'^addDin$',AddDin),\n (r'^addItem/(?P[0-9]+)$',AddItem),\n (r'^detail/(?P[0-9]+)$',Detail),\n (r'^dinars/$', dinar_list),\n (r'^dinar_detail/(?P[0-9]+)$', dinar_detail),\n (r'^dinarlist/$', DinarList),\n (r'^dinaritem/$', DinarItem),\n (r'^dindetail/(?P[0-9]+)$', DinDetail),\n (r'^dinexcept/(?P[0-9]+)$', DinExcept),\n (r'^dellist/(?P[0-9]+)$', DeleteList),\n (r'^delitem/(?P[0-9]+)$', DeleteItem),\n)\n","repo_name":"amaur/Mcon","sub_path":"apps/con/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"16108200284","text":"# input : n, connections : [시작노드, 끝노드]\n\nclass Solution:\n # List[List[int]] : int형의 2차원 배열\n def minReorder(self, n:int, connections:List[List[int]]) -> int:\n edges = { (a,b) for a, b in connections}\n # city:[]는 딕셔너리임. key는 city, value는 배열\n neighbors = {city:[] for city in range(n)}\n visit = set()\n changes = 0\n\n for a, b in connections:\n neighbors[a].append(b)\n neighbors[b].append(a)\n\n def dfs(city):\n # nonlocal : 지역변수가 아님을 선언, 한 단계 바깥쪽에 위치한 변수와 바인딩\n nonlocal edges, neighbors, visit, changes\n\n for neighbor in neighbors[city]:\n if neighbor in visit:\n continue\n # check if this neighbor can reach city 0\n if (neighbor, city) not in edges:\n changes += 1\n visit.add(neighbor)\n dfs(neighbor)\n visit.add(0)\n dfs(0)\n return changes","repo_name":"silver-whale/LeetCode","sub_path":"Python/Leetcode1466.py","file_name":"Leetcode1466.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"39543859580","text":"import json\nfrom pathlib import Path\n\npath = Path('./starknetid.json')\noutput = path.parent / 'result.json'\n\nwith open(path, 'r') as fin:\n data = json.load(fin)\n\nnodes = data.get('nodes')\nlinks = data.get('links')\n\ntargets, sources = zip(*[(link.get('target'), link.get('source')) for link in links])\nlink_nodes = targets + sources\nunique_link_nodes = set(link_nodes)\nprint(len(unique_link_nodes))\n\nremoves = [node for node in unique_link_nodes if link_nodes.count(node) > 1]\nremoves = [node for node in unique_link_nodes if link_nodes.count(node) > 1]\nprint(len(removes))","repo_name":"carbonable-labs/sybil-shield","sub_path":"filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"55"} +{"seq_id":"24364689913","text":"from fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\nimport logging\nfrom typing import List\nfrom . import config, crud\nfrom .database import MongoDB\nfrom .schemas import FeedbackUpdate, FeedbackCreate, Feedback\n\n\n################\n## INITIALIZE ##\n################\nlogger = logging.getLogger(\"feedback-service\")\nlogging.basicConfig(level=logging.INFO, \n format=\"[%(levelname)s][%(name)s][%(filename)s, line %(lineno)d]: %(message)s\")\n\nlogger.info(\"Service configuration loading...\")\ncfg: config.Config = config.load_config()\n\nlogger.info(\n 'Service configuration loaded:\\n' +\n f'{cfg.model_dump_json(by_alias=True, indent=4)}'\n)\n\nlogger.info(\"Service database loading...\")\nMongoDB(mongo_dsn=str(cfg.mongo_dsn))\nlogger.info(\"Service database loaded\")\n\n\n\napp = FastAPI(\n version='0.0.1',\n title='feedback service'\n)\n\n\n@app.get(\"/feedbacks\", \n summary=\"Returns all feedbacks\",\n response_model=List[Feedback],\n tags=['feedbacks']\n)\nasync def get_feedbacks(skip: int = 0, limit: int = 10):\n return crud.get_feedbacks(skip, limit)\n\n\n@app.post(\"/feedbacks\", \n summary=\"Add new feedback\",\n response_model=Feedback,\n tags=['feedbacks']\n)\nasync def add_feedback(feedback: FeedbackCreate) -> Feedback:\n return crud.add_feedback(feedback)\n\n\n@app.get(\"/feedbacks/{feedback_id}\", \n summary=\"Get feedback by id\",\n tags=['feedbacks']\n)\nasync def get_feedback_uid(feedback_id: str) -> Feedback:\n feedback = crud.get_feedback_by_uid(feedback_id)\n if feedback is None:\n return JSONResponse(status_code=404, content={\"message\": \"Not found\"})\n return feedback\n\n\n@app.put(\"/feedbacks/{feedback_id}\", \n summary=\"Update feedback info by id\",\n tags=['feedbacks']\n)\nasync def update_feedback(feedback_id: str, feedback_update: FeedbackUpdate) -> Feedback:\n feedback = crud.update_feedback_by_uid(feedback_id, feedback_update)\n if feedback is None:\n return JSONResponse(status_code=404, content={\"message\": \"Not found\"})\n return feedback\n\n\n@app.delete(\"/feedbacks/{feedback_id}\", \n summary=\"Delete feedback by id\",\n tags=['feedbacks']\n)\nasync def delete_feedback(feedback_id: str) -> Feedback:\n return crud.remove_feedback_by_uid(feedback_id)\n\n","repo_name":"MeRaLd2/Online-store","sub_path":"services/feedback-service/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"38133729169","text":"from os import getenv\n\nimport requests\n\n\ndef send_message(message: str):\n api_telegram = getenv(\"API_TELEGRAM\")\n bot_key = getenv(\"BOT_KEY\")\n chat_id = getenv(\"CHAT_ID\")\n requests.get(\n url=f\"{api_telegram}/bot{bot_key}/sendMessage?chat_id={chat_id}&text={message}\"\n )\n","repo_name":"Mateusmsouza/srbarriga","sub_path":"app/connections/send_message.py","file_name":"send_message.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"55"} +{"seq_id":"74280460650","text":"import numpy as np\nfrom units_and_constants import phys\nfrom make_grid import make_grid, make_axes\n\nimport deltaB_subroutine\n\n\n'''\nimport biot_savart as bs\nimport numpy as np\nX0 = np.array([[0.,1,2],[2,2,2]])\nX= 1.*np.arange(18).reshape(6,3)\nJ = 10*X\nresult = bs.deltaB('dB', X0, X, J)\n\n\nresult.shape\n\nX0[0,:]\nX0[1,:]\n\n\na=bs.deltaB('dB', X0[0,:], X, J)\nb=bs.deltaB('dB', X0[1,:], X, J)\nap=bs.deltaB_old('dB', X0[0,:], X, J)\nbp=bs.deltaB_old('dB', X0[1,:], X, J)\na==ap\nb==bp\n\n\n\nap==result[0,:,:]\nbp==result[1,:,:]\n'''\n\ndef deltaB_wrap_Nx3(variable, X0, X, J, V_char = 1.):\n #X and J must be (N,3)\n #X0 must be (M,3)\n print('\\n\\n from deltaB_wrap_Nx3 \\n\\n')\n\n\ndef deltaB_wrap_3xN():\n pass\n\n\ndef deltaB(variable, X0, X, J, V_char = 1.):\n print('\\n\\n from deltaB \\n\\n')\n\n X=np.array(X)\n if X.shape == (3,):\n X=np.array([X])\n\n X0=np.array(X0)\n if X0.shape == (3,):\n X0=np.array([X0])\n\n X0 = np.repeat([X0], X.shape[0], axis=0)\n memloc = X0.__array_interface__['data'][0]\n X0=np.swapaxes(X0,0,1)\n print(memloc == X0.__array_interface__['data'][0])\n\n num_eval_pts = X0.shape[0]\n\n R = np.repeat([X], num_eval_pts, axis=0)\n del X\n R *= -1\n R += X0\n del X0\n\n dB = np.repeat([J], num_eval_pts, axis=0) #extended J right now, but will become dB after modifications\n\n rcut = 1.733*np.cbrt(V_char) # np.sqrt(3) == 1.7320508075688772\n Rcubed = np.einsum('ijk,ijk->ij',R,R)**1.5\n #divRcubed = 1./Rcubed\n #https://stackoverflow.com/questions/26248654/how-to-return-0-with-divide-by-zero/40022737\n divRcubed = np.divide(1., Rcubed, out=np.zeros_like(Rcubed), where=(Rcubed >= rcut**3))\n\n #dB = np.cross(dB, R)\n dB = dB.transpose()\n R = R.transpose()\n deltaB_subroutine.cross(dB, R)\n dB = dB.transpose()\n del R\n print('checkpoint')\n\n #dB = np.einsum('ijk,ij->ijk', dB, divRcubed)\n dB *= divRcubed[:,:,None]\n\n dB *= phys['mu0']/(4*np.pi)\n try: #!!!!! better way?\n V_char.shape\n dB = np.einsum('i,ij->ij', V_char, dB)\n except:\n dB *= V_char\n\n if(variable=='dB'):\n if dB.shape[0]==1:\n dB = dB[0,:,:]\n return dB\n deltaB = np.sum(dB, axis=1)\n if(variable=='deltaB'):\n if deltaB.shape[0]==1:\n deltaB = deltaB[0,:]\n return deltaB\n return np.nan\n\n\n\ndef deltaB_old(variable, x0, X, J, V_char = 1.):\n print('\\n\\n from deltaB_old \\n\\n')\n X=np.array(X)\n if X.shape == (3,):\n X=np.array([X])\n\n x0=np.array(x0)\n \n\n X0 = np.repeat([x0], X.shape[0], axis=0)\n R = X0 - X\n\n rcut = 1.733*np.cbrt(V_char) # np.sqrt(3) == 1.7320508075688772\n Rcubed = (R[:,0]**2 + R[:,1]**2 + R[:,2]**2)**1.5\n #Rcubed = np.einstum('ij,ij->i',R,R)**1.5\n #divRcubed = 1./Rcubed\n #https://stackoverflow.com/questions/26248654/how-to-return-0-with-divide-by-zero/40022737\n divRcubed = np.divide(1., Rcubed, out=np.zeros_like(Rcubed), where=(Rcubed >= rcut**3))\n\n dB = (phys['mu0']/(4*np.pi))*( np.cross(J, R)*divRcubed[:,np.newaxis] ) #https://stackoverflow.com/questions/5795700/multiply-numpy-array-of-scalars-by-array-of-vectors\n #''''''''''''''''''''''''''''' np.einsum('ij,i->ij', np.cross(J, R), divRcubed)\n try: #!!!!! better way?\n V_char.shape\n dB = np.einsum('i,ij->ij', V_char, dB)\n except:\n dB = V_char*dB\n\n if(variable=='dB'):\n return dB\n\n deltaB = np.sum(dB, axis=0)\n if(variable=='deltaB'):\n return deltaB\n\n return np.nan\n\n\ndef biot_savart_run(run, time, pts, regions, summed=True, separateRegions=False):\n import os\n import sys\n sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../')\n from config import conf\n import util\n from probe import GetRunData\n\n if isinstance(regions, dict):\n regions = (regions,)\n\n if (not summed) and (not separateRegions):\n raise ValueError('cannot join unsummed regions')\n\n ret = []\n for region in list(regions):\n ax_list = make_axes(region['xlims'], region['ylims'], region['zlims'], region['d'])\n G = make_grid(ax_list, slices=False)\n J = GetRunData(run, time, G, 'j')\n J *= phys['muA']/(phys['m']**2)\n\n if summed:\n result = deltaB('deltaB', pts, G, J, V_char = region['d']**3)\n else:\n result = deltaB('dB', pts, G, J, V_char = region['d']**3)\n\n ret.append(result.copy())\n\n if summed:\n ret = np.array(ret)\n if separateRegions:\n return ret\n return np.sum(ret, axis=0)\n\n if len(ret) == 1:\n return ret[0]\n\n return ret\n\nif __name__ == '__main__':\n run = 'DIPTSUR2'\n time = (2019,9,2,6,30,0)\n\n #reg = {'xlims': (-31.875, 46.875), \n # 'ylims': (-31.875, 30.875),\n # 'zlims': (-31.875, 30.875), \n # 'd': 0.25}\n\n #reg = {'xlims': (-31.875, 31.875), \n # 'ylims': (-31.875, 31.875),\n # 'zlims': (-31.875, 31.875), \n # 'd': 0.25}\n\n reg = {'xlims': (-31.875, 31.875), 'd': 0.25, 'zlims': (-31.875, 30.875), 'ylims': (-31.875, 30.875)}\n\n ret = biot_savart_run(run, time, np.array([15., -1., -1.]), (reg,), separate=True)\n\n print(ret)\n print(ret.shape)\n\n","repo_name":"GaryQ-physics/magnetosphere","sub_path":"physics/biot_savart.py","file_name":"biot_savart.py","file_ext":"py","file_size_in_byte":5203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"22360634539","text":"\"\"\"\nGiven a list of edges, a start node, and an end node,\nreturn the shortest path between Start and End\n1 - 2 - 3\n \\ /\n 5 - 4\n\n 6 - 7\n\n\"\"\"\n\nedges = [\n [1,2],\n [2,3],\n [4,5],\n [5,1],\n [3,4],\n [6,7],\n [7,6],\n]\n\ndef shortest_path(edges, start, end):\n # plan: dfs (stack)\n # keep count of current sequence length\n # keep high score (result) of shortest found length\n graph = make_graph(edges)\n curr_seq = []\n result = edges[:]\n # print(graph)\n\n stack = [start]\n curr = None\n visited = set()\n while len(stack) > 0:\n curr = stack.pop()\n visited.add(curr)\n curr_seq.append(curr)\n if curr == end:\n if len(curr_seq) < len(result):\n result = curr_seq[:]\n curr_seq = []\n print(\"found path\", result)\n for node in graph[curr]:\n if node not in visited:\n stack.append(node) \n return result\n\n\ndef shortest_path(edges, start, end):\n \"\"\" PLAN: BFS, and keep track of visited bc it's non-directional.\n Also keep track of the length of the combo - as you add nodes onto the queue,\n increment the path length to take that particular paath.\n \"\"\"\n graph = make_graph(edges)\n q = [(start, 0)] # initialize queue with start node and length of current pattern\n curr = None\n visited = {start}\n while len(q) > 0:\n curr, length = q.pop()\n visited.add(curr)\n if curr == end:\n return length\n for node in graph[curr]:\n if node not in visited and node not in q:\n q.insert(0, (node, length + 1))\n return -1\n\n\n\n\ndef make_graph(edges):\n graph = dict()\n for edge in edges:\n x,y = edge\n if x not in graph:\n graph[x] = []\n if y not in graph:\n graph[y] = []\n graph[x] += [y]\n graph[y] += [x]\n return graph\n\nprint(shortest_path(edges, 1, 4))\nprint(shortest_path(edges, 1, 3))\nprint(shortest_path(edges, 1, 2))\nprint(shortest_path(edges, 7, 5))","repo_name":"mariapan0330/CodeWars-LeetCode-Problems","sub_path":"Interview Practice/grid traversal/shortest_path.py","file_name":"shortest_path.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"24210536648","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Dec 14 16:46:43 2018\r\n\r\n@author: Zongyue Qin\r\n\"\"\"\r\n\r\nimport pickle\r\nimport numpy as np\r\n\r\nfile_loc = '../dataset/cifar-10-batches-py/'\r\ntrain_data_prefix = '/data_batch_'\r\ntest_data_file = '/test_batch'\r\nmeta_file = '/batches.meta'\r\n\r\ndef load_data():\r\n X=None\r\n y=None\r\n Xtest=None\r\n ytest=None\r\n labels = None\r\n \r\n filename = file_loc + meta_file\r\n with open(filename, 'rb') as file:\r\n data = pickle.load(file, encoding='bytes')\r\n labels = data.get(b'label_names')\r\n \r\n filename = file_loc+train_data_prefix+'1'\r\n with open(filename, 'rb') as file:\r\n data = pickle.load(file, encoding='bytes')\r\n X = data.get(b'data')\r\n y = data.get(b'labels')\r\n \r\n for i in range(2,6):\r\n filename = file_loc + train_data_prefix+str(i)\r\n with open(filename, 'rb') as file:\r\n data = pickle.load(file, encoding='bytes')\r\n Xtmp = data.get(b'data')\r\n ytmp = data.get(b'labels')\r\n X = np.concatenate((X, Xtmp))\r\n y = np.concatenate((y, ytmp))\r\n \r\n \r\n filename = file_loc+test_data_file\r\n with open(filename, 'rb') as file:\r\n data = pickle.load(file, encoding='bytes')\r\n Xtest = data.get(b'data')\r\n ytest = data.get(b'labels')\r\n \r\n return X, y, Xtest, ytest, labels","repo_name":"ZongyueQin/ImageClassifierOnCifar","sub_path":"Image Classification/code/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"28974860273","text":"\"\"\"empty message\n\nRevision ID: 50683aeb21b9\nRevises: 7b250ac636e2\nCreate Date: 2019-02-09 19:05:23.162191\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '50683aeb21b9'\ndown_revision = '7b250ac636e2'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n # op.create_foreign_key(None, 'tagmap', 'papers', ['paper_id'], ['id'])\n op.add_column('teaching', sa.Column('code', sa.String(length=300), nullable=False))\n op.add_column('teaching', sa.Column('link', sa.String(length=300), nullable=False))\n # op.alter_column('users', 'email',\n # existing_type=mysql.VARCHAR(length=120),\n # nullable=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('users', 'email',\n existing_type=mysql.VARCHAR(length=120),\n nullable=True)\n op.drop_column('teaching', 'link')\n op.drop_column('teaching', 'code')\n op.drop_constraint(None, 'tagmap', type_='foreignkey')\n # ### end Alembic commands ###\n","repo_name":"cosanlab/cosanlab_website","sub_path":"migrations/versions/50683aeb21b9_.py","file_name":"50683aeb21b9_.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"962959474","text":"# -*- coding: utf-8 -*-\nfrom urllib.parse import urljoin\n\nimport scrapy\nfrom fake_useragent import UserAgent\n\nBASE_URL = 'http://milanuncios.com/alquiler-de-pisos-en-tarragona-tarragona/'\nUA = UserAgent()\n\n\nclass MilanSpider(scrapy.Spider):\n name = 'milan'\n allowed_domains = ['milanuncios.com']\n start_urls = [\n f'{BASE_URL}'\n '?fromSearch=1&hasta=500&vendedor=inmo'\n ]\n custom_settings = {\n 'DEFAULT_REQUEST_HEADERS': {\n 'authority': 'www.milanuncios.com',\n 'dnt': '1',\n 'upgrade-insecure-requests': '1',\n 'user-agent': UA.random,\n 'sec-fetch-dest': 'document',\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'sec-fetch-site': 'none',\n 'sec-fetch-mode': 'navigate',\n 'sec-fetch-user': '?1',\n 'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,es;q=0.6',\n }\n }\n\n def parse(self, response):\n for item in response.xpath('//div[@class=\"aditem-detail\"]'):\n url = item.xpath('./a[@class=\"aditem-detail-title\"]/@href')[0].root\n price = float(item.xpath('.//div[@class=\"aditem-price\"]/text()')[0].root.replace('.', ''))\n yield {\n 'url': urljoin(BASE_URL, url),\n 'price': price,\n 'rooms': 2,\n }\n","repo_name":"FilArt/alquiler-bot","sub_path":"spiders/milan.py","file_name":"milan.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"11772364006","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 28 13:33:55 2017\n\n@author: hanbyulkim\n\"\"\"\nimport sys\nrl = lambda: sys.stdin.readline()\n\nclass TriPath:\n def __init__(self, N, board):\n self.N = N\n self.cache = [[-1 for _ in range(N)] for _ in range(N)]\n self.board = board\n \n def path(self, y, x):\n if self.cache[y][x] != -1:\n return self.cache[y][x]\n\n cur_value = self.board[y][x]\n if y == self.N-1:\n self.cache[y][x] = cur_value\n return cur_value\n\n ret = cur_value + max(self.path(y+1, x), self.path(y+1, x+1))\n self.cache[y][x] = ret\n return ret\n \n def path_num(self, y, x):\n self.path(0, 0)\n \n if y == self.N - 1: \n return 1\n \n left = self.cache[y+1][x]\n right = self.cache[y+1][x+1]\n \n if left == right: return self.path_num(y+1, x) + self.path_num(y+1, x+1)\n elif left > right: return self.path_num(y+1, x)\n elif left < right: return self.path_num(y+1, x+1)\n\ndef parse_board(n):\n board = [[-1 for _ in range(n)] for _ in range(n)]\n for row in range(n):\n board[row][:row+1] = (int(num) for num in rl().split())\n return board\n\ndef main():\n C = int(rl())\n\n for _ in range(C):\n n = int(rl())\n board = parse_board(n)\n tripath = TriPath(n, board)\n print(tripath.path_num(0,0))\n\n return 0\n\nif __name__ == '__main__':\n main()\n","repo_name":"hanbyul-kim/algorithm_study","sub_path":"2017-03-1W/TRIPATHCNT.py","file_name":"TRIPATHCNT.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"73308505770","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 5 12:22:20 2020\n\n@author: Avinoam\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nfrom scipy.ndimage import maximum_filter\n\ndef createGaussianPyramid(im, sigma0, k, levels):\n GaussianPyramid = []\n for i in range(len(levels)):\n sigma_ = sigma0 * k ** levels[i]\n size = int(np.floor( 3 * sigma_ * 2) + 1)\n blur = cv2.GaussianBlur(im,(size,size),sigma_)\n GaussianPyramid.append(blur)\n return np.stack(GaussianPyramid)\n\ndef displayPyramid(pyramid):\n plt.figure(figsize=(16,5))\n plt.imshow(np.hstack(pyramid), cmap='gray')\n plt.axis('off')\n\ndef createDoGPyramid(GaussianPyramid, levels):\n # Produces DoG Pyramid\n # inputs\n # Gaussian Pyramid - A matrix of grayscale images of size\n # (len(levels), shape(im))\n # levels - the levels of the pyramid where the blur at each level is\n # outputs\n # DoG Pyramid - size (len(levels) - 1, shape(im)) matrix of the DoG pyramid\n # created by differencing the Gaussian Pyramid input\n DoGPyramid = []\n for level in range(1, len(levels)):\n DoGPyramid.append(GaussianPyramid[level] - GaussianPyramid[level-1])\n DoGPyramid = np.stack(DoGPyramid)\n return DoGPyramid\n\ndef computePrincipalCurvature(DoGPyramid):\n # Edge Suppression\n # Takes in DoGPyramid generated in createDoGPyramid and returns\n # PrincipalCurvature,a matrix of the same size where each point contains the\n # curvature ratio R for the corre-sponding point in the DoG pyramid\n #\n # INPUTS\n # DoG Pyramid - size (len(levels) - 1, shape(im)) matrix of the DoG pyramid\n #\n # OUTPUTS\n # PrincipalCurvature - size (len(levels) - 1, shape(im)) matrix where each\n # point contains the curvature ratio R for the\n # corresponding point in the DoG pyramid\n PrincipalCurvature = []\n eps = 1e-5\n for dog_level in DoGPyramid:\n # dog_level = (dog_level-np.min(dog_level))/(np.max(dog_level)-np.min(dog_level))\n gxx = cv2.Sobel(dog_level, cv2.CV_64F, 2, 0, ksize=3).astype(float)\n gyy = cv2.Sobel(dog_level, cv2.CV_64F, 0, 2, ksize=3).astype(float)\n gxy = cv2.Sobel(dog_level, cv2.CV_64F, 1, 1, ksize=3).astype(float)\n trace = gxx + gyy\n det = (gxx*gyy) - (gxy**2)\n R = (trace**2) / (det + eps)\n PrincipalCurvature.append(R)\n return np.stack(PrincipalCurvature)\n\ndef getLocalExtrema(DoGPyramid, PrincipalCurvature, th_contrast, th_r):\n mask_r = PrincipalCurvature.astype(float) < th_r\n mask_c = np.abs(DoGPyramid.astype(float)) > th_contrast\n both_th_mask = np.bitwise_and(mask_r, mask_c)\n locsDoG = []\n for i in range(len(DoGPyramid)):\n max_vals = maximum_filter(DoGPyramid[i], size=(3,3))\n if i==0:\n max_mask = (max_vals-DoGPyramid[i+1] > 0)\n elif i==len(DoGPyramid)-1:\n max_mask = (max_vals-DoGPyramid[i-1] > 0)\n else:\n max_mask = np.bitwise_and(max_vals-DoGPyramid[i+1] > 0, max_vals-DoGPyramid[i-1] > 0)\n max_same_level = (max_vals == DoGPyramid[i]) \n total_mask = np.bitwise_and(np.bitwise_and(both_th_mask[i], max_mask), max_same_level)\n valid_idx = np.argwhere(total_mask)\n level_col = np.expand_dims(np.array([i]*len(valid_idx)), 1)\n locsDoG.append(np.hstack((valid_idx, level_col)))\n return np.concatenate(locsDoG, axis=0).astype('int')\n\ndef DoGdetector(im, sigma0, k, levels, th_contrast, th_r):\n # Putting it all together\n # Inputs Description\n # --------------------------------------------------------------------------\n # im Grayscale image with range [0,1].\n # sigma0 Scale of the 0th image pyramid.\n # k Pyramid Factor. Suggest sqrt(2).\n # levels Levels of pyramid to construct. Suggest -1:4.\n # th_contrast DoG contrast threshold. Suggest 0.03.\n # th_r Principal Ratio threshold. Suggest 12.\n # Outputs Description\n # --------------------------------------------------------------------------\n # locsDoG N x 3 matrix where the DoG pyramid achieves a local extrema\n # in both scale and space, and satisfies the two thresholds.\n # gauss_pyramid A matrix of grayscale images of size (len(levels),imH,imW)\n GaussianPyramid = createGaussianPyramid(im, sigma0, k, levels)\n DoGPyramid = createDoGPyramid(GaussianPyramid, levels)\n # displayPyramid(DoGPyramid)\n PrincipalCurvature = computePrincipalCurvature(DoGPyramid)\n locsDoG = getLocalExtrema(DoGPyramid, PrincipalCurvature, th_contrast, th_r)\n return locsDoG, GaussianPyramid\n","repo_name":"barhom1307/Computer-Vision-046746","sub_path":"HW1 Features Descriptors/my_keypoint_det.py","file_name":"my_keypoint_det.py","file_ext":"py","file_size_in_byte":4554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"16907985710","text":"import math\nimport torch\nimport numpy as np\n\nfrom string import ascii_lowercase\n\ntorch_numpy_dtype_dict = {\n torch.complex64: np.complex64,\n torch.complex128: np.complex128,\n torch.float32: np.float32,\n torch.float64: np.float64,\n torch.int32: np.int32,\n torch.int64: np.int64,\n torch.bool: np.bool_,\n}\n\nC_DTYPE = torch.complex64\nF_DTYPE = torch.float32\n\nABC = ascii_lowercase\nABC_ARRAY = np.array(list(ABC))\n\nINV_SQRT2 = 1 / math.sqrt(2)\n\nC_DTYPE_NUMPY = torch_numpy_dtype_dict[C_DTYPE]\nF_DTYPE_NUMPY = torch_numpy_dtype_dict[F_DTYPE]\n","repo_name":"YuNariai/torchquantum","sub_path":"torchquantum/macro.py","file_name":"macro.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"55"} +{"seq_id":"71125568173","text":"class RandomizedSet:\n \"\"\"\n Runtime 484 ms / Beats 86.51%\n Memory 61.2 MB / Beats 74.27%\n \"\"\"\n def __init__(self):\n def default_val():\n return -1\n self.val_dict = collections.defaultdict(default_val)\n self.val_list = []\n self.count = 0\n\n def insert(self, val: int) -> bool:\n if self.val_dict[val] != -1 : return False\n self.val_dict[val] = len(self.val_list)\n self.val_list.append(val)\n self.count += 1\n return True\n\n def remove(self, val: int) -> bool:\n if self.val_dict[val] == -1 : return False\n idx = self.val_dict[val]\n # change\n self.val_list[-1], self.val_list[idx] = self.val_list[idx], self.val_list[-1]\n self.val_dict[self.val_list[idx]] = idx\n # remove\n self.val_list.pop()\n self.val_dict.pop(val)\n self.count -= 1\n return True\n\n def getRandom(self) -> int:\n num = random.randint(0, self.count-1)\n return self.val_list[num]\n\n\n# Your RandomizedSet object will be instantiated and called as such:\n# obj = RandomizedSet()\n# param_1 = obj.insert(val)\n# param_2 = obj.remove(val)\n# param_3 = obj.getRandom()","repo_name":"BoyuLin0906/LeetCode","sub_path":"Python/380_Insert_Delete_GetRandom_O(1)/Solution_2.py","file_name":"Solution_2.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"40270848090","text":"from math import ceil, floor\nwith open('input.txt') as f:\n data = f.readlines()\n data = [i.replace('\\n', '') for i in data]\n\n\ndef main():\n print(parse(data[0]))\n test = \"FBFBBFFRLR\"\n testrow, testcol = parse(test)\n row = binsearch(testrow, 0, 127)\n col = binsearch(testcol, 0, 7)\n print(row*8+col)\n testlist = [\"BFFFBBFRRR\",\n \"FBFBBFFRLR\",\n \"FFFBBBFRRR\",\n \"BBFFBBFRLL\"]\n testreslist = []\n for i in testlist:\n row, col = parse(i)\n testreslist.append(binsearch(row, 0, 127) * 8 + binsearch(col, 0, 7))\n\n print(max(testreslist))\n\n # Simple done\n reslist = []\n for i in data:\n row, col = parse(i)\n reslist.append(binsearch(row, 0, 127) * 8 + binsearch(col, 0, 7))\n print(\"Result: \", max(reslist))\n\n #Advanced\n print(type(reslist))\n reslist.sort()\n for k, v in enumerate(reslist):\n if v - 1 != reslist[k-1]:\n print(v-1)\n\n pass\n\n\ndef parse(s):\n return s[0:7], s[7:10]\n\ndef binsearch(li, mi, ma):\n minn, maxx, = mi, ma\n for k, i in enumerate(li):\n if i in [\"F\", \"L\"]:\n maxx = maxx - floor((maxx - minn) / 2)\n if i in [\"B\", \"R\"]:\n minn = ceil((maxx - minn) / 2) + minn\n if k == len(li) - 1:\n if \"F\": return minn\n else: return maxx\n\n\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gurkslask/AoC2020","sub_path":"day5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"37043593350","text":"from binarySearchTree import BST\nfrom itertools import groupby\nfrom collections import namedtuple\nimport heap\n\nmaxHeight = 1\nlastRowLen = 0\nnNodes = 0\n\ndef _initAtters(t):\n\ttoString = str\n\n\tdef dfs(root=t.root, height=1):\n\t\tglobal maxHeight, lastRowLen, nNodes\n\t\tif root!=None:\n\t\t\tlastRowLen += len(toString(root.value))\n\t\t\tnNodes+=1\n\t\t\tif root.left!=None:\n\t\t\t\tdfs(root.left, height+1)\n\t\t\tif root.right!=None:\n\t\t\t\tdfs(root.right, height+1)\n\t\t\tmaxHeight = max(height, maxHeight)\n\tdfs()\n\ndef _getNodes(t, gap):\n\t_initAtters(t)\n\tat = 1<>level\n\t\t\tlevels.append(node(str(root.value), level, side, at+gap, spread))\n\t\t\tif root.left!=None:\t\tdfs(root.left, level+1, 0, at-spread)\n\t\t\tif root.right!=None:\tdfs(root.right, level+1, 1, at+spread)\n\tdfs()\n\treturn levels\n\n# puts _s, to both sides of the nodes\ndef render_(s, node, eachGap):\n\ts[node.at+eachGap] = node.value\n\tfor i in range(node.at+eachGap-node.spread, node.at+eachGap):\ts[i] = \"_\"\t\t# left _s\n\tfor i in range(node.at+eachGap+1, node.at+eachGap+node.spread+1):\ts[i] = \"_\"\t# right _s\n\n# main function\ndef plot(tree, leftMargin=0):\n\tlevels = _getNodes(tree, leftMargin)\n\tlevels.sort(key=lambda x: (x.level, -x.at))\t\n\teachGap = lastRowLen//nNodes\n\n\tfor level, nodes in groupby(levels, key=lambda x: x.level):\n\t\tnode = next(nodes)\n\t\t# print(node)\n\t\ts = [\" \"]* (node.at+eachGap+node.spread+1)\n\n\t\tif level==maxHeight:\ts[node.at+eachGap] = node.value\n\t\telse: render_(s, node, eachGap)\n\t\tfor node in nodes:\n\t\t\t# print(node)\n\t\t\tif level==maxHeight:\ts[node.at+eachGap] = node.value\n\t\t\telse:\trender_(s, node, eachGap)\n\n\t\tprint(\"\".join(s))\n\n\nif __name__ == \"__main__\":\n\timport random\n\tt = BST()\n\tl = [random.randint(1, 100) for _ in range(10)]\n\tfor ele in l:\n\t\tt.insert(ele)\n\tplot(t)\n\t","repo_name":"abecus/DS-and-Algorithms","sub_path":"graph/tree/treePlotter.py","file_name":"treePlotter.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"55"} +{"seq_id":"72573297770","text":"import sys\nsys.stdin = open('../input.txt', 'rt')\n'''\n# stack\n- LIFO(last in, first out) like 구덩이!\n- list의 append(), pop() 으로 그대로 구현\n\n- 가장 top에 있는 숫자와 크기 비교 후 본인보다 크면 기존 숫자 pop 후 본인 append\n- stack이라는 리스트에 값을 담을 경우, minus(-) index 이용하여 stack[:-m]형태로 남은 제거 횟수 반영\n'''\nnum, m = map(int, input().split())\nnum = list(map(int, str(num)))\nstack = [] # 담을 빈 리스트\nfor x in num:\n while stack and m>0 and stack[-1] ?@[\\\\]^_`{|}~\"\n\nfull_characters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"\nhalf_characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n\nall_full = full_symbols + full_characters + kana\nall_half = half_symbols + half_characters\n\n\nall_english = all_half + all_full\nall_japanese = hiragana + all_katakana\n\n\ntry:\n from my_functions import cleanStringSet, independentize\n\nexcept:\n pass\n\n\nwith open('text\\de_50.txt', 'r', encoding=\"utf8\") as file:\n de_50 = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n \nwith open('text\\ga_50.txt', 'r', encoding=\"utf8\") as file:\n ga_50 = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\ha_50.txt', 'r', encoding=\"utf8\") as file:\n ha_50 = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\he_50.txt', 'r', encoding=\"utf8\") as file:\n he_50 = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\kara_50.txt', 'r', encoding=\"utf8\") as file:\n kara_50 = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\made_50.txt', 'r', encoding=\"utf8\") as file:\n made_50 = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\mo_50.txt', 'r', encoding=\"utf8\") as file:\n mo_50 = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\\\na_50.txt', 'r', encoding=\"utf8\") as file:\n na_50 = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\\\ni_50.txt', 'r', encoding=\"utf8\") as file:\n ni_50 = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\\\no_50.txt', 'r', encoding=\"utf8\") as file:\n no_50 = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\wo_50.txt', 'r', encoding=\"utf8\") as file:\n wo_50 = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n \nwith open('text\\\\no_50.txt', 'r', encoding=\"utf8\") as file:\n yori_50 = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n \nall_50 = de_50 + ga_50 + ha_50 + he_50 + kara_50 + made_50 + mo_50 + na_50 + ni_50 + no_50 + yori_50\n\n\n\nwith open('text\\Showa\\de_50_old.txt', 'r', encoding=\"utf8\") as file:\n de_50_old = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n \nwith open('text\\Showa\\ga_50_old.txt', 'r', encoding=\"utf8\") as file:\n ga_50_old = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\Showa\\ha_50_old.txt', 'r', encoding=\"utf8\") as file:\n ha_50_old = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\Showa\\he_50_old.txt', 'r', encoding=\"utf8\") as file:\n he_50_old = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\Showa\\kara_50_old.txt', 'r', encoding=\"utf8\") as file:\n kara_50_old = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\Showa\\made_50_old.txt', 'r', encoding=\"utf8\") as file:\n made_50_old = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\Showa\\mo_50_old.txt', 'r', encoding=\"utf8\") as file:\n mo_50_old = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\Showa\\\\na_50_old.txt', 'r', encoding=\"utf8\") as file:\n na_50_old = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\Showa\\\\ni_50_old.txt', 'r', encoding=\"utf8\") as file:\n ni_50_old = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\Showa\\\\no_50_old.txt', 'r', encoding=\"utf8\") as file:\n no_50_old = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nwith open('text\\Showa\\wo_50_old.txt', 'r', encoding=\"utf8\") as file:\n wo_50_old = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n \nwith open('text\\Showa\\\\no_50_old.txt', 'r', encoding=\"utf8\") as file:\n yori_50_old = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\nall_50_old = de_50_old + ga_50_old + ha_50_old + he_50_old + kara_50_old + made_50_old + mo_50_old + na_50_old + ni_50_old + no_50_old + yori_50_old\n\n\n\nsum_gendai = 0\nsum_showa = 0\nfor item in all_50:\n sum_gendai += len(item)\nfor item in all_50_old:\n sum_showa += len(item)\n\nprint(\"before\")\nprint(sum_gendai)\nprint(sum_showa)\n\nfiltered = independentize(all_50)\nfiltered_old = independentize(all_50_old)\n\nsum_gendai = 0\nsum_showa = 0\n\nfor item in filtered:\n sum_gendai += len(item)\nfor item in filtered_old:\n sum_showa += len(item)\n\nprint(\"after\") \nprint(sum_gendai)\nprint(sum_showa)\n\n\nOkayama = []\nfor i in range(1, 33):\n filename = \"D:\\(PC)\\Desktop\\Coding\\Python\\Japanese NLP\\%shild\\%skayama\\%s (%d).cha\"%('c','O','f',i)\n with open(filename, 'r', encoding=\"utf8\") as file:\n Okayama.append(cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t'))\n \nHamasaki = []\nfor i in range(1, 33):\n filename = \"D:\\(PC)\\Desktop\\Coding\\Python\\Japanese NLP\\%shild\\%samasaki\\%s (%d).cha\"%('c','H','a',i)\n with open(filename, 'r', encoding=\"utf8\") as file:\n Hamasaki.append(cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t'))\n\nwith open('kids.txt', 'r', encoding=\"utf8\") as file:\n kids = cleanStringSet(file.readlines(), garbage = '\\n', target = '\\t')\n\n#\n#kids = []\n#for block in Okayama:\n# kids += block\n#\n#\n#test = []\n#for i in range(0, len(kids)):\n# try:\n# if \"MOT\" in kids[i] or \"JIR\" in kids[i]:\n# while \"CHI\" not in kids[i]:\n# kids.pop(i)\n# \n# elif \"act\" in kids[i] or \"CHI\" in kids[i]:\n# kids.pop(i)\n#\n# else:\n# pass\n# newline = \"\"\n# for character in kids[i]:\n# if character not in all_characters:\n# newline += character\n# test.append(newline)\n# except:\n# pass\n#print(test)\n#\n#\n#\n#\n#\n#\n#print(save)\n#\n#f=open(\"kids.txt\", \"a+\", encoding = \"utf8\")\n#for line in filtered_kids:\n# f.write(line)\n# f.write('\\n')\n#f.close()\n\n\n","repo_name":"Ippanjin/japanese-nlp","sub_path":"text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":7789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"75012409759","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 16 18:28:44 2018\r\n\r\n@author: GPSINGH\r\n\"\"\"\r\nimport pickle\r\nimport numpy as np\r\nfrom sklearn.base import BaseEstimator, TransformerMixin\r\nfrom sklearn.feature_extraction import DictVectorizer\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.pipeline import FeatureUnion\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom collections import defaultdict\r\nfrom time import strftime\r\nimport logging\r\nfrom time import time\r\nfrom pattern.db import Datasheet\r\nfrom random import shuffle\r\nimport string\r\nimport nltk\r\nfrom numpy import genfromtxt\r\nimport pandas as pd\r\nfrom sklearn.svm import LinearSVC\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom pattern.en import sentiment\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nimport matplotlib.pyplot as plt\r\nfrom pandas_ml import ConfusionMatrix\r\nimport itertools\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom pattern.en import modality\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import roc_auc_score\r\nfrom sklearn.metrics import roc_curve, auc \r\n\r\n\r\n#To Plot the confusion matrix\r\ndef plot_confusion_matrix(cm, classes,\r\n normalize=False,\r\n title='Confusion matrix',\r\n cmap=plt.cm.Blues):\r\n \"\"\"\r\n This function prints and plots the confusion matrix.\r\n Normalization can be applied by setting `normalize=True`.\r\n \"\"\"\r\n if normalize:\r\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\r\n print(\"Normalized confusion matrix\")\r\n else:\r\n print('Confusion matrix, without normalization')\r\n\r\n print(cm)\r\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\r\n plt.title(title)\r\n plt.colorbar()\r\n tick_marks = np.arange(len(classes))\r\n plt.xticks(tick_marks, classes, rotation=45)\r\n plt.yticks(tick_marks, classes)\r\n fmt = '.2f' if normalize else 'd'\r\n thresh = cm.max() / 2.\r\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\r\n plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\")\r\n plt.tight_layout()\r\n plt.ylabel('True label')\r\n plt.xlabel('Predicted label')\r\n \r\n \r\nclass ItemSelector(BaseEstimator, TransformerMixin):\r\n def __init__(self, key):\r\n self.key = key\r\n\r\n def fit(self, x, y=None):\r\n return self\r\n\r\n def transform(self, data_dict):\r\n return data_dict[self.key]\r\n\r\n\r\n#To extract Punctuation features from each news \r\nclass Punct_Stats(BaseEstimator, TransformerMixin):\r\n \"\"\"Extract punctuation features from each document\"\"\"\r\n\r\n def fit(self, x, y=None):\r\n return self\r\n\r\n def transform(self, text_fields):\r\n punct_stats = []\r\n punctuations = list(string.punctuation)\r\n print(punctuations)\r\n additional_punc = ['``', '--', '\\'\\'']\r\n punctuations.extend(additional_punc)\r\n for field in text_fields:\r\n puncts = defaultdict(int)\r\n for ch in field:\r\n if ch in punctuations:\r\n puncts[ch]+=1\r\n punct_stats.append(puncts)\r\n return punct_stats\r\n\r\n\r\n\r\n#To extract the Text Statistics from each news\r\n#Text Stat includes \r\n#number of all caps words\r\n#sentence length of the news\r\n#Polarity of the news\r\n#Subjectivity of the news\r\n#Profanity of the news\r\n#Mood of the tex using modality\r\nclass Text_Stats(BaseEstimator, TransformerMixin):\r\n \"\"\"Extract text statistics from each document\"\"\"\r\n\r\n def fit(self, x, y=None):\r\n return self\r\n\r\n def transform(self, text_fields):\r\n stats = []\r\n punctuation = string.punctuation\r\n abvs = ['CNN', 'FBI', 'ABC', 'MSNBC', 'GOP', 'U.S.', 'US', 'ISIS', 'DNC', 'TV', 'CIA',\r\n 'I', 'AP', 'PM', 'AM', 'EU', 'USA', 'UK', 'UN', 'CEO', 'NASA', 'LGBT', 'LGBTQ', 'NAFTA', 'ACLU']\r\n for field in text_fields:\r\n field_stats = {}\r\n tok_text = nltk.word_tokenize(field)\r\n try:\r\n num_upper = float(len([w for w in tok_text if w.isupper() and w not in abvs]))/len(tok_text)\r\n except:\r\n num_upper = 0\r\n try:\r\n num_punct = float(len([ch for ch in field if ch in punctuation]))/len(field)\r\n except:\r\n num_punct = 0 \r\n try:\r\n sent_lengths = [len(nltk.word_tokenize(s)) for s in nltk.sent_tokenize(field)]\r\n av_sent_len = float(sum(sent_lengths))/len(sent_lengths)\r\n except:\r\n av_sent_len = 0\r\n try:\r\n num_prof = float(len([w for w in tok_text if w.lower() in PROFANITY]))/len(tok_text)\r\n except:\r\n num_prof = 0\r\n \r\n mood = modality(field) \r\n polarity, subjectivity = sentiment(field)\r\n field_stats['all_caps'] = num_upper\r\n field_stats['sent_len'] = av_sent_len\r\n field_stats['polarity'] = polarity\r\n field_stats['subjectivity'] = subjectivity\r\n field_stats['profanity'] = num_prof\r\n field_stats['mood'] = mood\r\n stats.append(field_stats)\r\n return stats\r\n\r\n\r\n\r\n#Initiator to extract the headline and body features \r\nclass HeadlineBodyFeaturesExtractor(BaseEstimator, TransformerMixin):\r\n \"\"\"Extracts the components of each input in the data: headline, body, and POS tags for each\"\"\"\r\n def fit(self, x, y=None):\r\n return self\r\n\r\n def transform(self, posts):\r\n headlineCol = posts[0].values.tolist()\r\n bodyCol = posts[1].values.tolist()\r\n punctuation = string.punctuation\r\n features = np.recarray(shape=(len(headlineCol),), dtype=[('headline', object), ('article_body', object), ('headline_pos', object), ('body_pos', object)])\r\n \r\n for i in range(0,len(headlineCol)):\r\n headline = headlineCol[i]\r\n article = bodyCol[i]\r\n features['headline'][i] = headline\r\n features['article_body'][i] = article\r\n\r\n tok_headline = nltk.word_tokenize(headline)\r\n features['headline_pos'][i] = (' ').join([x[1] for x in nltk.pos_tag(tok_headline)])\r\n\r\n tok_article = nltk.word_tokenize(article)\r\n features['body_pos'][i] = (' ').join([x[1] for x in nltk.pos_tag(tok_article)])\r\n \r\n return features\r\n\r\n\r\ntrain_path = \"C:\\\\Users\\\\GPSINGH\\Pictures\\\\NewsAudit\\\\Reduced\\\\training_data.csv\"\r\n\r\ntrain_data = pd.read_csv(train_path, sep=',',header=None )\r\ntrain,test = train_test_split(train_data , test_size = 0.2)\r\nprint(train)\r\ntrain_labels = train[3]\r\n\r\ndel train[3]\r\ntrain_texts = train\r\n\r\n \r\ntest_labels = test[3]\r\ndel test[3]\r\ntest_texts = test \r\n\r\n\r\n#Pipeline of the mentioned features\r\npipeline = Pipeline([\r\n # Extract the subject & body\r\n ('HeadlineBodyFeatures', HeadlineBodyFeaturesExtractor()),\r\n\r\n # Use FeatureUnion to combine the features from subject and body\r\n ('union', FeatureUnion(\r\n transformer_list=[\r\n\r\n #Pipeline for pulling features from articles\r\n ('punct_stats_headline', Pipeline([\r\n ('selector', ItemSelector(key='headline')),\r\n ('stats', Punct_Stats()), # returns a list of dicts\r\n ('vect', DictVectorizer()), # list of dicts -> feature matrix\r\n ])),\r\n\r\n ('punct_stats_body', Pipeline([\r\n ('selector', ItemSelector(key='article_body')),\r\n ('stats', Punct_Stats()), \r\n ('vect', DictVectorizer()), \r\n ])),\r\n\r\n #Usage of Tfidf Vectorizer\r\n ('pos_ngrams_headline', Pipeline([\r\n ('selector', ItemSelector(key='headline_pos')),\r\n ('vect', TfidfVectorizer(ngram_range=(1,2), token_pattern = r'\\b\\w+\\b', max_df = 0.5)),\r\n ])),\r\n\r\n #Usage of Tfidf Vectorizer\r\n ('pos_ngrams_body', Pipeline([\r\n ('selector', ItemSelector(key='body_pos')),\r\n ('vect', TfidfVectorizer(ngram_range=(1,2), token_pattern = r'\\b\\w+\\b', max_df = 0.5)),\r\n ])),\r\n\r\n #Usage of DictVectorizer Vectorizer for the headline of the news\r\n ('text_stats_headline', Pipeline([\r\n ('selector', ItemSelector(key='headline')),\r\n ('stats', Text_Stats()), \r\n ('vect', DictVectorizer()), \r\n ])),\r\n\r\n #Usage of DictVectorizer Vectorizer for the body of the news\r\n ('text_stats_body', Pipeline([\r\n ('selector', ItemSelector(key='article_body')),\r\n ('stats', Text_Stats()), # returns a list of dicts\r\n ('vect', DictVectorizer()), # list of dicts -> feature matrix\r\n ])),\r\n ],\r\n )),\r\n\r\n # Use an SVC classifier on the combined features\r\n ('clf', SVC(kernel = 'linear', random_state = 0)),\r\n])\r\n \r\n#Fitting the pipline to the training text and labels \r\npipeline.fit(train_texts,train_labels)\r\ny_pred = pipeline.predict(test_texts)\r\n\r\n\r\n#Plotting the classification report\r\nprint(classification_report(y_pred,test_labels))\r\n \r\n\r\n#AUC score from the ROC curve\r\nprint(\"AUC score\")\r\nprint(roc_auc_score(test_labels, y_pred))\r\nfpr, tpr, threshold = roc_curve(test_labels, y_pred)\r\nroc_auc = auc(fpr, tpr)\r\n\r\n\r\n#Plotting the ROC curve\r\nimport matplotlib.pyplot as plt\r\nplt.title('Receiver Operating Characteristic')\r\nplt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc)\r\nplt.legend(loc = 'lower right')\r\nplt.plot([0, 1], [0, 1],'r--')\r\nplt.xlim([0, 1])\r\nplt.ylim([0, 1])\r\nplt.ylabel('True Positive Rate')\r\nplt.xlabel('False Positive Rate')\r\nplt.show()\r\n\r\n\r\nlabels = ['Objective', 'Sensationalist'] \r\n#Call to plot the confusion Matrix \r\ncnf_matrix = confusion_matrix(test_labels, y_pred)\r\nplt.figure()\r\nplot_confusion_matrix(cnf_matrix, classes=labels,\r\n title='Confusion matrix')\r\nplt.show()\r\n \r\n ","repo_name":"gurpreetsingh91/Political-Fake-News-Detection","sub_path":"ObjectiveSensational_SVMClassifier.py","file_name":"ObjectiveSensational_SVMClassifier.py","file_ext":"py","file_size_in_byte":10376,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"41771972854","text":"from typing import List\r\n\r\nclass Solution:\r\n def longestOnes(self, nums: List[int], k: int) -> int:\r\n left = 0\r\n k_used = 0\r\n res = 0\r\n\r\n for right in range(len(nums)):\r\n if nums[right]:\r\n res = max(res, right - left + 1)\r\n else:\r\n if k_used < k:\r\n k_used += 1\r\n else:\r\n while nums[left] == 1:\r\n left += 1\r\n left += 1\r\n\r\n return max(res, right - left + 1)\r\n \r\nsol = Solution() \r\nprint(sol.longestOnes(nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2))","repo_name":"ItsMeOX/Application1","sub_path":"leetcode/completed/1004.py","file_name":"1004.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"15592669577","text":"import requests\n\nfrom app import app\n\n\ndef send_email(subject, sender, recipients, text_body, reply_to, message_id):\n \"\"\"\n Send email using the Mailgun APIv3\n :param recipients - [list]\n :param message_id - to keep track of db/webhooks\n \"\"\"\n return requests.post(\n \"https://api.mailgun.net/v3/miteshshah.com/messages\",\n auth=(\"api\", app.config['MAILGUN_API_KEY']),\n data={\"from\": sender + \" \",\n \"to\": recipients,\n \"subject\": subject,\n \"text\": text_body,\n \"h:Reply-to\": reply_to,\n \"v:my-custom-data\": {\"message_id\": message_id}})\n","repo_name":"oxalorg/mitesh.ninja","sub_path":"app/form/mailNinja.py","file_name":"mailNinja.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"51"} +{"seq_id":"25455159150","text":"import io\nimport os\n\nfrom setuptools import setup\n\nHERE = os.path.dirname(os.path.abspath(__file__))\n\n\ndef read(*parts, **kwargs):\n filepath = os.path.join(HERE, *parts)\n encoding = kwargs.pop(\"encoding\", \"utf-8\")\n with io.open(filepath, encoding=encoding) as fh:\n text = fh.read()\n return text\n\n\ndef get_requirements(path):\n content = read(path)\n return [req for req in content.split(\"\\n\") if req != \"\" and not req.startswith(\"#\")]\n\n\ninstall_requires = get_requirements(\"requirements.txt\")\n\nsetup(\n name=\"executor\",\n version=\"0.1.0\",\n py_modules=[\"executor\"],\n packages=[\"executor\"],\n install_requires=install_requires,\n entry_points=\"\"\"\n [console_scripts]\n executor=executor.cli:cli\n \"\"\",\n)\n","repo_name":"pkerpedjiev/executor","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"3772979128","text":"#!/usr/bin/python3\nimport pandas as pd\nimport os\n\n\ndir = \"/home/eveline/python/excel/tables\"\t#设置工作路径\n\nfile = os.listdir(dir)\npath_file = os.path.join(dir,file[0])\n\ndf = pd.read_excel(path_file)\t\t\t\t#打开第一个sheel\n#data = df.ix[0].values\t\t\t\t\t\t#读取第一行的内容,ix在新版取消了\ndata = df.loc[0].values\nprint(\"Read one line:\\n{0}\".format(data))\n#data = df.iloc[0].values\n#print(\"Index:\\n{0}\".format(data))\n\n#返回特定行\ndata = df.loc[[1,2]].values\nprint(\"Read two-three line:\\n{0}\".format(data))\n\n#返回指定sheel的指定行\nxl = pd.ExcelFile(path_file)\nsheet_name = xl.sheet_names\n#print(sheet_name[0],sheet_name[1])\n\n#data = df.loc[[1,2],[sheet_name[0],sheet_name[1]]].values\n#data = df.iloc[[1,2],[sheet_name[0],sheet_name[1]]].values\n#print(\"Read two-three line:\\n{0}\".format(data))\n\n#打印行号\ndf=pd.read_excel(path_file)\nprint(\"输出行号列表\",df.index.values)\n\n#打印列名\ndf=pd.read_excel(path_file)\nprint(\"输出列标题\",df.columns.values)\n\n#获取指定行数的值:\ndf=pd.read_excel(path_file)\nprint(\"输出值\",df.sample(3).values)#这个方法类似于head()方法以及df.values方法\n\n\n\n#获取指定列的值:\ndf=pd.read_excel(path_file)\nprint(\"输出值\\n\",df['Supplier'].values)\n\nfirstcolum=set(df['Supplier'].values)\n\nprint(\"输出值集合\",firstcolum)","repo_name":"youxi0011983/python3","sub_path":"python/excel/readoneline.py","file_name":"readoneline.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"72577033757","text":"#!/usr/bin/python3\ndef list_division(my_list_1, my_list_2, list_length):\n new_list = []\n for i in range(list_length):\n try:\n result = my_list_1[i] / my_list_2[i]\n except (ZeroDivisionError, TypeError):\n print(\"division by 0\")\n new_list.append(0)\n except IndexError:\n print(\"out of range\")\n new_list.append(0)\n else:\n new_list.append(result)\n finally:\n if type(result) != (int or float):\n print(\"wrong type\")\n return new_list\n","repo_name":"AbdElRhmanArafa/alx-higher_level_programming","sub_path":"0x05-python-exceptions/4-list_division.py","file_name":"4-list_division.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"8326646017","text":"from sqlalchemy import *\nfrom migrate import *\n\n\nfrom migrate.changeset import schema\npre_meta = MetaData()\npost_meta = MetaData()\nmediaitem = Table('mediaitem', post_meta,\n Column('id', Integer, primary_key=True, nullable=False),\n Column('title', String),\n Column('about', String),\n Column('date_published', Date),\n Column('licence', Integer),\n Column('postcard', Integer),\n)\n\npicture = Table('picture', pre_meta,\n Column('id', INTEGER, primary_key=True, nullable=False),\n Column('parent_id', INTEGER),\n Column('file_name', VARCHAR),\n Column('date_published', DATE),\n Column('resolution', VARCHAR),\n Column('file_size', INTEGER),\n)\n\ncode = Table('code', pre_meta,\n Column('id', INTEGER, primary_key=True, nullable=False),\n Column('parent_id', INTEGER),\n Column('file_name', VARCHAR),\n Column('date_published', DATE),\n Column('file_size', INTEGER),\n)\n\nvideo = Table('video', pre_meta,\n Column('id', INTEGER, primary_key=True, nullable=False),\n Column('parent_id', INTEGER),\n Column('file_name', VARCHAR(length=64)),\n Column('running_time', DOUBLE_PRECISION(precision=53)),\n Column('has_start_poster', BOOLEAN),\n Column('has_end_poster', BOOLEAN),\n Column('has_fullscreen', BOOLEAN),\n Column('date_published', DATE),\n Column('resolution', VARCHAR(length=16)),\n)\n\naudio = Table('audio', pre_meta,\n Column('id', INTEGER, primary_key=True, nullable=False),\n Column('parent_id', INTEGER),\n Column('file_name', VARCHAR),\n Column('running_time', DOUBLE_PRECISION(precision=53)),\n Column('has_start_poster', BOOLEAN),\n Column('has_end_poster', BOOLEAN),\n Column('date_published', DATE),\n)\n\n\ndef upgrade(migrate_engine):\n # Upgrade operations go here. Don't create your own engine; bind\n # migrate_engine to your metadata\n pre_meta.bind = migrate_engine\n post_meta.bind = migrate_engine\n post_meta.tables['mediaitem'].columns['date_published'].create()\n pre_meta.tables['picture'].columns['date_published'].drop()\n pre_meta.tables['code'].columns['date_published'].drop()\n pre_meta.tables['video'].columns['date_published'].drop()\n pre_meta.tables['audio'].columns['date_published'].drop()\n\n\ndef downgrade(migrate_engine):\n # Operations to reverse the above upgrade go here.\n pre_meta.bind = migrate_engine\n post_meta.bind = migrate_engine\n post_meta.tables['mediaitem'].columns['date_published'].drop()\n pre_meta.tables['picture'].columns['date_published'].create()\n pre_meta.tables['code'].columns['date_published'].create()\n pre_meta.tables['video'].columns['date_published'].create()\n pre_meta.tables['audio'].columns['date_published'].create()\n","repo_name":"dougmiller/theMetaCityMedia","sub_path":"db_repository/versions/012_migration.py","file_name":"012_migration.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"17320408161","text":"#funções = subrotinas\r\n#a função é um algoritmo que roda dentro do programa\r\n# def nomedafunção(parâmetro)\r\n# códigosdafunção\r\n#\r\n# https://www.pythonprogressivo.net/2018/06/Calculadora-Python-Funcoes.html\r\n\r\ndef calculadora(n1,n2,op):\r\n if(op == \"+\"):\r\n return n1+n2\r\n elif(op == \"-\"):\r\n return n1-n2\r\n elif(op == \"*\"):\r\n return n1*n2\r\n elif(op == \"/\"):\r\n if(n2 != 0):\r\n return n1/n2\r\n else:\r\n print(\"Divisão por 0 não é permitida\")\r\n else:\r\n print(\"Operador inválido\")\r\n\r\nnumero1 = float(input(\"Numero1> \"))\r\nnumero2 = float(input(\"Numero2> \"))\r\nsimbolo = input(\"Digite o operador> \")\r\nprint(calculadora(numero1,numero2,simbolo))\r\n\r\ndef media(num1, num2, num3):\r\n m = (num1+num2+num3) / 3\r\n if (m>=7):\r\n return \"Aprovado\"\r\n elif (m<7):\r\n return \"Reprovado\"\r\n\r\na = media(7, 8, 9)\r\nprint(a)\r\n\r\ndef func(num1, num2):\r\n return num1**2, num2**2\r\n\r\na, b = func(2, 3)\r\nprint(a)\r\nprint(b)\r\n\r\ndef eh_par(num):\r\n if (num % 2 == 0):\r\n return True\r\n else:\r\n return False\r\n\r\nnumero = int(input(\"Digite um número: \"))\r\nprint(eh_par(numero))\r\n\r\ndef soma(num1, num2):\r\n valor = num1+num2\r\n return valor\r\n\r\na = soma(5,7)\r\nprint(a)\r\n\r\ndef calcula_imc(peso,altura):\r\n res = peso/pow(altura,2)\r\n return res\r\n\r\na = calcula_imc(75, 1.78)\r\nprint(a)\r\n\r\ndef potencia(num1, num2):\r\n resultado = 1\r\n for a in range(num2):\r\n resultado *= num1\r\n return resultado\r\n\r\ndef meuNome (nome):\r\n print(\"Eu sou: \", nome)\r\n\r\nmeuNome(\"Douglas\")\r\n\r\na = potencia(2, 3)\r\nprint(a)\r\n","repo_name":"VG083/CCSemestre1","sub_path":"ProgramacaoDeComputadores/aula016.py","file_name":"aula016.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"34957455031","text":"# 2nd Oct, 2020 Sumantra Sharma\n# inputs - %VOC2012,%VOC2007,%I2R_Data, %I2R_Data_2 of the total images to select from ~/dataset//Annotations/*xml\n# \t\t - datasat_dir (path to the dataset directory)\n# output - a json file containing the filenames of all the images selected \n\n# 3rd Nov, 2020 : Adding option to read the folders in dataset directory through a text files\nimport os\nimport glob\nimport argparse\nimport sys\nimport random\nimport json\n\nparser = argparse.ArgumentParser(add_help=False)\nparser_full = argparse.ArgumentParser(\n description=\"Program to randomly select specified percentages of files from the dataset folder\")\n\nparser.add_argument(\"-d\",\n \"--dataset_dir\",\n help=\"Path to the dataset folder, default = ~/dataset\",\n default = '~/dataset/',\n type=str)\n# Open dataset directory and store folder namaes in a list\nd = parser.parse_known_args()[0].dataset_dir\nif not os.path.isdir(d):\n print(\"Usage python3 select_percentages.py -d \")\nfolders = [o for o in os.listdir(d) \n if os.path.isdir(os.path.join(d,o))]\nparser_full.add_argument(\"-d\",\n \"--dataset_dir\",\n help=\"Path to the dataset folder, default = ~/dataset\",\n default = '~/dataset/',\n type=str)\nfor f in folders:\n parser_full.add_argument(\"-\"+f,\n \"--\"+f+\"_p\",\n help=\"Percentage of dataset to select, default = 100\",\n default = 100,\n type=int) \nargs = parser_full.parse_args()\n\nfor arg in vars(args):\n print (arg,'=', getattr(args, arg))\ndata_dict = {}\nfor f in folders:\n\tdata_dict[f] = [getattr(args,f+\"_p\")\t, []]\n\ndef main():\t\t\t\n# glob through files and randomly select\n\tfor key,value in data_dict.items():\n\t\tfile_names = []\n\t\tcount = 0\n\t\tfor name in glob.glob(os.path.join(args.dataset_dir,key,'Annotations/') + '*xml'):\n\t\t\tfile_names.append(os.path.split(name)[1][:-4])\n\t\t\tcount+=1\n\t\tvalue[1] =random.sample(file_names, int((value[0]/100)*len(file_names)))\n\t\tprint('Randomly selected', len(value[1]), 'filenames from', key, 'from a total of', count, 'files')\n# \tsave fnames dict to json filwe\n\tfilename = os.path.join(args.dataset_dir,'dataset.txt')\n\tos.makedirs(os.path.dirname(filename), exist_ok=True)\n\twith open(filename, \"w\") as f:\n\t\tf.write(json.dumps(data_dict))\n\t\t\t\nif __name__ == '__main__':\n\tmain()\n","repo_name":"chinacat567/affordance_network","sub_path":"scripts/dataset_tools/select_percentages.py","file_name":"select_percentages.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"3174973346","text":"from flask import redirect, render_template\nfrom flask import request, url_for\nfrom flask_user import current_user, login_required, roles_accepted\n\nfrom flask.ext.wtf import Form\nfrom wtforms.ext.sqlalchemy.orm import model_form\nfrom sqlalchemy import func\nfrom app.application import app, db\nfrom app.models.user_models import UserProfileForm\nfrom app.models.app_models import Contacto, ContactoSearchForm\n\n# The Home page is accessible to anyone\n@app.route('/')\ndef home_page():\n return render_template('pages/home_page.html')\n\n\n# The User page is accessible to authenticated users (users that have logged in)\n@app.route('/user')\n@login_required # Limits access to authenticated users\ndef user_page():\n return render_template('pages/user_page.html')\n\n\n# The Admin page is accessible to users with the 'admin' role\n@app.route('/admin')\n@roles_accepted('admin') # Limits access to users with the 'admin' role\ndef admin_page():\n return render_template('pages/admin_page.html')\n\n@app.route('/contactos', methods=['GET', 'POST'])\n@login_required\ndef contactos_page():\n\n form = ContactoSearchForm(request.form, current_user)\n resultados = None\n busqueda=None\n cantidad=None\n\n if request.method == 'POST' and form.validate():\n form.populate_obj(current_user)\n buscar='%' + form.nombre.data.lower() +'%'\n resultados = Contacto.query.filter(Contacto.nombre.ilike(buscar) ).all()\n cantidad = len(resultados)\n # GET o invalid input\n return render_template('pages/contactos.html', \n form=form, \n contactos=resultados,\n busqueda=form.nombre.data,\n cantidad=cantidad)\n\n\n\n\n@app.route('/pages/profile', methods=['GET', 'POST'])\n@login_required\ndef user_profile_page():\n # Initialize form\n form = UserProfileForm(request.form, current_user)\n\n # Process valid POST\n if request.method == 'POST' and form.validate():\n # Copy form fields to user_profile fields\n form.populate_obj(current_user)\n\n # Save user_profile\n db.session.commit()\n\n # Redirect to home page\n return redirect(url_for('home_page'))\n\n # Process GET or invalid POST\n return render_template('pages/user_profile_page.html',\n form=form)\n\n\n@app.route('/contactos/')\n@login_required\ndef contacto_detail_page(id_contacto):\n \n query = Contacto.query.filter(Contacto.id == id_contacto).all()\n \n if query:\n contacto = query[0] \n else:\n datos = None\n return render_template('pages/contacto_detail.html',contacto=contacto)\n\n","repo_name":"PaPablo/contactask","sub_path":"app/views/misc_views.py","file_name":"misc_views.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"16518446614","text":"import subprocess\nimport os\nimport io\nimport time\n\nfrom googleapiclient.discovery import build\nfrom googleapiclient.http import MediaIoBaseDownload\nfrom google.oauth2 import service_account\n\nfrom steam import trouver_bin_zero_escape\nfrom credentials import credentials_info\n\npath_xdelta = \"ZE999Tool.v0.9.8.1\\\\xDeltaPatch\\\\\"\n\n\ncredentials = service_account.Credentials.from_service_account_info(credentials_info,\n scopes=['https://www.googleapis.com/auth/drive'])\n\ndrive_service = build('drive', 'v3', credentials=credentials)\n\n\ndef download_file(file_id, file_name, download_folder):\n file_path = os.path.join(download_folder, file_name)\n request = drive_service.files().get_media(fileId=file_id)\n fh = io.FileIO(file_path, mode='wb')\n downloader = MediaIoBaseDownload(fh, request)\n done = False\n while not done:\n status, done = downloader.next_chunk()\n\n\ndef download_files_in_folder(folder_id):\n results = drive_service.files().list(\n q=f\"'{folder_id}' in parents and trashed=false\",\n fields='files(id, name, mimeType)'\n ).execute()\n files = results.get('files', [])\n for file in files:\n if file['mimeType'] == 'application/vnd.google-apps.folder':\n download_files_in_folder(file['id'])\n else:\n download_file(file['id'], file['name'], path_xdelta)\n\n\ndef creer_patch(nom_exe, original=False):\n \"\"\"_summary_\n\n Args:\n nom_exe (_type_): _description_\n \"\"\"\n chemin_bin_steam = os.path.dirname(trouver_bin_zero_escape())\n\n path_exe_original = chemin_bin_steam + \"\\\\\" + nom_exe + \".exe\"\n path_exe_patche = chemin_bin_steam + \"\\\\\" + nom_exe + \"_new.exe\"\n\n path_exe1 = path_exe_original\n path_exe2 = path_exe_patche\n if original:\n nom_exe = nom_exe + \"_original\"\n path_exe1 = path_exe_patche\n path_exe2 = path_exe_original\n\n commande_shell = [\n path_xdelta + \"xdelta3\",\n \"-f\",\n \"-e\",\n \"-s\",\n path_exe1,\n path_exe2,\n path_xdelta + \"patch_\" + nom_exe + \"_exe.xdelta\",\n ]\n\n process = subprocess.run(commande_shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n creationflags=subprocess.CREATE_NO_WINDOW)\n\n return process.returncode\n\n\ndef patch_any_exe(nom_exe, original=False):\n \"\"\"patch le texte dans le ze1.exe\"\"\"\n chemin_bin_steam = os.path.dirname(trouver_bin_zero_escape())\n\n if original:\n nom_exe = nom_exe + \"_original\"\n commande_shell = [\n path_xdelta + \"xdelta3\",\n \"-f\",\n \"-d\",\n \"-s\",\n chemin_bin_steam + \"\\\\\" + nom_exe + \".exe\",\n path_xdelta + \"patch_\" + nom_exe + \"_exe.xdelta\",\n chemin_bin_steam + \"\\\\\" + nom_exe + \"_new.exe\",\n ]\n\n process = subprocess.run(commande_shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n creationflags=subprocess.CREATE_NO_WINDOW)\n return process.returncode\n\n\ndef remplace_vieux_exe(nom_exe, process_returncode):\n if process_returncode == 0:\n chemin_bin_steam = os.path.dirname(trouver_bin_zero_escape())\n os.remove(chemin_bin_steam + \"\\\\\" + nom_exe + \".exe\")\n time.sleep(0.3)\n os.rename(chemin_bin_steam + \"\\\\\" + nom_exe + \"_new.exe\", chemin_bin_steam + \"\\\\\" + nom_exe + \".exe\")\n\n\ndef patch_exe_full_process(nom_exe):\n if os.path.exists(os.path.join(path_xdelta, nom_exe + \"_original_exe.delta\")):\n returncode = patch_any_exe(nom_exe, original=True)\n remplace_vieux_exe(nom_exe, returncode)\n returncode = patch_any_exe(nom_exe)\n creer_patch(nom_exe, original=True)\n remplace_vieux_exe(nom_exe, returncode)\n\n\ndef patch_ze1_exe():\n patch_exe_full_process(\"ze1\")\n\n\ndef patch_Launcher_exe():\n patch_exe_full_process(\"Launcher\")\n\n\ncreer_patch(\"ze1\")\n# Pour qu'on puisse mettre à jour avec google drive, faudrait\n# télécharger le patch, l'appliquer et créer un nouveau exe\n# créer un nouveau patch qui permet de passer de l'exe patché au exe original\n# quand on rappele xdelta, faut vérifier si un patch de revert existe, si oui l'appliquer,\n# puis appliquer la nouvelle version du patch\n# puis recréer un patch de revert\n","repo_name":"silous888/999_patchFrAuto","sub_path":"patchExe.py","file_name":"patchExe.py","file_ext":"py","file_size_in_byte":4230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"35964857340","text":"import praw\nimport time\nfrom textblob import TextBlob\n\nreddit = praw.Reddit('bot')\n\ncounter = 0\nsubmissions = list(reddit.subreddit('BotTown2').top(limit=None))\nfor submission in submissions:\n submission_text = TextBlob(submission.title + ' ' + submission.selftext)\n print('title of submission = ', submission.title)\n print('submission_text = ', submission_text)\n if 'biden' in submission_text.lower() and submission_text.sentiment.polarity > 0.5:\n submission.upvote()\n counter += 1\n print('upvoted a submission. number: ', counter)\n elif 'biden' in submission_text.lower() and submission_text.sentiment.polarity < -0.5:\n submission.downvote()\n counter += 1\n print('downvoted a submission. number: ', counter)\n\n submission.comments.replace_more(limit=None)\n all_comments = submission.comments.list()\n print('len(all_comments) = ', len(all_comments))\n for comment in all_comments:\n comment_text = TextBlob(comment.body)\n if 'biden' in comment_text.lower() and comment_text.sentiment.polarity > 0.5:\n comment.upvote()\n counter += 1\n print('upvoted a comment. number: ', counter)\n elif 'biden' in comment_text.lower() and comment_text.sentiment.polarity < -0.5:\n comment.downvote()\n counter += 1\n print('downvoted a comment. number: ', counter)\n time.sleep(30)","repo_name":"KaranGoel1/Reddit-bot","sub_path":"upvote.py","file_name":"upvote.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"27394729929","text":"import contextlib\n\nimport torch\n\nfrom .parallel_state import get_tensor_model_parallel_rank\n\n_MODEL_PARALLEL_RNG_TRACKER_NAME = \"model-parallel-rng\"\n\n\ndef _set_xla_rng_state(new_state, device=-1):\n \"\"\"Sets the random number generator state.\n\n Args:\n new_state (torch.ByteTensor): The desired state\n\n \"\"\"\n torch.set_rng_state(new_state)\n\n\nclass XLARNGStatesTracker:\n \"\"\"Tracker for the xla RNG states.\n\n Using the `add` method, a xla rng state is initialized based on\n the input `seed` and is assigned to `name`. Later, by forking the\n rng state, we can perform operations and return to our starting\n xla state.\n \"\"\"\n\n def __init__(self):\n # Map from a string name to the xla rng state.\n self.states_ = {}\n # Seeds are just for book keeping and ensure no seed is set twice.\n self.seeds_ = set()\n\n def reset(self):\n \"\"\"Set to the initial state (no tracker).\"\"\"\n self.states_ = {}\n self.seeds_ = set()\n\n def get_states(self):\n \"\"\"Get rng states. Copy the dictionary so we have direct\n pointers to the states, not just a pointer to the dictionary.\"\"\"\n states = {}\n for name in self.states_:\n states[name] = self.states_[name]\n return states\n\n def set_states(self, states):\n \"\"\"Set the rng states. For efficiency purposes, we do not check\n the size of seed for compatibility.\"\"\"\n self.states_ = states\n\n def add(self, name, seed):\n \"\"\"Track the rng state.\"\"\"\n # Check seed is not already used.\n if seed in self.seeds_:\n raise Exception(\"seed {} already exists\".format(seed))\n self.seeds_.add(seed)\n # Check that state is not already defined.\n if name in self.states_:\n raise Exception(\"xla rng state {} already exists\".format(name))\n # Get the current rng state.\n orig_xla_rng_state = torch.get_rng_state()\n # Set the new state and store it.\n torch.manual_seed(seed)\n self.states_[name] = torch.get_rng_state()\n # Reset rng state to what it was.\n _set_xla_rng_state(orig_xla_rng_state)\n\n @contextlib.contextmanager\n def fork(self, name=_MODEL_PARALLEL_RNG_TRACKER_NAME):\n \"\"\"Fork the rng state, perform operations, and exit with\n the original state.\"\"\"\n # Check if we have added the state\n if name not in self.states_:\n raise Exception(\"rng state {} is not added\".format(name))\n # Store current rng state.\n orig_xla_rng_state = torch.get_rng_state()\n # Set rng state to the desired one\n _set_xla_rng_state(self.states_[name])\n # Do the stuff we wanted to do.\n try:\n yield\n finally:\n # Update the current rng state for later use.\n self.states_[name] = torch.get_rng_state()\n # And set the state to the original state we started with.\n _set_xla_rng_state(orig_xla_rng_state)\n\n\n# RNG tracker object.\n_XLA_RNG_STATE_TRACKER = XLARNGStatesTracker()\n\n\ndef get_xla_rng_tracker():\n \"\"\"Get xla rng tracker.\"\"\"\n return _XLA_RNG_STATE_TRACKER\n\n\ndef model_parallel_xla_manual_seed(seed):\n \"\"\"Initialize model parallel xla seed.\n\n This function should be called after the model parallel is\n initialized. Also, no torch.manual_seed should be called\n after this function. Basically, this is replacement for that\n function.\n Two set of RNG states are tracked:\n default state: This is for data parallelism and is the same among a\n set of model parallel Neuron devices but different across\n different model parallel groups. This is used for\n example for dropout in the non-tensor-model-parallel regions.\n tensor-model-parallel state: This state is different among a set of model\n parallel Neuron devices, but the same across data parallel\n groups. This is used for example for dropout in\n model parallel regions.\n \"\"\"\n # 2718 is just for fun and any POSITIVE value will work.\n offset = seed + 2718\n tensor_model_parallel_seed = offset + get_tensor_model_parallel_rank()\n # Data parallel gets the original seed.\n data_parallel_seed = seed\n\n _XLA_RNG_STATE_TRACKER.reset()\n # Set the default state.\n torch.manual_seed(data_parallel_seed)\n # and model parallel state.\n _XLA_RNG_STATE_TRACKER.add(_MODEL_PARALLEL_RNG_TRACKER_NAME, tensor_model_parallel_seed)\n","repo_name":"aws-neuron/neuronx-distributed","sub_path":"src/neuronx_distributed/parallel_layers/random.py","file_name":"random.py","file_ext":"py","file_size_in_byte":4586,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"51"} +{"seq_id":"11631189975","text":"#!/usr/bin/env python3\n\n# Given a list of inputs:\n# [A|B|C] [X|Y|Z]\n# Figure out what your final score is given:\n# (For part 1)\n# A and X = Rock\n# B and Y = Paper\n# C and Z = Scissors\n# (For part 2)\n# X = you need to lose\n# Y = you need to draw\n# Z = you need to win\n#\n# 1 point if you use rock\n# 2 points if you use paper\n# 3 points if you use scissors\n#\n# 6 points for a win\n# 3 points for a draw\n\nimport sys\nimport time\n\ndef now():\n return round(time.time() * 1000)\n\ndef readInput(fileName):\n input = open(fileName, \"r\")\n commands = input.read().split(\"\\n\")\n return commands\n\n# Solution code for part 1\ndef rockPaperScissors_part1(them, me):\n if them == \"A\": # Rock\n if me == \"X\": return 1 + 3 # Draw\n if me == \"Y\": return 2 + 6 # Win\n if me == \"Z\": return 3 + 0 # Loss\n if them == \"B\": # Paper\n if me == \"X\": return 1 + 0 # Loss\n if me == \"Y\": return 2 + 3 # Draw\n if me == \"Z\": return 3 + 6 # Win\n if them == \"C\": # Scissors\n if me == \"X\": return 1 + 6 # Win\n if me == \"Y\": return 2 + 0 # Loss\n if me == \"Z\": return 3 + 3 # Draw\n # Unexpected edge case:\n return 0\n\n# Solution code for part 2\ndef rockPaperScissors_part2(them, me):\n if them == \"A\": # Rock\n if me == \"X\": return 3 + 0 # Lose (Scissors)\n if me == \"Y\": return 1 + 3 # Draw (Rock)\n if me == \"Z\": return 2 + 6 # Win (Paper)\n if them == \"B\": # Paper\n if me == \"X\": return 1 + 0 # Lose (Rock)\n if me == \"Y\": return 2 + 3 # Draw (Paper)\n if me == \"Z\": return 3 + 6 # Win (Scissors)\n if them == \"C\": # Scissors\n if me == \"X\": return 2 + 0 # Lose (Paper)\n if me == \"Y\": return 3 + 3 # Draw (Scissors)\n if me == \"Z\": return 1 + 6 # Win (Rock)\n # Unexpected edge case:\n return 0\n\ndef processMoves(ary, isPart1):\n score = 0\n for x in range(0, len(ary)):\n moves = ary[x].split(\" \")\n them = moves[0]\n me = moves[1]\n points = 0 # Default until we pick a part...\n if isPart1:\n points = rockPaperScissors_part1(them, me)\n else:\n points = rockPaperScissors_part2(them, me)\n score += points\n return score\n\n#########\n# Script\n# Here be where the code runs\n#########\n\nfileName = \"input.txt\"\nif len(sys.argv) == 2 and sys.argv[1] == \"-sample\":\n fileName = \"sample_input.txt\"\n\nary = readInput(fileName)\nstart = now()\npart1 = processMoves(ary, True)\nprint(\"Part 1: \" + str(part1) + \" (\" + str(now() - start) + \"ms)\")\n\nstart = now()\npart2 = processMoves(ary, False)\nprint(\"Part 2: \" + str(part2) + \" (\" + str(now() - start) + \"ms)\")","repo_name":"elrobe/Advent_of_Code","sub_path":"2022/2/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"25256626470","text":"import serial\nimport time\nimport random\nimport threading\nimport sys\n\nprint('Initialising connection\\n');\n\n##USB1\narduinoSerialData = serial.Serial(\n \n port='/dev/ttyUSB0',\n baudrate = 115200,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS,\n timeout=1\n )\n\ntime.sleep(8)\narduinoSerialData.flushInput()\nprint('Port opened successfully\\n')\n\narduinoSerialData.write('SET_BRIGHTNESS:255\\r'.encode())\narduinoSerialData.write('SET_COLOUR:8:0xf00\\r'.encode())\n","repo_name":"ciancostelloe/YS2018","sub_path":"testtest.py","file_name":"testtest.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"25907060318","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n# 李俊杰 2018.10.25\n\n# 爬天猫笔记本价格\nfrom urllib import request\nfrom bs4 import BeautifulSoup\nimport datetime\nimport os\nimport pymysql\n\ndef creatmysql(productTitle, productPrice, productShop, productStatus, policy, dateTime):\n\tconnection = pymysql.connect(host = 'localhost', port=3306, user='root', passwd='0509gudu', db='homework', charset='utf8')\n\tcursor = connection.cursor()\n\tsql = \"select * from computers where productTitle = %s AND productPrice = %s AND productShop = %s\"\n\tcursor.execute(sql, (productTitle, productPrice, productShop,))\n\tif len(cursor.fetchall())>0:\n\t\tsql = \"update computers set dateTime = %s where productTitle = %s AND productPrice = %s AND productShop = %s\"\n\t\tcursor.execute(sql, (dateTime, productTitle, productPrice, productShop))\n\telse:\n\t\tsql = \"insert into computers (productTitle, productPrice, productShop, productStatus, policy, dateTime) values (%s,%s,%s,%s,%s,%s)\"\n\t\tcursor.execute(sql, (productTitle, productPrice, productShop, productStatus, policy, dateTime))\n\tcursor.close()\n\tconnection.commit()\t\n\tconnection.close()\n\ndef spider():\n\tresponse = request.urlopen('https://list.tmall.com/search_product.htm?cat=50024399')\n\thtml = response.read()\n\tsoup = BeautifulSoup(html, 'lxml')\n\n\tcomputerList = soup.find(id = 'J_ItemList').find_all(\"div\", {\"class\" : \"product item-1111 \"})\n\tfor co in computerList:\n\t\twrap = co.select('.product-iWrap')[0]\n\t\tproductPrice = wrap.select('.productPrice')[0].select('em')[0].get_text()\n\t\tpolicy = wrap.find('p', {'class' : 'icon-srp-1111'}).get_text()\n\t\tproductShop = wrap.select('div.productShop > a')[0].string\n\t\tproductStatus = wrap.find('p', {'class' : 'productStatus'})\n\t\tif productStatus:\n\t\t\tproductStatus = productStatus.find('span').get_text()\n\t\tproductTitle = \"\"\n\t\tfor a in wrap.find('div', {'class' : 'productTitle'}).find_all('a'):\n\t\t\tproductTitle += a.string\n\t\tdateTime = datetime.datetime.now()\n\t\tcreatmysql(productTitle.replace('\\n', '').replace(' ', ''), productPrice, productShop.replace('\\n', ''), str(productStatus), str(policy), dateTime)\nspider()\n","repo_name":"jiaoluoli/courseWorkApplyingSpider","sub_path":"homework2.py","file_name":"homework2.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"35657594858","text":"# Compatibilidad entre Python 2 y 3\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport pandas as pd # Para el manejo de datos\nimport numpy as np # Para operaciones matemáticas de nivel inicial\n\n# Preprocesamiento de los datos (texto)\nfrom keras.preprocessing import text,sequence \n\n# Modelo\nfrom keras.models import Sequential\nfrom keras.layers import Embedding,Conv1D,MaxPooling1D,Flatten,Dropout,Dense # SeparableConv1D, GlobalAveragePooling1D\nfrom keras.callbacks import EarlyStopping\nfrom keras.optimizers import Adam\n\nimport funciones_auxiliares as fa\nimport cargar_imdb as ci\n\nimport explore_data as ed\n\n# Carga de datos\n(x_entrenamiento,y_entrenamiento),(x_prueba,y_prueba) = ci.load_imdb_sentiment_analysis_dataset('E:\\\\Descargas\\\\Python\\\\neural_networks')\n\n# num_classes = ed.get_num_classes(y_entrenamiento)\n# print(num_classes)\n\n# print(ed.get_num_words_per_sample(x_entrenamiento))\n# ed.plot_sample_length_distribution(x_entrenamiento)\n\n# Variables\nTOP_PALABRAS_FRECUENTES = 20000 # Cantidad de palabras en el vocabulario\nMAXIMA_LONGITUD_EJEMPLOS = 500 # Máxima longitud de los ejemplos de entrada\nDIMENSION_VECTORES_EMBEDDING = 300 # Cantidad de elementos de los vectores de embedding\nEMBEDDING_ENTRENABLE = True # Bandera de adaptación de pesos para embeddings preentrenados\nPORCENTAJE_DROPEO = 0.5 # Pone en 0 el #% de los datos aleatoriamente\nCANTIDAD_FILTROS = 16 # Cantidad de filtro de convolución\nDIMENSION_KERNEL = 3 # De 1x3\nDIMENSION_POOLING = 2\nNEURONAS_OCULTAS = 32\nVELOCIDAD_APRENDIZAJE = 1e-3\nCANTIDAD_EPOCAS = 100\nPORCENTAJE_VALIDACION = 0.2 # 20% de ejemplos usados para validar. Son tomados desde el final\nDIMENSION_BACHA = 512\n\n# Crea el vocabulario a partir de los datos de entrenamiento\ntokenizer = text.Tokenizer(num_words=TOP_PALABRAS_FRECUENTES)\ntokenizer.fit_on_texts(x_entrenamiento)\n\n# Vectorización de los datos de entrada (entrenamiento y prueba): \"Hola querido mundo\" -> [3857 274 982]\nx_entrenamiento_vectorizado = tokenizer.texts_to_sequences(x_entrenamiento)\nx_prueba_vectorizado = tokenizer.texts_to_sequences(x_prueba)\n\n# Obtener longitud del ejemplo más largo\nmaxima_longitud = len(max(x_entrenamiento_vectorizado,key=len))\nif maxima_longitud > MAXIMA_LONGITUD_EJEMPLOS:\n maxima_longitud = MAXIMA_LONGITUD_EJEMPLOS\n\n# Se arreglan los ejemplos para que todos tengan la misma longitud\nx_entrenamiento_arreglado = sequence.pad_sequences(x_entrenamiento_vectorizado,maxlen=maxima_longitud)\nx_prueba_arreglado = sequence.pad_sequences(x_prueba_vectorizado,maxlen=maxima_longitud)\n\nindice_palabras = tokenizer.word_index\n\n# Se cargan vectores de embedding preentrenados (GloVe)\nembeddings_index = dict()\nf = open(\"E:/Descargas/Python/glove.6B.300d.txt\",encoding=\"utf8\")\nfor line in f:\n values = line.split()\n word = values[0]\n coefs = np.asarray(values[1:], dtype='float32')\n embeddings_index[word] = coefs\nf.close()\n\nembedding_matrix = np.zeros((TOP_PALABRAS_FRECUENTES,DIMENSION_VECTORES_EMBEDDING))\nfor word, index in tokenizer.word_index.items():\n if index > TOP_PALABRAS_FRECUENTES - 1:\n break\n else:\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n embedding_matrix[index] = embedding_vector\n\n# Modelo secuencial (una capa detrás de la otra): Perceptrón multicapa (Arquitectura)\nmodelo = Sequential()\n\n'''Dropout: se utiliza para evitar el sobreentrenamiento'''\n\n# model.add(Embedding(input_dim=TOP_PALABRAS_FRECUENTES,\n# output_dim=DIMENSION_VECTORES_EMBEDDING,\n# input_length=maxima_longitud))\n\nmodelo.add(Embedding(input_dim=TOP_PALABRAS_FRECUENTES,\n output_dim=DIMENSION_VECTORES_EMBEDDING,\n input_length=maxima_longitud,\n weights=[embedding_matrix],\n trainable=EMBEDDING_ENTRENABLE)) # De aca sale un 500x300\n\n# modelo.add(Dropout(PORCENTAJE_DROPEO))\n\nmodelo.add(Conv1D(filters=CANTIDAD_FILTROS,\n kernel_size=DIMENSION_KERNEL,\n activation='relu',\n bias_initializer='random_uniform',\n padding='same'))\nmodelo.add(MaxPooling1D(pool_size=DIMENSION_POOLING))\n\nmodelo.add(Conv1D(filters=CANTIDAD_FILTROS,\n kernel_size=DIMENSION_KERNEL,\n activation='relu',\n bias_initializer='random_uniform',\n padding='same'))\nmodelo.add(MaxPooling1D(pool_size=DIMENSION_POOLING))\n\nmodelo.add(Flatten()) # input_shape=(imagen_ancho,imagen_alto)\n\n# Capa de entrada\nmodelo.add(Dropout(PORCENTAJE_DROPEO))\nmodelo.add(Dense(NEURONAS_OCULTAS,activation='relu'))\n\n# Capa de salida\nmodelo.add(Dropout(PORCENTAJE_DROPEO))\nmodelo.add(Dense(1,activation='sigmoid'))\n\n'''\nActivations: Funciones de activación\n elu\n softmax\n selu\n softplus\n softsign\n relu\n tanh\n sigmoid\n hard_sigmoid\n exponential\n linear\n'''\n\n# Proceso de aprendizaje\noptimizador = Adam(lr=VELOCIDAD_APRENDIZAJE)\nmodelo.compile(optimizer=optimizador, # Velocidad de aprendizaje\n loss='binary_crossentropy', # Función de error\n metrics=['accuracy']) # Análisis del modelo (Tasa de acierto))\n\n'''\nOptimizers (Velocidad de aprendizaje):\n sgd\n rmsprop\n adagrad\n adadelta\n adam\n adamax\n nadam\n \nLoss: Función que compara la salida deseada con la calculada. Criterio de error.\nSe busca minimizar esta función mediante el método del gradiente descendente.\n mean_squared_error\n mean_absolute_error\n mean_absolute_percentage_error\n mean_squared_logarithmic_error\n squared_hinge\n hinge\n categorical_hinge\n logcosh\n huber_loss\n categorical_crossentropy\n sparse_categorical_crossentropy\n binary_crossentropy\n kullback_leibler_divergence\n poisson\n cosine_proximity\n is_categorical_crossentropy\n \nMetrics: Análisis de desempeño del modelo\n accuracy\n binary_accuracy\n categorical_accuracy\n sparse_categorical_accuracy\n top_k_categorical_accuracy\n sparse_top_k_categorical_accuracy\n cosine_proximity\n clone_metric\n clone_metrics\n'''\n\n# Create callback for early stopping on validation loss. If the loss does\n# not decrease in two consecutive tries, stop training.\ncallbacks = [EarlyStopping(monitor='val_accuracy',patience=1)] # 'val_loss'\n\n# Detalles del modelo neuronal\nmodelo.summary()\n\n# Entrenamiento del modelo\nregistro = modelo.fit(x_entrenamiento_arreglado,\n y_entrenamiento,\n epochs=CANTIDAD_EPOCAS,\n callbacks=callbacks,\n validation_data=(x_prueba_arreglado,y_prueba), # PORCENTAJE_VALIDACION\n verbose=1,\n batch_size=DIMENSION_BACHA)\n\nfa.graficas(registro)\n\n# Evaluación del modelo\n# prueba_error,prueba_acierto = model.evaluate(x_prueba,y_prueba)\n\n# Hacer predicciones\n# predicciones = model.predict(x_prueba)","repo_name":"johny65/PFC_DGIdb_src","sub_path":"practice/cnn_text.py","file_name":"cnn_text.py","file_ext":"py","file_size_in_byte":6967,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"74920287517","text":"from __future__ import division\nfrom parent import *\n\n\nclass FourWayBranchComplex(ParentComplex):\n\t\"\"\"Four-way strand exchange reaction\"\"\"\n\tdef __init__( self, ms, ns , theta,complex1, complex2, reporter1, reporter2, lenX, lenm, lenn ,T, concentration, sodium, magnesium, dataset_name, docID, kinetic_model):\n\t\tParentComplex.__init__(self, theta , T, concentration, sodium, magnesium, dataset_name, docID, kinetic_model )\n\t\tself.complex1 = complex1\n\t\tself.complex2 = complex2\n\t\tself.reporter1 = reporter1\n\t\tself.reporter2 = reporter2\n\t\tself.T = T\n\t\tself.concentration = concentration\n\t\tself.sodium = sodium\n\t\tself.magnesium = magnesium\n\t\tself.X = lenX\n\t\tself.m = lenm\n\t\tself.n = lenn\n\t\tself.ms = ms\n\t\tself.ns = ns\n\n\tdef dot_paren( self, state):\n\t\t\"\"\"Returns the structure of the complex in dot-paren notation\"\"\"\n\t\ti, j, ip, jp , k , l= state\n\t\treporter1= '(' * k + '.' * ( i - k ) +'('*( ip - i ) + '.'*( self.X + self.ms - ip )\n\t\tcomplex1 = '.' * (self.X + self.m - ip ) + ')' * (ip- i ) + '.' * ( i - l ) + '(' * l\n\t\tcomplex2 = ')' * l + '.' * ( j -l ) + '(' *( jp - j ) + '.' * (self.X+ self.n - jp )\n\t\treporter2= '.' * (self.X+ self.ns - jp ) + ')' * ( jp - j) + '.' * ( j -k ) + ')' * k\n\t\tif ( i == ip and j == jp ):\n\t\t\treturn [complex1 + '+' + complex2 , reporter1 + '+' + reporter2 ]\n\t\telif k == 0 and l ==0 :\n\t\t\treturn [reporter1 + '+' + complex1 , complex2 + '+'+ reporter2 ]\n\n\t\telse:\n\t\t\treturn [reporter1 +'+'+ complex1+'+' + complex2+'+' + reporter2, -1 ]\n\n\tdef dot_paren_modify( self,state):\n\t\t\"\"\"Insert \t`*' at the start and end of the dot-paren notation, before and after all `+' signs, and also before and after every space\"\"\"\n\t\ti, j, ip, jp , k , l= state\n\t\treporter1= '(' * k + '.' * ( i - k ) +'('*( ip - i ) + '.'*( self.X + self.ms - ip )\n\t\tcomplex1 = '.' * (self.X + self.m - ip ) + ')' * (ip- i ) + '.' * ( i - l ) + '(' * l\n\t\tcomplex2 = ')' * l + '.' * ( j -l ) + '(' *( jp - j ) + '.' * (self.X+ self.n - jp )\n\t\treporter2= '.' * (self.X+ self.ns - jp ) + ')' * ( jp - j) + '.' * ( j -k ) + ')' * k\n\t\treturn '*' + reporter1 + '*' + '+'+ '*' + complex1+ '*' + '+' + '*' + complex2+ '*' + '+' + '*' + reporter2 + '*'\n\n\tdef sequence( self, state):\n\t\t\"\"\"Returns the sequence of the complex as NUPACK expects. The\n\t\t first line is the number of independent strands, and the last\n\t\t line determines how many times each strand appears.\"\"\"\n\t\ti, j, ip, jp, k , l = state\n\t\tif ( i == ip and j == jp ):\n\t\t\t#return [complex1 + '+' + complex2 , reporter1 + '+' + reporter2 ]\n\t\t\treturn [ ('2\\n' + self.complex1.sequence + '\\n' + self.complex2.sequence+ '\\n1 2\\n'),\n\t\t\t('2\\n' + self.reporter1.sequence + '\\n' + self.reporter2.sequence + '\\n1 2\\n') ]\n\t\telif k == 0 and l == 0 :\n\t\t\treturn [ ('2\\n' + self.reporter1.sequence + '\\n' + self.complex1.sequence+ '\\n1 2\\n'),\n\t\t\t('2\\n' + self.complex2.sequence + '\\n' + self.reporter2.sequence + '\\n1 2\\n') ]\n\t\telse:\n\t\t\treturn [ ('4\\n' + self.reporter1.sequence + '\\n' +\n\t\t\t\t\tself.complex1.sequence + '\\n' +\n\t\t\t\t\tself.complex2.sequence + '\\n' +\n\t\t\t\t\tself.reporter2.sequence + '\\n1 2 3 4\\n'), -1 ]\n\n\n\tdef num_complex(self) :\n\t\t\"\"\"counts the number of complexes in each state \"\"\"\n\t\tself.n_complex = dict()\n\t\tfor state in self.statespace:\n\t\t\tdot_parenstate1 = self.dot_paren(state)\n\t\t\tself.n_complex[state] = 2 if dot_parenstate1[1] != -1 else 1\n\n\tdef allowed_state(self , state):\n\t\t\"\"\"Checks that a state is allowed.\"\"\"\n\t\ti, j, ip, jp , k , l = state\n\t\tallow = (l <= i and l <= j and k <= i and k <= j and 0 <=k <= self.X and 0 <= l <= self.X and 0 <= i <= ip and ip <= self.X+ self.m and 0 <= j <= jp and jp<=self.X +self.n )\n\t\t# Further prune the statespace to make computations tractable\n\t\tif ( ( i == ip or j == jp ) and ( k ==0 or l ==0 ) ) :\n\t\t\tallow = False\n\t\tif (self.m ==0 or self.n ==0 ) and ( ( i == ip ) or (j == jp ) ) and ( ( k < self.X -(2 - int(self.m/3) ) -1) or (l < self.X -(2 - int(self.n/3) ) -1) ):\n\t\t\tallow = False\n\t\tif (self.m !=0 and self.n !=0 ) and ( ( i == ip ) or (j == jp ) ) and ( ( k < self.X -1 ) or (l < self.X -1) ):\n\t\t\tallow = False\n\n\n\t\tif ip < self.X or jp < self.X:\n\t\t\tallow = False\n\t\tif (i != ip and j != jp ) and ( abs ( i -l )+ abs ( i - k ) + abs( j - l ) + abs ( j - k ) > 4 + ( 2- self.n/3 )+ ( 2- self.m/3 ) ):\n\t\t\tallow = False\n\n\t\treturn allow\n\n\tdef possible_states( self, state):\n\t\t\"\"\"Returns the neighbors of state\"\"\"\n\t\t\n\t\ti, j, ip, jp , k , l = state\n\t\tstates = []\n\t\tmaxkl = max ( k, l )\n\t\tif (i == ip ) :\n\t\t\tstates += [(n , j, n+ 1, jp , k, l ) for n in range ( maxkl , self.X + self.m) ]\n\t\telse :\n\t\t\tstates += [(i - 1, j, ip, jp , k, l ),\n\t\t\t\t\t (i + 1, j, ip, jp , k, l ),\n\t\t\t\t\t (i, j, ip - 1 , jp , k, l ),\n\t\t\t\t\t (i, j, ip +1 , jp , k, l ) ]\n\t\tif (j == jp ) :\n\t\t\tstates += [(i , n , ip, n+1 , k, l ) for n in range ( maxkl , self.X + self.n)]\n\t\telse :\n\t\t\tstates += [(i, j - 1, ip, jp ,k, l ),\n\t\t\t\t\t (i, j, ip, jp - 1 , k, l ),\n\t\t\t\t\t (i, j + 1,ip, jp , k, l ),\n\t\t\t\t\t (i, j, ip, jp + 1 , k, l ) ]\n\t\tif ( i!=ip or j!= jp ) or ( self.m == 0 or self.n ==0 ) :\n\t\t\tstates += [(i, j, ip, jp , k - 1, l ) ]\n\t\t\tstates += [(i, j, ip, jp , k + 1, l ) ]\n\t\t\tstates += [ (i, j, ip, jp ,k , l -1 ) ]\n\t\t\tstates += [ (i, j, ip, jp ,k , l +1 ) ]\n\t\tremoved = False\n\t\tremoveList = []\n\t\tfor s in states :\n\t\t\tif s[0] == s[2] and 0 <= s[0] < self.X+ self.m :\n\t\t\t\tremoveList.append((s[0],s[1], s[2] , s[3] , s[4] , s[5] ))\n\t\t\t\tremoved= True\n\t\tfor s in removeList:\n\t\t\tstates.remove(s )\n\t\tif removed == True :\n\t\t\tstates.append((self.X+ self.m , s[1], self.X+ self.m , s[3] , s[4], s[5] ))\n\t\tremoved = False\n\t\tremoveList = []\n\t\tfor s in states :\n\t\t\tif s[1] == s[3] and 0 <= s[1] < self.X+ self.n :\n\t\t\t\tremoveList.append((s[0],s[1], s[2] , s[3] , s[4] , s[5] ))\n\t\t\t\tremoved= True\n\t\tfor s in removeList:\n\t\t\tstates.remove(s )\n\t\tif removed == True :\n\t\t\tstates.append((s[0], self.X+ self.n , s[2], self.X+ self.n , s[4], s[5] ))\n\t\tfilteredStates = filter(self.allowed_state, states)\n\t\t# self.PSD[state ] = filteredStates\n\t\treturn filteredStates\n\n\tdef initial_final_state_config(self ):\n\t\t\"\"\"sets the initial and final state for four-way strand exchange\"\"\"\n\t\tinitialStateConfig = (self.X + self.m , self.X + self.n , self.X+ self.m , self.X + self.n , self.X , self.X )\n\t\tfinalStateConfig= ( 0 , 0 , self.X + self.m , self.X + self.n , 0 , 0 )\n\t\treturn [initialStateConfig, finalStateConfig]\n\ndef main(bi_real_rate, uni_real_rate , lenm, lenn, Xstr,toeholdstrm, toeholdstrn , ms, ns , theta, T, concentration, sodium, magnesium ,dataset_name, docID , name, kinetic_model):\n\t# Xstr= Xstr.encode()\n\t# toeholdstrm= toeholdstrm.encode()\n\t# toeholdstrn= toeholdstrn.encode()\n\tcomplex1 = MyStrand(toeholdstrm[len(toeholdstrm)- lenm: ] + Xstr )\n\tFullToehold = MyStrand(toeholdstrm[len(toeholdstrm)- ms : ] + Xstr )\n\treporter1 = FullToehold.complement\n\tcomplex2 = MyStrand( MyStrand(Xstr).complement.sequence + toeholdstrn[ :lenn ])\n\tFullToehold = MyStrand( MyStrand(Xstr).complement.sequence + toeholdstrn[ : ns ])\n\treporter2 = FullToehold.complement\n\tlenX = len(Xstr)\n\tfourwaybranch_complex= FourWayBranchComplex (ms, ns , theta,complex1, complex2, reporter1, reporter2,lenX, lenm, lenn, T, concentration, sodium, magnesium , dataset_name, docID, kinetic_model)\n\tbimolTransition = True\n\tif name == \"Dabby\":\n\t\t\"\"\"Table 5.1 from DABBY's thesis report unimolecular rates and Table 5.2 reports bimolecular rates separately. Combining the two rates to obtain an overall reaction rate constant \"\"\"\n\t\tt1 = 1 / (bi_real_rate * concentration)\n\t\tt2 = 1 / uni_real_rate\n\t\treal_rate = 1 / ((t1 + t2) * concentration)\n\treturn fourwaybranch_complex.rate_constant(concentration, real_rate, bimolTransition, kinetic_model)\n\nif __name__ == \"__main__\":\n\tmain( )\n","repo_name":"aliseyfi75/Probabilistic-Programming","sub_path":"Project/Code/Scripts/four_waystrandexchange.py","file_name":"four_waystrandexchange.py","file_ext":"py","file_size_in_byte":7919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"23368485875","text":"from invenio_access.permissions import system_identity\nfrom invenio_rdm_records.records.api import RDMRecord\nfrom invenio_rdm_records.resources.serializers.dublincore import (\n DublinCoreJSONSerializer,\n)\nfrom invenio_records_lom.records.api import LOMRecord\nfrom invenio_records_lom.utils import LOMMetadata\nfrom invenio_records_marc21.records.api import Marc21Record\nfrom invenio_records_marc21.services.record import Marc21Metadata\n\nfrom .components import map_metadata_from_a_to_b\nfrom .serializers import LOMRecordJSONSerializer, Marc21RecordJSONSerializer\n\n\ndef rebuild_database_rdm() -> None:\n \"\"\"Rebuild index rdm.\"\"\"\n records = RDMRecord.model_cls.query.all()\n for rec in records:\n record = RDMRecord(rec.data, model=rec)\n map_metadata_from_a_to_b(\n record,\n serializer_cls=DublinCoreJSONSerializer,\n schema=\"rdm\",\n identity=system_identity,\n )\n\n\ndef rebuild_database_marc21() -> None:\n \"\"\"Rebuild index marc21.\"\"\"\n records = Marc21Record.model_cls.query.all()\n for rec in records:\n record = Marc21Record(rec.data, model=rec)\n map_metadata_from_a_to_b(\n record,\n serializer_cls=Marc21RecordJSONSerializer,\n metadata_cls=Marc21Metadata,\n schema=\"marc21\",\n identity=system_identity,\n )\n\n\ndef rebuild_database_lom() -> None:\n \"\"\"Rebuild index lom.\"\"\"\n records = LOMRecord.model_cls.query.all()\n for rec in records:\n record = LOMRecord(rec.data, model=rec)\n map_metadata_from_a_to_b(\n record,\n serializer_cls=LOMRecordJSONSerializer,\n metadata_cls=LOMMetadata,\n schema=\"lom\",\n identity=system_identity,\n )\n","repo_name":"tu-graz-library/invenio-global-search","sub_path":"invenio_global_search/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"70439935199","text":"import math\nimport sys\n\ninput = sys.stdin.readline\nn = int(input())\nd = [0, 1]\n\nfor i in range(2, n + 1):\n mn = 1e9\n for j in range(1, int(math.sqrt(i)) + 1):\n mn = min(mn, d[i - j ** 2])\n d.append(mn + 1)\n\nprint(d[n])\n","repo_name":"XIO1016/algorithm","sub_path":"17626.py","file_name":"17626.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"29421389300","text":"import random\nimport math\nimport operator\n\n\ndef loadfile():\n data = {}\n lines = open('u.data').readlines()\n for line in lines:\n user,movie,star,addtime = line.strip().split('\\t')\n if user not in data: data[user] = {}\n data[user][movie] = star\n return data\n\n\ndef get_data(data,m=.75):\n train = {}\n test = {}\n for user,movies in data.items():\n for movie,star in movies.items():\n if random.random() < m:\n if user not in train: train[user] = {}\n train[user][movie] = star\n else:\n if user not in test: test[user] = {}\n test[user][movie] = star\n return train,test\n\n\ndef get_w(train):\n n = {}\n w = {}\n for user,movies in train.items():\n for x in movies:\n n[x] = n.get(x,0)+1\n for y in movies:\n if x != y:\n if x not in w: w[x] = {}\n w[x][y] = w[x].get(y,0)+1\n total = len(n)\n\n for x,related_movies in w.items():\n for y,wxy in related_movies.items():\n w[x][y] = float(wxy)/math.sqrt(n[x]*n[y])\n return w,total\n\n\ndef recommend(user,train,w,k=20,j=10):\n recommend_movies = {}\n watched_movies = train[user]\n for x,star in watched_movies.items():\n for y,wxy in sorted(w[x].items(),key=operator.itemgetter(1),reverse=True)[:k]:\n if y not in watched_movies: recommend_movies[y] = recommend_movies.get(y,0)+wxy*float(star)\n return sorted(recommend_movies.items(),key=operator.itemgetter(1),reverse=True)[:j]\n\n\ndef evaluate(train,test,w,total,k=20,j=10):\n hit = 0\n total_recall = 0\n total_precision = 0\n all_recommend_movies = set()\n for user in train:\n recommend_movies = recommend(user,train,w,k,j)\n test_movies = test.get(user,{})\n for movie,_ in recommend_movies:\n if movie in test_movies: hit += 1\n all_recommend_movies.add(movie)\n total_recall += len(test_movies)\n total_precision += len(recommend_movies)\n precision = float(hit)/total_precision\n recall = float(hit)/total_recall\n coverage = float(len(all_recommend_movies))/total\n return precision,recall,coverage\n\n\nif __name__ == '__main__':\n data = loadfile()\n train,test = get_data(data)\n w,total = get_w(train)\n print(evaluate(train,test,w,total)) #0.33775185577942735, 0.12710004389640447, 0.12021857923497267","repo_name":"zmx6999/ItemCFAndUserCF","sub_path":"ItemCF.py","file_name":"ItemCF.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"72698683998","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\nimport sys\nimport re\n\ns = sys.stdin.read() # The string to read and iterate over\n\nmy_regEx = re.compile(pattern=r'[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm]?([AEIOUaeiou]{2,})[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm]')\n\nif re.findall(pattern=my_regEx, string=s):\n for item in re.findall(pattern=my_regEx, string=s):\n print(item)\nelse:\n print('-1')\n","repo_name":"acarter881/hacker_rank_python_answers","sub_path":"re_findall_and_iter.py","file_name":"re_findall_and_iter.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"26387975905","text":"#!/usr/bin/python3\nimport sys\nimport os\nimport struct\nimport math\n\nclass Quaternion:\n\tdef __init__(self,w,x,y,z):\n\t\tself.w=w\n\t\tself.x=x\n\t\tself.y=y\n\t\tself.z=z\n\tdef getMagnitude(self):\n\t\treturn math.sqrt(self.w*self.w + self.x*self.x + self.y*self.y + self.z*self.z)\n\tdef getConjugate(self):\n\t\treturn Quaternion(self.w, -self.x, -self.y, -self.z)\n\tdef normalize(self):\n\t\tm=self.getMagnitude()\n\t\tself.w/=m\n\t\tself.x/=m\n\t\tself.y/=m\n\t\tself.z/=m\n\tdef getProduct(self,q):\n\t\treturn Quaternion(\n\t\t\tself.w*q.w - self.x*q.x - self.y*q.y - self.z*q.z,\n\t\t\tself.w*q.x + self.x*q.w + self.y*q.z - self.z*q.y,\n\t\t\tself.w*q.y - self.x*q.z + self.y*q.w + self.z*q.x,\n\t\t\tself.w*q.z + self.x*q.y - self.y*q.x + self.z*q.w\n\t\t)\n\tdef getEular(self):\n\t\treturn [\n\t\t\tmath.atan2(2*self.w*self.z + 2*self.x*self.y, 1-2*self.y*self.y-2*self.z*self.z)*180/math.pi,\n\t\t\tmath.asin(2*self.w*self.y - 2*self.z*self.x)*180/math.pi,\n\t\t\tmath.atan2(2*self.w*self.x + 2*self.y*self.z, 1-2*self.x*self.x-2*self.y*self.y)*180/math.pi\n\t\t]\n\t\n\ndef pwm_trim(ch):\n\tif ch<500:\n\t\treturn 500\n\tif ch>2500:\n\t\treturn 2500\n\treturn ch\nq0=Quaternion(1,0,0,0)\ndef angle_integral(xyz,q):\n\tglobal q0\n\tq.normalize()\n\tqd=q0.getConjugate().getProduct(q)\n\typrd=qd.getEular()\n\tq0=q\n\txyz[0]-=yprd[2]#CC3D X = MPU -Y = -Roll\n\txyz[1]-=yprd[1]#CC3D Y = MPU -X = -Pitch\n\txyz[2]+=yprd[0]#CC3D Z = MPU Z = Yaw\n\tfor i in range(0,3):\n\t\twhile xyz[i]>90:\n\t\t\txyz[i]-=45\n\t\twhile xyz[i]<0:\n\t\t\txyz[i]+=45\n\treturn xyz\t\ndef convert(filename):\n\tcsv=\"\"\n\tf = open(filename, \"rb\")\n\tlast_pn=0\n\tbyte = 1\n\tcsv+=\"T,CH1,CH2,CH3,CH4,CH5,RPM,X,Y,Z,TX1,TX2,TX3,TX4,TX5,TX6,TX7\\n\"\n\tcsv+=\"65536,2000,2000,2000,2000,2000,0,90,90,90,1023,1023,1023,1023,1023,1023,1023\\n\"\n\tcsv+=\"0,1000,1000,1000,1000,1000,0,0,0,0,0,0,0,0,0,0,0\\n\"\n\txyz=[0,0,0]\n\tbyte = [1]\n\twhile True:\n\t\tbyte = [byte[len(byte)-1]]\n\t\twhile byte[0] != 0x7f:\n\t\t\tbyte = f.read(1)\n\t\t\tif len(byte)<1:\n\t\t\t\tbreak\n\t\tbyte = f.read(1)\n\t\tif len(byte)<1:\n\t\t\tbreak\n\t\tif byte[0] != 0x7f:\n\t\t\tcontinue\n\t\t#sync with 0x7f7f\n\n\t\tbyte = f.read(47)\n\t\tif len(byte)<47:\n\t\t\tbreak\n\t\tif byte[46] != 0x7f:\n\t\t\tcontinue\n\t\t\n\t\tarr = struct.unpack(\"\", pn, \"SD card too slow\")\n\t\tlast_pn = pn\n\tf.close()\n\treturn csv\n\nif len(sys.argv)<2:\n\tfilenumber=0\n\tfor filename in os.listdir():\n\t\tif filename.endswith(\".TXT\") and filename.startswith(\"LOG\"):\n\t\t\tn=int(filename[3:8])\n\t\t\tif n>filenumber:\n\t\t\t\tfilenumber=n\n\tfilebasename=\"LOG\"+str(filenumber).zfill(5)\n\tfilename=filebasename+\".TXT\"\n\tif os.path.isfile(filename):\n\t\timport plot\n\t\tfrom io import StringIO\n\t\tcsvstring = convert(filename)\n#\t\tprint(csvstring)\n\t\tfout = open(filebasename+\".csv\",\"w\")\n\t\tfout.write(csvstring)\n\t\tfout.close()\n\t\tf = StringIO(csvstring)\n\t\tplot.plot(f)\n\telse:\n\t\tprint(\"no file found\")\n\nelse:\n\tprint(convert(sys.argv[1]))\n","repo_name":"gongtao0607/BlackboxCC3D","sub_path":"LogParser/BlackboxCC3D.py","file_name":"BlackboxCC3D.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"74541131999","text":"# -*- coding: utf-8 -*-\r\n# pylint: skip-file\r\n\"\"\"Configuration for Sphinx.\"\"\"\r\n\r\nfrom __future__ import unicode_literals\r\n\r\nimport os\r\n\r\nimport sphinx_rtd_theme\r\n\r\nwith open(\"../canlib/__about__.py\") as fp:\r\n exec(fp.read())\r\n\r\ntry:\r\n with open(\"../canlib/__version__.py\") as fp:\r\n exec(fp.read())\r\nexcept IOError:\r\n __version__ = __dummy_version__\r\n\r\nextensions = [\r\n 'sphinx.ext.autodoc',\r\n 'sphinx.ext.autosummary',\r\n 'sphinx.ext.coverage',\r\n 'sphinx.ext.doctest',\r\n 'sphinx.ext.extlinks',\r\n 'sphinx.ext.ifconfig',\r\n 'sphinx.ext.napoleon',\r\n 'sphinx.ext.todo',\r\n 'sphinx.ext.viewcode',\r\n]\r\nif os.getenv('SPELLCHECK'):\r\n extensions += 'sphinxcontrib.spelling'\r\n spelling_show_suggestions = True\r\n spelling_lang = 'en_US'\r\n\r\n\r\nsource_suffix = '.rst'\r\nmaster_doc = 'index'\r\nproject = __title__\r\nyear = __year__\r\nauthor = '{a} <{e}>'.format(a=__author__, e=__email__)\r\ncopyright = __copyright__\r\nversion = release = __version__\r\n\r\ndefault_role = 'py:obj'\r\n\r\n# RTD packages pygment styles inside its theme.css and cannot be overridden:\r\n# https://github.com/snide/sphinx_rtd_theme/blob/master/sass/theme.sass#L45\r\n# pygments_style = 'trac' # 'igor' # 'trac'\r\n# templates_path = ['.']\r\n\r\nhtml_theme = \"sphinx_rtd_theme\"\r\nhtml_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\r\n\r\nhtml_last_updated_fmt = '%a, %d %b %Y'\r\nhtml_split_index = False\r\nhtml_sidebars = {\r\n '**': ['searchbox.html', 'globaltoc.html', 'sourcelink.html'],\r\n}\r\n# html_short_title = '%s-%s' % (project, version)\r\n\r\n# Get Windows line endings in Relnotes for Finn in nightly build\r\ntext_newlines = 'native'\r\n\r\nnapoleon_use_ivar = True\r\nnapoleon_use_rtype = False\r\nnapoleon_use_param = False\r\n# napoleon_google_docstring = False\r\n# https://michaelgoerz.net/notes/extending-sphinx-napoleon-docstring-sections.html\r\n# https://samnicholls.net/2016/06/15/how-to-sphinx-readthedocs/\r\n","repo_name":"Kvaser/pycanlib","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"51"} +{"seq_id":"25387333487","text":"import math\nimport cv2\nimport random as rd\nimport matplotlib.pyplot as plt\nfrom nnga.callbacks.visualization.commons import plot_to_image\n\n\ndef segmentation_vis(model, validation_dataset):\n # Use the model to predict the values from the test_images.\n idx = rd.randint(0, len(validation_dataset) - 1)\n batch_imgs, batch_masks = validation_dataset[idx]\n pred_masks = model.predict(batch_imgs)\n\n return {\"Segmentation\": plot_to_image(\n plot_masks(batch_imgs, batch_masks, pred_masks))\n }\n\n\ndef plot_masks(imgs, masks, predcit_masks):\n columns = 3\n rows = math.ceil(len(imgs))\n img_size = 2.5\n figure = plt.figure(figsize=(math.ceil(columns * img_size),\n math.ceil(rows * img_size)))\n\n for i in range(len(imgs)):\n # Start next subplot.\n predcit_mask = predcit_masks[i]\n mask = masks[i]\n img = imgs[i]\n\n if img.shape[2] == 1:\n img = img[:, :, 0]\n\n plt.subplot(rows, columns, i * 3 + 1, title=\"Image\")\n plt.imshow(img, cmap=plt.cm.binary)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n\n _, mask = cv2.threshold(mask, 0.5, 255, cv2.THRESH_BINARY)\n mask = mask.astype('uint8')\n masked_data = cv2.bitwise_and(img, img, mask=mask)\n\n plt.subplot(rows, columns, i * 3 + 2, title=\"Mask\")\n plt.imshow(masked_data, cmap=plt.cm.binary)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n\n _, predcit_mask = cv2.threshold(predcit_mask, 0.5, 255, cv2.THRESH_BINARY)\n predcit_mask = predcit_mask.astype('uint8')\n predict_masked_data = cv2.bitwise_and(img, img, mask=predcit_mask)\n\n plt.subplot(rows, columns, i * 3 + 3, title=\"Predict Mask\")\n plt.imshow(predict_masked_data, cmap=plt.cm.binary)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n\n figure.tight_layout()\n return figure\n","repo_name":"rafaelsdellama/nnga","sub_path":"nnga/callbacks/visualization/segmentation_vis.py","file_name":"segmentation_vis.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"4311277645","text":"from django.urls import path\nfrom chinnu_reddy import views\nurlpatterns =[\npath('rt/',views.home,name=\"home\"),\npath('demo/',views.chk),\npath('hm/',views.homepage),\npath('lg/',views.lgn),\npath('rg/',views.reg),\npath('',views.bthm),\npath('about/',views.about,name=\"about\"),\npath('contact/',views.contact,name=\"contact\"),\npath('registration/',views.registration,name=\"registration\"),\npath('cr/',views.crud,name=\"cr\"),\npath('del/',views.deletedata,name=\"delete\"),\npath('df/',views.dform,name=\"dff\"),\npath('showdata/',views.showinfo,name=\"show\"),\npath('infodelete/',views.infodelete,name=\"infodelete\"),\n# path('edit/',views.edit,name=\"editdata\"),\npath('e//',views.userupdate,name=\"ue\"),\npath('ui//',views.userinfo,name=\"ufi\"),\n\n]\n\n","repo_name":"chinnureddy14/chinnureddyproject","sub_path":"chinnu_reddy/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"33256153847","text":"import time\n\nimport pytest\n\npytestmark = pytest.mark.ui\n\nfrom panel.io.server import serve\nfrom panel.pane import Markdown\nfrom panel.template import FastGridTemplate\n\n\ndef test_fast_grid_template_no_console_errors(page, port):\n tmpl = FastGridTemplate()\n md = Markdown('Initial')\n\n tmpl.main[0:3, 0:3] = md\n\n serve(tmpl, port=port, threaded=True, show=False)\n\n time.sleep(0.2)\n\n msgs = []\n page.on(\"console\", lambda msg: msgs.append(msg))\n\n page.goto(f\"http://localhost:{port}\", timeout=40_000)\n\n expected = ['maxWidth', 'maxHeight']\n assert [\n msg for msg in msgs if msg.type == 'error' and not any(e in msg.text for e in expected)\n ] == []\n\n\ndef test_fast_grid_template_updates(page, port):\n tmpl = FastGridTemplate()\n md = Markdown('Initial')\n\n tmpl.main[0:3, 0:3] = md\n\n serve(tmpl, port=port, threaded=True, show=False)\n\n time.sleep(0.2)\n\n page.goto(f\"http://localhost:{port}\", timeout=40_000)\n\n assert page.text_content(\".bk.markdown\") == 'Initial'\n md.object = 'Updated'\n time.sleep(0.1)\n assert page.text_content(\".bk.markdown\") == 'Updated'\n","repo_name":"mbunix/Data-visualization-santander-case","sub_path":"Lib/site-packages/panel/tests/ui/template/test_fastgridtemplate.py","file_name":"test_fastgridtemplate.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"10227187593","text":"from binascii import unhexlify\nfrom unittest import TestCase\n\nimport base58\n\nfrom bitmerchant.network import BitcoinMainNet\nfrom bitmerchant.network import BitcoinTestNet\nfrom bitmerchant.network import DogecoinMainNet\nfrom bitmerchant.network import LitecoinMainNet\nfrom bitmerchant.wallet.keys import ChecksumException\nfrom bitmerchant.wallet.keys import IncompatibleNetworkException\nfrom bitmerchant.wallet.keys import KeyParseError # TODO test this\nfrom bitmerchant.wallet.keys import PrivateKey\nfrom bitmerchant.wallet.keys import PublicKey\nfrom bitmerchant.wallet.utils import ensure_bytes\nfrom bitmerchant.wallet.utils import long_or_int\n\n\nclass _TestPrivateKeyBase(TestCase):\n @classmethod\n def setUpClass(cls):\n # This private key chosen from the bitcoin docs:\n # https://en.bitcoin.it/wiki/Wallet_import_format\n cls.expected_key = \\\n b\"0c28fca386c7a227600b2fe50b7cae11ec86d3bf1fbe471be89827e19d72aa1d\"\n cls.key = PrivateKey(long_or_int(cls.expected_key, 16))\n\n\nclass _TestPublicKeyBase(TestCase):\n @classmethod\n def setUpClass(cls):\n # This private key chosen from the bitcoin docs:\n # https://en.bitcoin.it/wiki/Wallet_import_format\n cls.expected_private_key = \\\n b\"18e14a7b6a307f426a94f8114701e7c8e774e7f9a47e2c2035db29a206321725\"\n cls.private_key = PrivateKey(\n long_or_int(cls.expected_private_key, 16))\n cls.public_key = PublicKey.from_hex_key(\n \"04\"\n \"50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352\"\n \"2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6\")\n\n\nclass TestPrivateKey(_TestPrivateKeyBase):\n def test_raw_key_hex(self):\n exp = self.key._private_key.privkey.secret_multiplier\n self.assertEqual(PrivateKey(exp), self.key)\n\n def test_raw_key_hex_bytes(self):\n key = unhexlify(self.key.get_key())\n self.assertEqual(PrivateKey.from_hex_key(key), self.key)\n\n def test_from_master_password(self):\n password = \"correct horse battery staple\"\n expected_wif = \"5KJvsngHeMpm884wtkJNzQGaCErckhHJBGFsvd3VyK5qMZXj3hS\"\n expected_pub_address = \"1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T\"\n\n key = PrivateKey.from_master_password(password)\n self.assertEqual(key.export_to_wif(), expected_wif)\n self.assertEqual(\n key.get_public_key().to_address(), expected_pub_address)\n\n def test_invalid_exponent(self):\n self.assertRaises(ValueError, PrivateKey, 'abcd')\n\n\nclass TestWIF(_TestPrivateKeyBase):\n @classmethod\n def setUpClass(cls):\n super(TestWIF, cls).setUpClass()\n cls.expected_wif = \\\n '5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ'\n\n def test_export_to_wif(self):\n self.assertEqual(\n self.key.export_to_wif(),\n self.expected_wif)\n\n def test_export_to_wif_compressed(self):\n compressed_wif = self.key.export_to_wif(compressed=True)\n self.assertNotEqual(compressed_wif, self.expected_key)\n\n pk = PrivateKey.from_wif(compressed_wif)\n self.assertEqual(pk, PrivateKey.from_wif(self.expected_wif))\n self.assertEqual(\n pk.export_to_wif(compressed=False), self.expected_wif)\n self.assertEqual(\n pk.export_to_wif(compressed=True), compressed_wif)\n self.assertEqual(pk, self.key)\n\n def test_import_wif(self):\n key = PrivateKey.from_wif(self.expected_wif)\n self.assertEqual(key, self.key)\n\n def test_import_wif_invalid_network(self):\n self.assertRaises(\n IncompatibleNetworkException, PrivateKey.from_wif,\n self.key.export_to_wif(), BitcoinTestNet)\n\n def test_import_wif_network(self):\n # Make a wif for bitcoin testnet:\n testnet_key = PrivateKey(\n self.key._private_key.privkey.secret_multiplier,\n network=BitcoinTestNet)\n testnet_wif = testnet_key.export_to_wif()\n # We should be able to load it properly\n key = PrivateKey.from_wif(testnet_wif, BitcoinTestNet)\n self.assertEqual(testnet_key, key)\n\n def test_bad_checksum(self):\n wif = self.key.export_to_wif()\n bad_checksum = base58.b58encode(\n unhexlify(ensure_bytes('FFFFFFFF')))\n wif = wif[:-8] + bad_checksum\n self.assertRaises(ChecksumException, PrivateKey.from_wif, wif)\n\n\nclass TestPublicKey(_TestPublicKeyBase):\n def test_leading_zeros(self):\n \"\"\"This zero-leading x coordinate generated by:\n\n pvk = '18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725' # nopep8\n from ecdsa import SECP256k1\n from ecdsa.ecdsa import Public_key\n from bitmerchant.wallet.utils import long_to_hex\n\n pubkey = Public_key(\n SECP256k1.generator,\n SECP256k1.generator * long(pvk, 16))\n for i in range(1, 10000):\n p = pubkey.point * i\n x = p.x()\n k = long_to_hex(x, 64)\n if k.startswith('0'):\n print(i)\n print(long_to_hex(p.x(), 64))\n print(long_to_hex(p.y(), 64))\n break\n \"\"\"\n expected_key = ensure_bytes(\n \"04\"\n \"02cbfd5410fd04973c096a4275bf75070955ebd689f316a6fbd449980ba7b756\"\n \"c559764e5c367c03e002751aaf4ef8ec40fe97cda9b2d3f14fdd4cd244e8fcd2\")\n public_key = PublicKey.from_hex_key(expected_key)\n self.assertEqual(public_key.get_key(), expected_key)\n\n def test_address(self):\n expected_address = \"16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM\"\n actual_address = self.public_key.to_address()\n self.assertEqual(expected_address, actual_address)\n\n def test_private_to_public(self):\n self.assertEqual(\n self.private_key.get_public_key(),\n self.public_key)\n\n def test_unhexlified_key(self):\n key_bytes = unhexlify(self.public_key.get_key())\n self.assertEqual(\n PublicKey.from_hex_key(key_bytes),\n self.public_key)\n\n def test_bad_key(self):\n self.assertRaises(KeyParseError, PublicKey.from_hex_key, 'badkey')\n\n def test_bad_network_key(self):\n key = self.public_key.get_key()\n # Change the network constant\n key = b\"00\" + key[2:]\n self.assertRaises(KeyParseError,\n PublicKey.from_hex_key, key)\n\n def test_uncompressed_bad_len(self):\n key = self.public_key.get_key(compressed=False)\n self.assertEqual(len(key), 65*2)\n # Change the network constant\n self.assertRaises(\n KeyParseError, PublicKey.from_hex_key, unhexlify(key[:-2]))\n self.assertRaises(\n KeyParseError, PublicKey.from_hex_key, unhexlify(key + b'00'))\n\n def test_compressed_bad_len(self):\n key = self.public_key.get_key(compressed=True)\n self.assertEqual(len(key), 33*2)\n # Change the network constant\n self.assertRaises(\n KeyParseError, PublicKey.from_hex_key, unhexlify(key[:-2]))\n self.assertRaises(\n KeyParseError, PublicKey.from_hex_key, unhexlify(key + b'00'))\n\n def test_compressed(self):\n compressed_key = self.public_key.get_key(compressed=True)\n self.assertEqual(len(compressed_key), 66)\n self.assertEqual(\n PublicKey.from_hex_key(compressed_key), self.public_key)\n\n def test_point(self):\n self.assertEqual(PublicKey.from_point(self.public_key.to_point()),\n self.public_key)\n\n def test_public_pair(self):\n self.assertEqual(\n PublicKey.from_public_pair(self.public_key.to_public_pair()),\n self.public_key)\n\n\nclass TestVectors(TestCase):\n \"\"\"Test vectors\n from https://github.com/bitcoin/bitcoin/blob/master/src/test/key_tests.cpp\n \"\"\"\n def _test(self, network, secret, address, compressed):\n key = PrivateKey.from_wif(secret, network=network)\n self.assertEqual(key.compressed, compressed)\n self.assertEqual(address, key.get_public_key().to_address())\n\n def test_1(self):\n secret = \"5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj\"\n address = \"1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ\"\n self._test(BitcoinMainNet, secret, address, False)\n\n def test_2(self):\n secret = \"5KC4ejrDjv152FGwP386VD1i2NYc5KkfSMyv1nGy1VGDxGHqVY3\"\n address = \"1F5y5E5FMc5YzdJtB9hLaUe43GDxEKXENJ\"\n self._test(BitcoinMainNet, secret, address, False)\n\n def test_3(self):\n secret = \"Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw\"\n address = \"1NoJrossxPBKfCHuJXT4HadJrXRE9Fxiqs\"\n self._test(BitcoinMainNet, secret, address, True)\n\n def test_4(self):\n secret = \"L3Hq7a8FEQwJkW1M2GNKDW28546Vp5miewcCzSqUD9kCAXrJdS3g\"\n address = \"1CRj2HyM1CXWzHAXLQtiGLyggNT9WQqsDs\"\n self._test(BitcoinMainNet, secret, address, True)\n\n # https://github.com/dogecoin/dogecoin/blob/master-1.5/src/test/key_tests.cpp # nopep8\n def test_dogecoin_1(self):\n secret = \"6JFPe8b4jbpup7petSB98M8tcaqXCigji8fGrC8bEbbDQxQkQ68\"\n address = \"DSpgzjPyfQB6ZzeSbMWpaZiTTxGf2oBCs4\"\n self._test(DogecoinMainNet, secret, address, False)\n\n def test_dogecoin_2(self):\n secret = \"6KLE6U3w8x3rM7nA1ZQxR4KnyEzeirPEt4YaXWdY4roF7Tt96rq\"\n address = \"DR9VqfbWgEHZhNst34KQnABQXpPWXeLAJD\"\n self._test(DogecoinMainNet, secret, address, False)\n\n def test_dogecoin_3(self):\n secret = \"QP8WvtVMV2iU6y7LE27ksRspp4MAJizPWYovx88W71g1nfSdAhkV\"\n address = \"D8jZ6R8uuyQwiybupiVs3eDCedKdZ5bYV3\"\n self._test(DogecoinMainNet, secret, address, True)\n\n def test_dogecoin_4(self):\n secret = \"QTuro8Pwx5yaonvJmU4jbBfwuEmTViyAGNeNyfnG82o7HWJmnrLj\"\n address = \"DP7rGcDbpAvMb1dKup981zNt1heWUuVLP7\"\n self._test(DogecoinMainNet, secret, address, True)\n\n # https://github.com/litecoin-project/litecoin/blob/master-0.8/src/test/key_tests.cpp # nopep8\n def test_litecoin_1(self):\n secret = \"6uu5bsZLA2Lm6yCxgwxDxHyZmhYeqBMLQT83Fyq738YhYucQPQf\"\n address = \"LWaFezDtucfCA4xcVEfs3R3xfgGWjSwcZr\"\n self._test(LitecoinMainNet, secret, address, False)\n\n def test_litecoin_2(self):\n secret = \"6vZDRwYgTNidWzmKs9x8QzQGeWCqbdUtNRpEKZMaP67ZSn8XMjb\"\n address = \"LXwHM6mRd432EzLJYwuKQMPhTzrgr7ur9K\"\n self._test(LitecoinMainNet, secret, address, False)\n\n def test_litecoin_3(self):\n secret = \"T6UsJv9hYpvDfM5noKYkB3vfeHxhyegkeWJ4y7qKeQJuyXMK11XX\"\n address = \"LZWK8h7C166niP6GmpUmiGrvn4oxPqQgFV\"\n self._test(LitecoinMainNet, secret, address, True)\n\n def test_litecoin_4(self):\n secret = \"T9PBs5kq9QrkBPxeGNWKitMi4XuFVr25jaXTnuopLVZxCUAJbixA\"\n address = \"Lgb6tdqmdW3n5E12johSuEAqRMt4kAr7yu\"\n self._test(LitecoinMainNet, secret, address, True)\n","repo_name":"sbuss/bitmerchant","sub_path":"tests/test_keys.py","file_name":"test_keys.py","file_ext":"py","file_size_in_byte":10844,"program_lang":"python","lang":"en","doc_type":"code","stars":78,"dataset":"github-code","pt":"51"} +{"seq_id":"74367892639","text":"from collections import Counter\n\ndef main():\n filename = 'wordlehistory.txt'\n try:\n with open(filename, 'r') as file:\n content = file.read()\n letter_counts = Counter(char.upper for char in content if char.isalpha())\n print(\"Letter Frequencies: \")\n for letter,count in letter_counts.items():\n print(f\"{letter}: {count}\")\n except FileNotFoundError:\n print(f\"The file '{filename}' was not found.\")\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"IAmKatharineC/Wordle","sub_path":"Analysis.py","file_name":"Analysis.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"3910914264","text":"\"\"\"\n SAI testing test bed setup.\n\n Notes:\n This test is used to setup the SAI testing environment,\n and start the SAI test cases\n from the PTF.\n For running this tests,\n please specify the sai test case\n folder via the parameters --sai_test_folder.\n\n\"\"\"\n\nimport pytest\nimport logging\nimport time\nfrom apscheduler.schedulers.background import BackgroundScheduler\n\nfrom .conftest import DUT_WORKING_DIR\nfrom .conftest import USR_BIN_DIR\nfrom .conftest import PORT_MAP_FILE_PATH\nfrom .conftest import PTF_TEST_ROOT_DIR\nfrom .conftest import SAI_TEST_REPORT_DIR_ON_PTF\nfrom .conftest import prepare_sai_test_container\nfrom .conftest import reload_dut_config\nfrom .conftest import revert_sai_test_container\nfrom .conftest import stop_and_rm_sai_test_container\nfrom .conftest import stop_dockers\nfrom .conftest import SAI_TEST_CONMUN_CASE_DIR_ON_PTF\nfrom .conftest import SAI_TEST_PTF_SAI_CASE_DIR_ON_PTF\nfrom .conftest import SAI_TEST_REPORT_TMP_DIR_ON_PTF\nfrom .conftest import SAI_TEST_T0_CASE_DIR_ON_PTF\nfrom .conftest import SAI_TEST_RESOURCE_ON_PTF_DIR\nfrom .conftest import SAI_TEST_INVOCATION_LOG_DIR\nfrom .conftest import WARM_TEST_ARGS\nfrom .conftest import PTF_TEST_CASE_TIMEOUT_IN_SEC\nfrom .conftest import start_sai_test_conatiner_with_retry\nfrom .conftest import get_sai_running_vendor_id\nfrom .conftest import get_sai_test_container_name\nfrom .conftest import saiserver_warmboot_config\nfrom .conftest import * # noqa: F403 F401\n\nlogger = logging.getLogger(__name__)\n\npytestmark = [\n pytest.mark.topology(\"ptf\")\n]\n\n\nSAI_TEST_ENV_RESET_TIMES = 3\nLIVENESS_CHECK_RETRY_TIMES = 12\nLIVENESS_CHECK_INTERVAL_IN_SEC = 5\nCONFIG_RELOAD_INTERVAL_IN_SEC = 30\nTEST_INTERVAL_IN_SEC = 1\n\n\n@pytest.fixture\ndef sai_test_env_check(creds, duthost, ptfhost, request):\n \"\"\"\n Check the sai test environment.\n In this function, it will make a liveness check test to check\n if the sai test container is ready for test.\n This check has three stage:\n 1. If the liveness check test failed, then it will\n make a environment reset.\n 2. If the envvironment reset failed with attempts,\n then the test environment will be marked as failed.\n 3. If environment marked as failed, this check will\n be failed in following round of check.\n\n Args:\n creds (dict): Credentials used to access the docker registry.\n duthost (SonicHost): The target device.\n dut_ip: dut ip address.\n ptfhost (AnsibleHost): The PTF server.\n test_case: Test case name used to make test.\n test_interface_params: Testbed switch interface\n request: Pytest request.\n \"\"\"\n global IS_TEST_ENV_FAILED\n if IS_TEST_ENV_FAILED:\n logger.info(\"Test env check is failed in previous check. \\\n Fails this check directly.\")\n raise Exception(\"SAI Test env error.\")\n check_test_env_with_retry(creds, duthost, ptfhost, request)\n\n\n@pytest.fixture(scope=\"module\")\ndef start_warm_reboot_watcher(duthost, request, ptfhost):\n \"\"\"\n In this function\n 1. First, a file will be created in the ptf container to interact with the ptf test\n 2. Start a watcher daemon\n Args:\n duthost (SonicHost): The target device.\n request: Pytest request.\n ptfhost (AnsibleHost): The PTF server.\n \"\"\"\n # install apscheduler before running\n logger.info(\"create and clean up the shared file with ptf\")\n ptfhost.shell(\"touch {}\".format(\"/tmp/warm_reboot\"))\n ptfhost.shell(\"echo > {}\".format(\"/tmp/warm_reboot\"))\n\n logger.info(\"start warm reboot watcher\")\n close_apschedule_log()\n scheduler = BackgroundScheduler(\n {'apscheduler.job_defaults.max_instances': 1})\n\n scheduler.add_job(warm_reboot_change_handler, \"cron\", [\n duthost, request, ptfhost], second=\"*/1\")\n scheduler.start()\n\n\ndef close_apschedule_log():\n logging.getLogger(\"apscheduler.executors.default\").propagate = False\n logging.getLogger(\"apscheduler.executors.default\").setLevel(logging.ERROR)\n\n\ndef warm_reboot_change_handler(duthost, request, ptfhost):\n '''\n 1. Loop to monitor whether the switch setup of the ptf test is completed\n 2. If setup ends ('rebooting' is obtained from the file)\n i. Stop the saiserver container\n ii. Update the script to start saiserver so that the next startup is a warm reboot,\n using the previous configuration\n iii. Restart saiserver\n iv. Write 'post_reboot_done' in the shared file to notify ptf that warm reboot is done\n '''\n result = ptfhost.shell(\"cat {}\".format(\"/tmp/warm_reboot\"))\n if result[\"stdout_lines\"] and result[\"stdout_lines\"][0] == 'rebooting':\n duthost.shell(USR_BIN_DIR + \"/saiserver.sh\" + \" stop\")\n saiserver_warmboot_config(duthost, \"start\")\n result = ptfhost.shell(\n \"echo rebooting_done > {}\".format(\"/tmp/warm_reboot\"))\n\n start_sai_test_conatiner_with_retry(\n duthost, get_sai_test_container_name(request))\n logger.info(\"saiserver start warm reboot\")\n result = ptfhost.shell(\n \"echo post_reboot_done > {}\".format(\"/tmp/warm_reboot\"))\n\n\n@pytest.fixture(scope=\"module\")\ndef sai_testbed(duthost,\n request,\n ptfhost,\n start_sai_test_container,\n prepare_ptf_server):\n \"\"\"\n Pytest fixture to handle setup and cleanup for the SAI tests.\n\n Args:\n duthost (SonicHost): The target device.\n request: Pytest request.\n ptfhost (AnsibleHost): The PTF server.\n start_sai_test_container: fixture to start the sai test container.\n prepare_ptf_server: fixture to prepare the ptf server.\n \"\"\"\n try:\n if not request.config.option.sai_test_skip_setup_env:\n dut_ip = duthost.host.options['inventory_manager'].get_host(\n duthost.hostname).vars['ansible_host']\n ptfhost.shell(\n \"echo \\\"export PLATFORM={}\\\" >> ~/.bashrc\".format(\n get_sai_running_vendor_id(duthost)))\n ptfhost.shell(\n \"echo \\\"export DUTIP={}\\\" >> ~/.bashrc\".format(dut_ip))\n prepare_test_cases(ptfhost, request)\n yield\n finally:\n # ptfhost.shell(\n # \"sed -i \\'/export PLATFORM={}/d\\' \\\n # ~/.bashrc\".format(get_sai_running_vendor_id(duthost)))\n store_test_result(ptfhost)\n if not request.config.option.sai_test_keep_test_env:\n teardown_dut(duthost, ptfhost, request)\n\n\ndef check_test_env_with_retry(creds, duthost, ptfhost, request):\n \"\"\"\n Args:\n creds (dict): Credentials used to access the docker registry.\n duthost (SonicHost): The target device.\n ptfhost (AnsibleHost): The PTF server.\n request: Pytest request.\n \"\"\"\n global IS_TEST_ENV_FAILED\n for retry in range(SAI_TEST_ENV_RESET_TIMES):\n try:\n start_sai_test_conatiner_with_retry(\n duthost, get_sai_test_container_name(request))\n break\n except BaseException as e:\n logger.info(\n \"Run test env check failed, reset the env, \\\n retry: [{}/{}], failed as {}.\".format(\n retry + 1, SAI_TEST_ENV_RESET_TIMES, e))\n if retry + 1 < SAI_TEST_ENV_RESET_TIMES:\n reset_sai_test_dut(duthost, creds, request)\n logger.info(\"Liveness check waiting {} \\\n sec for another retry.\".format(\n LIVENESS_CHECK_INTERVAL_IN_SEC))\n time.sleep(LIVENESS_CHECK_INTERVAL_IN_SEC)\n else:\n logger.info(\"Run test env check failed. \\\n Run test env is not ready. Error: {}\".format(e))\n IS_TEST_ENV_FAILED = True\n raise e\n\n\ndef run_case_from_ptf(duthost,\n dut_ip,\n ptfhost,\n test_case,\n test_interface_params,\n request,\n warm_boot_stage=None):\n \"\"\"\n Run the sai test cases from ptf.\n\n Args:\n duthost (SonicHost): The target device.\n dut_ip: dut ip address.\n ptfhost (AnsibleHost): The PTF server.\n test_case: Test case name used to make test.\n test_interface_params: Testbed switch interface\n request: Pytest request.\n warm_boot_stage: support warm reboot in three stage,\n WARM_TEST_STAGES, WARM_TEST_STARTING, WARM_TEST_POST\n \"\"\"\n logger.info(\"Running test: {0}\".format(test_case))\n logger.info(\"Sleep {} sec between tests.\".format(TEST_INTERVAL_IN_SEC))\n time.sleep(TEST_INTERVAL_IN_SEC)\n test_param = ''\n\n if request.config.option.enable_sai_test \\\n or request.config.option.enable_ptf_sai_test \\\n or request.config.option.enable_ptf_warmboot_test \\\n or request.config.option.enable_t0_warmboot_test:\n test_param = compose_sai_ptfv2_running_param(dut_ip, request)\n else: # for old community test\n test_param = compose_community_running_param(dut_ip, request)\n logger.info(\"Test case param: [{}].\".format(test_param))\n ptfhost.shell((\"ptf {} {} --relax --xunit --test-case-timeout={} \\\n --xunit-dir {} {}\").format(test_case,\n test_interface_params,\n PTF_TEST_CASE_TIMEOUT_IN_SEC,\n SAI_TEST_REPORT_TMP_DIR_ON_PTF,\n test_param))\n logger.info(\"Test case [{}] passed.\".format(test_case))\n\n\ndef compose_sai_ptfv2_running_param(dut_ip, request):\n \"\"\"\n Run the sai test cases from ptf.\n\n Args:\n dut_ip: dut ip address.\n request: Pytest request.\n \"\"\"\n test_param = ''\n test_set = ''\n warm_param = ''\n if request.config.option.enable_sai_test \\\n or request.config.option.enable_t0_warmboot_test:\n test_set = SAI_TEST_T0_CASE_DIR_ON_PTF\n elif request.config.option.enable_ptf_sai_test \\\n or request.config.option.enable_ptf_warmboot_test: # noqa: E125\n test_set = SAI_TEST_PTF_SAI_CASE_DIR_ON_PTF\n else:\n raise Exception(\"Unknown Test set.\")\n\n if request.config.option.enable_t0_warmboot_test \\\n or request.config.option.enable_ptf_warmboot_test:\n warm_param = WARM_TEST_ARGS\n\n port_config_file = SAI_TEST_RESOURCE_ON_PTF_DIR + '/port_config.ini'\n config_db_file = SAI_TEST_RESOURCE_ON_PTF_DIR + '/config_db.json'\n if request.config.option.sai_port_config_file:\n port_config_file = request.config.option.sai_port_config_file\n if request.config.option.sai_config_db_file:\n config_db_file = request.config.option.sai_config_db_file\n\n test_param = \"--test-dir {}\".format(test_set)\n if request.config.option.sai_port_config_file:\n test_param += \" \\\"--test-params=thrift_server='{}';\\\n port_config_ini='{}';config_db_json='{}';{}\\\"\".format(\n dut_ip,\n port_config_file,\n config_db_file,\n warm_param)\n else:\n test_param += \" \\\"--test-params=thrift_server='{}';\\\n config_db_json='{}';{}\\\"\".format(\n dut_ip,\n config_db_file,\n warm_param)\n return test_param\n\n\ndef compose_community_running_param(dut_ip, request):\n \"\"\"\n Run the community sai test cases from ptf.\n\n Args:\n dut_ip: dut ip address.\n request: Pytest request.\n \"\"\"\n test_param = \"--test-dir {} -t \\\"server='{}';port_map_file='{}'\\\"\".format(\n SAI_TEST_CONMUN_CASE_DIR_ON_PTF,\n dut_ip,\n PORT_MAP_FILE_PATH)\n return test_param\n\n\ndef reset_sai_test_dut(duthost, creds, request):\n \"\"\"\n Resets the sai test environment.\n This function will remove all the sai test container, reload config,\n re_deploy sai test container and start them.\n\n Args:\n duthost (SonicHost): The target device.\n creds (dict): Credentials used to access the docker registry.\n request: Pytest request.\n \"\"\"\n logger.info(\"Start to reset dut environment to default.\")\n stop_and_rm_sai_test_container(\n duthost, get_sai_test_container_name(request))\n revert_sai_test_container(\n duthost, creds,\n get_sai_test_container_name(request), request)\n reload_dut_config(duthost)\n logger.info(\"Resetting Dut env, \\\n waiting {} sec for env gets \\\n ready ...\".format(CONFIG_RELOAD_INTERVAL_IN_SEC))\n time.sleep(CONFIG_RELOAD_INTERVAL_IN_SEC)\n stop_dockers(duthost)\n prepare_sai_test_container(\n duthost, creds, get_sai_test_container_name(request), request)\n start_sai_test_conatiner_with_retry(\n duthost, get_sai_test_container_name(request))\n\n\ndef sai_test_container_liveness_check(duthost,\n ptfhost,\n test_case,\n request,\n sai_test_interface_para):\n \"\"\"\n Run a liveness check.\n This function will run a simple test to check\n if the sai test container is ready.\n\n Args:\n duthost (SonicHost): The target device.\n ptfhost (AnsibleHost): The PTF server.\n test_case: Test case name used to make the liveness check.\n request: Pytest request.\n sai_test_interface_para: Testbed switch interface\n \"\"\"\n logger.info(\"Checking test environment before running test.\")\n dut_ip = duthost.host.options['inventory_manager'].get_host(\n duthost.hostname).vars['ansible_host']\n start_sai_test_conatiner_with_retry(\n duthost, get_sai_test_container_name(request))\n for retry in range(LIVENESS_CHECK_RETRY_TIMES):\n try:\n run_case_from_ptf(\n duthost, dut_ip,\n ptfhost, test_case,\n sai_test_interface_para, request)\n break\n except BaseException as e:\n logger.info(\"Run liveness check [{}], \\\n retry: [{}/{}] failed as {}\".format(\n test_case, retry + 1, LIVENESS_CHECK_RETRY_TIMES, e))\n if retry + 1 < LIVENESS_CHECK_RETRY_TIMES:\n logger.info(\n \"Liveness check waiting {} sec for another retry.\".format(\n LIVENESS_CHECK_INTERVAL_IN_SEC))\n time.sleep(LIVENESS_CHECK_INTERVAL_IN_SEC)\n else:\n logger.info(\n \"Liveness check failed. \\\n TestBed is not ready. Error: {}\".format(e))\n raise e\n\n\ndef teardown_dut(duthost, ptfhost, request):\n \"\"\"\n Tears down the SAI test.\n\n Args:\n duthost (SonicHost): The target device.\n ptfhost (AnsibleHost): The PTF server.\n request: Pytest request.\n \"\"\"\n logger.info(\"Teardown SAI tests.\")\n collect_test_result(duthost, ptfhost, request)\n cleanup_ptf(ptfhost, request)\n\n\ndef cleanup_ptf(ptfhost, request):\n \"\"\"\n Cleanup PTF server, including delete test cases and root test folder.\n\n Args:\n ptfhost (AnsibleHost): The PTF server.\n request: Pytest request.\n \"\"\"\n delete_sai_test_cases(ptfhost, request)\n delete_sai_test_folder(ptfhost)\n\n\ndef delete_sai_test_cases(ptfhost, request):\n \"\"\"\n Delete SAI test cases on PTF.\n\n Args:\n ptfhost (AnsibleHost): The PTF server.\n request: Pytest request.\n \"\"\"\n logger.info(\"Delete SAI tests cases\")\n if request.config.option.enable_ptf_sai_test \\\n or request.config.option.enable_ptf_warmboot_test:\n ptfhost.file(path=\"{0}\".format(\n SAI_TEST_PTF_SAI_CASE_DIR_ON_PTF), state=\"absent\")\n if request.config.option.enable_sai_test \\\n or request.config.option.enable_t0_warmboot_test:\n ptfhost.file(path=\"{0}\".format(\n SAI_TEST_T0_CASE_DIR_ON_PTF), state=\"absent\")\n else:\n ptfhost.file(path=\"{0}\".format(\n SAI_TEST_CONMUN_CASE_DIR_ON_PTF), state=\"absent\")\n\n\ndef delete_sai_test_folder(ptfhost):\n \"\"\"\n Delete SAI test root folder on PTF.\n\n Args:\n ptfhost (AnsibleHost): The PTF server.\n \"\"\"\n logger.info(\"Delete SAI tests root folder: {0}.\".format(PTF_TEST_ROOT_DIR))\n ptfhost.file(path=PTF_TEST_ROOT_DIR, state=\"absent\")\n\n\ndef prepare_test_cases(ptfhost, request):\n \"\"\"\n Prepare SAI test env including create root test folder and copy cases.\n\n Args:\n ptfhost (AnsibleHost): The PTF server.\n request: Pytest request.\n \"\"\"\n logger.info(\"Preparing SAI test environment.\")\n create_sai_test_folders(ptfhost)\n copy_sai_test_cases(ptfhost, request)\n\n\ndef create_sai_test_folders(ptfhost):\n \"\"\"\n Create SAI test root folder on PTF server.\n\n Args:\n ptfhost (AnsibleHost): The PTF server.\n \"\"\"\n logger.info(\n \"Creating SAI tests root folder: {0}.\".format(\n PTF_TEST_ROOT_DIR))\n ptfhost.shell(\n \"mkdir -p {0}\".format(PTF_TEST_ROOT_DIR))\n logger.info(\n \"Creating SAI tests report folder: {0}.\".format(\n SAI_TEST_REPORT_DIR_ON_PTF))\n ptfhost.shell(\"mkdir -p {0}\".format(SAI_TEST_REPORT_DIR_ON_PTF))\n\n\ndef copy_sai_test_cases(ptfhost, request):\n \"\"\"\n Copy SAI test cases to PTF server.\n\n Args:\n ptfhost (AnsibleHost): The PTF server.\n request: Pytest request.\n \"\"\"\n if request.config.option.sai_test_dir:\n logger.info(\"Copying SAI test cases to PTF server.\")\n ptfhost.copy(\n src=request.config.option.sai_test_dir,\n dest=PTF_TEST_ROOT_DIR + \"/\")\n else:\n logger.info(\"Skip Copying SAI test cases to PTF server.\")\n\n\ndef collect_test_result(duthost, ptfhost, request):\n \"\"\"\n Collect SAI test resport from DUT and PTF server.\n\n Args:\n duthost (SonicHost): The DUT.\n ptfhost (AnsibleHost): The PTF server.\n request: Pytest request.\n \"\"\"\n logger.info(\"Collecting test result and related information.\")\n # TODO : collect DUT test report\n collect_sonic_os_and_platform_info(duthost, request)\n collect_sai_test_report_xml(ptfhost, request)\n collect_sai_test_invocation_report(ptfhost, request)\n\n\ndef collect_sonic_os_and_platform_info(duthost, request):\n \"\"\"\n Collect SONiC OS and Testbed info.\n\n Args:\n duthost (SonicHost): The DUT.\n request: Pytest request.\n \"\"\"\n logger.info(\"Getting SONiC OS version and Testbed platform info.\")\n\n out = duthost.shell(\"cd {0} && show version\".format(DUT_WORKING_DIR))\n parse_info(out['stdout'], request.config.option.sai_test_report_dir)\n\n\ndef parse_info(content, report_path):\n \"\"\"\n Parse the Version and platform info.\n Then output to the pipeline console as pipeline variable.\n\n Args:\n content: Ado pipeline stand output.\n report_path: sai test report dir.\n \"\"\"\n OS_VERSION = \"\"\n PLT_VERSION = \"\"\n\n with open(report_path + \"/version.txt\", 'w+') as f:\n f.writelines(content)\n\n with open(report_path + \"/version.txt\", 'r') as f:\n cc = f.readlines()\n\n for line in cc:\n if \"SONiC Software Version\" in line:\n OS_VERSION = line.split(\":\")[1].strip()\n if \"Platform\" in line:\n PLT_VERSION = line.split(\":\")[1].strip()\n\n # TODO: Getting info should not depend on AZP,\n # later this logging command will be removed\n logger.info(\n 'Get SONiC version: {0}, Platform: {1}'.format(\n OS_VERSION, PLT_VERSION))\n logger.info(\n '##vso[task.setvariable variable=OS_VERSION]{}'.format(\n OS_VERSION))\n logger.info(\n '##vso[task.setvariable variable=PLT_VERSION]{}'.format(\n PLT_VERSION))\n\n\ndef store_test_result(ptfhost):\n \"\"\"\n Backup the test result\n\n Args:\n ptfhost (AnsibleHost): The PTF server.\n \"\"\"\n logger.info(\n \"Copying file from folder: {0} to folder: {1}\".format(\n SAI_TEST_REPORT_TMP_DIR_ON_PTF,\n SAI_TEST_REPORT_DIR_ON_PTF))\n try:\n logger.info(\"Copy test reports\")\n ptfhost.shell(\"mkdir -p {}\".format(\n SAI_TEST_REPORT_TMP_DIR_ON_PTF))\n ptfhost.shell(\"mkdir -p {}\".format(\n SAI_TEST_REPORT_DIR_ON_PTF))\n ptfhost.shell(\"cp {0}/*.* {1}/\".format(\n SAI_TEST_REPORT_TMP_DIR_ON_PTF,\n SAI_TEST_REPORT_DIR_ON_PTF))\n\n except BaseException as e: # lgtm [py/catch-base-exception]\n logger.info(\n \"Error when restoring test result: {}.\".format(e))\n\n\ndef collect_sai_test_report_xml(ptfhost, request):\n \"\"\"\n Collect SAI test report.\n\n Args:\n ptfhost (AnsibleHost): The PTF server.\n request: Pytest request.\n \"\"\"\n logger.info(\"Collecting xunit SAI tests log from ptf\")\n try:\n ptfhost.shell(\n \"cd {0} && tar -czvf result.tar.gz *\".format(\n SAI_TEST_REPORT_DIR_ON_PTF))\n ptfhost.fetch(\n src=\"{0}/result.tar.gz\".format(SAI_TEST_REPORT_DIR_ON_PTF),\n dest=request.config.option.sai_test_report_dir + \"/\",\n flat=True)\n except BaseException as e: # lgtm [py/catch-base-exception]\n logger.info(\"Error when Collecting xunit SAI tests log from ptf.\\\n Failes as {0}\".format(e))\n\n\ndef collect_sai_test_invocation_report(ptfhost, request):\n \"\"\"\n Collect SAI test invocation report.\n\n Args:\n ptfhost (AnsibleHost): The PTF server.\n request: Pytest request.\n \"\"\"\n logger.info(\"Collecting invocation log from ptf\")\n try:\n\n logger.info(\"Copy test invocation logs\")\n ptfhost.shell(\"mkdir -p {}\".format(\n SAI_TEST_INVOCATION_LOG_DIR))\n if request.config.option.enable_sai_test \\\n or request.config.option.enable_t0_warmboot_test:\n logger.info(\"Copy test T0 invocation logs\")\n ptfhost.shell(\"mkdir -p {}/{}\".format(\n SAI_TEST_INVOCATION_LOG_DIR, \"T0\"))\n ptfhost.shell(\"cp {}/logs/*.* {}/{}/\".format(\n SAI_TEST_T0_CASE_DIR_ON_PTF,\n SAI_TEST_INVOCATION_LOG_DIR,\n \"T0\"))\n elif request.config.option.enable_ptf_sai_test \\\n or request.config.option.enable_ptf_warmboot_test:\n logger.info(\"Copy test PTF invocation logs\")\n ptfhost.shell(\"mkdir -p {}/{}\".format(\n SAI_TEST_INVOCATION_LOG_DIR, \"PTF\"))\n ptfhost.shell(\"cp {}/logs/*.* {}/{}/\".format(\n SAI_TEST_PTF_SAI_CASE_DIR_ON_PTF,\n SAI_TEST_INVOCATION_LOG_DIR,\n \"PTF\"))\n\n ptfhost.shell(\n \"cd {0} && tar -czvf invocation.tar.gz *\".format(\n SAI_TEST_INVOCATION_LOG_DIR))\n ptfhost.fetch(\n src=\"{0}/invocation.tar.gz\".format(SAI_TEST_INVOCATION_LOG_DIR),\n dest=request.config.option.sai_test_report_dir + \"/\",\n flat=True)\n except BaseException as e: # lgtm [py/catch-base-exception]\n logger.info(\"Error when Collecting xunit SAI tests log from ptf.\\\n Failes as {0}\".format(e))\n","repo_name":"sonic-net/sonic-mgmt","sub_path":"tests/sai_qualify/sai_infra.py","file_name":"sai_infra.py","file_ext":"py","file_size_in_byte":23064,"program_lang":"python","lang":"en","doc_type":"code","stars":161,"dataset":"github-code","pt":"51"} +{"seq_id":"40310504044","text":"from noc.services.discovery.jobs.base import DiscoveryCheck\nfrom noc.inv.models.vendor import Vendor\nfrom noc.inv.models.platform import Platform\nfrom noc.inv.models.firmware import Firmware\nfrom noc.inv.models.firmwarepolicy import FirmwarePolicy, FS_DENIED\nfrom noc.core.wf.diagnostic import SNMPTRAP_DIAG, SYSLOG_DIAG\n\n\nclass VersionCheck(DiscoveryCheck):\n \"\"\"\n Version discovery\n \"\"\"\n\n name = \"version\"\n required_script = \"get_version\"\n\n def handler(self):\n self.logger.info(\"Checking version\")\n result = self.object.scripts.get_version()\n changed = False\n # Sync vendor\n vendor = Vendor.ensure_vendor(result[\"vendor\"])\n if not self.object.vendor or vendor.id != self.object.vendor.id:\n if self.object.vendor:\n self.logger.info(\"Vendor changed: %s -> %s\", self.object.vendor.name, vendor.name)\n else:\n self.logger.info(\"Set vendor: %s\", vendor.name)\n self.object.vendor = vendor\n changed = True\n # Sync platform\n strict_platform = self.object.object_profile.new_platform_creation_policy != \"C\"\n platform = Platform.ensure_platform(vendor, result[\"platform\"], strict=strict_platform)\n if strict_platform and platform is None:\n # Denied to create platform, stop\n if self.object.object_profile.new_platform_creation_policy == \"A\":\n self.set_problem(\n alarm_class=\"NOC | Managed Object | New Platform\",\n message=f'New platform ({vendor}: {result[\"platform\"]}) creation is denied by policy',\n fatal=True,\n )\n else:\n self.job.set_fatal_error()\n return\n if not self.object.platform or platform.id != self.object.platform.id:\n if self.object.platform:\n self.logger.info(\n \"Platform changed: %s -> %s\", self.object.platform.name, platform.name\n )\n else:\n self.logger.info(\"Set platform: %s\", platform.name)\n self.object.platform = platform\n changed = True\n # Platform changed, clear links\n if self.object.object_profile.clear_links_on_platform_change:\n self.clear_links()\n # Invalidate neighbor cache\n self.invalidate_neighbor_cache()\n # Reset diagnostics\n self.object.diagnostic.reset_diagnostics([SNMPTRAP_DIAG, SYSLOG_DIAG])\n # Sync version\n version = Firmware.ensure_firmware(self.object.profile, vendor, result[\"version\"])\n if not self.object.version or version.id != self.object.version.id:\n if self.object.version:\n self.logger.info(\n \"Version changed: %s -> %s\", self.object.version.version, version.version\n )\n else:\n self.logger.info(\"Set version: %s\", version.version)\n self.object.event(\n self.object.EV_VERSION_CHANGED,\n {\"current\": str(version), \"prev\": str(self.object.version or \"\")},\n )\n self.object.version = version\n changed = True\n # @todo: Check next_version and report upgrade\n # Sync image\n image = result.get(\"image\", \"\") or None\n if image != self.object.software_image:\n if image:\n image = image.strip()[:255] # Cut to field length\n if not image:\n image = None\n if self.object.version:\n self.logger.info(\"Image changed: %s -> %s\", self.object.software_image, image)\n else:\n self.logger.info(\"Set image: %s\", image)\n self.object.software_image = image\n changed = True\n # Sync attributes\n if \"attributes\" in result:\n self.object.update_attributes(result[\"attributes\"])\n self.set_artefact(\"object_attributes\", result[\"attributes\"])\n else:\n # Clear capabilities by attributes\n self.set_artefact(\"object_attributes\", {})\n #\n if changed:\n self.object.save()\n #\n dfp = self.object.get_denied_firmware_policy()\n if dfp != \"I\":\n firmware_status = FirmwarePolicy.get_status(version, platform)\n if firmware_status == FS_DENIED:\n self.logger.info(\"Firmware version is denied by policy\")\n if dfp in (\"A\", \"S\"):\n self.set_problem(\n alarm_class=\"NOC | Managed Object | Denied Firmware\",\n message=\"Firmware version is denied to use by policy\",\n fatal=dfp == \"S\",\n )\n elif dfp == \"s\":\n self.job.set_fatal_error()\n if dfp in (\"s\", \"S\"):\n self.logger.error(\"Further box discovery is stopped by policy\")\n","repo_name":"nocproject/noc","sub_path":"services/discovery/jobs/box/version.py","file_name":"version.py","file_ext":"py","file_size_in_byte":4986,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"51"} +{"seq_id":"74689031518","text":"import requests \r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\nresponse = requests.get('https://thehackernews.com/').text\r\nsoup = BeautifulSoup(response, features= ('html.parser'))\r\nheadlines = []\r\nsummary = []\r\n\r\nheaders = soup.find_all('div', attrs={'class':'clear home-right'})\r\nfor header in headers:\r\n headlines.append(header.h2.text)\r\nsummaries = soup.find_all('div', attrs={'class':'home-desc'})\r\nfor summari in summaries:\r\n summary.append(summari.text)\r\n\r\ncsv = {\r\n 'headlines': headlines,\r\n 'summary': summary\r\n}\r\n\r\nimport pandas as pd\r\ndata = pd.DataFrame(csv)\r\nprint(data)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"ioenimil/MINI_PROJECTS","sub_path":"the_hacker_news_scraper.py","file_name":"the_hacker_news_scraper.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"74276383198","text":"\"\"\" Sum mark \"\"\"\ndef poisk_third_krit(first_krit, second_krit):\n return first_krit + second_krit\n\"\"\" Dividing line \"\"\"\ndef line_stolb(simvol):\n return simvol*64\ndef line_stolb_1(simvol_1):\n return simvol_1*44\n\nfile_in = open(\"spisok.txt\", 'r')\nline = file_in.read().splitlines()\nline_1 = line[0]\nline_2 = line[1]\nline_3 = line[2]\nline_4 = line[3]\nline_5 = line[4]\nfile_in.close()\n\nimport ru_local\n\nfirst_krit = int(input(ru_local.SEMESTR))\nsecond_krit = int(input(ru_local.EXZAMEN))\nthird_krit = poisk_third_krit(first_krit,second_krit)\nresalt = third_krit\n\nif third_krit >= 100:\n resalt = ru_local.YES\nelse:\n resalt = ru_local.NO\n\n\nfirst_krit_1 = int(input(ru_local.SEMESTR))\nsecond_krit_1 = int(input(ru_local.EXZAMEN))\nthird_krit_1 = poisk_third_krit(first_krit_1, second_krit_1)\nresalt_1 = third_krit_1\n\nif third_krit_1 >= 100:\n resalt_1 = ru_local.YES\nelse:\n resalt_1 = ru_local.NO\n\nfirst_krit_2 = int(input(ru_local.SEMESTR))\nsecond_krit_2 = int(input(ru_local.EXZAMEN))\nthird_krit_2 = poisk_third_krit(first_krit_2, second_krit_2)\nresalt_2 = third_krit_2\n\nif third_krit_2 >= 100:\n resalt_2 = ru_local.YES\nelse:\n resalt_2 = ru_local.NO\n\nfirst_krit_3 = int(input(ru_local.SEMESTR))\nsecond_krit_3 = int(input(ru_local.EXZAMEN))\nthird_krit_3 = poisk_third_krit(first_krit_3, second_krit_3)\nresalt_3 = third_krit_3\n\nif third_krit_3 >= 100:\n resalt_3 = ru_local.YES\nelse:\n resalt_3 = ru_local.NO\n\nfirst_krit_4 = int(input(ru_local.SEMESTR))\nsecond_krit_4 = int(input(ru_local.EXZAMEN))\nthird_krit_4 = poisk_third_krit(first_krit_4, second_krit_4)\nresalt_4 = third_krit_4\n\nif third_krit_4 >= 100:\n resalt_4 = ru_local.YES\nelse:\n resalt_4 = ru_local.NO\n\nfirst_krit_5 = int(input(ru_local.SEMESTR))\nsecond_krit_5 = int(input(ru_local.EXZAMEN))\nthird_krit_5 = poisk_third_krit(first_krit_5, second_krit_5)\nresalt_5 = third_krit_5\n\nif third_krit_5 >= 100:\n resalt_5 = ru_local.YES\nelse:\n resalt_5 = ru_local.NO\n\nprint(line_stolb(\"-\"))\nprint('| {:^20} | {:^7} | {:^7} | {:^7} | {:^7} |'.format(ru_local.NAME, ru_local.ONE,\n ru_local.TWO,\n ru_local.THREE, ru_local.FORE))\n\nprint(line_stolb(\"|\"))\nprint('| {:^20} | {:^7} | {:^7} | {:^7} | {:^7} |'.format(line_1, first_krit,\n second_krit, third_krit,\n resalt))\nprint(line_stolb(\"|\"))\nprint('| {:^20} | {:^7} | {:^7} | {:^7} | {:^7} |'.format(line_2, first_krit_1,\n second_krit_1, third_krit_1,\n resalt_1))\nprint(line_stolb(\"|\"))\nprint('| {:^20} | {:^7} | {:^7} | {:^7} | {:^7} |'.format(line_3, first_krit_2,\n second_krit_2, third_krit_2,\n resalt_2))\nprint(line_stolb(\"|\"))\nprint('| {:^20} | {:^7} | {:^7} | {:^7} | {:^7} |'.format(line_4, first_krit_3,\n second_krit_1, third_krit_3,\n resalt_3))\nprint(line_stolb(\"|\"))\nprint('| {:^20} | {:^7} | {:^7} | {:^7} | {:^7} |'.format(line_5, first_krit_4,\n second_krit_4, third_krit_4,\n resalt_4))\nprint(line_stolb(\"-\"))\nprint()\nprint(line_stolb_1(\"-\"))\nprint('{:^20} | {:^20}'.format(ru_local.SPISOK_1,ru_local.SPISOK_2))\nprint(line_stolb_1(\"-\"))\nif resalt == ru_local.YES:\n print('{:^20} | {:^20}'.format(line_1,'--'))\nelse:\n print ('{:^20} | {:^20}'.format ('--', line_1))\n\nif resalt_1 == ru_local.YES:\n print('{:^20} | {:^20}'.format(line_2,'--'))\nelse:\n print ('{:^20} | {:^20}'.format ('--', line_2))\n\nif resalt_2 == ru_local.YES:\n print ('{:^20} | {:^20}'.format (line_3, '--'))\nelse:\n print ('{:^20} | {:^20}'.format ('--', line_3))\n\nif resalt_3 == ru_local.YES:\n print ('{:^20} | {:^20}'.format (line_4, '--'))\nelse:\n print ('{:^20} | {:^20}'.format ('--', line_4))\n\nif resalt_4 == ru_local.YES:\n print('{:^20} | {:^20}'.format(line_5,'--'))\nelse:\n print ('{:^20} | {:^20}'.format ('--', line_5))\n\nprint (line_stolb_1(\"-\"))\n","repo_name":"KseniaZikova/Project_06","sub_path":"workout.py","file_name":"workout.py","file_ext":"py","file_size_in_byte":4364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"39293030330","text":"import unittest\nfrom statistics_service import StatisticsService\nfrom player import Player\n\n\nclass PlayerReaderStub:\n def get_players(self):\n return [\n Player(\"Niinimaa\", \"PHI\", 1, 2),\n Player(\"Nummelin\", \"WPG\", 6, 25),\n Player(\"Rantanen\", \"COL\", 35, 45),\n Player(\"Aho\", \"CAR\", 30, 60),\n Player(\"Selänne\", \"WPG\", 76, 23)\n ]\n\n\nclass TestStatisticsService(unittest.TestCase):\n def setUp(self):\n self.stats = StatisticsService(PlayerReaderStub())\n\n def test_search_with_valid_player_returns_correct_player(self):\n search_result = self.stats.search(\"Selänne\")\n player = Player(\"Selänne\", \"WPG\", 76, 23)\n # Added __eq__ to player class for easy comparison\n self.assertTrue(search_result, player)\n\n def test_seach_with_unkown_player_returns_none(self):\n self.assertIsNone(self.stats.search(\"Kurri\"))\n\n def test_team_returns_all_team_players(self):\n players = self.stats.team(\"WPG\")\n correct_players = [Player(\"Nummelin\", \"WPG\", 6, 25), Player(\n \"Selänne\", \"WPG\", 76, 23)]\n self.assertEqual(players, correct_players)\n\n def test_top_players_returned_correctly(self):\n top_scorers = self.stats.top(4)\n playerstub_top_scorers = [\n Player(\"Selänne\", \"WPG\", 76, 23),\n Player(\"Aho\", \"CAR\", 30, 60),\n Player(\"Rantanen\", \"COL\", 35, 45),\n Player(\"Nummelin\", \"WPG\", 6, 25),\n Player(\"Niinimaa\", \"PHI\", 1, 2)]\n self.assertEqual(top_scorers, playerstub_top_scorers)\n","repo_name":"eepek/palautusrepositorio","sub_path":"viikko1/nhl-statistics-1/src/tests/statisctics_service_test.py","file_name":"statisctics_service_test.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"23896791159","text":"import cv2\nimport os\nimport numpy as np\nimport face_recognition as fr\nimport random\nfrom datetime import datetime\nfrom PyQt5.QtCore import Qt, QFile, QTextStream\nfrom PyQt5.QtGui import QPixmap, QFont\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLabel, QInputDialog, QPushButton, QHBoxLayout, QVBoxLayout, QDialog, QMainWindow, QTableWidget, QTableWidgetItem\n\n\nclass MainWindow(QWidget):\n def __init__(self):\n super().__init__()\n \n self.setWindowTitle(\"Sistema de Gestión de Asistencias\")\n self.setFixedSize(500, 300)\n font = QFont()\n font.setPointSize(12) # set font size\n font.setBold(True) \n\n # Create UI elements\n self.label = QLabel(\"Bienvenido al Sistema de Gestión de Asistencias\")\n self.label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)\n self.label.setFont(font)\n\n # Add image to the UI\n self.image_label = QLabel(self)\n pixmap = QPixmap('resources/logo.png')\n self.image_label.setPixmap(pixmap)\n self.image_label.setAlignment(Qt.AlignCenter)\n \n self.register_button = QPushButton(\"Registrar nuevo estudiante\")\n self.register_button.clicked.connect(self.register_student)\n\n self.attendance_button = QPushButton(\"Registrar Asistencia\")\n self.attendance_button.clicked.connect(self.register_attendance)\n\n self.close_button = QPushButton(\"Salir\")\n self.close_button.clicked.connect(self.close)\n\n # Layout\n vbox = QVBoxLayout()\n vbox.addWidget(self.label)\n vbox.addWidget(self.image_label)\n vbox.addStretch(1)\n vbox.addWidget(self.register_button)\n vbox.addWidget(self.attendance_button)\n vbox.addWidget(self.close_button)\n\n hbox = QHBoxLayout()\n hbox.addStretch(1)\n hbox.addLayout(vbox)\n hbox.addStretch(1)\n\n self.setLayout(hbox)\n\n def register_student(self):\n # Show TextInput and accept button\n name, ok = QInputDialog.getText(self, \"Nuevo\", \"Ingrese el nombre del estudiante:\")\n if ok and name:\n route = \".\\\\images\\\\{}.jpg\".format(name)\n cap = cv2.VideoCapture(0)\n #Setting the dimensions of photos taken by the camera\n cap.set(cv2.CAP_PROP_FRAME_WIDTH, 720)\n cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)\n print(\"Nuevo estudiante registrado correctamente! Bienvenido \", name)\n image_saved = False\n try: \n while True:\n ret, frame = cap.read()\n frame_copy = frame.copy() # create a copy of the original frame\n cv2.putText(frame_copy, \"Presione 'a' para guardar la imagen o 'q' para salir\", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 0, 255), 1, cv2.LINE_AA)\n cv2.imshow(\"Registrar Estudiante\", frame_copy)\n if not ret:\n break\n key = cv2.waitKey(1)\n if (key & 0xFF == ord('q')) or (key % 256 == 97):\n if key % 256 == 97:\n #Saving the image {frame} in the created route\n cv2.imwrite(route, frame)\n break\n cap.release()\n cv2.destroyAllWindows()\n except:\n print(\"Ocurrio un error al capturar la imagen.\")\n cap.release()\n cv2.destroyAllWindows()\n\n def register_attendance(self):\n\n images = []\n names = []\n #-- Read Images --#\n path = 'images'\n images = [cv2.imread(f'{path}/{image}') for image in os.listdir(path)]\n names = [os.path.splitext(image)[0] for image in os.listdir(path)]\n \n if len(images) != 0:\n # Codificate our faces\n codificated_faces = [fr.face_encodings(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))[0] for image in images]\n # Create the list for users encountered\n encountered = []\n # Set a control variable for the faces comparison\n comp1 = 100\n # Create the camera object using opencv - (0) -> First Camera\n cap = cv2.VideoCapture(0)\n while True:\n # Read the frames\n ret, frame = cap.read()\n # Reduce the images to improve efficiency\n frame2 = cv2.resize(frame, (0,0), None, 0.25, 0.25)\n # Convert BGR -> RGB color\n rgb = cv2.cvtColor(frame2, cv2.COLOR_BGR2RGB)\n # Search for faces in the camera's vision field\n faces = fr.face_locations(rgb)\n # Codificate the faces located\n facescod = fr.face_encodings(rgb, faces)\n\n # Iterate in the faces encountered and each one's location facecod, faceloc\n for facecod, faceloc in zip(facescod, faces):\n #Comparison between registered faces and encountered faces in real time\n comparison = fr.compare_faces(codificated_faces, facecod)\n\n #Calculate the similarity -> similarity = [distance_to_face(1), distance_to_face(2), ... distance_to_face(n)]\n #distance_to_face(n) -> is lower according to the similarity to the registered face\n similarity = fr.face_distance(codificated_faces, facecod)\n\n #We search for the minimum value index\n minimum = np.argmin(similarity)\n\n #Check if the minimum value is in our comparison array\n if comparison[minimum]:\n #We get the name of the user\n if similarity[minimum] < 0.5:\n name = names[minimum].upper()\n else:\n name = \"Desconocido\"\n\n #Extract the coordinates of the face\n yi, xf, yf, xi = faceloc\n\n #Resize the coordinates\n yi, xf, yf, xi = yi*4, xf*4, yf*4, xi*4\n\n #Get the index of the location\n index = comparison.index(True)\n\n #Compare if the index of the face location to set up a color for the rectangle around the face\n if comp1 != index:\n #Set colors to draw the rectangle\n r = random.randrange(0, 255, 50)\n g = random.randrange(0, 255, 50)\n b = random.randrange(0, 255, 50)\n\n #Set the control variable to draw the rectangle\n comp1 = index\n \n if comp1 == index:\n #Draw the rectangle from (xi, yi) to (xf, yf) with color (r, g, b) and a thickness of 3\n cv2.rectangle(frame,(xi, yi), (xf, yf), (r, g, b), 3)\n \n #Draw a filled rectangle to display the name of the user\n cv2.rectangle(frame,(xi, yf-35), (xf, yf), (r, g, b), cv2.FILLED)\n\n #Display the name in the filled rectangle\n cv2.putText(frame, name, (xi+6, yf-6), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)\n\n #Save the record of the user attendance if is not recorded already\n if name not in encountered:\n encountered.append(name)\n #Save the record\n #Open the .csv in read-write mode\n if name != \"Desconocido\":\n with open('attendance.csv','r+') as file:\n #Read the information in the file\n data = file.readline()\n #Get the date and time\n date_info = datetime.now()\n #Extract the Date\n date = date_info.strftime('%Y:%m:%d')\n #Extract the hour\n hour = date_info.strftime('%H:%M:%S')\n #Save the new record [ User, Date, Hour ]\n file.writelines(f'\\n{name},{date},{hour}')\n \n else:\n # If the face is unknown, draw a red rectangle and display \"Desconocido\"\n yi, xf, yf, xi = faceloc\n yi, xf, yf, xi = yi*4, xf*4, yf*4, xi*4\n cv2.rectangle(frame,(xi, yi), (xf, yf), (0,0,255), 3)\n cv2.rectangle(frame,(xi, yf-35), (xf, yf), (0, 0, 255), cv2.FILLED)\n cv2.putText(frame, \"Desconocido\", (xi+6, yf-6), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)\n\n\n\n #Show the video recording in real time\n cv2.imshow('Registro de Asistencia', frame)\n\n #Listens for a keyboard input\n key = cv2.waitKey(1)\n\n #If the keyboard input -> \"a\"\n if (key%256) == 97:\n #Breaking the loop\n break\n\n #Release and close the camera object \n cap.release()\n cv2.destroyAllWindows()\n else:\n print(\"No hay registros\")\n\nif __name__ == '__main__':\n app = QApplication([])\n window = MainWindow()\n window.show()\n app.exec_()\n","repo_name":"BryanV475/face_recognition_attendance","sub_path":"attendance.py","file_name":"attendance.py","file_ext":"py","file_size_in_byte":9839,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"37699318309","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\ndef soort_driehoek( a, b, c ):\n if( a == b or a == c or b == c):\n if (a == b and b == c):\n print ( 'Gelijkzijdig' )\n else:\n print( 'Gelijkbenig' )\n else:\n print( 'Willekeurig' )\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()","repo_name":"dvanderfaeillie/comp-denken-sjc","sub_path":"3th year/Math/01 Selectie/99 exercises/11 triangle/solution/solution.nl.py","file_name":"solution.nl.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"73734428317","text":"codigos = []\nalturas = []\n\ncodigo = 1\n\nwhile codigo != \"0\":\n codigo = input(\"Digite o seu código: \")\n if codigo!= \"0\":\n codigos.append(codigo)\n\n altura = input(\"Digite a sua altura: \")\n altura = float(altura)\n alturas.append(altura)\n\n\ncod_mais_alto = codigos[0]\nvalor_mais_alto = alturas[0]\ncod_mais_baixo = codigos[0]\nvalor_mais_baixo = alturas[0]\n\nindex = 0\n\nwhile index < len(codigos):\n if alturas[index] > valor_mais_alto:\n valor_mais_alto = alturas[index]\n cod_mais_alto = codigos[index]\n\n if alturas[index] < valor_mais_baixo:\n valor_mais_baixo = alturas[index]\n cod_mais_baixo = codigos[index]\n\n index = index + 1\n\nprint(cod_mais_alto+\" é o mais alto com \"+str(valor_mais_alto))\nprint(cod_mais_baixo+\" é o mais baixo com \"+str(valor_mais_baixo))","repo_name":"fabriciopa/2023_1_ads_logica_programacao_algoritmica_manha","sub_path":"aula8/q34.py","file_name":"q34.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"pt","doc_type":"code","stars":4,"dataset":"github-code","pt":"51"} +{"seq_id":"31283213700","text":"# Prints values and column in tabular form. Values and columns should be in string format\n# Value => list of list (2d lists). The first dimension contains values for a single entry.\n# The second dimension contains each entry.\n# Column => List of column names.\n# value = [ [John, 1 , True], [Titer, 2 , False]] are 2 entries\n\n\ndef print_table(values, columns):\n num_columns = len(columns)\n if(num_columns == 0):\n print(\"NO COLUMNS\")\n exit(1)\n\n # Find max width\n\n len_li = []\n for x in columns:\n len_li.append([len(x)])\n\n for x in values:\n for i, y in enumerate(x):\n len_li[i].append(len(y))\n\n max_li = []\n for x in len_li:\n max_li.append(max(x) + 2)\n\n line = \"+\"\n for x in max_li:\n line = line + ((\"-\"*x) + \"+\")\n print(line)\n\n cols = \"\"\n for i, x in enumerate(columns):\n empty_width = max_li[i] - len(x) - 1\n cols = cols + \"| \" + x + \" \"*empty_width\n cols = cols + \"|\"\n print(cols)\n print(line)\n\n if (len(values) == 0):\n return\n\n for x in values:\n cols = \"\"\n for i, y in enumerate(x):\n empty_width = max_li[i] - len(y) - 1\n cols = cols + \"| \" + y + \" \"*empty_width\n\n cols = cols + \"|\"\n print(cols)\n print(line)\n","repo_name":"AhmedFarhan252/Python-Tables","sub_path":"pTable.py","file_name":"pTable.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"26685048796","text":"import os.path\nimport io\nimport numpy as np\nimport tensorflow as tf\n\n# tflearn\nimport tflearn\nfrom tflearn.data_utils import to_categorical, pad_sequences\nfrom tflearn.datasets import imdb\n\nFLAGS = tf.app.flags.FLAGS\n\n\nclass DataSet(object):\n def __init__(self, data, labels):\n assert data.shape[0] == labels.shape[0], (\n 'data.shape: %s labels.shape: %s' % (data.shape, labels.shape))\n self._num_examples = data.shape[0]\n\n self._data = data\n self._labels = labels\n self._epochs_completed = 0\n self._index_in_epoch = 0\n\n @property\n def data(self):\n return self._data\n\n @property\n def labels(self):\n return self._labels\n\n @property\n def num_examples(self):\n return self._num_examples\n\n @property\n def epochs_completed(self):\n return self._epochs_completed\n\n def next_batch(self, batch_size):\n assert batch_size <= self._num_examples\n\n start = self._index_in_epoch\n self._index_in_epoch += batch_size\n if self._index_in_epoch > self._num_examples:\n # Finished epoch\n self._epochs_completed += 1\n # Shuffle the data\n perm = np.arange(self._num_examples)\n np.random.shuffle(perm)\n self._data = self._data[perm]\n self._labels = self._labels[perm]\n # Start next epoch\n start = 0\n self._index_in_epoch = batch_size\n\n end = self._index_in_epoch\n\n return self._data[start:end], self._labels[start:end]\n\n\ndef create_datasets(file_path, vocab_size=30000, val_fraction=0.0):\n\n # IMDB Dataset loading\n train, test, _ = imdb.load_data(\n path=file_path,\n n_words=vocab_size,\n valid_portion=val_fraction,\n sort_by_len=False)\n trainX, trainY = train\n testX, testY = test\n\n # Data preprocessing\n # Sequence padding\n trainX = pad_sequences(trainX, maxlen=FLAGS.max_len, value=0.)\n testX = pad_sequences(testX, maxlen=FLAGS.max_len, value=0.)\n # Converting labels to binary vectors\n trainY = to_categorical(trainY, nb_classes=2)\n testY = to_categorical(testY, nb_classes=2)\n\n train_dataset = DataSet(trainX, trainY)\n\n return train_dataset\n\n\ndef main():\n create_datasets('imdb.pkl')\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"burness/paddle-101","sub_path":"script/tutorial/paddle/benchmark/tensorflow/rnn/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"51"} +{"seq_id":"4299907015","text":"import os\nfrom flask import Flask\nfrom dotenv import load_dotenv\nfrom flask_restful import Api\nfrom flask_sqlalchemy import SQLAlchemy\nfrom os import path, getenv, mknod\nfrom flask_jwt_extended import JWTManager\n\napi = Api()\ndb = SQLAlchemy()\njwt = JWTManager()\n\n\ndef create_app():\n\tapp = Flask(__name__)\n\tload_dotenv()\n\n\tif not os.path.exists(os.getenv('DATABASE_PATH') + os.getenv('DATABASE_NAME')):\n\t\tos.mknod(os.getenv('DATABASE_PATH')+os.getenv('DATABASE_NAME'))\n\n\tapp.config['SQLALCHEMY_TRACK_MODIFICATION'] = False\n\tapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////' + getenv('DATABASE_PATH') + getenv('DATABASE_NAME')\n\tdb.init_app(app)\n\n\timport main.resources as resources\n\n\tapi.add_resource(resources.UserResource, '/user/' )\n\tapi.add_resource(resources.UsersResource, '/users')\n\n\tapi.add_resource(resources.PoemaResource, '/poema/' )\n\tapi.add_resource(resources.PoemasResource, '/poemas')\n\n\tapi.add_resource(resources.CalificacionResource, '/calificacion/' )\n\tapi.add_resource(resources.CalificacionesResource, '/calificaciones')\n\n\tapi.init_app(app)\n\n\tapp.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY')\n\tapp.config['JWT_ACCESS_TOKEN_EXPIRES'] = int(os.getenv('JWT_ACCESS_TOKEN_EXPIRES'))\n\tjwt.init_app(app)\n\n\tfrom main.auth import routes\n\n\tapp.register_blueprint(routes.auth)\n\n\treturn app\n","repo_name":"santicoria/programacion_I","sub_path":"backend/main/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"24873635026","text":"from pyimagesocket.image_socket.image_receiver import Receiver, ImageReceiverHandler\n\nfrom threading import Thread\nfrom typing import Callable\n\n\nclass ImageListManeger:\n \"\"\"\n Image Loggerのバックエンドを統括するクラス\n\n Attribute\n ---------\n image_list\n 画像とテキストのリスト\n receiver: Receiver\n 送信されたメッセージを受信するやつ\n on_new_img_received: Callable\n 表示画像を最新の画像に更新する\n\n \"\"\"\n\n def __init__(self, on_new_img_received: Callable) -> None:\n self.image_list: list[dict] = []\n self.receiver = Receiver((\"localhost\", 9008), ImageReceiverHandler)\n self.on_new_img_received = on_new_img_received\n\n Thread(target=self._loop, daemon=True).start()\n\n def _loop(self):\n while True:\n message = self.receiver.q.get()\n if message:\n print(\"receive_message\")\n self.image_list.append(message)\n self.on_new_img_received()\n\n self.receiver.q.task_done()\n\n def get_img(self, index):\n if len(self.image_list) >= index:\n return self.image_list[index][\"image\"]\n else:\n try:\n raise IndexError(\"image_list: index out of range\")\n except IndexError as e:\n print(e)\n\n def del_img(self, index):\n if len(self.image_list) >= index:\n del self.image_list[index]\n return True\n else:\n try:\n raise IndexError(\"image_list: index out of range\")\n except IndexError as e:\n print(e)\n return False\n\n def del_all_img(self):\n self.image_list = []\n self.index = None\n\n def save_img(self, index):\n pass\n","repo_name":"HaoriHakama/ImageLogger","sub_path":"image_receiver/image_list_maneger.py","file_name":"image_list_maneger.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"27640832571","text":"from typing import List\n\nfrom aiogram import types\nfrom aiogram.dispatcher import FSMContext\n\nfrom loader import dp, db, bot\nfrom models import User, Homework\nfrom states import SendHomework\n\n\n@dp.message_handler(text='Отправить домашнее задание')\nasync def send_homework(message: types.Message):\n await message.answer(\"Введите ID студента:\")\n await SendHomework.enter_id.set()\n\n\n@dp.message_handler(content_types=['text'], state=SendHomework.enter_id)\nasync def enter_id(message: types.Message, state: FSMContext):\n user = db.query(User).filter(User.crm_user_id == message.text).first()\n if user is None:\n await message.answer(\"Пользователь с таким ID не зарегистрирован в боте\")\n else:\n await state.update_data(enter_id=message.text)\n await message.answer(\"Введите текст домашнего задания:\")\n await SendHomework.enter_homework.set()\n\n\n@dp.message_handler(content_types=['photo'], state=SendHomework.enter_homework)\nasync def enter_homework_photo(message: types.Message, state: FSMContext, album: List[types.Message]):\n data = await state.get_data()\n homework = db.query(Homework).filter(Homework.crm_user_id == data['enter_id']).first()\n if homework is None:\n homework = Homework()\n homework.crm_user_id = data['enter_id']\n db.add(homework)\n db.commit()\n homework.text = message.caption\n homework.photo = ' '.join(list(map(lambda x: x.photo[-1].file_id, album)))\n db.commit()\n await message.answer(\"Домашка записана\")\n user_tg_id = db.query(User).filter(User.crm_user_id == data['enter_id'], User.is_student == 1).first().tg_user_id\n await bot.send_message(chat_id=user_tg_id, text=\"Вам пришло новое домашнее задание, чтобы посмотреть\"\n \"введите /homework\")\n await state.finish()\n\n\n@dp.message_handler(content_types=['text'], state=SendHomework.enter_homework)\nasync def enter_homework_text(message: types.Message, state: FSMContext):\n data = await state.get_data()\n homework = db.query(Homework).filter(Homework.crm_user_id == data['enter_id']).first()\n if homework is None:\n homework = Homework()\n homework.crm_user_id = data['enter_id']\n db.add(homework)\n db.commit()\n homework.text = message.text\n homework.photo = 'У вас нет домашнего задания'\n db.commit()\n await message.answer(\"Домашка записана\")\n user_tg_id = db.query(User).filter(User.crm_user_id == data['enter_id'], User.is_student == 1).first().tg_user_id\n await bot.send_message(chat_id=user_tg_id, text=\"Вам пришло новое домашнее задание, чтобы посмотреть\"\n \"введите /homework\")\n await state.finish()\n","repo_name":"scolopendra2/selfree_bot","sub_path":"handlers/teacher/send_homework.py","file_name":"send_homework.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"20826828665","text":"from PIL import Image, ImageOps, ImageFilter\nimport os,sys\nimport glob\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nimage_dir = \"C:/Users/Jihun/Desktop/ZZZ/a/\"\n\n#image_dir = \"C:/Users/Jihun/Desktop/ABC/\"\ntarget_resize_dir = \"C:/Users/Jihun/Desktop/ZZZ/b/\"\n#target_resize_dir = \"C:/Users/Jihun/Desktop/last_check/predict/\"\n\nif not os.path.isdir(target_resize_dir):\n os.makedirs(target_resize_dir)\n\nfiles = glob.glob(image_dir+\"*\")\nprint(len(files))\ncount = 1;\n#size = (32, 32)\nfor file in files:\n #im = cv2.imread(file,cv2.IMREAD_COLOR)\n #im =cv2.resize(im, dsize=(400, 224), interpolation=cv2.INTER_AREA)\n #im = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)\n #im = cv2.GaussianBlur(im,(3,3),0)\n #im =cv2.adaptiveThreshold(im,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,17,6)\n #im = cv2.Canny(im,100,100)\n\n im = Image.open(file)\n im = im.convert('RGB')\n im = im.resize((800,600))\n im = im.rotate(270)\n im = im.crop((300,200,500,400))\n im = im.resize((64,64),Image.ANTIALIAS)\n\n '''im = im.resize((400,300))\n im = im.rotate(270)\n im = im.crop((150,100,250,200))\n size = (64,64)\n im = im.thumbnail(size)'''\n #im = im.resize((64,64))\n\n #im = im.filter(ImageFilter.MaxFilter) #GaussianBlur, BLUR, MaxFilter ...\n #print(\"i: \", count, im.format, im.size, im.mode, file.split(\"/\")[-1])\n count+=1\n\n\n #print(target_resize_dir+file.split(\"\\\\\")[-1])\n #cv2.imwrite(target_resize_dir+file.split(\"\\\\\")[-1],im)\n #cv2.imwrite(os.path.join(image_dir,file.split(\"\\\\\")[-1]),im)\n\n\n #im = ImageOps.fit(im, size, Image.ANTIALIAS, 0, (0.5, 0.5))\n #im.save(target_resize_dir+file.split(\"\\\\\")[-1]+\".jpg\", quality=100)\n im.save(target_resize_dir+file.split(\"\\\\\")[-1], quality=100)\n","repo_name":"ohmozi/Dr.pill_good","sub_path":"learningAlgo/reshape_code/change_size.py","file_name":"change_size.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"3285677564","text":"from __future__ import annotations\n\nfrom typing import Dict, List\n\nimport openai\nimport rich\nimport typer\nfrom openai import ChatCompletion\nfrom openai.error import (\n APIConnectionError,\n APIError,\n AuthenticationError,\n RateLimitError,\n ServiceUnavailableError,\n)\nfrom rich.markdown import Markdown\nfrom rich.prompt import Prompt\n\nfrom gpt_cli import pretty\n\nfrom .constants import DEFAULT_SYSTEM\nfrom .context import Context\nfrom .key import OpenaiApiKey\nfrom .message import Message\nfrom .role import Role\n\n\nclass Chat:\n RETRY_SLEEP: int = 10\n chat_completion_params: Dict[str, str | float | int | List[str]]\n\n def __init__(\n self,\n api_key: OpenaiApiKey,\n model: str = \"gpt-3.5-turbo\",\n system: str | None = None,\n out: str = None,\n context: Context = None,\n stop: List[str] | None = None,\n max_completion_tokens: int | None = None,\n max_context_tokens: int | None = None,\n temperature: float = 0.2,\n top_p: float = 1,\n presence_penalty: float = 0,\n frequency_penalty: float = 0,\n ):\n openai.api_key = api_key.get()\n self.model = model\n self.out = out\n\n if context:\n self.context = context\n else:\n self.context = Context(model=model)\n\n if system is None:\n self.system = DEFAULT_SYSTEM\n if not self.context.is_system_set():\n self.context.set_system(system)\n\n # Infer and check token counts\n if max_completion_tokens is not None and max_completion_tokens < 0:\n pretty.error(\"--max-completion-tokens should be a positive integer.\")\n quit(1)\n if max_context_tokens is not None and max_context_tokens < 0:\n pretty.error(\"--max-context-tokens should be a positive integer.\")\n quit(1)\n\n if max_completion_tokens:\n self.max_completion_tokens = max_completion_tokens\n else:\n self.max_completion_tokens = self.model.max_tokens // 2\n\n if max_context_tokens:\n self.max_context_tokens = max_context_tokens\n else:\n self.max_context_tokens = self.model.max_tokens - self.max_completion_tokens\n if self.max_context_tokens < 0:\n pretty.error(\n \"'--max-completion-tokens' cannot be larger than the \"\n \"maximum number of tokens allowed by the \"\n f\"'{self.model.name}' model: {self.model.max_tokens:,d}.\"\n )\n quit(1)\n\n if self.max_completion_tokens + self.max_context_tokens > self.model.max_tokens:\n pretty.error(\n \"Sum of '--max-completion-tokens' and '--max-context-tokens' \"\n \"cannot be larger than the \"\n \"maximum number of tokens allowed by the \"\n f\"'{self.model.name}' model: {self.model.max_tokens:,d}.\"\n )\n quit(1)\n\n self.stop = stop if stop else None # \"\" or [] becomes None\n self.temperature = temperature\n assert 0 <= self.temperature <= 2\n self.top_p = top_p\n assert 0 <= self.top_p <= 1\n self.presence_penalty = presence_penalty\n assert -2 <= self.presence_penalty <= 2\n self.frequency_penalty = frequency_penalty\n assert -2 <= self.frequency_penalty <= 2\n\n self.chat_completion_params = {\n \"stop\": self.stop,\n \"max_tokens\": self.max_completion_tokens,\n \"temperature\": self.temperature,\n \"top_p\": self.top_p,\n \"presence_penalty\": self.presence_penalty,\n \"frequency_penalty\": self.frequency_penalty,\n }\n\n @staticmethod\n def ask_for_input() -> str:\n prompt = Prompt\n prompt.prompt_suffix = \"> \"\n user_input = \"\"\n while True:\n user_input += prompt.ask()\n if user_input.strip()[-1] != \"\\\\\":\n break\n else:\n # Change \\ for \\n\n user_input = user_input[:-1]\n user_input += \"\\n\"\n if user_input in (\"exit\", \"quit\", \":q\"):\n raise typer.Exit()\n\n return user_input\n\n def _need_user_input(self) -> bool:\n if len(self.context.messages) == 0:\n # First message should be user input\n return True\n # Need input, if last message was not user message\n last_message = self.context.messages[-1]\n return last_message.role != Role.user\n\n def start(self):\n while True:\n # Check if we need user input\n if self._need_user_input():\n user_input = self.ask_for_input()\n self.context.add_message(\n Message(content=user_input, role=Role.user, model=self.model)\n )\n if self.out:\n self.context.save(self.out)\n\n # Send request\n success = False\n while not success:\n try:\n completion = pretty.typing_animation(\n ChatCompletion.create,\n model=self.model.name,\n messages=self.context.get_messages(\n max_tokens=self.model.max_tokens,\n ),\n **self.chat_completion_params,\n )\n success = True\n except RateLimitError:\n s = self.RETRY_SLEEP\n msg = f\"RateLimitError: retrying in {s:d} seconds.\"\n pretty.waiting_animation(s, msg)\n except APIError:\n s = self.RETRY_SLEEP\n msg = f\"APIError: retrying in {s:d} seconds.\"\n pretty.waiting_animation(s, msg)\n except ServiceUnavailableError:\n s = self.RETRY_SLEEP\n msg = f\"ServiceUnavailableError: retrying in {s:d} seconds.\"\n pretty.waiting_animation(s, msg)\n except APIConnectionError:\n s = self.RETRY_SLEEP\n msg = f\"APIConnectionError: retrying in {s:d} seconds.\"\n pretty.waiting_animation(s, msg)\n except AuthenticationError:\n msg = (\n \"Incorrect API key provided. You can find your API key \"\n \"at https://platform.openai.com/account/api-keys. \"\n \"Then rerun the 'init' command or specify it using the \"\n \"environment variable 'OPENAI_API_KEY', or the command line \"\n \"option '--openai-api-key'.\"\n )\n pretty.error(msg)\n quit(1)\n\n assistant_reply = completion.choices[0].message[\"content\"]\n self.context.add_message(\n Message(content=assistant_reply, role=Role.assistant, model=self.model)\n )\n rich.print()\n rich.print(Markdown(assistant_reply))\n rich.print()\n\n if self.out:\n self.context.save(self.out)\n","repo_name":"nickto/gpt-cli","sub_path":"gpt_cli/chat.py","file_name":"chat.py","file_ext":"py","file_size_in_byte":7187,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"23587304126","text":"# -*- coding: utf-8 -*-\n\nimport sys\nfrom pathlib import Path\nfrom s3pathlib import S3Path\nfrom boto_session_manager import BotoSesManager\nfrom aws_lambda_layer import api\n\n# ------------------------------------------------------------------------------\n# Update your configuration here\nbsm = BotoSesManager(profile_name=\"bmt_app_dev_us_east_1\")\nlayer_name = \"aws_lambda_layer_test\"\npython_versions = [\"python3.8\"]\ns3dir_lambda = S3Path(\n f\"s3://{bsm.aws_account_id}-{bsm.aws_region}-artifacts/projects/aws_lambda_layer/lambda/\"\n).to_dir()\nquiet = True\nmetadata = {\"project\": \"aws_lambda_layer_test\"}\ntags = {\"project\": \"aws_lambda_layer_test\"}\n#\n# ------------------------------------------------------------------------------\n\n_dir_here = Path(__file__).absolute().parent\ndir_build = _dir_here.joinpath(\"build\")\npath_requirements = _dir_here.joinpath(\"requirements.txt\")\nbin_pip = Path(sys.executable).parent.joinpath(\"pip\")\n\nlambda_layer_console_url = f\"https://{bsm.aws_region}.console.aws.amazon.com/lambda/home?region={bsm.aws_region}#/layers/{layer_name}?tab=versions\"\nprint(f\"try to deploy a new lambda layer version for {layer_name}\")\nprint(f\"preview lambda layer s3 files: {s3dir_lambda.console_url}\")\nprint(f\"preview lambda layer versions: {lambda_layer_console_url}\")\n\nlatest_layer_version = api.get_latest_layer_version(bsm=bsm, layer_name=layer_name)\n\nif api.is_current_layer_the_same_as_latest_one(\n bsm=bsm,\n latest_layer_version=latest_layer_version,\n path_requirements=path_requirements,\n s3dir_lambda=s3dir_lambda,\n):\n print(\"current layer is the same as the latest one, skip deploying\")\n exit(0)\n\nprint(\"build layer artifacts ...\")\nlayer_sha256 = api.build_layer_artifacts(\n path_requirements=path_requirements,\n dir_build=dir_build,\n bin_pip=bin_pip,\n quiet=quiet,\n)\n\nprint(\"upload layer artifacts ...\")\napi.upload_layer_artifacts(\n bsm=bsm,\n path_requirements=path_requirements,\n layer_sha256=layer_sha256,\n dir_build=dir_build,\n s3dir_lambda=s3dir_lambda,\n metadata=metadata,\n tags=tags,\n)\n\nprint(\"publish new layer version ...\")\n(\n layer_version,\n layer_version_arn,\n s3path_layer_zip,\n s3path_layer_requirements_txt,\n) = api.publish_layer(\n bsm=bsm,\n layer_name=layer_name,\n python_versions=python_versions,\n dir_build=dir_build,\n s3dir_lambda=s3dir_lambda,\n)\nlambda_layer_console_url = f\"https://{bsm.aws_region}.console.aws.amazon.com/lambda/home?region={bsm.aws_region}#/layers/{layer_name}?tab=versions\"\nprint(f\"Done! Published: {layer_version_arn}\")\n","repo_name":"MacHu-GWU/aws_lambda_layer-project","sub_path":"example/build_layer.py","file_name":"build_layer.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"71634600173","text":"import ujson as json\nimport requests\nfrom functools import wraps, update_wrapper\nfrom typing import List, Dict, Union\nfrom flask import Response, make_response, request, current_app\nfrom datetime import timedelta\n\n\ndef crossdomain(origin=None, methods=None, headers=None,\n max_age=21600, attach_to_all=True,\n automatic_options=True):\n if methods is not None:\n methods = ', '.join(sorted(x.upper() for x in methods))\n if headers is not None and not isinstance(headers, str):\n headers = ', '.join(x.upper() for x in headers)\n if not isinstance(origin, str):\n origin = ', '.join(origin)\n if isinstance(max_age, timedelta):\n max_age = max_age.total_seconds()\n\n def get_methods():\n if methods is not None:\n return methods\n\n options_resp = current_app.make_default_options_response()\n return options_resp.headers['allow']\n\n def decorator(f):\n def wrapped_function(*args, **kwargs):\n if automatic_options and request.method == 'OPTIONS':\n resp = current_app.make_default_options_response()\n else:\n resp = make_response(f(*args, **kwargs))\n if not attach_to_all and request.method != 'OPTIONS':\n return resp\n\n h = resp.headers\n\n h['Access-Control-Allow-Origin'] = origin\n h['Access-Control-Allow-Methods'] = get_methods()\n h['Access-Control-Max-Age'] = str(max_age)\n if headers is not None:\n h['Access-Control-Allow-Headers'] = headers\n return resp\n\n f.provide_automatic_options = False\n return update_wrapper(wrapped_function, f)\n\n return decorator\n\n\ndef ssfunc_gen(app):\n def ssfunc(path):\n def outer(func):\n @wraps(func)\n def inner(*args, **kwargs):\n return Response(json.encode(func(*args, **kwargs)), mimetype='application/json')\n\n return app.route(path)(crossdomain(origin=\"*\")(inner))\n\n return outer\n\n return ssfunc\n\n\ndef get_json(request: requests.Response) -> Union[List, Dict, int, str]:\n try:\n return request.json()\n except json.decoder.JSONDecodeError:\n if request.content == b'[]':\n # special case\n return []\n else:\n raise\n\n\ndef estimate_worth(symbol: str):\n quote = get_json(requests.get(\"https://api.robinhood.com/quotes/{}/\".format(symbol.upper())))\n if not quote['last_extended_hours_trade_price'] is None:\n return quote['last_extended_hours_trade_price']\n else:\n return quote['last_trade_price']\n\n\ndef fetch_orders(symbol: str) -> List[Dict]:\n return get_json(requests.get(\"http://api.stockstream.live/v1/orders/symbol/{}/\".format(symbol.upper())))\n\n\ndef stock_stats_raw(ticker):\n orders = fetch_orders(ticker)\n balance, buys, sells, total_trades = 0, 0, 0, 0\n\n for order in orders:\n if order['state'] == 'filled':\n price = order['price']\n shares = int(order['quantity'])\n total_trades += 1\n\n if order['side'] == 'sell':\n balance += price * shares\n sells += shares\n elif order['side'] == 'buy':\n balance -= price * shares\n buys += shares\n else:\n raise ValueError()\n\n shares = buys - sells\n worth = shares * float(estimate_worth(ticker))\n net = balance + worth\n return {\n 'total_trades': total_trades,\n 'buys': buys,\n 'sells': sells,\n 'net': net,\n }\n","repo_name":"CrazyPython/ssapp","sub_path":"ssfunc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"55"} +{"seq_id":"34749340637","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Sep 24 23:58:12 2019\r\n\r\n@author: Xiyu Li\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Sep 27 06:38:21 2019\r\n\r\n@author: Xiyu Li\r\n\"\"\"\r\n# import modules\r\nimport gzip\r\nimport struct\r\nfrom datetime import timedelta\r\nimport pandas as pd\r\nimport os\r\n\r\n# Use Object oriented programming\r\n# Create operations on the ITCH files as member function\r\nclass ITCH():\r\n # defalut constructor\r\n def __init__(self):\r\n # member data\r\n self.temp = []\r\n self.flag = None\r\n if not os.path.exists(os.path.join('.', 'output')):\r\n os.makedirs(os.path.join('.', 'output'))\r\n # member function\r\n def get_binary(self, size):\r\n read = bin_data.read(size)\r\n return read\r\n \r\n # interpert the information in binary code\r\n def trade_message(self, msg):\r\n # >HH6sQsI8sIQ\r\n # big-endian; follow the format of ITCH Documentation\r\n temp = struct.unpack('>HH6sQsI8sIQ', message)\r\n t = int.from_bytes(temp[2], byteorder='big')\r\n x='{0}'.format(timedelta(seconds=t * 1e-9))\r\n return [x, bytes.decode(temp[6]).strip(), temp[7]/10000, temp[5]], x.split(':')[0]\r\n \r\n # calculate the weighted average price for each stock\r\n def cal_vwap(self, df):\r\n df['amount'] = df['price'] * df['volume']\r\n df['time'] = pd.to_datetime(df['time'])\r\n df = df.groupby([df['time'].dt.hour, df['symbol']])['amount', 'volume'].sum()\r\n df['vwap'] = df['amount'] / df['volume']\r\n # if need to keep 2 digits after decimal, un-comment the code below\r\n # df['vwap'] = df['vwap'].round(2)\r\n df = df.reset_index()\r\n df['time'] = df.apply(lambda x: str(x['time']) + ':00:00', axis=1)\r\n df = df[['time', 'symbol', 'vwap']]\r\n return df\r\n \r\n # group information accroding to hours and compute hourly VWAP\r\n def get_vwap(self, message):\r\n parsed_data, hour = self.trade_message(message)\r\n if self.flag is None:\r\n self.flag = hour\r\n if self.flag != hour:\r\n df = pd.DataFrame(self.temp, columns=['time', 'symbol', 'price', 'volume'])\r\n result = self.cal_vwap(df)\r\n result.to_csv(os.path.join(str(self.flag) + '.csv'), index=False)\r\n #print(result)\r\n self.temp = []\r\n self.flag = hour\r\n self.temp.append(parsed_data)\r\n \r\n \r\nif __name__ == '__main__':\r\n # load file\r\n bin_data = gzip.open('E:\\\\Trexquant Coding Test\\\\01302019.NASDAQ_ITCH50.gz', 'rb')\r\n # create instance of the class\r\n itch= ITCH()\r\n # load first batch of bytes\r\n msg_header = bin_data.read(1)\r\n\r\n # iterate throught the binary file\r\n while msg_header:\r\n if msg_header == str.encode(\"S\"):\r\n # tranverse the index to 11 places later\r\n message = itch.get_binary(11)\r\n\r\n elif msg_header == str.encode(\"R\"):\r\n message = itch.get_binary(38)\r\n\r\n elif msg_header == str.encode(\"H\"):\r\n message = itch.get_binary(24)\r\n\r\n elif msg_header == str.encode(\"Y\"):\r\n message = itch.get_binary(19)\r\n\r\n elif msg_header == str.encode(\"L\"):\r\n message = itch.get_binary(25)\r\n\r\n elif msg_header == str.encode(\"V\"):\r\n message = itch.get_binary(34)\r\n\r\n elif msg_header == str.encode(\"W\"):\r\n message = itch.get_binary(11)\r\n\r\n elif msg_header == str.encode(\"K\"):\r\n message = itch.get_binary(27)\r\n\r\n elif msg_header ==str.encode(\"A\"):\r\n message = itch.get_binary(35)\r\n\r\n elif msg_header == str.encode(\"F\"):\r\n message = itch.get_binary(39)\r\n\r\n elif msg_header == str.encode(\"E\"):\r\n message = itch.get_binary(30)\r\n\r\n elif msg_header == str.encode(\"C\"):\r\n message = itch.get_binary(35)\r\n\r\n elif msg_header == str.encode(\"X\"):\r\n message = itch.get_binary(22)\r\n\r\n elif msg_header == str.encode(\"D\"):\r\n message = itch.get_binary(18)\r\n\r\n elif msg_header == str.encode(\"U\"):\r\n message = itch.get_binary(34)\r\n\r\n elif msg_header == str.encode(\"P\"):\r\n message = itch.get_binary(43)\r\n itch.get_vwap(message)\r\n\r\n elif msg_header == str.encode(\"Q\"):\r\n message = itch.get_binary(39)\r\n\r\n elif msg_header == str.encode(\"B\"):\r\n message = itch.get_binary(18)\r\n\r\n elif msg_header == str.encode(\"I\"):\r\n message = itch.get_binary(49)\r\n\r\n elif msg_header == str.encode(\"N\"):\r\n message = itch.get_binary(19)\r\n \r\n msg_header = bin_data.read(1)\r\n\r\n bin_data.close()\r\n #print(itch.temp)\r\n","repo_name":"LiSnH2O/ITCH5.0_Python_Parser","sub_path":"Li Xiyu - Python Code.py","file_name":"Li Xiyu - Python Code.py","file_ext":"py","file_size_in_byte":4727,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"35131874845","text":"import numpy as np\r\n\r\nif __name__ == '__main__':\r\n np.random.seed(0)\r\n\r\n\"\"\"\r\nThis enviroment assumes:\r\n - Price of the second item fixed\r\n - Convertion rates known and fixed in time\r\n - Assignment of promos fixed\r\n - Numbers of customers per day of each class known and fixed in time\r\n\"\"\"\r\n\r\n\r\nclass Enviroment():\r\n def __init__(self, n_arms, n_customers, margin1, margin2, conv_rate1, conv_rate2, promo_assig):\r\n self.n_arms = n_arms\r\n self.n_customers = n_customers\r\n self.margin1 = margin1\r\n self.margin2 = margin2\r\n self.conv_rate1 = conv_rate1\r\n self.conv_rate2 = conv_rate2\r\n self.promo_assig = promo_assig\r\n self.n_promos = len(margin2)\r\n\r\n def round(self, pulled_arm):\r\n reward = 0\r\n for cust_class in range(len(self.n_customers)):\r\n buyers = np.random.binomial(self.n_customers[cust_class], self.conv_rate1[cust_class, pulled_arm])\r\n # divide number of buyers by number of custumers to work with fractions and keep rewards bounded in [0,1]\r\n reward += self.margin1[pulled_arm] * buyers / self.n_customers[cust_class]\r\n\r\n for promo in range(self.n_promos):\r\n buyers2 = np.random.binomial(buyers * self.promo_assig[cust_class, promo],\r\n self.conv_rate2[cust_class, pulled_arm, promo])\r\n # divide buyers2 by maximum number of buyers to keep rewards bounded\r\n reward += self.margin2[promo] * buyers2 / (buyers * self.promo_assig[cust_class, promo])\r\n\r\n return reward\r\n\r\n\r\ndef main():\r\n # Each arm is a different price for the first item\r\n T = 365\r\n n_arms = 3\r\n n_arms = int(np.ceil((np.log10(T) * T) ** 0.25))\r\n\r\n # Number of classes of customers\r\n n_classes = 4\r\n n_promos = 5\r\n\r\n # Margin of product 1 at different prices\r\n # Vector of positive floats\r\n margin1 = 50 * np.random.rand(n_arms)\r\n\r\n # Margin of product 2 at different promos\r\n # Vector of positive floats\r\n margin2 = 50 * np.random.rand(n_promos)\r\n\r\n # Number of customers of each class\r\n # Vector of integers\r\n n_customers = (100 * np.random.rand(n_classes)).astype(int)\r\n\r\n # Convertion rate of the first item, from class i at price j.\r\n # Matrix of probabilities\r\n conv_rate1 = np.random.rand(n_classes, n_arms)\r\n\r\n # Convertion rate of the second item, from class i at original price j and discount from promo k\r\n # Matrix of probabilities\r\n conv_rate2 = np.random.rand(n_classes, n_arms, n_promos)\r\n\r\n # Percentage of people from class i that get the promotion j\r\n promo_assig = np.random.rand(n_classes, n_promos)\r\n\r\n # Normalization so the sum of each row is equal to 1\r\n # Matrix of probabilities\r\n promo_assig = promo_assig / promo_assig.sum(axis=1)[:, np.newaxis]\r\n\r\n env = Enviroment(n_arms, n_customers, margin1, margin2, conv_rate1, conv_rate2, promo_assig)\r\n\r\n env.round(0), env.round(1), env.round(2)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"karim-zakaria/DIA-project-polimi","sub_path":"pricing/enviroment/Environment.py","file_name":"Environment.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"23773223347","text":"import cv2\nimport numpy as np\nimport os\nimport pydicom\nfrom random import choice\nfrom dicompylercore import dicomparser\nfrom skimage.measure import regionprops\n\n\"\"\"\nADAPTIVE TEMPLATE MATCHING\n\"\"\"\n\n\ndef show(pixel_array):\n \"\"\"\n Exibe a imagem a partir de um array de pixels.\n\n :param pixel_array: numpy array com os pixels da imagem.\n :return:\n \"\"\"\n print(\"Show was called.\")\n cv2.imshow('image', pixel_array)\n k = cv2.waitKey(0)\n if k == 27: # wait for ESC key to exit\n cv2.destroyAllWindows()\n\n\ndef load_datasets(path):\n \"\"\"\n Carrega todos os arquivos DICOM de um diretório.\n\n :param path: str indicando o diretório de origem dos\n dos arquivos que se deseja carregar\n :return volume: lista com os arquivos dicom\n \"\"\"\n volume = list()\n slice_locations = dict()\n\n for root, dirs, files in os.walk(path):\n for file in files:\n ds = pydicom.dcmread(root + '/'+ file)\n if ds.Modality == 'CT':\n slice_locations[ds.SliceLocation] = ds\n volume = [slice_locations[key] for key in sorted(slice_locations.keys())]\n return volume\n\n\ndef load_rtstruct(path):\n \"\"\"\n Carrega o documento de marcação RT STRUCT do volume\n no referente path\n\n :param path: str indicando o diretório do conjunto\n de slices DICOM, incluindo o RT STRUCT\n :return rt_struct: uma instância do dicompyler com as\n marcações\n \"\"\"\n rt_struct = None\n\n for root, dirs, files in os.walk(path):\n for file in files:\n ds = pydicom.dcmread(root + '/'+ file)\n if ds.Modality != 'CT':\n rt_struct = dicomparser.DicomParser(ds)\n\n return rt_struct\n\n\ndef get_marking(rt_struct, structure_name, position_patient, pixel_spacing):\n \"\"\"\n Encontra a marcação da estrutura especificada no rt_struct\n na posição passada por parâmetro.\n\n :param rt_struct: instância do dicompyler \n :param structure_name: str com nome da estrutura marcada\n :param position_patient: float com a positiona do paciente na imagem\n\n :return marking: coordenadas da marcação\n \"\"\"\n marking = None\n structures = marking.GetStructures()\n number_roi = None\n for i in structures:\n if structures[i]['name'] == structure_name:\n number_roi = structures[i]['id']\n\n try:\n contour = np.array(marking.GetStructureCoordinates(number_roi)['{0:.2f}'.format(position_patient)][0]['data'])\n except KeyError:\n return None\n\n rows = ((contour[:, 1] - position_patient[1])/pixel_spacing[1]).astype(int)\n columns = ((contour[:, 0] - position_patient[0])/pixel_spacing[0]).astype(int)\n marking = [rows, columns]\n return marking\n\n\ndef loadpath_volumes(path):\n \"\"\"\n Gera uma lista com os paths dos volumes no path\n\n :param path: path onde os volumes estão armazenados\n :return volumes: paths dos volumes encontrados\n \"\"\"\n volumes = list()\n\n for root, dirs, files in os.walk(path):\n for dir in dirs:\n volumes.append(root + dir)\n break\n\n return volumes\n\n\ndef choice_volume(path):\n \"\"\"\n Seleciona aleatoriamente um volume do path\n :param path: path onde os volumes estão armazenado\n :return volume: lista com rtstruct dataset e lista de CT datasets\n \"\"\"\n path_volume = None\n ds = list()\n marks = None #Guarda o RT_STRUCT, as marcações do especialista.\n slice_locations = dict()\n for root, dirs, files in os.walk(path):\n path_volume = root+choice(dirs)\n break\n for root, dirs, files in os.walk(path_volume):\n for file in files:\n dataset = pydicom.dcmread(root + '/' + file)\n if dataset.Modality == 'CT':\n slice_locations[ds.SliceLocation] = dataset\n else:\n marks = dataset\n ds = [slice_locations[key] for key in sorted(slice_locations.keys())]\n volume = [marks, ds]\n\n return volume\n\n\ndef getImage(slice):\n \"\"\"\n Retorna um array de pixels com valores LUT\n\n :param slice: dataset dicom\n :return pixels_slice: array numpy com os pixels transformados\n \"\"\"\n ds = dicomparser.DicomParser(slice)\n intercept, slope = ds.GetRescaleInterceptSlope()\n rescaled_image = slice.pixel_array * slope + intercept\n window, level = ds.GetDefaultImageWindowLevel()\n pixels_slice = ds.GetLUTValue(rescaled_image, window, level)\n\n return pixels_slice\n\ndef getImages(datasets):\n \"\"\"\n Retorna um array de pixels com valores LUT para cada dataset\n\n :param datasets: lista de datasets dicom\n :return pixels_slice: lista de arrays numpy com os pixels transformados para\n cada dataset\n \"\"\"\n pixels_slice = list()\n for slice in datasets:\n ds = dicomparser.DicomParser(slice)\n intercept, slope = ds.GetRescaleInterceptSlope()\n rescaled_image = slice.pixel_array * slope + intercept\n window, level = ds.GetDefaultImageWindowLevel()\n pixels_slice.append(ds.GetLUTValue(rescaled_image, window, level))\n\n return pixels_slice\n\ndef getStandardTemplate(standard_path):\n ###########Suponha que o volume tenha sido selecionado aleatoriamente\n #Gerando o template padrão\n #- Seleciona aleatoriamente um volume dentre todos os outros do banco de dados.\n\n volume = choice_volume(standard_path)\n quant_slices = len(volume)\n slice = choice(volume[1])\n #- Encontrar a marcação do especialista, encontrar o centro da massa dessa marcação\n marking = dicomparser.DicomParser(volume[0])\n structures = marking.GetStructures()\n number_roi = None\n for i in structures:\n if structures[i]['name'] == 'SpinalCord':\n number_roi = structures[i]['id']\n\n\n while True:\n #Sorteia um novo slice caso o slice sorteado não contenha a medula\n try:\n contour = np.array(marking.GetStructureCoordinates(number_roi)['{0:.2f}'.format(slice.ImagePositionPatient[2])][0]['data'])\n break\n except KeyError:\n slice = choice(volume[1])\n\n rows = ((contour[:, 1] - slice.ImagePositionPatient[1])/slice.PixelSpacing[1]).astype(int)\n columns = ((contour[:, 0] - slice.ImagePositionPatient[0])/slice.PixelSpacing[0]).astype(int)\n #Conseguindo LUT Values\n pixels_slice = getImage(slice)\n\n diameter_x = rows.max() - rows.min()\n diameter_y = columns.max() - columns.min()\n center_x = int(diameter_x//2 + rows.min())\n center_y = int(diameter_y//2 + columns.min())\n\n\n #- Recortar duas vezes o tamanho da região correspondente de todos os lados.\n #print(\"[{0}:{1}, {2}:{3}]\".format(rows.min() - (2*diameter_y), rows.max() + (2*diameter_y), columns.min() - (2*diameter_x), columns.max() + (2*diameter_x)))\n standard_template = pixels_slice[rows.min() - (2*diameter_y): rows.max() + (2*diameter_y), columns.min() - (2*diameter_x):columns.max() + (2*diameter_x)]\n cv2.imwrite(\"standard_template.png\", standard_template)\n return standard_template\n\n\ndef getInitialTemplates(standard_template, volume_paths):\n results = list()\n cont = 0\n for path_volume in volume_paths:\n datasets = load_datasets(path_volume)\n mins = list()\n locations = list()\n # - Calcular a similaridade em cada slice;\n for i, ds in enumerate(datasets):\n image = getImage(ds)[200:400, 150:400]\n blur = cv2.blur(image, (5, 5))\n minmaxloc = cv2.minMaxLoc(cv2.matchTemplate(blur, standard_template, cv2.TM_SQDIFF))\n mins.append(minmaxloc[0])\n locations.append(minmaxloc[2])\n minimo = min(mins)\n indice = mins.index(minimo)\n\n image = getImage(datasets[indice])[200:400, 150:400]\n\n w, h = standard_template.shape\n top_left = [locations[indice][0], locations[indice][1]]\n\n if top_left[0] + w >= image.shape[1]:\n w = image.shape[1] - top_left[0] - 1\n if top_left[1] + h >= image.shape[0]:\n h = image.shape[0] - top_left[1] - 1\n\n # image[top_left[1], top_left[0]:top_left[0] + w] = 255\n # image[top_left[1] + h, top_left[0]:top_left[0] + w] = 255\n # image[top_left[1]:top_left[1]+ h, top_left[0]] = 255\n # image[top_left[1]:top_left[1] + h, top_left[0] + w] = 255\n # show(image)\n # - O template inicial selecionado é aquele que tem maior similaridade com o template padrão,\n # o número do slice do melhor template inicial é salvo.\n cv2.imwrite(\"./outputs/initial_templates/{0}-{1}.png\".format(cont, indice),\n image[top_left[1]:top_left[1] + h, top_left[0]:top_left[0] + w])\n cont += 1\n results.append(\n {'initial_template': image[top_left[1]:top_left[1] + h, top_left[0]:top_left[0] + w], 'indice': indice,\n 'path_volume': path_volume})\n return results\n\ndef getAdaptativeTemplates(results):\n templates_result = list()\n for initial_info in results: # Informações do template inicial\n # - Executa o Template Matching no primeiro slice onde a combinação ocorre, como resultado temos:\n # o Novo Template e uma imagem.\n volume = load_datasets(initial_info['path_volume'])\n datasets = getImages(volume)\n tam = len(datasets)\n # - O Novo Template é executado no próximo slice e, novamente, o resultado será um Novo Template e uma image.\n # - No final, teremos um conjunto de imagens onde á apenas a região da medula segmentada.\n results2 = list()\n adaptative_template = initial_info['initial_template'][::]\n print(initial_info['path_volume'])\n dirname = \"./outputs/adaptative_templates/\"+os.path.basename(initial_info['path_volume'])\n\n try:\n os.mkdir(dirname)\n except FileExistsError as e:\n pass\n\n for i in reversed(range(0, initial_info['indice'])):\n blur_image = cv2.blur(datasets[i][180:400, 150:400], (5, 5))\n adaptative_template = cv2.blur(adaptative_template, (5, 5))\n min, max, minloc, maxloc = cv2.minMaxLoc(cv2.matchTemplate(blur_image, adaptative_template, cv2.TM_SQDIFF))\n w, h = adaptative_template.shape\n if minloc[0] + w >= blur_image.shape[0]:\n w = blur_image.shape[0] - minloc[0] - 1\n if minloc[1] + h >= blur_image.shape[1]:\n h = blur_image.shape[1] - minloc[1] - 1\n adaptative_template = datasets[i][180:400, 150:400][minloc[1]:minloc[1] + h, minloc[0]:minloc[0] + w]\n cv2.imwrite(dirname + \"/{0}.png\".format(i), adaptative_template)\n results2.append(adaptative_template)\n\n results2 = results2[::-1]\n adaptative_template = initial_info['initial_template'][::]\n for i in range(initial_info['indice'], tam):\n blur_image = cv2.blur(datasets[i][180:400, 150:400], (5, 5))\n adaptative_template = cv2.blur(adaptative_template, (5, 5))\n min, max, minloc, maxloc = cv2.minMaxLoc(cv2.matchTemplate(blur_image, adaptative_template, cv2.TM_SQDIFF))\n w, h = adaptative_template.shape\n if minloc[0] + w >= blur_image.shape[0]:\n w = blur_image.shape[0] - minloc[0] - 1\n if minloc[1] + h >= blur_image.shape[1]:\n h = blur_image.shape[1] - minloc[1] - 1\n adaptative_template = datasets[i][180:400, 150:400][minloc[1]:minloc[1] + h, minloc[0]:minloc[0] + w]\n cv2.imwrite(dirname + \"/{0}.png\".format(i), adaptative_template)\n results2.append(adaptative_template)\n templates_result.append({'path':initial_info['path_volume'], 'results':results2})\n return templates_result\n\ndef getCandidatesSegmentation(path):\n for root, dirs, files in os.walk(path):\n dir_name = os.path.basename(root)\n if 'fail' in dir_name:\n continue\n try:\n os.mkdir('./outputs/candidates_segmentation/' + dir_name)\n except FileExistsError as e:\n pass\n\n for file in files:\n root = root.replace('\\\\', '/')\n filename = root + '/' + file\n seg_filename = './outputs/candidates_segmentation/' + dir_name + '/' + file\n print(filename)\n im = cv2.imread(filename, 0)\n print(im.shape)\n blur = cv2.GaussianBlur(im, (3, 3), 0)\n retval = cv2.ximgproc.createSuperpixelSLIC(blur, cv2.ximgproc.MSLIC, region_size=12, ruler=110.)\n #retval.enforceLabelConnectivity(12)\n retval.iterate()\n a = retval.getLabelContourMask()\n im[a == 255] = 255\n cv2.imwrite(seg_filename, im)\n\n\ndef get_bounding_boxes(image, width, height):\n bboxes = list()\n top = int(image.shape[0] * 0.5)\n bottom = top\n left = int(image.shape[1] * 0.5)\n right = left\n blur = cv2.GaussianBlur(image, (3, 3), 0)\n image = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT)\n retval = cv2.ximgproc.createSuperpixelSLIC(blur, cv2.ximgproc.MSLIC, region_size=12, ruler=110.)\n retval.iterate()\n a = retval.getLabelContourMask()\n labels = retval.getLabels()\n cont =0\n for prop in regionprops(labels):\n x = int(prop.centroid[0]) + int(blur.shape[0] * 0.5)\n y = int(prop.centroid[1]) + int(blur.shape[1] * 0.5)\n top = x + height//2\n bottom = x - height//2\n right = y + width//2\n left = y - width//2\n print(image[bottom:top, left:right].shape)\n bboxes.append(image[bottom:top, left:right])\n return bboxes\n\n\"\"\"\nstandard_path = \"C:/Users/luisc/Documents/dicom-database/LCTSC/Train/\"\nstandard_template = cv2.imread(\"./outputs/standard_template1.png\", 0) #getStandardTemplate(standard_path)\n#############################GERANDO TEMPLATE INITIAL ############################\n#- O algoritmo Template Matching é executado em cada slice do volume, onde o template é o\n#template padrão definido anteriormente;\nvolume_paths = loadpath_volumes(standard_path)\nresults = list() #Armazena ps templates iniciais e indices dos respectivos slices no seu volume\nstandard_template = cv2.blur(standard_template,(5,5))\nresults = getInitialTemplates(standard_template, volume_paths)\n\n\n#Adaptando o template para cada slice\n\nresults2 = getAdaptativeTemplates(results)\n\ngetCandidatesSegmentation(\"./outputs/adaptative_templates\")\n\"\"\"\nimag = cv2.imread(\"./outputs/adaptative_templates/100.png\", 0)\nget_bounding_boxes(imag, 30, 30)\n","repo_name":"luiscarlossf/dicom-segmentation","sub_path":"adaptative-matching.py","file_name":"adaptative-matching.py","file_ext":"py","file_size_in_byte":14493,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"33396251874","text":"import turtle\n\nwi = 800\nhe = 600\nwi2 = 800/2\nhe2 = 600 /2\nmovment = 35\nball_speed = 0.45\nplayer_x_pos = wi2 - 25\n\nwindow = turtle.Screen()\nwindow.title(\"Pong Game\")\nwindow.bgcolor(\"black\")\nwindow.setup(width= wi, height = he)\nwindow.tracer(0)\n\n# score\nscore_plyr_1 = 0\nscore_plyr_2 = 0\n\n#Player 1 \nplyr_1 = turtle.Turtle()\nplyr_1.speed(0)\nplyr_1.shape(\"square\")\nplyr_1.color(\"white\")\nplyr_1.shapesize(stretch_wid=5 , stretch_len=1)\nplyr_1.penup()\nplyr_1.goto(-player_x_pos,0)\n\n#Player 2 \nplyr_2 = turtle.Turtle()\nplyr_2.speed(0)\nplyr_2.shape(\"square\")\nplyr_2.color(\"white\")\nplyr_2.shapesize(stretch_wid=5 , stretch_len=1)\nplyr_2.penup()\nplyr_2.goto(player_x_pos,0)\n\n# Ball \nball = turtle.Turtle()\nball.speed(0)\nball.shape(\"circle\")\nball.color(\"white\")\n#ball.shapesize(stretch_wid=5 , stretch_len=1)\nball.penup()\nball.goto(0,0)\nball.dx = ball_speed\nball.dy = ball_speed\n\n# Pen\npen = turtle.Turtle()\npen.speed(0)\npen.color(\"white\")\npen.penup()\npen.hideturtle()\npen.goto(0,260)\npen.write(\"Player(1): 0 Player(2): 0\" , align=\"center\",font=(\"Courier\" , 20 ,\"normal\"))\n\n# functions \ndef plyr_1_up():\n y = plyr_1.ycor()\n y += movment\n plyr_1.sety(y)\n\ndef plyr_1_dwn():\n y = plyr_1.ycor()\n y -= movment\n plyr_1.sety(y)\n\ndef plyr_2_up(): \n y = plyr_2.ycor()\n y += movment\n plyr_2.sety(y)\n\ndef plyr_2_dwn(): \n y = plyr_2.ycor()\n y -= movment\n plyr_2.sety(y)\n \n# keyboard binging\nwindow.listen()\nwindow.onkeypress(plyr_1_up,\"z\")\nwindow.onkeypress(plyr_1_dwn,\"s\")\n\nwindow.onkeypress(plyr_2_up,\"Up\")\nwindow.onkeypress(plyr_2_dwn,\"Down\")\n# main Game \nwhile True:\n window.update()\n\n # ball movment \n ball.setx(ball.xcor() + ball.dx)\n ball.sety(ball.ycor() + ball.dy)\n\n # border cheking up and down \n if ball.ycor() > (he2 -10) :\n ball.sety(he2 -10)\n ball.dy *= -1\n\n if ball.ycor() < -(he2 -10) :\n ball.sety(-(he2 -10))\n ball.dy *= -1\n \n # border cheking left and right \n if ball.xcor() > (wi2 -10):\n ball.goto(0,0)\n ball.dx *= -1\n score_plyr_1 +=1\n pen.clear()\n pen.write(\"Player(1): {} Player(2): {}\".format(score_plyr_1,score_plyr_2) , align=\"center\",font=(\"Courier\" , 20 ,\"normal\"))\n\n if ball.xcor() < -(wi2 -10):\n ball.goto(0,0)\n ball.dx *= -1\n score_plyr_2 +=1\n pen.clear()\n pen.write(\"Player(1): {} Player(2): {}\".format(score_plyr_1,score_plyr_2) , align=\"center\",font=(\"Courier\" , 20 ,\"normal\"))\n\n # Player and ball collision\n if ( ball.xcor() > (player_x_pos-10) and ball.xcor() < player_x_pos) and ( ball.ycor() < plyr_2.ycor() + 40 and ball.ycor() > plyr_2.ycor() - 40):\n ball.setx((player_x_pos-10))\n ball.dx *= -1 \n\n if ( ball.xcor() < -(player_x_pos-10) and ball.xcor() > -player_x_pos ) and ( ball.ycor() < plyr_1.ycor() + 40 and ball.ycor() > plyr_1.ycor() - 40):\n ball.setx(-(player_x_pos-10))\n ball.dx *= -1\n \n","repo_name":"labr1younes/small_projects","sub_path":"Pong Game/pong V1.py","file_name":"pong V1.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"69967249133","text":"class Node():\r\n def __init__(self,val,next = None):\r\n self.val = val\r\n self.next = next\r\n\r\nclass LinkedList():\r\n def __init__(self, first = None):\r\n self.first = first\r\n\r\n def first_returner(self):\r\n return self.first\r\n\r\n def add_to_list(self, val):\r\n if self.first == None:\r\n self.first = Node(val)\r\n else:\r\n prev = None\r\n pointer = self.first\r\n while pointer:\r\n prev = pointer\r\n pointer = pointer.next\r\n prev.next = Node(val)\r\n\r\n def print_list(self):\r\n cur = self.first\r\n while cur:\r\n print(cur.val, end = ' ')\r\n cur = cur.next\r\n print()\r\n\r\n def reverse_list(self):\r\n prev = None\r\n current = self.first\r\n while current:\r\n tmp = current.next\r\n current.next = prev\r\n prev = current\r\n current = tmp\r\n self.first = prev\r\n\r\n def increase_by_1(self):\r\n self.reverse_list()\r\n current = self.first\r\n prev = None\r\n current.val += 1\r\n over9 = False\r\n while current:\r\n if over9:\r\n current.val += 1\r\n if current.val == 10:\r\n current.val = 0\r\n over9 = True\r\n prev = current\r\n current = current.next\r\n if over9:\r\n prev.next = Node(1)\r\n self.reverse_list()\r\n\r\nLL = LinkedList()\r\nLL.add_to_list(9)\r\nLL.add_to_list(9)\r\nLL.add_to_list(9)\r\nLL.add_to_list(9)\r\nLL.add_to_list(9)\r\nLL.print_list()\r\nLL.increase_by_1()\r\nLL.print_list()","repo_name":"JakubMlocek/Introduction_to_Computer_Science","sub_path":"Cwiczenia7/zad9.py","file_name":"zad9.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"39935908120","text":"import pandas as pd\r\nfrom collections import Counter\r\nimport pygsheets\r\n\r\ngc = pygsheets.authorize(service_file=\"data-science-363622-821c1039e981.json\")\r\n\r\ndata = pd.read_csv(\"Sample data for assignment.csv\")\r\ndata.dropna()\r\n\r\n# print(data)\r\n\r\nhscodes_list = []\r\nproduct_list = []\r\nquantity_list = []\r\nunit_list = []\r\nunit_rate_list = []\r\ncurrency_list = []\r\ntotal_usd_list = []\r\n\r\nhscode_data = data[\"HS_CODE\"]\r\nduplicated_data = data[hscode_data.isin(hscode_data[hscode_data.duplicated()])].sort_values(\"HS_CODE\")\r\nduplicated_data_hscode_to_total_usd = duplicated_data.iloc[:, 1:8]\r\n\r\n# print(duplicated_data_hscode_to_total_usd)\r\n\r\nhs_code = duplicated_data_hscode_to_total_usd[\"HS_CODE\"]\r\nproducts = duplicated_data_hscode_to_total_usd[\"PRODUCT\"]\r\nquantities = duplicated_data_hscode_to_total_usd[\"QUANTITY\"]\r\nunits = duplicated_data_hscode_to_total_usd[\"UNIT\"]\r\nunit_rates = duplicated_data_hscode_to_total_usd[\"UNIT_RATE\"]\r\ncurrencies = duplicated_data_hscode_to_total_usd[\"CURRENCY\"]\r\ntotal_usd = duplicated_data_hscode_to_total_usd[\"TOTAL_USD\"]\r\n\r\nfor hscode in hs_code:\r\n hscodes_list.append(hscode)\r\n# print(hscodes_list)\r\n\r\nd = Counter(hscodes_list)\r\n# print(d)\r\n\r\nfor product in products:\r\n product_list.append(product)\r\n\r\nfor quantity in quantities:\r\n quantity_list.append(quantity)\r\n\r\nfor unit in units:\r\n unit_list.append(unit)\r\n\r\nfor unit_rate in unit_rates:\r\n unit_rate_list.append(unit_rate)\r\n\r\nfor currency in currencies:\r\n currency_list.append(currency)\r\n\r\nfor usd in total_usd:\r\n total_usd_list.append(usd)\r\n\r\nvals = 3 # [2, 3, 5, 6, 10, 11, 16, 21]\r\nkeys_list = []\r\nhscode_index_list = []\r\n\r\nfor keys, values in d.items():\r\n # for val in vals:\r\n if vals == values:\r\n keys_list.append(keys)\r\n\r\n# print(keys_list)\r\n# position = keys_list\r\n\r\nfor hscode_index in range(len(hscodes_list)):\r\n # print(hscode_index)\r\n # for key_list in keys_list:\r\n # print(key_list)\r\n if hscodes_list[hscode_index] == keys_list[0]:\r\n # print(hscodes_list[hscode_index])\r\n hscode_index_list.append(hscode_index)\r\n\r\n# print(hscode_index_list)\r\nproduct_name = []\r\nproduct_quantity = []\r\nproduct_unit = []\r\nproduct_unit_rate = []\r\nproduct_currency = []\r\nproduct_USD = []\r\nsstr_dict = {}\r\n\r\nfor index in hscode_index_list:\r\n # print(index)\r\n product_name.append(product_list[index])\r\n product_quantity.append(quantity_list[index])\r\n product_unit.append(unit_list[index])\r\n product_unit_rate.append(unit_rate_list[index])\r\n product_currency.append(currency_list[index])\r\n product_USD.append(total_usd_list[index])\r\n\r\n sstr_dict = {\r\n \"Hs Code\": keys_list[0],\r\n \"Product Name\": product_name,\r\n \"Quantity\": product_quantity,\r\n \"Unit\": product_unit,\r\n \"Unit Rate\": product_unit_rate,\r\n \"Currency\": product_currency,\r\n \"Total USD\": product_USD,\r\n }\r\n\r\n# print(sstr)\r\n#\r\n# print(sstr_dict)\r\n\r\n# for keys, values in sstr_dict.items():\r\n\r\nData = pd.DataFrame(sstr_dict)\r\nData.to_csv(\"Duplicated_data.csv\", index=False, mode=\"a\")\r\n\r\nsheet = gc.open(\"Data\")\r\n\r\nwks = sheet[0]\r\n\r\nwks.set_dataframe(Data, (1, 1))\r\n","repo_name":"karthi-keyan-kk/Kreative_Organic_Assignment","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"35438303506","text":"class Solution:\n \"\"\"\n @param numbersbers : Give an array numbersbers of n integer\n @return : Find all unique triplets in the array which gives the sum of zero.\n \"\"\"\n def threeSum(self, numbers):\n # write your code here\n numbers.sort()\n ret = []\n for i in range(0, len(numbers) - 2):\n if i > 0 and numbers[i] == numbers[i-1]:\n continue\n target = -numbers[i]\n l,r = i+1, len(numbers)-1\n while l < r:\n if numbers[l] + numbers[r] == target:\n ret.append((numbers[i],numbers[l],numbers[r]))\n l += 1\n r -= 1\n while l< r and numbers[l]==numbers[l-1]:\n l += 1\n while l< r and numbers[r] ==numbers[r+1]:\n r -= 1\n elif numbers[l] + numbers[r] < target:\n l += 1\n else:\n r -= 1\n return ret\n\n","repo_name":"umnstao/lintcode-practice","sub_path":"twoPointers/57.3SumUniqueSol.py","file_name":"57.3SumUniqueSol.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"25929917526","text":"import csv\nimport time\nimport argparse\nfrom multiprocessing import Process, Manager\n\nfrom automation.grading_metrics import collision, acceleration, speeding\n\nRECORD_DIR = '/apollo/automation/results/recorded_scenarios/'\nCSV_PATH = '/apollo/automation/oracles/file_names.txt'\n\n\ndef generate_record_name(generation_num: int, scenario_num: int):\n return f'{generation_num}_{scenario_num}.00000'\n\n\ndef run_oracles(record_path):\n processes = []\n manager = Manager()\n return_dict = manager.dict()\n\n processes.append(\n Process(target=acceleration.walk_messages,\n args=(record_path, 4),\n kwargs={'return_dict': return_dict}))\n processes.append(\n Process(target=acceleration.walk_messages,\n args=(record_path, -4),\n kwargs={'return_dict': return_dict}))\n processes.append(\n Process(target=collision.walk_messages,\n args=(record_path,),\n kwargs={'return_dict': return_dict}))\n processes.append(\n Process(target=speeding.walk_messages,\n args=(record_path,),\n kwargs={'return_dict': return_dict}))\n\n for process in processes:\n process.start()\n\n for process in processes:\n process.join()\n\n accl = return_dict['accl']\n hardbreak = return_dict['hardbreak']\n min_dist = return_dict['min_dist']\n min_speed = return_dict['min_speed']\n traveled_lanes = return_dict['traveled_lanes']\n boundary_dist = return_dict['boundary_dist']\n\n return min_dist, traveled_lanes, min_speed, boundary_dist, accl, hardbreak\n\n\ndef main():\n paths = list()\n print('Reading the record description...')\n with open(CSV_PATH) as file:\n reader = csv.reader(file)\n for row in reader:\n record_name = generate_record_name(row[0], row[1])\n paths.append(RECORD_DIR + record_name)\n\n print('Running the oracles...')\n with open('/apollo/automation/oracles/oracle_output.csv', mode='w') as output_file:\n output_writer = csv.writer(\n output_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n output_writer.writerow(\n ['record_name', 'Speeding', 'FastAccel', 'HardBraking'])\n\n record_count = len(paths)\n for i, oracle_path in enumerate(paths):\n start_time = time.time()\n # if i % int(record_count / 10) == 0:\n # print(f'{int(i/record_count)}% finished')\n print(\n f'Running the {i+1}/{record_count} record ({oracle_path})', end=',\\t')\n min_dist, traveled_lanes, min_speed, boundary_dist, accl, hardbreak = run_oracles(\n oracle_path)\n # output_writer.writerow([oracle_path, min_speed, accl, hardbreak])\n end_time = time.time()\n output_writer.writerow([end_time, oracle_path])\n print(f'finished in {end_time-start_time} seconds.')\n\n\nif __name__ == '__main__':\n init_time = time.time()\n main()\n end_time = time.time()\n print(f'run_oracles finished in {end_time-init_time} seconds')\n","repo_name":"Software-Aurora-Lab/scenoRITA","sub_path":"grading_metrics/run_oracles.py","file_name":"run_oracles.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"55"} +{"seq_id":"34189839534","text":"from utils import Token_Type\nfrom utils import ExprNode\nfrom utils import syntax_error\nfrom Lexer import Lexer\nfrom utils import set_param, get_param, change_param\nimport math\nimport matplotlib.pyplot as plt\n\n# global\nOrigin_x = 0.0\nOrigin_y = 0.0\nRot_ang = 0.0\nScale_x = 1\nScale_y = 1\nColor = 'BLACK'\n\n\ndef set_origin(x, y):\n global Origin_x, Origin_y\n Origin_x = x\n Origin_y = y\n print(\"^^^^^^^^^^^Set Origin^^^^^^^^^^^^\")\n print(str(Origin_x) + ' ' + str(Origin_y))\n\n\ndef set_scale(x, y):\n global Scale_x, Scale_y\n Scale_x = x\n Scale_y = y\n print(\"^^^^^^^^^^^Set Scale^^^^^^^^^^^^\")\n print(str(Scale_x) + ' ' + str(Scale_y))\n\n\ndef set_rot(x):\n global Rot_ang\n Rot_ang = x\n print(\"^^^^^^^^^^^Set Rot^^^^^^^^^^^^\")\n print(str(Rot_ang))\n\n\ndef set_color(x):\n global Color\n Color = x\n print(\"^^^^^^^^^^^Set Color^^^^^^^^^^^^\")\n print(Color)\n\n\n# get the value of expression\n# dfs\ndef get_expr_value(root):\n if root is None:\n return 0.0\n if root.type == Token_Type.PLUS.name:\n return float(get_expr_value(root.left)) + float(get_expr_value(root.right))\n elif root.type == Token_Type.MINUS.name:\n return float(get_expr_value(root.left)) - float(get_expr_value(root.right))\n elif root.type == Token_Type.MUL.name:\n return float(get_expr_value(root.left)) * float(get_expr_value(root.right))\n elif root.type == Token_Type.DIV.name:\n return float(get_expr_value(root.left)) / float(get_expr_value(root.right))\n elif root.type == Token_Type.FUNC.name:\n return float(root.func(get_expr_value(root.left)))\n elif root.type == Token_Type.CONST_ID.name:\n return float(root.value)\n elif root.type == Token_Type.T.name:\n return float(root.get_param())\n return 0.0\n\n\n# calculate (x, y) after transformation\ndef cal_coord(x_ptr, y_ptr):\n global Origin_x, Origin_y, Scale_x, Scale_y\n x = get_expr_value(x_ptr)\n y = get_expr_value(y_ptr)\n # scaling\n x *= Scale_x\n y *= Scale_y\n # rotation\n temp = x * math.cos(Rot_ang) + y * math.sin(Rot_ang)\n y = y * math.cos(Rot_ang) - x * math.sin(Rot_ang)\n x = temp\n # translation\n x += Origin_x\n y += Origin_y\n return x, y\n\n\n# draw the pic dot by dot\ndef draw_loop(start, end, step, x_ptr, y_ptr):\n global Color\n set_param(start)\n while get_param() <= end:\n x, y = cal_coord(x_ptr, y_ptr)\n if Color == 'RED':\n plt.plot(x, y, 'r.')\n elif Color == 'GREEN':\n plt.plot(x, y, 'g.')\n elif Color == 'BLUE':\n plt.plot(x, y, 'b.')\n else:\n plt.plot(x, y, 'k.')\n change_param(step)\n\n\ndef close_scanner():\n print(\"Close scanner\")\n\n\n# print the syntax tree\ndef print_tree(root):\n if root is not None:\n root.show()\n print(\"left_child: \")\n print_tree(root.left)\n print(\"right_child: \")\n print_tree(root.right)\n\n\nclass Parser:\n def __init__(self, filename):\n self.lexer = Lexer(filename)\n self.token = None\n self.root = None\n\n def start(self):\n print(\"-----Enter Start-----\")\n self.lexer.start()\n self.fetch_token()\n self.program()\n close_scanner()\n print(\"-----Exit Start-----\")\n\n # get one token\n def fetch_token(self):\n print(\"-----Enter FetchToken-----\")\n self.token = self.lexer.gettoken()\n if self.token.type == Token_Type.ERRTOKEN.name:\n syntax_error(1)\n # skip comment\n if self.token.type == Token_Type.COMMENT.name:\n self.fetch_token()\n print(\"-----Exit FetchToken-----\")\n\n def match_token(self, ob):\n print(\"-----Enter MatchToken-----\")\n if self.token.type != ob:\n syntax_error(2, sb=self.token.type, ob=ob)\n print(\"-----Exit MatchToken-----\")\n return False\n print(\"*****MatchToken \" + ob + \"*****\")\n print(\"-----Exit MatchToken-----\")\n return True\n\n def program(self):\n print(\"-----Enter Program-----\")\n while self.token.type != Token_Type.NONTOKEN.name:\n self.statement()\n # end with ';'\n self.match_token(Token_Type.SEMICO.name)\n self.fetch_token()\n print(\"-----Exit Program-----\")\n\n def statement(self):\n print(\"-----Enter Statement-----\")\n if self.token.type == Token_Type.ORIGIN.name:\n self.origin_statement()\n elif self.token.type == Token_Type.SCALE.name:\n self.scale_statement()\n elif self.token.type == Token_Type.ROT.name:\n self.rot_statement()\n elif self.token.type == Token_Type.FOR.name:\n self.for_statement()\n elif self.token.type == Token_Type.COLOR.name:\n self.color_statement()\n else:\n syntax_error(3)\n print(\"-----Exit Statement-----\")\n\n def origin_statement(self):\n print(\"-----Enter OriginStatement-----\")\n self.match_token(Token_Type.ORIGIN.name)\n self.fetch_token()\n self.match_token(Token_Type.IS.name)\n self.fetch_token()\n self.match_token(Token_Type.L_BRACKET.name)\n self.fetch_token()\n tmp_ptr = self.expression()\n print(\"--------------------------------------------------\")\n print_tree(tmp_ptr)\n print(\"--------------------------------------------------\")\n\n x = get_expr_value(tmp_ptr)\n\n self.match_token(Token_Type.COMMA.name)\n self.fetch_token()\n tmp_ptr = self.expression()\n print(\"--------------------------------------------------\")\n print_tree(tmp_ptr)\n print(\"--------------------------------------------------\")\n\n y = get_expr_value(tmp_ptr)\n\n self.match_token(Token_Type.R_BRACKET.name)\n self.fetch_token()\n\n set_origin(x, y)\n\n print(\"-----Exit OriginStatement-----\")\n\n def scale_statement(self):\n print(\"-----Enter ScaleStatement-----\")\n self.match_token(Token_Type.SCALE.name)\n self.fetch_token()\n self.match_token(Token_Type.IS.name)\n self.fetch_token()\n self.match_token(Token_Type.L_BRACKET.name)\n self.fetch_token()\n tmp_ptr = self.expression()\n print(\"--------------------------------------------------\")\n print_tree(tmp_ptr)\n print(\"--------------------------------------------------\")\n\n x = get_expr_value(tmp_ptr)\n\n self.match_token(Token_Type.COMMA.name)\n self.fetch_token()\n tmp_ptr = self.expression()\n print(\"--------------------------------------------------\")\n print_tree(tmp_ptr)\n print(\"--------------------------------------------------\")\n\n y = get_expr_value(tmp_ptr)\n\n self.match_token(Token_Type.R_BRACKET.name)\n self.fetch_token()\n\n set_scale(x, y)\n\n print(\"-----Exit ScaleStatement-----\")\n\n def rot_statement(self):\n print(\"-----Enter RotStatement-----\")\n self.match_token(Token_Type.ROT.name)\n self.fetch_token()\n self.match_token(Token_Type.IS.name)\n self.fetch_token()\n tmp_ptr = self.expression()\n print(\"--------------------------------------------------\")\n print_tree(tmp_ptr)\n print(\"--------------------------------------------------\")\n\n x = get_expr_value(tmp_ptr)\n\n # self.fetch_token()\n\n set_rot(x)\n print(\"-----Exit RotStatement-----\")\n\n def for_statement(self):\n print(\"-----Enter ForStatement-----\")\n self.match_token(Token_Type.FOR.name)\n self.fetch_token()\n self.match_token(Token_Type.T.name)\n self.fetch_token()\n self.match_token(Token_Type.FROM.name)\n self.fetch_token()\n start_ptr = self.expression()\n print(\"--------------------------------------------------\")\n print_tree(start_ptr)\n print(\"--------------------------------------------------\")\n\n start = get_expr_value(start_ptr)\n\n self.match_token(Token_Type.TO.name)\n self.fetch_token()\n end_ptr = self.expression()\n print(\"--------------------------------------------------\")\n print_tree(end_ptr)\n print(\"--------------------------------------------------\")\n\n end = get_expr_value(end_ptr)\n\n self.match_token(Token_Type.STEP.name)\n self.fetch_token()\n step_ptr = self.expression()\n print(\"--------------------------------------------------\")\n print_tree(step_ptr)\n print(\"--------------------------------------------------\")\n\n step = get_expr_value(step_ptr)\n\n self.match_token(Token_Type.DRAW.name)\n self.fetch_token()\n self.match_token(Token_Type.L_BRACKET.name)\n self.fetch_token()\n x_ptr = self.expression()\n print(\"--------------------------------------------------\")\n print_tree(x_ptr)\n print(\"--------------------------------------------------\")\n self.match_token(Token_Type.COMMA.name)\n self.fetch_token()\n y_ptr = self.expression()\n print(\"--------------------------------------------------\")\n print_tree(y_ptr)\n print(\"--------------------------------------------------\")\n self.match_token(Token_Type.R_BRACKET.name)\n self.fetch_token()\n\n draw_loop(start, end, step, x_ptr, y_ptr)\n\n print(\"-----Exit ForStatement-----\")\n\n def color_statement(self):\n print(\"-----Enter ColorStatement-----\")\n self.match_token(Token_Type.COLOR.name)\n self.fetch_token()\n self.match_token(Token_Type.IS.name)\n self.fetch_token()\n self.match_token(Token_Type.SP_COLOR.name)\n\n set_color(self.token.lexeme)\n\n self.fetch_token()\n print(\"-----Exit ColorStatement-----\")\n\n def expression(self):\n print(\"-----Enter Expression-----\")\n left = self.term()\n while self.token.type == Token_Type.PLUS.name or self.token.type == Token_Type.MINUS.name:\n token_tmp = self.token.type\n self.match_token(token_tmp)\n right = self.term()\n left = ExprNode(token_tmp, lnode=left, rnode=right)\n print(\"-----Exit Expression-----\")\n return left\n\n def term(self):\n print(\"-----Enter Term-----\")\n left = self.factor()\n while self.token.type == Token_Type.MUL.name or self.token.type == Token_Type.DIV.name:\n token_tmp = self.token.type\n self.match_token(token_tmp)\n self.fetch_token()\n right = self.factor()\n left = ExprNode(token_tmp, lnode=left, rnode=right)\n print(\"-----Exit Term-----\")\n return left\n\n def factor(self):\n print(\"-----Enter Factor-----\")\n if self.token.type == Token_Type.PLUS.name or self.token.type == Token_Type.MINUS.name:\n token_tmp = self.token.type\n self.match_token(token_tmp)\n left = ExprNode(Token_Type.CONST_ID.name, 0)\n self.fetch_token()\n right = self.factor()\n res = ExprNode(token_tmp, lnode=left, rnode=right)\n print(\"-----Exit Factor-----\")\n return res\n else:\n res = self.component()\n print(\"-----Exit Factor-----\")\n return res\n\n def component(self):\n print(\"-----Enter Component-----\")\n left = self.atom()\n self.fetch_token()\n while self.token.type == Token_Type.POWER.name:\n token_tmp = self.token.type\n self.match_token(token_tmp)\n self.fetch_token()\n right = self.component()\n left = ExprNode(token_tmp, lnode=left, rnode=right)\n print(\"-----Exit Component-----\")\n return left\n\n def atom(self):\n print(\"-----Enter Atom-----\")\n if self.token.type == Token_Type.CONST_ID.name:\n print(\"leaf: \" + str(self.token.value))\n print(\"-----Exit Atom-----\")\n return ExprNode(self.token.type, self.token.value) # leaf\n elif self.token.type == Token_Type.T.name:\n print(\"leaf: \" + self.token.type)\n print(\"-----Exit Atom-----\")\n return ExprNode(self.token.type, self.token.value) # leaf\n elif self.token.type == Token_Type.FUNC.name:\n token_tmp = self.token.type\n func_tmp = self.token.func\n self.fetch_token()\n self.match_token(Token_Type.L_BRACKET.name)\n self.fetch_token()\n left = self.expression()\n self.match_token(Token_Type.R_BRACKET.name)\n print(\"-----Exit Atom-----\")\n return ExprNode(token_tmp, lnode=left, func=func_tmp)\n elif self.token.type == Token_Type.L_BRACKET:\n self.match_token(Token_Type.L_BRACKET.name)\n self.fetch_token()\n left = self.expression()\n self.match_token(Token_Type.R_BRACKET.name)\n print(\"-----Exit Atom-----\")\n return left\n\n\nif __name__ == '__main__':\n # init the parser\n p = Parser(\"test.txt\")\n # run the parser\n p.start()\n\n plt.xlim(0)\n plt.ylim(0)\n plt.show()\n","repo_name":"AidenFan/Simple-Interpreter","sub_path":"Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":13164,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"302658682","text":"#%% \r\nimport sdre\r\nfrom sdre.helper import *\r\nfrom sdre.estimators import dual\r\nfrom scipy import stats\r\nfrom scipy import io\r\n\r\nfrom autograd.numpy import *\r\nfrom matplotlib import pyplot as plt\r\n\r\nfrom multiprocessing import Pool\r\nfrom time import time\r\n\r\nd = 20\r\nn = 250\r\ndTheta = d-5\r\n\r\n#%%\r\n# Unnormalized density parameterized by theta\r\nlogpBar = lambda x,theta:-sum(x**2, 0) / 2 + \\\r\n sum(reshape(theta,[dTheta,1])*ones([dTheta,1])*tanh(x[:dTheta,:]),0)\r\n# f in Stein feature\r\nf = lambda X: vstack([tanh(X)])\r\nb = d\r\n\r\n#%% Show asymptotic distribution of Log-likelihood\r\ndef infer(seed): \r\n # Generate Dataset\r\n random.seed(seed)\r\n XData = random.standard_normal((d, n))\r\n # infer model parameters\r\n delta_dua,theta_dua,LL,TfData = dual(logpBar, f, XData, theta=zeros(dTheta))\r\n\r\n print(seed, 'log likelihood',LL)\r\n return LL\r\n\r\nif __name__ == '__main__':\r\n # LL = infer(0)\r\n # LL = 2*array(list(map(infer, range(20))))\r\n\r\n start = time()\r\n # if you want to be parallel...\r\n ncores = getThreads(); print('number of threads,', ncores)\r\n LL = 2*array(list(Pool(ncores).map(infer, range(10000))))\r\n print('elapsed:', time() - start)\r\n \r\n # output results to matlab file\r\n io.savemat('LL.mat',{'LL':LL}) \r\n\r\n # plot results \r\n res = stats.probplot(LL,dist=stats.chi2, sparams=(d-dTheta,), plot=plt)\r\n plt.show()","repo_name":"anewgithubname/Stein-Density-Ratio-Estimation","sub_path":"script/Inference/demo_Chi2.py","file_name":"demo_Chi2.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"55"} +{"seq_id":"43734745076","text":"import sys\nfrom heapq import heappush, heappop\nInput = sys.stdin.readline\nnodes, edges = map(int, Input().split())\nroot = [-1] * (nodes + 1)\npq = []\n\n\ndef initialize():\n for _ in range(edges):\n a, b, c = map(int, Input().split())\n heappush(pq, (c, a, b)) # cost, start, end\n\n\ndef find(a):\n if root[a] < 0:\n return a\n root[a] = find(root[a])\n return root[a]\n\n\ndef union(a, b):\n root_a = find(a)\n root_b = find(b)\n\n if root_a == root_b:\n return False\n if root_a > root_b:\n root_a, root_b = root_b, root_a\n\n root[root_a] += root[root_b]\n root[root_b] = root_a\n return True\n\n\ndef operate():\n ans = 0\n used_edge = 0\n while used_edge != nodes - 1:\n c, s, e = heappop(pq)\n if union(s, e):\n ans += c\n used_edge += 1\n print(ans)\n\n\ninitialize()\noperate()","repo_name":"shinjh0305-jhshin/Algorithm_python","sub_path":"[1197]최소 스패닝 트리.py","file_name":"[1197]최소 스패닝 트리.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"74959041770","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef difference_equation(x):\n N = x.size\n y = np.zeros(N)\n NUM_TERMS = 5\n\n for n in range(N):\n for i in range(NUM_TERMS):\n if n - i >= 0:\n y[n] += x[n - i] / NUM_TERMS\n return y\n\n\ndef frequency_response(a, b, omega):\n N = a.size\n M = b.size\n bsum = 0\n asum = 0\n for m in range(M):\n bsum += b[m] * np.exp(-1j * omega * m)\n for n in range(1, N):\n asum += a[n] * np.exp(-1j * omega * n)\n h = bsum / (asum + 1)\n\n return h\n\n\nN = 100\na = np.zeros(N)\na[0] = 1\nb = difference_equation(a)\n\nfs = 16000\nf = np.arange(N) / N * fs\nomega = 2 * np.pi * f / fs\nH = np.zeros(N, dtype=complex)\nfor i in range(N):\n H[i] = frequency_response(a, b, omega[i])\n\nplt.subplot(2, 1, 1)\nplt.plot(omega, np.abs(H))\nplt.subplot(2, 1, 2)\nplt.plot(omega, np.angle(H))\nplt.show()\n","repo_name":"onolab-tmu/asp-tutorial-2023","sub_path":"eimamura/chapter03/q09.py","file_name":"q09.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"55"} +{"seq_id":"3491379242","text":"import requests\n\nfrom Scraper import Scraper\n\nsend_data_url = 'https://pythonapp.ir/api/add'\nget_data_url = 'https://pythonapp.ir/api/get'\n\n\ndef get_data(number):\n request = requests.get(url=get_data_url + '?number={}'.format(str(number)))\n try:\n return request.json()\n except:\n return request.text\n\n\ndef send_data(application_name,\n category_the_app_belongs,\n overall_user_rating_of_the_app,\n number_of_user_reviews_for_the_app,\n size_of_the_app,\n number_of_user_downloads_installs_for_the_app,\n paid_or_free,\n price_of_the_app,\n age_group_the_app_is_targeted_at_children_mature_adult,\n an_app_can_belong_to_multiple_genres):\n data = {\n 'application_name': str(application_name),\n 'category_the_app_belongs': str(category_the_app_belongs),\n 'overall_user_rating_of_the_app': str(overall_user_rating_of_the_app),\n 'number_of_user_reviews_for_the_app': str(number_of_user_reviews_for_the_app),\n 'size_of_the_app': str(size_of_the_app),\n 'number_of_user_downloads_installs_for_the_app': str(number_of_user_downloads_installs_for_the_app),\n 'paid_or_free': str(paid_or_free),\n 'price_of_the_app': str(price_of_the_app),\n 'age_group_the_app_is_targeted_at_children_mature_adult': str(\n age_group_the_app_is_targeted_at_children_mature_adult),\n 'an_app_can_belong_to_multiple_genres': str(an_app_can_belong_to_multiple_genres),\n\n }\n request = requests.post(url=send_data_url, data=data)\n try:\n return request.json()\n except:\n return request.text\n\n\ndef call_send(number: int):\n sc = Scraper()\n sc.scraper(number=number)\n sc.driver.close()\n for key, value in sc.data.items():\n print(\n send_data(\n application_name=str(key),\n category_the_app_belongs=str(value[0]),\n overall_user_rating_of_the_app=str(value[1]),\n number_of_user_reviews_for_the_app=str(value[2]),\n size_of_the_app=str(value[3]),\n number_of_user_downloads_installs_for_the_app=str(value[4]),\n paid_or_free=str(value[5]),\n price_of_the_app=str(value[6]),\n age_group_the_app_is_targeted_at_children_mature_adult=str(value[7]),\n an_app_can_belong_to_multiple_genres=str(value[8]),\n )\n )\n print(key, value)\n\n\ndef call_get(number: int):\n print(\n get_data(\n number=str(number)\n )\n )\n\n\nif __name__ == \"__main__\":\n call_send(1)\n call_get(0)\n","repo_name":"zahrashirazi/SWESEMNAN","sub_path":"WebScraper/Core.py","file_name":"Core.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"22883374042","text":"'''\nProgram Name: Lab04busenium.py\nClass: ENSE496AD Machine Learning\n\nName: Mckenzie Busenius\nSID: 200378076\n\nProfessor: Dr. Kin-Choong Yow\nLab Professor: Usman Munawar\n\nDescription: Implementation of the algorithm, Support Vector Machine. Then we are apply it\n to two different datasets, Breast Cancer Wisconsin and Titanic Dataset.\n\nAcknowledgments:\n [1] https://towardsdatascience.com/svm-implementation-from-scratch-python-2db2fc52e5c2#66a2\n\n'''\nimport pandas as pd\nimport numpy as np\nimport warnings\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nimport random as rd\nfrom copy import deepcopy\n\nfrom sklearn.metrics import confusion_matrix,accuracy_score, recall_score\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split as tts\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import normalize\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import accuracy_score, log_loss\nfrom sklearn import linear_model\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegressionCV\nfrom sklearn.utils import shuffle\nimport sys,os\n# import seaborn as sns\n# %matplotlib inline\n\n\n################################################################\n# Problem 1: Breast Cancer Wisconsin Dataset #\n# #\n# Description: Predict whether the cancer isbenign or #\n# malignant #\n################################################################\n'''\nPart A: Dataset ‘breast-cancer-wisconsin-data’ is given in the assignment\n pack. Load the dataset in dataframe.\n'''\nbreast_Cancer_df = pd.read_csv('breast-cancer-wisconsin-data.csv', low_memory=False)\n\n\n'''\nPart B: Inspect loaded dataframe using describe (), Head() and Info().\n'''\n#breast_Cancer_Dataframe.info()\n'''\n Dataset Info:\n 69 entries\n 33 Colunms\n Range = 0 to 568\n'''\nbreast_Cancer_df.describe()\n\n\n'''\nPart C: Split the train and test sets with ratio 60:40\n'''\ndiagnosis_map = {'M':1, 'B':-1}\nbreast_Cancer_df['diagnosis'] = breast_Cancer_df['diagnosis'].map(diagnosis_map)\nbreast_Cancer_df.drop(breast_Cancer_df.columns[[-1, 0]], axis=1, inplace=True)\n\nY = breast_Cancer_df.loc[:, 'diagnosis']\nX = breast_Cancer_df.iloc[:, 1:]\n\nX_normalized = MinMaxScaler().fit_transform(X.values)\nX = pd.DataFrame(X_normalized)\n\nX.insert(loc=len(X.columns), column='intercept', value=1)\n\nprint(\"splitting dataset into train and test sets...\")\nX_train, X_test, y_train, y_test = tts(X, Y, test_size=0.4, random_state=42)\n\n\n'''\nPart D: Define the Cost function which take Weight, Input(X) and Output(Y).\n\nFunction Name: cost_function\nParameters: Weight(w), Input(x), Output(Y)\nDescription: Also known as as the Objective Function. We use this function to try and\n maximize to acheive our objective.\n\nReturns: weight\n'''\ndef cost_function(W, X, Y):\n c = 10000\n # # calculate hinge loss\n # N = X.shape[0]\n # distances = 1 - Y * (np.dot(X, W))\n # distances[distances < 0] = 0 # equivalent to max(0, distance)\n # hinge_loss = c * (np.sum(distances) / N)\n\n # # calculate cost\n # cost = 1 / 2 * np.dot(W, W) + hinge_loss\n\n N = X.shape[0]\n distances = 1 - Y * (np.dot(X, W))\n distances[distances < 0] = 0 # equivalent to max(0, distance)\n hinge_loss = c * (np.sum(distances) / N)\n\n # calculate cost\n cost = 1 / 2 * np.dot(W, W) + hinge_loss\n return cost\n\n return cost\n\n'''\nPart E: Define the gradient of cost function.\n\nFunction Name: gradient_cost\nParameters: Weight(w), Input(x), Output(Y)\nDescription: Calculates the gradient cost function\n\nReturns: gradient cost\n'''\ndef gradient_cost(W, X_batch, Y_batch):\n c = 10000\n # N = x.shape[0]\n\n # distances = 1 - y * (np.dot(x, w))\n # dw = np.zeros(len(w))\n\n # for ind, d in enumerate(distances):\n # if max(0, d) == 0:\n # di = w\n # else:\n # di = w - (c * y[ind] * x[ind])\n # dw += di\n\n # return dw\n\n # if only one example is passed (eg. in case of SGD)\n if type(Y_batch) == np.float64:\n Y_batch = np.array([Y_batch])\n X_batch = np.array([X_batch])\n distance = 1 - (Y_batch * np.dot(X_batch, W))\n dw = np.zeros(len(W))\n\n if max(0, distance) == 0:\n dw += W\n else:\n dw += W - (c * Y_batch * X_batch)\n\n return dw\n\n'''\nPart F: Define function for Stochastic Gradient Decent and set the stopping conditions.\n\nFunction Name: stochastic_gradient_decent\nParameters: features, outputs\nDescription: Calculates the stochastic gradient bases the stoppage criteria of when the current\n cost hasent decreased much as compares to the previous cost.\n\nReturns: weights\n'''\ndef stochastic_gradient_decent(features, outputs):\n max_epochs = 5000\n weights = np.zeros(features.shape[1])\n n = 0\n learning_rate = 0.000001\n\n # previous_cost = float(\"inf\")\n # cost_threshold = 0.01\n\n # for epoch in range(max_epochs):\n # X, Y = shuffle(features, outputs)\n\n # for x in enumerate(X):\n # ascent = gradient_cost(weights, X, Y)\n # wights = weights - (learning_rate * ascent)\n\n # if epoch == 2 ** n or epoch == max_epochs - 1:\n # cost = cost_function(weights, features, outputs)\n # print(\"Epoch is: {} and cost is: {}\".format(epoch, cost))\n\n # if abs (previous_cost - cost) < cost_threshold * previous_cost:\n # return weights\n\n # previous_cost = cost\n # n = 1 + n\n\n weights = np.zeros(features.shape[1])\n nth = 0\n prev_cost = float(\"inf\")\n cost_threshold = 0.01\n\n # stochastic gradient descent\n for epoch in range(1, max_epochs):\n # shuffle to prevent repeating update cycles\n X, Y = shuffle(features, outputs)\n for ind, x in enumerate(X):\n ascent = gradient_cost(weights, x, Y[ind])\n weights = weights - (learning_rate * ascent)\n\n # convergence check on 2^nth epoch\n if epoch == 2 ** nth or epoch == max_epochs - 1:\n cost = cost_function(weights, features, outputs)\n print(\"Epoch is:{} and Cost is: {}\".format(epoch, cost))\n # stoppage criterion\n if abs(prev_cost - cost) < cost_threshold * prev_cost:\n return weights\n prev_cost = cost\n nth += 1\n\n return weights\n\n\n\n#######################################################################\n# Problem 2: Titanic Dataset #\n# #\n# Description: Predict the passenger is survived or not #\n#######################################################################\n\n## Pre-processing Taken from given file.\ntraining_data = pd.read_csv('train.csv')\ntest_data = pd.read_csv('test.csv')\ntraining_data.sample(5)\n\ntraining_data.describe()\ndef simplify_ages(df):\n df.Age = df.Age.fillna(-0.5)\n bins = (-1, 0, 5, 12, 18, 25, 35, 60, 120)\n group_names = ['Unknown', 'Baby', 'Child', 'Teenager', 'Student', 'Young Adult', 'Adult', 'Senior']\n categories = pd.cut(df.Age, bins, labels=group_names)\n df.Age = categories\n return df\n\ndef simplify_cabins(df):\n df.Cabin = df.Cabin.fillna('N')\n df.Cabin = df.Cabin.apply(lambda x: x[0])\n return df\n\ndef simplify_fares(df):\n df.Fare = df.Fare.fillna(-0.5)\n bins = (-1, 0, 8, 15, 31, 1000)\n group_names = ['Unknown', '1_quartile', '2_quartile', '3_quartile', '4_quartile']\n categories = pd.cut(df.Fare, bins, labels=group_names)\n df.Fare = categories\n return df\n\ndef format_name(df):\n df['Lname'] = df.Name.apply(lambda x: x.split(' ')[0])\n df['NamePrefix'] = df.Name.apply(lambda x: x.split(' ')[1])\n return df\n\ndef drop_features(df):\n return df.drop(['Ticket', 'Name', 'Embarked'], axis=1)\n\ndef transform_features(df):\n df = simplify_ages(df)\n df = simplify_cabins(df)\n df = simplify_fares(df)\n df = format_name(df)\n df = drop_features(df)\n return df\n\ntransformed_train = transform_features(training_data)\ntransformed_train.head()\n\ntest_data.sample(5)\n\ntransformed_test = transform_features(test_data)\ntransformed_test.head()\n\nfrom sklearn import preprocessing\ndef encode_features(df_train, df_test):\n features = ['Fare', 'Cabin', 'Age', 'Sex', 'Lname', 'NamePrefix']\n df_combined = pd.concat([df_train[features], df_test[features]])\n\n for feature in features:\n le = preprocessing.LabelEncoder()\n le = le.fit(df_combined[feature])\n df_train[feature] = le.transform(df_train[feature])\n df_test[feature] = le.transform(df_test[feature])\n return df_train, df_test\n\ndata_train, data_test = encode_features(transformed_train, transformed_test)\ndata_train.head()\ndata_test.head()\n\nX_Train_Titanic = data_train.drop(['Survived'], axis=1)\nY_Train_Titanic = data_train.Survived\nX_Test_Titanic = data_test\nY_Test_Titanic = data_train.Survived\n\n\n\n#######################################################################\n# Main Program #\n# ### PART 2: SVM Implementation ### #\n#######################################################################\ndef main():\n\n ### Question 1: Predict whether the cancer is benign or malignant\n #Titianic Dataset Information\n # '''\n # X_train\n # X_test\n # y_train\n # y_test\n # '''\n print(\"Training Started...\")\n W = stochastic_gradient_decent(X_train.to_numpy(), y_train.to_numpy())\n print(\"Training Finished.\")\n print(\"Weights are: {}\".format(W))\n\n y_test_predicted = np.array([])\n\n for i in range(X_test.shape[0]):\n yp = np.sign(np.dot(W, X_test.to_numpy()[i]))\n y_test_predicted = np.append(y_test_predicted, yp)\n\n print(\"accuracy on test dataset: {}\".format(accuracy_score(y_test.to_numpy(), y_test_predicted)))\n print(\"recall on test dataset: {}\".format(recall_score(y_test.to_numpy(), y_test_predicted)))\n print(\"precision on test dataset: {}\".format(recall_score(y_test.to_numpy(), y_test_predicted)))\n print(\"\")\n print(\"\")\n print(\"\")\n print(\"\")\n\n\n ## Question 2: Predict the passenger is survived or not.\n #Titianic Dataset Information\n '''\n data_train\n data_test\n X_Train_Titanic = data_train.drop(['Survived'], axis=1)\n Y_Train_Titanic = data_train.Survived\n X_Test_Titanic = data_test\n Y_Test_Titanic = data_train.Survived\n '''\n print(\"Titanic Training Started...\")\n tW = stochastic_gradient_decent(X_Train_Titanic.to_numpy(), Y_Train_Titanic.to_numpy())\n print(\"Training Finished.\")\n print(\"Weights are: {}\".format(tW))\n\n y_test_predicted_titanic = np.array([])\n\n for i in range(X_Test_Titanic.shape[0]):\n yp = np.sign(np.dot(tW, X_Test_Titanic.to_numpy()[i]))\n y_test_predicted_titanic = np.append(y_test_predicted_titanic, yp)\n\n print(\"accuracy on test dataset: {}\".format(accuracy_score(Y_Test_Titanic.to_numpy(), y_test_predicted_titanic)))\n print(\"recall on test dataset: {}\".format(recall_score(Y_Test_Titanic.to_numpy(), y_test_predicted_titanic)))\n print(\"precision on test dataset: {}\".format(recall_score(Y_Test_Titanic.to_numpy(), y_test_predicted_titanic)))\n\nmain()\n","repo_name":"macbusenius/Artificial_Intelligence","sub_path":"Machine Learning/04 - Support Vector Machine/Lab04busenium.py","file_name":"Lab04busenium.py","file_ext":"py","file_size_in_byte":11528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"30835829234","text":"\nimport pandas as pd\nfrom bs4 import BeautifulSoup as bs\nfrom selenium import webdriver\nimport time\n\nchromedriver_path = \"/usr/bin/chromedriver\"\ndomain = \"https://www.morizon.pl\"\n\n\"\"\"\nCreate a general class for scraping a page.\nReturns: a soup object (an entire html)\n\"\"\"\n\n\"\"\"\ndef get_html(url):\n driver = webdriver.Chrome(chromedriver_path)\n driver.get(url)\n time.sleep(5)\n html = driver.page_source\n time.sleep(10)\n soup = bs(html, \"html.parser\")\n return soup\n\"\"\"\n\n\"\"\"\nGet urls of all ads we would like to scrape.\nArguments to pass: a path with a query (filters)\nReturns: a set of links with ads of interest.\n\"\"\"\n\n\"\"\"\ndef get_ads_urls_set(path_with_filters):\n main_page_html = get_html(path_with_filters)\n all_offers_html = main_page_html.find_all(\"a\", {\"class\": \"offer__outer\"})\n offers_paths_set = set()\n for i in all_offers_html:\n link = i['href']\n full_url = domain + link\n offers_paths_set.add(full_url)\n return offers_paths_set\n\"\"\"\n\n\"\"\"\nA function for a single ad. Should be in a loop.\n\"\"\"\n\n\ndef get_single_offer(offer):\n adv_html = get_html(offer)\n description_html = adv_html.find_all(\"div\", {\"class\": \"basic-info\"})\n detailed_info_html = adv_html.find_all(\n \"div\", {\"class\": \"detailed-information\"})\n new_df = pd.DataFrame({'link': [offer], 'description': [\n description_html[0]], 'detailed_info': [detailed_info_html[0]]})\n return new_df\n # do smth to get all needed data\n # put it into a df\n # get next ad\n\n\n\"\"\"\nLoop through ads of interest, scrape each one of them.\nArguments to pass: a set of urls.\nReturns: a df with info.\n\"\"\"\n\n\ndef get_data_for_regex(offers_paths_set):\n # ads_df = pd.DataFrame(columns=['link', 'price', 'location', 'rooms_meters', 'description', 'detailed_info'])\n ads_df = pd.DataFrame(columns=['link', 'description', 'detailed_info'])\n for i in offers_paths_set:\n new_df = get_single_offer(i)\n ads_df = ads_df.append(new_df, ignore_index=True)\n return ads_df\n","repo_name":"khralovich/real_estate_scraper","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"22330476822","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 ('main', '0045_role_commit_created'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='role',\n name='min_ansible_container_version',\n field=models.CharField(max_length=10, null=True, verbose_name=b'Min Ansible Container Version', blank=True),\n ),\n migrations.AlterField(\n model_name='role',\n name='min_ansible_version',\n field=models.CharField(max_length=10, null=True, verbose_name=b'Min Ansible Version', blank=True),\n ),\n migrations.AlterField(\n model_name='role',\n name='role_type',\n field=models.CharField(default=b'ANS', max_length=3, editable=False, choices=[(b'ANS', b'Ansible'), (b'CON', b'Container Enabled'), (b'APP', b'Container App')]),\n ),\n ]\n","repo_name":"smrutikanta/ansible-galaxy","sub_path":"galaxy/main/migrations/0046_auto_20160930_1752.py","file_name":"0046_auto_20160930_1752.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"32624299820","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 28 22:36:55 2019\n\n@author: dan\n\"\"\"\n\n\nimport re\n\n\n\ndef formatSections_DE(sections):\n newSections = []\n for sec in sections:\n newSect = {}\n newSect['sectiontype'] = sec['sectiontype']\n newSect['number'] = sec['number']\n newSect['title'] = sec['title']\n newSect['sectionstack'] = sec['sectionstack']\n newSect['text'] = formatSecText(sec['text'])\n newSections.append(newSect)\n \n return newSections\n\n\n\n\ndef formatSecText(linelist):\n text = \"

    \"\n sectionStack = []\n\n for i, line in enumerate(linelist):\n \n proline = line.strip().replace('\\n', ' ')\n \n # New paragraph for section history (DE statutes)\n if re.search(r\"\\(\\d\\sdel\\.\\sc\\.\\s\\d{4}\\,\\s\\§\\s\\d{2,5}\", proline.lower()):\n pos = re.search(r\"\\(\\d\\sdel\\.\\sc\\.\\s\\d{4}\\,\\s\\§\\s\\d{2,5}\", proline.lower()).span()[0]\n proline = proline[:pos] + \"

    \" + proline[pos:]\n\n # New paragraph for explanatory notes (PA rules)\n if (proline == \"Explanatory Note\"):\n if linelist[i-1].strip() == \"\":\n proline = \"

    Explanatory Note

    \"\n\n # New paragraph for official notes (PA rules of civil procedure, e.g.)\n if proline.startswith(\"Official Note:\"):\n if linelist[i-1].strip() == \"\":\n proline = proline.replace(\"Official Note:\", \"

    Official Note:

    \")\n\n # New paragraph for source (PA rules)\n if (proline == \"Source\"):\n if linelist[i-1].strip() == \"\":\n proline = \"

    Source

    \"\n\n # New paragraph for comments (PA Rules of Evidence)\n if (proline == \"Comment\"):\n if linelist[i-1].strip() == \"\":\n proline = \"

    Comment

    \"\n\n # New paragraph for Committee Explanatory Reports (PA Rules of Evidence)\n if (proline == \"Committee Explanatory Reports:\"):\n if linelist[i-1].strip() == \"\":\n proline = \"

    Committee Explanatory Reports:

    \"\n\n # Determine whether or not this line STARTS A NEW PARAGRAPH\n sLevel = getSectionLevel(proline, sectionStack)\n \n # Add text to big string\n if sLevel > 0: text = text + \"

    \" + proline\n else: text = text + \" \" + proline\n \n text = text + \"

    \"\n\n return text\n\n\n\n\n### -------------------------------------------------------------\n\n\n\n\n\ndef getSectionLevel(line, sectionStack):\n proline = line.lower()\n if re.search(r\"^\\([a-z]\\)\\s\", proline): return 1\n if re.search(r\"^\\(\\d\\)\\s\", proline): return 1\n\n if re.search(r\"^\\(a{2,3}\\)\\s\", proline): return 1\n\n if re.search(r\"^\\(ii\\)\\s\", proline): return 1\n if re.search(r\"^\\(iii\\)\\s\", proline): return 1\n if re.search(r\"^\\(iv\\)\\s\", proline): return 1\n if re.search(r\"^\\(v\\)\\s\", proline): return 1\n if re.search(r\"^\\(vi\\)\\s\", proline): return 1\n if re.search(r\"^\\(vii\\)\\s\", proline): return 1\n if re.search(r\"^\\(viii\\)\\s\", proline): return 1\n if re.search(r\"^\\(ix\\)\\s\", proline): return 1\n if re.search(r\"^\\(x\\)\\s\", proline): return 1\n if re.search(r\"^\\(xii\\)\\s\", proline): return 1\n \n return 0\n\n\n\n\n\n\n\n\ndef addPrevNext_DE(sections, titleNum):\n\n newSections0 = []\n prevSection = 0\n prevTitle = \"\"\n for section in sections:\n newSection = section\n if prevSection == 0:\n prevLink = \"\"\n else:\n prevLink = \"
    \" + \"§ \" + prevSection + \" - \" + prevTitle + \"\"\n newSection['previous'] = prevLink\n newSections0.append(newSection)\n if section['sectiontype'] == 'Section': \n prevSection = section['number']\n prevTitle = section['title']\n\n newSections1 = []\n nextSection = 0\n nextTitle = \"\"\n for section in reversed(newSections0):\n newSection = section\n if nextSection == 0:\n nextLink = \"\"\n else:\n nextLink = \"\" + \"§ \" + nextSection + \" - \" + nextTitle + \"\"\n newSection['next'] = nextLink\n newSections1.append(newSection)\n if section['sectiontype'] == 'Section':\n nextSection = section['number']\n nextTitle = section['title']\n\n newSections2 = [section for section in reversed(newSections1)]\n\n return newSections2","repo_name":"ciarrocki/LibreLaw","sub_path":"STATparser/STATparser_format.py","file_name":"STATparser_format.py","file_ext":"py","file_size_in_byte":4468,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"55"} +{"seq_id":"10685216713","text":"from os.path import abspath, dirname, join\n\n\n# Define the application directory\nBASE_DIR = dirname(dirname(abspath(__file__)))\n\n# Media dir\nMEDIA_DIR = join(BASE_DIR, 'media')\nPOSTS_IMAGES_DIR = join(MEDIA_DIR, 'posts')\n\nSECRET_KEY = ''\n\n# Database configuration\nSQLALCHEMY_TRACK_MODIFICATIONS = False\n\n# App environments\nAPP_ENV_LOCAL = 'local'\nAPP_ENV_TESTING = 'testing'\nAPP_ENV_DEVELOPMENT = 'development'\nAPP_ENV_STAGING = 'staging'\nAPP_ENV_PRODUCTION = 'production'\nAPP_ENV = ''\n\n# Configuración del email\nMAIL_SERVER = 'tu servidor smtp'\nMAIL_PORT = 587\nMAIL_USERNAME = 'tu correo'\nMAIL_PASSWORD = 'tu contraseña'\nDONT_REPLY_FROM_EMAIL = 'dirección from'\nADMINS = ('usuario@dominio.com', )\nMAIL_USE_TLS = True\nMAIL_DEBUG = False\n\nITEMS_PER_PAGE = 3\n","repo_name":"UrbOSDev/Concentrador_Sensores_LoRa","sub_path":"config/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"24688469075","text":"# CONFIGURATION:\n# - basic, constant configuration is done here\n# - secrets, keys, and other local adaptation is done in the local_configuration.py file (which is not in github)\n# - runtime parameters for test runs are done in ./input/parameter.txt files;\n# - instead of 'parameter.txt', a different name may be provided as command-line argument when starting the test.\n\n# sub-directories and parameter file:\nDATA = 'data'\nTEMPLATES = 'templates'\nINPUT = 'input'\nINPUT_PARAMETERS_DEFAULT = 'parameters.txt'\nOUTPUT = 'output'\n\n# OJP service environments, each with a short name like \"PROD\":\nENVIRONMENTS = {\n \"PROD\": {\n \"apiEndpoint\": \"https://api.opentransportdata.swiss/ojp2020\",\n \"authBearerKey\": \"... key can be obtained by registering at https://opentransportdata.swiss/de/ ...\",\n \"supported_requests\": {\"TR\", \"TIR\", \"LIR\", \"SER\"}\n },\n \"TRIAS2020\": {\n \"apiEndpoint\": \"https://api.opentransportdata.swiss/trias2020\",\n \"authBearerKey\": \"...\",\n \"supported_requests\": {\"TRIAS2020TR\"}\n }\n}\n\n# URL of the DIDOK data file (list of stations/stops in Swiss public transport)\nDIDOK_PERMALINK = \"https://opentransportdata.swiss/en/dataset/didok/resource_permalink/verkehrspunktelemente_actualdate.csv\"\nDIDOK_FILE = \"verkehrspunktelemente_actualdate.csv\"\n\n# lookup file for didok codes of named places:\nDIDOK_FOR_PLACES = \"didok_for_places.json\"\n\n\n# if there exists a local_configuration, it is used and may supersede some of the above constants.\ntry:\n from local_configuration import *\nexcept:\n pass","repo_name":"openTdataCH/ojpch-performance-test","sub_path":"configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"71125588013","text":"class Solution:\n def longestPalindrome(self, s: str) -> str:\n str_length = len(s)\n longest_string = ''\n \n def check_palindromic(left, right):\n # middle to left and right\n while left >= 0 and right < str_length and s[left] == s[right]:\n left -= 1\n right += 1\n return s[left+1:right]\n \n for i in range(str_length):\n odd_str = check_palindromic(i,i)\n even_str = check_palindromic(i,i+1)\n longest_string = max(longest_string, odd_str,even_str, key=lambda x: len(x))\n \n return longest_string","repo_name":"BoyuLin0906/LeetCode","sub_path":"Python/5_Longest_Palindromic_Substring/Solution_2.py","file_name":"Solution_2.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"39560241617","text":"import pytest\n\nimport pyndata\n\nclass FixedArrayTests(pyndata.Struct):\n arr = pyndata.array(pyndata.uint8(), 3)\n\ndef test_array_unpack():\n x = FixedArrayTests()\n x.unpack(b'\\x01\\x02\\x03')\n assert x.arr == [1,2,3]\n\ndef test_array_pack():\n x = FixedArrayTests()\n x.arr = [4,5,6]\n packed = x.pack()\n assert packed == b'\\x04\\x05\\x06'\n\nclass S1(pyndata.Struct):\n\tf = pyndata.uint8()\n\nclass S2(pyndata.Struct):\n\ta = pyndata.array(kind=S1(), length=2)\n\nclass VariableArray(pyndata.Struct):\n l = pyndata.uint8()\n a = pyndata.array(pyndata.uint8(), length=l)\n\ndef test_variable_unpack_length():\n v = VariableArray()\n v.unpack(b'\\x03\\x01\\x02\\x03')\n assert v.l == 3\n assert v.a == [1, 2, 3]\n\ndef test_variable_pack():\n v = VariableArray()\n v.a = [1, 2, 3]\n assert v.l == 3\n assert v.pack() == b'\\x03\\x01\\x02\\x03'\n\ndef test_bad_unpack_length():\n v = VariableArray()\n with pytest.raises(pyndata.error):\n v.unpack(b'\\x04\\x01\\x02\\x03')\n\nclass ArrayWithBitfieldLength(pyndata.Struct):\n a = pyndata.uint8()\n b = pyndata.BitField(a, 8, 0)\n c = pyndata.array(pyndata.uint8(), length=b)\n\ndef test_array_bitfield_length():\n x = ArrayWithBitfieldLength(b'\\x02\\x00\\x01')\n assert x.c == [0, 1]\n y = ArrayWithBitfieldLength()\n y.b = 2\n y.c = [0, 1]\n assert y.pack() == b'\\x02\\x00\\x01'\n\n# This is disgusting.\n# But it's been a couple of months and I don't remember why.\nclass ArrayWithFunctionLength(pyndata.Struct):\n def __init__(self, *a, **kw):\n super(ArrayWithFunctionLength, self).__init__(*a, **kw)\n self.real_length = 3\n\n def length(self, length=None):\n if length:\n self.real_length = length\n else:\n return self.real_length\n\n a = pyndata.array(pyndata.uint8(), length=length)\n\ndef test_array_function_length_unpack():\n v = ArrayWithFunctionLength()\n print(v.fields[0].length)\n v.unpack(b'\\x01\\x02\\x03')\n assert v.a == [1, 2, 3]\n\ndef test_array_function_length_pack():\n v = ArrayWithFunctionLength()\n v.a = [3, 2, 1]\n assert v.real_length == 3\n assert v.pack() == b'\\x03\\x02\\x01'\n","repo_name":"alcarithemad/zfsp","sub_path":"pyndata/tests/test_array.py","file_name":"test_array.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","stars":567,"dataset":"github-code","pt":"55"} +{"seq_id":"10130159423","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom tqdm import tqdm\nimport time\nfrom datetime import timedelta\n\n\ndef epoch_train(loader, model, criterion, opt, device):\n \"\"\"\n training per epoch\n \"\"\"\n model.train(True)\n model.eval()\n\n total_loss = 0.0\n correct = 0\n\n for data in loader:\n inputs, labels = data\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # zero the parameter gradients\n opt.zero_grad()\n\n # forward + backward + optimize\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n opt.step()\n\n total_loss += loss.item() * loader.batch_size\n\n _, predicted = outputs.max(1)\n correct += (predicted == labels).sum().item()\n\n avg_loss = total_loss / len(loader.dataset)\n avg_accuracy = correct / len(loader.dataset)\n\n return avg_loss, avg_accuracy\n\n\ndef epoch_val(loader, model, criterion, device):\n \"\"\"\n validating per epoch\n \"\"\"\n model.train(True)\n model.eval()\n total_loss = 0.0\n correct = 0\n\n for data in loader:\n inputs, labels = data\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n total_loss += loss.item() * loader.batch_size\n\n _, predicted = torch.max(outputs.data, 1)\n correct += (predicted == labels).sum().item()\n\n avg_loss = total_loss / len(loader.dataset)\n avg_accuracy = correct / len(loader.dataset)\n\n return avg_loss, avg_accuracy\n\n\ndef log_experiment(experiment, epoch, train_loss, train_acc, test_loss, test_acc):\n experiment.log_metric(\"Train Loss\", train_loss, step=epoch)\n experiment.log_metric(\"Train Accuracy\", train_acc, step=epoch)\n experiment.log_metric(\"Val Loss\", test_loss, step=epoch)\n experiment.log_metric(\"Test Accuracy\", test_acc, step=epoch)\n\n\ndef train(\n experiment,\n checkpoint_name,\n train_loader,\n test_loader,\n model,\n criterion,\n opt,\n scheduler,\n device,\n n_epochs=50,\n checkpoint_path=\"./checkpoints/\",\n):\n \"\"\"\n training loop\n \"\"\"\n for epoch in tqdm(range(n_epochs)):\n train_loss, train_acc = epoch_train(train_loader, model, criterion, opt, device)\n test_loss, test_acc = epoch_val(test_loader, model, criterion, device)\n\n print(\n f\"[Epoch {epoch + 1}] train loss: {train_loss:.3f}; train acc: {train_acc:.2f}; \"\n + f\"test loss: {test_loss:.3f}; test acc: {test_acc:.2f}\"\n )\n log_experiment(experiment, epoch, train_loss, train_acc, test_loss, test_acc)\n scheduler.step()\n\n # saving every 5 epoches\n if epoch % 5 == 0:\n PATH = checkpoint_path\n PATH += checkpoint_name\n torch.save(model.state_dict(), PATH)\n\n\ndef evaluate(testloader, model, device):\n \"\"\"\n evaluate loop\n \"\"\"\n correct = 0\n total = 0\n start = time.time()\n total_time = 0\n\n with torch.no_grad():\n for i, data in enumerate(testloader):\n images, labels = data\n t0 = time.time()\n images = images.to(device)\n labels = labels.to(device)\n\n # calculate outputs by running images through the network\n outputs = model(images)\n t1 = time.time()\n total_time = total_time + (t1 - t0)\n # the class with the highest energy is what we choose as prediction\n _, predicted = torch.max(outputs.data, 1)\n correct += (predicted == labels).sum().item()\n time_elapse = time.time() - start\n print(\"CPU prediction time\", float(total_time) / (i + 1), i + 1)\n print(\"inference time:\", str(timedelta(seconds=time_elapse)))\n print(\n f\"Accuracy of the network on the test images: {100 * correct / len(testloader.dataset)} %\"\n )\n","repo_name":"highly0/CP_Tucker_Decomposition","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"55"} +{"seq_id":"8979641047","text":"import logging\n\nfrom transformers import (\n BertConfig,\n BertForTokenClassification,\n DistilBertConfig,\n DistilBertForTokenClassification,\n)\n\nimport fedml\nfrom data.data_loader import load\nfrom fedml import FedMLRunner\nfrom trainer.seq_tagging_trainer import MyModelTrainer as MySTTrainer\nfrom trainer.tagging_aggregator import TaggingAggregator \n\ndef create_model(args, output_dim=1):\n model_name = args.model\n logging.info(\n \"create_model. model_name = %s, output_dim = %s\" % (model_name, output_dim)\n )\n MODEL_CLASSES = {\n \"seq_tagging\": {\n \"bert\": (BertConfig, BertForTokenClassification),\n \"distilbert\": (DistilBertConfig, DistilBertForTokenClassification),\n },\n }\n try:\n config_class, model_class = MODEL_CLASSES[args.formulation][args.model_type]\n except KeyError:\n raise Exception(\"such model or formulation does not exist currently!\")\n model_args = {}\n\n model_args[\"num_labels\"] = output_dim\n config = config_class.from_pretrained(args.model, **model_args)\n model = model_class.from_pretrained(args.model, config=config)\n trainer = MySTTrainer(model, args)\n return model, trainer\n\n\nif __name__ == \"__main__\":\n # init FedML framework\n args = fedml.init()\n\n # init device\n device = fedml.device.get_device(args)\n\n # load data\n dataset, output_dim = load(args)\n\n # load model and trainer\n args.num_labels = output_dim\n model, trainer = create_model(args, output_dim)\n aggregator = TaggingAggregator(model, args)\n # start training\n fedml_runner = FedMLRunner(args, device, dataset, model, trainer, aggregator)\n fedml_runner.run()\n","repo_name":"FedML-AI/FedML","sub_path":"python/examples/federate/prebuilt_jobs/fednlp/seq_tagging/torch_main.py","file_name":"torch_main.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":3294,"dataset":"github-code","pt":"55"} +{"seq_id":"39908478313","text":"'''\nControls the Thermostat based on outside temperature, user's schedule and detection of movement\n'''\nimport time\n# IBM cloud connection\nimport ibmiotf.application\nimport os, json\nfrom flask import Flask, redirect\nfrom flask import render_template\nfrom flask import request\nfrom datetime import datetime\n# from get_calendar import *\nimport get_calendar as calendar\nimport threading\n\nDECISION_HEAT_ON = \"rgba(255,102,102,0.5)\"\nDECISION_AC_ON = \"rgba(102,102,255,0.5)\"\nDECISION_TURN_OFF = \"rgba(192,192,192,0.5)\"\n\nrunning = False\n\nLIST_SAMPLE_SIZE = 60\n\noutside_temp_list = [0] * LIST_SAMPLE_SIZE\n# outside_temp_list = [78, 76, 67, 58, 87]\n\nhvac_decision_list = [0] * LIST_SAMPLE_SIZE\n# hvac_decision_list = [DECISION_AC_ON, DECISION_TURN_OFF, DECISION_HEAT_ON, DECISION_HEAT_ON]\n\ntimestamp_list = [0] * LIST_SAMPLE_SIZE\n# timestamp_list = [datetime.now().strftime('%Y-%m-%d %H:%M:%S'), datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n# datetime.now().strftime('%Y-%m-%d %H:%M:%S'), datetime.now().strftime('%Y-%m-%d %H:%M:%S'), datetime.now().strftime('%Y-%m-%d %H:%M:%S')]\n\nhvac_counter = 0\ntemp_counter = 0\n\n# Current Time of day in UTC\ntimestamp_string = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n# Is user home according to schedule\nscheduledHome = False\n# Movement detected\nmovement = False\n# Outside temperature\noutsideTemp = 0\n# final decision if user is home\nuserHome = False\n# Away Heat setting\nawayHeat = 60\n# Away Cool setting\nawayCool = 80\n# Home heat setting\nhomeHeat = 68\n# Home Cool setting\nhomeCool = 75\n# ZIP code\nzipCode = 27607\n\n# Decision on what to do with the HVAC system. 'Turn AC on', 'Turn Heat on'\ndecision = 'Turn unit off'\n\n\napp = Flask(__name__)\nport = os.getenv('VCAP_APP_PORT', '5000')\n\nevent_list = calendar.get_event_list()\n\n# Connect to IBM cloud instance\nclient = None\n\n# Connection data for IBM Cloud\ntry:\n options = {\n \"org\": \"jbkg3j\",\n \"id\": \"8\",\n \"auth-method\": \"apikey\",\n \"auth-key\": \"a-jbkg3j-2fh4t6fddr\",\n \"auth-token\": \"LieV-Obn1G1Q97QU*A\"\n }\n client = ibmiotf.application.Client(options)\n client.connect()\n\n\nexcept ibmiotf.ConnectionException as e:\n print(e)\n\ndef update_lists(element_list, element, counter):\n if counter >= LIST_SAMPLE_SIZE:\n element_list.pop(0)\n element_list.append(element)\n else:\n element_list[counter] = element\n\n\n# Determines if the user is home based on data from motion sensor and schedule\ndef is_user_home():\n global movement\n global userHome\n\n # Favor input from the motion sensor over the schedule to determine if they are home\n if movement:\n userHome = True\n elif scheduledHome:\n userHome = True\n else:\n userHome = False\n return userHome\n\n\n# Callback for a sensor value change\ndef event_callback(data):\n\n # New Data has been published\n payload = json.loads(data.payload)\n global movement\n global outsideTemp\n global temp_counter\n global scheduledHome\n\n movement = int(payload[\"movement\"])\n print(movement)\n\n if float(payload[\"temperature\"]) != outsideTemp:\n update_lists(outside_temp_list, outsideTemp, temp_counter)\n scheduledHome = not calendar.check_user_event(event_list, datetime.now())\n \n outsideTemp = float(payload[\"temperature\"])\n decide()\n temp_counter += 1\n\n \n# Decide whether to turn heat or AC on\ndef decide():\n desiredCool = 0\n desiredHeat = 0\n global decision\n global hvac_counter\n global hvac_decision_list\n global timestamp_list\n\n # This needs work to decide exactly what to do and how long to do it\n if is_user_home():\n desiredCool = homeCool\n desiredHeat = homeHeat\n else:\n desiredCool = awayCool\n desiredHeat = awayHeat\n\n if (outsideTemp > desiredCool):\n decision = 'Turn AC On'\n update_lists(hvac_decision_list, DECISION_AC_ON, hvac_counter)\n elif (outsideTemp < desiredHeat):\n decision = 'Turn Heat On'\n update_lists(hvac_decision_list, DECISION_HEAT_ON, hvac_counter)\n else:\n decision = 'Turn unit off'\n update_lists(hvac_decision_list, DECISION_TURN_OFF, hvac_counter)\n \n timestamp_string = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n update_lists(timestamp_list, timestamp_string, hvac_counter)\n\n hvac_counter += 1\n\n my_data = {\"status\": decision}\n # Publish decision to broker\n\n # Update this based on the Laptop information\n client.publishEvent(\"Laptop\", \"e4b3187eb170\", \"hvac\", \"json\", my_data)\n\n@app.route('/')\ndef show_writeup():\n return render_template('writeup.html')\n\n# event = zipcode, key = zip\n@app.route('/zip', methods=['GET', 'POST'])\ndef get_zip_code():\n global zipCode\n global running\n global awayHeat\n global homeHeat\n global awayCool\n global homeCool\n\n if request.method == 'POST':\n zipCode = request.form['zip'] if request.form['zip'] != '' else zipCode\n awayHeat = int(request.form['awayHeat']) if request.form['awayHeat'] != '' else awayHeat\n homeHeat = int(request.form['homeHeat']) if request.form['homeHeat'] != '' else homeHeat\n awayCool = int(request.form['awayCool']) if request.form['awayCool'] != '' else awayCool\n homeCool = int(request.form['homeCool']) if request.form['homeCool'] != '' else homeCool\n\n my_data = {'zip': str(zipCode)}\n client.publishEvent(\"Laptop\", \"7\", \"zipcode\", \"json\", my_data)\n \n running = True\n return redirect('/graph')\n return render_template('zip.html')\n\n# Default route for display of data\n@app.route('/graph')\ndef temp_controller():\n global timestamp_list\n global hvac_decision_list\n global outside_temp_list\n\n if hvac_counter < LIST_SAMPLE_SIZE:\n # print(outside_temp_list)\n return render_template('graph.html', status=decision, labels=timestamp_list[0: hvac_counter], \n title='Temperatures over Time', hvac_decisions=hvac_decision_list[0: hvac_counter],\n outside_values=outside_temp_list[0: hvac_counter], away_heat=awayHeat, home_heat=homeHeat,\n away_cool=awayCool, home_cool=homeCool, outside_temp=outsideTemp, current_decision=decision,\n zip_code=zipCode, currently_present=userHome)\n else:\n return render_template('graph.html', status=decision, labels=timestamp_list, \n title='Temperatures over Time', hvac_decisions=hvac_decision_list,\n outside_values=outside_temp_list, away_heat=awayHeat, home_heat=homeHeat,\n away_cool=awayCool, home_cool=homeCool, outside_temp=outsideTemp, current_decision=decision,\n zip_code=zipCode, currently_present=userHome)\n\n\n# Subscribe to motion and temp events\nclient.subscribeToDeviceEvents(event=\"sensorData\")\nclient.deviceEventCallback = event_callback\n\n\ndef schedule_app_run():\n while True:\n if running:\n # Check the user's schedule every 15 minutes\n # Returns True if the user has something scheduled at this time\n print(scheduledHome)\n time.sleep(5)\n \n\nif __name__ == \"__main__\":\n # threading.Thread(target=signal_event).start()\n # threading.Thread(target=schedule_app_run).start()\n app.run(host='0.0.0.0', port=int(port))\n \n \n ","repo_name":"Buhlakay/SmartHVAC","sub_path":"thermostatController.py","file_name":"thermostatController.py","file_ext":"py","file_size_in_byte":7250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"12042695686","text":"from keras import Model\nfrom keras.layers import *\nfrom util import *\nfrom keras.applications import ResNet50, VGG16\nfrom projective import vec2mat\nfrom keras.models import model_from_json\n\n\ndef model_from_file(model_file):\n json_file = open(model_file, 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n return model_from_json(loaded_model_json)\n\n\ndef save_model(filename, model):\n model_json = model.to_json()\n with open(filename, \"w\") as json_file:\n json_file.write(model_json)\n\n\n# nn for depth estimation\nclass DepthModel:\n def __init__(self, input_shape=None, input_tensor=None, mode='multi'):\n self.inputs = None\n self.model = None\n self.outputs = None\n self.mode = mode\n self.input_tensor = input_tensor\n self.input_shape = input_shape\n # self.build()\n\n def build(self):\n if self.input_shape is not None:\n input = Input(shape=self.input_shape)\n else:\n input = self.input_tensor\n\n x = ResNet50(include_top=False, weights=None, input_tensor=input)\n\n skip1 = x.get_layer('activation_1').output\n skip2 = x.get_layer('activation_10').output\n skip3 = x.get_layer('activation_22').output\n skip4 = x.get_layer('activation_40').output\n\n skip1 = conv(skip1, 1, (1, 1), (1, 1))\n skip2 = conv(skip2, 1, (1, 1), (1, 1))\n skip3 = conv(skip3, 1, (1, 1), (1, 1))\n skip4 = conv(skip4, 1, (1, 1), (1, 1))\n\n code = conv(x.get_layer('activation_49').output, 1, (1, 1), (1, 1), name='conv_post_res')\n\n dec4 = deconv(code, 1, kernel=(4, 4), stride=(2, 2))\n x = Add()([dec4, skip4])\n dec3 = deconv(x, 1, kernel=(4, 4), stride=(2, 2))\n x = Add()([dec3, skip3])\n dec2 = deconv(x, 1, kernel=(4, 4), stride=(2, 2))\n x = Add()([dec2, skip2])\n dec1 = deconv(x, 1, kernel=(4, 4), stride=(2, 2))\n x = Add()([dec1, skip1])\n dec0 = deconv(x, 1, kernel=(4, 4), stride=(2, 2))\n\n\n dec0 = activiate(dec0)\n if self.mode == 'multi':\n outputs = [dec0, dec1, dec2, dec3]\n else:\n outputs = [dec0]\n self.model = Model(inputs=[input], outputs=outputs)\n print('network built')\n\n def model_from_file(self, model_file):\n self.model = model_from_file(model_file)\n\n def predict(self, input):\n self.model.predict(input)\n\n def load_weights(self, path, resnet_only=False):\n\n if resnet_only:\n self.model.load_weights(path, by_name=True)\n else:\n self.model.load_weights(path)\n\n\n# nn for pose estimation\nclass OdometryModel():\n\n def __init__(self, inputs=None, input_shape=None, mode='unsupervised'):\n\n self.mode = mode\n if input_shape is not None:\n self.input1 = Input(batch_shape=input_shape)\n self.input2 = Input(batch_shape=input_shape)\n else:\n self.input1 = inputs[0]\n self.input2 = inputs[1]\n\n self.input = concatenate([self.input1, self.input2])\n self.model = None\n\n def build(self):\n\n # vgg = VGG16(include_top=False, weights=None, input_tensor=self.input)\n # l = vgg.get_layer(name='block1_conv1')\n # l.name = 'block1_conv0'\n\n x = Conv2D(64, (7, 7), strides=(2, 2), padding='same', activation='relu', kernel_initializer='uniform')(\n self.input)\n x = Conv2D(64, (5, 5), strides=(2, 2), padding='same', activation='relu', kernel_initializer='uniform')(x)\n x = MaxPooling2D(pool_size=(2, 2))(x)\n x = Conv2D(128, (3, 2), strides=(1, 1), padding='same', activation='relu', kernel_initializer='uniform')(x)\n x = Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='uniform')(x)\n x = MaxPooling2D(pool_size=(2, 2))(x)\n x = Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='uniform')(x)\n x = Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='uniform')(x)\n x = MaxPooling2D(pool_size=(2, 2))(x)\n x = Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='uniform')(x)\n x = Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='uniform')(x)\n x = MaxPooling2D(pool_size=(2, 2))(x)\n x = Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='uniform')(x)\n x = Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu', kernel_initializer='uniform')(x)\n x = MaxPooling2D((3, 3))(x)\n x = Flatten()(x)\n\n t = Dense(units=512, name='trans2')(x)\n t = Activation('tanh')(t)\n t = Dense(units=512, name='trans1')(t)\n t = Activation('tanh')(t)\n t = Dense(3, name='trans0')(t)\n # t = Activation('tanh')(t)\n\n r = Dense(units=512, name='orient2')(x)\n r = Activation('tanh')(r)\n r = Dense(units=512, name='orient1')(r)\n r = Activation('tanh')(r)\n r = Dense(3, name='orient0')(r)\n # r = Activation('tanh')(r)\n\n pose = Concatenate()([t, r])\n\n # if self.mode is not 'unsupervised':\n # mat = Lambda(post_process)(mat)\n\n self.model = Model(inputs=[self.input1, self.input2], outputs=[pose])\n\n def load_weights(self, path): # , vgg_only=False):\n # if vgg_only:\n # self.model.load_weights(path, by_name=True)\n # else:\n self.model.load_weights(path)\n\n def model_from_file(self, file):\n self.model = model_from_file(file)\n","repo_name":"PatrickStaar/visual_odometry_practice","sub_path":"model/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"28661378433","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 20 11:07:55 2022\n\n@author: huzongxiang\n\"\"\"\n\n\nimport warnings\nimport logging\nimport time\nfrom pathlib import Path\nimport numpy as np\nimport tensorflow as tf\nfrom matdgl.data import Dataset\nfrom matdgl.models import Finetune\nfrom matdgl.data.generator import GraphGenerator\nfrom matdgl.models.finetune import FinetuneTransformer, FinetuneTransformerRes\n\ntf.get_logger().setLevel(logging.ERROR)\nwarnings.filterwarnings(\"ignore\")\n\nnp.random.seed(88)\ntf.random.set_seed(88)\n\n# get current work dir of test.py\nModulePath = Path(__file__).parent.absolute()\n\n# read datas from ModulePath/datas/multiclassfication.json\nprint('reading dataset...')\n'multiclassification'\n'topology_multi'\n'formation_energy'\n'regression'\n'my_regression'\nstart = time.time()\ndataset = Dataset(task_type='topology_multi', data_path=ModulePath, ratio=[0.6, 0.8])\nend = time.time()\nrun_time = end - start\nprint('done')\nprint('run time: {:.2f} s'.format(run_time))\nprint(dataset.dataset_file)\n\nBATCH_SIZE = 16\nDATA_SIZE = None\nCUTOFF = 4.5\n\n# building batch generator for model trainning\nGenerators = GraphGenerator(dataset, data_size=DATA_SIZE, batch_size=BATCH_SIZE, cutoff=CUTOFF)\ntrain_data = Generators.train_generator\nvalid_data = Generators.valid_generator\ntest_data = Generators.test_generator\n\n#if task is multiclassfication, should define variable multiclassifiction\nmulticlassification = Generators.multiclassification \n\nepochs=32\nlr=1e-3\n\n# default trainning parameters\nstate_dim=16\nsp_dim=230\noutput_dim=32\nreadout_units=128\ndropout=0.0\nreg2=0.0\nreg3=0.0\nreg_rec=0.0\nregression=dataset.regression\noptimizer = 'Adam'\n\nprint('\\n----- parameters -----',\n '\\ntask_type: ', dataset.task_type,\n '\\nsample_size: ', Generators.data_size,\n '\\ncutoff: ', CUTOFF,\n '\\nstate_dim: ', state_dim,\n '\\nsp_dim: ', sp_dim,\n '\\noutput_dim: ', output_dim,\n '\\nreadout_units: ', readout_units,\n '\\ndropout: ', dropout,\n '\\nreg2: ', reg2,\n '\\nreg3: ', reg3,\n '\\nreg_rec: ', reg_rec,\n '\\noptimizer: ', optimizer,\n '\\nmulticlassification: ', multiclassification,\n '\\nregression: ', regression,)\n\ndel dataset\n\n# default model is a GraphTransformer model, can be changed to MPNN model by set 'model=MpnnModel'\ngnn = Finetune(model=FinetuneTransformerRes,\n state_dim=state_dim,\n sp_dim=sp_dim,\n output_dim=output_dim,\n readout_units=readout_units,\n dropout=dropout,\n reg2=reg2,\n reg3=reg3,\n reg_rec=reg_rec,\n optimizer = optimizer,\n regression=regression,\n multiclassification=multiclassification,\n )\n\n# trainning model\ngnn.train(train_data, valid_data, test_data, epochs=epochs, lr=lr, warm_up=True,\\\n verbose=1, checkpoints=None, save_weights_only=True, workdir=ModulePath)\n\nprint('\\n----- parameters -----',\n '\\nsample_size: ', Generators.data_size,\n '\\ncutoff: ', CUTOFF,\n '\\nstate_dim: ', state_dim,\n '\\nsp_dim: ', sp_dim,\n '\\noutput_dim: ', output_dim,\n '\\nreadout_units: ', readout_units,\n '\\noptimizer: ', optimizer,\n '\\nmulticlassification: ', multiclassification,\n '\\nregression: ', regression,\n '\\nepochs: ', epochs,\n '\\nlr: ', lr)","repo_name":"huzongxiang/MatDGL","sub_path":"user_easy_train_scripts/train_finetune.py","file_name":"train_finetune.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"55"} +{"seq_id":"21547692262","text":"# https://leetcode.com/problems/pancake-sorting/\nfrom typing import List\n\n\ndef flip(arr: List[int], k: int):\n \"\"\"k is 0 indexed\"\"\"\n i = 0\n j = k\n while i < j:\n arr[i], arr[j] = arr[j], arr[i]\n i += 1\n j -= 1\n\n\nclass Solution:\n def pancakeSort(self, arr: List[int]) -> List[int]:\n # result\n result = []\n lArr = len(arr)\n for i in range(lArr, 0, -1):\n # find index of i in arr\n idx = -1\n for j in range(0, i):\n if arr[j] == i:\n idx = j\n break\n # if index of i == i - 1 continue\n if idx == i-1:\n continue\n else:\n flip(arr, idx)\n flip(arr, i-1)\n result.append(idx+1)\n result.append(i)\n return result\n","repo_name":"brukted/comptetive-programming","sub_path":"weeks/week 3/day 1/pancake-sorting.py","file_name":"pancake-sorting.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"669873340","text":"\"\"\" \nIntroduction to Pattern Recognition and Machine Learning\nSara Hirvonen\nExercise 5 Reinforcement learning (OpenAI Gym)\n\n\"\"\"\nimport gym\nimport random\nimport numpy as np\nimport time\n\ndef train(alpha, gamma, episodes, steps, env):\n Q_reward = np.zeros((500,6))\n\n # Training w/ random sampling of actions\n for i in range(episodes):\n state1 = env.reset()\n for j in range(steps):\n random_num = random.randint(0,5)\n state2, reward, done, info = env.step(random_num)\n new_value = Q_reward[state1, random_num]+alpha*(reward + gamma*max(Q_reward[state2, :])-Q_reward[state1, random_num])\n Q_reward[state1, random_num] = new_value\n state1 = state2\n\n if done:\n break\n\n return Q_reward\n\ndef test(Q_reward, env):\n tot_actions = 0\n tot_reward = 0\n\n state = env.reset()\n for t in range(50):\n action = np.argmax(Q_reward[state, :])\n state, reward, done, info = env.step(action)\n tot_reward += reward\n tot_actions += 1\n env.render()\n time.sleep(1)\n if done:\n print(\"Total reward {}\".format(tot_reward))\n break\n\n return tot_actions, tot_reward\n\ndef main():\n # Environment\n env = gym.make(\"Taxi-v3\")\n\n # Training parameters for Q learning\n alpha = 0.9 # learning rate\n gamma = 0.9 # Future reward discount factor\n num_of_episodes = 1000\n num_of_steps = 500 # per each episode\n\n # Q tables for rewards \n Q_reward = train(alpha, gamma, num_of_episodes, num_of_steps, env)\n \n tot_reward = 0\n tot_actions = 0\n\n for _ in range(10):\n actions, reward = test(Q_reward, env)\n tot_actions += actions\n tot_reward += reward\n\n avg_of_actions = tot_actions/10\n avg_of_total_reward = tot_reward/10\n\n print(\"Average total reward is\", avg_of_total_reward)\n print(\"Average number of actions is\", avg_of_actions)\n\n\nmain()","repo_name":"hirvonensara/intro_prml","sub_path":"week5/reinforcement_learning_taxi.py","file_name":"reinforcement_learning_taxi.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"33431706007","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport pandas as pd\ndf=pd.read_csv('D:\\\\yt\\\\train.csv')\n\ndf.head()\n\n\n# In[6]:\n\n\ndf.describe()\n\n\n# In[7]:\n\n\n#seperating features (X) and outcome(y) from historical data\nX=df.drop(['Loan_Status','Loan_ID'], axis=1)\ny=df['Loan_Status']\nprint(X.shape)\n\n\n# In[8]:\n\n\n#Handling Null Values\nX.isnull().sum()\n\n\n# In[9]:\n\n\nX['Gender'].value_counts()\n\n\n# In[10]:\n\n\nX['Gender'].fillna(\"Male\", inplace=True)\n\n\n# In[11]:\n\n\nX.isnull().sum()\n\n\n# In[12]:\n\n\nX['Married'].value_counts()\n\n\n# In[13]:\n\n\nX['Married'].fillna(\"Yes\", inplace=True)\nX.isnull().sum()\n\n\n# In[14]:\n\n\nX['Dependents'].value_counts()\n\n\n# In[15]:\n\n\nX['Dependents'].fillna(\"0\", inplace=True)\nX.isnull().sum()\n\n\n# In[16]:\n\n\nX['Self_Employed'].value_counts()\n\n\n# In[17]:\n\n\nX['Self_Employed'].fillna(\"No\", inplace=True)\nX.isnull().sum()\n\n\n# In[18]:\n\n\nmean_loan=X['LoanAmount'].mean()\nX['LoanAmount'].fillna(mean_loan,inplace=True)\nX.isnull().sum()\n\n\n# In[19]:\n\n\nX['Loan_Amount_Term'].fillna(X['Loan_Amount_Term'].mean(),inplace=True)\n\nX['Credit_History'].fillna(X['Credit_History'].mean(),inplace=True)\n\nX.isnull().sum()\n\n\n# In[20]:\n\n\n#Now X does not have any null value\n#One hot Encoding- Changing Categorical Values into numerical values\nX=pd.get_dummies(X)\nX.head()\n\n\n# In[21]:\n\n\nfrom sklearn.model_selection import train_test_split\n\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.30,random_state=30)\nprint(X_train.shape)\n\nprint(X_test.shape)\n\nprint(y_test.shape)\nX_train.head()\n\n\n# In[22]:\n\n\n#Applying Machine Learning Algorithm – Logistic Regression\n\nfrom sklearn.linear_model import LogisticRegression\nLr = LogisticRegression()\n\nLr.fit(X_train,y_train)\n#Lr now contains the model\n\n\n# In[23]:\n\n\n#Applying Machine Learning Algorithm – Support Vector Machines\nfrom sklearn.svm import SVC\nsvc = SVC()\n\nsvc.fit(X_train, y_train)\n#svc is another ML model\n\n\n# In[24]:\n\n\n#Applying Machine Learning Algorithm – Decision Tree Classifier\nfrom sklearn.tree import DecisionTreeClassifier\n\ndtf = DecisionTreeClassifier()\n\ndtf.fit(X_train, y_train)\n\n\n# In[25]:\n\n\nfrom sklearn.naive_bayes import GaussianNB\n\nn_b = GaussianNB()\n\nn_b.fit(X_train, y_train)\n\n\n# In[26]:\n\n\nfrom sklearn.neighbors import KNeighborsClassifier\n\nknn = KNeighborsClassifier() \n\nknn.fit(X_train, y_train)\nprint(knn.score(X_test,y_test))\n\n\n# In[27]:\n\n\n#How to Predict using model\ny_predict=Lr.predict(X_test)\ny_predict1=svc.predict(X_test)\ny_predict2=dtf.predict(X_test)\ny_predict3=n_b.predict(X_test)\ny_predict4=knn.predict(X_test)\ndf1=pd.DataFrame({'Actual':y_test,'Predicted_LR':y_predict,'Predicted_svc':y_predict1,'Predicted_dtr':y_predict2,'Predicted_nb':y_predict3,'Predicted_knn':y_predict4 })\ndf1.to_csv(\"Day16_Output.csv\")\n\n\n# In[28]:\n\n\n#Score is simplest parameter to evaluate ML Model for classification problem\n# Score=Total Matching/Total data\n# Goal of a ML Classification problem is to achieve a score closer to 1.\nprint(Lr.score(X_test,y_test))\nprint(svc.score(X_test,y_test))\nprint(dtf.score(X_test,y_test))\nprint(n_b.score(X_test,y_test))\nprint(knn.score(X_test,y_test))\n\n\n# In[29]:\n\n\n#The model made by Logistic Regression Algorithm Lr is the best model so far\n\n\n# In[30]:\n\n\n#Deployment of model \ngender=input(\"What is your gender:\")\nmarried=input(\"Married:\")\ndependents=input(\"dependents value:\")\nEducation=input(\"enter your education\")\nSelfEmployed=input(\"Self Employed:\")\nApplicantincome=int(input(\"enter applicant income\"))\ncoapplicantincome=int(input(\"enter co applicant income:\"))\nloanamount=int(input(\"enter loan amount:\"))\nloanamountterm=int(input(\"enter loan amount term:\"))\ncredithistory=int(input(\"enter credit history:\"))\npropertyarea=input(\"enter property area:\")\ndata = [[gender,married,dependents,Education,SelfEmployed,Applicantincome,coapplicantincome,loanamount,loanamountterm,credithistory,propertyarea]]\n\nnewdf = pd.DataFrame(data, columns = ['Gender','Married','Dependents','Education','Self_Employed','ApplicantIncome','CoapplicantIncome','LoanAmount','Loan_Amount_Term','Credit_History','Property_Area'])\nnewdf.head()\n\n\n# In[31]:\n\n\nnewdf = pd.get_dummies(newdf)\nnewdf.head()\n\n\n# In[32]:\n\n\nX_train.columns\n\n\n# In[33]:\n\n\nmissing_cols = set( X_train.columns ) - set( newdf.columns )\nprint(missing_cols)\n\n\n# In[34]:\n\n\nfor c in missing_cols:\n newdf[c] = 0\n\n\n# In[35]:\n\n\nnewdf = newdf[X_train.columns]\n\n\n# In[36]:\n\n\nyp=Lr.predict(newdf)\nprint(yp)\n\n\n# In[37]:\n\n\nif (yp[0]=='Y'):\n print(\"Your Loan is approved, Please contact at HDFC Bank Any Branch for further processing\")\nelse:\n print(\"Sorry ! Your Loan is not approved\")\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"shababAster/Machine-Learnig2","sub_path":"Day16_Python (1).py","file_name":"Day16_Python (1).py","file_ext":"py","file_size_in_byte":4582,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"11377068508","text":"command = input().split(\"-\")\ndect = {}\nwhile len(command) > 1:\n name, number = command\n if name not in dect:\n dect[name] = 0\n dect[name] = number\n command = input().split(\"-\")\nfor i in range(int(command[0])):\n check_name = input()\n if check_name in dect:\n print(f\"{check_name} -> {dect[check_name]}\")\n else:\n print(f\"Contact {check_name} does not exist.\")","repo_name":"Vigyrious/python_advanced","sub_path":"Tuples-and-Sets-Exercise/Phonebook.py","file_name":"Phonebook.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"31589117878","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nclass HW2EKF:\n def __init__(self, x_0_mean, x_0_var, a_0_mean, a_0_var, a_gt, n_obs):\n self.n_obs = n_obs\n self.a_gt = a_gt # ground truth coefficient\n \n self.x_0_mean = x_0_mean\n self.x_0_var = x_0_var\n self.a_0_mean = a_0_mean\n self.a_0_var = a_0_var\n\n self.mean = np.zeros((self.n_obs + 1, 2))\n self.var_x = np.zeros((self.n_obs + 1, ))\n self.var_a = np.zeros((self.n_obs + 1, ))\n \n self.rng = np.random.default_rng(1998)\n\n self.epsilon_var = 1\n self.nu_var = 0.5\n self.a_noise_var = 0.01\n\n self.x_gt, self.D = self.generateDataset(a_gt, x_0_mean)\n\n\n def getGaussian(self, mean, var, shape = (), useSeed = False):\n if useSeed:\n return self.rng.normal(mean, np.sqrt(var), shape)\n else:\n return np.random.normal(mean, np.sqrt(var), shape)\n\n def generateDataset(self, a_gt, mu_0):\n # Compute Gaussian noise components for dynamics and observations\n # RNG for Gaussian Sampling\n epsilon = self.getGaussian(0, self.epsilon_var, (self.n_obs, ))\n nu = self.getGaussian(0, self.nu_var, (self.n_obs, ))\n\n # states over n_obs + 1 timesteps\n x = np.zeros((n_obs + 1, ))\n x[0] = mu_0 # initial\n\n for i in range(n_obs):\n # compute new mean\n x[i+1] = a_gt * x[i] + epsilon[i]\n\n y = np.sqrt(x[1:]**2 + 1) + nu\n\n return x, y\n\n\n def propagateDynamics(self, mean_k_k, Cov_k_k):\n mu_x = mean_k_k[0]\n mu_a = mean_k_k[1]\n\n mean_k1_k = np.array([(mu_a * mu_x), mu_a])\n\n # Jacobian\n A = np.array([[mu_a, mu_x],\n [ 0, 1]])\n\n Cov_k1_k = A @ Cov_k_k @ A.T + np.diag([self.epsilon_var, self.a_noise_var])\n\n return mean_k1_k, Cov_k1_k\n\n def incorporateObservation(self, mean_k1_k, Cov_k1_k, y_k1):\n mu_x = mean_k1_k[0]\n\n # Jacobian\n C = np.array([mu_x / np.sqrt(mu_x**2 + 1), 0]).reshape(1,2)\n\n # Kalman Gain\n K = Cov_k1_k @ C.T @ np.linalg.inv(C @ Cov_k1_k @ C.T + self.nu_var)\n\n # Innovation\n innovation = y_k1 - np.sqrt(mu_x**2 + 1)\n # Update\n mean_k1_k1 = mean_k1_k + (K * innovation).ravel()\n Cov_k1_k1 = (np.eye(2,2) - K @ C) @ Cov_k1_k\n\n return mean_k1_k1, Cov_k1_k1\n\n def runEKF(self):\n\n self.mean[0] = [self.x_0_mean, a_0_mean]\n self.var_x[0] = self.x_0_var\n self.var_a[0] = self.a_0_var\n\n Cov = np.array([[self.x_0_var, 0],\n [0, self.a_0_var]])\n\n for k in range(self.n_obs):\n \n # Propagate Dynamics\n self.mean[k+1], Cov = self.propagateDynamics(self.mean[k], Cov)\n\n # Incorporate Observation\n self.mean[k+1], Cov = self.incorporateObservation(self.mean[k+1], Cov, self.D[k])\n\n self.var_x[k+1] = Cov[0,0]\n self.var_a[k+1] = Cov[1,1]\n\n return self.mean, self.var_x, self.var_a\n\n def plotResults(self):\n '''\n Plots the results of the EKF\n '''\n a_gt_array = np.ones(self.n_obs + 1) * self.a_gt\n sigma = np.sqrt(self.var_a)\n a_minus_sigma = self.mean[:,1] - sigma\n a_plus_sigma = self.mean[:,1] + sigma\n\n fig, ax = plt.subplots(1, 2, figsize=(18, 6))\n\n fig.suptitle('EKF Results')\n\n ax[0].plot(self.x_gt, label='x ground truth')\n ax[0].plot(self.mean[:,0], label='x estimate')\n ax[0].plot(self.D, label='Dataset (observations)')\n ax[0].set_title('State and Observation')\n ax[0].set_xlabel(\"Timesteps\")\n ax[0].legend()\n\n ax[1].plot(a_gt_array, label='a (ground truth)', color='black', linestyle='--')\n ax[1].plot(self.mean[:,1], label='a (estimation)', color='red')\n ax[1].fill_between(range(self.n_obs + 1), a_minus_sigma, a_plus_sigma, color='gray', alpha=.2, label='a +/- sigma')\n # ax[1].plot(a_minus_sigma, label='a - sigma')\n # ax[1].plot(a_plus_sigma, label='a + sigma')\n ax[1].set_title('Coefficient (a)')\n ax[1].set_xlabel(\"Timesteps\")\n ax[1].legend(loc = 'lower right')\n\n plt.show()\n\n\n##############################\n### Execute the code ###\n##############################\n\nn_obs = 100\na_gt = -1\nx_0_mean = 1\nx_0_var = 2\na_0_mean = -5\na_0_var = 0.5\n\nekf = HW2EKF(x_0_mean, x_0_var, a_0_mean, a_0_var, a_gt, n_obs)\nmean, var_x, var_a = ekf.runEKF()\n\nekf.plotResults()","repo_name":"edgrant3/ESE650_HW2","sub_path":"HW2/edgrant_hw2_problem1_EKF.py","file_name":"edgrant_hw2_problem1_EKF.py","file_ext":"py","file_size_in_byte":4577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"1196029206","text":"import sys\nimport os\nimport time\nimport shutil\n\n#扫描无用资源(代码未使用)\n\noutPath = \"/Users/luph/Documents/sizetj/\" #输出目录\nscanSrcPath = \"/Users/luph/Documents/sizetj/entmobile-ios_7.10_composite_feature\" #获取资源的源工程\nscanSrcExtendPath = \"/Users/luph/Documents/luph/svn/tinyvideo-ios_7.10_feature\" #扩展扫描目录\noutPods = True #是否排除pods目录\n\n#前缀白名单\nresPrefixWhiteList = [\"yye_online_guardianlevel\",\"yye_level_\",\"treasureFansLevel\",\"teampk_icon_team_\",\"pk_png_team_\",\"expense_lv_medal_\",\"combo_plane_0\",\n \"combo_lv_medal_\",\"bg_liveroom_confession_animationBoom_\",\n \"{zk\",\"{zjt\",\"{yjt\",\"{xjt\",\"{sjt\",\"{kel\",\n \"zhubodengji\",\"yyent_gift_magician_number_\",\"yyent_gift_magician_\",\"yye_liansongtishi_num_\",\"yybear_loading_\",\n \"yonghudengji_\",\"vulgarAppearAnimate\",\"v_personal_\",\"v_enterprise_\",\"top_player_\",\"tips_user card_labelling\",\n \"talentLive_time_num_\",\"shenqu_hot_top\",\"shenqu_boardlist_no\",\"run_medal\",\"qinmidudengji\",\"official_liveroom_logobg_\",\n \"noble_honour_level_\",\"myHeart\",\"module_rank_\",\"module_icon_\",\"mission_quiz_pic_\",\"majia_image_\",\"magicDrag_down_loading_\",\n \"lottery_rank_\",\"lottery_number_\",\"lottery_compose_\",\"live_thumb_animator_\",\"live_notification\",\"live_animator_image_\",\n \"knight_lv_num_\",\"icon_wish_time_small_\",\"icon_wish_time_big_\",\"heart\",\"group_image\",\"gift_flash_number_white_\",\n \"gift_flash_number_\",\"gift_flash_bg_lower_\",\"gift_flash_bg_\",\"gift_flash_\",\"follow_anchor_living\",\"combo_number_\",\n \"channel_freemode_speakingAnimation\",\"channel_freemode_new_speakingAnimation\",\"ch_animate_F2B_\",\"ch_animate_B2F_\",\n \"RankRome_\",\"RankNumber_\",\"RankMedal_\",\"TeamPVP_GiftBox_type\",\"TeamPVP_ico_seat_delete_\",\"TeamPVP_ico_seat_add_\",\n \"op_stock_\",\"op_liveing_music_\",\"正在发言_\",\"环节介绍弹窗0\",\"光\",\"mf_\",\n\n \"video_shoot_count-down\",\"topicMusicAlbumCover\",\"title_\",\"tinyVideo_icon_color_\",\"rank_\",\"liveing_music2\",\"MerryBasketball_star_\",\n \"MerryBasketball_loading_\",\"newBaseTemplate_speakingAnimation\",\"happypk_\",\n \"3d_touch_video\",\"3d_touch_news\",\"3d_touch_live\",\"3d_touch_accompany\",\"knight_lv_\",\n \"TeamPVP_bg_seat_add_tips_\",\"TeamPVP_Result_\",\"TeamPVP_Portrait_\",\"ic_livinig_\",\"liveroom_\",\n \"mvppk_\",\"mutillive_setting_openmic_dis\" #RN用的\n ]\n\ntmpDir = time.strftime(\"TmpPro_%Y-%m-%d-%H_%M_%S\",time.localtime(time.time())) \nscanTargetDir = outPath+tmpDir #创建临时目录(因为后面会删文件)\n\ndef isInResWhiteList(name):\n for prefix in resPrefixWhiteList:\n if name.startswith(prefix):\n return True\n return False\n\nclass FileModel :\n file = \"\"\n size = 0\n path = \"\"\n\ndef getdirsize(dir): \n size = 0\n if os.path.isdir(dir):\n for root, dirs, files in os.walk(dir):\n for file in files :\n size += os.path.getsize(os.path.join(root, file)) \n else:\n size = os.path.getsize(dir)\n return size \n\ndef getDirOrFileBySuffix(scanImagePath,suffix):\n dirList = []\n for root, dirs, files in os.walk(scanImagePath):\n for dir in dirs:\n if dir.endswith(suffix):\n imagePathDir = os.path.join(root, dir)\n dirList.append(imagePathDir) \n return dirList\n\ndef getImagesetNamelist(scanImagePath,suffix):\n imageNamelist = []\n for root, dirs, files in os.walk(scanImagePath):\n for file in dirs:\n if file.endswith(suffix) and not isInResWhiteList(file):\n imagePathDir = os.path.join(root, file)\n imageName = file.replace(suffix,'')\n fileModel = FileModel()\n fileModel.file = imageName\n fileModel.size = getdirsize(imagePathDir)\n fileModel.path = imagePathDir.replace(scanTargetDir,'')\n # imageNamelist.append(imageName)\n imageNamelist.append(fileModel)\n return imageNamelist\n\ndef getImageNamelist(scanImagePath,suffix):\n imageNamelist = []\n for root, dirs, files in os.walk(scanImagePath):\n for file in files:\n if file.endswith(suffix) and not isInResWhiteList(file):\n imagePathDir = os.path.join(root, file)\n imageName = file.replace(suffix,'')\n imageName = imageName.replace(\"@2x\",'')\n imageName = imageName.replace(\"@3x\",'')\n \n fileModel = FileModel()\n fileModel.file = imageName\n fileModel.size = getdirsize(imagePathDir)\n fileModel.path = imagePathDir.replace(scanTargetDir,'')\n\n # imageNamelist.append(imageName)\n imageNamelist.append(fileModel)\n return imageNamelist\n\ndef isFindRes(scanContent,resName):\n return scanContent.find(resName,0,len(scanContent))\n \ndef scanAction(imageNamelist,scanTargetDir):\n scanSuffix_m = \".m\"\n scanSuffix_mm = \".mm\"\n scanSuffix_xib = \".xib\"\n scanSuffix_sb = \".storyboard\"\n invalidResList = []\n for nameModel in imageNamelist :\n isExist = False\n for root, dirs, files in os.walk(scanTargetDir):\n for file in files:\n currentFilePath = os.path.join(root,file)\n if (not os.path.isdir(currentFilePath)) and (file.endswith(scanSuffix_m) or file.endswith(scanSuffix_xib) or file.endswith(scanSuffix_sb) or file.endswith(scanSuffix_mm)):\n try:\n f = open(currentFilePath, \"r\")\n fileContent = f.read()\n isFind = fileContent.find(nameModel.file,0,len(fileContent))\n if isFind != -1:\n isExist = True\n break\n except:\n print (\"读取失败%s\",currentFilePath)\n finally:\n f.close()\n if isExist:\n break\n\n if not isExist:\n print (\"找到无用资源:\",nameModel.file)\n invalidResList.append(nameModel)\n return invalidResList\n\ndef rmDir(fileOrDir):\n cmd = \"rm -rf \"+fileOrDir\n os.system(cmd)\n\ndef getName(path):\n pathlist = path.split(\"/\")\n timeStamp = int(time.time())\n nameDir = \"{}_{}\".format(pathlist[-1],timeStamp)\n # nameDir = time.strftime(\"%Y-%m-%d-%H_%M_%S\",pathlist[-1],time.localtime(time.time())) \n return nameDir\n\n\ndef main():\n # cmd_cp = \"mkdir -p \"+scanTargetDir +\" | cp -rf \"+scanSrcPath+\" \"+ scanTargetDir\n # os.system(cmd_cp)\n shutil.copytree(scanSrcPath, scanTargetDir)\n shutil.copytree(scanSrcExtendPath,os.path.join(scanTargetDir,scanSrcExtendPath.split(\"/\")[-1]))\n if outPods:\n rmDir(scanTargetDir+\"/Pods\") \n\n\n # scanImagePathCfg = [\n # (\".imageset\",\n # [scanTargetDir+\"/YYMobile/Images.xcassets\",\n # scanTargetDir+\"/YYMobile/YingShou.xcassets\",\n # scanTargetDir+\"/YYMobile/TemplatePlugin/MakeFriends/yytp_makefriend.xcassets\",\n # scanTargetDir+\"/YYMobile/TemplatePlugin/OnePiece/OnePiece.xcassets\",\n # scanTargetDir+\"/YYMobile/TemplatePlugin/VoiceRoom/Images/VoiceRoom.xcassets\"]\n # ),\n # (\".png\",\n # [scanTargetDir])#在无xcassets的情况下使用\n # ]\n\n xcassetsPathList = getDirOrFileBySuffix(scanTargetDir,\".xcassets\")\n print(\"有以下xcassets\\n【{0}】\".format(xcassetsPathList))\n scanImagePathCfg = [\n (\".imageset\",\n xcassetsPathList\n ),\n (\".png\",\n [scanTargetDir])#在无xcassets的情况下使用\n ]\n\n #白名单中的不会检查\n # whiteList = [\"3rd/SSKeychain/Example/iOS/Images.xcassets\",\n # \"YYMobile/YingShou.xcassets\",\n # ]\n whiteList = []\n\n def isInWhileList(curPath):\n for white in whiteList:\n if white in curPath:\n return True\n return False\n\n\n for cfg in scanImagePathCfg:\n suffix = cfg[0]\n for scanImagePath in cfg[1]:\n if isInWhileList(scanImagePath):\n continue\n imageNamelist = []\n print(\"开始检查【{0}】\".format(scanImagePath))\n imageNamelist = []\n if os.path.isdir(scanImagePath) and suffix == \".imageset\":\n imageNamelist = getImagesetNamelist(scanImagePath,suffix)\n else:\n imageNamelist = getImageNamelist(scanImagePath,suffix)\n invalidResList = scanAction(imageNamelist,scanTargetDir)\n invalidResList.sort(key = lambda filemodel:(filemodel.file,filemodel.size),reverse = True)\n #输出\n result = \"资源名\\t大小K\\t路径\\n\"\n for model in invalidResList:\n result += \"{}\\t{:.2f}\\t{}\\n\".format(model.file,model.size/1024.0,model.path)\n outFileName = getName(scanImagePath)\n outputDir = outPath+\"unuseRes\"\n os.system(\"mkdir -p \"+outputDir)\n outputFilePath = os.path.join(outputDir,outFileName+\"_unuseRes.txt\") \n output = open(outputFilePath, 'w') \n output.write(result) \n output.close()\n rmDir(scanImagePath)\n \n\nif __name__ == \"__main__\":\n main()","repo_name":"lupeihong/OCScan","sub_path":"unuseResScan.py","file_name":"unuseResScan.py","file_ext":"py","file_size_in_byte":9318,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"42508672606","text":"from __main__ import app\nfrom app import db\nfrom app import ma\nfrom flask import Flask, request, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_marshmallow import Marshmallow\nimport uuid\n\nclass Checkout(db.Model):\n id = db.Column(db.String(100), primary_key=True)\n first_name = db.Column(db.String(100))\n last_name = db.Column(db.String(100))\n email = db.Column(db.String(100))\n phone_number = db.Column(db.String(10))\n amount = db.Column(db.Float)\n state = db.Column(db.String(30))\n reference = db.Column(db.String(100))\n currency = db.Column(db.String(3))\n\n def __init__(self, first_name, last_name, email, phone_number, amount, reference, currency):\n self.id = 'co-' + str(uuid.uuid4())\n self.first_name = first_name\n self.last_name = last_name\n self.email = email\n self.phone_number = phone_number\n self.amount = amount\n self.reference = reference\n self.currency = currency\n self.state = 'created'\n\n# Checkout Schema\nclass CheckoutSchema(ma.Schema):\n class Meta:\n fields = ('id', 'first_name', 'last_name', 'email', 'phone_number', 'amount', 'reference', 'currency', 'state')\n\n# init schema\ncheckout_schema = CheckoutSchema()\ncheckouts_schema = CheckoutSchema(many=True)\n\n# Create a checkout\n@app.route('/checkouts', methods=['POST'])\ndef create_checkout():\n first_name = request.json['first_name']\n last_name = request.json['last_name']\n email = request.json['email']\n phone_number = request.json['phone_number']\n amount = request.json['amount']\n reference = request.json['reference']\n currency = request.json['currency']\n\n new_checkout = Checkout(first_name, last_name, email, phone_number, amount, reference, currency)\n\n db.session.add(new_checkout)\n db.session.commit()\n\n return checkout_schema.jsonify(new_checkout)\n\n@app.route('/checkouts/', methods=['GET'])\ndef retrieve_checkout(id):\n checkout = Checkout.query.get(id)\n if(checkout == None):\n return jsonify({'Error': 'Checkout does not exist'})\n else: \n return checkout_schema.jsonify(checkout)\n\n# helper endpoint to approve a checkout for charge \n@app.route('/checkouts/approve/', methods=['PUT'])\ndef update_checkout(id):\n checkout = Checkout.query.get(id)\n\n checkout.state = 'approved'\n\n db.session.commit()\n\n return checkout_schema.jsonify(checkout)","repo_name":"KyleMcSweeney3/eCommerce-API","sub_path":"checkouts.py","file_name":"checkouts.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"42733096546","text":"import random\nfrom typing import Union\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom ProcessSimulator.src.simulator.process_model import ProcessSimulator, ProcessStepFunction, BinetTensorSpec, \\\n Preprocessing\nfrom ProcessSimulator.src.simulator.signal_generator import perlin_noise, transition, add_noise, spaced_sawtooth, \\\n add_trend, padding, add_spike_cluster\n\n\"\"\"\n\nVery Easy Process with Sensor Data\n\"\"\"\n\n\nclass LaboratorySimulator(ProcessSimulator):\n DECIMALS = 2\n\n @property\n def __name__(self):\n return 'LaboratorySimulator'\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n self.add_edge(origin='start', dest='customer_meeting')\n\n # Step 0 - Customer Meeting\n self.add_node(id='customer_meeting', label='Customer Meeting')\n self.add_edge(origin='customer_meeting', dest='scan')\n\n # Step 1 - Scan\n self.add_node(id='scan', label='Scan')\n self.add_edge(origin='scan', dest='3d_design')\n\n # Step 2 - 3D Design\n self.add_node(id='3d_design', label='3D Design')\n self.add_edge(origin='3d_design', dest='print_prep')\n\n def process_type(self) -> list:\n chosen_type = random.choice(['mold', 'cast'])\n self.process_properties['process_type'] = chosen_type\n if chosen_type == 'mold':\n return [0]\n elif chosen_type == 'cast':\n return [1]\n else:\n raise Exception('process_type not chosen correctly')\n\n self.add_attribute(node_id='3d_design', attribute_function=process_type,\n attributes_signature=BinetTensorSpec(shape=(1,), dtype=tf.int8, name='product_type'))\n\n # Step 3 - Print Preparation\n\n self.add_node(id='print_prep', label='Print Prep')\n self.add_edge(origin='print_prep', dest='print')\n\n # Step 4 - Print\n\n self.add_node(id='print', label='Print')\n self.add_edge(origin='print', dest='wash')\n\n def sensor_temperature(self) -> list:\n result_type = np.random.choice(['cold', 'normal', 'hot'], p=[0.03, 0.92, 0.05])\n if result_type == 'cold':\n flexible_heat = random.uniform(10, 12)\n signal = perlin_noise(amplitude=1, wavelength=400, octaves=5, divisor=2, num_points=300, fixed=10,\n variable=flexible_heat)\n elif result_type == 'hot':\n flexible_heat = random.uniform(13, 20)\n signal = perlin_noise(amplitude=1, wavelength=400, octaves=5, divisor=2, num_points=300, fixed=30,\n variable=flexible_heat)\n elif result_type == 'normal':\n flexible_heat = random.uniform(10, 12)\n signal = perlin_noise(amplitude=1, wavelength=400, octaves=5, divisor=2, num_points=300, fixed=30,\n variable=flexible_heat)\n\n else:\n raise Exception('result_type %s not implemented' % result_type)\n\n signal = transition(signal, strength=6)\n\n self.process_properties['print_temperature'] = max(signal)\n return signal\n\n self.add_attribute(node_id='print', attribute_function=sensor_temperature,\n attributes_signature=BinetTensorSpec(shape=(300,), dtype=tf.float32,\n name='sensor_print_temp'))\n\n def load_curve(self) -> list:\n anomalous = np.random.choice([0, 1], p=[0.95, 0.05])\n signal = add_noise(spaced_sawtooth(30, 20, anomaly=anomalous), strength=0.05)\n self.process_properties['load_curve_anomaly'] = anomalous\n return signal\n\n self.add_attribute(node_id='print', attribute_function=load_curve,\n attributes_signature=BinetTensorSpec(shape=(600,), dtype=tf.float32,\n name='sensor_load_curve'))\n\n def skipped_layer(self) -> list:\n layer_skipped = np.random.choice([0, 1], p=[0.95, 0.05])\n self.process_properties['skipped_layer'] = layer_skipped\n return [layer_skipped]\n\n self.add_attribute(node_id='print', attribute_function=skipped_layer,\n attributes_signature=BinetTensorSpec(shape=(1,), dtype=tf.int8, name='skipped_layer'))\n\n def print_finished(self) -> list:\n finished = np.random.choice([1, 0], p=[0.99, 0.01])\n self.process_properties['print_finished'] = finished\n return [finished]\n\n self.add_attribute(node_id='print', attribute_function=print_finished,\n attributes_signature=BinetTensorSpec(shape=(1,), dtype=tf.int8, name='print_finished'))\n\n # Step 5 - Wash\n class CheckSensor(ProcessStepFunction):\n __destination__ = ['cure', 'fix']\n\n def destination(self, model) -> Union[int, str]:\n if model.process_properties['broken_sensor'] == True:\n return self.__destination__[1]\n else:\n return self.__destination__[0]\n\n def isopropanol_curve(self) -> list:\n result_type = np.random.choice(['short', 'normal', 'long'], p=[0.03, 0.94, 0.03])\n broken_sensor = np.random.choice([False, True], p=[0.95, 0.05])\n isopropanol_purity_start = np.round(np.random.uniform(low=0.85, high=1), self.DECIMALS).astype(float)\n if result_type == 'short':\n wash_duration = random.randint(50, 170)\n elif result_type == 'normal':\n wash_duration = random.randint(200, 500)\n elif result_type == 'long':\n wash_duration = random.randint(530, 620)\n else:\n raise Exception('result_type not chosen correctly')\n signal = add_trend([isopropanol_purity_start] * wash_duration, strength=0.05, negative=True)\n self.process_properties['wash_duration'] = wash_duration\n self.process_properties['broken_sensor'] = broken_sensor\n self.process_properties['isopropanol_purity_min'] = min(signal)\n if broken_sensor:\n signal = add_spike_cluster(signal)\n result = np.zeros(620)\n result[:len(signal)] = signal\n return result\n\n self.add_node(id='wash', label='Wash')\n self.add_decision(origin='wash', dest=CheckSensor, label='LD1: Is the sensor broken?')\n\n self.add_attribute(node_id='wash', attribute_function=isopropanol_curve,\n attributes_signature=BinetTensorSpec(shape=(620,), dtype=tf.float32,\n name='sensor_washing'))\n\n self.add_node(id='fix', label='Fix Sensor')\n self.add_edge(origin='fix', dest='cure')\n\n # Step 6 - Cure\n self.add_node(id='cure', label='Cure')\n self.add_edge(origin='cure', dest='material_test')\n\n def cure_curve(self) -> list:\n \"\"\"\n 120 - 300\n :param self:\n :return: Seconds\n \"\"\"\n energy = np.round(np.random.uniform(low=2, high=4), self.DECIMALS).astype(float) # mWatt\n cure_duration = random.randint(250, 300)\n signal = add_noise([energy] * cure_duration)\n self.process_properties['cure_duration'] = cure_duration\n self.process_properties['cure_energy_joule'] = sum(signal)\n result = np.zeros(300)\n result[:len(signal)] = signal\n return result\n\n self.add_attribute(node_id='cure', attribute_function=cure_curve,\n attributes_signature=BinetTensorSpec(shape=(300,), dtype=tf.float32,\n name='sensor_cure_energy'))\n\n # Step 7 - Material Test\n\n self.add_node(id='material_test', label='Material Test')\n\n class MaterialTest(ProcessStepFunction):\n __destination__ = ['cure', 'print_prep', 'end', 'cast_isolation']\n\n def destination(self, model) -> Union[int, str]:\n if model.process_properties['cure_energy_joule'] < 600: # mJoule\n return self.__destination__[0]\n\n flawless = model.process_properties['skipped_layer'] == False \\\n and model.process_properties['print_finished'] == True \\\n and model.process_properties['print_temperature'] < 40 \\\n and model.process_properties['print_temperature'] > 20 \\\n and model.process_properties['load_curve_anomaly'] == False \\\n and 500 > model.process_properties['wash_duration'] > 200 \\\n and model.process_properties['isopropanol_purity_min'] > 0.8\n\n if not flawless:\n return self.__destination__[1]\n if model.process_properties['process_type'] == 'mold':\n return self.__destination__[2]\n elif model.process_properties['process_type'] == 'cast':\n return self.__destination__[3]\n else:\n raise Exception('process_type must be mold or cast')\n\n self.add_decision(origin='material_test', dest=MaterialTest, label='LD2: Was the print successful?')\n\n # Step 8 - Cast Isolation\n\n self.add_node(id='cast_isolation', label='Cast Isolation')\n\n self.add_edge(origin='cast_isolation', dest='drying')\n\n # Step 9 - Drying\n\n self.add_node(id='drying', label='Drying')\n self.add_edge(origin='drying', dest='casting')\n\n def dry_temperature_curve(self) -> list:\n short = np.random.choice([True, False], p=[0.05, 0.95])\n if short:\n dry_duration = random.randint(120, 540)\n else:\n dry_duration = random.randint(600, 1320)\n self.process_properties['dry_duration'] = dry_duration\n flexible_heat = random.uniform(5, 25)\n signal = perlin_noise(amplitude=1, wavelength=10, octaves=3, divisor=2, num_points=dry_duration, fixed=30,\n variable=flexible_heat)\n self.process_properties['dry_temp'] = sum(signal)\n signal = transition(signal, strength=6, position='bilateral')\n signal = padding(signal, size=1320)\n self.process_properties['print_temperature'] = max(signal)\n\n # Compute duration for the next step already here\n # Dirty hack to have the same duration in two parallel timeseries attributes\n too_short = np.random.choice([True, False], p=[0.02, 0.98])\n if too_short:\n poly_duration = random.randint(10, 24)\n else:\n poly_duration = random.randint(25, 45)\n self.process_properties['poly_duration'] = poly_duration\n return signal\n\n self.add_attribute(node_id='drying', attribute_function=dry_temperature_curve,\n attributes_signature=BinetTensorSpec(preprocessing=Preprocessing.CONVOLUTION, shape=(1320,),\n dtype=tf.float32, name='sensor_dry_temp'))\n\n # Step 10 - Casting\n\n self.add_node(id='casting', label='Casting')\n\n self.add_edge(origin='casting', dest='polymerizing')\n\n # Step 11 - Polymerizing\n\n self.add_node(id='polymerizing', label='Polymerizing')\n self.add_edge(origin='polymerizing', dest='extract')\n\n def pressure_curve(self) -> list:\n lid_not_closed_properly = np.random.choice([True, False], p=[0.05, 0.95])\n poly_duration = self.process_properties['poly_duration']\n if lid_not_closed_properly:\n pressure = np.round(np.random.uniform(low=1, high=2.5), self.DECIMALS).astype(float)\n else:\n pressure = np.round(np.random.uniform(low=3, high=4), self.DECIMALS).astype(float)\n self.process_properties['pressure'] = pressure\n signal = transition(add_noise([pressure] * poly_duration), strength=1.5, position='bilateral')\n signal = padding(signal, size=45)\n return signal\n\n self.add_attribute(node_id='polymerizing', attribute_function=pressure_curve,\n attributes_signature=BinetTensorSpec(shape=(45,), dtype=tf.float32, name='sensor_pressure'))\n\n def poly_temp(self) -> list:\n poly_duration = self.process_properties['poly_duration']\n flexible_heat = random.uniform(15, 25)\n signal = perlin_noise(amplitude=1, wavelength=10, octaves=3, divisor=2, num_points=poly_duration, fixed=40,\n variable=flexible_heat)\n self.process_properties['poly_temp'] = max(signal)\n signal = transition(signal, strength=2, position='bilateral')\n signal = padding(signal, size=45)\n self.process_properties['print_temperature'] = max(signal)\n return signal\n\n self.add_attribute(node_id='polymerizing', attribute_function=poly_temp,\n attributes_signature=BinetTensorSpec(shape=(45,), dtype=tf.float32, name='sensor_poly_temp'))\n\n # Step 12 - Extract\n\n self.add_node(id='extract', label='Extract')\n\n class Extract(ProcessStepFunction):\n __destination__ = ['end', 'print']\n\n def destination(self, model) -> Union[int, str]:\n flawless = model.process_properties['dry_temp'] > 2400 \\\n and model.process_properties['dry_duration'] > 600 \\\n and model.process_properties['pressure'] > 3 \\\n and model.process_properties['poly_temp'] > 45 \\\n and model.process_properties['poly_duration'] > 25\n if flawless:\n return self.__destination__[0]\n else:\n return self.__destination__[1]\n\n self.add_decision(origin='extract', dest=Extract, label='LD3: Broke during extraction?')\n\n # Step 13 - Finish\n\n self.add_node(id='end', label='End')\n\n class Finish(ProcessStepFunction):\n __destination__ = ['start']\n\n def destination(self, model) -> Union[int, str]:\n model.reset()\n return model.last_visited_step_id\n\n self.add_decision(origin='end', dest=Finish)\n","repo_name":"ErikBird/SensorProcessMining","sub_path":"code/ProcessSimulator/src/processes/laboratory_process_sensor.py","file_name":"laboratory_process_sensor.py","file_ext":"py","file_size_in_byte":14636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"72995280170","text":"\nimport numpy as np\nimport cv2\nimport pdb\nimport math\n\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\neye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') \nmouth_cascade = cv2.CascadeClassifier('haarcascade_mcs_mouth.xml')\nnose_cascade = cv2.CascadeClassifier('haarcascade_mcs_nose.xml')\n\nimg = cv2.imread('sampleFaceImage3.JPG')\nimg2 = img.copy()\n#img = cv2.imread('sampleFaceImage2.jpg')\n#img = cv2.imread('sampleFaceImage3.JPG')\n#----For Debugging-------\n# img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nheight, width, depth= img.shape\nheight, width = width, height\nmaxDimension = 400\nif (height>width):\n dim = (maxDimension, int(((width*maxDimension)/height)))\n img = cv2.resize(img, dim)#, interpolation = cv2.INTER_AREA)\nelse:\n dim = (int(((height*maxDimension)/width)), maxDimension)\n# pdb.set_trace();\nimg = cv2.resize(img, dim)#, interpolation = cv2.INTER_AREA)\n# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n#img2 = cv2.resize(img, img2, np.array([height, width]), b, b, cv2.INTER_LINEAR)\n\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\ncv2.equalizeHist(gray, gray)\n\nfaces = face_cascade.detectMultiScale(gray, 1.1,2)\nmidPoint = np.arange(8)\n#midPoint = [0 for x in range(6)]\n\nmask = np.zeros(img.shape[:2],dtype = np.uint8) # mask initialized to PR_BG\nbgdmodel = np.zeros((1,65),np.float64)\nfgdmodel = np.zeros((1,65),np.float64)\nfor (x,y,w,h) in faces:\n cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\n rect = (max((x-w/2), 0),max((y-h/2),0),2*w,2*h)\n #cv2.equalizeHist(img,rect)\n cv2.grabCut(img,mask,rect,bgdmodel,fgdmodel,1,cv2.GC_INIT_WITH_RECT)\n\n\nmask2 = np.where((mask==1) + (mask==3),255,0).astype('uint8')\noutput = cv2.bitwise_and(img,img,mask=mask2)\n\ncv2.imshow('input image',img)\ncv2.imshow('output image',output)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n\n","repo_name":"ashray/MITDentalIntern","sub_path":"grabcut_modified.py","file_name":"grabcut_modified.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"55"} +{"seq_id":"17004804124","text":"import boto3\nfrom dotenv import load_dotenv\nimport requests\nimport pprint as pp\nimport random\n\n\ndef main():\n dynamodb = boto3.resource(\n 'dynamodb',\n region_name=\"us-west-2\"\n )\n\n table = dynamodb.create_table(\n TableName='Pokemons',\n KeySchema=[\n {\n 'AttributeName': 'name',\n 'KeyType': 'HASH'\n },\n {\n 'AttributeName': 'id',\n 'KeyType': 'RANGE'\n }\n ],\n AttributeDefinitions=[\n {\n 'AttributeName': 'name',\n 'AttributeType': 'S'\n },\n {\n 'AttributeName': 'id',\n 'AttributeType': 'N'\n },\n\n ],\n ProvisionedThroughput={\n 'ReadCapacityUnits': 1,\n 'WriteCapacityUnits': 1\n }\n\n )\n # Wait until the table exists.\n table.wait_until_exists()\n print(table)\n print(list(dynamodb.tables.all()))\n return table\n\n\ndef get_pokemons(api_url):\n response = requests.get(api_url)\n res = response.json()\n return res\n\n\ndef insert_pokemon(table, pokemon):\n table.put_item(\n Item={\n 'name': pokemon['name'],\n 'id': pokemon['id'],\n 'abilities': pokemon['abilities'],\n 'height': pokemon['height'],\n }\n )\n\n\ndef pokemon_exist(table, pokemon):\n response = table.get_item(\n Key={\n 'name': pokemon['name'],\n 'id': pokemon['id'],\n }\n )\n if 'Item' in response:\n return True\n else:\n return False\n\ndef retrive_pokemon(table, pokemon):\n response = table.get_item(\n Key={\n 'name': pokemon['name'],\n 'id': pokemon['id'],\n }\n )\n\n item=response[\"Item\"]\n name=item[\"name\"]\n id=item[\"id\"]\n abilities=item[\"abilities\"]\n height=item[\"height\"]\n pp.pprint(f\"name: {name} , id: {id} , abilities: {abilities} , height: {height} \")\n\nif __name__ == '__main__':\n load_dotenv()\n pokemon_table = main()\n api_url = \"https://pokeapi.co/api/v2/pokemon\"\n result = get_pokemons(api_url)\n pokemon_list = result[\"results\"]\n draw =\"yes\"\n while draw == \"yes\":\n draw=input(\"Would you like to draw a Pokemon? yes/no: \")\n if draw == \"yes\" :\n pokemon = random.choice(pokemon_list)\n pokemon_name = pokemon[\"name\"]\n pokemon_url = pokemon[\"url\"]\n api_url = pokemon_url\n pokemon = get_pokemons(api_url)\n pokemon_id = pokemon[\"id\"]\n\n if pokemon_exist(pokemon_table, pokemon) == False:\n insert_pokemon(pokemon_table, pokemon)\n\n retrive_pokemon(pokemon_table, pokemon)\n if draw != 'yes':\n print(\"Goodbye, have a nice day!\")\n\n\n\n#pokemons_table.delete()","repo_name":"ingulator/PokemonDynamoDB","sub_path":"LabDynamoDB.py","file_name":"LabDynamoDB.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"10233729865","text":"import os\nimport cv2\nimport numpy as np\nroot_path=\"./images\"\nout_path=\"./result\"\nA1 = np.array([255,255,255])\nD1=np.array([250,250,250])\nB1=np.array([0,0,0])\nC1=np.array([100,100,100])\nadd_num=np.array([50,50,50]).astype(np.uint8)\nblack=np.array([0,0,0]).astype(np.uint8)\n# sub_num=np.array([50,50,50]).astype(np.uint8)\n# print(add_num)\nfor i in os.listdir(root_path):\n filename=os.path.join(root_path,i)\n img=cv2.imread(filename)\n for x in range(img.shape[0]):\n for y in range(img.shape[1]):\n # if (img[x,y,:]<=A1-add_num).all() and (img[x,y,:]>B1).all():\n if (img[x,y,:]>B1).all() and (img[x,y,:] 255, 255, img)\n out_img = np.where(tmp_img < 0, 0, tmp_img)\n # cv2.imshow(\"img\",out_img)\n # cv2.waitKey(0)\n cv2.imwrite(os.path.join(out_path,i),out_img)","repo_name":"mohenghui/xianGaoPaint","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"13158351600","text":"from multiprocessing import Process\nimport os\n\n\ndef info(title):\n print(title)\n print('module name:', __name__)\n print('parent process', os.getppid())\n print('process id:', os.getpid())\n\n\ndef f(name):\n print('Hello %s' % name)\n print(os.getpid())\n\n\ndef q(name):\n print('Hello %s' % name)\n print(os.getpid())\n\n\nif __name__ == '__main__':\n info('main line')\n p = Process(target=f, args=('xiaoming',))\n d = Process(target=q, args=('xiaohu', ))\n p.start()\n d.start()\n d.join()\n p.join()","repo_name":"GBXZ/pythoncode","sub_path":"ceshi/multiprocesssing/Process.py","file_name":"Process.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"11034575021","text":"import time\nimport serial\n\nprint(\"Starting UART\")\nser = serial.Serial(\n port='/dev/serial0', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0\n baudrate = 115200,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS,\n)\n\nprint(\"Sending Messages\")\nmessages = [0x00, 0x01, 0x02, 0x03, 0x04]\nfor msg in messages:\n print(f\"<<< {msg}\")\n ser.write(b\"Hello world\")\n time.sleep(1)\n print(ser.read(size=1))\n","repo_name":"murexrobotics/murex-2024","sub_path":"test-code/uart.py","file_name":"uart.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"55"} +{"seq_id":"40017657345","text":"import os\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nSECRET_KEY = 'c+#8x$+zfq00i(z@6_81ht9i-0dcp53iyl_bp$mr^f22k600i*'\n\nDEBUG = True\n\nALLOWED_HOSTS = []\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'rest_framework',\n 'register',\n 'inventory'\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n)\n\nROOT_URLCONF = 'orthosie.urls'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n)\n\nTEMPLATE_DIRS = (\n os.path.join(os.path.dirname(__file__), '../templates').replace('\\\\', '/'),\n)\n\nWSGI_APPLICATION = 'orthosie.wsgi.application'\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'orthosie/orthosie.db'),\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': '',\n }\n}\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'America/New_York'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nSTATIC_URL = '/static/'\n\nADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)\n\nSTATICFILES_DIRS = (\n os.path.join(os.path.dirname(__file__), '../static').replace('\\\\', '/'),\n)\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\nTAX = .075\nPRINTER = '/dev/null'\nRECEIPT_HEADER = ['Header 1', 'Header 2']\nRECEIPT_FOOTER = ['Footer 1', 'Footer 2']\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n 'LOCATION': '127.0.0.1:11211',\n }\n}\n\nTEST_RUNNER = 'django.test.runner.DiscoverRunner'\n","repo_name":"gitter-badger/orthosie","sub_path":"orthosie/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"55"} +{"seq_id":"9600708307","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n\tpath('', views.index, name='index'),\n\tpath('about/', views.about, name='about'),\n path('hello/', views.hello, name='hello'),\n path('proyectos/',views.proyectos, name='proyectos'),\n path('proyectos/',views.detalle_proyectos, name='detalle_proyectos'),\n path('tareas/',views.tareas, name='tareas'),\n path('crear_tarea/',views.crear_tareas, name='crear_tarea'),\n path('crear_proyecto/',views.crear_proyectos, name='crear_proyecto'),\n path('lucas/',views.lucas, name='lucas')\n]\n","repo_name":"oterl/django","sub_path":"miapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"26037926408","text":"import torch\nimport random\n\nimport footsteps\n\nimport icon_registration\nimport icon_registration.pretrained_models\nimport glob\n\nmodel = icon_registration.pretrained_models.brain_registration_model(pretrained=True)\nGPUS=4\nBATCH_SIZE=4\nif GPUS == 1:\n model_par = model.cuda()\nelse:\n model_par = torch.nn.DataParallel(model).cuda()\nopt = torch.optim.Adam(model_par.parameters(), lr=0.00005)\n\nmodel_par.train()\n\ndataset = torch.load(\"/playpen-ssd/tgreer/ICON_brain_preprocessed_data/BRATS_.9_mosttrain-6/BRATS_train_train.torch\")\n\ndef make_batch():\n pairs = [random.choice(dataset) for _ in range(GPUS * BATCH_SIZE)]\n\n for i in range(GPUS * BATCH_SIZE):\n if random.random() > .5:\n pairs[i] = (pairs[i][1], pairs[i][0])\n\n image_A = torch.cat([p[0] for p in pairs]).cuda()\n image_B = torch.cat([p[1] for p in pairs]).cuda()\n return image_A, image_B\n\n\nicon_registration.train_batchfunction(\n model_par, opt, make_batch, steps=50000, unwrapped_net=model\n)\n","repo_name":"HastingsGreer/BratsRegGradICON","sub_path":"finetune_brats.py","file_name":"finetune_brats.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"24899841139","text":"import os, sys, hashlib, torch\nimport numpy as np\nfrom PIL import Image\nimport torch.utils.data as data\nfrom ..registry import DATASETS_CLS\nimport torchvision.transforms as transforms\n\ndef get_trans(info):\n assert isinstance(info, list)\n piplines = []\n for args in info:\n trans_cls = getattr(transforms, args.pop('type'))\n piplines.append(trans_cls(**args))\n return transforms.Compose(piplines)\n\n\nif sys.version_info[0] == 2:\n import cPickle as pickle\nelse:\n import pickle\n\n\ndef calculate_md5(fpath, chunk_size=1024 * 1024):\n md5 = hashlib.md5()\n with open(fpath, \"rb\") as f:\n for chunk in iter(lambda: f.read(chunk_size), b\"\"):\n md5.update(chunk)\n return md5.hexdigest()\n\n\ndef check_md5(fpath, md5, **kwargs):\n return md5 == calculate_md5(fpath, **kwargs)\n\n\ndef check_integrity(fpath, md5=None):\n if not os.path.isfile(fpath):\n return False\n if md5 is None:\n return True\n else:\n return check_md5(fpath, md5)\n\n@DATASETS_CLS.register(\"ImageNet16\")\nclass ImageNet16(data.Dataset):\n # http://image-net.org/download-images\n # A Downsampled Variant of ImageNet as an Alternative to the CIFAR datasets\n # https://arxiv.org/pdf/1707.08819.pdf\n\n train_list = [\n [\"train_data_batch_1\", \"27846dcaa50de8e21a7d1a35f30f0e91\"],\n [\"train_data_batch_2\", \"c7254a054e0e795c69120a5727050e3f\"],\n [\"train_data_batch_3\", \"4333d3df2e5ffb114b05d2ffc19b1e87\"],\n [\"train_data_batch_4\", \"1620cdf193304f4a92677b695d70d10f\"],\n [\"train_data_batch_5\", \"348b3c2fdbb3940c4e9e834affd3b18d\"],\n [\"train_data_batch_6\", \"6e765307c242a1b3d7d5ef9139b48945\"],\n [\"train_data_batch_7\", \"564926d8cbf8fc4818ba23d2faac7564\"],\n [\"train_data_batch_8\", \"f4755871f718ccb653440b9dd0ebac66\"],\n [\"train_data_batch_9\", \"bb6dd660c38c58552125b1a92f86b5d4\"],\n [\"train_data_batch_10\", \"8f03f34ac4b42271a294f91bf480f29b\"],\n ]\n valid_list = [\n [\"val_data\", \"3410e3017fdaefba8d5073aaa65e4bd6\"],\n ]\n\n def __init__(self, root, is_train, transform, use_num_of_class_only=None):\n self.root = root\n self.transform = get_trans(transform)\n self.is_train = is_train # training set or valid set\n if not self._check_integrity():\n raise RuntimeError(\"Dataset not found or corrupted.\")\n\n self.data = []\n self.targets = []\n\n\n if self.is_train:\n downloaded_list = self.train_list\n\n else:\n downloaded_list = self.valid_list\n\n # now load the picked numpy arrays\n for i, (file_name, checksum) in enumerate(downloaded_list):\n file_path = os.path.join(self.root, file_name)\n # print ('Load {:}/{:02d}-th : {:}'.format(i, len(downloaded_list), file_path))\n with open(file_path, \"rb\") as f:\n if sys.version_info[0] == 2:\n entry = pickle.load(f)\n else:\n entry = pickle.load(f, encoding=\"latin1\")\n self.data.append(entry[\"data\"])\n self.targets.extend(entry[\"labels\"])\n self.data = np.vstack(self.data).reshape(-1, 3, 16, 16)\n self.data = self.data.transpose((0, 2, 3, 1)) # convert to HWC\n if use_num_of_class_only is not None:\n assert (\n isinstance(use_num_of_class_only, int)\n and use_num_of_class_only > 0\n and use_num_of_class_only < 1000\n ), \"invalid use_num_of_class_only : {:}\".format(use_num_of_class_only)\n new_data, new_targets = [], []\n for I, L in zip(self.data, self.targets):\n if 1 <= L <= use_num_of_class_only:\n new_data.append(I)\n new_targets.append(L)\n self.data = new_data\n self.targets = new_targets\n if self.is_train:\n self._set_group_flag()\n\n def _set_group_flag(self):\n \"\"\"Set flag according to image aspect ratio.\n\n Images with aspect ratio greater than 1 will be set as group 1,\n otherwise group 0.\n \"\"\"\n self.flag = np.zeros(len(self.data), dtype=np.uint8)\n # test\n for i in range(len(self.data)):\n self.flag[i] = 1 if i % 2 else 0\n\n def _rand_another(self, idx):\n pool = np.where(self.flag == self.flag[idx])[0]\n return np.random.choice(pool)\n\n def __repr__(self):\n return \"{name}({num} images, {classes} classes)\".format(\n name=self.__class__.__name__,\n num=len(self.data),\n classes=len(set(self.targets)),\n )\n\n def __getitem__(self, index):\n img, target = self.data[index], self.targets[index] - 1\n\n img = Image.fromarray(img)\n\n if self.transform is not None:\n img = self.transform(img)\n\n return {'img': img, 'gt_label': target}\n\n def __len__(self):\n return len(self.data)\n\n def _check_integrity(self):\n root = self.root\n for fentry in self.train_list + self.valid_list:\n filename, md5 = fentry[0], fentry[1]\n fpath = os.path.join(root, filename)\n if not check_integrity(fpath, md5):\n return False\n return True\n","repo_name":"C-ID/automl-nas","sub_path":"core/dataset/dataset_construct/imagenet120.py","file_name":"imagenet120.py","file_ext":"py","file_size_in_byte":5247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"40240954182","text":"# Create your views here.\n#a view is supposed to send a http object with the content of the page that will be shown in the templates\n\nfrom django.shortcuts import render_to_response, get_object_or_404, redirect, HttpResponseRedirect, HttpResponse\nfrom django import forms\nfrom django.db import connection, transaction\nfrom django.db.models import Q\nfrom django.template import RequestContext\nfrom django.core.urlresolvers import reverse\n\nfrom plato.models import User, Group, EnsFile, Page, Tool, KW\nfrom util import auth, object_util\nfrom util.object_util import *\nfrom util.views import *\n\nimport datetime\n\nfrom plato.form import *\n\n\n##############################################################################################\n\t###################################### INDEX ########################################\n##############################################################################################\n\n#def check_login(request):\ndef index(request, error=None):\n\t\"\"\"\n\t\\brief{just render the index page, with the last publication, tools and data and the most viewed publication, tools and data}\n\t\"\"\"\n\n\t# publications are always render ! \n\tlp = Page.objects.filter(flag_suppr=False).order_by('-id_page')[:5]\n\n\t# if logged => render all the tools, only the visible otherwise !\n\tif request.session.has_key('login'):\n\t\tlt = Tool.objects.all().order_by('-date_creation')[:5]\n\telse:\n\t\tlt = Tool.objects.filter(visible=True).order_by('-date_creation')[:5]\n\n\t# if logged => render all the data, public ones otherwise\n\t\n\tif request.session.has_key('login'):\n\t\tme = get_object_or_404(User,login = request.session['login'])\n\t\tlef = EnsFile.objects.filter(Q(public=True)|Q(group__in=me.group_users.all())).order_by('-date_creation')[:5]\n\telse:\n\t\tlef = EnsFile.objects.filter(public=True).order_by('-date_creation')[:5]\n\n\tld = Demo.objects.all().order_by('-date_creation')[:5]\n\n\tif not request.session.has_key('lang'):\n\t\trequest.session['lang'] = 'en' # create the 'lang' key in the cookies for multi langage support\n\n\treturn render_to_response('users/index.html',{'lp': lp,'lt': lt,'lef': lef, 'ld':ld,'error_message':error}, context_instance=RequestContext(request))\n\n\n##############################################################################################\n\t######################### Shows Users and User information ###########################\n##############################################################################################\ndef show_users(request):\n\t\"\"\"\n\t\\brief{view all the TSI personal, usrs are the currents persons, olds are the alumni }\n\t\"\"\"\n\tusrs = User.objects.exclude(nm_person__exact=\"guest\").filter(actif=True).order_by('status','nm_person')\n\tolds = User.objects.exclude(nm_person__exact=\"guest\").exclude(actif=True).order_by('status','nm_person')\n\treturn render_to_response('users/usrs.html',{\n\t\t'usrs': usrs,\n\t\t'olds': olds,\n\t\t},context_instance=RequestContext(request))\n\t\n\ndef usr(request, log):\n\t\"\"\"\n\t\\brief{View of personal info of the log person }\n\t\\input{log : String that contains the log information}\n\t\\author{B.Petitpas}\n\t\\date{03/05/2012}\n\t\\version{1}\n\t\"\"\"\n\tuser = get_object_or_404(User,login=log)\n\tboss = None\n\tif user.id_boss:\n\t\tboss = get_object_or_404(User,id_user=user.id_boss) # get the boss information\n\tflag = False\n\tif request.session.has_key('login'):\n\t\tif log == request.session['login']:\n\t\t\tflag= True # flag equal true if the connected person is the person that you want to see\n\t\t#sess = request.session.load()\n\treturn render_to_response('users/usr.html',{\n\t\t'User': user,\n\t\t'f' : flag,\n\t\t'boss': boss,\n\t\t},context_instance=RequestContext(request))\n\n\n#error function \ndef display_error(request,error):\n\tif not error:\n\t\treturn render_to_response('error_msg.html',{'error_message' : \"fill the formular please\" },context_instance=RequestContext(request))\n\telse:\n\t\treturn render_to_response('error_msg.html',{'error_message' : error},context_instance=RequestContext(request))\n\t\t\n\n\n#function to change the langage into the cookie 'put that cookie down!'\ndef change_lang(request):\n\t\"\"\"\n\ttake the \n\t\"\"\"\n\t\n\tif request.GET.has_key('value'):\n\t\tv = request.GET['value']\n\t\tif v == 'fr': #french selected\n\t\t\trequest.session['lang']='fr'\n\t\telse:\n\t\t\trequest.session['lang']='en'\n\t#return HttpResponse(v)\n\treturn return_referer(request)\n\t#return redirect(request.META['HTTP_REFERER'])\n","repo_name":"ben6684/PLATO","sub_path":"plato/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"4544872009","text":"from django.urls import path\nfrom FirstApp.views import viewStudentInfoForm, testView, index, helpView, displayUserInfo, viewBasicForm, relativeURL, other\n\n\n\napp_name = \"FirstApp\"\n\nurlpatterns = [\n path('', helpView),\n path('info/', displayUserInfo),\n path('form/', viewBasicForm),\n path('studentinfo/', viewStudentInfoForm),\n path('relative/', relativeURL, name = \"relative\"),\n path('other/', other, name = \"other\"),\n path('index/', index, name = \"index\"),\n]","repo_name":"AjaykumarGP/Django-Development","sub_path":"FirstApp/FirstAppURLs.py","file_name":"FirstAppURLs.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"30822610510","text":"#1.\r\ndef birthdate(dic_1,name):\r\n for key, value in dic_1.items():\r\n if (key == name):\r\n print(value)\r\n break\r\n elif (key == 'Hardik Pandya'):\r\n print(\"Player not found\")\r\ndic_1 = {\r\n 'Virat Kohli': '5 November 1988',\r\n 'Umesh Yadav': '25 October 1987',\r\n 'Manish Pandey': '10 September 1989',\r\n 'Rohit Sharma': '30 April 1987',\r\n 'Ravindra Jadeja': '6 December 1988',\r\n 'Hardik Pandya': '11 October 1993'\r\n}\r\nname = input(\"Enter the name of the player : \")\r\nbirthdate(dic_1,name)\r\n#2.\r\n\r\n\r\ns=(\"\"\"I bought a new laptop for $3.5k. The medel was recommended by my friend, Dr. Smith. I like its functionalities, but found that the same model is sold for only $2.8k at amazon .com... Lessonslearned? It’s worth checking online prices before shopping!\"\"\")\r\nd = { x: ele for x, ele in enumerate(s.split(\". \"))}\r\nprint(d)\r\n\r\n\r\n#3\r\ndef encodeQr(s):\r\n ns=\"\"\r\n for i in range(0,len(s)):\r\n l1=['0','0','0','0','0','0','0','0']\r\n l1[i]='1'\r\n pre=''.join(l1)\r\n asc=ord(s[i])\r\n b1=bin(asc)\r\n ns= ns+pre+b1[2:]\r\n x=lambda ns: ns+\"000\" if(len(ns)>50) else(ns+\"00\" if(len(ns)>70) else ns)\r\n print(x(ns))\r\ns = input(\"Enter the string \")\r\nencodeQr(s)\r\n\r\n#3-b\r\nimport python_module_16 as p\r\ns = input(\"Enter the string \")\r\np.encodeQr(s)\r\n","repo_name":"AkshayaAgarwal/PythonLabs","sub_path":"Labs/16.8.22 Q4.py","file_name":"16.8.22 Q4.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"26194226163","text":"\n# Advent of Code 2015 - Day 14 Part 1\n# 30 Nov 2021 Brian Green\n#\n# Problem:\n# What distance has the winning reindeer traveled?\n#\n\nimport os\n\nfilename = \"data\" + os.sep + \"brian_aoc201514.dat\"\nwith open(filename) as data_file:\n data_set = data_file.readlines()\n\n# print(data_set)\n\nroster = {}\n\nfor deer in data_set:\n stats = deer.split()\n name = stats[0]\n speed = int(stats[3])\n duration = int(stats[6])\n cooldown = int(stats[13])\n # print(f\"{name} {speed} {duration} {cooldown}\")\n roster[name] = list([speed for i in range(duration)] +\n [0 for i in range(cooldown)])\n\n# print(roster)\n\nlog = {deer: 0 for deer in roster}\n\nfor t in range(2503):\n for deer in roster:\n log[deer] += roster[deer][t % len(roster[deer])]\n\n\nprint(log)\nprint(max(log.values()))\n","repo_name":"brianjgreen/AOC2020","sub_path":"python/aoc-2015/aoc-201514p1.py","file_name":"aoc-201514p1.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"72563008810","text":"'''\nWrite an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:\n\n Integers in each row are sorted from left to right.\n The first integer of each row is greater than the last integer of the previous row.\n\nFor example,\n.\nConsider the following matrix:\n\n[\n [1, 3, 5, 7],\n [10, 11, 16, 20],\n [23, 30, 34, 50]\n]\n\nGiven target = 3, return true.\n'''\nclass Solution:\n # @param matrix, a list of lists of integers\n # @param target, an integer\n # @return a boolean\n def searchMatrix(self, matrix, target):\n assert matrix\n m = len(matrix); n = len(matrix[0])\n l = 0; r = m * n - 1\n while l <= r:\n mid = (l + r) / 2\n val = matrix[mid/n][mid%n]\n if val == target: return True\n elif val > target: r = mid-1\n else: l = mid + 1\n return False","repo_name":"yzl232/code_training_leet_code","sub_path":"Search a 2D Matrix.py","file_name":"Search a 2D Matrix.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"29915069006","text":"import os\nimport shutil\nimport csv\n\n\n#csv path\ncsv_path = os.path.join('./', '.csv')\n\nroot_path = ''\n\nsave_path = '/'\nos.makedirs(save_path)\n\ndf = open(csv_path, 'r')\n\nread = csv.reader(df, delimiter=',')\n\nfor i, row in enumerate(read):\n barcode = row[0]\n dst = os.path.join(save_path, barcode)\n if not os.path.exists(dst):\n os.makedirs(dst)\n shutil.copy(os.path.join(root_path, row[1]), dst)\n \n \n \n","repo_name":"siraasony/TIL","sub_path":"basic_code_for_python/04_basic_move_with_csv.py","file_name":"04_basic_move_with_csv.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"15926184062","text":"from django.http import HttpResponse\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.conf import settings\nimport json\nimport requests\nfrom ndc_user.models import Ndc_user\nfrom django.contrib.auth import authenticate,login\n\ndef exe(social_account_name,auth_code,redirect_uri):\n if social_account_name == 'google':\n return _get_google_profile(auth_code,redirect_uri)\n\ndef _get_google_profile(auth_code,redirect_uri):\n token_url = 'https://accounts.google.com/o/oauth2/token'\n profile_url = 'https://www.googleapis.com/userinfo/v2/me'\n\n payload = dict(client_id=settings.OAUTH_GOOGLE_ID,\n redirect_uri=redirect_uri,\n client_secret=settings.OAUTH_GOOGLE_SECRETE,\n code=auth_code,\n grant_type='authorization_code')\n\n # Step 1. Exchange authorization code for access token.\n r = requests.post(token_url, data=payload)\n token = json.loads(r.text)\n headers = {'Authorization': 'Bearer {0}'.format(token['access_token'])}\n\n # Step 2. Retrieve information about the current user.\n r = requests.get(profile_url, headers=headers)\n profile = json.loads(r.text)\n return {\n 'email' : profile['email'],\n 'first_name' : profile['given_name'],\n 'last_name' : profile['family_name']\n }","repo_name":"khanhlu2013/ndc-ng2","sub_path":"account/get_social_profile.py","file_name":"get_social_profile.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"16387322694","text":"\"\"\"Компоновщик — это структурный паттерн, позволяющий представлять группы объектов в виде дерева. \r\nВ дальнейшем позволяет работать с составным объектом, как с одиночным.\r\nВ данном примере мы группируем Circle и Square в одну группу \r\nи далее добавляем в эту группу еще одну группу с такими же объектами\"\"\"\r\n\r\nclass GraphicObject:\r\n def __init__(self, color=None):\r\n self.color = color\r\n self.children = []\r\n self._name = 'Group'\r\n\r\n @property\r\n def name(self):\r\n return self._name\r\n\r\n def _print(self, items, depth):\r\n items.append('*' * depth)\r\n if self.color:\r\n items.append(self.color)\r\n items.append(f'{self.name}\\n')\r\n for child in self.children:\r\n child._print(items, depth + 1)\r\n\r\n def __str__(self):\r\n items = []\r\n self._print(items, 0)\r\n return ''.join(items)\r\n\r\n\r\nclass Circle(GraphicObject):\r\n @property\r\n def name(self):\r\n return 'Circle'\r\n\r\n\r\nclass Square(GraphicObject):\r\n @property\r\n def name(self):\r\n return 'Square'\r\n\r\n\r\nif __name__ == '__main__':\r\n drawing = GraphicObject()\r\n drawing._name = 'My Drawing'\r\n drawing.children.append(Square('Red'))\r\n drawing.children.append(Circle('Yellow'))\r\n\r\n group = GraphicObject() # no name\r\n group.children.append(Circle('Blue'))\r\n group.children.append(Square('Blue'))\r\n drawing.children.append(group)\r\n\r\n print(drawing)\r\n","repo_name":"Nataliyi/design_patterns_python","sub_path":"Section_8_Composite/geometric_shapes.py","file_name":"geometric_shapes.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"43509825976","text":"#Code will capture images from your webcam video stream\n# Will extract all faces from the image frame(haarcascades)\n# Storing the image in the form on numpy aray\n\n# 1. Capture img, read and show video stream\n# 2. Detect faces and show the boundary box\n# 3. Flatten the large image(grayscale) and save it in numpy arr form\n# 4. Repeating the above process for multiple ppl to form training data\n\n\nimport cv2\nimport numpy as np \n\n#init camera\ncap = cv2.VideoCapture(0)\n\n# face detection\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\nskip = 0\nface_data=[]\ndataset_path='./Data/'\n\nfile_name=input(\"Enter name of person : \")\nwhile True:\n\n\tret,frame = cap.read()\n\tif ret==False:\n\t\tcontinue\n\n\tgray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n\n\t\n\tfaces = face_cascade.detectMultiScale(frame,1.3,5) # scaling parameter and num of neighbours\n\tfaces = sorted(faces,key=lambda f:f[2]*f[3])\n\t\n\tface_section=frame\n\t# pic last face as it is largest\n\tfor fac in faces[-1:]:\n\t\tx,y,w,h=fac # we will sort on the basis of h w\n\t\tcv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,255),2)\n\n\t\t#extract the required part\n\t\toffset = 10 # pixels\n\n\t\tface_section=frame[y-offset:y+h+offset,x-offset:x+w+offset]\n\t\tface_section=cv2.resize(face_section,(100,100))\n\t\tskip+=1\n\t\tif skip%10==0:\n\t\t\tface_data.append(face_section)\n\t\t\tprint(len(face_data))\n\n\t\n\tcv2.imshow(\"Frame\",gray_frame)\n\tcv2.imshow(\"Face Section\",face_section)\n\n\tkey_pressed = cv2.waitKey(1) & 0xFF\n\tif key_pressed== ord('q'):\n\t\tbreak\n# convert face data to np array\n\nface_data= np.asarray(face_data)\nface_data = face_data.reshape((face_data.shape[0],-1))\n\nprint(face_data.shape)\nnp.save(dataset_path+file_name+'.npy',face_data)\nprint(\"Data saved successfully\")\n\ncap.release()\ncv2.destroyAllWindows()","repo_name":"Akshat63/Face-Recognition","sub_path":"Face_Recognition_Project.py","file_name":"Face_Recognition_Project.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"71481277293","text":"#!/usr/bin/python3\nimport pyperclip\n\n'''\n Programa que tira todas quebras de linhas de uma string \ncopiada para o clipboard. Muito útil para textos grandes\ncopiados diretamente de pdfs.\n'''\n\ntext = pyperclip.paste().split('\\n')\nprint(text)\ntext = ' '.join(text)\n\npyperclip.copy(text)","repo_name":"MagnumJulio/besteiradas_com_python","sub_path":"src/copyPDF.py","file_name":"copyPDF.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"71083587692","text":"'''\n==============\n3D quiver plot\n==============\n\nDemonstrates plotting directional arrows at points on a 3d meshgrid.\n'''\n\n# This import registers the 3D projection, but is otherwise unused.\nfrom mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\n\n# Make the grid\nx, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),\n np.arange(-0.8, 1, 0.2),\n np.arange(-0.8, 1, 0.8))\n\n# Make the direction data for the arrows\nu = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z)\nv = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z)\nw = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) *\n np.sin(np.pi * z))\n\nax.quiver(x, y, z, u, v, w, length=0.1, normalize=True)\n\nplt.show()\n","repo_name":"holzschu/python3_ios","sub_path":"extraPackages/matplotlib-3.0.2/examples/mplot3d/quiver3d.py","file_name":"quiver3d.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"55"} +{"seq_id":"34191768264","text":"from collections import Counter\r\nimport math\r\nimport pickle\r\n\r\n\r\nclass Vocab(object):\r\n \"\"\"\r\n Vocab object loosely based on harvardnlp/opennmt-py.\r\n \"\"\"\r\n\r\n def __init__(self, args, filename=None, data=[\"\"], lower=False,\r\n embeddings=\"../data/pickled_data/embeddings.pickle\"):\r\n self.idxToLabel = {}\r\n self.labelToIdx = {}\r\n self.frequencies = Counter()\r\n self.lower = lower\r\n\r\n # Special entries will not be pruned.\r\n self.specials = data\r\n\r\n if data is not None:\r\n self.addSpecials(data)\r\n if filename is not None:\r\n self.loadFile(filename)\r\n\r\n if args is None:\r\n glove = pickle.load(open(embeddings, 'rb'))\r\n for x in glove:\r\n self.add(x)\r\n else:\r\n if args.dataset != \"arithmetic\":\r\n glove = pickle.load(open(embeddings, 'rb'))\r\n for x in glove:\r\n self.add(x)\r\n elif args.dataset == \"sentiment\" and args.baseline:\r\n for w in [\"1\", \"2\", \"3\", \"4\", \"5\", \")\", \"(\", \"dummy\"]:\r\n self.add(w)\r\n else:\r\n for w in open(\"../data/input_vocabulary.txt\").readlines():\r\n self.add(w.strip())\r\n\r\n def size(self):\r\n return len(self.labelToIdx)\r\n\r\n # Load entries from a file.\r\n def loadFile(self, filename):\r\n idx = 0\r\n for line in open(filename, 'r', encoding='utf8', errors='ignore'):\r\n token = line.rstrip('\\n')\r\n self.add(token)\r\n idx += 1\r\n\r\n def getIndex(self, key, default=None):\r\n key = key.lower() if self.lower else key\r\n return self.labelToIdx.get(key, default)\r\n\r\n def getLabel(self, idx, default=None):\r\n try:\r\n return self.idxToLabel[idx]\r\n except KeyError:\r\n return default\r\n\r\n # Mark this `label` and `idx` as special\r\n def addSpecial(self, label, idx=None):\r\n idx = self.add(label)\r\n self.frequencies[idx] = math.inf\r\n\r\n # Mark all labels in `labels` as specials\r\n def addSpecials(self, labels):\r\n for label in labels:\r\n self.addSpecial(label)\r\n\r\n # Add `label` in the dictionary. Use `idx` as its index if given.\r\n def add(self, label):\r\n label = label.lower() if self.lower else label\r\n if label in self.labelToIdx:\r\n idx = self.labelToIdx[label]\r\n else:\r\n idx = len(self.idxToLabel)\r\n self.idxToLabel[idx] = label\r\n self.labelToIdx[label] = idx\r\n if label not in self.specials:\r\n self.frequencies[idx] += 1\r\n\r\n def add_all(self, sent):\r\n for w in sent:\r\n self.add(w.strip())\r\n\r\n # Convert `labels` to indices. Use `unkWord` if not found.\r\n # Optionally insert `bosWord` at the beginning and `eosWord` at the .\r\n def convertToIdx(self, labels, unkWord):\r\n vec = []\r\n unk = self.getIndex(unkWord)\r\n vec += [self.getIndex(label, default=unk) for label in labels]\r\n return vec\r\n\r\n # Convert `idx` to labels. If index `stop` is reached, convert it and return.\r\n def convertToLabels(self, idx, stop):\r\n labels = []\r\n\r\n for i in idx:\r\n labels += [self.getLabel(i)]\r\n if i == stop:\r\n break\r\n return labels\r\n","repo_name":"vernadankers/bottleneck_compositionality_metric","sub_path":"tree_lstms/lib/vocab.py","file_name":"vocab.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"4038839973","text":"import ctypes as ct\n\n\nclass FloatBits(ct.Structure):\n _fields_ = [\n ('M', ct.c_uint, 23),\n ('E', ct.c_uint, 8),\n ('S', ct.c_uint, 1)\n ]\n\n\nclass Float(ct.Union):\n _anonymous_ = ('bits',)\n _fields_ = [\n ('value', ct.c_float),\n ('bits', FloatBits)\n ]\n\n\ndef nextpow2(x):\n if x < 0:\n x = -x\n if x == 0:\n return 0\n d = Float()\n d.value = x\n if d.M == 0:\n return d.E - 127\n return d.E - 127 + 1\n","repo_name":"itaa/soja-box","sub_path":"enhance_speach/nextpow2/nextpow2.py","file_name":"nextpow2.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"55"} +{"seq_id":"31705923034","text":"import numpy as np\n\n\ndef add_norm(self, parameters, timeslots=None, blockid=0):\n r\"\"\"\n Add storage for the norms.\n \"\"\"\n grp_ob = self._srf[self._prefixb+str(blockid)].require_group(\"observables\")\n\n # Create the dataset with appropriate parameters\n grp_no = grp_ob.create_group(\"norm\")\n\n if timeslots is None:\n # This case is event based storing\n daset_n = grp_no.create_dataset(\"norm\", (0, parameters[\"ncomponents\"]), dtype=np.floating, chunks=True, maxshape=(None,parameters[\"ncomponents\"]))\n daset_tg = grp_no.create_dataset(\"timegrid\", (0,), dtype=np.integer, chunks=True, maxshape=(None,))\n else:\n # User specified how much space is necessary.\n daset_n = grp_no.create_dataset(\"norm\", (timeslots, parameters[\"ncomponents\"]), dtype=np.floating)\n daset_tg = grp_no.create_dataset(\"timegrid\", (timeslots,), dtype=np.integer)\n\n daset_tg.attrs[\"pointer\"] = 0\n\n\ndef delete_norm(self, blockid=0):\n r\"\"\"\n Remove the stored norms.\n \"\"\"\n try:\n del self._srf[self._prefixb+str(blockid)+\"/observables/norm\"]\n # Check if there are other children, if not remove the whole node.\n if len(self._srf[self._prefixb+str(blockid)+\"/observables\"].keys()) == 0:\n del self._srf[self._prefixb+str(blockid)+\"/observables\"]\n except KeyError:\n pass\n\n\ndef has_norm(self, blockid=0):\n r\"\"\"\n Ask if the specified data block has the desired data tensor.\n \"\"\"\n return (\"observables\" in self._srf[self._prefixb+str(blockid)].keys() and\n \"norm\" in self._srf[self._prefixb+str(blockid)][\"observables\"].keys())\n\n\ndef save_norm(self, norm, timestep=None, blockid=0):\n r\"\"\"\n Save the norm of wavefunctions or wavepackets.\n \"\"\"\n pathtg = \"/\"+self._prefixb+str(blockid)+\"/observables/norm/timegrid\"\n pathd = \"/\"+self._prefixb+str(blockid)+\"/observables/norm/norm\"\n timeslot = self._srf[pathtg].attrs[\"pointer\"]\n\n # Refactor: remove np.array\n norms = np.real(np.array(norm))\n\n # Write the data\n self.must_resize(pathd, timeslot)\n self._srf[pathd][timeslot,:] = norms\n\n # Write the timestep to which the stored values belong into the timegrid\n self.must_resize(pathtg, timeslot)\n self._srf[pathtg][timeslot] = timestep\n\n # Update the pointer\n self._srf[pathtg].attrs[\"pointer\"] += 1\n\n\ndef load_norm_timegrid(self, blockid=0):\n r\"\"\"\n Load the timegrid corresponding to the norm data.\n \"\"\"\n pathtg = \"/\"+self._prefixb+str(blockid)+\"/observables/norm/timegrid\"\n return self._srf[pathtg][:]\n\n\ndef load_norm(self, timestep=None, split=False, blockid=0):\n r\"\"\"\n Load the norm data.\n \"\"\"\n pathtg = \"/\"+self._prefixb+str(blockid)+\"/observables/norm/timegrid\"\n pathd = \"/\"+self._prefixb+str(blockid)+\"/observables/norm/norm\"\n\n if timestep is not None:\n index = self.find_timestep_index(pathtg, timestep)\n axis = 0\n else:\n index = slice(None)\n axis = 1\n\n if split is True:\n return self.split_data( self._srf[pathd][index,...], axis)\n else:\n return self._srf[pathd][index,...]\n","repo_name":"WaveBlocks/WaveBlocks","sub_path":"src/WaveBlocks/IOM_plugin_norm.py","file_name":"IOM_plugin_norm.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"5207644898","text":"from flask import Flask, render_template\nimport random\nfrom datetime import datetime\nimport requests\n\napp = Flask(__name__)\n\ndef get_age(name):\n endpoint = \"https://api.agify.io?name=\" + name\n response = requests.get(endpoint).json()\n guessed_age = response[\"age\"]\n return guessed_age\n\ndef get_gender(name):\n endpoint = \"https://api.genderize.io?name=\" + name\n response = requests.get(endpoint).json()\n guessed_gender = response[\"gender\"]\n return guessed_gender\n\ndef get_probability(name):\n endpoint = \"https://api.genderize.io?name=\" + name\n response = requests.get(endpoint).json()\n gender_probability = float(response[\"probability\"]) * 100\n return gender_probability\n\n@app.route('/')\ndef home():\n random_number = random.randint(1,10)\n year = datetime.now().year\n return render_template('index.html', num=random_number, current_yr=year)\n\n@app.route('/guess/')\ndef guess(name):\n age = get_age(name)\n gender = get_gender(name)\n probability = get_probability(name)\n return f\"

    Hello, {name.title()}!\" \\\n f\"
    I'm {probability}% sure you are a {gender}\" \\\n f\"
    Age guess: {age}\"\n\n@app.route(\"/blog/\")\ndef get_blog(num):\n print(num)\n blog_url = \"https://api.npoint.io/5abcca6f4e39b4955965\"\n response = requests.get(blog_url)\n all_posts = response.json()\n return render_template(\"blog.html\", posts=all_posts)\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"nolan887/100Days","sub_path":"Day57/jinja/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"32249773657","text":"import csv\nimport os\nfrom typing import Any, List, Tuple\n\n\nclass DataRecorder:\n def __init__(self, data_slug) -> None:\n self.filename = f'{data_slug}.csv'\n\n if os.path.getsize(self.filename) == 0:\n self.add_header()\n\n def add_header(self):\n with open(self.filename, mode='a', newline='') as f:\n record_writer = csv.writer(f) # defaults CSV\n record_writer.writerow([\n 'timestamp', 'token_name', 'amount', 'staked_amount',\n 'eur_price', 'total_amount', 'total_eur_amount'\n ])\n\n def add_record(self, timestamp, token_name, eur_price, amount,\n staked_amount, total_amount, total_eur_amount):\n with open(self.filename, mode='a', newline='') as f:\n record_writer = csv.writer(f) # defaults CSV\n record_writer.writerow([\n timestamp, token_name, amount, staked_amount, eur_price,\n total_amount, total_eur_amount\n ])\n\n\nclass DataReader:\n def __init__(self, data_slug) -> None:\n self.filename = f'{data_slug}.csv'\n\n def get_records(self) -> Tuple[List[Any], List[List[Any]]]:\n with open(self.filename, newline='') as csvfile:\n reader = csv.reader(csvfile)\n headers = next(reader)\n data = [row for row in reader]\n return headers, data\n","repo_name":"dhensen/coinbase-monitor","sub_path":"recorder.py","file_name":"recorder.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"75005546399","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 25 14:50:32 2017\n\n@author: Alex\n\"\"\"\n\nfrom astropy import units as u\n\n# Select years for solar maxma\nlis_int_years = [ 2011, 2012, 2013 ]\n\n# Folders for GOES data and saving results\nstr_h5_goes_data_path = 'C:\\\\goes_h5\\\\'\nstr_fits_data_path = 'C:\\\\goes_fits\\\\'\nstr_h5_flare_data_path = 'C:\\\\flare_h5\\\\'\n\n# Decide what parameter/s to use\nlis_qua_bins = [ 12 * u.s ]\nlis_int_rolling_mean = [5]\nlis_qua_par_N = [ 4.0 * u.min ]\nlis_flo_par_thr = [ 0.4 ]\nlis_flo_par_drop = [ 0.5 ]\n\n############\n#\n# Generate the combined/smooth GOES data files\n#\n############\n# If there arn't already gibgle year files for the GOES data then make them from the day FITS files.\nfor int_year in lis_int_years:\n str_year = str(int_year)\n for qua_bin in lis_qua_bins:#for str_bin_size in lis_str_bins:\n str_bin_size = quantity_to_pandas_string(qua_bin)\n for int_rolling_mean in lis_int_rolling_mean:\n try:\n # Check for data files\n\n #str_bin_size = '12s'\n int_rolling_mean = 5\n\n # Check if the rebinned data file exists\n str_h5_year_smoothed_data_path = str_h5_goes_data_path + str_year+'_goes__rebinned_'+str_bin_size+'_median__smoothed_rolling_mean_'+str(int_rolling_mean)+'.h5'\n if not os.path.isfile(str_h5_year_smoothed_data_path):\n # Check if the rebinned data file exists\n str_h5_year_rebinned_data_path = str_h5_goes_data_path + str_year+'_goes__rebinned_'+str_bin_size+'_median.h5'\n if not os.path.isfile(str_h5_year_rebinned_data_path):\n # The data hasn't been rebinned\n str_h5_year_data_path = str_h5_goes_data_path + str_year+'_goes.h5'\n\n # Check if the raw h5 file for the whole year exists\n if not os.path.isfile(str_h5_year_data_path):\n # Need to create the years data using the fits files\n str_year_datapath = str_fits_data_path + str_year + '\\\\'\n save_folder_as_h5(str_year_datapath, str_h5_year_data_path)\n\n # Generate the rebinned files\n rebin_h5_files(str_h5_year_data_path, lis_qua_bins=[qua_bin])\n # Generate the smoothed file\n smooth_h5_files(str_h5_year_rebinned_data_path, str_h5_year_smoothed_data_path, int_rolling_mean)\n except:\n print('Error generating data files.')","repo_name":"Alex-Ian-Hamilton/flarepy","sub_path":"examples/2017-05-25_priliminary_data.py","file_name":"2017-05-25_priliminary_data.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"28934945965","text":"from flask import Flask, render_template, redirect, url_for,request\nfrom flask import make_response\nfrom werkzeug import secure_filename\nimport io\nimport csv\nimport random\nimport pandas as pd\n# from StringIO import StringIO\nfrom io import StringIO\nimport numpy as np\nimport csv\nimport random\nfrom fancyimpute import KNN\nfrom sklearn.metrics import accuracy_score\nfrom io import StringIO\nimport os\nimport random\n\n\n\n# csv_input = csv.reader(stream)\n# read to csv for computation\ndf = pd.read_csv(\"./whiskey-missing.csv\")\n# print(\"pd_input\",df.describe())\n# to track original data\ntemp = df\ntemp_mean = df\ntemp_knn = df\ntemp_random = df\n# ****transform, this is for the global mean part\nrate_mean = df[\"Rating\"].mean()\nprice_mean = df[\"Price\"].mean()\nabv_mean = df[\"ABV\"].mean()\nage_mean = df[\"Age\"].mean()\n\nprint(\"temp_mean before\", temp_mean.describe())\nprint(\"df before count\",df.describe())\n\n\n\n# part where the transform works\nfor i in range(len(df)):\n if np.isnan(df.at[i,'Rating']):\n temp_mean.at[i, 'Rating'] = rate_mean\n temp_mean.at[i, 'rate_impute'] = 1\n\n else:\n temp_mean.at[i, 'rate_impute'] = 0\n\n if np.isnan(df.at[i,'Price']):\n temp_mean.at[i, 'Price'] = price_mean\n temp_mean.at[i, 'price_impute'] = 1\n\n else:\n temp_mean.at[i, 'price_impute'] = 0\n\n if np.isnan(df.at[i,'ABV']):\n temp_mean.at[i, 'ABV'] = abv_mean\n temp_mean.at[i, 'abv_impute'] = 1\n else:\n temp_mean.at[i, 'abv_impute'] = 0\n\n if np.isnan(df.at[i,'Age']):\n temp_mean.at[i, 'Age'] = age_mean\n temp_mean.at[i, 'age_impute'] = 1\n\n else:\n temp_mean.at[i, 'age_impute'] = 0\n\n\nprint(\"temp_mean after\", temp_mean.describe())\nprint(\"df after\", df.describe())\n\n\n\ntemp_mean.to_csv('./new_data/whiskey_global.csv', index=False, header=True)\n\ndf = pd.read_csv(\"./whiskey-missing.csv\")\n\nprint(\"df before count knn\",df.describe())\n\n\n\n# ***knn function\ndf_numeric = df.select_dtypes(include=[np.float])\n# df_filled = pd.DataFrame(KNN(3).complete(df_numeric))\ndf_filled = pd.DataFrame(KNN(3).fit_transform(df_numeric))\ndf_filled.columns = df_numeric.columns\ndf_filled.index = df_numeric.index\n\n\n\ntemp_knn['Rating'] = df_filled['Rating']\ntemp_knn['Price'] = df_filled['Price']\ntemp_knn['ABV'] = df_filled['ABV']\ntemp_knn['Age'] = df_filled['Age']\n\n# this is adding the imputation boolean label\n# temp_knn['Rating_impute'] = temp['Rating_impute']\n# temp_knn['Price_impute'] = temp['Price_impute']\n# temp_knn['ABV_impute'] = temp['ABV_impute']\n# temp_knn['Age_impute'] = temp['Age_impute']\ntemp_knn['rate_impute'] = temp_mean['rate_impute']\ntemp_knn['price_impute'] = temp_mean['price_impute']\ntemp_knn['abv_impute'] = temp_mean['abv_impute']\ntemp_knn['age_impute'] = temp_mean['age_impute']\n\nprint(\"temp_knn\", temp_knn.describe())\n\n\n\ntemp_knn.to_csv('./new_data/whiskey_knn.csv', index=False, header=True)\n\n\n\ndf = pd.read_csv(\"./whiskey-missing.csv\")\n\nprint(\"df before count knn\",df.describe())\n\n\n\n\n# this is for the random selction\nfor i in range(len(df)):\n if np.isnan(df.at[i,'Rating']):\n temp_random.at[i, 'Rating'] = random.choice(temp[\"Rating\"])\n if np.isnan(df.at[i,'Price']):\n temp_random.at[i, 'Price'] = random.choice(temp[\"Price\"])\n if np.isnan(df.at[i,'ABV']):\n temp_random.at[i, 'ABV'] = random.choice(temp[\"ABV\"])\n if np.isnan(df.at[i,'Age']):\n temp_random.at[i, 'Age'] = random.choice(temp[\"Age\"])\n\nprint(\"temp_knn\", temp_random.describe())\n\n\ntemp_random['rate_impute'] = temp['rate_impute']\ntemp_random['price_impute'] = temp['price_impute']\ntemp_random['abv_impute'] = temp['abv_impute']\ntemp_random['age_impute'] = temp['age_impute']\n\n\n\ntemp_random.to_csv('./new_data/whiskey_random.csv', index=False, header=True)\n\n","repo_name":"hsong300-repo/missingdata_backend","sub_path":"data_analysis.py","file_name":"data_analysis.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"37116882202","text":"from flask import Flask, request\nimport pickle\n\napp = Flask(__name__)\nmodel = pickle.load(open('fire_prediction_model_unscaled.sav', 'rb'))\n\n@app.route(\"/\", methods=['POST'])\ndef predictor():\n data = request.get_json()\n prediction = model.predict(data['x'])\n if (prediction < 500):\n size = 'Low'\n elif (prediction < 1500):\n size = 'medium'\n else:\n size = 'High'\n return {\"Risk\": size}\n\n\n","repo_name":"JayLi1209/FireNet","sub_path":"Flask.py","file_name":"Flask.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"31084262","text":"import time\r\nimport random\r\nimport decimal\r\nimport datetime\r\n\r\ncurrent_time = datetime.datetime.now()\r\n\r\nprint(\"Current time is: \", current_time)\r\nprint(\"Please insert your CARD\")\r\ntime.sleep(5)\r\npassword= 1234\r\npin=int(input(\"enter your pin: \"))\r\nbalance= decimal.Decimal(int(random.uniform(1,1000000)))\r\n\r\n\r\nif pin == password:\r\n while True:\r\n \r\n print(\"\"\"\r\n 1 == balance\r\n 2 == withdraw\r\n 3 == deposit\r\n 4 == exit\r\n \"\"\")\r\n\r\n try:\r\n option =int(input(\"Please select your choice: \"))\r\n except:\r\n print(\"Please enter a vailid option\")\r\n\r\n if option==1:\r\n print(\"checking balance...\")\r\n time.sleep(4)\r\n print(f\"Your current balance is {balance}\")\r\n time.sleep(4)\r\n \r\n\r\n if option==2:\r\n withdrawal_amount=int(input(\"enter withdrawal amount: \"))\r\n balance=balance-withdrawal_amount\r\n print(\"checking...\")\r\n time.sleep(4)\r\n if withdrawal_amount >= balance:\r\n print(f\"invalid,Please enter an amount less than {balance}\")\r\n if withdrawal_amount >= 50000:\r\n print(\"You cannot withdraw more than 50,000 in a single transaction\")\r\n else:\r\n print(f\"{withdrawal_amount} has been debited from your account\")\r\n print(f\"your new balance is {balance}\")\r\n time.sleep(4)\r\n\r\n if option==3:\r\n deposit_amount=int(input(\"enter deposit amount: \"))\r\n balance=balance+deposit_amount\r\n print(\"checking...\")\r\n time.sleep(4)\r\n print(\"Successful!!!\")\r\n time.sleep(2)\r\n print(f\"{deposit_amount} has been credited into account\")\r\n print(f\"your new balance is {balance}\")\r\n time.sleep(4)\r\n\r\n if option==4:\r\n print(\"...\")\r\n time.sleep(4)\r\n print(\"Transaction ended,please take your card\")\r\n\r\n \r\n break\r\n \r\n\r\n\r\n\r\nelse:\r\n print(\"Wrong pin,Please try again\")\r\n\r\n\r\n\r\n","repo_name":"Zacksammy/virtual-atm-machine","sub_path":"atm code/atm.py","file_name":"atm.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"5309918623","text":"import pygame\r\nimport singletons\r\n\r\n# https://rvros.itch.io/animated-pixel-hero?download\r\n\r\n# x = 8\r\n# y = 5\r\n# w = 32\r\n# h = 32\r\n\r\n\r\nclass _BaseMode(pygame.sprite.Sprite):\r\n def __init__(self):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.images = []\r\n self.spriteCount = 0\r\n self.image = None\r\n self.fpsIndex = 0\r\n self.step = 0\r\n self.indexResetValue = 0\r\n self.rect = None\r\n self.loadSprites()\r\n\r\n def loadSprites(self):\r\n pass\r\n\r\n def update(self, *args):\r\n self.image = self.images[self.fpsIndex / self.step]\r\n self.fpsIndex += 1\r\n if self.fpsIndex >= self.indexResetValue:\r\n self.fpsIndex = 0\r\n\r\n def _updateIndexes(self):\r\n self.spriteCount = len(self.images)\r\n self.image = self.images[0]\r\n self.fpsIndex = 0\r\n self.step = 30 / self.spriteCount\r\n self.indexResetValue = self.step * self.spriteCount\r\n self.size = self.images[0].get_size()\r\n\r\n\r\nclass _IdleMode(_BaseMode):\r\n def __init__(self):\r\n _BaseMode.__init__(self)\r\n\r\n def loadSprites(self):\r\n self.images.append(pygame.image.load('assets/adventurer/idle/0.png'))\r\n self.images.append(pygame.image.load('assets/adventurer/idle/1.png'))\r\n self.images.append(pygame.image.load('assets/adventurer/idle/2.png'))\r\n self.images.append(pygame.image.load('assets/adventurer/idle/3.png'))\r\n _BaseMode._updateIndexes(self)\r\n\r\n\r\nclass _RunMode(_BaseMode):\r\n def __init__(self):\r\n _BaseMode.__init__(self)\r\n\r\n def loadSprites(self):\r\n self.images.append(pygame.image.load('assets/adventurer/run/0.png'))\r\n self.images.append(pygame.image.load('assets/adventurer/run/1.png'))\r\n self.images.append(pygame.image.load('assets/adventurer/run/2.png'))\r\n self.images.append(pygame.image.load('assets/adventurer/run/3.png'))\r\n self.images.append(pygame.image.load('assets/adventurer/run/4.png'))\r\n self.images.append(pygame.image.load('assets/adventurer/run/5.png'))\r\n _BaseMode._updateIndexes(self)\r\n\r\n\r\nclass _FallingMode(_BaseMode):\r\n def __init__(self):\r\n _BaseMode.__init__(self)\r\n\r\n def loadSprites(self):\r\n self.images.append(pygame.image.load('assets/adventurer/fall/1.png'))\r\n self.images.append(pygame.image.load('assets/adventurer/fall/2.png'))\r\n _BaseMode._updateIndexes(self)\r\n\r\n\r\nclass _Animations:\r\n IDLE = 1\r\n FALL = 2\r\n MOVING = 3\r\n\r\n def __init__(self):\r\n self._modeIndex = self.IDLE\r\n self._modes = {\r\n self.IDLE: _IdleMode(),\r\n self.FALL: _FallingMode(),\r\n self.MOVING: _RunMode(),\r\n }\r\n\r\n def setIdle(self):\r\n self._modeIndex = self.IDLE\r\n\r\n def setFall(self):\r\n self._modeIndex = self.FALL\r\n\r\n def setMoving(self):\r\n self._modeIndex = self.MOVING\r\n\r\n @property\r\n def animation(self):\r\n return self._modes[self._modeIndex]\r\n\r\n\r\nclass Adventurer:\r\n IDLE = 1\r\n MOVE_LEFT = 2\r\n MOVE_RIGHT = 3\r\n FALLING = 4\r\n\r\n def __init__(self):\r\n self._state = self.IDLE\r\n self.__x = 64\r\n self.__y = 192\r\n self.__dx = 0\r\n self.__dy = 0\r\n self.__speedX = 2\r\n self.__speedY = 2\r\n self.__keyRightPressed = False\r\n self.__keyLeftPressed = False\r\n self.__isFalling = False\r\n self.__direction = 'Right'\r\n self.__animations = _Animations()\r\n self.__level = None\r\n self.__surface = singletons.Display.getInstance().getSurface\r\n self.__gameMode = singletons.GameMode.getInstance()\r\n\r\n def setLevelObject(self, level):\r\n self.__level = level\r\n\r\n def draw(self):\r\n if self.__direction == 'Right':\r\n self.__surface.blit(self.animation.image, self.position)\r\n else:\r\n self.__surface.blit(pygame.transform.flip(self.animation.image, True, False), self.position)\r\n\r\n def eventProcessing(self, event):\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_RIGHT:\r\n self.__keyRightPressed = True\r\n elif event.key == pygame.K_LEFT:\r\n self.__keyLeftPressed = True\r\n elif event.type == pygame.KEYUP:\r\n if event.key == pygame.K_RIGHT:\r\n self.__keyRightPressed = False\r\n elif event.key == pygame.K_LEFT:\r\n self.__keyLeftPressed = False\r\n elif event.key == pygame.K_ESCAPE:\r\n self.__gameMode.setPause()\r\n\r\n def update(self):\r\n self.__dx = 0\r\n self.__dy = 0\r\n\r\n self.__isFalling = self.canFalling()\r\n\r\n if self.__keyLeftPressed:\r\n self.setStateMoveLeft()\r\n elif self.__keyRightPressed:\r\n self.setStateMoveRight()\r\n else:\r\n self.setStateIdle()\r\n\r\n self.stateProcessing()\r\n self.animation.update()\r\n\r\n def stateProcessing(self):\r\n if self.__isFalling:\r\n self.moveByDxDy(dy=self.__speedY)\r\n\r\n if self._state == self.MOVE_LEFT:\r\n if self.canMove():\r\n self.moveByDxDy(dx=-self.__speedX)\r\n elif self._state == self.MOVE_RIGHT:\r\n if self.canMove():\r\n self.moveByDxDy(dx=self.__speedX)\r\n\r\n def setStateMoveLeft(self):\r\n self.__direction = 'Left'\r\n self._state = self.MOVE_LEFT\r\n if self.__isFalling:\r\n self.__animations.setFall()\r\n else:\r\n self.__animations.setMoving()\r\n\r\n def setStateMoveRight(self):\r\n self.__direction = 'Right'\r\n self._state = self.MOVE_RIGHT\r\n if self.__isFalling:\r\n self.__animations.setFall()\r\n else:\r\n self.__animations.setMoving()\r\n\r\n def setStateIdle(self):\r\n self._state = self.IDLE\r\n if self.__isFalling:\r\n self.__animations.setFall()\r\n else:\r\n self.__animations.setIdle()\r\n\r\n def canMove(self):\r\n if self.__direction == 'Left':\r\n x = self.__x - self.__speedX\r\n cell = x / 32\r\n ci = cell - 1 if cell > 0 else 0\r\n else:\r\n x = self.__x + self.__speedX\r\n cell = x / 32\r\n ci = cell + 1 if cell < 30 else 30\r\n\r\n size = self.animation.size\r\n rect = pygame.Rect(x, self.__y, size[0], size[1])\r\n\r\n row = self.__y / 32\r\n c1 = self.__level.map()[row][cell]\r\n c2 = self.__level.map()[row][ci]\r\n c3 = self.__level.map()[row + 1][cell]\r\n c4 = self.__level.map()[row + 1][ci]\r\n if not (rect.colliderect(c1.rect) or\r\n rect.colliderect(c2.rect) or\r\n rect.colliderect(c3.rect) or\r\n rect.colliderect(c4.rect)):\r\n return True\r\n return False\r\n\r\n def canFalling(self):\r\n size = self.animation.size\r\n y = self.__y + self.__speedY\r\n row = y / 32\r\n cell = self.__x / 32\r\n rect = pygame.Rect(self.__x, y, size[0], size[1])\r\n\r\n ci2 = cell + 1 if cell < 30 else 30\r\n c1 = self.__level.map()[row][cell]\r\n c2 = self.__level.map()[row + 1][cell]\r\n c3 = self.__level.map()[row + 1][ci2]\r\n if not (rect.colliderect(c1.rect) or\r\n rect.colliderect(c2.rect) or\r\n rect.colliderect(c3.rect)):\r\n return True\r\n return False\r\n\r\n def moveByDxDy(self, dx=0, dy=0):\r\n self.__x += dx\r\n self.__y += dy\r\n\r\n @property\r\n def rect(self):\r\n return self.__rect\r\n\r\n @property\r\n def animation(self):\r\n return self.__animations.animation\r\n\r\n @property\r\n def position(self):\r\n return self.__x, self.__y\r\n","repo_name":"cCppProsto/python_somegame","sub_path":"adventurer.py","file_name":"adventurer.py","file_ext":"py","file_size_in_byte":7738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"39262684359","text":"import random\n\nmax_roll = 5\ncurrent_outcome = 0\nmax_outcome = 20\n\nprint(\"WELCOME TO ROLL THE DIE ...\\n\\n\")\nfor i in range(1, 6):\n die_roll = random.randint(1, 6)\n current_outcome = current_outcome + die_roll\n\n print(f\"Roll #{i}: You've rolled a {die_roll}\")\n\n if current_outcome == max_outcome:\n print(\"fYour total outcom is {current_roll}. Congratulations, you win!\")\n break\n elif current_outcome > max_outcome:\n print(f\"Unfortunately, that takes you past total number of {max_outcome} outcomes, You lose!\")\n break\n elif i == max_roll and current_outcome < max_outcome:\n print(f\"Your total outcome is {current_outcome}\")\n print(f\"Unfortunatly, you didn't make it to the total outcomes of {max_outcome} as required. You lose!\")\n else:\n remaining_outcomes = max_outcome - current_outcome\n print(f\"Your total number of outcomes are {current_outcome}. You still have {remaining_outcomes} to go.\")\n\n print(\" \\n\\n\")\n\n\n","repo_name":"iayakubu/die-game","sub_path":"die_game.py","file_name":"die_game.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"33353276303","text":"from posts.components import *\n\n\nclass Post:\n \"\"\"\n A generic post object. Composed of notes, source info, post info and a body.\n \"\"\"\n def __init__(self, post_type: str, body: Body, meta_info: MetaInfo, source: Source, notes: Notes):\n self.type = post_type\n self.body = body\n self.meta_info = meta_info\n self.source = source\n self.notes = notes\n","repo_name":"whywrd/notheme","sub_path":"app/posts/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"20117712379","text":"#!/usr/bin/env python3\n\ndef snake_ladder(board_sz, moves_list):\n \n # makes moves 0 based. Incoming moves is 1 based\n moves = [0] * len(moves_list)\n for i in range(len(moves_list)):\n moves[i] = moves_list[i]\n if moves[i] != -1:\n moves[i] -= 1\n\n return _snake_ladder(board_sz, moves)\n\ndef _snake_ladder(n, moves):\n visited = set()\n q = []\n dist = 0\n q.append( (0, dist))\n back_refs = {0:None}\n\n while q:\n cur, dist = q.pop(0)\n\n if cur in visited:\n continue\n\n if cur == n-1:\n #while cur:\n # print(cur)\n # cur = back_refs[cur]\n #print(back_refs)\n # If we need to print the dices used to reach the final\n # cell, I am kind of stuck here.\n return dist\n\n visited.add(cur)\n\n for dice in range(1,7):\n if cur + dice < n:\n if moves[cur+dice] == -1:\n nxt = cur+dice\n else:\n nxt = moves[cur+dice]\n\n q.append((nxt, dist+1))\n back_refs[nxt] = dice\n #print(back_refs)\n\n return -1 # can't reach final cell using the moves\n\nn = 20\nmoves = [-1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]\nprint(\"number of moves:\", snake_ladder(n, moves))\n\n","repo_name":"insipel/achked","sub_path":"python3/graphs/practice/snake_ladder.py","file_name":"snake_ladder.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"882697792","text":"import PySimpleGUI as sg\n\nimport codewars as cw\n\nsg.theme('BluePurple') # Add a touch of color\n# All the stuff inside your window.\nlayout = [[sg.Text('Basic Course Homeworks')],\n [sg.Text('DescOrder'), sg.InputText(key='DescIn'), sg.InputText(readonly=True, key='DescRes'),\n sg.Button('DescOrder')],\n [sg.Text('RomanNum'), sg.InputText(key='RomanIn'), sg.InputText(readonly=True, key='RomanRes'),\n sg.Button('RomanNum')],\n [sg.Text('IfPrime'), sg.InputText(key='IfPrimeIn'), sg.InputText(readonly=True, key='IfPrimeRes'),\n sg.Button('IfPrime')],\n [sg.Text('Vowels'), sg.InputText(key='VowelsIn'), sg.InputText(readonly=True, key='VowelsRes'),\n sg.Button('Vowels')],\n [sg.Text('Bus'), sg.InputText(key='BusIn'), sg.InputText(readonly=True, key='BusRes'), sg.Button('Bus')],\n [sg.Text('PigLatin'), sg.InputText(key='PigLatinIn'), sg.InputText(readonly=True, key='PigLatinRes'),\n sg.Button('PigLatin')],\n [sg.Text('IntFilter'), sg.InputText(key='IntFilterIn'), sg.InputText(readonly=True, key='IntFilterRes'),\n sg.Button('IntFilter')],\n [sg.Text('WordScore'), sg.InputText(key='WordScoreIn'), sg.InputText(readonly=True, key='WordScoreRes'),\n sg.Button('WordScore')],\n [sg.Text('Unique'), sg.InputText(key='UniqueIn'), sg.InputText(readonly=True, key='UniqueRes'),\n sg.Button('Unique')],\n [sg.Button('EXIT')]]\n\n# Create the Window\nwindow = sg.Window('Basic Course Homeworks', layout)\n\n# Event Loop to process \"events\" and get the \"values\" of the inputs\nwhile True:\n event, values = window.read()\n if event == sg.WIN_CLOSED or event == 'EXIT': # if user closes window or clicks cancel\n break\n if event == 'DescOrder':\n window.Element('DescRes').Update(cw.descending_order(values['DescIn']))\n if event == 'RomanNum':\n window.Element('RomanRes').Update(cw.romanNum(values['RomanIn']))\n if event == 'IfPrime':\n window.Element('IfPrimeRes').Update(cw.primeCheck(values['IfPrimeIn']))\n if event == 'Vowels':\n window.Element('VowelsRes').Update(cw.vowelsCount(values['VowelsIn']))\n if event == 'Bus':\n window.Element('BusRes').Update(cw.BusStops(values['BusIn']))\n if event == 'PigLatin':\n window.Element('PigLatinRes').Update(cw.pigLatin(values['PigLatinIn']))\n if event == 'IntFilter':\n window.Element('IntFilterRes').Update(cw.intFilter(values['IntFilterIn']))\n if event == 'WordScore':\n window.Element('WordScoreRes').Update(cw.high(values['WordScoreIn']))\n if event == 'Unique':\n cw.unique(values['UniqueIn'])\nwindow.close()\n","repo_name":"uinleader/codewars","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"10799390863","text":"from pyspark.sql import SparkSession\n\n#Create spark object from Spark session\n\n\ndef get_spark_session(env, app_name):\n if env == 'DEV':\n spark = SparkSession. \\\n builder. \\\n master('local'). \\\n appName(app_name). \\\n getOrCreate()\n\n return spark\n\n\n#'Getting started for GitHub activity'\n","repo_name":"Semiu/data-engineering","sub_path":"data-pipeline-cron/ranjit-udemy/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"34185112990","text":"from urllib import request\n\n# src = \"https://www.ntu.edu.tw/\" # 就用 台大官网 试试\n\n\n# with request.urlopen(src) as responce:\n# # 取得(前端)网站源代码 (HTML, CSS, JS)\n# data = responce.read().decode(\"utf-8\") # decode(utf-8) => 文字编码 转 utf-8 (支援中文)\n\n# print(data)\n\n\n'''\n 取得资料 以 API 的方式存取\n'''\n\nimport json # 处理 json 资料格式\n\nsrc = \"https://www.cdc.gov.tw/TravelEpidemic/ExportJSON\" # 以 Python 解读是 [{}, {}, ...]\n\n# 开启网址\nwith request.urlopen(src) as response:\n data = json.load(response)\n\n# print(data)\n\n# 取得 目标资料\n\nfor i in range(len(data)):\n result = data[i]['headline']\n \n print(result)\n\n\n","repo_name":"RexIscodingnow/python_practice","sub_path":"學習範例/python_基礎範例/網路連線_資料串接/web_request.py","file_name":"web_request.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"8528535984","text":"class Person:\n def __init__(self, name):\n self._name = name\n\n def _get_name(self):\n print(\"Get name\")\n return self._name\n\n def _set_name(self, value):\n print(\"Set name\")\n if not isinstance(value, str):\n raise ValueError(\"Имя должно быть строкой\")\n self._name = value\n\n def _del_name(self):\n print(\"Delete name\")\n del self._name\n\n name = property(\n fget=_get_name,\n fset=_set_name,\n fdel=_del_name,\n doc=\"The name property.\"\n )","repo_name":"Kuzin566/OOP","sub_path":"2 Методы и Свойства/2.6 Геттеры и сеттеры, property атрибуты/1. Lesson.py","file_name":"1. Lesson.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"2279149420","text":"from typing import Tuple, Sequence, Optional\n\nimport numba\nimport numpy as np\nfrom numba.typed import List\n\n\nLayerParameters = Tuple[np.ndarray, np.ndarray, Optional[np.ndarray], int, int, int, int, int, bool]\nNetworkParameters = Sequence[LayerParameters]\nNetworkOutputs = Sequence[np.ndarray]\n\n\n@numba.njit\ndef pad_2d(inputs: np.ndarray, padding_height: int, padding_width: int) -> np.ndarray:\n num_channels, height, width = inputs.shape\n\n outputs = np.zeros((num_channels, height + 2 * padding_height, width + 2 * padding_width), dtype=inputs.dtype)\n\n outputs[:, padding_height:(padding_height + height), padding_width:(padding_width + width)] = inputs\n\n return outputs\n\n\n@numba.njit\ndef ravel(inputs: np.ndarray, group_size: int) -> np.ndarray:\n num_channels, height, width = inputs.shape\n\n raveled = np.empty((num_channels * height * width,), dtype=inputs.dtype)\n\n num_groups = num_channels // group_size\n\n index = 0\n\n for group_index in range(num_groups):\n start_channel = group_index * group_size\n end_channel = start_channel + group_size\n\n for h in range(height):\n for w in range(width):\n for c in range(start_channel, end_channel):\n raveled[index] = inputs[c, h, w]\n index += 1\n\n return raveled\n\n\n@numba.njit\ndef calculate_padding(layer_index: int, network_parameters: NetworkParameters) -> Tuple[int, int]:\n if layer_index + 1 < len(network_parameters):\n _, _, kernel_height, kernel_width = network_parameters[layer_index + 1][0].shape\n\n padding_height = kernel_height // 2\n padding_width = kernel_width // 2\n\n else:\n padding_height = padding_width = 0\n\n return padding_height, padding_width\n\n\n@numba.njit\ndef index_to_location(index: int, shape: Tuple[int, int, int], group_size: int) -> Tuple[int, int, int]:\n num_channels, height, width = shape\n\n num_elements_per_group = group_size * height * width\n num_elements_per_slice = group_size * width\n\n group_index = index // num_elements_per_group * group_size\n index = index % num_elements_per_group\n\n h = index // num_elements_per_slice\n index = index % num_elements_per_slice\n\n w = index // group_size\n c = group_index + index % group_size\n\n return c, h, w\n\n\n@numba.njit\ndef get_previous_location(c: int, h: int, w: int, height: int, width: int, padding: int) -> Tuple[int, int, int]:\n if c == 0 and h == 0 and w == 0:\n c_previous = -1\n h_previous = -1\n w_previous = -1\n elif h == 0 and w == 0:\n c_previous = c - 1\n h_previous = height - padding - 1\n w_previous = width - padding - 1\n elif w == 0:\n c_previous = c\n h_previous = h + padding - 1\n w_previous = width - padding - 1\n else:\n c_previous = c\n h_previous = h + padding\n w_previous = w + padding - 1\n\n return c_previous, h_previous, w_previous\n\n\n@numba.njit\ndef disentangle(inputs: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n return inputs[::2], inputs[1::2]\n\n\n@numba.njit\ndef convolve(inputs: np.ndarray, weights: np.ndarray, biases: np.ndarray) -> np.ndarray:\n _, height, width = inputs.shape\n out_channels, in_channels, length_height, length_width = weights.shape\n padding = (length_height - 1) // 2\n num_steps = height * width\n num_dimensions = in_channels * length_height * length_width\n\n shape = (height, width, in_channels, length_height, length_width)\n strides = inputs.strides[1:] + inputs.strides\n\n inputs_view = pad_2d(inputs, padding)\n inputs_view = np.lib.stride_tricks.as_strided(inputs_view, shape, strides)\n inputs_view = np.ascontiguousarray(inputs_view)\n inputs_view = np.reshape(inputs_view, (num_steps, num_dimensions))\n\n weights_view = np.reshape(weights, (out_channels, num_dimensions))\n\n outputs = np.dot(weights_view, np.transpose(inputs_view))\n outputs += np.expand_dims(biases, axis=1)\n outputs = np.reshape(outputs, (out_channels, height, width))\n\n return outputs\n\n\n@numba.njit\ndef convolve_location(inputs: np.ndarray, weights: np.ndarray, biases: np.ndarray) -> np.ndarray:\n return np.vdot(np.ravel(weights), np.ravel(inputs)) + biases\n\n\n@numba.njit\ndef leaky_relu(inputs: np.ndarray, negative_slope: float = 1e-2) -> np.ndarray:\n return np.maximum(inputs, np.float32(0)) + np.float32(negative_slope) * np.minimum(inputs, np.float32(0))\n\n\n@numba.njit\ndef initialize_network_outputs(\n network: NetworkParameters,\n height: int,\n width: int,\n dtype: np.dtype = np.float32,\n) -> Tuple[np.ndarray, NetworkOutputs]:\n\n _, num_channels, _, _ = network[0][0].shape\n padding_height, padding_width = calculate_padding(-1, network)\n\n inputs = np.zeros((num_channels, height + 2 * padding_height, width + 2 * padding_width), dtype=dtype)\n\n outputs = List()\n\n for layer_index, (weight, _, _, _, _, _, _, _, _) in enumerate(network):\n num_channels, _, _, _ = weight.shape\n padding_height, padding_width = calculate_padding(layer_index, network)\n\n output = np.zeros((num_channels, height + 2 * padding_height, width + 2 * padding_width), dtype=dtype)\n\n outputs.append(output)\n\n return inputs, outputs\n","repo_name":"adeandrade/research","sub_path":"projects/conditional-residual/coding/autoregression.py","file_name":"autoregression.py","file_ext":"py","file_size_in_byte":5246,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"51"} +{"seq_id":"41113630403","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 1 18:14:35 2022\r\n\r\n@author: 2244530j\r\nOnly for PhD Python Workshop, Univeristy of Glasgow.\r\n\"\"\"\r\n\r\n\"\"\"\r\nObjective: download and save a google search result web page\r\n\"\"\"\r\n\r\n#pip install requests\r\n#import\r\nimport requests\r\n\r\n#Step 1: Web Targeting\r\n#request headers\r\nheaders ={\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'\r\n }\r\n#url = 'https://www.google.co.uk/search?q=test'\r\nurl = 'https://www.google.co.uk/search'\r\n#the parameters of the url\r\nsearch = input('enter what to search:')\r\nparam ={\r\n 'query': search\r\n }\r\n\r\n#Step 2: Request url with parameters\r\nresponse = requests.get(url = url, params = param, headers = headers)\r\n\r\n#Step 3: Obtain and Parse the Response\r\npage_text = response.text\r\n\r\n#Step 4: Data Saving \r\nfileName = search + '.html'\r\nwith open(fileName, 'w', encoding = 'utf-8') as fp:\r\n fp.write(page_text)\r\n\r\n#Finish\r\n print(fileName, 'is successfully downloaded')\r\n \r\n \r\n \r\n","repo_name":"liangjiawenr/Python-Workshop","sub_path":"Data_visulation&Web_scarping/demo2.py","file_name":"demo2.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"41805019581","text":"from datetime import datetime, timedelta\nfrom calendar import HTMLCalendar\nfrom .models import Event\nfrom django.urls import reverse\nimport locale\n\nlocale.setlocale(locale.LC_ALL, \"pl_PL\")\n\n\nclass Calendar(HTMLCalendar):\n def __init__(self, year=None, month=None, tor_id=None, user=None):\n self.year = year\n self.month = month\n self.tor_id = tor_id\n self.user = user\n super(Calendar, self).__init__()\n\n def formatday(self, day, events):\n events_per_day = events.filter(day=day).order_by(\"hour_start\")\n current_day = \"\"\n for event in events_per_day:\n if self.user.is_superuser or event.user == self.user:\n current_day += f'
  • {event.get_html_url(tor_id=self.tor_id)}
  • '\n else:\n current_day += f'
  • {event.hour_start}:00 - {event.hour_stop}:00
  • '\n\n url_to_event = reverse(\n \"cal:event_newer\", args=(self.tor_id, day, self.month, self.year)\n )\n url_string = f'{day}'\n if day != 0:\n if current_day:\n return f\"
    {url_string}
    Rezerwacje:
      {current_day}
    \"\n\n return f\"{url_string}
      {current_day}
    \"\n return \"\"\n\n def formatweek(self, theweek, events):\n week = \"\"\n for current_day, weekday in theweek:\n week += self.formatday(current_day, events)\n return f\" {week} \"\n\n def formatmonth(self, withyear=True):\n events = Event.objects.filter(year=self.year, month=self.month, tor=self.tor_id)\n\n cal = f'\\n'\n cal += f\"{self.formatmonthname(self.year, self.month, withyear=withyear)}\\n\"\n cal += f\"{self.formatweekheader()}\\n\"\n for week in self.monthdays2calendar(self.year, self.month):\n cal += f\"{self.formatweek(week, events)}\\n\"\n\n return cal\n","repo_name":"maciekrepository/system_rezerwacji_strzelnicy","sub_path":"cal/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"21907310159","text":"import os\nimport sys\nimport time\n\nimport galsim\n\ndef time_silicon_accumulate():\n nx = 1000\n ny = 1000\n nobj = 1000\n photons_per_obj = 10000\n flux_per_photon = 1\n\n rng = galsim.UniformDeviate(314159)\n\n sensor = galsim.SiliconSensor(rng=rng.duplicate(), diffusion_factor=0.0)\n\n im = galsim.ImageF(nx, ny)\n\n num_photons = nobj * photons_per_obj\n photons = galsim.PhotonArray(num_photons)\n\n rng.generate(photons.x)\n photons.x *= nx\n photons.x += 0.5\n rng.generate(photons.y)\n photons.y *= ny\n photons.y += 0.5\n photons.flux = flux_per_photon\n\n t1 = time.time()\n sensor.accumulate(photons, im)\n t2 = time.time()\n print('Time = ', t2-t1)\n\n\nif __name__ == \"__main__\":\n time_silicon_accumulate()\n","repo_name":"GalSim-developers/GalSim","sub_path":"devel/time_silicon_accumulate.py","file_name":"time_silicon_accumulate.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":203,"dataset":"github-code","pt":"51"} +{"seq_id":"39748398909","text":"from game_nodes import *\nimport copy\n\nclass CanonGameTree():\n def __init__(self, root_state, player_num):\n self.root = GameNode(root_state, 1, player_num)\n self.player = player_num\n self.current_nodes = [self.root] # for creating the game tree\n self.total_nodes = 1\n self.terminal_nodes = 0\n \n def create_node_children(self, node):\n if node.winner != None or len(node.children) != 0:\n return\n board = node.state\n turn = node.turn\n children = []\n child_boards = []\n options = [(i,j) for i in range(len(board)) for j in range(len(board)) if board[i][j] == None]\n for option in options:\n board_copy = copy.deepcopy(board)\n board_copy[option[0]][option[1]] = turn\n child_boards.append(board_copy)\n child = GameNode(board_copy, 3-turn, self.player)\n child.added_coord = option\n child.previous = [node]\n children.append(child)\n node.children = children\n return board_copy\n\n def create_game_tree(self):\n if len(self.current_nodes) == 0:\n self.current_nodes = [self.root]\n return\n all_children = []\n for node in self.current_nodes:\n child_boards = self.create_node_children(node)\n if len(node.children) != 0:\n all_children += node.children\n self.total_nodes += len(node.children)\n else:\n self.terminal_nodes += 1\n self.current_nodes = all_children\n self.create_game_tree()\n \n def set_node_scores(self):\n assert len(self.root.children) != 0, \"create game tree before setting scores\"\n self.root.set_score()\n return\n \n def get_best_move(self):\n scores = [node.score for node in self.root.children]\n max_index = scores.index(max(scores))\n best_result = self.root.children[max_index]\n return best_result.added_coord\n","repo_name":"JHpusd/games","sub_path":"game_tree_ttt/canon_game_tree.py","file_name":"canon_game_tree.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"19172575458","text":"import argparse #to use the command line\nimport csv \nimport datetime\nimport logging #other form to show informatión in console, similar to print\n#configure us login module \nlogging.basicConfig(level=logging.INFO)\n\nimport news_page_objects as news\n#regular expression module\nimport re\n\n#para manejar los errores\nfrom requests.exceptions import HTTPError, ContentDecodingError #TODO averiguar estas exceptions\nfrom urllib3.exceptions import MaxRetryError, DecodeError\nfrom common import config\n\n#give name file --> __name__ \nlogger = logging.getLogger(__name__)\n\n#regular expression to verify links\n# ^h --> simbolo con el que empieza\n# s? --> is optional\n# .+ --> uno o más letras\n# $ --> terminal el patron\nis_well_formed_link = re.compile(r'^https?://.+/.+$') # https://example.com/hello\nis_root_path = re.compile(r'^/.+$') # /some-text\n\n#news_site_uid para este caso es eluniversal ó elpais\ndef _news_scraper(news_site_uid):\n counter = 0\n #we want acces to news_sites, we pass id select for users\n #and requests(solicitamos) url of news_site_uid\n host = config()['news_sites'][news_site_uid]['url']\n \n #print message with url requested\n logging.info('Beggining scraper for {}'.format(host))\n homepage = news.HomePage(news_site_uid, host)\n\n articles = []\n for link in homepage.article_links:\n #print(link)\n #dado que no todos los links no vienen con la estructura correcta\n #entonces _fetch... nos devolvera un link correcto al cual podamso acceder\n article = _fetch_article(news_site_uid, host, link)\n\n #si hay un link con body entonces\n if article:\n logger.info('Article fetched!!')\n articles.append(article)\n #print('titulo loks: {}'.format(article.title))\n counter +=1\n print(counter)\n if counter >= 5:\n break\n \n _save_articles(news_site_uid, articles)\n\n \n #article numbers got\n #print(len(article))\n\ndef _save_articles(news_site_uid, articles):\n #para conocer el dia de hoy\n now = datetime.datetime.now().strftime('%Y_%m_%d')\n #file name -- type csv\n out_file_name = '{news_site_uid}_{datetime}_articles.csv'.format(\n news_site_uid = news_site_uid,\n datetime= now)\n\n #headers del csv\n #lambda es una función inline\n #se va a filtrar por las propiedades que no empiecen por \"_\"\n # dir(articles[0]) se le pasa el 1er articulo\n #el filtro devuelve una iterador pro eso se uda list\n csv_headers = list(filter(lambda property: not property.startswith('_'), dir(articles[0]))\n )\n\n with open(out_file_name, mode = 'w+', encoding = \"utf-8\") as f:\n counter = 0\n writer = csv.writer(f)\n writer.writerow(csv_headers)\n\n for article in articles:\n row = [str(getattr(article, prop)) for prop in csv_headers]\n writer.writerow(row)\n counter +=1\n print(counter)\n \ndef _fetch_article(news_site_uid, host, link):\n logger.info('Start fetching article at {}'.format(link))\n\n article = None\n try:\n article = news.ArticlePage(news_site_uid, _build_link(host,link))\n #HTTPError sucede cuando el recurso web no existe, \n #MaxRetryError elimina la posibilidad que se vaya al infinito tratando de\n #encontrar la pag\n #exc_info = False -->para que no muestre el error\n except (HTTPError, MaxRetryError, DecodeError, ContentDecodingError) as e:\n logger.warning('Error while fetching the article', exc_info = False)\n\n #si existe el articulo y no tiene body\n if article and not article.body:\n logger.warning('Invalid article. There is no body')\n return None\n\n return article \n\n#this function return a correct liks\ndef _build_link(host, link):\n\n #si la funcion esta completa, entonces devuelva el link\n if is_well_formed_link.match(link):\n return link\n #si empezo con / entonces concatene\n elif is_root_path.match(link):\n return '{}{}'.format(host,link)\n #si el link no empieza con diagonal estructuramos el link\n else:\n return '{host}/{uri}'.format(host=host, uri=link)\n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n \n #access to keys of the map\n #return a iter and for this we used the list\n news_site_choices = list(config()['news_sites'].keys())\n\n #difference betwen arguments and options is tha first are necessaries\n #add arguments\n parser.add_argument('news_site',\n #help is necessary to use the program or command line\n help='The news site that you want to scrape',\n type= str,\n #choices in this case are eluniversal or elpais\n choices= news_site_choices)\n\n # as by now we have the arguments\n #ask to parser, that \"parsee\" and return an object \n #with write python main.py --help argparse generate a command line with info\n args = parser.parse_args()\n #send site option select for the user\n _news_scraper(args.news_site)\n\n","repo_name":"GustavoDavila77/Curso-de-ingenieria-de-datos-con-python-","sub_path":"automation/extract/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"17008836297","text":"import re\n\ndef check_code(phone):\n if phone[0:4] == '+254' or phone[0:2] == '07' or phone[0:2] == '01':\n return 1\n\ndef getContact(filename, outputFilename):\n data = ''\n kenCon = []\n\n with open(filename, 'r') as f:\n data = f.read()\n\n pattern = r'(?s)BEGIN:VCARD\\n.*?END:VCARD\\n'\n match = re.findall(pattern,data,re.DOTALL)\n\n for contact in match:\n pattern = r'(?s)TEL;TYPE=CELL:.*?\\n'\n match = str(re.findall(pattern,contact,re.DOTALL))\n item = match.strip('\\n').split(':')\n try:\n phone = item[1]\n if check_code(phone) != 1:\n continue\n else:\n kenCon.append(contact)\n except IndexError:\n continue\n write_to_vcf(kenCon, outputFilename)\n\ndef write_to_vcf(kenCon, file):\n kenCon = ''.join(kenCon)\n with open(file, 'w') as f:\n f.write(kenCon)\n","repo_name":"castorichy/vcf-splitter_byCountry","sub_path":"vcfdel.py","file_name":"vcfdel.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"3107144997","text":"class Solution:\n def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:\n cities = [0] * n\n\n for a, b in roads:\n cities[a] += 1\n cities[b] += 1\n\n s = set()\n for r in roads:\n s.add(tuple(sorted(r)))\n\n res = 0\n for u in range(n):\n for v in range(u + 1, n):\n ans = cities[u] + cities[v]\n ans -= tuple(sorted([u, v])) in s\n res = max(res, ans)\n\n return res","repo_name":"Vleshchik/Leetcode--my-answers-","sub_path":"1615. Maximal Network Rank.py","file_name":"1615. Maximal Network Rank.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"7421116823","text":"# DANGEROUS WRITING\nfrom tkinter import *\nfrom tkinter.scrolledtext import ScrolledText\nimport datetime\n\n# program settings\nPROGRAM_NAME = \"Dangerous Writing\"\nBG_COLOR = \"#A9A9A9\"\nWINDOW_SIZE = \"600x450\"\nTIME_LIMIT = 5\n\n\n# program class\nclass Program:\n\n # initialize settings\n def __init__(self):\n\n self.text = \"\"\n self.elapsed_time = 0\n\n self.window = Tk()\n self.window.title(PROGRAM_NAME)\n self.window.config(padx=50, pady=50, bg=BG_COLOR)\n self.window.geometry(WINDOW_SIZE)\n self.window.resizable(width=0, height=0)\n\n self.title_label = Label(text=PROGRAM_NAME, font=(\"Arial\", 16, \"bold\"), bg=BG_COLOR, justify=\"center\")\n self.title_label.grid(row=0, column=0, pady=10, sticky='we')\n\n self.user_textbox = ScrolledText(self.window, wrap=WORD, width=50, height=10, font=(\"Arial\", 12, \"normal\"), padx=10, pady=10)\n self.user_textbox.grid(row=1, column=0, padx=5, pady=(20, 0), sticky='we')\n self.user_textbox.focus()\n\n self.save_button = Button(text=\" SAVE \", width=20, font=(\"Arial\", 12, \"bold\"), command=self.save_work)\n self.save_button.grid(row=2, column=0, padx=10, pady=(30, 0))\n\n self.dangerous_writing()\n\n self.window.mainloop()\n\n # save work\n def save_work(self):\n\n with open(\"work.txt\", \"a\") as file:\n\n file.write(\"TEXT - \" + datetime.datetime.now().strftime(\"%x\") + \"\\n\\n\" + self.user_textbox.get(\"1.0\", END).strip() + \"\\n\\n\")\n\n # write text\n def dangerous_writing(self):\n\n if self.user_textbox.get(\"1.0\", END).strip() == self.text:\n self.elapsed_time += 1\n else:\n self.elapsed_time = 0\n\n if self.elapsed_time >= TIME_LIMIT:\n self.user_textbox.delete('1.0', END)\n\n self.text = self.user_textbox.get(\"1.0\", END).strip()\n self.window.after(1000, self.dangerous_writing)\n\n\n# main program\nprogram = Program()\n","repo_name":"MariaMa-GitHub/dangerous-writing","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"13986699305","text":"from django.shortcuts import render,redirect\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate,logout,login\nfrom home.models import *\nfrom django.contrib import messages\nfrom datetime import datetime\nfrom django.db import connection\nfrom django.db.models import Q\n\nfrom django.views.decorators.cache import cache_control\n\n\n# Create your views here.\ndef index(request):\n return render(request,'index.html')\ndef signin(request):\n if request.method==\"POST\":\n #check if user entered correct credentials\n username = request.POST.get('username')\n password = request.POST.get('password')\n user = authenticate(username=username, password=password)\n if user is not None:\n login(request,user)\n return redirect('/dashboard')\n else:\n messages.error(request,\"Incorrect Credentials, Try again\")\n print(\"yes\")\n return render(request,\"signin.html\",{'messages': messages.get_messages(request)})\n return render(request,'signin.html',{'messages': messages.get_messages(request)})\ndef signout(request):\n logout(request)\n return redirect(\"/\")\ndef contact(request):\n if request.method == \"POST\":\n name = request.POST.get('name')\n email = request.POST.get('email')\n phone = request.POST.get('phone')\n desc = request.POST.get('desc')\n contact = Contact(name=name, email=email, phone=phone, desc=desc, date = datetime.today())\n contact.save()\n messages.success(request, 'Your message has been sent!')\n return render(request,'contact.html')\ndef about(request):\n return render(request,'about.html')\ndef clubmembers(request):\n if request.user.is_authenticated:\n username=request.user.username\n with connection.cursor() as cursor:\n select_query=f\"SELECT CLUB_TYPE,CATEGORY FROM home_clubidentifier where username = '{username}'\"\n cursor.execute(select_query)\n result = cursor.fetchall()\n if result:\n category=result[0][1]\n return render(request,'clubmembers.html',{'category':category})\ndef addmembers(request):\n if request.user.is_authenticated:\n username=request.user.username\n with connection.cursor() as cursor:\n select_query=f\"SELECT CLUB_TYPE,CATEGORY FROM home_clubidentifier where username = '{username}'\"\n cursor.execute(select_query)\n result = cursor.fetchall()\n if result:\n category=result[0][1]\n return render(request,'addmembers.html',{'category':category})\ndef eventslist(request):\n if request.user.is_authenticated:\n username=request.user.username\n with connection.cursor() as cursor:\n select_query=f\"SELECT CLUB_TYPE,CATEGORY FROM home_clubidentifier where username = '{username}'\"\n cursor.execute(select_query)\n result = cursor.fetchall()\n if result:\n category=result[0][1]\n return render(request,'eventslist.html',{'category':category})\ndef addevents(request):\n if request.user.is_authenticated:\n username=request.user.username\n with connection.cursor() as cursor:\n select_query=f\"SELECT CLUB_TYPE,CATEGORY FROM home_clubidentifier where username = '{username}'\"\n cursor.execute(select_query)\n result = cursor.fetchall()\n if result:\n category=result[0][1]\n return render(request,'addevents.html',{'category':category})\ndef clubtimeline(request):\n if request.user.is_authenticated:\n username=request.user.username\n with connection.cursor() as cursor:\n select_query=f\"SELECT CLUB_TYPE,CATEGORY FROM home_clubidentifier where username = '{username}'\"\n cursor.execute(select_query)\n result = cursor.fetchall()\n if result:\n category=result[0][1]\n return render(request,'clubtimeline.html',{'category':category})\n\ndef dashboard(request):\n if request.user.is_anonymous:\n return redirect(\"/index.html\")\n if request.user.is_authenticated:\n username=request.user.username\n with connection.cursor() as cursor:\n select_query=f\"SELECT CLUB_TYPE,CATEGORY FROM home_clubidentifier where username = '{username}'\"\n cursor.execute(select_query)\n result = cursor.fetchall()\n if result:\n category=result[0][1]\n return render(request,'dashboard.html',{\"category\":category})\n\n'''def approveRequestOd(request,request_id):\n if request.user.is_authenticated:\n username=request.user.username\n with connection.cursor() as cursor:\n select_query=f\"SELECT CLUB_TYPE,CATEGORY FROM home_clubidentifier where username = '{username}'\"\n cursor.execute(select_query)\n result = cursor.fetchall()\n if result:\n type=result[0][0]\n category=result[0][1]\n if category==\"SC\":\n if type==\"cultural\":\n duty_request=OnDutyRequestClubCultural.objects.get(id=request_id)\n if duty_request:\n on_duty_sc = OnDutyRequestSCCultural(\n student_roll_no=duty_request.student_roll_no,\n date_of_od=duty_request.date_of_od,\n course_code=duty_request.course_code,\n faculty_name=duty_request.faculty_name,\n reason=duty_request.reason)\n on_duty_sc.save()\n duty_request.delete()\n return \n elif type==\"technical\":\n duty_request=OnDutyRequestClubTechnical.objects.get(id=request_id)\n if duty_request:\n on_duty_sc = OnDutyRequestSCTechnical(\n student_roll_no=duty_request.student_roll_no,\n date_of_od=duty_request.date_of_od,\n course_code=duty_request.course_code,\n faculty_name=duty_request.faculty_name,\n reason=duty_request.reason)\n on_duty_sc.save()\n duty_request.delete()\n return \n elif type==\"sports\":\n duty_request=OnDutyRequestClubSports.objects.get(id=request_id)\n if duty_request:\n on_duty_sc = OnDutyRequestSCSports(\n student_roll_no=duty_request.student_roll_no,\n date_of_od=duty_request.date_of_od,\n course_code=duty_request.course_code,\n faculty_name=duty_request.faculty_name,\n reason=duty_request.reason)\n on_duty_sc.save()\n duty_request.delete()\n return \n elif category==\"FI\":\n if type==\"cultural\":\n duty_request=OnDutyRequestSCCultural.objects.get(id=request_id)\n if duty_request:\n duty_request.delete()\n return \n elif type==\"technical\":\n duty_request=OnDutyRequestSCTechnical.objects.get(id=request_id)\n if duty_request:\n duty_request.delete()\n return \n elif type==\"sports\":\n duty_request=OnDutyRequestSCSports.objects.get(id=request_id)\n if duty_request:\n duty_request.delete()\n return \n else:\n return\n else:\n return'''\n\ndef approvalStatus(request):\n print(\"inside approval status\")\n if request.user.is_anonymous:\n return redirect(\"/\")\n if request.user.is_authenticated:\n username=request.user.username\n with connection.cursor() as cursor:\n select_query=f\"SELECT CLUB_TYPE,CATEGORY FROM home_clubidentifier where username = '{username}'\"\n cursor.execute(select_query)\n result = cursor.fetchall()\n if result:\n type=result[0][0]\n category=result[0][1]\n try:\n if request.method==\"POST\":\n roll_no = request.POST.get('roll_no')\n date = request.POST.get('date')\n course_code = request.POST.get('course-code')\n faculty = request.POST.get('faculty')\n reason = request.POST.get('reason')\n query=OnDutyRequest.objects.all()\n conditions=[]\n if roll_no:\n conditions.append(Q(student_roll_no=roll_no))\n if date:\n conditions.append(Q(date_of_od=date))\n if course_code:\n conditions.append(Q(course_code=course_code))\n if faculty:\n conditions.append(Q(faculty_name=faculty))\n if reason:\n conditions.append(Q(reason=reason))\n if category==\"C\":\n conditions.append(Q(type_of_club=type))\n conditions.append(Q(username=username))\n #on_duty_approval_status = OnDutyRequest.objects.filter(student_roll_no=roll_no, date_of_od=date, course_code=course_code, faculty_name=faculty, type_of_club=type, username=username)\n elif category==\"SC\" or category==\"FI\":\n conditions.append(Q(type_of_club=type))\n # conditions.append(Q(username=username))\n #on_duty_approval_status = OnDutyRequest.objects.filter(student_roll_no=roll_no, date_of_od=date, course_code=course_code, faculty_name=faculty, type_of_club=type)\n \n if conditions:\n query = query.filter(*conditions)\n on_duty_approval_status = query.all()\n\n else:\n if category==\"C\":\n print(\"inside C\")\n on_duty_approval_status = OnDutyRequest.objects.filter(type_of_club=type,username=username)\n # if on_duty_approval_status.exists():\n # print(\"not empty\")\n # else:\n # print(\"emtpy\")\n elif category==\"SC\" or category==\"FI\":\n on_duty_approval_status = OnDutyRequest.objects.filter(type_of_club=type)\n except OnDutyRequest.DoesNotExist:\n on_duty_approval_status = None\n return render(request, \"approval_status.html\", {'on_duty_approval_status': on_duty_approval_status,'category':category})\n\n\ndef approve(request,request_id=None):\n if request.user.is_anonymous:\n return redirect(\"/\")\n if request.user.is_authenticated:\n username=request.user.username\n with connection.cursor() as cursor:\n select_query=f\"SELECT CLUB_TYPE,CATEGORY FROM home_clubidentifier where username = '{username}'\"\n cursor.execute(select_query)\n result = cursor.fetchall()\n if result:\n type=result[0][0]\n category=result[0][1]\n print(category,type)\n try:\n if request.method==\"POST\":\n if category==\"SC\":\n od_object = OnDutyRequest.objects.get(id=request_id)\n od_object.status=\"PFI\"\n od_object.save()\n # approveRequestOd(request,request_id)\n on_duty_requests = OnDutyRequest.objects.filter(type_of_club=type,status=\"PSC\")\n # if type==\"cultural\":\n # on_duty_requests = OnDutyRequestClubSports.objects.all() \n # elif type==\"technical\":\n # on_duty_requests = OnDutyRequestClubTechnical.objects.all() \n # elif type==\"sports\":\n # on_duty_requests = OnDutyRequestClubSports.objects.all() \n elif category==\"FI\":\n od_object = OnDutyRequest.objects.get(id=request_id)\n od_object.status=\"AP\"\n od_object.save()\n on_duty_requests = OnDutyRequest.objects.filter(type_of_club=type,status=\"PFI\")\n # approveRequestOd(request,request_id)\n # if type==\"cultural\":\n # on_duty_requests = OnDutyRequestSCCultural.objects.all()\n # elif type==\"technical\":\n # on_duty_requests = OnDutyRequestSCTechnical.objects.all()\n # elif type==\"sports\":\n # on_duty_requests = OnDutyRequestSCCultural.objects.all()\n return render(request, \"approval.html\", {'on_duty_requests': on_duty_requests,'category':category})\n # elif category==\"SC\" and type==\"cultural\":\n # #display request list of cultural from clubs\n # # print(\"inside sc and cultural\")\n # # on_duty_requests = OnDutyRequestClubCultural.objects.get()\n # on_duty_requests = OnDutyRequest.objects.get(type_of_club=type,status=\"PSC\")\n # elif category==\"SC\" and type==\"technical\":\n # #display request list of technical from clubs\n # on_duty_requests = OnDutyRequestClubTechnical.objects.all()\n # elif category==\"SC\" and type==\"sports\":\n # #display request list of sports from clubs\n # on_duty_requests = OnDutyRequestClubSports.objects.all()\n # elif category==\"FI\" and type==\"cultural\":\n # #display request list of sports from sc\n # on_duty_requests = OnDutyRequestSCCultural.objects.all()\n # elif category==\"FI\" and type==\"technical\":\n # #display request list of sports from sc\n # on_duty_requests = OnDutyRequestSCTechnical.objects.all()\n # elif category==\"FI\" and type==\"sports\":\n # #display request list of sports from sc\n # on_duty_requests = OnDutyRequestSCCultural.objects.all()\n \n\n elif category==\"SC\":\n on_duty_requests = OnDutyRequest.objects.filter(type_of_club=type,status=\"PSC\")\n elif category==\"FI\":\n on_duty_requests = OnDutyRequest.objects.filter(type_of_club=type,status=\"PFI\")\n except OnDutyRequest.DoesNotExist:\n on_duty_requests = None\n return render(request, \"approval.html\", {'on_duty_requests': on_duty_requests,'category':category})\n\n\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\ndef requestOnDuty(request):\n if request.user.is_anonymous:\n return redirect(\"/\")\n if request.user.is_authenticated:\n username = request.user.username\n with connection.cursor() as cursor:\n select_query=f\"SELECT CLUB_TYPE,CATEGORY FROM home_clubidentifier where username = '{username}'\"\n cursor.execute(select_query)\n result = cursor.fetchall()\n if result:\n type=result[0][0]\n category=result[0][1]\n if request.method == 'POST':\n username = request.user.username\n roll_nos = request.POST.getlist('roll_no')\n dates = request.POST.getlist('date')\n course_codes = request.POST.getlist('course-code')\n faculties = request.POST.getlist('faculty')\n reasons = request.POST.getlist('reason') \n if category==\"C\":\n if type==\"cultural\":\n for i in range(len(roll_nos)):\n record = OnDutyRequest(\n student_roll_no=roll_nos[i],\n date_of_od=dates[i],\n course_code=course_codes[i],\n faculty_name=faculties[i],\n reason=reasons[i],\n type_of_club=\"cultural\",\n status=\"PSC\",\n username=username\n )\n record.save()\n return redirect('/requestOd')\n elif type==\"sports\":\n for i in range(len(roll_nos)):\n record = OnDutyRequest(\n student_roll_no=roll_nos[i],\n date_of_od=dates[i],\n course_code=course_codes[i],\n faculty_name=faculties[i],\n reason=reasons[i],\n type_of_club=\"sports\",\n status=\"PSC\",\n username=username\n )\n record.save()\n return redirect('/requestOd')\n elif type==\"technical\":\n for i in range(len(roll_nos)):\n record = OnDutyRequest(\n student_roll_no=roll_nos[i],\n date_of_od=dates[i],\n course_code=course_codes[i],\n faculty_name=faculties[i],\n reason=reasons[i],\n type_of_club=\"technical\",\n status=\"PSC\",\n username=username\n )\n record.save()\n return redirect('/requestOd')\n elif category==\"SC\":\n if type==\"cultural\":\n for i in range(len(roll_nos)):\n record = OnDutyRequest(\n student_roll_no=roll_nos[i],\n date_of_od=dates[i],\n course_code=course_codes[i],\n faculty_name=faculties[i],\n reason=reasons[i],\n type_of_club=\"cultural\",\n status=\"PFI\",\n username=username\n )\n record.save()\n return redirect('/requestOd')\n elif type==\"technical\":\n for i in range(len(roll_nos)):\n record = OnDutyRequest(\n student_roll_no=roll_nos[i],\n date_of_od=dates[i],\n course_code=course_codes[i],\n faculty_name=faculties[i],\n reason=reasons[i],\n type_of_club=\"technical\",\n status=\"PFI\",\n username=username\n )\n record.save()\n return redirect('/requestOd')\n elif type==\"sports\":\n for i in range(len(roll_nos)):\n record = OnDutyRequest(\n student_roll_no=roll_nos[i],\n date_of_od=dates[i],\n course_code=course_codes[i],\n faculty_name=faculties[i],\n reason=reasons[i],\n type_of_club=\"sports\",\n status=\"PFI\",\n username=username\n )\n record.save()\n return redirect('/requestOd') \n return render(request,\"requestOd.html\",{'category':category})\n \n\n \n\ndef changePassword(request):\n if request.user.is_anonymous:\n return redirect(\"/\")\n if request.user.is_authenticated:\n if request.method == 'POST':\n current_password = request.POST['current_password']\n new_password = request.POST['new_password']\n confirm_password = request.POST['confirm_new_password']\n user = request.user\n # Check if the current password is correct\n if user.check_password(current_password):\n if new_password == confirm_password:\n # Change the user's password\n user.set_password(new_password)\n user.save()\n print(\"changed password\")\n logout(request)\n return render(request,'index.html') \n\n return render(request, 'changePassword.html')\n\n\ndef addUser(request):\n if request.user.is_anonymous:\n return redirect(\"/\")\n if request.user.is_authenticated:\n username=request.user.username\n with connection.cursor() as cursor:\n select_query=f\"SELECT CLUB_TYPE,CATEGORY FROM home_clubidentifier where username = '{username}'\"\n cursor.execute(select_query)\n result = cursor.fetchall()\n if result:\n type=result[0][0]\n category=result[0][1]\n if category==\"FI\":\n if request.method == 'POST':\n club_username = request.POST['username']\n club_password = request.POST['password']\n club_confirm_password = request.POST['confirm_password']\n if club_password == club_confirm_password:\n # Check if a user with the same username or email already exists\n if not User.objects.filter(username=club_username).exists():\n User.objects.create_user(username=club_username,password=club_password)\n return redirect('adduser.html',{\"category\":category})\n return render(request, 'adduser.html',{\"category\":category})\n return render(request, 'adduser.html')\n\ndef profile(request):\n if request.user.is_anonymous:\n return redirect(\"/\")\n if request.user.is_authenticated:\n return render(request,'profile.html')\n","repo_name":"Akram3104/Club-Management-DBMS","sub_path":"ClubManagement/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":24175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"51"} +{"seq_id":"42710748000","text":"import sys\nimport cmath\n\nast = list()\nlines = sys.stdin.readlines()\nfor i in range(len(lines)):\n for k in range(len(lines[i])):\n if lines[i][k] == \"#\":\n a = complex(i, k)\n ast.append(a)\n\nmax_ast = 0\nfor i in range(len(ast)):\n direct = set()\n for j in range(len(ast)):\n if i == j:\n continue\n diff = ast[i]-ast[j]\n #angle = diff.real / diff.imag\n direct.add(cmath.phase(diff))\n if len(direct) > max_ast:\n max_ast = len(direct)\n\nprint(max_ast)\n","repo_name":"ribalda/adventofcode","sub_path":"2019/10/step1.py","file_name":"step1.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"74699228317","text":"env = WengoGetEnvironment()\r\n\r\nlibs = [\r\n\t'imwrapper',\r\n\t'owutil'\r\n]\r\nlib_path = []\r\ninclude_path = ['../null']\r\ndefines = {}\r\nheaders = []\r\nsources = [\n\t'NullIMFactory.cpp',\r\n\t'NullIMChat.cpp',\n\t'NullIMConnect.cpp',\n\t'NullIMPresence.cpp',\n\t'NullIMContactList.cpp',\r\n]\r\n\nenv.WengoAddIncludePath(include_path)\r\nenv.WengoUseLibraries(libs)\r\nenv.WengoStaticLibrary('nullimwrapper', sources)\r\n","repo_name":"tkrotoff/WengoPhone","sub_path":"archaeology/200901-source-without-versioning/wengophone-2.0/libs/imwrapper/src/null/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"74541101279","text":"\"\"\"helper module for handling deprecation via the standard warnings module\r\n\r\nThe first time any function marked in this module is called, a RuntimeWarning\r\nwill be issued. This is because DeprecationWarnings are hidden by default while\r\nRuntimeWarnings are not. The RuntimeWarning explains to run python with the -Wd\r\nflag to show DeprecationWarnings.\r\n\r\nNote:\r\n\r\n All decorators in this module (and most other) must be placed before\r\n (below) any `staticmethod` and `classmethod` decorators, as those\r\n decorators do not wrap the functions well enough for `deprecation` to\r\n function.\r\n\r\nTo simply mark a function as deprecated, just decorate it with this module's\r\n`deprecated` decorator::\r\n\r\n @deprecated\r\n def function():\r\n ...\r\n\r\nThis will produce a simple warning that the function is deprecated. If you want\r\nto be a little more helpful, you can also tell your users what function to use\r\ninstead::\r\n\r\n @deprecated.favour(\"new_function\")\r\n def function():\r\n ...\r\n\r\nThis will produce a warning that tells the user to use whatever is supplied as\r\nthe first argument instead of the decorated function.\r\n\r\nAlternatively, in the case of a function being renamed, one can use::\r\n\r\n @deprecated.replacedby(new_function):\r\n def function():\r\n pass\r\n\r\nThis will completely replace the decorated function with a dummy function that\r\nfirst warns about the use of the deprecated name, and then calls the function\r\nsupplied as the first argument to the decorator.\r\n\r\nIf only certain uses a function are deprecated the `manual_warn` function can\r\nbe called when something deprecated is used, passing the full message to be\r\ndisplayed::\r\n\r\n def function(arg=None):\r\n if arg is None:\r\n manual_warn(\"Calling function without arg is deprecated\")\r\n\r\nIf classes are renamed, their old names can be deprecated with::\r\n\r\n Class = class_replaced(\"Class\", NewClass)\r\n\r\nLikewise, class attributes can be deprecated with::\r\n\r\n class Class:\r\n attr = attr_replaced(\"attr\", \"new_attr\")\r\n\r\n\"\"\"\r\n\r\nimport functools\r\nimport textwrap\r\nimport warnings\r\n\r\n\r\nclass KvWarning(Warning):\r\n \"\"\"Base class for all canlib warnings\"\"\"\r\n\r\n pass\r\n\r\n\r\nclass KvDeprecationBase(Warning):\r\n \"\"\"Base class for canlib warnings related to deprecation\"\"\"\r\n\r\n pass\r\n\r\n\r\nclass KvDeprecationWarning(KvDeprecationBase, DeprecationWarning):\r\n \"\"\"canlib equivalent of standard DeprecationWarning\"\"\"\r\n\r\n pass\r\n\r\n\r\nclass KvDeprecatedUsage(KvDeprecationBase, RuntimeWarning):\r\n \"\"\"Special RuntimeWarning emitted on first KvDeprecationWarning\"\"\"\r\n\r\n pass\r\n\r\n\r\ndef manual_warn(message, stacklevel=3):\r\n \"\"\"Manually warn using this module\r\n\r\n Any calls to this function qualifies as the \"first\" call in terms of\r\n raising a KvDeprecatedUsage.\r\n\r\n Args:\r\n message (str): used to initialize a KvDeprecationWarning\r\n stacklevel (int) [optional]: passed on to `warnings.warn`\r\n\r\n \"\"\"\r\n deprecated._any_called()\r\n warnings.warn(KvDeprecationWarning(message), stacklevel=stacklevel)\r\n\r\n\r\ndef attr_replaced(original, replacement):\r\n \"\"\"Create a `property` object representing a deprecated attribute\r\n\r\n Provides a getter, setter, and docstring.\r\n\r\n Args:\r\n original (str): the name of the deprecated attribute\r\n replacement (str): the name of the new attribute, to be used instead\r\n \"\"\"\r\n\r\n def fget(self):\r\n manual_warn(\r\n f\"Accessing {original} is deprecated, use {replacement} instead\"\r\n )\r\n return getattr(self, replacement)\r\n\r\n def fset(self, val):\r\n manual_warn(\r\n f\"Accessing {original} is deprecated, use {replacement} instead\"\r\n )\r\n setattr(self, replacement, val)\r\n\r\n doc = f\"Deprecated name for `{replacement}`\"\r\n\r\n return property(fget=fget, fset=fset, doc=doc)\r\n\r\n\r\ndef class_replaced(original, new, replacement=None):\r\n \"\"\"Create a deprecated class that preserves backwards compatibility\r\n\r\n Args:\r\n original (str): the name of the deprecated class\r\n new: the new class that replaces this one\r\n replacement (str) [optional]: the name of the new class, by default\r\n inferred from `new` argument\r\n \"\"\"\r\n if replacement is None:\r\n replacement = new.__name__\r\n\r\n def init_moved_class(self, *args, **kwargs):\r\n manual_warn(\r\n f\"{original} is deprecated, please use {replacement} instead\"\r\n )\r\n return new.__init__(self, *args, **kwargs)\r\n\r\n docparagraph = (\r\n \" `{old}` has been renamed `{new}`, using the old name (`{old}`) is deprecated.\"\r\n ).format(old=original, new=replacement)\r\n\r\n docparagraph = textwrap.fill(docparagraph, width=79, subsequent_indent=\" \")\r\n\r\n docstring = f\"Deprecated name for `{replacement}`\\n\\n{docparagraph}\\n\\n \"\r\n\r\n newcls = type(original, (new, object), {'__init__': init_moved_class, '__doc__': docstring})\r\n\r\n return newcls\r\n\r\n\r\nclass deprecated:\r\n \"\"\"Decorator for deprecating functions\r\n\r\n Also provides several class methods for alternate ways to wrap functions\r\n (or classes).\r\n\r\n \"\"\"\r\n\r\n _replacement = None\r\n _first = True\r\n\r\n @classmethod\r\n def cls(cls, replacement):\r\n \"\"\"Wrap a class's `__init__` function as deprecated\r\n\r\n Args:\r\n replacement (str): the name of the new class\r\n \"\"\"\r\n\r\n def expanded(old):\r\n obj = cls(old.__init__)\r\n old.__init__ = obj\r\n obj.__name__ = old.__name__\r\n obj._replacement = replacement\r\n return obj\r\n\r\n return expanded\r\n\r\n @classmethod\r\n def favour(cls, replacement):\r\n \"\"\"Wraps a function as deprecated\r\n\r\n Args:\r\n replacement (str): the name of the new function\r\n \"\"\"\r\n\r\n def expanded(func):\r\n obj = cls(func)\r\n obj._replacement = replacement\r\n return obj\r\n\r\n return expanded\r\n\r\n @classmethod\r\n def replacedby(cls, new, replacement=None):\r\n \"\"\"Wraps a function as deprecated, completely replacing it\r\n\r\n A function wrapped with this is never actually executed; when called,\r\n the call is delegated to the new function instead.\r\n\r\n Args:\r\n original (str): the name of the deprecated function\r\n new: the new function that replaces this one\r\n replacement (str) [optional]: the name of the new function, by default\r\n inferred from `new` argument\r\n\r\n \"\"\"\r\n\r\n def expanded(old):\r\n obj = cls(old)\r\n obj.func = new\r\n obj._replacement = replacement or new.__name__\r\n return obj\r\n\r\n return expanded\r\n\r\n def __init__(self, func):\r\n \"\"\"Wraps a function as deprecated\"\"\"\r\n self.func = func\r\n functools.update_wrapper(self, func)\r\n\r\n def __call__(self, *args, **kwargs):\r\n self._any_called()\r\n if self._replacement is None:\r\n msg = self.__name__ + \" has been deprecated!\"\r\n else:\r\n msg = \"{f} has been deprecated, use {r} instead!\".format(\r\n f=self.__name__,\r\n r=self._replacement,\r\n )\r\n warnings.warn(KvDeprecationWarning(msg), stacklevel=2)\r\n ret = self.func(*args, **kwargs)\r\n return ret\r\n\r\n def __get__(self, instance, owner):\r\n if instance is None:\r\n return self\r\n else:\r\n return functools.partial(self, instance)\r\n\r\n @classmethod\r\n def _any_called(cls):\r\n if cls._first:\r\n warnings.warn(\r\n KvDeprecatedUsage(\r\n \"A deprecated function was called! \"\r\n + \"Run python with -Wd flag for more information.\"\r\n )\r\n )\r\n cls._first = False\r\n","repo_name":"Kvaser/pycanlib","sub_path":"canlib/deprecation.py","file_name":"deprecation.py","file_ext":"py","file_size_in_byte":7805,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"51"} +{"seq_id":"10752528452","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom .models import Login_User\nfrom .serializers import Login_User_Serializer\nfrom rest_framework.parsers import JSONParser\nfrom django.views.decorators.csrf import csrf_exempt\n\n\n# Create your views here.\ndef Homepage (request):\n return HttpResponse (\"Hello and Welcome!!\")\ndef IndexPage (request):\n return HttpResponse (\"!!It's the Index Page!!\")\n\n@csrf_exempt\ndef AllUsers(request):\n try:\n all_users = Login_User.objects.all()\n except:\n return HttpResponse('Not Found! Sorry', status=404)\n \n if request.method == 'GET':\n users_serialized=Login_User_Serializer(all_users, many=True)\n return JsonResponse(users_serialized.data, safe=False, status=200)\n elif request.method == 'POST':\n input_data = JSONParser().parse(request)\n de_serialized=Login_User_Serializer(data=input_data)\n \n if de_serialized.is_valid():\n de_serialized.save()\n return JsonResponse(de_serialized.data, safe=False, status=200)\n else:\n return JsonResponse(de_serialized.errors, safe=False, status=400)\n \n@csrf_exempt\ndef SingleUserDetails(request,pk):\n try:\n user=Login_User.objects.get(pk=pk)\n except:\n return HttpResponse('Sorry, this is not found',status=404)\n \n if request.method == 'GET':\n users_serialized=Login_User_Serializer(user)\n return JsonResponse(users_serialized.data, status=200)\n \n elif request.method == 'PUT':\n input_data = JSONParser().parse(request)\n de_serialized=Login_User_Serializer(user, input_data)\n \n if de_serialized.is_valid():\n de_serialized.save()\n return JsonResponse(de_serialized.data, status=200)\n else:\n return JsonResponse(de_serialized.errors, status=400)\n \n elif request.method == 'DELETE':\n user.delete()\n return HttpResponse('Successfully deleted', status=204)","repo_name":"Jainika790/django-basic","sub_path":"env/Login_Syatem/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"7517321861","text":"#!/usr/bin/python\n\n\"\"\"Import modules\"\"\"\nimport logging\nimport argparse\nfrom movement import Movement as Move\nfrom turn import Turn\n\nlogging.basicConfig(format='[%(levelname)s] (%(threadName)-10s) %(message)s',)\n\n# help info\nPARSER = argparse.ArgumentParser(description='Laat de auto rijden.')\n# PARSER.add_argument('--loglevel', help='log alles', default='info')\nPARSER.add_argument(\"-v\", \"--verbose\", help=\"increase output verbosity\",\n action=\"store_true\")\nPARSER.add_argument(\n '--direction', help='Set to 1 for clockwise and -1 for anti-clockwise', type=int, default=1)\nPARSER.add_argument(\n '--seconds', help='How long must the car drive', type=int, default=1)\nPARSER.add_argument(\n '--speed', help='How fast must the car drive', type=int, default=1)\nARGS = PARSER.parse_args()\n# LOGLEVEL = ARGS.loglevel\nDIRECTION = ARGS.direction\nDIRECTION = -1 # backward\nDRIVE_TIME = ARGS.seconds\nWAIT_TIME = ARGS.speed / float(1000)\n\n# set log level\nif ARGS.verbose:\n logging.getLogger().setLevel(logging.DEBUG)\n\nAMOVE = Move()\nAMOVE.drive_time = 2\nAMOVE.run()\n\nATURN = Turn()\nATURN.drive_time = 2\nATURN.direction = -1\nATURN.run()\n\nAMOVE = Move()\nAMOVE.wait_time = 5\nAMOVE.run()\n","repo_name":"tuvokki/pistuff","sub_path":"autobot/mover.py","file_name":"mover.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"75029672478","text":"import numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nfrom Network import Unet2D\r\nimport DataPreprocessing as DP\r\nimport math\r\nimport torch.optim as optim\r\nfrom tqdm import tqdm\r\n\r\n[data, label] = DP.load_data('spectrogram\\\\Training set')\r\n\r\n## gpu setting ##\r\nDP.gpu_setting(gpu_num=0)\r\n\r\n\r\nfor test_sub in range(0, 50):\r\n ## initialize variable ##\r\n start_epoch = 0\r\n max_epoch = 50\r\n mdl = []\r\n mdl = Unet2D.UNet(1, 5)\r\n mdl.cuda()\r\n loss = nn.CrossEntropyLoss()\r\n batch_size = 128\r\n optimizer = optim.Adam(mdl.parameters(), lr=1e-5, betas=(0.9, 0.999), weight_decay=0.01)\r\n\r\n ## training model ##\r\n for epoch in range(start_epoch, max_epoch):\r\n\r\n if not (start_epoch == 0):\r\n checkpoint = torch.load('Unet2D\\\\epoch'+str(start_epoch)+'_test_sub'+str(test_sub+1))\r\n mdl.load_state_dict(checkpoint['model_state_dict'])\r\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\r\n loss = checkpoint['loss']\r\n mdl.train()\r\n loss_epoch = 0.0\r\n\r\n for sub in tqdm(range(data['len'])):\r\n\r\n if sub == test_sub:\r\n continue\r\n\r\n n = data[sub].shape[2]\r\n batch_max = math.ceil(n/batch_size)\r\n temp = data[sub]\r\n tempy = label[sub]\r\n temp = np.transpose(temp, [2, 0, 1])\r\n idx = np.arange(n)\r\n np.random.shuffle(idx)\r\n temp = temp[idx, :, :]\r\n tempy = tempy[:, idx]\r\n loss_tot = 0.0\r\n\r\n for batch_num in range(batch_max):\r\n\r\n xtrain = torch.FloatTensor(temp[batch_size*batch_num:batch_size*(batch_num+1), :, :]).cuda()\r\n ytrain = torch.LongTensor(np.squeeze(tempy[:, batch_size*batch_num:batch_size*(batch_num+1)])).cuda()\r\n\r\n xtrain = xtrain.unsqueeze(1)\r\n\r\n out = mdl(xtrain)\r\n\r\n loss_sub = loss(out, ytrain)\r\n mdl.zero_grad()\r\n loss_sub.backward()\r\n optimizer.step()\r\n\r\n loss_tot += loss_sub.data.item()\r\n\r\n #print('[Epoch %d/Sub %d] loss: %.3f'%(epoch+1, sub+1, loss_tot))\r\n loss_epoch += loss_tot\r\n\r\n print('[Epoch %d] total loss: %.3f'%(epoch+1, loss_epoch))\r\n\r\n torch.save({\r\n 'model_state_dict': mdl.state_dict(),\r\n 'optimizer_state_dict': optimizer.state_dict(),\r\n 'loss': loss\r\n }, 'Unet2D\\\\epoch'+str(epoch+1)+'_test_sub'+str(test_sub+1))\r\n\r\n","repo_name":"DeepBCI/Deep-BCI","sub_path":"3_Cognitive_BCI/Detection_Micro-sleep_Using_Transfer_Learning/Sleepstage.py","file_name":"Sleepstage.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","stars":336,"dataset":"github-code","pt":"51"} +{"seq_id":"28503494126","text":"import minion.core.components\nimport minion.core.utils\nimport multiprocessing\nimport subprocess\n\nlogger = multiprocessing.get_logger()\n\n\nclass BaseActuator(minion.core.components.BaseComponent):\n \"\"\"\n Base actuator class\n Sub classes need to implement the \"act\" method\n \"\"\"\n configuration = {}\n\n def __init__(self, name, configuration, channels=[], preprocessors=[], **kwargs):\n super(BaseActuator, self).__init__(name, configuration)\n self.channels = channels\n logger.info('Actuator <%s> created with configuration %s. Able to handle channels %s', name, self._configuration, ', '.join(channels))\n\n processors = []\n for p in preprocessors:\n try:\n c = minion.core.utils.module_loading.import_string(p['class'])\n except ImportError:\n logger.critical('Unable to import {}'.format(p['class']))\n else:\n processors.append(c(p.get('configuration', {})))\n\n self.preprocessors = processors\n\n def can_handle(self, channel, **kwargs):\n return channel in self.channels\n\n def preprocess_then_act(self, *args, **kwargs):\n # Go through the preprocessors\n go_ahead = True\n for p in self.preprocessors:\n try:\n p.test()\n except minion.preprocessors.exceptions.StopProcess:\n go_ahead = False\n break\n except minion.preprocessors.exceptions.ProcessValid:\n # Means we can go ahead without checking other preprocessors\n break\n\n if go_ahead:\n self.act(*args, **kwargs)\n\n def act(self, *args, **kwargs):\n raise NotImplementedError('Act needs to be implemented in actuator')\n\n\nclass ShellCommandActuator(BaseActuator):\n \"\"\"\n Actuator that will run a shell command using subprocess.\n Child classes need to implement _build_command which receives the same args and kwargs as BaseActuator's act\n\n Setting shell=True in child class is unsafe, see https://docs.python.org/2/library/subprocess.html#frequently-used-arguments\n \"\"\"\n shell = False\n\n def _build_command(self, *args, **kwargs):\n \"\"\"\n Returns a string or an array that will be passed to subprocess\n \"\"\"\n raise NotImplementedError('Shell command actuator needs to implement build command')\n\n def act(self, *args, **kwargs):\n command = self._build_command(*args, **kwargs)\n exit_code = subprocess.call(command, shell=self.shell)\n if exit_code:\n logger.info('Command \"%s\" with shell set as %s exited with code %s', ' '.join(command), self.shell, exit_code)\n","repo_name":"matiboy/minion","sub_path":"minion/acting/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"51"} +{"seq_id":"8617655604","text":"#Uses python3\nimport sys\nimport math\n\ndef dist(p1, p2):\n return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)\n\ndef minimum_distance(cord):\n m = len(cord) // 2\n if m == 1:\n return naive(cord)\n\n mid = cord[m][0]\n d1 = minimum_distance(cord[:m])\n d2 = minimum_distance(cord[m:])\n d = min(d1, d2)\n d3 = split(cord,d)\n #write your code here\n return min(d,d3)\n\ndef split(coord, ds):\n p = []\n m = len(coord)//2\n mid = coord[m][0]\n for c in coord:\n if abs(c[0] - mid) < ds :\n p.append(c)\n p.sort(key=lambda pi: pi[1])\n if len(p) < 2:\n return ds\n else:\n ds1 = dist(p[0], p[1])\n for i in range(len(p) - 1):\n for j in range(i + 1, min(i + 7, len(p))):\n ds1 = min(ds1, dist(p[i], p[j]))\n return ds1\n\ndef naive(ax):\n mi = dist(ax[0], ax[1])\n ln_ax = len(ax)\n if ln_ax == 2:\n return mi\n for i in range(ln_ax-1):\n for j in range(i + 1, ln_ax):\n if i != 0 and j != 1:\n d = dist(ax[i], ax[j])\n if d < mi: # Update min_dist and points\n mi = d\n return mi\n\nif __name__ == '__main__':\n n = int(input())\n points = []\n for i in range(n):\n points.append(tuple(map(int, input().split())))\n points.sort()\n # print(points)\n d1 = minimum_distance(points)\n print(\"{0:.9f}\".format(d1))\n","repo_name":"vikykumar/coursera-solutions","sub_path":"algorithm toolbox/week4 divide and conquer/closest.py","file_name":"closest.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"23441401016","text":"from django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom planner.models import DayTemplateRule, RuleSet, RuleSetElement, DateRule, \\\n Schedule, Task\nfrom datetime import datetime, date\nimport testing.postgresql\n\nPostgresql = testing.postgresql.PostgresqlFactory(cache_initialized_db=True)\n\ndef tearDownModule():\n Postgresql.clear_cache()\n\nclass PgTestCase(APITestCase):\n def setUp(self):\n self.postgresql = Postgresql()\n\n def tearDown(self):\n self.postgresql.stop()\n\n\nclass SimpleRuleTests(PgTestCase):\n def test_create_simplerule(self):\n url = '/planner/daytemplaterules/'\n data = {\"name_fr\": \"Lundi de Pâques\", \"name_en\": \"Easter Monday\",\"freq\": \"YEARLY\", \"byeaster\": \"1\"}\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(DayTemplateRule.objects.count(),1)\n self.assertEqual(DayTemplateRule.objects.get().name_fr,'Lundi de Pâques')\n\n\nclass RuleSetTests(PgTestCase):\n def test_create_ruleset(self):\n url = '/planner/rulesets/'\n data = {\"name_fr\" : \"Jours fériés France\", \"name_en\" : \"Days off France\"}\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(RuleSet.objects.count(),1)\n self.assertEqual(RuleSet.objects.get().name,'Jours fériés France')\n\nclass RuleSetElementTests(PgTestCase):\n def test_create_rulesetelement(self):\n url = '/planner/daytemplaterules/'\n data = {\"name_fr\": \"Lundi de Pâques\", \"name_en\": \"Easter Monday\",\"freq\": \"YEARLY\", \"byeaster\": \"1\"}\n response = self.client.post(url, data, format='json')\n\n url = '/planner/rulesets/'\n data = {\"name_fr\" : \"Jours fériés France\", \"name_en\" : \"Days off France\"}\n response = self.client.post(url, data, format='json')\n\n url = '/planner/rulesetelements/'\n data = {\"direction\":\"INCLUDE\", \"ruleset\" : RuleSet.objects.get().pk, \\\n \"baserule\" : DayTemplateRule.objects.get().pk }\n\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(RuleSetElement.objects.count(),1)\n\n url= '/planner/rulesets/'+ str(RuleSet.objects.get().pk) +'/between/?start=2017-01-01&end=2018-01-01'\n response = self.client.get(url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.content.decode('UTF-8'),'[\"2017-04-17\"]')\n\n def test_precedence(self):\n '''\n https://www.ietf.org/rfc/rfc2445.txt\n This implies that start date and times within exclusion related\n properties (i.e., \"EXDATE\" and \"EXRULE\") take precedence over those\n specified by inclusion properties (i.e., \"RDATE\" and \"RRULE\").\n\n There is so no need to order inclusions / exclusions\n '''\n\n mercredis = DayTemplateRule.objects.create(name_fr='Mercredis', name_en='Wednesdays',\\\n freq='WEEKLY', byweekday='WE', bymonth='', bysetpos='', bymonthday='', byyearday='',\\\n byweekno='', byeaster='')\n mercredis.save()\n\n derniers_mercredis_mois = DayTemplateRule.objects.create(name_fr=\"Derniers mercredis du mois\",\\\n name_en=\"Last wednesdays of month\", freq=\"MONTHLY\", byweekday=\"WE\", bymonth='',bysetpos=\"-1\",\\\n bymonthday='', byyearday='', byweekno='', byeaster='')\n derniers_mercredis_mois.save()\n\n april26_2017 = DateRule.objects.create(date = '2017-04-26')\n april26_2017.save()\n\n ruleset1 = RuleSet.objects.create(name='ruleset1')\n RuleSetElement.objects.create(direction='INCLUDE', baserule=mercredis, ruleset = ruleset1)\n RuleSetElement.objects.create(direction='EXCLUDE', baserule=derniers_mercredis_mois, ruleset = ruleset1)\n RuleSetElement.objects.create(direction='INCLUDE', baserule=april26_2017, ruleset = ruleset1)\n self.assertTrue(datetime(2017,3,22).date() in list(ruleset1.between(datetime(2017,3,1),datetime(2017,5,1))))\n self.assertFalse(datetime(2017,4,26).date() in list(ruleset1.between(datetime(2017,3,1),datetime(2017,5,1))))\n\n\nclass DeltaTests(APITestCase):\n pass\n\n\n\n\n# Create your tests here.\n","repo_name":"alehenaff/prodplanner","sub_path":"planner/tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"10114966211","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/1/15 10:05 AM\n# @Author : Insomnia\n# @Desc : 求数组中两个出现一次的数, 其他数出现两次\n# @File : SingleNumIII.py\n# @Software: PyCharm\n\nclass Solution:\n def singleNum(self, arr):\n xval = 0\n for val in arr:\n xval ^= val\n\n xval ^= xval & (xval - 1)\n\n res = [0] * 2\n for val in arr:\n if (xval & val) > 0:\n res[0] ^= val\n else:\n res[1] ^= val\n\n return res\n\nif __name__ == '__main__':\n arr = [1, 1, 2, 2, 3, 5, 5, 6]\n sol = Solution()\n print(sol.singleNum(arr))\n","repo_name":"Insofan/LeetCode","sub_path":"Python3/Offer/56/SingleNumIII.py","file_name":"SingleNumIII.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"4131201050","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Sep 9 13:36:48 2020\r\n\r\n@author: Casper Witlox (426233)\r\n\"\"\"\r\n\r\n\"perform assignment 2\"\r\nimport pandas as pd\r\nfrom sklearn.linear_model import Ridge\r\n\r\n#adjust data\r\ndf = pd.read_csv('trainingSet.csv')\r\noutcome = df[\"Outcome\"]\r\ndel df[\"Outcome\"]\r\nX = df\r\n\r\n#declare ridge variables\r\nlamba = 100\r\n\r\n\"develop prediction model using Ridge regression on diabetes\"\r\n#using ridge regression function\r\nrr = Ridge(lamba)\r\nrr.fit(X, outcome)\r\nw_ridge = rr.coef_\r\n\r\n","repo_name":"sm4machinelearning/hobby","sub_path":"Machine Learning in Finance/Week 2/assignment2_part1.py","file_name":"assignment2_part1.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"999188237","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport itertools\n\nfrom sklearn.manifold import TSNE\n\n\ndef plot_confusion(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap='coolwarm'):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n\ndef plot_tsne(df, labels, title=\"\"):\n \"\"\"\n Plot the t-SNE embedding\n \n Positional arguments:\n df - t-SNE fitted data\n labels - labels corresponding to df\n \"\"\"\n unique_labels = np.unique(labels)\n colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k', 'SaddleBrown', 'SlateGrey', 'DarkOrange']\n \n for i in range(len(unique_labels)):\n # Mask and filter the array\n m = labels==unique_labels[i]\n m_df = df[m]\n\n # Draw the points\n plt.scatter(m_df[:,0], m_df[:,1], label=unique_labels[i], alpha=0.5, color=colors[i], marker='.')\n \n plt.legend(ncol=2, scatterpoints=1)\n plt.xlabel(\"First Component\")\n plt.ylabel(\"Second Component\")\n plt.title(\"Data Projection into 2D Subspace - t-SNE{}\".format(title))\n","repo_name":"rtjfarrimond/hotel-review-embedding","sub_path":"plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"18810958802","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Aug 28 12:17:09 2018\r\n\r\n@author: jm2080\r\n\"\"\"\r\n\r\ndef folderwatch(directory, count):\r\n \"\"\"\r\n Creates a dictionary containing the contents of a chosen directory.\r\n If the directory is empty it checks every 'count' number seconds until something is added.\r\n\r\n Example:\r\n folderwatch(C:/Users/jm2080/Google Drive/TBAnalysed, 30)\r\n \"\"\"\r\n import os\r\n import time\r\n\r\n vidfiles = []\r\n while not vidfiles:\r\n print(\"Monitoring Folder\")\r\n time.sleep(count)\r\n for dirpath, dirnames, files in os.walk(directory):\r\n if not files:\r\n continue\r\n for name in files:\r\n if name.lower().endswith('.avi'):\r\n vidfiles.append(os.path.join(dirpath, name))\r\n return vidfiles\r\n","repo_name":"AndresenLab/otnp_3Dtrak","sub_path":"Folderwatch2.py","file_name":"Folderwatch2.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"17439763540","text":"import argparse\n\n\ndef main():\n data = open(args.big, \"r\").readlines()\n lines_num = len(data)\n div_num = lines_num // args.num\n for i in range(args.num):\n if i != args.num - 1:\n i_data = data[i * div_num:(i + 1) * div_num]\n else:\n i_data = data[i * div_num:]\n with open(f\"{args.small}{i}.txt\", \"w\") as w:\n for w_data in i_data:\n w.write(w_data)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--big\",\n default=\"/home/lidongwen/gpt3-dataset/txt/online/clue_oscar.txt\",\n type=str,\n required=False,\n help=\"data dir\",\n )\n parser.add_argument(\n \"--small\",\n default=\"/home/lidongwen/gpt3-dataset/txt/online/clue_oscar_\",\n type=str,\n required=False,\n help=\"dst json path\",\n )\n parser.add_argument(\n \"--num\",\n default=30,\n type=int,\n required=False,\n help=\"dead func\",\n )\n args = parser.parse_args()\n main()\n","repo_name":"NKCSICLab/nkcorpus","sub_path":"multilingual-coding/src/big2small.py","file_name":"big2small.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"19379675871","text":"from activity.models import Event\nfrom customers.models import Customer\nfrom datetime import datetime, timedelta\nfrom django.contrib.auth.models import User, Permission\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.management.base import BaseCommand\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.db import connection\nfrom django.db.models import F, Q\nfrom django.template import Context\nfrom django.template.loader import get_template\nfrom django.utils.dateformat import DateFormat\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n tenant = Customer.objects.filter(schema_name=connection.schema_name).first()\n if tenant.is_public_tenant():\n return\n ContentType.objects.clear_cache()\n\n # Get Daily Digest subscribers\n content_type = ContentType.objects.get_for_model(Event)\n perm = Permission.objects.get(content_type=content_type, codename='receive_daily_digest')\n recipients = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm)).distinct()\n\n dt = datetime.now()\n start_dt = dt-timedelta(days=1)\n plaintext = get_template('email/daily_digest_email.txt')\n htmly = get_template('email/daily_digest_email.html')\n checkin_type = ContentType.objects.get(model=\"checkin\")\n comment_type = ContentType.objects.get(model=\"comment\")\n employeezone_type = ContentType.objects.get(model=\"employeezone\")\n feedbackdigest_type = ContentType.objects.get(model=\"feedbackdigest\")\n\n for recipient in recipients:\n # Get past days worth of activity items subscriber is allowed to see\n events = Event.objects.get_events_for_all_employees(requester=recipient)\n events = events.exclude(event_type=employeezone_type,user__employee__id=F(\"employee__id\"))\n events = events.filter(date__range=[start_dt,dt])\n if events.count() > 0:\n df = DateFormat(dt)\n from_email = 'Scoutmap'\n subject = 'Daily Recap for ' + df.format('l, d F')\n date = df.format('l, d F')\n data = Context(\n {\n 'date': date,\n 'events': events,\n 'site': tenant.domain_url,\n 'checkin_type': checkin_type,\n 'comment_type': comment_type,\n 'employeezone_type': employeezone_type,\n 'feedbackdigest_type': feedbackdigest_type,\n 'recipient': recipient\n }\n )\n text_content = plaintext.render(data)\n html_content = htmly.render(data)\n msg = EmailMultiAlternatives(subject, text_content, from_email, [recipient.email])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n self.stdout.write('Successfully sent Daily Digest.')\n else:\n self.stdout.write('Daily Digest had no new events to send.')\n\n","repo_name":"predictable-success/predictable_success","sub_path":"activity/management/commands/send_daily_digest.py","file_name":"send_daily_digest.py","file_ext":"py","file_size_in_byte":3156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"14658497142","text":"import logging\nimport os\nimport time\nfrom collections import defaultdict\n\nimport gym\nimport gym.envs.atari\nimport numpy as np\nfrom gym import spaces\nfrom gym.spaces.box import Box\n\nimport cv2\nimport universe\n#import gym_ple\nfrom humanrl import pacman, pong_catastrophe\nfrom humanrl.catastrophe_wrapper import CatastropheWrapper\nfrom humanrl.classifier_tf import (SavedCatastropheBlockerTensorflow,\n SavedCatastropheClassifierTensorflow)\nfrom humanrl.exploration import ExplorationWrapper\nfrom humanrl.location_wrapper import LocationWrapper\nfrom humanrl.space_invaders import (SpaceInvadersMonitoringWrapper,\n SpaceInvadersStartsWrapper,\n SpaceInvadersStartsWrapper2)\nfrom humanrl.utils import ACTION_MEANING, ACTION_MEANING_TO_ACTION\nfrom universe import spaces as vnc_spaces\nfrom universe import vectorized\nfrom universe.spaces.vnc_event import keycode\nfrom universe.wrappers import (BlockingReset, EpisodeID, GymCoreAction, Logger,\n Unvectorize, Vectorize, Vision)\n\nos.environ['SDL_VIDEODRIVER'] = \"dummy\"\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nuniverse.configure_logging()\n\n\ndef add_diagnostics(env, *args, **kwargs):\n env = Vectorize(env)\n env = DiagnosticsInfo(env, *args, **kwargs)\n env = Unvectorize(env)\n return env\n\n\nclass FireProofWrapper(gym.Wrapper):\n def _step(self, action):\n if \"FIRE\" in ACTION_MEANING[action]:\n action = ACTION_MEANING_TO_ACTION[\"NOOP\"]\n obs, reward, done, info = self.env.step(action)\n return obs, reward, done, info\n\n\ndef create_env(env_id,\n client_id=None,\n remotes=None,\n explore=False,\n classifier_file=\"\",\n blocker_file=\"\",\n classifier_threshold=None,\n blocker_threshold=None,\n catastrophe_type=\"\",\n log_reward=False,\n no_jump=False,\n extra_wrapper=\"\",\n **kwargs):\n print('classifier_file, blocker_file, catastrophe_type: ', classifier_file, blocker_file,\n catastrophe_type)\n logger.info(str((classifier_file, blocker_file, catastrophe_type)))\n if env_id == \"Pong\":\n frame = ((34, 160 + 34), (0, 160), )\n if env_id == \"Montezuma\":\n env_id += \"Revenge\"\n frame = ((34, 160 + 34), (0, 160), )\n elif env_id == \"Pacman\":\n env = pacman.Pacman(**kwargs)\n return add_diagnostics(env)\n elif env_id == \"RoadRunner\":\n frame = ((40, 200), (0, 160), )\n elif env_id == \"Berzerk\":\n frame = ((0, 182), (0, 160), )\n elif env_id == \"SpaceInvaders\":\n frame = ((0, 200), (0, 160), )\n else:\n print(\"Unknown env id \" + env_id)\n\n env = make_env(env_id, **kwargs)\n\n if env_id == \"RoadRunner\":\n if no_jump:\n env._action_set = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n env.action_space = spaces.Discrete(len(env._action_set))\n env = FireProofWrapper(env)\n env = RoadRunnerLevelWrapper(env, **kwargs)\n\n if env_id == \"SpaceInvaders\":\n if extra_wrapper == \"SpaceInvadersStartsWrapper\":\n env = SpaceInvadersStartsWrapper(env)\n if extra_wrapper == \"SpaceInvadersStartsWrapper2\":\n env = SpaceInvadersStartsWrapper2(env)\n env = SpaceInvadersMonitoringWrapper(env)\n\n if catastrophe_type:\n classifier = None\n if classifier_file and not (isinstance(classifier_file, list) and\n len(classifier_file) == 1 and not classifier_file[0]):\n classifier = SavedCatastropheClassifierTensorflow(\n classifier_file, threshold=classifier_threshold)\n\n blocker = None\n if blocker_file and not (isinstance(blocker_file, list) and len(blocker_file) == 1 and\n not blocker_file[0]):\n blocker = SavedCatastropheBlockerTensorflow(\n blocker_file, env.action_space.n, threshold=blocker_threshold)\n classifier_baseline = None\n\n allowed_actions_heuristic = None\n safe_action_mapping = None\n if env_id == \"Pong\":\n if catastrophe_type == \"1\":\n classifier_baseline = pong_catastrophe.CatastropheClassifierHeuristic(**kwargs)\n location = \"bottom\"\n if \"location\" in kwargs:\n location = kwargs[\"location\"]\n allowed_actions_heuristic = lambda observation: pong_catastrophe.allowed_actions_heuristic(observation, location=location)\n if classifier is None:\n classifier = classifier_baseline\n if blocker is None:\n blocker = pong_catastrophe.CatastropheBlockerHeuristic(**kwargs)\n\n if env_id == \"RoadRunner\":\n if catastrophe_type == \"2\":\n allowed_actions_heuristic = lambda observation: [4] # Left\n\n if env_id == \"SpaceInvaders\":\n if catastrophe_type == \"1\":\n safe_action_mapping = \"SpaceInvaders\"\n\n env = CatastropheWrapper(\n env,\n classifier=classifier,\n blocker=blocker,\n classifier_baseline=classifier_baseline,\n allowed_actions_heuristic=allowed_actions_heuristic,\n safe_action_mapping=safe_action_mapping,\n **kwargs)\n\n if log_reward:\n env = LogReward(env)\n if explore:\n env = LocationWrapper(env)\n env = ExplorationWrapper(env, **kwargs)\n env = AtariEnvironment(env, frame_coordinates=frame, **kwargs)\n env = add_diagnostics(env, info_ignore_prefix=[\"ale.\"])\n env = LogActionFrequency(env)\n\n return env\n\n # spec = gym.spec(env_id)\n # atari = spec.tags.get('atari', False)\n #\n # if spec.tags.get('flashgames', False):\n # return create_flash_env(env_id, client_id, remotes, **kwargs)\n # elif atari and spec.tags.get('vnc', False):\n # return create_vncatari_env(env_id, client_id, remotes, **kwargs)\n # elif spec.tags.get('ple'):\n # return create_generic_env(env_id)\n # else:\n # # Assume atari.\n # assert \".\" not in env_id # universe environments have dots in names.\n #\n # return create_generic_env(env_id, atari=True)\n\n\ndef create_flash_env(env_id, client_id, remotes, **_):\n env = gym.make(env_id)\n env = Vision(env)\n env = Logger(env)\n env = BlockingReset(env)\n\n reg = universe.runtime_spec('flashgames').server_registry\n height = reg[env_id][\"height\"]\n width = reg[env_id][\"width\"]\n env = CropScreen(env, height, width, 84, 18)\n env = FlashRescale(env)\n\n keys = ['left', 'right', 'up', 'down', 'x']\n if env_id == 'flashgames.NeonRace-v0':\n # Better key space for this game.\n keys = ['left', 'right', 'up', 'left up', 'right up', 'down', 'up x']\n logger.info('create_flash_env(%s): keys=%s', env_id, keys)\n\n env = DiscreteToFixedKeysVNCActions(env, keys)\n env = EpisodeID(env)\n env = DiagnosticsInfo(env)\n env = Unvectorize(env)\n env.configure(\n fps=5.0,\n remotes=remotes,\n start_timeout=15 * 60,\n client_id=client_id,\n vnc_driver='go',\n vnc_kwargs={\n 'encoding': 'tight',\n 'compress_level': 0,\n 'fine_quality_level': 50,\n 'subsample_level': 3\n })\n return env\n\n\ndef create_vncatari_env(env_id, client_id, remotes, **_):\n env = gym.make(env_id)\n env = Vision(env)\n env = Logger(env)\n env = BlockingReset(env)\n env = GymCoreAction(env)\n env = AtariRescale42x42(env)\n env = EpisodeID(env)\n env = DiagnosticsInfo(env)\n env = Unvectorize(env)\n\n logger.info('Connecting to remotes: %s', remotes)\n fps = env.metadata['video.frames_per_second']\n env.configure(remotes=remotes, start_timeout=15 * 60, fps=fps, client_id=client_id)\n return env\n\n\ndef create_atari_env(env_id):\n return create_generic_env(env_id, atari=True)\n\n\ndef wrap_generic_env(env, atari=False):\n env = Vectorize(env)\n if atari:\n env = AtariRescale42x42(env)\n env = DiagnosticsInfo(env)\n env = Unvectorize(env)\n return env\n\n\ndef create_generic_env(env_id, atari=False):\n env = gym.make(env_id)\n env = Vectorize(env)\n if atari:\n env = AtariRescale42x42(env)\n env = DiagnosticsInfo(env)\n env = Unvectorize(env)\n return env\n\n\ndef DiagnosticsInfo(env, *args, **kwargs):\n return vectorized.VectorizeFilter(env, DiagnosticsInfoI, *args, **kwargs)\n\n\nclass DiagnosticsInfoI(vectorized.Filter):\n def __init__(self, log_interval=503, info_ignore_prefix=[]):\n super(DiagnosticsInfoI, self).__init__()\n\n self._episode_time = time.time()\n self._last_time = time.time()\n self._local_t = 0\n self._log_interval = log_interval\n self._episode_reward = 0\n self._real_episode_reward = 0\n self._episode_length = 0\n self._all_rewards = []\n self._num_vnc_updates = 0\n self._last_episode_id = -1\n self._info_ignore_prefix = info_ignore_prefix\n\n def _after_reset(self, observation):\n logger.info('Resetting environment')\n self._episode_reward = 0\n self._real_episode_reward = 0\n self._episode_length = 0\n self._all_rewards = []\n return observation\n\n def _after_step(self, observation, reward, done, info):\n to_log = {}\n if self._episode_length == 0:\n self._episode_time = time.time()\n\n self._local_t += 1\n if info.get(\"stats.vnc.updates.n\") is not None:\n self._num_vnc_updates += info.get(\"stats.vnc.updates.n\")\n\n if self._local_t % self._log_interval == 0:\n cur_time = time.time()\n elapsed = cur_time - self._last_time\n fps = self._log_interval / elapsed\n self._last_time = cur_time\n cur_episode_id = info.get('vectorized.episode_id', 0)\n to_log[\"diagnostics/fps\"] = fps\n if self._last_episode_id == cur_episode_id:\n to_log[\"diagnostics/fps_within_episode\"] = fps\n self._last_episode_id = cur_episode_id\n if info.get(\"stats.gauges.diagnostics.lag.action\") is not None:\n to_log[\"diagnostics/action_lag_lb\"] = info[\"stats.gauges.diagnostics.lag.action\"][0]\n to_log[\"diagnostics/action_lag_ub\"] = info[\"stats.gauges.diagnostics.lag.action\"][1]\n if info.get(\"reward.count\") is not None:\n to_log[\"diagnostics/reward_count\"] = info[\"reward.count\"]\n if info.get(\"stats.gauges.diagnostics.clock_skew\") is not None:\n to_log[\"diagnostics/clock_skew_lb\"] = info[\"stats.gauges.diagnostics.clock_skew\"][0]\n to_log[\"diagnostics/clock_skew_ub\"] = info[\"stats.gauges.diagnostics.clock_skew\"][1]\n if info.get(\"stats.gauges.diagnostics.lag.observation\") is not None:\n to_log[\"diagnostics/observation_lag_lb\"] = info[\n \"stats.gauges.diagnostics.lag.observation\"][0]\n to_log[\"diagnostics/observation_lag_ub\"] = info[\n \"stats.gauges.diagnostics.lag.observation\"][1]\n\n if info.get(\"stats.vnc.updates.n\") is not None:\n to_log[\"diagnostics/vnc_updates_n\"] = info[\"stats.vnc.updates.n\"]\n to_log[\"diagnostics/vnc_updates_n_ps\"] = self._num_vnc_updates / elapsed\n self._num_vnc_updates = 0\n if info.get(\"stats.vnc.updates.bytes\") is not None:\n to_log[\"diagnostics/vnc_updates_bytes\"] = info[\"stats.vnc.updates.bytes\"]\n if info.get(\"stats.vnc.updates.pixels\") is not None:\n to_log[\"diagnostics/vnc_updates_pixels\"] = info[\"stats.vnc.updates.pixels\"]\n if info.get(\"stats.vnc.updates.rectangles\") is not None:\n to_log[\"diagnostics/vnc_updates_rectangles\"] = info[\"stats.vnc.updates.rectangles\"]\n if info.get(\"env_status.state_id\") is not None:\n to_log[\"diagnostics/env_state_id\"] = info[\"env_status.state_id\"]\n\n for k, v in info.items():\n if not any([k.startswith(prefix) for prefix in self._info_ignore_prefix]):\n to_log[k] = v\n # if k.startswith(\"log/\") or k.startswith(\"frame/\"):\n # to_log[k] = v\n\n try:\n real_reward = info.pop(\"log/reward\")\n self._real_episode_reward += real_reward\n except KeyError:\n pass\n\n if reward is not None:\n self._episode_reward += reward\n if observation is not None:\n self._episode_length += 1\n self._all_rewards.append(reward)\n\n if done:\n logger.info('Episode terminating: episode_reward=%s episode_length=%s',\n self._episode_reward, self._episode_length)\n total_time = time.time() - self._episode_time\n to_log[\"global/episode_reward\"] = self._episode_reward\n to_log[\"global/real_episode_reward\"] = self._real_episode_reward\n to_log[\"global/episode_length\"] = self._episode_length\n to_log[\"global/reward_per_step\"] = self._episode_reward / self._episode_length\n to_log[\"global/episode_time\"] = total_time\n\n for key, value in info.items():\n if not any([key.startswith(prefix) for prefix in self._info_ignore_prefix]):\n to_log[key] = value\n\n # if key.startswith(\"global/\") or key.startswith(\"action_frequency/\"):\n # to_log[key] = value\n\n self._episode_reward = 0\n self._episode_length = 0\n self._all_rewards = []\n\n return observation, reward, done, to_log\n\n\ndef _process_frame42(frame):\n frame = frame[34:34 + 160, :160]\n # Resize by half, then down to 42x42 (essentially mipmapping). If\n # we resize directly we lose pixels that, when mapped to 42x42,\n # aren't close enough to the pixel boundary.\n frame = cv2.resize(frame, (80, 80))\n frame = cv2.resize(frame, (42, 42))\n frame = frame.mean(2)\n frame = frame.astype(np.float32)\n frame *= (1.0 / 255.0)\n frame = np.reshape(frame, [42, 42, 1])\n return frame\n\n\nclass AtariRescale42x42(vectorized.ObservationWrapper):\n def __init__(self, env=None):\n super(AtariRescale42x42, self).__init__(env)\n self.observation_space = Box(0.0, 1.0, [42, 42, 1])\n\n def _observation(self, observation_n):\n return [_process_frame42(observation) for observation in observation_n]\n\n\nclass FixedKeyState(object):\n def __init__(self, keys):\n self._keys = [keycode(key) for key in keys]\n self._down_keysyms = set()\n\n def apply_vnc_actions(self, vnc_actions):\n for event in vnc_actions:\n if isinstance(event, vnc_spaces.KeyEvent):\n if event.down:\n self._down_keysyms.add(event.key)\n else:\n self._down_keysyms.discard(event.key)\n\n def to_index(self):\n action_n = 0\n for key in self._down_keysyms:\n if key in self._keys:\n # If multiple keys are pressed, just use the first one\n action_n = self._keys.index(key) + 1\n break\n return action_n\n\n\nclass DiscreteToFixedKeysVNCActions(vectorized.ActionWrapper):\n \"\"\"\n Define a fixed action space. Action 0 is all keys up. Each element of keys can be a single key or a space-separated list of keys\n\n For example,\n e=DiscreteToFixedKeysVNCActions(e, ['left', 'right'])\n will have 3 actions: [none, left, right]\n\n You can define a state with more than one key down by separating with spaces. For example,\n e=DiscreteToFixedKeysVNCActions(e, ['left', 'right', 'space', 'left space', 'right space'])\n will have 6 actions: [none, left, right, space, left space, right space]\n \"\"\"\n\n def __init__(self, env, keys):\n super(DiscreteToFixedKeysVNCActions, self).__init__(env)\n\n self._keys = keys\n self._generate_actions()\n self.action_space = spaces.Discrete(len(self._actions))\n\n def _generate_actions(self):\n self._actions = []\n uniq_keys = set()\n for key in self._keys:\n for cur_key in key.split(' '):\n uniq_keys.add(cur_key)\n\n for key in [''] + self._keys:\n split_keys = key.split(' ')\n cur_action = []\n for cur_key in uniq_keys:\n cur_action.append(\n vnc_spaces.KeyEvent.by_name(cur_key, down=(cur_key in split_keys)))\n self._actions.append(cur_action)\n self.key_state = FixedKeyState(uniq_keys)\n\n def _action(self, action_n):\n # Each action might be a length-1 np.array. Cast to int to\n # avoid warnings.\n return [self._actions[int(action)] for action in action_n]\n\n\nclass CropScreen(vectorized.ObservationWrapper):\n \"\"\"Crops out a [height]x[width] area starting from (top,left) \"\"\"\n\n def __init__(self, env, height, width, top=0, left=0):\n super(CropScreen, self).__init__(env)\n self.height = height\n self.width = width\n self.top = top\n self.left = left\n self.observation_space = Box(0, 255, shape=(height, width, 3))\n\n def _observation(self, observation_n):\n return [\n ob[self.top:self.top + self.height, self.left:self.left + self.width, :]\n if ob is not None else None for ob in observation_n\n ]\n\n\ndef _process_frame_flash(frame):\n frame = cv2.resize(frame, (200, 128))\n frame = frame.mean(2).astype(np.float32)\n frame *= (1.0 / 255.0)\n frame = np.reshape(frame, [128, 200, 1])\n return frame\n\n\nclass FlashRescale(vectorized.ObservationWrapper):\n def __init__(self, env=None):\n super(FlashRescale, self).__init__(env)\n self.observation_space = Box(0.0, 1.0, [128, 200, 1])\n\n def _observation(self, observation_n):\n return [_process_frame_flash(observation) for observation in observation_n]\n\n\nclass RewardScale(gym.Wrapper):\n def __init__(self, env, scale):\n super(RewardScale, self).__init__(env)\n self.scale = scale\n\n def _step(self, action):\n obs, reward, done, info = self.env.step(action)\n reward *= self.scale\n return obs, reward, done, info\n\n\nclass LogReward(gym.Wrapper):\n def _step(self, action):\n obs, reward, done, info = self.env.step(action)\n info['log/reward'] = reward\n return obs, reward, done, info\n\n\nclass LogActionFrequency(gym.Wrapper):\n def __init__(self, env):\n super().__init__(env)\n self._action_set = None\n if isinstance(env.unwrapped, gym.envs.atari.atari_env.AtariEnv):\n self._action_set = env.unwrapped._action_set\n self.counts = defaultdict(lambda: 0)\n\n def _reset(self):\n obs = self.env.reset()\n self.counts = defaultdict(lambda: 0)\n return obs\n\n def _action_name(self, action):\n if self._action_set is not None:\n action = self._action_set[action]\n return gym.envs.atari.atari_env.ACTION_MEANING[action]\n\n def _step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.counts[action] += 1\n if done:\n s = sum(self.counts.values())\n for a, c in self.counts.items():\n info[\"action_frequency/{}\".format(self._action_name(a))] = float(c) / float(s)\n return obs, reward, done, info\n\n\ndef make_env(env_id, deterministic=True, v=3, **unused):\n if deterministic:\n env_id += \"Deterministic\"\n env_id += \"-v%d\" % v\n\n return gym.make(env_id)\n\n\nclass AtariEnvironment(gym.Wrapper):\n def __init__(self,\n env,\n frame_coordinates,\n reward_scale=1.0,\n death_penalty=0.0,\n squash_rewards=False,\n **_):\n super(AtariEnvironment, self).__init__(env)\n self.reward_scale = reward_scale\n self.frame_coordinates = frame_coordinates\n self.observation_space = gym.spaces.Box(0.0, 1.0, [42, 42, 1])\n self.death_penalty = death_penalty\n self.lives = None\n self.squash_rewards = squash_rewards\n\n def process_observation(self, obs):\n # return obs\n frame = obs.mean(2)\n (x1, x2), (y1, y2) = self.frame_coordinates\n frame = frame[x1:x2, y1:y2]\n frame = cv2.resize(frame, (80, 80))\n frame = cv2.resize(frame, (42, 42))\n frame = frame.astype(np.float32)\n frame *= (1.0 / 255.0)\n frame = np.reshape(frame, [42, 42, 1])\n return frame\n\n def _reset(self):\n obs = self.env.reset()\n self.lives = None\n return self.process_observation(obs)\n\n def _step(self, action):\n obs, reward, done, info = self.env.step(action)\n obs = self.process_observation(obs)\n\n if self.squash_rewards:\n reward = float(np.sign(reward))\n else:\n reward = float(reward) / float(self.reward_scale)\n\n info[\"frame/lives\"] = info[\"ale.lives\"]\n if self.lives is None:\n self.lives = info[\"ale.lives\"]\n else:\n current_lives = info[\"ale.lives\"]\n lost = self.lives - current_lives\n self.lives = current_lives\n if lost > 0:\n reward -= lost * self.death_penalty\n\n return obs, reward, done, info\n\n\nclass RoadRunnerLevelWrapper(gym.Wrapper):\n def __init__(self, env, lose_first_two_lives=False, max_level=None, **_):\n super().__init__(env)\n self.level = None\n self.in_level_transition = False\n self.higher_level_reward = 0\n self.higher_level_steps = 0\n self.level_1_lives_lost = 0\n self.lives = None\n self.lose_first_two_lives = lose_first_two_lives\n self.max_level = max_level\n\n def _reset(self):\n obs = self.env.reset()\n self.level = 1\n self.in_level_transition = False\n self.higher_level_reward = 0\n self.higher_level_steps = 0\n self.level_1_lives_lost = 0\n self.lives = None\n if self.lose_first_two_lives:\n while (self.lives != 1):\n self.step(0)\n return obs\n\n def _step(self, action):\n obs, reward, done, info = self.env.step(action)\n\n if self.lives is None:\n self.lives = info[\"ale.lives\"]\n else:\n current_lives = info[\"ale.lives\"]\n lost = self.lives - current_lives\n self.lives = current_lives\n if lost > 0 and self.level == 1:\n self.level_1_lives_lost += 1\n\n if np.mean(obs) < 10:\n if not self.in_level_transition:\n self.in_level_transition = True\n self.level += 1\n else:\n self.in_level_transition = False\n\n if self.level > 1:\n self.higher_level_reward += reward\n self.higher_level_steps += 1\n\n if self.max_level is not None and self.level > self.max_level:\n done = True\n\n info[\"frame/level\"] = self.level\n if done:\n info[\"global/higher_level_reward\"] = self.higher_level_reward\n info[\"global/higher_level_steps\"] = self.higher_level_steps\n info[\"global/level_1_lives_lost\"] = self.level_1_lives_lost\n\n return obs, reward, done, info\n","repo_name":"gsastry/human-rl","sub_path":"universe-starter-agent/envs.py","file_name":"envs.py","file_ext":"py","file_size_in_byte":23485,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"51"} +{"seq_id":"39118465515","text":"\"\"\"A setuptools based setup module.\n\nSee:\nhttps://packaging.python.org/guides/distributing-packages-using-setuptools/\nhttps://github.com/pypa/sampleproject\n\"\"\"\n\nfrom setuptools import setup, find_packages\nwith open(\"README.md\", encoding=\"utf8\") as f:\n long_description = f.read()\n\nsetup(\n name='package',\n version='0.1.0',\n description='',\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='',\n author='',\n author_email='',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n\n 'Intended Audience :: Education',\n 'Intended Audience :: Science/Research',\n\n 'Topic :: Education',\n 'Topic :: Scientific/Engineering',\n 'Topic :: Scientific/Engineering :: Physics',\n\n 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',\n\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n ],\n keywords='',\n packages=find_packages(),\n python_requires = '>=3.6, <3.9',\n install_requires=['numpy'],\n extras_require={\n 'dev': [],\n },\n package_data={\n },\n data_files=[\n ],\n entry_points={\n },\n project_urls={ \n 'Bug Reports': '',\n 'Source': '',\n 'Docs': '',\n },\n)","repo_name":"jpvantassel/py-template","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"5919357073","text":"import os\nimport time\n\nopcion = True\n## CONVIERTE NUMEROS A ENTERO O DECIMAL\ndef convertir_numeros():\n a = input(\"Ingrese nota: \")\n if \".\" in a:\n a = float(a)\n else:\n a = int(a)\n return a\n## MUESTRA LOS PRIMEROS 20 NUMEROS PARES\ndef contar_20_primeros_pares(numero):\n numero = 0\n lista_de_pares = []\n for n in range(0, 20):\n numero += 2\n lista_de_pares.append(numero)\n print(lista_de_pares)\n print(len(lista_de_pares))\n## PROMEDIA 3 NOTAS Y SI ES IGUAL O MAYOR A 4 APRUEBAS\ndef promedio_de_3_notas():\n n1 = convertir_numeros()\n n2 = convertir_numeros()\n n3 = convertir_numeros()\n print(\"Calculando.....\")\n time.sleep(2)\n total = n1 + n2 + n3\n promedio = total/3\n print(\"el promedio es: {} por lo cual\".format(promedio))\n if promedio >= 4:\n print(\"Su promedio es suficiente para aprobar\")\n else:\n print(\"Su promedio es insuficiente, tendra que rendir EXAMEN\")\n\n\ndef saludo():\n nombre = input(\"Ingresa tu nombre: \")\n apellido = input(\"Ingresa tu apellido: \")\n edad = int(input(\"Ingresa tu edad: \"))\n\n Saludo_v = (\"Hola me llamo {} {} y tengo {} años\".format(nombre,apellido,edad))\n return Saludo_v\n\nwhile opcion != False:\n seleccion = int(input(\"1.-20 primeros pares, 2.-promedio de 3 notas, 3.- Saludo\\n\"\n \"Elije una opcion: \"))\n if seleccion == 1:\n contar_20_primeros_pares(0)\n elif seleccion == 2:\n promedio_de_3_notas()\n elif seleccion == 3:\n print(saludo())\n opcion_repetir = input(\"Quieres usar otro codigo? S/N: \")\n if opcion_repetir.lower() == \"s\":\n print(\"Reiniciando...\")\n time.sleep(2)\n os.system(\"cls\")\n elif opcion_repetir.lower() == \"n\":\n print(\"Saliendo\")\n time.sleep(2)\n opcion = False\n else:\n print(\"La opcion no es valida, asi que me ire\")\n print(\"Saliendo.....\")\n time.sleep(2)\n exit()","repo_name":"ABZA-del/Trabajo-en-clases_3_en_1","sub_path":"Trabajo en clases 3 juntos.py","file_name":"Trabajo en clases 3 juntos.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"24718930365","text":"# Python3\n# utf-8\nimport configparser\nimport csv\nimport docx\n# --------------------------------------------------------\n# ▼仕様\n# ・CSVファイルに含まれる「見出し」「質問」「回答」を\n# Wordファイルに転記します。\n# ・CSVファイルは、当pyファイルと同一ディレクトリ内に存在すること、\n# パラメータ設定「config.ini」も同ディレクトリ内に存在すること、\n# Wordファイルも、同ディレクトリ内に作成or上書きされることを\n# 想���しています。\n# ・CSVファイル1行につき1つの質問、\n# 質問に対する回答は1〜n回分あることを想定しています。\n# ・Wordファイルに転記する回答は「最終回答」のみとします。\n# ・1見出し/質問/回答を出力後に改ページします。\n# ・「見出し」のスタイルはTitle固定、\n# 「質問」「回答」(小見出し)のスタイルはHeading 1固定、\n# 「質問」「回答」の内容自体はスタイル指定なしとします。\n# ・Title、Heading 1の書式はWord側で適宜編集してください。\n# ・config.iniにファイル名、列インデックスを指定してください。\n# --------------------------------------------------------\n# パラメータ設定(config.iniより取得)\nconfig = configparser.ConfigParser()\n\ntry:\n # configのファイルを開く\n config.read('config.ini')\n # セクションを取得\n file_section = config['FILE_NAME']\n index_section = config['COLUMN_INDEX']\n\n # パラメータの読み込み\n # 各ファイル名\n CSV_FILE_NAME = file_section.get('csv_file')\n DOCX_FILE_NAME = file_section.get('docx_file')\n\n # CSVから取り出したい文字列の列インデックス(0〜)\n TITLE_COLUMN_INDEX = int(index_section.get('title_column'))\n QUESTION_COLUMN_INDEX = int(index_section.get('question_column'))\n FIRST_ANSWER_COLUMN_INDEX = int(index_section.get('first_answer_column'))\n LAST_ANSWER_COLUMN_INDEX = int(index_section.get('last_answer_column'))\n\n# iniファイルオープン、セクション取得に失敗した場合\n# ※パラメータ読み込みチェックは実装していません。\nexcept:\n print(\"config.iniが存在しないか、config.ini内のパラメータが不正です。\")\n exit()\n\n# --------------------------------------------------------\n# Wordに転記する「最終回答」を対象行より取得するメソッド\ndef get_last_answer(row):\n # 回答列を1列のみパラメータ指定している場合、その回答を「最終回答」とする\n if FIRST_ANSWER_COLUMN_INDEX == LAST_ANSWER_COLUMN_INDEX:\n return row[FIRST_ANSWER_COLUMN_INDEX]\n\n # 回答を後ろから初回回答へ検索し、最初にヒットした回答を「最終回答」とする\n for i in range(LAST_ANSWER_COLUMN_INDEX, FIRST_ANSWER_COLUMN_INDEX, -1):\n if row[i] != \"\":\n return row[i]\n\n # 仮に全ての回答が空白だった場合、空白を返す\n return \"\"\n\n# --------------------------------------------------------\n# カレントディレクトリにあるCSVファイルオープン\ncsv_file = \\\n open(\"./\" + CSV_FILE_NAME, \"r\", encoding=\"utf_8\", errors=\"\", newline=\"\" )\n\n# Wordファイル新規作成\ndoc = docx.Document()\n\n# CSVファイル読み込み\ncsv_rows = \\\n csv.reader(csv_file, delimiter=\",\", doublequote=True, \\\n lineterminator=\"\\r\\n\", quotechar='\"', skipinitialspace=True)\n\n# 1行目のヘッダは読み飛ばし\nheader = next(csv_rows)\n\n# 2行目以降をWordファイルに転記\nfor row in csv_rows:\n # 見出し\n doc.add_heading(row[TITLE_COLUMN_INDEX], 0)\n # 質問\n doc.add_heading(\"質問\", 1)\n doc.add_paragraph(row[QUESTION_COLUMN_INDEX])\n doc.add_paragraph('\\n')\n # 回答(最終回答のみをセットする)\n doc.add_heading(\"回答\", 1)\n doc.add_paragraph(get_last_answer(row))\n # 改ページ\n doc.add_page_break()\n\n# Wordファイルをカレントディレクトリに保存\ndoc.save(DOCX_FILE_NAME)\n","repo_name":"ssyk442/study_memo","sub_path":"100_python_study/005_filetest/createdocx.py","file_name":"createdocx.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"6723626726","text":"from spotipy.oauth2 import SpotifyClientCredentials\nimport spotipy\nimport numpy as np\nfrom scipy.stats import norm\nimport json\n\n# recommends the next ten tracks\nNUM_TRACKS = 20\n\nwith open('api.json') as api:\n api_obj = json.loads(api.read())\n\napi_key = api_obj[\"api\"][\"key\"]\napi_secret = api_obj[\"api\"][\"secret\"]\n\n# initialize a single client\nclient_credentials = SpotifyClientCredentials(client_id=api_key, client_secret=api_secret)\nsp = spotipy.Spotify(client_credentials_manager=client_credentials)\n\n\ndef recommend(curr_rate, target_rate, seed_tracks, cutoffs):\n \"\"\"\n Generates a list of recommended songs.\n @param curr_rate: the current heart_rate\n @param target_rate: the projected target heart rate\n @param seed_tracks: the user-based seed tracks for each mode \n @param cutoffs: the cutoffs for the user, based on activity\n \"\"\"\n\n # The \"to\" probability value\n to_prob_val = dict((k, 0) for k in cutoffs.keys())\n\n # The \"from\" probability value\n from_prob_val = dict((k,0) for k in cutoffs.keys())\n\n # create a pseudoprobability value P(x, a) = N(x, a) / sum([N(x, b) for b in cutoffs])\n # Assume std of half of average difference between cutoffs\n avg_cutoffs = ((cutoffs[\"RUN\"] - cutoffs[\"WEIGHTS\"]) + (cutoffs[\"WEIGHTS\"] - cutoffs[\"POST_WORKOUT\"]) + (cutoffs[\"POST_WORKOUT\"] - cutoffs[\"RELAX\"])) / 3\n std = avg_cutoffs / 2\n for k in cutoffs.keys():\n mean = cutoffs[k]\n to_prob_val[k] = norm(mean, std).pdf(target_rate)\n from_prob_val[k] = norm(mean, std).pdf(curr_rate)\n \n # Now get the sum of all projected pseudoprobabilites in order to normalize to 1\n to_prob_tot = sum([i for i in to_prob_val.values()])\n from_prob_tot = sum([i for i in from_prob_val.values()])\n\n # normalize pseudoprobabilities\n to_prob_val = dict((k, v / to_prob_tot) for k, v in to_prob_val.items())\n from_prob_val = dict((k, v / from_prob_tot) for k, v in from_prob_val.items())\n\n # get the most probable from and to\n most_prob_to = max(to_prob_val, key=to_prob_val.get)\n most_prob_from = max(from_prob_val, key=from_prob_val.get)\n \n # now based on \"how far away\" the target is from the most prob centers, assign weights\n total_distance = (target_rate - cutoffs[most_prob_from]) + (target_rate - cutoffs[most_prob_to])\n weight_from = (target_rate - cutoffs[most_prob_from]) / total_distance\n weight_to = (target_rate - cutoffs[most_prob_to]) / total_distance\n\n # now to assign these weights in seed_tracks.\n # given seed tracks for from and to, take the minimum sized one as the seed base.\n # choose weight_from / seed_base tracks for from, weight_to / seed_base tracks for to\n\n seed_from = seed_tracks[most_prob_from]\n seed_to = seed_tracks[most_prob_to]\n seed_base = min(len(seed_from), len(seed_to))\n num_from_tracks = max(1, int(len(seed_from) * (weight_from / seed_base)))\n num_to_tracks = max(1, int(len(seed_to) * (weight_to / seed_base)))\n input_seed_tracks = list(set(list(np.random.choice(seed_from, num_from_tracks)) + list(np.random.choice(seed_to, num_to_tracks))))\n print(input_seed_tracks)\n\n # use the input seed tracks to get recommendations\n results = sp.recommendations(seed_tracks=input_seed_tracks)\n return results[\"tracks\"][:NUM_TRACKS]\n\n\n\nif __name__ == \"__main__\":\n # testing data\n\n curr_rate = 160\n target_rate = 130\n cutoffs = {\n \"RELAX\": 75,\n \"POST_WORKOUT\": 95,\n \"WEIGHTS\": 120,\n \"RUN\": 160\n }\n seed_tracks = {\n \"RELAX\": [\n \"spotify:track:4GKk1uNzpxIptBuaY97Dkj\",\n \"spotify:track:5M4yti0QxgqJieUYaEXcpw\",\n \"spotify:track:48ygvZn1YcxRP1gfHEDfsV\",\n \"spotify:track:7jnEVqyvscIaGLsJ8ezkEV\",\n \"spotify:track:6iZxpy5Z0BztLHsWE8cSzD\",\n ],\n \"POST_WORKOUT\": [\n \"spotify:track:2cnhi0n4UMWCXQIEaVjnm5\",\n \"spotify:track:5ANm5gWv5a65hjFAnDWMP3\",\n \"spotify:track:2gaZJDgE71VL9PzzUUlpMg\",\n \"spotify:track:3VdzKymHyCA7OQdUiDREKF\"\n ],\n \"WEIGHTS\": [\n \"spotify:track:4yGmiOowOj1ycFVd2E9Tj7\",\n \"spotify:track:2A49wpUOEgqWDWsE1qQ5Uv\",\n \"spotify:track:7ISL3LO8AWP3fKIXunvqTa\",\n \"spotify:track:1HhI5cx0VmyqclpbvYEwTV\"\n ],\n \"RUN\": [\n \"spotify:track:7vnYDHo16TCV9sE70zvB4b\",\n \"spotify:track:57bgtoPSgt236HzfBOd8kj\",\n \"spotify:track:57k0N16KmhOZVl5YFJebIw\",\n \"spotify:track:10s9tSE1e8RXSufhzw9Aw3\",\n \"spotify:track:39ZiU2QVBvDQzeepJjg8tp\",\n \"spotify:track:78lgmZwycJ3nzsdgmPPGNx\",\n \"spotify:track:2KHRENHQzTIQ001nlP9Gdc\"\n ]\n }\n\n results = recommend(curr_rate, target_rate, seed_tracks, cutoffs)\n for r in results:\n print(r[\"name\"])","repo_name":"Skeletrox/musiquity","sub_path":"web_api/daemons/music_recommender.py","file_name":"music_recommender.py","file_ext":"py","file_size_in_byte":4828,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"25319518714","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Created on Tue Apr 22 07:14:05 2014\n# License is MIT, see COPYING.txt for more details.\n# @author: Danilo de Jesus da Silva Bellini\n\nfrom fractal import Point, exec_command\ntry:\n from collections import OrderedDict\nexcept ImportError: # Python 2.6\n from ordereddict import OrderedDict\n\n# String formatting functions\nPoint.__str__ = lambda self: \"x\".join(map(str, self))\nbasic_str = lambda el: str(el).lstrip(\"(\").rstrip(\")\") # Complex or model name\nitem_str = lambda k, v: (basic_str(v) if k in [\"model\", \"c\"] else\n \"{}={}\".format(k, v))\nfilename = lambda kwargs: \"_\".join(item_str(*pair) for pair in kwargs.items())\n\n# Example list\nkwargs_list = [\n OrderedDict([(\"model\", \"julia\"),\n (\"c\", -.7102+.2698j),\n (\"size\", Point(500, 300)),\n (\"depth\", 512),\n (\"zoom\", .65),\n ]),\n OrderedDict([(\"model\", \"julia\"),\n (\"c\", -1.037+.17j),\n (\"size\", Point(600, 300)),\n (\"depth\", 40),\n (\"zoom\", .55),\n ]),\n OrderedDict([(\"model\", \"julia\"),\n (\"c\", -.644),\n (\"size\", Point(300, 200)),\n (\"depth\", 25),\n (\"zoom\", .6),\n ]),\n OrderedDict([(\"model\", \"julia\"),\n (\"c\", -.7+.27015j),\n (\"size\", Point(500, 300)),\n (\"depth\", 512),\n (\"zoom\", .6),\n ]),\n OrderedDict([(\"model\", \"julia\"),\n (\"c\", -.8+.156j),\n (\"size\", Point(500, 300)),\n (\"depth\", 512),\n (\"zoom\", .6),\n ]),\n OrderedDict([(\"model\", \"julia\"),\n (\"c\", -.8+.156j),\n (\"size\", Point(400, 230)),\n (\"depth\", 50),\n (\"zoom\", .65),\n ]),\n OrderedDict([(\"model\", \"julia\"),\n (\"c\", -.77777-.25j),\n (\"size\", Point(527, 331)),\n (\"depth\", 200),\n (\"zoom\", .7),\n ]),\n OrderedDict([(\"model\", \"mandelbrot\"),\n (\"size\", Point(500, 500)),\n (\"depth\", 80),\n (\"zoom\", .8),\n (\"center\", Point(-.75, 0)),\n ]),\n OrderedDict([(\"model\", \"mandelbrot\"),\n (\"size\", Point(300, 300)),\n (\"depth\", 80),\n (\"zoom\", 1.2),\n (\"center\", Point(-1, 0)),\n ]),\n OrderedDict([(\"model\", \"mandelbrot\"),\n (\"size\", Point(400, 300)),\n (\"depth\", 80),\n (\"zoom\", 2),\n (\"center\", Point(-1, 0)),\n ]),\n OrderedDict([(\"model\", \"mandelbrot\"),\n (\"size\", Point(500, 500)),\n (\"depth\", 256),\n (\"zoom\", 6.5),\n (\"center\", Point(-1.2, .35)),\n ]),\n OrderedDict([(\"model\", \"mandelbrot\"),\n (\"size\", Point(600, 600)),\n (\"depth\", 256),\n (\"zoom\", 90),\n (\"center\", Point(-1.255, .38)),\n ]),\n]\n\n# Creates all examples\nif __name__ == \"__main__\":\n for kwargs in kwargs_list:\n kwargs[\"output\"] = \"images/{}.png\".format(filename(kwargs))\n #kwargs[\"show\"] = True\n exec_command(kwargs)\n","repo_name":"danilobellini/fractal","sub_path":"generate_examples.py","file_name":"generate_examples.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"51"} +{"seq_id":"16497044891","text":"\"\"\"@package docstring\n\nFile: netscape_bookmark_tool.py\n \nhttps://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa753582(v=vs.85)\n\n\"\"\"\nimport argparse\nimport os\nimport pdb\nimport lxml.html\nimport csv\nimport datetime\nimport requests\n\n# locals\nimport icon_exporter\nimport link_exporter\n\n\ndef get_timestamp_from_epoch(epoch: str) -> str:\n \n return datetime.datetime.fromtimestamp(int(epoch)).strftime(\"%Y%m%d%H%M\")\n\n\ndef parse_bookmarks_export(bookmark_export_filename: str):\n\n # all_bookmarks_links = list()\n\n all_bookmarks = list()\n\n html_doc_root = lxml.html.parse(bookmark_export_filename).getroot()\n\n icons_export_folder_name = icon_exporter.generate_icons_folder_name(\n argparse_args.input_bookmark_file)\n os.makedirs(icons_export_folder_name)\n\n num_bookmarks_found = 0\n num_icons_exported = 0\n\n for bookmark_elem in html_doc_root.iter('a'):\n\n bookmark_obj = dict.fromkeys([\"bookmark_name\", \"bookmark_url\", \"bookmark_icon_filename\",\n \"bookmark_date_created_epoch\", \"bookmark_date_created_timestamp\", \"is_accessible\"])\n\n num_bookmarks_found += 1\n\n # Initialize name\n bookmark_obj[\"bookmark_name\"] = bookmark_elem.text\n\n # Initialize URL\n bookmark_link = bookmark_elem.attrib['href']\n bookmark_obj['bookmark_url'] = bookmark_link\n\n # Check if the URL is accessible by trying to access it\n is_url_accessible = True\n try:\n # print(f\"[DEBUG] Checking validity of URL: {bookmark_link}\")\n is_url_accessible = requests.get(\n bookmark_link, timeout=5, verify=False).ok\n\n except:\n is_url_accessible = False\n\n bookmark_obj[\"is_accessible\"] = is_url_accessible\n\n bookmark_added_epoch = bookmark_elem.attrib[\"add_date\"]\n bookmark_obj[\"bookmark_date_created_epoch\"] = bookmark_added_epoch\n\n bookmark_added_date = get_timestamp_from_epoch(bookmark_added_epoch)\n bookmark_obj[\"bookmark_date_created_timestamp\"] = datetime.datetime.fromtimestamp(\n int(bookmark_added_epoch)).strftime('%c')\n\n icon_image_data_key = \"icon\"\n\n if icon_image_data_key not in bookmark_elem.attrib:\n print(\"[WARNING] Bookmark found with no icon\")\n continue\n\n icon_image_data = bookmark_elem.attrib[icon_image_data_key]\n\n icon_image_filename = \"\"\n\n if bookmark_elem.text is not None:\n icon_image_filename = icon_exporter.extract_bookmark_icon(\n icons_export_folder_name, (bookmark_added_date + \"__\" + bookmark_elem.text), icon_image_data)\n\n else:\n icon_image_filename = icon_exporter.extract_bookmark_icon(\n icons_export_folder_name, (bookmark_added_date + \"__\" + bookmark_link), icon_image_data)\n\n bookmark_obj[\"bookmark_icon_filename\"] = icon_image_filename\n num_icons_exported += 1\n\n all_bookmarks.append(bookmark_obj)\n\n link_exporter.write_bookmark_links_to_file(\n [bookmark[\"bookmark_url\"] for bookmark in all_bookmarks], \"bookmark_links.txt\")\n\n with open(\"all_bookmarks.csv\", 'w') as csv_file:\n\n csv_writer = csv.writer(csv_file)\n\n # Header columns\n csv_writer.writerow(all_bookmarks[0].keys())\n\n for bookmark in sorted(all_bookmarks, key=lambda k: k[\"bookmark_date_created_epoch\"]):\n csv_writer.writerow(list(bookmark.values()))\n\n print(\"==========FINISHED==========\")\n print(\n f\"Exported {num_bookmarks_found} bookmarks, with {num_icons_exported} icons\")\n\n\nif __name__ == \"__main__\":\n argparse_parser = argparse.ArgumentParser()\n\n argparse_parser.add_argument(\"-f\", \"--input-bookmark-file\", type=str,\n help=\"The full path to the Netscape format bookmark file\", required=True)\n\n argparse_args = argparse_parser.parse_args()\n\n parse_bookmarks_export(argparse_args.input_bookmark_file)\n","repo_name":"raleighlittles/Netscape-Bookmark-Tool","sub_path":"netscape_bookmark_tool.py","file_name":"netscape_bookmark_tool.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"43819972150","text":"\"\"\"Base settings file; used by manage.py. All settings can be overridden via\nlocal_settings.py\"\"\"\nimport logging\nimport os\n\nfrom django.utils.crypto import get_random_string\n\n# Stop South from spitting out debug messages during tests\nlogging.getLogger('south').setLevel(logging.CRITICAL)\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'ideatest',\n 'USER': 'root',\n 'PASSWORD': '',\n 'HOST': '', # Set to empty string for localhost\n 'PORT': '', # Set to empty string for default\n },\n}\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = True\n\nSITE_ID = 1\n\nTEMPLATE_DIRS = (\n './templates',\n)\n\nINSTALLED_APPS = [\n 'idea',\n 'south',\n 'django.contrib.auth',\n 'django.contrib.admin',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.comments',\n 'django.contrib.staticfiles',\n 'mptt',\n 'core.custom_comments', # from Collab\n 'core.taggit',\n]\n\nROOT_URLCONF = 'idea.example_urls'\n\nDEBUG = True\nSTATIC_URL = '/static/'\n\nSECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', get_random_string(50))\n\nSOUTH_MIGRATION_MODULES = {\n 'taggit': 'taggit.south_migrations',\n}\n\nCOMMENTS_APP = 'core.custom_comments'\n\ntry:\n from local_settings import *\nexcept ImportError:\n pass\n","repo_name":"cfpb/idea-box","sub_path":"idea/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":152,"dataset":"github-code","pt":"51"} +{"seq_id":"70191735838","text":"def error_response(ex, code=400):\n return {'error': str(ex)}, code\n\n\ndef for_presentation(path, base):\n return {\n 'path': path,\n 'url': f'{base}{path}',\n }\n\n\ndef boolean(v):\n return v.lower() not in ('false', 'f', 'no', 'n', '0')\n\nclass InvalidParam(ValueError): pass\n\ndef address_list(v):\n if not v:\n raise InvalidParam('list cannot be empty')\n addresses = v.split(',')\n if any(not a for a in addresses):\n raise InvalidParam('addresses cannot be empty')\n return addresses\n\n\ndef validate_input(args, **schema):\n params = {}\n for key, meta in schema.items():\n default = meta['default']\n call = meta['type']\n\n try:\n val = args[key]\n except KeyError:\n params[key] = default\n continue\n\n try:\n val = call(val)\n except InvalidParam as e:\n raise ValueError(f\"'{key}' param invalid: {e}\")\n except ValueError:\n raise ValueError(\n f\"'{key}' param expects {call.__name__}, not '{val}'\"\n )\n\n try:\n values = meta['values']\n if val not in values:\n raise ValueError(\n f\"'{key}' must be one of {values}, not '{val}'\"\n )\n except KeyError:\n pass\n\n params[key] = val\n return params\n","repo_name":"bieron/tailog","sub_path":"app/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"30667042345","text":"from pico2d import *\nfrom mario import Mario\nfrom Mob import Mob\nimport Framework\nimport life_state\nimport select_state\n\nfrom frac import Frac\nfrom Item import Item\nimport math\nimport copy\n\n\nBLOCK_TYPES = 8\nMOB_TYPES = 2\nITEM_TYPES = 4\nMW, MH = 1024, 768\n\nbimglist = None\nmimglist = None\niimglist = None\nTilelist = None\nmap_bg = None\nfimg = None\nfbimg = None\ngimg = None\ncamPos = None\nbackPos = None\nfraclist = None\nchr = None\nisRight = None\nisLeft = None\nisLeftMove = None\nTilelist = None\nItemlist_ = None\nMoblist_ = None\nitmpdata = None\ngoalp = ( 1024, 0 )\nbgm = None\nclearbgm = None\ncnimg = None\nlnimg = None\nnimg = None\ndef init():\n if(Framework.selectStage == 0):\n from maptile1 import Mapset\n from maptile1 import Moblist\n from maptile1 import Itemlist\n from maptile1 import goal\n if(Framework.selectStage == 1):\n from maptile2 import Mapset\n from maptile2 import Moblist\n from maptile2 import Itemlist\n from maptile2 import goal\n if(Framework.selectStage == 2):\n from maptile3 import Mapset\n from maptile3 import Moblist\n from maptile3 import Itemlist\n from maptile3 import goal\n if(Framework.selectStage == 3):\n from maptile4 import Mapset\n from maptile4 import Moblist\n from maptile4 import Itemlist\n from maptile4 import goal\n if(Framework.selectStage == 4):\n from maptile5 import Mapset\n from maptile5 import Moblist\n from maptile5 import Itemlist\n from maptile5 import goal\n print(\"Init\")\n global mimglist\n global bimglist\n global map_bg\n global fimg\n global fbimg\n global fraclist\n global camPos\n global backPos\n global chr\n global isRight\n global isLeft\n global isLeftMove\n global Tilelist\n global Moblist_\n global Itemlist_\n global iimglist\n global goalp\n global gimg\n global bgm\n global clearbgm\n global cnimg\n global lnimg\n global nimg\n Tilelist = copy.deepcopy(Mapset)\n Moblist_ = copy.deepcopy(Moblist)\n Itemlist_ = Itemlist\n map_bg = load_image('./img/bg.jpg')\n fimg = load_image('./img/frac.png')\n fbimg = load_image('./img/fireball.png')\n gimg = load_image('./img/goal.png')\n cnimg = load_image('./img/coinnum.png')\n lnimg = load_image('./img/lifenum.png')\n nimg = load_image('./img/num.png')\n bimglist = []\n fraclist = []\n mimglist = []\n iimglist = []\n for i in range(BLOCK_TYPES):\n bimglist.append(load_image(\"./img/b%d.png\" % i))\n for i in range(MOB_TYPES):\n mimglist.append(load_image(\"./img/m%d.png\" % i))\n for i in range(ITEM_TYPES):\n iimglist.append(load_image(\"./img/i%d.png\" % i))\n camPos = 0\n backPos = 0\n\n bgm = load_music('./sound/bgm.mp3')\n clearbgm = load_music('./sound/round_clear.wav')\n bgm.repeat_play()\n\n goalp = goal\n chr = Mario()\n isRight = False\n isLeft = False\n isLeftMove = False\n\n\ndef exit():\n print(\"main exit\")\n global mimglist\n global bimglist\n global map_bg\n global fimg\n global fraclist\n global camPos\n global backPos\n global chr\n global isRight\n global isLeft\n global isLeftMove\n global Tilelist\n global Moblist_\n global Itemlist_\n global fbimg\n global goalp\n del(mimglist)\n del(bimglist)\n del(map_bg)\n del(fimg)\n del(fraclist)\n del(camPos)\n del(chr)\n del(isRight)\n del(isLeft)\n del(isLeftMove)\n del(fbimg)\n del(goalp)\n Tilelist = None\n Moblist_ = None\n Itemlist_ = None\n\n \n\ndef handle_events():\n global running \n global isRight\n global isLeft\n global isLeftMove\n global Moblist_\n events = get_events()\n for event in events:\n if event.type == SDL_MOUSEMOTION:\n pass\n if event.type == SDL_KEYDOWN:\n if event.key == SDLK_RIGHT:\n isRight = True\n isLeftMove = False\n if event.key == SDLK_LEFT:\n isLeft = True\n isLeftMove = True\n if event.key == SDLK_UP:\n chr.chuplook(1)\n if event.key == SDLK_DOWN:\n chr.chuplook(2)\n if event.key == SDLK_SPACE and chr.isjump == False:\n chr.jump(10)\n if event.key == SDLK_a:\n #chr.eat_Mushroom()\n chr.launchFb()\n pass\n if event.key == SDLK_b:\n chr.rtxy()\n for i in range(len(Moblist_)):\n Moblist_[i].rtxy()\n if event.key == SDLK_ESCAPE:\n bgm.stop()\n Framework.chstate(select_state)\n if event.type == SDL_KEYUP:\n if event.key == SDLK_RIGHT:\n isRight = False \n if event.key == SDLK_LEFT:\n isLeft = False\n if event.key == SDLK_UP:\n chr.chuplook(0)\n chr.resetMotion()\n if event.key == SDLK_DOWN:\n chr.chuplook(0)\n chr.resetMotion()\n elif event.key == SDLK_RIGHT or event.key == SDLK_LEFT:\n chr.setfric()\n if event.type == SDL_QUIT:\n quit()\n\ndef draw():\n clear_canvas()\n map_bg.draw(MW // 2 - backPos, MH // 2)\n map_bg.draw(MW // 2 - backPos + MW, MH // 2)\n draw_tileset()\n\n draw_mob()\n draw_item()\n draw_fb()\n chr.draw()\n\n cnimg.draw(800, 720)\n lnimg.draw(100, 720)\n nimg.clip_draw(Framework.life * 16, 0, 16, 32, 200, 720)\n if(Framework.score>9):\n nimg.clip_draw((Framework.score // 10) * 16, 0, 16, 32, 900, 720)\n nimg.clip_draw((Framework.score % 10) * 16, 0, 16, 32, 916, 720)\n gimg.draw_to_origin(goalp[0] * 32 - camPos, goalp[1] * 32 - 32)\n update_canvas()\n chr.delayCheck()\n\n\ndef draw_mob():\n for i in range(len(Moblist_)):\n if Moblist_[i].xsp > 0:\n mimglist[Moblist_[i].type].clip_draw(Moblist_[i].motion * 32, 0, 32, Moblist_[i].height, Moblist_[i].xpos+16-camPos, Moblist_[i].ypos+Moblist_[i].height/2)\n elif Moblist_[i].xsp < 0:\n mimglist[Moblist_[i].type].clip_composite_draw(Moblist_[i].motion * 32, 0, 32, Moblist_[i].height, 0, 'h', Moblist_[i].xpos+16-camPos, Moblist_[i].ypos+Moblist_[i].height/2, Moblist_[i].width, Moblist_[i].height)\n #draw_rectangle(Moblist_[i].xpos - camPos, Moblist_[i].ypos, Moblist_[i].xpos - camPos + 32, Moblist_[i].ypos + Moblist_[i].height)\n\ndef draw_item():\n for i in range(len(Itemlist_)):\n iimglist[Itemlist_[i].type].clip_draw(Itemlist_[i].motion * 32, 0, 32, 32, Itemlist_[i].xpos+16-camPos, Itemlist_[i].ypos+Itemlist_[i].height/2)\n #draw_rectangle(Itemlist_[i].xpos - camPos, Itemlist_[i].ypos, Itemlist_[i].xpos - camPos + 32, Itemlist_[i].ypos + Itemlist_[i].height)\n\n\ndef draw_tileset():\n global camPos\n global fimg\n for i in range(len(Tilelist)):\n if Tilelist[i].hbright - camPos >= 0 and Tilelist[i].hbleft - camPos <= MW:\n if Tilelist[i].dl == True:\n draw_frac(Tilelist[i])\n del Tilelist[i]\n break\n for i in range(len(Tilelist)):\n if Tilelist[i].hbright - camPos >= 0 and Tilelist[i].hbleft - camPos <= MW:\n \n Tilelist[i].ani()\n bimglist[Tilelist[i].sptype].clip_draw(Tilelist[i].frame * 32, 0, 32, 32, Tilelist[i].hbleft + 16 - camPos, Tilelist[i].hbdown + 16)\n\n if len(fraclist) > 0: # 조각 그리기\n for i in range(len(fraclist)): \n if fraclist[i].y < -16:\n del fraclist[i]\n return\n x, y = fraclist[i].rtxy()\n fimg.draw(x - camPos, y)\n \n \n\ndef draw_frac(t):\n global fraclist\n cx = t.hbleft + 16\n cy = t.hbup + 16\n\n fraclist.append(Frac(cx, cy, -2, 1))\n fraclist.append(Frac(cx, cy, -2, 2))\n fraclist.append(Frac(cx, cy, 2, 1))\n fraclist.append(Frac(cx, cy, 2, 2))\n\ndef draw_fb():\n global fbimg\n\n fblist = chr.drFb()\n for i in range(len(fblist)):\n fbimg.draw(fblist[i].xpos- camPos, fblist[i].ypos)\n\n\ndef update():\n if chr.dead_check() == True:\n life_state.state_type = 0\n Framework.chstate(life_state)\n return\n global camPos\n camPos = chr.rtView()\n\n for i in range(len(Moblist_)):\n Moblist_[i].camPos = camPos\n if isRight == True and isLeft == True:\n pass\n elif isRight == True:\n chr.xyrun(0, 3) \n elif isLeft == True:\n chr.xyrun(0, -3)\n else:\n chr.xyrun(0,0)\n\n if chr.xpos + chr.width > goalp[0] * 32 and chr.xpos < goalp[0] * 32 + 47 and chr.ypos + chr.height > goalp[1] * 32 + 64 and chr.ypos < goalp[1] * 32 + 64 and chr.isDeadAni == False:\n bgm.stop()\n clearbgm.play()\n print(chr.xpos , goalp[0] * 32)\n life_state.state_type = 1\n if(life_state.stage < Framework.selectStage):\n life_state.stage = Framework.selectStage+1\n Framework.chstate(life_state)\n \n return \n\n backPos = camPos\n backPos %= MW\n\n for i in range(len(fraclist)): \n fraclist[i].upd()\n #chr.xyrun(0,0)\n if chr.isMushAni == True:\n chr.mush_Ani()\n elif chr.isDeadAni == True:\n bgm.stop()\n chr.dead_Ani()\n elif chr.isFireAni == True:\n chr.fire_Ani()\n else: \n chr.motionUpdate(Tilelist)\n for i in range(len(Moblist_)):\n Moblist_[i].motionUpdate(Tilelist) # 몹 업데이트\n\n for i in range(len(Itemlist_)):\n Itemlist_[i].motionUpdate(Tilelist) # 아이템 업데이트\n\n for i in range(len(chr.firelist)):\n chr.firelist[i].motionUpdate(Tilelist) # 불 업데이트\n chr.firelist[i].CollideMob(Moblist_) # 불 몹충돌\n \n for i in range(len(chr.firelist)): \n if(chr.firelist[i].dl == True):\n del(chr.firelist[i])\n return\n\n chr.CollideMob(Moblist_) # 몹충돌 검사\n result = chr.CollideItem(Itemlist_) # 아이템 충돌 검사\n if(result!=0):\n chr.eat_Item(result)\n hitItem = chr.popItems()\n if(hitItem != None):\n if hitItem[2] == 0:\n Itemlist_.append(Item(hitItem[0], hitItem[1], 5)) # 튀어나오는 버섯\n else:\n Itemlist_.append(Item(hitItem[0], hitItem[1], 2)) # 꽃\n chr.itmpdata = None\n\n\n \n\n \n#close_canvas()\n","repo_name":"grjsm99/Mario_Project","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"4211866080","text":"# Program is to calculate the number of days between given date string and the present day.\n# Installed Module : pytz\n# pip install pytz\n\nimport datetime\nimport pytz\n\n\ndef str_to_datetime(ts):\n fmt = '%Y-%m-%d %H:%M:00'\n return datetime.datetime.strptime(ts, fmt)\n\n\ndef time_now():\n now_utc = datetime.datetime.utcnow()\n local_tz = pytz.timezone('Asia/Kolkata') # Local timezone which we want to convert the UTC time\n now_utc = pytz.utc.localize(now_utc) # Add timezone information to UTC time\n x = now_utc.astimezone(local_tz) # Convert to local time\n timestamp_in_str = x.strftime('%Y-%m-%d %H:%M:00')\n timestamp_in_datetime = datetime.datetime.strptime(timestamp_in_str, '%Y-%m-%d %H:%M:00')\n return timestamp_in_datetime\n\n\n\nif __name__ == \"__main__\":\n rt = '2022-02-28 00:05:00'\n tday = time_now()\n rt_dts = str_to_datetime(rt)\n t1 = tday-rt_dts\n print(t1.days)\n","repo_name":"BalaNagendraReddy/Python_Codes","sub_path":"days_diff.py","file_name":"days_diff.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"38546151747","text":"'''\nCreated on Feb 4, 2013\n\n@author: GoldRatio\n'''\nfrom model.topic import Message, Comment\nfrom model.operation import Operation\nfrom model.attachment import Attachment\nfrom model.project import Project\nimport logging\nimport tornado\nfrom tornado.options import options\nfrom tornado.web import RequestHandler\nfrom core.BaseHandler import BaseHandler \nfrom forms import Form, TextField, ListField\nfrom datetime import datetime\nfrom core.database import db\nfrom core.html2text import html2text\nfrom websocket.urls import send_message\nimport pysolr\nimport core.web\n\n\nclass MessageForm(Form):\n title = TextField('title')\n content = TextField('content')\n attachment = ListField('attachment')\n attachmentDel = ListField('attachmentDel')\n\nclass CommentForm(Form):\n content = TextField('content')\n attachment = ListField('attachment')\n attachmentDel = ListField('attachmentDel')\n\n\nclass MessageHandler(BaseHandler):\n _error_message = \"email or password incorrect!\"\n @tornado.web.authenticated\n def get(self, teamId, projectId):\n project = Project.query.filter_by(id=projectId).first()\n self.render(\"topic/messages.html\", project= project, teamId= teamId)\n\n @tornado.web.authenticated\n def post(self, teamId, projectId):\n form = MessageForm(self.request.arguments, locale_code=self.locale.code)\n if form.validate():\n currentUser = self.current_user\n teamId = currentUser.teamId\n now = datetime.now()\n allDigest = html2text(form.content.data)\n digest = allDigest[:100]\n\n message = Message(title=form.title.data, content=form.content.data, \n own_id=currentUser.id, project_id= projectId, team_id=teamId, comment_digest= digest, attachments=[])\n\n for attachment in form.attachment.data:\n attachment = Attachment.query.filter_by(url=attachment).first()\n if attachment is not None:\n message.attachments.append(attachment)\n\n try:\n db.session.add(message)\n db.session.flush()\n messageId = message.id\n\n url = \"/project/%s/message/%d\"%(projectId, message.id)\n operation = Operation(own_id = currentUser.id, createTime= now, operation_type=1, target_type=1,\n target_id=messageId, title= message.title, team_id= teamId, project_id= projectId, url= url)\n db.session.add(operation)\n\n project = Project.query.filter_by(id=projectId).with_lockmode(\"update\").first()\n project.discussionNum = project.discussionNum + 1\n \n db.session.add(project)\n\n db.session.commit()\n except:\n db.session.rollback()\n raise\n\n try:\n documentId = 'message%d'%messageId\n documentTitle = form.title.data\n solr = pysolr.Solr(options.solr_url, timeout=10)\n solr.add([{'id': documentId ,\n 'title': documentTitle,\n 'type': 'message',\n 'timestamp': now.strftime(\"%Y-%m-%dT%H:%M:%SZ\"),\n 'text': allDigest\n }]\n )\n '''\n solr = Solr(base_url=options.solr_url)\n document = [{'id': documentId ,\n 'title': documentTitle,\n 'type': 'message',\n 'timestamp': now.strftime(\"%Y-%m-%dT%H:%M:%SZ\"),\n 'text': allDigest\n }]\n solr.update(document, 'json', commit=False)\n solr.commit()\n '''\n except:\n pass\n\n print(teamId)\n print(projectId)\n\n \n self.writeSuccessResult(message, successUrl='/%s/project/%s/message/%d'%(teamId, projectId, message.id))\n\n\nclass NewMessageHandler(BaseHandler):\n @tornado.web.authenticated\n def get(self, teamId, projectId):\n project = Project.query.filter_by(id=projectId).first()\n self.render(\"topic/newMessage.html\", project= project, teamId = teamId)\n\nclass MessageDetailHandler(BaseHandler):\n @tornado.web.authenticated\n @core.web.authenticatedProject\n def get(self, teamId, projectId, messageId):\n project = Project.query.filter_by(id=projectId).first()\n message = Message.query.filter_by(id=messageId).first()\n currentUser = self.current_user\n self.render(\"topic/messageDetail.html\", project= project, message= message, teamId= teamId)\n\n @tornado.web.authenticated\n @core.web.authenticatedProject\n def post(self, teamId, projectId, messageId, **kwargs):\n form = MessageForm(self.request.arguments, locale_code=self.locale.code)\n project = Project.query.filter_by(id=projectId).first()\n message = Message.query.filter_by(id=messageId).first()\n currentUser = self.current_user\n now = datetime.now()\n message.title = form.title.data\n message.content = form.content.data\n messageId = message.id\n\n url = \"/project/%s/message/%d\"%(projectId, messageId)\n operation = Operation(own_id = currentUser.id, createTime= now, operation_type=4, target_type=1,\n target_id=messageId, title= message.title, team_id= teamId, project_id= projectId, url= url)\n\n try:\n db.session.add(operation)\n\n for url in form.attachmentDel.data:\n for attachment in message.attachments:\n if attachment.url == url:\n message.attachments.remove(attachment)\n\n for attachment in form.attachment.data:\n attachment = Attachment.query.filter_by(url=attachment).first()\n if attachment is not None:\n message.attachments.append(attachment)\n \n db.session.add(message)\n db.session.commit()\n except:\n db.session.rollback()\n raise\n self.writeSuccessResult(message)\n\nclass CommentDetailHandler(BaseHandler):\n @tornado.web.authenticated\n @core.web.authenticatedProject\n def get(self, teamId, projectId, messageId, commentId):\n project = Project.query.filter_by(id=projectId).first()\n message = Message.query.filter_by(id=messageId).first()\n currentUser = self.current_user\n self.render(\"topic/messageDetail.html\", project= project, message= message)\n\n @tornado.web.authenticated\n @core.web.authenticatedProject\n def post(self, teamId, projectId, messageId, commentId, **kwargs):\n form = MessageForm(self.request.arguments, locale_code=self.locale.code)\n message = Message.query.filter_by(id=messageId).first()\n comment = Comment.query.filter_by(id=commentId).first()\n currentUser = self.current_user\n teamId = currentUser.teamId\n now = datetime.now()\n comment.content = form.content.data\n commentId = comment.id\n\n url = \"/project/%s/message/%s/comment/%d\"%(projectId, messageId, commentId)\n operation = Operation(own_id = currentUser.id, createTime= now, operation_type=4, target_type=2,\n target_id=messageId, title= message.title, digest=comment.content, team_id= teamId, project_id= projectId, url= url)\n\n try:\n db.session.add(operation)\n\n for attachment in form.attachment.data:\n attachment = Attachment.query.filter_by(url=attachment).first()\n if attachment is not None:\n meeesage.attachments.append(attachment)\n \n for url in form.attachmentDel.data:\n for attachment in message.attachments:\n if attachment.url == url:\n comment.attachments.remove(attachment)\n\n db.session.add(comment)\n db.session.commit()\n except:\n db.session.rollback()\n raise\n self.writeSuccessResult(comment)\n\nclass CommentHandler(BaseHandler):\n @tornado.web.authenticated\n def post(self, teamId, projectId, messageId):\n form = CommentForm(self.request.arguments, locale_code=self.locale.code)\n if form.validate():\n currentUser = self.current_user\n teamId = currentUser.teamId\n message = Message.query.filter_by(id=messageId).with_lockmode(\"update\").first()\n now = datetime.now()\n comment = Comment(content=form.content.data, message_id=messageId ,\n own_id=currentUser.id, project_id= projectId, team_id=teamId, createTime= now, attachments = [])\n\n for attachment in form.attachment.data:\n attachment = Attachment.query.filter_by(url=attachment).first()\n if attachment is not None:\n comment.attachments.append(attachment)\n\n try:\n db.session.add(comment)\n db.session.flush()\n commentId = comment.id\n digest = html2text(form.content.data)\n digest = digest[:100]\n\n message.comment_num = message.comment_num + 1\n message.comment_digest = digest\n\n db.session.add(message)\n\n url = \"/project/%s/message/%s/comment/%d\"%(projectId, messageId, commentId)\n\n operation = Operation(own_id = currentUser.id, createTime= now, operation_type=2, target_type=1,\n target_id=messageId, title= message.title, digest= digest, team_id= teamId, project_id= projectId, url= url)\n\n db.session.add(operation)\n\n db.session.commit()\n except:\n db.session.rollback()\n raise\n send_message(currentUser.id, teamId, 2, 1, comment)\n\n self.writeSuccessResult(comment)\n\n","repo_name":"mqshen/MyTask","sub_path":"MyTask/controller/topic.py","file_name":"topic.py","file_ext":"py","file_size_in_byte":9927,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"51"} +{"seq_id":"34858995726","text":"import datetime\nimport unittest\n\nfrom pbshipping import *\n\nimport test_util\n\n\nclass TestManifest(unittest.TestCase):\n\n def setUp(self):\n test_util.setup_env() \n self.auth_obj = AuthenticationToken(api_key=test_util._test_api_key,\n api_secret=test_util._test_api_secret)\n self.developer = test_util.setup_developer(self.auth_obj)\n merchant, acct_num = test_util.setup_merchant(self.auth_obj, self.developer)\n self.shipper_id = merchant.postalReportingNumber\n\n def tearDown(self):\n pass\n\n def testManifest(self):\n shipment1, txid1 = test_util.create_single_shipment(\n self.auth_obj, self.developer, self.shipper_id)\n shipment2, txid2 = test_util.create_single_shipment(\n self.auth_obj, self.developer, self.shipper_id)\n trk_nums = [shipment1.parcelTrackingNumber, \n shipment2.parcelTrackingNumber]\n manifest = Manifest(\n carrier=test_util._MY_RATE_REQUEST_CARRIER_USPS[\"carrier\"], \n submissionDate=datetime.datetime.utcnow().strftime(\"%Y-%m-%d\"),\n parcelTrackingNumbers=trk_nums,\n fromAddress=shipment1.fromAddress)\n txid = test_util.get_pb_tx_id()\n\n #print \"Testing manifest creation ...\"\n manifest.create(self.auth_obj, txid)\n self.assertEqual(\"manifestId\" in manifest, True)\n \n #print \"Testing reprint manifest ...\"\n manifest.reprint(self.auth_obj)\n \n #print \"Testing retry manifest ...\"\n manifest.retry(self.auth_obj, test_util.get_pb_tx_id(), txid)\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()","repo_name":"ajay-cz/pb-hackathon","sub_path":"app/libs/pbshipping/test/manifest_test.py","file_name":"manifest_test.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"23461097123","text":"from django.urls import path\nfrom .views import *\nfrom OrderFood.views.home import *\nfrom OrderFood.views.moduloAdministrador import *\nfrom OrderFood.views.moduloCajero import *\nfrom OrderFood.views.moduloCliente import *\nfrom OrderFood.views.moduloEncCocina import *\nfrom OrderFood.views.moduloEncConvenio import *\nfrom OrderFood.views.moduloRepartidor import *\n\n\nfrom .middlewares.auth import auth_middleware,auth_middleware_enc_cocina,auth_middleware_enc_convenio,auth_middleware_repartidor,auth_middleware_cliente,auth_middleware_cajero\n\n\nurlpatterns = [\n path('', home.as_view(), name=\"home\"),\n path('home', incio_trabajador, name=\"incio_trabajador\"),\n\n path('platos//',home.as_view() and listar_plato_restaurante, name='platos'),\n\n path('login', Login.as_view(), name=\"login\"),\n path('logout', logout, name=\"logout\"),\n\n path('eliminar-plato-carro/', eliminar_plato_carro,name=\"eliminar-plato-carro\"),\n path('limpiar-carro/', limpiar_carro,name=\"limpiar-carro\"),\n\n\n #CLIENTE\n path('registro/', generarCuentaCliente , name=\"auto-registro-cliente\"),\n path(\"editar-perfil-cliente/\", auth_middleware_cliente(editar_perfil_cliente), name=\"editar-perfil-cliente\"),\n path(\"cambiar-contraseña-cliente/\",auth_middleware_cliente(cambiar_contraseña_cliente),name=\"cambiar-contraseña-cliente\"),\n path('realizar-pedido', auth_middleware_cliente(realizar_pedido.as_view()), name=\"realizar-pedido\"),\n path('pagar', auth_middleware_cliente(realizar_pedido.as_view()), name=\"pagar\"),\n path('webpay', webpay, name=\"webpay\"),\n path('terminar', webpaycommit, name=\"terminar\"),\n\n\n path('mis-pedidos', auth_middleware_cliente(pedidos.as_view()), name=\"mis-pedidos\"),\n path('historial-pedidos', auth_middleware_cliente(historial_pedidos.as_view()), name=\"historial-pedidos\"),\n\n\n #ADMINITRACION\n path(\"editar-perfil/\",auth_middleware(editar_perfil_admin),name=\"editar-perfil\"),\n path(\"cambiar-contraseña/\",auth_middleware(cambiar_contraseña_admin),name=\"cambiar-contraseña\"),\n\n path('gestionar-enc-cocina/', auth_middleware(generar_cuenta_enc_cocina), name=\"gestionar-encCocina\"),\n path('editar-cuenta-enc-cocina/', auth_middleware(editar_cuenta_enc_cocina), name='editar-cuenta-enc-cocina'),\n path('eliminar-cuenta-enc-cocina/', auth_middleware(eliminar_cuenta_enc_cocina), name='eliminar-cuenta-enc-cocina'),\n\n path('gestionar-enc-convenio', generar_cuenta_enc_convenio, name=\"gestionar-enc-convenio\"),\n path('editar-cuenta-enc-convenio/', auth_middleware(editar_cuenta_enc_convenio), name='editar-cuenta-enc-convenio'),\n path('eliminar-cuenta-enc-convenio/', auth_middleware(eliminar_cuenta_enc_convenio), name='eliminar-cuenta-enc-convenio'),\n\n\n path('gestionar-repartidor/', auth_middleware(generar_cuenta_repartidor), name='gestionar-repartidor'),\n path('editar-cuenta-repartidor/', auth_middleware(editar_cuenta_repartidor), name='editar-cuenta-repartidor'),\n path('eliminar-cuenta-repartidor/', auth_middleware(eliminar_cuenta_repartidor), name='eliminar-cuenta-repartidor'),\n\n path('gestionar-cajero/', auth_middleware(generar_cuenta_cajero), name='gestionar-cajero'),\n path('editar-cuenta-cajero/', auth_middleware(editar_cuenta_cajero), name='editar-cuenta-cajero'),\n path('eliminar-cuenta-cajero/', auth_middleware(eliminar_cuenta_cajero), name='eliminar-cuenta-cajero'),\n #FIN ADMINITRACION\n\n #ENCARGADO COCINA\n path(\"editar-perfil-enc-cocina/\",auth_middleware_enc_cocina(editar_perfil_enc_cocina),name=\"editar-perfil-enc-cocina\"),\n path(\"cambiar-contraseña-enc-cocina/\",auth_middleware_enc_cocina(cambiar_contraseña_enc_cocina),name=\"cambiar-contraseña-enc-cocina\"),\n #path Platos\n path('gestionar-plato/', auth_middleware_enc_cocina(gestionar_plato), name=\"gestionar-plato\"),\n path('modificar-plato/', auth_middleware_enc_cocina(modificar_plato), name=\"modificar_plato\"),\n path('eliminar-plato/', auth_middleware_enc_cocina(eliminar_plato), name=\"eliminar-plato\"),\n # path('buscar-plato/', (buscar_plato), name=\"buscar-plato\"),\n\n #path Proveedor\n path('proveedor',proveedor, name=\"proveedor\"),\n path('listar-proveedor/', auth_middleware_enc_cocina(listar_proveedor), name=\"listar-proveedor\"),\n path('modificar-proveedor/', auth_middleware_enc_cocina(modificar_proveedor), name=\"modificar-proveedor\"),\n path('eliminar-proveedor/', auth_middleware_enc_cocina(eliminar_proveedor), name=\"eliminar-proveedor\"),\n #path Restaurant\n path('restaurant', restaurant, name=\"restaurant\"),\n path('listar-restaurant/', auth_middleware_enc_cocina(listar_restaurant), name=\"listar-restaurant\"),\n path('modificar-restaurant/', auth_middleware_enc_cocina(modificar_restaurant), name=\"modificar-restaurant\"),\n path('eliminar-restaurant/', auth_middleware_enc_cocina(eliminar_restaurant), name=\"eliminar-restaurant\"),\n \n\n #FIN ENCARGADO COCINA\n\n #ENCARGADO CONVENIO\n path(\"editar-perfil-enc-convenio/\",auth_middleware_enc_convenio(editar_perfil_enc_convenio),name=\"editar-perfil-enc-convenio\"),\n path(\"cambiar-contraseña-enc-convenio/\",auth_middleware_enc_convenio(cambiar_contraseña_enc_convenio),name=\"cambiar-contraseña-enc-convenio\"),\n path('gestionar-empresa/', auth_middleware_enc_convenio(agregar_empresa) , name='gestionar-empresa'),\n path('modificar-convenio//', modificar_convenio, name='modificar_convenio'),\n path('eliminar-empresa/', eliminar_empresa, name='eliminar-empresa'),\n path('generar-cuenta-empleado/', auth_middleware_enc_convenio(generar_cuenta_empleado), name='generar-cuenta-empleado'),\n path('gestionar-empresa/listar-cuentas-empleados/', listar_cuenta_empleados, name='listar-cuentas-empleados'),\n path(\"registrarsaldo/\", cargar_saldo_cliente , name=\"registrarsaldo\"),\n path(\"leertxt\", leertxt , name=\"leertxt\"),\n\n path('editar-cuentaTrabEmp/', auth_middleware_enc_convenio(editar_cuenta_trab_emp), name='editar-cuentaTrabEmp'),\n path('eliminar-cuentaTrabEmp/', eliminar_cuenta_trab_emp, name='eliminar-cuentaTrabEmp'),\n #FIN ENCARGADO CONVENIO\n\n\n #REPARTIDOR\n path('editar-perfil-repartidor/',auth_middleware_repartidor(editar_perfil_repartidor),name=\"editar-perfil-repartidor\"),\n path('cambiar-contraseña-repartidor/',auth_middleware_repartidor(cambiar_contraseña_repartidor),name=\"cambiar-contraseña-repartidor\"),\n path('listar-pedidos-activos/',auth_middleware_repartidor(listar_pedidos_activos),name=\"listar-pedidos-activos\"),\n path('aceptar-pedido//',aceptar_pedido,name=\"aceptar-pedido\"),\n path('listar-pedidos-aceptados',auth_middleware_repartidor(listar_pedidos_aceptados),name=\"listar-pedidos-aceptados\"),\n path('entregar-pedido//',entregar_pedido,name=\"entregar-pedido\"),\n path('cancelar-pedido//',cancelar_pedido,name=\"cancelar-pedido\"),\n\n #FIN REPARTIDOR\n\n\n #path Pedidos\n path('agregar-pedido/', agregar_pedido, name=\"agregar-pedido\"),\n path('listar-pedido/', listar_pedido, name=\"listar-pedido\"),\n path('modificar-pedido//', modificar_pedido, name=\"modificar-pedido\"),\n path('eliminar-pedido//', eliminar_pedido, name=\"eliminar-pedido\"),\n #End Path\n\n #path CAJERO\n path('listar-pedidos-pendientes/',auth_middleware_cajero(listar_pedidos_pendientes), name=\"listar-pedidos-pendientes\"),\n path('confirmar-pedido//',confirmar_pedido, name=\"confirmar-pedido\"),\n path('listar-pedidos-confirmados/',auth_middleware_cajero(listar_pedidos_confirmados), name=\"listar-pedidos-confirmados\"),\n path('cancelar-pedido-cajero//',cancelar_pedido_cajero, name=\"cancelar-pedido-cajero\"),\n \n #END CAJERO\n # path('agregar_carrito', agregar_carrito, name= 'agregar_carrito'),\n # path('listar_carrito', listar_carrito, name='listar_carrito'),\n # path('eliminar_item_carrito//', eliminar_item_carrito, name='eliminar_item_carrito'), \n]\n","repo_name":"oscarlmL/AlimentosSantiago","sub_path":"OrderFood/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":7936,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"22211298913","text":"import os.path as osp \nimport json\nimport pdb \n\ndef dict2xml(data_dict, path_out):\n for vid_key in data_dict.keys():\n path_out_file = osp.join(path_out, vid_key+'.xml')\n with open(path_out_file, 'w') as fp:\n print('', file=fp)\n \ndef split_data():\n path_json_categories = \"/home/nttung/Challenge/MediaevalSport/2020_data/data/data_json/train.json\"\n path_out_train_xml = \"/home/nttung/Challenge/MediaevalSport/2020_data/data/classificationTask/split_data/train\"\n path_out_val_xml = \"/home/nttung/Challenge/MediaevalSport/2020_data/data/classificationTask/split_data/valid\"\n ratio = 0.7\n \n # read json \n with open(path_json_categories, \"r\") as fp:\n json_data = json.load(fp)\n\n train_dict = {}\n val_dict = {}\n\n for cat_name in json_data.keys():\n print(\"Process:\", cat_name)\n\n # count total instances for each cat \n total_count = 0\n for vid_key in json_data[cat_name].keys():\n total_count += len(json_data[cat_name][vid_key])\n\n threshold_train_idx = int(total_count*ratio)\n\n # start to add to train and val dict\n ref_dict = train_dict # start with train\n num_instance_run = 0\n for vid_key in json_data[cat_name].keys():\n for interval in json_data[cat_name][vid_key]:\n if vid_key not in ref_dict:\n ref_dict[vid_key] = []\n ref_dict[vid_key].append([interval, cat_name, num_instance_run])\n num_instance_run += 1\n\n # debug\n if num_instance_run == threshold_train_idx:\n # switch to val dictionary\n ref_dict = val_dict\n\n \n print(\"Write to xml....\")\n # write to xml for train dict\n dict2xml(train_dict, path_out_train_xml)\n dict2xml(val_dict, path_out_val_xml)\n \n\nif __name__ == '__main__':\n split_data()","repo_name":"nttung1110/Mediaeval21-Baseline","sub_path":"utils/split_trainval2020.py","file_name":"split_trainval2020.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"27457756547","text":"# This function runs leave-many-out (LMO) cross validation test based on K-fold cross validation.\r\n# This program has been written by Dr. Bakhtyar Sepehri.\r\n######################################################################################################################################################################\r\n# \"repeats\" is the number of iteartion.\r\n# \"NG\" is the number of groups. \r\n# \"Ytrain\" is dependent variable (activity or property) vector.\r\n# \"Xtrain\" is independent variable(molecular descriptors) matrix.\r\n# In Xtrain matrice,molecules are in rows and descriptors are in columns.\r\n# m is the number of molecules or samples.\r\n# \"average_R2traincv\", \"Min_R2traincv\" and \"Max_R2traincv\", respectively, are the mean, minimum and maximum of obtained R2 for \"repeat\" time run of program.\r\n# \"average_RMSEtraincv\" is the mean of obtained RMSE for \"repeat\" time run of program.\r\n########################################################################################################################################################################\r\n# To run script:\r\n# 1- Source script\r\n# 2- Copy following command and paste it in Consoleand then push Enter key:\r\n# Command: Average_R2train_cv,Average_RMSEtrain_cv,MAX_R2train_cv,MIN_R2train_cv=Kfold_LMO_CV(Ytrain,Xtrain,NG,repeats)\r\n#######################################################################################################################################################################\r\ndef Kfold_LMO_CV(Ytrain,Xtrain,NG,repeats):\r\n import numpy as np\r\n All_R2_CV=np.zeros((repeats,1))\r\n All_RMSE_CV=np.zeros((repeats,1))\r\n m=len(Ytrain)\r\n Ones_train=np.ones(((m),1))\r\n Ytest_cv_pred_all_samples=np.zeros(((m),1))\r\n Ytrain=Ytrain.reshape(m,1)\r\n for i in range(0,repeats):\r\n index_train=np.arange(m)\r\n np.random.shuffle(index_train)\r\n Xtrain=Xtrain[index_train,:]\r\n Ytrain=Ytrain[index_train]\r\n groups=np.arange(m)%NG\r\n for group in range(0,NG):\r\n Train_NG=np.where(groups!=group)\r\n Train_NG=np.asarray(Train_NG)\r\n Train_NG=np.transpose(Train_NG)\r\n Train_NG=Train_NG.reshape(len(Train_NG),)\r\n Test_NG=np.where(groups==group)\r\n Test_NG=np.asarray(Test_NG)\r\n Test_NG=np.transpose(Test_NG)\r\n Test_NG=Test_NG.reshape(len(Test_NG),)\r\n Xtrain_cv=Xtrain[Train_NG,:]\r\n Ytrain_cv=Ytrain[Train_NG]\r\n Xtest_cv=Xtrain[Test_NG,:]\r\n Ytest_cv=Ytrain[Test_NG]\r\n LY_train=len(Ytrain_cv)\r\n LY_test=len(Ytest_cv)\r\n ones_LY_train=np.ones((LY_train,1))\r\n ones_LY_test=np.ones((LY_test,1))\r\n Xtrain_cv=np.hstack((ones_LY_train,Xtrain_cv))\r\n b=np.linalg.inv(np.transpose(Xtrain_cv)@Xtrain_cv)@np.transpose(Xtrain_cv)@Ytrain_cv\r\n Xtest_cv=np.hstack((ones_LY_test,Xtest_cv))\r\n Ytest_cv_pred=Xtest_cv@b\r\n Ytest_cv_pred_all_samples[Test_NG]=Ytest_cv_pred\r\n residualstest=Ytrain-Ytest_cv_pred_all_samples\r\n All_RMSE_CV[i]=np.std(residualstest)\r\n Ytrain_bar=np.mean(Ytrain)*Ones_train\r\n z=Ytrain-Ytrain_bar\r\n d=Ytrain-Ytest_cv_pred_all_samples\r\n All_R2_CV[i]=1-((np.transpose(d)@d)/(np.transpose(z)@z))\r\n Average_R2train_cv=np.mean(All_R2_CV)\r\n Average_RMSEtrain_cv=np.mean(All_RMSE_CV)\r\n MAX_R2train_cv=np.max(All_R2_CV)\r\n MIN_R2train_cv=np.min(All_R2_CV)\r\n return Average_R2train_cv,Average_RMSEtrain_cv,MAX_R2train_cv,MIN_R2train_cv\r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"sepehribakhtyar/Python_codes","sub_path":"Kfold_LMO_CV.py","file_name":"Kfold_LMO_CV.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"32885393884","text":"cadastro_jogador = []\n\nwhile True:\n jogador = {}\n\n nome = input('Nome do jogador: ')\n qntd_partidas = int(input(f'Quantas partidas {nome} jogou? '))\n jogador['nome'] = nome\n\n gols_partidas = []\n\n for partida in range(qntd_partidas):\n gols = int(input(f'Quantos gols na partida {partida + 1}? '))\n gols_partidas.append(gols)\n\n jogador['gols'] = gols_partidas\n\n total_gols = sum(gols_partidas)\n jogador['total'] = total_gols\n\n cadastro_jogador.append(jogador)\n\n escolha = input('Quer continuar? [S/N] ').upper()\n if escolha == 'N':\n break\n\nprint('-='*25)\nprint(cadastro_jogador)\nprint('cod nome gols total')\nprint('-'*35)\nfor cod, jogador in enumerate(cadastro_jogador):\n nome = jogador['nome']\n gols = jogador['gols']\n total = jogador['total']\n print(f'{cod:<5}{nome:<8}{gols}{total:>12}')\nprint('-'*35)\n\nwhile True:\n dados = int(input('Mostrar dados de qual jogador? '))\n for cod, jogador in enumerate(cadastro_jogador):\n if dados == cod:\n nome = jogador['nome']\n gols = jogador['gols']\n total = jogador['total']\n print(f'-- LEVANTAMENTO DO JOGADOR {nome}:')\n for partida, gol in enumerate(gols):\n print(f'No jogo {partida+1} fez {gol} gols.')\n break\n opcao = input('Deseja continuar? [S/N] ').upper()\n if opcao == 'N':\n break","repo_name":"lele-sf/python-curso-em-video","sub_path":"mundo03/ex095.py","file_name":"ex095.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"24429201220","text":"import os\nimport struct\nfrom io import BytesIO\nimport PIL\nfrom PIL import Image\nfrom typing import Any\nfrom collections.abc import Callable\n\nfrom xpra.util.types import typedict\nfrom xpra.util.str_fn import csv\nfrom xpra.os_util import hexstr, strtobytes\nfrom xpra.codecs.debug import may_save_image\nfrom xpra.log import Logger\n\nlog = Logger(\"encoder\", \"pillow\")\n\nImage.init()\n\nDECODE_FORMATS = os.environ.get(\"XPRA_PILLOW_DECODE_FORMATS\", \"png,png/L,png/P,jpeg,webp\").split(\",\")\n\nPNG_HEADER = struct.pack(\"BBBBBBBB\", 137, 80, 78, 71, 13, 10, 26, 10)\ndef is_png(data) -> bool:\n return data.startswith(PNG_HEADER)\nRIFF_HEADER = b\"RIFF\"\nWEBP_HEADER = b\"WEBP\"\ndef is_webp(data) -> bool:\n return data[:4]==RIFF_HEADER and data[8:12]==WEBP_HEADER\nJPEG_HEADER = struct.pack(\"BBB\", 0xFF, 0xD8, 0xFF)\ndef is_jpeg(data) -> bool:\n #the jpeg header is actually more complicated than this,\n #but in practice all the data we receive from the server\n #will have this type of header\n return data[:3]==JPEG_HEADER\ndef is_svg(data) -> bool:\n return strtobytes(data[:5])==b\" bool:\n return data[:9]==XPM_HEADER\n\ndef is_tiff(data) -> bool:\n if data[:2]==b\"II\":\n return data[2]==42 and data[3]==0\n if data[:2]==b\"MM\":\n return data[2]==0 and data[3]==42\n return False\n\n\nHEADERS : dict[Callable, str] = {\n is_png : \"png\",\n is_webp : \"webp\",\n is_jpeg : \"jpeg\",\n is_svg : \"svg\",\n is_xpm : \"xpm\",\n is_tiff : \"tiff\",\n }\n\ndef get_image_type(data) -> str:\n if not data:\n return \"\"\n if len(data)<32:\n return \"\"\n for fn, encoding in HEADERS.items():\n if fn(data):\n return encoding\n return \"\"\n\n\ndef open_only(data, types=(\"png\", \"jpeg\", \"webp\")) -> Image:\n itype = get_image_type(data) or \"unknown\"\n if itype not in types:\n raise ValueError(f\"invalid data: {itype}, not recognized as {csv(types)}, header: \"+hexstr(data[:64]))\n buf = BytesIO(data)\n return Image.open(buf)\n\n\ndef get_version() -> str:\n return PIL.__version__\n\ndef get_type() -> str:\n return \"pillow\"\n\ndef do_get_encodings() -> list[str]:\n log(\"PIL.Image.OPEN=%s\", Image.OPEN)\n encodings = []\n for encoding in DECODE_FORMATS:\n #strip suffix (so \"png/L\" -> \"png\")\n stripped = encoding.split(\"/\")[0].upper()\n if stripped in Image.OPEN:\n encodings.append(encoding)\n log(\"do_get_encodings()=%s\", encodings)\n return encodings\n\ndef get_encodings() -> tuple[str,...]:\n return ENCODINGS\n\nENCODINGS : tuple[str,...] = tuple(do_get_encodings())\n\ndef get_info() -> dict[str,Any]:\n return {\n \"version\" : get_version(),\n \"encodings\" : get_encodings(),\n }\n\ndef decompress(coding:str, img_data:bytes, options:typedict) -> tuple[str,bytes,int,int,int]:\n # can be called from any thread\n actual = get_image_type(img_data)\n if not actual or not coding.startswith(actual):\n raise ValueError(f\"expected {coding!r} image data but received %r\" % (actual or \"unknown\"))\n buf = BytesIO(img_data)\n img = Image.open(buf)\n assert img.mode in (\"L\", \"LA\", \"P\", \"RGB\", \"RGBA\", \"RGBX\"), f\"invalid image mode: {img.mode}\"\n transparency = options.intget(\"transparency\", -1)\n if img.mode==\"P\":\n if transparency>=0:\n #this deals with alpha without any extra work\n img = img.convert(\"RGBA\")\n else:\n img = img.convert(\"RGB\")\n elif img.mode==\"L\":\n if transparency>=0:\n #why do we have to deal with alpha ourselves??\n def mask_value(a):\n if a!=transparency:\n return 255\n return 0\n mask = Image.eval(img, mask_value)\n mask = mask.convert(\"L\")\n def nomask_value(a):\n if a!=transparency:\n return a\n return 0\n img = Image.eval(img, nomask_value)\n img = img.convert(\"RGBA\")\n img.putalpha(mask)\n else:\n img = img.convert(\"RGB\")\n elif img.mode==\"LA\":\n img = img.convert(\"RGBA\")\n\n width, height = img.size\n if img.mode==\"RGB\":\n #PIL flattens the data to a continuous straightforward RGB format:\n rowstride = width*3\n rgb_format = options.strget(\"rgb_format\", \"\")\n rgb_format = rgb_format.replace(\"A\", \"\").replace(\"X\", \"\")\n #the webp encoder only takes BGRX input,\n #so we have to swap things around if it was fed \"RGB\":\n if rgb_format==\"RGB\":\n rgb_format = \"BGR\"\n else:\n rgb_format = \"RGB\"\n elif img.mode in (\"RGBA\", \"RGBX\"):\n rowstride = width*4\n rgb_format = options.strget(\"rgb_format\", img.mode)\n if coding==\"webp\":\n #the webp encoder only takes BGRX input,\n #so we have to swap things around if it was fed \"RGBA\":\n if rgb_format==\"RGBA\":\n rgb_format = \"BGRA\"\n elif rgb_format==\"RGBX\":\n rgb_format = \"BGRX\"\n elif rgb_format==\"BGRA\":\n rgb_format = \"RGBA\"\n elif rgb_format==\"BGRX\":\n rgb_format = \"RGBX\"\n else:\n log.warn(\"Warning: unexpected RGB format '%s'\", rgb_format)\n else:\n raise ValueError(f\"invalid image mode: {img.mode}\")\n raw_data = img.tobytes(\"raw\", img.mode)\n log(\"pillow decoded %i bytes of %s data to %i bytes of %s\", len(img_data), coding, len(raw_data), rgb_format)\n may_save_image(coding, img_data)\n return rgb_format, raw_data, width, height, rowstride\n\n\ndef selftest(_full=False) -> None:\n global ENCODINGS\n from xpra.codecs.checks import TEST_PICTURES #pylint: disable=import-outside-toplevel\n #test data generated using the encoder:\n for encoding, test_data in TEST_PICTURES.items():\n if encoding not in ENCODINGS:\n #removed already\n continue\n for size, samples in test_data.items():\n log(f\"testing {encoding} at size {size} with {len(samples)} samples\")\n for i, cdata in enumerate(samples):\n try:\n log(f\"testing sample {i}: {len(cdata):5} bytes\")\n buf = BytesIO(cdata)\n img = PIL.Image.open(buf)\n assert img, \"failed to open image data\"\n raw_data = img.tobytes(\"raw\", img.mode)\n assert raw_data\n #now try with junk:\n cdata = b\"ABCD\"+cdata\n buf = BytesIO(cdata)\n try:\n img = PIL.Image.open(buf)\n log.warn(f\"Pillow failed to generate an error parsing invalid input: {img}\")\n except Exception as e:\n log(\"correctly raised exception for invalid input: %s\", e)\n except Exception as e:\n log(\"selftest:\", exc_info=True)\n log.error(\"Pillow error decoding %s with data:\", encoding)\n log.error(\" %r\", cdata)\n log.error(\" %s\", e, exc_info=True)\n ENCODINGS = tuple(x for x in ENCODINGS if x!=encoding)\n\n\nif __name__ == \"__main__\":\n selftest(True)\n print(csv(get_encodings()))\n","repo_name":"Xpra-org/xpra","sub_path":"xpra/codecs/pillow/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":7360,"program_lang":"python","lang":"en","doc_type":"code","stars":1133,"dataset":"github-code","pt":"51"} +{"seq_id":"15544507896","text":"from typing import TYPE_CHECKING, Union\n\nfrom dvc.utils.cli_parse import parse_params\n\nfrom . import locked\nfrom .scm_context import scm_context\n\nif TYPE_CHECKING:\n from dvc.stage import PipelineStage, Stage\n\n from . import Repo\n\n\n@locked\n@scm_context\ndef run(\n self: \"Repo\",\n no_exec: bool = False,\n no_commit: bool = False,\n run_cache: bool = True,\n force: bool = True,\n **kwargs,\n) -> Union[\"Stage\", \"PipelineStage\"]:\n assert not kwargs.get(\"single_stage\")\n assert not kwargs.get(\"fname\")\n kwargs.update({\"force\": force, \"params\": parse_params(kwargs.get(\"params\", []))})\n stage = self.stage.create(**kwargs)\n\n if no_exec:\n stage.ignore_outs()\n else:\n stage.run(no_commit=no_commit, run_cache=run_cache)\n\n stage.dump(update_lock=not no_exec)\n return stage\n","repo_name":"iterative/dvc","sub_path":"dvc/repo/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":12419,"dataset":"github-code","pt":"51"} +{"seq_id":"13665123178","text":"class Memoize:\n def __init__(self, fn):\n self.fn = fn\n self.memo = {}\n\n def __call__(self, *args):\n if args not in self.memo:\n self.memo[args] = self.fn(*args)\n return self.memo[args]\n\n\n@Memoize\ndef lcs(strA, strB):\n if len(strA) == 0 or len(strB) == 0:\n return 0\n elif strA[-1] == strB[-1]: # if the last characters match\n return 1 + lcs(strA[:-1], strB[:-1])\n else: # if the last characters don't match\n return max(lcs(strA[:-1], strB), lcs(strA, strB[:-1]))\n\n\ndef lcs_dp(strA, strB):\n \"\"\"Determine the length of the Longest Common Subsequence of 2 strings.\"\"\"\n rows = len(strA) + 1\n cols = len(strB) + 1\n\n dp_table = [[0 for j in range(cols)] for i in range(rows)]\n \n\n for row in range(rows):\n for col in range(cols):\n if len(strA) == 0 or len(strB) == 0:\n dp_table[row][col] = 0\n \n elif strA[row-1] == strB[col-1]:\n dp_table[row][col] = dp_table[row-1][col-1] + 1\n \n else:\n dp_table[row][col] = max(dp_table[row-1][col], dp_table[row][col-1])\n\n print(dp_table)\n return dp_table[rows-1][cols-1]\n\ndef knapsack(items, capacity):\n \"\"\"Return the maximum value that can be stored in the knapsack using the\n items given.\"\"\"\n # print(items, capacity)\n if len(items) == 0 or capacity <= 0:\n return 0\n \n # Take the value of the first item, add that to whatever the value of the remaining items would be, but with less capacity\n value_with = items[0][2] + knapsack(items[1:], capacity - items[0][1])\n \n # Assuming the first item doesn't go in the knapsack, what would the value be\n value_without = knapsack(items[1:], capacity)\n \n if capacity - items[0][1] < 0:\n return value_without\n else:\n return max(value_with, value_without)\n\ndef knapsack_dp(items, capacity):\n \"\"\"Return the maximum value that can be stored in the knapsack using the\n items given.\"\"\"\n rows = len(items) + 1\n cols = capacity + 1\n dp_table = [[0 for j in range(cols)] for i in range(rows)]\n\n # Fill in the table using a nested for loop.\n # Go through the table\n for row in range(rows):\n for col in range(cols):\n # If either the rows or the column go past the edge of the table, go back\n if rows == 0 or cols == 0:\n dp_table[row][col] = 0\n \n # If it's over capacity go back\n elif items[row-1][1] > col:\n dp_table[row][col] = dp_table[row-1][col]\n \n else:\n value_with = items[row-1][2] + dp_table[row-1][col - items[row-1][1]]\n value_without = dp_table[row-1][col]\n dp_table[row][col] = max(value_with, value_without)\n\n return dp_table[rows-1][cols-1]\n \ndef edit_distance(str1, str2):\n \"\"\"Compute the Edit Distance between 2 strings.\"\"\"\n # Base Case:\n if len(str1) == 0:\n return len(str2)\n if len(str2) == 0:\n return len(str1)\n \n # Other base case\n if str1[-1] == str2[-1]:\n return edit_distance(str1[:-1], str2[:-1])\n \n option1 = edit_distance(str1[:-1], str2)\n option2 = edit_distance(str1, str2[:-1])\n option3 = edit_distance(str1[:-1], str2[:-1])\n \n return min(option1, option2, option3) + 1\n\ndef edit_distance_dp(str1, str2):\n \"\"\"Compute the Edit Distance between 2 strings.\"\"\"\n rows = len(str1) + 1\n cols = len(str2) + 1\n dp_table = [[0 for j in range(cols)] for i in range(rows)]\n\n for row in range(rows):\n for col in range(cols):\n if row == 0 or col == 0:\n dp_table[row][col] = max(row, col)\n \n elif str1[row-1] == str2[col-1]:\n dp_table[row][col] = dp_table[row-1][col-1]\n \n else:\n insert = dp_table[row-1][col]\n delete = dp_table[row][col-1]\n replace = dp_table[row-1][col-1]\n \n dp_table[row][col] = min(insert, delete, replace) + 1\n\n print(dp_table)\n return dp_table[-1][-1]\n\n","repo_name":"MaxIsWell42/CS22-dynamic-programming","sub_path":"challenges.py","file_name":"challenges.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"23712601359","text":"#!/usr/bin/python3\n\nfrom flask import Flask, request, Response, redirect\nfrom news_get import get_sql\nfrom datetime import date\n\napp = Flask(__name__)\n\n\"\"\"Set up the base html for the root page.\"\"\"\nhtml = '''\\\n\n\n \n News Review\n \n \n \n

    News Review

    \n
    \n
    \n \n \n \n
    \n \n \n\n'''\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef news_items():\n \"\"\"Set up the flow to follow to determine which page to show.\"\"\"\n if request.method == 'POST':\n if 'top3' in request.form:\n return redirect('/top3')\n if 'pop_artists' in request.form:\n return redirect('/artists')\n if 'high_error_days' in request.form:\n return redirect('/higherrors')\n return html\n\n\n@app.route('/top3', methods=['GET', 'POST'])\ndef get_top3():\n results = top3()\n response = Response(results, status=200, mimetype=\"text/plain\")\n response.headers[\"Content-Type\"] = \"text/plain; charset=utf-8\"\n return response\n\n\n@app.route('/artists', methods=['GET', 'POST'])\ndef get_popular_artists():\n results = high_errors\n response = Response(results, status=200, mimetype=\"text/plain\")\n response.headers[\"Content-Type\"] = \"text/plain; charset=utf-8\"\n return response\n\n\n@app.route('/higherrors', methods=['GET', 'POST'])\ndef get_high_errors():\n results = high_errors()\n response = Response(results, status=200, mimetype=\"text/plain\")\n response.headers[\"Content-Type\"] = \"text/plain; charset=utf-8\"\n return response\n\ndef top3():\n \"\"\"\"This section queries the database for the top three\n most popular articles.\"\"\"\n sql = \"select slug, popular from top3_view\"\n results = \"\".join(\n '\\\"%s\\\" -- %d views\\n'\n % (slug.title().replace('-', ' '), popular)\n for slug, popular in get_sql(sql))\n return results\n\n\ndef popular_artists():\n \"\"\"This section queries the database for the artists of\n the articles.\"\"\"\n sql = \"select name, popular from popular_artists_view\"\n results = \"\".join(\n '%s -- %d views\\n'\n % (name, popular) for name, popular in get_sql(sql))\n return results\n\n\ndef high_errors():\n \"\"\"\"This section queries the database for the dates\n with more than 1% error rate.\"\"\"\n sql = \"select dates, percent from high_error_view\"\n dateformat = \"%B %d, %Y\"\n results = \"\".join(\n '%s -- %.1f%% errors'\n % (date.strftime(dates, '%B %d, %Y'), percent)\n for dates, percent in get_sql(sql))\n return results\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8000)\n","repo_name":"david-hansen-000/Logs_Analysis","sub_path":"news_page.py","file_name":"news_page.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"70068673119","text":"import time\nimport tkinter as tk\nfrom tkinter import filedialog\nfrom tkinter import *\nfrom tkinter import ttk\n\nfrom PIL import Image, ImageTk, ImageDraw, ImageFont, ImageChops\n\n\n\ndef openfn():\n global filename\n f_types = [('Jpg Files', '*.jpg'), ('PNG Files', '*.png'), ('JPEG Files', '*.jpeg')]\n filename = filedialog.askopenfilename(title='open',filetypes=f_types)\n return filename\n\n\ndef open_img():\n global panel\n x = openfn()\n if x:\n img = Image.open(x).convert(\"RGBA\")\n img = img.resize((350,350), Image.ANTIALIAS)\n img= ImageTk.PhotoImage(img)\n panel=Label(canvas, image=img)\n panel.image = img\n panel.place(relx=.5, rely=.5, anchor=CENTER)\n\n\n\ndef draw_it():\n img = filename\n my_image = Image.open(img)\n text_font = ImageFont.truetype('arial.ttf', 46)\n text_to_add = my_entry.get()\n edit_image = ImageDraw.Draw(my_image)\n edit_image.text((50,500), text= text_to_add, fill='red', font=text_font)\n\n my_image.save('C:/Users/Mike/Downloads/me.jpg')\n time.sleep(2)\n img_2 = Image.open('C:/Users/Mike/Downloads/me.jpg').convert(\"RGBA\")\n img_3 = img_2.resize((350,350), Image.ANTIALIAS)\n img_4 = ImageTk.PhotoImage(img_3)\n panel.config(image=img_4)\n panel.image= img_4\n my_entry.delete(0, END)\n\n\nwindow = Tk()\nwindow.title('watermark creator')\nwindow.minsize(width=700,height=700)\ncanvas = Canvas(width=700, height=700, bg='#e7305b')\ncanvas.pack(fill='both', expand=True)\n\nthe_label= Label(canvas,bg='#e7305b',fg='white', text='Please Upload the photo to which you want to add a water mark')\nthe_label.config(font=('Times New Roman',12, 'bold'))\nthe_label.place(relx=.49, rely=.12, anchor=CENTER)\nupload_t = StringVar()\nupload = Label(canvas, width=30,textvariable=upload_t, fg='#e7305b')\nupload.place(relx=.40,rely=.2,anchor=CENTER)\nupload_t.set('Your upload path here',)\nupload_button= Button(canvas,width=13, text='Upload',command=open_img)\nupload_button.place(relx=.65,rely=.2,anchor=CENTER)\n\n'''cancel_button = Button(canvas, text='Cancel')\ncancel_button.place(relx=.45, rely=.22)'''\n\nmy_entry = Entry(canvas, font=('arial', 14))\nmy_entry.place(relx=.40, rely=.8, anchor=CENTER)\nmy_button = Button(canvas, text='add you water-mark', font=('arial', 10), command=draw_it)\nmy_button.place(relx=.65, rely=.8, anchor=CENTER)\nwindow.mainloop()\n\n\n\n","repo_name":"MahmoudMorsyDev/Watermark-creator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"12016551298","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\nimport os\r\nimport json\r\nimport getpass\r\nimport requests\r\nfrom vkinder.vk.api import vk_login\r\n\r\n\r\nYES = ['yes', 'y', 'да', 'д', 1, '1', 'lf', 'l', 'нуы']\r\nNO = ['no', 'not', 'n', 'нет', 'н', 0, '0', 'ytn', 'тщ', 'тще']\r\nURL = 'https://translate.yandex.net/api/v1.5/tr.json/translate'\r\nKEY_API = 'trnsl.1.1.20190704T182934Z.17f33d8db55385c6.e6d41260c9ccabfba9197455fd6d6679fec9bf38'\r\n\r\n\r\ndef init_variable():\r\n two_factor = input('\\nВы используете двухфакторную авторизацию? (да/нет) - ')\r\n login = str(input('Пожалуйста, введите логин (желательно номер телефона): '))\r\n password = getpass.getpass('Введите Ваш пароль и нажмите \"Enter\" (символы не отображаются): ')\r\n if two_factor in YES:\r\n vk_ = vk_login(login, password, True)\r\n else:\r\n vk_ = vk_login(login, password)\r\n return vk_\r\n\r\n\r\ndef translate(text, from_='en', to='ru'):\r\n ''' translation text '''\r\n params = {\r\n 'key': KEY_API,\r\n 'text': text,\r\n 'lang': f'{from_}-{to}',\r\n }\r\n response = requests.get(URL, params=params)\r\n return ''.join(response.json()['text'])\r\n\r\n\r\ndef translate_auto(text, to='ru'):\r\n ''' auto translation text '''\r\n params = {\r\n 'key': KEY_API,\r\n 'text': text,\r\n 'lang': f'{to}',\r\n 'options': 1,\r\n }\r\n response = requests.get(URL, params=params)\r\n return ''.join(response.json()['text'])\r\n\r\n\r\ndef max_value_of_keys(dict_):\r\n index = 0\r\n key_ = None\r\n for key in dict_.keys():\r\n if index < dict_[key]:\r\n index = dict_[key]\r\n key_ = key\r\n continue\r\n return key_\r\n\r\n\r\ndef get_top_ids(dict_):\r\n list_top_ids = []\r\n index = 0\r\n if len(dict_) < 10:\r\n for k in dict_.copy():\r\n key_ = max_value_of_keys(dict_)\r\n list_top_ids.append(key_)\r\n dict_.pop(key_)\r\n index += 1\r\n else:\r\n while index < 10:\r\n key_ = max_value_of_keys(dict_)\r\n list_top_ids.append(key_)\r\n dict_.pop(key_)\r\n index += 1\r\n return list_top_ids\r\n\r\n\r\ndef write_json(text, filename, path='', mode='wt'):\r\n if path:\r\n make_dir(path)\r\n out_file = os.path.join(path, f'{filename}')\r\n txt = json.dumps(text, sort_keys=True, indent=4, ensure_ascii=False)\r\n with open(out_file, mode=mode, encoding='utf8') as file:\r\n file.write(txt)\n \r\ndef make_dir(path):\n pwd = os.getcwd()\n if '\\\\' in path:\n lst = path.split('\\\\')\n for i in lst:\n if i in os.listdir():\n os.chdir(i)\n else:\n os.mkdir(i)\n os.chdir(i)\n elif '/' in path:\n lst = path.split('/')\n for i in lst:\n if i in os.listdir():\n os.chdir(i)\n else:\n os.mkdir(i)\n os.chdir(i)\n else:\n if path not in os.listdir():\n os.mkdir(path)\n os.chdir(pwd)\r\n\r\n\r\n","repo_name":"Speccy-Rom/Search-service-for-people","sub_path":"vkinder/common_functions.py","file_name":"common_functions.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"7405539033","text":"from logging import getLogger\nfrom abc import ABC\nfrom collections import defaultdict\nimport importlib\n\nfrom .util import get_config_value, get_config_file, get_config_sections\n\nlogger = getLogger(__name__)\n\n\ndef _get_database_class(dbname, exp=None, config_file_name=None):\n '''Get the database class for the given database name\n\n Uses the calour config file (calour.config) keys\n\n Parameters\n ----------\n dbname : str\n the database name. common options are:\n 'dbbact' : the amplicon sequence manual annotation database\n 'spongeworld' : the sponge microbiome database\n 'redbiome' : the qiita automatic amplicon sequence database\n config_file_name: str or None (optional)\n None (default) to use the default calour condig file.\n str to use the file names str as the conig file\n\n\n Returns\n -------\n calour.database.Database\n A ``Database`` class for the requested dbname\n '''\n class_name = get_config_value('class_name', section=dbname, config_file_name=config_file_name)\n module_name = get_config_value('module_name', section=dbname, config_file_name=config_file_name)\n if class_name is not None and module_name is not None:\n # import the database module\n db_module = importlib.import_module(module_name)\n # get the class\n DBClass = getattr(db_module, class_name)\n cdb = DBClass(exp)\n return cdb\n # not found, so print available database names\n databases = []\n sections = get_config_sections()\n for csection in sections:\n class_name = get_config_value('class_name', section=csection, config_file_name=config_file_name)\n module_name = get_config_value('class_name', section=csection, config_file_name=config_file_name)\n if class_name is not None and module_name is not None:\n databases.append(csection)\n if len(databases) == 0:\n raise ValueError('calour config file %s does not contain any database sections.' % get_config_file())\n raise ValueError('Database %s not found in config file (%s).\\n'\n 'Currently contains the databases: %s' % (dbname, get_config_file(), databases))\n\n\ndef add_terms_to_features(exp, dbname, use_term_list=None, field_name='common_term', term_type=None):\n '''Add a field to the feature metadata, with most common term for each feature\n\n Create a new feature_metadata field, with the most common term (out of term_list) for each feature in experiment\n Note : Adds annotations in-place.\n\n Parameters\n ----------\n use_term_list : list of str or None (optional)\n Use only terms appearing in this list\n None (default) to use all terms\n field_name : str (optional)\n Name of feature_metadata field to store the annotatiosn.\n term_type : str or None (optional)\n type of the annotation summary to get from the database (db specific)\n None to get default type\n Returns\n -------\n exp : Experiment\n '''\n db = _get_database_class(dbname, exp)\n features = exp.feature_metadata.index.values\n term_list = db.get_feature_terms(features, exp=exp, term_type=term_type)\n feature_terms = []\n for cfeature in features:\n term_count = defaultdict(int)\n if len(term_list[cfeature]) == 0:\n feature_terms.append('NA')\n continue\n for cterm in term_list[cfeature]:\n if use_term_list is not None:\n if cterm in use_term_list:\n term_count[cterm] += 1\n else:\n term_count[cterm] += 1\n if len(term_count) == 0:\n max_term = 'other'\n else:\n max_term = max(term_count, key=term_count.get)\n feature_terms.append(max_term)\n exp.feature_metadata[field_name] = feature_terms\n return exp\n\n\nclass Database(ABC):\n def __init__(self, exp=None, database_name=None, methods=['get', 'annotate', 'feature_terms']):\n '''Initialize the database interface\n\n Parameters\n ----------\n exp : Experiment or None (optional)\n The experiment link for the database (if needed)\n database_name : str (optional)\n name of the database\n methods : list of str (optional)\n 'get' if database interface supports get_seq_annotation_strings()\n 'annotate' if database interface supports add_annotation()\n 'enrichment' if database interface supports get_feature_terms()\n '''\n self.database_name = database_name\n self._methods = set(methods)\n self._exp = exp\n\n @property\n def annotatable(self):\n '''True if the database supports adding annotations via the add_annotation() function\n '''\n return 'annotate' in self._methods\n\n @property\n def can_get_feature_terms(self):\n '''True if the database supports getting a dict of terms per feature via the get_feature_terms() function\n '''\n return 'feature_terms' in self._methods\n\n def get_seq_annotation_strings(self, sequence):\n '''Get nice string summaries of annotations for a given sequence\n\n Parameters\n ----------\n sequence : str\n the DNA sequence to query the annotation strings about\n\n Returns\n -------\n shortdesc : list of (dict,str) (annotationdetails,annotationsummary)\n a list of:\n annotationdetails : dict\n 'annotationid' : int, the annotation id in the database\n 'annotationtype : str\n ...\n annotationsummary : str\n a short summary of the annotation\n '''\n logger.debug('Generic function for get_annotation_strings')\n return []\n\n def show_annotation_info(self, annotation):\n '''Show details about the annotation\n\n Parameters\n ----------\n annotation : dict\n keys/values are database specific.\n E.g. See dbBact REST API /annotations/get_annotation for keys / values\n '''\n # open in a new tab, if possible\n logger.debug('Generic function for show annotation info')\n return\n\n def add_annotation(self, features, exp):\n '''Add an entry to the database about a set of features\n\n Parameters\n ----------\n features : list of str\n the features to add to the database\n exp : calour.Experiment\n the experiment where the features are coming from\n\n Returns\n -------\n err : str\n empty if ok, otherwise the error encountered\n '''\n logger.debug('Generic function for add_annotations')\n raise NotImplementedError\n\n def upadte_annotation(self, annotation, exp=None):\n '''Update an existing annotation\n\n Parameters\n ----------\n annotation : dict\n The annotation to update (keys/values are database specific)\n exp : ``Experiment`` (optional)\n The calour experiment from which the annotation is coming from\n Returns\n -------\n str\n empty if ok, otherwise the error encountered\n '''\n logger.debug('Generic function for update_annotation')\n raise NotImplementedError\n\n def delete_annotation(self, annotation_details):\n '''Delete an annotation from the database (if allowed)\n\n Parameters\n ----------\n annotation_details : dict\n The details about the annotation to delete (annotationdetails from get_seq_annotation_strings() )\n Should contain a unique identifier for the annotation (created/used by the database)\n\n Returns\n -------\n str\n empty if ok, otherwise the error encountered\n '''\n logger.debug('Generic function for delete_annotation')\n return 'Not implemented'\n\n def remove_feature_from_annotation(self, features, annotation_details):\n '''remove a feature from the annotation in the database (if allowed)\n\n Parameters\n ----------\n features : list of str\n The feature ids to remove\n annotation_details : dict\n The details about the annotation to delete (annotationdetails from get_seq_annotation_strings() )\n Should contain a unique identifier for the annotation (created/used by the database)\n\n Returns\n -------\n str\n empty if ok, otherwise the error encountered\n '''\n logger.debug('Generic function for remove_features_from_annotation')\n return 'Not implemented'\n\n def get_feature_terms(self, features, exp=None):\n '''Get list of terms per feature\n\n Parameters\n ----------\n features : list of str\n the features to get the terms for\n exp : calour.Experiment (optional)\n not None to store results inthe exp (to save time for multiple queries)\n\n Returns\n -------\n feature_terms : dict of list of str/int\n key is the feature, list contains all terms associated with the feature\n '''\n logger.debug('Generic function for get_feature_terms')\n return {}\n","repo_name":"serenejiang/calour","sub_path":"calour/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":9230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"51"} +{"seq_id":"1451339703","text":"import matplotlib.pyplot as plt\nfrom matplotlib import animation\n\nfrom triple_triple.plot.full_court import draw_court\nfrom triple_triple.nbastats_game_data import hometeam_id, awayteam_id\nfrom triple_triple.startup_data import (\n get_game_id_dict,\n get_df_pos_dist\n)\nfrom triple_triple.player_passing_habits import get_player_court_region_df\nfrom triple_triple.generate_player_positions import (\n get_player_region_prob,\n get_player_simulated_regions,\n # generate_back_court,\n # generate_mid_range,\n # generate_key,\n # generate_out_of_bounds,\n # generate_paint,\n # generate_perimeter,\n # generate_rand_regions,\n get_simulated_coord,\n)\nfrom triple_triple.plot.play_animation import (\n playerid_from_name,\n plot_points,\n)\n\n# TODO: DELETE THIS FILE?????\n\n\ndef sim_animation(player_sim_coord):\n fig = plt.figure(figsize=(15, 9))\n ax = fig.gca()\n ax = draw_court(ax)\n\n def init():\n return scat_player.set_offsets([])\n\n x_coord, y_coord = zip(*player_sim_coord)\n\n playerid = playerid_from_name(player_name)\n team = game_id_dict[playerid][2]\n\n # plot initial points\n if team == hometeam_id:\n color = 'blue'\n elif team == awayteam_id:\n color = 'red'\n\n # label jersey_number\n anno = ax.annotate(\n game_id_dict[playerid][1],\n xy=(x_coord[0] - 0.5, y_coord[0] - 0.4)\n )\n\n scat_player = plot_points(ax, x_coord[0], y_coord[0], color=color)\n\n def update(frame_number):\n scat_player.set_offsets((x_coord[frame_number], y_coord[frame_number]))\n anno.set_position(\n (x_coord[frame_number] - 0.5, y_coord[frame_number] - 0.4)\n )\n\n no_frame = len(x_coord)\n\n anim = animation.FuncAnimation(\n fig,\n func=update,\n init_func=init,\n frames=no_frame,\n interval=200,\n blit=False\n )\n\n return anim\n\n############################\n############################\n\nif __name__ == '__main__':\n game_id_dict = get_game_id_dict()\n df_pos_dist = get_df_pos_dist()\n df_pos_dist_reg = get_player_court_region_df(df_pos_dist)\n\n reg_to_num = {\n 'bench': 0,\n 'back court': 1,\n 'mid-range': 2,\n 'key': 3,\n 'out of bounds': 4,\n 'paint': 5,\n 'perimeter': 6\n }\n\n player_name = 'Chris Bosh'\n df_player_region = list(df_pos_dist_reg[player_name].region)\n player_reg_prob = get_player_region_prob(player_name, df_pos_dist_reg)\n\n player_sim_reg = get_player_simulated_regions(player_reg_prob, num_sim=100)\n\n player_sim_coord = get_simulated_coord(player_sim_reg, 'left')\n\n anim = sim_animation(player_sim_coord)\n plt.show()\n plt.ioff()\n","repo_name":"parul-l/Triple-Triple","sub_path":"triple_triple/plot/animate_simulated_coord.py","file_name":"animate_simulated_coord.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"658693503","text":"import torch\n\nfrom pytorch_gleam.data.collators import NliTextBatchCollator\nfrom pytorch_gleam.data.datasets.base_datasets import BaseDataModule\nfrom pytorch_gleam.data.datasets.kbi_misinfo_stance import KbiMisinfoInferStanceDataset, KbiMisinfoStanceDataset\n\n\nclass NliTextMisinfoStanceDataset(KbiMisinfoStanceDataset):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def __getitem__(self, idx):\n ex = super().__getitem__(idx)\n t_ex = ex[\"t_ex\"]\n p_ex = ex[\"p_samples\"][0]\n p_label, _ = ex[\"relations\"]\n direction = ex[\"direction\"]\n n_ex = ex[\"n_samples\"][0]\n\n label = self._sample_label()\n # pos sample\n if label == 0:\n # 0 - entail\n # 1 - contradict\n # 2 - no relation\n s_label = p_label\n s_ex = p_ex\n # neg_sample\n else:\n # negative examples have no relation\n s_label = 2\n s_ex = n_ex\n if direction == 0:\n token_data = self.tokenizer(t_ex[\"t_text\"], s_ex[\"t_text\"])\n else:\n token_data = self.tokenizer(s_ex[\"t_text\"], t_ex[\"t_text\"])\n labels = [t_ex[\"m_label\"], s_ex[\"m_label\"]]\n stages = [t_ex[\"stage\"], s_ex[\"stage\"]]\n ex = {\n \"t_ex\": ex[\"t_ex\"],\n \"m_ex\": ex[\"m_ex\"],\n \"p_ex\": s_ex,\n \"labels\": labels,\n \"relations\": s_label,\n \"stages\": stages,\n \"input_ids\": token_data[\"input_ids\"],\n \"attention_mask\": token_data[\"attention_mask\"],\n }\n if \"token_type_ids\" in token_data:\n ex[\"token_type_ids\"] = token_data[\"token_type_ids\"]\n\n return ex\n\n def _sample_label(self):\n r = torch.rand(\n size=(1,),\n ).tolist()[0]\n if r < 0.5:\n return 0\n else:\n return 1\n\n\nclass NliTextMisinfoInferStanceDataset(KbiMisinfoInferStanceDataset):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n\n ex = self.examples[idx]\n t_ex = ex[\"t_ex\"]\n m_ex = ex[\"m_ex\"]\n p_ex = ex[\"p_ex\"]\n token_data = self.tokenizer(t_ex[\"t_text\"], p_ex[\"t_text\"])\n\n labels = [t_ex[\"m_label\"], p_ex[\"m_label\"]]\n stages = [t_ex[\"stage\"], p_ex[\"stage\"]]\n # unknown relations\n relations = 2\n ex = {\n \"t_ex\": t_ex,\n \"m_ex\": m_ex,\n \"p_ex\": p_ex,\n \"labels\": labels,\n \"stages\": stages,\n \"relations\": relations,\n \"input_ids\": token_data[\"input_ids\"],\n \"attention_mask\": token_data[\"attention_mask\"],\n }\n if \"token_type_ids\" in token_data:\n ex[\"token_type_ids\"] = token_data[\"token_type_ids\"]\n\n return ex\n\n\nclass NliTextMisinfoStanceDataModule(BaseDataModule):\n def __init__(\n self,\n train_misinfo_path: str = None,\n val_misinfo_path: str = None,\n test_misinfo_path: str = None,\n predict_misinfo_path: str = None,\n *args,\n **kwargs\n ):\n super().__init__(*args, **kwargs)\n\n self.train_misinfo_path = train_misinfo_path\n self.val_misinfo_path = val_misinfo_path\n self.test_misinfo_path = test_misinfo_path\n self.predict_misinfo_path = predict_misinfo_path\n self.pos_samples = 1\n self.neg_samples = 1\n\n if self.train_path is not None and self.train_misinfo_path is not None:\n self.train_dataset = NliTextMisinfoStanceDataset(\n pos_samples=self.pos_samples,\n neg_samples=self.neg_samples,\n tokenizer=self.tokenizer,\n data_path=self.train_path,\n misinfo_path=self.train_misinfo_path,\n )\n if self.val_path is not None and self.val_misinfo_path is not None:\n val_triplet_dataset = NliTextMisinfoStanceDataset(\n pos_samples=self.pos_samples,\n neg_samples=self.neg_samples,\n tokenizer=self.tokenizer,\n data_path=self.val_path,\n misinfo_path=self.val_misinfo_path,\n )\n val_infer_dataset = NliTextMisinfoInferStanceDataset(\n pos_samples=1,\n neg_samples=1,\n tokenizer=self.tokenizer,\n data_path=self.val_path,\n misinfo_path=self.val_misinfo_path,\n )\n\n self.val_dataset = [val_triplet_dataset, val_infer_dataset]\n if self.test_path is not None and self.test_misinfo_path is not None:\n test_triplet_dataset = NliTextMisinfoStanceDataset(\n pos_samples=self.pos_samples,\n neg_samples=self.neg_samples,\n tokenizer=self.tokenizer,\n data_path=self.test_path,\n misinfo_path=self.test_misinfo_path,\n )\n test_infer_dataset = NliTextMisinfoInferStanceDataset(\n pos_samples=1,\n neg_samples=1,\n tokenizer=self.tokenizer,\n data_path=[self.val_path, self.test_path],\n misinfo_path=self.test_misinfo_path,\n )\n\n self.test_dataset = [test_triplet_dataset, test_infer_dataset]\n if self.predict_path is not None and self.predict_misinfo_path is not None:\n self.predict_dataset = NliTextMisinfoInferStanceDataset(\n pos_samples=1,\n neg_samples=1,\n tokenizer=self.tokenizer,\n data_path=[self.val_path, self.predict_path],\n misinfo_path=self.predict_misinfo_path,\n )\n\n def create_collator(self):\n return NliTextBatchCollator(\n max_seq_len=self.max_seq_len,\n use_tpus=self.use_tpus,\n )\n","repo_name":"Supermaxman/pytorch-gleam","sub_path":"pytorch_gleam/data/datasets/nli_text_stance.py","file_name":"nli_text_stance.py","file_ext":"py","file_size_in_byte":5934,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"31476092081","text":"'''\nAuthor: doumu\nDate: 2021-09-27 17:44:05\nLastEditTime: 2022-02-28 21:12:00\nLastEditors: ChHanXiao\nDescription: \nFilePath: /D2/projects/NanoDet/modeling/nanodet.py\n'''\nimport logging\nimport math\nimport numpy as np\nimport torch\nimport copy\nfrom torch import nn, Tensor\nfrom typing import List, Dict, Tuple\n\nfrom detectron2.config import configurable\nfrom detectron2.layers import ShapeSpec, Conv2d\nfrom detectron2.modeling.meta_arch.build import META_ARCH_REGISTRY\nfrom detectron2.modeling.backbone import Backbone\nfrom detectron2.structures import ImageList, Instances, Boxes\nfrom detectron2.utils.events import get_event_storage\nfrom detectron2.data.detection_utils import convert_image_to_rgb\nfrom detectron2.modeling.postprocessing import detector_postprocess\n\nfrom .backbone import build_backbone\nfrom .fpn import build_fpn\nfrom .head import build_head\n\n__all__ = [\"NanoDet\",\"NanoDetPlus\"]\n\n\ndef warp_boxes(boxes, M, width, height):\n n = len(boxes)\n if n:\n # warp points\n xy = np.ones((n * 4, 3))\n xy[:, :2] = boxes[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1\n xy = xy @ M.T # transform\n xy = (xy[:, :2] / xy[:, 2:3]).reshape(n, 8) # rescale\n # create new boxes\n x = xy[:, [0, 2, 4, 6]]\n y = xy[:, [1, 3, 5, 7]]\n xy = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T\n # clip boxes\n xy[:, [0, 2]] = xy[:, [0, 2]].clip(0, width)\n xy[:, [1, 3]] = xy[:, [1, 3]].clip(0, height)\n return xy.astype(np.float32)\n else:\n return boxes\n\n\n@META_ARCH_REGISTRY.register()\nclass NanoDet(nn.Module):\n\n @configurable\n def __init__(\n self, \n *,\n backbone: nn.Module,\n fpn: nn.Module,\n head: nn.Module,\n pixel_mean,\n pixel_std,\n vis_period=0,\n input_format=\"BGR\",\n ):\n super().__init__()\n self.backbone = backbone\n self.fpn = fpn\n self.head = head\n self.vis_period = vis_period\n self.input_format = input_format\n self.visthresh = 0.3\n self.register_buffer(\"pixel_mean\", torch.tensor(pixel_mean).view(-1, 1, 1), False)\n self.register_buffer(\"pixel_std\", torch.tensor(pixel_std).view(-1, 1, 1), False)\n self.iter = 0\n \n @classmethod\n def from_config(cls, cfg):\n model_yml_file = cfg.MODEL.YML\n from .util import cfg_s, load_config\n load_config(cfg_s, model_yml_file)\n\n backbone = build_backbone(cfg_s.model.arch.backbone)\n fpn = build_fpn(cfg_s.model.arch.fpn)\n head = build_head(cfg_s.model.arch.head)\n \n return{\n \"backbone\": backbone,\n \"fpn\": fpn,\n \"head\": head,\n \"pixel_mean\": cfg.MODEL.PIXEL_MEAN,\n \"pixel_std\": cfg.MODEL.PIXEL_STD,\n \"vis_period\": cfg.VIS_PERIOD,\n \"input_format\": cfg.INPUT.FORMAT,\n }\n \n @property\n def device(self):\n return self.pixel_mean.device\n\n def forward(self, batched_inputs):\n if torch.onnx.is_in_onnx_export():\n return self.forward_(batched_inputs)\n\n images = self.preprocess_image(batched_inputs)\n features = self.backbone(images.tensor)\n x = self.fpn(features)\n preds = self.head(x)\n gt_meta=dict()\n gt_meta['img'] = images.tensor\n\n if self.training:\n # 转成原loss计算格式\n gt_instances = [x[\"instances\"]for x in batched_inputs]\n targets_boxes = []\n targets_classes = []\n for i, gt_per_image in enumerate(gt_instances):\n boxes=[]\n classes=[]\n if len(gt_per_image) > 0:\n boxes=gt_per_image.gt_boxes.tensor.clone().numpy()\n classes=gt_per_image.gt_classes.clone().numpy()\n else:\n boxes = np.zeros((0, 4), dtype=np.float32)\n classes = np.array([], dtype=np.int64)\n targets_boxes.append(boxes)\n targets_classes.append(classes)\n gt_meta['gt_bboxes'] = targets_boxes\n gt_meta['gt_labels'] = targets_classes\n loss_states = self.head.loss(preds, gt_meta)\n return loss_states\n else:\n results_infer = self.head.post_process(preds, gt_meta)\n\n raw_size_ = []\n warp_matrix_ = []\n for input_per_image in batched_inputs:\n height = input_per_image.get(\"height\")\n width = input_per_image.get(\"width\")\n warp_matrix = input_per_image.get(\"warp_matrix\", np.eye(3))\n raw_size_.append((width,height))\n warp_matrix_.append(warp_matrix)\n\n results = self.process_inference(results_infer, images.image_sizes, raw_size_, warp_matrix_)\n processed_results = []\n for results_per_image in results:\n processed_results.append({\"instances\": results_per_image})\n return processed_results\n\n def process_inference(self, out, image_sizes, raw_size_, warp_matrix_):\n assert len(out) == len(image_sizes) == len(raw_size_) == len(warp_matrix_)\n results_all: List[Instances] = []\n # Statistics per image\n for si, (pred, img_size, raw_size, warp_matrix) in enumerate(zip(out, image_sizes, raw_size_, warp_matrix_)):\n det_bboxes, det_labels = pred\n if len(det_bboxes) == 0:\n continue\n det_bboxes = det_bboxes.detach().cpu().numpy()\n predc = det_labels.clone()\n det_bboxes[:, :4] = warp_boxes(det_bboxes[:, :4], np.linalg.inv(warp_matrix), raw_size[0], raw_size[1])\n det_bboxes = torch.from_numpy(det_bboxes).to(det_labels.device)\n # Predictions\n predn = det_bboxes.clone()\n # Predn shape [ndets, 6] of format [xyxy, conf, cls] relative to the input image size\n result = Instances((raw_size[1], raw_size[0]))\n result.pred_boxes = Boxes(predn[:, :4]) # TODO: Check if resizing needed\n result.scores = predn[:, 4]\n result.pred_classes = predc # TODO: Check the classes\n results_all.append(result)\n return results_all\n \n def preprocess_image(self, batched_inputs: Tuple[Dict[str, Tensor]]):\n \"\"\"\n Normalize, pad and batch the input images.\n \"\"\"\n images = [x[\"image\"].to(self.device) for x in batched_inputs]\n images = [(x - self.pixel_mean) / self.pixel_std for x in images]\n images = ImageList.from_tensors(images, 0)\n return images\n\n @torch.no_grad()\n def forward_(self, batched_inputs):\n features = self.backbone(batched_inputs)\n x = self.fpn(features)\n preds = self.head(x)\n return preds\n\n@META_ARCH_REGISTRY.register()\nclass NanoDetPlus(NanoDet):\n @configurable\n def __init__(\n self, \n *,\n backbone: nn.Module,\n fpn: nn.Module,\n aux_head: nn.Module,\n head: nn.Module,\n detach_iter,\n pixel_mean,\n pixel_std,\n vis_period=0,\n input_format=\"BGR\",\n ):\n super(NanoDetPlus, self).__init__(\n backbone=backbone,\n fpn=fpn,\n head=head,\n pixel_mean=pixel_mean,\n pixel_std=pixel_std,\n vis_period=vis_period,\n input_format=input_format,\n )\n self.aux_fpn = copy.deepcopy(self.fpn)\n self.aux_head = aux_head\n self.detach_iter = detach_iter\n self.visthresh = 0.3\n self.register_buffer(\"pixel_mean\", torch.tensor(pixel_mean).view(-1, 1, 1), False)\n self.register_buffer(\"pixel_std\", torch.tensor(pixel_std).view(-1, 1, 1), False)\n\n \n @classmethod\n def from_config(cls, cfg):\n model_yml_file = cfg.MODEL.YML\n from .util import cfg_s, load_config\n load_config(cfg_s, model_yml_file)\n\n backbone = build_backbone(cfg_s.model.arch.backbone)\n fpn = build_fpn(cfg_s.model.arch.fpn)\n head = build_head(cfg_s.model.arch.head)\n aux_head = build_head(cfg_s.model.arch.aux_head)\n return{\n \"backbone\": backbone,\n \"fpn\": fpn,\n \"aux_head\": aux_head,\n \"head\": head,\n \"detach_iter\": cfg.SOLVER.DETACH_ITER,\n \"pixel_mean\": cfg.MODEL.PIXEL_MEAN,\n \"pixel_std\": cfg.MODEL.PIXEL_STD,\n \"vis_period\": cfg.VIS_PERIOD,\n \"input_format\": cfg.INPUT.FORMAT,\n }\n def forward(self, batched_inputs):\n # for batched_input in batched_inputs:\n # images = batched_input[\"image\"]\n # import cv2\n # img = images.numpy().transpose(1,2,0)\n # cv2.imwrite('filename.jpg', img)\n # print(images.shape)\n\n # for batched_input in batched_inputs:\n # images = batched_input[\"image\"]\n # from detectron2.data import detection_utils as utils\n # from detectron2.utils.visualizer import Visualizer\n # import cv2\n # img = batched_input[\"image\"].permute(1, 2, 0).cpu().detach().numpy()\n # target_fields = batched_input[\"instances\"].get_fields()\n # img = utils.convert_image_to_rgb(img, self.input_format)\n # visualizer = Visualizer(img)\n # vis = visualizer.overlay_instances(boxes=target_fields.get(\"gt_boxes\", None),)\n # cv2.imwrite('filename.jpg', vis.get_image()[:, :, ::-1])\n if torch.onnx.is_in_onnx_export():\n return self.forward_(batched_inputs)\n\n images = self.preprocess_image(batched_inputs)\n features = self.backbone(images.tensor)\n fpn_feat = self.fpn(features)\n preds = self.head(fpn_feat)\n\n gt_meta=dict()\n gt_meta['img'] = images.tensor\n\n if self.training:\n if self.iter >= self.detach_iter:\n aux_fpn_feat = self.aux_fpn([f.detach() for f in features])\n dual_fpn_feat = (\n torch.cat([f.detach(), aux_f], dim=1)\n for f, aux_f in zip(fpn_feat, aux_fpn_feat)\n )\n else:\n aux_fpn_feat = self.aux_fpn(features)\n dual_fpn_feat = (\n torch.cat([f, aux_f], dim=1) \n for f, aux_f in zip(fpn_feat, aux_fpn_feat)\n )\n aux_head_out = self.aux_head(dual_fpn_feat)\n \n # 转成原loss计算格式\n gt_instances = [x[\"instances\"]for x in batched_inputs]\n targets_boxes = []\n targets_classes = []\n for i, gt_per_image in enumerate(gt_instances):\n boxes=[]\n classes=[]\n if len(gt_per_image) > 0:\n boxes=gt_per_image.gt_boxes.tensor.clone().numpy()\n classes=gt_per_image.gt_classes.clone().numpy()\n else:\n boxes = np.zeros((0, 4), dtype=np.float32)\n classes = np.array([], dtype=np.int64)\n targets_boxes.append(boxes)\n targets_classes.append(classes)\n gt_meta['gt_bboxes'] = targets_boxes\n gt_meta['gt_labels'] = targets_classes\n loss_states = self.head.loss(preds, gt_meta, aux_preds=aux_head_out)\n\n return loss_states\n else:\n results_infer = self.head.post_process(preds, gt_meta)\n raw_size_ = []\n warp_matrix_ = []\n for input_per_image in batched_inputs:\n height = input_per_image.get(\"height\")\n width = input_per_image.get(\"width\")\n warp_matrix = input_per_image.get(\"warp_matrix\", np.eye(3))\n raw_size_.append((width,height))\n warp_matrix_.append(warp_matrix)\n\n results = self.process_inference(results_infer, images.image_sizes, raw_size_, warp_matrix_)\n processed_results = []\n for results_per_image in results:\n processed_results.append({\"instances\": results_per_image})\n return processed_results\n","repo_name":"ChHanXiao/D2","sub_path":"projects/NanoDet/modeling/nanodet.py","file_name":"nanodet.py","file_ext":"py","file_size_in_byte":12211,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"51"} +{"seq_id":"32316265158","text":"import cv2 \r\nimport numpy as np \r\n\r\nq = cv2.imread(\"Queen1.jpg\")\r\ns= cv2.imread(\"sor.jpg\")\r\nq = cv2.resize(q , [230 , 300])\r\ns= cv2.resize(s , [230 , 300])\r\nq = cv2.cvtColor(q , cv2.COLOR_BGR2GRAY)\r\ns = cv2.cvtColor(s , cv2.COLOR_BGR2GRAY)\r\n\r\nlookUpTable = np.empty((1,256), np.uint8)\r\nfor i in range(256):\r\n lookUpTable[0,i] = np.clip(pow(i / 255.0, 2) * 255.0, 0, 255)\r\nq = cv2.LUT(q, lookUpTable)\r\n\r\nlookUpTable = np.empty((1,256), np.uint8)\r\nfor i in range(256):\r\n lookUpTable[0,i] = np.clip(pow(i / 255.0, 0.6) * 255.0, 0, 255)\r\ns = cv2.LUT(s, lookUpTable)\r\n\r\n\r\nq = q.astype(np.float32)\r\ns = s.astype(np.float32)\r\na,b,c= [0,0,0] \r\nimg_list = []\r\n\r\nfor i in range(3):\r\n print(a , b , c)\r\n r = ( q*((1+a)/(2+c)) + s*((1+b)/(2+c)) )\r\n if i==0 :\r\n c+=1\r\n a+=1\r\n if i==1 :\r\n a-=1\r\n b+=1\r\n r=r.astype(np.uint8)\r\n img_list.append(r)\r\n cv2.imwrite(f\"morph_{i+1}.jpg\" , r) \r\n\r\nfor i in range(1,4):\r\n img_list.append(cv2.imread(f\"morph_{i}.jpg\"))\r\n\r\ns=s.astype(np.uint8)\r\nq=q.astype(np.uint8)\r\nresult = cv2.hconcat([q,img_list[1],img_list[0],img_list[2],s])\r\n\r\ncv2.imshow(\"Queen + Sori\" , result)\r\ncv2.imwrite(\"face_morphing_result.jpg\" , result )\r\ncv2.waitKey()\r\n","repo_name":"kiana-jahanshid/Image-Processing","sub_path":"Assignment_29/1_face_morphing.py","file_name":"1_face_morphing.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"51"} +{"seq_id":"27613642131","text":"class Singleton:\n _instance = None\n\n def __new__(cls, *args, **kwargs):\n if not cls._instance:\n cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)\n return cls._instance\n\n# Usage\nsingleton1 = Singleton()\nsingleton2 = Singleton()\n\nprint(singleton1 == singleton2) # True\n\n\ndef singleton(cls):\n instances = {}\n def get_instance(*args, **kwargs):\n if cls not in instances:\n instances[cls] = cls(*args, **kwargs)\n return instances[cls]\n return get_instance\n\n@singleton\nclass MySingletonClass:\n pass\n\n# Usage\nsingleton1 = Singleton()\nsingleton2 = Singleton()\n\nprint(singleton1 == singleton2) # True\n","repo_name":"pablocuestagarcia/myLearnings","sub_path":"design_patterns/creational_patterns/singleton.py","file_name":"singleton.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"73724707359","text":"import spotipy\nfrom spotipy.oauth2 import SpotifyClientCredentials\nimport csv\n\n# Connect to Spotify - Create a web app at https://developer.spotify.com/dashboard/. Then paste client id & secret below\nspotify = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id='CLIENT ID',client_secret='CLIENT SECRET'))\n\n\n# Set up the output - just paste your file path in line 10. Change nothing else\nwith open('PASTE YOUR OUTPUT FILEPATH', 'w', newline='') as csv_output:\n csv_writer = csv.writer(csv_output, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n csv_writer.writerow([\"spotify_track_id\", \"danceability\", \"energy\", \"key\", \"loudness\", \"mode\", \"speechiness\", \"acousticness\", \"instrumentalness\", \"liveness\", \"valence\", \"tempo\", \"time_signature\"])\n\n# Paste the input file path with the spotify_id column called 'spotify_track_id' or change the variable in line 21\n i = 0\n with open('PASTE YOUR INPUT FILEPATH') as csv_input:\n csv_reader = csv.DictReader(csv_input, delimiter=',')\n for song in csv_reader:\n i += 1\n\n spotify_track_id = song[\"spotify_track_id\"]\n\n results = spotify.audio_features(spotify_track_id)\n if results[0] is not None:\n track = results[0]\n danceability = track[\"danceability\"]\n energy = track[\"energy\"]\n key = track[\"key\"]\n loudness = track[\"loudness\"]\n mode = track[\"mode\"]\n speechiness = track[\"speechiness\"]\n acousticness = track[\"acousticness\"]\n instrumentalness = track[\"instrumentalness\"]\n liveness = track[\"liveness\"]\n valence = track[\"valence\"]\n tempo = track[\"tempo\"]\n time_signature = track[\"time_signature\"]\n else:\n danceability = \"\"\n energy = \"\"\n key = \"\"\n loudness = \"\"\n mode = \"\"\n speechiness = \"\"\n acousticness = \"\"\n instrumentalness = \"\"\n liveness = \"\"\n valence = \"\"\n tempo = \"\"\n time_signature = \"\"\n\n row_to_write = [spotify_track_id, danceability, energy, key, loudness, mode, speechiness, acousticness, instrumentalness, liveness, valence, tempo, time_signature]\n\n if i % 100 == 0:\n print(i)\n print(row_to_write)\n\n csv_writer.writerow(row_to_write)","repo_name":"HipsterVizNinja/random-data","sub_path":"Scripts/spotify-song-attributes-from-id.py","file_name":"spotify-song-attributes-from-id.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"51"} +{"seq_id":"17671539238","text":"#ler 5 valores, guardar em UMA lista;\n#Posicionar os valores na posição correta sem usar o sort();\n#Mostrar os a lista ordernada;\n\nvalores = []\n\nfor c in range (0, 5):\n v0 = int(input('\\nDigite um valor: '))\n if c == 0 or v0 > valores[-1]:\n valores.append(v0)\n print(f'{v0} foi adicionado na ultima posição da lista')\n else:\n pos = 0\n while pos < len(valores):\n if v0 <= valores[pos]:\n valores.insert(pos, v0)\n print(f'{v0} foi adicionado na posição {pos} da lista.')\n break\n pos += 1\n\nprint(f'\\nOs valores digitados em ordem crescente ficam nessa ordem: {valores}.\\n')\n\n","repo_name":"IgorGhabriel/aulas_python","sub_path":"exec lista/ex080.py","file_name":"ex080.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"10330946309","text":"from curses.ascii import SP\nimport math\nclass Solution:\n #naive solution\n def isPowerOfFour_1(self, n):\n \"\"\"\n type: int\n rtpye: bool \n \"\"\"\n target, exp = 0, 0\n while target < n: \n target = 4 ** exp \n exp +=1 \n if target == n: return True\n return False\n\n def isPowerOfFour_2(self, n):\n \"\"\"\n type: int\n rtpye: bool \n \"\"\"\n return n > 0 and not n & (n - 1) and len(bin(n)) % 2\n\n def isPowerOfFour_3(self, n):\n \"\"\"\n type: int\n rtpye: bool \n \"\"\"\n return n > 0 and math.log(n, 4).is_integer()\n\nif __name__ == '__main__':\n s = Solution()\n print(s.isPowerOfFour_1(16)) #prints True\n print(s.isPowerOfFour_2(5)) #prints False\n print(s.isPowerOfFour_3(1)) #prints True","repo_name":"jeewonkoo/LeetCode","sub_path":"python3/PowerOfFour.py","file_name":"PowerOfFour.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"38819940072","text":"\"\"\"Image feature extraction.\"\"\"\n# Disable no-member for torch.\n# pylint: disable=E1101\nimport os\nimport sys\nimport json\nimport time\nimport argparse\nimport h5py\nimport torch\nfrom model import FullBiLSTM as inception\nfrom model_vgg import FullBiLSTM as vgg\nfrom model_squeezenet import FullBiLSTM as squeezenet\nfrom datasets import PolyvoreDataset, collate_seq\nfrom evaluation import Evaluation\n\n# Disable too-many-locals.\n# pylint: disable=R0914\ndef get_features(model_name, feats_filename, model_type):\n \"\"\"Main function for feature extraction.\"\"\"\n\n if not os.path.exists(feats_filename):\n\n batch_size = 1\n\n if model_type == 'inception':\n model = inception(512, 512, 2480, batch_first=True, dropout=0.7)\n elif model_type == 'vgg':\n model = vgg(512, 512, 2480, batch_first=True, dropout=0.7)\n elif model_type == 'squeezenet':\n model = squeezenet(512, 512, 2480, batch_first=True, dropout=0.7)\n else:\n print(\"Please, specify a valid model type: inception, vgg or squeezenet\"\\\n \"instead of %s\" % model_type)\n return\n\n evaluator = Evaluation(model, model_type, model_name, 'data/images',\n batch_first=True, cuda=True)\n\n json_filenames = {'train': 'train_no_dup.json',\n 'test': 'test_no_dup.json',\n 'val': 'valid_no_dup.json'}\n\n img_dir, json_dir = 'data/images', 'data/label'\n dataloaders = {x: torch.utils.data.DataLoader(\n PolyvoreDataset(os.path.join(json_dir, json_filenames[x]), img_dir,\n img_transform=None, txt_transform=None),\n batch_size=batch_size,\n shuffle=False, num_workers=4,\n collate_fn=collate_seq)\n for x in ['test']}\n\n test_files = json.load(open(os.path.join(json_dir, json_filenames['test'])))\n\n filenames = []\n features = torch.Tensor().cuda()\n\n for i, (test_file, batch) in enumerate(zip(test_files, dataloaders['test'])):\n if i == 0:\n tic = time.time()\n sys.stdout.write(\"%d/%d sets - %.2f secs remaining\\r\" % (i, len(test_files),\n (time.time() - tic)/\n (i + 1)*(len(test_files) - i)))\n sys.stdout.flush()\n set_id = test_file['set_id']\n im_idxs = [x['index'] for x in test_file['items']]\n im_feats = evaluator.get_img_feats(batch[0]['images'])\n for idx in im_idxs:\n filenames.append(set_id + '_' + str(idx))\n features = torch.cat((features, im_feats.data))\n for ignored in batch[0]['ignored']:\n filenames.remove(ignored)\n if not os.path.exists(os.path.dirname(feats_filename)):\n os.makedirs(os.path.dirname(feats_filename))\n filenames = [n.encode(\"ascii\", \"ignore\") for n in filenames]\n savefile = h5py.File(feats_filename, 'w')\n savefile.create_dataset('filenames', data=filenames)\n savefile.create_dataset('features', data=features)\n savefile.close()\n\nif __name__ == '__main__':\n\n PARSER = argparse.ArgumentParser()\n PARSER.add_argument('--model_path', '-m', type=str, help='path to the model', default='')\n PARSER.add_argument('--model_type', '-t', type=str, help='type of the model: inception, vgg or squeezenet',\n default='inception')\n PARSER.add_argument('--save_path', '-sp', type=str,\n help='path to save the features', default='')\n ARGS = PARSER.parse_args()\n\n MODEL_NAME = ARGS.model_path\n FEATS_FILENAME = ARGS.save_path\n MODEL_TYPE = ARGS.model_type\n\n get_features(MODEL_NAME, FEATS_FILENAME, MODEL_TYPE)\n","repo_name":"arubior/bilstm","sub_path":"bilstm/src/get_features.py","file_name":"get_features.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"51"} +{"seq_id":"2531842715","text":"\"\"\"Ex02 - One Short Wordle - An improvement of Ex01 where the player will have to guess the secret word.\"\"\"\n\n__author__ = \"730476155\"\n\n# this part of the program lets the user guess and try again if the user inputs an incorrect number of letters\n# this part of the program also allows for any word to be replaced for the secret_word and the program will still run accordingly\nsecret_word: str = \"python\"\nguess: str = input(f\"What is your {len(secret_word)}-letter guess? \")\nwhile len(secret_word) != len(guess):\n guess = input(f\"That was not {len(secret_word)}! Try again: \")\n\ni: int = 0\nresulting_emoji: str = \" \"\nWHITE_BOX: str = \"\\U00002B1C\"\nGREEN_BOX: str = \"\\U0001F7E9\"\nYELLOW_BOX: str = \"\\U0001F7E8\"\n\nto_keep_track_of: bool = False\nalternate_indices: int = 0\n\n# checking for if the index of the guess matches the index of the secret_word. If so changes the resulting_emoji changes to green\n# if the current index does not match the index of the secret_word but is somewhere else in the secret_word, the resulting_emoji will change to yellow\n# if the current index is no where found in the secret_word, the resulting_emoji will be white\n\nwhile i < len(secret_word):\n if guess[i] == secret_word[i]:\n resulting_emoji = resulting_emoji + GREEN_BOX \n else:\n while to_keep_track_of is False and alternate_indices < len(secret_word):\n if guess[i] == secret_word[alternate_indices]:\n resulting_emoji = resulting_emoji + YELLOW_BOX\n to_keep_track_of = True\n alternate_indices = alternate_indices + 1\n if to_keep_track_of is False:\n resulting_emoji = resulting_emoji + WHITE_BOX\n to_keep_track_of = False\n alternate_indices = 0\n \n i = i + 1\nprint(resulting_emoji)\n\nif secret_word == guess:\n print(\"Woo! You got it!\")\nelse:\n if len(secret_word) == len(guess) and secret_word != guess:\n print(\"Not quite. Play again soon!\")","repo_name":"rkhetan12/comp110-22s-workspace","sub_path":"exercises/ex02_one_shot_wordle.py","file_name":"ex02_one_shot_wordle.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"51"} +{"seq_id":"15151614565","text":"# -*- coding:UTF-8 -*-\nimport time\nimport os\nimport commands\nimport subprocess\n\nimport pika\n\nparameters = pika.URLParameters('amqp://hardchain:pswHd@localhost:5672/%2F')\n\nconnection = pika.BlockingConnection(parameters)\nchannelr = connection.channel()\n#声明queue\nchannelr.queue_declare(queue='electron3', durable=False) # 若声明过���则换一个名字\n#n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.\nchannelr.basic_publish(exchange='xxx',\n routing_key='electron3',\n body='test',\n properties=pika.BasicProperties(\n delivery_mode=2, # make message persistent\n )\n )\n\nprint(\" [x] Sent 'Hello World!'\")\nconnection.close()\n\n","repo_name":"yuyongpeng/raspberrypi","sub_path":"test-mq.py","file_name":"test-mq.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"26766399774","text":"import random\nimport time\nimport os\nimport winsound\n\n#limpar tela\n\n\ndef clean():\n os.system('cls')\n\n\n#input\nclean()\nir = input(\"digite sim para começar: \")\n#escolher aleatório (100%)\nif ir == str('sim'):\n r = random.randint(1, 101)\n print('carregando..')\n time.sleep(1)\n clean()\nelse:\n print('oh..')\n\n#SETUP\n#matérias\n\n\ndef portugues(): # 20%\n print('português!!')\n time.sleep(0.6)\n Mpt = ['semântica e figuras', 'classificações', 'classificações',\n'orações', 'concordância', 'concordância']\n print(f'a matéria escolhida foi: {random.choice(Mpt)}')\n\n\ndef matematica(): # 30%\n print('matemática!!')\n time.sleep(0.6)\n Mmat = ['conjunto', 'números', 'cálculo algébrico', 'cálculo algébrico',\n 'equações', 'geometria', 'geometria', ]\n print(f'a matéria escolhida foi: {random.choice(Mmat)}')\n\n\ndef ciencias(): # 15%\n print('ciências!!')\n time.sleep(0.6)\n Mcien = ['ecologia', 'ecologia', 'zoologia', 'botânica', 'física', 'física',\n'química', 'química']\n print(f'a matéria escolhida foi: {random.choice(Mcien)}')\n\n\ndef historia(): # 15%\n print('história!!')\n time.sleep(0.6)\n Mhist = ['antiguidade clássica', 'idade média', 'idade média', 'idade moderna',\n'idade moderna', 'mundo contemporâneo', 'história do Brasil',\n'história do Brasil']\n print(f'a matéria escolhida foi: {random.choice(Mhist)}')\n\n\ndef redacao(): # 20%\n print('redação!!')\n\n\n#if's\nif r >= 1 and r <= 20:\n portugues()\nelif r > 20 and r <= 50:\n matematica()\nelif r > 50 and r <= 65:\n ciencias()\nelif r > 65 and r <= 80:\n historia()\nelif r > 80 and r <= 100:\n redacao()\nelse:\n print(f\"erro, o número é {r}.\")\n\n#POMODORO\n\n\ndef countdown(t):\n\n while t > 0:\n mins, secs = divmod(t, 60)\n timer = '{:02d}:{:02d}'.format(mins, secs)\n print(timer, end=\"\\r\")\n time.sleep(1)\n t -= 1\n if t == 0:\n print('00:00')\n winsound.Beep(2500, 1000)\n\ndef pomodoro():\n tempo = int(input('quanto tempo (em minutos?): ')) * 60\n for i in range(3):\n print('\\n\\nestude!')\n countdown(tempo)\n print('\\n\\nlanchinho!!')\n countdown(10*60)\n\n#display\ntime.sleep(0.5)\nprint('bons estudos!! ^^')\ntime.sleep(0.5)\ninput('aperte qualquer tecla para começar o pomodoro/cronometragem: ')\npomodoro()\n#add pause e escrever materia","repo_name":"pixarpixel/python2","sub_path":"personal/randomish.py","file_name":"randomish.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"73861048477","text":"class SelectionEncoder:\n def __init__(self, args_handler):\n \"\"\"\n selection encoding and decoding for algorithms\n :param args_handler: A object for handling commands and flags\n \"\"\"\n self.flags = args_handler.flags\n\n def get_selected_flags(self, flag_sequence):\n \"\"\"\n Get the selected flags\n :param flag_sequence: list[int] a flag sequence with 0s and 1s indicate the flags enabled or not\n :return: list[String] a list of selected flags name\n \"\"\"\n selected_flags = []\n for index, value in enumerate(flag_sequence):\n if value == 1:\n selected_flags.append(self.flags[index])\n return selected_flags\n\n def generate_flag_sequence_from_decimal(self, decimal_number):\n \"\"\"\n generate a list of 0s and 1s that stands for the flags sequence for the actual flag sequence generation from decimal number\n :param decimal_number:\n :return: list[int] A list of 0s and 1s that stands for the flags sequence for the actual flag sequence generation\n \"\"\"\n binary_sequence = bin(decimal_number).replace('0b', '')\n # Use 0s to fill up the remaining part, since the 0b has been replaced\n binary_sequence = '0' * (len(self.flags) - len(binary_sequence)) + binary_sequence\n sequence_lst = []\n for binary_num in binary_sequence:\n if binary_num == '1':\n sequence_lst.append(1)\n else:\n sequence_lst.append(0)\n\n return sequence_lst","repo_name":"ChenglinW/PRJ","sub_path":"src/selection_encoding.py","file_name":"selection_encoding.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"6005517651","text":"import sys\n\nsys.stdin = open('input.txt', 'r')\n\n\ndef find_num(now_node):\n global n, num_list\n if 2 * now_node < n:\n return find_num(2 * now_node) + find_num(2 * now_node + 1)\n elif 2 * now_node == n:\n return num_list[n]\n else:\n return num_list[now_node]\n\n\nT = int(input())\nfor test_case in range(1, T + 1):\n n, m, l = map(int, input().split())\n num_list = [0] * (n+1)\n for _ in range(m):\n ind, num = map(int, input().split())\n num_list[ind] = num\n print('#{} {}'.format(test_case, find_num(l)))","repo_name":"ohsean93/algo","sub_path":"10월/10_11/5178.py","file_name":"5178.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"17510257603","text":"from django_auth_ldap3.conf import settings\n\nfrom django.contrib.auth.models import Group\nfrom django.contrib.auth import get_user_model\nfrom ldap3.core.exceptions import LDAPSocketOpenError\nimport hashlib\nimport ldap3\nimport logging\nimport ssl\n\nUser = get_user_model()\n\nlogger = logging.getLogger('django_auth_ldap3')\n\nclass LDAPUser(object):\n \"\"\"\n A class representing an LDAP user returned from the directory.\n \"\"\"\n\n connection = None\n _attrib_keys = [settings.UID_ATTRIB, 'cn', 'givenName', 'sn', 'mail']\n\n def __init__(self, connection, attributes):\n self.connection = connection\n for k, v in attributes.items():\n # Flatten any lists into their first element\n if type(v) == list and len(v) >= 1:\n v = v[0]\n setattr(self, k, v)\n\n # Set any missing attributes\n for k in self._attrib_keys:\n if not hasattr(self, k):\n setattr(self, k, '')\n\n def __str__(self):\n return self.username\n\n @property\n def username(self):\n return getattr(self, settings.UID_ATTRIB)\n\nclass LDAPBackend(object):\n \"\"\"\n An authentication backend for LDAP directories.\n \"\"\"\n\n backend = None\n\n def __init__(self):\n tls_config = None\n\n if settings.TLS:\n tls_opts = {\n 'validate': ssl.CERT_REQUIRED if settings.TLS_VALIDATE else ssl.CERT_NONE\n }\n\n if settings.TLS_CA_CERTS:\n tls_opts['ca_certs_file'] = settings.TLS_CA_CERTS\n\n if settings.TLS_PRIVATE_KEY:\n tls_opts['local_private_key_file'] = settings.TLS_PRIVATE_KEY\n\n if settings.TLS_LOCAL_CERT:\n tls_opts['local_certificate_file'] = settings.TLS_LOCAL_CERT\n\n tls_config = ldap3.Tls(**tls_opts)\n\n self.backend = ldap3.Server(settings.URI, use_ssl=settings.TLS, tls=tls_config)\n\n def __del__(self):\n # TODO: disconnect?\n pass\n\n def authenticate(self, username=None, password=None):\n \"\"\"\n Required for Django auth. Authenticate the uesr against the LDAP\n backend and populate the local User model if this is the first\n time the user has authenticated.\n \"\"\"\n\n # Authenticate against the LDAP backend and return an LDAPUser.\n ldap_user = self.retrieve_ldap_user(username, password)\n if ldap_user is None:\n logger.debug('Authentication failed for {}'.format(ldap_user))\n return None\n\n # If we get here, authentication is successful and we have an LDAPUser\n # instance populated with the user's attributes. We still need to check\n # group membership and populate a local User model.\n\n # Check LDAP group membership before creating a local user. The default\n # is '*' so any user can log in.\n if not self.check_group_membership(ldap_user, settings.LOGIN_GROUP):\n logger.debug('Failed group membership test: {} !memberOf {}'.format(ldap_user, settings.LOGIN_GROUP))\n return None\n\n # Check if this user is part of the admin group.\n admin = False\n if settings.ADMIN_GROUP:\n admin = self.check_group_membership(ldap_user, settings.ADMIN_GROUP)\n\n # Get or create the User object in Django's auth, populating it with\n # fields from the LDAPUser. Note we set the password to a random hash\n # as authentication should never occur directly off this user.\n django_user = User.objects.filter(username__iexact=username)\n if not django_user:\n # Create new user. We use `ldap_user.username` here as it is the\n # case-sensitive version\n django_user = User(username=ldap_user.username,\n password=hashlib.sha1().hexdigest(),\n first_name=ldap_user.givenName,\n last_name=ldap_user.sn,\n email=ldap_user.mail,\n is_superuser=False,\n is_staff=admin,\n is_active=True\n )\n django_user.save()\n else:\n # If the user wasn't created, update its fields from the directory.\n django_user = django_user[0]\n django_user.first_name = ldap_user.givenName\n django_user.last_name = ldap_user.sn\n django_user.email = ldap_user.mail\n django_user.is_staff = admin\n django_user.save()\n\n self.update_group_membership(ldap_user, django_user)\n\n return django_user\n\n def get_user(self, user_id):\n \"\"\"\n Required for Django auth.\n \"\"\"\n try:\n return User.objects.get(pk=user_id)\n except User.DoesNotExist:\n return None\n\n def check_group_membership(self, ldap_user, group_dn):\n \"\"\"\n Check the LDAP user to see if it is a member of the given group.\n\n This is straightforward with OpenLDAP but tricky with AD as due to\n the weird way AD handles \"primary\" group membership, we must test for\n a separate attribute as well as the usual 'memberof' as the primary\n group is not returned with that filter.\n \"\"\"\n\n # Don't bother search directory if '*' was given: this denotes any group\n # so pass the test immediately.\n if group_dn == '*':\n return True\n\n # Hack for AD: fetch the group's attributes and check for the\n # primaryGroupToken. This will return 0 results in OpenLDAP and hence\n # be ignored.\n pgt = None\n group_attribs = self.search_ldap(ldap_user.connection, '(distinguishedName={})' \\\n .format(group_dn), attributes=['primaryGroupToken'])\n if group_attribs:\n pgt = group_attribs.get('primaryGroupToken', None)\n if type(pgt) == list:\n pgt = pgt[0]\n\n # Now perform our group membership test. If the primary group token is not-None,\n # then we wrap the filter in an OR and test for that too.\n search_filter = '(&(objectClass=user)({}={})(memberof={}))'.format(\n settings.UID_ATTRIB, str(ldap_user), group_dn)\n if pgt:\n search_filter = '(|{}(&(cn={})(primaryGroupID={})))'.format(search_filter, ldap_user.cn, pgt)\n\n # Return True if user is a member of group\n r = self.search_ldap(ldap_user.connection, search_filter)\n return r is not None\n\n def retrieve_ldap_user(self, username, password):\n \"\"\"\n Proxy method for retrieving an LDAP user depending on configuration.\n Currently we only support direct binding.\n \"\"\"\n return self.bind_ldap_user(username, password)\n\n def search_ldap(self, connection, ldap_filter, **kwargs):\n \"\"\"\n Searches the LDAP directory against the given LDAP filter in the form\n of '(attr=val)' e.g. '(uid=test)'.\n\n Any keyword arguments will be passed directly to the underlying search\n method.\n\n A dictionary of attributes will be returned.\n \"\"\"\n connection.search(settings.BASE_DN, ldap_filter, **kwargs)\n entry = None\n for d in connection.response:\n if d['type'] == 'searchResEntry':\n entry = d['attributes']\n entry['dn'] = d['dn']\n break\n return entry\n\n def bind_ldap_user(self, username, password):\n \"\"\"\n Attempts to bind the specified username and password and returns\n an LDAPUser object representing the user.\n\n Returns None if the bind was unsuccessful.\n\n This implements direct binding.\n \"\"\"\n\n # Construct the user to bind as\n if settings.BIND_TEMPLATE:\n # Full CN\n ldap_bind_user = settings.BIND_TEMPLATE.format(username=username,\n base_dn=settings.BASE_DN)\n elif settings.USERNAME_PREFIX:\n # Prepend a prefix: useful for DOMAIN\\user\n ldap_bind_user = settings.USERNAME_PREFIX + username\n elif settings.USERNAME_SUFFIX:\n # Append a suffix: useful for user@domain\n ldap_bind_user = username + settings.USERNAME_SUFFIX\n logger.debug('Attempting to authenticate to LDAP by binding as ' + ldap_bind_user)\n\n try:\n c = ldap3.Connection(self.backend,\n read_only=True,\n lazy=False,\n auto_bind=True,\n client_strategy=ldap3.SYNC,\n authentication=ldap3.SIMPLE,\n user=ldap_bind_user,\n password=password)\n except ldap3.core.exceptions.LDAPSocketOpenError as e:\n logger.error('LDAP connection error: ' + str(e))\n return None\n except ldap3.core.exceptions.LDAPBindError as e:\n if 'invalidCredentials' in str(e):\n # Invalid bind DN or password\n return None\n else:\n logger.error('LDAP bind error: ' + str(e))\n return None\n except Exception as e:\n logger.exception('Caught exception when trying to connect and bind to LDAP')\n raise\n\n # Search for the user using their full DN\n search_filter = '({}={})'.format(settings.UID_ATTRIB, username)\n attributes = self.search_ldap(c, search_filter, attributes=LDAPUser._attrib_keys, size_limit=1)\n if not attributes:\n logger.error('LDAP search error: no results for ' + search_filter)\n return None\n\n # Construct an LDAPUser instance for this user\n return LDAPUser(c, attributes)\n\n def update_group_membership(self, ldap_user, django_user):\n \"\"\"Update the user's group memberships\n\n Checks settings.GROUP_MAP to determine group memberships\n that should be added.\n \"\"\"\n\n if not settings.GROUP_MAP:\n return None\n\n groups = {'add': [], 'remove': []}\n for ldap_group, django_groups in settings.GROUP_MAP.items():\n if self.check_group_membership(ldap_user, ldap_group):\n groups['add'] += [group for group in django_groups if group not in groups['add']]\n else:\n groups['remove'] += [group for group in django_groups if group not in groups['remove']]\n\n for operation in ('remove', 'add'):\n grouplist = groups[operation]\n for group in grouplist:\n try:\n g = Group.objects.get(name=group)\n except Group.DoesNotExist:\n logger.error('Django group does not exist: {}'.format(group))\n continue\n else:\n getattr(django_user.groups, operation)(g)\n\n django_user.save()\n","repo_name":"sjkingo/django_auth_ldap3","sub_path":"django_auth_ldap3/backends.py","file_name":"backends.py","file_ext":"py","file_size_in_byte":10777,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"51"} +{"seq_id":"34691411343","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n======================================================================================\n=== ===\n=== Phase 1 ===\n=== ===\n======================================================================================\n v1 29/05/2021\n\"\"\"\n\n\n# Niveau C\nimport C___inscription as fIns\n\n\n# Niveau B\n\n# Niveau A\nfGoo = fIns.fGoo\nfDis = fIns.fDis\nv = fIns.v\n\n\n\n@fDis.bot.command(aliases = [\"Debut_Phase1\"])\n@fDis.commands.has_permissions(ban_members = True)\nasync def lancement_Inscription(ctx):\n \n v.phaseEnCours = v.phase1\n await fDis.channelHistorique.edit(topic = v.phase1) \n \n \n#### Message de Inscription\n \n msgInscription = await fDis.channelInscription.fetch_message(fIns.idMessage_Inscription)\n await msgInscription.clear_reactions()\n await msgInscription.add_reaction(fDis.Emo_BabyYellow)\n \n \n#### Nettoyage de Infos Joueurs\n \n nb_Joueurs_anc_partie = len( fGoo.donneeGoogleSheet(fGoo.page1_InfoJoueurs) )\n \n if nb_Joueurs_anc_partie != 0 :\n fGoo.page1_InfoJoueurs.delete_rows(2, nb_Joueurs_anc_partie + 1)\n \n v.plantage()","repo_name":"LeTokamak/MegaLG","sub_path":"phase_1.py","file_name":"phase_1.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"14395635724","text":"import sqlite3\nfrom sqlite3 import Error\n\ndef create_database():\n\tconn = None\n\ttry:\n\t\tconn = sqlite3.connect(\"data.sqlite\")\n\t\treturn conn\n\texcept Error as e:\n\t\tprint(e)\n\treturn conn\n\ndef create_table(conn):\n\ttry:\n\t\tcur = conn.cursor()\n\t\ttable = \"\"\"CREATE TABLE IF NOT EXISTS data (\n\t\t\tcouncil_reference VARCHAR(20) PRIMARY KEY,\n\t\t\taddress TEXT,\n\t\t\tcouncil TEXT,\n\t\t\tdescription TEXT,\n\t\t\tinfo_url TEXT,\n\t\t\tdate_scraped DATE,\n\t\t\ton_notice_from DATE,\n\t\t\ton_notice_to DATE\n\t\t\t);\"\"\"\n\t\tcur.execute(table)\n\t\t# print(\"Table created\")\n\texcept Error as e:\n\t\tprint(e)\n\t\t\ndef update_table(conn):\n\ttry:\n\t\tcur = conn.cursor()\n\t\tq = \"\"\" ALTER TABLE data\n\t\t\t\tADD COLUMN on_notice_from DATE;\n\t\t\t\t\"\"\"\n\t\tcur.execute(q)\n\t\t# print(\"Column added\")\n\texcept Error as e:\n\t\tprint(e)\n\ttry:\n\t\tq = \"\"\" ALTER TABLE data\n\t\t\t\tADD COLUMN on_notice_to DATE;\n\t\t\t\t\"\"\"\n\t\tcur.execute(q)\n\t\t# print(\"Column added\")\n\texcept Error as e:\n\t\tprint(e)\n\ndef store_data(data, conn):\n\t# replace if exists\n\tsql = \"\"\"\tINSERT OR REPLACE INTO data(council_reference, address, council, description, info_url, date_scraped, on_notice_from, on_notice_to)\n\t\t\t\tVALUES(?, ?, ?, ?, ?, ?, ?, ?)\"\"\"\n\tcur = conn.cursor()\n\tcur.execute(sql, data)\n\tconn.commit()\n","repo_name":"N-2-O/nsw_planning_major_projects","sub_path":"sqlitedb.py","file_name":"sqlitedb.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"12020107478","text":"# You are the manager of a basketball team. For the upcoming tournament,\n# you want to choose the team with the highest overall score.\n# The score of the team is the sum of scores of all the players in the team.\n#\n# However, the basketball team is not allowed to have conflicts.\n# A conflict exists if a younger player has a strictly higher score than an older player.\n# A conflict does not occur between players of the same age.\n#\n# Given two lists, scores and ages, where each scores[i] and ages[i] represents the score\n# and age of the ith player, respectively, return the highest overall score of all possible basketball teams.\n#\n#\n#\n# Example 1:\n#\n# Input: scores = [1,3,5,10,15], ages = [1,2,3,4,5]\n# Output: 34\n# Explanation: You can choose all the players.\n# Example 2:\n#\n# Input: scores = [4,5,6,5], ages = [2,1,2,1]\n# Output: 16\n# Explanation: It is best to choose the last 3 players.\n# Notice that you are allowed to choose multiple people of the same age.\nfrom typing import List\n\n\n# Example 3:\n#\n# Input: scores = [1,2,3,5], ages = [8,9,10,1]\n# Output: 6\n# Explanation: It is best to choose the first 3 players.\n#\n#\n# Constraints:\n#\n# 1 <= scores.length, ages.length <= 1000\n# scores.length == ages.length\n# 1 <= scores[i] <= 106\n# 1 <= ages[i] <= 1000\n\n# class Solution:\n# def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:\n# players = sorted(zip(ages, scores))\n# dp = [0] * len(players)\n# for i, (_, score) in enumerate(players):\n# dp[i] = score\n# for j in range(i):\n# if players[j][1] <= score:\n# dp[i] = max(dp[i], dp[j] + score)\n# return max(dp)\n\n\nclass Solution:\n def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:\n max_scores = [0] * (max(ages) + 1)\n for score, age in sorted(zip(scores, ages)):\n max_scores[age] = score + max(max_scores[:age + 1])\n return max(max_scores)\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n print(solution.bestTeamScore([1, 3, 5, 10, 15], [1, 2, 3, 4, 5]))\n print(solution.bestTeamScore([4, 5, 6, 5], [2, 1, 2, 1]))\n print(solution.bestTeamScore([1, 2, 3, 5], [8, 9, 10, 1]))\n","repo_name":"Speccy-Rom/Leetcode_aka_speccy-rom","sub_path":"Python problems/Medium/1626_Best Team With No Conflicts.py","file_name":"1626_Best Team With No Conflicts.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"51"} +{"seq_id":"4202889592","text":"from itertools import combinations\n\n\ndef solve(N, A, B, Ps):\n q1 = len([p for p in Ps if p <= A])\n q2 = len([p for p in Ps if A + 1 <= p <= B])\n q3 = len([p for p in Ps if B + 1 <= p])\n return min(q1, q2, q3)\n\n\nif __name__ == \"__main__\":\n N = int(input())\n A, B = tuple(map(int, input().split(\" \")))\n Ps = list(map(int, input().split(\" \")))\n print(solve(N, A, B, Ps))\n","repo_name":"mitsuo0114/competitive_programming","sub_path":"python/atcoder/AISing Programming Contest 2019/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"72521880158","text":"from enum import StrEnum\n\nfrom sqlalchemy.orm import Mapped, mapped_column\n\nfrom .mixin import UuidMixin, UuidOrmMixin\n\n\nclass RoleName(StrEnum):\n \"\"\"An enumeration representing user roles.\"\"\"\n\n user = 'user'\n admin = 'admin'\n\n\nclass RoleOrm(UuidOrmMixin):\n \"\"\"Role table.\"\"\"\n\n __tablename__ = 'role'\n\n name: Mapped[RoleName] = mapped_column(unique=True)\n\n def __repr__(self):\n return f'Role {self.name}'\n\n\nclass Role(UuidMixin):\n \"\"\"Role model.\"\"\"\n\n name: RoleName\n","repo_name":"TRUEVORO/Auth_sprint_1","sub_path":"auth/src/models/role.py","file_name":"role.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"11865445930","text":"#***********************************************************\r\n# Guia de ejercitación nº2\r\n# Fecha: 04/09/2021\r\n# Autor: Aldana Vallejos\r\n#***********************************************************\r\n# EJERCICIO 6: Dadas dos fechas informar cual es la más reciente.\r\n# Determine cuales serían los datos de entrada y las \r\n# leyendas a informar de acuerdo al proceso solicitado. \r\n#***********************************************************\r\n# A N A L I S I S\r\n#***********************************************************\r\n# Entradas: fecha1, fecha2, fechaactual, diferencia, diferencia2, continuar\r\n# Salidas: la mas reciente\r\n# Procesos: Ingresar fechaactual\r\n# Ingresar fecha1\r\n# Ingresar fecha2\r\n# Validar que sean fechas pasadas\r\n# Validar que no sean fechas iguales\r\n# Calculo las diferencias -> diferencia=fechaactual-fecha1\r\n# diferencia2=fechaactual-fecha2\r\n# Muestro el resultado en pantalla\r\n#***********************************************************\r\n# D I S E Ñ O\r\n#***********************************************************\r\n# Declaración de variables\r\nfechaactual=0\r\nfecha1=0\r\nfecha2=0\r\ncontinuar=\"S\"\r\ndiferencia=0\r\ndiferencia2=0\r\n\r\nwhile continuar==\"S\":\r\n # Ingreso de datos\r\n fechaactual=int(input(\"Ingrese la fecha actual en orden (AAAAMMDD): \"))\r\n fecha1=int(input(\"Ingrese la primera fecha en orden (AAAAMMDD): \"))\r\n fecha2=int(input(\"Ingrese la segunda fecha en orden (AAAAMMDD): \"))\r\n \r\n # Verifico que no sean fechas futuras a la actual\r\n if fecha1>fechaactual or fecha2>fechaactual:\r\n # Salida por pantalla\r\n print(\"Error - Ingrese una fecha pasada a la actual\")\r\n \r\n # Verifico que no sean fechas iguales\r\n if fecha1==fecha2:\r\n # Salida por pantalla\r\n print(\"Error - Ingrese fechas distintas\")\r\n continuar=\"N\"\r\n\r\n# Calculo la diferencia entre la fecha actual menos las fechas\r\ndiferencia=fechaactual-fecha1\r\ndiferencia2=fechaactual-fecha2\r\n\r\nif diferencia int:\n table = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\n res = 0\n for i in range(len(s)):\n if i == 0:\n res += table[s[0]]\n else:\n here = table[s[i]]\n left = table[s[i-1]]\n # if increasing, subtract\n if here > left:\n res -= 2 * left\n res += here\n return res\n# @lc code=end\n\n","repo_name":"flutcla/langchallange","sub_path":"leetcode/13.roman-to-integer.py","file_name":"13.roman-to-integer.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"2220652895","text":"from dataclasses import dataclass, field\nfrom typing import Optional\nfrom netex.fare_demand_factor_ref import FareDemandFactorRef\nfrom netex.fare_price_versioned_child_structure import FarePriceVersionedChildStructure\nfrom netex.fare_quota_factor_ref import FareQuotaFactorRef\nfrom netex.quality_structure_factor_ref import QualityStructureFactorRef\n\n__NAMESPACE__ = \"http://www.netex.org.uk/netex\"\n\n\n@dataclass(unsafe_hash=True, kw_only=True)\nclass QualityStructureFactorPriceVersionedChildStructure(FarePriceVersionedChildStructure):\n \"\"\"\n Type for a QUALITY STRUCTURE FACTOR PRICEs.\n \"\"\"\n class Meta:\n name = \"QualityStructureFactorPrice_VersionedChildStructure\"\n\n fare_quota_factor_ref_or_fare_demand_factor_ref_or_quality_structure_factor_ref: Optional[object] = field(\n default=None,\n metadata={\n \"type\": \"Elements\",\n \"choices\": (\n {\n \"name\": \"FareQuotaFactorRef\",\n \"type\": FareQuotaFactorRef,\n \"namespace\": \"http://www.netex.org.uk/netex\",\n },\n {\n \"name\": \"FareDemandFactorRef\",\n \"type\": FareDemandFactorRef,\n \"namespace\": \"http://www.netex.org.uk/netex\",\n },\n {\n \"name\": \"QualityStructureFactorRef\",\n \"type\": QualityStructureFactorRef,\n \"namespace\": \"http://www.netex.org.uk/netex\",\n },\n ),\n }\n )\n","repo_name":"skinkie/reference","sub_path":"gtfs-netex-test/netex/quality_structure_factor_price_versioned_child_structure.py","file_name":"quality_structure_factor_price_versioned_child_structure.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"37541999240","text":"from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication\nfrom qgis.PyQt.QtGui import QIcon\nfrom qgis.PyQt.QtWidgets import QAction\n\n# Initialize Qt resources from file resources.py\nfrom .resources import *\n# Import the code for the dialog\nfrom .findRoute_dialog import FindRouteDialog\nimport os.path\n\n\n# ###############FUNCTIONS################\nimport os, sys\nimport numpy as np\nimport gdal\nimport math\nimport itertools\n\n#import functions\nfrom qgis.core import QgsProject, QgsVectorFileWriter, QgsCoordinateReferenceSystem\nfrom osgeo import ogr, osr\nfrom qgis.core import QgsWkbTypes, QgsVectorLayer, QgsPointXY, QgsFields, QgsField, QgsFeature, QgsGeometry, QgsProject\nfrom PIL import Image \nfrom numpy.lib import recfunctions as rfn\nfrom qgis.utils import iface\n\nfrom PyQt5 import QtWidgets, uic, QtCore\nfrom PyQt5.QtCore import pyqtSlot, QVariant\nfrom PyQt5.QtWidgets import QLineEdit, QFileDialog, QTableWidgetItem, QMessageBox\n\n#_____IMPORT_EXTERNAL_FUNCTIONS_____\nfrom .functions import open_raster, raster_height_array, raster_parameters, raster_XYZ_array,\\\nopen_vector, vector_objects, vector_objects_elements, empty_array, vertex_information_array,\\\npixel_elevation, add_elevation, create_type_array, sort_lines_elements, add_array_element,\\\nraster_line_intersection, new_vertex_elevation_array, new_vertex_information_array,\\\npoints_objects_elements, points_information_array, closest_point, closest_pts_possibility,\\\ndelete_arr_elem, next_origin_vertex, prev_origin_vertex, check_elem_exist, duplicate_vertex,\\\nadd_next_elem_array, add_equal_id, other_objects, calc_last_vert, calc_last_vert_prev,\\\nadd_type_element_arr, next_vert2, prev_vert2, identical_line, calc_routes, possible_routes,\\\ncomplete_possible_route, check_array_shortages, add_type_element_section, calculate_time,\\\ncalculate_slope_vrt_position, route_sections_attributes, route_optimization, points_set,\\\ncreate_shp_route\n\n# ###############FUNCTIONS################\n\nclass FindRoute:\n \"\"\"QGIS Plugin Implementation.\"\"\"\n\n def __init__(self, iface):\n \"\"\"Constructor.\n\n :param iface: An interface instance that will be passed to this class\n which provides the hook by which you can manipulate the QGIS\n application at run time.\n :type iface: QgsInterface\n \"\"\"\n # Save reference to the QGIS interface\n self.iface = iface\n # initialize plugin directory\n self.plugin_dir = os.path.dirname(__file__)\n # initialize locale\n locale = QSettings().value('locale/userLocale')[0:2]\n locale_path = os.path.join(\n self.plugin_dir,\n 'i18n',\n 'FindRoute_{}.qm'.format(locale))\n\n if os.path.exists(locale_path):\n self.translator = QTranslator()\n self.translator.load(locale_path)\n QCoreApplication.installTranslator(self.translator)\n\n # Declare instance attributes\n self.actions = []\n self.menu = self.tr(u'&Find Route')\n\n # Check if plugin was started the first time in current QGIS session\n # Must be set in initGui() to survive plugin reloads\n self.first_start = None\n\n # noinspection PyMethodMayBeStatic\n def tr(self, message):\n \"\"\"Get the translation for a string using Qt translation API.\n\n We implement this ourselves since we do not inherit QObject.\n\n :param message: String for translation.\n :type message: str, QString\n\n :returns: Translated version of message.\n :rtype: QString\n \"\"\"\n # noinspection PyTypeChecker,PyArgumentList,PyCallByClass\n return QCoreApplication.translate('FindRoute', message)\n\n\n def add_action(\n self,\n icon_path,\n text,\n callback,\n enabled_flag=True,\n add_to_menu=True,\n add_to_toolbar=True,\n status_tip=None,\n whats_this=None,\n parent=None):\n \"\"\"Add a toolbar icon to the toolbar.\n\n :param icon_path: Path to the icon for this action. Can be a resource\n path (e.g. ':/plugins/foo/bar.png') or a normal file system path.\n :type icon_path: str\n\n :param text: Text that should be shown in menu items for this action.\n :type text: str\n\n :param callback: Function to be called when the action is triggered.\n :type callback: function\n\n :param enabled_flag: A flag indicating if the action should be enabled\n by default. Defaults to True.\n :type enabled_flag: bool\n\n :param add_to_menu: Flag indicating whether the action should also\n be added to the menu. Defaults to True.\n :type add_to_menu: bool\n\n :param add_to_toolbar: Flag indicating whether the action should also\n be added to the toolbar. Defaults to True.\n :type add_to_toolbar: bool\n\n :param status_tip: Optional text to show in a popup when mouse pointer\n hovers over the action.\n :type status_tip: str\n\n :param parent: Parent widget for the new action. Defaults None.\n :type parent: QWidget\n\n :param whats_this: Optional text to show in the status bar when the\n mouse pointer hovers over the action.\n\n :returns: The action that was created. Note that the action is also\n added to self.actions list.\n :rtype: QAction\n \"\"\"\n\n icon = QIcon(icon_path)\n action = QAction(icon, text, parent)\n action.triggered.connect(callback)\n action.setEnabled(enabled_flag)\n\n if status_tip is not None:\n action.setStatusTip(status_tip)\n\n if whats_this is not None:\n action.setWhatsThis(whats_this)\n\n if add_to_toolbar:\n # Adds plugin icon to Plugins toolbar\n self.iface.addToolBarIcon(action)\n\n if add_to_menu:\n self.iface.addPluginToMenu(\n self.menu,\n action)\n\n self.actions.append(action)\n\n return action\n\n def initGui(self):\n \"\"\"Create the menu entries and toolbar icons inside the QGIS GUI.\"\"\"\n\n icon_path = ':/plugins/findRoute/icon.png'\n self.add_action(\n icon_path,\n text=self.tr(u'Find the best route between points'),\n callback=self.run,\n parent=self.iface.mainWindow())\n\n # will be set False in run()\n self.first_start = True\n\n\n def unload(self):\n \"\"\"Removes the plugin menu item and icon from QGIS GUI.\"\"\"\n for action in self.actions:\n self.iface.removePluginMenu(\n self.tr(u'&Find Route'),\n action)\n self.iface.removeToolBarIcon(action)\n\n#______________________________FUNCTIONS__________________________________\n#_________________________________________________________________________\n \n#_____LAYERS_____\n \n #check layer extension for all \"layers\" from project and return an array \n #...wich contains names of all layers with the specified extension \"ext\"\n def load_layers_to_frame(self,layers,ext):\n #save layers with appropriate extension\n arr_name = []\n for la in layers:\n #get the path\n layer_path = la.layer().dataProvider().dataSourceUri()\n layer_directory, layer_name = os.path.split(layer_path)\n #get the layer name with its extension\n try:\n layer_name, rest = layer_name.split(\"|\")\n except:\n layer_name = layer_name[:]\n #check if layer ends with appropriate extension\n if layer_name.endswith(ext):\n arr_name.append(layer_name)\n \n return arr_name\n\n \n #select place to save an output\n def select_output_file(self):\n filename, _filter = QFileDialog.getSaveFileName(self.dlg, \"Select output file \",\"\", '*.shp')\n self.dlg.outputLE.setText(filename)\n \n \n #select files from browser: 1)grid, 2)linear layer and 3)points layer\n def select_input_file1(self):\n filename, filter = QFileDialog.getOpenFileName(self.dlg,\"Open File\",\"\",\"*.tif\")\n if filename != \"\":\n self.dlg.inputGridCB.addItems([filename])\n\n\n def select_input_file2(self):\n filename, filter = QFileDialog.getOpenFileName(self.dlg,\"Open File\",\"\",\"*.shp\")\n if filename != \"\":\n self.dlg.inputLinesCB.addItems([filename])\n\n\n def select_input_file3(self):\n filename, filter = QFileDialog.getOpenFileName(self.dlg,\"Open File\",\"\",\"*.shp\")\n if filename != \"\":\n self.dlg.inputPointsCB.addItems([filename])\n \n \n #get the path, if path not exists -> pass\n def get_path(self,layers,box_text):\n for la in layers:\n try:\n layer_path = la.layer().dataProvider().dataSourceUri().split(\"|\")\n if layer_path[0].find(box_text) != -1:\n raster_file_path = layer_path[0]\n except:\n pass\n return str(raster_file_path)\n \n \n #read paths to files: grid, linear layer, points layer\n def read_input_file(self,layers):\n \n #take current text from the \"inputGridCB\", \"inputLinesCB\", \"inputPointsCB\"\n raster_file_path = self.dlg.inputGridCB.currentText()\n lines_file_path = self.dlg.inputLinesCB.currentText() \n points_file_path = self.dlg.inputPointsCB.currentText()\n result_file_path = self.dlg.outputLE.text()\n\n\n #check if the text is a path to the file, if not -> find a path to the file, if it is impossible -> error\n try:\n if not os.path.isfile(raster_file_path):\n raster_file_path = self.get_path(layers,raster_file_path)\n except:\n QMessageBox(QMessageBox.Warning, \"Error\",\"Failed to find the grid layer path.\\nThe file does not exist or try refresh the plugin.\", QMessageBox.Ok).exec()\n try:\n if not os.path.isfile(lines_file_path):\n lines_file_path = self.get_path(layers,lines_file_path)\n except:\n QMessageBox(QMessageBox.Warning, \"Error\",\"Failed to find the linear layer path.\\nThe file does not exist or try refresh the plugin.\", QMessageBox.Ok).exec()\n try:\n if not os.path.isfile(points_file_path):\n points_file_path = self.get_path(layers,points_file_path)\n except:\n QMessageBox(QMessageBox.Warning, \"Error\",\"Failed to find the points layer path.\\nThe file does not exist or try refresh the plugin.\", QMessageBox.Ok).exec()\n \n #check if the text is a right path, if not -> error\n if result_file_path.find(\"\\0\"):\n result_file_path = result_file_path.replace(\"\\0\",\"\\\\0\")\n dirname = os.path.dirname(result_file_path) or os.getcwd() \n try:\n dirname = os.path.dirname(result_file_path) or os.getcwd()\n creatable = os.access(dirname, os.W_OK) \n except:\n QMessageBox(QMessageBox.Warning, \"Error\",\"Failed to find the output file path.\", QMessageBox.Ok).exec()\n \n return raster_file_path, lines_file_path, points_file_path, result_file_path\n \n\n#_____CONDITIONS_____\n\n #check selected optimization condition\n def check_optimization(self):\n optimization = \"none\"\n if self.dlg.lengthRB.isChecked():\n optimization = 'length_3D'\n if self.dlg.timeRB.isChecked():\n optimization = 'time'\n if self.dlg.heightDifRB.isChecked():\n optimization = 'height_differences'\n if self.dlg.approachesRB.isChecked():\n optimization = 'approaches'\n if self.dlg.descentsRB.isChecked():\n optimization = 'descents'\n if self.dlg.slopesRB.isChecked():\n optimization = 'mean_slope'\n return optimization\n \n \n #check optimization option: minimalization/maximization\n def check_min_max(self):\n if self.dlg.minMaxCB.currentText() == \"min\":\n cond = \"min\"\n elif self.dlg.minMaxCB.currentText() == \"max\":\n cond = \"max\"\n return cond\n\n\n#_____ATTRIBUTES_____\n \n #choose attributes to attach\n def choose_attributes(self):\n length_2D = self.dlg.length2DChB.checkState()\n length_3D = self.dlg.length3DChB.checkState()\n time = self.dlg.timeChB.checkState()\n elevation = self.dlg.elevationChB.checkState()\n height_differences = self.dlg.heightDifChB.checkState()\n approaches = self.dlg.approachesChB.checkState()\n descents = self.dlg.descentsChB.checkState()\n mean_slope = self.dlg.slopeChB.checkState()\n return length_2D, length_3D, time, elevation, height_differences, approaches, descents, mean_slope\n\n\n#_____MAIN_WINDOW_____\n \n #close main window, when \"closePB\" clicked\n def close_main_window(self):\n self.dlg.accept()\n \n #run all application processes, when \"runPB\" clicked\n def run_all(self,layers):\n \n #[1] get paths\n all_paths = self.read_input_file(layers)\n raster_file_path = all_paths[0]\n lines_file_path = all_paths[1]\n points_file_path = all_paths[2]\n result_file_path = all_paths[3]\n \n #[2] open a raster file\n raster_file = open_raster(self,raster_file_path)\n \n #[3] create heights array from the grid\n raster_height_arr = raster_height_array(self,raster_file)\n \n #[4] return raster parameters\n raster_param_arr = raster_parameters(self,raster_file,raster_height_arr)\n\n #[5] return x,y,z array for all raster pixels\n XYZ = raster_XYZ_array(self,raster_param_arr[3],raster_param_arr[4],raster_param_arr[5],raster_param_arr[6],raster_param_arr[7],raster_param_arr[8],raster_height_arr)\n \n #[6] open the file a the linear layer\n lines = open_vector(self,lines_file_path)\n\n #[7] return objects from liear layer\n fts = vector_objects(self,lines)\n \n #[8] save information about existing vertex into an array\n vertex_array = vertex_information_array(self,lines,fts)\n \n #[9] find an intersection between pixels and linear layer, finally return an array: [object number, first vertex value, next vertex value, new vertex number, x, y]\n end_std_new_vert_arr = raster_line_intersection(self,lines,raster_param_arr[4],raster_param_arr[3],raster_param_arr[5],raster_param_arr[6],raster_param_arr[7],raster_param_arr[8],vertex_array)\n \n #[10] assign heights to all vertices\n new_z_arr = new_vertex_elevation_array(self,end_std_new_vert_arr,XYZ,raster_param_arr)\n\n #[11]return an array with sorted information about vertices\n new_info_arr = new_vertex_information_array(self,end_std_new_vert_arr,new_z_arr,4,4)\n\n #[12] open a file with the points layer\n route_pts = open_vector(self,points_file_path)\n\n #[13] return an array with information about point layer\n route_pts_arr = points_information_array(self,route_pts)\n \n #[14] find the closest vertices to points \n closest_pts_arr0 = closest_point(self,route_pts_arr, new_info_arr)\n \n #[15] return an array with the possible combinations of routes between the closest vertices\n closest_pts_arr = closest_pts_possibility(self,closest_pts_arr0,new_info_arr)\n\n #[16] find all possible routes\n possible_routes_arr = possible_routes(self,closest_pts_arr,new_info_arr)\n \n #[17] complete route array\n compl_poss_route_arr = complete_possible_route(self,possible_routes_arr,new_info_arr)\n \n #[18] fill shortages on \"compl_poss_route_arr\"\n new_compl_poss_route_arr = check_array_shortages(self,compl_poss_route_arr,possible_routes_arr) \n \n #[19] make a table with attributes for sections of the routes (routes between two points)\n sections_attr_arr = route_sections_attributes(self,new_compl_poss_route_arr)\n \n #[20] choose the best route using optimization parameters \n route_optim_array = route_optimization(self,sections_attr_arr,closest_pts_arr0)\n \n #[21] choose atributes to be attached\n atr = self.choose_attributes()\n \n #[22] create and display an output file\n create_shp_route(self,atr[0],atr[1],atr[2],atr[3],atr[4],atr[5],atr[6],atr[7],result_file_path,raster_param_arr[11],route_optim_array[0],new_compl_poss_route_arr,route_optim_array[1],raster_param_arr,3,2,2)\n \n return None\n\n#_________________________________________________________________________\n\n\n def run(self):\n \"\"\"Run method that performs all the real work\"\"\"\n\n # Create the dialog with elements (after translation) and keep reference\n # Only create GUI ONCE in callback, so that it will only load when the plugin is started\n if self.first_start == True:\n self.first_start = False\n self.dlg = FindRouteDialog()\n\n\n#_______________________________LAYERS____________________________________\n#_________________________________________________________________________\n \n \n # Link to the currently loaded layers from the project\n layers = QgsProject.instance().layerTreeRoot().children()\n \n \n #_____Add grid layer_____\n \n # Clear the contents of the inputGridCB from previous runs\n self.dlg.inputGridCB.clear()\n # Connect the inputGridCB with names of the specified layers\n self.dlg.inputGridCB.addItems(self.load_layers_to_frame(layers,\"tif\"))\n\n #Open a file browser\n self.dlg.openGridTB.clicked.connect(self.select_input_file1)\n\n\n #_____Add linear layer_____\n self.dlg.inputLinesCB.clear()\n self.dlg.inputLinesCB.addItems(self.load_layers_to_frame(layers,\"shp\"))\n \n self.dlg.openLinesTB.clicked.connect(self.select_input_file2)\n \n \n #_____Add points layer_____\n self.dlg.inputPointsCB.clear()\n self.dlg.inputPointsCB.addItems(self.load_layers_to_frame(layers,\"shp\"))\n \n self.dlg.openPointsTB.clicked.connect(self.select_input_file3)\n \n \n #_____Output file path_____\n self.dlg.openOutputTB.clicked.connect(self.select_output_file)\n\n\n#_______________________________CONDITIONS________________________________\n#_________________________________________________________________________\n\n\n#_______________________________ATTRIBUTES________________________________\n#_________________________________________________________________________\n\n\n#______________________________MAIN_WINDOW________________________________\n#_________________________________________________________________________\n \n #_____CLOSE_____\n self.dlg.closePB.clicked.connect(self.close_main_window)\n \n #_____RUN_____\n self.dlg.runPB.clicked.connect(lambda: self.run_all(layers))\n\n \n # show the dialog\n self.dlg.show()\n # Run the dialog event loop\n result = self.dlg.exec_()\n # See if OK was pressed\n if result:\n # Do something useful here - delete the line containing pass and\n # substitute with your code.\n pass\n","repo_name":"AksamitKarolina/Praca_Magisterska_FindRoute_Aksamit_Karolina","sub_path":"findroute/findRoute.py","file_name":"findRoute.py","file_ext":"py","file_size_in_byte":19444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"74949730412","text":"#coding = utf-8\n\nfrom selenium import webdriver\nimport os,time\n\ndriver = webdriver.Chrome()\nfile_path = 'file:///' + os.path.abspath('3.17js.html')\ndriver.get(file_path)\n\n#通过js隐藏选中的元素#第一种方法\n#隐藏文字信息\n#execute_script() 接口用来调用 js 代码\ndriver.execute_script('$(\"#tooltip\").fadeOut();')\ntime.sleep(3)\n\n#隐藏按钮\nbutton = driver.find_element_by_class_name('btn')\ndriver.execute_script('$(arguments[0]).fadeOut',button)\ntime.sleep(3)\n\n","repo_name":"yenan1988/learn_testing","sub_path":"python/Selenium/虫师/3.17调用js.py","file_name":"3.17调用js.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"31005987812","text":"import matplotlib.pyplot as plt\n\ndef parse_file(file_name):\n f = open(file_name, \"r\")\n lines = f.read()\n x = lines.split(',')\n si = int(x[0])\n x = x[1::]\n\n #Converting string values to float\n for i in range(len(x)):\n x[i] = float(x[i])\n\n return (si, x)\n\n\ndef plot_even_odd_parts(x, si):\n\n\n x_original = x\n #Reverse the list to get x[-n]\n x_reverse = x[::-1]\n\n #Append zeros to the beginning because of the starting index\n x = ([0] * abs(si) + x)\n x_reverse = ([0] * abs(si) + x_reverse)\n\n\n #Calculate even (xe) and odd (xo) parts of the signal x\n xe = [(x[n] + x_reverse[n])/2 for n in range(abs(si), abs(si)+len(x_original))]\n xo = [(x[n] - x_reverse[n])/2 for n in range(abs(si), abs(si)+len(x_original))]\n\n xe = [0] * 2 + xe + [0] * 2\n xo = [0] * 2 + xo + [0] * 2\n\n # Plotting the even part\n plt.stem(range(si-2, si+len(x_original)+2), xe, linefmt='b-', markerfmt='bo', label='Even part')\n\n # Plotting the odd part\n plt.stem(range(si-2, si+len(x_original)+2), xo, linefmt='r-', markerfmt='ro', label='Odd part')\n\n #Adding title and labels for the graph\n plt.title('Even and Odd Parts of Signal a Discrete Signal')\n plt.xlabel('n')\n plt.ylabel('Odd and Even Parts')\n plt.legend()\n plt.show()\n\n\ninput_list = [\"chirp_part_a.csv\", \"shifted_sawtooth_part_a.csv\", \"sine_part_a.csv\"]\n\nfor file_name in input_list:\n my_input = parse_file(file_name)\n plot_even_odd_parts(my_input[1], my_input[0])\n\n","repo_name":"ayselbbzd/ceng384-hw1","sub_path":"ceng384a.py","file_name":"ceng384a.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"5545866801","text":"import fitz\nimport os\nfrom flask import Flask, render_template, request, redirect\n\napp = Flask(__name__)\n\ndef extract_sentences_with_word(pdf_path, target_word):\n sentences = []\n pdf_document = fitz.open(pdf_path)\n\n for page_number in range(pdf_document.page_count):\n page = pdf_document[page_number]\n page_text = page.get_text()\n\n all_sentences = page_text.split('.')\n\n for sentence in all_sentences:\n if target_word.lower() in sentence.lower():\n sentences.append((sentence.strip() + '.', page_number + 1))\n\n pdf_document.close()\n return sentences\n\nUPLOAD_FOLDER = 'uploads'\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\nif not os.path.exists(UPLOAD_FOLDER):\n os.makedirs(UPLOAD_FOLDER)\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n if request.method == \"POST\":\n target_word = request.form.get(\"target_word\")\n\n if 'pdf_file' not in request.files:\n return redirect(request.url)\n\n pdf_file = request.files['pdf_file']\n if pdf_file.filename == '':\n return redirect(request.url)\n\n if pdf_file and pdf_file.filename.endswith('.pdf'):\n pdf_path = os.path.join(app.config['UPLOAD_FOLDER'], pdf_file.filename)\n pdf_file.save(pdf_path)\n found_sentences = extract_sentences_with_word(pdf_path, target_word)\n os.remove(pdf_path)\n\n return render_template(\"result.html\", sentences=found_sentences)\n\n return render_template(\"index.html\")\n\nif __name__ == \"__main__\":\n app.run(debug=False)\n","repo_name":"jothi-prasath/pdf-sentence-searcher","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"11309172912","text":"from flask import Flask, url_for, render_template, request, redirect, session\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask import request\nimport sqlite3 as sql\n\n\napp = Flask(__name__)\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///database.db\"\ndb = SQLAlchemy(app)\n\n\nclass User(db.Model):\n \"\"\"Create user table\"\"\"\n\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(80), unique=True)\n password = db.Column(db.String(80))\n\n def __init__(self, username, password):\n self.username = username\n self.password = password\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef home():\n \"\"\"Session control\"\"\"\n if not session.get(\"logged_in\"):\n return render_template(\"index.html\")\n else:\n if request.method == \"POST\":\n return render_template(\"index.html\")\n return render_template(\"index.html\")\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n \"\"\"Login Form\"\"\"\n if request.method == \"GET\":\n return render_template(\"login.html\")\n else:\n name = request.form[\"username\"]\n passw = request.form[\"password\"]\n try:\n data = User.query.filter_by(username=name, password=passw).first()\n if data is not None:\n session[\"logged_in\"] = True\n return redirect(url_for(\"home1\"))\n else:\n return \"Invalid Credentials\"\n except:\n return \"Invalid Credentials\"\n\n\n@app.route(\"/register/\", methods=[\"GET\", \"POST\"])\ndef register():\n \"\"\"Register Form\"\"\"\n if request.method == \"POST\":\n new_user = User(\n username=request.form[\"username\"], password=request.form[\"password\"]\n )\n db.session.add(new_user)\n db.session.commit()\n return render_template(\"login.html\")\n return render_template(\"register.html\")\n\n\n@app.route(\"/logout\")\ndef logout():\n \"\"\"Logout Form\"\"\"\n session[\"logged_in\"] = False\n return redirect(url_for(\"home\"))\n\n\n@app.route(\"/home\")\ndef home1():\n return render_template(\"home.html\")\n\n\n\n # stock balance\n@app.route(\"/stockbalance\")\ndef Stockbalance():\n con = sql.connect(\"database.db\")\n con.row_factory = sql.Row\n\n cur = con.cursor()\n cur.execute(\"select * from Product\")\n\n rows = cur.fetchall()\n return render_template(\"stock.html\", rows=rows)\n\n\ncon = sql.connect(\n \"database.db\", check_same_thread=False\n) # con is a variable and sql.connect is used to connect the test(BASICALLY CONNECTION)\ncon.row_factory = sql.Row # when queriying instead of tuples, objects are returned\ncur = (\n con.cursor()\n) # cur is a object which can further be used with methods like execute\n\n\n# stock balance\n@app.route(\"/stockbalance\")\ndef Stockbalance1():\n con = sql.connect(\"database.db\") # connecting DB\n con.row_factory = sql.Row\n\n cur = con.cursor()\n cur.execute(\"select * from Product\") # executes the query\n rows = cur.fetchall() # returns all the rows in list type\n return render_template(\"stock.html\", rows=rows)\n\n\n# Product Page\n@app.route(\"/Product\")\ndef Product():\n con = sql.connect(\"database.db\")\n con.row_factory = sql.Row\n\n cur = con.cursor()\n cur.execute(\"select * from Product\")\n\n rows = cur.fetchall() # returns all the rows in list type\n return render_template(\"Product.html\", rows=rows)\n\n\n# ADD Product\n@app.route(\"/addProduct\", methods=[\"POST\"]) # POST=sends the data to DB/server\ndef addProduct():\n if request.method == \"POST\":\n try:\n pn = request.form[\"pn\"] # accepts product name\n pd = request.form[\"pd\"] # accepts product description\n pq = request.form[\"pq\"] # accepts product quantity\n\n with sql.connect(\"database.db\") as con:\n cur = con.cursor()\n cur.execute(\n \"INSERT INTO Product (productName,productDescription,QTY) VALUES (?,?,?)\",\n (pn, pd, pq),\n )\n\n con.commit() # saves all changes to DB\n msg = \"Record added\" # display a message\n except:\n con.rollback() # return the DB to previous state\n msg = \"error in operation\"\n\n finally:\n\n return redirect(\n url_for(\"Product\") + \"?msg=\" + msg\n ) # redirects to the products page with message msg\n con.close() # close the connection\n\n\n# Edit Product\n@app.route(\"/editProduct\", methods=[\"POST\"])\ndef editProduct():\n if request.method == \"POST\":\n try:\n productID = request.form[\"ProductID\"] # for this product ID\n productName = request.form[\"NEWProductName\"] # accepts all the data\n productDescription = request.form[\"NEWProductDescription\"]\n ProductQty = request.form[\"NEWProductQty\"]\n cur.execute(\n \"UPDATE Product SET productName = ?,productDescription = ?, QTY = ? WHERE productID = ?\",\n (productName, productDescription, ProductQty, productID),\n ) # update query\n\n con.commit()\n msg = \"Product Edited \"\n except:\n con.rollback()\n msg = \"error in operation\"\n\n finally:\n return redirect(\n url_for(\"Product\") + \"?msg=\" + msg\n ) # redirect to the products page with msg\n con.close()\n\n # Delete Product\n\n\n@app.route(\"/deleteProduct/\") # for the productID\ndef deleteProduct(productID):\n try:\n cur.execute(\n \"DELETE FROM Product WHERE productID = ?\", (productID,)\n ) # delete query\n\n con.commit()\n msg = \"Product Deleted\"\n except:\n con.rollback()\n msg = \"error in operation\"\n\n finally:\n return redirect(\n url_for(\"Product\") + \"?msg=\" + msg\n ) # redirect to product page with msg\n con.close()\n\n # Location Page\n\n\n@app.route(\"/Location\")\ndef Location():\n con = sql.connect(\"database.db\")\n con.row_factory = sql.Row\n\n cur = con.cursor()\n cur.execute(\"select * from locations\")\n\n rows = cur.fetchall()\n return render_template(\"Location.html\", rows=rows)\n\n # ADD Locations\n\n\n@app.route(\"/addlocation\", methods=[\"POST\"])\ndef addlocation():\n if request.method == \"POST\":\n try:\n ln = request.form[\"ln\"]\n\n with sql.connect(\"database.db\") as con:\n cur = con.cursor()\n cur.execute(\"INSERT INTO locations (locationName) VALUES (?)\", (ln,))\n\n con.commit()\n msg = \"successfully added\"\n except:\n con.rollback()\n msg = \"error in operation\"\n\n finally:\n return redirect(url_for(\"Location\") + \"?msg=\" + msg)\n con.close()\n\n # Edit Location\n\n\n@app.route(\"/editlocation\", methods=[\"POST\"])\ndef editlocation():\n if request.method == \"POST\":\n try:\n locationID = request.form[\"locationID\"]\n locationName = request.form[\"NEWLocationName\"]\n cur.execute(\n \"UPDATE locations SET locationName = ? WHERE locationID = ?\",\n (locationName, locationID),\n )\n\n con.commit()\n msg = \"location Edit Successfully\"\n except:\n con.rollback()\n msg = \"error operation\"\n\n finally:\n return redirect(url_for(\"Location\") + \"?msg=\" + msg)\n con.close()\n\n # Delete Location\n\n\n@app.route(\"/deletelocation/\")\ndef deletelocation(locationID):\n try:\n cur.execute(\"DELETE FROM locations WHERE locationID = ? \", (locationID))\n\n con.commit()\n msg = \"location Delete Successfully\"\n except:\n con.rollback()\n msg = \"error operation\"\n\n finally:\n return redirect(url_for(\"Location\") + \"?msg=\" + msg)\n con.close()\n\n\n# Product movement\n\n\n@app.route(\"/ProductMovement\")\ndef ProductMovement():\n cur.execute(\"select * from product_movement\")\n\n rows = cur.fetchall()\n\n cur.execute(\"select * from Stockbalance\")\n productRows = cur.fetchall()\n\n cur.execute(\"select * from locations\")\n locationRows = cur.fetchall()\n\n for pr in productRows:\n for lr in locationRows:\n cur.execute(\n \"SELECT * FROM Balance WHERE locationName = ? AND productName = ? \",\n (lr[\"locationName\"], pr[\"productName\"]),\n )\n data = cur.fetchall()\n\n if len(data) == 0:\n cur.execute(\n \"INSERT INTO Balance (locationName, productName, qty)VALUES (?,?,?)\",\n (lr[\"locationName\"], pr[\"productName\"], 0),\n )\n con.commit()\n\n return render_template(\n \"ProductMovement.html\",\n rows=rows,\n productRows=productRows,\n locationRows=locationRows,\n )\n\n # ADD ProductMovement\n\n\n@app.route(\"/addProductMovement\", methods=[\"POST\"])\ndef addProductMovement():\n if request.method == \"POST\":\n try:\n pn = request.form[\"pn\"]\n datetime = request.form[\"datetime\"]\n fromlocation = request.form[\"fromlocation\"]\n tolocation = request.form[\"tolocation\"]\n pq = request.form[\"pq\"]\n\n with sql.connect(\"database.db\") as con:\n cur = con.cursor()\n cur.execute(\n \"INSERT INTO product_movement (productName,Timing,fromlocation,tolocation,QTY) VALUES (?,?,?,?,?)\",\n (pn, datetime, fromlocation, tolocation, pq),\n )\n\n con.commit()\n msg = \"Record added\"\n except:\n con.rollback()\n msg = \"error in operation\"\n\n finally:\n return redirect(url_for(\"ProductMovement\") + \"?msg=\" + msg)\n con.close()\n\n # Edit ProductMovement\n\n\n@app.route(\"/editProductMovement\", methods=[\"POST\"])\ndef editProductMovement():\n if request.method == \"POST\":\n try:\n movementID = request.form[\"movementID\"]\n ProductName = request.form[\"NEWProductName\"]\n datetime = request.form[\"NEWDateTime\"]\n fromlocation = request.form[\"NEWfromlocation\"]\n tolocation = request.form[\"NEWtolocation\"]\n qty = request.form[\"NEWProductQty\"]\n cur.execute(\n \"UPDATE product_movement SET productName = ?,Timing = ?,fromlocation = ?,tolocation = ?,QTY = ? WHERE movementID = ?\",\n (ProductName, datetime, fromlocation, tolocation, qty, movementID),\n )\n\n con.commit()\n msg = \" movement Edit Successfully\"\n except:\n con.rollback()\n msg = \"error operation\"\n\n finally:\n return redirect(url_for(\"ProductMovement\") + \"?msg=\" + msg)\n con.close()\n\n # Delete Product Movement\n\n\n@app.route(\"/deleteprouctmovement/\")\ndef deleteprouctmovement(movementID):\n try:\n cur.execute(\"DELETE FROM product_movement WHERE movementID = ? \", (movementID))\n\n con.commit()\n msg = \"movement Delete Successfully\"\n except:\n con.rollback()\n msg = \"error operation\"\n\n finally:\n return redirect(url_for(\"ProductMovement\") + \"?msg=\" + msg)\n con.close()\n\n\nif __name__ == \"__main__\":\n app.debug = True\n db.create_all()\n app.secret_key = \"123\"\n app.run(host=\"0.0.0.0\")\n","repo_name":"karna-sam/miniproject","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"32691972215","text":"\"\"\"courseDetails table\n\nRevision ID: 2892a6f9c0de\nRevises: a601b334133a\nCreate Date: 2019-03-11 17:19:22.139099\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '2892a6f9c0de'\ndown_revision = 'a601b334133a'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('courseDetails',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('course_id', sa.Integer(), nullable=True),\n sa.Column('locations_id', sa.Integer(), nullable=True),\n sa.Column('start_date', sa.DateTime(), nullable=True),\n sa.Column('end_date', sa.DateTime(), nullable=True),\n sa.Column('start_time', sa.Time(), nullable=True),\n sa.Column('end_time', sa.Time(), nullable=True),\n sa.ForeignKeyConstraint(['course_id'], ['courses.id'], ),\n sa.ForeignKeyConstraint(['locations_id'], ['locations.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('reservations',\n sa.Column('student_id', sa.Integer(), nullable=False),\n sa.Column('details_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['details_id'], ['courseDetails.id'], ),\n sa.ForeignKeyConstraint(['student_id'], ['students.id'], ),\n sa.PrimaryKeyConstraint('student_id', 'details_id')\n )\n op.drop_table('course_details')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('course_details',\n sa.Column('id', sa.INTEGER(), nullable=False),\n sa.Column('course_id', sa.INTEGER(), nullable=True),\n sa.Column('locations_id', sa.INTEGER(), nullable=True),\n sa.Column('start_date', sa.DATETIME(), nullable=True),\n sa.Column('end_date', sa.DATETIME(), nullable=True),\n sa.Column('start_time', sa.TIME(), nullable=True),\n sa.Column('end_time', sa.TIME(), nullable=True),\n sa.ForeignKeyConstraint(['course_id'], ['courses.id'], ),\n sa.ForeignKeyConstraint(['locations_id'], ['locations.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.drop_table('reservations')\n op.drop_table('courseDetails')\n # ### end Alembic commands ###\n","repo_name":"loveknight11/Learning-Center","sub_path":"migrations/versions/2892a6f9c0de_coursedetails_table.py","file_name":"2892a6f9c0de_coursedetails_table.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"72714589932","text":"# ----------------------------------------------------------------------------------\n# Self Racing Cars - SRC_model.py\n# ----------------------------------------------------------------------------------\n'''\nPart 1: Build model using keras\n\nPart 2: Setup the data for the generator, perform image augmentation,\nand generate images/steerings to train, validate and test model\n\nPart 3: Main Program for running train, validation and test\n\nBy: Chris Gundling, chrisgundling@gmail.com\n'''\n\nfrom __future__ import print_function\n\nimport numpy as np\nimport pandas as pd\nimport csv\nimport cv2\nimport random\nimport matplotlib as mpl\nimport matplotlib.image as mpimg\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport argparse\nimport os\nimport time\n\nfrom os import path\nfrom collections import defaultdict\nfrom numpy import sin, cos\nfrom scipy.misc import imread, imresize, imsave\nfrom scipy import ndimage\nfrom scipy import misc\n\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom keras.models import Model, Sequential\nfrom keras.preprocessing import image\nfrom keras.layers import Dense, Flatten, Dropout, Input, BatchNormalization\nfrom keras.layers import Convolution2D, MaxPooling2D, AveragePooling2D, GlobalAveragePooling2D\nfrom keras.layers.advanced_activations import ELU\nfrom keras.optimizers import Adam\nfrom keras import backend as K\n\nfrom PIL import Image\nfrom PIL import ImageOps\n\n###########################################################################################\n# Model Structure\n###########################################################################################\n\n'''\nNVIDIA model layers have been modified for 320X160 images. Images should not be resized \nas it will alter the top-down view settings. First layer now uses 8X8 convs with stride 4 \nand the third layer used 2X2 convs with stride 2.\n'''\ndef build_cnn(image_size=None,weights_path=None):\n image_size = image_size or (128, 128)\n if K.image_dim_ordering() == 'th':\n input_shape = (3,) + image_size\n else:\n input_shape = image_size + (3, )\n\n img_input = Input(input_shape)\n\n # Layer 1\n #x = Convolution2D(24, 5, 5, activation='elu', subsample=(2, 2), border_mode='valid', init='he_normal')(img_input)\n x = Convolution2D(24, 8, 8, activation='elu', subsample=(4, 4), border_mode='valid', init='he_normal')(img_input)\n\n # Layer 2\n x = Convolution2D(36, 5, 5, activation='elu', subsample=(2, 2), border_mode='valid', init='he_normal')(x)\n\n # Layer 3\n #x = Convolution2D(48, 5, 5, activation='elu', subsample=(2, 2), border_mode='valid', init='he_normal')(x)\n x = Convolution2D(48, 2, 2, activation='elu', subsample=(2, 2), border_mode='valid', init='he_normal')(x)\n\n # Layer 4\n x = Convolution2D(64, 3, 3, activation='elu', subsample=(1, 1), border_mode='valid', init='he_normal')(x)\n\n # Layer 5\n x = Convolution2D(64, 3, 3, activation='elu', subsample=(1, 1), border_mode='valid', init='he_normal')(x)\n \n # Flatten\n y = Flatten()(x)\n\n # FC 1\n y = Dense(100, activation='elu', init='he_normal')(y)\n\n # FC 2\n y = Dense(50, activation='elu', init='he_normal')(y)\n\n # FC 3\n y = Dense(10, activation='elu', init='he_normal')(y)\n\n # FC 4\n y = Dense(1, init='he_normal')(y)\n\n model = Model(input=img_input, output=y)\n model.compile(optimizer=Adam(lr=1e-4), loss = 'mse')\n return model\n\n##########################################################################################\n# Data Processing and Augmentations\n##########################################################################################\n'''\nGenerator assumes the dataset folder has the following structure:\n\ndriving_log.csv IMG/\n'''\n\n# The following are all the functions used for data processing/augmentation\n# ----------------------------------------------------------------------------------\n\ndef data_setup(steering_log):\n # Read in .csv and store all information numpy arrays and pandas dataframes\n df_steer = pd.read_csv(steering_log,usecols=['center','left','right','steering','speed'],index_col = False)\n df_steer['t1'] = df_steer['center'].str.split('.').str[0]\n df_steer['timestamp'] = df_steer['t1'].str.split('_').str[4:8]\n x = np.zeros((df_steer.shape[0]))\n for i in range(df_steer.shape[0]):\n x[i] = np.int(''.join(df_steer['timestamp'].iloc[i]))\n df_steer['timestamp'] = x\n \n angle = np.zeros((df_steer.shape[0],1))\n time = np.zeros((df_steer.shape[0],1))\n speed = np.zeros((df_steer.shape[0],1))\n \n angle[:,0] = df_steer['steering'].values\n time[:,0] = df_steer['timestamp'].values.astype(int)\n speed[:,0] = df_steer['speed'].values\n \n data = np.append(time,angle,axis=1)\n data = np.append(data,speed,axis=1)\n\n image_paths = pd.read_csv(steering_log,usecols=['center','left','right'],index_col = False)\n return data, image_paths\n\n\ndef read_data(data, image_paths):\n # Convert the .csv info to dictionaries for data generator\n steerings = defaultdict(list)\n speeds = defaultdict(list)\n timestamps = defaultdict(list)\n image_path = defaultdict(list)\n image_path_l = defaultdict(list)\n image_path_r = defaultdict(list)\n for i in range(data.shape[0]):\n time, angle, speed = int(data[i,0]), float(data[i,1]), float(data[i,2])\n steerings[time].append(angle)\n speeds[time].append(speed)\n timestamps[time].append(time)\n image_path[time].append(image_paths['center'].iloc[i])\n image_path_l[time].append(image_paths['left'].iloc[i].strip(' '))\n image_path_r[time].append(image_paths['right'].iloc[i].strip(' '))\n return steerings, speeds, timestamps, image_path, image_path_l, image_path_r\n\n\ndef camera_adjust(angle,speed,camera):\n # Steering angle adjustment for left, right camera\n angle_adj = 0.25\n if camera == 'right':\n angle_adj = -angle_adj\n angle = angle_adj + angle\n return angle\n\n\ndef image_rotate(img):\n # Rotate image randomly to simulate camera jitter\n rotate = random.uniform(-1, 1)\n M = cv2.getRotationMatrix2D((img.shape[1]/2, img.shape[0]/2), rotate, 1)\n img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))\n return img\n\n\ndef image_shift(img):\n # Shift image and transform steering angle\n trans_range = 80\n shift_x = trans_range*np.random.uniform()-trans_range/2 # random.randint(-40, 40)\n shift_y = 0 \n M = np.float32([[1,0,shift_x],[0,1,shift_y]])\n img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))\n ang_adj = shift_x/trans_range*2*.2 #shift_x / 200.\n return img, ang_adj\n\n\ndef image_blur(img):\n # Blur image with random kernel\n kernel_size = random.randint(1, 5)\n if kernel_size % 2 != 1:\n kernel_size += 1\n return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)\n\n\ndef image_HSV(img):\n # HSV brightness transform\n img = cv2.cvtColor(img,cv2.COLOR_RGB2HSV)\n brightness = np.random.uniform(0.5,1.1)\n img[:,:,2] = img[:,:,2]*brightness\n return cv2.cvtColor(img,cv2.COLOR_HSV2RGB)\n\n\ndef image_viewpoint_transform(im, isdeg=True):\n # Viewpoint transform for recovery\n theta = random.randint(-80,80)\n if isdeg:\n theta = np.deg2rad(theta)\n\n f = 2.\n h, w, _ = im.shape\n cx = cz = cos(0)\n sx = sz = sin(0)\n cy = cos(theta)\n sy = sin(theta)\n\n R = np.array([[cz * cy, cz * sy * sx - sz * cx],[sz * cy, sz * sy * sx + cz * cx],[ -sy, cy * sx]], np.float32)\n\n pts1 = [[-w/2, -h/2],[w/2, -h/2],[w/2, h/2],[-w/2, h/2]]\n\n pts2 = []\n mx, my = 0, 0\n for i in range(4):\n pz = pts1[i][0] * R[2][0] + pts1[i][1] * R[2][1];\n px = w / 2 + (pts1[i][0] * R[0][0] + pts1[i][1] * R[0][1]) * f * h / (f * h + pz);\n py = h / 2 + (pts1[i][0] * R[1][0] + pts1[i][1] * R[1][1]) * f * h / (f * h + pz);\n pts2.append([px, py])\n\n pts2 = np.array(pts2, np.float32)\n pts1 = np.array([[0, 0],[w, 0],[w, h],[0, h]], np.float32)\n\n x1, x2 = int(min(pts2[0][0], pts2[3][0])), int(max(pts2[1][0], pts2[2][0]))\n y1, y2 = int(max(pts2[0][1], pts2[1][1])), int(min(pts2[2][1], pts2[3][1]))\n\n M = cv2.getPerspectiveTransform(pts1, pts2)\n dst = cv2.warpPerspective(im, M, (w, h), cv2.INTER_NEAREST | cv2.INTER_NEAREST)\n\n x1 = np.clip(x1, 0, w)\n x2 = np.clip(x2, 0, w)\n y1 = np.clip(y1, 0, h)\n y2 = np.clip(y2, 0, h)\n z = dst[y1:y2, x1:x2]\n x, y, _ = z.shape\n if x == 0 or y == 0:\n return\n return cv2.resize(z, (w, h), interpolation = cv2.INTER_AREA), -np.rad2deg(theta) / 200.\n\n\ndef birds_eye(img): \n # Grab the image shape\n img_size = (img.shape[1], img.shape[0])\n \n # Four Source Points\n src = np.float32(\n [[100, 75],\n [0, 120],\n [200, 75],\n [320, 120]])\n \n # Four Destination Points\n dst = np.float32(\n [[80, 0],\n [100, 160],\n [215, 0],\n [215, 160]])\n \n # Given src and dst points, calculate the perspective transform matrix\n M = cv2.getPerspectiveTransform(src, dst)\n warped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_LINEAR)\n return warped\n \n\ndef read_images(image_log, image_path, ids, image_size):\n # Baseline function for reading images and perspective transform\n imgs = []\n for id in image_path:\n prefix = path.join(image_log,id)\n img = mpimg.imread(prefix)\n \n # Birds Eye\n img = birds_eye(img) \n imgs.append(img)\n \n if len(imgs) < 1:\n print('Error no image at timestamp')\n print(ids)\n \n img_block = np.stack(imgs, axis=0)\n \n if K.image_dim_ordering() == 'th':\n img_block = np.transpose(img_block, axes = (0, 3, 1, 2)) \n return img_block\n\n\ndef image_augment(image_log, image_path, ids, image_size, option):\n imgs = []\n for id in image_path:\n prefix = path.join(image_log,id)\n img = mpimg.imread(prefix)\n\n if option == 1:\n # Flip Image\n img = np.fliplr(img)\n\n # Rotate randomly by small amount (not a viewpoint transform)\n img = image_rotate(img)\n\n # Blur Image\n img = image_blur(img)\n\n # Image Brightness\n img = image_HSV(img)\n #imsave('aug1.jpg', img)\n \n # Birds Eye\n img = birds_eye(img)\n \n # Steering angle not adjusted\n ang_adj = 0.\n\n if option == 2:\n # Birds Eye\n img = birds_eye(img)\n\n # Shift Image\n img, ang_adj = image_shift(img)\n\n if option == 3:\n # Viewpoint Transform\n img, ang_adj = image_viewpoint_transform(img, isdeg=True)\n \n # Birds Eye\n img = birds_eye(img)\n\n imgs.append(img)\n \n if len(imgs) < 1:\n print('Error no image at timestamp')\n print(ids)\n \n img_block = np.stack(imgs, axis=0)\n \n if K.image_dim_ordering() == 'th':\n img_block = np.transpose(img_block, axes = (0, 3, 1, 2))\n return img_block, ang_adj\n\n\ndef normalize_input(x):\n return (x - 128.) / 128. #255.\n\n\ndef exact_output(y):\n return y\n\n\n# Data generator (output steering angles and images)\n# ---------------------------------------------------------------------------------\ndef data_generator(steering_log, image_log, image_folder, gen_type='train',\n camera='center', batch_size=64, time_factor=10, image_size=0.5,\n timestamp_start=None, timestamp_end=None, shuffle=True,\n preprocess_input=normalize_input,\n preprocess_output=exact_output):\n \n # Constants\n # -----------------------------------------------------------------------------\n minmax = lambda xs: (min(xs), max(xs))\n\n # Read all steering angles, speeds and timestamps\n # -----------------------------------------------------------------------------\n data, image_paths = data_setup(steering_log)\n steerings, speeds, image_stamps, image_path, image_path_l, image_path_r = read_data(data, image_paths)\n\n # More data exploration stats\n # -----------------------------------------------------------------------------\n print('timestamp range for all steerings: %d, %d' % minmax(steerings.keys()))\n print('timestamp range for all images: %d, %d' % minmax(image_stamps.keys()))\n print('min and max # of steerings per time unit: %d, %d' % minmax(map(len, steerings.values())))\n print('min and max # of images per time unit: %d, %d' % minmax(map(len, image_stamps.values())))\n \n # Generate images and steerings within one time unit\n # (Mean steering angles used for multiple steering angles within a single unit)\n # (Doesn't apply to simulator data, but does for real world data from car)\n # -----------------------------------------------------------------------------\n start = max(min(steerings.keys()), min(image_stamps.keys()))\n if timestamp_start:\n start = max(start, timestamp_start)\n end = min(max(steerings.keys()), max(image_stamps.keys()))\n if timestamp_end:\n end = min(end, timestamp_end)\n print(\"sampling data from timestamp %d to %d\" % (start, end))\n \n # While loop for data generator\n # -----------------------------------------------------------------------------\n i = start\n if gen_type == 'train':\n thresh = 0.2\n else:\n thresh = 0\n print(thresh)\n epochs = 0\n epoch_num = 0\n bias = 0.\n x_buffer, y_buffer, buffer_size = [], [], 0\n j = 0\n while True:\n if i > end:\n i = start\n\n if gen_type =='train':\n camera_select = 'center' #random.choice(camera) not using left/right\n else:\n camera_select = camera\n\n coin = random.randint(1, 2)\n if steerings[i] and image_stamps[i]:\n if camera_select == 'right':\n if coin == 1:\n images = read_images(image_log, image_path_r[i], image_stamps[i], image_size)\n elif coin == 2:\n option = random.randint(1, 3)\n images, ang_adj = image_augment(image_log, image_path_r[i], image_stamps[i], image_size, option)\n elif camera_select == 'left':\n if coin == 1:\n images = read_images(image_log, image_path_l[i], image_stamps[i], image_size)\n elif coin == 2:\n option = random.randint(1, 3)\n images, ang_adj = image_augment(image_log, image_path_l[i], image_stamps[i], image_size, option)\n elif camera_select == 'center':\n if gen_type == 'train':\n if coin == 1:\n images = read_images(image_log, image_path[i], image_stamps[i], image_size)\n elif coin == 2:\n option = random.randint(1, 3)\n images, ang_adj = image_augment(image_log, image_path[i], image_stamps[i], image_size, option)\n else:\n images = read_images(image_log, image_path[i], image_stamps[i], image_size)\n\n # Mean angle/speed with a timestamp\n angle = np.repeat([np.mean(steerings[i])], images.shape[0])\n speed = np.repeat([np.mean(speeds[i])], images.shape[0])\n\n # Adjust the steerings of the offcenter cameras\n if camera_select != 'center':\n angle = camera_adjust(angle[0],speed[0],camera_select)\n angle = np.repeat([angle], images.shape[0])\n\n # Adjust steering angle for flips and shifts\n if gen_type == 'train':\n if coin == 2 and option == 1:\n angle = -angle\n if coin == 2 and option > 1:\n angle = angle + ang_adj\n\n if (abs(angle) + bias) >= thresh: \n # Pass images and steerings to yield\n x_buffer.append(images)\n y_buffer.append(angle)\n buffer_size += images.shape[0]\n if buffer_size >= batch_size:\n epoch_num += batch_size\n if epoch_num == 8000:\n epochs += 1\n epoch_num = 0\n bias = 0.0 + (epochs*0.05)\n print()\n print(bias)\n if buffer_size >= batch_size:\n indx = range(buffer_size)\n if gen_type == 'train':\n np.random.shuffle(indx)\n x = np.concatenate(x_buffer, axis=0)[indx[:batch_size], ...]\n y = np.concatenate(y_buffer, axis=0)[indx[:batch_size], ...] \n x_buffer, y_buffer, buffer_size = [], [], 0\n yield preprocess_input(x.astype(np.float32)), preprocess_output(y)\n\n if shuffle:\n i = int(random.choice(image_stamps.keys()))\n while i not in image_stamps.keys():\n i = int(random.choice(range(start,end)))\n else:\n i += 1\n while i not in image_stamps.keys():\n i += 1\n if i > end:\n i = start\n\n##########################################################################################\n# Main Program\n##########################################################################################\n\ndef main():\n # Parse arguments\n parser = argparse.ArgumentParser(description=\"Testing Udacity SRC Models\")\n parser.add_argument('--dataset', type=str, help='dataset folder with csv and image folders')\n parser.add_argument('--model', type=str, help='model to evaluate, current list: {cnn}')\n parser.add_argument('--resized-image-height', type=int, help='image resizing')\n parser.add_argument('--resized-image-width', type=int, help='image resizing')\n parser.add_argument('--nb-epoch', type=int, help='# of training epoch')\n parser.add_argument('--camera', type=str, default='center', help='camera to use, default is center')\n parser.add_argument('--batch_size', type=int, default=64, help='training batch size')\n args = parser.parse_args()\n\n # Model and data gen args\n # ---------------------------------------------------------------------------------\n dataset_path = args.dataset\n model_name = args.model\n image_size = (args.resized_image_height, args.resized_image_width)\n camera = args.camera\n camera_train = 'center','right','left'\n batch_size = args.batch_size\n nb_epoch = args.nb_epoch\n weights_path = None\n\n # Data paths\n # ---------------------------------------------------------------------------------\n # build model and train it\n steering_log = path.join(dataset_path, 'driving_log.csv')\n image_log = dataset_path\n camera_images = dataset_path\n epoch = 0\n\n # Model build\n # ---------------------------------------------------------------------------------\n model_builders = {'cnn': (build_cnn, normalize_input, exact_output)}\n\n if model_name not in model_builders:\n raise ValueError(\"unsupported model %s\" % model_name)\n model_builder, input_processor, output_processor = model_builders[model_name]\n model = model_builder(image_size,weights_path)\n print('model %s built...' % model_name)\n \n # Use data_sim.py to generate training data\n # ---------------------------------------------------------------------------------\n if not weights_path:\n train_generator = data_generator(steering_log=steering_log,\n image_log=image_log,\n image_folder=camera_images,\n gen_type='train',\n camera=camera_train,\n batch_size=batch_size,\n image_size=image_size,\n timestamp_start=204030536,\n timestamp_end=210120660,\n shuffle=True,\n preprocess_input=input_processor,\n preprocess_output=output_processor)\n \n # Use data_sim.py to generate validation data\n # -----------------------------------------------------------------------------\n val_generator = data_generator(steering_log=steering_log,\n image_log=image_log,\n image_folder=camera_images,\n gen_type='val',\n camera=camera,\n batch_size=240, \n image_size=image_size,\n timestamp_start=203954079,\n timestamp_end=204030464,\n shuffle=False,\n preprocess_input=input_processor,\n preprocess_output=output_processor)\n \n # Training the model - with EarlyStopping, ModelCheckpoint\n # ------------------------------------------------------------------------------\n callbacks = [EarlyStopping(monitor='val_loss', patience=5, verbose=0), \n ModelCheckpoint(filepath=os.path.join('model_sim_{epoch:02d}.hdf5'), \n monitor='val_loss', verbose=0, save_best_only=False)]\n model.fit_generator(train_generator, samples_per_epoch=8000, nb_epoch=nb_epoch,verbose=1,\n callbacks=callbacks, validation_data=val_generator,nb_val_samples=480)\n\n print('Model was successfully trained and saved...')\n \n\n # Use data generator to generate test data\n # Test set here is same as validation data - seperate script was used for final tests\n # -----------------------------------------------------------------------------------\n test_generator = data_generator(steering_log=steering_log,\n image_log=image_log, \n image_folder=camera_images,\n gen_type='test',\n camera=camera,\n batch_size=480,\n image_size=image_size,\n timestamp_start=203954079,\n timestamp_end=204030464,\n shuffle=False,\n preprocess_input=input_processor,\n preprocess_output=output_processor)\n \n print('Testing...')\n\n test_x, test_y = test_generator.next()\n print('test data shape:', test_x.shape, test_y.shape)\n\n # Store test predictions\n yhat = model.predict(test_x)\n \n # Use dataframe to write results, calculate RMSE and plot actual vs. predicted steerings\n # ------------------------------------------------------------------------------------ \n df_test = pd.read_csv('output1.csv',usecols=['frame_id','steering_angle','pred'],index_col = None)\n df_test['steering_angle'] = test_y\n df_test['pred'] = yhat # test_res\n df_test.to_csv('output2.csv')\n \n # Calculate RMSE\n # ------------------------------------------------------------------------------------\n sq = 0\n mse = 0\n for j in range(test_y.shape[0]):\n sqd = ((yhat[j]-test_y[j])**2)\n sq = sq + sqd\n print(sq)\n mse = sq/480\n rmse = np.sqrt(mse)\n print(\"model evaluated RMSE:\", rmse)\n\n # Plot the results\n # ------------------------------------------------------------------------------------\n plt.figure(figsize = (32, 8))\n plt.plot(test_y, 'r.-', label='target')\n plt.plot(yhat, 'b.-', label='predict')\n plt.legend(loc='best')\n plt.title(\"RMSE Evaluated on 480 TimeStamps: %.4f\" % rmse)\n plt.show()\n model_fullname = \"%s_%d.png\" % (model_name, int(time.time()))\n plt.savefig(model_fullname)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"teamsoulless/thunderhill","sub_path":"models/cg23/SRC_model.py","file_name":"SRC_model.py","file_ext":"py","file_size_in_byte":23816,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"55"} +{"seq_id":"39889637556","text":"import requests\nimport pandas as pd\nimport json\n\n# Assumes you've gotten a HUD census key at ./config/hudkey \n# from https://www.huduser.gov/hudapi/public/register?comingfrom=1\n# Supports Zip->Tract or Tract->Zip\n\nrequest_url = 'https://www.huduser.gov/hudapi/public/register?comingfrom=1'\n\nclass HUDCall():\n def __init__(\n self,\n geo_value: str,\n hud_apikey : str,\n geotype : str\n ):\n self.geotype = geotype\n self.geo_value = geo_value\n self.request = self.call_api(hud_apikey)\n print(self.request.status_code)\n if self.request.status_code ==200:\n self.json = json.loads(self.request.text)\n self.pandas = self._toPandas()\n else:\n RuntimeError(f'Request invalid. Status code {self.request.status_code} received.')\n \n def help(self):\n '''Tag to keep crosswalks straight'''\n print(f'General info: Queries HUD API with available key registered from {request_url}')\n if self.geotype =='zip':\n print('Using zip-tract crosswalk:','Identifies what proportion of a zipcode lies across census tracts.',\n sep='\\n\\t')\n if self.geotype =='tract':\n print('Using tract-zip crosswalk:','Identifies what proportion of a tract lies within a zipcode.',\n sep='\\n\\t')\n print('For more information, please see https://www.huduser.gov/portal/dataset/uspszip-api.html')\n \n\n def call_api(self,apikey ):\n baseurl = 'https://www.huduser.gov/hudapi/public/usps'\n if self.geotype == 'zip': _type = 1\n elif self.geotype =='tract': _type = 6\n if (len(self.geo_value) != 5 and _type ==1):\n raise ValueError('Only 5 digit zipcode supported. Check input.')\n elif (len(self.geo_value) !=11 and _type==6):\n raise ValueError('Census tracts are 11 digits. Check input.')\n \n call = baseurl + f'?type={_type}&query={self.geo_value}'\n request_header = {'Authorization': f'Bearer {apikey}'}\n r = requests.get(call, headers=request_header)\n return r\n\n def _toPandas(self):\n j = self.json['data']\n _tuple = (\n ( j['year'], j['quarter'], j['input'], j['crosswalk_type'], self.geotype,\n j['results'][n]['geoid']) for n, _ in enumerate(j['results']))\n _dict = {}\n for n, t in enumerate(_tuple):\n tmp_val = j['results'][n]\n _dict[t] = {x:tmp_val[x] for x in tmp_val.keys() if 'ratio' in x}\n df = pd.DataFrame.from_dict(_dict, orient='index')\n df.index.set_names(\n ['year','quarter','input_value','crosswalk_type','geotype','crosswalk_value'], \n inplace=True)\n return df\n","repo_name":"tomrod/geohud","sub_path":"hud_geo.py","file_name":"hud_geo.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"43412934868","text":"pilihan=\"Y\"\r\nwhile pilihan==\"Y\":\r\n print(\"\"\"\r\n RESTORAN SEHATI\r\nMENU=\r\n 1. NASI GORENG\r\n 2. MIE GORENG\r\n 3. FUYUNG HAI\r\n 4. NASI PUTIH\r\n 5. ES TEH\r\n 6. ES JERUK\r\n 7. ES DALUMAN\r\n 8. ES CAMPUR\r\n \"\"\")\r\n pesan=str(input(\"masukkan list menu =\"))\r\n jumlahpesan=int(input(\"masukkan jumlah pesanan =\"))\r\n if pesan == \"1\":\r\n listnama= \"NASI GORENG\"\r\n harga=(20000*jumlahpesan)\r\n ppn= int(harga * 0.15)\r\n if jumlahpesan >= 3:\r\n diskon = int(harga*0.1)\r\n totalharga=int(harga-diskon+ppn)\r\n else:\r\n diskon =(0)\r\n totalharga=int(harga+ppn)\r\n elif pesan == \"2\":\r\n listnama= \"MIE GORENG\"\r\n harga = (20000*jumlahpesan)\r\n ppn = int(harga * 0.15)\r\n if jumlahpesan >= 5:\r\n diskon = int(harga * 0.2)\r\n totalharga =int(harga-diskon+ppn)\r\n else:\r\n diskon =(0)\r\n totalharga =int(harga+ppn)\r\n elif pesan == \"3\":\r\n listnama= \"FUYUNG HAI\"\r\n harga=int(15000*jumlahpesan)\r\n ppn = int(harga * 0.15)\r\n diskon=0\r\n totalharga=int(harga+ppn)\r\n elif pesan == \"4\":\r\n listnama= \"NASI PUTIH\"\r\n harga=int(10000*jumlahpesan)\r\n ppn = int(harga * 0.15)\r\n diskon=0\r\n totalharga = int(harga+ppn)\r\n elif pesan == \"5\":\r\n listnama= \"ES TEH\"\r\n harga=int(7000*jumlahpesan)\r\n ppn = int(harga * 0.15)\r\n diskon=0\r\n totalharga = int(harga+ppn)\r\n elif pesan == \"6\":\r\n listnama= \"ES JERUK\"\r\n harga=int(8000*jumlahpesan)\r\n ppn = int(harga * 0.15)\r\n diskon=0\r\n totalharga = int(harga+ppn)\r\n elif pesan == \"7\":\r\n listnama= \"ES DALUMAN\"\r\n harga=int(15000*jumlahpesan)\r\n ppn = int(harga * 0.15)\r\n diskon=0\r\n totalharga = int(harga+ppn)\r\n elif pesan == \"8\":\r\n listnama= \"ES CAMPUR\"\r\n harga=int(15000*jumlahpesan)\r\n ppn = int(harga * 0.15)\r\n diskon=0\r\n totalharga = int(harga+ppn)\r\n else:\r\n pilihan=input(\"menu tidak tersedia, silahkan masukkan abjad menu yang tersedia silahkan ulangi kembali Y/N =\")\r\n \r\n\r\n print()\r\n print(\"PEMBAYARAN\")\r\n print(\"Menu :\",listnama)\r\n print(\"Jumlah Pesan :\", jumlahpesan)\r\n print(\"Harga :\", harga)\r\n print(\"Diskon :\", diskon)\r\n print(\"PPN :\", ppn)\r\n print(\"Jumlah Bayar :\", totalharga)\r\n pilihan=input(\"apakah anda ingin order kembali Y/N =\")\r\n","repo_name":"wahyushintya/code-python-dan-html","sub_path":"restoran.py","file_name":"restoran.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"id","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"27661925074","text":"from PyQt5 import QtWidgets, uic\nfrom PyQt5.QtWidgets import QMessageBox\nimport sys\n \nclass Bmi(QtWidgets.QMainWindow):\n def __init__(self):\n super(Bmi, self).__init__()\n uic.loadUi('bmi.ui', self)\n self.pushButton.clicked.connect(self.onClick)\n\n def onClick(self):\n\n if self.lineEdit.text() == '' or self.lineEdit_2.text() == '':\n QtWidgets.QMessageBox.about(self, \"BMI\", \"Type something\") \n else:\n height = float(self.lineEdit.text())\n mass = float(self.lineEdit_2.text())\n\n bmi = mass / (height*height)\n bmi = round(bmi,2)\n self.outputLabel.setText(str(bmi))\n print('BMI ' + str(bmi))\n\n\napp = QtWidgets.QApplication([])\nwin = Bmi()\nwin.show()\nsys.exit(app.exec())\n","repo_name":"Danielotuo/BMI-App","sub_path":"bmi.py","file_name":"bmi.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"39760003644","text":"# -*- coding: utf-8 -*-\r\n\r\nimport streamlit as st\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nfrom PIL import Image\r\nst.sidebar.title('Indian News Analysis App')\r\ncategories=['india-news','business','education','science',\r\n 'entertainment','opinion','world-news']\r\n\r\ndef FetchTitle(soup):\r\n body_text=soup.find(class_='ins_headline')\r\n text_1=body_text.find_all('h1')\r\n text_2=text_1[0].find_all('span')\r\n title=text_2[0].contents[0]\r\n return title\r\n\r\ndef FetchDate(soup):\r\n try:\r\n body_text=soup.find(class_='ins_dateline')\r\n filtered_text=body_text.find_all('span')\r\n return filtered_text[2].contents\r\n except:\r\n return '23-11-2019'\r\nst.sidebar.title('NDTV')\r\nval=st.sidebar.selectbox('Select Category to See the Details',categories)\r\ncategory=val\r\nst.title(f'All News From {category.capitalize()} Category')\r\nst.sidebar.multiselect('Select Multiple Categories to See the News',categories)\r\nfilename=category+'.txt'\r\nwith open(filename,'r') as f:\r\n for url in f:\r\n url=url.split('\\n')[0]\r\n response=requests.get(url)\r\n soup=BeautifulSoup(response.text,'html.parser')\r\n title=FetchTitle(soup)\r\n date=FetchDate(soup)\r\n st.markdown(f'#### {date}')\r\n st.markdown(f'### [{title}]({url})')\r\n #st.markdown(f'### [{title}]({url})')\r\n ","repo_name":"Shahid7870/indian-news-analysis-app","sub_path":"fetch_news.py","file_name":"fetch_news.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"39783081212","text":"import music21 as m21\nimport numpy as np\n\ndef MIDImidi(yvf,vnorm=80,dur=4,outmidi='./music'):\n\tmt = m21.midi.MidiTrack(1)\n\t# map MIDI velocity to data\n\tyminf = min(yvf)\n\tymaxf = max(yvf)\n\tyvel = (yvf-yminf)/(ymaxf-yminf)*127 \n\tyvel=yvel.astype(int)\n\t# NOTE: full amplitute might be too high volume in some cases\n\tvmin = min(yvel)\n\tvmax = max(yvel)\n\tvel = (yvel-vmin)/(vmax-vmin)*vnorm\n\tvel = vel.astype(int)\n\n\t# duration, pitch, velocity\n\tdata = []\n\tpb = []\n\tfor i in range(yvf.shape[0]):\n\t\tp = [int(1024/dur*abs(yvf[i]-yvf[i-1])+1),\n\t\t\t int(yvf[i]-12//1),\n\t\t\t vel[i]]\n\t\tdata.append(p)\n\t\tpb.append(int(np.around((yvf[i]-12)%1,3)*100))\n\n\tt = 0\n\ttLast = 0\n\tfor d, p, v in data:\n\t\tdt = m21.midi.DeltaTime(mt)\n\t\tdt.time = t - tLast\n\t\t# add to track events\n\t\tmt.events.append(dt)\n\t\t\n\t\tme = m21.midi.MidiEvent(mt, type=\"PITCH_BEND\", channel=1)\n\t\t#environLocal.printDebug(['creating event:', me, 'pbValues[i]', pbValues[i]])\n\t\tme.time = None #d\n\t\tme.setPitchBend(pb[i]) # set values in cents\n\t\tmt.events.append(me)\n\n\t\tdt = m21.midi.DeltaTime(mt)\n\t\tdt.time = t - tLast\n\t\t# add to track events\n\t\tmt.events.append(dt)\n\t\t\n\t\tme = m21.midi.MidiEvent(mt)\n\t\tme.type = \"NOTE_ON\"\n\t\tme.channel = 1\n\t\tme.time = None #d\n\t\tme.pitch = p\n\t\tme.velocity = v\n\t\tmt.events.append(me)\n\n\t\t# add note off / velocity zero message\n\t\tdt = m21.midi.DeltaTime(mt)\n\t\tdt.time = d\n\t\t# add to track events\n\t\tmt.events.append(dt)\n\n\t\tme = m21.midi.MidiEvent(mt)\n\t\tme.type = \"NOTE_ON\"\n\t\tme.channel = 1\n\t\tme.time = None #d\n\t\tme.pitch = p\n\t\tme.velocity = 0\n\t\tmt.events.append(me)\n\n\t\ttLast = t + d # have delta to note off\n\t\tt += d # next time\n\n\t# add end of track\n\tdt = m21.midi.DeltaTime(mt)\n\tdt.time = 0\n\tmt.events.append(dt)\n\n\tme = m21.midi.MidiEvent(mt)\n\tme.type = \"END_OF_TRACK\"\n\tme.channel = 1\n\tme.data = '' # must set data to empty string\n\tmt.events.append(me)\n\n\t# for e in mt.events:\n\t# print e\n\n\tmf = m21.midi.MidiFile()\n\tmf.ticksPerQuarterNote = 1024 # cannot use: 10080\n\tmf.tracks.append(mt)\n\n\tmf.open(outmidi+'.mid', 'wb')\n\n\tmf.write()\n\tmf.close()\n","repo_name":"marcobn/musicntwrk","sub_path":"musicntwrk-2.0/src/data/MIDImidi.py","file_name":"MIDImidi.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"55"} +{"seq_id":"72189535533","text":"\"\"\"\nCuidados com dados mutáveis\n= - copiado o valor (imutáveis)\n= - aponta para o mesmo valor na memória (mutável)\n\"\"\"\n\nlista_a = ['Felipe', 'Marina', 1, True, 1.2]\nlista_b = lista_a.copy()\n\nlista_a[0] = 'Leite'\nprint(lista_b)\nprint(lista_a)","repo_name":"marina6coneto/Reposit-rio","sub_path":"aula55.py","file_name":"aula55.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"19403479752","text":"#-----------------------------------------------------------------------\n\n### TEST ###\n\n#-----------------------------------------------------------------------\n\nfrom database.post_methods import *\nfrom database.moderator_methods import *\nfrom database.get_methods import *\nfrom database.strings import uri\nfrom pymongo import MongoClient\n\n#-----------------------------------------------------------------------\n\ndef test():\n client = MongoClient(uri)\n\n def print_collections(client, commentids, postid, groupid):\n print(get_comments(client, commentids))\n print(\"\")\n print(get_post(client, postid))\n print(\"\")\n print(get_group(client, groupid))\n print(\"\")\n print(get_user_infos(client, ['user1', 'user2', 'user3']))\n print(\"\")\n print(\"__________\")\n print(\"\")\n\n # create user1, 2, 3\n insert_user(client, 'user1')\n insert_user(client, 'user2')\n insert_user(client, 'user3')\n # user1 creates group\n groupid = insert_group(client, 'user1', 'Princeton University', \"World's no. 1 University\", 'orange')\n # user1 adds user2 and user3 to the group\n add_user_to_group(client, groupid, 'user2')\n add_user_to_group(client, groupid, 'user3')\n # user2 posts\n postid = insert_post(client, 'user2', groupid, 'Princeton Students', 'What are Princeton Students like?')\n # user1 and user3 comments\n commentids = []\n commentids.append(insert_comment(client, 'user1', postid, 'Smart'))\n commentids.append(insert_comment(client, 'user3', postid, 'Over-worked'))\n # makes user2 moderator\n promote_to_moderator(client, groupid, 'user2')\n # demote user1 from being moderator\n demote_from_moderator(client, groupid, 'user1')\n print_collections(client, commentids, postid, groupid)\n\n # delete group\n delete_group(client, groupid)\n print_collections(client, commentids, postid, groupid)\n # remove users\n db = client[database_name]\n user_col = db[user_collection_title]\n user_col.delete_many({\"_id\": {\"$in\": ['user1', 'user2', 'user3']}})\n print_collections(client, commentids, postid, groupid)\n\nif __name__ == \"__main__\":\n test() ","repo_name":"piercemaloney/TigerGroups","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"16000613670","text":"from datetime import datetime, timedelta\nimport pickle\n\nsession_gap = timedelta(hours=1)\n\n\n\n# Reconstruction start\n\nf1_name = '_hi_userEditsPickle.pkl'\nf_name = '_hi_userSessionsPickle.pkl'\npickled_file_number = 19\n\n\ndef list_to_session(l):\n\tsession_list = []\n\tcurr_session = []\n\tcurr_session.append(l[0])\n\tfor i in xrange(1, len(l)):\n\t\tif (l[i] - curr_session[-1]) > session_gap:\n\t\t\tsession_list.append(curr_session)\n\t\t\tcurr_session = []\n\t\tcurr_session.append(l[i])\n\n\tsession_list.append(curr_session)\n\treturn session_list\n\nfor i in xrange(1, pickled_file_number+1):\n\tuserEdits = {}\n\tf = open(\"pickled/edits/\" + str(i) + f1_name, 'rb')\n\ttmp_list = pickle.load(f)\n\tfor t in tmp_list:\n\t\tl = list_to_session(t[1])\n\t\tuserEdits[t[0]] = l\n\tf.close()\n\n\titem_list = userEdits.items()\n\tf = open(\"pickled/sessions/\" + str(i) + f_name, 'wb')\n\tpickle.dump(item_list, f, -1)\n\tf.close()\n\n# Reconstruction end","repo_name":"omirho/wikipedia-mining","sub_path":"pickled_to_sessions.py","file_name":"pickled_to_sessions.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"1283906186","text":"# Use index based search\nimport logging\nfrom datetime import datetime\nfrom mongoengine import *\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s : %(levelname)s : %(name)s : %(message)s')\n\n# Connection\nconnection = connect(db=\"library_book\", host=\"192.168.56.103\", port=27017)\n\n\n# # Non Index Based Search\n# # Book\n# class BookNonIndex(Document):\n# name = StringField()\n#\n#\n# # Create and search\n# b1 = BookNonIndex(name=\"Theory of Relativity\")\n# b2 = BookNonIndex(name=\"Discovery of India\")\n# b1.save()\n# b2.save()\n#\n# # Search\n# logging.info(\"Searching\")\n# logging.info(BookNonIndex.objects(name=\"Theory of Relativity\"))\n# logging.info(\"Query Explain :\")\n# logging.info(BookNonIndex.objects(name=\"Theory of Relativity\").explain())\n# You should see COLLSCAN (Collection Scan) meaning you doing full table scan\n\n\n# Non Index Based Search\n# Book\nclass BookIndex(Document):\n name = StringField()\n meta = {\n 'indexes': [\n 'name'\n ]\n }\n# We can create more than one index by adding element in list and create compound index by (e1, e2) and\n# Also create index in reverse order by specifying negation (e1, -e2)\n\n\n# Create and search\nb1 = BookIndex(name=\"Theory of Relativity\")\nb2 = BookIndex(name=\"Discovery of India\")\nb1.save()\nb2.save()\n\n# Search\nlogging.info(\"Searching\")\nlogging.info(BookIndex.objects(name=\"Theory of Relativity\"))\nlogging.info(\"Query Explain :\")\nlogging.info(BookIndex.objects(name=\"Theory of Relativity\").explain())\n# You should see IXSCAN to denote scan in Index\n\n# Note to much index can degrade performance in write\n\n# Create Index\n# logging.info(\"Create new Index\")\n# BookIndex.create_index('-name')\n# db.book_index.getIndexes() <- Show all Indexes\n\n# Drop Index\nc = BookIndex._get_collection()\nc.drop_index('name_1')\n\nlogging.info(\"Disconnecting\")\ndisconnect()\n","repo_name":"sankamuk/NoSQLCheatsheet","sub_path":"05/sources/search_by_index.py","file_name":"search_by_index.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"5135270587","text":"import os\nfrom typing import Any, Callable, Dict, List, Optional, Set, Union, Tuple\n\nimport pandas as pd\nfrom mmproteo.utils import log, visualization\nfrom mmproteo.utils.formats.mgf import read_mgf\nfrom mmproteo.utils.formats.mz import read_mzid, read_mzml\nfrom pyteomics.mgf import MGFBase\nfrom pyteomics.mzid import MzIdentML\nfrom pyteomics.mzml import MzML\n\n\ndef iter_entries(iterator: Union[MGFBase, MzIdentML, MzML], logger: log.Logger = log.DEFAULT_LOGGER) \\\n -> List[Dict[str, Any]]:\n logger.debug(\"Iterator type = \" + str(type(iterator)))\n entries = list(iterator)\n if len(entries) > 0 and logger.is_verbose():\n logger.debug(\"Length: %d\" % len(entries))\n logger.debug(\"Example:\\n\" + visualization.pretty_print_json(entries[0]))\n return entries\n\n\ndef read_parquet(filename: str, logger: log.Logger = log.DEFAULT_LOGGER) -> pd.DataFrame:\n return pd.read_parquet(filename)\n\n\n_FILE_READING_CONFIG: Dict[\n str,\n Union[Callable[[str, log.Logger], pd.DataFrame],\n Callable[[str, log.Logger, Any], pd.DataFrame]]\n] = {\n \"mgf\": read_mgf,\n \"mzid\": read_mzid,\n \"mzml\": read_mzml,\n \"parquet\": read_parquet,\n}\n\n\ndef get_readable_file_extensions() -> Set[str]:\n return set(_FILE_READING_CONFIG.keys())\n\n\ndef read(\n filename: str,\n filename_col: Optional[str] = \"%s_filename\",\n logger: log.Logger = log.DEFAULT_LOGGER,\n **kwargs: Any,\n) -> pd.DataFrame:\n _, ext = separate_extension(filename=filename, extensions=get_readable_file_extensions())\n\n if len(ext) > 0:\n logger.debug(\"Started reading %s file '%s'\" % (ext, filename))\n df = _FILE_READING_CONFIG[ext](filename, logger, **kwargs) # type: ignore\n logger.info(\"Finished reading %s file '%s'\" % (ext, filename))\n else:\n raise NotImplementedError\n if filename_col is not None:\n if \"%s\" in filename_col:\n col = filename_col % ext\n else:\n col = filename_col\n if col in df.columns:\n logger.warning(\"'%s' already exists in DataFrame columns. Please choose a different column name.\")\n else:\n df[col] = filename.split(os.sep)[-1]\n return df\n\n\ndef separate_extension(filename: str, extensions: Set[str]) -> Tuple[str, str]:\n lower_filename = filename.lower()\n longest_extension = \"\"\n for ext in extensions:\n if lower_filename.endswith(\".\" + ext) and len(longest_extension) < len(ext):\n longest_extension = ext\n\n if len(longest_extension) > 0:\n base_filename = filename[:len(filename) - len(longest_extension) - len(\".\")]\n return base_filename, longest_extension\n else:\n return filename, \"\"\n","repo_name":"Miroka96/mmproteo","sub_path":"src/mmproteo/utils/formats/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"9217243301","text":"import random\r\n\r\ndef jogar_adivinhacao():\r\n print(\"------------------------------\")\r\n print(\"Bem vindo o jogo de advinhação!\")\r\n print(\"------------------------------\")\r\n\r\n random.seed(100)\r\n numero_secreto = random.randrange(1,101)\r\n\r\n rodada = 1\r\n tentativas = 0\r\n pontos = 1000\r\n\r\n print(\"Qual o nivel de dificuldade?\")\r\n print(\"(1) Fácil (2) Médio (3) Difícil\")\r\n\r\n nivel = int(input(\"Escolha o nível: \"))\r\n\r\n if(nivel == 1):\r\n tentativas = 10\r\n elif(nivel == 2):\r\n tentativas = 5\r\n else:\r\n tentativas = 3\r\n\r\n for rodada in range(1,tentativas + 1):\r\n print(\"Tentativa {} de {}\".format(rodada, tentativas))\r\n numer\r\n\r\n o = input(\"Digite um número de 0 a 100: \")\r\n\r\n chute = int(numero)\r\n\r\n if(chute < 1 or chute > 100):\r\n print(\"Por favor, digite um numero entre 1 e 100\")\r\n continue\r\n\r\n acertou = chute == numero_secreto\r\n maior = chute > numero_secreto\r\n menor = chute < numero_secreto\r\n\r\n if(acertou):\r\n print(\"você acertou e fez {} pontos!\".format(pontos))\r\n break\r\n else:\r\n if (maior):\r\n print(\"você errou, seu numero é maior que o numero secreto\")\r\n elif (menor):\r\n print(\"Você errou, seu numero é menor que o numero secreto\")\r\n pontos_perdidos = abs(numero_secreto - chute)\r\n pontos = pontos - pontos_perdidos\r\n\r\n print(\"Fim do jogo!\")\r\n\r\nif(__name__==\"__main__\"):\r\n jogar_adivinhacao()","repo_name":"gustavodamaceno1/python3","sub_path":"advinha.py","file_name":"advinha.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"17782050096","text":"#! /usr/bin/env python3\n\n\"\"\"A more efficient VM translator for the book's CPU.\n\nUses a single trick: when an opcode is encountered, if the opcode pushes a value on to the stack,\nthe value is simply left in D and the translator remembers that this was done. If the next opcode\nconsumes the top of the stack, it can usually generate a simpler sequence using the value from D.\nOtherwise, the value is pushed and then the usual opcodes are emitted.\n\nNote on debugging: this tends to make tracing hard to interpret, because whenever a stack operation\nis omitted, the stack just looks wrong in the trace. Maybe the registers should be exposed so\ntrace() could at least show the value?\n\"\"\"\n\nfrom nand.platform import Platform, BUNDLED_PLATFORM\nfrom nand.translate import AssemblySource, translate_dir\nfrom nand.solutions import solved_05, solved_06, solved_07\n\n\nclass Translator(solved_07.Translator):\n def __init__(self):\n self.asm = AssemblySource()\n\n solved_07.Translator.__init__(self, self.asm)\n\n self.top_in_d = False\n\n def finish(self):\n self._fix_stack()\n\n def push_constant(self, value):\n self._fix_stack()\n\n # TODO: this is _costing_ one instruction when the following instr. can't take it\n # from D, by doing D=0/1 ... M=D instead of folding the constant in.\n self.asm.start(f\"push constant {value}\")\n if value <= 1:\n self.asm.instr(f\"D={value}\")\n else:\n self.asm.instr(f\"@{value}\")\n self.asm.instr(f\"D=A\")\n self.top_in_d = True\n\n def lt(self):\n self._fix_stack()\n solved_07.Translator.lt(self)\n\n def eq(self):\n self._fix_stack()\n solved_07.Translator.eq(self)\n\n def gt(self):\n self._fix_stack()\n solved_07.Translator.gt(self)\n\n\n def _binary(self, opcode, op):\n if self.top_in_d:\n self.asm.start(opcode + \" (from D)\")\n self.asm.instr(\"@SP\")\n self.asm.instr(\"AM=M-1\")\n self.asm.instr(f\"D={op}\")\n # Note: this isn't really a win if the next instruction is going to just push.\n else:\n solved_07.Translator._binary(self, opcode, op)\n\n def _unary(self, opcode, op):\n if self.top_in_d:\n self.asm.start(opcode + \" (from D)\")\n self.asm.instr(f\"D={op.replace('M', 'D')}\")\n # Note: and it stays in D\n else:\n solved_07.Translator._unary(self, opcode, op)\n\n def _pop_segment(self, segment_name, segment_ptr, index):\n # Believe it or not, using this unrolled loop for indexes all the way to 13\n # makes the code smaller overall (empirically determined.)\n if self.top_in_d and index <= 13:\n self.asm.start(f\"pop {segment_name} {index} (from D)\")\n self.asm.instr(f\"@{segment_ptr}\")\n if index == 0:\n self.asm.instr(\"A=M\")\n else:\n self.asm.instr(\"A=M+1\")\n for _ in range(index-1):\n self.asm.instr(\"A=A+1\")\n self.asm.instr(\"M=D\")\n self.top_in_d = False\n else:\n self._fix_stack()\n solved_07.Translator._pop_segment(self, segment_name, segment_ptr, index)\n\n def pop_temp(self, index):\n assert 0 <= index < 8\n if not self.top_in_d: # Beautiful: only this conditional is added\n self.asm.start(f\"pop temp {index}\")\n self._pop_d()\n else:\n self.asm.start(f\"pop temp {index} (from D)\")\n self.top_in_d = False\n self.asm.instr(f\"@R{5+index}\")\n self.asm.instr(\"M=D\")\n\n def _push_segment(self, segment_name, segment_ptr, index):\n self._fix_stack()\n\n self.asm.start(f\"push {segment_name} {index}\")\n if index == 0:\n self.asm.instr(f\"@{segment_ptr}\")\n self.asm.instr(\"A=M\")\n self.asm.instr(\"D=M\")\n elif index == 1:\n self.asm.instr(f\"@{segment_ptr}\")\n self.asm.instr(\"A=M+1\")\n self.asm.instr(\"D=M\")\n elif index == 2:\n self.asm.instr(f\"@{segment_ptr}\")\n self.asm.instr(\"A=M+1\")\n self.asm.instr(\"A=A+1\")\n self.asm.instr(\"D=M\")\n else:\n self.asm.instr(f\"@{index}\")\n self.asm.instr(\"D=A\")\n self.asm.instr(f\"@{segment_ptr}\")\n self.asm.instr(\"A=D+M\")\n self.asm.instr(\"D=M\")\n self.top_in_d = True\n\n def push_temp(self, index):\n assert 0 <= index < 8\n\n self._fix_stack()\n\n self.asm.start(f\"push temp {index}\")\n self.asm.instr(f\"@R{5+index}\")\n self.asm.instr(\"D=M\")\n self.top_in_d = True\n\n\n def pop_pointer(self, index):\n if self.top_in_d:\n self.asm.start(f\"pop pointer {index} (from D)\")\n segment_ptr = (\"THIS\", \"THAT\")[index]\n self.asm.instr(f\"@{segment_ptr}\")\n self.asm.instr(\"M=D\")\n self.top_in_d = False\n else:\n solved_07.Translator.pop_pointer(self, index)\n\n def push_pointer(self, index):\n self._fix_stack()\n\n self.asm.start(f\"push pointer {index}\")\n segment_ptr = (\"THIS\", \"THAT\")[index]\n self.asm.instr(f\"@{segment_ptr}\")\n self.asm.instr(\"D=M\")\n self.top_in_d = True\n\n\n def pop_static(self, index):\n if self.top_in_d:\n self.asm.start(f\"push static {index} (from D)\")\n self.asm.instr(f\"@{self.class_namespace}.static{index}\")\n self.asm.instr(\"M=D\")\n self.top_in_d = False\n else:\n solved_07.Translator.pop_static(self, index)\n\n def push_static(self, index):\n self._fix_stack()\n\n self.asm.start(f\"push static {index}\")\n self.asm.instr(f\"@{self.class_namespace}.static{index}\")\n self.asm.instr(\"D=M\")\n self.top_in_d = True\n\n\n def label(self, name):\n self._fix_stack()\n solved_07.Translator.label(self, name)\n\n def if_goto(self, name):\n if self.top_in_d:\n self.asm.start(f\"if-goto {name} (from D)\")\n self.asm.instr(f\"@{self.function_namespace}${name}\")\n self.asm.instr(\"D;JNE\")\n self.top_in_d = False\n else:\n solved_07.Translator.if_goto(self, name)\n\n def goto(self, name):\n self._fix_stack()\n solved_07.Translator.goto(self, name)\n\n\n def function(self, class_name, function_name, num_vars):\n assert not self.top_in_d\n solved_07.Translator.function(self, class_name, function_name, num_vars)\n\n def return_op(self):\n # TODO: an alt. return handler?\n self._fix_stack()\n solved_07.Translator.return_op(self)\n\n def call(self, class_name, function_name, num_args):\n self._fix_stack()\n solved_07.Translator.call(self, class_name, function_name, num_args)\n\n\n def _fix_stack(self):\n if self.top_in_d:\n self._push_d()\n self.top_in_d = False\n\n\nLAZY_PLATFORM = BUNDLED_PLATFORM._replace(\n translator=Translator)\n\n\nif __name__ == \"__main__\":\n # Note: this import requires pygame; putting it here allows the tests to import the module\n import computer\n\n computer.main(LAZY_PLATFORM)\n","repo_name":"mossprescott/pynand","sub_path":"alt/lazy.py","file_name":"lazy.py","file_ext":"py","file_size_in_byte":7222,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"55"} +{"seq_id":"16078338594","text":"from data import question_data\r\nfrom question_model import Question\r\nfrom quiz_brain import QuizBrain\r\nquestion_object = []\r\nfor question in question_data:\r\n new_question = question[\"text\"]\r\n new_answer = question[\"answer\"]\r\n new_object = Question(new_question,new_answer)\r\n question_object.append(new_object)\r\nquiz = QuizBrain(question_object)\r\nwhile quiz.still_has_question():\r\n quiz.next_question()\r\n\r\nprint(\"\\nYou just completed the quiz\")\r\nprint(f\"You get {quiz.score}/{len(question_object)}\")","repo_name":"sourav4u/Quiz_Game","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"17893803457","text":"from collections import Counter\nfrom heapq import heappush, heappop\n\ndef topKFrequent(nums, k):\n freq_counter = Counter(nums)\n priority_queue = []\n for i in freq_counter:\n heappush(priority_queue, (-freq_counter[i], i))\n\n res = []\n while k:\n i, j = heappop(priority_queue)\n res.append(j)\n k -= 1\n\n return res\n \ndef topKFrequent(self, nums: List[int], k: int) -> List[int]:\n from collections import Counter\n \n freq_counter = Counter(nums)\n freq_sorted = sorted(freq_counter, key=freq_counter.get, reverse=True)\n return freq_sorted[:k]","repo_name":"amit-singh-rathore/problem-solving-nov","sub_path":"problems/53-TopKFrequentElements/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"43733120249","text":"from datetime import datetime\r\nimport os\r\nimport requests\r\n\r\napi_key = 'dfaeda882c810caadceb818b5e5e2337'\r\nlocation = input(\"Enter the city name: \")\r\n\r\ncomplete_api_link = \"https://api.openweathermap.org/data/2.5/weather?q=\"+location+\"&appid=\"+api_key\r\napi_link = requests.get(complete_api_link)\r\napi_data = api_link.json()\r\n\r\ntemp_city = ((api_data['main']['temp']) - 273.15)\r\nweather_desc = api_data['weather'][0]['description']\r\nhmdt = api_data['main']['humidity']\r\nmax_temp = api_data['main']['temp_max']\r\nmin_temp =api_data['main']['temp_min']\r\nwind_spd = api_data['wind']['speed']\r\ndate_time = datetime.now().strftime(\"%d %b %Y | %I:%M:%S %p\")\r\n\r\nwith open('weather.txt','wt') as f:\r\n f.write(api_link.text)\r\n\r\nprint (\"-------------------------------------------------------------\")\r\nprint (\"Weather Stats for - {} || {}\".format(location.upper(), date_time))\r\nprint (\"-------------------------------------------------------------\")\r\n\r\nprint (\"Current temperature is: {:.2f} deg C\".format(temp_city))\r\nprint (\"Current weather desc :\",weather_desc)\r\nprint(\"maximum temperature :\",max_temp-273.15)\r\nprint(\"minimum temperature :\",min_temp-273.05)\r\nprint (\"Current Humidity :\",hmdt, '%')\r\nprint (\"Current wind speed :\",wind_spd ,'kmph')","repo_name":"Ashik-Muhammed/shapeaiproject","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"11703376268","text":"import torch\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import Dataset\n\nfrom .. import constants\nfrom ..utils import load_model\n\n\nclass LettersDatasetTest(Dataset):\n def __init__(self):\n test = [\n [\n [0, 0, 1, 0, 0],\n [0, 1, 0, 1, 0],\n [1, 0, 0, 0, 1],\n [1, 0, 0, 0, 1],\n [1, 0, 0, 1, 1],\n [1, 0, 0, 0, 1],\n [1, 0, 0, 0, 1],\n ],\n [\n [1, 1, 1, 0, 0],\n [1, 0, 0, 1, 0],\n [0, 0, 0, 1, 0],\n [0, 1, 1, 1, 0],\n [0, 0, 0, 1, 0],\n [1, 0, 0, 1, 0],\n [1, 1, 1, 0, 0],\n ],\n [\n [1, 1, 1, 0, 0],\n [1, 1, 1, 1, 0],\n [0, 1, 0, 1, 0],\n [0, 1, 1, 1, 0],\n [0, 0, 0, 1, 0],\n [1, 0, 0, 1, 0],\n [1, 1, 1, 0, 0],\n ],\n [\n [1, 1, 1, 1, 0],\n [1, 0, 0, 0, 0],\n [1, 0, 0, 0, 0],\n [1, 0, 0, 0, 0],\n [1, 0, 0, 0, 0],\n [1, 0, 0, 0, 0],\n [1, 1, 1, 1, 0],\n ]\n ]\n self.x = torch.tensor(test, dtype=torch.float32)\n labels = [0, 1, 1, 2]\n self.y = torch.tensor(labels)\n self.n_samples = len(labels)\n\n def __getitem__(self, index):\n return self.x[index], self.y[index]\n\n def __len__(self):\n return self.n_samples\n\n\nif __name__ == '__main__':\n\n test_dataset = LettersDatasetTest()\n test_loader = DataLoader(dataset=test_dataset)\n\n loaded_model = load_model(constants.PATH)\n\n with torch.no_grad():\n n_correct = 0\n n_samples = 0\n for images, labels in test_loader:\n images = images.reshape(-1, 5 * 7)\n outputs = loaded_model(images)\n # max returns (value ,index)\n _, predicted = torch.max(outputs.data, 1)\n n_samples += labels.size(0)\n n_correct += (predicted == labels).sum().item()\n\n acc = 100.0 * n_correct / n_samples\n print(f'Accuracy of the network on the test images: {acc} %')\n","repo_name":"SzymonSzczot/DrawGithubBoard","sub_path":"ml_app/test/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"1135738172","text":"\"\"\"\r\n Dense pose estimation module no. 1\r\n\r\n Copyright (C) 2020 Siemens AG\r\n SPDX-License-Identifier: MIT\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom torchvision import transforms\r\nimport yaml\r\nfrom yaml import CLoader\r\n\r\n\r\ndef read_cfg_string(cfg, section, key, default):\r\n \"\"\"\r\n Read string from a config file\r\n Args:\r\n cfg: config file\r\n section: [section] of the config file\r\n key: key to be read\r\n default: value if couldn't be read\r\n\r\n Returns: resulting string\r\n\r\n \"\"\"\r\n if cfg.has_option(section, key):\r\n return cfg.get(section, key)\r\n else:\r\n return default\r\n\r\n\r\ndef read_cfg_int(cfg, section, key, default):\r\n \"\"\"\r\n Read int from a config file\r\n Args:\r\n cfg: config file\r\n section: [section] of the config file\r\n key: key to be read\r\n default: value if couldn't be read\r\n\r\n Returns: resulting int\r\n\r\n \"\"\"\r\n if cfg.has_option(section, key):\r\n return cfg.getint(section, key)\r\n else:\r\n return default\r\n\r\n\r\ndef read_cfg_float(cfg, section, key, default):\r\n \"\"\"\r\n Read float from a config file\r\n Args:\r\n cfg: config file\r\n section: [section] of the config file\r\n key: key to be read\r\n default: value if couldn't be read\r\n\r\n Returns: resulting float\r\n\r\n \"\"\"\r\n if cfg.has_option(section, key):\r\n return cfg.getfloat(section, key)\r\n else:\r\n return default\r\n\r\n\r\ndef read_cfg_bool(cfg, section, key, default):\r\n \"\"\"\r\n Read bool from a config file\r\n Args:\r\n cfg: config file\r\n section: [section] of the config file\r\n key: key to be read\r\n default: value if couldn't be read\r\n\r\n Returns: resulting bool\r\n\r\n \"\"\"\r\n if cfg.has_option(section, key):\r\n return cfg.get(section, key) in ['True', 'true']\r\n else:\r\n return default\r\n\r\n\r\ndef read_cfg_cam(cfg, section, key, default):\r\n \"\"\"\r\n Read camera matrix from a config file\r\n Args:\r\n cfg: config file\r\n section: [section] of the config file\r\n key: key to be read\r\n default: value if couldn't be read\r\n\r\n Returns: resulting camera matrix\r\n\r\n \"\"\"\r\n if cfg.has_option(section, key):\r\n str = cfg.get(section, key).split(',')\r\n cam = np.array([[float(str[0]), 0., float(str[1])],\r\n [0., float(str[2]), float(str[3])],\r\n [0., 0., 1.]])\r\n return cam\r\n else:\r\n return default\r\n\r\n\r\ndef read_cfg_intrinsics(cfg, section, key, default):\r\n \"\"\"\r\n Read intrinsics from a config file\r\n Args:\r\n cfg: config file\r\n section: [section] of the config file\r\n key: key to be read\r\n default: value if couldn't be read\r\n\r\n Returns: resulting intrinsic dict\r\n\r\n \"\"\"\r\n if cfg.has_option(section, key):\r\n str = cfg.get(section, key).split(',')\r\n\r\n intinsics = {\r\n \"x0\": 320,\r\n \"y0\": 240,\r\n \"fx\": float(str[0]),\r\n \"fy\": float(str[2])\r\n }\r\n return intinsics\r\n else:\r\n return default\r\n\r\n\r\ndef read_cfg_resolution(cfg, section, key, default):\r\n \"\"\"\r\n Read input image resolution from a config file\r\n Args:\r\n cfg: config file\r\n section: [section] of the config file\r\n key: key to be read\r\n default: value if couldn't be read\r\n\r\n Returns: resulting resolution tuple\r\n\r\n \"\"\"\r\n if cfg.has_option(section, key):\r\n str = cfg.get(section, key).split(',')\r\n resolution = (int(str[0]), int(str[1]))\r\n return resolution\r\n else:\r\n return default\r\n\r\n\r\ndef load_yaml(dir_path):\r\n \"\"\"\r\n Load YAML file to read datasets\r\n Args:\r\n dir_path: path to the file\r\n\r\n Returns: corresponding Python object\r\n\r\n \"\"\"\r\n with open(dir_path, 'r') as stream:\r\n data = yaml.load(stream, Loader=CLoader)\r\n\r\n return data\r\n\r\n\r\n# Data transformation and augmentation routines\r\nnormalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\r\n std=[0.229, 0.224, 0.225])\r\n\r\npreprocess = transforms.Compose([\r\n transforms.ToTensor(),\r\n])\r\n\r\npreprocess_test = transforms.Compose([\r\n transforms.ToTensor(),\r\n normalize\r\n])\r\n\r\npreprocess_rgb = transforms.Compose([\r\n transforms.ColorJitter(brightness=32. / 255., contrast=0.5, saturation=0.5, hue=0.2), #TODO was 0.05\r\n transforms.ToTensor(),\r\n normalize\r\n])\r\n\r\npreprocess_rgb_refinement = transforms.Compose([\r\n transforms.ColorJitter(brightness=1. / 255., contrast=0.00001, saturation=0.0001, hue=0.05), #TODO was 0.05\r\n transforms.ToTensor(),\r\n normalize\r\n])","repo_name":"zakharos/DPOD","sub_path":"utils/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4654,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"55"} +{"seq_id":"24937240279","text":"# -*- coding: UTF-8 -*-\n\"\"\"\n=================================================\nProblem: 面试题13. 机器人的运动范围\nWebsite: https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/\nDifficulty: 简单\nAuthor: ZYZ\nLanguage: Python3\nResult: Accepted\nRuntime: 52 ms, 在所有 Python3 提交中击败了90.28%的用户\nMemory Usage: 13.5 MB, 在所有 Python3 提交中击败了100.00%的用户\n==================================================\"\"\"\n\n\nclass Solution:\n \"\"\"\n 地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。\n 一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),\n 不能进入行坐标和列坐标的数位之和大于k的格子。\n 例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。\n 但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?\n \"\"\"\n def movingCount(self, m: int, n: int, k: int) -> int:\n res = 0\n if k >= 9:\n for i in range(min(m, (k - 8) * 10 + 9)):\n for j in range(min(n, (k - 8) * 10 + 9)):\n if i + j >= (k - 8) * 10 + 9:\n break\n if self.separate(i, j) <= k:\n res += 1\n else:\n for i in range(min(m, 9)):\n for j in range(min(n, 9)):\n if i + j <= k:\n res += 1\n return res\n \n def separate(self, m, n):\n r = 0\n for c in str(m):\n r += int(c)\n for c in str(n):\n r += int(c)\n return r\n\n\"\"\"\nhttps://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/solution/mian-shi-ti-13-ji-qi-ren-de-yun-dong-fan-wei-dfs-b/\n\"\"\"\n\n\"\"\"\n搜索的方向只需要朝下或朝右\n\ndef digitsum(n):\n ans = 0\n while n:\n ans += n % 10\n n //= 10\n return ans\n\nclass Solution:\n def movingCount(self, m: int, n: int, k: int) -> int:\n vis = set([(0, 0)])\n for i in range(m):\n for j in range(n):\n if ((i - 1, j) in vis or (i, j - 1) in vis) and digitsum(i) + digitsum(j) <= k:\n vis.add((i, j))\n return len(vis)\n\n作者:LeetCode-Solution\n链接:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/solution/ji-qi-ren-de-yun-dong-fan-wei-by-leetcode-solution/\n来源:力扣(LeetCode)\n著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\n\"\"\"\n","repo_name":"Zesunlight/Online-Judge","sub_path":"剑指Offer/13_机器人的运动范围.py","file_name":"13_机器人的运动范围.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"37214123206","text":"import os\nimport setuptools\n\nwith open('README.md') as file:\n long_description = file.read()\n\nsetuptools.setup(\n name=\"typemallow\",\n version=\"0.0.4\",\n url=\"https://github.com/adenh93/typemallow\",\n\n author=\"Aden Herold\",\n author_email=\"aden.herold1@gmail.com\",\n\n description=\"An elegant and automatic solution for generating/outputting Typescript interfaces from your Marshmallow Schemas.\",\n long_description=long_description,\n long_description_content_type='text/markdown',\n keywords=['Marshmallow', 'Typescript', 'Python', 'Flask', 'Django'],\n\n packages=['typemallow'],\n include_package_data=True,\n zip_safe=False,\n platforms='any',\n\n install_requires=[\n 'marshmallow'\n ]\n)\n","repo_name":"adenh93/typemallow","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"55"} +{"seq_id":"34964234107","text":"class Tool(object):#Python中类也是一个对象,叫类对象(包含类属性,类方法)\n\n #类属性\n '''类属性是属于类对象的,并且多个实例对象是共享的同一个 类属性'''\n num = 0\n\n #方法\n def __init__(self, new_name):\n #实例属性\n '''实例属性和具体的某个实例对象有关系,并且一个实例对象和另一个实例对象是不共享 属性的'''\n self.name = new_name\n\n #对类属性+=1 ========》类属性用于所有实例对象共享数据,类属性变了,对所有实例对象来说都变了(共享的)\n Tool.num += 1\n\n\ntool1 = Tool(\"铁锹\")#实例化的对象称为实例对象(包含实例属性,实例方法)\ntool2 = Tool(\"工兵铲\")\ntool3 = Tool(\"水桶\")\n\nprint(Tool.num)#打印的Tool.num就是创建的实例对象的个数\n","repo_name":"hurongyang/UUUU","sub_path":"s14/黑马/面向对象2/14-类属性-实例属性(应用).py","file_name":"14-类属性-实例属性(应用).py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"3265349297","text":"# -*- coding: utf-8 -*-\nimport os, sys, shutil, zipfile, threading, re, wx, urllib3\nimport core_studio, removabledrive, dialogs, utilities\n\n########################################################################\nPAGES = [\"Logs\", \"Profiles\", \"Core profiles\", \"Firmware\"]\n\ndef ellipsis(txt, ln):\n return re.sub(r'\\s\\S*$', ' ...', txt[:ln])\n\nclass showMemstickDialog(wx.Dialog):\n\n def saveCoreProfiles(self, obj, data, errorMessage, extra, flag):\n try:\n self.parent\n except wx.PyDeadObjectError:\n return\n\n self.dataFolder = self.parent.options.programDataFolder\n self.downloadsFolder = self.dataFolder + os.sep + 'downloads'\n\n if errorMessage is None:\n errorConnecting = False\n fileName = self.dataFolder + os.sep + 'downloaded.zip'\n try:\n with open(fileName, 'wb') as output:\n output.write(data)\n except IOError as e:\n dial = wx.MessageDialog(None,\n 'This file could not be saved.\\n' + fileName + '\\n' + e.strerror + '.',\n 'Error',\n wx.OK | wx.ICON_EXCLAMATION)\n dial.ShowModal()\n flag.clear()\n return\n\n if os.path.exists(self.downloadsFolder):\n try:\n shutil.rmtree(self.downloadsFolder)\n except:\n errorMessage = \"Unable to update all local copies of the files. At least one file is write protected or open in another app.\"\n try:\n zip = zipfile.ZipFile(fileName)\n zip.extractall(self.downloadsFolder)\n zip.close()\n except:\n if errorMessage is None:\n errorMessage = 'Unzip failed.'\n if os.path.exists(self.downloadsFolder + os.sep + '__MACOSX'):\n shutil.rmtree(self.downloadsFolder + os.sep + '__MACOSX')\n else:\n errorConnecting = True\n flag.clear()\n self.displayCoreProfilesStatus(errorMessage, errorConnecting, extra)\n\n def useLocal(self, target):\n self.displayCoreProfilesStatus(None, False, self.notebook.GetPage(PAGES.index(\"Core profiles\")).htmlObject)\n\n def downloadCoreProfiles(self, target):\n if self.coreProfilesIsRunning.is_set(): return\n self.coreProfilesIsRunning.set()\n htmlString = '

    Core profile set

    '\n htmlString += \"

    Downloading...

    \"\n self.notebook.GetPage(PAGES.index(\"Core profiles\")).htmlObject.SetPage(htmlString)\n worker = GetURL_Thread(self, self.saveCoreProfiles,\n core_studio.CORE_PROFILES_ZIP_URL,\n extra=target,\n flag=self.coreProfilesIsRunning)\n worker.start()\n\n def displayCoreProfilesStatus(self, errorMessage, errorConnecting, htmlObject):\n try:\n self.parent\n except wx.PyDeadObjectError:\n return\n \"\"\"\n we assume the zip contains only one folder\n \"\"\"\n if os.path.exists(self.downloadsFolder):\n zipFolderList = [x for x in os.listdir(self.downloadsFolder) if os.path.isdir(self.downloadsFolder + os.sep + x)]\n else:\n zipFolderList = [] \n self.zipFolder = zipFolderList[0] if len(zipFolderList) > 0 else ''\n self.unzippedFolder = self.downloadsFolder + os.sep + self.zipFolder\n manualsFolder = self.unzippedFolder + os.sep + 'manuals'\n USB_dir = core_studio.USB_PROFILE_DIR\n coreProfilesFolder = self.unzippedFolder + os.sep + USB_dir\n htmlString = '

    Core profile set

    '\n if errorMessage is None:\n htmlString += '

    '\n htmlString += 'The core profiles are a set of roast profiles that allow you to fine tune your roast '\n htmlString += 'profile to your coffee and your tastes. Read the guide and view the map:'\n htmlString += 'Download again

    '\n htmlString += '
      '\n manuals = [os.path.basename(x) for x in os.listdir(manualsFolder) if 'core profile guide' in x.lower() or 'map of coffee' in x.lower()]\n for manual in manuals:\n htmlString += '
    • ' + manual + '
    • '\n htmlString += '
    '\n suffix = 'kpro'\n tableColumns = ['profile_short_name', 'profile_modified']\n sort = True\n if self.parent.currentRemovableDrive is None:\n htmlString = '

    No memory stick found

    '\n else:\n thisDir = self.parent.currentRemovableDrive + core_studio.USB_KAFFELOGIC_DIR + os.sep + USB_dir\n if os.path.exists(thisDir):\n usb_files = core_studio.dirToKeyValuesArray(thisDir, tableColumns, suffix, sort)\n else:\n usb_files =[]\n if os.path.exists(coreProfilesFolder):\n self.core_files = core_studio.dirToKeyValuesArray(coreProfilesFolder, tableColumns, suffix, sort)\n else:\n core_files = []\n for core_f in self.core_files:\n core_f['fname_matches'] = [x['profile_file_name'] for x in usb_files if x['profile_file_name'] == core_f['profile_file_name']]\n core_f['short_matches'] = [x['profile_file_name'] for x in usb_files if x['profile_short_name'] == core_f['profile_short_name']]\n if len(core_f['short_matches']) >= 1:\n if len(core_f['fname_matches']) == 1:\n if core_f['short_matches'][0] == core_f['fname_matches'][0]:\n core_f['replace_me'] = core_f['short_matches'][0]\n core_f['rename'] = False\n else:\n core_f['replace_me'] = core_f['short_matches'][0]\n core_f['rename'] = True\n else:\n core_f['replace_me'] = core_f['short_matches'][0]\n core_f['rename'] = False\n else:\n if len(core_f['fname_matches']) == 1:\n core_f['replace_me'] = core_f['fname_matches'][0]\n core_f['rename'] = False\n else:\n core_f['replace_me'] = ''\n core_f['rename'] = False\n htmlString += '
    '\n htmlString += '

    Copy/replace all core profiles on ' + self.memstick + '

    '\n htmlString += '

    '\n for core_f in self.core_files:\n htmlString += ''\n htmlString += '
    On Kaffelogic web siteOn ' + self.memstick + '
    ' + core_f['profile_file_name'] + u'»' + core_f['replace_me'] + '

    '\n else:\n if errorConnecting:\n htmlString += UNABLE_TO_CONNECT_MESSAGE.replace('[[errorMessage]]', errorMessage)\n else:\n htmlString += errorMessage\n if os.path.exists(coreProfilesFolder):\n htmlString += '

    Use local copy

    '\n htmlObject.SetPage(htmlString)\n\n def copyCoreProfiles(self, target):\n htmlObj = self.notebook.GetPage(PAGES.index(\"Core profiles\")).htmlObject\n htmlObj.SetPage('

    copying files to ' + self.memstick + ' ...

    ')\n wx.CallAfter(self.copyCoreProfilesMain)\n \n def copyCoreProfilesMain(self):\n errorMessage = None\n if self.parent.currentRemovableDrive is not None:\n thisDir = self.parent.currentRemovableDrive + core_studio.USB_KAFFELOGIC_DIR + os.sep + core_studio.USB_PROFILE_DIR\n coreProfilesFolder = self.unzippedFolder + os.sep + core_studio.USB_PROFILE_DIR\n if self.parent.ensureFolderExists(thisDir):\n for core_f in self.core_files:\n if core_f['replace_me'] != '' and os.path.exists(thisDir + os.sep + core_f['replace_me']):\n try:\n os.remove(thisDir + os.sep + core_f['replace_me'])\n except:\n pass\n destination = thisDir + os.sep + core_f['profile_file_name']\n if core_f['rename']:\n n = 0\n root, ext = os.path.splitext(destination)\n while os.path.exists(destination):\n n += 1\n destination = root + ' (' + str(n) + ')' + ext\n try:\n shutil.copy(coreProfilesFolder + os.sep + core_f['profile_file_name'], destination)\n except Exception as e:\n errorMessage = str(e)\n else:\n dial = wx.MessageDialog(None, 'There was a problem creating the profiles folder.', 'Error',\n wx.OK | wx.ICON_EXCLAMATION)\n dial.ShowModal()\n self.displayCoreProfilesStatus(errorMessage, False, self.notebook.GetPage(PAGES.index(\"Core profiles\")).htmlObject)\n\n def sysOpen(self, target):\n utilities.system_open(target)\n\n def saveDownload(self, obj, data, errorMessage, extra, flag):\n try:\n self.parent\n except wx.PyDeadObjectError:\n return\n if errorMessage is None:\n d = self.parent.currentRemovableDrive + core_studio.USB_KAFFELOGIC_DIR + os.sep + core_studio.USB_FIRMWARE_DIR\n if self.parent.ensureFolderExists(d):\n fileName = d + os.sep + core_studio.MODEL_NUMBER + '-' + extra + '.bin'\n try:\n with open(fileName, 'wb') as output:\n output.write(data)\n except IOError as e:\n dial = wx.MessageDialog(None,\n 'This file could not be saved.\\n' + fileName + '\\n' + e.strerror + '.',\n 'Error',\n wx.OK | wx.ICON_EXCLAMATION)\n dial.ShowModal()\n flag.clear()\n return\n worker = GetURL_Thread(self, self.displayFirmwareStatus, url=core_studio.FIRMWARE_RELEASE_NOTES_URL,\n extra=self.notebook.GetPage(PAGES.index(\"Firmware\")).htmlObject)\n worker.start()\n flag.clear()\n else:\n dial = wx.MessageDialog(None, 'There was a problem downloading the update.\\n' + errorMessage, 'Error',\n wx.OK | wx.ICON_EXCLAMATION)\n dial.ShowModal()\n flag.clear()\n\n def downloadFirmware(self, target):\n if self.downloadIsRunning.is_set(): return\n self.downloadIsRunning.set()\n htmlString = '

    ' + core_studio.FULL_MODEL_NAME + ' firmware updates

    '\n htmlString += \"

    Downloading...

    \"\n self.notebook.GetPage(PAGES.index(\"Firmware\")).htmlObject.SetPage(htmlString)\n worker = GetURL_Thread(self, self.saveDownload,\n core_studio.FIRMWARE_RELEASE_FOLDER + '/' + core_studio.MODEL_NUMBER + '-' + target + '.bin', extra=target,\n flag=self.downloadIsRunning)\n worker.start()\n\n def displayFirmwareStatus(self, obj, data, errorMessage, htmlObject):\n try:\n self.parent\n except wx.PyDeadObjectError:\n return\n htmlString = '

    ' + core_studio.FULL_MODEL_NAME + ' firmware updates

    '\n existingVersion = core_studio.getFirmwareVersionFromDrive(self.parent.currentRemovableDrive)\n if errorMessage is None:\n newVersion = core_studio.extractVersionFromNotes(data)\n htmlString += \"

    The latest firmware update available is Version \" + newVersion + \"

    \"\n status = core_studio.compareVersions(existingVersion, newVersion) if existingVersion is not None else None\n if status == -1:\n htmlString += \"

    The latest firmware update on \" + self.memstick + \" is Version \" + existingVersion + \" and is older than the latest available.

    \"\n htmlString += \"

    Copy the latest firmware update to \" + self.memstick + \" (Recommended)

    \"\n elif status == 0:\n htmlString += \"

    The firmware update on \" + self.memstick + \" is the latest.

    \"\n htmlString += \"

    When you update the firmware the default profile is loaded. If you have been using a different profile or level, make a note of this before you update.

    \"\n htmlString += \"

    Update the firmware on your \" + core_studio.FULL_MODEL_NAME + \" personal coffee roaster:

    \"\n htmlString += \"
    1. Remove the memory stick and put it into the roaster.
    2. \"\n htmlString += \"
    3. Hold the roaster's start button down while you turn the roaster on.
    4. \"\n htmlString += \"
    5. You should see a message confirming that the roaster is Reflashing. This confirms that the update is being applied.
    \"\n elif status == 1:\n htmlString += \"

    The latest firmware update on \" + self.memstick + \" is Version \" + existingVersion + \"

    \"\n htmlString += \"

    The firmware update on \" + self.memstick + \" is newer than the latest release and is intended for beta testing.

    \"\n elif status is None:\n htmlString += \"

    There is no firmware update on \" + self.memstick + \"

    \"\n htmlString += \"

    Copy the latest firmware update to \" + self.memstick + \" (Recommended)

    \"\n else:\n htmlString += UNABLE_TO_CONNECT_MESSAGE.replace('[[errorMessage]]', errorMessage)\n if existingVersion is not None:\n htmlString += \"

    The firmware update on \" + self.memstick + \" is Version \" + existingVersion + \"

    \"\n htmlString += u\"

    Verify the firmware version that is installed on your roaster:

    \"\n htmlString += u\"
    1. Press ≡ until you see the option for technical info.
    2. \"\n htmlString += u\"
    3. Press › until you see the firmware version displayed.
    \"\n\n htmlObject.SetPage(htmlString)\n\n def openLinkFile(self, target):\n self.result = wx.ID_OK\n if self.parent.openDroppedFile(target):\n wx.CallAfter(self.Close)\n\n def __init__(self, parent):\n super(showMemstickDialog, self).__init__(parent)\n self.parent = parent\n self.coreProfilesDownloaded = False\n self.memstick = removabledrive.volumeDescriptor(\n self.parent.currentRemovableDrive) if self.parent.currentRemovableDrive is not None else None\n pageTitles = PAGES\n self.initNotebook(pageTitles)\n self.onNotebookChange(None)\n self.downloadIsRunning = threading.Event()\n firmwareWorker = GetURL_Thread(self, self.displayFirmwareStatus, url=core_studio.FIRMWARE_RELEASE_NOTES_URL,\n extra=self.notebook.GetPage(PAGES.index(\"Firmware\")).htmlObject)\n firmwareWorker.start()\n\n def onNotebookChange(self, event):\n where = self.notebook.GetPage(self.notebook.GetSelection())\n self.updateTitle(where)\n if not self.coreProfilesDownloaded and self.notebook.GetPage(PAGES.index(\"Core profiles\")) is where:\n self.coreProfilesDownloaded = True\n self.coreProfilesIsRunning = threading.Event()\n self.downloadCoreProfilesAgain(None)\n where.htmlObject.SetFocus()\n\n def downloadCoreProfilesAgain(self, target):\n self.downloadCoreProfiles(target=self.notebook.GetPage(PAGES.index(\"Core profiles\")).htmlObject)\n\n def updateTitle(self, where):\n if where.pageTitle == \"Logs\":\n if self.parent.currentRemovableDrive is not None:\n name = \" on \" + self.memstick\n else:\n name = \"\"\n self.SetTitle(\"Logs saved\" + name)\n elif where.pageTitle == \"Profiles\":\n if self.parent.currentRemovableDrive is not None:\n name = \" from \" + self.memstick\n else:\n name = \"\"\n self.SetTitle(\"Profiles available for loading into the Nano 7\" + name)\n elif where.pageTitle == \"Core profiles\":\n if self.parent.currentRemovableDrive is not None:\n name = \" on \" + self.memstick\n else:\n name = \"\"\n self.SetTitle(\"Core profiles\" + name)\n elif where.pageTitle == \"Firmware\":\n if self.parent.currentRemovableDrive is not None:\n name = \" on \" + self.memstick\n else:\n name = \"\"\n self.SetTitle(\"Firmware updates\" + name)\n\n def initNotebook(self, panelList):\n self.panel = wx.Panel(self, wx.ID_ANY)\n if core_studio.isWindows:\n self.notebook = wx.Notebook(self.panel)\n else:\n self.notebook = wx.aui.AuiNotebook(self.panel, style=wx.aui.AUI_NB_TOP)\n for panelName in panelList:\n self.notebook.AddPage(self.initPage(self.notebook, panelName), panelName)\n sizer = wx.BoxSizer()\n sizer.Add(self.notebook, 1, wx.EXPAND)\n self.panel.SetSizerAndFit(sizer)\n self.panel.Layout()\n sizer.SetSizeHints(self.panel)\n self.panel.SetAutoLayout(True)\n self.notebook.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.onNotebookChange)\n self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.onNotebookChange)\n\n def initPage(self, notebook, pageTitle):\n page = wx.Panel(notebook, wx.ID_ANY)\n self.expandDescription = False\n self.expandNotes = False\n if pageTitle == \"Logs\":\n page.USB_dir = core_studio.USB_LOG_DIR\n page.suffix = 'klog'\n page.columnHeadings = ['File name', 'Profile name', 'Profile Designer', 'Profile modified', 'Level', 'Length',\n 'Notes']\n page.tableColumns = ['profile_short_name', 'profile_designer', 'profile_modified', 'roasting_level', 'roast_end',\n 'tasting_notes']\n page.sort = True\n elif pageTitle == \"Profiles\":\n page.USB_dir = core_studio.USB_PROFILE_DIR\n page.suffix = 'kpro'\n page.columnHeadings = ['File name', 'Display name', 'Description', 'Designer', 'Date modified']\n page.tableColumns = ['profile_short_name', 'profile_description', 'profile_designer', 'profile_modified']\n page.sort = False\n elif pageTitle == \"Core profiles\":\n page.USB_dir = core_studio.USB_PROFILE_DIR\n page.suffix = 'kpro'\n page.columnHeadings = []\n page.tableColumns = []\n page.sort = False\n elif pageTitle == \"Firmware\":\n page.USB_dir = core_studio.USB_FIRMWARE_DIR\n page.suffix = 'bin'\n page.columnHeadings = []\n page.tableColumns = []\n page.sort = False\n\n if not core_studio.isLinux: wx.App.Get().doRaise()\n page.pageTitle = pageTitle\n outX, outY = self.parent.GetPosition()\n inX, inY = self.GetPosition()\n sizeX, sizeY = self.parent.GetSize()\n box = wx.BoxSizer(wx.VERTICAL)\n page.htmlObject = dialogs.wxHTML(page, -1, size=(sizeX - inX + outX - 30, sizeY - inY + outY - 100))\n if pageTitle == \"Firmware\":\n htmlString = \"

    Looking for firmware updates...

    \"\n elif pageTitle == \"Core profiles\":\n htmlString = \"

    Downloading official core profile set...

    \"\n else:\n if self.parent.currentRemovableDrive is None:\n htmlString = '

    No memory stick found

    '\n else:\n page.thisDir = self.parent.currentRemovableDrive + core_studio.USB_KAFFELOGIC_DIR + os.sep + page.USB_dir\n if os.path.exists(page.thisDir):\n\n htmlString = self.buildTableOfFileNames(page.pageTitle, page.columnHeadings, page.tableColumns, page.thisDir, page.suffix, page.sort)\n\n else:\n htmlString = '

    Memory stick has no ' + page.USB_dir + ' folder

    '\n page.htmlObject.SetPage(htmlString)\n okButton = wx.Button(page, label='Close')\n box.Add(page.htmlObject, 1, wx.GROW)\n box.Add(okButton, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 10)\n box.SetSizeHints(self)\n page.SetSizerAndFit(box)\n okButton.Bind(wx.EVT_BUTTON, page.htmlObject.onOk)\n okButton.SetDefault()\n if not core_studio.isLinux: self.Raise()\n return page\n\n def buildTableOfFileNames(self, pageTitle, columnHeadings, tableColumns, thisDir, suffix, sort):\n htmlString = u'

    ' + core_studio.REFRESH_CHAR + '' \\\n u'Refresh     '\n # weird layout bug on Mac with unicode chars, so don't include refresh char in the link text\n if pageTitle == 'Logs':\n if not self.expandNotes:\n htmlString += '+Expand'\n else:\n htmlString += '-Collapse'\n htmlString += ' notes'\n elif pageTitle == 'Profiles':\n if not self.expandDescription:\n htmlString += u'+Expand'\n else:\n htmlString += '-Collapse'\n htmlString += ' descriptions'\n htmlString += ' 

    '\n htmlString += ''\n htmlString += ''\n for col in columnHeadings:\n htmlString += ''\n htmlString += ''\n odd = True\n filesData = core_studio.dirToKeyValuesArray(thisDir, tableColumns, suffix, sort)\n if filesData is None:\n return '

    ' + thisDir + ' not found

    '\n for fil in filesData:\n if odd:\n htmlString += ''\n odd = False\n else:\n htmlString += ''\n odd = True\n for col in ['profile_file_name'] + tableColumns:\n try:\n info = fil[col]\n if col == 'profile_short_name':\n info = core_studio.extractShortName(fil['profile_file_name'], fil['profile_short_name'])\n except:\n info = ''\n if col == 'profile_short_name':\n info = core_studio.DEFAULT_PROFILE # there was no 'profile_short_name' row in the profile file\n if (col == 'profile_description' and not self.expandDescription) or (col == 'tasting_notes' and not self.expandNotes):\n info = ellipsis(info, 35)\n htmlString += ''\n htmlString += ''\n htmlString += '
    ' + col + '
    '\n if col == 'profile_file_name':\n htmlString += ''\n htmlString += re.sub(r\"\\\\v\", r\"
    \", info)\n if col == 'profile_file_name':\n htmlString += '
    '\n htmlString += '
    '\n return htmlString\n\n def refresh(self, target):\n page = self.notebook.GetPage(self.notebook.GetSelection())\n if page.pageTitle == \"Logs\":\n if target == 'toggle_expansion':\n self.expandNotes = not self.expandNotes\n htmlString = self.buildTableOfFileNames(page.pageTitle, page.columnHeadings, page.tableColumns, page.thisDir, page.suffix, page.sort)\n page.htmlObject.SetPage(htmlString)\n elif page.pageTitle == \"Profiles\":\n if target == 'toggle_expansion':\n self.expandDescription = not self.expandDescription\n htmlString = self.buildTableOfFileNames(page.pageTitle, page.columnHeadings, page.tableColumns, page.thisDir, page.suffix, page.sort)\n page.htmlObject.SetPage(htmlString)\n \n########################################################################\nUNABLE_TO_CONNECT_MESSAGE = \\\n '

    Unable to contact the Kaffelogic web server. [[errorMessage]]

    ' + \\\n '

    Try:

    ' \\\n '

      ' \\\n '
    • Reconnecting to Wi-Fi
    • ' \\\n '
    • Checking the network cables, modem and router
    '\n\n\nclass GetURL_Thread(threading.Thread):\n\n def __init__(self, obj, callback, url, extra=None, flag=None):\n threading.Thread.__init__(self)\n # guarantee url is a list of urls\n if not isinstance(url, list):\n url = [url]\n self.url = url\n self.extra = extra\n self.callback = callback\n self.flag = flag\n self.obj = obj\n self.canJoin = True\n self.setName('GetURL')\n\n def run(self):\n \"\"\"Overrides Thread.run. Don't call this directly its called internally\n when you call Thread.start().\n \"\"\"\n timeToKill = self.obj.app.timeToKillThreads.isSet() if hasattr(self.obj, 'app') else wx.App.Get().timeToKillThreads.isSet()\n if not timeToKill:\n http = urllib3.PoolManager()\n urllib3.disable_warnings()\n errorMessage = None\n data = None\n for U in self.url:\n if errorMessage is None:\n try:\n response = http.request('GET', U)\n if response.status == 200:\n errorMessage = None\n if data is None:\n data = response.data\n else:\n if isinstance(data, list):\n data.append(response.data)\n else:\n data = [data, response.data]\n else:\n errorMessage = response.reason\n except Exception as e:\n if hasattr(e, '__module__') and e.__module__ == 'urllib3.exceptions':\n errorMessage = e.__class__.__name__\n if hasattr(e, 'reason'):\n errorMessage += ', ' + e.reason.__class__.__name__\n else:\n errorMessage = str(sys.exc_info()[1][0])\n if self.flag is None:\n wx.CallAfter(self.callback, self.obj, data, errorMessage, self.extra)\n else:\n wx.CallAfter(self.callback, self.obj, data, errorMessage, self.extra, self.flag)\n\n########################################################################\n","repo_name":"Mimoja/kaffeelogic-studio","sub_path":"viewmemstick.py","file_name":"viewmemstick.py","file_ext":"py","file_size_in_byte":27741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"22430466935","text":"import sqlite3\nMatrícula = int(input(\"Digite a matricula do aluno: \"))\n\n\n\nconexão = sqlite3.connect(\"bc_exemplo1.bd\")\n\nc = conexão.cursor()\n\nc.execute(\"Update aluno set curso = ? where Matrícula = ?\", (Matrícula,))\nlinhas=c.fatchone()\n\nif linhas:\n print(\"ID:\", linhas[0])\n print(\"Nome:\", linhas[1])\n print(\"Curso:\",linhas[2])\n print(\"Matricula:\",linhas[3])\n print(\"Data_ingresso\",linhas[4])\n\nelse:\n print(\"Matricula não encontrada!\")\n\n\n\n\nconexão.commit()\nc.close()\nconexão.close()","repo_name":"jonas-rafael/Data-Base","sub_path":"exemplo_4/select_unico_aluno.py","file_name":"select_unico_aluno.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"5678373574","text":"from common import *\n\nfrom dataset.transform import *\nfrom dataset.sampler import *\nfrom utility.file import *\nfrom utility.draw import *\n\nSCIENCE_WIDTH =256\nSCIENCE_HEIGHT=256\n\n\n\n\n\n#\ndef collate(batch):\n batch_size = len(batch)\n num = len(batch[0])\n indices = [batch[b][num-1]for b in range(batch_size)]\n tensors = torch.stack([batch[b][0]for b in range(batch_size)], 0)\n if batch[0][1] is None:\n masks = None\n else:\n masks = torch.stack([batch[b][1]for b in range(batch_size)], 0)\n return [tensors,masks,indices]\n\n\n# #data iterator ----------------------------------------------------------------\nclass ScienceDataset(Dataset):\n\n def __init__(self, split, transform=None, mode='train'):\n super(ScienceDataset, self).__init__()\n start = timer()\n\n self.split = split\n self.transform = transform\n self.mode = mode\n\n #read split\n ids = read_list_from_file(DATA_DIR + '/split/' + split, comment='#')\n\n #save\n self.ids = ids\n\n #print\n print('\\ttime = %0.2f min'%((timer() - start) / 60))\n print('\\tnum_ids = %d'%(len(self.ids)))\n print('')\n\n\n def __getitem__(self, index):\n id = self.ids[index]\n name = id.split('/')[-1]\n image_file = DATA_DIR + '/' + id + '/images/' + name +'.png'\n image = cv2.imread(image_file, cv2.IMREAD_COLOR)\n\n if self.mode in ['train']:\n mask_file = DATA_DIR + '/' + id + '/one_mask.png'\n mask = cv2.imread(mask_file, cv2.IMREAD_GRAYSCALE)\n if self.transform is not None:\n return self.transform(image,mask,index)\n else:\n return image, mask, index\n\n if self.mode in ['test']:\n if self.transform is not None:\n return self.transform(image,index)\n else:\n return image, index\n\n\n\n def __len__(self):\n return len(self.ids)\n\n\n\n\n## check ## ----------------------------------------------------------\n\ndef run_check_dataset():\n\n def augment(image,mask,index):\n image,mask = fix_resize_transform2(image, mask, SCIENCE_WIDTH, SCIENCE_HEIGHT)\n return image,mask,index\n\n dataset = ScienceDataset(\n 'train_ids_remove_error_669', mode='train',\n transform = augment,\n )\n #sampler = SequentialSampler(dataset)\n sampler = RandomSampler(dataset)\n\n\n for n in iter(sampler):\n #for n in range(10):\n #n=0\n #while 1:\n image,mask,index = dataset[n]\n\n image_show('image',image)\n image_show('mask',mask)\n cv2.waitKey(0)\n\n\n# main #################################################################\nif __name__ == '__main__':\n print( '%s: calling main function ... ' % os.path.basename(__file__))\n\n run_check_dataset()\n\n print( 'sucess!')\n","repo_name":"joshp112358/KaggleDSBOWL","sub_path":"unet/source/dataset/science_dataset.py","file_name":"science_dataset.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"42429815252","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jan 16 19:19:32 2021\r\n\r\n@author: asrinutku\r\n\"\"\"\r\ndef score(dice):\r\n one = dice.count(1)\r\n two = dice.count(2)\r\n three = dice.count(3)\r\n four = dice.count(4)\r\n five = dice.count(5)\r\n six = dice.count(6)\r\n \r\n score = 0\r\n \r\n if one < 3: score += 100 * one\r\n \r\n elif one >= 3: \r\n score += 1000\r\n one -= 3\r\n if (one==1):\r\n score += 100\r\n if (one==2):\r\n score += 200\r\n \r\n\r\n if five < 3:\r\n score+= 50 * five\r\n \r\n elif five >= 3: \r\n score += 500\r\n five -= 3\r\n if (five==1):\r\n score += 50\r\n if (five==2):\r\n score += 100\r\n \r\n \r\n if two >= 3: score += 200\r\n elif three >= 3 : score += 300\r\n elif four >= 3 : score += 400\r\n elif six >= 3 : score += 600\r\n \r\n return score\r\n ","repo_name":"asrinutku/Codewars-Solutions","sub_path":"Greed is Good.py","file_name":"Greed is Good.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"33549444687","text":"\nimport sys\nimport git\n\nPROJECT_ROOT = git.Repo(\".\", search_parent_directories=True).working_tree_dir\nsys.path.append(PROJECT_ROOT)\n\nimport pandas as pd\n\nfrom geopy.distance import geodesic\nfrom pprint import pprint\n\nNUMERIC_VARS = [\n \"building_area\",\n \"year_alt_1\",\n \"year_alt_2\",\n \"lot_area\",\n \"n_floors\",\n]\nOUTPUTS = f\"{PROJECT_ROOT}/outputs\"\nCENTER = (40.765983, -73.977208) # (LAT, LNG)\nRADIUS = 1\n\n\ndef buildings_within_radius(data):\n return data[data.apply(lambda r: km_diff(r) <= RADIUS, axis=1)]\n\n\ndef km_diff(r):\n return geodesic(CENTER, (r.lat, r.lng)).km\n\n\ndef statistics(data):\n return {v: numeric_statistics(data, v) for v in NUMERIC_VARS}\n\n\ndef numeric_statistics(data, var):\n return {\n \"min\": data[var].min(),\n \"mean\": data[var].mean(),\n \"median\": data[var].median(),\n \"max\": data[var].max(),\n \"std\": data[var].std(),\n }\n\n\nif __name__ == \"__main__\":\n data = pd.read_csv(f\"{OUTPUTS}/data.csv\")\n data = data[~data.lat.isnull()]\n print(f\"[+] FINDING BUILDINGS IN AREA ({3.14 * RADIUS ** 2} KM2)...\")\n data_subset = buildings_within_radius(data)\n print(f\"[+] GETTING STATISTICS FOR BUILDINGS IN AREA...\")\n stats = statistics(data_subset)\n pprint(stats)\n print(\"[+] DONE\")\n","repo_name":"otrenav/dkt-building-age-detection-with-deep-learning","sub_path":"scripts/analysis/area-year-statistics.py","file_name":"area-year-statistics.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"4709155693","text":"from flask import (\r\n abort,\r\n Blueprint,\r\n flash,\r\n redirect,\r\n render_template,\r\n request,\r\n url_for,\r\n)\r\nfrom forms import ShowForm\r\nfrom models.artist import Show\r\n\r\nbp = Blueprint(\"shows\", __name__)\r\n\r\n\r\n@bp.route(\"/\")\r\ndef shows():\r\n data = Show.get_shows()\r\n return render_template(\"pages/shows.html\", shows=data)\r\n\r\n\r\n@bp.route(\"/search\", methods=[\"POST\"])\r\ndef search_shows():\r\n search_term = request.form.get(\"search_term\", \"\")\r\n results = Show.search(search_term)\r\n return render_template(\r\n \"pages/search_shows.html\", results=results, search_term=search_term,\r\n )\r\n\r\n\r\n@bp.route(\"/\", methods=[\"GET\"])\r\ndef show_show(show_id):\r\n show = Show.get_show(show_id)\r\n if not show:\r\n return render_template(\"pages/home.html\")\r\n return render_template(\"pages/show_show.html\", show=show)\r\n\r\n\r\n@bp.route(\"/create\")\r\ndef create_shows():\r\n form = ShowForm()\r\n return render_template(\"forms/new_show.html\", form=form)\r\n\r\n\r\n@bp.route(\"/create\", methods=[\"POST\"])\r\ndef create_show_submission():\r\n data = request.form.to_dict()\r\n show = Show(**data)\r\n result = show.save_to_db()\r\n if result[\"error\"]:\r\n flash(\"An error occurred. Show could not be listed.\")\r\n abort(500)\r\n flash(\"Show was successfully listed!\")\r\n return render_template(\"pages/home.html\")\r\n","repo_name":"wanderindev/fyyur","sub_path":"views/shows.py","file_name":"shows.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"31924437136","text":"from discord.ext import commands\n\nclient = commands.Bot(command_prefix=\"/\")\n\n\n@client.event\nasync def on_ready():\n print(\"Ready!\")\n\n\n@client.slash_command(name=\"help\")\nasync def rules(ctx):\n await ctx.respond(\"How can I help you?\")\n\n\nclient.run(input(\"token: \"))\n","repo_name":"hiluex/Active-Developer-Badge","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"32858730697","text":"import time\r\nimport urllib.parse\r\nimport urllib.parse\r\n\r\nfrom archived.old_model import LogisticRegression\r\nfrom thrift.protocol import TBinaryProtocol\r\nfrom thrift.transport import TSocket\r\nfrom thrift.transport import TTransport\r\nfrom thrift_ps import constants\r\nfrom thrift_ps.client import ps_client\r\nfrom thrift_ps.ps_service import ParameterServer\r\n\r\n# algorithm setting\r\nNUM_FEATURES = 30\r\nNUM_CLASSES = 2\r\nLEARNING_RATE = 0.1\r\nBATCH_SIZE = 10000\r\nNUM_EPOCHS = 10\r\nVALIDATION_RATIO = .2\r\nSHUFFLE_DATASET = True\r\nRANDOM_SEED = 42\r\n\r\n\r\ndef handler(event, context):\r\n startTs = time.time()\r\n num_features = event['num_features']\r\n learning_rate = event[\"learning_rate\"]\r\n batch_size = event[\"batch_size\"]\r\n num_epochs = event[\"num_epochs\"]\r\n validation_ratio = event[\"validation_ratio\"]\r\n\r\n # Reading data from S3\r\n bucket_name = event['bucket_name']\r\n key = urllib.parse.unquote_plus(event['key'], encoding='utf-8')\r\n print(f\"Reading training data from bucket = {bucket_name}, key = {key}\")\r\n key_splits = key.split(\"_\")\r\n worker_index = int(key_splits[0])\r\n num_worker = int(key_splits[1])\r\n\r\n # read file from s3\r\n file = get_object(bucket_name, key).read().decode('utf-8').split(\"\\n\")\r\n print(\"read data cost {} s\".format(time.time() - startTs))\r\n\r\n parse_start = time.time()\r\n dataset = SparseDatasetWithLines(file, num_features)\r\n print(\"parse data cost {} s\".format(time.time() - parse_start))\r\n\r\n preprocess_start = time.time()\r\n dataset_size = len(dataset)\r\n indices = list(range(dataset_size))\r\n split = int(np.floor(validation_ratio * dataset_size))\r\n np.random.seed(42)\r\n np.random.shuffle(indices)\r\n train_indices, val_indices = indices[split:], indices[:split]\r\n\r\n train_set = [dataset[i] for i in train_indices]\r\n val_set = [dataset[i] for i in val_indices]\r\n\r\n print(\"preprocess data cost {} s\".format(time.time() - preprocess_start))\r\n\r\n # Set thrift connection\r\n # Make socket\r\n transport = TSocket.TSocket(constants.HOST, constants.PORT)\r\n # Buffering is critical. Raw sockets are very slow\r\n transport = TTransport.TBufferedTransport(transport)\r\n # Wrap in a protocol\r\n protocol = TBinaryProtocol.TBinaryProtocol(transport)\r\n # Create a client to use the protocol encoder\r\n t_client = ParameterServer.Client(protocol)\r\n # Connect!\r\n transport.open()\r\n\r\n # test thrift connection\r\n ps_client.ping(t_client)\r\n print(\"create and ping thrift server >>> HOST = {}, PORT = {}\"\r\n .format(constants.HOST, constants.PORT))\r\n\r\n # register model\r\n model_name = \"w.b\"\r\n model_length = num_features+1\r\n ps_client.register_model(t_client, worker_index, model_name, model_length, num_worker)\r\n ps_client.exist_model(t_client, model_name)\r\n print(\"register and check model >>> name = {}, length = {}\".format(model_name, model_length))\r\n\r\n # Training the Model\r\n train_start = time.time()\r\n iter_counter = 0\r\n lr = LogisticRegression(train_set, val_set, num_features, num_epochs, learning_rate, batch_size)\r\n # Training the Model\r\n for epoch in range(num_epochs):\r\n epoch_start = time.time()\r\n num_batches = math.floor(len(train_set) / batch_size)\r\n print(f\"worker {worker_index} epoch {epoch}\")\r\n\r\n for batch_idx in range(num_batches):\r\n batch_start = time.time()\r\n # pull latest model\r\n ps_client.can_pull(t_client, model_name, iter_counter, worker_index)\r\n latest_model = ps_client.pull_model(t_client, model_name, iter_counter, worker_index)\r\n lr.grad = torch.from_numpy(np.asarray(latest_model[:-1])).reshape(num_features, 1)\r\n lr.bias = float(latest_model[-1])\r\n\r\n compute_start = time.time()\r\n batch_ins, batch_label = lr.next_batch(batch_idx)\r\n batch_grad = torch.zeros(lr.n_input, 1, requires_grad=False)\r\n batch_bias = np.float(0)\r\n train_loss = Loss()\r\n train_acc = Accuracy()\r\n\r\n for i in range(len(batch_ins)):\r\n z = lr.forward(batch_ins[i])\r\n h = lr.sigmoid(z)\r\n loss = lr.loss(h, batch_label[i])\r\n # print(\"z= {}, h= {}, loss = {}\".format(z, h, loss))\r\n train_loss.update(loss, 1)\r\n train_acc.update(h, batch_label[i])\r\n g = lr.backward(batch_ins[i], h.item(), batch_label[i])\r\n batch_grad.add_(g)\r\n batch_bias += np.sum(h.item() - batch_label[i])\r\n batch_grad = batch_grad.div(len(batch_ins))\r\n batch_bias = batch_bias / len(batch_ins)\r\n batch_grad.mul_(-1.0 * learning_rate)\r\n lr.grad.add_(batch_grad)\r\n lr.bias = lr.bias - batch_bias * learning_rate\r\n\r\n np_grad = lr.grad.numpy().flatten()\r\n w_b_grad = np.append(np_grad, lr.bias)\r\n compute_end = time.time()\r\n\r\n sync_start = time.time()\r\n ps_client.can_push(t_client, model_name, iter_counter, worker_index)\r\n ps_client.push_grad(t_client, model_name, w_b_grad, learning_rate, iter_counter, worker_index)\r\n ps_client.can_pull(t_client, model_name, iter_counter + 1, worker_index) # sync all workers\r\n sync_time = time.time() - sync_start\r\n\r\n print('Epoch: [%d/%d], Step: [%d/%d] >>> Time: %.4f, Loss: %.4f, epoch cost %.4f, '\r\n 'batch cost %.4f s: cal cost %.4f s and communication cost %.4f s'\r\n % (epoch + 1, NUM_EPOCHS, batch_idx + 1, len(train_indices)/batch_size,\r\n time.time() - train_start, train_loss, time.time() - epoch_start,\r\n time.time() - batch_start, compute_end-batch_start, sync_time))\r\n iter_counter += 1\r\n\r\n val_loss, val_acc = lr.evaluate()\r\n print(f\"Validation loss: {val_loss}, validation accuracy: {val_acc}\")\r\n print(f\"Epoch takes {time.time() - epoch_start}s\")\r\n","repo_name":"DS3Lab/LambdaML","sub_path":"archived/ps_functions/rcv/LR_grad_avg_ps.py","file_name":"LR_grad_avg_ps.py","file_ext":"py","file_size_in_byte":6004,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"55"} +{"seq_id":"30928994696","text":"\"\"\"\n소세지공장 (greedy)\n기준을 정해서 정렬(높이 or 너비)\n만약 높이를 기준으로 정렬한다면 너비 상태만 확인하면 된다.\n너비를 확인 할 때 기준이 되는 소시지와 비교, 이때 너비가 크다면 기준을 바꿔준다.\n\"\"\"\ndef solution(arr, chk, n):\n cnt = 0\n while 0 in chk:\n base = 0\n cnt += 1\n for i in range(n):\n if not chk[i] and base <= arr[i][1]:\n chk[i] = 1\n base = arr[i][1]\n return cnt\n\n\nn = int(input())\ntemp = list(map(int, input().split()))\narr = []\nfor i in range(n):\n arr.append((temp[i*2], temp[i*2+1]))\narr.sort(key=lambda x: x[0])\nchk = [0]*n\nprint(solution(arr, chk, n))","repo_name":"chulsea/TIL","sub_path":"algorithm/Python/algorithm/problems/sausage_factory.py","file_name":"sausage_factory.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"30823756451","text":"import pandas as pd\nimport datetime\nimport calendar\n\n# 엑셀 파일 읽기\nraw_data = pd.read_excel('/Users/yuhyeonseung/Downloads/시장약정 정리.xlsx', header=None, index_col=None)\n\n# 오늘의 년월 구하기\ntoday = datetime.datetime.now()\n\n# 오늘 날짜의 이전 달의 마지막 날짜를 구하기\nif today.month == 1: # 현재 달이 1월인 경우 작년 12월로 설정\n end_date = datetime.datetime(today.year - 1, 12, 1) - datetime.timedelta(days=1)\nelse:\n end_date = datetime.datetime(today.year, today.month - 1, 1) - datetime.timedelta(days=1)\nlast_day = calendar.monthrange(end_date.year, end_date.month)[1]\nprint(last_day)\n\n# 해당 셀까지의 날짜 범위를 생성\ndate_range = pd.date_range(start='2023-01-01', end=f'2023-{today.month - 1}-30', freq='MS')\n\n# 해당 열에 날짜 데이터 입력\nfor idx, date in enumerate(date_range):\n # 새 열 추가\n raw_data.insert(idx + 3, date.strftime('%Y/%m'), \"\")\n\n# 결과 확인\n# print(raw_data)\n\n# 수정한 데이터를 엑셀 파일로 저장\nraw_data.to_excel('/Users/yuhyeonseung/Downloads/시장약정 정리(수정).xlsx', index=False)\n","repo_name":"hyeunseungYu/python","sub_path":"2nd_QnA/question12.py","file_name":"question12.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"31770332424","text":"\"\"\" provide version info, conftest/environment config names. \n\"\"\"\nimport py\nimport sys\n\ndef pytest_addoption(parser):\n group = parser.getgroup('debugconfig')\n group.addoption(\"--help-config\", action=\"store_true\", dest=\"helpconfig\", \n help=\"show available conftest.py and ENV-variable names.\")\n group.addoption('--version', action=\"store_true\", \n help=\"display py lib version and import information.\")\n\ndef pytest_configure(__multicall__, config):\n if config.option.version:\n p = py.path.local(py.__file__).dirpath()\n sys.stderr.write(\"This is py.test version %s, imported from %s\\n\" % \n (py.__version__, p))\n sys.exit(0)\n if not config.option.helpconfig:\n return\n __multicall__.execute()\n options = []\n for group in config._parser._groups:\n options.extend(group.options)\n widths = [0] * 10 \n tw = py.io.TerminalWriter()\n tw.sep(\"-\")\n tw.line(\"%-13s | %-18s | %-25s | %s\" %(\n \"cmdline name\", \"conftest.py name\", \"ENV-variable name\", \"help\"))\n tw.sep(\"-\")\n\n options = [opt for opt in options if opt._long_opts]\n options.sort(lambda x, y: cmp(x._long_opts, y._long_opts))\n for opt in options:\n if not opt._long_opts:\n continue\n optstrings = list(opt._long_opts) # + list(opt._short_opts)\n optstrings = filter(None, optstrings)\n optstring = \"|\".join(optstrings)\n line = \"%-13s | %-18s | %-25s | %s\" %(\n optstring, \n \"option_%s\" % opt.dest, \n \"PYTEST_OPTION_%s\" % opt.dest.upper(),\n opt.help and opt.help or \"\", \n )\n tw.line(line[:tw.fullwidth])\n for name, help in conftest_options:\n line = \"%-13s | %-18s | %-25s | %s\" %(\n \"\", \n name, \n \"\",\n help, \n )\n tw.line(line[:tw.fullwidth])\n \n tw.sep(\"-\")\n sys.exit(0)\n\nconftest_options = (\n ('pytest_plugins', 'list of plugin names to load'),\n ('collect_ignore', '(relative) paths ignored during collection'), \n ('rsyncdirs', 'to-be-rsynced directories for dist-testing'), \n)\n","repo_name":"tav/plexnet","sub_path":"third_party/generic/pypy/py/test/plugin/pytest_helpconfig.py","file_name":"pytest_helpconfig.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"55"} +{"seq_id":"11420573693","text":"from function1 import Poke\n\nclass Play:\n def __init__(self, number=5):\n \"\"\"\n 初始化扑克堆并进行发牌\n :param number: 参与人数\n \"\"\"\n self.poke = Poke()\n self.poke.shuffle()\n if number < 2 or number > 10:\n print('玩家数错误,无法开始游戏')\n self.players = self.poke.deal_poke(number)\n\n def showPlayers(self):\n \"\"\"展示所有玩家\"\"\"\n print(self.players.keys())\n\n def showPlayerCard(self, player):\n \"\"\"展示指定玩家的牌\"\"\"\n cards = self.players[player]\n print(player + '\\'s cards: ', end='')\n for card in cards:\n print(card, end='')\n print()\n\n def showAllPlayersCard(self):\n \"\"\"展示所有玩家的牌\"\"\"\n for player in self.players.keys():\n self.showPlayerCard(player)\n\n def showPlayerCardsType(self, player):\n \"\"\"\n 展示指定玩家的牌型\n :param player:\n :return:\n \"\"\"\n # 获取该玩家的手牌\n cards = self.players[player]\n # 将该玩家的手牌的花色和数值分开\n colors = []\n values = []\n for card in cards:\n colors.append(card.color)\n values.append(card.value)\n # 获取该玩家手牌的花色和数值的种类数\n # set()集合不允许重复,通过set()强制转型并取其长度,即可获得种类数\n colorsLen = len(set(colors))\n valuesLen = len(set(values))\n\n # 获取该玩家手牌中 数值数量最多的牌的数量 与 数值数量最少的牌的数量 之差,最终结果为sameCardNum\n # result,统计每种数值类型的个数的字典\n # 例对于 3, 4, 4, 5, 5 数值数量分别为3:一个,4:两个,5:两个,所以...之差为2-1 = 1,result={3: 1, 4: 2, 5: 2}\n # 例对于 4, 4, 4, 4, 5 数值数量分别4:四个,5:一个,所以...之差为4-1 = 3,result={4: 4, 5: 1}\n result = dict()\n for i in values:\n if i not in result.keys():\n result[i] = 1\n else:\n result[i] += 1\n sameCardNum = max(result.values()) - min(result.values())\n\n print('玩家' + player + '的牌型是')\n if colorsLen == 1 and [1, 10, 11, 12, 13] == sorted(values):\n print('大同花顺')\n elif colorsLen == 1 and valuesLen == 5 and max(values) - min(values) == 4:\n print('同花顺')\n elif valuesLen == 2 and result[min(result.keys())] - result[max(result.keys())] == 3:\n print('四条')\n elif valuesLen == 2 and sameCardNum == 1:\n print('满堂红')\n elif colorsLen == 1:\n print('同花')\n elif valuesLen == 5 and max(values) - min(values) == 4:\n print('顺子')\n elif valuesLen == 3 and sameCardNum == 2:\n print('三条')\n elif valuesLen == 3 and sameCardNum == 1:\n print('两队')\n elif valuesLen == 4 and sameCardNum == 1:\n print('一对')\n else:\n print('散牌')\n\n def showAllPlayersCardsType(self):\n \"\"\"\n 展示所有玩家的牌型\n :return:\n \"\"\"\n for i in self.players.keys():\n self.showPlayerCardsType(i)\n\n","repo_name":"ritsuwyh/Code","sub_path":"python/游戏/德州扑克.py/function2.py","file_name":"function2.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"44404143196","text":"from sklearn.cluster import KMeans\nfrom sklearn import metrics\nfrom Preprocessing import *\nimport glob\nimport TFIDF\nimport csv\n\n\ndef load_data():\n\n d = []\n for name in glob.glob('Dataset/*'):\n temp = open(name)\n d.append(temp.read())\n return d\n\n\ndef preprocessing(sentence):\n sentence = caseFolding(sentence)\n token = tokenization(sentence)\n token = stopwordRemoval(token)\n for i in range(len(token)):\n token[i] = stemming(token[i])\n return token\n\n\nif __name__ == '__main__':\n\n data = load_data()\n data.insert(0, 'content')\n with open('Model_data/Article.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerows([data])\n # temp = load_data()\n #\n # for i in range(len(data)):\n # data[i] = preprocessing(data[i])\n # data[i] = list(filter(None, data[i]))\n #\n # tfidf, words = TFIDF.termfreq(data)\n #\n # a = [2, 3, 5, 10]\n #\n # for i in a:\n # model = KMeans(n_clusters=i, random_state=1).fit(tfidf)\n # print('{}\\t{}\\t{}'.format(i, metrics.silhouette_score(tfidf, model.labels_, metric='euclidean'),\n # metrics.davies_bouldin_score(tfidf, model.labels_)\n # ))\n #\n # with open('Model_data/label_cluster-{}.csv'.format(i), 'w') as f:\n # writer = csv.writer(f)\n # writer.writerows([model.labels_])\n","repo_name":"fahmisalman/News_clustering","sub_path":"Prep_data.py","file_name":"Prep_data.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38655992563","text":"import os\nimport logging\n\nfrom twisted.internet import protocol, reactor\nfrom twisted.internet.protocol import connectionDone\nfrom twisted.internet.endpoints import TCP4ServerEndpoint\nfrom twisted.internet.defer import Deferred\n\nfrom google.protobuf.internal.encoder import _VarintBytes\nfrom google.protobuf.internal.decoder import _DecodeVarint32\n\nimport tcp_connection_pb2\nfrom utils import time_now\n\nDEBUG = True\n\nif DEBUG:\n HOST = 'localhost'\n PORT = 9999\nelse:\n HOST = os.getenv('SERVER_IP')\n PORT = os.getenv('DEFAULT_PORT')\n\n\ndef check_all():\n return all([HOST, PORT])\n\n\nclass TSServerProtocol(protocol.Protocol):\n \"\"\"\n Server side protocol\n Each client connection corresponds to an instance.\n \"\"\"\n\n def __init__(self, users):\n self.users = users\n self.message = tcp_connection_pb2.WrapperMessage()\n self._buffer = b\"\"\n self.clientInfo = \"\"\n self.start = 0\n\n def connectionMade(self):\n self.clientInfo = self.transport.getPeer()\n self.users.append(self)\n logging.info(\n f'Successful connection with '\n f'{self.clientInfo.host}:{self.clientInfo.port}'\n )\n\n def dataReceived(self, data):\n self._buffer += data\n self.message.Clear()\n try:\n message_size, pos = _DecodeVarint32(\n self._buffer, self.start\n )\n current_message = self._buffer[pos:(message_size + pos)]\n self.message.ParseFromString(current_message)\n self._buffer = self._buffer[pos+message_size:]\n logging.info('Message received successfully')\n logging.info(\n f'Message received from '\n f'{self.clientInfo.host}:{self.clientInfo.port}'\n )\n except Exception as error:\n logging.error(f'Failed received message: {error}')\n message_size, pos = _DecodeVarint32(\n self._buffer, self.start\n )\n if len(self._buffer) > message_size:\n self._buffer = self._buffer[pos+message_size:]\n return\n try:\n if self.message.HasField('request_for_fast_response'):\n self.fast_response()\n return\n if self.message.HasField('request_for_slow_response'):\n self.slow_response()\n return\n if len(self._buffer) >= 1024:\n logging.error(\n f'Receive message buffer full:'\n f'{len(self._buffer)}, {self._buffer}'\n )\n self._buffer = b\"\"\n return\n logging.error(\n f'Only part of the message was delivered: '\n f'{self.message}, {self._buffer}'\n )\n return\n except Exception as error:\n logging.error(f'Failed sending sata: {error}')\n\n def fast_response(self):\n self.message.Clear()\n self.message.fast_response.current_date_time = time_now()\n self.send_message(self.message)\n\n def slow_response(self):\n client_count = len(self.users)\n delay = self.message.request_for_slow_response.time_in_seconds_to_sleep\n self.message.Clear()\n self.message.slow_response.connected_client_count = client_count\n deferred = Deferred()\n deferred.addCallback(self.send_message)\n reactor.callLater(delay, deferred.callback, self.message)\n\n def send_message(self, message):\n self.transport.write(_VarintBytes(message.ByteSize()))\n self.transport.write(message.SerializeToString())\n logging.info(f'Message successfully sent')\n\n def connectionLost(self, reason=connectionDone):\n logging.info('Delete user from server_python_twisted')\n self.users.remove(self)\n\n\nclass TSServerFactory(protocol.Factory):\n \"\"\"\n Factory for instantiating the protocol on the server_python_twisted side\n \"\"\"\n\n def __init__(self):\n self.users = []\n logging.info(f'Server started on {HOST}:{PORT}')\n\n def buildProtocol(self, addr):\n return TSServerProtocol(self.users)\n\n\nif __name__ == '__main__':\n from logging_config import logger_conf\n\n logger_conf()\n if not check_all():\n logging.critical('Started failed: empty host or port')\n endpoint = TCP4ServerEndpoint(reactor, PORT)\n endpoint.listen(TSServerFactory())\n reactor.run()\n","repo_name":"chill-o-u-t/task24_tcp_server","sub_path":"python/server_twisted/server_twisted.py","file_name":"server_twisted.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"8515292926","text":"import eng_to_ipa as pa\r\ndef count_syl(word):\r\n delim = \"ˈ\"\r\n vowels = ['æ','ɛ','ɪ','ʊ','i','ə','ɑ','u','a','e']\r\n diphthongs= ['aʊ','aɪ','ɔɪ','oʊ','eɪ']\r\n phon = pa.convert(word)\r\n count=0\r\n for j in vowels:\r\n if j in phon:\r\n count +=phon.count(j)\r\n for k in diphthongs:\r\n if k in phon:\r\n count -=phon.count(k)\r\n return count\r\n\r\n\r\n\r\ndef phone(word):\r\n phon = pa.convert(word)\r\n return phon","repo_name":"sagar-9850/syllabification","sub_path":"final_version/programs/count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"3049129542","text":"import socket\n\nlocalIP = \"127.0.0.1\"\nlocalPort = 20001\nbufferSize = 1024\n\nmessageFromClient = \"Hello UDP Server\"\nBytesToSend = str.encode(messageFromClient)\nClientSocket = socket.socket(family = socket.AF_INET, type = socket.SOCK_DGRAM)\nClientSocket.sendto(BytesToSend, (localIP, localPort))\n\nserverMessage = ClientSocket.recvfrom(bufferSize)\nprint(f\"Message From Server: {serverMessage[0]}\")\n","repo_name":"spacebiz24/IoT-Basics","sub_path":"P6/P6-Client.py","file_name":"P6-Client.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"42213350702","text":"from tkinter import *\nimport socket\nimport threading\nfrom tkinter.messagebox import showinfo\nimport time\nimport traceback\n\nthis_votecal=[0,0,0,0,0,0] # 各选项得票计数\n# 锁\n\n\ndef NotifyAll(xx):\n global msg\n if con.acquire():\n msg = xx\n con.notifyAll()\n con.release()\n\n\ncon = threading.Condition() # 条件\nmsg = \"\"\nmysk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# 发送\n\n\ndef CTout(conn,connaddr):\n global msg\n while True:\n if con.acquire():\n con.wait()\n if msg:\n try:\n conn.send(msg.encode())\n NotifyAll(\"\")\n con.release()\n except:\n con.release()\n return\n# 接收\n\n\ndef CTin(conn,connaddr):\n global this_votecal\n while True:\n try:\n data = conn.recv(1024).decode()\n if not data:\n conn.close()\n return\n else:\n if data == \"1\" or \\\n data == \"2\" or \\\n data == \"3\" or \\\n data == \"4\" or \\\n data == \"5\" or \\\n data == \"6\":\n this_votecal[int(data)-1] += 1\n else:\n InfoWin(data)\n writetxt = open(\"e:\\\\vote.txt\", \"a\")\n writetxt.write(time.strftime(\"%Y/%m/%d %H:%M:%S\", time.localtime()) + \"\\n\" +data)\n writetxt.close()\n except:\n InfoWin(\"异常!!!\"+\"\\n\"+traceback.format_exc())\n return\n# 发布投票\n\n\ndef Dealoutvote():\n myconn = int((threading.activeCount()) / 2)\n if myconn == 0:\n InfoWin(\"没有客户端连接!\")\n else:\n if str(topictext.get()) == \"\":\n InfoWin(\"请输入投票主题!\")\n else:\n if str(c1text.get()) == \"\" or str(c2text.get()) == \"\":\n InfoWin(\"请至少输入选项1和2\")\n else :\n msg = \"投票主题:\\n\" + str(topictext.get()) + \"\\n\" + \\\n \"选项1:\" + str(c1text.get()) + \"\\n\" + \\\n \"选项2:\" + str(c2text.get()) + \"\\n\" + \\\n \"选项3:\" + str(c3text.get()) + \"\\n\" + \\\n \"选项4:\" + str(c4text.get()) + \"\\n\" + \\\n \"选项5:\" + str(c5text.get()) + \"\\n\" + \\\n \"选项6:\" + str(c6text.get())\n InfoWin(\"投票已发送(主题:\" + str(topictext.get()) + \")\")\n NotifyAll(msg)\n# 发布结果\n\n\ndef Dealoutres():\n myconn = int((threading.activeCount()) / 2)\n if myconn == 0:\n InfoWin(\"没有客户端连接!\")\n else:\n temp = \"投票主题:\\n\" + str(topictext.get()) + \"\\n\" + \\\n \"选项1:\" + str(c1text.get()) + \"\\n\" + str(this_votecal[0]) + \\\n \"票\\n选项2:\" + str(c2text.get()) + \"\\n\" + str(this_votecal[1]) + \\\n \"票\\n选项3:\" + str(c3text.get()) + \"\\n\" + str(this_votecal[2]) + \\\n \"票\\n选项4:\" + str(c4text.get()) + \"\\n\" + str(this_votecal[3]) + \\\n \"票\\n选项5:\" + str(c5text.get()) + \"\\n\" + str(this_votecal[4]) + \\\n \"票\\n选项6:\" + str(c6text.get()) + \"\\n\" + str(this_votecal[5]) + \\\n \"票\\n\"\n NotifyAll(temp)\n InfoWin(\"投票结果已发布!\")\n writetxt = open(\"e:\\\\finallvote.txt\", \"a\")\n writetxt.write(time.strftime(\"%Y/%m/%d %H:%M:%S\", time.localtime()) + \"\\n\" + temp)\n writetxt.close()\n# 启动服务器\n\n\ndef StartSever():\n global mysk\n ip_port = (str(ipinput.get()), int(portinput.get()))\n mysk.bind(ip_port)\n InfoWin(\"服务器开启\")\n mysk.listen(5)\n InfoWin(\"等待...\")\n threading.Thread(target=ConnW, args=(mysk,)).start()\n\n\ndef ConnW(mysk):\n global msg\n while True:\n conn, address = mysk.accept()\n connaddr = conn.recv(2048).decode()\n InfoWin(connaddr + \"连接\")\n InfoWin(\"当前连接数:\" + str(int((threading.activeCount()) / 2)))\n threading.Thread(target=CTin, args=(conn, connaddr)).start()\n threading.Thread(target=CTout, args=(conn, connaddr)).start()\n# 帮助信���\n\n\ndef MyHelp():\n showinfo(title=\"帮助信息\", message=\"应用程序使用说明:1)输入端口和ip以启动服务器。2)等待各个客户端连接后,输入投票主题和选项(至少要输入选项一选项二)\"+\n \"3)等待客户端投票(投票情况可按刷新键实时查看),后可按需求停止投票。4)发布结果,后可重置投票,以开始新的投票。\")\n# 信息\n\n\ndef InfoWin(msg):\n wininfo = time.strftime(\"%Y/%m/%d %H:%M:%S\", time.localtime()) + \"\\n\" + msg + \"\\n\"\n InfoText.config(state=NORMAL)\n InfoText.insert(END, wininfo)\n InfoText.config(state=DISABLED)\n# 投票计数\n\n\ndef VoteCal(i):\n global this_votecal\n return this_votecal[i-1]\n# 刷新\n\n\ndef ResShow():\n c1R[\"text\"] = \"1: \" + str(VoteCal(1)) + \"票\"\n c2R[\"text\"] = \"2: \" + str(VoteCal(2)) + \"票\"\n c3R[\"text\"] = \"3: \" + str(VoteCal(3)) + \"票\"\n c4R[\"text\"] = \"4: \" + str(VoteCal(4)) + \"票\"\n c5R[\"text\"] = \"5: \" + str(VoteCal(5)) + \"票\"\n c6R[\"text\"] = \"6: \" + str(VoteCal(6)) + \"票\"\n# 停止投票\n\n\ndef StopVote():\n mysk.close()\n InfoWin(\"投票已停止!\")\n# 重置投票\n\n\ndef NewVote():\n global this_votecal\n i = 0\n while i < 6:\n this_votecal[i] = 0\n i += 1\n topictext[\"text\"] = \"\"\n c1text[\"text\"] = \"\"\n c2text[\"text\"] = \"\"\n c3text[\"text\"] = \"\"\n c4text[\"text\"] = \"\"\n c5text[\"text\"] = \"\"\n c6text[\"text\"] = \"\"\n c1R[\"text\"] = \"1: \" + str(VoteCal(1)) + \"票\"\n c2R[\"text\"] = \"2: \" + str(VoteCal(2)) + \"票\"\n c3R[\"text\"] = \"3: \" + str(VoteCal(3)) + \"票\"\n c4R[\"text\"] = \"4: \" + str(VoteCal(4)) + \"票\"\n c5R[\"text\"] = \"5: \" + str(VoteCal(5)) + \"票\"\n c6R[\"text\"] = \"6: \" + str(VoteCal(6)) + \"票\"\n InfoWin(\"投票已重置!\")\n\n# 窗体GUI\n\n\nwin1 = Tk()\nwin1.title(\"V_sever\")\nwin1.geometry(\"500x400\")\nTopTlitle = Label(win1, text=\"欢迎使用投票系统!\", font=(\"楷体\", 16, \"normal\"))\nTopTlitle.place(x=280, y=10)\n# 信息窗\nInfoframe = Frame(win1, height=300, width=160, )\nInfoText = Text(Infoframe, fg=\"white\", bg=\"black\")\nInfoText.config(state=DISABLED)\nInfoText.grid()\nInfoframe.grid(row=0, column=0, columnspan=2, padx=30, pady=80)\nInfoframe.grid_propagate(0)\n# 设置端口\nbtn = Button(win1, text=\"启动服务器\", command=StartSever)\nbtn.place(x=160, y=40)\nport = Label(win1, text=\"端口号:\")\nport.place(x=30, y=20)\nip = Label(win1, text=\"ip:\")\nip.place(x=30, y=50)\nportinput = Entry(win1, width=4)\nportinput.insert(INSERT, \"\")\nportinput.place(x=88, y=20)\nipinput = Entry(win1, width=8)\nipinput.insert(INSERT, \"\")\nipinput.place(x=60, y=50)\n# 设置投票\nTopic = Label(win1, text=\"投票主题:\")\nTopic.place(x=220, y=80)\ntopictext = Entry(win1, width=8)\ntopictext.place(x=220, y=100)\ntopictext.insert(INSERT, \"\")\nc1 = Label(win1, text=\"选项1:\")\nc1.place(x=220, y=120)\nc1text = Entry(win1, width=8)\nc1text.place(x=220, y=140)\nc1text.insert(INSERT, \"\")\nc2 = Label(win1, text=\"选项2:\")\nc2.place(x=220, y=160)\nc2text = Entry(win1, width=8)\nc2text.place(x=220, y=180)\nc2text.insert(INSERT, \"\")\nc3 = Label(win1, text=\"选项3:\")\nc3.place(x=220, y=200)\nc3text = Entry(win1, width=8)\nc3text.place(x=220, y=220)\nc3text.insert(INSERT, \"\")\nc4 = Label(win1, text=\"选项4:\")\nc4.place(x=220, y=240)\nc4text = Entry(win1, width=8)\nc4text.place(x=220, y=260)\nc4text.insert(INSERT, \"\")\nc5 = Label(win1, text=\"选项5:\")\nc5.place(x=220, y=280)\nc5text = Entry(win1, width=8)\nc5text.place(x=220, y=300)\nc5text.insert(INSERT, \"\")\nc6 = Label(win1, text=\"选项6:\")\nc6.place(x=220, y=320)\nc6text = Entry(win1, width=8)\nc6text.place(x=220, y=340)\nc6text.insert(INSERT, \"\")\n# 投票情况\nRes = Label(win1, text=\"当前投票情况:\")\nc1R = Label(win1, text=\"1: \" + str(VoteCal(1)) + \"票\")\nc2R = Label(win1, text=\"2: \" + str(VoteCal(2)) + \"票\")\nc3R = Label(win1, text=\"3: \" + str(VoteCal(3)) + \"票\")\nc4R = Label(win1, text=\"4: \" + str(VoteCal(4)) + \"票\")\nc5R = Label(win1, text=\"5: \" + str(VoteCal(5)) + \"票\")\nc6R = Label(win1, text=\"6: \" + str(VoteCal(6)) + \"票\")\nRes.place(x=330, y=210)\nc1R.place(x=330, y=230)\nc2R.place(x=390, y=230)\nc3R.place(x=330, y=260)\nc4R.place(x=390, y=260)\nc5R.place(x=330, y=290)\nc6R.place(x=390, y=290)\nc1R[\"text\"] = win1.update()\n# 功能键\nSendVote = Button(win1, text=\"发起投票\", command=Dealoutvote)\nStopVote = Button(win1, text=\"停止投票\", command=StopVote)\nReVote = Button(win1, text=\"重置投票\", command=NewVote)\nReashow = Button(win1, text=\" 刷 新 \", command=ResShow)\nSendResult = Button(win1, text=\"发布结果\", command=Dealoutres)\nSendVote.place(x=330, y=100)\nStopVote.place(x=330, y=140)\nReVote.place(x=330, y=180)\nReashow.place(x=330, y=330)\nSendResult.place(x=390, y=330)\n# 菜单\nMymenu = Menu(win1)\nMymenu.add_command(label=\" 帮 助 \", command=MyHelp)\nwin1[\"menu\"] = Mymenu\n\nwin1.update_idletasks()\nwin1.mainloop()","repo_name":"Zombinn/VoteSysterm","sub_path":"Voting_system/Votingsys_sever.py","file_name":"Votingsys_sever.py","file_ext":"py","file_size_in_byte":9152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"29239486082","text":"from utils import str_list\n\nf = [x.replace(':', '=') for x in str_list(21)]\nroot = None\nwhile not root:\n for p in f:\n try:\n exec(p)\n except NameError:\n continue\nprint(int(root))\n","repo_name":"mrisoli/adventofcode","sub_path":"python/2022/d21p1.py","file_name":"d21p1.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"47"} +{"seq_id":"37885990823","text":"\nimport os\nimport sys\nimport gzip\nimport email\nimport imaplib\nfrom flow.downloaders.downloader import IDownloader, ZeroDownloadExcept\n\n\nclass ZaloraDownloader(IDownloader):\n 'Zalora downloader'\n\n def __init__(self, kwargs):\n IDownloader.__init__(self, kwargs)\n self.kwargs['download_file_gz'] = os.path.join(\n kwargs['download_path'],\n kwargs['site'] + '.' + kwargs['country'] + '.gz')\n\n def download(self):\n try:\n self.kwargs['download_result'] = 1\n self.kwargs['downloaded'] = 0\n fil = self.kwargs['download_file']\n fgz = self.kwargs['download_file_gz']\n search_word = self.kwargs['search_word']\n user = \"zaloraiq@gmail.com\"\n pwd = \"Iqnect@123\"\n maplib = imaplib.IMAP4_SSL(\"imap.gmail.com\")\n maplib.login(user, pwd)\n maplib.select(\"[Gmail]/All Mail\")\n _, items = maplib.search(None, \"ALL\")\n items = items[0].split()\n for emailid in reversed(items):\n _, data = maplib.fetch(emailid, \"(RFC822)\")\n email_body = data[0][1]\n mail = email.message_from_string(email_body)\n if mail.get_content_maintype() != 'multipart' or (search_word not in email_body):\n continue\n for part in mail.walk():\n if part.get_content_maintype() == 'multipart' or (\n part.get('Content-Disposition') is None):\n continue\n with open(fgz, 'wb') as file_gz:\n file_gz.write(part.get_payload(decode=True))\n with gzip.open(fgz, 'rb') as ifile, open(fil, 'wb') as ofile:\n ofile.write(ifile.read())\n self.kwargs['downloaded'] = 1\n return\n\n if not self.kwargs['downloaded']:\n raise ZeroDownloadExcept\n\n except:\n self.kwargs['download_error'] = sys.exc_info()\n self.kwargs.update({'download_result': 0})\n\n def transform(self):\n pass\n","repo_name":"StephenWangasg/aflow","sub_path":"flow/downloaders/zalora_downloader.py","file_name":"zalora_downloader.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"9345187520","text":"import os\nimport sys\nimport time\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\nimport pymc as pm\nimport pymcmcstat.ParallelMCMC\nimport pytensor.tensor as at\nfrom pytensor.tensor.basic import as_tensor_variable\n\nsys.path.append('../ga/mpi_scripts/')\nfrom classes import DRAM, CustomLogLike\nfrom functions import func_model, return_data_cut\nfrom gene_utils import update_C_from_genes\nfrom ina_model import InaModel\nfrom io_utils import collect_results\nfrom copy import deepcopy\n\ntrace_name = 'activation#1'\n\nga_result_dirname = '../results/ga/' #dir with the results of GA optimization\ndirname_case = os.path.join(ga_result_dirname, trace_name)\ncase = '230709_115003'#os.listdir(dirname_case)[0]\n\n\n\n#Create_output_dir\npath_mcmc_output = f'../results/pymc/activation/{trace_name}'\n\nabspath_mcmc_output = os.path.abspath(path_mcmc_output)\npath_mcmc_output_list = abspath_mcmc_output.split('/')\nfor k in range(2, len(path_mcmc_output_list)+1):\n part_path = os.path.join('/',*abspath_mcmc_output.split('/')[:k])\n logic = os.path.isdir(part_path)\n if not logic:\n os.mkdir(part_path)\n\ntime_suffix = datetime.now().strftime(\"%y%m%d_%H%M%S\")\nfull_filename = os.path.join(abspath_mcmc_output, time_suffix+'.nc')\n\n### For using gradient of trace, instead current trace: GRAD=True\n### For log parameters: LOG=True\n\nINACT = 0 #Activation/Inactivation protocol\nGRAD = 1 #Derivative of trace is used\nLOG = 1 #Logarithmic scale\nPIPETTE = 0 #Model accounting for pipette\n\n#nchain = 40\n#ndraws = 10_000\nnchain = 4 #number of MCMC chains\nndraws = 100 #number of draws\nnburn = 0 #burn-in period. Set to 0, we remove it manually.\n\nprint(f'Trace name = {trace_name}')\nprint(f'GRAD = {GRAD}\\nLOG = {LOG}\\nPIPETTE = {PIPETTE}\\nDraws = {ndraws}\\nChains = {nchain}')\n\n\nresult = collect_results(case, dirname_case, dump_keys=['best'])\nsol_best = result['sol_best']\nconfig = result['config']\nbounds = config['runtime']['bounds']\nphenotype_best = result['phenotype_best']['individual']\ndata = config['experimental_conditions']['individual']['phenotype']\n\nif PIPETTE:\n model_dir = '../src/model_ctypes/PC_model_with_pipette/'\nelse:\n model_dir = '../src/model_ctypes/PC_model'\n\nlegend_states = config['runtime']['legend']['states'] \nlegend_algebraic = config['runtime']['legend']['algebraic'] \nlegend_constants = config['runtime']['legend']['constants']\n\nA = deepcopy(legend_algebraic)\nC = deepcopy(legend_constants)\nS = deepcopy(legend_states)\n\n\nfilename_so = config['filename_so'] \nIna = InaModel(filename_so)\n\ndata_no_grad = data.copy()\n\nweight = config['experimental_conditions']['individual']['sample_weight']\nweight_grad = config['experimental_conditions']['individual']['sample_derivative_weight']\n\n\n#Parameters that we do not want to sample\npass_params = ['alpha',\n # 'c_m', 'R', 'g_max',\n # 'x_c_comp', 'x_r_comp', 'tau_z',\n # 'a0_m', 'b0_m', 's_m', 'delta_m', 'tau_m_const',\n # 'a0_h', 'b0_h', 's_h', 'delta_h', 'tau_h_const',\n # 'a0_j', 'b0_j', 's_j', 'delta_j', 'tau_j_const',\n # 'v_half_m', 'k_m',\n # 'v_half_h', 'k_h',\n # 'v_rev', 'g_leak',\n ]\n\nexperiment_condition_name = list(config['experimental_conditions'].keys())[-1]\nupdate_C_from_genes(C, sol_best, experiment_condition_name, config)\n\nconst_from_sol_best = deepcopy(C)\nfor param in const_from_sol_best.index:\n if param not in pass_params:\n const_from_sol_best[param] = legend_constants[param]\n\n# delete pass parameters from m_index and sol_best_before by their number\nm_index = config['runtime']['m_index']\nmask_multipliers = config['runtime']['mask_multipliers']\n\ndelete_parameters = []\nfor param in pass_params:\n for condition_name in config['experimental_conditions']:\n if param in config['experimental_conditions'][condition_name]['params']:\n delete_index = (condition_name, param)\n param_number = np.where(m_index == delete_index) \n delete_parameters.append(param_number)\n\nm_index = m_index.delete(delete_parameters)\nsol_best_before = np.delete(sol_best.values, delete_parameters)\nbounds = np.delete(bounds, delete_parameters, 0)\nif LOG:\n mask_log = np.delete(mask_multipliers, delete_parameters) \n for i, logic in enumerate(mask_log):\n if logic:\n bounds[i] = np.log10(bounds[i])\n sol_best_before[i] = np.log10(sol_best_before[i])\nelse:\n mask_log = None \n\n\nchange_bounds = {'v_half_h':np.array([30., 100.]),\n 'k_h':np.array([3., 20.]),\n 'v_half_m':np.array([-10., 60.]),\n 'k_m':np.array([3., 20.]),\n 'g_leak':np.array([0.01, 20.]),\n 'g_max':np.array([0.005, 20.]),\n 'v_rev':np.array([1., 150.])}\n\nfor param in change_bounds:\n if param not in pass_params:\n param_ind = np.where(m_index.get_level_values(1)==param)[0][0]\n bounds[param_ind] = change_bounds[param]\n\nif GRAD:\n flag = 'grad'\n data = np.gradient(data)\nelse:\n flag = 'ina'\n\n\nmatrix_name = 'proposal_all_parameters.csv'\nparam_cov_mat = pd.read_csv(matrix_name, index_col=0)\ncov_mat_len = len(param_cov_mat)\nparam_cov_mat = param_cov_mat.loc[list(m_index.get_level_values(1)), \n list(m_index.get_level_values(1))]\nparam_cov_mat = param_cov_mat.values * len(sol_best_before) / cov_mat_len\n\n#Some parameters are multipliers. The routine below converts them to absolute values.\n\n\ntrace = func_model(sol_best_before,\n m_index,\n Ina=Ina,\n const=const_from_sol_best,\n config=config,\n flag=flag,\n mask_log=mask_log,)\n\n#Calculate the solution with no sodium current at all. \n#Used to check for 'bad' initial MCMC states.\nsol_no_ina = sol_best_before.copy()\nsol_no_ina[np.where(m_index.get_level_values(1) == 'g_max')[0][0]] = -100\nno_ina = func_model(sol_no_ina, \n m_index, \n Ina=Ina, \n const=const_from_sol_best, \n config=config, \n flag=flag,\n mask_log=mask_log,\n ) \n\ndownsampl = 10 #downsampling \n \nweight_cut = weight.drop('t', axis = 1)\nmask_cut = np.zeros_like(weight_cut)\n\nmask_cut_big = mask_cut.copy()\nmask_cut_big[(np.where(weight_cut > 1.)[0][::1], \n np.where(weight_cut > 1.)[1][::1])]= 1.\nmask_cut_big[:, 2300:] = 0\nmask_cut_big = mask_cut_big.reshape(-1)\nmask_cut_big = mask_cut_big.astype('bool')\n\n\nmask_cut[(np.where(weight_cut > 1.)[0][::downsampl], \n np.where(weight_cut > 1.)[1][::downsampl])]= 1.\nmask_cut[:, 2300:] = 0\nmask_cut[1::2] = 0\nmask_cut[:6] = 0\n\nmask_cut_down = mask_cut.reshape(-1)\nmask_cut_down = mask_cut_down.astype('bool')\n\ndata_cut_size = np.sum(mask_cut_down)\ndata_cut = np.zeros_like(data_cut_size)\ndelta_data = np.array(data - trace)\ndata_cut = delta_data[mask_cut_down.astype(bool)]\n \n\ndiff_no_ina = np.sum((data[mask_cut_down] - no_ina[mask_cut_down])**2)\ndiff_best = np.sum((data[mask_cut_down] - trace[mask_cut_down])**2)\n\nina_dict = {}\nina_dict['data'] = data\nina_dict['m_index'] = m_index\nina_dict['Ina'] = Ina\nina_dict['const'] = const_from_sol_best\nina_dict['config'] = config\nina_dict['mask_log'] = mask_log\nina_dict['mask_cut'] = mask_cut_down\nina_dict['flag'] = flag\nina_dict['mask_cut_big'] = mask_cut_big\nina_dict['return_data_cut'] = return_data_cut\n\n\nsols = []\nsols.append(sol_best_before)\n\nlen_random_start = nchain - len(sols)\nif nchain - len(sols) < 0:\n len_random_start = 0\n\n\ninitial_values_parameters = []\n\n\ninitial_bounds = {'v_half_m':np.array([15.0, 40.]),\n 'v_half_h':np.array([60., 90.]),\n 'k_m':np.array([5., 15.]),\n 'k_h':np.array([5., 15.])}\n\nmax_cmodel_time = 1.3\nmin_dv_between_act_inact = 30\n\nwhile len(initial_values_parameters)!=len_random_start:\n if True:\n s_b_b = sols[0] #Solution of GA is included as initial state of one of the chains.\n#!!!Following piece of code was used to reduce burn-in period\n#!!!Several GA solutions (three_starts) were used as initial Markov Chain states.\n#!!!Hardcoded magic number 13 is 40 chains divided by 3 initial solutions.\n# if len(initial_values_parameters)%13 == 0 :\n# s_b_b = sols[len(initial_values_parameters)//13] \n \n up, low = 0.8, 1.2\n new_bounds = []\n\n for i, [index, param_bounds] in enumerate(zip(m_index.get_level_values(1), bounds)):\n lb, ub = np.sort([s_b_b[i]*up, s_b_b[i]*low])\n if lb < param_bounds[0]:\n lb = param_bounds[0]*1.01\n if ub > param_bounds[1]:\n ub = param_bounds[1]*0.99\n\n new_bounds.append([lb, ub])\n new_bounds = np.array(new_bounds)\n\n for param in initial_bounds:\n if param not in pass_params:\n param_ind = np.where(m_index.get_level_values(1) == param)[0][0]\n new_bounds[param_ind] = initial_bounds[param]\n\n#Initial states of chain are generated below within new_bounds.\n#For some reason we use pymcmcstat here. This is a leftover from previous version, but it works. \n initial_value = pymcmcstat.ParallelMCMC.generate_initial_values(1,\n len(new_bounds),\n new_bounds.T[0],\n new_bounds.T[1])\n \n#This is to decrease burn-in. We don't want to start with 'bad' solutions with no Ina. \n check_time = -time.time()\n trace_now = func_model(initial_value[0],\n m_index,\n Ina=Ina,\n const=const_from_sol_best,\n config=config,\n flag=flag,\n mask_log=mask_log,\n )\n check_time += time.time()\n diff_trace_now = np.sum((data[mask_cut_down] - trace_now[mask_cut_down])**2)\n\n if np.all([_ not in pass_params for _ in ['v_half_h', 'v_half_m']]):\n v_half_h_ind = np.where(m_index.get_level_values(1) == 'v_half_h')[0][0]\n v_half_m_ind = np.where(m_index.get_level_values(1) == 'v_half_m')[0][0]\n diff_v = initial_value[0][v_half_h_ind] - initial_value[0][v_half_m_ind]\n else:\n diff_v = min_dv_between_act_inact\n\n if np.all([check_time < max_cmodel_time, #time to model counting is not too much\n diff_v >= min_dv_between_act_inact, #start difference between half activationd and half inactivation is more than min_dv_between_act_inact\n diff_trace_now < diff_no_ina]): #trace from start parameters not equal trace without sodium curreny\n initial_values_parameters.append(initial_value[0])\n\ninitial_values_parameters = np.array(initial_values_parameters)\ninitial_values_parameters = np.append(initial_values_parameters, sols, axis=0)\n\n\nstart_dicts = []\nfor sol in initial_values_parameters:\n start_val = np.array(sol)\n start_vals = {}\n start_vals['parameters'] = start_val\n start_dicts.append(start_vals)\nstart_dicts = np.array(start_dicts)\n# print(f'start_dicts = {start_dicts}')\n\nmodel = pm.Model()\ntransform = None\nscale = 1 #Proposal matrix is empirical covariance matrix multiplied by scale factor.\ntune_interval = 10_000 #Proposal matrix is adaptive change it every N steps. 10_000 if initial proposal is good enough.\nscale_factor = 1/5 #scaling factor used for delayed rejection\n\nn = 1\np = np.shape(data_cut)[0]\nS_0 = np.eye(p) * data_cut**2\n\n\nmu = (bounds.T[0] + bounds.T[1]) / 2\nspecial_mu = {'v_half_h':76.,\n 'k_h':11,\n 'v_rev':18}\n\nfor param in special_mu:\n if param not in pass_params:\n mu[np.where(m_index.get_level_values(1)==param)[0][0]] = special_mu[param]\n\n\nsigma = (bounds.T[1] - bounds.T[0]) * 2\nspecial_sigma = {'v_half_h':9.,\n 'k_h':3,\n 'v_rev':7}\nfor param in special_sigma:\n if param not in pass_params:\n sigma[np.where(m_index.get_level_values(1)==param)[0][0]] = special_sigma[param]\n\n\nwith model:\n parameters = pm.Normal('parameters',\n mu=mu,\n sigma=sigma,\n transform=transform)\n\n\n loglike = CustomLogLike(ina_dict=ina_dict,\n n=n,\n p=p,\n S=S_0,\n )\n\n params = as_tensor_variable(parameters,)\n pm.Potential(\"likelihood\", loglike(params))\n\n step_parameters = DRAM([parameters],\n loglike=loglike,\n S=param_cov_mat,\n proposal_dist=pm.MultivariateNormalProposal,\n scaling=scale,\n tune='S',\n tune_interval=tune_interval,\n bounds=bounds.T,\n initial_values_size=len(sol_best_before),\n transform=transform,\n scale_factor=scale_factor,\n )\n\n\n steps = step_parameters\n\nidata = pm.sample(ndraws,\n tune=nburn,\n step=steps,\n model = model,\n chains=nchain,\n cores=nchain,\n return_inferencedata=True,\n initvals=start_dicts,\n )\n\n\n\nidata.to_netcdf(full_filename)\nprint(f'MCMC result saved at {full_filename}')","repo_name":"humanphysiologylab/PCoptim","sub_path":"MCMC/run_act.py","file_name":"run_act.py","file_ext":"py","file_size_in_byte":13694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"32815722806","text":"import os\nimport tkinter as tk\nfrom decimal import *\nfrom tkinter import filedialog, ttk\n\nfrom tkinterdnd2 import *\n\nimport sys\nsys.path.append('./')\n\nimport fileData, graphAutocorrelation, graphESA, graphOSA, graphWaveform\n\nclass Main(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n\n # 著作権表示\n license_label = ttk.Label(\n self.master,\n foreground='gray',\n text='Copyright © 2001-2022 Python Software Foundation; All Rights Reserved',\n font=(\"Arial Narrow\", 10)\n )\n license_label.pack(anchor=tk.W)\n \n # 説明書き\n discription1 = ttk.Label(\n self.master,\n text='ボタンを押すとグラフ用の新しいウィンドウが生成されます。\\nそれぞれのウィンドウにファイルをドロップすることで再描画が可能です。',\n font=(\"\", 12),\n justify='center'\n )\n discription1.pack(pady=[15,0])\n\n # 説明書き2\n discription2 = ttk.Label(\n self.master,\n text='※R&S InstrumentViewを初期の場所にインストールしていれば、setファイルからcsvを生成して描画します。\\n※ファイル選択時、右下のプルダウンから拡張子を選択できます。',\n foreground='gray',\n font=(\"\", 9),\n justify='center'\n )\n discription2.pack(pady=[5,0])\n\n # ファイル選択チェックボタン\n self.select_bln = tk.BooleanVar(value=False)\n select_file = ttk.Checkbutton(\n self.master,\n text='ウィンドウを開く際にファイルを選択',\n variable=self.select_bln,\n )\n select_file.pack(pady=[15,0])\n\n # フレーム作成\n frame1 = ttk.Frame(self.master)\n\n # グラフ作成用のボタンをフレームに設置\n graph_button_frame = tk.Frame(frame1)\n OSAbutton = ttk.Button(graph_button_frame, text=\"OSAグラフの表示\", width=18, padding=[0,10], command=self.make_OSA)\n WFbutton = ttk.Button(graph_button_frame, text=\"パルス波形の表示\", width=18, padding=[0,10], command=self.make_WF)\n ESAbutton = ttk.Button(graph_button_frame, text=\"ESAグラフの表示\", width=18, padding=[0,10], command=self.make_ESA)\n ACbutton = ttk.Button(graph_button_frame, text=\"自己相関波形の表示\", width=18, padding=[0,10], command=self.make_AC)\n \n OSAbutton.grid(row=0, column=0, sticky=tk.EW)\n WFbutton.grid(row=0, column=1, sticky=tk.EW)\n ESAbutton.grid(row=1, column=0, sticky=tk.EW)\n ACbutton.grid(row=1, column=1, sticky=tk.EW)\n \n graph_button_frame.pack()\n frame1.pack()\n\n def make_OSA(self):\n sub_win = tk.Toplevel(self.master)\n sub_win.title('OSA')\n graph = graphOSA.GraphOSA(sub_win)\n\n if self.select_bln.get():\n file = filedialog.askopenfilename(title='ファイルを選択:OSA', filetypes=[('テキストファイル', 'txt'),('csvファイル', 'csv')])\n if not file:\n return\n graph.file_data.set_file_data(file)\n graph.file_data.read_OSA_TXT()\n\n graph.draw_graph()\n\n def make_WF(self):\n sub_win = tk.Toplevel(self.master)\n sub_win.title('Waveform')\n graph = graphWaveform.GraphWaveform(sub_win)\n\n if self.select_bln.get():\n file = filedialog.askopenfilename(title='ファイルを選択:パルス波形', filetypes=[('csvファイル', 'csv')])\n if not file:\n return\n graph.file_data.set_file_data(file)\n graph.file_data.read_oscillo_csv()\n\n graph.draw_graph()\n\n def make_ESA(self):\n sub_win = tk.Toplevel(self.master)\n sub_win.title('ESA')\n graph = graphESA.GraphESA(sub_win)\n\n if self.select_bln.get():\n file = filedialog.askopenfilename(title='ファイルを選択:ESA', filetypes=[('csvファイル', 'csv'),('setファイル', 'set')])\n if not file:\n return\n graph.file_data.set_file_data(file)\n graph.file_data.read_ESA()\n\n graph.draw_graph()\n\n def make_AC(self):\n sub_win = tk.Toplevel(self.master)\n sub_win.title('Autocorrelation')\n graph = graphAutocorrelation.GraphAutocorrelation(sub_win)\n\n if self.select_bln.get():\n file = filedialog.askopenfilename(title='ファイルを選択:自己相関波形', filetypes=[('csv', 'csv')])\n if not file:\n return\n graph.file_data.set_file_data(file)\n graph.file_data.read_oscillo_csv()\n\n graph.draw_graph()\n\nif __name__ == '__main__':\n #ウィンドウ作製 \n main_win = TkinterDnD.Tk()\n win_w = 600\n win_h = 260\n sw = main_win.winfo_screenwidth()\n sh = main_win.winfo_screenheight()\n main_win.geometry(str(win_w) + 'x' + str(win_h) + '+' + str(int(sw/2-win_w/2)) + '+' + str(int(sh/2-win_h/2)))\n main_win.title(\"データ→グラフ変換ソフト v1.0.2\")\n\n app = Main(main_win)\n main_win.mainloop()\n","repo_name":"Skey7731/Easy-Graph-Draw-for-Mode-Locking-Measurement-2","sub_path":"Graph-Draw/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5260,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"28623177426","text":"N = int(input())\nxy = set([tuple(map(int,input().split())) for _ in range(N)])\nmove = [[-1,-1], [-1,0], [0,-1], [0,1], [1,0], [1,1]]\n\ndone = set()\nans = 0\n\nfor x,y in xy:\n if (x,y) in done:\n continue\n todo = [(x,y)]\n done.add((x,y))\n ans += 1\n \n while todo:\n nx,ny = todo.pop()\n for di,dj in move:\n if (nx+di,ny+dj) not in xy or (nx+di,ny+dj) in done:\n continue\n todo.append((nx+di,ny+dj))\n done.add((nx+di,ny+dj))\n\nprint(ans)\n","repo_name":"Tom0llow/atcoder_submissions","sub_path":"submissions/abc269/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"21976908413","text":"'''\nAnalyze attack outputs\n\n1) For input json attack file (e.g. textfooler), check what fraction satisfy the constraints of attack (e.g. bae)\n2) Find the worst good-bad word pair for eval of original text (test sensitivity)\n3) Find the highest (on average) rank of sent words and check what fraction of predicted mask tokens change\n'''\nimport sys\nimport os\nimport argparse\nimport json\nfrom tqdm import tqdm\nimport torch\nfrom statistics import mean, stdev\n\nfrom src.attack.constraints import Constraint\nfrom src.models.model_selector import select_model\n\ndef constraints_satisfied(data, attack_method='bae'):\n checker = Constraint(attack_method)\n satisfied = 0\n for d in tqdm(data):\n if checker.check_constraint(d['text'], d['att_text']):\n satisfied +=1\n return satisfied/len(data)\n\ndef get_highest_rank(logits, ids):\n '''Get highest rank for any of word id in ids'''\n ranked_inds = torch.argsort(logits, descending=True).detach().cpu().tolist()\n for ind in ranked_inds:\n if ind in ids:\n return ind, ranked_inds\n \ndef max_vote(mask_logits, id_pairs):\n summed = 0\n for id_pair in id_pairs:\n with torch.no_grad():\n logits = mask_logits[id_pair]\n pred_ind = torch.argmax(logits).detach().cpu().item()\n summed += pred_ind\n if summed == int(len(id_pairs)/2):\n return -1\n else:\n return int(summed/len(id_pairs))\n\n\nif __name__ == \"__main__\":\n\n # Get command line arguments\n commandLineParser = argparse.ArgumentParser()\n commandLineParser.add_argument('--json_path', type=str, nargs='+', required=True, help='saved .json file(s)')\n\n commandLineParser.add_argument('--cross_constraint', action='store_true', help='check constraint against attack method constraints')\n commandLineParser.add_argument('--attack_constraint', type=str, default='bae', help='which attack method constraints to check')\n\n commandLineParser.add_argument('--worst_pair', action='store_true', help='Eval the original text accuracy with worst performing good/bad masked token per sample')\n commandLineParser.add_argument('--best_pair', action='store_true', help='Eval the adv text accuracy with best performing good/bad masked token per sample')\n commandLineParser.add_argument('--model_path', type=str, required=False, help='trained prompt model path')\n commandLineParser.add_argument('--model_name', type=str, required=False, help='e.g. roberta-large')\n\n commandLineParser.add_argument('--task_mismatch', action='store_true', help='does task of mask token pred match sent prediction')\n # commandLineParser.add_argument('--model_path', type=str, required=False, help='trained prompt model path')\n # commandLineParser.add_argument('--model_name', type=str, required=False, help='e.g. roberta-large')\n\n commandLineParser.add_argument('--max_vote', action='store_true', help='vote after all good-bad pairs selected')\n # commandLineParser.add_argument('--model_path', type=str, required=False, help='trained prompt model path')\n # commandLineParser.add_argument('--model_name', type=str, required=False, help='e.g. roberta-large')\n\n args = commandLineParser.parse_args()\n\n # Save the command run\n if not os.path.isdir('CMDs'):\n os.mkdir('CMDs')\n with open('CMDs/analysis.cmd', 'a') as f:\n f.write(' '.join(sys.argv)+'\\n')\n\n # load the json object\n datas = []\n for json_path in args.json_path:\n with open(json_path, 'r') as f:\n datas.append(json.load(f))\n if len(args.json_path) == 1:\n data = datas[0]\n\n if args.cross_constraint:\n # check what fraction of correctly classified samples satisfied constraint\n # split successful and unsuccessful attacks\n\n success = [d for d in data if (d['label'] == d['pred_label']) and d['att_pred_label'] != d['label']]\n unsuccess = [d for d in data if (d['label'] == d['pred_label']) and d['att_pred_label'] == d['label']]\n\n print(f'Successful Attack, {args.attack_constraint} satisfied:\\t {constraints_satisfied(success, args.attack_constraint)*100}% of {len(success)} samples')\n print(f'Unsuccessful Attack, {args.attack_constraint} satisfied:\\t {constraints_satisfied(unsuccess, args.attack_constraint)*100}% of {len(unsuccess)} samples')\n \n if args.worst_pair or args.best_pair:\n # worst_pair: For each original text, find worst good-bad pair to harm the performance the most\n # best_pair: For each adv text, find best good-bad pair to boost the performance the most\n\n # load model\n model = select_model(args.model_name, model_path=args.model_path, num_labels=2, prompt_finetune=True)\n\n neg_words = ['terrible', 'horrible', 'poor', 'bad']\n pos_words = ['great', 'good', 'amazing', 'fantastic']\n\n neg_ids = [model.tokenizer(word).input_ids[1] for word in neg_words]\n pos_ids = [model.tokenizer(word).input_ids[1] for word in pos_words]\n\n id_pairs = []\n for neg in neg_ids:\n for pos in pos_ids:\n id_pairs.append([neg, pos])\n\n correct = 0\n total = 0\n\n if args.worst_pair:\n\n for d in tqdm(data):\n total += 1\n with torch.no_grad():\n mask_pos_logits = model.predict([d['text']], all_logits=True).squeeze()\n failed = False\n for id_pair in id_pairs:\n logits = mask_pos_logits[id_pair]\n pred_ind = torch.argmax(logits).detach().cpu().item()\n if pred_ind != d['label']:\n failed = True\n break\n if not failed:\n correct += 1\n print(f'Worst pair accuracy\\t{100*correct/total}%')\n\n if args.best_pair:\n\n for d in tqdm(data):\n total += 1\n with torch.no_grad():\n mask_pos_logits = model.predict([d['att_text']], all_logits=True).squeeze()\n for id_pair in id_pairs:\n logits = mask_pos_logits[id_pair]\n pred_ind = torch.argmax(logits).detach().cpu().item()\n if pred_ind == d['label']:\n correct += 1\n break\n\n print(f'Best pair accuracy\\t{100*correct/total}%')\n \n if args.task_mismatch:\n # a) Highest Rank of any sentiment word (positive or negative) in masked token prediction, averaged over the data samples\n # b) Fraction of samples with changed predicted masked token\n\n # Consider only originally correctly classified samples and for the adversarial attacks consider only successfully attacked samples.\n\n # load model\n model = select_model(args.model_name, model_path=args.model_path, num_labels=2, prompt_finetune=True)\n\n words = ['terrible', 'horrible', 'poor', 'bad', 'great', 'good', 'amazing', 'fantastic']\n ids = [model.tokenizer(word).input_ids[1] for word in words]\n\n pred_tkn_top_k = {'1':0, '10':0, '100':0} # is the original predicted token in the top-k of adv prediction for the mask token\n pred_tkn_count = 0\n\n sent_rank_orig = []\n sent_rank_adv = []\n\n for d in tqdm(data):\n if d['label'] != d['pred_label']:\n continue\n with torch.no_grad():\n mask_pos_logits_orig = model.predict([d['text']], all_logits=True).squeeze()\n rank, _ = get_highest_rank(mask_pos_logits_orig, ids)\n sent_rank_orig.append(rank)\n\n if d['att_pred_label'] != d['pred_label']:\n mask_pos_logits_adv = model.predict([d['att_text']], all_logits=True).squeeze()\n rank, ranked_adv_inds = get_highest_rank(mask_pos_logits_adv, ids)\n sent_rank_adv.append(rank)\n\n # check if predicted token changed\n pred_tkn_count += 1\n orig_pred = torch.argmax(mask_pos_logits_orig).cpu().detach().item()\n if orig_pred in ranked_adv_inds[:100]:\n pred_tkn_top_k['100'] += 1\n if orig_pred in ranked_adv_inds[:10]:\n pred_tkn_top_k['10'] += 1\n if orig_pred in ranked_adv_inds[:1]:\n pred_tkn_top_k['1'] += 1\n \n print('Rank of highest sentiment words')\n print(f'Original\\t{mean(sent_rank_orig)}+-{stdev(sent_rank_orig)}')\n print(f'Successful Adversarial\\t{mean(sent_rank_adv)}+-{stdev(sent_rank_adv)}')\n print()\n\n print('Fraction of samples with original predicted token in the top-k of adv prediction for the mask token')\n print(f'k=1\\t{pred_tkn_top_k[\"1\"]/pred_tkn_count}')\n print(f'k=10\\t{pred_tkn_top_k[\"10\"]/pred_tkn_count}')\n print(f'k=100\\t{pred_tkn_top_k[\"100\"]/pred_tkn_count}')\n \n if args.max_vote:\n # Report accuracy after using max-voting for class prediction\n\n # load model\n model = select_model(args.model_name, model_path=args.model_path, num_labels=2, prompt_finetune=True)\n\n neg_words = ['terrible', 'horrible', 'poor', 'bad']\n pos_words = ['great', 'good', 'amazing', 'fantastic']\n\n neg_ids = [model.tokenizer(word).input_ids[1] for word in neg_words]\n pos_ids = [model.tokenizer(word).input_ids[1] for word in pos_words]\n\n id_pairs = []\n for neg in neg_ids:\n for pos in pos_ids:\n id_pairs.append([neg, pos])\n\n correct_orig = 0\n correct_adv = 0\n total = 0\n\n for d in tqdm(data):\n total += 1\n with torch.no_grad():\n mask_pos_logits_orig = model.predict([d['text']], all_logits=True).squeeze()\n mask_pos_logits_adv = model.predict([d['att_text']], all_logits=True).squeeze()\n\n orig_pred = max_vote(mask_pos_logits_orig, id_pairs)\n if orig_pred == d['label']:\n correct_orig += 1\n \n adv_pred = max_vote(mask_pos_logits_adv, id_pairs)\n if adv_pred == d['label']:\n correct_adv += 1\n \n print('Max Voter Accuracy')\n print(f'Original\\t{100*correct_orig/total}%')\n print(f'Adversarial\\t{100*correct_adv/total}%')\n\n\n \n\n","repo_name":"rainavyas/nlp_attacker","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":10463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"28051947928","text":"\"\"\" Summary of the Panda Log $Rev: 16465 $ \"\"\"\n# $Id$\n# Display Panda logger content\n#\nimport re, os\nfrom datetime import datetime, timedelta\n\nimport pmConfig.pmConfig as config\nimport pmUtils.pmUtils as utils\nfrom pmUtils.pmOracle import sqlSelect\nfrom pmUtils.pmState import pmstate\nfrom pmCore.pmModule import pmModule\nfrom pmTaskBuffer.pmTaskBuffer import pmtaskbuffer as pmt\n\nlogColumns = ( 'TIME', 'NAME', 'LEVELNAME', 'TYPE', 'MESSAGE' )\n \nclass logsummary(pmModule):\n \"\"\" Summary of the Panda Log $Rev: 16465 $ \"\"\"\n #______________________________________________________________________________________ \n def __init__(self,name=None,parent=None,obj=None):\n pmModule.__init__(self,name,parent,obj)\n self.publishUI(self.doQuery)\n\n #______________________________________________________________________________________ \n def doQuery(self,tstart=None,tend=None,hours=6,days=None):\n if tstart != None and tend != None: hours = None\n duration = sqlSelect().prepareTime(hours,tstart,tend,'f',days).times('duration')\n hrs =duration.days*24+duration.seconds/3600 \n q = pmt.logSummary(hours,tstart,tend,days)\n header = q['header']\n rows = q['rows'] \n main = {}\n main['header'] = header if len(rows) >0 else []\n main['info'] = rows\n main['time'] = {}\n main['params'] = {'hours':hrs}\n self.publish(main)\n # elf.publishNav('Incindent log summary: \"%s\". \"%s\"' % ( query , timer ) ) # I know the cyber security will be mad ;-) VF.\n self.publish( \"%s/%s\" % ( self.server().fileScriptURL(),\"monitor/%s.js\" % \"logsummary\" ),role=\"script\")\n self.publishTitle(\"Summary of Panda logged incidents, last %s hours\" % hrs )\n \n\n","repo_name":"vfine/webplatform","sub_path":"pmModules/logsummary.py","file_name":"logsummary.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"11252655903","text":"\"\"\"\nbudget.py contains the routes and methods for Flask to interact with the budget database\ntable.\n\"\"\"\n\nimport datetime\nfrom http import HTTPStatus\n\nimport pytz\nimport sqlalchemy\nfrom flask import Blueprint, request\nfrom werkzeug.exceptions import abort\n\nimport budgeter.db as budgeter_db\nimport budgeter.utils as utils\nfrom budgeter.db_model.budget import Budget\nfrom budgeter.schemas.budget_item import BudgetItemSchema\n\nbp = Blueprint(\"budget\", __name__, url_prefix=\"/budget\")\n\n\n@bp.route(\"/\")\ndef budget_view() -> dict:\n db = budgeter_db.get_db()\n with db.connect() as conn:\n budget = conn.execute(sqlalchemy.select(Budget)).fetchall()\n return {\n \"status\": HTTPStatus.OK,\n \"result\": [BudgetItemSchema().dump(row) for row in budget],\n }\n\n\n@bp.route(\"/items/\", methods=(\"GET\", \"POST\"))\ndef create() -> dict:\n if request.method == \"POST\":\n data = utils.parse_json(json_data=request.get_json(), schema=BudgetItemSchema())\n\n db = budgeter_db.get_db()\n with db.connect() as conn:\n # Keys better be there marshmallow, but can be adjusted to use .get() method\n query = sqlalchemy.insert(Budget).values(\n item=data[\"item\"],\n dollars=data[\"dollars\"],\n cents=data[\"cents\"],\n flow=data[\"flow\"],\n payor_id=data[\"payor\"],\n payee_id=data[\"payee\"],\n transaction_date=data[\"transaction_date\"],\n )\n result = conn.execute(query)\n conn.commit()\n return {\n \"status\": HTTPStatus.CREATED,\n \"result\": {\n \"message\": \"Created new budget item.\",\n \"key\": result.inserted_primary_key[0],\n },\n }\n elif request.method == \"GET\":\n return budget_view()\n\n\ndef get_budget_item(id: int) -> dict:\n \"\"\"\n get_budget_item retrieves a single row from a database representing a budget row.\n\n Parameters\n ----------\n id : int\n The primary key of the budget item row.\n\n Returns\n -------\n dict\n The HTTP status code and the query result for a single budget item.\n \"\"\"\n db = budgeter_db.get_db()\n with db.connect() as conn:\n item = conn.execute(sqlalchemy.select(Budget).where(Budget.id == id)).fetchone()\n if item is None:\n abort(HTTPStatus.NOT_FOUND, f\"Budget item id {id} does not exist.\")\n return {\"status\": HTTPStatus.OK, \"result\": BudgetItemSchema().dump(item)}\n\n\n@bp.route(\"/items/\", methods=(\"GET\", \"POST\", \"DELETE\"))\ndef update(id: int):\n budget_item = get_budget_item(id)\n if request.method == \"GET\":\n return budget_item\n\n db = budgeter_db.get_db()\n if request.method == \"POST\":\n data = request.get_json()\n budget_item = budget_item[\"result\"]\n id = budget_item.pop(\"id\") # Not part of the schema and we have it already.\n budget_item[\"item\"] = data.get(\"item\", budget_item[\"item\"])\n budget_item[\"dollars\"] = data.get(\"dollars\", budget_item[\"dollars\"])\n budget_item[\"cents\"] = data.get(\"cents\", budget_item[\"cents\"])\n budget_item[\"flow\"] = data.get(\"flow\", budget_item[\"flow\"])\n budget_item[\"payor_id\"] = data.get(\"payor\", budget_item[\"payor_id\"])\n budget_item[\"payee_id\"] = data.get(\"payee\", budget_item[\"payee_id\"])\n budget_item[\"transaction_date\"] = data.get(\n \"transaction_date\", datetime.datetime.now(pytz.UTC).isoformat()\n )\n budget_item = utils.parse_json(json_data=budget_item, schema=BudgetItemSchema())\n with db.connect() as conn:\n result = conn.execute(\n sqlalchemy.update(Budget)\n .where(Budget.id == id)\n .values(\n item=budget_item[\"item\"],\n dollars=budget_item[\"dollars\"],\n cents=budget_item[\"cents\"],\n flow=budget_item[\"flow\"],\n payor_id=budget_item[\"payor_id\"],\n payee_id=budget_item[\"payee_id\"],\n date_modified=budget_item[\"transaction_date\"],\n )\n )\n conn.commit()\n return {\n \"status\": HTTPStatus.OK,\n \"result\": BudgetItemSchema().dump(result.last_updated_params()),\n }\n elif request.method == \"DELETE\":\n if budget_item[\"result\"]:\n with db.connect() as conn:\n query = sqlalchemy.delete(Budget).where(Budget.id == id)\n conn.execute(query)\n conn.commit()\n return {\"status\": HTTPStatus.NO_CONTENT, \"result\": {}}\n","repo_name":"jeffvswanson/built","sub_path":"budgeter/budget.py","file_name":"budget.py","file_ext":"py","file_size_in_byte":4692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"31804863702","text":"#LCCS\r\n#April 2023\r\n#Analysis of Selection search algorithm p81\r\n\r\nimport random\r\n\r\ndef simple_selection_sort(L):\r\n swaps = 0\r\n comparisons = 0\r\n print(\"Before: \", L)\r\n \r\n # Traverse over all list elements\r\n for i in range(len(L)):\r\n min_idx = i # Find the minimum to the right of i\r\n for j in range(i+1, len(L)):\r\n comparisons = comparisons + 1\r\n if L[j] < L[min_idx]:\r\n min_idx = j\r\n # Swap minimum element with the current element\r\n L[i], L[min_idx] = L[min_idx], L[i]\r\n min_idx = i\r\n swaps = swaps + 1\r\n\r\n print(\"After: \", L)\r\n print(\"N(%d), #Comparisons(%d),#Swaps(%d)\"%(len(L),comparisons, swaps))\r\n# Driver code ...\r\n# ... run this code for a list sizes 5, 10, 100 and 1000\r\n# ... run for already sorted, reversed and randomised lists\r\n# ... record the #comparisons and #swaps in the manual\r\nL = list(range(5)) # generate the ordered list\r\n#L.reverse() # uncomment this line to reverse the list\r\n#random.shuffle(L) # uncomment this line to randomise the list\r\nsimple_selection_sort(L)","repo_name":"pdst-lccs/NW7_Algorithms","sub_path":"activity3SelectionSortp81.py","file_name":"activity3SelectionSortp81.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"2433636164","text":"'''\n Transformations compatible with image data\n and segmentation masks simultaneously.\n\n 2020 Benjamin Kellenberger\n'''\n\nimport importlib\nimport random\nimport numpy as np\nimport torch\nimport torchvision.transforms.functional as F\nfrom PIL import Image\n\n\n''' Functionals '''\ndef _horizontalFlip(img, segMask=None):\n img = F.hflip(img)\n if segMask is not None:\n segMask = F.hflip(segMask)\n return img, segMask\n\n\ndef _verticalFlip(img, segMask=None):\n img = F.vflip(img)\n if segMask is not None:\n segMask = F.vflip(segMask)\n return img, segMask\n\n\ndef _clipPatch(img_in, segMask, patchSize, jitter=(0,0,), limitBorders=False):\n '''\n Clips a patch of size \"patchSize\" from both \"img_in\" and \"segMask\"\n at the same location. \"img_in\" and \"segMask\" can either be PIL images\n or else Torch tensors.\n\n \"jitter\" is a scalar or tuple of scalars defining the maximum pixel\n values that are randomly added or subtracted to the X and Y coordinates\n of the patch location to maximize variability.\n\n If \"limitBorders\" is set to True, the clipped patch will not exceed the\n image boundaries.\n '''\n\n # setup\n if isinstance(patchSize, int) or isinstance(patchSize, float):\n patchSize = tuple((patchSize, patchSize))\n patchSize = tuple((int(patchSize[0]), int(patchSize[1])))\n\n if jitter is None:\n jitter = 0.0\n elif isinstance(jitter, int) or isinstance(jitter, float):\n jitter = tuple((jitter, jitter))\n jitter = tuple((float(jitter[0]), float(jitter[1])))\n\n if isinstance(img_in, torch.Tensor):\n sz = tuple((img_in.size(2), img_in.size(1)))\n img = img_in.clone()\n else:\n sz = tuple((img_in.size[0], img_in.size[1]))\n img = img_in.copy()\n\n # clip\n baseCoords = torch.tensor([np.random.choice(sz[0], 1), np.random.choice(sz[1], 1)], dtype=torch.float32).squeeze()\n\n # jitter\n jitterAmount = (2*jitter[0]*(random.random()-0.5), 2*jitter[1]*(random.random()-0.5),)\n baseCoords[0] += jitterAmount[0]\n baseCoords[1] += jitterAmount[1]\n\n # sanity check\n baseCoords = torch.ceil(baseCoords).int()\n if limitBorders:\n baseCoords[0] = max(0, baseCoords[0])\n baseCoords[1] = max(0, baseCoords[1])\n baseCoords[0] = min(sz[0]-patchSize[0], baseCoords[0])\n baseCoords[1] = min((sz[1]-patchSize[1]), baseCoords[1])\n\n # assemble\n coordinates = tuple((baseCoords[0].item(), baseCoords[1].item(), patchSize[0], patchSize[1]))\n\n # do the clipping\n if isinstance(img, torch.Tensor):\n coordinates_input = tuple((coordinates[0], coordinates[1], min((sz[0]-coordinates[0]), coordinates[2]), min((sz[1]-coordinates[1]), coordinates[3])))\n img_clip = torch.zeros((img.size(0), int(patchSize[1]), int(patchSize[0]),), dtype=img.dtype, device=img.device)\n img_clip[:,0:coordinates_input[3],0:coordinates_input[2]] = img[:,coordinates_input[1]:(coordinates_input[1]+coordinates_input[3]), coordinates_input[0]:(coordinates_input[0]+coordinates_input[2])]\n else:\n img_clip = img.crop((coordinates[0], coordinates[1], coordinates[0]+coordinates[2], coordinates[1]+coordinates[3],))\n\n if segMask is not None:\n if isinstance(segMask, torch.Tensor):\n coordinates_input = tuple((coordinates[0], coordinates[1], min((sz[0]-coordinates[0]), coordinates[2]), min((sz[1]-coordinates[1]), coordinates[3])))\n segMask_clip = torch.zeros((segMask.size(0), int(patchSize[1]), int(patchSize[0]),), dtype=segMask.dtype, device=segMask.device)\n segMask_clip[:,0:coordinates_input[3],0:coordinates_input[2]] = segMask[:,coordinates_input[1]:(coordinates_input[1]+coordinates_input[3]), coordinates_input[0]:(coordinates_input[0]+coordinates_input[2])]\n else:\n segMask_clip = segMask.crop((coordinates[0], coordinates[1], coordinates[0]+coordinates[2], coordinates[1]+coordinates[3],))\n else:\n segMask_clip = None\n\n return img_clip, segMask_clip, coordinates\n\n\n''' Class definitions '''\nclass Compose(object):\n\n def __init__(self, transforms):\n self.transforms = transforms\n\n\n def __call__(self, img, segMask=None):\n for t in self.transforms:\n img, segMask = t(img, segMask)\n return img, segMask\n\n\n\nclass DefaultTransform(object):\n\n def __init__(self, transform, transform_kwargs=None):\n self.transform = transform\n\n # load transform if string\n if isinstance(self.transform, str):\n idx = self.transform.rfind('.')\n classPath, executableName = self.transform[0:idx], self.transform[idx+1:]\n execFile = importlib.import_module(classPath)\n self.transform = getattr(execFile, executableName)(**transform_kwargs)\n\n\n def __call__(self, img, segMask=None):\n if isinstance(img, list):\n for i in range(len(img)):\n img[i] = self.transform(img[i])\n else:\n img = self.transform(img)\n return img, segMask\n\n\n\nclass JointTransform(object):\n\n def __init__(self, transform, transform_kwargs=None):\n self.transform = transform\n\n # load transform if string\n if isinstance(self.transform, str):\n idx = self.transform.rfind('.')\n classPath, executableName = self.transform[0:idx], self.transform[idx+1:]\n execFile = importlib.import_module(classPath)\n self.transform = getattr(execFile, executableName)(**transform_kwargs)\n\n\n def __call__(self, img, segMask=None):\n if isinstance(img, list):\n for i in range(len(img)):\n img[i] = self.transform(img[i])\n if segMask[i] is not None:\n segMask[i] = self.transform(segMask[i])\n else:\n img = self.transform(img)\n if segMask is not None:\n segMask = self.transform(segMask)\n return img, segMask\n\n\n\nclass RandomClip(object):\n\n def __init__(self, patchSize, jitter, limitBorders, numClips=1):\n self.patchSize = patchSize\n self.jitter = jitter\n self.limitBorders = limitBorders\n self.numClips = numClips\n \n\n def __call__(self, img, segMask=None):\n if self.numClips>1:\n patch = []\n segMask_out = []\n for _ in range(self.numClips):\n patch_n, segMask_out_n, _ = _clipPatch(img, segMask, self.patchSize, self.jitter, self.limitBorders)\n patch.append(patch_n)\n segMask_out.append(segMask_out_n)\n else:\n patch, segMask_out, _ = _clipPatch(img, segMask, self.patchSize, self.jitter, self.limitBorders)\n return patch, segMask_out\n\n\n\nclass RandomSizedClip(object):\n\n def __init__(self, patchSizeMin, patchSizeMax, jitter, limitBorders, numClips=1):\n self.patchSizeMin = patchSizeMin\n if isinstance(self.patchSizeMin, int) or isinstance(self.patchSizeMin, float):\n self.patchSizeMin = (self.patchSizeMin, self.patchSizeMin,)\n self.patchSizeMax = patchSizeMax\n if isinstance(self.patchSizeMax, int) or isinstance(self.patchSizeMax, float):\n self.patchSizeMax = (self.patchSizeMax, self.patchSizeMax,)\n self.jitter = jitter\n self.limitBorders = limitBorders\n self.numClips = numClips\n \n\n def __call__(self, img, segMask=None):\n if self.numClips>1:\n patch = []\n segMasks_out = []\n for n in range(self.numClips):\n patchSize = (random.randint(self.patchSizeMin[0], self.patchSizeMax[0]), random.randint(self.patchSizeMin[1], self.patchSizeMax[1]),)\n jitter = (min(patchSize[0]/2, self.jitter[0]), min(patchSize[1]/2, self.jitter[1]),)\n patch_n, segMask_out_n, _ = _clipPatch(img, segMask, patchSize, jitter, self.limitBorders)\n patch.append(patch_n)\n segMasks_out.append(segMask_out_n)\n else:\n patchSize = (random.randint(self.patchSizeMin[0], self.patchSizeMax[0]), random.randint(self.patchSizeMin[1], self.patchSizeMax[1]),)\n jitter = (min(patchSize[0]/2, self.jitter[0]), min(patchSize[1]/2, self.jitter[1]),)\n patch, segMasks_out, _ = _clipPatch(img, segMask, patchSize, jitter, self.limitBorders)\n return patch, segMasks_out\n\n\n\nclass Resize(object):\n\n def __init__(self, size, interpolation=Image.BILINEAR):\n if isinstance(size,int):\n size = tuple((size,size))\n self.size = (size[1], size[0],)\n self.interpolation = interpolation\n if isinstance(self.interpolation, str):\n self.interpolation = self.interpolation.upper()\n if self.interpolation == 'NEAREST':\n self.interpolation = Image.NEAREST\n elif self.interpolation == 'BILINEAR':\n self.interpolation = Image.BILINEAR\n elif self.interpolation == 'BICUBIC':\n self.interpolation = Image.BILINEAR\n elif hasattr(Image, self.interpolation):\n self.interpolation = getattr(Image, self.interpolation)\n else:\n # unparsable; issue warning\n print(f'WARNING: interpolation mode \"{self.interpolation}\" not understood; set to bilinear instead.')\n self.interpolation = Image.BILINEAR\n \n\n def __call__(self, img, segMask=None):\n img = F.resize(img, self.size, self.interpolation)\n if segMask is not None:\n segMask = F.resize(img, self.size, Image.NEAREST)\n \n return img, segMask\n\n\n\nclass RandomHorizontalFlip(object):\n\n def __init__(self, p=0.5):\n self.p = p\n \n def __call__(self, img, segMask=None):\n if isinstance(img, list):\n for i in range(len(img)):\n if random.random() < self.p:\n img[i], segMask[i] = _horizontalFlip(img[i], segMask[i])\n else:\n if random.random() < self.p:\n img, segMask = _horizontalFlip(img, segMask)\n return img, segMask\n\n\n\nclass RandomFlip(object):\n \n def __init__(self, p_h=0.5, p_v=0.5):\n self.p_h = p_h\n self.p_v = p_v\n\n def __call__(self, img, segMask=None):\n if isinstance(img, list):\n for i in range(len(img)):\n if random.random() < self.p_h:\n img[i], segMask[i] = _horizontalFlip(img[i], segMask[i])\n \n if random.random() < self.p_v:\n img[i], segMask[i] = _verticalFlip(img[i], segMask[i])\n else:\n if random.random() < self.p_h:\n img, segMask = _horizontalFlip(img, segMask)\n \n if random.random() < self.p_v:\n img, segMask = _verticalFlip(img, segMask)\n return img, segMask\n\n\n\nclass RandomRot90(object):\n\n def __init__(self, stops, p):\n self.stops = min(3,abs(stops))\n self.p = p\n\n\n def __call__(self, img, segMask=None):\n if random.random() < self.p:\n numStops = random.randint(-self.stops,self.stops)\n if numStops==0:\n return img, segMask\n\n angle = numStops*90\n img = F.rotate(img, angle, resample=False, expand=False)\n segMask = F.rotate(segMask, angle, resample=False, expand=False)\n \n return img, segMask","repo_name":"microsoft/aerial_wildlife_detection","sub_path":"ai/models/pytorch/functional/transforms/segmentationMasks.py","file_name":"segmentationMasks.py","file_ext":"py","file_size_in_byte":11393,"program_lang":"python","lang":"en","doc_type":"code","stars":203,"dataset":"github-code","pt":"47"} +{"seq_id":"22900861628","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom datetime import *\nfrom PIL import ImageTk,Image\nfrom tkinter import scrolledtext\nfrom tkinter import messagebox\nimport os.path\nimport datetime\nimport random\nimport mysql.connector\nimport smtplib\n\n\n#Declaring User defined exception\nclass MyEx(Exception):\n\tdef __init__(self, msg):\n\t\tself.msg = msg\n\n#Back-End of TBS\nclass Product:\n\tdef __init__(self,name,price,qty):\n\t\tself.name = name\n\t\tself.price = price\n\t\tself.qty = qty\n\n\tdef getName(self):\n\t\treturn self.name\n\n\tdef getPrice(self):\n\t\treturn self.price\n\n\tdef getQty(self):\n\t\treturn self.qty\n\n#Database:\nveg_burger = Product(\"Veg Burger\",100,1)\nchicken_burger = Product(\"Chicken Burger\",150,1)\nmutton_burger = Product(\"Mutton Burger\",200,1)\n\ncoke_bev = Product(\"Coke\",50,1)\nsprite_bev = Product(\"Sprite\",50,1)\nfanta_bev = Product(\"Fanta\",50,1)\n\nfrench_fry = Product(\"French Fries\",75,1)\nonion_ring = Product(\"Onion Rings\",75,1)\n\npaneer_bbq = Product(\"Paneer Bbq\",150,1)\nchicken_bbq = Product(\"Chicken Bbq\",200,1)\nprawns_bbq = Product(\"Prawns Bbq\",200,1)\n\ncheese_des = Product(\"Cheese Cake\",150,1)\nchoco_des = Product(\"Chocolate Truffle\",150,1)\n\n#Inititalising Billing database\ncon = None\ncursor = None\ntry:\n\tcon = mysql.connector.connect(user = 'root',password = 'abcd1234',host = 'localhost')\n\tprint(\"Connected to database\")\n\tcursor = con.cursor()\n\tsql1 = \"create database if not exists bill;\"\n\tcursor.execute(sql1)\n\tsql3 = \"use bill;\"\n\tcursor.execute(sql3)\n\tsql2 = \"create table if not exists bill(name varchar(30), price int, qty int);\"\n\tcursor.execute(sql2)\n\tprint(\"Table Bill created\")\nexcept Exception as e:\n\tmessagebox.showerror(e)\n\tcon.rollback()\nfinally:\n\tcursor.close()\n\tif con is not None:\n\t\tcon.close()\n\n#Creating and updating the cart list\ndata = \"\"\ncart_list = []\nbill = []\nnum = random.randrange(100,999)\n\n#Front End of TBS\n#Main page of TBS\nroot = Tk()\nroot.title(\"TBS-Online Order System\")\nroot.geometry(\"640x450+400+200\")\n\ncanvas = Canvas(root,width = 700, height = 550)\ncanvas.pack()\n\nbgImage = ImageTk.PhotoImage(Image.open('root/TBS.jpg'))\ncanvas.create_image(280,150,image = bgImage)\n\ncanvas.create_text(450,30,fill=\"Red\",font=\"Times 35 italic bold\",text=\"The Burger Surfer\")\n\ncanvas.create_line(300, 42, 436, 42)\ncanvas.create_line(450, 42, 544, 42)\ncanvas.create_line(550, 42, 600, 42)\n\ndef order():\n\troot.withdraw()\n\torder.deiconify()\n\n#Cart Page using scrolled text to display the cart\ndef cart():\n\t\n\tcon = None\n\tcursor = None\n\ttry:\n\t\tcon = mysql.connector.connect(user = 'root',password = 'abcd1234',host = 'localhost')\n\t\tcursor = con.cursor()\n\t\tsql = \"use bill;\"\n\t\tcursor.execute(sql)\n\t\tfor c in cart_list:\n\t\t\tname = c.getName()\n\t\t\tprice = c.getPrice()\n\t\t\tqty = c.getQty()\n\t\t\tsql = \"insert into bill values('%s','%d','%d')\"\n\t\t\targs = (name,price,qty)\n\t\t\tcursor.execute(sql % args)\n\t\t\tcon.commit()\n\n\t\tsql = \"select * from bill;\"\n\t\tcursor.execute(sql)\n\t\tbill = cursor.fetchall()\n\n\t\tif len(cart_list) == 0:\n\t\t\traise MyEx(\"Cart Empty\")\n\t\telse:\n\t\t\troot.withdraw()\n\t\t\tcart.deiconify()\n\t\t\tfoodData.delete('1.0',END)\n\t\t\tmsg = \"Name of Item Price Qty\\n\" +\"---------------------------------------\\n\"\n\t\t\tfor c in cart_list:\n\t\t\t\tnamex = c.getName()\n\t\t\t\tls = 25 - len(namex)\n\t\t\t\tpricex = c.getPrice()\n\t\t\t\tls2 = 10 - len(str(pricex))\n\t\t\t\tqtyx = c.getQty()\n\t\t\t\tmsg += str(namex) + (\" \" *ls) + str(pricex)+ (\" \" *ls2) + str(qtyx)+\"\\n\"\n\t\t\tfoodData.insert(INSERT,msg)\n\n\t\t\ttotal = 0\n\t\t\tfor c in cart_list:\n\t\t\t\ttotal += c.getPrice() * c.getQty()\n\t\t\tfoodData.insert(INSERT,\"\\n\\n\")\n\t\t\ttotalmsg = \"Total Amount: \" + str(total)\n\t\t\tfoodData.insert(INSERT,totalmsg)\n\texcept MyEx as e:\n\t\tmessagebox.showerror(\"Error\",e)\n\texcept Exception as e:\n\t\tmessagebox.showerror(e)\n\t\tcon.rollback()\n\tfinally:\n\t\tcursor.close()\n\t\tif con is not None:\n\t\t\tcon.close()\n\n#Check-out Page for bill creation and mailing\ndef checkout():\n\n\ttry:\n\t\tif len(cart_list) == 0:\n\t\t\traise MyEx(\"Cart Empty\")\t\n\t\telse:\n\t\t\ttotal = 0\n\t\t\tmsg = \"\"\n\t\t\tdt = datetime.datetime.now().date()\n\t\t\ttime = datetime.datetime.today().time()\n\t\t\tdt = str(dt)\n\t\t\tday = dt[8:10]\n\t\t\tmonth = dt[5:7]\n\t\t\tyear = dt[0:4]\n\t\t\tdt = day + \"-\" + month +\"-\" + year\n\t\t\tdate = \"Date:\" + dt + \"\\n\" +\"Time:\"+str(time)[0:8]\n\t\t\tmsg = \"Name of Item Price Qty\\n\" +\"---------------------------------------\\n\"\n\t\t\tfor c in cart_list:\n\t\t\t\tnamex = c.getName()\n\t\t\t\tls = 25 - len(namex)\n\t\t\t\tpricex = c.getPrice()\n\t\t\t\tls2 = 10 - len(str(pricex))\n\t\t\t\tqtyx = c.getQty()\n\t\t\t\tmsg += str(namex) + (\" \" *ls) + str(pricex)+ (\" \" *ls2) + str(qtyx)+\"\\n\"\n\t\t\t\n\t\t\tfor c in cart_list:\n\t\t\t\ttotal += c.getPrice() * c.getQty()\n\t\t\ttotalmsg = \"Total Amount: Rs.\" + str(total)\n\n\t\t\t#Login page for Gmail details\n\t\t\tlogin.deiconify()\n\n\t\t\t#File-Handling for Bill\n\t\t\tfilename = \"bill.txt\"\n\t\t\tif os.path.exists(filename):\n\t\t\t\tf = None\n\t\t\t\ttry:\n\t\t\t\t\tf = open(filename,\"w\")\n\t\t\t\t\tdata = \"Bill no: \"+ str(num) +\"\\n\" + msg +\"\\n\\n\" + totalmsg + \"\\n\\n\" + date\n\t\t\t\t\tf.write(data +\"\\n\")\t\t\t\t\t\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tmessagebox.showerror(\"Error\",e)\n\t\t\t\tfinally:\n\t\t\t\t\tf.close()\n\t\t\telse:\n\t\t\t\tmessagebox.showerror(\"Error\",\"File not found\")\n\texcept MyEx as e:\n\t\tmessagebox.showerror(\"Error\",e)\n\nbtnOrder = Button(root,text = 'Order',width = 13, font = ('roman',25,'bold'),command = order)\nbtnOrderWindow =canvas.create_window(450,90, window = btnOrder)\n\nbtnCart = Button(root,text = 'Cart',width = 13, font = ('roman',25,'bold'), command = cart)\nbtnOrderWindow =canvas.create_window(450,140, window = btnCart)\n\nbtnCheckout = Button(root,text = 'Checkout',width = 13, font = ('roman',25,'bold'),command = checkout)\nbtnOrderWindow =canvas.create_window(450,190, window = btnCheckout)\n\n\n#Login Page\nlogin = Toplevel(root)\nlogin.title(\"Login\")\nlogin.geometry(\"300x200+550+300\")\nlogin.configure(background = \"White\")\n\n\ndef loginEmail():\n\teid = str(entEmailId.get())\n\tepd = str(entPwd.get())\n\tto = 'theburgersurfer@gmail.com'\n\tsubject = \"Order no:-\" + str(num)\n\n\ttext = \"\"\n\tdt = datetime.datetime.now().date()\n\ttime = datetime.datetime.today().time()\n\tdt = str(dt)\n\tday = dt[8:10]\n\tmonth = dt[5:7]\n\tyear = dt[0:4]\n\tdt = day + \"-\" + month +\"-\" + year\n\tdate = \"Date:\" + dt + \"\\n\" +\"Time:\"+str(time)[0:8]\n\ttext = \"Name of item- Qty\\n\" + (\"-\" * 25) + \"\\n\" \n\n\tfor c in cart_list:\n\t\tnamex = c.getName()\n\t\tqtyx = c.getQty()\n\t\ttext += str(namex) + \"-\" + str(qtyx)+\"\\n\"\n\n\ttotal = 0\n\tfor c in cart_list:\n\t\ttotal += c.getPrice() * c.getQty()\n\ttotalmsg = \"Total Amount: Rs.\" + str(total)\n\ttext += \"\\n\\n\" + totalmsg + \"\\n\\n\" + date\n\n\tsender = eid\n\tpassword = epd\n\tmessage = 'Subject: {}\\n\\n{}'.format(subject,text)\n\tserver = smtplib.SMTP('smtp.gmail.com',587)\n\tserver.ehlo()\n\tserver.starttls()\n\tserver.login(sender,password)\n\tprint(\"Logged In\")\n\ttry:\n\t\tserver.sendmail(sender,to,message)\n\t\tprint(\"Email Sent\")\n\t\tlogin.withdraw()\n\t\tmessagebox.showinfo(\"Information\",\"Order confirmed\\nBill Ready\")\n\t\troot.destroy()\n\texcept:\n\t\tprint(\"Error in sending Email\")\n\tfinally:\n\t\tserver.quit()\n\nemailId = Label(login,text = \"Gmail-Id:\",font = ('roman',20,'bold'))\nemailId.pack(pady = 5)\n\nentEmailId = Entry(login, bd = 5)\nentEmailId.pack(pady = 2)\n\npwd = Label(login, text = \"Password:\",font = ('roman',20,'bold'))\npwd.pack(pady = 5)\n\nentPwd = Entry(login,show = \"*\", bd = 5)\nentPwd.pack(pady = 2)\n\nconfirmButton = Button(login, text = \"Confirm\",width = 10, command = loginEmail)\nconfirmButton.pack(pady = 10)\nlogin.withdraw()\n\n#'Order' Page of TBS\n\norder = Toplevel(root)\norder.title(\"Menu\")\norder.geometry(\"650x600+400+150\")\norder.configure(background = \"Black\")\n\ndef burgersMenu():\n\torder.withdraw()\n\tbrg.deiconify()\n\ndef beveragesMenu():\n\torder.withdraw()\n\tbev.deiconify()\n\ndef friesMenu():\n\torder.withdraw()\n\tfry.deiconify()\n\ndef barbequeMenu():\n\torder.withdraw()\n\tbbq.deiconify()\n\ndef desertsMenu():\n\torder.withdraw()\n\tdes.deiconify()\n\ndef backToRoot():\n\torder.withdraw()\n\troot.deiconify()\n\nimgBurger = Image.open('root/Menu/Burgers.jpg')\nimgBurger = imgBurger.resize((200,200), Image.ANTIALIAS)\nimgBurger = ImageTk.PhotoImage(imgBurger)\nlblBurger = Label(order, image = imgBurger)\nlblBurger.place(x=60,y=20)\nbtnBurger = Button(order, text = \"Burgers\",width = 12,font = ('roman',20),command = burgersMenu)\nbtnBurger.place(x=85,y=230)\n\nimgBeverages = Image.open('root/Menu/Beverages.jpg')\nimgBeverages = imgBeverages.resize((200,200), Image.ANTIALIAS)\nimgBeverages = ImageTk.PhotoImage(imgBeverages)\nlblBeveragesFries = Label(order, image = imgBeverages)\nlblBeveragesFries.place(x=370,y=20)\nbtnBeverages = Button(order, text = \"Beverages\",width = 12,font = ('roman',20),command = beveragesMenu)\nbtnBeverages.place(x=395,y=230)\n\n\nimgFries = Image.open('root/Menu/Fries.jpg')\nimgFries = imgFries.resize((170,170), Image.ANTIALIAS)\nimgFries = ImageTk.PhotoImage(imgFries)\nlblFries = Label(order, image = imgFries)\nlblFries.place(x=30,y=320)\nbtnFries = Button(order, text = \"Fries\",width = 10,font = ('roman',20), command = friesMenu)\nbtnFries.place(x=50,y=500)\n\nimgBarbeque = Image.open('root/Menu/Barbeque.jpg')\nimgBarbeque = imgBarbeque.resize((170,170), Image.ANTIALIAS)\nimgBarbeque = ImageTk.PhotoImage(imgBarbeque)\nlblBarbeque = Label(order, image = imgBarbeque)\nlblBarbeque.place(x=240,y=320)\nbtnBarbeque = Button(order, text = \"Barbeque\",width = 10,font = ('roman',20), command = barbequeMenu)\nbtnBarbeque.place(x=260,y=500)\n\nimgDeserts = Image.open('root/Menu/Deserts.jpeg')\nimgDeserts = imgDeserts.resize((170,170), Image.ANTIALIAS)\nimgDeserts = ImageTk.PhotoImage(imgDeserts)\nlblDeserts = Label(order, image = imgDeserts)\nlblDeserts.place(x=450,y=320)\nbtnDeserts = Button(order, text = \"Desserts\",width = 10,font = ('roman',20), command = desertsMenu)\nbtnDeserts.place(x=470,y=500)\n\nimgBack = Image.open('root/Back.png')\nimgBack = imgBack.resize((10,10), Image.ANTIALIAS)\nimgBack = ImageTk.PhotoImage(imgBack)\nbackBtn = Button(order, text = \"Back\", width = 5, image = imgBack, compound = LEFT, command = backToRoot)\nbackBtn.place(x = 590, y = 570)\norder.withdraw()\n\n#Burger-Menu\n\ndef vBurg():\n\tx = veg_burger\n\tif x in cart_list:\n\t\tx.qty += 1\n\telse:\n\t\tcart_list.append(veg_burger)\n\ndef mBurg():\n\tx = mutton_burger\n\tif x in cart_list:\n\t\tx.qty += 1\n\telse:\n\t\tcart_list.append(mutton_burger)\n\ndef cBurg():\n\tx = chicken_burger\n\tif x in cart_list:\n\t\tx.qty += 1\n\telse:\n\t\tcart_list.append(chicken_burger)\n\ndef backToOrder():\n\tbrg.withdraw()\n\tfry.withdraw()\n\tbbq.withdraw()\n\tdes.withdraw()\n\tbev.withdraw()\n\torder.deiconify()\n\n\ndef nextToFries():\n\tbrg.withdraw()\n\tfry.deiconify()\n\nbrg = Toplevel(order)\nbrg.title(\"Burgers\")\nbrg.geometry(\"740x310+350+300\")\nbrg.configure(background = \"White\")\n\nimgBurger1 = Image.open('root/Burgers/VegBurger.jpg')\nimgBurger1 = imgBurger1.resize((250,250), Image.ANTIALIAS)\nimgBurger1 = ImageTk.PhotoImage(imgBurger1)\nlblBurger1 = Label(brg, image = imgBurger1)\nlblBurger1.place(x=0,y=0)\nbtnBurger1 = Button(brg, text = \"Veg-Burger\",width = 12,font = ('roman',20), command = vBurg)\nbtnBurger1.place(x=50,y=240)\n\nimgBurger2 = Image.open('root/Burgers/MuttonBurger.jpg')\nimgBurger2 = imgBurger2.resize((300,250), Image.ANTIALIAS)\nimgBurger2 = ImageTk.PhotoImage(imgBurger2)\nlblBurger2 = Label(brg, image = imgBurger2)\nlblBurger2.place(x=230,y=0)\nbtnBurger2 = Button(brg, text = \"Mutton-Burger\",width = 12,font = ('roman',20), command = mBurg)\nbtnBurger2.place(x=290,y=240)\n\n\nimgBurger3 = Image.open('root/Burgers/ChickenBurger.jpg')\nimgBurger3 = imgBurger3.resize((250,250), Image.ANTIALIAS)\nimgBurger3 = ImageTk.PhotoImage(imgBurger3)\nlblBurger3 = Label(brg, image = imgBurger3)\nlblBurger3.place(x=480,y=0)\nbtnBurger3 = Button(brg, text = \"Chicken-Burger\",width = 12,font = ('roman',20), command = cBurg)\nbtnBurger3.place(x=530,y=240)\n\nimgBack1 = Image.open('root/Back.png')\nimgBack1 = imgBack1.resize((10,10), Image.ANTIALIAS)\nimgBack1 = ImageTk.PhotoImage(imgBack1)\nbackBtn1 = Button(brg, text = \"Back\", width = 5, image = imgBack1, compound = LEFT, command = backToOrder)\nbackBtn1.place(x = 10, y = 280)\n\nimgNext1 = Image.open('root/Next.jpg')\nimgNext1 = imgNext1.resize((10,10), Image.ANTIALIAS)\nimgNext1 = ImageTk.PhotoImage(imgNext1)\nNextBtn1 = Button(brg, text = \"Next\", width = 5, image = imgNext1, compound = RIGHT, command = nextToFries)\nNextBtn1.place(x = 680, y = 280)\n\nbrg.withdraw()\n\n#Fries-Menu\ndef fFry():\n\tx = french_fry\n\tif x in cart_list:\n\t\tx.qty += 1\n\telse:\n\t\tcart_list.append(french_fry)\n\n\ndef oFry():\n\tx = onion_ring\n\tif x in cart_list:\n\t\tx.qty += 1\n\telse:\n\t\tcart_list.append(onion_ring)\n\n\ndef nextToBBQ():\n\tfry.withdraw()\n\tbbq.deiconify()\n\nfry = Toplevel(order)\nfry.title(\"Fries\")\nfry.geometry(\"600x330+400+300\")\nfry.configure(background = \"White\")\n\nimgFry1 = Image.open('root/Fries/FrenchFries.jpg')\nimgFry1 = imgFry1.resize((250,250), Image.ANTIALIAS)\nimgFry1 = ImageTk.PhotoImage(imgFry1)\nlblFry1 = Label(fry, image = imgFry1)\nlblFry1.place(x=30,y=0)\nbtnFry1 = Button(fry, text = \"French-Fries\",width = 12,font = ('roman',20), command = fFry)\nbtnFry1.place(x=80,y=260)\n\nimgFry2 = Image.open('root/Fries/OnionRings.png')\nimgFry2 = imgFry2.resize((250,250), Image.ANTIALIAS)\nimgFry2 = ImageTk.PhotoImage(imgFry2)\nlblFry2 = Label(fry, image = imgFry2)\nlblFry2.place(x=300,y=0)\nbtnFry2 = Button(fry, text = \"Onion-Rings\",width = 12,font = ('roman',20), command = oFry)\nbtnFry2.place(x=350,y=260)\n\nimgBack2 = Image.open('root/Back.png')\nimgBack2 = imgBack2.resize((10,10), Image.ANTIALIAS)\nimgBack2 = ImageTk.PhotoImage(imgBack2)\nbackBtn2 = Button(fry, text = \"Back\", width = 5, image = imgBack2, compound = LEFT, command = backToOrder)\nbackBtn2.place(x = 20, y = 300)\n\nimgNext2 = Image.open('root/Next.jpg')\nimgNext2 = imgNext2.resize((10,10), Image.ANTIALIAS)\nimgNext2 = ImageTk.PhotoImage(imgNext2)\nNextBtn2 = Button(fry, text = \"Next\", width = 5, image = imgNext2, compound = RIGHT, command = nextToBBQ)\nNextBtn2.place(x = 530, y = 300)\n\nfry.withdraw()\n\n#BBQ-Menu\n\ndef cBbq():\n\tx = chicken_bbq\n\tif x in cart_list:\n\t\tx.qty += 1\n\telse:\n\t\tcart_list.append(chicken_bbq)\n\n\ndef paBbq():\n\tx = paneer_bbq\n\tif x in cart_list:\n\t\tx.qty += 1\n\telse:\n\t\tcart_list.append(paneer_bbq)\n\n\ndef prBbq():\n\tx = prawns_bbq\n\tif x in cart_list:\n\t\tx.qty += 1\n\telse:\n\t\tcart_list.append(prawns_bbq)\n\n\ndef nextToBev():\n\tbbq.withdraw()\n\tbev.deiconify()\n\nbbq = Toplevel(order)\nbbq.title(\"Barbeque\")\nbbq.geometry(\"900x340+300+300\")\nbbq.configure(background = \"Black\")\n\nimgBbq1 = Image.open('root/Barbeque/Paneer.jpg')\nimgBbq1 = imgBbq1.resize((250,250), Image.ANTIALIAS)\nimgBbq1 = ImageTk.PhotoImage(imgBbq1)\nlblBbq1 = Label(bbq, image = imgBbq1)\nlblBbq1.place(x=10,y=10)\nbtnBbq1 = Button(bbq, text = \"BBQ-Paneer\",width = 12,font = ('roman',20), command = paBbq)\nbtnBbq1.place(x=50,y=270)\n\nimgBbq2 = Image.open('root/Barbeque/Chicken.jpg')\nimgBbq2 = imgBbq2.resize((250,250), Image.ANTIALIAS)\nimgBbq2 = ImageTk.PhotoImage(imgBbq2)\nlblBbq2 = Label(bbq, image = imgBbq2)\nlblBbq2.place(x=320,y=10)\nbtnBbq2 = Button(bbq, text = \"BBQ-Chicken\",width = 12,font = ('roman',20), command = cBbq)\nbtnBbq2.place(x=380,y=270)\n\nimgBbq3 = Image.open('root/Barbeque/Prawns.jpg')\nimgBbq3 = imgBbq3.resize((250,250), Image.ANTIALIAS)\nimgBbq3 = ImageTk.PhotoImage(imgBbq3)\nlblBbq3 = Label(bbq, image = imgBbq3)\nlblBbq3.place(x=630,y=10)\nbtnBbq3 = Button(bbq, text = \"BBQ-Prawns\",width = 12,font = ('roman',20), command = prBbq)\nbtnBbq3.place(x=690,y=270)\n\nimgBack3 = Image.open('root/Back.png')\nimgBack3 = imgBack3.resize((10,10), Image.ANTIALIAS)\nimgBack3 = ImageTk.PhotoImage(imgBack3)\nbackBtn3 = Button(bbq, text = \"Back\", width = 5, image = imgBack3, compound = LEFT, command = backToOrder)\nbackBtn3.place(x = 20, y = 310)\n\nimgNext3 = Image.open('root/Next.jpg')\nimgNext3 = imgNext3.resize((10,10), Image.ANTIALIAS)\nimgNext3 = ImageTk.PhotoImage(imgNext3)\nNextBtn3 = Button(bbq, text = \"Next\", width = 5, image = imgNext3, compound = RIGHT, command = nextToBev)\nNextBtn3.place(x = 830, y = 310)\n\nbbq.withdraw()\n\n#Beverages-Menu\n\ndef coke():\n\tx = coke_bev\n\tif x in cart_list:\n\t\tx.qty += 1\n\telse:\n\t\tcart_list.append(coke_bev)\n\n\ndef sprite():\n\tx = sprite_bev\n\tif x in cart_list:\n\t\tx.qty += 1\n\telse:\n\t\tcart_list.append(sprite_bev)\n\n\ndef fanta():\n\tx = fanta_bev\n\tif x in cart_list:\n\t\tx.qty += 1\n\telse:\n\t\tcart_list.append(fanta_bev)\n\n\ndef nextToDes():\n\tbev.withdraw()\n\tdes.deiconify()\n\nbev = Toplevel(order)\nbev.title(\"Beverages\")\nbev.geometry(\"620x270+400+300\")\nbev.configure(background = \"White\")\n\nimgBev1 = Image.open('root/SoftDrinks/Coke.jpg')\nimgBev1 = imgBev1.resize((175,175), Image.ANTIALIAS)\nimgBev1 = ImageTk.PhotoImage(imgBev1)\nlblBev1 = Label(bev, image = imgBev1)\nlblBev1.place(x=40,y=0)\nbtnBev1 = Button(bev, text = \"Coke\",width = 7,font = ('roman',20), command = coke)\nbtnBev1.place(x=80,y=200)\n\nimgBev2 = Image.open('root/SoftDrinks/Sprite.jpg')\nimgBev2 = imgBev2.resize((175,170), Image.ANTIALIAS)\nimgBev2 = ImageTk.PhotoImage(imgBev2)\nlblBev2 = Label(bev, image = imgBev2)\nlblBev2.place(x=220,y=5)\nbtnBev2 = Button(bev, text = \"Sprite\",width = 7,font = ('roman',20), command = sprite)\nbtnBev2.place(x=260,y=200)\n\nimgBev3 = Image.open('root/SoftDrinks/Fanta.jpg')\nimgBev3 = imgBev3.resize((175,170), Image.ANTIALIAS)\nimgBev3 = ImageTk.PhotoImage(imgBev3)\nlblBev3 = Label(bev, image = imgBev3)\nlblBev3.place(x=400,y=5)\nbtnBev3 = Button(bev, text = \"Fanta\",width = 7,font = ('roman',20), command = fanta)\nbtnBev3.place(x=440,y=200)\n\nimgBack4 = Image.open('root/Back.png')\nimgBack4 = imgBack4.resize((10,10), Image.ANTIALIAS)\nimgBack4 = ImageTk.PhotoImage(imgBack4)\nbackBtn4 = Button(bev, text = \"Back\", width = 5, image = imgBack4, compound = LEFT, command = backToOrder)\nbackBtn4.place(x = 20, y = 240)\n\nimgNext4 = Image.open('root/Next.jpg')\nimgNext4 = imgNext4.resize((10,10), Image.ANTIALIAS)\nimgNext4 = ImageTk.PhotoImage(imgNext4)\nNextBtn4 = Button(bev, text = \"Next\", width = 5, image = imgNext4, compound = RIGHT, command = nextToDes)\nNextBtn4.place(x = 550, y = 240)\n\nbev.withdraw()\n\n#Desserts-Menu\n\ndef cheeseCake():\n\tx = cheese_des\n\tif x in cart_list:\n\t\tx.qty += 1\n\telse:\n\t\tcart_list.append(cheese_des)\n\n\ndef chocoTruffle():\n\tx = choco_des\n\tif x in cart_list:\n\t\tx.qty += 1\n\telse:\n\t\tcart_list.append(choco_des)\n\n\ndes = Toplevel(order)\ndes.title(\"Desserts\")\ndes.geometry(\"500x270+450+300\")\ndes.configure(background = \"Black\")\n\nimgDes1 = Image.open('root/Desserts/CheeseCake.jpg')\nimgDes1 = imgDes1.resize((175,175), Image.ANTIALIAS)\nimgDes1 = ImageTk.PhotoImage(imgDes1)\nlblDes1 = Label(des, image = imgDes1)\nlblDes1.place(x=40,y=10)\nbtnDes1 = Button(des, text = \"Cheese-Cake\",width = 12,font = ('roman',20), command = cheeseCake)\nbtnDes1.place(x=50,y=200)\n\nimgDes2 = Image.open('root/Desserts/ChocTruffle.jpg')\nimgDes2 = imgDes2.resize((175,175), Image.ANTIALIAS)\nimgDes2 = ImageTk.PhotoImage(imgDes2)\nlblDes2 = Label(des, image = imgDes2)\nlblDes2.place(x=280,y=10)\nbtnDes2 = Button(des, text = \"Chocolate-Truffle\",width = 12,font = ('roman',20), command = chocoTruffle)\nbtnDes2.place(x=290,y=200)\n\nimgBack5 = Image.open('root/Back.png')\nimgBack5 = imgBack5.resize((10,10), Image.ANTIALIAS)\nimgBack5 = ImageTk.PhotoImage(imgBack5)\nbackBtn5 = Button(des, text = \"Back\", width = 5, image = imgBack4, compound = LEFT, command = backToOrder)\nbackBtn5.place(x = 20, y = 240)\n\ndes.withdraw()\n\n#Cart-Menu\n\ndef addItem():\n\tcart.withdraw()\n\torder.deiconify()\n\ndef removeItem():\n\tcart.withdraw()\n\tremo.deiconify()\n\ndef home():\n\tcart.withdraw()\n\troot.deiconify()\n\ncart = Toplevel(root)\ncart.title(\"Cart\")\ncart.geometry(\"400x400+400+200\")\ncart.configure(background = \"White\")\n\nfoodData = scrolledtext.ScrolledText(cart, width = 45, height = 20)\nfoodData.pack(pady = 20)\n\naddBtn = Button(cart,text = \"Add-Item\",command = addItem,font = ('roman',20))\naddBtn.place(x=20,y = 350)\n\nhomeBtn = Button(cart,text = \"Home\",command = home,font = ('roman',20))\nhomeBtn.place(x=140,y = 350)\n\nremBtn = Button(cart,text = \"Remove-Item\",command = removeItem,font = ('roman',20))\nremBtn.place(x=230,y = 350)\ncart.withdraw()\n\ndef confirm():\n\ttry:\n\t\tflag = False\n\t\tentName.focus()\n\t\tx = entName.get()\n\t\tfor c in cart_list:\n\t\t\ty = c.getName()\n\t\t\tif x.lower() == y.lower():\n\t\t\t\tcart_list.remove(c)\n\t\t\t\tflag = True\n\t\t\t\tmessagebox.showinfo(\"Information\",\"Item removed from cart\")\n\t\t\t\tentName.delete(0,END)\n\t\t\t\tentName.focus()\n\t\tif len(cart_list) == 0:\n\t\t\traise MyEx(\"Cart Empty\")\n\t\tif flag:\n\t\t\tpass\n\t\telse:\n\t\t\traise MyEx(\"Element not present in the cart\")\n\texcept MyEx as e:\n\t\tmessagebox.showerror(\"Error\",str(e))\n\ndef cancel():\n\tremo.withdraw()\n\troot.deiconify()\n\n\nremo = Toplevel(cart)\nremo.geometry(\"250x170+400+200\")\nremo.title(\"Removing an element\")\nremo.configure(background = \"White\")\n\nlblName = Label(remo, text = \"Name of item:\", font = ('roman',20,'bold'))\nlblName.pack(pady = 5)\n\nentName = Entry(remo, bd = 5)\nentName.pack()\n\nbtnConfirm = Button(remo,text = \"Confirm\", font= ('roman',20,'bold'), command = confirm)\nbtnConfirm.pack(pady = 5)\n\nbtnCancel = Button(remo,text = \"Cancel\", font= ('roman',20,'bold'), command = cancel)\nbtnCancel.pack(pady = 5)\nremo.withdraw()\n\nroot.mainloop()","repo_name":"hitenlulla/Food_Ordering_System","sub_path":"TBS.py","file_name":"TBS.py","file_ext":"py","file_size_in_byte":20807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"21917951684","text":"#!/usr/bin/env python\n\nimport sys; sys.path.insert(0, 'lib') # this line is necessary for the rest\nimport os # of the imports to work!\n\nimport web\nimport sqlitedb\nfrom jinja2 import Environment, FileSystemLoader\nfrom datetime import datetime\n\n###########################################################################################\n##########################DO NOT CHANGE ANYTHING ABOVE THIS LINE!##########################\n###########################################################################################\n\n######################BEGIN HELPER METHODS######################\n\n# helper method to convert times from database (which will return a string)\n# into datetime objects. This will allow you to compare times correctly (using\n# ==, !=, <, >, etc.) instead of lexicographically as strings.\n\n# Sample use:\n# current_time = string_to_time(sqlitedb.getTime())\n\ndef string_to_time(date_str):\n return datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')\n\n# helper method to render a template in the templates/ directory\n#\n# `template_name': name of template file to render\n#\n# `**context': a dictionary of variable names mapped to values\n# that is passed to Jinja2's templating engine\n#\n# See curr_time's `GET' method for sample usage\n#\n# WARNING: DO NOT CHANGE THIS METHOD\ndef render_template(template_name, **context):\n extensions = context.pop('extensions', [])\n globals = context.pop('globals', {})\n\n jinja_env = Environment(autoescape=True,\n loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')),\n extensions=extensions,\n )\n jinja_env.globals.update(globals)\n\n web.header('Content-Type','text/html; charset=utf-8', unique=True)\n\n return jinja_env.get_template(template_name).render(context)\n\n#####################END HELPER METHODS#####################\n\nurls = ('/currtime', 'curr_time',\n '/selecttime', 'select_time',\n '/add_bid','add_bid',\n '/search','search',\n '/view','view',\n # TODO: add additional URLs here\n # first parameter => URL, second parameter => class name\n )\n\nclass curr_time:\n # A simple GET request, to '/currtime'\n #\n # Notice that we pass in `current_time' to our `render_template' call\n # in order to have its value displayed on the web page\n def GET(self):\n current_time = sqlitedb.getTime()\n return render_template('curr_time.html', time = current_time)\n\nclass select_time:\n # Aanother GET request, this time to the URL '/selecttime'\n def GET(self):\n return render_template('select_time.html')\n\n # A POST request\n #\n # You can fetch the parameters passed to the URL\n # by calling `web.input()' for **both** POST requests\n # and GET requests\n def POST(self):\n post_params = web.input()\n MM = post_params['MM']\n dd = post_params['dd']\n yyyy = post_params['yyyy']\n HH = post_params['HH']\n mm = post_params['mm']\n ss = post_params['ss'];\n enter_name = post_params['entername']\n\n\n selected_time = '%s-%s-%s %s:%s:%s' % (yyyy, MM, dd, HH, mm, ss)\n \n \n # TODO: save the selected time as the current time in the database\n t = sqlitedb.transaction()\n try:\n sqlitedb.selectTime(selected_time)\n except Exception as e:\n t.rollback()\n update_message = e\n else:\n t.commit()\n update_message = '(Hello, %s. Previously selected time was: %s.)' % (enter_name, selected_time)\n\n # Here, we assign `update_message' to `message', which means\n # we'll refer to it in our template as `message'\n return render_template('select_time.html', message = update_message)\n\nclass add_bid:\n def GET(self):\n return render_template('add_bid.html')\n def POST(self):\n post_param = web.input()\n itemID = post_param['itemID']\n userID = post_param['userID']\n price = post_param['price']\n \n t = sqlitedb.transaction()\n try:\n bid = sqlitedb.enterBid(itemID, userID, price)\n except Exception as e:\n t.rollback()\n bid_message = e\n bid=[]\n else:\n t.commit()\n bid_message = '(%s has successfully add a bid on %s with a price %s.)' % (userID,itemID,price)\n\n return render_template('add_bid.html', add_result =bid, message = bid_message)\n\nclass search:\n def GET(self):\n return render_template('search.html')\n def POST(self):\n post_param = web.input()\n itemID = post_param['itemID']\n userID = post_param['userID']\n minPrice = post_param['minPrice']\n maxPrice = post_param['maxPrice']\n status = post_param['status']\n category=post_param['category']\n description=post_param['description']\n \n t = sqlitedb.transaction()\n try:\n results = sqlitedb.browse(itemID, userID, category, description, minPrice, maxPrice, status)\n except Exception as e:\n t.rollback()\n search_message = e\n results=[]\n else:\n t.commit()\n search_message = 'Items found.'\n return render_template('search.html', search_result = results, message = search_message)\n\nclass view:\n def GET(self):\n get_param = web.input()\n itemID = get_param['itemID']\n t = sqlitedb.transaction()\n try:\n attributes = sqlitedb.getItemById(itemID)\n categories = sqlitedb.categories_of_item(itemID)\n status = sqlitedb.status_of_auction(itemID)\n bids = sqlitedb.bids_of_auction(itemID)\n winner=sqlitedb.winner_of_auction(itemID)\n except Exception as e:\n t.rollback()\n view_message = e\n winner_result=''\n else:\n t.commit()\n view_message = 'The following are the information of the item'\n if winner !=[]:\n winner_result = ' Winning Bid: %s.' % (winner[0].user_id)\n else:\n winner_result = 'No Winning Bid.'\n return render_template('view.html',message=view_message, attributes_result = attributes, categories_result =categories, status_result = status, bids_result = bids,auction_winner = winner_result)\n\n\n\n###########################################################################################\n##########################DO NOT CHANGE ANYTHING BELOW THIS LINE!##########################\n###########################################################################################\n\nif __name__ == '__main__':\n web.internalerror = web.debugerror\n app = web.application(urls, globals())\n app.add_processor(web.loadhook(sqlitedb.enforceForeignKey))\n app.run()\n","repo_name":"zgdsh29/CS-145","sub_path":"Final Project-AuctionBase/Web/auctionbase.py","file_name":"auctionbase.py","file_ext":"py","file_size_in_byte":6834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6868746762","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport logging\nimport random\nimport re\nimport subprocess\nfrom tempfile import mkstemp\nfrom shutil import move, copymode\nfrom os import fdopen, remove\n\ndef line_in_file(file_path, pattern, subst):\n regexp = re.compile(pattern)\n found = False\n fh, abs_path = mkstemp()\n with fdopen(fh,'w') as new_file:\n with open(file_path) as old_file:\n for line in old_file:\n if regexp.search(line):\n found = True\n new_file.write(subst)\n else:\n new_file.write(line)\n #Copy the file permissions from the old file to the new file\n copymode(file_path, abs_path)\n #Remove original file\n remove(file_path)\n #Move new file\n move(abs_path, file_path)\n\n if not found:\n with open(file_path, 'a') as file:\n file.write(f\"{subst}\\n\")\n\ndef apt_update():\n process = subprocess.Popen(['apt-get', 'update'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n logging.info(\"Finished update.\")\n\ndef disable_dumps():\n line_in_file('/etc/security/limits.conf', '^\\* hard core 0', '* hard core 0')\n logging.info(\"Finished disable_dumps.\")\n\ndef minimum_password_age():\n line_in_file('/etc/login.defs', '^PASS_MIN_DAYS\\s+\\d', 'PASS_MIN_DAYS 1')\n logging.info(\"Finished minimum_password_age.\")\n\ndef maximum_password_age():\n line_in_file('/etc/login.defs', '^PASS_MAX_DAYS\\s+\\d', 'PASS_MAX_DAYS 90')\n logging.info(\"Finished maximum_password_age.\")\n\ndef default_umask():\n line_in_file('/etc/login.defs', '^UMASK\\s+\\d+', 'UMASK 027')\n logging.info(\"Finished default_umask.\")\n\n\"\"\"\nhttps://cisofy.com/lynis/controls/PKGS-7370/\n\"\"\"\ndef install_debsums():\n apt_update()\n process = subprocess.Popen(['apt-get', 'install', 'debsums', '-y'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n logging.info(\"Finished install_debsums.\")\n\n\"\"\"\nhttps://cisofy.com/lynis/controls/PKGS-7394/\n\"\"\"\ndef install_aptshowversions():\n apt_update()\n process = subprocess.Popen(['apt-get', 'install', 'apt-show-versions', '-y'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n logging.info(\"Finished install_aptshowversions.\")\n\ndef ssh_config():\n line_in_file('/etc/ssh/sshd_config', '^AllowTcpForwarding', 'AllowTcpForwarding no')\n line_in_file('/etc/ssh/sshd_config', '^ClientAliveCountMax', 'ClientAliveCountMax 2')\n line_in_file('/etc/ssh/sshd_config', '^Compression', 'Compression no')\n line_in_file('/etc/ssh/sshd_config', '^LogLevel', 'LogLevel VERBOSE')\n line_in_file('/etc/ssh/sshd_config', '^MaxAuthTries', 'MaxAuthTries 3')\n line_in_file('/etc/ssh/sshd_config', '^MaxSessions', 'MaxSessions 2')\n line_in_file('/etc/ssh/sshd_config', '^TCPKeepAlive', 'TCPKeepAlive no')\n line_in_file('/etc/ssh/sshd_config', '^X11Forwarding', 'X11Forwarding no')\n line_in_file('/etc/ssh/sshd_config', '^AllowAgentForwarding', 'AllowAgentForwarding no')\n logging.info(\"Finished ssh_config.\")\n\ndef legal_banner():\n line_in_file('/etc/ssh/sshd_config', '^Banner', 'Banner /etc/issue.net')\n logging.info(\"Finished legal_banner.\")\n\n\"\"\"\nhttps://cisofy.com/lynis/controls/PKGS-9626/\n\"\"\"\ndef install_sysstat():\n apt_update()\n process = subprocess.Popen(['apt-get', 'install', 'sysstat', '-y'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n logging.info(\"Finished install_sysstat.\")\n\n\"\"\"\nhttps://cisofy.com/lynis/controls/PKGS-9628/\n\"\"\"\ndef install_auditd():\n apt_update()\n process = subprocess.Popen(['apt-get', 'install', 'auditd', '-y'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n logging.info(\"Finished install_auditd.\")\n\n\"\"\"\nhttps://cisofy.com/lynis/controls/FINT-4350/\n\"\"\"\ndef install_aide():\n apt_update()\n process = subprocess.Popen(['apt-get', 'install', 'aide', '-y'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n logging.info(\"Finished install_aide.\")\n\n\"\"\"\nhttps://cisofy.com/lynis/controls/HRDN-7230/\n\"\"\"\ndef install_rkhunter():\n apt_update()\n process = subprocess.Popen(['apt-get', 'install', 'rkhunter', '-y'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n logging.info(\"Finished install_rkhunter.\")\n\n\"\"\"\nhttps://cisofy.com/lynis/controls/KRNL-6000/\n\"\"\"\ndef tune_sysctl_1():\n line_in_file('/etc/sysctl.conf', '^dev.tty.ldisc_autoload', 'dev.tty.ldisc_autoload=0')\n line_in_file('/etc/sysctl.conf', '^fs.protected_fifos', 'fs.protected_fifos=2')\n line_in_file('/etc/sysctl.conf', '^fs.suid_dumpable', 'fs.suid_dumpable=0')\n line_in_file('/etc/sysctl.conf', '^kernel.core_uses_pid', 'kernel.core_uses_pid=1')\n line_in_file('/etc/sysctl.conf', '^kernel.dmesg_restrict', 'kernel.dmesg_restrict=1')\n line_in_file('/etc/sysctl.conf', '^kernel.kptr_restrict', 'kernel.kptr_restrict=2')\n\ndef tune_sysctl_2():\n line_in_file('/etc/sysctl.conf', '^kernel.modules_disabled', 'kernel.modules_disabled=1')\n line_in_file('/etc/sysctl.conf', '^kernel.sysrq', 'kernel.sysrq=0')\n line_in_file('/etc/sysctl.conf', '^kernel.unprivileged_bpf_disabled', 'kernel.unprivileged_bpf_disabled=1')\n line_in_file('/etc/sysctl.conf', '^net.core.bpf_jit_harden', 'net.core.bpf_jit_harden=2')\n line_in_file('/etc/sysctl.conf', '^net.ipv4.conf.all.accept_redirects', 'net.ipv4.conf.all.accept_redirects=0')\n line_in_file('/etc/sysctl.conf', '^net.ipv4.conf.all.log_martians', 'net.ipv4.conf.all.log_martians=1')\n\ndef tune_sysctl_3():\n line_in_file('/etc/sysctl.conf', '^net.ipv4.conf.all.rp_filter', 'net.ipv4.conf.all.rp_filter=1')\n line_in_file('/etc/sysctl.conf', '^net.ipv4.conf.all.send_redirects', 'net.ipv4.conf.all.send_redirects=0')\n line_in_file('/etc/sysctl.conf', '^net.ipv4.conf.default.accept_redirects', 'net.ipv4.conf.default.accept_redirects=0')\n line_in_file('/etc/sysctl.conf', '^net.ipv4.conf.default.accept_source_route', 'net.ipv4.conf.default.accept_source_route=0')\n line_in_file('/etc/sysctl.conf', '^net.ipv4.conf.default.log_martians', 'net.ipv4.conf.default.log_martians=1')\n line_in_file('/etc/sysctl.conf', '^net.ipv6.conf.all.accept_redirects', 'net.ipv6.conf.all.accept_redirects=0')\n line_in_file('/etc/sysctl.conf', '^net.ipv6.conf.default.accept_redirects', 'net.ipv6.conf.default.accept_redirects=0')\n\n process = subprocess.Popen(['sysctl', '-p'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n logging.info(\"Finished tune_sysctl.\")\n\ndef upgrade():\n apt_update()\n \n process = subprocess.Popen(['apt-get', 'upgrade', '-y'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n logging.info(\"Finished upgrade.\")\n\ndef harden_it():\n logging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s %(levelname)-8s %(message)s')\n\n f = []\n f.append(disable_dumps)\n f.append(minimum_password_age)\n f.append(maximum_password_age)\n f.append(default_umask)\n f.append(install_debsums)\n f.append(install_aptshowversions)\n f.append(ssh_config)\n f.append(legal_banner)\n f.append(install_sysstat)\n f.append(install_auditd)\n # to enable aide need to configure unattended postfix install\n # f.append(install_aide)\n f.append(tune_sysctl_1)\n f.append(tune_sysctl_2)\n f.append(tune_sysctl_3)\n f.append(upgrade)\n\n number_of_functions = len(f)\n t = random.randint(0, number_of_functions)\n mask = [True]*t + [False]*(number_of_functions-t)\n random.shuffle(mask)\n logging.info(f\"The mask is {mask}.\")\n\n for i, m in enumerate(mask):\n logging.info(f\"Function {i} has a {m} mask.\")\n if m:\n f[i]()\n\nif __name__ == '__main__':\n harden_it()\n","repo_name":"landersanmi/calibra","sub_path":"client/files/harden.py","file_name":"harden.py","file_ext":"py","file_size_in_byte":8113,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"70595020944","text":"# -*- coding: utf-8 -*-\n\n# Django imports\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\nfrom django import forms\n# Project imports\nfrom .models import Card, Transaction\n\nINVALID_CARD_ERROR = 'This name or card number had already been used'\nEMPTY_FORM_ERROR = 'Please fill the empty fields in the form'\n\nclass CardInputForm(forms.ModelForm):\n class Meta:\n model = Card\n fields = ('cardholders_name', 'card_number', 'card_balance',)\n labels = {\n 'cardholders_name': _('Full name:'),\n 'card_number': _('Card number:'),\n 'card_balance': _('Amount of currency (in €):'),\n }\n error_messages = {\n 'card_number': {\n 'unique': INVALID_CARD_ERROR,\n 'required': EMPTY_FORM_ERROR,\n },\n 'cardholders_name': {\n 'unique': INVALID_CARD_ERROR,\n 'required': EMPTY_FORM_ERROR,\n },\n 'card_balance': {\n 'required': EMPTY_FORM_ERROR,\n },\n }\n\nclass TransactionForm(forms.ModelForm):\n class Meta:\n model = Transaction\n fields = ('card', 'withdraw_amount',)\n labels = {\n 'card': _('Choose your name:'),\n 'withdraw_amount': _('Withdraw amount (in €):'),\n }\n error_messages = {\n 'card': {\n 'required': EMPTY_FORM_ERROR,\n },\n 'withdraw_amount': {\n 'required': EMPTY_FORM_ERROR,\n }\n }","repo_name":"HyoMiYing/OnlineShop","sub_path":"TrgovinaApp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"877527659","text":"import pandas as pd\r\nimport asyncio\r\n\r\nimport get_data\r\n\r\ncompleted_cells = []\r\n\r\ndef get_completed_cells(filename):\r\n with open(filename) as f:\r\n for line in f.readlines():\r\n completed_cells.append(int(line)) \r\n\r\ndf = pd.read_csv(\"cells.csv\")\r\nget_completed_cells('done_cells.txt')\r\n\r\nfor cell_id in df[\"Cell ID\"]:\r\n if cell_id in completed_cells:\r\n continue\r\n loop = asyncio.get_event_loop()\r\n loop.run_until_complete(get_data.download_cell(int(cell_id)))\r\n with open('done_cells.txt', 'a') as f:\r\n f.write(\"{}\\n\".format(int(cell_id)))","repo_name":"BLimmie/eyewire_validator","sub_path":"data_scripts/get_data_full.py","file_name":"get_data_full.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"73358128461","text":"# -*- coding: utf-8 -*-\n\n# Python stdlib\nimport unittest\n\n# Unit tests\nfrom unit_tests.test_tfstate.test_provider import test_aws, test_other\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTests(test_aws.suite())\n suite.addTests(test_other.suite())\n return suite\n\nif __name__ == '__main__':\n unittest.TextTestRunner(verbosity=2).run(suite())\n","repo_name":"bclodius/python-tfstate","sub_path":"unit_tests/test_tfstate/test_provider/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"47"} +{"seq_id":"72454461264","text":"from django.core.urlresolvers import reverse\nfrom django.http import HttpResponsePermanentRedirect, Http404\nfrom issue.models import Issue\nfrom users.models import User\nfrom django.shortcuts import get_object_or_404\nfrom etc.view_helpers import json_error, json_response, render_inclusiontag, render_string\n\ndef old_issuename_permalink(request, issuename):\n try:\n i = Issue.objects.get(name = issuename)\n return HttpResponsePermanentRedirect(reverse('entity_url', args=[i.handle]))\n except:\n raise Http404\n\n\ndef old_issue_permalink(request, mongo_id):\n try:\n i = Issue.objects.get(mongo_id = mongo_id)\n return HttpResponsePermanentRedirect(reverse('entity_url', args=[i.handle]))\n except:\n raise Http404\n\ndef followed_issue_list(request, user_id):\n start = int(request.GET.get('start', 0))\n end = int(request.GET.get('end', 20))\n user = get_object_or_404(User, id=user_id)\n issue_commitments = user.commitments.with_issues()[start:end].fetch_generic_relations()\n issues = [commitment.entity for commitment in issue_commitments]\n num_issues = user.commitments.with_issues().count()\n\n html = render_string(request, \"issue/includes/followed_issue_list.html\", {\n 'issues': issues,\n 'start_index': start,\n })\n\n return json_response({\n 'html': html,\n 'has_more': end < num_issues,\n })\n","repo_name":"jumoconnect/openjumo","sub_path":"jumodjango/issue/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"47"} +{"seq_id":"25998329377","text":"# -*- encoding:utf-8 -*-\n\nimport os, uuid\n\nclass Tasktory(object):\n\n # ステータス用定数\n OPEN = 'open'\n WAIT = 'wait'\n CLOSE = 'close'\n CONST = 'const'\n\n def __init__(self, name, deadline, status=OPEN):\n\n # タスクトリID\n self.ID = str(uuid.uuid4())\n\n # タスクトリ名(ディレクトリ/フォルダ名に使用できる文字列)\n self.name = name\n\n # 期日(グレゴリオ序数)\n self.deadline = deadline\n\n # ステータス(ステータス用定数)\n self.status = status\n\n # タイムテーブル(開始エポック秒と作業時間(秒)のタプルのリスト)\n self.timetable = []\n\n # 親タスクトリ\n self.parent = None\n\n # 子タスクトリ(リスト)\n self.children = []\n\n # 種別(任意)\n self.category = None\n\n # コメント\n self.comments = ''\n\n return\n\n #==========================================================================\n # 比較/テスト\n #==========================================================================\n def __lt__(self, other):\n \"\"\"最新のタイムテーブルの大小に基づいて比較する\n \"\"\"\n return self.timestamp() < other.timestamp()\n\n def __le__(self, other):\n return self.timestamp() <= other.timestamp()\n\n def __eq__(self, other):\n return self.name == other.name\n\n def __ne__(self, other):\n return self.name != other.name\n\n def __gt__(self, other):\n return self.timestamp() > other.timestamp()\n\n def __ge__(self, other):\n return self.timestamp() >= other.timestamp()\n\n def __bool__(self):\n return True\n\n #==========================================================================\n # コンテナエミュレート\n #==========================================================================\n def __len__(self):\n \"\"\"ツリー内の全ノード数を返す\n \"\"\"\n return 1 + sum([c.__len__() for c in self.children])\n\n def __iter__(self):\n \"\"\"ツリー内の全タスクトリを走査する\n \"\"\"\n yield self\n for child in self.children:\n for c in child: yield c\n\n #==========================================================================\n # 数値型エミュレート\n #==========================================================================\n def __add__(self, other):\n \"\"\"2つのタスクトリをマージする\"\"\"\n if self != other:\n raise ValueError()\n\n # 期日はotherを優先する\n deadline = self.deadline if other.deadline is None else other.deadline\n\n # ステータスは新しい方を優先する\n status = self.status if other.status is None else other.status\n\n # 新しいタスクトリを作成する\n # 名前はどっちでも良い\n ret = Tasktory(self.name, deadline, status)\n\n # IDはselfを使用する\n ret.ID = self.ID\n\n # 作業時間は結合する。\n for s,t in self.timetable + other.timetable: ret.add_time(s,t)\n\n # 親タスクトリはotherを優先する\n ret.parent = other.parent if other.parent else self.parent\n\n # 子タスクトリリスト\n _ = self.children + other.children\n while _:\n c = _.pop(0)\n ret.append((c + _.pop(_.index(c))) if c in _ else c.deepcopy())\n\n # 種別はotherを優先する\n ret.category = self.category if other.category is None\\\n else other.category\n\n # コメントはotherを使用する\n ret.comments = other.comments\n\n return ret\n\n #==========================================================================\n # タスクトリ参照メソッド\n #==========================================================================\n def get(self, name, default=None):\n \"\"\"子タスクトリから名前で検索する\n \"\"\"\n children = [c for c in self.children if c.name == name]\n return children[0] if children else default\n\n def total_time(self):\n \"\"\"合計作業時間(秒)を返す\n \"\"\"\n return sum(t for _,t in self.timetable)\n\n def timestamp(self):\n \"\"\"タイムテーブルの中から最も大きい終了エポック秒を返す\n 作業時間が無い場合は0を返す\n \"\"\"\n return sum(sorted(self.timetable, key=lambda t:t[0])[-1])\\\n if self.timetable else 0\n\n def copy(self):\n \"\"\"単一タスクトリのディープコピーを返す(親と子を含まない)\n \"\"\"\n task = Tasktory(self.name, self.deadline, self.status)\n task.ID = self.ID\n task.timetable = [(s,t) for s,t in self.timetable]\n task.category = self.category\n task.comments = self.comments\n return task\n\n #==========================================================================\n # タスクトリ変更メソッド\n #==========================================================================\n def add_time(self, start, sec):\n \"\"\"作業時間を追加する\n start - 作業開始時刻をエポック秒で指定する\n sec - 作業時間を秒で指定する\n \"\"\"\n if (start, sec) not in self.timetable:\n self.timetable.append((start, sec))\n return self\n\n def append(self, child):\n \"\"\"子タスクトリリストにタスクトリを加える\n 子タスクトリの親タスクトリに自身をセットする\n \"\"\"\n self.children.append(child)\n child.parent = self\n return self\n\n def wash(self, other):\n \"\"\"selfのデータをotherのもので上書きする\n \"\"\"\n # otherはTasktoryでなければならない\n if not isinstance(other, Tasktory): raise TypeError()\n\n self.ID = other.ID\n self.name = other.name\n self.deadline = other.deadline\n self.timetable = [(s,t) for s,t in other.timetable]\n self.parent = other.parent\n self.children = [c for c in other.children]\n self.status = other.status\n self.category = other.category\n self.comments = other.comments\n return self\n\n #==========================================================================\n # ツリー参照メソッド\n #==========================================================================\n def find(self, path):\n \"\"\"ツリー全体からパスで検索する\n 例)tree.find('/Project/LargeTask/SmallTask/step1')\n \"\"\"\n if isinstance(path, str): path = path.rstrip('/').split('/')\n if self.name != path[0]: return None\n if len(path) == 1: return self\n for child in self.children:\n ret = child.find(path[1:])\n if ret is not None: return ret\n return None\n\n def search(self, test):\n \"\"\"ツリー全体から条件に一致するタスクトリ全てを返す\n 例)期日��一定未満かつCLOSEでないもの\n tree.search(lambda t:t.deadline < DEADLINE and t.status != CLOSE)\n 例)特定のIDのタスクトリ\n tree.search(lambda t:t.ID == SPECIFIC_ID)[0]\n \"\"\"\n ret = [self] if test(self) else []\n for child in self.children: ret += child.search(test)\n return ret\n\n def path(self, root='/'):\n \"\"\"タスクトリのフルパスを返す\n \"\"\"\n return os.path.join(self.parent.path(root) if self.parent\n else root, self.name).replace('\\\\', '/')\n\n def level(self):\n \"\"\"タスクトリの階層を返す\n \"\"\"\n return self.parent.level() + 1 if self.parent else 0\n\n def deepcopy(self):\n \"\"\"タスクトリのディープコピーを返す\n \"\"\"\n task = Tasktory(self.name, self.deadline, self.status)\n task.ID = self.ID\n task.timetable = [(s,t) for s,t in self.timetable]\n task.parent = self.parent\n task.children = [c.deepcopy() for c in self.children]\n task.category = self.category\n task.comments = self.comments\n return task\n\n def clip(self, test=lambda t:t.status!=Tasktory.CLOSE):\n \"\"\"条件に一致するノードと、そのノードへの経路となるノードのみをコピーし\n て返す。\n test : 条件関数。引数としてタスクトリを受け取ってbool値を返す\n \"\"\"\n children = [c.clip(test) for c in self.children]\n if test(self) or any(children):\n task = self.copy()\n [task.append(c) for c in children if c is not None]\n return task\n return None\n","repo_name":"fukatataku/tasktory-0.1","sub_path":"lib/core/Tasktory.py","file_name":"Tasktory.py","file_ext":"py","file_size_in_byte":8825,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"38231058559","text":"\nclass Player:\n\n\tdef __init__(self, name, pokemons=[], items={}, money=0, exp_difficulty_cap=5000):\n\t\t\n\t\tself.exp_difficulty_cap = exp_difficulty_cap\n\t\t\n\t\tself.name = name\n\t\tself.pokemons = pokemons\n\t\tself.items = items\n\t\tself.money = money\n\n\tdef give_pokemon_exp(self, amount, silent=False):\n\t\tfor pokemon in self.pokemons:\n\t\t\tpokemon.give_exp(amount, silent=silent)\n\n\tdef exp_sum(self):\n\t\ttotal = 0\n\t\tfor pokemon in self.pokemons:\n\t\t\ttotal += pokemon.exp\n\t\treturn int(total)\n\n\tdef display_info(self):\n\t\tprint(f\"{self.name} Ƀ{self.money:.2f}\")\n\t\tself.display_items()\n\t\tself.display_pokemon()\n\n\tdef display_items(self):\n\t\tprint(f\"{self.name}'s pouch: \")\n\t\tif self.items:\n\t\t\tfor item, amount in self.items.items():\n\t\t\t\tif amount > 0:\n\t\t\t\t\tprint(f\"\\t {amount}x {item.title()}\")\n\t\telse:\n\t\t\tprint(\"empty\")\n\n\tdef display_pokemon(self):\n\t\tif self.pokemons:\n\t\t\tprint(f\"{self.name}'s pokemon: \")\n\t\t\tfor pokemon in self.pokemons:\n\t\t\t\tpokemon.display_info()\n\t\telse:\n\t\t\tprint(\"empty\")\n\n\tdef get_alive_pokemon(self):\n\t\talive_pokemon = 0\n\t\tfor pokemon in self.pokemons:\n\t\t\tif pokemon.hp > 0:\n\t\t\t\talive_pokemon += 1\n\t\treturn alive_pokemon\n\n\tdef switch_pokemon(self, pokemon):\n\t\ttemp = self.pokemons[0]\n\n\t\t\n\t\tfor i in range(len(self.pokemons)):\n\t\t\tif self.pokemons[i] is pokemon:\n\t\t\t\tself.pokemons[i] = temp\n\n\t\tself.pokemons[0] = pokemon\n","repo_name":"mihirmm/keymon","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"6259106539","text":"class SmartContract:\n\n # ohne Konstruktor bzw. OHNE Eigenschaften\n # NUR mit Methode, um \"intelligenten\" Vertrag einzusetzen bzw. anzuwenden\n # an offene Transaktionen bevor diese in den Mempool abgelegt werden\n # in Rücksprache mit vorrherigen Transaktionen der Blockchain\n\n def apply(self, current_transaction, blocks):\n\n print(\"apply!\")\n\n for block in blocks: # jeden Block der Blockchain durchlaufen\n\n for transaction in block.transactions: # jede einzelne Transaktion eines jew. Blocks\n\n # Check ob die Führerschein-ID bereits vorhanden in vorherigen Transaktionen\n if current_transaction.driving_license_id == transaction.driving_license_id:\n\n print(\"driving_license_id bereits bekannt\")\n\n # Anzahl der Verstöße wird um 1 erhöht\n current_transaction.number_of_violations += 1\n\n # weiterer Check, ob Füherschein entzogen werden soll\n # hier: mehr 1 Verstoß: Füherschein weg!\n if current_transaction.number_of_violations > 1:\n\n current_transaction.is_driver_license_suspended = True\n print(\"Füherschein entzogen\")\n\n \"\"\"\n a)\n transaktion(zu schnell, 24.Mai, 5645645475475)\n b) SmartContract ausgeführt BEVOR Transaktion in den Mempool\n\n # Mempool\n transaktionen.append(transaktion)\n c)\n\n Block(transaktionen)\n \"\"\"\n","repo_name":"federerkristijan/py_mi","sub_path":"blockchain/Tag_05/smart_contract_flensburg.py","file_name":"smart_contract_flensburg.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"10909514128","text":"#!/usr/bin/env python\n# coding=utf-8\n'''\nAuthor: JiangJi\nEmail: johnjim0816@gmail.com\nDate: 2023-03-10 23:35:32\nLastEditor: JiangJi\nLastEditTime: 2023-03-11 00:13:55\nDiscription: \n'''\nfrom collections import defaultdict\nimport numpy as np\nimport math\nimport torch\n\nclass Agent(object):\n def __init__(self,cfg):\n self.n_actions = cfg.n_actions \n self.lr = cfg.lr \n self.gamma = cfg.gamma \n self.epsilon = cfg.epsilon_start\n self.epsilon_start = cfg.epsilon_start\n self.epsilon_end = cfg.epsilon_end\n self.epsilon_decay = cfg.epsilon_decay\n self.Q_table = defaultdict(lambda: np.zeros(self.n_actions)) # Q table\n self.sample_count = 0 \n def sample_action(self, state):\n ''' another way to represent e-greedy policy\n '''\n self.sample_count += 1\n self.epsilon = self.epsilon_end + (self.epsilon_start - self.epsilon_end) * \\\n math.exp(-1. * self.sample_count / self.epsilon_decay) # The probability to select a random action, is is log decayed\n if np.random.uniform(0, 1) > self.epsilon:\n action = np.argmax(self.Q_table[str(state)]) # choose action corresponding to the maximum q value\n else:\n action = np.random.choice(self.n_actions) # choose action randomly\n return action\n def predict_action(self,state):\n ''' predict action while testing \n '''\n action = np.argmax(self.Q_table[str(state)])\n return action\n def update(self, state, action, reward, next_state, next_action, done):\n Q_predict = self.Q_table[str(state)][action]\n if done:\n Q_target = reward # terminal state\n else:\n Q_target = reward + self.gamma * self.Q_table[str(next_state)][next_action] # the only difference from Q learning\n self.Q_table[str(state)][action] += self.lr * (Q_target - Q_predict) \n def save_model(self,fpath):\n import dill\n from pathlib import Path\n # create path\n Path(fpath).mkdir(parents=True, exist_ok=True)\n torch.save(\n obj=self.Q_table,\n f=f\"{fpath}/checkpoint.pkl\",\n pickle_module=dill\n )\n def load_model(self, fpath):\n import dill\n self.Q_table=torch.load(f=f\"{fpath}/checkpoint.pkl\",pickle_module=dill)","repo_name":"curryliu30/joyrl-offline","sub_path":"algos/Sarsa/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"47"} +{"seq_id":"14006285162","text":"import time,math\nt0=time.time()\nStr=str(math.factorial(100))\ndigits=[int(x) for x in Str]\nS=0\nfor x in digits:\n S=S+x\nprint(S)\nprint(time.time()-t0)\n\n","repo_name":"prudhvirajboddu/IDE_VScode_projects","sub_path":"PycharmProjects/Samples/nth Prime.py","file_name":"nth Prime.py","file_ext":"py","file_size_in_byte":153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"29072176153","text":"# Utwórz dowolną tablicę n x n zawierającą dowolny znak, a następnie wyświetl jej elementy\n# w formie tabeli n x n. Elementy powinny być oddzielone spacją\n# wejście:\n# n = 3\n# tab = [['-', '-', '-']\n# ['-', '-', '-'],\n# ['-', '-', '-']]\n# wyjście:\n# - - -\n# - - -\n# - - -\n\nn = int(input('Podaj liczbę od 1 do 10 ->'))\ntab = [['_'] * n] * n\n\nfor row in tab:\n for i in row:\n print(i, end=' ')\n print()\n","repo_name":"Adam-Kolowrocki/PythonCourse2022","sub_path":"04_Kolekcje/Zad_all_03.py","file_name":"Zad_all_03.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"19002440998","text":"# mathatic one-liner\n\n\nclass Solution(object):\n def escapeGhosts(self, ghosts, target):\n \"\"\"\n :type ghosts: List[List[int]]\n :type target: List[int]\n :rtype: bool\n \"\"\"\n return all(\n [\n abs(target[0]) + abs(target[1])\n < abs(g[0] - target[0]) + abs(g[1] - target[1])\n for g in ghosts\n ]\n )\n","repo_name":"devilhtc/leetcode-solutions","sub_path":"0x0315_789.Escape_The_Ghosts/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"19930254127","text":"import re\nfrom lxml import etree\nfrom typing import Dict\nfrom xextract.parsers import ParsingError\nfrom xextract import Element, Group, Prefix, String, Url\n\n\nclass TooManyRequestsError(Exception):\n \"\"\"Too many requests\"\"\"\n\n\nclass BaseParser:\n THROTTLE_PATTERN = re.compile(r\"Too?.+?many.+?requests\", flags=re.IGNORECASE)\n\n def __init__(self, html):\n self.html = html\n\n def _strip(self, string: str):\n \"\"\"Strips excess spaces & converts newlines to spaces\"\"\"\n return re.sub(r\"\\s{2,}\", \" \", re.sub(r\"\\r?\\n\", \" \", string.strip()))\n\n def _parse_errors(self) -> None:\n \"\"\"Throws if page content indicates a know error state\"\"\"\n if self.THROTTLE_PATTERN.search(self.html):\n raise TooManyRequestsError\n\n\nclass TitleSearchResultsParser(BaseParser):\n def __init__(self, html: str = \"\"):\n super().__init__(html)\n self._sections = Prefix(\n css=\".search-result\",\n children=[\n Element(name=\"exact\", css=\".exact + ul\", callback=self._outerhtml),\n Element(name=\"close\", css=\".close + ul\", callback=self._outerhtml),\n Element(name=\"popular\", css=\".popular + ul\", callback=self._outerhtml,),\n ],\n )\n self._movies = Group(\n quant=\"*\",\n css=\"li\",\n children=[\n Url(name=\"url\", css=\".title a\", quant=1),\n String(name=\"title\", css=\".title a\", quant=1, callback=self._strip),\n ],\n )\n\n def _outerhtml(self, etree_node):\n \"\"\"Returns outer html for an HTML node\"\"\"\n return etree.tostring(etree_node).decode()\n\n def parse(self, base_url: str = None) -> Dict:\n self._parse_errors()\n sections = {}\n for key, section in self._sections.parse(self.html).items():\n if section:\n sections[key] = []\n for movie in self._movies.parse(section[0], url=base_url):\n sections[key].append(movie)\n return sections\n\n\nclass TitlePageParser(BaseParser):\n def __init__(self, html: str = \"\"):\n super().__init__(html)\n self._empty = String(quant=\"?\", css=\".subtitles.byFilm tbody tr td.empty\")\n self._rows = Group(\n quant=\"+\",\n css=\".subtitles.byFilm tbody td.a1\",\n children=[\n Url(name=\"url\", css=\"a\", quant=1),\n String(\n name=\"name\", css=\"span:last-child\", quant=1, callback=self._strip,\n ),\n String(\n name=\"rating\",\n css=\"span:first-child\",\n attr=\"class\",\n quant=1,\n callback=self._parse_rating,\n ),\n ],\n )\n\n def _parse_rating(self, rating_class: str) -> str:\n \"\"\"Extract rating from icon class name\"\"\"\n pattern = re.compile(r\".*?(positive|neutral|bad)-icon\", flags=re.IGNORECASE)\n if not pattern.match(rating_class):\n raise ParsingError\n return pattern.sub(r\"\\1\", rating_class)\n\n def parse(self, base_url: str = None) -> Dict:\n self._parse_errors()\n if self._empty.parse(self.html):\n return []\n return self._rows.parse(self.html, url=base_url)\n\n\nclass SubtitlePageParser(BaseParser):\n def __init__(self, html: str = \"\"):\n super().__init__(html)\n self._download = Url(quant=\"1\", css=\".download a\")\n\n def parse(self, base_url: str = None) -> Dict:\n self._parse_errors()\n return self._download.parse(self.html, url=base_url)\n","repo_name":"sa3dany/subscene-dl","sub_path":"subscene/htmlparse.py","file_name":"htmlparse.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"23295605672","text":"\"\"\"\r\n用来隔250帧选择一张图片\r\n\"\"\"\r\n\r\nimport os\r\nimport shutil\r\n\r\nimport cv2\r\n\r\ncurr_dir=os.getcwd()\r\ndir_name=\"NAVER1784_ch3_20190830080000_20190830090000\"\r\nimages_path = curr_dir+'/{}/allframes/'.format(dir_name)\r\nimages_list = os.listdir(images_path)\r\nimages_list.sort(key=lambda x: int(x.split(\"-\")[-1].split(\".\")[0]))\r\n\r\ni=0\r\nfor img in images_list:\r\n print(img)\r\n img_index=int(img.split(\"-\")[-1].split(\".\")[0])\r\n savedpath = curr_dir+'/{}/VOCdevkit/VOC2007/JPEGImages/'.format(dir_name)\r\n if not os.path.exists(savedpath):\r\n os.makedirs(savedpath)\r\n # 生成VOC文件夹系统\r\n VOC_dir1=curr_dir + '/{}/VOCdevkit/VOC2007/Annotations/'.format(dir_name)\r\n VOC_dir2=curr_dir + '/{}/VOCdevkit/VOC2007/ImageSets/Main/'.format(dir_name)\r\n VOC_dir3=curr_dir + '/{}/VOCdevkit/VOC2007/labels/'.format(dir_name)\r\n if not os.path.exists(VOC_dir1):\r\n os.makedirs(VOC_dir1)\r\n if not os.path.exists(VOC_dir2):\r\n os.makedirs(VOC_dir2)\r\n if not os.path.exists(VOC_dir3):\r\n os.makedirs(VOC_dir3)\r\n shutil.copy(\"./bak/voc_label.py\", \"./{}/voc_label.py\".format(dir_name))\r\n\r\n if img_index % 250 == 0:\r\n print(img_index)\r\n frame=cv2.imread(images_path+img)\r\n cv2.imwrite(savedpath+img, frame)\r\n","repo_name":"cszr-liuxiaobo/VisualAnalyticsPlatform","sub_path":"dataprocessing/video_process/frames_ori/some_operations.py","file_name":"some_operations.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"ar","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"27142542399","text":"# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\n@author: Nicolás Nieto - nnieto@sinc.unl.edu.ar\r\n\r\nPlot power difference between two clases or conditions.\r\n\"\"\"\r\n# In[] Imports modules\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nfrom Utilitys import Ensure_dir\r\nfrom Data_extractions import Extract_TFR\r\n\r\n# In[] Imports modules\r\n\r\nroot_spectrograms = \"/media/nnieto/50e793fa-4717-4997-b590-b4167be63ee7/home/nnieto/Escritorio/Nico/Doctorado/Tesis/LIAA - sinc(i)/Toma de datos/Analisis/Espectrales/Dataset final/Spectograms/\"\r\nsave_dir='/media/nnieto/50e793fa-4717-4997-b590-b4167be63ee7/home/nnieto/Escritorio/Nico/Doctorado/Tesis/LIAA - sinc(i)/Toma de datos/Analisis/Espectrales/Dataset final/TopoPSD_diferencia/PSD_Topomaps/'\r\n\r\n\r\nTRF_method= \"Morlet\" # \"Multitaper - \"Morlet\"\r\n# Cue are present at t=0\r\ntmin = 1\r\ntmax = 3\r\nTRF_type = \"power\"\r\n# Baseline options\r\nbaseline_bool= False\r\nbaseline = [3,4]\r\n\r\n# Normalized\r\nnormalized_bool = False\r\n\r\n# Plot Options\r\noutlines = \"head\" # \"head\" - \"skirt\"\r\nsensors = True\r\nsphere = None\r\n\r\n# Saving \r\nsave_bool = True\r\n# Prefix for saving\r\nprefix=\"TRF_differences_Topomaps\"\r\n\r\n# Comparation 1\r\nCondition_1= \"Vis\"\r\nClass_1 = \"All\"\r\n\r\n# Comparation 2\r\nCondition_2= \"Pron\"\r\nClass_2 = \"All\"\r\n\r\n# Bands\r\nbands = [(0.5, 4, 'Delta (0.5-4 Hz)'), (4, 8, 'Theta (4-8 Hz)'), (8, 12, 'Alpha (8-12 Hz)'),\r\n (12, 30, 'Beta (12-30 Hz)'), (30, 45, 'Low Gamma (30-45Hz)'), (55, 100, 'High Gamma (55-100 Hz)')]\r\n\r\n\r\n\r\n# In[] Load Data\r\n\r\n# Load Class and condition\r\npower_1 = Extract_TFR(TRF_dir = root_spectrograms, Cond = Condition_1, Class = Class_1, TFR_method = TRF_method, TRF_type = TRF_type)\r\n\r\n# Load Class and Condition\r\npower_2 = Extract_TFR(TRF_dir = root_spectrograms, Cond = Condition_2, Class = Class_2, TFR_method = TRF_method, TRF_type = TRF_type)\r\n\r\n\r\n# Create a new Power where the diference will be stored\r\npower_dif=power_1.copy()\r\nif baseline_bool:\r\n power_1.apply_baseline(baseline)\r\n power_2.apply_baseline(baseline)\r\n\r\n\r\nif normalized_bool:\r\n power_dif._data = (power_1._data - power_2._data) / np.maximum(power_1._data, power_2._data)\r\n # Plot limit per band - [min_lim, max_lim]\r\n vlim= [(-1, 1),(-1, 1),(-1, 1),(-1, 1),(-1, 1),(-1, 1)]\r\n\r\nelse: \r\n power_dif._data = power_1._data - power_2._data\r\n # Plot limit per band - [min_lim, max_lim]\r\n vlim= [(-7.5e-9, 7.5e-9),(-9e-10, 9e-10),(-3e-10, 3e-10),(-9e-11, 9e-11),(-1.2e-10, 1.2e-10),(-1.2e-10, 1.2e-10)]\r\n\r\n\r\n# In[]: Plotting\r\nfontsize=20\r\nplt.rcParams.update({'font.size': fontsize})\r\nplt.rcParams.update({'legend.framealpha':0})\r\n\r\n\r\nfor band in range (len(bands)):\r\n bands_loop = bands[band]\r\n vlim_loop = vlim[band]\r\n fig = plt.figure(figsize=(20,10))\r\n ax = fig.add_axes([0.1,0.1,0.8,0.8])\r\n \r\n power_dif.plot_topomap(fmin=bands_loop[0], fmax=bands_loop[1], tmin=tmin, tmax=tmax,\r\n title=bands_loop[2], show=False, axes=ax, vmin=vlim_loop[0], vmax=vlim_loop[1],\r\n outlines=outlines, sensors=sensors, sphere=sphere, unit = \"Power difference\")\r\n \r\n if save_bool:\r\n Ensure_dir(save_dir) \r\n \r\n if baseline_bool:\r\n fig.savefig(save_dir + prefix+'_'+Condition_1+'_'+Class_1+'_vs_'+Condition_2+'_'+Class_2+'_band'+str(band)+'_Baseline.png',\r\n transparent = True , pad_inches= 0.5) \r\n\r\n else :\r\n fig.savefig(save_dir + prefix+'_'+Condition_1+'_'+Class_1+'_vs_'+Condition_2+'_'+Class_2+'_band'+str(band)+'_NO_Baseline.png',\r\n transparent = True) \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"N-Nieto/Inner_Speech_Dataset","sub_path":"Python_Processing/Plotting/Plot_TRF_differences.py","file_name":"Plot_TRF_differences.py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"47"} +{"seq_id":"38251935592","text":"from django.shortcuts import render, redirect\nfrom django.http import JsonResponse, HttpResponse\nfrom .models import *\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.auth import authenticate, login, logout\nfrom .form import creatUser\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models import Q\n\n\n# Create your views here.\n\n\ndef home(request):\n return render(request, 'base/home.html', {})\n\n\ndef session_register(request):\n if request.user.is_authenticated:\n return redirect('market')\n\n form = creatUser()\n if request.method == 'POST':\n form = creatUser(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return JsonResponse('hecho', safe=False)\n else:\n return JsonResponse({'status' : False}, safe=False)\n context = {'session' : True, 'form' : form}\n return render(request, 'base/login_register.html', context)\n\n\ndef session_login(request):\n if request.method == 'GET':\n username = request.GET.get('email')\n password = request.GET.get('password')\n\n try:\n user = authenticate(request, username = username, password = password)\n login(request, user)\n return JsonResponse({'status' : True}, safe=False)\n except:\n return JsonResponse({'status' : False, 'message' : 'usuario o contraseña incorrectos'}, safe=False)\n\n \ndef session_logOut(request):\n logout(request)\n return redirect('session')\n\n\ndef market(request): \n q = request.GET.get('q') if request.GET.get('q') != None else ''\n\n products = Product.objects.filter(category__name__icontains = q)\n categories = Category.objects.all()\n if request.user.is_authenticated:\n order , created = Order.objects.get_or_create(client = request.user, complete = False)\n else:\n order = {}\n\n return render(request, 'base/market.html', {'products' : products, 'order' : order, 'categories' : categories})\n\n\ndef addItemsCard(request):\n print(request.method)\n try:\n id = request.POST.get('id')\n type = request.POST.get('type')\n product = Product.objects.get(id = id)\n order , created = Order.objects.get_or_create(client = request.user, complete = False)\n orderItems, created = OrderItems.objects.get_or_create(order = order, product = product)\n\n if type == 'plus':\n orderItems.quantify += 1\n orderItems.save()\n else:\n if orderItems.quantify <= 1:\n orderItems.delete()\n else:\n orderItems.quantify -= 1\n orderItems.save()\n return JsonResponse({'status': True}, safe=False)\n except:\n return JsonResponse({'status': False}, safe=False)\n\n\ndef card(request):\n if request.user.is_authenticated:\n order , created = Order.objects.get_or_create(client = request.user, complete = False)\n itemsOrder = order.orderitems_set.all()\n else:\n order = {}\n itemsOrder = {}\n return render(request, 'base/card.html', {'itemsOrder' : itemsOrder, 'order' : order})\n\n\n@login_required(login_url='session')\ndef checkOut(request):\n if request.method == 'POST':\n name = request.POST.get('name')\n email = request.POST.get('email')\n address = request.POST.get('address')\n city = request.POST.get('city')\n barrio = request.POST.get('barrio')\n zip = request.POST.get('zip')\n order , created = Order.objects.get_or_create(client = request.user, complete = False)\n order.complete = True\n order.save()\n ClientAddres.objects.create(\n client = request.user,\n order = order,\n address = address,\n city = city,\n zipcode = zip,\n )\n return JsonResponse('ordern realizada', safe=False)\n return render(request, 'base/check-out.html', {})","repo_name":"facuCogliati/Ecommerce-Mandalorian","sub_path":"base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"72902995983","text":"from EMAN2 import PDBReader, EMData\nfrom .emapplication import EMApp, get_application\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom .emimage3d import EMImage3DWidget\nfrom .emimage3diso import EMIsosurfaceModel\nfrom .empdbviewer import *\nfrom .emselector import EMSelectorDialog\n\n\nclass EMPDBValWidget(QtWidgets.QWidget):\n\t'''\n\tEMPDB versus isosurface visual evaluation\n\t'''\n\trun_validate = QtCore.pyqtSignal(str, str, int, float)\n\n\tdef __init__(self):\n\t\tQtWidgets.QWidget.__init__(self)\n\n\t\tself.pdb_model = None # will eventually be a EMPDBModel\n\t\tself.iso_model = None # will eventually be a EMIsosurfaceModel\n\t\tself.viewer_window = EMImage3DWidget()\n\t\tself.__init_gui()\n\n\t\tself.validate_button.clicked.connect(self.run_validate)\n\t\tself.pdb_browse_button.clicked.connect(self.browse_pdb)\n\t\tself.pdb_line_edit.textChanged.connect(self.update_pdb_file)\n\t\tself.volume_browse_button.clicked.connect(self.browse_iso)\n\t\tself.volume_line_edit.textChanged.connect(self.update_iso_file)\n\t\t\n\t\tget_application().attach_child(self)\n\t\t\n\tdef __init_gui(self):\n\t\tself.data_groupbox = QtWidgets.QGroupBox(self.tr(\"Data\"))\n\t\t\n\t\tpdb_label = QtWidgets.QLabel(\"PDB:\")\n\t\tself.pdb_line_edit = QtWidgets.QLineEdit()\n\t\tself.pdb_browse_button = QtWidgets.QPushButton(self.tr(\"Browse\"))\n\t\tpdb_layout = QtWidgets.QHBoxLayout()\n\t\tpdb_layout.addWidget(pdb_label)\n\t\tpdb_layout.addWidget(self.pdb_line_edit)\n\t\tpdb_layout.addWidget(self.pdb_browse_button)\t\t\n\t\t\n\t\tvolume_label = QtWidgets.QLabel(\"Volume:\")\n\t\tself.volume_line_edit = QtWidgets.QLineEdit()\n\t\tself.volume_browse_button = QtWidgets.QPushButton(self.tr(\"Browse\"))\n\t\tvolume_layout = QtWidgets.QHBoxLayout()\n\t\tvolume_layout.addWidget(volume_label)\n\t\tvolume_layout.addWidget(self.volume_line_edit)\n\t\tvolume_layout.addWidget(self.volume_browse_button)\n\t\t\n\t\tdata_layout = QtWidgets.QVBoxLayout()\n\t\tdata_layout.addLayout(pdb_layout)\n\t\tdata_layout.addLayout(volume_layout)\n\t\t\n\t\tself.data_groupbox.setLayout(data_layout)\n\n\t\t\n\t\tself.validation_groupbox = QtWidgets.QGroupBox(self.tr(\"Validation\"))\n\t\t\n\t\ttransformations_label = QtWidgets.QLabel(self.tr(\"&Number of Transformations\"))\n\t\tself.transformations_spinbox = QtWidgets.QSpinBox()\n\t\tself.transformations_spinbox.setMaximum(9999)\n\t\tself.transformations_spinbox.setValue(20)\n\t\ttransformations_label.setBuddy(self.transformations_spinbox)\n\t\ttransformations_layout = QtWidgets.QHBoxLayout()\n\t\ttransformations_layout.addWidget(transformations_label)\n\t\ttransformations_layout.addWidget(self.transformations_spinbox)\n\t\t\n\t\tthreshold_label = QtWidgets.QLabel(self.tr(\"Isosurface &Threshold\"))\n\t\tself.threshold_doublespinbox = QtWidgets.QDoubleSpinBox()\n\t\tself.threshold_doublespinbox.setValue(0.1)\n\t\tthreshold_label.setBuddy(self.threshold_doublespinbox)\n\t\tthreshold_layout = QtWidgets.QHBoxLayout()\n\t\tthreshold_layout.addWidget(threshold_label)\n\t\tthreshold_layout.addWidget(self.threshold_doublespinbox)\n\t\t\n\t\tself.validate_button = QtWidgets.QPushButton(self.tr(\"&Validate\"))\n\t\t\n\t\tvalidation_layout = QtWidgets.QVBoxLayout()\n\t\tvalidation_layout.addLayout(transformations_layout)\n\t\tvalidation_layout.addLayout(threshold_layout)\n\t\tvalidation_layout.addWidget(self.validate_button)\n\t\tself.validation_groupbox.setLayout(validation_layout)\n\t\t\n\t\tlayout = QtWidgets.QVBoxLayout()\n\t\tlayout.addWidget(self.data_groupbox)\n\t\tlayout.addWidget(self.validation_groupbox)\n\t\t\n\t\tself.setLayout(layout)\n\n\tdef __init_iso_model(self):\n\t\tif self.iso_model == None:\n\t\t\tself.viewer_window.add_isosurface()\n\t\t\tself.iso_model = self.viewer_window.viewables[-1]\n\t\t\t#self.iso_model = EMIsosurfaceModel(self.viewer_window, None, enable_file_browse=False)\n\t\t\t#self.viewer_window.add_model(self.iso_model)\n\t\t\t#self.viewer_window.get_inspector().update_selection()\n\t\t\t#self.__set_model_contexts(self.iso_model)\n\n\tdef __init_pdb_model(self):\n\t\tif self.pdb_model == None:\n\t\t\tself.pdb_model = EMPDBModel(self.viewer_window)\n\t\t\tself.viewer_window.add_model(self.pdb_model)\n\t\t\tself.__set_model_contexts(self.pdb_model)\n\n\tdef __set_model_contexts(self,model):\n\t\tmodel.set_gl_widget(self.viewer_window)\n\t\tmodel.set_dont_delete_parent() # stops a RunTimeError\n\t\n\tdef browse_iso(self):\n\t\tem_selector = EMSelectorDialog()\n\t\tfile_path = em_selector.exec_()\n\t\tget_application().detach_child(em_selector)\n\t\tself.volume_line_edit.setText(file_path)\n\t\t\n\tdef browse_pdb(self):\n\t\tfile_path = QtWidgets.QFileDialog.getOpenFileName(filter=\"Protein Data Bank (*.pdb)\")[0]\n\t\tself.pdb_line_edit.setText(file_path)\n\t\t\n\tdef closeEvent(self, event):\n\t\tself.viewer_window.close()\n\t\tQtWidgets.QWidget.closeEvent(self, event)\n\t\t\n\tdef draw_objects(self):\n\t\tif self.iso_model == None: \n\t\t\tself. __init_iso_model()\n\t\tif self.pdb_model == None:\n\t\t\tself.__init_pdb_model()\n\t\tif self.pdb_model != None:\n\t\t\tglPushMatrix()\n\t\t\tself.pdb_model.draw_objects()\n\t\t\tglPopMatrix()\n\t\tif self.iso_model != None:\n\t\t\tglPushMatrix()\n\t\t\tself.iso_model.render()\n\t\t\tglPopMatrix()\n\n\tdef run_validate(self): \n\t\tnum_transformations = self.transformations_spinbox.value()\n\t\tthreshold = self.threshold_doublespinbox.value()\n\t\tcurrent_pdb = str(self.pdb_line_edit.text())\n\t\tcurrent_mrc = str(self.volume_line_edit.text())\n\n\t\tself.run_validate.emit(current_mrc, current_pdb, num_transformations, threshold)\n\t\t\n\tdef update_iso_file(self):\n\t\tiso_file_path = str(self.volume_line_edit.text())\n\t\tdata = EMData(iso_file_path)\n\t\tself.viewer_window.set_data(data, iso_file_path)\n\t\tself.iso_model = self.viewer_window.viewables[0]\n#\t\tif self.iso_model == None: \n#\t\t\tself. __init_iso_model()\n#\t\tself.iso_model.set_data(data)\n\t\tself.viewer_window.updateGL()\n\t\t\n#\t\tself.iso_model.get_inspector().mrc_text.setText(file_name) #Use self.iso_model.data[\"source_path\"] instead\n\n\tdef update_pdb_file(self):\n\t\tpdb_file = str(self.pdb_line_edit.text())\n\t\tif self.pdb_model == None:\n\t\t\tself.__init_pdb_model()\n\t\tself.pdb_model.set_current_text(pdb_file) #updates GL with the new pdb file\n\n\ndef main():\n\tem_app = EMApp()\n\tpdb_widget = EMPDBValWidget()\n\n\tpdb_widget.volume_line_edit.setText(\"rdv-target2.mrc\")\n\tpdb_widget.pdb_line_edit.setText(\"fh-solution-0-1UF2-T.pdb\")\n\t\n\tem_app.show()\n\tem_app.execute()\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"cryoem/eman2","sub_path":"libpyEM/qtgui/empdbvaltool.py","file_name":"empdbvaltool.py","file_ext":"py","file_size_in_byte":6103,"program_lang":"python","lang":"en","doc_type":"code","stars":127,"dataset":"github-code","pt":"47"} +{"seq_id":"40871027249","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef identify_patterns_and_anomalies(dataset):\n # Load dataset\n df = pd.read_csv(dataset)\n \n # Perform advanced logic and reasoning on the dataset\n \n # Identify patterns\n patterns = df.describe()\n \n # Identify anomalies\n anomalies = df[df['column_name'] > threshold]\n \n # Generate markdown report\n report = f\"# Dataset Analysis\\n\\n\"\n \n # Summary of patterns\n report += \"## Patterns\\n\\n\"\n report += \"### Summary Statistics\\n\\n\"\n report += patterns.to_markdown() + \"\\n\\n\"\n \n # Visualizations of patterns\n report += \"### Visualizations\\n\\n\"\n for column in df.columns:\n plt.figure(figsize=(10, 6))\n sns.histplot(df[column], kde=True)\n plt.title(f\"Distribution of {column}\")\n plt.xlabel(column)\n plt.ylabel(\"Count\")\n plt.savefig(f\"{column}_distribution.png\")\n plt.close()\n report += f\"#### {column} Distribution\\n\\n\"\n report += f\"![{column} Distribution](./{column}_distribution.png)\\n\\n\"\n \n # Summary of anomalies\n report += \"## Anomalies\\n\\n\"\n report += f\"Number of anomalies: {len(anomalies)}\\n\\n\"\n report += anomalies.to_markdown() + \"\\n\\n\"\n \n return report\n","repo_name":"KOSASIH/HyperLogic-Sentinel","sub_path":"identify_patterns_and_anomalies.py","file_name":"identify_patterns_and_anomalies.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"74047843023","text":"import time\nimport winsound\nimport plyer\n\n\nmessage = \"You need to drink water please\"\ntitle = 'Drinking water reminder'\nsound = (500,1000)\n\n\ntry:\n interval = float(input(\"Enter the interval in seconds: \"))\nexcept ValueError:\n print(\"Invalid input. Please enter a number.\")\n exit()\n \n# Import the datetime module\nimport datetime\n\n# Get the current date and time\nnow = datetime.datetime.now()\n\n# Format the date and time\ndate = now.strftime(\"%d/%m/%Y\")\ntime2 = now.strftime(\"%H:%M:%S\")\n\n# Print the date and time\nprint(f\"Today is {date} and the time is {time2}.\")\n\n\n\nwhile True:\n time.sleep(interval)\n winsound.Beep(*sound)\n plyer.notification.notify(title = title,message = message)","repo_name":"rafi671/Python-projects-GITHUB-repository","sub_path":"drinking_water_reminder.py","file_name":"drinking_water_reminder.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"29503964124","text":"from itertools import chain\n\nfrom django.shortcuts import render\nfrom django.db.models import Count\nfrom django.db.models import F\n\nfrom rest_framework.viewsets import ModelViewSet\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly\n\nfrom file_manager.models import Answer, Asset, Chapter, Contributor, Collection, CountryTag, LearnerJourney, Question, Tag, TagGroup\nfrom . import serializers\n\n# Create your views here.\nclass AnswerViewSet(ModelViewSet):\n serializer_class = serializers.AnswerSerializer\n queryset = Answer.objects.all()\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\nclass AnswerPerCollectionAndQuestionViewSet(ModelViewSet):\n serializer_class = serializers.AnswerPlusFormatSerializer\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n collection_id = self.kwargs['collection_id']\n question_id = self.kwargs['question_id']\n return Answer.objects.filter(\n question=question_id).filter(\n asset__collections=collection_id).annotate(\n format=F('asset__format')).order_by('position')\n\nclass AssetViewSet(ModelViewSet):\n serializer_class = serializers.AssetSerializer\n queryset = Asset.objects.all()\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\nclass AssetPerAnswerViewSet(ModelViewSet):\n serializer_class = serializers.AssetSerializer\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n answer_id = self.kwargs['answer_id']\n asset = Answer.objects.get(id=answer_id).asset\n return [asset]\n\nclass AssetPerCollectionViewSet(ModelViewSet):\n serializer_class = serializers.AssetSerializer\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n collection_id = self.kwargs['id']\n return Asset.objects.filter(collections__id=collection_id)\n\nclass AssetPerCollectionAndLearnerJourneyViewSet(ModelViewSet):\n serializer_class = serializers.AssetSerializer\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n \"\"\"\n Returns all Assets from a given Learner Journey\n \"\"\"\n learner_journey_id = self.kwargs['learner_journey_id']\n collection_id = self.kwargs['collection_id']\n chapters = Chapter.objects.filter(\n learner_journey=learner_journey_id).filter(asset__collections=collection_id).order_by('position')\n asset_query_sets = []\n for chapter in chapters:\n asset_query_set = Asset.objects.get(id=chapter.asset.id)\n asset_query_sets.append(asset_query_set)\n\n return list(chain(asset_query_sets))\n\nclass AssetPerTagViewSet(ModelViewSet):\n serializer_class = serializers.AssetSerializer\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n tag_id = self.kwargs['id']\n return Asset.objects.filter(tags__id=tag_id)\n\nclass AssetPerCollectionAndTagViewSet(ModelViewSet):\n serializer_class = serializers.AssetSerializer\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n collection_id = self.kwargs['collection_id']\n tag_id = self.kwargs['tag_id']\n return Asset.objects.filter(collections__id=collection_id).filter(tags__id=tag_id)\n\nclass AssetPerCollectionAndTagGroupViewSet(ModelViewSet):\n serializer_class = serializers.AssetSerializer\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n collection_id = self.kwargs['collection_id']\n tag_group_id = self.kwargs['tag_group_id']\n\n tags = Tag.objects.filter(group=tag_group_id)\n return Asset.objects.filter(collections__id=collection_id).filter(tags__in=tags).distinct()\n\nclass AssetPerCollectionAndLocationViewSet(ModelViewSet):\n serializer_class = serializers.AssetSerializer\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n collection_id = self.kwargs['collection_id']\n location_id = self.kwargs['location_id']\n return Asset.objects.filter(collections__id=collection_id).filter(locations__id=location_id)\n\nclass ChapterViewSet(ModelViewSet):\n serializer_class = serializers.ChapterSerializer\n queryset = Chapter.objects.all()\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n# class ChapterPlusAssetViewSet(ModelViewSet):\n# serializer_class = serializers.ChapterSerializer\n# permission_classes = (IsAuthenticatedOrReadOnly,)\n#\n# def get_queryset(self):\n# collection_id = self.kwargs['collection_id']\n# learner_journey_id = self.kwargs['learner_journey_id']\n# chapter_num = int(self.kwargs['chapter_num'])\n# chapters = Chapter.objects.filter(learner_journey=learner_journey_id).filter(asset__collections=collection_id).order_by('position')\n# return [chapters[chapter_num -1]]\n\nclass ChapterPerCollectionAndLearnerJourneyViewSet(ModelViewSet):\n serializer_class = serializers.ChapterSerializer\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n collection_id = self.kwargs['collection_id']\n learner_journey_id = self.kwargs['learner_journey_id']\n return Chapter.objects.filter(learner_journey=learner_journey_id).filter(asset__collections=collection_id).order_by('position')\n\nclass ChapterIdsPerCollectionAndLearnerJourneyViewSet(ModelViewSet):\n serializer_class = serializers.ChapterIdsSerializer\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n collection_id = self.kwargs['collection_id']\n learner_journey_id = self.kwargs['learner_journey_id']\n return Chapter.objects.filter(learner_journey=learner_journey_id).filter(asset__collections=collection_id).order_by('position')\n\nclass ContributorViewSet(ModelViewSet):\n serializer_class = serializers.ContributorSerializer\n queryset = Contributor.objects.all()\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\nclass CollectionViewSet(ModelViewSet):\n serializer_class = serializers.CollectionSerializer\n queryset = Collection.objects.all()\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\nclass CountryTagViewSet(ModelViewSet):\n serializer_class = serializers.CountryTagSerializer\n queryset = CountryTag.objects.all()\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\nclass LearnerJourneyViewSet(ModelViewSet):\n serializer_class = serializers.LearnerJourneySerializer\n queryset = LearnerJourney.objects.all()\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n return LearnerJourney.objects.annotate(parts=Count('chapter'))\n\nclass QuestionViewSet(ModelViewSet):\n serializer_class = serializers.QuestionSerializer\n queryset = Question.objects.all()\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n\nclass TagViewSet(ModelViewSet):\n serializer_class = serializers.TagSerializer\n queryset = Tag.objects.all()\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\nclass TagGroupViewSet(ModelViewSet):\n serializer_class = serializers.TagGroupSerializer\n queryset = TagGroup.objects.all()\n permission_classes = (IsAuthenticatedOrReadOnly,)\n","repo_name":"emfoundation/asset-manager","sub_path":"asset_manager/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7204,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"47"} +{"seq_id":"11521077408","text":"import requests\nimport json\nfrom collections import namedtuple\nfrom typing import List\n\nMovie = namedtuple('Movie', 'imdb_code, title, director, keywords, duration,'\n 'genres, rating, year, imdb_score')\n\n\nclass EmptyTitleException(Exception):\n pass\n\n\ndef search_by_title(title: str) -> List[Movie]:\n url = 'http://movie_service.talkpython.fm/api/search/'\n\n if not title.strip():\n raise EmptyTitleException('Title can\\'t be empty.')\n\n try:\n res = requests.get(url+title)\n res.raise_for_status()\n\n results = json.loads(res.text)\n\n return sorted(\n [Movie(**row) for row in results.get('hits')],\n key=lambda m: -m.year\n )\n except Exception as e:\n raise e from e\n","repo_name":"neironus/100DaysOfPython","sub_path":"TalkPython/python-jumpstart/10/movie_service.py","file_name":"movie_service.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"35857797932","text":"# app.py\n\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\n# Create dummy secrey key so we can use sessions\napp.config['SECRET_KEY'] = '123456790'\n\n# Create in-memory database\napp.config['DATABASE_FILE'] = 'sample_db.sqlite'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' #+ app.config['DATABASE_FILE']\napp.config['SQLALCHEMY_ECHO'] = True\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)","repo_name":"shahajinangare/pythonprojects","sub_path":"flaskcrudapp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"5729663427","text":"class Student:\n # name = 이름\n # sid = 학번\n # pos = 활동 가능 시간을 30분 단위로 자른 표\n def __init__(self, name, sid, pos):\n self.name = name\n self.sid = sid\n self.pos = pos\n\nclass Schedule:\n # equality_flag = 균등 분배 여부\n # duplication_flag = 여러번 참가 가능 여부\n # unit_time = 단위 시간\n # mini = 최소 필요 인원\n # maxi = 최대 필요 인원\n # need = 전체 시간대 (시작 분, 끝 분) 튜플의 리스트\n def __init__(self, equality_flag, duplication_flag, unit_time, mini, maxi, need):\n self.equality_flag = equality_flag\n self.duplication_flag = duplication_flag\n self.unit_time = unit_time\n self.mini = mini\n self.maxi = maxi\n self.need = need\n","repo_name":"chaejin98330/campuScheduler","sub_path":"code/Scheduling_Class.py","file_name":"Scheduling_Class.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"30212779190","text":"from jax import vmap\n\n\ndef calculate_resources(\n state_space,\n exog_savings_grid,\n income_shock_draws_unscaled,\n params,\n compute_beginning_of_period_wealth,\n):\n income_shock_draws = income_shock_draws_unscaled * params[\"sigma\"]\n resources_beginning_of_period = vmap(\n vmap(\n vmap(\n calculate_resources_for_each_grid_point,\n in_axes=(None, None, 0, None, None),\n ),\n in_axes=(None, 0, None, None, None),\n ),\n in_axes=(0, None, None, None, None),\n )(\n state_space,\n exog_savings_grid,\n income_shock_draws,\n params,\n compute_beginning_of_period_wealth,\n )\n return resources_beginning_of_period\n\n\ndef calculate_resources_for_each_grid_point(\n state_vec,\n exog_savings_grid_point,\n income_shock_draw,\n params,\n compute_beginning_of_period_wealth,\n):\n out = compute_beginning_of_period_wealth(\n **state_vec,\n savings_end_of_previous_period=exog_savings_grid_point,\n income_shock_previous_period=income_shock_draw,\n params=params,\n )\n return out\n","repo_name":"segsell/dc-egm","sub_path":"src/dcegm/budget.py","file_name":"budget.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"47"} +{"seq_id":"74996140622","text":"from django.shortcuts import get_object_or_404, redirect, render\nfrom django.http import HttpResponse\nfrom portal.models import Professor, Department, Project\n\n# Create your views here.\n\n\ndef home(request):\n\n context = {'depts':Department.objects.all()}\n return render(request, 'portal/home.html', context)\n\n\ndef about(request):\n return HttpResponse('

    About Us

    ')\n\n\ndef civilView(request):\n context = {'profs':Professor.objects.filter(deptId='CIV'), 'projects':Project.objects.all()}\n return render(request, 'portal/civ.html', context)\n\n\ndef cseView(request):\n context = {'profs':Professor.objects.filter(deptId='CS'), 'projects':Project.objects.all()}\n return render(request, 'portal/cs.html', context)\n\ndef eeeView(request):\n context = {'profs':Professor.objects.filter(deptId='EEE'), 'projects':Project.objects.all()}\n return render(request, 'portal/eee.html', context)\n\ndef mechView(request):\n context = {'profs':Professor.objects.filter(deptId='MECH'), 'projects':Project.objects.all()}\n return render(request, 'portal/mech.html', context)\n\n\ndef csapply(request, pk):\n project=get_object_or_404(Project, pk=pk)\n if project.numberOfCurrentApplicants < project.maxNumberOfApplicants:\n project.numberOfCurrentApplicants+=1\n project.save()\n return redirect('cseView')\n else:\n project.projectStatus = \"ONGOING\"\n project.save()\n return redirect('cseView')\n\ndef eeeapply(request, pk):\n project=get_object_or_404(Project, pk=pk)\n if project.numberOfCurrentApplicants < project.maxNumberOfApplicants:\n project.numberOfCurrentApplicants+=1\n project.save()\n return redirect('eeeView')\n else:\n project.projectStatus = \"ONGOING\"\n project.save()\n return redirect('eeeView')\n\ndef civapply(request, pk):\n project=get_object_or_404(Project, pk=pk)\n if project.numberOfCurrentApplicants < project.maxNumberOfApplicants:\n project.numberOfCurrentApplicants+=1\n project.save()\n return redirect('civView')\n else:\n project.projectStatus = \"ONGOING\"\n project.save()\n return redirect('civView')\n\ndef mechapply(request, pk):\n project=get_object_or_404(Project, pk=pk)\n if project.numberOfCurrentApplicants < project.maxNumberOfApplicants:\n project.numberOfCurrentApplicants+=1\n project.save()\n return redirect('mechView')\n else:\n project.projectStatus = \"ONGOING\"\n project.save()\n return redirect('mechView')\n\n\ndef projectView(request):\n projects = {'projects':Project.objects.all()}\n return render(request, 'portal/project.html', projects)\n\n\ndef ProfProjectListView(request, profId):\n projects = {'projects':Project.objects.filter(profId=profId)}\n return render(request, 'portal/profProjects.html', projects)\n","repo_name":"ssvaditya/Research-Portal","sub_path":"rpportal/portal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"47"} +{"seq_id":"36861864700","text":"import os, random\r\nimport numpy as np\r\n\r\n# change noise\r\n# clean_dir = '../coco/labels/val2017/'\r\n# noisy_dir = '../coco/labels/val2017_noise_0.4/'\r\nclean_dir = '../VOC/labels/val_voc/'\r\nnoisy_dir = '../VOC/labels/val_voc_noise2/'\r\nif not os.path.exists(noisy_dir):\r\n os.makedirs(noisy_dir)\r\n\r\nfor clean_file in os.listdir(clean_dir):\r\n with open(clean_dir + clean_file, 'r') as f:\r\n data = f.readlines()\r\n table = []\r\n for i in range(len(data)):\r\n clean_list = data[i].split(' ')\r\n num_list = []\r\n for j in range(len(clean_list)):\r\n num_list.append(float(clean_list[j]))\r\n # change noise\r\n noise = 0.2\r\n random_w1 = random.uniform(-noise*num_list[3], noise*num_list[3])\r\n random_h1 = random.uniform(-noise*num_list[4], noise*num_list[4])\r\n random_w2 = random.uniform(-noise*num_list[3], noise*num_list[3])\r\n random_h2 = random.uniform(-noise*num_list[4], noise*num_list[4])\r\n num_list[1] += random_w1\r\n num_list[2] += random_h1\r\n num_list[3] += random_w2\r\n num_list[4] += random_h2\r\n # make new bbox in the image\r\n num_list[3] = np.clip(num_list[3], 0.001, 0.999)\r\n num_list[4] = np.clip(num_list[4], 0.001, 0.999)\r\n num_list[1] = np.clip(num_list[1], 0.5*num_list[3], 1-0.5*num_list[3])\r\n num_list[2] = np.clip(num_list[2], 0.5*num_list[4], 1-0.5*num_list[4])\r\n table.append(num_list)\r\n\r\n noise_anno = open(noisy_dir + clean_file, 'a+')\r\n for number in table:\r\n box_info = \" %d %f %f %f %f\" % (\r\n number[0], number[1], number[2], number[3], number[4])\r\n noise_anno.write(box_info)\r\n noise_anno.write('\\n')\r\n noise_anno.close()\r\n","repo_name":"Jacobi93/Alpha-IoU","sub_path":"generate_noisy_labels.py","file_name":"generate_noisy_labels.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","stars":153,"dataset":"github-code","pt":"47"} +{"seq_id":"2618799627","text":"import websocket\r\nimport threading\r\nimport requests\r\nimport sqlite3\r\nimport json\r\nimport time\r\nimport os\r\nfrom config import botToken, botName, botPrefix, botPrefixActive, ownerId, testerIds\r\n\r\n\r\nclass DiscordBot:\r\n def __init__(self):\r\n self.botToken = botToken\r\n self.botName = botName\r\n self.botPrefix = botPrefix\r\n self.botPrefixActive = botPrefixActive\r\n self.ownerId = ownerId\r\n self.testerIds = testerIds\r\n\r\n def getBotSettings(self):\r\n connection = sqlite3.connect('bot.sql')\r\n cursor = connection.cursor()\r\n\r\n # Execute query to retrieve bot settings\r\n cursor.execute(\r\n 'SELECT botToken, botName, botPrefix, botPrefixActive, ownerId FROM bot_settings')\r\n result = cursor.fetchone() # Get the first row\r\n\r\n connection.close()\r\n\r\n return result\r\n\r\n def directChannelMessage(self, url, message):\r\n payload2 = {\r\n \"content\": message\r\n }\r\n\r\n header = {\r\n \"authorization\": self.botToken\r\n }\r\n\r\n r = requests.post(url=url, data=payload2, headers=header)\r\n\r\n def command(self, prompt, message, ownerOnly=0, testerOnly=0, url=\"\"):\r\n prompt = str(prompt)\r\n message = str(message)\r\n\r\n if not prompt and message:\r\n print(f\"{self.botName}: Please enter the command and its response.\")\r\n elif not prompt:\r\n print(f\"{self.botName}: Please enter the command.\")\r\n elif not message:\r\n print(f\"{self.botName}: Please enter the response.\")\r\n elif ownerOnly == 1 and testerOnly == 0:\r\n if id == self.ownerId:\r\n if content == prompt:\r\n message = message.replace(\"$userid\", f\"<@{id}>\")\r\n self.directChannelMessage(url=url, message=f\"{self.botName}: {message}\")\r\n elif testerOnly == 1 and ownerOnly == 0:\r\n if id in testerIds:\r\n if content == prompt:\r\n message = message.replace(\"$userid\", f\"<@{id}>\")\r\n self.directChannelMessage(url=url, message=f\"{self.botName}: {message}\")\r\n elif ownerOnly and testerOnly == 1:\r\n if id in testerIds or self.ownerId == id:\r\n if content == prompt:\r\n message = message.replace(\"$userid\", f\"<@{id}>\")\r\n self.directChannelMessage(url=url, message=f\"{self.botName}: {message}\")\r\n elif ownerOnly == 0 and testerOnly == 0:\r\n if content == prompt:\r\n message = message.replace(\"$userid\", f\"<@{id}>\")\r\n self.directChannelMessage(url=url, message=f\"{self.botName}: {message}\")\r\n\r\n def startTerminal(self):\r\n # Create database connection\r\n print(f\"{self.botName}: System is starting!\")\r\n time.sleep(1)\r\n os.system(\"cls\")\r\n\r\n # Sends a JSON-based request over WebSocket\r\n def sendJsonRequest(self, ws, request):\r\n ws.send(json.dumps(request))\r\n\r\n # Receives a JSON-based response over WebSocket\r\n def receiveJsonResponse(self, ws):\r\n response = ws.recv()\r\n if response:\r\n return json.loads(response)\r\n\r\n # Keeps the WebSocket connection alive by sending a \"heartbeat\" request at a specified interval\r\n def heartbeat(self, interval, ws):\r\n print(f'{self.botName}: Heartbeat started')\r\n\r\n while True:\r\n time.sleep(interval)\r\n\r\n # Create a \"heartbeat\" request as JSON\r\n heartbeatJson = {\r\n \"op\": 1,\r\n \"d\": \"null\"\r\n }\r\n\r\n # Send the \"heartbeat\" request\r\n self.sendJsonRequest(ws, heartbeatJson)\r\n print(f'{self.botName}: Heartbeat sent')\r\n\r\n def start(self):\r\n self.startTerminal()\r\n ws = websocket.WebSocket()\r\n ws.connect('wss://gateway.discord.gg/?v=6&encording=json')\r\n event = self.receiveJsonResponse(ws)\r\n\r\n heartbeat_interval = event['d']['heartbeat_interval'] / 1000\r\n threading._start_new_thread(self.heartbeat, (heartbeat_interval, ws))\r\n\r\n payload = {\r\n \"op\": 2,\r\n \"d\": {\r\n \"token\": self.botToken,\r\n \"properties\": {\r\n \"$os\": \"windows\",\r\n \"$browser\": \"edge\",\r\n \"$device\": \"pc\"\r\n }\r\n }\r\n }\r\n\r\n self.sendJsonRequest(ws, payload)\r\n\r\n while True:\r\n event = self.receiveJsonResponse(ws)\r\n\r\n try:\r\n global content\r\n global id\r\n global url\r\n global channelId\r\n global username\r\n\r\n id = int(event['d']['author']['id'])\r\n username = str(event['d']['author']['username'])\r\n channelId = event['d']['channel_id']\r\n content = str(event['d']['content'])\r\n url = f\"https://discord.com/api/v9/channels/{channelId}/messages\"\r\n\r\n if self.ownerId == id:\r\n if content == \"prefix\":\r\n if self.botPrefixActive == 0:\r\n self.botPrefixActive = 1\r\n elif self.botPrefixActive == 1:\r\n self.botPrefixActive = 0\r\n\r\n if self.botPrefixActive == 1:\r\n self.command(self.botPrefix + \" merhaba\",\r\n \"merhaba\", url=url)\r\n else:\r\n self.command(\"merhaba\", \"merhaba\", url=url)\r\n except:\r\n pass\r\n\r\n\r\nbot = DiscordBot()\r\nbot.botToken, bot.botName, bot.botPrefix, bot.botPrefixActive, bot.ownerId = bot.getBotSettings()\r\nbot.start()\r\n","repo_name":"Cyrussw/discord-bot-creator","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"47"} +{"seq_id":"74925439850","text":"import discord\nfrom discord.ext import commands, tasks\n\nclass admin_commands(commands.Cog):\n \n def __init__(self,client):\n self.client=client\n \n \n @commands.command()\n @commands.has_permissions(manage_messages=True)\n async def clear(self, ctx, amount : int):\n await ctx.channel.purge(limit=amount+1)\n\n @clear.error\n async def clear_error(self,ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n await ctx.send('Please specify an ammount of messages to delete')\n\n @commands.command()\n @commands.has_permissions(kick_members=True)\n async def kick(self,ctx, member : discord.Member, *,reason=None):\n await member.kick(reason=reason)\n await ctx.send(f'{member} has been kicked from the server')\n \n @commands.command()\n @commands.has_permissions(ban_members=True)\n async def ban(self,ctx, member : discord.Member, *,reason=None):\n await member.ban(reason=reason)\n\n @commands.command()\n @commands.has_permissions(ban_members=True)\n async def unban(self,ctx, *, member):\n banned_users = await ctx.guild.bans()\n member_name,member_discriminator =member.split('#')\n for ban_entry in banned_users:\n user=ban_entry.user\n\n if(user.name, user.discriminator) == (member_name, member_discriminator):\n await ctx.guild.unban(user)\n await ctx.send(f'Unbanned{user.mention}')\n return\n\n @commands.command()\n @commands.has_permissions(administrator=True)\n async def load(self,ctx, extention):\n client.load_extension(f'cogs.{extention}')\n\n @commands.command()\n @commands.has_permissions(administrator=True)\n async def unload(self,ctx, extention):\n client.unload_extension(f'cogs.{extention}')\n\ndef setup(client):\n client.add_cog(admin_commands(client))\n","repo_name":"nzwoodturner/order-bot","sub_path":"cogs/admin commands.py","file_name":"admin commands.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"34787783434","text":"def Merge(mergeIt, p, q, r):\n print(\"Merging\")\n n1 = q-p+1\n n2 = r-p\n leftList = mergeIt[p:n1+1]\n rightList = mergeIt[q:n2+1]\n\n leftList[n1] = 10000\n rightList[n2] = 10000\n i = 1\n j = 1\n\n for num in range(p,r):\n if leftList[i] <= rightList[j]:\n mergeIt[num] = leftList[i]\n\n i = i + 1\n else:\n mergeIt[num] = rightList[j]\n j = j + 1\n\n\n\n\n\ndef MergeSort(listToSort, p, r):\n print(\"Inside MergeSort\")\n if p < r:\n q = int((r - p) / 2)\n print(q)\n print(listToSort)\n MergeSort(listToSort, p, q)\n MergeSort(listToSort, q+1, r)\n Merge(listToSort, p, q, r)\n\nlistToSort = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\nr = len(listToSort)\nprint(\"size of the list: \",r)\np = 0\nMergeSort(listToSort, p, r)\n","repo_name":"Almazi/Intro_To_Algorithm_Practice_Codes","sub_path":"_2_2_Merge_Sort.py","file_name":"_2_2_Merge_Sort.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"18630406032","text":"import sys\nsys.setrecursionlimit(100000)\n\ndx = [0, 0, -1, 1]\ndy = [1, -1, 0, 0]\n\ndef DFS(x,y):\n # 방문처리\n visited[x][y] = 1\n for direction in range(4):\n nx = x + dx[direction]\n ny = y + dy[direction]\n\n # 범위안에 들어오고 방문안했으면 방문\n if 0 <= nx < N and 0 <= ny < M and graph[nx][ny] == 1 and visited[nx][ny] == 0:\n DFS(nx,ny)\n\nT = int(input())\n\nfor tc in range(T):\n # M은 가로길이, N은 세로길이, K는 배추개수\n M, N, K = map(int, input().split())\n\n graph = [[0] * M for _ in range(N)]\n visited = [[0] * M for _ in range(N)]\n\n for k in range(K):\n # a가 가로 b가 세로임\n a, b = map(int, input().split())\n graph[b][a] = 1\n\n cnt = 0\n for i in range(N):\n for j in range(M):\n if graph[i][j] == 1 and visited[i][j] == 0:\n DFS(i, j)\n cnt += 1\n\n print(cnt)","repo_name":"SSAFY-Busan/SSAFY_Algorithm","sub_path":"210930/dohun/BOJ_1012.py","file_name":"BOJ_1012.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"14769346807","text":"import os\nimport spyral\nfrom .sprites import sprite\nfrom . import collision\n\nWIDTH = 1200\nHEIGHT = 900\nWHITE = (255, 255, 255)\nSIZE = (WIDTH, HEIGHT)\nGREEN = (60, 179, 113)\nRED = (255, 0, 0)\nBLACKBLUE = (19, 15, 48)\nBG_COLOR = BLACKBLUE\n\nENEMYGAP = 30\nXMARGIN = 175\nYMARGIN = 100\nMOVEX = 15\nMOVEY = 20\nENEMYSIDE = 50\n\nBACKGROUND = os.path.join(\"game\", \"graphics\", \"spacebackground.png\")\n\n\nclass Level1(spyral.Scene):\n def __init__(self):\n spyral.Scene.__init__(self, SIZE)\n self.space = spyral.Image(filename=BACKGROUND)\n self.background = self.space.scale((1200, 900))\n\n self.collision_handler = collision.CollisionHandler(self)\n self.player = sprite.Player(self, 'left', self.collision_handler)\n self.alien_list = self.make_aliens(6, 3)\n self.collision_handler.add_player(self.player)\n self.collision_handler.add_aliens(self.alien_list)\n\n spyral.event.register(\"system.quit\", spyral.director.pop)\n spyral.event.register(\"director.update\", self.update)\n spyral.event.register(\"input.keyboard.down.q\", spyral.director.pop)\n \n def update(self, delta):\n pass\n\n def make_aliens(self, columns, rows):\n \"\"\"\n Make aliens and send them to collision handler.\n \"\"\"\n alien_list = []\n\n for column in range(columns):\n for row in range(rows):\n alien = sprite.Alien(self, row, column)\n alien_list.append(alien)\n\n return alien_list\n\n","repo_name":"justinmeister/spaceinvaders-spyral","sub_path":"game/level.py","file_name":"level.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"7645325790","text":"#!/usr/bin/python3\r\n\r\n# Task: Rosalind problem FIB.\r\n# Input: Positive integers n ≤ 40 and k ≤ 5.\r\n# Output: The total number of rabbit pairs that will be present after n months, if we begin with 1 pair and in each\r\n# generation, every pair of reproduction-age rabbits produces a litter of k rabbit pairs\r\n# (instead of only 1 pair).\r\n# Date: 06/06/2020\r\n\r\n\r\n# The sys module allows intake of input variables.\r\nimport sys\r\n\r\n\r\n# This is the function which will be used to compute the answer to the task, receiving month and offspring/generation\r\n# as input parameters\r\ndef fibonacci(n_months, k_offspring):\r\n\r\n # Prior to operating on any variables, me must first ensure that they are integers.\r\n # This try block converts the input variables from strings to integers.\r\n try:\r\n n_months = int(n_months)\r\n k_offspring = int(k_offspring)\r\n\r\n # If the input variables are not numbers as requested, an error message will be printed and the program exited.\r\n except ValueError:\r\n print(\"The correct input format has not been followed.\\n\"\r\n \"Please provide positive integers n ≤ 40 and k ≤ 5.\")\r\n exit()\r\n\r\n # Once the try checkpoint is passed, the rabbit number is generated.\r\n # The conventional Fibonacci sequence follows the format of \"Fn = (Fn-1) + (Fn-2)\"\r\n # For this task, each mature rabbit pair will produce k offspring pairs, instead of 1.\r\n # Thus, a formula of \"Fn = (Fn-1) + k(Fn-2)\" will be used, up to a value of n provided.\r\n\r\n # Here, we set month 0 and month 1 to a value of 1. This is because we assume a starting value of 1, and a\r\n # maturation time of 1 month (hence the formula).\r\n # These values will provide our initial (Fn-1) and (Fn-2).\r\n fminus2 = 1\r\n fminus1 = 1\r\n\r\n # This is the forumala which will be used to compute the answer for n months.\r\n fn = fminus1 + k_offspring * fminus2\r\n\r\n # To calculate, we count up to n-2. This is because we already know the initial values for month 0 and 1 (both 1).\r\n for i in range(1, n_months-1):\r\n\r\n # Each iteration/month, we update our counter\r\n # Fn, our current count becomes the sum of the last month's count (Fn-1) plus the offspring of our mature\r\n # rabbits (Fn-2 multiplied by offspring/generation multiplier, k)\r\n fn = fminus1 + k_offspring*fminus2\r\n\r\n # In addition, we update our Fn-1/Fn-2 values. Fn-1 (fminus1) becomes Fn-2 (is assigned to fminus2)\r\n fminus2 = fminus1\r\n\r\n # The current generation value (fn) will become Fn-1 in the next month, and so is assigned to fminus1.\r\n fminus1 = fn\r\n\r\n # The answer is then returned.\r\n return fn\r\n\r\n\r\n# This main function is unnecessary for this rosalind problem, but is here to be consistent with the usual structure.\r\ndef main(n_months, k_offspring):\r\n rabbit_num = fibonacci(n_months, k_offspring)\r\n\r\n print(rabbit_num)\r\n\r\n\r\n# Here we execute our code, first checking that two variables have been entered.\r\nif __name__ == \"__main__\":\r\n if len(sys.argv) == 3:\r\n main(sys.argv[1], sys.argv[2])\r\n\r\n else:\r\n print(\"The correct input format has not been followed.\\n\"\r\n \"Please provide positive integers n ≤ 40 and k ≤ 5\")\r\n","repo_name":"Matt-McElheron/python_study","sub_path":"gene30040/Rosalind_FIB.py","file_name":"Rosalind_FIB.py","file_ext":"py","file_size_in_byte":3282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"32310024553","text":"import os\n\nfrom ament_index_python.packages import get_package_share_directory\nfrom launch import LaunchDescription\nfrom launch.actions import DeclareLaunchArgument\nfrom launch.actions import IncludeLaunchDescription\nfrom launch.conditions import IfCondition\nfrom launch.launch_description_sources import PythonLaunchDescriptionSource\nfrom launch.substitutions import LaunchConfiguration\nfrom launch_ros.actions import Node\n\ndef generate_launch_description():\n\n\tpkg_ros_ign_gazebo = get_package_share_directory('ros_ign_gazebo')\n\tpkg_igt_ignition = get_package_share_directory('igt_ignition')\n\turdf_path = pkg_igt_ignition + '/models/igt_one/igt_one.urdf'\n\tuse_sim_time = LaunchConfiguration('use_sim_time')\n\n\t# Gazebo launch\n\tgazebo = IncludeLaunchDescription(\n\t\tPythonLaunchDescriptionSource(\n\t\t os.path.join(pkg_ros_ign_gazebo, 'launch', 'ign_gazebo.launch.py'),\n\t\t),\n\t)\n\n\t# launch ign_bridge if with_bridge is true\n\tign_bridge = IncludeLaunchDescription(\n\t\tPythonLaunchDescriptionSource(\n\t\t os.path.join(pkg_igt_ignition, 'launch', 'ign_bridge.launch.py'),\n\t\t),\n launch_arguments={\n 'use_sim_time': use_sim_time}.items(),\n\t\tcondition = IfCondition(LaunchConfiguration('with_bridge'))\n\t)\n\n\t# spawn sdf\n\tspawn_sdf = Node(package='ros_ign_gazebo', executable='create',\n\t\t\targuments=['-name', 'igt_one',\n\t\t\t\t'-x', '2.0',\n '-y', '0.0',\n\t\t\t\t'-z', '0.0',\n\t\t\t\t'-Y', '-1.57',\n\t\t\t\t'-file', os.path.join(pkg_igt_ignition, 'models', 'igt_one', 'model.sdf')],\n\t\t\toutput='screen')\n\n\t# robot state publisher node\n\tstate_publisher = Node(package='robot_state_publisher', executable='robot_state_publisher',\n\t\t\t\toutput='screen',\n\t\t\t\tparameters = [\n\t\t\t\t\t{'ignore_timestamp': False},\n {'use_sim_time': use_sim_time},\n\t\t\t\t\t{'use_tf_static': True},\n\t\t\t\t\t{'robot_description': open(urdf_path).read()}],\n\t\t\t\targuments = [urdf_path])\t\n\n\treturn LaunchDescription([\n\t\tDeclareLaunchArgument(\n\t\t 'ign_args', default_value=[os.path.join(pkg_igt_ignition, 'worlds', 'lab.sdf') +\n\t\t\t\t\t ' -v 2 --gui-config ' +\n\t\t\t\t\t os.path.join(pkg_igt_ignition, 'ign', 'gui.config'), ''],\n\t\t description='Ignition Gazebo arguments'),\n\t\tDeclareLaunchArgument('with_bridge', default_value=['false'],\n\t\t\t\t\tdescription='Launch simulation with ros ign brigde'),\n DeclareLaunchArgument('use_sim_time', default_value=['true'],\n description='Enable sim time from /clock'),\n\t\tgazebo,\n\t\tspawn_sdf,\n\t\tign_bridge,\n\t\tstate_publisher\n\t])\n","repo_name":"acceleration-robotics/ros2-igt","sub_path":"igt_ignition/launch/igt_ignition.launch.py","file_name":"igt_ignition.launch.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"55"} +{"seq_id":"44501002335","text":"\"\"\"\nGère les compte à rebours.\n\"\"\"\n\nimport datetime\nimport itertools\nimport discord\n\nfrom discord.ext import commands, tasks\nfrom config.config import cluster, access\nfrom models.mongo import MongoDatabase\n\n\nclass CountDown(commands.Cog):\n \"\"\"Cog des comptes à rebours.\"\"\"\n\n def __init__(self, bot: commands.Bot):\n \"\"\"Count down.\"\"\"\n self.bot = bot\n self.color = discord.Color(0xFF0033)\n self.update.start()\n\n @property\n def countdowns(self):\n \"\"\"Return the mongo countdown database.\"\"\"\n return cluster.countdown.countdown\n\n @commands.group(name=\"compte-à-rebours\", aliases=[\"countdown\", \"count\"])\n async def countdown(self, ctx: commands.Context):\n \"\"\"Gestion de compte à rebours\"\"\"\n if not ctx.invoked_subcommand:\n print(\"Vous n'avez pas invoké de sous-commande.\")\n\n @countdown.command(name=\"réinitialiser\", aliases=[\"reset\", \"rs\"])\n @access.admin\n async def reset(self, ctx: commands.Context):\n \"\"\"Réinitialise la base de données.\"\"\"\n del cluster[\"countdown\"]\n await ctx.send(f\"> La base de données **countdown** a été supprimée.\")\n await self.restart(ctx)\n\n @countdown.command(name=\"ajouter\", aliases=[\"add\", \"a\"])\n async def add(\n self, ctx: commands.Context, name: str, date: str, time: str = \"00:00:00\"\n ):\n \"\"\"Ajoute un compte à rebours.\"\"\"\n datetime_str = date + \" \" + time\n print(datetime_str)\n datetime_ = datetime.datetime.strptime(datetime_str, \"%Y-%m-%d %H:%M:%S\")\n embed = self.get_embed(name, datetime_)\n message: discord.Message = await ctx.send(embed=embed)\n self.countdowns[name].bot = self.bot.user.id\n self.countdowns[name].author = ctx.author.id\n self.countdowns[name].datetime = datetime_\n self.countdowns[name].message = message.id\n self.countdowns[name].guild = message.guild.id\n self.countdowns[name].channel = message.channel.id\n\n print(self.countdowns[name])\n\n @countdown.command(name=\"supprimer\", aliases=[\"remove\", \"rm\"])\n async def remove(self, ctx: commands.Context, name: str):\n \"\"\"Retire un compte à rebours.\"\"\"\n del self.countdowns[name]\n\n @countdown.command(name=\"liste\", aliases=[\"list\", \"l\"])\n async def list(self, ctx: commands.Context, *names: str):\n \"\"\"Liste les comptes à rebours.\"\"\"\n for countdown in self.countdowns.find():\n name = countdown[\"_id\"]\n datetime_ = countdown[\"datetime\"]\n await ctx.send(f\"> **{name}** jusqu'à **{datetime_}**.\")\n\n @countdown.command(name=\"liste-brute\", aliases=[\"raw-list\", \"rl\"])\n async def raw_list(self, ctx: commands.Context, *names: str):\n \"\"\"Liste les comptes à rebours sans traitement.\"\"\"\n for countdown in self.countdowns.find():\n await ctx.send(f\"> **{countdown}**\")\n\n @countdown.command(name=\"trouver\", aliases=[\"find\", \"f\"])\n async def find(self, ctx: commands.Context, *names: str):\n \"\"\"Trouve des comptes à rebours.\"\"\"\n for countdown in self.countdowns.find():\n await self.refresh(ctx, countdown)\n\n @countdown.command(name=\"relance\", aliases=[\"restart\"])\n async def restart(self, ctx: commands.Context):\n \"\"\"Recommence l'actualisation automatique.\n À utiliser en cas d'erreur.\"\"\"\n self.update.start()\n await ctx.send(\n f\"> Relance de l'actualisation automatique des comptes à rebours.\"\n )\n\n async def refresh(self, ctx: commands.Context, countdown: dict):\n \"\"\"Rafraîchi la collection,\n ainsi que le message.\"\"\"\n name = countdown[\"_id\"]\n datetime_ = countdown[\"datetime\"]\n\n message = await self.get_countdown_message(countdown)\n\n await message.delete()\n\n embed = self.get_embed(countdown[\"_id\"], datetime_)\n\n del self.countdowns[countdown[\"_id\"]]\n message: discord.Message = await ctx.send(embed=embed)\n\n self.countdowns[name].bot = message.author.id\n self.countdowns[name].author = ctx.author.id\n self.countdowns[name].datetime = datetime_\n self.countdowns[name].message = message.id\n self.countdowns[name].guild = message.guild.id\n self.countdowns[name].channel = message.channel.id\n\n def get_embed(self, name: str, datetime_: datetime.datetime) -> discord.Embed:\n \"\"\"Crée une intégration discord pour les comptes à rebours.\"\"\"\n now = datetime.datetime.now().replace(microsecond=0)\n time_left = datetime_ - now\n # time_left_str = time_left.strftime(\"%Y/%m/%d %H:%M:%S\")\n time_left_str = str(time_left)\n # print('time left:', time_left_str)\n embed = discord.Embed(title=time_left_str, description=name, color=self.color)\n return embed\n\n async def get_countdown_message(self, countdown: dict) -> discord.Message:\n \"\"\"Return the message.\"\"\"\n channel_id = int(countdown[\"channel\"])\n guild_id = int(countdown[\"guild\"])\n guild: discord.Guild = self.bot.get_guild(guild_id)\n channel: discord.TextChannel = guild.get_channel(channel_id)\n message = await channel.fetch_message(countdown[\"message\"])\n return message\n\n @tasks.loop(seconds=1)\n async def update(self):\n \"\"\"Actualise les compteurs.\"\"\"\n # print(list(self.countdowns.find()))\n try:\n for countdown in self.countdowns.find():\n datetime_ = countdown[\"datetime\"]\n try:\n message = await self.get_countdown_message(countdown)\n except discord.errors.NotFound:\n print(\"[countdown] cant find message\", countdown)\n continue\n\n # If the mongo message was posted by another bot\n # we can't write it, so we refresh it.\n if countdown[\"bot\"] != self.bot.user.id:\n ctx = self.bot.get_context(message)\n await self.refresh(ctx, countdown)\n continue\n\n now = datetime.datetime.now().replace(microsecond=0)\n time_left = datetime_ - now\n if time_left.total_seconds() < 0:\n del self.countdowns[countdown[\"_id\"]]\n await message.delete()\n continue\n embed = self.get_embed(countdown[\"_id\"], datetime_)\n await message.edit(embed=embed)\n\n except discord.errors.Forbidden as e:\n print(e)\n\n def cog_unload(self):\n \"\"\"Retire les tâches de fonds.\"\"\"\n self.update.cancel()\n\n @update.before_loop\n async def before_printer(self):\n \"\"\"Wait until the bot is ready.\"\"\"\n await self.bot.wait_until_ready()\n\n\ndef setup(bot):\n \"\"\"Setup the CountDown cog.\"\"\"\n bot.add_cog(CountDown(bot))\n","repo_name":"MarcPartensky/discord-bot","sub_path":"cogs/countdown.py","file_name":"countdown.py","file_ext":"py","file_size_in_byte":6879,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"55"} +{"seq_id":"4380771379","text":"import tkinter as tk\r\nfrom tkinter import ttk, messagebox\r\nimport mysql.connector\r\nfrom tkinter import *\r\n\r\ndef GetValue(event):\r\n e1.delete(0, END)\r\n e2.delete(0, END)\r\n e3.delete(0, END)\r\n e4.delete(0, END)\r\n row_id = listBox.selection()[0]\r\n select = listBox.set(row_id)\r\n e1.insert(0,select['id'])\r\n e2.insert(0,select['empname'])\r\n e3.insert(0,select['mobile'])\r\n e4.insert(0,select['salary'])\r\n\r\n\r\ndef Add():\r\n empid = e1.get()\r\n empname = e2.get()\r\n mobile = e3.get()\r\n salary = e4.get()\r\n\r\n if(empid!=\"\" or empname!=\"\" or mobile!=\"\" or salary !=\"\"):\r\n mysqldb=mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"root\", port=3306,database=\"sonudb\")\r\n mycursor=mysqldb.cursor()\r\n\r\n try:\r\n sql = \"INSERT INTO registation (id,empname,mobile,salary) VALUES (%s, %s, %s, %s)\"\r\n val = (empid,empname,mobile,salary)\r\n mycursor.execute(sql, val)\r\n mysqldb.commit()\r\n lastid = mycursor.lastrowid\r\n messagebox.showinfo(\"information\", \"Employee inserted successfully...\")\r\n e1.delete(0, END)\r\n e2.delete(0, END)\r\n e3.delete(0, END)\r\n e4.delete(0, END)\r\n e1.focus_set()\r\n except Exception as e:\r\n print(e)\r\n mysqldb.rollback()\r\n mysqldb.close()\r\n else:\r\n messagebox.showinfo(\"information\", \"Not All Information Provided..\")\r\n\r\n\r\ndef update():\r\n empid = e1.get()\r\n empname = e2.get()\r\n mobile = e3.get()\r\n salary = e4.get()\r\n mysqldb=mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"root\", port=3306,database=\"sonudb\")\r\n mycursor=mysqldb.cursor()\r\n\r\n if(empid!=\"\" or empname!=\"\" or mobile!=\"\" or salary !=\"\"):\r\n try:\r\n sql = \"Update registation set empname= %s,mobile= %s,salary= %s where id= %s\"\r\n val = (empname,mobile,salary,empid)\r\n mycursor.execute(sql, val)\r\n mysqldb.commit()\r\n lastid = mycursor.lastrowid\r\n messagebox.showinfo(\"information\", \"Record Updateddddd successfully...\")\r\n\r\n e1.delete(0, END)\r\n e2.delete(0, END)\r\n e3.delete(0, END)\r\n e4.delete(0, END)\r\n e1.focus_set()\r\n except Exception as e:\r\n print(e)\r\n mysqldb.rollback()\r\n mysqldb.close()\r\n else:\r\n messagebox.showinfo(\"information\", \"Record to update not selected..\")\r\n\r\ndef delete():\r\n empid = e1.get()\r\n\r\n if(empid!=\"\"):\r\n mysqldb=mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"root\", port=3306,database=\"sonudb\")\r\n mycursor=mysqldb.cursor()\r\n\r\n try:\r\n sql = \"delete from registation where id = %s \"\r\n val = (empid,)\r\n mycursor.execute(sql, val)\r\n mysqldb.commit()\r\n lastid = mycursor.lastrowid\r\n messagebox.showinfo(\"information\", \"Record Deleteeeee successfully...\")\r\n\r\n e1.delete(0, END)\r\n e2.delete(0, END)\r\n e3.delete(0, END)\r\n e4.delete(0, END)\r\n e1.focus_set()\r\n \r\n except Exception as e:\r\n print(e)\r\n mysqldb.rollback()\r\n mysqldb.close()\r\n else:\r\n messagebox.showinfo(\"information\", \"No Record Deleted.\")\r\n\r\ndef show(): \r\n mysqldb = mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"root\", port=3306,database=\"sonudb\")\r\n mycursor = mysqldb.cursor()\r\n\r\n for item in listBox.get_children():\r\n listBox.delete(item)\r\n \r\n mycursor.execute(\"SELECT id,empname,mobile,salary FROM registation\")\r\n records = mycursor.fetchall()\r\n\r\n for i, (id,stname, course,fee) in enumerate(records, start=1):\r\n listBox.insert(\"\", \"end\", values=(id, stname, course, fee))\r\n mysqldb.close()\r\n\r\nroot = Tk()\r\nroot.geometry(\"800x500\")\r\nglobal e1\r\nglobal e2\r\nglobal e3\r\nglobal e4\r\n\r\ntk.Label(root, text=\"Employee Registation\", fg=\"red\", font=(None, 30)).place(x=300, y=5)\r\n\r\ntk.Label(root, text=\"Employee ID\").place(x=10, y=10)\r\nLabel(root, text=\"Employee Name\").place(x=10, y=40)\r\nLabel(root, text=\"Mobile\").place(x=10, y=70)\r\nLabel(root, text=\"Salary\").place(x=10, y=100)\r\n\r\ne1 = Entry(root)\r\ne1.place(x=140, y=10)\r\n\r\ne2 = Entry(root)\r\ne2.place(x=140, y=40)\r\n\r\ne3 = Entry(root)\r\ne3.place(x=140, y=70)\r\n\r\ne4 = Entry(root)\r\ne4.place(x=140, y=100)\r\n\r\nButton(root, text=\"Add\",command = Add,height=3, width= 13).place(x=30, y=130)\r\nButton(root, text=\"update\",command = update,height=3, width= 13).place(x=140, y=130)\r\nButton(root, text=\"Delete\",command = delete,height=3, width= 13).place(x=250, y=130)\r\nButton(root, text=\"Show\",command = show,height=3, width= 13).place(x=370, y=130)\r\n\r\ncols = ('id', 'empname', 'mobile','salary')\r\nlistBox = ttk.Treeview(root, columns=cols, show='headings' )\r\n\r\nfor col in cols:\r\n listBox.heading(col, text=col)\r\n listBox.grid(row=1, column=0, columnspan=2)\r\n listBox.place(x=10, y=200)\r\n\r\nlistBox.bind('',GetValue)\r\n\r\nroot.mainloop()\r\n","repo_name":"SpWorkspace22/python_gui","sub_path":"Solution_Python_14.py","file_name":"Solution_Python_14.py","file_ext":"py","file_size_in_byte":5095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"37849191858","text":"# coding=utf-8\nimport socket\nimport time\n\n\ndef request_handler(client_socket):\n \"\"\"\n 处理客户端请求\n :param client_socket:\n :return:\n \"\"\"\n receive_data = client_socket.recv(1024).decode(\"utf-8\")\n multiple_lines = receive_data.splitlines()\n for line in multiple_lines:\n print(line)\n\n # time.sleep(10) 用以测试请求为串行\n\n # 构造响应数据\n response_headers = \"HTTP/1.1 200 OK\\r\\n\"\n response_headers += \"\\r\\n\"\n response_body = \"hello world\"\n response = response_headers + response_body\n client_socket.send(response.encode(\"utf-8\"))\n client_socket.close() # 服务器端4次挥手之后资源能够立即释放,保证下次运行程序时,可以立即绑定8080端口\n\n\ndef main():\n \"\"\"\n 解释一些常量值含义\n socket.AF_INET: 基于网络的套接字\n socket.AF_UNIX: 基于文件的套接字\n socket.SOCK_STREAM: TCP套接字\n socket.SOCK_DGRAM: UDP套接字\n socket.SO_REUSEADDR: 让端口释放后立即就可以被再次使用\n\n :return:\n \"\"\"\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建一个基于网络并且使用tcp协议的套接字,用于通信\n server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server_socket.bind((\"\", 8080))\n server_socket.listen(128)\n while True:\n client_socket, client_addr = server_socket.accept()\n client_handler(client_socket)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"WytheLi/mini-server","sub_path":"static_server/single_page_server.py","file_name":"single_page_server.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"21088420554","text":"# dataset settings\ndataset_type = 'GenBuildingDataset'\ndata_root = '../data/BuildingDataset'\nimg_norm_cfg = dict(\n mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)\ncrop_size = (512, 512)\ntrain_pipeline = [\n dict(type=\"LoadImageFromFile\"),\n dict(type='LoadGenImageFromFile'),\n dict(type='LoadAnnotations', reduce_zero_label=True),\n dict(type='RandomCrop', crop_size=crop_size, cat_max_ratio=0.75),\n dict(type='RandomFlip', prob=0.5, direction=\"horizontal\"),\n dict(type='RandomFlip', prob=0.5, direction=\"vertical\"),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='Pad', size=crop_size, pad_val=0, seg_pad_val=255),\n dict(type='DefaultFormatBundle'),\n # Insert custom transform for combining the images\n dict(type=\"CombineImageGen\"),\n dict(type='Collect', keys=['img', 'gt_semantic_seg']),\n]\ntest_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(type='LoadGenImageFromFile'),\n dict(\n type='MultiScaleFlipAug',\n img_scale=(512, 512),\n # img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75],\n flip=False,\n transforms=[\n dict(type='Normalize', **img_norm_cfg),\n dict(type='CombineImageGen'),\n dict(type='Collect', keys=['img']),\n ])\n]\ndata = dict(\n samples_per_gpu=4,\n workers_per_gpu=4,\n train=dict(\n type=dataset_type,\n data_root=data_root,\n img_dir='train/images',\n gen_dir='train/images',\n ann_dir='train/masks',\n pipeline=train_pipeline),\n val=dict(\n type=dataset_type,\n data_root=data_root,\n img_dir='val/images',\n gen_dir='train/images',\n ann_dir='val/masks',\n pipeline=test_pipeline),\n test=dict(\n type=dataset_type,\n data_root=data_root,\n img_dir='test/images',\n gen_dir='train/images',\n ann_dir='test/masks',\n pipeline=test_pipeline))","repo_name":"Sjyhne/mmsegmentation_merge","sub_path":"configs/_base_/datasets/genbuildingdataset.py","file_name":"genbuildingdataset.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"18066802608","text":"import pandas as pd\r\nimport numpy as np\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.model_selection import train_test_split\r\nfrom collections import Counter\r\n\r\n#索引1为activity_id\r\n#索引[4:16)/[21,33)/[38,50)分别为3个IMU的3D-acc1,3D-acc2,3D-gyro,3D-magn(共36种特征)\r\nloc = [1] + [*range(4,16)] + [*range(21,33)] + [*range(38,50)]\r\n\r\ndef window(data, label, size, stride):\r\n '''将数组data和label按照滑窗尺寸size和stride进行切割'''\r\n x, y = [], []\r\n for i in range(0, len(label), stride):\r\n if i+size < len(label): #不足一个滑窗大小的数据丢弃\r\n\r\n l = set(label[i:i+size])\r\n if len(l) > 1 or label[i] == 0: #当一个滑窗中含有包含多种activity或者activity_id为0(即属于其他动作),丢弃\r\n continue\r\n elif len(l) == 1:\r\n x.append(data[i: i + size, :])\r\n y.append(label[i])\r\n\r\n return x, y\r\n\r\ndef generate(window_size, step):\r\n '''生成训练样本X和对应标签Y'''\r\n X, Y = [], []\r\n # 遍历9个subject文件\r\n for i in range(1, 10):\r\n total = pd.read_csv('./Protocol/subject10' + str(i) + '.dat', header=None, sep=' ', usecols=loc).values\r\n total = total[~np.isnan(total).any(axis=1), :] #去除NaN\r\n data = total[:, 1:]\r\n label = total[:, 0].reshape(-1)\r\n\r\n # 调用window函数进行滑窗处理\r\n x, y = window(data, label, window_size, step)\r\n X += x\r\n Y += y\r\n\r\n # 将索引从0开始依次编号\r\n cate_idx = list(Counter(Y).keys())\r\n cate_idx.sort()\r\n for i in range(len(Y)):\r\n Y[i] = cate_idx.index(Y[i])\r\n\r\n return X, Y\r\n\r\ndef category(X, Y):\r\n '''按照种类分类动作'''\r\n result = [[] for i in range(len(list(Counter(Y).keys())))] #result对应的索引即标签\r\n for step, y in enumerate(Y):\r\n result[y].append(X[step])\r\n return result\r\n\r\ndef split(result, test_size):\r\n '''划分数据集\r\n test_size:测试集样本数量占比'''\r\n x_train, x_test, y_train, y_test = [], [], [], []\r\n for i, data in enumerate(result):\r\n label = [i for n in range(len(data))]\r\n x_train_, x_test_, y_train_, y_test_ = train_test_split(data, label, test_size=test_size, shuffle=True)\r\n x_train.extend(x_train_)\r\n y_train.extend(y_train_)\r\n x_test.extend(x_test_)\r\n y_test.extend(y_test_)\r\n return x_train, y_train, x_test, y_test\r\n\r\nif __name__ == '__main__':\r\n X, Y = generate(171, 85)\r\n result = category(X, Y)\r\n x_train, y_train, x_test, y_test = split(result, 0.2)\r\n\r\n x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, shuffle=True)\r\n np.save('./x_train', x_train)\r\n np.save('./x_test', x_test)\r\n np.save('./y_train', y_train)\r\n np.save('./y_test', y_test)\r\n","repo_name":"Chaolei98/Baseline-with-HAR-datasets","sub_path":"Pre-processing/PAMAP2.py","file_name":"PAMAP2.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"55"} +{"seq_id":"23534606966","text":"import numpy as np\nimport cv2\nimport os\nimport math\n\nintrinsic_camera_matrix_filenames = ['intri_left.xml', 'intri_right.xml']\nextrinsic_camera_matrix_filenames = ['extri_left.xml', 'extri_right.xml']\n\n# camera calibration to get the rvec and tvec\ndef camera_calibration(camera):\n if (camera == \"left\"):\n object_3d_points = np.array(([3805, 4226, 0.],\n [2186, 1902, 0.],\n [3818, 674, 0],\n [5835, 3049, 0],\n [7225, 1888, 0]), dtype=np.double)\n\n object_2d_point = np.array(([84, 147],\n [188, 293],\n [502, 215],\n [318, 104],\n [464, 85]), dtype=np.double)\n\n fz_camera_matrix = np.array(([672.696475436197, 0.0, 336.091575679676],\n [0.0, 631.740668979164, 232.912518319968],\n [0.0, 0.0, 1.0]), dtype=\"double\")\n\n dist_coefs = np.array(\n [-0.0753413793419683, 0.242546341519954, -0.00219587406317966, 0.00396341324028028, -0.107908652593460],\n dtype=np.double)\n\n else:\n object_3d_points = np.array(([4315, 238, 0.],\n [5829, 2601, 0],\n [4342, 3782, 0],\n [2196, 1459, 0],\n [794, 2596, 0]), dtype=np.double)\n\n object_2d_point = np.array(([60, 153],\n [177, 312],\n [493, 231],\n [308, 102],\n [460, 78]), dtype=np.double)\n\n fz_camera_matrix = np.array(([654.690854219901, 0.0, 331.747624399371],\n [0.0, 615.075013458089, 257.729982008233],\n [0.0, 0.0, 1.0]), dtype=\"double\")\n\n dist_coefs = np.array(\n [-0.0721106179904230, 0.178067038866243, 0.00122551662740768, 0.00414688113770697, -0.0844652346664083],\n dtype=np.double)\n\n (success, rotation_vector, translation_vector) = cv2.solvePnP(object_3d_points, object_2d_point, fz_camera_matrix,\n dist_coefs,\n flags=cv2.SOLVEPNP_ITERATIVE)\n fz_rvec = cv2.Rodrigues(rotation_vector)[0]\n fz_tvec = translation_vector\n\n return fz_rvec, fz_tvec, fz_camera_matrix\n\n\ndef get_intrinsic_extrinsic_matrix(self, camera_i, root):\n intrinsic_camera_path = os.path.join(root, 'calibration', 'intrinsic')\n intrinsic_params_file = cv2.FileStorage(os.path.join(intrinsic_camera_path,\n intrinsic_camera_matrix_filenames[camera_i]),\n flags=cv2.FILE_STORAGE_READ)\n intrinsic_matrix = intrinsic_params_file.getNode('intri_matrix').mat()\n intrinsic_params_file.release()\n\n extrinsic_camera_path = os.path.join(root, 'calibration', 'extrinsic')\n extrinsic_params_file = cv2.FileStorage(os.path.join(extrinsic_camera_path,\n extrinsic_camera_matrix_filenames[camera_i]),\n flags=cv2.FILE_STORAGE_READ)\n extrinsic_matrix = extrinsic_params_file.getNode('extri_matrix').mat()\n extrinsic_params_file.release()\n # convert millimeter to centimeter\n for i in range(3):\n extrinsic_matrix[i, 3] /= 10\n return intrinsic_matrix, extrinsic_matrix\n\n# 3D points to image points\ndef getimage(points3d, rvec, tvec, camera_matrix):\n newpoints3d = np.vstack((points3d, 1.0))\n Zc = np.dot(np.hstack((rvec, tvec)), newpoints3d)[-1]\n imagepoints = np.dot(camera_matrix, np.dot(np.hstack((rvec, tvec)), newpoints3d)) / Zc\n return imagepoints\n\n# get the 8 points of 3D box in image\ndef get3Dlocation(objectx, objecty, dimesions, angle, rvec, tvec, camera_matrix):\n high = float(dimesions[0])\n width = float(dimesions[1])\n length = float(dimesions[2])\n\n true_angle = angle\n pose1 = np.array(([length / 2], [width / 2]), dtype=\"double\") * 1000\n pose2 = np.array(([length / 2], [-width / 2]), dtype=\"double\") * 1000\n pose3 = np.array(([-length / 2], [-width / 2]), dtype=\"double\") * 1000\n pose4 = np.array(([-length / 2], [width / 2]), dtype=\"double\") * 1000\n\n ro_matrix = np.array(([math.cos(true_angle), -math.sin(true_angle)],\n [math.sin(true_angle), math.cos(true_angle)]), dtype=\"double\")\n\n points3d = []\n result = []\n\n points3d.append(np.vstack((np.dot(ro_matrix, pose1) + np.array([[objectx],[objecty]]), high * 800)))\n points3d.append(np.vstack((np.dot(ro_matrix, pose2) + np.array([[objectx],[objecty]]), high * 800)))\n points3d.append(np.vstack((np.dot(ro_matrix, pose3) + np.array([[objectx],[objecty]]), high * 800)))\n points3d.append(np.vstack((np.dot(ro_matrix, pose4) + np.array([[objectx],[objecty]]), high * 800)))\n points3d.append(np.vstack((np.dot(ro_matrix, pose1) + np.array([[objectx],[objecty]]), 0)))\n points3d.append(np.vstack((np.dot(ro_matrix, pose2) + np.array([[objectx],[objecty]]), 0)))\n points3d.append(np.vstack((np.dot(ro_matrix, pose3) + np.array([[objectx],[objecty]]), 0)))\n points3d.append(np.vstack((np.dot(ro_matrix, pose4) + np.array([[objectx],[objecty]]), 0)))\n\n for i in points3d:\n result.append(getimage(i, rvec, tvec, camera_matrix))\n\n return result\n\ndef main(logpath, image_path, savepath, camera):\n\n # read the log\n flog_list = open(logpath)\n lines = flog_list.readlines()\n\n # get the imageslist\n frame_list = os.listdir(image_path)\n frame_list.sort()\n\n for i in range(len(lines)):\n\n line = lines[i].split(\" \")\n\n red1_x = float(line[1])\n red1_y = float(line[2])\n red1_yaw = float(line[3])\n\n red2_x = float(line[5])\n red2_y = float(line[6])\n red2_yaw = float(line[7])\n\n blue1_x = float(line[9])\n blue1_y = float(line[10])\n blue1_yaw = float(line[11])\n\n blue2_x = float(line[13])\n blue2_y = float(line[14])\n blue2_yaw = float(line[15])\n\n # the car's high width length\n dimensions = [0.505, 0.499, 0.592]\n img_name = frame_list[i].split('.')[0]\n\n\n copyimg = cv2.imread(image_path + frame_list[i])\n\n rvec, tvec, camera_matrix = camera_calibration(camera)\n\n b1_img_points = get3Dlocation(blue1_x * 1000, blue1_y * 1000, dimensions, blue1_yaw, rvec, tvec, camera_matrix)\n b2_img_points = get3Dlocation(blue2_x * 1000, blue2_y * 1000, dimensions, blue2_yaw, rvec, tvec, camera_matrix)\n r1_img_points = get3Dlocation(red1_x * 1000, red1_y * 1000, dimensions, red1_yaw, rvec, tvec, camera_matrix)\n r2_img_points = get3Dlocation(red2_x * 1000, red2_y * 1000, dimensions, red2_yaw, rvec, tvec, camera_matrix)\n\n b1_up1 = [b1_img_points[0][0], b1_img_points[0][1]]\n b1_up2 = [b1_img_points[1][0], b1_img_points[1][1]]\n b1_up3 = [b1_img_points[2][0], b1_img_points[2][1]]\n b1_up4 = [b1_img_points[3][0], b1_img_points[3][1]]\n b1_down1 = [b1_img_points[4][0], b1_img_points[4][1]]\n b1_down2 = [b1_img_points[5][0], b1_img_points[5][1]]\n b1_down3 = [b1_img_points[6][0], b1_img_points[6][1]]\n b1_down4 = [b1_img_points[7][0], b1_img_points[7][1]]\n\n b2_up1 = [b2_img_points[0][0], b2_img_points[0][1]]\n b2_up2 = [b2_img_points[1][0], b2_img_points[1][1]]\n b2_up3 = [b2_img_points[2][0], b2_img_points[2][1]]\n b2_up4 = [b2_img_points[3][0], b2_img_points[3][1]]\n b2_down1 = [b2_img_points[4][0], b2_img_points[4][1]]\n b2_down2 = [b2_img_points[5][0], b2_img_points[5][1]]\n b2_down3 = [b2_img_points[6][0], b2_img_points[6][1]]\n b2_down4 = [b2_img_points[7][0], b2_img_points[7][1]]\n\n r1_up1 = [r1_img_points[0][0], r1_img_points[0][1]]\n r1_up2 = [r1_img_points[1][0], r1_img_points[1][1]]\n r1_up3 = [r1_img_points[2][0], r1_img_points[2][1]]\n r1_up4 = [r1_img_points[3][0], r1_img_points[3][1]]\n r1_down1 = [r1_img_points[4][0], r1_img_points[4][1]]\n r1_down2 = [r1_img_points[5][0], r1_img_points[5][1]]\n r1_down3 = [r1_img_points[6][0], r1_img_points[6][1]]\n r1_down4 = [r1_img_points[7][0], r1_img_points[7][1]]\n\n r2_up1 = [r2_img_points[0][0], r2_img_points[0][1]]\n r2_up2 = [r2_img_points[1][0], r2_img_points[1][1]]\n r2_up3 = [r2_img_points[2][0], r2_img_points[2][1]]\n r2_up4 = [r2_img_points[3][0], r2_img_points[3][1]]\n r2_down1 = [r2_img_points[4][0], r2_img_points[4][1]]\n r2_down2 = [r2_img_points[5][0], r2_img_points[5][1]]\n r2_down3 = [r2_img_points[6][0], r2_img_points[6][1]]\n r2_down4 = [r2_img_points[7][0], r2_img_points[7][1]]\n\n # 3D box\n b1_pts1 = np.array([b1_up1, b1_up2, b1_down2, b1_down1], np.int32)\n b1_pts2 = np.array([b1_up2, b1_up3, b1_down3, b1_down2], np.int32)\n b1_pts3 = np.array([b1_up1, b1_up4, b1_down4, b1_down1], np.int32)\n b1_pts4 = np.array([b1_up3, b1_up4, b1_down4, b1_down3], np.int32)\n b1_pts1 = b1_pts1.reshape((-1, 1, 2))\n b1_pts2 = b1_pts2.reshape((-1, 1, 2))\n b1_pts3 = b1_pts3.reshape((-1, 1, 2))\n b1_pts4 = b1_pts4.reshape((-1, 1, 2))\n\n b2_pts1 = np.array([b2_up1, b2_up2, b2_down2, b2_down1], np.int32)\n b2_pts2 = np.array([b2_up2, b2_up3, b2_down3, b2_down2], np.int32)\n b2_pts3 = np.array([b2_up1, b2_up4, b2_down4, b2_down1], np.int32)\n b2_pts4 = np.array([b2_up3, b2_up4, b2_down4, b2_down3], np.int32)\n b2_pts1 = b2_pts1.reshape((-1, 1, 2))\n b2_pts2 = b2_pts2.reshape((-1, 1, 2))\n b2_pts3 = b2_pts3.reshape((-1, 1, 2))\n b2_pts4 = b2_pts4.reshape((-1, 1, 2))\n\n r1_pts1 = np.array([r1_up1, r1_up2, r1_down2, r1_down1], np.int32)\n r1_pts2 = np.array([r1_up2, r1_up3, r1_down3, r1_down2], np.int32)\n r1_pts3 = np.array([r1_up1, r1_up4, r1_down4, r1_down1], np.int32)\n r1_pts4 = np.array([r1_up3, r1_up4, r1_down4, r1_down3], np.int32)\n r1_pts1 = r1_pts1.reshape((-1, 1, 2))\n r1_pts2 = r1_pts2.reshape((-1, 1, 2))\n r1_pts3 = r1_pts3.reshape((-1, 1, 2))\n r1_pts4 = r1_pts4.reshape((-1, 1, 2))\n\n r2_pts1 = np.array([r2_up1, r2_up2, r2_down2, r2_down1], np.int32)\n r2_pts2 = np.array([r2_up2, r2_up3, r2_down3, r2_down2], np.int32)\n r2_pts3 = np.array([r2_up1, r2_up4, r2_down4, r2_down1], np.int32)\n r2_pts4 = np.array([r2_up3, r2_up4, r2_down4, r2_down3], np.int32)\n r2_pts1 = r2_pts1.reshape((-1, 1, 2))\n r2_pts2 = r2_pts2.reshape((-1, 1, 2))\n r2_pts3 = r2_pts3.reshape((-1, 1, 2))\n r2_pts4 = r2_pts4.reshape((-1, 1, 2))\n\n cv2.polylines(copyimg, [b1_pts1], True, (0, 255, 0), 2)\n cv2.polylines(copyimg, [b1_pts2], True, (0, 255, 0), 2)\n cv2.polylines(copyimg, [b1_pts3], True, (0, 255, 0), 2)\n cv2.polylines(copyimg, [b1_pts4], True, (0, 255, 0), 2)\n\n cv2.polylines(copyimg, [b2_pts1], True, (0, 255, 0), 2)\n cv2.polylines(copyimg, [b2_pts2], True, (0, 255, 0), 2)\n cv2.polylines(copyimg, [b2_pts3], True, (0, 255, 0), 2)\n cv2.polylines(copyimg, [b2_pts4], True, (0, 255, 0), 2)\n\n cv2.polylines(copyimg, [r1_pts1], True, (0, 255, 0), 2)\n cv2.polylines(copyimg, [r1_pts2], True, (0, 255, 0), 2)\n cv2.polylines(copyimg, [r1_pts3], True, (0, 255, 0), 2)\n cv2.polylines(copyimg, [r1_pts4], True, (0, 255, 0), 2)\n\n cv2.polylines(copyimg, [r2_pts1], True, (0, 255, 0), 2)\n cv2.polylines(copyimg, [r2_pts2], True, (0, 255, 0), 2)\n cv2.polylines(copyimg, [r2_pts3], True, (0, 255, 0), 2)\n cv2.polylines(copyimg, [r2_pts4], True, (0, 255, 0), 2)\n\n # 2D box\n b1_x_min = np.array(min(b1_up1[0], b1_up2[0], b1_up3[0], b1_up4[0]))\n b1_y_min = np.array(min(b1_up1[1], b1_up2[1], b1_up3[1], b1_up4[1]))\n b1_x_max = np.array(max(b1_down1[0], b1_down2[0], b1_down3[0], b1_down4[0]))\n b1_y_max = np.array(max(b1_down1[1], b1_down2[1], b1_down3[1], b1_down4[1]))\n\n b2_x_min = np.array(min(b2_up1[0], b2_up2[0], b2_up3[0], b2_up4[0]))\n b2_y_min = np.array(min(b2_up1[1], b2_up2[1], b2_up3[1], b2_up4[1]))\n b2_x_max = np.array(max(b2_down1[0], b2_down2[0], b2_down3[0], b2_down4[0]))\n b2_y_max = np.array(max(b2_down1[1], b2_down2[1], b2_down3[1], b2_down4[1]))\n\n r1_x_min = np.array(min(r1_up1[0], r1_up2[0], r1_up3[0], r1_up4[0]))\n r1_y_min = np.array(min(r1_up1[1], r1_up2[1], r1_up3[1], r1_up4[1]))\n r1_x_max = np.array(max(r1_down1[0], r1_down2[0], r1_down3[0], r1_down4[0]))\n r1_y_max = np.array(max(r1_down1[1], r1_down2[1], r1_down3[1], r1_down4[1]))\n #\n r2_x_min = np.array(min(r2_up1[0], r2_up2[0], r2_up3[0], r2_up4[0]))\n r2_y_min = np.array(min(r2_up1[1], r2_up2[1], r2_up3[1], r2_up4[1]))\n r2_x_max = np.array(max(r2_down1[0], r2_down2[0], r2_down3[0], r2_down4[0]))\n r2_y_max = np.array(max(r2_down1[1], r2_down2[1], r2_down3[1], r2_down4[1]))\n\n cv2.imshow('line', copyimg)\n\n # cv2.imwrite(savepath + img_name + \".jpg\", copyimg)\n cv2.waitKey(2)\n\nif __name__ == '__main__':\n camera = \"left\"\n\n savepath = \"/media/mmj/casia/202109/0907/img/4cars/\" + camera + \"/\"\n\n imgpath = \"/media/mmj/casia/202109/0907/4cars/0907_camera_raw_\" + camera + \"/\"\n logpath = \"/media/mmj/casia/202109/0907/4cars/0907log.log\"\n main(logpath, imgpath, savepath, camera)\n","repo_name":"DRL-CASIA/MVM3D","sub_path":"sample_datasets/label visuallization.py","file_name":"label visuallization.py","file_ext":"py","file_size_in_byte":13809,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"55"} +{"seq_id":"17289892952","text":"# Given a singly linked list and a key, count the number of occurrences of the given key in the linked list.\n# For example,\n# if the given linked list is 1->2->1->2->1->3->1 and the given key is 1, then the output should be 4\nfrom linkedlist import *\nlinkedlist1=LinkedList()\nsize = int(input())\ndata = input()\nnode = Node(data)\nlinkedlist1.head=node\nfor i in range(size-1):\n data = input()\n linkedlist1.pushAtEnd(data)\n# linkedlist1.printll()\nkey = input(\"what key do you want to count?\\n\")\ndef numberOfOccurance(linkedlist1, key):\n count=0\n temp = linkedlist1.head\n while temp:\n if temp.data is key:\n count+=1\n temp = temp.next\n print(\"{} is repeated {} times\".format(key,count))\n\nnumberOfOccurance(linkedlist1,key)","repo_name":"mehrzadian/data-structure-algorithm","sub_path":"Linked list/number-of-occurance.py","file_name":"number-of-occurance.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"10443603663","text":"import sensor, image, time\n\nfrom pyb import UART\n\n\n# UART COMMUNICATION\n\nuart = UART(3)\n\nuart.init(baudrate=115200, timeout_char=1)\n\n# CAMERA\n\nsensor.reset() \nsensor.set_pixformat(sensor.RGB565)\nsensor.set_framesize(sensor.QQVGA)\nsensor.skip_frames(time = 2000)\ntime.sleep(0.01)\n\ni = 0\n\nuart.write(\"Ciao da openMV\")\n\nwhile(True):\n uart.write(str(i))\n i += 1\n time.sleep(0.5)\n","repo_name":"Dave879/robot-v2","sub_path":"camera/Serial Test/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"55"} +{"seq_id":"35963789687","text":"n = int(input())\n\nanswer = 0\nrow = [0] * n\n# 퀸을 놓지 못하는 경우\n # 같은 열에 다른 퀸이 있는 경우\n # 왼쪽 대각선, 오른쪽 대각선에 다른 퀸이 있는 경우 False를 반환\ndef is_possible(x):\n for i in range(x):\n if row[x] == row[i] or abs(row[x] - row[i]) == abs(x-i):\n return False\n return True\n\n\ndef n_queens(x):\n global answer\n # x가 최종 깊이인 n이 되면 모든 퀸을 놓았았다는 것이 되므로 1을 추가\n if x == n:\n answer += 1\n\n else:\n for i in range(n):\n row[x] = i\n # 퀸을 높지 못하는 경우가 아니라면 그 다음 열을 비교한다.\n if is_possible(x):\n n_queens(x+1)\n\nn_queens(0)\nprint(answer)\n\n","repo_name":"Eunyeol-Lucas/python-algorithm","sub_path":"baekjoon/Python/백트래킹/9663_2.py","file_name":"9663_2.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"70094593772","text":"import pandas as pd\nimport pickle\n\nfrom os import listdir\nfrom torch.utils.data import Dataset\nfrom PIL import Image\n\nfrom transformers import LayoutLMv2Processor\n\nfrom torch.utils.data import DataLoader\n\nfrom transformers import LayoutLMv2ForTokenClassification\nimport torch\nfrom tqdm import tqdm\n\nimport numpy as np\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom seqeval.metrics import (\n classification_report,\n f1_score,\n precision_score,\n recall_score)\n\n#\n\ntrain = pd.read_pickle('data/cord/out/train.pkl')\nval = pd.read_pickle('data/cord/out/dev.pkl')\ntest = pd.read_pickle('data/cord/out/test.pkl')\n\n#\n\nreplacing_labels = {'menu.etc': 'O', 'mneu.itemsubtotal': 'O', 'menu.sub_etc': 'O', 'menu.sub_unitprice': 'O', 'menu.vatyn': 'O',\n 'void_menu.nm': 'O', 'void_menu.price': 'O', 'sub_total.othersvc_price': 'O'}\n\ndef replace_elem(elem):\n try:\n return replacing_labels[elem]\n except KeyError:\n return elem\ndef replace_list(ls):\n return [replace_elem(elem) for elem in ls]\ntrain[1] = [replace_list(ls) for ls in train[1]]\nval[1] = [replace_list(ls) for ls in val[1]]\ntest[1] = [replace_list(ls) for ls in test[1]]\n\n#\n\nall_labels = [item for sublist in train[1] for item in sublist] + [item for sublist in val[1] for item in sublist] + [item for sublist in test[1] for item in sublist]\nlabels = list(set(all_labels))\n# label2id = {label: idx for idx, label in enumerate(labels)}\n\nwith open('data/cord/label2id.pkl', 'rb') as t:\n label2id = pickle.load(t)\n\n#\n\nclass CORDDataset(Dataset):\n \"\"\"CORD dataset.\"\"\"\n\n def __init__(self, annotations, image_dir, processor=None, max_length=512):\n \"\"\"\n Args:\n annotations (List[List]): List of lists containing the word-level annotations (words, labels, boxes).\n image_dir (string): Directory with all the document images.\n processor (LayoutLMv2Processor): Processor to prepare the text + image.\n \"\"\"\n self.words, self.labels, self.boxes = annotations\n self.image_dir = image_dir\n self.image_file_names = [f for f in listdir(image_dir)]\n self.processor = processor\n\n def __len__(self):\n return len(self.image_file_names)\n\n def __getitem__(self, idx):\n # first, take an image\n item = self.image_file_names[idx]\n image = Image.open(self.image_dir + item).convert(\"RGB\")\n\n # get word-level annotations\n words = self.words[idx]\n boxes = self.boxes[idx]\n word_labels = self.labels[idx]\n\n assert len(words) == len(boxes) == len(word_labels)\n\n word_labels = [label2id[label] for label in word_labels]\n # use processor to prepare everything\n encoded_inputs = self.processor(image, words, boxes=boxes, word_labels=word_labels,\n padding=\"max_length\", truncation=True,\n return_tensors=\"pt\")\n\n # remove batch dimension\n for k, v in encoded_inputs.items():\n encoded_inputs[k] = v.squeeze()\n\n assert encoded_inputs.input_ids.shape == torch.Size([512])\n assert encoded_inputs.attention_mask.shape == torch.Size([512])\n assert encoded_inputs.token_type_ids.shape == torch.Size([512])\n assert encoded_inputs.bbox.shape == torch.Size([512, 4])\n assert encoded_inputs.image.shape == torch.Size([3, 224, 224])\n assert encoded_inputs.labels.shape == torch.Size([512])\n\n return encoded_inputs\n\n#\n\nprocessor = LayoutLMv2Processor.from_pretrained(\"microsoft/layoutlmv2-base-uncased\", revision=\"no_ocr\")\n\ntest_dataset = CORDDataset(annotations=test,\n image_dir='data/cord/CORD/test/image/',\n processor=processor)\n\n#\n\ntest_dataloader = DataLoader(test_dataset, batch_size=2)\n\n#\n\nmodel = LayoutLMv2ForTokenClassification.from_pretrained('models/cord',\n num_labels=len(labels))\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel.to(device)\n\n#\n\npreds_val = None\nout_label_ids = None\n\n# put model in evaluation mode\nmodel.eval()\nfor batch in tqdm(test_dataloader, desc=\"Evaluating\"):\n with torch.no_grad():\n input_ids = batch['input_ids'].to(device)\n bbox = batch['bbox'].to(device)\n image = batch['image'].to(device)\n attention_mask = batch['attention_mask'].to(device)\n token_type_ids = batch['token_type_ids'].to(device)\n labels = batch['labels'].to(device)\n\n # forward pass\n outputs = model(input_ids=input_ids, bbox=bbox, image=image, attention_mask=attention_mask,\n token_type_ids=token_type_ids, labels=labels)\n\n if preds_val is None:\n preds_val = outputs.logits.detach().cpu().numpy()\n out_label_ids = batch[\"labels\"].detach().cpu().numpy()\n else:\n preds_val = np.append(preds_val, outputs.logits.detach().cpu().numpy(), axis=0)\n out_label_ids = np.append(\n out_label_ids, batch[\"labels\"].detach().cpu().numpy(), axis=0\n )\n\n#\n\ndef results_test(preds, out_label_ids, labels):\n preds = np.argmax(preds, axis=2)\n\n label_map = {i: label for i, label in enumerate(labels)}\n\n out_label_list = [[] for _ in range(out_label_ids.shape[0])]\n preds_list = [[] for _ in range(out_label_ids.shape[0])]\n\n for i in range(out_label_ids.shape[0]):\n for j in range(out_label_ids.shape[1]):\n if out_label_ids[i, j] != -100:\n out_label_list[i].append(label_map[out_label_ids[i][j]])\n preds_list[i].append(label_map[preds[i][j]])\n\n results = {\n \"precision\": precision_score(out_label_list, preds_list),\n \"recall\": recall_score(out_label_list, preds_list),\n \"f1\": f1_score(out_label_list, preds_list),\n }\n return results, classification_report(out_label_list, preds_list)\n\n#\n\nlabels = list(set(all_labels))\nval_result, class_report = results_test(preds_val, out_label_ids, labels)\nprint(\"Overall results:\", val_result)\nprint(class_report)\n\n#\n\ndef process_document(image):\n print('PROCESS DOCUMENT')\n\n return image\n","repo_name":"katanaml/sparrow-research","sub_path":"sparrow-research/app/layoutlmv2_cord_evaluate.py","file_name":"layoutlmv2_cord_evaluate.py","file_ext":"py","file_size_in_byte":6164,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"55"} +{"seq_id":"13444844735","text":"import numpy as np\r\nfrom itertools import combinations_with_replacement\r\n\r\n\r\ndef normal_equations_estimate(x, y, alpha=1e-10):\r\n \"\"\"return the estimated coefficient vector for linear regression X @ w.T + e = y\"\"\"\r\n n = x.shape[1]\r\n return np.linalg.inv(x.T @ x + alpha*np.identity(n)) @ x.T @ y\r\n\r\n\r\ndef compute_test_mse(y_test, y_prediction):\r\n\r\n return np.linalg.norm(y_test - y_prediction) ** 2 / (y_test.shape[0] * np.linalg.norm(y_test)**2)\r\n\r\n\r\ndef normalize(x):\r\n \"\"\"Return the standardized matrix of x, the mean vector, and the column variances vector\"\"\"\r\n mean = np.sum(x, axis=0) / x.shape[0]\r\n variance = np.diag(x.T @ x)\r\n\r\n return (x - mean) / np.sqrt(variance), mean, variance\r\n\r\n\r\ndef adding_polynomial_terms(x, degree=[]):\r\n \"\"\"Adding new terms of a polynomial in Rn w.r.t to the degree parameters\"\"\"\r\n n = x.shape[1]\r\n features = range(n)\r\n\r\n for i in range(len(degree)):\r\n j = degree[i]\r\n for r in combinations_with_replacement(features, j):\r\n new_col = np.ones(x.shape[0])\r\n for i in r:\r\n new_col = new_col * x[:, i]\r\n\r\n new_col = new_col.reshape(x.shape[0], 1)\r\n x = np.concatenate((x, new_col), axis=1)\r\n\r\n return x\r\n","repo_name":"atn-iastate/EE425_homework","sub_path":"Project/king_county/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"73794256171","text":"import pandas as pd\nimport wptools\nimport json\n\n\ndef get_profiles_from_titles(input_csv_path, output_json_path):\n df = pd.read_csv(input_csv_path)\n title_list = [profile for profile in df.get('title')]\n data = {}\n for idx in range(0, len(title_list)):\n try:\n dict_img = wptools.page(title_list[idx]).get().data.get('wikidata')\n dict_img.update({'url_img': str(wptools.page(title_list[idx]).get().data.get('image')[0].get('url', \"\")) if wptools.page(title_list[idx]).get().data.get('image',None) is not None else \"\"})\n data.update({title_list[idx]: dict_img})\n with open(output_json_path, \"w+\") as output:\n json.dump(data, output)\n except:\n print(\"Caught it!\")\n\n\nget_profiles_from_titles(\n input_csv_path='/home/abhi/IdeaProjects/charvalue-2021/dataScrapperPython/layer_1_scrapped_data/data/wiki_page_id_title_politicians_india.csv',\n output_json_path='/home/abhi/IdeaProjects/charvalue-2021/dataScrapperPython/layer_2_profile_scrapped/data/profile_data_politicians.json'\n)\n","repo_name":"abhishekvermax/charvalue-scrapper-python-2021","sub_path":"layer_2_profile_scrapped/scrapper/profiles_db.py","file_name":"profiles_db.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"7751287573","text":"import asyncio\nimport logging\nfrom typing import Type\nfrom unittest.mock import MagicMock\n\nimport jsonschema\nimport pytest\n\nimport lightbus\nimport lightbus.path\nfrom lightbus.client.commands import SendResultCommand\nfrom lightbus.config import Config\nfrom lightbus.exceptions import LightbusTimeout, LightbusWorkerError\nfrom lightbus.transports.redis.event import StreamUse\nfrom lightbus.utilities.async_tools import cancel\nfrom lightbus.utilities.features import Feature\nfrom lightbus.utilities.testing import BusQueueMockerContext\nfrom tests.conftest import Worker\n\npytestmark = pytest.mark.integration\n\nstream_use_test_data = [StreamUse.PER_EVENT, StreamUse.PER_API]\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.asyncio\n@pytest.mark.timeout(5)\n@pytest.mark.also_run_in_child_thread\nasync def test_rpc_simple(bus: lightbus.path.BusPath, dummy_api):\n \"\"\"Full rpc call integration test\"\"\"\n bus.client.register_api(dummy_api)\n\n await bus.client.consume_rpcs(apis=[dummy_api])\n\n result = await bus.my.dummy.my_proc.call_async(field=\"Hello! 😎\")\n assert result == \"value: Hello! 😎\"\n\n\n@pytest.mark.asyncio\nasync def test_rpc_timeout(bus: lightbus.path.BusPath, dummy_api):\n \"\"\"Full rpc call integration test\"\"\"\n bus.client.register_api(dummy_api)\n\n await bus.client.consume_rpcs(apis=[dummy_api])\n\n with pytest.raises(LightbusTimeout):\n await bus.my.dummy.sudden_death.call_async(n=0)\n\n\n@pytest.mark.asyncio\nasync def test_rpc_error(bus: lightbus.path.BusPath, dummy_api, worker: Worker, caplog):\n \"\"\"Test what happens when the remote procedure throws an error\"\"\"\n bus.client.register_api(dummy_api)\n caplog.set_level(logging.ERROR)\n\n bus.client.register_api(dummy_api)\n async with worker(bus):\n with pytest.raises(LightbusWorkerError):\n await bus.my.dummy.general_error.call_async()\n\n # Event loop not stopped, because RPCs should continue to be served\n # even in the case of an error\n assert not bus.client.stop_loop.called\n assert len(caplog.records) == 1, caplog.records\n assert \"Oh no, there was some kind of error\" in caplog.records[0].message\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\n \"stream_use\", stream_use_test_data, ids=[\"stream_per_event\", \"stream_per_api\"]\n)\nasync def test_event_simple(\n bus: lightbus.path.BusPath, dummy_api, stream_use, redis_client, worker: Worker\n):\n \"\"\"Full event integration test\"\"\"\n bus.client.set_features([Feature.EVENTS])\n bus.client.register_api(dummy_api)\n\n event_transport_pool = bus.client.transport_registry.get_event_transport(\"default\")\n async with event_transport_pool as t1, event_transport_pool as t2:\n # The pool will need two transports for this, so get two from the pool and set\n # their stream_use config option\n t1.stream_use = stream_use\n t2.stream_use = stream_use\n\n received_messages = []\n\n async def listener(event_message, **kwargs):\n nonlocal received_messages\n received_messages.append(event_message)\n\n bus.my.dummy.my_event.listen(listener, listener_name=\"test\")\n\n async with worker(bus):\n await asyncio.sleep(0.1)\n await bus.my.dummy.my_event.fire_async(field=\"Hello! 😎\")\n await asyncio.sleep(0.1)\n\n assert len(received_messages) == 1\n assert received_messages[0].kwargs == {\"field\": \"Hello! 😎\"}\n assert received_messages[0].api_name == \"my.dummy\"\n assert received_messages[0].event_name == \"my_event\"\n assert received_messages[0].native_id\n\n # Check the event was acknowledged\n stream_name = (\n \"my.dummy.my_event:stream\" if stream_use == StreamUse.PER_EVENT else \"my.dummy.*:stream\"\n )\n info = await redis_client.xinfo_groups(stream=stream_name)\n assert (\n len(info) == 1\n ), \"There should only be one consumer group, that for out event listener above\"\n assert info[0][b\"pending\"] == 0\n\n\n@pytest.mark.asyncio\nasync def test_ids(\n bus: lightbus.path.BusPath, dummy_api, queue_mocker: Type[BusQueueMockerContext]\n):\n \"\"\"Ensure the id comes back correctly\"\"\"\n bus.client.register_api(dummy_api)\n\n await bus.client.consume_rpcs(apis=[dummy_api])\n\n with queue_mocker(bus.client) as q:\n await bus.my.dummy.my_proc.call_async(field=\"foo\")\n\n send_result_command = q.rpc_result.to_transport.commands.get(SendResultCommand)\n\n assert send_result_command.rpc_message.id\n assert send_result_command.message.id\n assert send_result_command.message.rpc_message_id == send_result_command.rpc_message.id\n\n\nclass ApiA(lightbus.Api):\n event_a = lightbus.Event()\n\n class Meta:\n name = \"api_a\"\n\n def rpc_a(self):\n return \"A\"\n\n\nclass ApiB(lightbus.Api):\n event_b = lightbus.Event()\n\n class Meta:\n name = \"api_b\"\n\n def rpc_b(self):\n return \"b\"\n\n\n@pytest.mark.asyncio\nasync def test_multiple_rpc_transports(loop, redis_server_url, redis_server_b_url, consume_rpcs):\n \"\"\"Configure a bus with two redis transports and ensure they write to the correct redis servers\"\"\"\n redis_url_a = redis_server_url\n redis_url_b = redis_server_b_url\n\n logging.warning(f\"Server A url: {redis_url_a}\")\n logging.warning(f\"Server B url: {redis_url_b}\")\n\n config = Config.load_dict(\n {\n \"bus\": {\"schema\": {\"transport\": {\"redis\": {\"url\": redis_url_a}}}},\n \"apis\": {\n \"default\": {\n \"rpc_transport\": {\"redis\": {\"url\": redis_url_a}},\n \"result_transport\": {\"redis\": {\"url\": redis_url_a}},\n },\n \"api_b\": {\n \"rpc_transport\": {\"redis\": {\"url\": redis_url_b}},\n \"result_transport\": {\"redis\": {\"url\": redis_url_b}},\n },\n },\n }\n )\n\n bus = lightbus.create(config=config)\n bus.client.disable_proxy()\n bus.client.register_api(ApiA())\n bus.client.register_api(ApiB())\n\n task = asyncio.ensure_future(consume_rpcs(bus))\n await asyncio.sleep(0.1)\n\n await bus.api_a.rpc_a.call_async()\n await bus.api_b.rpc_b.call_async()\n await asyncio.sleep(0.1)\n\n await cancel(task)\n await bus.client.close_async()\n\n\n@pytest.mark.asyncio\nasync def test_multiple_event_transports(\n loop, redis_server_url, redis_server_b_url, create_redis_client\n):\n \"\"\"Configure a bus with two redis transports and ensure they write to the correct redis servers\"\"\"\n redis_url_a = redis_server_url\n redis_url_b = redis_server_b_url\n\n logging.warning(f\"Server A URL: {redis_url_a}\")\n logging.warning(f\"Server B URL: {redis_url_b}\")\n\n config = Config.load_dict(\n {\n \"bus\": {\"schema\": {\"transport\": {\"redis\": {\"url\": redis_url_a}}}},\n \"apis\": {\n \"default\": {\n \"event_transport\": {\n \"redis\": {\"url\": redis_url_a, \"stream_use\": StreamUse.PER_EVENT.value}\n }\n },\n \"api_b\": {\n \"event_transport\": {\n \"redis\": {\"url\": redis_url_b, \"stream_use\": StreamUse.PER_EVENT.value}\n }\n },\n },\n }\n )\n\n bus = lightbus.create(config=config)\n bus.client.disable_proxy()\n bus.client.register_api(ApiA())\n bus.client.register_api(ApiB())\n await asyncio.sleep(0.1)\n\n await bus.api_a.event_a.fire_async()\n await bus.api_b.event_b.fire_async()\n\n redis_a = await create_redis_client(address=redis_server_url)\n redis_b = await create_redis_client(address=redis_server_b_url)\n\n assert await redis_a.xrange(\"api_a.event_a:stream\")\n assert await redis_a.xrange(\"api_b.event_b:stream\") == []\n\n assert await redis_b.xrange(\"api_a.event_a:stream\") == []\n assert await redis_b.xrange(\"api_b.event_b:stream\")\n\n await bus.client.close_async()\n\n\n@pytest.mark.asyncio\nasync def test_validation_rpc(loop, bus: lightbus.path.BusPath, dummy_api, mocker):\n \"\"\"Check validation happens when performing an RPC\"\"\"\n bus.client.register_api(dummy_api)\n config = Config.load_dict({\"apis\": {\"default\": {\"validate\": True, \"strict_validation\": True}}})\n bus.client.config = config\n mocker.patch(\"jsonschema.validate\", autospec=True)\n\n async def co_consume_rpcs():\n return await bus.client.consume_rpcs(apis=[dummy_api])\n\n await bus.client.schema.add_api(dummy_api)\n await bus.client.schema.save_to_bus()\n await bus.client.schema.load_from_bus()\n\n consume_task = asyncio.ensure_future(co_consume_rpcs(), loop=loop)\n\n await asyncio.sleep(0.1)\n result = await bus.my.dummy.my_proc.call_async(field=\"Hello\")\n\n await cancel(consume_task)\n\n assert result == \"value: Hello\"\n\n # Validate gets called\n jsonschema.validate.assert_called_with(\n \"value: Hello\",\n {\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"title\": \"RPC my.dummy.my_proc() response\",\n \"type\": \"string\",\n },\n )\n\n\n@pytest.mark.asyncio\nasync def test_validation_event(\n loop, bus: lightbus.path.BusPath, dummy_api, mocker, worker: Worker\n):\n \"\"\"Check validation happens when firing an event\"\"\"\n bus.client.register_api(dummy_api)\n config = Config.load_dict({\"apis\": {\"default\": {\"validate\": True, \"strict_validation\": True}}})\n bus.client.config = config\n mocker.patch(\"jsonschema.validate\", autospec=True)\n\n async def co_listener(*a, **kw):\n pass\n\n await bus.client.schema.add_api(dummy_api)\n await bus.client.schema.save_to_bus()\n await bus.client.schema.load_from_bus()\n\n bus.client.listen_for_event(\"my.dummy\", \"my_event\", co_listener, listener_name=\"test\")\n\n async with worker(bus):\n await asyncio.sleep(0.1)\n await bus.my.dummy.my_event.fire_async(field=\"Hello\")\n await asyncio.sleep(0.001)\n\n # Validate gets called\n jsonschema.validate.assert_called_with(\n {\"field\": \"Hello\"},\n {\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": False,\n \"properties\": {\"field\": {\"type\": \"string\"}},\n \"required\": [\"field\"],\n \"title\": \"Event my.dummy.my_event parameters\",\n },\n )\n\n\n@pytest.mark.asyncio\nasync def test_listen_to_multiple_events_across_multiple_transports(\n loop, redis_server_url, redis_server_b_url, worker: Worker\n):\n redis_url_a = redis_server_url\n redis_url_b = redis_server_b_url\n\n logging.warning(f\"Server A URL: {redis_url_a}\")\n logging.warning(f\"Server B URL: {redis_url_b}\")\n\n config = Config.load_dict(\n {\n \"bus\": {\"schema\": {\"transport\": {\"redis\": {\"url\": redis_url_a}}}},\n \"apis\": {\n \"default\": {\"event_transport\": {\"redis\": {\"url\": redis_url_a}}},\n \"api_b\": {\"event_transport\": {\"redis\": {\"url\": redis_url_b}}},\n },\n }\n )\n\n bus = lightbus.create(config=config)\n bus.client.disable_proxy()\n bus.client.register_api(ApiA())\n bus.client.register_api(ApiB())\n await asyncio.sleep(0.1)\n\n calls = 0\n\n def listener(*args, **kwargs):\n nonlocal calls\n calls += 1\n\n bus.client.listen_for_events(\n events=[(\"api_a\", \"event_a\"), (\"api_b\", \"event_b\")], listener=listener, listener_name=\"test\"\n )\n\n async with worker(bus):\n await asyncio.sleep(0.1)\n await bus.api_a.event_a.fire_async()\n await bus.api_b.event_b.fire_async()\n await asyncio.sleep(0.1)\n\n assert calls == 2\n\n\n@pytest.mark.asyncio\nasync def test_event_exception_in_listener_realtime(\n bus: lightbus.path.BusPath, new_bus, worker: Worker, dummy_api, redis_client\n):\n \"\"\"Start a listener (which errors) and then add events to the stream.\n The listener will load them one-by-one.\"\"\"\n bus.client.register_api(dummy_api)\n received_messages = []\n\n async def listener(event_message, **kwargs):\n nonlocal received_messages\n received_messages.append(event_message)\n raise Exception()\n\n worker_bus = new_bus()\n bus.client.proxied_client.stop_loop = MagicMock()\n worker_bus.my.dummy.my_event.listen(\n listener, listener_name=\"test_listener\", bus_options={\"since\": \"0\"}\n )\n\n async with worker(worker_bus, raise_errors=False):\n await bus.client.lazy_load_now()\n await asyncio.sleep(0.1)\n await bus.my.dummy.my_event.fire_async(field=\"Hello! 😎\")\n await bus.my.dummy.my_event.fire_async(field=\"Hello! 😎\")\n await bus.my.dummy.my_event.fire_async(field=\"Hello! 😎\")\n await bus.my.dummy.my_event.fire_async(field=\"Hello! 😎\")\n await bus.my.dummy.my_event.fire_async(field=\"Hello! 😎\")\n await asyncio.sleep(0.1)\n\n # Ensure the server stopped the loop (we've mocked this otherwise this\n # test would be stopped too)\n assert worker_bus.client.stop_loop.called\n\n # Died when processing first message, so we only saw one message\n assert len(received_messages) == 1\n\n # Now check we have not acked any messages\n\n messages = await redis_client.xrange(\"my.dummy.my_event:stream\")\n # Messages 0 is the noop message used to create the stream\n message_ids = [id_ for id_, *_ in messages]\n\n pending_messages = await redis_client.xpending(\n \"my.dummy.my_event:stream\", \"test_service-test_listener\", \"-\", \"+\", 10, \"test_consumer\"\n )\n\n pending_message_ids = [id_ for id_, *_ in pending_messages]\n\n # The erroneous message is still pending\n assert len(pending_message_ids) == 1\n\n\n@pytest.mark.asyncio\nasync def test_event_exception_in_listener_batch_fetch(\n bus: lightbus.path.BusPath, dummy_api, redis_client, worker: Worker\n):\n \"\"\"Add a number of events to a stream then startup a listener which errors.\n The listener will fetch them all at once.\"\"\"\n bus.client.register_api(dummy_api)\n bus.client.features = [Feature.EVENTS]\n received_messages = []\n\n async def listener(event_message, **kwargs):\n nonlocal received_messages\n received_messages.append(event_message)\n raise Exception()\n\n await bus.client.lazy_load_now()\n\n await bus.my.dummy.my_event.fire_async(field=\"Hello! 😎\")\n await bus.my.dummy.my_event.fire_async(field=\"Hello! 😎\")\n await bus.my.dummy.my_event.fire_async(field=\"Hello! 😎\")\n\n bus.my.dummy.my_event.listen(\n listener, listener_name=\"test_listener\", bus_options={\"since\": \"0\"}\n )\n\n async with worker(bus):\n await asyncio.sleep(0.2)\n\n # Died when processing first message, so we only saw one message\n assert len(received_messages) == 1\n\n # Now check we have not acked any of them\n\n messages = await redis_client.xrange(\"my.dummy.my_event:stream\")\n # No message0 here because the stream already exists (because we've just added events to it)\n message1_id, message2_id, message3_id = [id_ for id_, *_ in messages]\n\n pending_messages = await redis_client.xpending(\n \"my.dummy.my_event:stream\", \"test_service-test_listener\", \"-\", \"+\", 10, \"test_consumer\"\n )\n\n assert len(pending_messages) == 3\n","repo_name":"adamcharnock/lightbus","sub_path":"tests/transports/redis/test_integration_redis.py","file_name":"test_integration_redis.py","file_ext":"py","file_size_in_byte":15104,"program_lang":"python","lang":"en","doc_type":"code","stars":189,"dataset":"github-code","pt":"55"} +{"seq_id":"4504339213","text":"import random\nN =[]\nestado = True\nwhile estado == True:\n x = int (input(\"Ingrese numero entre 1 y 10:\"))\n while x > 10:\n x = int (input (\"Ingrese un numero entre 1 y 10:\"))\n if x < 10: \n N.append (x)\n if len(N) == 6:\n estado = False\n print (N)\n\n\nM = []\nA =[]\nfor i in range (1,10):\n\n M.append (i)\nprint (M)\n \nc = random.choice(M)\n\nwhile len(A)< 6:\n A.append(c)\nprint (A)\n\ncont = 0\nfor i in N:\n for j in A:\n if i == j:\n cont = cont +1 \nprint (cont)\n\nif cont == 6:\n print (\"Ha ganado 6 millones de soles\")\nelif cont == 5:\n print (\"Ha ganado 100 mil soles\")\nelif cont == 4:\n print (\"Siga intentado\")","repo_name":"AndreaCH17/PC2","sub_path":"Pregunta03.py","file_name":"Pregunta03.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"14585837704","text":"# Built-in modules #\nimport tempfile, datetime, dateutil, hashlib\n\n# One liners #\nflatter = lambda x: [item for sublist in x for item in sublist]\n\n################################################################################\ndef new_temp_path(**kwargs):\n \"\"\"A new temporary path\"\"\"\n handle = tempfile.NamedTemporaryFile(**kwargs)\n path = handle.name\n handle.close()\n return path\n\n################################################################################\nclass GenWithLength(object):\n \"\"\"A generator with a length attribute\"\"\"\n def __init__(self, gen, length): self.gen, self.length = gen, length\n def __iter__(self): return self.gen\n def __len__(self): return self.length\n\n################################################################################\ndef pretty_now():\n \"\"\"Returns some thing like '2014-07-24 11:12:45 CEST+0200'\"\"\"\n now = datetime.datetime.now(dateutil.tz.tzlocal())\n return now.strftime(\"%Y-%m-%d %H:%M:%S %Z%z\")\n\n################################################################################\ndef md5sum(file_path, blocksize=65536):\n \"\"\"Compute the md5 of a file. Pretty fast.\"\"\"\n md5 = hashlib.md5()\n with open(file_path, \"rb\") as f:\n for block in iter(lambda: f.read(blocksize), \"\"):\n md5.update(block)\n return md5.hexdigest()\n\n################################################################################\ndef download_from_url(source, destination, progress=False, uncompress=True):\n \"\"\"Download a file from an URL and place it somewhere. Like wget.\n Uses requests and tqdm to display progress if you want.\n By default it will uncompress files.\"\"\"\n # Modules #\n from tqdm import tqdm\n import requests\n from autopaths import FilePath\n # Check destination exists #\n destination = FilePath(destination)\n destination.directory.create_if_not_exists()\n # Over HTTP #\n response = requests.get(source, stream=True)\n total_size = int(response.headers.get('content-length'))\n block_size = total_size/1024\n # Do it #\n with open(destination, \"wb\") as handle:\n if progress:\n for data in tqdm(response.iter_content(chunk_size=block_size), total=1024): handle.write(data)\n else:\n for data in response.iter_content(chunk_size=block_size): handle.write(data)\n # Uncompress #\n if uncompress:\n with open(destination) as f: header = f.read(4)\n if header == \"PK\\x03\\x04\": unzip(destination, inplace=True)\n # Add other compression formats here\n # Return #\n return destination\n\n################################################################################\ndef unzip(source, destination=None, inplace=False, single=True):\n \"\"\"Unzip a standard zip file. Can specify the destination of the\n uncompressed file, or just set inplace=True to delete the original.\"\"\"\n # Load #\n import zipfile, tempfile, shutil\n # Check #\n assert zipfile.is_zipfile(source)\n # Load #\n z = zipfile.ZipFile(source)\n if single or inplace: assert len(z.infolist()) == 1\n # Single file #\n if single:\n member = z.infolist()[0]\n tmpdir = tempfile.mkdtemp() + '/'\n z.extract(member, tmpdir)\n z.close()\n if inplace: shutil.move(tmpdir + member.filename, source)\n else: shutil.move(tmpdir + member.filename, destination)\n # Multifile - no security, dangerous #\n if not single:\n z.extractall()\n","repo_name":"xapple/seqenv","sub_path":"seqenv/common/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"55"} +{"seq_id":"29763089393","text":"import sqlite3\nimport pandas as pd\nimport pandas.io.sql as psql\n\n# sqlite3に接続\ncon = sqlite3.connect('npbdb')\ncon2 = sqlite3.connect('db.sqlite3')\ncur = con2.cursor()\n\n# TABLE作成\n#cur.execute('DROP TABLE pitchingdata')\n#cur.execute('CREATE TABLE pitchingdata (kyusyumark,numberofpitch,balltype,ballspeed,result,course,first,second,third,hometeam,visitorteam,pitcher,batter,time,B,S,O,hit,walk,out,strikeout)')\n\ndf = psql.read_sql('select * from pitchingdata;', con)\ndf.head(10).to_sql('blog_pitchingdata',con2, if_exists='append', index=None)\ndf2 = psql.read_sql('select * from blog_pitchingdata;', con2)\n\nprint(df2)\n\ncon2.commit()\ncon.close()\ncon2.close()\n","repo_name":"sordes1219/npbproject","sub_path":"import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"21784221207","text":"import os\nfrom datetime import timedelta\n\nfrom airflow import DAG\nfrom airflow.providers.docker.operators.docker import DockerOperator\nfrom airflow.utils.dates import days_ago\n\ndefault_args = {\n \"owner\": \"airflow\",\n \"retries\": 1,\n \"retry_delay\": timedelta(minutes=5),\n}\n\nwith DAG(\n \"get_predict\",\n default_args=default_args,\n schedule_interval=\"@daily\",\n start_date=days_ago(0),\n) as dag:\n get_predict = DockerOperator(\n image=\"airflow-get-predict\",\n command=\"--input-dir-data /data/processed/{{ ds }} --input-dir-model /data/models/{{ ds }} --output-dir /data/predictions/{{ ds }}\",\n network_mode=\"bridge\",\n task_id=\"docker-airflow-get-predict\",\n do_xcom_push=False,\n volumes=[\"/home/vadim/MADE/vzavadskyi/data:/data\"],\n )\n","repo_name":"made-ml-in-prod-2021/vzavadskyi","sub_path":"dags/get_predict.py","file_name":"get_predict.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"8403620650","text":"import pytest\nimport unittest.mock\nfrom dataclasses import dataclass\nfrom pika import URLParameters\n\nfrom rectifier import settings\nfrom rectifier.config import Config, CoordinatorConfig, QueueConfig, AppConfig, AppMode\n\nfrom .rabbitmq_mock import RabbitMQAPIMock\n\n\nclass TestableEnv:\n \"\"\"Wrapper for providing mocked services and default\n test-able configuration.\"\"\"\n\n def __init__(self):\n self.rabbitmq = RabbitMQAPIMock()\n\n apps = dict(\n rectifier=AppConfig(\n mode=AppMode.SCALE,\n queues=dict(\n queue=QueueConfig(\n intervals=[1, 10, 20, 30],\n workers=[1, 5, 50, 500],\n cooldown=600,\n queue_name='queue',\n consumers_formation_name='worker_queue',\n )\n ),\n )\n )\n\n coordinator_config = CoordinatorConfig(apps=apps)\n self.config = Config(coordinator_config=coordinator_config)\n\n def start(self):\n \"\"\"Starts the test-able environment.\"\"\"\n\n self.rabbitmq.start()\n\n def stop(self):\n \"\"\"Stops the test-able environment.\"\"\"\n\n self.rabbitmq.stop()\n\n def rabbit_mq_uri(self, app):\n host = '%s:%s' % (self.rabbitmq.host, self.rabbitmq.port)\n return 'amqp://%s:%s@%s/%s' % ('guest', 'guest', host, app)\n\n\n@pytest.fixture(scope='function')\ndef env():\n \"\"\"Provides a test-able environment to the test,\n this includes mocked configurations and services\n as well as utilities to faciliate testing.\"\"\"\n\n env = TestableEnv()\n env.start()\n settings.RABBIT_MQ_SECURE = False\n\n with unittest.mock.patch(\n 'pika.URLParameters.host', new_callable=unittest.mock.PropertyMock\n ) as p:\n p.return_value = f'127.0.0.1:{env.rabbitmq.port}'\n yield env\n\n env.stop()\n","repo_name":"SectorLabs/heroku-rectifier","sub_path":"tests/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"55"} +{"seq_id":"40139595044","text":"import os\nimport sys\nimport random\nimport math\n\nimport numpy as np\nfrom config import parse_arguments\nfrom datasets import DiseaseDataset\nfrom models.resnet import resnet50, resnet152\nfrom models.vgg import vgg16\nfrom models.inception_v3 import Inception3\n\nimport pandas as pd\nfrom utils_folder.utils import AverageMeter, ProgressMeter\nfrom utils_folder.eval_metric import *\n\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torch.backends.cudnn as cudnn\n\nfrom tensorboardX import SummaryWriter\n\nimport time\nimport pathlib\nfrom datetime import datetime\nimport cv2\n\n\ndef evaluate(args, loader, model, device, num_classes , class_list):\n\n model.eval()\n correct = 0\n total = 0\n overall_logits = []\n overall_preds = []\n overall_gts = []\n\n for iter_, (imgs, labels) in enumerate(iter(loader)):\n\n imgs = imgs.to(device)\n labels = labels.to(device, dtype=torch.long)\n\n outputs = model(imgs)\n outputs = torch.sigmoid(outputs)\n outputs_preds = outputs.clone()\n overall_logits += outputs.cpu().detach().numpy().tolist()\n\n outputs_preds[outputs_preds >= 0.5] = 1\n outputs_preds[outputs_preds < 0.5] = 0\n total += labels.size(0) * labels.size(1)\n correct += torch.sum(outputs_preds == labels.data).item()\n\n ## For evaluation\n overall_preds += outputs_preds.cpu().detach().numpy().tolist()\n overall_gts += labels.cpu().detach().numpy().tolist()\n\n print('[*] Test Acc: {:5f}'.format(100.*correct/total))\n \n AUROCs = compute_AUCs(overall_gts, overall_logits, num_classes , class_list)\n AUROC_avg = np.array(AUROCs).mean()\n\n print('The average AUROC is {AUROC_avg:.3f}'.format(AUROC_avg=AUROC_avg))\n for i in range(num_classes):\n if class_list[i] == 'Fracture':\n continue\n print('The AUROC of {} is {}'.format(class_list[i], AUROCs[i]))\n\n cnf_matrix = compute_confusion_matrix(overall_gts, overall_preds, num_classes , class_list)\n \n for label, matrix in cnf_matrix.items():\n print(\"Confusion matrix for label {}:\".format(label))\n get_mertrix(matrix, args.log_dir, class_list)\n\ndef main(args):\n ##### Initial Settings\n csv_data = pd.read_csv(args.csv_file)\n class_list = csv_data.keys().tolist()[5:] # warning\n print(\"[*] class list : \" , class_list)\n num_classes = args.num_class\n downstream = '{}_{}_class'.format(args.downstream_name, num_classes)\n\n print('\\n[*****] ', downstream)\n print('[*] using {} bit images'.format(args.bit))\n\n # device check & pararrel\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n print('[*] device: ', device)\n\n # path setting\n pathlib.Path(args.log_dir).mkdir(parents=True, exist_ok=True)\n folder_name = '{}_{}'.format(args.message , downstream)\n \n args.log_dir = os.path.join(args.log_dir, folder_name)\n\n pathlib.Path(args.log_dir).mkdir(parents=True, exist_ok=True)\n \n # for log\n f = open(os.path.join(args.log_dir,'arguments.txt'), 'w')\n f.write(str(args))\n f.close()\n print('[*] log directory: {} '.format(args.log_dir))\n \n if args.seed is not None:\n random.seed(args.seed)\n torch.manual_seed(args.seed)\n os.environ['PYTHONHASHSEED'] = str(args.seed) # os 자체의 seed 고정\n np.random.seed(args.seed) # numpy seed 고정 \n torch.cuda.manual_seed(args.seed) # cudnn seed 고정\n torch.backends.cudnn.deterministic = True # cudnn seed ���정(nn.Conv2d)\n torch.backends.cudnn.benchmark = False # CUDA 내부 연산에서 가장 빠른 알고리즘을 찾아 수행\n\n\n # select network\n print('[*] build network... backbone: {}'.format(args.backbone))\n if args.backbone == 'resnet50':\n model = resnet50(num_classes=args.num_class)\n elif args.backbone == 'vgg':\n model = vgg16(num_classes=args.num_class)\n elif args.backbone == 'densenet':\n model = densenet169(num_classes=args.num_class)\n elif args.backbone == 'inception':\n model = Inception3(num_classes=args.num_class)\n else:\n ValueError('Have to set the backbone network in [resnet, vgg, densenet]')\n\n model = model.to(device)\n\n if args.resume is True:\n checkpoint = torch.load(args.pretrained)\n pretrained_dict = checkpoint['state_dict']\n pretrained_dict = {key.replace(\"module.\", \"\"): value for key, value in pretrained_dict.items()}\n model.load_state_dict(pretrained_dict)\n print(\"load model completed\")\n else:\n ValueError('Have to input a pretrained network path')\n\n ##### Dataset & Dataloader\n print('[*] prepare datasets & dataloader...')\n test_datasets = DiseaseDataset(args.test_path, 'test', args.img_size, args.bits, args)\n test_loader = torch.utils.data.DataLoader(test_datasets, batch_size=1, \n num_workers=args.w, pin_memory=True, drop_last=True)\n \n ##### Train & Test\n print('[*] start a test')\n evaluate(args, test_loader, model, device, num_classes , class_list)\n \nif __name__ == '__main__':\n argv = parse_arguments(sys.argv[1:])\n main(argv)\n","repo_name":"mi2rl/CheSS","sub_path":"downstream/classification/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":5104,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"55"} +{"seq_id":"38790990323","text":"import cv2\r\nimport glob\r\nimport os\r\nimport os.path\r\n\r\nfiles = glob.glob(\"C:\\\\Users\\\\Divya\\\\Desktop\\\\original_images\\\\*.png\")\r\nout = \"C:\\\\Users\\\\Divya\\\\Desktop\\\\out\\\\\"\r\nif not os.path.isdir(out):\r\n os.mkdir(out)\r\ncount = 0\r\nfor file in files:\r\n count += 1\r\n img = cv2.imread(file)\r\n crop_img = img[642:1463, 720:1090] \r\n try:\r\n\r\n cv2.imwrite(out + \"img\" + str(count) + \".png\", crop_img)\r\n if count >= 100:\r\n break\r\n print(count, \"cropped successfull....\", file)\r\n except:\r\n continue","repo_name":"Divyasailaxmi/Python-Programs","sub_path":"crop.py","file_name":"crop.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"72029484972","text":"import pandas as pd\nimport numpy as np\n\nfrom sklearn.feature_selection import chi2\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.neighbors.classification import KNeighborsClassifier\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.preprocessing import normalize\nfrom sklearn.preprocessing import OneHotEncoder\nfrom imblearn.over_sampling import SMOTE as smt\n\nn_fold = 10\n\n#####################\n# DISCRETIZER #\n#####################\ndef columnisbinary(column):\n col = column.unique()\n\n for val in col:\n if val == 0 or val == 1 or val is True or val is False:\n pass\n else:\n return False\n\n return True\n\n\ndef widthnumericpreprocess(df, bins):\n # label_encoder = LabelEncoder()\n dummy_encoder = OneHotEncoder()\n pdf = pd.DataFrame()\n\n bin_map = {}\n numbs = []\n\n for atrib in df:\n\n if columnisbinary(df[atrib]):\n pdf = pd.concat([pdf, df[atrib]], axis=1)\n\n\n elif df[atrib].dtype == np.float64 or df[atrib].dtype == np.int64:\n\n # can make bins\n if df[atrib].nunique() >= bins:\n intervals, bin1 = pd.cut(df[atrib], bins, retbins=True)\n\n vec = []\n\n counter = 0\n\n while counter < len(bin1) - 1:\n a = f\"]{bin1[counter]} , {bin1[counter+1]}]\"\n vec.append([a, counter])\n counter += 1\n\n # store bin mapping (binval, binID)\n bin_map[atrib] = vec\n\n vec = df[atrib]\n\n for val in range(len(df[atrib])):\n\n counter = 0\n\n while df.iloc[val][atrib] > bin1[counter + 1]:\n counter += 1\n\n vec.at[val] = counter\n\n numbs = []\n\n for i in vec:\n if i not in numbs:\n numbs.append(int(i))\n\n numbs = sorted(numbs, reverse=False)\n\n # print(range(len(bin1) - 2 ))\n\n # Fitting One Hot Encoding on train data\n temp = dummy_encoder.fit_transform(vec.values.reshape(-1, 1)).toarray()\n\n # print(temp)\n # Changing encoded features into a dataframe with new column names\n temp = pd.DataFrame(temp,\n columns=[(atrib + \"_\" + str(i)) for i in numbs])\n # In side by side concatenation index values should be same\n # Setting the index values similar to the data frame\n elif df[atrib].nunique() == 2:\n vals = df[atrib].unique()\n temp = df[atrib]\n\n pair = f\"old: {vals[0]} new 0, old: {vals[1]} new 1\"\n bin_map[atrib] = pair\n\n temp = temp.map({vals[0]: 0, vals[1]: 1})\n\n\n else:\n print('debug \\n')\n return\n # temp = temp.set_index(df.index.values)\n # adding the new One Hot Encoded varibales to the dataframe\n # print(pdf)\n\n pdf = pd.concat([pdf, temp], axis=1)\n\n # print(pdf)\n\n # column is not binary and cannot be discritized by formula\n else:\n print('column with n dif values less than bins or non-numeric')\n\n return pdf, bin_map\n\n######################\n# DATA Generation #\n######################\n\ngreen_data = pd.read_csv('../col_dataset/green.csv')\n\nY_green = green_data['consensus']\nY_green = np.asarray(Y_green)\ngreen_labels = pd.unique(Y_green)\nX_green = pd.read_csv('../col_dataset/green_test.csv')\nX_green = X_green.iloc[:,1:]\n\ngreen_atribs = X_green.columns.values\n\n#data_1, map = widthnumericpreprocess(X_green, 4)\n\n#print (data_1)\n\n#y = pd.DataFrame(data=data_1)\n\n#y.to_csv('../col_dataset/green_test.csv')\n\n\nchi, pval = chi2 (X_green, Y_green)\n\nprint(chi)\nprint(pval)\n\npvals = []\natrib_todrop = []\n\natri_index = 0\nfor atrib in green_atribs:\n if pval[atri_index] <= 0.001: #99% confidence for discarding attributes\n print(atrib)\n atrib_todrop.append(atrib)\n atri_index += 1\n else:\n atri_index += 1\n\nprint (atrib_todrop)\n\ngreen_data = pd.read_csv('../col_dataset/green_test.csv')\n\nbla = green_data.drop(atrib_todrop, axis=1)\n\nX_green = bla.iloc[:,1:]\nX_green = np.asarray(X_green)\n\nscores = []\nx_train = []\ny_train = []\nx_test = []\ny_test = []\n\n#################\n# PREPROCESSING #\n#################\n# Normalization (comment it if want to check results with no normalization)\nX_green = normalize(X_green, axis=0, norm='max')\n\n# Resampling (comment it if want to check results with no resampling)\n#X_hinselmann, Y_hinselmann = resample(X_hinselmann, Y_hinselmann)\n\n# Smote (comment it if want to check results with no smote)\nsmote = smt(ratio='minority')\nX_green, Y_green = smote.fit_sample(X_green, Y_green)\n\n#######################\n# CLASSIFICATION #\n#######################\n\nkf = StratifiedKFold(n_splits=10, random_state=None, shuffle=False)\nclf = KNeighborsClassifier(n_neighbors=3)\n\nfor train_index, test_index in kf.split(X_green, Y_green):\n #print('TRAIN:', train_index, 'TEST:', test_index)\n x_train, x_test = X_green[train_index], X_green[test_index]\n y_train, y_test = Y_green[train_index], Y_green[test_index]\n\n clf.fit(x_train, y_train)\n\n reses = clf.predict(x_test)\n\n confusion = confusion_matrix(y_test, reses)\n\n print (confusion)\n\n trueNeg = confusion[0][0]\n truePos = confusion[1][1]\n\n falseNeg = confusion[1][0]\n falsePos = confusion[0][1]\n\n total = trueNeg + truePos + falseNeg + falsePos\n acc = ((truePos+trueNeg)/total) * 100.0\n specificity = trueNeg/(trueNeg+falsePos)\n sensivity = truePos / (truePos + falseNeg)\n\n print(f'number of predictions was {total}')\n print(f'accuracy was {acc}')\n print(f'specificity rate was {specificity}')\n print(f'sensivity rate was {sensivity}')\n print(\"\\n\")","repo_name":"cmmbranco/cdados_p1","sub_path":"col_part/col_ec/feature_selection.py","file_name":"feature_selection.py","file_ext":"py","file_size_in_byte":5919,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"73998810410","text":"\nimport os\n\nfrom epyk_studio.core.Page import Report\nfrom epyk_studio.static.pages import add_code, nav_bar\nfrom epyk.core.data import events\nfrom epyk.core.data import tree as data_tree\nfrom epyk.core.data import components\n\n\n# Create a basic report object\npage = Report()\nnav = nav_bar(page, \"Project\")\n\nc = page.ui.title(\"Create new report\")\n\ns_new = page.ui.input(html_code=\"name\")\ns_new.style.css.text_align = \"left\"\ns_new.style.css.padding_left = 5\n\npills = page.ui.panels.pills(html_code=\"category\")\npills.style.css.padding_bottom = 5\npills.style.css.padding_top = 5\n\npills.add_panel(\"Page\", None, selected=True)\npills.add_panel(\"Blog\", None)\npills.add_panel(\"Gallery\", None)\npills.add_panel(\"Dashboard\", None)\n\nb_new = page.ui.buttons.large(\"New Report\", align=\"center\")\n\nwa = page.ui.title(\"Get web artifacts\", align=\"center\")\nwa.style.css.margin_top = 30\nwp = page.ui.texts.text('''\nProduce rich HTML pages from your Python code\n''', align=\"center\")\nwp.style.css.margin_bottom = 10\n\nradios = page.ui.radio(\n components.radio.from_list(['Single', 'Multiple']), html_code=\"trans_type\", #checked=\"Single\",\n align=\"center\")\n\nb_transpile = page.ui.buttons.large(\"Transpile Project\", align=\"center\")\nb_transpile.style.css.margin_top = 10\n\ns = page.ui.title(\"Attach a server\", align=\"center\")\ns.style.css.margin_top = 30\n\npim = page.studio.pills.images([\n {\"image\": \"flask.jpg\", 'path': '/static', 'text': 'Flask'},\n {\"image\": \"tornado.jpg\", 'path': '/static', 'text': 'Tornado', 'selected': True},\n {\"image\": \"fastapi-logo.png\", 'path': '/static', 'text': 'FastAPI'},\n #{\"image\": \"django-logo.png\", 'path': '/static', 'text': 'Django'},\n], radius=False, html_code=\"server\", align=\"center\")\n\nb_server = page.ui.buttons.large(\"Server\", align=\"center\")\n\nt = page.ui.title(\"Scan external packages\", align=\"center\")\nt.style.css.margin_top = 35\npr = page.ui.texts.text('''\nFind an existing report in the project\n''', align=\"center\")\n\np_packages = page.ui.buttons.large(\"Scan Packages\", align=\"center\")\np_packages.style.css.margin_bottom = 15\np_packages.style.css.margin_top = 10\n\ntable = page.ui.table(cols=['pkg'], rows=['vr', 'get'])\ntable.get_column('pkg').title = \"Package\"\ntable.get_column('vr').title = \"Version\"\ntable.get_column('get').title = \"Install\"\ntable.get_column('get').formatters.html()\n\ntree = page.ui.trees.tree()\ntree.style.css.max_height = \"300px\"\n\ntt = page.ui.title(\"Available reports\", align=\"center\")\ntt.style.css.margin_top = 30\n\nrow = page.ui.row([\n [tt, tree],\n [wa, wp, radios, b_transpile, s, pim, b_server]\n], position=\"Top\")\nrow.set_size_cols(3)\n\nbox = page.studio.containers.box()\nbox.extend([c, s_new, pills, b_new, row, t, pr, p_packages, table])\nbox.style.standard()\n\nadd_code(page)\ndis = page.ui.banners.disclaimer()\ndis.style.css.margin_top = 20\n\n\ndef add_inputs(inputs):\n ui_path = os.path.join(inputs[\"current_path\"], inputs[\"name\"], \"ui\")\n tree._vals = data_tree.folders(ui_path, make_url=lambda x: \"/code_frame?classpath=%(root)s&script=%(path)s\" % x)\n nav.title._vals = inputs.get('name', '')\n b_new.click([\n page.js.post(\"/projects_page_add\", {'project': inputs.get('name', '')}, components=[s_new, pills])\n ])\n\n b_transpile.click([\n page.js.post(\"/projects_transpile\", {'project': inputs.get('name', '')}, components=[radios]).onSuccess([\n page.js.msg.status()\n ])\n ])\n\n b_server.click([\n page.js.post(\"/projects_add_server\", {'project': inputs.get('name', '')}, components=[pim])\n ])\n\n p_packages.click([\n page.js.post(\"/projects_get_packages\", {'project': inputs.get('name', '')}).onSuccess([\n table.build(events.data[\"packages\"])\n ])\n ])\n","repo_name":"epykure/epyk-studio","sub_path":"epyk_studio/static/pages/project_page.py","file_name":"project_page.py","file_ext":"py","file_size_in_byte":3651,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"55"} +{"seq_id":"34218334706","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n'''\nConverts the .txt image labels from the stanford background dataset to png mask images for training\naccording to train.py\n'''\n\nimport argparse\nimport glob\nimport os\nfrom os import path\nfrom PIL import Image\nimport numpy as np\nfrom utils import interp_map, pascal_palette\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--in-dir', type=str, help='Input folder',\n required=True)\n parser.add_argument('--out-dir', type=str, help='Output folder',\n required=True)\n args = parser.parse_args()\n\n files = sorted(glob.glob(path.join(args.in_dir, '*.txt')))\n\n assert len(files), 'no txt region files found in the input folder'\n\n try:\n os.makedirs(args.out_dir)\n except OSError:\n pass\n\n for f_cnt, fname in enumerate(files):\n img_data = []\n with open(fname,'rb') as f:\n \tfor line in f:\n \t\timg_data.append(line.split())\n \t\t# if img_data.size:\n \t\t# \timg_data = img_data.vstack((img_data,line.split()))\n \t\t# else:\n \t\t# \timg_data = np.array(line.split())\n\n img_data = np.array(img_data, dtype=np.uint8)\n np.place(img_data,img_data==255,[8])\n print (img_data.shape)\n\n npy_name = str.replace(path.basename(fname), '.regions.txt', '_label.npy')\n out_path = path.join(args.out_dir,npy_name)\n np.save(out_path, img_data)\n\n\n # #img = Image.fromarray(img_data)\n # img_name = str.replace(path.basename(fname), '.regions.txt', '_true.png')\n # #img.save(path.join(args.out_dir, img_name), 'png')\n # color_image = np.array(pascal_palette)[img_data.ravel()].reshape(\n # img_data.shape + (3,))\n\n # out_path = path.join(args.out_dir,img_name)\n # print('Saving results to: ', out_path)\n # with open(out_path, 'wb') as out_file:\n # Image.fromarray(color_image).save(out_file)\n\n #print(f'{f_cnt:05}/{len(files):05}')\n\nif __name__ == '__main__':\n main()","repo_name":"strikehead/dilated_seg","sub_path":"convert_stanford.py","file_name":"convert_stanford.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"55"} +{"seq_id":"27413385217","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 8 22:18:29 2019\n\n@author: pNser\n\"\"\"\nfrom nltk.corpus import gutenberg, inaugural\nfrom nltk.probability import *\n\n## 导出hamlet这本小说所有的单词\n#allwords = gutenberg.words('shakespeare-hamlet.txt')\n#\n#\n#print(len(allwords))\n#\n## 其中Hamlet出现的次数\n#print(allwords.count('Hamlet'))\n#\n#A = set(allwords)\n#\n##找出单词长度大于12 的单词\n#longwords = [w for w in allwords if len(w) > 12]\n#\n#print(sorted(longwords))\n#\n## 挖掘Hamlet这本小说中前20各最够词频的单词\n#fd2 = FreqDist([sx.lower() for sx in allwords if sx.isalpha()])\n#print(fd2.B())\n#print(fd2.N())\n#fd2.tabulate(20)\n#fd2.plot(20)\n#fd2.plot(20, cumulative=True)\n\nfd3 = FreqDist([s for s in inaugural.words()])\nprint(fd3.freq('freedom'))\n\ncfd = ConditionalFreqDist((fileid, len(w)) for fileid in inaugural.fileids() for w in inaugural.words(fileid) if fileid > '1980' and fileid < '2010')\nprint(cfd.items())\ncfd.plot()","repo_name":"gitpNser/learndata","sub_path":"nltk1.py","file_name":"nltk1.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"34095791754","text":"\nimport os\n\n\n'''\nThis script takes a beatmap ID (the difficulty one) and downloads the associated *.osu file and all nomod replays (if accessible). \nIt returns beatmap name, where beatmap got saved, and directory where all the replays are saved. This script works for std gamemode only.\nUses a mix of web requests and api v1. Requires your api key filled in the `api_key` variable in osu/online/login.py as well as your\nosu! login info in same file as well.\n'''\nclass DownloadReplays():\n\n def create_dir(self, dir_path):\n if not os.path.exists(dir_path):\n try: os.mkdir(dir_path)\n except OSError: print(f'failed to create folder: {dir_path}') \n\n\n def run(self, beatmap_id):\n self.create_dir('download')\n self.create_dir('download/osu')\n self.create_dir('download/osu/maps')\n self.create_dir('download/osu/replays')\n\n beatmap = CmdOnline.get_beatmap(beatmap_id)\n if beatmap == None: \n print('Unable to get beatmap')\n return\n\n beatmap_name, beatmap_data = beatmap\n\n beatmap_pathname = f'download/osu/maps/{beatmap_name}.osu'\n with open(beatmap_pathname, 'w', encoding='utf-8') as f:\n f.write(beatmap_data)\n\n replay_path = f'download/osu/replays/{beatmap_name}'\n self.create_dir(replay_path)\n\n scores = CmdOnline.get_scores_api(beatmap_id, 0, 0)\n for score in scores:\n replay_pathname = f'{replay_path}/{str(score)}.osr'\n with open(replay_pathname, 'wb') as f:\n f.write(score.get_replay_data_web())\n\n return beatmap_name, beatmap_pathname, replay_path","repo_name":"abraker95/ultimate_osu_analyzer","sub_path":"scripts/download_replays.py","file_name":"download_replays.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"55"} +{"seq_id":"11039344393","text":"\"\"\"empty message\n\nRevision ID: 47aab57dc761\nRevises: 8b14e2567e9f\nCreate Date: 2021-08-22 23:14:14.204049\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '47aab57dc761'\ndown_revision = '8b14e2567e9f'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('product_product', schema=None) as batch_op:\n batch_op.add_column(sa.Column('image', flask_appbuilder.models.mixins.ImageColumn(), nullable=True))\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('product_product', schema=None) as batch_op:\n batch_op.drop_column('image')\n\n # ### end Alembic commands ###\n","repo_name":"wahhid/fab_weha_smart_pos","sub_path":"migrations/versions/47aab57dc761_.py","file_name":"47aab57dc761_.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"27748142325","text":"from os import cpu_count\n\nfrom imblearn.over_sampling import SMOTE\nfrom numpy import concatenate, linspace, logspace\nfrom scipy.stats import loguniform, norm, truncnorm\nfrom sklearn.base import BaseEstimator, ClassifierMixin\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\nfrom sklearn.svm import SVC\n\nfrom src import config\nfrom src.models.abstractmodel import GaspipelineModelTrainer\nfrom src.preprocess.binarylabelencoder import BinaryLabelEncoder\nfrom src.preprocess.dataset import balance_dataset, convert_binary_labels, remove_missing_values, scale_features\nfrom src.preprocess.featureextraction import GasPipelineFeatureExtraction\nfrom src.preprocess.featureselection import get_first_cca_feature, get_first_ica_feature, get_first_pca_feature\n\n\nclass SvmTrainer(GaspipelineModelTrainer):\n best_parameters = {\n 'balance_dataset': False,\n 'feature_reduction': False,\n 'scale_features': True,\n 'kernel': 'rbf',\n 'cache_size': 4000,\n 'shrinking': False,\n 'balance_dataset': True,\n 'feature_reduction': False,\n 'scale_features': True,\n }\n\n tuning_parameters = {\n 'balance_dataset': [False],\n 'feature_reduction': [False],\n 'scale_features': [True],\n 'kernel': ['rbf'],\n 'cache_size': [4000],\n 'shrinking': [False],\n 'balance_dataset': [True, False],\n 'feature_reduction': [True, False],\n 'scale_features': [True, False],\n 'feature_n_components': linspace(1, 12, 5, dtype=int),\n }\n\n def __init__(self):\n super().__init__()\n self.model = GasPipelineSvc(verbose=config.verbosity, **self.best_parameters)\n\n def train(self):\n self.model.fit(self.x_train, self.y_train)\n\n def tune(self):\n tuned_model = GridSearchCV(self.model, self.tuning_parameters, cv=5, verbose=config.verbosity, n_jobs=-1)\n tuned_model = tuned_model.fit(self.x_train, self.y_train)\n\n return tuned_model.cv_results_\n\n def get_model(self):\n return self.model\n\n\nclass GasPipelineSvc(BaseEstimator, ClassifierMixin):\n def __init__(self, balance_dataset=False, feature_reduction=False, scale_features=False, feature_n_components=1, **kwargs):\n self.balance_dataset = balance_dataset\n self.feature_reduction = feature_reduction\n self.scale_features = scale_features\n self.feature_n_components = feature_n_components\n self.feature_extraction = GasPipelineFeatureExtraction(self.feature_reduction, self.scale_features, self.feature_n_components)\n self.svc = SVC(**kwargs)\n\n def fit(self, X, y):\n if self.balance_dataset:\n X, y = SMOTE().fit_resample(X, y)\n X = self.feature_extraction.fit_transform(X, y)\n self.svc.fit(X, y)\n\n def predict(self, X):\n X = self.feature_extraction.transform(X)\n return self.svc.predict(X)\n\n def score(self, X, y, sample_weight=None):\n X = self.feature_extraction.transform(X)\n return self.svc.score(X, y, sample_weight)\n\n def set_params(self, **params):\n self.__init__(**params)\n return self\n","repo_name":"FGRCL/scada-intrusion-detection","sub_path":"src/models/svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"28375372192","text":"from django.contrib import admin\nfrom django.urls import path\nfrom blog import views as blog_views\n\napp_name = 'blog'\n\nurlpatterns = [\n # path('admin/', admin.site.urls),\n path('', blog_views.BlogPostsView.as_view(), name='home'),\n path('bloggers/', blog_views.BloggersList.as_view(), name='bloggers'),\n path('search/', blog_views.BlogSearchView.as_view(), name=\"search\"),\n path('blog/', blog_views.BlogPostDetailView.as_view(), name='post'),\n path('author/', blog_views.AuthorPostsView.as_view(), name='author'),\n]","repo_name":"pawankumar1310/Blog-System","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"72575924332","text":"from typing import List, Optional\n\nfrom pydantic import BaseModel, Field\n\nfrom minichain.functions import tool\nfrom minichain.dtypes import ExceptionForAgent\n\n\nclass TasksNotDoneError(ExceptionForAgent):\n pass\n\n\nclass Task(BaseModel):\n id: Optional[int] = Field(\n None, description=\"The id of the task - only specify when updating a task.\"\n )\n description: str = Field(\n ...,\n description=\"The description of the task - be verbose and make sure to mention every piece of information that might be relevant to the assignee.\",\n )\n status: str = Field(\n \"TODO\",\n description=\"The status of the task.\",\n enum=[\"TODO\", \"IN_PROGRESS\", \"DONE\", \"BLOCKED\", \"CANCELED\"],\n )\n\n comments: List[str] = []\n\n def __str__(self):\n result = f\"#{self.id} ({self.status})\\n{self.description}\"\n if self.comments:\n result += \"\\nComments:\\n\" + \"\\n\".join(self.comments)\n return result\n\n\nclass TaskBoard:\n def __init__(self):\n self.tasks = []\n self.issue_counter = 1\n\n\nasync def add_task(\n board: TaskBoard = None, task: Task = Field(..., description=\"The task to update.\")\n):\n \"\"\"Add a task to the task board.\"\"\"\n if isinstance(task, dict):\n task = Task(**task)\n task.id = board.issue_counter\n board.issue_counter += 1\n board.tasks.append(task)\n return await get_board(board)\n\n\nasync def get_board(board: TaskBoard = None):\n \"\"\"Get the task board.\"\"\"\n return \"# Tasks\\n\" + \"\\n\".join([str(t) for t in board.tasks])\n\n\nasync def update_status(\n board: TaskBoard = None,\n task_id: int = Field(..., description=\"The task to update.\"),\n status: str = Field(\n ...,\n description=\"The new status of the task.\",\n enum=[\"TODO\", \"IN_PROGRESS\", \"DONE\", \"BLOCKED\", \"CANCELED\"],\n ),\n):\n \"\"\"Update a task on the task board.\"\"\"\n task = [i for i in board.tasks if i.id == task_id][0]\n task.status = status\n return await get_board(board)\n\n\nasync def comment_on_issue(\n board: TaskBoard = None,\n task_id: int = Field(..., description=\"The task to comment on.\"),\n comment: str = Field(..., description=\"The comment to add to the task.\"),\n):\n \"\"\"Update a task on the task board.\"\"\"\n task = [i for i in board.tasks if i.id == task_id][0]\n task.comments.append(comment)\n return str(task)\n\n\ndef tools(board: TaskBoard):\n return [\n tool(board=board)(add_task),\n tool(board=board)(get_board),\n tool(board=board)(update_status),\n tool(board=board)(comment_on_issue),\n ]\n","repo_name":"nielsrolf/minichain","sub_path":"minichain/tools/taskboard.py","file_name":"taskboard.py","file_ext":"py","file_size_in_byte":2569,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"55"} +{"seq_id":"42552194046","text":"from payload.ResponsePayload import ResponsePayload\n\nfrom controller.AuthController import AuthController\nfrom controller.AuthController import UserController\nfrom controller.PersonController import PersonGetController,PersonAddController,PersonEditController,PersonDeleteController,PersonListController\n\n\n\n\nclass Config:\n\n\n @staticmethod\n def mongo_config(app, db):\n app.config[\"MONGODB_PORT\"] = 27017\n app.config[\"MONGODB_DB\"] = 'admin'\n app.config[\"MONGODB_USERNAME\"] = 'devroot'\n app.config[\"MONGODB_PASSWORD\"] = 'devroot'\n app.config['MONGODB_HOST'] = \"mongodb://devroot:devroot@mongodb/admin?retryWrites=true&w=majority\"\n db.init_app(app)\n @staticmethod\n def exception_config(app):\n pass\n @staticmethod\n def route_config(api):\n api.add_resource(AuthController, \"/Auth/getToken\")\n api.add_resource(UserController, \"/Auth/addUser\")\n api.add_resource(PersonGetController, \"/Person/Get\")\n api.add_resource(PersonAddController, \"/Person/Add\")\n api.add_resource(PersonEditController, \"/Person/Edit\")\n api.add_resource(PersonDeleteController, \"/Person/Delete/\")\n api.add_resource(PersonListController, \"/Person/List\")\n\n @staticmethod\n def jwt_config(jwt, app):\n app.config['JWT_ALGORITHM'] = 'HS256'\n app.config['JWT_SECRET_KEY'] = '123456'\n app.config['JWT_PRIVATE_KEY'] = '123456'\n app.config['JWT_PUBLIC_KEY'] = '12222'\n\n @jwt.expired_token_loader\n def my_expired_token_callback():\n return ResponsePayload.error(\n status=401,\n message=\"The token has expired\"\n )\n\n @jwt.invalid_token_loader\n def my_invalid_token_loader(e):\n return ResponsePayload.error(\n status=401,\n message=\"The token is invalid:\"\n )\n\n @jwt.unauthorized_loader\n def my_unauthorized_loader(fp):\n return ResponsePayload.error(\n status=401,\n message=\"The token is unauthorized\"\n )\n\n @jwt.needs_fresh_token_loader\n def my_needs_fresh_token_loader():\n return ResponsePayload.error(\n status=401,\n message=\"Needs fresh token\"\n )\n\n\n\n","repo_name":"ysfgrl/FlaskVuejs","sub_path":"api/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"15601641009","text":"\"\"\"empty message\n\nRevision ID: f50f2fbf4e19\nRevises: 558cabb2c775\nCreate Date: 2020-01-31 04:37:18.832563\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = 'f50f2fbf4e19'\ndown_revision = '558cabb2c775'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('probe_data', 'value')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('probe_data', sa.Column('value', mysql.DECIMAL(precision=3, scale=0), nullable=True))\n # ### end Alembic commands ###\n","repo_name":"annndrey/plantdata-backend","sub_path":"api/migrations/versions/f50f2fbf4e19_.py","file_name":"f50f2fbf4e19_.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"33051033476","text":"import pandas as pd\nfrom collections import Counter\n\ngeneName = pd.read_csv(r'../data/Biomart_geneid.txt',\n sep=\"\\t\",\n header=None)\ngeneName.columns = ['ID', 'Symbol']\nid_count = dict(Counter(geneName['ID'].tolist()))\nid_retain = [k for k,v in id_count.items() if v == 1]\n\ngeneName2 = geneName[geneName['ID'].isin(id_retain)]\nid_name = dict(zip(geneName2['ID'], geneName2['Symbol']))\n\ndef id2name(id):\n if id in id_name.keys():\n return id_name[id]\n else:\n return 0","repo_name":"DuLab-SYSU/HUMPPI-2022","sub_path":"src/gene_id2symbol.py","file_name":"gene_id2symbol.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"9720795163","text":"import json\nfrom Core.l2.json.second import setJsonAcc\nimport tkinter as tk\nclass JsonGenerator:\n data = ''\n def __init__(self,config,consol):\n self.consol = consol\n self.read_wallets()\n self.generate(config)\n\n def read_wallets(self,file='wallets.txt'):\n try:\n\n with open(file) as f:\n data = f.readlines()\n if len(data) == 0:\n self.consol.insert(tk.END,'Wallets.txt is empty\\n')\n # raise Exception('Wallets.txt is empty')\n for i,v in enumerate(data):\n data[i] = v.replace('\\n','')\n self.data = data\n except:\n self.consol.insert(tk.END, 'Can not open wallets.txt\\n')\n\n def generate(self,configuration:setJsonAcc,papka='Accs'):\n for i in self.data:\n data = json.loads(configuration.setInfo(i))\n if data != 'ERROR':\n with open(f\"{papka}/{data['address']}.json\",'w') as file:\n json.dump(data,file)\n\n","repo_name":"Alexots/SyncSwap","sub_path":"Core/l2/json/first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"55"} +{"seq_id":"33078670631","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport argparse\n\n\ndef sum_args():\n parser = argparse.ArgumentParser(usage='python argparse_dev.py [-h] [-s] N [N ...]',\n description='sum the integers',\n epilog='-'*50)\n parser.add_argument('integers', metavar='N', type=int, nargs='+',\n help='an integer for the accumulator')\n parser.add_argument('-s', '--sum', dest='accumulate', action='store_const',\n const=sum, default=max,\n help='sum the integers')\n args = parser.parse_args()\n print(args.accumulate(args.integers))\n\n\ndef person_info():\n parser = argparse.ArgumentParser(description='Personal Infomation')\n parser.add_argument('name', type=str, help='Your name')\n parser.add_argument('birth', type=str, help='Your birthday')\n parser.add_argument('-r', '--race', type=str, dest='race', help='Your race')\n parser.add_argument('-a', '--age', type=int, dest='age', default=0,\n choices=range(150), help='Your age')\n parser.add_argument('-s', '--sex', type=str, dest='sex', default='male',\n choices=['male', 'female'], help='Your sex')\n parser.add_argument('-g', '--girl', type=str, dest='girl', default='None',\n nargs='*', help='Your girlfriend')\n parser.add_argument('-o', '--other', type=str, dest='other', required=False,\n nargs='*', help='Othe Infomation')\n args = parser.parse_args()\n\n print('argparse.args = {0}'.format(args), type(args))\n print('name = {0}'.format(args.name))\n\n d = args.__dict__\n for key, value in d.items():\n print('{0} = {1}'.format(key, value))\n\n\ndef parse_argument():\n parser = argparse.ArgumentParser()\n # parser.add_argument('--count', '-c', action='count')\n parser.add_argument('--version', action='version', version='version 2.0')\n parser.parse_args()\n\n\ndef main():\n parse_argument()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"letterli/py-cookbook","sub_path":"modules/argparse/argpase_dev.py","file_name":"argpase_dev.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"30110920016","text":"from fastapi import FastAPI, HTTPException\r\nfrom fastapi.responses import JSONResponse\r\nfrom pydantic import BaseModel\r\nfrom pymongo import MongoClient\r\nfrom bson import ObjectId\r\nimport joblib\r\n\r\napp = FastAPI()\r\n\r\n@app.exception_handler(HTTPException)\r\nasync def http_exception_handler(request, exc):\r\n return JSONResponse(\r\n status_code=exc.status_code,\r\n content={\"message\": exc.detail},\r\n )\r\n\r\n# load the pre-trained model\r\nmodel = joblib.load(\"trained_model.pkl\")\r\n\r\n# connect to MongoDB\r\nclient = MongoClient(\"mongodb://localhost:27017/\")\r\ndb = client[\"bot_classifier\"]\r\ncollection = db[\"bot_results\"]\r\n\r\n\r\nclass BotParams(BaseModel):\r\n screen_name: str\r\n description: str\r\n location: str\r\n verified: bool\r\n\r\n\r\n@app.get('/classify_bots')\r\ndef classify_bots(screen_name: str, description: str, location: str, verified: bool):\r\n result = model.predict([[int('bot' in screen_name.lower()), \r\n int('bot' in description.lower()), \r\n int(location is None), \r\n int(not verified)]])[0]\r\n is_bot = not bool(result)\r\n existing_result = collection.find_one({\"screen_name\": screen_name, \"description\": description, \"location\": location, \"verified\": verified})\r\n if existing_result:\r\n collection.update_one({\"_id\": existing_result[\"_id\"]}, {\"$set\": {\"is_bot\": is_bot}})\r\n return JSONResponse(content={\"id\": str(existing_result[\"_id\"]), \"is_bot\": is_bot})\r\n else:\r\n result_data = {\"screen_name\": screen_name, \"description\": description, \"location\": location, \"verified\": verified, \"is_bot\": is_bot}\r\n inserted_id = collection.insert_one(result_data).inserted_id\r\n return JSONResponse(content={\"id\": str(inserted_id), \"is_bot\": is_bot})\r\n\r\n\r\n@app.get('/bot_results/{id}')\r\ndef get_bot_result(id: str):\r\n result = collection.find_one({\"_id\": ObjectId(id)})\r\n if result:\r\n result[\"_id\"] = str(result[\"_id\"]) # convert ObjectId to string\r\n return JSONResponse(content=result)\r\n else:\r\n return JSONResponse(content={\"error\": \"Result not found\"}, status_code=404)\r\n\r\n\r\n\r\n@app.get('/bot_ids')\r\ndef get_bot_ids():\r\n results = collection.find({}, {\"_id\": 1})\r\n ids = [str(result[\"_id\"]) for result in results]\r\n return JSONResponse(content={\"ids\": ids})","repo_name":"baransar/twitter_bot_detection","sub_path":"twitter_bot_detection/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"32755752271","text":"from fractions import Fraction\n\n'''\nGearing Up for Destruction\n==========================\n\nAs Commander Lambda's personal assistant, you've been assigned the task of configuring the LAMBCHOP doomsday device's axial orientation gears. It should be pretty simple -- just add gears to create the appropriate rotation ratio. But the problem is, due to the layout of the LAMBCHOP and the complicated system of beams and pipes supporting it, the pegs that will support the gears are fixed in place.\n\nThe LAMBCHOP's engineers have given you lists identifying the placement of groups of pegs along various support beams. You need to place a gear on each peg (otherwise the gears will collide with unoccupied pegs). The engineers have plenty of gears in all different sizes stocked up, so you can choose gears of any size, from a radius of 1 on up. Your goal is to build a system where the last gear rotates at twice the rate (in revolutions per minute, or rpm) of the first gear, no matter the direction. Each gear (except the last) touches and turns the gear on the next peg to the right.\n\nGiven a list of distinct positive integers named pegs representing the location of each peg along the support beam, write a function solution(pegs) which, if there is a solution, returns a list of two positive integers a and b representing the numerator and denominator of the first gear's radius in its simplest form in order to achieve the goal above, such that radius = a/b. The ratio a/b should be greater than or equal to 1. Not all support configurations will necessarily be capable of creating the proper rotation ratio, so if the task is impossible, the function solution(pegs) should return the list [-1, -1].\n\nFor example, if the pegs are placed at [4, 30, 50], then the first gear could have a radius of 12, the second gear could have a radius of 14, and the last one a radius of 6. Thus, the last gear would rotate twice as fast as the first one. In this case, pegs would be [4, 30, 50] and solution(pegs) should return [12, 1].\n\nThe list pegs will be given sorted in ascending order and will contain at least 2 and no more than 20 distinct positive integers, all between 1 and 10000 inclusive.\n'''\nfrom fractions import Fraction\n\n\ndef solution(array):\n ##TO DO###\n # find way to create standard form of outputs\n # test on input size of 4 and 5\n ##########\n if ((not array) or len(array) == 1):\n return [-1, -1]\n\n rhs_arr = []\n\n for i, val in enumerate(array):\n if i == len(array) - 1:\n rhs_arr.append(Fraction(0))\n else:\n rhs_arr.append(Fraction(array[i + 1] - val))\n size = len(rhs_arr)\n intial_value = rhs_arr[:size - 1]\n\n # subtract second last row from previous row till we reach the first row\n for i in range(size - 2, 0, -1):\n rhs_arr[i - 1] = rhs_arr[i - 1] - rhs_arr[i]\n\n # subtract last row from first row\n rhs_arr[size - 1] = Fraction(-1 * rhs_arr[size - 1]) + rhs_arr[0]\n if size % 2 == 0:\n rhs_arr[size - 1] = rhs_arr[size - 1] / Fraction(3.0)\n rhs_arr[:size - 1] = intial_value\n\n for i in range(size - 1, 0, -1):\n rhs_arr[i - 1] = rhs_arr[i - 1] - rhs_arr[i]\n\n # return rhs_arr\n for value in rhs_arr:\n if value <= 0:\n return [-1, -1]\n #\n #\n # value = float(rhs_arr[0])\n output = rhs_arr[0].limit_denominator(100000000000000000)\n\n if output < 2:\n return [-1, -1]\n\n for value in rhs_arr:\n if value >= 1:\n continue\n else:\n return [-1, -1]\n\n return [output.numerator, output.denominator]\n","repo_name":"YahyaHaq/GoogleFoobarChallenge","sub_path":"Level 2/level2.py","file_name":"level2.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"21807678116","text":"# Prompts the user for the face values of banknotes and their associated quantities\n# as well as for an amount, and if possible, outputs the minimal number of banknotes\n# needed to match that amount, as well as the detail of how many banknotes of each type value are used.\n#\n# Written by Eric Martin for COMP9021\n\n\ndef print_solution(solution):\n max_width = max([len(str(value)) for value in solution]) + 1\n for value in sorted(solution.keys()):\n print('{:>{:}}: {:}'.format('$' + str(value), max_width, solution[value]))\n\n \nprint(\"Input pairs of the form 'value : number'\\n\"\n \" to indicate that you have 'number' many banknotes of face value 'value'.\")\nprint('Input these pairs one per line, with a blank line to indicate end of input.\\n')\nface_values = []\nwhile True:\n line = input()\n if ':' not in line:\n break\n value, quantity = line.split(':')\n face_values.append((int(value), int(quantity)))\n# Might make the computation more efficient.\nface_values.sort(reverse = True)\nnb_of_face_values = len(face_values)\namount = int(input('Input the desired amount: '))\n\n# minimal_combinations[sub_amount] will be a pair whose first element is the minimal number of banknotes\n# needed to yield sub_amount, and whose second element is the list of all possible solutions,\n# each solution being a dictionary with face values as keys and number of banknotes used as values.\nminimal_combinations = [[0, []]] + [[float('inf'), []] for i in range(amount)]\nfor sub_amount in range(1, amount + 1):\n for i in range(nb_of_face_values):\n value = face_values[i][0]\n if sub_amount < value:\n continue\n if value == sub_amount:\n minimal_combinations[sub_amount] = [1, [{value : 1}]]\n continue\n # Using \"value\" to get \"sub_amount\" would require most banknotes that the minimum\n # number of banknotes so far found out to sum up to \"sub_amount\".\n if minimal_combinations[sub_amount - value][0] >= minimal_combinations[sub_amount][0]:\n continue\n for option in minimal_combinations[sub_amount - value][1]:\n # A banknote with face value \"value\" is available to complete \"option\" and result in a sum of \"sub_amount\".\n if value not in option or option[value] < face_values[i][1]:\n # Moreover, it determines a new minimum to then umber of banknotes that can sum of to \"sub_amount\".\n if minimal_combinations[sub_amount - value][0] + 1 < minimal_combinations[sub_amount][0]:\n minimal_combinations[sub_amount][0] = minimal_combinations[sub_amount - value][0] + 1\n minimal_combinations[sub_amount][1].clear()\n extended_option = dict(option)\n if value not in option:\n extended_option[value] = 1\n else:\n extended_option[value] += 1\n if extended_option not in minimal_combinations[sub_amount][1]:\n minimal_combinations[sub_amount][1].append(extended_option)\nminimal_nb_of_banknotes = minimal_combinations[amount][0]\nif minimal_nb_of_banknotes == float('inf'):\n print('\\nThere is no solution.')\nelse:\n solutions = minimal_combinations[amount][1]\n nb_of_solutions = len(solutions)\n if nb_of_solutions == 1:\n print('\\nThere is a unique solution:')\n print_solution(solutions[0])\n else:\n print('\\nThere are {:} solutions:'.format(nb_of_solutions))\n for i in range(nb_of_solutions - 1):\n print_solution(solutions[i])\n print()\n print_solution(solutions[nb_of_solutions - 1])\n \n\n","repo_name":"iteong/comp9021-principles-of-programming","sub_path":"labs/Lab_6_solutions/question_2.py","file_name":"question_2.py","file_ext":"py","file_size_in_byte":3663,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"6"} +{"seq_id":"24181990483","text":"#Leetcode daily challenge: day 06\n# 04/11/2023\n\nclass Solution:\n def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:\n \n fall = [] #add ants falling off\n\n # ants on the left to fall\n for ant in left:\n fall.append(ant)\n\n #ants on the right to fall\n for ant in right:\n fall.append(n - ant)\n\n max_time = max(fall) #maximum time\n\n return max_time\n\n\n","repo_name":"nabilah-afrin/Leetcode-problem-solving","sub_path":"List_Array/Medium/44. Last Moment Before All Ants Fall Out of a Plank.py","file_name":"44. Last Moment Before All Ants Fall Out of a Plank.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"14451041980","text":"\n# Unsupervised Clustering of Visually Similar Images using a Neural Network\n\n#My Effort -\n#To cluster the images , firstly we should be able to extract the features from the Images\n#There can be various ways to extract the features from the image eg. edge detection , SURF etc .\n\n# I have used the pre-trained model of the VGG-16 Convolutional Neural Network for extracting the features\n# From the (Last -1) layer I am extracting the features and flattening it to become of the shape (1,25088)\n\n# Now I have fed those flattened features into the clustering algorithm to cluster\n# Clustering Algorithm Used = K means\n\n# And I also did tried to cluster it using the Self Organizing Featuer Maps (SOFM) ,\n# but the result was not satisfatory\n\nimport numpy as np\n#import tensorflow as tf\nimport scipy as sci\nimport matplotlib.image as img\nimport matplotlib.pyplot as plt\nimport os , sys ,cv2\nfrom PIL import Image as pimg\nimport matplotlib.pyplot as plt\nfrom neupy import algorithms, environment\nfrom keras.applications.vgg16 import VGG16\nfrom keras.preprocessing import image\nfrom keras.applications.vgg16 import preprocess_input\nfrom sklearn.cluster import KMeans\nimport scipy.cluster.hierarchy as hac\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\ntrain_data=[]\nmissing_file=[]\nfiles=[]\n\n\nX_train=[]\nclusters={}\n#n=0\n\ndef file_size(fname):\n stat=os.stat(\"f/\"+str(fname))\n return stat.st_size\n\n\ndef vgg16():\n n=0\n model = VGG16(weights='imagenet', include_top=False)\n images_path = \"../Task/f\"\n for f in os.listdir(images_path):\n files.append(f)\n for img_path in files:\n if(file_size(img_path)!=0):\n print(str(img_path))\n n+=1\n print(n)\n\n img = image.load_img(\"f/\"+str(img_path), target_size=(224, 224))\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n features = model.predict(x)\n #print(features.shape)\n a=features.shape[0]\n b=features.shape[1]\n c=features.shape[2]\n d=features.shape[3]\n features = np.array(features)\n features= features.flatten()\n X_train.append(features)\n features = (features - np.mean(features))/(np.std(features,axis=0));\n\n\n #print(features)\n #MinMaxScalar(copy = False , feature_range=(0,1))\n\ndef kmeans():\n #print(\"X_train's length=\"+str(len(X_train)))\n #print(X_train)\n kmeans = KMeans(n_clusters=15, init='k-means++', max_iter=100, n_init=10,tol=1e-6, verbose=1)\n kmeans.fit(X_train)\n labels=kmeans.predict(X_train)\n centroids = kmeans.cluster_centers_\n labels = kmeans.labels_\n\n print (\"centroids : \")\n #print (centroids)\n print (\"labels : \")\n #print (labels)\n p=dict(zip(files,labels))\n\n for i,j in p.items() :\n new_path=str(\"../Task/\"+str(j))\n if not os.path.exists(new_path):\n os.makedirs(new_path)\n img = cv2.imread(\"f/\"+str(i), 1)\n cv2.imwrite(os.path.join(new_path , i), img)\n\ndef som():\n input_data = np.array(X_train)\n sofmnet = algorithms.SOFM(\n n_inputs=25088,\n n_outputs=25,\n\n step=0.5,\n show_epoch=100,\n shuffle_data=True,\n verbose=True,\n\n learning_radius=0,\n features_grid=(5,5),\n )\n\n sofmnet.train(input_data,epochs=100);\n plt.plot(input_data.T[0:1, :], input_data.T[1:2, :], 'ko')\n\n print(\"> Start plotting\")\n plt.xlim(-1, 1.2)\n plt.ylim(-1, 1.2)\n\n plt.plot(sofmnet.weight[0:1, :], sofmnet.weight[1:2, :], 'bx')\n plt.show()\n\n for data in input_data:\n print(sofmnet.predict(np.reshape(data, (2, 1)).T))\n\n\n\nif __name__ ==\"__main__\":\n #reader()\n vgg16()\n #kmeans();\n #som();\n hierarchial()\n","repo_name":"kesarianubhav/Unsupervised-Image-Clustering","sub_path":"f1/neural_classifier.py","file_name":"neural_classifier.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"6"} +{"seq_id":"39081254882","text":"import os\n\n\ndef getKeepRows() -> list:\n \"\"\"gets the data in keeprows.txt as an array\n\n Returns\n -------\n A list\n \"\"\"\n ret = []\n with open(os.path.join(\"data\", \"keeprows.txt\")) as f:\n ret = [line.strip() for line in f.readlines()]\n return ret\n\n\nif __name__ == '__main__':\n print(getKeepRows())\n","repo_name":"SL477/Predicting_future_trends_in_airline_profitability","sub_path":"data/keepRows.py","file_name":"keepRows.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"18014926182","text":"\"\"\"\nDataLink Manager\n\"\"\"\n\nimport logging\nimport queue\nimport threading\nfrom .queue import DataLinkQueue\nfrom .uart import DataLinkUART\nfrom .exceptions import *\n\n\nclass DataLinkManager(object):\n \"\"\"\n DataLink Manager class\n \"\"\"\n\n TYPE_UART = b'U'\n TYPE_QUEUE = b'Q'\n\n def __init__(self, mode):\n \"\"\"\n Initialization\n \"\"\"\n\n # Creating connection\n self.__current_mode = mode\n try:\n if mode == self.TYPE_QUEUE:\n self.__datalink = DataLinkQueue()\n elif mode == self.TYPE_UART:\n self.__datalink = DataLinkUART()\n else:\n raise DataLinkManagerWrongTypeException()\n except DataLinkRealisationException:\n raise DataLinkManagerInitializationException()\n\n # Creating queues\n self.__inbound_queue = queue.Queue()\n self.__outbound_queue = queue.Queue()\n\n # Threads\n self.__inbound_thread = None\n self.__outbound_thread = None\n\n # Run event\n self.__run_event = threading.Event()\n\n def connect(self, **kwargs):\n \"\"\"\n Connection\n\n kwargs:\n for queue: rx,tx - queue\n TODO for uart: only god knows\n \"\"\"\n self.__datalink.connect(**kwargs)\n self.__run_event.set()\n self.__run_process_inbound()\n self.__run_process_outbound()\n\n def __run_process_inbound(self):\n \"\"\"\n Start in new thread\n \"\"\"\n self.__inbound_thread = threading.Thread(\n target=self.__process_inbound,\n name='THREAD_DATALINK_INBOUND_PROCESS'\n )\n self.__inbound_thread.daemon = True\n self.__inbound_thread.start()\n\n def __run_process_outbound(self):\n \"\"\"\n Start in new thread\n \"\"\"\n self.__outbound_thread = threading.Thread(\n target=self.__process_outbound,\n name='THREAD_DATALINK_OUTBOUND_PROCESS'\n )\n self.__outbound_thread.daemon = True\n self.__outbound_thread.start()\n\n def __process_inbound(self):\n \"\"\"\n Infinite cycle\n \"\"\"\n\n while self.__run_event.is_set():\n data = self.__datalink.receive()\n if data is not None:\n while not self.__put_data(data):\n pass\n\n logging.info(\"Stopping inbound processing..\")\n\n def __put_data(self, data):\n \"\"\"\n Put data\n\n :param data:\n :return bool:\n \"\"\"\n\n try:\n self.__inbound_queue.put_nowait(data)\n except queue.Full:\n return False\n\n return True\n\n def __process_outbound(self):\n \"\"\"\n Infinite cycle\n \"\"\"\n\n while self.__run_event.is_set():\n try:\n data = self.__outbound_queue.get_nowait()\n while not self.__datalink.send(data):\n pass\n\n except DataLinkRealisationWrongArgsException:\n logging.error('Somehow message {0} wasn\\'t meant to be delivered'.format(data))\n\n except queue.Empty:\n pass\n\n logging.info(\"Stopping outbound processing..\")\n\n def receive(self):\n \"\"\"\n Get first message from queue\n \"\"\"\n\n try:\n return self.__inbound_queue.get_nowait()\n\n except queue.Empty:\n pass\n\n return None\n\n def send(self, message):\n \"\"\"\n Send message\n \"\"\"\n if type(message) is not bytes:\n raise DataLinkManagerWrongTypeException()\n\n try:\n self.__outbound_queue.put_nowait(message)\n except queue.Full:\n return False\n\n return True\n\n def stop(self):\n \"\"\"\n Stop\n \"\"\"\n\n if self.__datalink:\n self.__datalink.stop()\n\n if self.__run_event:\n self.__run_event.clear()\n\n if self.__inbound_thread:\n self.__inbound_thread.join()\n if self.__outbound_thread:\n self.__outbound_thread.join()\n","repo_name":"connax-utim/utim-python","sub_path":"utim/connectivity/datalink/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"4729333607","text":"#!/usr/bin/env python\nimport os\nimport sys\n\nMODULES = \"module purge && module load gcc/6.3.0 openblas openmpi cuda/10.1.243\"\n\nif 'CUDA_HOME' in os.environ:\n CUDA_HOME = os.environ['CUDA_HOME']\nelse:\n print(\"CUDA_HOME not found in environment. Did you load the correct modules?\")\n print(\" \" + MODULES)\n sys.exit(1)\n\nconfigure_options = [\n '--with-fc=mpif90',\n '--with-cc=mpicc',\n '--with-cxx=mpiCC',\n '--with-cuda=1',\n '--with-cuda-dir=%s' % CUDA_HOME,\n '--with-valgrind=0',\n '--with-debugging=no',\n '--FOPTFLAGS=\\'-g -O3\\'',\n '--COPTFLAGS=\\'-g -O3\\'' ,\n '--CXXOPTFLAGS=\\'-g -O3\\'',\n '--known-mpi-shared-libraries=1 ',\n '--with-blaslapack-lib=-lopenblas',\n '--with-shared-libraries=0',\n 'PETSC_ARCH=arch-leonhard-cuda',\n 'LIBS=-lgomp',\n]\n\nif __name__ == '__main__':\n sys.path.insert(0, os.path.abspath('config'))\n import configure\n configure.petsc_configure(configure_options)\n","repo_name":"psanan/petsc_configure_helpers","sub_path":"old/arch-leonhard-cuda.py","file_name":"arch-leonhard-cuda.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"9208700087","text":"from utils.io import IO\nfrom utils.classifer import Classifier\n\ndef main():\n\n in_arg = IO.get_input_args(train=True)\n\n device = IO.get_device(in_arg.gpu)\n\n dataloaders, class_to_idx = IO.get_image_data(in_arg.data_directory)\n\n classifier = Classifier(\n arch=in_arg.arch, \n hidden_units=in_arg.hidden_units, \n output_units=102,\n learning_rate=in_arg.learning_rate,\n epochs=in_arg.epochs,\n device=device\n )\n\n classifier.train_model(dataloaders['trainloader'], dataloaders['validloader'])\n\n trained_classifier = classifier.get_trained_classifier()\n\n checkpoint = {\n 'classifier': trained_classifier['classifier'],\n 'state_dict': trained_classifier['state_dict'],\n 'learning_rate': trained_classifier['learning_rate'],\n 'epochs': trained_classifier['epochs'],\n 'class_to_idx': class_to_idx\n }\n\n IO.save_checkpoint(checkpoint, in_arg.save_dir)\n\nif __name__ == \"__main__\":\n main()","repo_name":"yufrances90/Image_Classifier","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"11422381674","text":"\"\"\"\n\nManipulando arquivo de texto em um sistema modularizado\n\nCrie um sistema modularizado que permita cadastrar pessoas pelo seu nome e idade em um arquivo de texto simples.\nO sistema só vai ter 2 opções:\n - cadastrar uma nova pessoa;\n - listar todas as pessoas cadastradas.\n\n\"\"\"\nfrom ex115.lib.interface import *\nfrom ex115.lib.arquivo import *\n\ncria_cabecalho(4, '=')\n\ndestino = 'cadastro.txt'\nif arquivo_existe(destino):\n while True:\n mostra_menu()\n opcao = verificador(f'{ansi(\"amarelo\", \"bold\")}Sua opção:{ansi()} ')\n if opcao == 1:\n le_arquivo(destino)\n elif opcao == 2:\n escreve_arquivo(destino)\n elif opcao == 3:\n cria_cabecalho(3)\n break\n else:\n print(f'{ansi(\"vermelho\", \"bold\")}ERRO! Digite uma opção válida. Tente novamente!{ansi()}')\n continue\n","repo_name":"cicerohr/Curso_em_video","sub_path":"ex115/lib/sistema.py","file_name":"sistema.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"29555155186","text":"# !wget https://people.eecs.berkeley.edu/~bmild/nerf/tiny_nerf_data.npz\n# Use the Tiny-NeRF dataset (a subset of the original Blender dataset)\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import ImageGrid\n\ndata = np.load(\"tiny_nerf_data.npz\")\nimages = data[\"images\"]\nposes = data[\"poses\"]\nfocal = float(data[\"focal\"])\n\n_, image_ht, image_wid, _ = images.shape\n\n# use first 100 images&poses as training data\ntrain_images, train_poses = images[:100], poses[:100]\n\n# use a single image&pose pair for validation\nval_images, val_pose = images[101], poses[101]\n\n# visualize the training data\nfig = plt.figure(figsize=(16, 16))\ngrid = ImageGrid(fig, 111, nrows_ncols=(4,4), axes_pad=0.1)\n\nrandom_images = images[np.random.choice(np.arange(images.shape[0]), 16)]\nfor ax, image in zip(grid, random_images):\n ax.imshow(image)\nplt.title(\"Sample images from Tiny-NeRF dataset\")\nplt.show()","repo_name":"Guanghan/ngp_jax","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"10601033206","text":"# -*- coding: utf-8 -*-\nimport time\nimport argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom datasets import get_loaders\n\n\ndef train(epoch, model, optimizer, criterion, train_loader, device):\n model.train()\n train_loss = 0\n correct = 0\n total = 0\n start = time.time()\n for batch_idx, (inputs, targets) in enumerate(train_loader):\n inputs, targets = inputs.to(device), targets.to(device)\n optimizer.zero_grad()\n outputs = model(inputs)\n\n loss = criterion(outputs, targets)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.item()\n _, pred = outputs.max(1)\n total += targets.size(0)\n correct += pred.eq(targets).sum().item()\n\n print(\"Epoch: {}, Loss: {:.5f}, Acc: {:.3f}, [{:3f} sec]\".format(\n epoch,\n train_loss / total,\n 100. * correct / total,\n time.time() - start,\n ))\n\ndef test(model, criterion, test_loader, device):\n model.eval()\n test_loss = 0\n correct = 0\n total = 0\n start = time.time()\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(test_loader):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = model(inputs)\n loss = criterion(outputs, targets)\n test_loss += loss.item()\n _, pred = outputs.max(1)\n total += targets.size(0)\n correct += pred.eq(targets).sum().item()\n\n print(\"Loss: {:.5f}, Acc: {:.3f}, [{:.3f} sec]\".format(\n test_loss / total,\n 100. * correct / total,\n time.time() - start))\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--mode\", type=str, default=\"train\")\n parser.add_argument(\"--model\", type=str, default=\"mobilenet_v2\")\n parser.add_argument(\"--dataset\", type=str, default=\"cifar10\")\n parser.add_argument(\"--dataroot\", type=str, default=\"/tmp/data\")\n parser.add_argument(\"--batch_size\", type=int, default=128)\n parser.add_argument(\"--n_epochs\", type=int, default=100)\n parser.add_argument(\"--lr\", type=float, default=1e-3)\n parser.add_argument(\"--n_gpus\", type=int, default=1)\n parser.add_argument(\"--checkpoint\", type=str, default=\"/tmp/chkpt.pth.tar\")\n parser.add_argument(\"--save_every\", type=int, default=10)\n parser.add_argument(\"--pretrained\", type=str, default=None)\n args = parser.parse_args()\n print(args)\n\n if torch.cuda.is_available():\n print(\"cuda is available, use cuda\")\n device = torch.device(\"cuda\")\n else:\n print(\"cuda is not available, use cpu\")\n device = torch.device(\"cpu\")\n\n print(\"download dataset: {}\".format(args.dataset))\n train_loader, test_loader, n_classes = get_loaders(dataset=args.dataset,\n root=args.dataroot,\n batch_size=args.batch_size)\n\n print(\"build model: {}\".format(args.model))\n if args.model == \"mobilenet\":\n from models import MobileNet\n model = MobileNet(n_classes=n_classes)\n elif args.model == \"mobilenet_v2\":\n from models import MobileNet_v2\n model = MobileNet_v2(n_classes=n_classes)\n elif args.model == \"shufflenet\":\n from models import ShuffleNet\n model = ShuffleNet(n_classes=n_classes)\n elif args.model == \"shufflenet_v2\":\n from models import ShuffleNet_v2\n model = ShuffleNet_v2(n_classes=n_classes)\n elif args.model == \"squeezenet\":\n from models import SqueezeNet\n model = SqueezeNet(n_classes=n_classes)\n else:\n raise NotImplementedError\n\n model = model.to(device)\n if args.pretrained:\n model.load_state_dict(torch.load(args.checkpoint))\n\n if args.n_gpus > 1:\n gpus = []\n for i in range(args.n_gpus):\n gpus.append(i)\n model = nn.DataParallel(model, device_ids=gpus)\n\n optimizer = optim.Adam(model.parameters(), lr=args.lr)\n criterion = nn.CrossEntropyLoss()\n\n if args.mode == \"train\":\n for epoch in range(args.n_epochs):\n train(epoch, model, optimizer, criterion, train_loader, device)\n if (epoch + 1) % args.save_every == 0:\n print(\"saving model...\")\n torch.save(the_model.state_dict(), args.checkpoint)\n elif args.mode == \"test\":\n test(model, criterion, test_loader, device)\n else:\n raise NotImplementedError\n\nif __name__ == \"__main__\":\n torch.backends.cudnn.benchmark = True\n main()\n","repo_name":"nocotan/lightweight_models.torch","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"26423973784","text":"\n\n# import gc\nimport time\nimport random\n# import _thread\nimport datetime\n# import threading\nimport numpy as np\nfrom pyTCP import *\n# from Log_Tools import *\nfrom Pytorch_Model import *\nfrom client_generator import *\n# import matplotlib.pyplot as plt\nfrom client_control_algorithm import *\n#from plotO import FirstScreen\n\nt_img = []\nt_lab = []\n\n#fs = FirstScreen()\nfs = 0\n\n# from plotO import FirstScreen\n# Screen1 = FirstScreen()\n\n# Set number of phones to connect\nnumOfPhone = 3\n\n# Ignore\nnumOfConnect = None\n\ndef FL_server_pre_process(num_of_client, num_of_client_connect, ti, d_f):\n global t_img, t_lab, numOfConnect\n # create model and network\n # new_model = load_model(\"models/standard_model.pkl\") \n new_model = Model()\n save_model(new_model, \"models/standard_model_RS.pkl\")\n # init clients with data \n client_set, t_img, t_lab = p2_init_client_with_data(num_of_client, ti, d_f)\n # show data distribution\n p2_show_client_with_data(client_set)\n \n #socketServer = create_socket_server(num_of_client_connect)\n socketServer = create_socket_server_for_show(num_of_client_connect, numOfPhone)\n #print(socketServer.cliList)\n \n # assign id to phone\n numOfConnect = num_of_client_connect\n for i in range(num_of_client_connect+1, num_of_client_connect+numOfPhone+1):\n socketServer.send_raw_msg(i, client_set[i-num_of_client_connect-1].ID)\n \n # get upload and compute time \n \n # create and save a network and use it to test speed\n # save model to test_speed.pkl\n save_model(new_model, \"models/test_speed.pkl\")\n for i in range(num_of_client_connect):\n client = client_set[i]\n pos = client.ID\n upload_time = socketServer.server_get_recv_speed(pos)\n compute_speed = socketServer.recvMSG(pos)\n compute_speed /= 1000\n client.get_time_info(compute_speed, upload_time)\n print(\"\\nclient {}:\".format(pos))\n print(\" |_ average upload time: {}s\".format(upload_time))\n print(\" |_ unit data compute time: {}s\".format(compute_speed))\n # hand out train data to all client\n for i in range(num_of_client_connect):\n client = client_set[i]\n p2_server_send_data(socketServer, client)\n\n # create and save network to local file\n print()\n print(\"---\"*22, \"pre process finished\", \"\\n\")\n \n return socketServer, client_set\n\ndef gen_useful_data(selected_client, client_set):\n\n tlab = []\n clients = [ i+1 for i in range(len(client_set))]\n tc = [ 0 for i in clients ]\n tu = [ 0 for i in clients ]\n for i in selected_client:\n cli = client_set[i]\n #clients.append(cli.ID)\n #print(cli.real_time_computation)\n #print(cli.real_time_upload)\n p = cli.ID\n tc[p-1] = cli.real_time_computation\n tu[p-1] = cli.real_time_upload\n return clients, tc, tu\n\n\ndef TS_FL_every_algorithm(round_num, socketServer, flg_para, algr, client_selected, client_set, model_name, log_file_name, round_log):\n # get test data\n global t_img, t_lab, fs\n \n \n st_time = time.time()\n \n hand_out_standard_model(round_num, socketServer, client_selected, client_set, model_name)\n fire_starting_gun(socketServer, client_selected, client_set)\n # recieve model one by one\n recv_local_model(socketServer, client_selected, client_set, t_img, t_lab, fs)\n \n # aggregation\n tot_time = time.time() - st_time\n aggregate(client_selected, client_set, model_name)\n \n tot_time_ = 0\n \n for i in client_selected:\n client = client_set[i]\n pos = client.ID\n socketServer.sendMSG(pos, 1)\n t_download = socketServer.recvMSG(pos)\n t_compute = socketServer.recvMSG(pos)\n t_upload = socketServer.recvMSG(pos)\n client.get_log_time(t_download, t_compute, t_upload)\n \n if flg_para:\n tot_time = tot_time_\n \n # show acc\n aggr_loss, aggr_acc = evaluate(model_name, t_img, t_lab)\n print(\"\\tACC -> total loss: {:.5}, acc: {:.5}\".format(aggr_loss, aggr_acc))\n for i in client_selected:\n client = client_set[i]\n pos = client.ID\n local_file_name = \"models/model{}.pkl\".format(pos)\n local_loss, local_acc = evaluate(local_file_name, client.train_images, client.train_labels)\n print(\"\\t\\t(client {}) loss: {:.5}, acc: {:.5}\".format(pos, local_loss, local_acc))\n client.get_local_accuracy(local_loss, local_acc)\n print()\n # show time \n print(\"\\tTime-> total time: {:.5}s\".format(tot_time))\n for i in client_selected:\n client = client_set[i]\n pos = client.ID \n print(\"\\t\\t(client {}) download: {:.5}s, compute: {:.5}s, upload: {:.5}s\".format(pos, client.log_download_t, client.log_compute_t, client.log_upload_t))\n print(\"\\n\")\n \n # Log Round/Algorithm/data type( num of data, num of label, label type )/accury(local and total/cost time)\n # log_round_time(round_num, algr, client_selected, client_set, (aggr_loss, aggr_acc), tot_time, log_file_name)\n #plt.clf()\n # Screen1.update_glob(aggr_acc, aggr_loss)\n clients, tc, tu = gen_useful_data(client_selected, client_set)\n # Screen1.update_cli(clients, tc, tu)\n # gc.collect()\n for i in range(numOfConnect+1, numOfConnect+numOfPhone+1):\n #print('send to ', i )\n socketServer.send_raw_msg(i, client_set[i-numOfConnect-1].local_loss)\n \n\ndef TS_process_every_round(round_num, socketServer, flg_para, round_log, client_set, num_of_client_connect, K, log_file_name=\"round_time_log.txt\"):\n \n print(\"----{}th round FL\\n\".format(round_num))\n # select clients using MILP\n num_of_client = len(client_set)\n client_fraction_selected = [ i for i in range(num_of_client_connect) ] # avil \n \n # Random selection\n model_name_RS = \"models/standard_model_RS.pkl\"\n client_selected_RS = randomly_select(client_fraction_selected, K)\n #print(client_selected_RS)\n \n # send chosen one\n for i in range(num_of_client_connect+1, num_of_client_connect+numOfPhone+1):\n #print('send to', i)\n if i-1-num_of_client_connect in client_selected_RS: \n socketServer.send_raw_msg(i, 1)\n else:\n socketServer.send_raw_msg(i, 0)\n \n TS_FL_every_algorithm(round_num, socketServer, flg_para, \"RS\", client_selected_RS, client_set, model_name_RS, log_file_name, round_log)\n\n\ndef gen_add_list(num_of_client, dis_info, flg_same_type):\n if flg_same_type == True:\n mean = dis_info[0]\n return [ mean for i in range(num_of_client) ]\n else:\n mean = dis_info[0]\n sig = dis_info[1]\n s = np.random.normal(mean, sig, num_of_client)\n l = [ x for x in s ]\n return l\n\ndef FL_control(SEED, E, K, bt_size, epoch, l_rate, decay_rate, ti, d_f, num_of_client, num_of_client_connect, num_of_round, download_dis_info, compute_dis_info, upload_dis_info, flg_same_type, flg_para):\n log_file = \"round_time_log.txt\"\n f = open(log_file, \"a\")\n the_time = datetime.datetime.now()\n f.write(\"\\n{}\\n\".format(the_time))\n \n np.random.seed(SEED)\n random.seed(SEED)\n socketServer, client_set = FL_server_pre_process(num_of_client, num_of_client_connect, ti, d_f)\n \n # tell num of round\n tell_every_client(socketServer, num_of_client_connect, num_of_round)\n # tell E\n tell_every_client(socketServer, num_of_client_connect, E)\n tell_every_client(socketServer, num_of_client_connect, bt_size)\n tell_every_client(socketServer, num_of_client_connect, epoch)\n tell_every_client(socketServer, num_of_client_connect, l_rate)\n tell_every_client(socketServer, num_of_client_connect, decay_rate)\n # tell random seed \n \n tell_every_client(socketServer, num_of_client_connect, SEED)\n \n # create wave\n l_add_download = gen_add_list(num_of_client, download_dis_info, flg_same_type)\n l_add_compute = gen_add_list(num_of_client, compute_dis_info, flg_same_type)\n l_add_upload = gen_add_list(num_of_client, upload_dis_info, flg_same_type)\n generate_constant_clients(client_set, l_add_download, l_add_compute, l_add_upload)\n\n # Log \n round_log = []\n # do n rounds federated learning\n for i in range(num_of_round):\n TS_process_every_round(i+1, socketServer, flg_para, round_log, client_set, num_of_client_connect, K)\n\n # do some plot here using round_log list\n # e.g\n\n\n\nif __name__ == \"__main__\":\n\n FL_control(\n SEED= 10,\n E= 10, # iteration\n K= 1, # num of choice client\n bt_size=64,\n epoch=1,\n l_rate=0.01,\n decay_rate=0.996,\n ti= 2, # non-iid type 1,2,4,8\n d_f= 0.6, # data fraction\n num_of_client= 10, \n # set number of devices to connect\n num_of_client_connect= 3,\n num_of_round= 4000000,\n download_dis_info=(0,0.5),\n compute_dis_info=(0,0.5), # (mean, sig)\n upload_dis_info=(0,0.5), \n flg_same_type=True, # same distribution or not\n flg_para=False # control parallel or serial\n )\n # plt.show()\n\n\n","repo_name":"WENLIXIAO-CS/FL-IoT-Demo","sub_path":"Fed-IoT-demo-lightly/FL_ServerMain.py","file_name":"FL_ServerMain.py","file_ext":"py","file_size_in_byte":9031,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"73817244668","text":"import argparse\nimport os\nfrom load_data import load_image, load_label\nfrom EM import EM\nfrom metric import confusion_matrices, accuracy, print_metric\nfrom plot import plot_imagine\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_path', type=str, default='../../HW2/HW2-1/', help='')\n parser.add_argument('--max_iter', type=int, default=None, help='')\n parser.add_argument('--delta', type=float, default=None, help='')\n parser.add_argument('--record_path', type=str, default='./', help='')\n parser.add_argument('--metric_path', type=str, default='./', help='')\n\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n args = parse_args()\n X = load_image(os.path.join(args.data_path, 'train-images-idx3-ubyte'))\n y = load_label(os.path.join(args.data_path, 'train-labels-idx1-ubyte'))\n\n pred_cluster, mapping, converge_iter = EM(X, y, max_iter=args.max_iter, delta=args.delta, verbose=True, record_path=args.record_path)\n error_rate = 1 - accuracy(pred_cluster, y, mapping)\n pred_label = mapping[pred_cluster]\n CM = confusion_matrices(pred_label, y)\n print_metric(CM, converge_iter, error_rate, metric_path=args.metric_path)","repo_name":"ericlinqq/NYCU_ML_2023_Spring","sub_path":"HW4/HW4-2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"1403388013","text":"import math\r\nimport pandas\r\nimport time\r\nimport numpy as np\r\nimport sympy\r\nimport matplotlib.pyplot as plt\r\nimport sys\r\n\r\n\r\n# function calculating f(x) for any value of x\r\n# reserved functions is a dictionary for any known functions input as strings\r\ndef f(x_val, function):\r\n x = sympy.symbols('x')\r\n function = sympy.sympify(function)\r\n result = function.evalf(8, subs={x: x_val})\r\n result = round(result, 6) # rounding the result to only 6 decimals places\r\n return result\r\n\r\n# False Position method calculations\r\ndef falseposition(function, xlow, xupper, eps, max_iterations):\r\n\r\n start_time = time.time()\r\n fxl = f(xlow, function) # calculate x lower function\r\n fxu = f(xupper, function) # calculate x upper function\r\n xr = 0\r\n\r\n if fxl*fxu > 0: # checking base condition if False position is valid\r\n print(\"False Position not valid\")\r\n return -1\r\n\r\n # calculating number of iteration which is the minimum of the ( max iterations argument ) and the calculated iterations\r\n iterations = min(int(math.ceil(math.log((xupper - xlow) / eps, 2))), max_iterations)\r\n i = 0\r\n\r\n # a list for each output type\r\n xlower_list = []\r\n xupper_list = []\r\n xr_list = []\r\n fxr_list = []\r\n error_list = []\r\n\r\n while i < iterations:\r\n xlower_list.append(xlow)\r\n xupper_list.append(xupper)\r\n xr = (xlow*fxu - xupper*fxl) / (fxu - fxl)\r\n xr = round(xr, 6) # rounding xr to only 6 decimals places\r\n fxr = f(xr, function)\r\n xr_list.append(xr)\r\n fxr_list.append(fxr)\r\n if fxr == 0: # when x is the root\r\n break\r\n if fxr * fxl > 0: # when x root is the same sign as x lower\r\n xlow = xr\r\n else: # when x root is the same sign as x upper\r\n xupper = xr\r\n\r\n if i == 0 and i != iterations:\r\n error_list.append(np.nan)\r\n i += 1\r\n continue\r\n error = abs((xr_list[i] - xr_list[i - 1]) / xr_list[i])\r\n error_list.append(error)\r\n i += 1\r\n\r\n if error < eps:\r\n break\r\n\r\n end_time = time.time()\r\n elapsed_time = end_time - start_time\r\n\r\n # returning each iteration details in a row of a 2d list to print it using dataframe\r\n data = []\r\n for x in range(iterations):\r\n row = []\r\n row.append(xlower_list[x])\r\n row.append(xupper_list[x])\r\n row.append(xr_list[x])\r\n row.append(fxr_list[x])\r\n row.append(error_list[x])\r\n data.append(row)\r\n data.append(elapsed_time)\r\n return data\r\n\r\n# function to plot the equation\r\ndef plot(equation):\r\n # setting the x - coordinates\r\n x = np.arange(-10, 10, 0.1)\r\n # setting the corresponding y - coordinates\r\n y = []\r\n i = 0\r\n while i < 200:\r\n ans = f(x[i], equation)\r\n y.append(ans)\r\n i += 1\r\n\r\n # plotting the points\r\n plt.plot(x, y)\r\n plt.grid(True, which='both')\r\n\r\n # function to show the plot\r\n plt.show()\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n equation = input(\"Enter function :\\n\")\r\n equation = equation.split(\"=\", 1)[0]\r\n xl = float(input(\"Xl = \"))\r\n xu = float(input(\"Xu = \"))\r\n epsilon = float(input(\"Epsilon = \"))\r\n max_iterations = int(input(\"Maximum Iterations = \"))\r\n falsePosition_data = falseposition(equation, xl, xu, epsilon, max_iterations)\r\n elapsed_time = falsePosition_data[len(falsePosition_data) - 1]\r\n falsePosition_data.pop(len(falsePosition_data) - 1)\r\n root = falsePosition_data[len(falsePosition_data) - 1][2]\r\n precision = falsePosition_data[len(falsePosition_data) - 1][4]\r\n iterations = len(falsePosition_data)\r\n\r\n print(pandas.DataFrame(falsePosition_data, index=range(1, iterations + 1), columns=[\"X lower\", \"X upper\", \"X root\", \"F(x root)\", \"Tolerance\"]))\r\n print(\"\\nApproximate root is = %f\" % root)\r\n print(\"\\nElapsed time is %f seconds\" % elapsed_time)\r\n print(\"\\nPrecision is %f\" % precision)\r\n print(\"\\nNumber of iterations = %d \\n\" % iterations)\r\n plot(equation)","repo_name":"NoureldinHazem/Root-Finding-Methods","sub_path":"falsePosition.py","file_name":"falsePosition.py","file_ext":"py","file_size_in_byte":4432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"21213021451","text":"import json\nimport os\nfrom certvalidator import CertificateValidator, ValidationContext, errors\nimport boto3\nfrom asn1crypto import pem\n\n'''\nLets load our truststore from s3. Doing this outside of handler function so that this will be loaded only on coldstart.\nIf the truststore contents change, you need to update the lambda env var 'TRUSTSTORE_FILE_VERSIONID'\nwith the new files versionId. And also update the same in 'API Gateway > Custom domain names > Domain details > Truststore version' and wait till Status becomes Available.\nIf APi Gw finds some problem with the truststote, such as could not find complete chain, it will display a warning. The warning details will tell you which cert it has a problem with and the problem. You need to fix the truststore chain till this warning goes away.\n'''\n\ns3_client = boto3.client('s3')\n\nbucket = os.environ.get('TRUSTSTORE_BUCKET')\nkey = os.environ.get('TRUSTSTORE_FILENAME')\nversionId = os.environ.get('TRUSTSTORE_FILE_VERSIONID')\n\ndownload_path = '/tmp/{}'.format(key)\ns3_client.download_file(bucket, key, download_path, ExtraArgs={'VersionId': versionId})\n\ntrust_roots = []\nwith open(download_path, 'rb') as f:\n for _, _, der_bytes in pem.unarmor(f.read(), multiple=True):\n trust_roots.append(der_bytes)\n\ndef lambda_handler(event, context):\n print(\"Received event: \" + json.dumps(event, indent=2))\n ''' Get the client cert from lambda event '''\n cert = event[\"requestContext\"][\"authentication\"][\"clientCert\"][\"clientCertPem\"].encode()\n\n '''\n hard-fail mode, any error in checking revocation is considered a failure. However, if there is no known source of revocation information, it is not considered a failure.\n This allows us to keep using self signed certs too.\n '''\n context = ValidationContext(allow_fetching=True, revocation_mode=\"hard-fail\", trust_roots=trust_roots)\n\n try:\n validator = CertificateValidator(cert, validation_context=context)\n validator.validate_usage(\n set(['digital_signature', 'key_encipherment']),\n set(['server_auth', 'client_auth']),\n True\n )\n except Exception as inst:\n print(type(inst))\n print(inst.args)\n print(inst)\n print(\"The certificate could not be validated\")\n return {\n \"isAuthorized\": \"false\",\n \"context\": {\n \"exception\": str(inst.args)\n }\n }\n else:\n print(\"The certificate is ok\")\n return {\n \"isAuthorized\": \"true\",\n \"context\": {\n \"exception\": None\n }\n }","repo_name":"kmkale/apigw-custom-auth-mtls","sub_path":"mtls_custom_auth/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"6"} +{"seq_id":"74576264826","text":"import tkinter as tk\nfrom tkinter import font\nfrom datetime import date\nimport time\nfrom twisted.internet import tksupport, reactor\nfrom twisted.internet.protocol import DatagramProtocol\n\ndef get_checksum(string, num_digits=3):\n return abs(hash(string)) % (10 ** num_digits)\n \ndef ParseStreamingUDP(msg):\n # Streaming Protocol Sample\n # #|1.0|VEH_MHAFB1|CMD|123|45|56837|S,0|A,0|B,100|G,1|V,0|X,0,1,0,0,0,,,|Y,0,0,0,0,0,,,|Z,0,0,0,,,,,|C,XXX\n # 0 # Header\n # | Delimiter\n # 1 1.0 Message Version\n # 2 VEH_MHAFB1 Vehicle name\n # 3 CMD Command Message to Robotic Asset\n # 4 123 Session ID\n # 5 45 Message Sequence\n # 6 56837 Time stamp, ms from midnight\n # 7 0 Steering Angle, Steering Wheel Centered\n # 8 0 Throttle Percentage, 0%\n # 9 100 Brake Percentage, 100%\n # 10 1 Transmission state, 1=Park\n # 11 0 Vehicle speed in mph\n # 12 Vehicle State No Estop, No Pause, Enabled, Manual\n # 13 Vehicle Sequence Not Initiating or shutting down, No Start, No Steering Cal, No Shifting\n # 14 Vehicle Mode Progressive Steering, Progressive Braking, No Speed Control\n # 15 XXX Default Checksum\n parsed_UDP_msg = msg.split('|')\n # check that msg starts with a proper header character\n if parsed_UDP_msg[0] != '#':\n valid = False\n #verify checksum\n c,checksum = parsed_UDP_msg[15].split(',')\n if c == 'C':\n n = len(parsed_UDP_msg[15]) + 1#-n = start idx of checksum in msg\n chk = get_checksum(msg[:-n])\n if checksum.upper() == 'XXX' or chk == int(checksum):\n valid = True\n else:\n valid = False\n else:\n valid = False\n # populate the stream_in_dictionary\n strminDict = {}\n strminDict['Checksum'] = checksum\n strminDict['Version'] = parsed_UDP_msg[1]\n strminDict['Name'] = parsed_UDP_msg[2]\n strminDict['Type'] = parsed_UDP_msg[3]\n strminDict['Session'] = parsed_UDP_msg[4]\n strminDict['Sequence'] = parsed_UDP_msg[5]\n strminDict['TimeStamp'] = parsed_UDP_msg[6]\n\n # Get the steering command\n c,val = parsed_UDP_msg[7].split(',')\n if c == 'S':\n strminDict['Steering'] = int(val)\n else:\n valid = False\n\n # Get the throttle command\n c,val = parsed_UDP_msg[8].split(',')\n if c == 'A':\n strminDict['Throttle'] = int(val)\n else:\n valid = False\n\n # Get the break command\n c,val = parsed_UDP_msg[9].split(',')\n if c == 'B':\n strminDict['Brake'] = int(val)\n else:\n valid = False\n\n # Get the transission state (1=Parked)\n c,val = parsed_UDP_msg[10].split(',')\n if c == 'G':\n strminDict['Trans'] = int(val)\n else:\n valid = False\n\n # Get the velocity\n c,val = parsed_UDP_msg[11].split(',')\n if c == 'V':\n strminDict['Velocity'] = int(val)\n else:\n valid = False\n\n #break out the state parameters\n state_list = parsed_UDP_msg[12].split(',')\n if state_list.pop(0) == 'X':\n strminDict['State_Estop'] = state_list[0]\n strminDict['State_Paused'] = state_list[1]\n strminDict['State_Enable'] = state_list[2]\n strminDict['State_Manual'] = state_list[3]\n strminDict['State_L1'] = state_list[4]\n strminDict['State_L2'] = state_list[5]\n strminDict['State_Motion'] = state_list[6]\n strminDict['State_Reserved7'] = state_list[7]\n else:\n valid = False\n\n #break out the process parameters\n process_list = parsed_UDP_msg[13].split(',')\n if process_list.pop(0) == 'Y':\n strminDict['Process_Operation']=process_list[0]\n strminDict['Process_Shutdown']=process_list[1]\n strminDict['Process_Start']=process_list[2]\n strminDict['Process_SteeringCal']=process_list[3]\n strminDict['Process_TransShift']=process_list[4]\n strminDict['Process_Reserved5']=process_list[5]\n strminDict['Process_Reserved6']=process_list[6]\n strminDict['Process_Reserved7']=process_list[7]\n else:\n valid = False\n\n #break out the mode parameters\n mode_list = parsed_UDP_msg[14].split(',')\n if mode_list.pop(0) == 'Z':\n strminDict['Mode_ProgressiveSteeringDisable']=mode_list[0]\n strminDict['Mode_ProgressiveBrakingDisable']=mode_list[1]\n strminDict['Mode_VelocityControlEnable']=mode_list[2]\n strminDict['Mode_Reserved3']=mode_list[3]\n strminDict['Mode_Reserved4']=mode_list[4]\n strminDict['Mode_Reserved5']=mode_list[5]\n strminDict['Mode_Reserved6']=mode_list[6]\n strminDict['Mode_Reserved7']=mode_list[7]\n else:\n valid = False\n strminDict['Valid'] = valid\n return strminDict\n\nclass RX(DatagramProtocol):\n def __init__(self, widget):\n super().__init__()\n self.widget = widget\n self.params = {}\n\n def datagramReceived(self, datagram, address):\n self.msg = datagram.decode('utf-8')\n self.widget.set(self.msg) # update the label\n # print(self.params)\n #self.transport.write(datagram, address) # cause recursive issue\n\nclass RX_GUI():\n def __init__(self, msg_dict):\n self.width = 15\n self.root = tk.Tk()\n self.root.protocol('WM_DELETE_WINDOW', self.quit)\n self.init_params(msg_dict)\n self.configure_port()\n # self.start_button()\n self.show_params()\n tksupport.install(self.root)\n self.quit_button()\n reactor.run()\n\n def configure_port(self):\n self.port_label = tk.Label(self.root,text=\"Enter Port #:\", width=self.width )\n self.port_label.grid(column=0, sticky = tk.E, row=1)\n self.port_label['font'] = font.Font(weight='bold')\n self.port_field = tk.Entry(self.root,width=self.width)\n self.port_field.grid(column=1, sticky = tk.W, row=1)\n self.port_field.insert(tk.END, '7200')\n self.msg = tk.StringVar()\n self.msg.set('')\n self.button = tk.Button(self.root, text=\"Start Listening\",\n command=self.start_listening, bg='green')\n self.button.grid(column=3, columnspan=2, row=1)\n\n def start_listening(self):\n self.button.destroy()\n self.rx_port = reactor.listenUDP(int(self.port_field.get()), RX(self.msg))\n\n def quit_button(self):\n self.quit_button = tk.Button(self.root,text=\"Exit\",command=self.quit)\n self.quit_button.grid(columnspan = 4, sticky = tk.W+tk.E)\n self.quit_button['font'] = font.Font(size=16, weight='bold')\n\n def show_params(self, param_cnt=34):\n l = tk.Label(self.root,text=f\"Message Parameters:\" )\n l['font'] = font.Font(weight='bold', underline=1)\n l.grid(columnspan = 4, sticky = tk.W+tk.E,row=3)\n\n self.msg_lbl = tk.Label(self.root, textvariable=self.msg)\n self.msg_lbl.grid(row=4, columnspan=4)\n self.msg.trace('w', self.parse_msg)\n\n def init_params(self, msg_dict):\n self.labels = {}\n self.params = {}\n for key in msg_dict:\n if 'Reserved' in key:\n continue\n self.params[key] = tk.StringVar()\n self.params[key].set('')\n self.labels[key] = [tk.Label(self.root, text=f\"{key}:\"),\n tk.Label(self.root, textvariable=self.params[key])]\n\n def parse_msg(self, *args):\n param_cnt=len(self.params)\n parsed_msg = ParseStreamingUDP(self.msg.get())\n row_offset = 6\n row = 0\n for key in self.params:\n row_num = row_offset + int(row%(param_cnt//2))\n col = int(row//(param_cnt//2))*2\n row+=1\n self.params[key].set(parsed_msg[key])\n self.labels[key][0].grid(column = col, row=row_num)\n self.labels[key][1].grid(column = col+1, row=row_num)\n\n def quit(self):\n reactor.stop()\n self.root.destroy()\n\nif __name__ == \"__main__\":\n strmDict = {\n 'Version': '1.0',\n 'Type': 'CMD',\n 'Name': '',\n 'Session': '123',\n 'Sequence': '45',\n 'Steering': 0,\n 'Throttle': 0,\n 'Brake': 100,\n 'Trans': 1,\n 'Velocity': 0,\n 'State_Estop': '0',\n 'State_Paused': '1',\n 'State_Manual': '0',\n 'State_Enable': '0',\n 'State_L1': '0',\n 'State_L2': '',\n 'State_Motion': '',\n 'State_Reserved7': '',\n 'Process_Operation': '0',\n 'Process_Shutdown': '0',\n 'Process_Start': '0',\n 'Process_SteeringCal': '0',\n 'Process_TransShift': '0',\n 'Process_Reserved5': '',\n 'Process_Reserved6': '',\n 'Process_Reserved7': '',\n 'Mode_ProgressiveSteeringDisable': '0',\n 'Mode_ProgressiveBrakingDisable': '0',\n 'Mode_VelocityControlEnable': '0',\n 'Mode_Reserved3': '',\n 'Mode_Reserved4': '',\n 'Mode_Reserved5': '',\n 'Mode_Reserved6': '',\n 'Mode_Reserved7': '',\n 'Checksum': 'XXX',\n 'TimeStamp': '56837',\n 'Valid': True,\n }\nRX_GUI(strmDict)\n","repo_name":"dan-goodrick/Kairos_udp","sub_path":"rx_udp.py","file_name":"rx_udp.py","file_ext":"py","file_size_in_byte":9434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"12906645730","text":"from django.conf.urls import url, include\nfrom django.contrib.auth.decorators import login_required\n\nfrom .views import UserSettingsView, CredentialsVeiw, CredentialsAddView, CredentialsEditView\n\nurlpatterns = [\n url(r'^settings/(?P[0-9]+)/$',\n login_required(UserSettingsView.as_view()), name='settings'),\n\n url(r'^settings/credentials/$',\n CredentialsVeiw.as_view(), name='credentials'),\n\n url(r'^settings/credentials/add/$',\n login_required(CredentialsAddView.as_view()), name='add_credentials'),\n\n url(r'^settings/credentials/edit/(?P[0-9]+)/$',\n login_required(CredentialsEditView.as_view()), name='edit_credentials'),\n\n url(r'^', include('registration.backends.hmac.urls')),\n]\n","repo_name":"Tyapkin/spicy-ebay","sub_path":"apps/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"28734473915","text":"from PyQt5 import QtCore, QtGui, QtWidgets\n\nimport numpy as np\n\nfrom .dataplotter import DataPlotter\n\nfrom simuplot.data import DATATYPES, DataZoneError, MONTHS, TimeInterval\n\nHEAT_SOURCES = ['HEATING_RATE',\n 'PEOPLE_HEATING_RATE',\n 'LIGHTING_HEATING_RATE',\n 'EQUIPMENT_HEATING_RATE',\n 'WINDOWS_HEATING_RATE',\n 'OPAQUE_SURFACES_HEATING_RATE',\n 'INFILTRATION_HEATING_RATE',\n ]\n\nclass HeatGainPileBar(DataPlotter):\n\n def __init__(self, building, color_chart):\n\n super(HeatGainPileBar, self).__init__(building, color_chart)\n\n self._name = self.tr(\"Heat gains per month\")\n\n # Results dict\n self._heat_build_zone = None\n\n # Set column number and add headers\n self.dataTable.setColumnCount(13)\n self.dataTable.setHorizontalHeaderLabels(\n [self.tr('Heat sources')] + [m[0] for m in MONTHS])\n self.dataTable.horizontalHeader().setSectionResizeMode(\n QtWidgets.QHeaderView.ResizeToContents)\n\n # Initialize table with one row per heat source with checkbox\n self.dataTable.setRowCount(len(HEAT_SOURCES))\n for i, val in enumerate(HEAT_SOURCES):\n # DATATYPES is a dict of type:(unit, string)\n hs_name = QtCore.QCoreApplication.translate(\n 'Data', DATATYPES[val][1])\n name_item = QtWidgets.QTableWidgetItem(hs_name)\n name_item.setFlags(QtCore.Qt.ItemIsUserCheckable |\n QtCore.Qt.ItemIsEnabled)\n name_item.setCheckState(QtCore.Qt.Checked)\n\n self.dataTable.setItem(i, 0, name_item)\n\n # Refresh plot when zoneSelectBox is modified\n self.zoneSelectBox.activated.connect(self.refresh_table_and_plot)\n\n # Refresh plot when zone is clicked/unclicked\n self.dataTable.itemClicked.connect(self.refresh_plot)\n\n @property\n def name(self):\n return self._name\n\n @QtCore.pyqtSlot()\n def refresh_data(self):\n\n # Get zones in building, sorted by name\n zones = self._building.zones\n zones.sort()\n\n # Set combobox with zone names\n # and add 'Building' as a ficticious \"all zones\" zone\n self.zoneSelectBox.clear()\n self.zoneSelectBox.addItems(zones)\n self.zoneSelectBox.addItem(self.tr('Building'))\n self.zoneSelectBox.setCurrentIndex(self.zoneSelectBox.count() - 1)\n\n # Compute heat gain per source in each zone\n self._heat_build_zone = {}\n for name in zones:\n zone = self._building.get_zone(name)\n # Compute heat gains for desired study period\n self._heat_build_zone[name] = {}\n for hs in HEAT_SOURCES:\n try:\n # Get the Array object for current heat source\n val_array = zone.get_array(hs, 'HOUR')\n except DataZoneError:\n # If hourly heat source data not available,\n # \"mark it zero, Donnie\", for each month\n self._heat_build_zone[name][hs] = np.zeros(12)\n else:\n # Create array of monthly energy in [kWh]\n self._heat_build_zone[name][hs] = np.array(\n [val_array.sum(TimeInterval.from_month_nb(m))\n for m in range(len(MONTHS))]) / 1000\n\n # Compute heat gain per source for building by summing all zones\n self._heat_build_zone['Building'] = {}\n if len(zones):\n for hs in HEAT_SOURCES:\n self._heat_build_zone['Building'][hs] = np.sum(\n [self._heat_build_zone[zone][hs] for zone in zones],\n axis=0)\n else:\n # If no Zone data, set 0 values to Building for each source\n for hs in HEAT_SOURCES:\n self._heat_build_zone['Building'][hs] = np.zeros(12)\n\n # Write in Table and draw plot\n self.refresh_table_and_plot()\n\n @QtCore.pyqtSlot()\n def refresh_table_and_plot(self):\n\n # Current zone or building displayed\n if self.zoneSelectBox.currentIndex() == self.zoneSelectBox.count() - 1:\n cur_zone = 'Building'\n else:\n cur_zone = self.zoneSelectBox.currentText()\n\n # Display Zone or building values in table\n for i, hs in enumerate(HEAT_SOURCES):\n # Get current heat gains for heat source in the zone\n hs_value = self._heat_build_zone[cur_zone][hs]\n\n for j, monthly_val in enumerate(hs_value):\n # Set item value for month column\n val_item = QtWidgets.QTableWidgetItem()\n val_item.setData(QtCore.Qt.DisplayRole, int(monthly_val))\n val_item.setFlags(QtCore.Qt.ItemIsEnabled)\n self.dataTable.setItem(i, j+1, val_item)\n\n # Uncheck heat source name if value is zero\n name_item = self.dataTable.item(i, 0)\n if np.sum(hs_value) == 0:\n name_item.setCheckState(QtCore.Qt.Unchecked)\n else:\n name_item.setCheckState(QtCore.Qt.Checked)\n\n # Draw plot\n self.refresh_plot()\n\n @QtCore.pyqtSlot()\n def refresh_plot(self):\n\n canvas = self.plotWidget.canvas\n\n # Clear axes\n canvas.axes.cla()\n canvas.set_tight_layout_on_resize(False)\n\n # Get all heat sources names\n hs_names = [self.dataTable.item(i, 0).text()\n for i in range(self.dataTable.rowCount())]\n\n # Compute heat source sum and\n # create plot list removing unchecked values\n name_plot = []\n value_plot = []\n sum_values = 0\n for i in range(self.dataTable.rowCount()):\n\n month_vals = [int(self.dataTable.item(i, j).text())\n for j in range(1, len(MONTHS)+1)]\n sum_values += np.sum(np.abs(month_vals))\n\n if self.dataTable.item(i, 0).checkState() == QtCore.Qt.Checked:\n name_plot.append(self.dataTable.item(i, 0).text())\n value_plot.append(month_vals)\n\n # If sum is 0, heat gains and losses are 0. Do not plot anything.\n if sum_values != 0:\n\n # Create a uniform x axis\n ind = np.arange(len(MONTHS))\n\n # Create a colormap adapted to HEAT_SOURCES\n # TODO: move to __init__ ?\n hs_cmap = {hs_names[i] : self._color_chart[i]\n for i in range(len(HEAT_SOURCES))}\n\n # Create and draw bar chart\n prev_height = np.zeros(len(MONTHS))\n width = 0.8\n for i, (hs_name, hs_vals) in enumerate(zip(name_plot, value_plot)):\n canvas.axes.bar(ind,\n hs_vals,\n width=width,\n edgecolor='white',\n color=hs_cmap[hs_name],\n bottom=prev_height,\n label=hs_name)\n prev_height += np.array(hs_vals)\n\n # Add text for labels, title and axes ticks\n canvas.axes.set_ylabel(self.tr('Heat gains / loss [kWh]'))\n canvas.axes.set_xticks(ind + width/2)\n canvas.axes.set_xticklabels([m[0] for m in MONTHS], ha='center')\n\n # Set title\n title_str = self.tr('Heat gains repartition')\n canvas.axes.set_title(title_str, y=1.05)\n\n # Add legend\n legend = canvas.axes.legend(loc='upper center',\n bbox_to_anchor=(0.5, -0.05),\n fancybox=True, ncol=4)\n for text in legend.texts:\n text.set_size('small')\n\n canvas.set_tight_layout_on_resize(False)\n\n # Draw plot\n canvas.draw()\n\n","repo_name":"Nobatek/simuplot","sub_path":"src/simuplot/dataplotter/heatgainpilebar.py","file_name":"heatgainpilebar.py","file_ext":"py","file_size_in_byte":7907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"16630272780","text":"import os\n\nfrom ke_logic.terminology_extraction import TerminologyExtraction\nfrom ke_logic.support import Support\nfrom ke_root import ROOT_OUTPUT, ROOT_INPUT\n\n\nROOT_INPUT = ROOT_INPUT + '/spanish_billion_words/'\ndef import_corpus(ruta = ROOT_INPUT):\n result = []\n i = 0\n contenido = os.listdir(ruta)\n for elemento in contenido:\n archivo = ruta + os.sep + elemento\n texto = ''\n if os.path.isfile(archivo):\n with open(archivo, 'r', encoding='ascii', errors='ignore') as archivo:\n for linea in archivo:\n texto += linea\n result.append([i, texto])\n i += 1\n archivo.close()\n return result\n\n#dict_corpus_terms = {}\n#te = TerminologyExtraction()\n#support = Support()\n\nprint(import_corpus())\n\n\n\n# raw_corpusA = support.import_corpus('TASS2018',key=0, content=2,encoding='utf-8')\n# corpusA = te.extracting_sentences(raw_corpusA)\n# dict_corpus_terms = te.get_terminology([corpusA],list_patterns=['NOUN'])\n# dict_corpus_terms_frequency = te.calulated_frecuency(dict_corpus_terms, False)\n# dict_normalized_corpus = te.normalized_corpus(dict_corpus_terms_frequency)\n# corpus_cut_off = te.corpus_cut_off(dict_normalized_corpus, 100)\n# support.export_corpus_cvs('TerminologyTASS',corpus_cut_off)","repo_name":"EdwinPuertas/KnowledgeExtraction","sub_path":"test/testing_corpus_cardellino.py","file_name":"testing_corpus_cardellino.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"39477107205","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\n\nclass BkmySpider(scrapy.Spider):\n name = 'bkmy'\n allowed_domains = ['baikemy.com']\n start_urls = ['http://www.baikemy.com/']\n\n def parse(self, response):\n\n search_url = 'https://www.baikemy.com/ask/asksquare'\n\n yield scrapy.Request(url=search_url,callback=self.next1)\n\n def next1(self,response):\n node_list =response.xpath('//*[@id=\"tab_curr\"]/li/a/@href').extract()\n for node in node_list:\n link = 'https://www.baikemy.com' + node\n yield scrapy.Request(url=link,callback=self.next2)\n\n def next2(self,response):\n node_list =response.xpath('//*[@id=\"zx_content\"]/div/div/ul/li/div/a/@href').extract()\n for node in node_list:\n link = 'https://www.baikemy.com' + node + '?pageIndex='\n for i in range(10):\n link1 = link + str(i)\n yield scrapy.Request(url=link1,callback=self.next3)\n\n def next3(self,response):\n node_list = response.xpath('//*[@id=\"zx_content\"]/div[3]/div/table//tr/td/span/a/@href').extract()\n\n for node in node_list:\n yield scrapy.Request(url=node,callback=self.next4)\n\n def next4(self,response):\n\n temp = {}\n\n temp['questions'] = ''.join(response.xpath('/html/body/div/div/div/div[1]/div[1]/text()').extract())\n\n temp['des'] = ''.join(response.xpath('/html/body/div[6]/div/div/div/div[4]/text()').extract())\n\n temp['answer'] = ''.join(response.xpath('/html/body/div[6]/div/div/div/div[6]/div[2]/text()').extract())\n\n temp['url'] = response.url\n\n yield temp","repo_name":"zhang8929/zhangyuguang","sub_path":"zyg/spider/BKMY/BKMY/spiders/bkmy.py","file_name":"bkmy.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"584707917","text":"import os, sys\nimport numpy as np\nfrom scipy.io import loadmat,savemat\nimport glob\nfrom scipy.signal import savgol_filter\nimport argparse\n\nparser = argparse.ArgumentParser(description='netface_setting')\nparser.add_argument('--param_folder', type=str, default='/root/FACIAL/video_preprocess/train1_deep3Dface')\n\nopt = parser.parse_args()\n\nparam_folder = opt.param_folder\n\nmat_path_list = sorted(glob.glob(os.path.join(param_folder, '*.mat')))\nlen_mat = len(mat_path_list)\nfaceshape = np.zeros((len_mat, 257),float)\n\nfor i in range(1,len_mat+1):\n d = loadmat(os.path.join(param_folder,str(i).zfill(6)+'.mat'))\n faceshape[i-1,0:80] = d['id'][0,:]\n faceshape[i-1,80:80+64] = d['exp'][0,:]\n faceshape[i-1,80+64:80+64+80] = d['tex'][0,:]\n faceshape[i-1,80+64+80:80+64+80+3] = d['angle'][0,:]\n faceshape[i-1,80+64+80+3:80+64+80+3+27] = d['gamma'][0,:]\n faceshape[i-1,80+64+80+3+27:80+64+80+3+27+3] = d['trans'][0,:]\n\n\nframes_out_path = os.path.join(param_folder,'train1.npz')\nnp.savez(frames_out_path, face = faceshape)","repo_name":"ProgrammerManstein/FACIAL","sub_path":"FACIAL/face_render/handle_netface.py","file_name":"handle_netface.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"11880138973","text":"from app.models import *\nfrom django.contrib.auth.models import User\nfrom rest_framework import serializers\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ['id', 'username', 'email', 'first_name']\n\n \nclass DronSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Dron\n fields = [\n 'inventario',\n 'velocidad',\n 'nombre',\n 'desc',\n 'peso_maximo',\n 'precio',\n 'icono',\n 'id',\n 'url'\n ]\n \nclass EnvioSerializer(serializers.HyperlinkedModelSerializer):\n dron_id = serializers.PrimaryKeyRelatedField(many=False, read_only=False,queryset=Dron.objects.all())\n user_id = UserSerializer(many=False, read_only=True)\n class Meta:\n model = Envio\n fields = [ 'user_id', 'dron_id', 'lat_inicio', 'lon_inicio', 'hora_inicio', 'lat_fin', 'lon_fin', 'hora_fin']\n \n def create(self, validated_data):\n validated_data['dron']=validated_data.pop('dron_id')\n validated_data['user_id'] = self.context['request'].user\n return Envio.objects.create(**validated_data)","repo_name":"emilianofh01/UABCSenvios","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"21947778765","text":"#!/usr/bin/python3\nimport datetime\nimport json\n\nimport googleapiclient.discovery\nfrom google.oauth2.credentials import Credentials\nfrom googleapiclient.http import MediaFileUpload\n\nfrom smtplib import SMTP_SSL\nfrom email.message import EmailMessage\n\nNOW = datetime.datetime.now(tz=datetime.timezone.utc)\nwith open('/opt/webcast/recurring.json') as f:\n RECURRING = json.load(f)\n\n\ndef convert_time(time: str):\n if not time:\n return ''\n\n return datetime.datetime.fromisoformat(time.replace('Z', '-00:00'))\n\nstream_ids = {\n \"wardname\": \"STREAM_ID_FROM_GOOGLE_API\"\n}\n\nfor ward in stream_ids.keys():\n creds = Credentials.from_authorized_user_file(f'/opt/webcast/auth/{ward}.json')\n youtube = googleapiclient.discovery.build(\"youtube\", \"v3\", credentials=creds)\n\n broadcasts = youtube.liveBroadcasts().list(\n part=\"id,snippet,contentDetails,status\",\n mine=True,\n maxResults=50\n ).execute()\n\n for broadcast in broadcasts['items']:\n if not broadcast['snippet'].get('scheduledStartTime', None):\n youtube.liveBroadcasts().delete(id=broadcast['id']).execute()\n continue\n\n endTime = convert_time(broadcast['snippet'].get('scheduledEndTime', ''))\n if not endTime:\n endTime = convert_time(broadcast['snippet']['scheduledStartTime']) + datetime.timedelta(hours=1)\n\n if NOW > endTime and broadcast['status']['lifeCycleStatus'] != 'complete':\n stream_id = stream_ids.get(ward, None)\n stream = youtube.liveStreams().list(\n part=\"id,status\",\n id=stream_id\n ).execute()['items'][0]\n if (stream['status']['streamStatus'] == 'inactive') or (NOW > endTime + datetime.timedelta(minutes=15)):\n youtube.liveBroadcasts().transition(part='id', id=broadcast['id'], broadcastStatus='complete').execute()\n print(f\"Marked broadcast for {ward} complete ({broadcast['id']})\")\n print(f\"Reason: \", end='')\n print(f\"Stream status ({stream['status']['streamStatus']})\" if stream['status']['streamStatus'] == 'inactive' else \"Time exceeded 15 minutes past end time\")\n\n if broadcast['status']['lifeCycleStatus'] == 'complete' and datetime.datetime.now().day != endTime.day:\n with open('/opt/webcast/clerk_emails.json') as f:\n clerks = json.load(f)\n viewers = round(int(youtube.videos().list(part='statistics', id=broadcast['id']).execute()['items'][0]['statistics']['viewCount']) * 2.1)\n msg = EmailMessage()\n msg[\"Subject\"] = \"Online YouTube Meeting Attendance\"\n msg[\"From\"] = \"Webcast \"\n msg[\"To\"] = clerks[ward]\n msg.set_content(f\"The number of individuals watching {broadcast['snippet']['title']} online on {convert_time(broadcast['snippet']['scheduledStartTime']).strftime('%d %b %Y')} was {viewers}.\\n\\n\\nThis is an automated message. Please do not respond.\")\n with SMTP_SSL('SMTP_SERVER_HERE', 465) as smtp:\n smtp.login('TheEmailYouSendFrom@gmail.com', 'ITS_PASSWORD')\n smtp.send_message(msg)\n smtp.quit()\n youtube.liveBroadcasts().delete(id=broadcast['id']).execute()\n print(f\"Deleted broadcast on {ward} ({broadcast['id']})\")\n\n if broadcast['contentDetails'].get(\"boundStreamId\", \"\") != stream_ids.get(ward, \"NOT FOUND\"):\n youtube.liveBroadcasts().bind(\n id=broadcast['id'],\n part=\"id\",\n streamId=stream_ids.get(ward, '')\n ).execute()\n print(f\"Attempted to bind stream to broadcast for {ward}\")\n\n for event in RECURRING[ward]:\n changeInDays = event['day'] - datetime.datetime.now().weekday()\n if changeInDays < 0:\n changeInDays += 7\n recurringDate = datetime.datetime.now() + datetime.timedelta(days=changeInDays)\n startTime = datetime.datetime.combine(recurringDate, datetime.time(*[int(x) for x in event['start'].split(':')]))\n endTime = datetime.datetime.combine(recurringDate, datetime.time(*[int(x) for x in event['end'].split(':')]))\n startTime = startTime.replace(tzinfo=NOW.astimezone().tzinfo)\n endTime = endTime.replace(tzinfo=NOW.astimezone().tzinfo)\n\n if startTime not in [convert_time(x['snippet']['scheduledStartTime']) for x in broadcasts['items']] and startTime > NOW:\n new = youtube.liveBroadcasts().insert(\n part='id,snippet,contentDetails,status',\n body={\n 'snippet': {\n 'title': event['title'],\n 'scheduledStartTime': startTime.isoformat(),\n 'scheduledEndTime': endTime.isoformat(),\n },\n 'contentDetails': {\n 'enableAutoStart': 'true',\n },\n 'status': {\n 'privacyStatus': 'public',\n 'selfDeclaredMadeForKids': 'true',\n },\n }\n ).execute()\n youtube.liveBroadcasts().bind(\n id=new['id'],\n part=\"id\",\n streamId=stream_ids.get(ward, '')\n ).execute()\n\n","repo_name":"ChickenDevs/webcast","sub_path":"code/scheduler/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"6"} +{"seq_id":"10035850873","text":"\"\"\"\nRun script for a pick and place Gym environment featuring a Fetch robot.\nCan be used to collect expert trajectories, replay recorded trajectories or\nrun and evaluate a controller.\n\nExample calls:\n\n* Simulation of expert trajectories with onscreen rendering:\nLD_PRELOAD=\"/usr/lib/x86_64-linux-gnu/libGLEW.so\" python3 gym_pickplace.py \\\n --rendering_mode viewer\n\n* Simulation of expert trajectories with video rendering:\npython3 gym_pickplace.py \\\n --rendering_mode video\n\n* Running a controller:\npython3 gym_pickplace.py \\\n --shapes pad1-cube1 \\\n --sim_mode controller \\\n --model_dir ../models/geeco-f/pick11 \\\n --goal_condition none \\\n --rendering_mode video \\\n --debug\n\"\"\"\n\nimport argparse\nimport os\nimport pickle\nimport csv\nimport json\n\nimport gym\nfrom gym.envs.registration import register\nfrom mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport numpy as np\nfrom PIL import Image\nfrom tqdm import tqdm\n\nfrom data.geeco_gym import load_target_frame\nfrom mj_engine.engine.recorder import MjVideoRecorder\nfrom models.e2evmc.predictor import E2EVMCPredictor, GoalE2EVMCPredictor\nfrom utils.runscript import save_run_command\n\n\n#region: CLI arguments\n\nARGPARSER = argparse.ArgumentParser(\n description='Collect data for a simple block stacking task with a Fetch robot in a\\\n gym environment.')\nARGPARSER.add_argument(\n '--wrk_dir', type=str, default='../logs/gym_pickplace',\n help=\"The path to the working directory for this run (where logs, videos \\\n etc. will be stored).\")\nARGPARSER.add_argument(\n '--shapes', type=str, default='pad2-cube2',\n help=\"The shape set used for stacking. \\\n Available: pad1-cube1 | pad2-cube1 | pad1-cube2 | pad2-cube2 | \\\n pad2-cube2-clutter4 | pad2-cube2-clutter12 | \\\n ball-cup | bridge-pad | diamond-pad | nut-cone\")\nARGPARSER.add_argument(\n '--sim_mode', type=str, default='collect',\n help=\"The simulation mode to use: \\\n collect = collect expert data \\\n replay = replay from control buffer \\\n random = random freestyle control \\\n controller = run with controller\")\nARGPARSER.add_argument(\n '--max_episode_steps', type=int, default=-1,\n help=\"Max. simulation steps in one episode. If < 0, use defaults.\")\nARGPARSER.add_argument(\n '--dry_run', default=False, action='store_true',\n help=\"Saves images of initial configurations without running the simulation. \\\n Only effective in 'collect' mode.\")\nARGPARSER.add_argument(\n '--init_states', type=str, default='',\n help=\"The path to a CSV file containing initial qpos of objects.\")\n# --- data collection options\nARGPARSER.add_argument(\n '--start_idx', type=int, default=0,\n help=\"Index of the first record to be collected.\")\nARGPARSER.add_argument(\n '--end_idx', type=int, default=100,\n help=\"Index of the last record to be collected.\")\n# --- replay options\nARGPARSER.add_argument(\n '--replay_buffer', type=str, default='../data/gym-pick-pad2-cube2-v4/data/replay_buffer_0001.pkl',\n help=\"The path to the buffer file to be replayed. Only used with --sim_mode=replay.\")\n# --- control options\nARGPARSER.add_argument( # determines which controller to use\n '--controller', type=str, default='e2evmc',\n help=\"Controller model to use. Options are: e2evmc. \\\n e2evmc = E2E visuomotor control (reflex), works in all goal_conditon modes\")\nARGPARSER.add_argument( # determines which predictor mode to use\n '--goal_condition', type=str, default='none',\n help=\"Conditioning mode of the reflex. Options are: none | target | inter_targets. \\\n none = no goal provided, unconditional reflex \\\n target = target image provided, conditional reflex \\\n inter_targets = intermediate target images provided, conditional reflex\")\nARGPARSER.add_argument(\n '--model_dir', type=str, default='../models/geeco-f/pick11',\n help=\"Directory from where the controller model is loaded.\")\nARGPARSER.add_argument(\n '--checkpoint_name', type=str, default=None,\n help=\"Specific checkpoint to load. If none, load latest in model_dir.\")\nARGPARSER.add_argument(\n '--dataset_dir', type=str, default='../data/gym-pick-pad2-cube2-v4/',\n help=\"Dataset from which evaluation data is loaded.\")\nARGPARSER.add_argument(\n '--tfrecord_list', type=str, default='',\n help=\"The path to txt file containing tfrecords to be evaluated on.\")\n# --- randomization options\nARGPARSER.add_argument(\n '--background_video', type=str, default='',\n help=\"The path to the distractor video to be looped in the background. If empty, no video is used.\")\n# --- rendering options\nARGPARSER.add_argument(\n '--rendering_mode', type=str, default='viewer',\n help=\"The rendering mode to use: viewer | video | tfrecord\")\nARGPARSER.add_argument(\n '--frame_res', type=int, nargs=2, default=[256, 256],\n help=\"Resolution of the recorded camera frames as (width, height).\")\nARGPARSER.add_argument(\n '--observation_format', type=str, default='rgb',\n help='Observation data to be used (sets img_channels): rgb | rgbd. \\\n Only effective in `controller` mode.')\n# --- debug options\nARGPARSER.add_argument(\n '--debug', default=False, action='store_true',\n help=\"Enables debug output.\")\n\n#endregion\n\n\n#region: constants\n\nNAME_GRIPPER = 'robot0:grip'\nNAME_TABLE = 'table0'\nOFFSET_HEIGHT_PRE_GRASP = 0.05 # gripper offset above target object\nDIST_PRE_GRASP = 0.005 # distance to target object for pre-grasp pose\nDIST_GRASP = 0.002 # distance to target object for grasp pose (defines firmness of grip)\nDIST_ON_TOP = 0.175 # distance for placement position on top of a target\nDIST_GOAL = 0.01 # radius around goal pos, positions within are considered 'in goal'\nSIZE_BOX = 0.05 # side-length of a box\nMULT_POS_ACTION = 6.0 # multiplier for pos action (for faster movement to target pos)\nTOL_GRIPPER_RELEASE = 0.0001 # tolerance between gripper state and full open (for release)\nPAUSE_AFTER_DROP = 10 # number of simulation steps for the robot to sit idle after placing an object (to let the stack settle)\nCMD_GRIPPER_OPEN = 1.0\nCMD_GRIPPER_CLOSE = -1.0\nCMD_GRIPPER_NOOP = 0.0\n\nGOAL_NAMES = { # env_name -> [goal_name]\n 'pad1-cube1' : ['goal0'],\n 'pad2-cube1' : ['goal0', 'goal1'],\n 'pad1-cube2' : ['goal0'],\n 'pad2-cube2' : ['goal0', 'goal1'],\n 'pad2-cube2-clutter4' : ['goal0', 'goal1'],\n 'pad2-cube2-clutter12' : ['goal0', 'goal1'],\n # generalization scenarios\n 'ball-cup' : ['goal0', 'goal1'],\n 'bridge-pad' : ['goal0', 'goal1'],\n 'diamond-pad' : ['goal0', 'goal1'],\n 'nut-cone' : ['goal0', 'goal1'],\n}\nCUBE_NAMES = { # env_name -> [cube_name]\n 'pad1-cube1' : ['object0'],\n 'pad2-cube1' : ['object0'],\n 'pad1-cube2' : ['object0', 'object1'],\n 'pad2-cube2' : ['object0', 'object1'],\n 'pad2-cube2-clutter4' : ['object0', 'object1'],\n 'pad2-cube2-clutter12' : ['object0', 'object1'],\n # generalization scenarios\n 'ball-cup' : ['goal0', 'goal1'],\n 'bridge-pad' : ['goal0', 'goal1'],\n 'diamond-pad' : ['goal0', 'goal1'],\n 'nut-cone' : ['goal0', 'goal1'],\n}\n\n#endregion\n\n\n#region: I/O helper\n\ndef _load_reset_queue_v2(env, reset_states_path, start_idx, end_idx):\n with open(reset_states_path) as fp:\n reader = csv.reader(fp, delimiter=';')\n iterator = iter(reader)\n # parse CSV header: extract joint names\n header_row = next(iterator)\n state_header = header_row[:-2] # last two fields are task_goal & task_object\n task_header = header_row[-2:]\n num_joints = len(state_header) // 7\n joint_names = [state_header[i * 7].split('::')[0] for i in range(num_joints)]\n for i in range(0, end_idx):\n try:\n row = next(iterator)\n except StopIteration:\n break\n if i < start_idx:\n continue\n # each parsed row is one init state and task definition\n state_row = row[:-2]\n task_row = row[-2:]\n state_row = [float(e) for e in state_row]\n qpos_list = np.split(np.array(state_row), num_joints)\n state_dict = dict(list(zip(joint_names[:-1], qpos_list[:-1])))\n robot_dict = dict([(joint_names[-1], qpos_list[-1])])\n task_dict = {\n 'goal' : task_row[0].split(','),\n 'object' : task_row[1].split(','),\n }\n reset_state = {\n 'init' : state_dict,\n 'task' : task_dict,\n 'robot' : robot_dict,\n }\n env.enqueue_reset_state(reset_state)\n\ndef _load_reset_queue_v3(env, reset_states_path, tfrecord_list_path, dataset_dir, start_idx, end_idx):\n \"\"\"Row in reset state CSV and lines in tfrecord list file must be aligned!\"\"\"\n with open(reset_states_path) as fp:\n reader = csv.reader(fp, delimiter=';')\n state_iterator = iter(reader)\n # parse CSV header: extract joint names\n header_row = next(state_iterator)\n state_header = header_row[:-2] # last two fields are task_goal & task_object\n task_header = header_row[-2:]\n num_joints = len(state_header) // 7\n joint_names = [state_header[i * 7].split('::')[0] for i in range(num_joints)]\n # load tfrecord list\n with open(tfrecord_list_path) as fp2:\n tfrecord_list = fp2.read().split('\\n')[:-1]\n record_iterator = iter(tfrecord_list)\n # only load tfrecords that are needed\n for i in range(0, end_idx):\n try:\n row = next(state_iterator)\n record_name = next(record_iterator)\n except StopIteration:\n break\n if i < start_idx:\n continue\n # each parsed row is one init state and task definition\n state_row = row[:-2]\n task_row = row[-2:]\n state_row = [float(e) for e in state_row]\n qpos_list = np.split(np.array(state_row), num_joints)\n state_dict = dict(list(zip(joint_names[:-1], qpos_list[:-1])))\n robot_dict = dict([(joint_names[-1], qpos_list[-1])])\n task_dict = {\n 'goal' : task_row[0].split(','),\n 'object' : task_row[1].split(','),\n }\n reset_state = {\n 'init' : state_dict,\n 'task' : task_dict,\n 'target' : [load_target_frame(dataset_dir, record_name, load_depth=False)], # HOTFIX: disabled depth!\n 'robot' : robot_dict,\n }\n env.enqueue_reset_state(reset_state)\n\ndef _animate_trajectories(traj_ee, traj_obj, pred_traj_ee, pred_traj_obj):\n \"\"\"\n traj_ee: gray\n traj_obj: red\n pred_traj_ee: blue\n pred_traj_obj: yellow\n \"\"\"\n # reshape trajectory tensors\n traj_ee = np.stack(traj_ee) # [t, xyz]\n traj_obj = np.stack(traj_obj) # [t, xyz]\n pred_traj_ee = np.stack(pred_traj_ee) # [t, xyz]\n pred_traj_obj = np.stack(pred_traj_obj) # [t, xyz]\n # determine sequence length\n seq_length = np.min([\n traj_ee.shape[0], traj_obj.shape[0], pred_traj_ee.shape[0], pred_traj_obj.shape[0]\n ])\n # create figure and set limits\n fig = plt.figure()\n ax = plt.axes(projection='3d')\n x_data = np.concatenate([\n traj_ee[:, 0], traj_obj[:, 0], pred_traj_ee[:, 0], pred_traj_obj[:, 0]\n ])\n y_data = np.concatenate([\n traj_ee[:, 1], traj_obj[:, 1], pred_traj_ee[:, 1], pred_traj_obj[:, 1]\n ])\n z_data = np.concatenate([\n traj_ee[:, 2], traj_obj[:, 2], pred_traj_ee[:, 2], pred_traj_obj[:, 2]\n ])\n ax.set_xlim(left=np.min(x_data), right=np.max(x_data))\n ax.set_ylim(bottom=np.min(y_data), top=np.max(y_data))\n ax.set_zlim(bottom=np.min(z_data), top=np.max(z_data))\n # internal anim func\n def _init():\n _traj_ee, = ax.plot3D([traj_ee[0, 0]], [traj_ee[0, 1]], [traj_ee[0, 2]], 'black')\n _traj_obj, = ax.plot3D([traj_obj[0, 0]], [traj_obj[0, 1]], [traj_obj[0, 2]], 'green')\n _pred_traj_ee, = ax.plot3D([pred_traj_ee[0, 0]], [pred_traj_ee[0, 1]], [pred_traj_ee[0, 2]], 'blue')\n _pred_traj_obj, = ax.plot3D([pred_traj_obj[0, 0]], [pred_traj_obj[0, 1]], [pred_traj_obj[0, 2]], 'red')\n return _traj_ee, _traj_obj, _pred_traj_ee, _pred_traj_obj\n def _animate(i):\n _traj_ee, = ax.plot3D(traj_ee[0:i, 0], traj_ee[0:i, 1], traj_ee[0:i, 2], 'black')\n _traj_obj, = ax.plot3D(traj_obj[0:i, 0], traj_obj[0:i, 1], traj_obj[0:i, 2], 'green')\n _pred_traj_ee, = ax.plot3D(pred_traj_ee[0:i, 0], pred_traj_ee[0:i, 1], pred_traj_ee[0:i, 2], 'blue')\n _pred_traj_obj, = ax.plot3D(pred_traj_obj[0:i, 0], pred_traj_obj[0:i, 1], pred_traj_obj[0:i, 2], 'red')\n return _traj_ee, _traj_obj, _pred_traj_ee, _pred_traj_obj\n # build animation\n ani = animation.FuncAnimation( # interval: 40 ms = 25 Hz\n fig, _animate, init_func=_init, interval=40, blit=True, save_count=seq_length)\n return ani\n\ndef _animate_commands(cmd_ee, cmd_grp):\n \"\"\"stub\"\"\"\n # reshape trajectory tensors\n cmd_ee = np.stack(cmd_ee) # [t, Dxyz]\n cmd_grp = np.array(cmd_grp) # [t, 1]\n # determine sequence length\n seq_length = np.min([cmd_ee.shape[0], cmd_grp.shape[0]])\n # create figure and set limits\n fig, (ax_cmd_dx, ax_cmd_dy, ax_cmd_dz, ax_cmd_grp) = plt.subplots(nrows=4, ncols=1, sharex=True)\n cmd_ee_range = np.max(cmd_ee) - np.min(cmd_ee)\n for ax in [ax_cmd_dx, ax_cmd_dy, ax_cmd_dz]:\n ax.set_xlim(left=0, right=seq_length)\n # ax.set_ylim(bottom=np.min(cmd_ee)-0.1*cmd_ee_range, top=np.max(cmd_ee)+0.1*cmd_ee_range)\n ax.set_ylim(bottom=-2.0, top=2.0)\n ax_cmd_grp.set_xlim(left=0, right=seq_length)\n ax_cmd_grp.set_ylim(bottom=-1.5, top=1.5)\n # internal anim func\n def _init():\n _cmd_dx, = ax_cmd_dx.plot([0], [cmd_ee[0, 0]], color='orange')\n _cmd_dy, = ax_cmd_dy.plot([0], [cmd_ee[0, 1]], color='orange')\n _cmd_dz, = ax_cmd_dz.plot([0], [cmd_ee[0, 2]], color='orange')\n _cmd_grp, = ax_cmd_grp.plot([0], [cmd_grp[0, 0]], color='orange')\n return _cmd_dx, _cmd_dy, _cmd_dz, _cmd_grp\n def _animate(i):\n _cmd_dx, = ax_cmd_dx.plot(np.arange(0, i), cmd_ee[0:i, 0], color='orange')\n _cmd_dy, = ax_cmd_dy.plot(np.arange(0, i), cmd_ee[0:i, 1], color='orange')\n _cmd_dz, = ax_cmd_dz.plot(np.arange(0, i), cmd_ee[0:i, 2], color='orange')\n _cmd_grp, = ax_cmd_grp.plot(np.arange(0, i), cmd_grp[0:i, 0], color='orange')\n return _cmd_dx, _cmd_dy, _cmd_dz, _cmd_grp\n # build animation\n ani = animation.FuncAnimation( # interval: 40 ms = 25 Hz\n fig, _animate, init_func=_init, interval=40, blit=True, save_count=seq_length)\n return ani\n\nfrom moviepy.editor import VideoFileClip\nclass VideoCycler:\n def __init__(self, video_path):\n \"\"\"Loads the video from `video_path` and cycles it using a memory-economic generator.\"\"\"\n self.video = VideoFileClip(video_path)\n self.reset()\n def reset(self):\n self.ite = self.video.iter_frames()\n def __next__(self):\n try:\n next_frame = next(self.ite)\n except StopIteration:\n self.reset()\n next_frame = next(self.ite)\n return next_frame\n def __iter__(self):\n return self\n\n#endregion\n\n\n#region: sub-routines for expert trajectory collection\n\ndef _move_to_pre_grasp(env, obj_name: str):\n \"\"\"Move gripper into pre-grasp pose for object.\"\"\"\n # initial positions\n grip_pos = env.sim.data.get_site_xpos(NAME_GRIPPER)\n object_pos = env.sim.data.get_site_xpos(obj_name)\n object_rel_pos = object_pos - grip_pos\n # first make the gripper go slightly above the object\n object_oriented_goal = object_rel_pos.copy()\n object_oriented_goal[2] += OFFSET_HEIGHT_PRE_GRASP\n # set goal\n env.sample_goal(object_oriented_goal)\n # movement loop\n while np.linalg.norm(object_oriented_goal) >= DIST_PRE_GRASP \\\n and env.ts < env._max_episode_steps:\n env.render_extended()\n object_oriented_goal = object_rel_pos.copy()\n object_oriented_goal[2] += OFFSET_HEIGHT_PRE_GRASP\n # adjust action\n action = [0, 0, 0, 0]\n for i in range(len(object_oriented_goal)):\n action[i] = object_oriented_goal[i] * MULT_POS_ACTION\n action[-1] = CMD_GRIPPER_OPEN\n # forward environment\n obs, reward, done, info = env.step(action)\n # re-compute positions\n grip_pos = env.sim.data.get_site_xpos(NAME_GRIPPER)\n object_pos = env.sim.data.get_site_xpos(obj_name)\n object_rel_pos = object_pos - grip_pos\n return True # pre-grasp pose reached\n\ndef _grasp(env, obj_name: str):\n \"\"\"Grasp object.\"\"\"\n # initial positions\n grip_pos = env.sim.data.get_site_xpos(NAME_GRIPPER)\n object_pos = env.sim.data.get_site_xpos(obj_name)\n object_rel_pos = object_pos - grip_pos\n # movement loop\n while np.linalg.norm(object_rel_pos) >= DIST_GRASP \\\n and env.ts < env._max_episode_steps:\n env.render_extended()\n # adjust action\n action = [0, 0, 0, 0]\n for i in range(len(object_rel_pos)):\n action[i] = object_rel_pos[i] * MULT_POS_ACTION\n action[-1] = CMD_GRIPPER_CLOSE\n # forward environment\n obs, reward, done, info = env.step(action)\n # re-compute positions\n grip_pos = env.sim.data.get_site_xpos(NAME_GRIPPER)\n object_pos = env.sim.data.get_site_xpos(obj_name)\n object_rel_pos = object_pos - grip_pos\n return True # object has been grasped\n\ndef _move_to_post_grasp(env, obj_name: str):\n \"\"\"Move gripper into post-grasp pose for object.\"\"\"\n # initial positions\n grip_pos = env.sim.data.get_site_xpos(NAME_GRIPPER)\n goal_grip_pos = grip_pos.copy()\n goal_grip_pos[2] += OFFSET_HEIGHT_PRE_GRASP\n # set goal\n env.sample_goal(goal_grip_pos)\n # first make the gripper go slightly above the object\n diff_grip_pos = goal_grip_pos - grip_pos\n # movement loop\n while np.linalg.norm(diff_grip_pos) >= DIST_PRE_GRASP \\\n and env.ts < env._max_episode_steps:\n env.render_extended()\n # adjust action\n action = [0, 0, 0, 0]\n for i in range(len(diff_grip_pos)):\n action[i] = diff_grip_pos[i] * MULT_POS_ACTION\n action[-1] = CMD_GRIPPER_CLOSE\n # forward environment\n obs, reward, done, info = env.step(action)\n # re-compute positions\n grip_pos = env.sim.data.get_site_xpos(NAME_GRIPPER)\n diff_grip_pos = goal_grip_pos - grip_pos\n return True # post-grasp pose reached\n\ndef _move(env, obj_name: str, goal_pos):\n \"\"\"Move object to a goal position. Object needs to be grasped first!\"\"\"\n # initial positions\n grip_pos = env.sim.data.get_site_xpos(NAME_GRIPPER)\n object_pos = env.sim.data.get_site_xpos(obj_name)\n object_rel_pos = object_pos - grip_pos\n # set goal\n env.sample_goal(goal_pos)\n # movement loop\n while np.linalg.norm(goal_pos - object_pos) >= DIST_GOAL \\\n and env.ts < env._max_episode_steps:\n env.render_extended()\n # adjust action\n action = [0, 0, 0, 0]\n for i in range(len(goal_pos - object_pos)):\n action[i] = (goal_pos - object_pos)[i] * MULT_POS_ACTION\n action[-1] = CMD_GRIPPER_CLOSE\n # forward environment\n obs, reward, done, info = env.step(action)\n # re-compute positions\n grip_pos = env.sim.data.get_site_xpos(NAME_GRIPPER)\n object_pos = env.sim.data.get_site_xpos(obj_name)\n object_rel_pos = object_pos - grip_pos\n return True # object has been moved to goal position\n\ndef _drop(env, obj_name: str):\n \"\"\"Open gripper and drop object.\"\"\"\n gripper_open = np.array([CMD_GRIPPER_OPEN, CMD_GRIPPER_OPEN])\n gripper_act = np.array([ # only gripper in ctrl array, remaining arm pose is set via mocap array\n env.sim.data.get_joint_qpos('robot0:l_gripper_finger_joint'),\n env.sim.data.get_joint_qpos('robot0:r_gripper_finger_joint'),\n ])\n # movement loop\n while np.linalg.norm(gripper_act - gripper_open) >= TOL_GRIPPER_RELEASE \\\n and env.ts < env._max_episode_steps:\n env.render_extended()\n # adjust action\n # xpos_grp = env.sim.data.get_site_xpos('robot0:grip')\n action = [0, 0, OFFSET_HEIGHT_PRE_GRASP / 2, CMD_GRIPPER_OPEN]\n # forward environment\n obs, reward, done, info = env.step(action)\n # re-compute positions\n gripper_act = np.array([\n env.sim.data.get_joint_qpos('robot0:l_gripper_finger_joint'),\n env.sim.data.get_joint_qpos('robot0:r_gripper_finger_joint'),\n ])\n return True # gripper is fully open and has released object\n\ndef _idle(env, idle_steps):\n \"\"\"Lets the robot sit idle for a number of steps.\"\"\"\n step_cnt = 0\n while step_cnt < idle_steps \\\n and env.ts < env._max_episode_steps:\n env.render_extended()\n action = [0, 0, 0, 0]\n obs, reward, done, info = env.step(action)\n step_cnt += 1\n return\n\ndef _on_top(env, obj_top: str, obj_bottom: str):\n \"\"\"Computes a goal position for `obj_top` on top of `obj_bottom`.\"\"\"\n xpos_bottom = env.sim.data.get_site_xpos(obj_bottom)\n xpos_top = xpos_bottom.copy()\n xpos_top[2] += DIST_ON_TOP\n return xpos_top\n\ndef _get_obj_heights(env):\n \"\"\"Returns the names and heights (site_xpos) of all objects, sorted desc.\"\"\"\n obj_names = [n for n in env.sim.model.site_names \\\n if n.startswith('object') or n.startswith('goal')] # TODO: use regex here!\n obj_heights = [env.sim.data.get_site_xpos(obj_name)[2] for obj_name in obj_names]\n result = list(zip(obj_names, obj_heights))\n result.sort(key=lambda t: t[1])\n result.reverse()\n return result\n\n# NOTE: hard-coded for box towers!\ndef _get_stack_height(env):\n \"\"\"Returns the height of the highest stack.\"\"\"\n offset_table = env.sim.data.get_body_xpos(NAME_TABLE)[2] * 2 # body center is at half-height\n _obj, _h = _get_obj_heights(env)[0] # get highest object site xpos\n # TODO: make box half-heights constant\n max_height = _h + SIZE_BOX / 2\n print(max_height, offset_table)\n num_stacked = (max_height - offset_table) / SIZE_BOX\n return num_stacked\n\ndef _stack(env, obj_names, goal_name):\n num_waypoints = 1 # TODO: compute more waypoints for collision-free trajectory\n obj_moved = [] # keep track of the objects which have already been moved\n # set goals\n obj_moved.append(goal_name)\n for obj_idx, obj_name in enumerate(obj_names):\n _move_to_pre_grasp(env, obj_name)\n _grasp(env, obj_name)\n _move_to_post_grasp(env, obj_name)\n for i in range(num_waypoints):\n # move object on top of currently highest one\n obj_by_height = _get_obj_heights(env)\n for _obj, _h in obj_by_height:\n if _obj in obj_moved: # ensure that bottom object has already been moved!\n obj_bottom, cur_h = _obj, _h\n break\n goal = _on_top(env, obj_name, obj_bottom)\n _move(env, obj_name, goal)\n _drop(env, obj_name)\n obj_moved.append(obj_name)\n _idle(env, PAUSE_AFTER_DROP)\n stack_height = int(np.rint(_get_stack_height(env)))\n print(\">> Current stack height\", stack_height)\n while env.ts < env._max_episode_steps:\n env.render_extended()\n action = [0, 0, 0, 0]\n obs, reward, done, info = env.step(action)\n stack_height = int(np.rint(_get_stack_height(env))) # TODO: save\n print(\">> Final stack height\", stack_height)\n\n#endregion\n\n\n#region: sub-routines for controller evaluation\n\n# TODO: refactor into application constants / make parameter\nOBJ_VICINITY = 0.0625 # radius around manipulated object; determines vicinity test\nGRASP_VICINITY = 0.025 # distance between gripper and manipulated object; determines grasp test\nGOAL_VICINITY = 0.05 # radius around goal object; determines task success test\n\ndef _eval_object_vicinity(env, obj_name: str):\n \"\"\"Checks whether the gripper has come close enough to the object.\"\"\"\n grip_pos = env.sim.data.get_site_xpos(NAME_GRIPPER)\n object_pos = env.sim.data.get_site_xpos(obj_name)\n dist = np.linalg.norm(object_pos - grip_pos)\n return dist <= OBJ_VICINITY\n\ndef _eval_grasp_success(env, obj_name: str):\n \"\"\"Checks whether the gripper has grasped the object.\"\"\"\n grip_pos = env.sim.data.get_site_xpos(NAME_GRIPPER)\n object_pos = env.sim.data.get_site_xpos(obj_name)\n dist = np.linalg.norm(object_pos - grip_pos)\n return dist <= GRASP_VICINITY\n\ndef _eval_task_success(env, obj_name: str, goal_name: str):\n \"\"\"Checks whether the manipulated object is near the goal.\"\"\"\n object_pos = env.sim.data.get_site_xpos(obj_name)\n goal_pos = env.sim.data.get_site_xpos(goal_name)\n dist = np.linalg.norm(goal_pos - object_pos)\n return dist <= GOAL_VICINITY\n\ndef _eval_goal_dist(env, obj_name: str, goal_name: str):\n \"\"\"Returns the distance of the manipulated object to the goal.\"\"\"\n object_pos = env.sim.data.get_site_xpos(obj_name)\n goal_pos = env.sim.data.get_site_xpos(goal_name)\n dist = np.linalg.norm(goal_pos - object_pos)\n return dist\n\n# endregion\n\n\n#region: main\n\ndef main(args):\n # --- set up directories\n wrk_dir = os.path.join(args.wrk_dir, args.sim_mode)\n os.makedirs(wrk_dir, exist_ok=True)\n run_cmd_path = save_run_command(argparser=ARGPARSER, run_dir=wrk_dir)\n\n # --- environment registration\n for reward_type in ['sparse', 'dense']:\n suffix = 'Dense' if reward_type == 'dense' else ''\n kwargs = {\n 'work_dir' : wrk_dir,\n 'shapes' : args.shapes,\n 'reward_type' : reward_type,\n 'rendering_mode' : args.rendering_mode,\n 'frame_res' : tuple(args.frame_res),\n }\n if args.sim_mode == 'controller': # max_episode_steps depend\n if args.max_episode_steps < 0: # use defaults\n max_episode_steps = 200 # normal controller execution (2x expert demonstration time)\n else:\n max_episode_steps = args.max_episode_steps\n else:\n max_episode_steps = 100 # time for expert demonstration\n register(\n id='PickAndPlaceEnv{}-v1'.format(suffix),\n entry_point='geeco_gym:PickAndPlaceEnv',\n kwargs=kwargs,\n max_episode_steps=max_episode_steps,\n )\n\n # --- build gym environment\n env = gym.make('PickAndPlaceEnv-v1')\n env.reset()\n print(\"Initial environment reset done.\")\n\n # --- constants\n goal_names = GOAL_NAMES[args.shapes]\n cube_names = CUBE_NAMES[args.shapes]\n\n # --- queue up intial environment configurations\n if os.path.isfile(args.init_states):\n if args.sim_mode == 'collect':\n _load_reset_queue_v2(env, args.init_states, args.start_idx, args.end_idx)\n elif args.sim_mode == 'controller':\n if args.goal_condition == 'none':\n _load_reset_queue_v2(env, args.init_states, args.start_idx, args.end_idx)\n elif args.goal_condition == 'target':\n _load_reset_queue_v3(\n env, args.init_states, args.tfrecord_list, args.dataset_dir, args.start_idx, args.end_idx)\n else:\n err_msg = \">>> Couldn't load initial states from %s! Defaulting to random initialization.\" \\\n % (args.init_states, )\n print(err_msg)\n\n # --- set up domain randomization\n randomize_background = False\n if args.background_video != '':\n randomize_background = True\n bg_video_cycler = VideoCycler(args.background_video)\n from mujoco_py.modder import TextureModder\n texmodder = TextureModder(env.sim)\n\n # --- set up predictor from model_dir\n if args.sim_mode == 'controller':\n # E2EVMC\n if args.controller == 'e2evmc':\n if args.goal_condition == 'none':\n predictor = E2EVMCPredictor(args.model_dir, args.checkpoint_name)\n elif args.goal_condition == 'target':\n predictor = GoalE2EVMCPredictor(args.model_dir, args.checkpoint_name)\n else:\n err_msg = \"Unknown goal condition: %s!\" % (args.goal_condition, )\n raise ValueError(err_msg)\n else:\n err_msg = \"Unknown controller model '%s'\" % (args.controller, )\n raise ValueError(err_msg)\n # --- register video recorders\n recorders = {}\n recorders['rgb'] = MjVideoRecorder( # TODO: set parameters via config\n ctx_name='default', ctx_type='rgb', cam_name='cam_default',\n record_name='observation', record_dir=wrk_dir,\n res_height=256, res_width=256)\n if args.debug:\n if predictor.cfg.proc_obs == 'dynimg': # register recorder for dynamic buffer\n recorders['dynbuff'] = MjVideoRecorder( # TODO: set parameters via config\n ctx_name='default', ctx_type='rgb', cam_name='cam_default',\n record_name='dynbuff', record_dir=wrk_dir,\n res_height=256, res_width=256)\n if predictor.cfg.proc_tgt == 'dyndiff': # register recorder for dynamic buffer\n recorders['dyndiff'] = MjVideoRecorder( # TODO: set parameters via config\n ctx_name='default', ctx_type='rgb', cam_name='cam_default',\n record_name='dyndiff', record_dir=wrk_dir,\n res_height=256, res_width=256)\n\n # --- set up evaluation data structures\n if args.sim_mode == 'controller':\n eval_results = []\n episode_eval_spec = [\n ('episode_id', 0),\n ('obj_vicinity', 0), # binary success indicator\n ('grasp_success', 0), # binary success indicator\n ('task_success', 0), # binary success indicator\n ('init_goal_dist', 0), # set at start of episode\n ('min_goal_dist', 1000), # updated via min operator\n ('max_goal_dist', 0), # updated via max operator\n ('final_goal_dist', 0), # set at end of episode\n ('video_file', ''), # path to video file\n ]\n eval_spec_fields = [t[0] for t in episode_eval_spec]\n report_path = os.path.join(wrk_dir, 'eval_results.csv')\n csv_report = open(report_path, 'w', newline='')\n writer = csv.DictWriter(csv_report, fieldnames=eval_spec_fields, delimiter=';')\n writer.writeheader()\n\n # --- main loop\n for i in tqdm(range(args.start_idx, args.end_idx)):\n obs = env.reset()\n episode_id = i + 1\n print(\"ITERATION NUMBER %d / %d\" % (episode_id, args.end_idx))\n\n # --- collect data and save replay buffer (and video / tfrecord)\n if args.sim_mode == 'collect':\n if args.dry_run: # only save initial image\n _h, _w = args.frame_res\n _cam_name = 'external_camera_1'\n rgb_frame = env.sim.render(width=_w, height=_h, camera_name=_cam_name)\n rgb_frame = rgb_frame[::-1, :, :] # original image is upside-down, flip\n rgb_frame = rgb_frame / 255.0 # normalize RGB for predictor feeding\n img_path = os.path.join(wrk_dir, 'init_%04d.png' % (episode_id, ))\n # scipy.misc.imsave(img_path, rgb_frame)\n Image.fromarray((rgb_frame * 255).astype(np.uint8)).save(img_path)\n continue\n # get task information from env\n obj_names = env.task_object\n goal_name = env.task_goal[0]\n # save meta information\n meta_info_dict = env.encoding_meta._asdict()\n meta_info_path = os.path.join(wrk_dir, 'meta_info.json')\n with open(meta_info_path, 'w') as fp:\n json.dump(meta_info_dict, fp, indent=2, sort_keys=True)\n # start tfrecorder\n if args.rendering_mode == 'tfrecord':\n record_name = 'replay_buffer_%04d' % (episode_id, )\n env.start_tfrecorder(record_name)\n # perform stacking\n _stack(env, obj_names=obj_names, goal_name=goal_name)\n # save as pkl\n save_path = os.path.join(wrk_dir, 'replay_buffer_%04d.pkl' % (episode_id, ))\n env.save_replay_buffer_pkl(save_path)\n # save as tfrecord\n if args.rendering_mode == 'tfrecord':\n env.save_tfrecord()\n # save as video\n if env.rendering_mode == 'video':\n env.recorder.flush()\n\n # --- replay a buffer\n elif args.sim_mode == 'replay':\n with open(args.replay_buffer, 'rb') as f:\n replay_buffer = pickle.load(f)\n # read meta\n operated_joints = replay_buffer['monitored_joints']\n operated_mocaps = replay_buffer['monitored_mocaps']\n operated_actuators = replay_buffer['actuated_joints']\n operated_objects = replay_buffer['monitored_objects']\n # read buffers\n joint_qpos_buffer = replay_buffer['joint_qpos_buffer']\n joint_qvel_buffer = replay_buffer['joint_qvel_buffer']\n mocap_qpos_buffer = replay_buffer['mocap_qpos_buffer']\n cmd_buffer = replay_buffer['cmd_buffer']\n object_qpos_buffer = replay_buffer['object_qpos_buffer']\n # init scene\n for obj_name in operated_objects:\n qpos0 = object_qpos_buffer[obj_name][0]\n env.sim.data.set_joint_qpos(obj_name, qpos0)\n for mcp_name in operated_mocaps:\n qpos0 = mocap_qpos_buffer[mcp_name][0]\n env.sim.data.set_mocap_pos(mcp_name, qpos0[:3])\n env.sim.data.set_mocap_quat(mcp_name, qpos0[3:])\n for _ in range(10): # step forward to drag mocap-controlled EE into place\n env.sim.step()\n print(\">>> Scene reset to recorded initial state!\")\n while True:\n env.render_extended()\n action = cmd_buffer[env.get_ts()]\n obs, reward, done, info = env.step(action)\n if env.get_ts() >= env._max_episode_steps: break\n\n # --- random wiggling (mostly debug)\n elif args.sim_mode == 'random':\n operated_joints = [\n 'robot0:shoulder_pan_joint',\n 'robot0:shoulder_lift_joint',\n 'robot0:upperarm_roll_joint',\n 'robot0:elbow_flex_joint',\n 'robot0:forearm_roll_joint',\n 'robot0:wrist_flex_joint',\n 'robot0:wrist_roll_joint',\n 'robot0:r_gripper_finger_joint',\n 'robot0:l_gripper_finger_joint',\n ]\n operated_mocaps = ['robot0:mocap']\n while True:\n env.render_extended()\n for jnt_name in operated_joints:\n qvel = np.random.normal(loc=0.0, scale=2.0)\n env.sim.data.set_joint_qvel(jnt_name, qvel)\n for mcp_name in operated_mocaps:\n cur_pos = env.sim.data.get_mocap_pos(mcp_name)\n new_pos = cur_pos + np.random.normal(loc=0.0, scale=0.1, size=3)\n env.sim.data.set_mocap_pos(mcp_name, new_pos)\n env.ts += 1\n env.sim.step()\n if env.ts >= env._max_episode_steps: break\n\n # --- controller\n elif args.sim_mode == 'controller':\n # constants\n operated_joints = [ # <-- cmd_vel\n 'robot0:shoulder_pan_joint',\n 'robot0:shoulder_lift_joint',\n 'robot0:upperarm_roll_joint',\n 'robot0:elbow_flex_joint',\n 'robot0:forearm_roll_joint',\n 'robot0:wrist_flex_joint',\n 'robot0:wrist_roll_joint',\n ]\n operated_mocaps = ['robot0:mocap'] # <-- cmd_ee\n operated_actuators = [ # <-- cmd_grp\n 'robot0:r_gripper_finger_joint',\n 'robot0:l_gripper_finger_joint',\n ]\n _h, _w = args.frame_res\n _cam_name = 'external_camera_1'\n # eval spec\n eval_spec = dict(episode_eval_spec)\n eval_spec['episode_id'] = episode_id\n eval_spec['init_goal_dist'] = _eval_goal_dist(env, env.task_object[0], env.task_goal[0])\n # command and trajectory information\n cmd_ee, cmd_grp = [], []\n traj_ee, traj_obj, pred_traj_ee, pred_traj_obj = [], [], [], []\n # reset\n predictor.reset()\n if args.goal_condition == 'target':\n target_frame = env.target_frame[0]\n predictor.set_goal(target_frame)\n # DEBUG dump target frame\n target_frame_path = os.path.join(wrk_dir, 'target-%05d.png' % (episode_id, ))\n # scipy.misc.imsave(target_frame_path, target_frame)\n Image.fromarray((target_frame * 255).astype(np.uint8)).save(target_frame_path)\n while True:\n # render frame\n if randomize_background:\n wall_geom_name = 'wall_04'\n wall_tex = texmodder.get_texture(wall_geom_name)\n frame_wall_tex = next(bg_video_cycler)\n img_frame_wall_tex = Image.fromarray(frame_wall_tex)\n img_frame_wall_tex = img_frame_wall_tex.resize((wall_tex.width, wall_tex.height))\n mod_wall_tex = np.array(img_frame_wall_tex)\n texmodder.set_rgb(wall_geom_name, mod_wall_tex)\n if args.observation_format == 'rgb':\n data = env.sim.render(width=_w, height=_h, camera_name=_cam_name)\n rgb_frame = np.copy(data[::-1, :, :]) # original image is upside-down\n recorders['rgb'].feed(rgb_frame) # feed as uint8 frame to video recorder\n rgb_frame = rgb_frame / 255.0 # normalize RGB for predictor feeding\n obs_frame = rgb_frame\n elif args.observation_format == 'rgbd':\n rgb, depth = env.sim.render(width=_w, height=_h, camera_name=_cam_name, depth=True)\n rgb_frame = np.copy(rgb[::-1, :, :]) # original image is upside-down\n depth_frame = np.copy(depth[::-1]) # original image is upside-down\n recorders['rgb'].feed(rgb_frame) # feed as uint8 frame to video recorder\n rgb_frame = rgb_frame / 255.0 # normalize RGB for predictor feeding\n obs_frame = np.concatenate([rgb_frame, np.expand_dims(depth_frame, axis=-1)], axis=-1) # RGB-D\n # get robot state\n if args.controller == 'e2evmc':\n proprioception = np.zeros(shape=(7, ), dtype=np.float32)\n for idx_jnt, jnt_name in enumerate(operated_joints):\n proprioception[idx_jnt] = env.sim.data.get_joint_qpos(jnt_name)\n elif args.controller == 'vfs':\n mcp_name = 'robot0:mocap'\n proprioception = env.sim.data.get_mocap_pos(mcp_name)\n elif args.controller == 'tecnet':\n proprioception = np.zeros(shape=(10, ), dtype=np.float32)\n for idx_jnt, jnt_name in enumerate(operated_joints):\n proprioception[idx_jnt] = env.sim.data.get_joint_qpos(jnt_name)\n mcp_name = 'robot0:mocap'\n proprioception[-3:] = env.sim.data.get_mocap_pos(mcp_name)\n elif args.controller == 'static' or args.controller == 'gaussian':\n proprioception = np.zeros(shape=(7, ), dtype=np.float32) # not used inside predictor\n # predict commands\n pred = predictor.predict(obs_frame, proprioception)\n action = np.concatenate([pred['cmd_ee'], pred['cmd_grp']])\n # feed additional debug output into separate recorders\n if args.debug:\n if predictor.cfg.proc_obs == 'dynimg':\n dynbuff_frame = (pred['dynbuff'] * 255.0).astype(np.uint8)\n recorders['dynbuff'].feed(dynbuff_frame)\n if predictor.cfg.proc_tgt == 'dyndiff':\n dyndiff_frame = (pred['dyndiff'] * 255.0).astype(np.uint8)\n recorders['dyndiff'].feed(dyndiff_frame)\n # print(action) # DEBUG\n obs, reward, done, info = env.step(action)\n # perform eval checks\n goal_name = env.task_goal[0]\n obj_name = env.task_object[0]\n obj_vicinity = _eval_object_vicinity(env, obj_name)\n if obj_vicinity and eval_spec['obj_vicinity'] < 1:\n eval_spec['obj_vicinity'] += 1\n print(\">>> Successfully reached %s!\" % obj_name)\n grasp_success = _eval_grasp_success(env, obj_name)\n if grasp_success and eval_spec['grasp_success'] < 1:\n eval_spec['grasp_success'] += 1\n print(\">>> Successfully grasped %s!\" % obj_name)\n goal_dist = _eval_goal_dist(env, obj_name, goal_name)\n eval_spec['min_goal_dist'] = min([eval_spec['min_goal_dist'], goal_dist])\n eval_spec['max_goal_dist'] = max([eval_spec['max_goal_dist'], goal_dist])\n # record commands and trajectories\n cmd_ee.append(pred['cmd_ee'])\n cmd_grp.append(pred['cmd_grp'])\n traj_ee.append(np.copy(env.sim.data.get_mocap_pos('robot0:mocap')))\n traj_obj.append(np.copy(env.sim.data.get_site_xpos(env.task_object[0])))\n if 'pos_ee' in pred:\n pred_traj_ee.append(pred['pos_ee'])\n if 'pos_obj' in pred:\n pred_traj_obj.append(pred['pos_obj'])\n # terminate episode\n if env.get_ts() >= env._max_episode_steps: break\n # final evaluation of task success\n eval_spec['final_goal_dist'] = _eval_goal_dist(env, env.task_object[0], env.task_goal[0])\n task_success = _eval_task_success(env, obj_name, goal_name)\n if task_success and eval_spec['task_success'] < 1:\n eval_spec['task_success'] += 1\n print(\">>> Successfully placed %s!\" % obj_name)\n # save videos\n for rec_key in recorders.keys():\n video_path = recorders[rec_key].flush()\n if rec_key == 'rgb':\n eval_spec['video_file'] = video_path\n # TODO: currently broken, because of ffmpeg clash -> refacor and fix!\n # if args.debug: # save command and trajectory videos\n # # commands\n # ani = _animate_commands(cmd_ee, cmd_grp)\n # save_path = os.path.join(wrk_dir, 'commands_%06d.mp4' % episode_id)\n # ani.save(save_path)\n # # trajectories\n # ani = _animate_trajectories(traj_ee, traj_obj, pred_traj_ee, pred_traj_obj)\n # save_path = os.path.join(wrk_dir, 'trajectories_%06d.mp4' % episode_id)\n # ani.save(save_path)\n # add eval spec to results\n eval_results.append(eval_spec)\n # print current success averages\n for k in ['obj_vicinity', 'grasp_success', 'task_success']:\n cur_avg = np.average([res[k] for res in eval_results]) * 100\n print(\">>> Current average success rate for %s: %.02f\" % (k, cur_avg))\n # append result to CSV\n writer.writerow(eval_spec)\n\n # --- unknown mode\n else:\n raise ValueError(\"Unknown simulation mode: %s\" % (args.sim_mode, ))\n \n # --- end main loop, cleanup\n if args.sim_mode == 'controller':\n csv_report.close()\n txt_report_file = os.path.join(args.wrk_dir, 'controller', 'final_results.txt')\n with open(txt_report_file, 'w') as fp:\n for k in ['obj_vicinity', 'grasp_success', 'task_success']:\n cur_avg = np.average([res[k] for res in eval_results]) * 100\n fp.write(f\"{k}\\t{cur_avg:.2f}\\n\")\n\n#endregion\n\n# ---------- program entry point ----------\n\nif __name__ == \"__main__\":\n ARGS, UNPARSED = ARGPARSER.parse_known_args()\n main(ARGS)\n","repo_name":"ogroth/geeco","sub_path":"scripts/gym_pickplace.py","file_name":"gym_pickplace.py","file_ext":"py","file_size_in_byte":40921,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"6"} +{"seq_id":"11192147373","text":"import numpy as np\nfrom utils.util_functions import *\nimport random\nfrom scipy.stats import dirichlet\nfrom scipy.special import factorial\nfrom utils.params import *\nfrom utils.reward import *\nfrom utils.transition import *\nfrom utils.gen_trajectories import *\nfrom utils.acc_ratio import *\nfrom utils.lmdp import *\n\n\ndef initialise_c(tl):\n c = np.zeros((tl, 1))\n for i in range(0, tl):\n c[i] = int(random.randint(0, tl - 1))\n\n return c\n\n\ndef sample_reward(F, mu, sigma, lb, ub):\n r = np.zeros((F, 1))\n r = mu + np.random.randn(F) * sigma\n r = np.maximum(lb, np.minimum(ub, r));\n r = r.reshape((1, F))\n # print(\"sample reward\", r)\n return r\n\n\ndef assignment_prob(c, alpha):\n z = count(c).astype(int)\n ix = np.arange(1, len(z) + 1).astype(int)\n Z = np.sum(z*ix)\n k = np.power(ix, z) * factorial(z)\n\n\n #alpha is one so dont need the first part as of now\n #pr = np.math.factorial(Z) / np.prod(np.arange(alpha, alpha + Z)) * np.power(alpha, sum(z)) / np.prod(k)\n pr = np.power(alpha, sum(z)) / np.prod(k)\n\n assert pr >0, \"PR IS NEGATIVE\"\n\n\n return np.float128(pr)\n\n\ndef count(c):\n N = len(c)\n nrCl = int(np.max(c))\n szCl = np.zeros((1, nrCl))\n z = np.zeros((1, N))\n for k in range(0, nrCl):\n for j in range(0, len(c)):\n if c[j] == k + 1:\n szCl[0, k] = szCl[0, k] + 1\n for i in range(0, nrCl):\n if szCl[0, i] > 0:\n z[0, int(szCl[0, i]) - 1] = z[0, int(szCl[0, i]) - 1] + 1\n return z[0]\n\n\ndef log_post(c):\n log_cluster_ass = np.log(assignment_prob(c, alpha))\n\n return log_post\n\n\nclass Cluster:\n assignment = []\n reward = []\n policy = []\n values = []\n llh = []\n prior = []\n gradL = []\n gradP = []\n\n\ndef init_cluster(C, tn, F, X, P_un):\n C.assignment = np.random.randint(0, tn, size=(1, tn))[0]\n C.reward = np.zeros((tn, F))\n C.policy = np.zeros((X, X, tn))\n C.value = np.zeros((X, tn))\n NC = np.max(C.assignment)\n for i in range(0, NC + 1):\n C.reward[i, :] = sample_reward(F, mu, sigma, lb, ub)\n r = reward_feature(M, N, C.reward[i, :]).reshape(X, 1)\n z, r2 = get_z(r, P_un)\n C.value[:, i] = np.squeeze(z)\n C.reward = np.transpose(C.reward)\n C.llh = np.zeros((NC, 1))\n C.prior = np.zeros((NC, 1))\n C.gradL = np.zeros((C.reward.shape[0], C.reward.shape[1]))\n C.gradP = np.zeros((C.reward.shape[0], C.reward.shape[1]))\n C.policy_empty = True\n return C\n\n\ndef newZ(P_un):\n r = sample_reward(F, mu, sigma, lb, ub)\n r = r.reshape((F, 1))\n r2 = reward_feature(M, N, r).reshape(X, 1)\n z, r = get_z(r2, P_un)\n return r, P, z\n\n\ndef update_cluster(C, m, traj_set, P_un, iter=2):\n for it in range(0, iter):\n c = int(C.assignment[m])\n r1 = C.reward[:, c]\n p1 = C.policy[:, :, c]\n z1 = C.value[:, c]\n NC = int(np.max(C.assignment))\n prior = np.zeros((NC + 1, 1))\n for k in range(0, NC + 1):\n for l in range(0, len(C.assignment)):\n if C.assignment[l] == k:\n prior[k] = prior[k] + 1\n\n prior[c] = prior[c] - 1\n prior[NC] = alpha\n c2 = int(sampleMult(prior))\n if c2 > NC: # if its a new cluster, accept it with prob\n r2, p2, z2 = newZ(P_un)\n else:\n r2 = C.reward[:, c2]\n p2 = C.policy[:, :, c2]\n z2 = C.value[:, c2]\n # if its an existing cluster, acceptance ratio\n traj = []\n traj.append(traj_set[:, :, m])\n ratio = acc_ratio(traj, r2, z2, r1, z1, P_un)\n # print(\"ratio\",ratio)\n rand_n = random.uniform(0, 1)\n if rand_n < ratio:\n C.assignment[m] = c2\n if c2 > NC:\n # print(\"reward shape\",C.reward.shape)\n C.reward[:, c2] = r2\n C.policy[:, :, c2] = p2\n C.value[:, c2] = v2\n C.policy_empty = False\n return C\n\n\ndef sampleMult(p):\n s = sum(p)\n if s != 1:\n p = p / s\n q = np.cumsum(p)\n c2 = 0\n r = random.uniform(0, 1)\n for i in range(0, len(q)):\n if q[i] > r:\n c2 = i\n break\n return c2\n\n\ndef relabel_cluster(C, tn):\n R = np.zeros((1, F))\n P = np.zeros((X, X))\n V = np.zeros((X, 1))\n tmpId = np.zeros((1, 2))\n relabel = 0\n for k in range(0, int(np.max(C.assignment)) + 1):\n sum = 0\n for l in range(0, len(C.assignment)):\n if C.assignment[l] == k:\n sum = sum + 1\n if sum > 0:\n R = np.append(R, C.reward[:, k].reshape((1, C.reward[:, k].shape[0])), axis=0)\n P_temp = C.policy[:, :, k].reshape((C.policy[:, :, k].shape[0], C.policy[:, :, k].shape[1]))\n P = np.dstack((P, P_temp))\n V = np.append(V, C.value[:, k].reshape((C.value[:, k].shape[0], 1)), axis=1)\n tmpId = np.append(tmpId, np.asarray([k, R.shape[0] - 2]).reshape((1, 2)), axis=0)\n relabel = 1\n R = R[1:, :]\n V = V[:, 1:]\n P = P[:, :, 1:]\n tmpId = tmpId[1:, :]\n if relabel == 1:\n B = np.zeros((len(C.assignment), 1))\n # print(len(tmpId))\n for i in range(0, len(tmpId)):\n for l in range(0, len(C.assignment)):\n if C.assignment[l] == tmpId[i, 0]:\n B[l] = int(tmpId[i, 1])\n C.assignment = B\n C.reward = np.transpose(R)\n C.value = V\n C.policy = P\n\n return C\n","repo_name":"ahanadeb/DPMBIRL_LMDP","sub_path":"src/utils/cluster_assignment.py","file_name":"cluster_assignment.py","file_ext":"py","file_size_in_byte":5443,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"10863023074","text":"import torch\nfrom pytorch_lightning import LightningModule\nfrom torchmetrics.detection.mean_ap import MeanAveragePrecision\n\nimport numpy as np\nfrom datetime import datetime\n\nfrom .iou import evaluate_iou\nfrom ..constants import Metrics\nfrom ..config import TEST_MAP_KWARGS, LEARNING_RATE\n\nfrom .architectures import STR2FUNC\n\nfrom typing import Dict, List, Optional\n\n\nclass DetectionBase(LightningModule):\n def __init__(\n self,\n model_base: Optional[str],\n num_classes: int,\n learning_rate: float = LEARNING_RATE,\n **kwargs,\n ) -> None:\n super().__init__()\n self.learning_rate = learning_rate\n if model_base is not None:\n self.model = STR2FUNC[model_base](num_classes=num_classes, **kwargs)\n\n def forward(self, x):\n return self.model(x)\n\n def test_step(self, batch, _):\n images, targets = batch\n # fasterrcnn takes only images for eval() mode\n with torch.no_grad():\n self.model.eval()\n outs = self.model(images)\n iou = torch.stack([evaluate_iou(t, o) for t, o in zip(targets, outs)]).mean()\n return {Metrics.IOU: iou, Metrics.PREDICTIONS: outs, Metrics.TARGETS: targets}\n\n def test_epoch_end(self, outs):\n metric = MeanAveragePrecision(**TEST_MAP_KWARGS)\n for output in outs:\n metric.update(\n self._to_cpu(output[Metrics.PREDICTIONS]),\n self._to_cpu(output[Metrics.TARGETS]),\n )\n computed_metrics = metric.compute()\n print(f\"mAP: {computed_metrics['map']}, \\n {computed_metrics}\")\n\n # now, we also want to plot precision recall curves.\n classes = metric._get_classes()\n precisions, _ = metric._calculate(classes)\n # the precision tensors have the following dimensions:\n # [IOU_THRESHOLD, RECALL_THRESHOLD, CLASS_IDX, BBOX_SIZE, MAX_DETECTION]\n # we care about all bbox sizes (index 0) and only use a single max detection\n # value (index 0), so we want to plot precision and recall by\n # iterating through the recall threshold for a given class index\n precisions = precisions[:, :, :, 0, 0].detach().cpu().numpy()\n\n # This is hacky because pytorch lightning makes it super difficult to\n # nicely save stuff in the checkpoint folder >:(\n precision_filename = (\n f\"{str(datetime.now()).replace(' ', 'H')}-precision_curve.npy\"\n )\n np.save(precision_filename, precisions)\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(\n self.model.parameters(),\n lr=self.learning_rate,\n )\n return {\n \"optimizer\": optimizer,\n }\n\n\nclass FullySupervised(DetectionBase):\n def training_step(self, batch, _):\n images, targets = batch\n # fasterrcnn takes both images and targets for training, returns\n loss_dict = self.model(images, targets)\n loss = sum(loss for loss in loss_dict.values())\n self.log(\"training_loss\", loss)\n return {\"loss\": loss, \"log\": loss_dict}\n\n def validation_step(self, batch, _):\n images, targets = batch\n # fasterrcnn takes only images for eval() mode\n with torch.no_grad():\n self.model.eval()\n outs = self.model(images)\n iou = torch.stack([evaluate_iou(t, o) for t, o in zip(targets, outs)]).mean()\n return {Metrics.IOU: iou, Metrics.PREDICTIONS: outs, Metrics.TARGETS: targets}\n\n def validation_epoch_end(self, outs):\n avg_iou = torch.stack([o[Metrics.IOU] for o in outs]).mean()\n self.log(Metrics.AVG_IOU, avg_iou)\n\n metric = MeanAveragePrecision()\n for output in outs:\n metric.update(\n self._to_cpu(output[Metrics.PREDICTIONS]),\n self._to_cpu(output[Metrics.TARGETS]),\n )\n computed_metrics = metric.compute()\n self.log(Metrics.MAP, computed_metrics[\"map\"])\n return {\n Metrics.AVG_IOU: avg_iou,\n \"log\": {Metrics.AVG_IOU: avg_iou, Metrics.MAP: computed_metrics[\"map\"]},\n }\n\n @staticmethod\n def _to_cpu(\n targets: List[Dict[str, torch.Tensor]]\n ) -> List[Dict[str, torch.Tensor]]:\n return [{key: val.detach().cpu() for key, val in d.items()} for d in targets]\n","repo_name":"SmallRobotCompany/smallteacher","sub_path":"smallteacher/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4335,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"6"} +{"seq_id":"571887383","text":"import calendar\nprofile = [\n {\"first_name\":\" Awwal\", \"last_name\":\"Adeleke\", \"age\":14, \"attendance\": 70, \"weight\":65, \"height\":79, \"day_and_month\":\"16-07\"},\n {\"first_name\":\"Abdulwali\", \"last_name\":\"Tajudeen\", \"age\":14, \"attendance\": 70, \"weight\":56, \"height\":45, \"day_and_month\":\"03-08\"},\n {\"first_name\":\"Abraham\", \"last_name\":\"Adekunle\", \"age\":14, \"attendance\": 71, \"weight\":49, \"height\":81, \"day_and_month\":\"18-09\"},\n {\"first_name\":\"Yusuff\", \"last_name\":\"oyedele\", \"age\":14, \"attendance\": 72, \"weight\":61, \"height\":74, \"day_and_month\":\"19-01\"},\n {\"first_name\":\"Adebusola\", \"last_name\":\"Adeyeye\", \"age\":14, \"attendance\": 69, \"weight\":70, \"height\":75, \"day_and_month\":\"30-12\"},\n {\"first_name\":\"Basheer\", \"last_name\":\"Balogun\", \"age\":14, \"attendance\": 68, \"weight\":45, \"height\":80, \"day_and_month\":\"31-07\"},\n {\"first_name\":\"Abdullahi\", \"last_name\":\"salaam\", \"age\":14, \"attendance\": 67, \"weight\":72, \"height\":63, \"day_and_month\":\"07-04\"},\n {\"first_name\":\"Faith\", \"last_name\":\"Adeosun\", \"age\":14, \"attendance\": 73, \"weight\":62, \"height\":74, \"day_and_month\":\"20-05\"},\n {\"first_name\":\" Ahmad\", \"last_name\":\"Sharafudeen\", \"age\":14, \"attendance\": 60, \"weight\":69, \"height\":65, \"day_and_month\":\"06-07\"},\n {\"first_name\":\"Lukman\", \"last_name\":\"Abisoye\", \"age\":14, \"attendance\": 74, \"weight\":49, \"height\":70, \"day_and_month\":\"07-06\"},\n {\"first_name\":\"Toluwanimi\", \"last_name\":\"Ogunbiyi\", \"age\":14, \"attendance\": 21, \"weight\":64, \"height\":64, \"day_and_month\":\"05-11\"}\n]\ndef increment_attendance(first_name):\n user_profile = {}\n for x in profile:\n user_profile = x\n user_profile +=1\n return user_profile\n\ndef add_profile(profile):\n new_profile = {}\n f_name = input(\"What is your first name: \")\n l_name = input(\"What is your last name: \")\n age = int(input(\"What si your age: \"))\n attendance = int(\"How frequent are you in class: \")\n height = int(input(\"What is your height: \"))\n weight = int(input(\"What is your weight: \"))\n day_and_month = input(\"what is your day and birth month\")\ndef count_number_profile(profile):\n count = 0\n for i in enumerate(profile):\n count += 1\n return count\n\n\n","repo_name":"olamide16/ATS_Training","sub_path":"week 1/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"18509367017","text":"#-*- coding:utf-8 -*-\r\n\r\nimport time\r\nimport os.path \r\nimport shutil \r\n\r\ndef CopyFiles(sourceDir, targetDir): \r\n if sourceDir.find(\".svn\") > 0: \r\n return \r\n for filePath in os.listdir(sourceDir): \r\n sourceFile = os.path.join(sourceDir, filePath) \r\n targetFile = os.path.join(targetDir, filePath) \r\n if os.path.isfile(sourceFile): \r\n if not os.path.exists(targetDir): \r\n os.makedirs(targetDir) \r\n if not os.path.exists(targetFile) or(os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(sourceFile))): \r\n open(targetFile, \"wb\").write(open(sourceFile, \"rb\").read()) \r\n if os.path.isdir(sourceFile): \r\n \r\n CopyFiles(sourceFile, targetFile)\r\n\r\n#删除文件\r\ndef DeleteFile(*filePaths):\r\n for filePath in filePaths:\r\n if os.path.isfile(filePath): \r\n os.remove(filePath)\r\n\r\n\r\n#删除一级目录下的所有文件:\r\ndef DeleteFileInDir(targetDir): \r\n for filePath in os.listdir(targetDir): \r\n targetFile = os.path.join(targetDir, filePath) \r\n if os.path.isfile(targetFile): \r\n os.remove(targetFile)\r\n#复制一级目录下的所有文件到指定目录:\r\ndef coverFiles(sourceDir, targetDir): \r\n for filePath in os.listdir(sourceDir): \r\n sourceFile = os.path.join(sourceDir, filePath) \r\n targetFile = os.path.join(targetDir, filePath) \r\n #cover the files \r\n if os.path.isfile(sourceFile): \r\n open(targetFile, \"wb\").write(open(sourceFile, \"rb\").read())\r\n#复制指定文件到目录:\r\ndef moveFileto(sourceDir, targetDir): \r\n shutil.copy(sourceDir, targetDir)\r\n\r\n#往指定目录写文本文件:\r\ndef writeVersionInfo(targetDir): \r\n open(targetDir, \"wb\").write(\"Revison:\")\r\n\r\n#返回当前的日期,以便在创建指定目录的时候用:\r\ndef getCurTime(): \r\n nowTime = time.localtime() \r\n year = str(nowTime.tm_year) \r\n month = str(nowTime.tm_mon) \r\n if len(month) < 2: \r\n month = '0' + month \r\n day = str(nowTime.tm_yday) \r\n if len(day) < 2: \r\n day = '0' + day \r\n return (year + '-' + month + '-' + day)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"djangochina/UUBlog","sub_path":"UUBlog/common/filehelper.py","file_name":"filehelper.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"zh","doc_type":"code","stars":28,"dataset":"github-code","pt":"6"} +{"seq_id":"7161994644","text":"\"\"\"\nGiven two strings s and t, return true if s is a subsequence of t, or false otherwise.\n\nA subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \"abcde\" while \"aec\" is not).\n\n\n\nExample 1:\n\nInput: s = \"abc\", t = \"ahbgdc\"\nOutput: true\nExample 2:\n\nInput: s = \"axc\", t = \"ahbgdc\"\nOutput: false\n\n\nConstraints:\n\n0 <= s.length <= 100\n0 <= t.length <= 104\ns and t consist only of lowercase English letters.\n\n\nFollow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?\n\"\"\"\nimport unittest\nfrom typing import List\n\n\nclass Solution():\n def find_subsequence(self, t: List[str], output: List[str], idx: int, ans: List[str]) -> List[str]:\n if idx >= len(t):\n ans.append(\"\".join(output))\n return\n\n else:\n element = t[idx]\n output.append(element)\n self.find_subsequence(t, output, idx + 1, ans)\n output.pop()\n self.find_subsequence(t, output, idx + 1, ans)\n return ans\n\n #TLE\n def isSubsequence(self, s: str, t: str) -> bool:\n t_arr = [ch for ch in t]\n subsequence = self.find_subsequence(t_arr, [], 0, [])\n if subsequence is None:\n if len(s) == 0:\n return True\n else:\n return False\n if s in subsequence:\n return True\n else:\n return False\n\n\nclass TestSolution(unittest.TestCase):\n def setUp(self) -> None:\n self.obj = Solution()\n\n def test_case1(self):\n self.assertTrue(self.obj.isSubsequence(\"abc\",\"ahbgdc\"))\n\n def test_case2(self):\n self.assertFalse(self.obj.isSubsequence(\"axc\",\"ahbgdc\"))\n\n def test_case3(self):\n self.assertTrue(self.obj.isSubsequence(\"\",\"\"))","repo_name":"CompetitiveCodingLeetcode/LeetcodeEasy","sub_path":"Recursion/Subsets/IsSubsequence_Q392.py","file_name":"IsSubsequence_Q392.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"30546140544","text":"# %%\nfrom collections import Counter\n\nimport category_encoders as ce\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\nfrom sklearn.preprocessing import StandardScaler\n\nfrom src import consts as const\nfrom src import utils\nfrom src.processing.imputation import helper\nfrom src.processing.imputation.autoencoder.masked_ae import Autoencoder\n\nsns.set(palette=\"Set2\")\n\n\n## %%\n# Read data\ndf_incomplete, df_no_nan, df = helper.imputation_dataset(\n const.PROCESSED_DATA_DIR / 'enhanced_with_nan.csv')\n\n## %%\n# Split data\nX_train, y_train, X_val, y_val, X_test, y_test = utils.split_data(\n df_incomplete, df_no_nan)\n\n## %%\n# Encode categorical using Target encoding\nnum_cols = y_train.select_dtypes(include=np.number).columns\ncat_cols = y_train.select_dtypes(include=['object']).columns\n\n## Encode categorical using Label Encoding\ntrain_encoder = ce.ordinal.OrdinalEncoder(verbose=2, handle_missing=-1)\ntrain_encoder = train_encoder.fit(y_train[cat_cols])\nX_train[cat_cols] = train_encoder.transform(X_train[cat_cols])\ny_train[cat_cols] = train_encoder.transform(y_train[cat_cols])\nX_train[X_train[cat_cols] == -1] = np.nan\n\nval_encoder = ce.ordinal.OrdinalEncoder(verbose=2, handle_missing=-1)\nval_encoder = val_encoder.fit(y_val[cat_cols])\nX_val[cat_cols] = val_encoder.transform(X_val[cat_cols])\ny_val[cat_cols] = val_encoder.transform(y_val[cat_cols])\nX_val[X_val[cat_cols] == -1] = np.nan\n\ntest_encoder = ce.ordinal.OrdinalEncoder(verbose=2, handle_missing=-1)\ntest_encoder = test_encoder.fit(y_test[cat_cols])\nX_test[cat_cols] = test_encoder.transform(X_test[cat_cols])\nX_test[X_test[cat_cols] == -1] = np.nan\n\n## %%\n# Convert to arrays\nX_train_arr = X_train.values.astype(float)\ny_train_arr = y_train.values.astype(float)\n\nX_val_arr = X_val.values.astype(float)\ny_val_arr = y_val.values.astype(float)\n\nX_test_arr = X_test.values.astype(float)\n\n## %%\n# Normalize data\nobs_row_idx = np.where(np.isfinite(np.sum(X_train_arr, axis=1)))\nX_train_complete_records = X_train_arr[obs_row_idx]\ntrain_scaler = StandardScaler().fit(X_train_complete_records)\nX_train_arr = train_scaler.transform(X_train_arr)\ny_train_arr = train_scaler.transform(y_train_arr)\ndel X_train_complete_records\n\nX_val_arr = train_scaler.transform(X_val_arr)\ny_val_arr = train_scaler.transform(y_val_arr)\n\ntest_obs_row_idx = np.where(np.isfinite(np.sum(X_test_arr, axis=1)))\nX_test_complete_records = X_test_arr[test_obs_row_idx]\ntest_scaler = StandardScaler().fit(X_test_complete_records)\nX_test_arr = test_scaler.transform(X_test_arr)\ndel X_test_complete_records\n\n# %%\nautoencoder = Autoencoder(X_train_arr.shape[1])\nautoencoder.train(X_train_arr, y_train_arr, X_val_arr,\n y_val_arr, batch_size=512)\n\n#autoencoder.recreate_model('autoencoder_weights.h5')\n\n# %%\npred = autoencoder.infer(np.copy(X_test_arr))\n\n# %%\n# Revert normalization\nimputed_arr = test_scaler.inverse_transform(pred)\n\n# %%\n# Revert categorical encoding\nimputed_df = pd.DataFrame(imputed_arr, columns=y_train.columns)\nimputed_df[cat_cols] = imputed_df[cat_cols].round()\nimputed_df[cat_cols] = test_encoder.inverse_transform(imputed_df[cat_cols])\n\n\n# %%\n# Numerical error (MSE)\n# Numerical mask\nnum_nan_mask = X_test[num_cols].apply(pd.isnull)\nmasked_y_test = y_test[num_cols]\nmasked_pred = imputed_df[num_cols]\nmse = helper.masked_mse(\n masked_y_test, masked_pred, num_nan_mask)\nmae = helper.masked_mae(\n masked_y_test, masked_pred, num_nan_mask)\nbaseline = mean_absolute_error(masked_y_test,\n np.full(masked_y_test.values.shape, masked_y_test.mean()))\n\n\n# %%\n# Categorical error (accuracy)\ncat_nan_mask = X_test[cat_cols].apply(pd.isnull)\naccuracy = helper.masked_accuracy(\n y_test[cat_cols], imputed_df[cat_cols], cat_nan_mask)\n\n\n# %%\nprint('MSE: {:.3f}'.format(mse))\nprint('MAE: {:.3f}'.format(mae))\nprint('Baseline (mean): {:.3f}'.format(baseline))\nprint('Accuracy: {:.3f}'.format(accuracy))\n\n\n# %%\nmissing_cols = df.columns[df.isna().any()].tolist()\nmae_dict = {}\nmse_dict = {}\nmape_dict = {}\naccuracy_dict = {}\nfor col in missing_cols:\n col_nan_mask = X_test[col].apply(pd.isnull)\n if df[col].dtype == np.number:\n mae_dict[col] = helper.masked_mae(\n y_test[col], imputed_df[col], col_nan_mask)\n mse_dict[col] = helper.masked_mse(\n y_test[col], imputed_df[col], col_nan_mask)\n mape_dict[col] = helper.masked_mape(\n y_test[col], imputed_df[col], col_nan_mask)\n if df[col].dtype == np.object:\n accuracy_dict[col] = helper.masked_accuracy(\n y_test[col], imputed_df[col], col_nan_mask)\nprint('MAE', end=\"\\n\\n\")\n[print('{}: {:.3f}'.format(key, mae_dict[key])) for key in mae_dict]\nprint('MSE', end=\"\\n\\n\")\n[print('{}: {:.3f}'.format(key, mse_dict[key])) for key in mse_dict]\nprint('MAPE', end=\"\\n\\n\")\n[print('{}: {:.3f}'.format(key, mape_dict[key])) for key in mape_dict]\nprint('ACCURACY', end=\"\\n\\n\")\n[print('{}: {:.3f}'.format(key, accuracy_dict[key])) for key in accuracy_dict]\n\n\n#%%\nnan_num_cols = set(num_cols) & set(missing_cols)\ntrue_df = masked_y_test[nan_num_cols].head(100)\npred_df = masked_pred[nan_num_cols].head(100)\ntrue_df.reset_index(drop=True, inplace=True)\npred_df.reset_index(drop=True, inplace=True)\nfig, ax = plt.subplots(figsize=(8, 6))\n\nfor col in nan_num_cols:\n true_col = true_df[col].sort_values()\n ax = sns.scatterplot(true_col.values, true_col.index)\n pred_col = pred_df[col].sort_values()\n ax = sns.scatterplot(pred_col.values, pred_col.index)\n\n\n#%%\n# Baseline Numerical\nnum_y_test = y_test[num_cols]\nnum_nan_mask = X_test[num_cols].apply(pd.isnull)\nmean_df = X_test[num_cols].copy().fillna(X_test[num_cols].mean())\n\n#%%\nprint(mean_absolute_error(num_y_test.values[num_nan_mask], mean_df.values[num_nan_mask]))\nprint(mean_squared_error(num_y_test.values[num_nan_mask], mean_df.values[num_nan_mask]))\n\n\n#%%\n# Baseline Categorical\ncat_y_test = y_test[cat_cols]\ncat_nan_mask = X_test[cat_cols].apply(pd.isnull)\nmost_freq_df = X_test[cat_cols].copy().apply(lambda x: x.fillna(x.value_counts().index[0]))\n\n#%%\ntruth_values = [true == pred for true, pred in zip(cat_y_test.values[cat_nan_mask], most_freq_df.values[cat_nan_mask])]\ntruth_values = Counter(truth_values)\nprint(truth_values[True] / (truth_values[True] + truth_values[False]))\n\n\n#%%\n","repo_name":"ajmcastro/flight-time-prediction","sub_path":"src/processing/imputation/autoencoder/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6368,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"72486088188","text":"# x - x^2 /2! + x^3 /3! - x^4 /4! + x^5 /5! - x^6 /6! (Input x)\nimport math\nx = int(input(\"Enter the value of x: \"))\nans = 0\nfor i in range(1, 7):\n if i % 2 == 1:\n ans += (x**i)/math.factorial(i)\n else:\n ans -= (x**i)/math.factorial(i)\nprint(f\"Answer: {ans}\")\n","repo_name":"arnab7070/BeyondCoding","sub_path":"Python Programs/AOT IT Workshop/Final Lab Exam Revison/question26.py","file_name":"question26.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"4534773976","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport os, string, time\nimport numpy as np\nimport keras_ocr\nimport matplotlib.pyplot as plt\n\n# REF [site] >> https://github.com/faustomorales/keras-ocr\ndef old_detection_and_recognition_test():\n\tif 'posix' == os.name:\n\t\tdata_base_dir_path = '/home/sangwook/work/dataset'\n\telse:\n\t\tdata_base_dir_path = 'D:/work/dataset'\n\n\tif True:\n\t\tdata_dir_path = data_base_dir_path + '/text/receipt_icdar2019'\n\n\t\timage_filepaths = [\n\t\t\tdata_dir_path + '/0325updated.task1train(626p)-20190531T071023Z-001/0325updated.task1train(626p)/X00016469612.jpg',\n\t\t]\n\telif False:\n\t\tdata_dir_path = data_base_dir_path + '/text/receipt_epapyrus/epapyrus_20190618'\n\n\t\timage_filepaths = list()\n\t\tfor idx in range(1, 11):\n\t\t\timage_filepaths.append(data_dir_path + '/receipt_1/img{:02}.jpg'.format(idx))\n\t\tfor idx in range(1, 32):\n\t\t\timage_filepaths.append(data_dir_path + '/receipt_2/img{:02}.jpg'.format(idx))\n\t\tfor idx in range(1, 40):\n\t\t\timage_filepaths.append(data_dir_path + '/receipt_3/img{:02}.jpg'.format(idx))\n\telif False:\n\t\tdata_dir_path = data_base_dir_path + '/text/receipt_epapyrus/keit_20190619'\n\n\t\timage_filepaths = list()\n\t\tfor idx in range(1, 6):\n\t\t\timage_filepaths.append(data_dir_path + '/카드영수증_{}-1.png'.format(idx))\n\t\timage_filepaths.extend([\n\t\t\tdata_dir_path + '/tax_invoice_01/tax_invoice_01.jpg',\n\t\t\tdata_dir_path + '/tax_invoice_01/tax_invoice_02.jpg',\n\t\t\tdata_dir_path + '/tax_invoice_01/tax_invoice_03.jpg',\n\t\t\tdata_dir_path + '/tax_invoice_01/tax_invoice_04.jpg',\n\t\t\tdata_dir_path + '/tax_invoice_02/tax_invoice_01.jpg',\n\t\t\tdata_dir_path + '/tax_invoice_02/tax_invoice_02.jpg',\n\t\t\tdata_dir_path + '/tax_invoice_02/tax_invoice_03.jpg',\n\t\t\tdata_dir_path + '/tax_invoice_03/tax_invoice_01.jpg',\n\t\t\tdata_dir_path + '/tax_invoice_04/tax_invoice_01.jpg',\n\t\t\tdata_dir_path + '/tax_invoice_05/tax_invoice_01.jpg',\n\t\t])\n\t\tfor idx in range(1, 7):\n\t\t\timage_filepaths.append(data_dir_path + 'import_license_01/import_license_{:02}.png'.format(idx))\n\n\tif True:\n\t\tdetector = keras_ocr.detection.Detector(pretrained=True)\n\telse:\n\t\tdetector = keras_ocr.detection.Detector(pretrained=False)\n\t\tdetector.model.load_weights('./craft_mlt_25k.h5')\n\t\t# REF [function] >> training_test().\n\t\t#detector.model.load_weights('./v0_detector.h5') # FIXME [fix] >> Not correctly working.\n\n\t\"\"\"\n\t# The alphabet defines which characters the OCR will be trained to detect.\n\talphabet = string.digits + \\\n\t\t\t string.ascii_lowercase + \\\n\t\t\t string.ascii_uppercase + \\\n\t\t\t string.punctuation + ' '\n\n\trecognizer = keras_ocr.recognition.Recognizer(\n\t\talphabet=alphabet,\n\t\twidth=128,\n\t\theight=64\n\t)\n\t# REF [function] >> training_test().\n\trecognizer.model.load_weights('./v0_recognizer.h5') # FIXME [fix] >> Not correctly working.\n\t\"\"\"\n\n\tfor image_filepath in image_filepaths:\n\t\timage = keras_ocr.tools.read(image_filepath)\n\n\t\t# Boxes will be an Nx4x2 array of box quadrangles, where N is the number of detected text boxes.\n\t\tboxes = detector.detect(images=[image])[0]\n\t\tcanvas = keras_ocr.detection.drawBoxes(image, boxes)\n\t\tplt.imshow(canvas)\n\t\tplt.show()\n\n\t\t\"\"\"\n\t\tboxes = detector.detect(images=[image])[0]\n\t\tpredictions = recognizer.recognize_from_boxes(boxes=boxes, image=image)\n\t\tprint('Predictions = ', predictions)\n\t\t\"\"\"\n\n# REF [site] >> https://github.com/faustomorales/keras-ocr\ndef training_test():\n\t# The alphabet defines which characters the OCR will be trained to detect.\n\talphabet = string.digits + \\\n\t\t\t string.ascii_lowercase + \\\n\t\t\t string.ascii_uppercase + \\\n\t\t\t string.punctuation + ' '\n\n\t# Build the text detector (pretrained).\n\tdetector = keras_ocr.detection.Detector(pretrained=True)\n\tdetector.model.compile(\n\t\tloss='mse',\n\t\toptimizer='adam'\n\t)\n\n\t# Build the recognizer (randomly initialized) and build the training model.\n\trecognizer = keras_ocr.recognition.Recognizer(\n\t\talphabet=alphabet,\n\t\twidth=128,\n\t\theight=64\n\t)\n\trecognizer.create_training_model(max_string_length=16)\n\n\t# For each text sample, the text generator provides\n\t# a list of (category, string) tuples. The category\n\t# is used to select which fonts the image generator\n\t# should choose from when rendering those characters \n\t# (see the image generator step below) this is useful\n\t# for cases where you have characters that are only\n\t# available in some fonts. You can replace this with\n\t# your own generator, just be sure to match\n\t# that function signature if you are using\n\t# recognizer.get_image_generator. Alternatively,\n\t# you can provide your own image_generator altogether.\n\t# The default text generator uses the DocumentGenerator\n\t# from essential-generators.\n\tdetection_text_generator = keras_ocr.tools.get_text_generator(\n\t\tmax_string_length=32,\n\t\talphabet=alphabet\n\t)\n\n\t# The image generator generates (image, sentence, lines)\n\t# tuples where image is a HxWx3 image, \n\t# sentence is a string using only letters\n\t# from the selected alphabet, and lines is a list of\n\t# lines of text in the image where each line is a list of \n\t# tuples of the form (x1, y1, x2, y2, x3, y3, y4, c). c\n\t# is the character in the line and (x1, y2), (x2, y2), (x3, y3),\n\t# (x4, y4) define the bounding coordinates in clockwise order\n\t# starting from the top left. You can replace\n\t# this with your own generator, just be sure to match\n\t# that function signature.\n\tdetection_image_generator = keras_ocr.tools.get_image_generator(\n\t\theight=256,\n\t\twidth=256,\n\t\tx_start=(10, 30),\n\t\ty_start=(10, 30),\n\t\tsingle_line=False,\n\t\ttext_generator=detection_text_generator,\n\t\tfont_groups={\n\t\t\t'characters': [\n\t\t\t\t'Century Schoolbook',\n\t\t\t\t'Courier',\n\t\t\t\t'STIX',\n\t\t\t\t'URW Chancery L',\n\t\t\t\t'FreeMono'\n\t\t\t]\n\t\t}\n\t)\n\n\t# From our image generator, create a training batch generator and train the model.\n\tdetection_batch_generator = detector.get_batch_generator(\n\t\timage_generator=detection_image_generator,\n\t\tbatch_size=2,\n\t)\n\tdetector.model.fit_generator(\n\t generator=detection_batch_generator,\n\t steps_per_epoch=100,\n\t epochs=10,\n\t workers=0\n\t)\n\tdetector.model.save_weights('v0_detector.h5')\n\n\t# This next part is similar to before but now\n\t# we adjust the image generator to provide only\n\t# single lines of text.\n\trecognition_image_generator = keras_ocr.tools.convert_multiline_generator_to_single_line(\n\t\tmultiline_generator=detection_image_generator,\n\t\tmax_string_length=recognizer.training_model.input_shape[1][1],\n\t\ttarget_width=recognizer.model.input_shape[2],\n\t\ttarget_height=recognizer.model.input_shape[1]\n\t)\n\trecognition_batch_generator = recognizer.get_batch_generator(\n\t\timage_generator=recognition_image_generator,\n\t\tbatch_size=8\n\t)\n\trecognizer.training_model.fit_generator(\n\t\tgenerator=recognition_batch_generator,\n\t\tsteps_per_epoch=100,\n\t\tepochs=100\n\t)\n\n\t# You can save the model weights to use later.\n\trecognizer.model.save_weights('v0_recognizer.h5')\n\n\t# Once training is done, you can use recognize to extract text.\n\t#image, _, _ = next(detection_image_generator)\n\tif 'posix' == os.name:\n\t\treceipt_icdar2019_base_dir_path = '/home/sangwook/work/dataset/text/receipt_icdar2019'\n\telse:\n\t\treceipt_icdar2019_base_dir_path = 'D:/work/dataset/text/receipt_icdar2019'\n\t#image_filepath = receipt_icdar2019_base_dir_path + '/image/00000.jpg'\n\timage_filepath = receipt_icdar2019_base_dir_path + '/0325updated.task1train(626p)-20190531T071023Z-001/0325updated.task1train(626p)/X00016469612.jpg'\n\n\timage = keras_ocr.tools.read(image_filepath)\n\n\tboxes = detector.detect(images=[image])[0]\n\tpredictions = recognizer.recognize_from_boxes(boxes=boxes, image=image)\n\tprint('Predictions =', predictions)\n\ndef new_detection_test():\n\t# Get a set of images.\n\timage_filepaths = [\n\t\t'./image.jpg',\n\t]\n\n\tprint('Start creating a detection model...')\n\tstart_time = time.time()\n\tdetector = keras_ocr.detection.Detector(\n\t\tweights='clovaai_general',\n\t\tload_from_torch=False,\n\t\toptimizer='adam',\n\t\tbackbone_name='vgg'\n\t)\n\tprint('End creating a detection model: {} secs.'.format(time.time() - start_time))\n\tprint('Start detecting text...')\n\tstart_time = time.time()\n\tboxes_lst = detector.detect(\n\t\timage_filepaths, #images,\n\t\tdetection_threshold=0.7,\n\t\ttext_threshold=0.4,\n\t\tlink_threshold=0.4,\n\t\tsize_threshold=10\n\t)\n\tprint('End detecting text: {} secs.'.format(time.time() - start_time))\n\n\t#--------------------\n\timport matplotlib.image\n\n\t# Plot the bounding boxes.\n\tfor img_fpath, boxes in zip(image_filepaths, boxes_lst):\n\t\timg = matplotlib.image.imread(img_fpath)\n\t\tif img is None:\n\t\t\tprint('Failed to load an image: {}.'.format(img_fpath))\n\t\t\tcontinue\n\n\t\timg = keras_ocr.tools.drawBoxes(image=img, boxes=boxes, color=(255, 0, 0), thickness=5, boxes_format='boxes')\n\t\tplt.imshow(img)\n\t\tplt.show()\n\n# REF [site] >> https://github.com/faustomorales/keras-ocr\ndef new_detection_and_recognition_test():\n\tprint('Start creating a model...')\n\tstart_time = time.time()\n\tif True:\n\t\t# keras-ocr will automatically download pretrained weights for the detector and recognizer.\n\t\tpipeline = keras_ocr.pipeline.Pipeline(detector=None, recognizer=None, scale=2, max_size=2048)\n\telse:\n\t\tdetector = keras_ocr.detection.Detector(\n\t\t\tweights='clovaai_general',\n\t\t\tload_from_torch=False,\n\t\t\toptimizer='adam',\n\t\t\tbackbone_name='vgg'\n\t\t)\n\t\trecognizer = keras_ocr.recognition.Recognizer(\n\t\t\talphabet=None,\n\t\t\tweights='kurapan',\n\t\t\tbuild_params=None\n\t\t)\n\n\t\t# keras-ocr will automatically download pretrained weights for the detector and recognizer.\n\t\tpipeline = keras_ocr.pipeline.Pipeline(detector=detector, recognizer=recognizer, scale=2, max_size=2048)\n\tprint('End creating a model: {} secs.'.format(time.time() - start_time))\n\n\t# Get a set of three example images.\n\timages = [\n\t\tkeras_ocr.tools.read(url) for url in [\n\t\t\t'https://upload.wikimedia.org/wikipedia/commons/b/bd/Army_Reserves_Recruitment_Banner_MOD_45156284.jpg',\n\t\t\t'https://upload.wikimedia.org/wikipedia/commons/e/e8/FseeG2QeLXo.jpg',\n\t\t\t'https://upload.wikimedia.org/wikipedia/commons/b/b4/EUBanana-500x112.jpg',\n\t\t]\n\t]\n\n\t# Each list of predictions in prediction_groups is a list of (word, box) tuples.\n\tprint('Start recognizing text...')\n\tstart_time = time.time()\n\tprediction_groups = pipeline.recognize(images, detection_kwargs=None, recognition_kwargs=None)\n\tprint('End recognizing text: {} secs.'.format(time.time() - start_time))\n\n\t# Plot the predictions.\n\tfig, axs = plt.subplots(nrows=len(images), figsize=(20, 20))\n\tfor ax, image, predictions in zip(axs, images, prediction_groups):\n\t\tkeras_ocr.tools.drawAnnotations(image=image, predictions=predictions, ax=ax)\n\tplt.show()\n\ndef main():\n\t#old_detection_and_recognition_test() # Error.\n\t#training_test()\n\n\tnew_detection_test()\n\t#new_detection_and_recognition_test()\n\n#--------------------------------------------------------------------\n\nif '__main__' == __name__:\n\tmain()\n","repo_name":"sangwook236/SWDT","sub_path":"sw_dev/python/rnd/test/language_processing/keras_ocr_test.py","file_name":"keras_ocr_test.py","file_ext":"py","file_size_in_byte":10659,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"6"} +{"seq_id":"23002853187","text":"import librosa as lib\nimport sklearn.decomposition as decomp\nimport numpy as np\n\nimport dataToNotes as data \n\nfrom scipy import signal\n\nINDEX_TO_NOTE = {1 : 'C', 2: 'C#', 3: 'D', 4: 'D#', 5:'E', 6:'F', 7:'F#', 8:'G', 9: 'G#', 10: 'A', 11: 'A#', 12: 'B'}\n\ndef loudness_filter(song):\n b1, a1 = [0.98500175787242, -1.97000351574484, 0.98500175787242], [1.96977855582618, -0.97022847566350] #2nd order butterworth \n b2 = [0.05418656406430 , -0.02911007808948, -0.00848709379851, -0.00851165645469, -0.00834990904, 0.02245293253, -0.02596338512915, 0.01624864962975, -0.00240879051584, 0.00674613682247, -0.00187763777362] \n a2 = [3.47845948550071, -6.36317777566148, 8.54751527471874, -9.47693607801280, 8.81498681370155, -6.85401540936998, 4.39470996079559, -2.19611684890774, 0.75104302451432, -0.13149317958808] #Yulewalk filter 10th order\n\n filter_song = signal.lfilter(b2, a2, signal.lfilter(b1, a1, song))\n return filter_song\n\ndef load_song(audio_file, sr=44100., duration = None):\n song, sr_song = lib.load(audio_file, sr=sr, duration = duration)\n if len(song.shape) == 2:\n song = np.average(song, axis=1)\n song = loudness_filter(song)\n return song, sr_song \n\ndef find_essential_notes(song, sr):\n cqt = np.abs(lib.cqt(song, sr=sr, hop_length=128, n_bins=84, bins_per_octave=12,real=False, filter_scale=0.75))\n strong_elem = []\n for time_slice in cqt.T:\n local_peaks = signal.argrelextrema(time_slice, np.greater)[0]\n peaks = []\n for elem in local_peaks:\n db = 20 * np.log10(time_slice[elem])\n if db > -110:\n peaks.append(elem)\n strong_elem.append(peaks)\n \n weight1 = 1.0\n weight2 = 1.5\n weight3 = 1.0\n\n notes_idx = []\n for idx,notes in enumerate(strong_elem):\n if len(notes) == 0 or len(notes_idx) == 0:\n notes_idx.append(notes)\n else:\n if len(notes_idx[idx-1]) == 0:\n note_choice = []\n power_sum = sum(cqt[note][idx] for note in notes)\n for note in notes:\n score = weight1 * cqt[note][idx]/power_sum - weight3 * abs(84/2. - note)/84.\n note_choice.append((score,note))\n notes_idx.append([max(note_choice)[1]])\n else:\n prev_note = notes_idx[idx-1]\n power_sum = sum(cqt[note][idx] for note in notes)\n note_choice = []\n for note in notes:\n score = weight1 * cqt[note][idx]/power_sum - weight2 * abs(note - prev_note)/84. - weight3 * abs(84/2. - note)/84.\n note_choice.append((score,note))\n notes_idx.append([max(note_choice)[1]])\n \n notes = []\n for peaks in notes_idx:\n note_slice = [(idx/12 + 1, idx % 12 + 1) for idx in peaks]\n note_slice = [INDEX_TO_NOTE[note[1]]+ str(note[0]) for note in note_slice]\n notes.append(note_slice)\n\n return notes\n\ndef extract_tempo(song, sr):\n tempo, _ = lib.beat.beat_track(song, sr=sr)\n return tempo\n\ndef test():\n song,sr = load_song('./rondo.mp3')\n notes = find_essential_notes(song, sr)\n tempo = extract_tempo(song, sr) / 4\n data.processNotes(notes, float(sr), tempo=tempo) \n\nif __name__ == '__main__': test()\n","repo_name":"JonghyunAhn/MusicScore","sub_path":"music_analysis.py","file_name":"music_analysis.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"5026664686","text":"#\nimport socket\nimport threading\n\n\ndef recv_date(udp_socket):\n # 接收数据\n while True:\n recv = udp_socket.recvfrom(1024)\n print(recv)\n\n\ndef send(udp_socket, dest_ip, dest_port):\n # 发送数据\n while True:\n data = input(\"请输入要发送的内容:\")\n udp_socket.sendto(data.encode(\"utf-8\"), (dest_ip, dest_port))\n\n\ndef main():\n # 1、创建套接字\n udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n # 2、绑定本地信息\n udp_socket.bind((\"192.168.1.51\", 7890))\n # 3、定义要发送的端口和IP\n dest_ip = input(\"请输入对方的IP:\")\n dest_port = int(input(\"请输入对方的PORT:\"))\n\n t1 = threading.Thread(target=recv_date, args=(udp_socket,))\n t2 = threading.Thread(target=send, args=(udp_socket, dest_ip, dest_port))\n\n t1.start()\n t2.start()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"xinlongOB/python_docment","sub_path":"网络编程/多任务/多线程版udp聊天器.py","file_name":"多线程版udp聊天器.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"5556053877","text":"#!/bin/env python\nfrom collections import OrderedDict\nimport torch\nfrom torch.nn import Parameter\nfrom torch import nn\nimport numpy as np\nimport math\nfrom torch.nn.functional import softplus\n\n# GPU setup\nargs_no_cuda = False #True when manually turn off cuda\nuse_cuda = not args_no_cuda and torch.cuda.is_available()\nif use_cuda:\n print('device for inference on',torch.cuda.device_count(),'GPU(s)')\nelse:\n print('device for inference on CPU')\n\n\ncem_testing_flag = False\nif cem_testing_flag:\n import os\n from constants.paths import ONLINE_MODELS\n fn = f'cem_20230418.pth'\n path = os.path.join(ONLINE_MODELS,fn)\n nn_load_main_file = path\nelse:\n nn_load_main_file= '/scratch/cimes/cz3321/MOM6/MOM6-examples/src/MOM6/config_src/external/ML_Forpy/Forpy_CNN_GZ21/global_model.pt'\n\nnn_load_name = 'gaussian_four_regions'\n\nu_scale = 1/0.1 #0.09439346225350978\nv_scale = 1/0.1 #0.07252696573672539\nSu_scale = 1e-7 #4.9041400042653195e-08\nSv_scale = 1e-7 #4.8550991806254025e-08\n\n \n\nclass ConvLayer(nn.Sequential):\n def __init__(self,width0:int,width1:int,kernel0:int,kernel1:int = None,batchnorm:bool = False,nnlnr:bool = True):\n if kernel1 is None:\n kernel1 = kernel0\n d = []\n d.append(('conv',nn.Conv2d(width0,width1,(kernel0,kernel1))))\n if batchnorm and nnlnr:\n assert nnlnr\n d.append(('bnorm', nn.BatchNorm2d(width1)))\n if nnlnr:\n d.append(('nnlnr',nn.ReLU(inplace = True)))\n super().__init__(OrderedDict(d))\n \nclass SoftPlusLayer_(nn.Module):\n def __init__(self,min_value = 0) -> None:\n super().__init__()\n self._min_value = Parameter(torch.tensor(min_value))\n @property\n def min_value(self,):\n return softplus(self._min_value)\n def forward(self, x_):\n x = torch.clone(x_)\n x0,x1 = torch.split(x,x.shape[1]//2,dim=1)\n x1 = softplus(x1) + self.min_value\n return x0,x1\n def __repr__(self) -> str:\n return f'SoftPlusLayer({self.min_value.item()})'\n \nclass PartialSoftPlusLayer(nn.Module):\n def forward(self, x_):\n x = torch.clone(x_)\n x0,x1 = torch.split(x,x.shape[1]//2,dim=1)\n x1 = softplus(x1)\n return x0,x1\n def __repr__(self) -> str:\n return self.__class__.__name__\n\nclass CNN(nn.Sequential):\n def __init__(self,widths = None,kernels = None,batchnorm = None,seed = None,**kwargs):\n d = []\n zipwidths = zip(widths[:-1],widths[1:])\n nlayers = len(kernels)\n torch.manual_seed(seed)\n for i,((w0,w1),k,b,) in enumerate(zip(zipwidths,kernels,batchnorm)):\n d.append(\n (f'layer-{i}',ConvLayer(w0,w1,k,k,b,nnlnr = i < nlayers - 1))\n )\n d.append(\n (f'layer-{i+1}',PartialSoftPlusLayer())\n )\n super().__init__(OrderedDict(d))\n spread = 0\n for k in kernels:\n spread += (k-1)/2\n self.spread = int(spread)\n\n\nstatedict = torch.load(nn_load_main_file)\nmodeldict,statedict = statedict[nn_load_name]\ncnn=CNN(**modeldict)\ncnn.load_state_dict(statedict)\ncnn.eval()\n\n\n\ndef MOM6_testNN(uv,pe,pe_num,index):\n global cnn,gpu_id,u_scale,v_scale,Su_scale,Sv_scale\n # start_time = time.time()\n # print('PE number is',pe_num)\n # print('PE is',pe)\n # print(u.shape,v.shape)\n #normalize the input by training scaling\n u= uv[0,:,:,:]*u_scale\n v= uv[1,:,:,:]*v_scale\n x = np.array([np.squeeze(u),np.squeeze(v)])\n if x.ndim==3:\n x = x[:,:,:,np.newaxis]\n x = x.astype(np.float32)\n print(x.shape)\n x = x.transpose((3,0,1,2)) # new the shape is (nk,2,ni,nj)\n x = torch.from_numpy(x) # quite faster than x = torch.tensor(x)\n if use_cuda:\n if not next(cnn.parameters()).is_cuda:\n gpu_id = int(pe/math.ceil(pe_num/torch.cuda.device_count()))\n print('GPU id is:',gpu_id)\n cnn = cnn.cuda(gpu_id)\n x = x.cuda(gpu_id)\n with torch.no_grad():\n # start_time = time.time()\n outs = cnn.forward(x)\n if isinstance(outs,tuple):\n mean,precision = outs\n else:\n mean,precision = torch.split(outs,2,dim = 1)\n # end_time = time.time()\n if use_cuda:\n mean = mean.to('cpu')\n precision = precision.to('cpu')\n mean = mean.numpy().astype(np.float64)\n std = np.sqrt(1/precision.numpy().astype(np.float64))\n # At this point, python out shape is (nk,4,ni,nj)\n # Comment-out is tranferring arraies into F order\n # convert out to (ni,nj,nk)\n mean = mean.transpose((1,2,3,0)) # new the shape is (4,ni,nj,nk)\n std = std.transpose((1,2,3,0))\n dim = np.shape(mean)\n Sxy = np.zeros((6,dim[1],dim[2],dim[3])) # the shape is (2,ni,nj,nk)\n epsilon_x = np.random.normal(0, 1, size=(dim[1],dim[2]))\n epsilon_x = np.dstack([epsilon_x]*dim[3])\n epsilon_y = np.random.normal(0, 1, size=(dim[1],dim[2]))\n epsilon_y = np.dstack([epsilon_y]*dim[3])\t\t\t\t \n Sxy[0,:,:,:] = (mean[0,:,:,:] )*Su_scale\n Sxy[1,:,:,:] = (mean[1,:,:,:] )*Sv_scale\n Sxy[2,:,:,:] = mean[0,:,:,:]*Su_scale\n Sxy[3,:,:,:] = mean[1,:,:,:]*Sv_scale\n # Sxy[4,:,:,:] = std[0,:,:,:]*Su_scale\n # Sxy[5,:,:,:] = std[1,:,:,:]*Sv_scale\n \"\"\"\n np.savetxt('Sx_mean_cem.txt',Sxy[2,:,:,0])\n np.savetxt('Sy_mean_cem.txt',Sxy[3,:,:,0])\n np.savetxt('Sx_std_cem.txt',Sxy[4,:,:,0])\n np.savetxt('Sy_std_cem.txt',Sxy[5,:,:,0])\n np.savetxt('WH_u_cem.txt',uv[0,:,:,0])\n np.savetxt('WH_v_cem.txt',uv[1,:,:,0])\n \"\"\"\n return Sxy \n","repo_name":"CemGultekin1/cm2p6","sub_path":"online/run_script.py","file_name":"run_script.py","file_ext":"py","file_size_in_byte":5535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"12578341917","text":"import os\n\ndef main():\n i = 0\n path = 'C:/Users/elton/OneDrive/Área de Trabalho/BACKUP/Faculdade/Projetos_pequenos/RenameFiles/Docs'\n \n for filename in os.listdir(path):\n my_dest = 'img' + str(i) + '.jpg'\n my_source = path + filename\n my_dest = path + my_dest\n os.rename(my_source, my_dest)\n i += 1\n\nif __name__ == '__main__':\n main()\n ","repo_name":"EltonLunardi/Projetos_pequenos","sub_path":"RenameFiles/rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"28207521795","text":"import os\nimport sys\nimport json\nimport inspect\nimport traceback\nfrom importlib import import_module\n\nimport requests\n\n# ENV = 'Linux'\nENV = 'Mac'\n\nif ENV == 'Mac':\n SERVER = 'http://host.docker.internal:8899/pyapi'\nelse:\n SERVER = 'http://172.17.0.1:8899/pyapi'\n\nif 'PY_SERVER' in os.environ:\n SERVER = os.environ.get('PY_SERVER')\n\n\nclass RedirectPrints:\n def __init__(self, job_id):\n self.job_id = job_id\n\n def __enter__(self):\n self._original_stdout = sys.stdout\n self._original_stderr = sys.stderr\n sys.stdout = Logger(self.job_id, 'stdout')\n sys.stderr = Logger(self.job_id, 'stderr')\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n sys.stdout = self._original_stdout\n sys.stderr = self._original_stderr\n\n\nclass HiddenPrints:\n def __enter__(self):\n self._original_stdout = sys.stdout\n sys.stdout = open(os.devnull, 'w')\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n sys.stdout = self._original_stdout\n\n\nclass Logger(object):\n def __init__(self, job_id, log_type):\n self.job_id = job_id\n self.log_type = log_type\n if log_type == 'stdout':\n self.terminal = sys.stdout\n else:\n self.terminal = sys.stderr\n\n def write(self, message):\n self.terminal.write(message)\n # job log\n job_id = self.job_id\n requests.put('{SERVER}/jobs/{job_id}/log'.format(SERVER=SERVER,\n job_id=job_id),\n json={'log_type': self.log_type, 'message': message})\n\n def flush(self):\n # this flush method is needed for python 3 compatibility.\n # this handles the flush command by doing nothing.\n # you might want to specify some extra behavior here.\n pass\n\n\ndef get_module_info(module_identity):\n [encoded_name, version] = module_identity.split('/')\n version = '_'.join(version.split('.'))\n project = requests.get(\n '{SERVER}/project/projects/{encoded_name}?by=encoded_name'.format(\n SERVER=SERVER,\n encoded_name=encoded_name)).json()['response']\n return project['user_ID'], project['name'], version\n\n\ndef module_general(module_id, action, *args, **kwargs):\n [user_ID, module_name, version] = module_id.split('/')\n version = '_'.join(version.split('.'))\n try:\n main_module = import_module(\n 'modules.{user_ID}.{module_name}.{version}.main'.format(\n user_ID=user_ID, module_name=module_name, version=version))\n except ImportError:\n main_module = import_module(\n 'modules.{user_ID}.{module_name}.{version}.src.main'.format(\n user_ID=user_ID, module_name=module_name, version=version))\n cls = getattr(main_module, module_name)()\n return getattr(cls, action)(*args, **kwargs)\n\n\ndef get_module(module_id):\n # [user_ID, module_name, version] = module_id.split('/')\n # version = '_'.join(version.split('.'))\n user_ID, module_name, version = get_module_info(module_id)\n try:\n main_module = import_module(\n 'modules.{user_ID}.{module_name}.{version}.main'.format(\n user_ID=user_ID, module_name=module_name, version=version))\n except ImportError:\n main_module = import_module(\n 'modules.{user_ID}.{module_name}.{version}.src.main'.format(\n user_ID=user_ID, module_name=module_name, version=version))\n cls = getattr(main_module, module_name)\n return cls\n\n\ndef json_parser(json_obj):\n return json.loads(json_obj)\n\n\nclass Client:\n\n def __init__(self, api_key, project_id, user_ID, project_type,\n source_file_path, silent=False):\n self.silent = silent\n self.api_key = api_key\n self.project_id = project_id\n self.user_ID = user_ID\n self.project_type = project_type\n self.source_file_path = source_file_path\n\n def controller(self, func, *args, **kw):\n if func.__name__ in ['run', 'predict', 'train']:\n other = {\n 'running_module': kw.pop('module_id')\n }\n else:\n other = {\n 'running_code': inspect.getsource(func)\n }\n # log start\n job = requests.post('{SERVER}/jobs'.format(SERVER=SERVER),\n json={'project_id': self.project_id,\n 'type': self.project_type,\n 'source_file_path': self.source_file_path,\n 'user_ID': self.user_ID,\n 'run_args': {'args': args, 'kwargs': kw},\n **other},\n ).json()['response']\n job_id = job['_id']\n with RedirectPrints(job_id):\n try:\n ret = func(*args, **kw)\n except Exception as e:\n exc = traceback.format_exc()\n requests.put('{SERVER}/jobs/{job_id}/log'.format(\n SERVER=SERVER, job_id=job_id),\n json={'log_type': 'exception',\n 'message': exc})\n raise e\n else:\n # log end\n requests.put('{SERVER}/jobs/{job_id}/success'.format(\n SERVER=SERVER, job_id=job_id)).json()\n return ret\n\n def record_invoke(self, module_id, *args, **kwargs):\n body = {\n 'module_identity': module_id,\n 'project_id': self.project_id,\n 'project_type': self.project_type,\n 'api_key': self.api_key,\n 'source_file_path': self.source_file_path,\n 'user_ID': self.user_ID\n }\n try:\n json.dumps({'args': args, 'kwargs': kwargs})\n except:\n pass\n else:\n body.update({'run_args': {'args': args, 'kwargs': kwargs}})\n finally:\n # check auth and create invoke\n invoke = requests.post(\n '{SERVER}/user/auth_and_create_invoke'.format(SERVER=SERVER),\n json=body,\n ).json()['response']\n\n if invoke == 'INVALID_KEY':\n raise Exception('api key is not valid')\n\n def invoke_wrapper(self, func, *args, with_control=False, **kwargs):\n\n if self.silent and with_control:\n with HiddenPrints():\n return self.controller(func, *args, **kwargs)\n elif not self.silent and with_control:\n return self.controller(func, *args, **kwargs)\n elif self.silent and not with_control:\n with HiddenPrints():\n return func(*args, **kwargs)\n else:\n return func(*args, **kwargs)\n\n def run_module_general(self, action, module_id, *args, with_control=False,\n **kwargs):\n\n self.record_invoke(module_id, *args, **kwargs)\n\n return self.invoke_wrapper(module_general, module_id, action, *args,\n with_control=with_control, **kwargs)\n\n def module(self, module_id, *m_args, **m_kwargs):\n\n cls = get_module(module_id)\n\n class WrappedClass(cls):\n\n def invoke_helper(w_self, fn_name, *args, **kwargs):\n if hasattr(super(), fn_name):\n self.record_invoke(module_id, *args, **kwargs)\n if kwargs.get('with_control'):\n kwargs.update({'module_id': module_id})\n return self.invoke_wrapper(getattr(super(), fn_name),\n *args, **kwargs)\n else:\n raise AttributeError(\n \"AttributeError: '{name}' object has no \"\n \"attribute f'{fn_name}'\".format(name=cls.__name__,\n fn_name=fn_name))\n\n def run(w_self, *args, **kwargs):\n \"\"\"\n example:\n cls = client.module('user1/project1/0.0.1')\n cls.run({'a': 1, 'b': 2}, with_control=True)\n cls.run({'a': 1, 'b': 2})\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n frame = inspect.currentframe()\n fn_name = inspect.getframeinfo(frame).function\n return w_self.invoke_helper(fn_name, *args, **kwargs)\n\n def train(w_self, *args, **kwargs):\n frame = inspect.currentframe()\n fn_name = inspect.getframeinfo(frame).function\n return w_self.invoke_helper(fn_name, *args, **kwargs)\n\n def predict(w_self, *args, **kwargs):\n frame = inspect.currentframe()\n fn_name = inspect.getframeinfo(frame).function\n return w_self.invoke_helper(fn_name, *args, **kwargs)\n\n def load_model(w_self, *args, **kwargs):\n frame = inspect.currentframe()\n fn_name = inspect.getframeinfo(frame).function\n return w_self.invoke_helper(fn_name, *args, **kwargs)\n\n return WrappedClass(*m_args, **m_kwargs)\n\n def run(self, module_id, *args, with_control=False, **kwargs):\n return self.run_module_general('run', module_id, *args,\n with_control=with_control,\n **kwargs)\n\n def train(self, module_id, *args, with_control=False, **kwargs):\n return self.run_module_general('train', module_id, *args,\n with_control=with_control,\n **kwargs)\n\n def predict(self, module_id, *args, with_control=False, **kwargs):\n return self.run_module_general('predict', module_id, *args,\n with_control=with_control,\n **kwargs)\n","repo_name":"zjubio/jupyterhub","sub_path":"base-notebook/modules/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"36908926615","text":"def grid_visual(data):\n \"\"\"\n This function displays a grid of images to show full misclassification\n :param data: grid data of the form;\n [nb_classes : nb_classes : img_rows : img_cols : nb_channels]\n :return: if necessary, the matplot figure to reuse\n \"\"\"\n import matplotlib.pyplot as plt\n\n plt.rcParams['figure.figsize'] = [15, 15]\n # Ensure interactive mode is disabled and initialize our graph\n plt.ioff()\n figure = plt.figure()\n figure.canvas.set_window_title('Cleverhans: Grid Visualization')\n\n # Add the images to the plot\n num_cols = data.shape[0]\n num_rows = data.shape[1]\n num_channels = data.shape[4]\n for y in range(num_rows):\n for x in range(num_cols):\n figure.add_subplot(num_rows, num_cols, (x + 1) + (y * num_cols))\n plt.axis('off')\n\n if num_channels == 1:\n plt.imshow(data[x, y, :, :, 0], cmap='gray')\n else:\n plt.imshow(data[x, y, :, :, :])\n\n # Draw the plot and return\n plt.show()\n return figure\n\n\nif __name__ == '__main__':\n from art.attacks.evasion import FastGradientMethod as FGM, ProjectedGradientDescentTensorFlowV2 as PGD, \\\n CarliniL2Method as CW\n from art.classifiers import TensorFlowV2Classifier as Wrapper\n from art.utils import compute_accuracy, compute_success\n import tensorflow as tf\n import numpy as np\n\n dataset = 'mnist'\n if dataset == 'mnist':\n (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\n x_train, x_test = x_train[..., None] / np.float32(255), x_test[..., None] / np.float32(255)\n y_train = tf.keras.utils.to_categorical(y_train, 10)\n y_test = tf.keras.utils.to_categorical(y_test, 10)\n\n num_epochs = 12\n batch_size = 256\n eps, sigma = 76 / 255, 76 / 255\n optimizer = tf.keras.optimizers.Adam()\n\n elif dataset == 'cifar10':\n (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()\n x_train, x_test = x_train / np.float32(255), x_test / np.float32(255)\n y_train = tf.keras.utils.to_categorical(y_train, 10)\n y_test = tf.keras.utils.to_categorical(y_test, 10)\n input_shape = x_train[0].shape\n m = 1000\n eps = 0.3\n attacks = [\n 'FGM',\n 'PGD',\n # 'CW',\n ]\n\n FGM_params = {\n 'eps': eps,\n 'norm': np.inf,\n 'batch_size': 500,\n 'num_random_init': 0\n }\n\n PGD_params = {\n 'eps': eps,\n 'eps_step': 0.02, # !!!\n 'max_iter': 30,\n 'norm': np.inf,\n 'batch_size': 500,\n 'num_random_init': 0\n }\n\n CW_params = {\n 'learning_rate': .1,\n 'confidence': 1,\n 'batch_size': 1000,\n 'max_iter': 100,\n }\n loss_fn = tf.losses.CategoricalCrossentropy(from_logits=True)\n source_models = []\n source_models.append(tf.keras.models.load_model('./Models/ens/model_1.h5'))\n target_models = []\n # target_models.append(tf.keras.models.load_model('./Models/ens/ens_model_0.h5')) # 集成对抗训练\n target_models.append(tf.keras.models.load_model('./Models/ens/pr_model_0.h5')) # 投影正则化\n # target_models.append(tf.keras.models.load_model('./Models/ens/model_0.h5')) # 无防御\n # target_models.append(tf.keras.models.load_model('./Models/ens/pgd_model_0.h5')) # PGD对抗训练\n\n art = Wrapper(source_models[0], nb_classes=10, clip_values=(0, 1), input_shape=input_shape, loss_object=loss_fn)\n for attack in attacks:\n print('Performing' + attack + 'attack:')\n adv_acc = []\n for eps in [0, 0.2, 0.3, 0.4]: # !!!\n if eps > 0:\n FGM_params['eps'] = eps\n PGD_params['eps'] = eps\n adversary = eval(attack + '(art, **' + attack + '_params)')\n x_adv = adversary.generate(x_test[:m])\n else:\n x_adv = x_test[:m]\n for target in target_models:\n adv_acc.append(compute_accuracy(target.predict(x_adv), y_test[:m])[0])\n # print('Target Accuracy=', round(target_acc*100, 2),'%')\n # row = (lambda a: 1 if a < 10 else (10 if a > 100 else a//10))(m)\n # column = np.amin([10, m])\n # grid_visual(x_adv[:int(row * column)].reshape(column, row, input_shape[0], input_shape[1], input_shape[2]))\n print(adv_acc)\n","repo_name":"JoshuaCN/Gradient-Projection-Regularization","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":4404,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"73817265466","text":"import pytest\n\nimport torch\n\nfrom pystiche_papers import utils\n\n\n@pytest.fixture\ndef create_too_large_cuda_tensor():\n if torch.cuda.is_available():\n\n def creator():\n device_idx = torch.cuda.current_device()\n device_properties = torch.cuda.get_device_properties(device_idx)\n max_memory_in_bytes = device_properties.total_memory\n max_memory_in_gibibytes = max_memory_in_bytes / 1024**3\n requested_memory_in_gibibytes = int(2 * max_memory_in_gibibytes)\n size = (requested_memory_in_gibibytes, *[1024] * 3)\n return torch.empty(\n size, device=torch.device(\"cuda\", device_idx), dtype=torch.uint8\n )\n\n else:\n\n def creator():\n raise RuntimeError(\"CUDA out of memory\")\n\n return creator\n\n\ndef test_use_cuda_out_of_memory_error(create_too_large_cuda_tensor):\n with pytest.raises(utils.CudaOutOfMemoryError):\n with utils.use_cuda_out_of_memory_error():\n create_too_large_cuda_tensor()\n\n\ndef test_abort_if_cuda_memory_exausts(create_too_large_cuda_tensor):\n create_too_large_cuda_tensor = utils.abort_if_cuda_memory_exausts(\n create_too_large_cuda_tensor\n )\n\n with pytest.warns(utils.CudaOutOfMemoryWarning):\n create_too_large_cuda_tensor()\n","repo_name":"pystiche/papers","sub_path":"tests/unit/utils/test_cuda.py","file_name":"test_cuda.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"6"} +{"seq_id":"30220752715","text":"\n#? Реализуйте RLE алгоритм: реализуйте модуль сжатия и восстановления данных.\n#? Входные данные хранятся в отдельных текстовых файлах.\n\n# stroka = \"aaabbbbccbbb\"\n# ....\n# stroka = \"3a4b2c3b\"\n# Вывод: stroka = \"aaabbbbccbbb\"\n\n\nimport re\n\ndef compress(string):\n compressed = \"\"\n count = 1\n for i in range(len(string)):\n if i+1 < len(string) and string[i] == string[i+1]:\n count += 1\n else:\n compressed += str(count) + string[i]\n count = 1\n return compressed\n\ndef decompress(string):\n decompressed = \"\"\n pattern = re.compile(r\"(\\d+)(\\D)\")\n matches = pattern.finditer(string)\n for match in matches:\n count = int(match.group(1))\n char = match.group(2)\n decompressed += char * count\n return decompressed\n\n# Reading the input string from a file\nwith open(\"005\\input.txt\", \"r\") as file:\n string = file.read()\n\ncompressed = compress(string)\n\n# Writing the compressed string to a file\nwith open(\"005\\compressed.txt\", \"w\") as file:\n file.write(compressed)\n\n# Reading the compressed string from a file\nwith open(\"005\\compressed.txt\", \"r\") as file:\n compressed = file.read()\n\ndecompressed = decompress(compressed)\n\n# Writing the decompressed string to a file\nwith open(\"005\\decompressed.txt\", \"w\") as file:\n file.write(decompressed)\n","repo_name":"toorts/py_hm","sub_path":"005/task_03.py","file_name":"task_03.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"39886288487","text":"#!/usr/local/bin/python3.6\nimport argparse\nimport ipaddress\nimport os\nimport pytricia\nimport sys\nfrom itertools import groupby\n\n\n\"\"\"\n================================================================================\nPurpose\n================================================================================\nTake two files as input: (1) IPs (2) Subnets\n\nWill match every IP to a subnet\nIf the IP is in a subnet, then show what subnet it is in\n\nip file (input file):\n101.24.8.175\n10.130.166.216\n\nsubnet file (input file):\n101.24.8.0/24\n10.130.166.0/24\n\noutput file:\nSource,Destination\n101.24.8.0/24,101.24.8.175\n10.130.166.0/24,10.130.166.216\n\"\"\"\n\n\"\"\"\n================================================================================\nVariables\n================================================================================\n\"\"\"\nfile_dir = str(os.getcwd()+'/')\nsubnet_relationship_file = file_dir + 'ip-subnet-relationship.csv'\n\nIPSR_DDI = set()\nIP_DDI = set()\nSN_DDI = set()\n\n# Command line arguments\nparser = argparse.ArgumentParser(description='Purpose of script is to create a relationship file showing what subnet every IP is in when given two input files: #1 IP and #2 Subnets')\nparser.add_argument('--log', '-l', default='20', choices=['10', '20'],\n help='Used to specify the logging level. Set logging to DEBUG when troubleshooting. If you do not specify a logging level, the default is 20(INFO). Valid choices are either 10 or 20. Explanation of choices: 10(DEBUG) 20(INFO)')\nparser.add_argument('--subnets', '-s',\n help='Used to specify the input file that contains all of the Subnets.')\nparser.add_argument('--ips', '-i',\n help='Used to specify the input file that contains all of the IPs.')\nargs = parser.parse_args()\n\ndef keyfunc(s):\n \"\"\"\n Sorts sets based on numbers so that IP's appear in order\n Common usage is:\n sorted(my_set, key=keyfunc)\n \"\"\"\n return [int(''.join(g)) if k else ''.join(g) for k, g in groupby('\\0'+s, str.isdigit)]\n\n\"\"\"\n================================================================================\nValidating expected options were given and that files exist\n================================================================================\n\"\"\"\n\n# If the user does not specify input file on command line\ntry:\n if not args.ips:\n print('\\nNeed to run script again, but specify an input file that contains all of IPs that you want a relationship for.\\n')\n # Stopping script so user can rerun correctly\n sys.exit()\n if not args.subnets:\n print('\\nNeed to run script again, but specify an input file that contains all of Subnets that you will use to find relationship for the IPs.\\n')\n # Stopping script so user can rerun correctly\n sys.exit()\nexcept Exception as e:\n print('Unable to look for input files - '+str(e))\n\n\n# If specified file does not exist in current working directory\ntry:\n if not os.path.isfile(file_dir+args.ips):\n print ('Expecting to find file containing list of IPs to create relationship for in ' + file_dir+'\\nPut file in correct directory, then re-run script.')\n # Stopping script so user can rerun correctly\n sys.exit()\nexcept Exception as e:\n print('Unable to look for IPs file - '+str(e))\n\ntry:\n if not os.path.isfile(file_dir+args.subnets):\n print ('Expecting to find file containing list of Subnets to create IP relationship for in ' + file_dir+'\\nPut file in correct directory, then re-run script.')\n # Stopping script so user can rerun correctly\n sys.exit()\nexcept Exception as e:\n print('Unable to look for Subnets file - '+str(e))\n\n\n\"\"\"\n================================================================================\nCreating relationship file\n================================================================================\n\"\"\"\n\n# Adding IPs to set\ntry:\n with open(file_dir+args.ips, 'r') as ipfile:\n for line in ipfile:\n try:\n IP_DDI.add(ipaddress.ip_address(line.strip()))\n except:\n pass\nexcept Exception as e:\n print('Unable to add IPs to set - '+str(e))\n sys.exit()\n\n\n# Adding subnets to set\ntry:\n with open(file_dir+args.subnets, 'r') as subfile:\n for lines in subfile:\n try:\n SN_DDI.add(ipaddress.ip_network(lines.strip()))\n except:\n pass\nexcept Exception as e:\n print('Unable to add Subnets to set - '+str(e))\n sys.exit()\n\n\n# Create Trie object\ntry:\n pyt = pytricia.PyTricia(128)\n for i in SN_DDI:\n try:\n pyt.insert(ipaddress.IPv4Network(i), ipaddress.IPv4Network(i))\n except:\n try:\n pyt.insert(ipaddress.IPv6Network(i), ipaddress.IPv6Network(i))\n except:\n pass\nexcept Exception as e:\n print('Unable to add subnets to Trie object - '+str(e))\n sys.exit()\n\n\n# Identifying the subnet for each IP\ntry:\n # If the set is not empty\n if len(IP_DDI) != 0:\n for i in IP_DDI:\n a = i in pyt\n if a:\n IPSR_DDI.add(pyt.get_key(i) + ',' + str(i))\n if not a:\n IPSR_DDI.add(',' + str(i))\nexcept Exception as e:\n print('Unable to find the relationship for the Subnets and IPs - '+str(e))\n sys.exit()\n\n# Adding data to relationship file\ntry:\n # If the set is not empty\n if len(IPSR_DDI) != 0:\n IPSR_DDI_SORT = sorted(IPSR_DDI, key=keyfunc)\n with open(subnet_relationship_file, \"a\") as f:\n f.write('Subnet,IP\\n')\n for iprha in IPSR_DDI_SORT:\n f.write(iprha + '\\n')\nexcept Exception as e:\n print('Unable to find the size of the IP relationship set and write to output file - '+str(e))\n sys.exit()\n","repo_name":"ddiguy/ip-subnet-relationship","sub_path":"ip-subnet-relationship.py","file_name":"ip-subnet-relationship.py","file_ext":"py","file_size_in_byte":5750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"30971859825","text":"\"\"\"Add newsletter statistics table\n\nRevision ID: 20230228134447\nRevises: 20220921134624\nCreate Date: 2023-02-28 13:48:49.647245\n\n\"\"\"\nfrom alembic import op\nfrom osha.oira.upgrade.utils import has_table\n\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = \"20230228134447\"\ndown_revision = \"20220921134624\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade(engine_name):\n if not has_table(\"newsletter\"):\n op.create_table(\n \"newsletter\",\n sa.Column(\"zodb_path\", sa.String(length=512), nullable=False),\n sa.Column(\"count\", sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint(\"zodb_path\"),\n )\n\n\ndef downgrade(engine_name):\n if has_table(\"newsletter\"):\n op.drop_table(\"newsletter\")\n","repo_name":"euphorie/osha.oira","sub_path":"src/osha/oira/upgrade/alembic_statistics/versions/20230228134447_add_newsletter_statistics_table.py","file_name":"20230228134447_add_newsletter_statistics_table.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"6"} +{"seq_id":"39206961336","text":"import os\n\nimport numpy as np\nimport keras \n\nfrom keras.utils import to_categorical, Sequence\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\n\nclass ImageSequence(Sequence): \n '''Extends the keras Sequence class. It takes in a series of indicies and it pulls the pictures from the folder specified\n it generates batches with the inputed batch size that have been preprocessed by the inputed preprocess function\n '''\n def __init__(self,labeldict, batch_size, train_indicies,preprocessing_func,folder = 'data/initial_images/'):\n self.NUM_CLASSES = 228\n self.image_folder = folder\n self.indicies = train_indicies\n self.labels = labeldict\n self.batch_size = batch_size\n #self.data_generator = data_generator\n self.preprocessing_func = preprocessing_func\n def __len__(self):\n return (len(self.indicies)//self.batch_size)\n \n def __getitem__(self, idx):\n '''gets and processes one batch\n '''\n inds = self.indicies[idx * self.batch_size : (idx+1) * (self.batch_size)]\n X = np.array([self.get_img_array(n) for n in inds])\n y = np.array([self.get_label(n) for n in inds]) \n return X, y\n \n def get_label(self,n):\n '''helper function to get one label'''\n y = [int(x) - 1 for x in self.labels[n]['labelId']]\n y = np.array(keras.utils.to_categorical(y, num_classes = self.NUM_CLASSES).sum(axis = 0))\n return y\n \n def get_img_array(self,n):\n '''helper function to get one image and process it'''\n img = image.load_img('{}{}.jpg'.format(self.image_folder,n),grayscale=False,target_size=(224,224,3))\n image.img_to_array(img)\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis = 0)\n x = x.reshape((224,224,3))\n x = self.preprocessing_func(x)\n return x\n\n \ndef create_train_val_inds(val_size,folder = 'data/initial_images/',seed = 42):\n '''helper function to make a train/val split\n '''\n np.random.seed = seed\n inds = [x[:-4] for x in os.listdir(folder)]\n val_inds = np.random.choice(inds,size = val_size)\n train_inds = np.array([x for x in inds if x not in val_inds])\n return train_inds, val_inds\n \ndef create_validation(labels, validation_inds, preprocess_func, folder = 'data/initial_images/',NUM_CLASSES = 228): \n '''creates and processes the validation set \n '''\n X,y = [],[]\n for n in validation_inds: \n img = image.load_img('{}{}.jpg'.format(folder,n),grayscale=False,target_size=(224,224,3))\n image.img_to_array(img)\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis = 0)\n x = preprocess_func(x)\n X.append(x.reshape((224,224,3)))\n label = labels[n]['labelId']\n label = np.array([int(l) - 1 for l in label])\n label = keras.utils.to_categorical(label, num_classes = NUM_CLASSES).sum(axis = 0)\n y.append(label)\n X,y = np.array(X), np.array(y)\n return X,y\n\ndef create_sequence_and_val(labels, val_size,batch_size,preprocess_func,folder = 'data/initial_images/',seed = 42):\n '''creates a ImageSequence object as well as a validation set for the keras \n fit_generator method\n '''\n \n train_inds,val_inds = create_train_val_inds(val_size, folder = folder,seed = seed)\n \n Xval,yval = create_validation(labels,val_inds,preprocess_func,folder = folder)\n \n train_sequence = ImageSequence(labels, batch_size, train_inds, preprocess_func, folder = folder)\n \n return train_sequence, Xval, yval\n","repo_name":"GougeC/iMaterialist_Challenge","sub_path":"training_utils.py","file_name":"training_utils.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"25649084195","text":"# COS738 Assignment 3\n# Ezra Fielding, 3869003\n\nfrom tkinter import filedialog\nfrom tkinter import*\nimport time\nfrom stegcrypt import StegCrypt\n\n#=========================Methods=================================\ndef browse_button_plainfile():\n '''\n Spawns filedialog to select Plaintext Image\n '''\n file_path=filedialog.askopenfilename()\n folder_path_plainfile.set(file_path)\n print (folder_path_plainfile)\n\ndef browse_button_stegofile():\n '''\n Spawns filedialog to select Stegotext Image\n '''\n file_path=filedialog.askopenfilename()\n folder_path_stegofile.set(file_path)\n print (folder_path_stegofile)\n\ndef browse_button_coverfile1():\n '''\n Spawns filedialog to select Covertext Image for encryption\n '''\n file_path=filedialog.askopenfilename()\n folder_path_coverfile1.set(file_path)\n print (folder_path_coverfile1)\n\ndef browse_button_coverfile2():\n '''\n Spawns filedialog to select Covertext Image for decryption\n '''\n file_path=filedialog.askopenfilename()\n folder_path_coverfile2.set(file_path)\n print (folder_path_coverfile2)\n\ndef btnEncrypt():\n '''\n Encrypts the Plaintext with the Covertext\n '''\n try:\n # Open and load image files\n plaintext = SC.open_img(folder_path_plainfile.get())\n covertext = SC.open_img(folder_path_coverfile1.get())\n # Encrypt Plaintext image\n stegotext = SC.encrypt(plaintext, covertext)\n # Save Stegotext Image\n SC.save_stegotext_tiff(stegotext, \"Stegotext.tiff\")\n # Set status\n status_text.set(\"Encryption Complete! Stegotext Image Saved\")\n except ValueError as v:\n status_text.set(v)\n except Exception as e:\n status_text.set(e)\n\ndef btnDecrypt():\n '''\n Decrypts Stegotext with the Covertext\n '''\n try:\n # Open and load image files\n stegotext = SC.open_stegotext_tiff(folder_path_stegofile.get())\n covertext = SC.open_img(folder_path_coverfile2.get())\n # Decrypt Stegotext Image\n plaintext = SC.decrypt(stegotext, covertext)\n # Save Plaintext Image\n SC.save_image(plaintext, \"Plaintext.jpg\")\n # Set Status\n status_text.set(\"Decryption Complete! Plaintext Image Saved\")\n except ValueError as v:\n status_text.set(v)\n except Exception as e:\n status_text.set(e)\n\ndef quit():\n '''\n Function to end program after Tkinter window is closed\n '''\n root.quit()\n root.destroy()\n\n#=============Tkinter root Window Creation=========================\nroot = Tk()\nTk().withdraw()\nroot.geometry(\"600x650+0+0\")\nroot.title(\"Image Steganocryptography Implementation\")\nroot.protocol(\"WM_DELETE_WINDOW\", quit)\n# Window Framing\nTops = Frame(root, width = 1000, relief = SUNKEN)\nTops.pack(side=TOP)\nwindow = Frame(root, width = 1000, relief = SUNKEN)\nwindow.pack(side=TOP)\n\n#================Variable Declaration==============================\n# Image File Path Variables\nfolder_path_plainfile = StringVar()\nfolder_path_coverfile1 = StringVar()\nfolder_path_coverfile2 = StringVar()\nfolder_path_stegofile = StringVar()\n# Status Variable\nstatus_text = StringVar()\n# StegCrypt Object\nSC = StegCrypt()\n\n#=========================Time======================================\nlocaltime=time.asctime(time.localtime(time.time()))\n\n#=========================Labels======================================\n# Heading\nlblInfo = Label(Tops, font=('arial', 18, 'bold'), text=\"Image Steganocryptography\\nImplementation\",fg=\"Black\")\nlblInfo.grid(row=0,column=0)\nlblInfo = Label(Tops, font=('arial', 8, 'bold', 'italic'),text=localtime, fg=\"Black\")\nlblInfo.grid(row=1,column=0)\n# Encryption Subheading\nlblInfo = Label(window, font=('arial', 15, 'bold'),text=\"\\nEncryption and Image Hiding\", fg=\"Black\")\nlblInfo.grid(row=2,column=0)\n# Image Selection Labels\nlblInfo = Label(window, font=('arial', 8, 'italic', 'bold'),text=\"\\nAttach Plaintext Image file (.jpg)\", fg=\"Steel Blue\")\nlblInfo.grid(row=3,column=0)\nlblInfo = Label(window, font=('arial', 8, 'italic','bold'), text=\"\\nAttach Covertext Image file (.jpg)\", fg=\"Steel Blue\")\nlblInfo.grid(row=5,column=0)\n# Decryption Subheading\nlblInfo = Label(window, font=('arial', 15, 'bold'),text=\"\\nDecryption\", fg=\"Black\")\nlblInfo.grid(row=10,column=0)\n# Image Selection Labels\nlblInfo = Label(window, font=('arial', 8, 'italic', 'bold'),text=\"\\nAttach Stegotext Image file (.tiff)\", fg=\"Steel Blue\")\nlblInfo.grid(row=11,column=0)\nlblInfo = Label(window, font=('arial', 8, 'italic','bold'), text=\"\\nAttach Covertext Image file (.jpg)\", fg=\"Steel Blue\")\nlblInfo.grid(row=13,column=0)\n# Status Section label\nlblInfo = Label(window, font=('arial', 8, 'bold'), text=\" \\n \\nSTATUS\", fg=\"Steel Blue\")\nlblInfo.grid(row=17,column=0)\n\n#=========================Text Variable Display===================================\n# Encryption Image Paths\ntxtDisplay = Entry(window, font=('arial',8),textvariable=folder_path_plainfile, bd=5,width =50, bg=\"white\")\ntxtDisplay.grid(row=4,column=0)\ntxtDisplay = Entry(window, font=('arial',8),textvariable=folder_path_coverfile1, bd=5,width=50, bg=\"white\")\ntxtDisplay.grid(row=6,column=0)\n# Decryption Image Paths\ntxtDisplay = Entry(window, font=('arial',8),textvariable=folder_path_stegofile, bd=5,width =50, bg=\"white\")\ntxtDisplay.grid(row=12,column=0)\ntxtDisplay = Entry(window, font=('arial',8),textvariable=folder_path_coverfile2, bd=5,width=50, bg=\"white\")\ntxtDisplay.grid(row=14,column=0)\n# Status Message\ntxtDisplay = Entry(window, font=('arial',8),textvariable=status_text, bd=5, width =50, bg=\"white\")\ntxtDisplay.grid(row=18,column=0)\n\n#=========================Buttons===================================\n# Encryption Buttons\nbtnbrowseplaintxt=Button(window, padx=5,pady=5,bd=5,fg=\"black\", font=('arial', 8,'bold'), text=\"Select Plaintext Image\",bg =\"brown\", command=browse_button_plainfile).grid(row=4,column=1)\nbtnbrowsecovertxt1=Button(window, padx=5,pady=5,bd=5,fg=\"black\", font=('arial', 8,'bold'), text=\"Select Covertext Image\",bg =\"brown\", command=browse_button_coverfile1).grid(row=6,column=1)\nbtnEncr=Button(window, padx=5,pady=5,bd=5,fg=\"black\", font=('arial', 12,'bold'), text=\"Encrypt\",bg =\"powder blue\", command=btnEncrypt).grid(row=9,column=0)\n# Decryption Buttons\nbtnbrowsestegotxt=Button(window, padx=5,pady=5,bd=5,fg=\"black\", font=('arial', 8,'bold'), text=\"Select Stegotext Image\",bg =\"brown\", command=browse_button_stegofile).grid(row=12,column=1)\nbtnbrowsecovertxt2=Button(window, padx=5,pady=5,bd=5,fg=\"black\", font=('arial', 8,'bold'), text=\"Select Covertext Image\",bg =\"brown\", command=browse_button_coverfile2).grid(row=14,column=1)\nbtnDecr=Button(window, padx=5,pady=5,bd=5,fg=\"black\", font=('arial', 12,'bold'), text=\"Decrypt\",bg =\"powder blue\", command=btnDecrypt).grid(row=15,column=0)\n\n#=====================Start Main Loop==============================\nroot.mainloop()","repo_name":"ezrafielding/ImageStegoCrypt","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6840,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"16621635300","text":"\"\"\"\n load_configs.py\n\"\"\"\nimport errno\nimport json\nimport os\n\n\n\ndef load_config(cache_dir, tenant_id, username, client_name):\n \"\"\" Load configurations from file\n\n Load configuration information from file, if it exists.\n These function will look for the file config.json to restore a session.\n\n PARAMETERS\n ----------\n cache_dir: string\n Path to store session configuration.\n tenant_id: string\n username: string\n client_name: string\n\n RETURNS\n -------\n current_context: dict\n Dictionary with client name as key and session context as value.\n \"\"\"\n # Configuration info will be store by default in these files.\n config_file = \"{}/config.json\".format(cache_dir)\n\n # Read in configuration from cache dir if it exist, raise an exception.\n if os.path.isfile(config_file):\n with open(config_file, \"r\") as f:\n agave_context = json.load(f)\n else:\n raise FileNotFoundError(\n errno.ENOENT, os.strerror(errno.ENOENT), config_file)\n\n # Return the current session context if no extra parameters are passed.\n if tenant_id is None or username is None or client_name is None:\n client_name = list(agave_context[\"current\"])[0]\n return client_name, agave_context[\"current\"][client_name]\n else:\n return client_name, agave_context[\"sessions\"][tenant_id][username][client_name]\n","repo_name":"tapis-project/tapispy","sub_path":"tapispy/utils/load_configs.py","file_name":"load_configs.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"18918354519","text":"import os\nimport re\nimport sys\nimport thread\n \nclass testManager(object):\n \"\"\"Deals with scanning test directories, gathering test cases, and \n collecting per-test information (opt files, etc) for use by the\n test-runner\n\n \"\"\"\n\n def __init__( self, variables, system_manager):\n\n self.system_manager = system_manager\n self.time_manager = system_manager.time_manager\n self.logging = system_manager.logging\n if variables['verbose']:\n self.logging.verbose(\"Initializing test manager...\")\n\n self.skip_keys = [ 'system_manager'\n , 'verbose'\n , 'debug'\n ]\n self.test_list = []\n self.first_test = 1\n self.total_test_count = 0\n self.executed_tests = {} # We have a hash of 'status':[test_name..]\n self.executing_tests = {}\n self.verbose = variables['verbose']\n self.debug = variables['debug']\n self.default_engine = variables['defaultengine']\n self.dotest = variables['dotest']\n if self.dotest:\n self.dotest = self.dotest.strip()\n self.skiptest = variables['skiptest']\n if self.skiptest:\n self.skiptest = self.skiptest.strip()\n self.reorder = variables['reorder']\n self.suitelist = variables['suitelist']\n self.mode = variables['mode']\n \n self.suitepaths = variables['suitepaths']\n self.testdir = variables['testdir']\n self.desired_tests = variables['test_cases']\n \n self.logging.debug_class(self)\n\n def add_test(self, new_test_case):\n \"\"\" Add a new testCase to our self.test_list \"\"\"\n\n self.test_list.append(new_test_case)\n \n def gather_tests(self):\n self.logging.info(\"Processing test suites...\")\n # BEGIN terrible hack to accomodate the fact that\n # our 'main' suite is also our testdir : /\n if self.suitelist is None and self.mode=='dtr':\n self.suitepaths = [self.testdir]\n self.suitelist = ['main']\n # END horrible hack\n for suite in self.suitelist:\n suite_path = self.find_suite_path(suite)\n if suite_path:\n self.process_suite(suite_path)\n else:\n self.logging.error(\"Could not find suite: %s in any of paths: %s\" %(suite, \", \".join(self.suitepaths)))\n self.process_gathered_tests()\n\n def process_gathered_tests(self):\n \"\"\" We do some post-gathering analysis and whatnot\n Report an error if there were desired_tests but no tests\n were found. Otherwise just report what we found\n \n \"\"\"\n\n # See if we need to reorder our test cases\n if self.reorder:\n self.sort_testcases()\n\n if self.desired_tests and not self.test_list:\n # We wanted tests, but found none\n # Probably need to make this smarter at some point\n # To maybe make sure that we found all of the desired tests...\n # However, this is a start / placeholder code\n self.logging.error(\"Unable to locate any of the desired tests: %s\" %(\" ,\".join(self.desired_tests))) \n self.total_test_count = len(self.test_list) \n self.logging.info(\"Found %d test(s) for execution\" %(self.total_test_count))\n \n self.logging.debug(\"Found tests:\")\n self.logging.debug(\"%s\" %(self.print_test_list()))\n\n def find_suite_path(self, suitename):\n \"\"\" We have a suitename, we need to locate the path to\n the juicy suitedir in one of our suitepaths.\n\n Theoretically, we could have multiple matches, but\n such things should never be allowed, so we don't\n code for it. We return the first match.\n \n testdir can either be suitepath/suitename or\n suitepath/suitename/tests. We test and return the\n existing path. Return None if no match found\n\n \"\"\"\n # BEGIN horrible hack to accomodate bad location of main suite\n if self.mode == 'dtr':\n if self.suitepaths == [self.testdir] or suitename == 'main':\n # We treat this as the 'main' suite\n return self.testdir\n # END horrible hack\n for suitepath in self.suitepaths:\n suite_path = self.system_manager.find_path([ os.path.join(suitepath,suitename,'tests'),\n os.path.join(suitepath,suitename) ], required = 0 )\n if suite_path:\n return suite_path\n return suite_path\n\n def process_suite(self,suite_dir):\n \"\"\"Process a test suite.\n This includes searching for tests in test_list and only\n working with the named tests (all tests in suite is the default)\n Further processing includes reading the disabled.def file\n to know which tests to skip, processing the suite.opt file,\n and processing the individual test cases for data relevant\n to the rest of the test-runner\n \n \"\"\"\n self.logging.verbose(\"Processing suite: %s\" %(suite))\n\n def has_tests(self):\n \"\"\"Return 1 if we have tests in our testlist, 0 otherwise\"\"\"\n \n return len(self.test_list)\n\n def get_testCase(self, requester):\n \"\"\"return a testCase \"\"\"\n if self.first_test:\n # we start our timer\n self.time_manager.start('total_time','total_time')\n self.first_test = 0\n test_case = None\n if self.has_tests():\n test_case = self.test_list.pop(0)\n self.record_test_executor(requester, test_case.fullname)\n return test_case\n\n def record_test_executor(self, requester, test_name):\n \"\"\" We record the test case and executor name as this could be useful\n We don't *know* this is needed, but we can always change this \n later\n \n \"\"\"\n\n self.executing_tests[test_name] = requester\n\n def record_test_result(self, test_case, test_status, output, exec_time):\n \"\"\" Accept the results of an executed testCase for further\n processing.\n \n \"\"\"\n if test_status not in self.executed_tests:\n self.executed_tests[test_status] = [test_case]\n else:\n self.executed_tests[test_status].append(test_case)\n # report. If the test failed, we print any additional\n # output returned by the test executor\n # We may want to report additional output at other times\n if test_status != 'pass':\n report_output = True\n else:\n report_output = False\n self.logging.test_report( test_case.fullname, test_status\n , exec_time, output, report_output)\n\n\n def print_test_list(self):\n test_names = []\n for test in self.test_list:\n test_names.append(test.fullname)\n return \"[ %s ]\" %(\", \".join(test_names))\n\n def statistical_report(self):\n \"\"\" Report out various testing statistics:\n Failed/Passed %success\n list of failed test cases\n \n \"\"\"\n # This is probably hacky, but I'll think of a better\n # location later. When we are ready to see our\n # statistical report, we know to stop the total time timer\n if not self.first_test:\n total_exec_time = self.time_manager.stop('total_time')\n self.logging.write_thick_line()\n self.logging.info(\"Test execution complete in %d seconds\" %(total_exec_time))\n self.logging.info(\"Summary report:\")\n self.report_executed_tests()\n self.report_test_statuses()\n if not self.first_test:\n self.time_manager.summary_report()\n\n def report_test_statuses(self):\n \"\"\" Method to report out various test statuses we\n care about\n\n \"\"\"\n test_statuses = [ 'fail'\n , 'timeout'\n , 'skipped'\n , 'disabled'\n ]\n for test_status in test_statuses:\n self.report_tests_by_status(test_status)\n \n def get_executed_test_count(self):\n \"\"\" Return how many tests were executed \"\"\"\n total_count = 0\n for test_list in self.executed_tests.values():\n total_count = total_count + len(test_list)\n return total_count\n\n def report_executed_tests(self):\n \"\"\" Report out tests by status \"\"\"\n total_executed_count = self.get_executed_test_count()\n if self.total_test_count:\n executed_ratio = (float(total_executed_count)/float(self.total_test_count))\n executed_percent = executed_ratio * 100\n else:\n # We prevent division by 0 if we didn't find any tests to execute\n executed_ratio = 0\n executed_percent = 0\n self.logging.info(\"Executed %s/%s test cases, %.2f percent\" %( total_executed_count\n , self.total_test_count\n , executed_percent))\n\n for test_status in self.executed_tests.keys():\n status_count = self.get_count_by_status(test_status)\n test_percent = (float(status_count)/float(total_executed_count))*100\n self.logging.info(\"STATUS: %s, %d/%d test cases, %.2f percent executed\" %( test_status.upper()\n , status_count\n , total_executed_count\n , test_percent \n ))\n\n\n def report_tests_by_status(self, status):\n matching_tests = []\n if status in self.executed_tests:\n for testcase in self.executed_tests[status]:\n matching_tests.append(testcase.fullname)\n self.logging.info(\"%s tests: %s\" %(status.upper(), \", \".join(matching_tests)))\n\n def get_count_by_status(self, test_status):\n \"\"\" Return how many tests are in a given test_status \"\"\"\n if test_status in self.executed_tests:\n return len(self.executed_tests[test_status])\n else:\n return 0\n\n def sort_testcases(self):\n \"\"\" Sort testcases to optimize test execution.\n This can be very mode-specific\n\n \"\"\"\n \n self.logging.verbose(\"Reordering testcases to optimize test execution...\")\n\n def has_failing_tests(self):\n return (self.get_count_by_status('fail') + self.get_count_by_status('timeout'))\n\n","repo_name":"facebook/mysql-5.6","sub_path":"xtrabackup/test/kewpie/lib/test_mgmt/test_management.py","file_name":"test_management.py","file_ext":"py","file_size_in_byte":10759,"program_lang":"python","lang":"en","doc_type":"code","stars":2396,"dataset":"github-code","pt":"55"} +{"seq_id":"13203739972","text":"# -*- coding: utf-8 -*-\n__author__ = 'Lilyu'\n\nimport sys\nimport os\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtWebKit import *\nimport uuid\n\n\nreload(sys)\nsys.setdefaultencoding('utf8')\n# cxfreeze D:\\Users\\Lilyu\\PycharmProjects\\untitled4\\order\\WebMain.py --target-dir E:\\order\\ --base-name=\"win32gui\"\napp, browser = None, None\n# adb shell screencap -p /sdcard/screen.png\n# adb pull /sdcard/screen.png D:/screen.png\n# adb shell input swipe 320 410 320 410 1 349\n\n\ndef show_close():\n print('close')\n\n\nclass BrowserScreen(QWebView):\n def __init__(self):\n QWebView.__init__(self)\n self.setWindowTitle(u'跳一跳')\n # self.setContextMenuPolicy(Qt.CustomContextMenu)\n self.resize(1200, 800)\n path = os.getcwd()\n self.load(QUrl.fromLocalFile(path + \"/testjs/a.html\"))\n self.show()\n\n def closeEvent(self, event):\n global IS_CONNECTION\n IS_CONNECTION = 'END'\n show_close()\n\n def show_message(self, msg):\n pass\n\n\ndef remove_all_files():\n rootdir = 'D:\\\\'\n list_dir = os.listdir(rootdir)\n for i in range(0, len(list_dir)):\n png_check = list_dir[i]\n if \"screen\" in png_check and \".png\" in png_check:\n os.remove(\"D:\\\\\" + png_check)\n\n\nclass PythonJS(QObject):\n @pyqtSignature(\"QString\", result=\"QString\")\n def find_order_c_excel(self, order):\n return order\n\n @pyqtSignature(\"\", result=\"QString\")\n def find_new_img(self):\n remove_all_files()\n os.system(\"adb shell screencap -p /sdcard/screen.png\")\n file_name = \"screen\" + str(uuid.uuid1()) + \".png\"\n ret_path = \"file:///D://\" + file_name\n os.system(\"adb pull /sdcard/screen.png D:/\" + file_name)\n print(ret_path)\n return ret_path\n\n @pyqtSignature(\"QString\", result=\"QString\")\n def op_run(self, value):\n cmd = \"adb shell input swipe 320 410 320 410 \" + str(value)\n os.system(cmd)\n return cmd\n\n\ndef my_main():\n app = QApplication(sys.argv)\n browser = BrowserScreen()\n pjs = PythonJS()\n browser.page().mainFrame().addToJavaScriptWindowObject(\"python\", pjs)\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n my_main()","repo_name":"janninaweigal/jump","sub_path":"code/WebMain.py","file_name":"WebMain.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"55"} +{"seq_id":"41267708348","text":"import time\nimport argparse\nfrom distutils.util import strtobool\nfrom typing import Any\n\nfrom Src.Apriori.main import apriori\nfrom config import (\n MIN_SUP,\n BEAT_FREQUENCY,\n FILE_PATH,\n FILE_PATH_TEST,\n FLAG_TEST,\n NO_CACHE,\n ONLY_FINAL,\n)\n\n\ndef read(flag_test) -> list[list[Any, set[int]]]:\n if flag_test:\n dat_file = open(FILE_PATH_TEST, \"r\")\n else:\n dat_file = open(FILE_PATH, \"r\")\n dat_text = dat_file.readlines()\n data_list = [set([n for n in l.split() if len(n) > 0]) for l in dat_text]\n raw_data = [[i + 1, d] for i, d in enumerate(data_list)]\n return raw_data\n\n\nif __name__ == \"__main__\":\n argument_list = argparse.ArgumentParser()\n argument_list.add_argument(\"--min_sup\", type=float, default=MIN_SUP)\n argument_list.add_argument(\n \"--beat_frequency\", type=int, default=BEAT_FREQUENCY\n )\n argument_list.add_argument(\"--flag_test\", type=str, default=FLAG_TEST)\n argument_list.add_argument(\"--no_cache\", type=str, default=NO_CACHE)\n argument_list.add_argument(\"--only_final\", type=str, default=ONLY_FINAL)\n MIN_SUP = argument_list.parse_args().min_sup\n BEAT_FREQUENCY = argument_list.parse_args().beat_frequency\n FLAG_TEST = bool(strtobool(argument_list.parse_args().flag_test))\n NO_CACHE = bool(strtobool(argument_list.parse_args().no_cache))\n ONLY_FINAL = bool(strtobool(argument_list.parse_args().only_final))\n print(\"MIN_SUP:\", MIN_SUP)\n print(\"BEAT_FREQUENCY:\", BEAT_FREQUENCY)\n print(\"FLAG_TEST:\", FLAG_TEST)\n print(\"NO_CACHE:\", NO_CACHE)\n print(\"ONLY_FINAL:\", ONLY_FINAL)\n\n raw_data = read(FLAG_TEST)\n # print(raw_data)\n start_time_global = time.time()\n apriori(raw_data, MIN_SUP, BEAT_FREQUENCY, ONLY_FINAL, NO_CACHE)\n end_time_global = time.time()\n print(\"Total time:\", end_time_global - start_time_global)\n","repo_name":"LaoshuBaby/Homework_DataMining","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"17804062303","text":"#definimos as listas\r\n\r\nvetor_x = []\r\nvetor_y = []\r\n\r\n#criamos o input para o usuário\r\n\r\nfor i in range(0,5):\r\n vetor_x.append(int(input(\"digite os valores para o vetor 1: \")))\r\n\r\nfor i in range(0,5):\r\n vetor_y.append(int(input(\"digite os valores para o vetor 2: \")))\r\n\r\n#importamos chain de intertools para fazer as listas interagirem\r\n\r\nfrom itertools import chain\r\n\r\nresultado = chain.from_iterable(zip(vetor_x, vetor_y))\r\n\r\nprint(\"União intercalada dos vetores 1 e 2:\", *resultado)\r\n","repo_name":"YhasmimTigre/Programas-Python","sub_path":"exercícios-P1/vetores-intercalados.py","file_name":"vetores-intercalados.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"30085472440","text":"# AtCoder Beginners Contest 201 D - Game in Momotetsu World\n# https://atcoder.jp/contests/abc201/tasks/abc201_d\n# tag: 二人ゲーム グリッド DP 高橋君 青木君\n\ndef main():\n H, W = map(int, input().split())\n field = [input() for _ in range(H)]\n\n # マスごとの点数を持っておく\n score = [[0] * W for _ in range(H)]\n for h in range(H):\n for w in range(W):\n score[h][w] = 1 if field[h][w] == '+' else -1\n\n # dp[h][w]: \n # 現在 (h, w) にいるとき、そこからゴールへと向かう時に\n # 互いに最善を尽くした場合の点数差分。\n # 但し (h, w) で手番のプレイヤーを基準とする。\n dpt = [[-10**10] * W for _ in range(H)]\n dpt[-1][-1] = 0\n\n # ひとつ前の DP の場所、つまり次に進む場所の点数を足すが、\n # その場所の DP の値は、手番が入れ替わって\n # 相手の点数になるので、ひくことになる。\n for h in range(H-1, -1, -1):\n for w in range(W-1, -1, -1):\n if h < H-1:\n dpt[h][w] = max(dpt[h][w], score[h+1][w] - dpt[h+1][w])\n if w < W-1:\n dpt[h][w] = max(dpt[h][w], score[h][w+1] - dpt[h][w+1])\n\n if dpt[0][0] > 0:\n print('Takahashi')\n elif dpt[0][0] == 0:\n print('Draw')\n else:\n print('Aoki')\n\nmain()","repo_name":"scrblbug/atcoder","sub_path":"python/abc201_d.py","file_name":"abc201_d.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"34943814256","text":"from rest_framework import serializers\n\nfrom api import models\n\n\nclass TimelineSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.Timeline\n fields = ('id', 'name')\n\n\nclass EventTypeSerializer(serializers.ModelSerializer):\n\n name = serializers.CharField(max_length=255, source='event_type.name')\n event_type_id = serializers.CharField(max_length=255, source='event_type.id', read_only=True)\n\n def create(self, validated_data):\n event_type = models.EventType.objects.create(name=validated_data['event_type']['name'])\n shared_event_type = models.SharedEventType.objects.create(\n event_type=event_type, timeline_id=self.context['timeline_id'], relationship=validated_data['relationship'],\n color_primary=validated_data['color_primary'], color_secondary=validated_data['color_secondary']\n )\n return shared_event_type\n\n class Meta:\n model = models.SharedEventType\n fields = ('event_type_id', 'name', 'relationship', 'color_primary', 'color_secondary')\n\n\nclass EventSerializer(serializers.ModelSerializer):\n\n def validate_type(self, value):\n \"\"\"Raise an exception if the event type given is not originally on the timeline given.\"\"\"\n if not value.sharedeventtype_set.filter(timeline_id=self.context['timeline_id'], relationship=models.RELATIONSHIP_ORIGINAL).exists():\n print(\"Invalid\")\n raise serializers.ValidationError('Invalid event type')\n return value\n\n def create(self, validated_data):\n return models.Event.objects.create(\n type=validated_data['type'], time_start=validated_data['time_start'],\n time_end=validated_data['time_end'], title=validated_data['title']\n )\n\n def update(self, instance, validated_data):\n instance.type = validated_data['type']\n instance.title = validated_data['title']\n instance.time_start = validated_data['time_start']\n instance.time_end = validated_data['time_end']\n instance.save()\n return instance\n\n class Meta:\n model = models.Event\n fields = ('id', 'type', 'title', 'time_start', 'time_end')\n","repo_name":"DHerls/timeline","sub_path":"backend/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"34166979979","text":"import pytest\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom itflex.common.tokens import encode\nfrom itflex.config import TOKEN_SECRET\nfrom itflex.testing import create_sqlite_functions\nfrom itflex_firewall.models import SQLBase\nfrom itflex_sdwan.models import SQLBase as Sdwan_SQLBase\n\nfrom .deps import get_scopes\n\nDB_URL = \"sqlite:///:memory:\"\n\n\n@pytest.fixture\ndef scopes():\n scopes = []\n\n for scope in get_scopes():\n scopes.append({\"name\": scope, \"read\": True, \"write\": True})\n\n return scopes\n\n\n@pytest.fixture\ndef superuser_token():\n payload = {\n \"sub\": 0,\n \"sub_type\": \"user\",\n \"type\": \"access\",\n \"superuser\": True,\n \"scopes\": [],\n }\n token_bytes = encode(payload, TOKEN_SECRET, 3000)\n return token_bytes.decode()\n\n\n@pytest.fixture\ndef user_token(scopes):\n payload = {\n \"sub\": 1,\n \"sub_type\": \"user\",\n \"type\": \"access\",\n \"superuser\": False,\n \"scopes\": scopes,\n }\n token_bytes = encode(payload, TOKEN_SECRET, 3000)\n return token_bytes.decode()\n\n\n@pytest.fixture\ndef ssl_token():\n payload = {\n \"sub\": 0,\n \"sub_type\": \"itflex\",\n \"type\": \"access\",\n \"fullname\": \"User Test\",\n \"username\": \"user01\",\n \"email\": \"user01@email.com\",\n \"superuser\": True,\n \"scopes\": [],\n }\n token_bytes = encode(payload, TOKEN_SECRET, 3000)\n return token_bytes.decode()\n\n\n@pytest.fixture\ndef db_engine():\n engine = create_engine(DB_URL)\n conn = engine.raw_connection()\n create_sqlite_functions(conn)\n engine.execute(\"pragma foreign_keys=on\")\n yield engine\n engine.dispose()\n\n\n@pytest.fixture\ndef db_sessionmaker(db_engine):\n return sessionmaker(bind=db_engine)\n\n\n@pytest.fixture(autouse=True)\ndef create_db(db_engine):\n SQLBase.metadata.create_all(db_engine)\n Sdwan_SQLBase.metadata.create_all(db_engine)\n\n","repo_name":"joelffg/itflex__desafio_backend","sub_path":"backend/itflex_service/contest.py","file_name":"contest.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"71017469612","text":"# -*- coding:utf-8 -*-\nimport os\nimport random\nimport urllib\n\nimport requests\nfrom PIL import Image, ImageEnhance\nfrom io import BytesIO\n\nfrom rk import RClient\n\n\ndef get_phantomjs():\n return '/Users/debrahe/Desktop/phantomjs-2.1.1-macosx/bin/phantomjs'\n\n\ndef get_img(left, right, up, down):\n left = int(left)\n right = int(right)\n up = int(up)\n down = int(down)\n im = Image.open('code.jpg')\n im = im.crop((left, up, right, down))\n im = im.convert('L')\n sharpness = ImageEnhance.Contrast(im)\n sharper_im = sharpness.enhance(2.0)\n sharper_im.save('code.jpg')\n with open('code.jpg', 'rb') as f:\n res = f.read()\n return res\n\n\ndef get_code():\n captchaId = ''.join(random.sample('0123456789abcdef0123456789abcdef', 32))\n rc = RClient('XXX', 'XXX', 'XXX', 'XXX')\n code = ''\n while code == '':\n try:\n img_url = 'http://zhixing.court.gov.cn/search/captcha.do?captchaId={}&random=0.4750974032186893'.format(captchaId)\n urllib.urlretrieve(img_url, 'code.jpg')\n with open('code.jpg', 'rb') as f:\n res = f.read()\n os.remove('code.jpg')\n code = rc.rk_create(res, 2040)['Result']\n except:\n pass\n return captchaId, code\n\n\ndef get_code_shixin():\n captchaId = ''.join(random.sample('0123456789abcdef0123456789abcdef', 32))\n rc = RClient('XXX', 'XXX', 'XXX', 'XXX')\n code = ''\n while code == '':\n try:\n img_url = 'http://shixin.court.gov.cn/captchaNew.do?captchaId={}&random=0.23790190675874312'.format(captchaId)\n response = requests.get(img_url)\n image = Image.open(BytesIO(response.content))\n try:\n r, g, b, a = image.split()\n except:\n r, g, b = image.split()\n im = Image.merge(\"RGB\", (r, g, b))\n im.save('code2.jpg')\n with open('code2.jpg', 'rb') as f:\n res = f.read()\n os.remove('code2.jpg')\n code = rc.rk_create(res, 2040)['Result']\n except:\n pass\n return captchaId, code\n","repo_name":"DebraHe/scrapy_projects","sub_path":"can_rk/tool/tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"28407052321","text":"import numpy as np\nimport cv2\nfrom PIL import Image\nfrom argparse import ArgumentParser\nimport os.path\nfrom scipy.ndimage import gaussian_filter\n\n''' Input: img of square dimensions.\n Output: Blurred image for use as a distance field \n Obstacles should be BLACK, background is WHITE '''\ndef create_distance_field(img):\n if (img.shape[0]!=1000 or img.shape[1]!=1000):\n print(\"Resizing to 1000 x 1000\")\n img = cv2.resize(img, (1000, 1000))\n\n # Convolve with a Gaussian to effect a blur.\n blur = gaussian_filter(img, sigma=5)\n blur = cv2.normalize(blur, None, 0, 1.0, cv2.NORM_MINMAX, dtype=cv2.CV_32F)\n \n distance_field = blur\n return distance_field\n\ndef is_valid_file(parser, arg):\n if not os.path.exists(arg):\n parser.error(\"The file %s does not exist!\" % arg)\n else:\n return open(arg, 'r') # return an open file handle\n\n\n\nif __name__==\"__main__\":\n parser = ArgumentParser(description=\"Input and output files for createing distance field\")\n parser.add_argument(\"-i\", \"--input\", help=\"Input obstacle file to convert to distance field. Obstacles must be BLACK on WHITE background\", default=None)\n parser.add_argument(\"-o\", \"--output\", help=\"Output file name for distance field. Default = replaces input\", default=None)\n args = parser.parse_args()\n input_file = args.input\n if ((input_file is None) or (not os.path.isfile(input_file))):\n print(\"Invalid file path given as input\")\n exit()\n output_file = args.output\n if args.output is None:\n output_file = input_file\n\n\n # Load in input obstacle file \n image = np.asarray(Image.open(input_file).convert('L'))\n \n # Create distance field with a blur\n blurred = create_distance_field(image)\n\n # Write to output\n cv2.imwrite(output_file, 255*blurred)","repo_name":"aalpatya/gbpplanner","sub_path":"assets/scripts/create_distance_field.py","file_name":"create_distance_field.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"55"} +{"seq_id":"1778271697","text":"import sys\nimport heapq\nsys.stdin = open('input1.txt')\n\ndef dijkstra(start, end):\n visited = [0] * (N + 1)\n distance = [INF] * (N + 1)\n Q = [(0, start)]\n while Q:\n time, node = heapq.heappop(Q)\n if visited[node] == 0:\n distance[node] = time\n visited[node] = 1\n for v, w in graph[node]:\n temp = time + w\n heapq.heappush(Q, (temp, v))\n return distance[end]\n\ninput = sys.stdin.readline\nN, E = map(int, input().split()) # 정점의 개수, 간선의 개수\nINF = float(\"inf\")\ngraph = [[] for _ in range(N + 1)]\n\n\n# draw graph\nfor _ in range(E):\n a, b, c = map(int, input().split()) # 양방향 길과 거리\n graph[a].append((b, c))\n graph[b].append((a, c))\n\nv1, v2 = map(int, input().split()) # 반드시 지나야하는 정점\n\n# 경로 ver1) 1 -> v1 -> v2 -> N\n_1 = dijkstra(1, v1) + dijkstra(v1, v2) + dijkstra(v2, N)\n# 경로 ver2) 1 -> v2 -> v1 -> N\n_2 = dijkstra(1, v2) + dijkstra(v2, v1) + dijkstra(v1, N)\n\nif min(_1, _2) != INF:\n print(min(_1, _2))\nelse:\n print(-1)\n\n","repo_name":"yongjunism/CSKY-Algorithm-Study","sub_path":"BOJ 최단경로(0707)/BOJ 1504 - 특정한 최단 경로/염수홍.py","file_name":"염수홍.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"72649037932","text":"import os\nimport ctypes\nimport sys\nimport json\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom multiprocessing import Process, freeze_support\n\ndef access_spreadsheet():\n print('child')\n \n if len(sys.argv) > 1:\n if len(sys.argv) == 7:\n fn = 'manualreport'\n else:\n fn = sys.argv[1]\n else:\n fn = 'noarg'\n print(fn)\n status = open('timerstatus.txt','w')\n status.write('authorizing')\n status.close()\n scope = ['https://spreadsheets.google.com/feeds']\n credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)\n\n gc = gspread.authorize(credentials)\n print('authorized')\n wks = gc.open(\"Yggdrasil Boss Timers\").sheet1\n print('open sheet')\n bossnames = wks.col_values(1)\n mapnames = wks.col_values(3)\n channels = wks.col_values(4)\n print('bossnames')\n if fn == 'report' or fn == 'manualreport':\n print('go')\n bossname = sys.argv[2]\n if fn == 'report':\n print('report')\n wks.update_acell('F1','=NOW()')\n time = wks.acell('F1').value\n else:\n print('set time')\n time = sys.argv[6]\n mapname = sys.argv[3]\n user = sys.argv[4]\n channel = sys.argv[5]\n bossFound = 0\n status = open('timerstatus.txt','w')\n status.write('sending')\n status.close()\n\n for i in range(len(bossnames)):\n if bossname == bossnames[i]:\n print(channel)\n print(channels[i])\n if channel != channels[i] or mapname != mapnames[i]:\n pass\n else:\n wks.update_cell(i+1,2,time)\n wks.update_cell(i+1,3,mapname)\n wks.update_cell(i+1,4,channel)\n wks.update_cell(i+1,5,user)\n bossFound = 1\n print('update')\n break\n\n if bossFound == 0:\n for i in range(len(bossnames)):\n if len(bossnames[i]) < 1:\n cell_row = i+1\n break\n bossnames[cell_row-1] = bossname\n print(bossnames[cell_row-1])\n wks.update_cell(cell_row,1,bossname)\n wks.update_cell(cell_row,2,time)\n wks.update_cell(cell_row,3,mapname)\n wks.update_cell(cell_row,4,channel)\n wks.update_cell(cell_row,5,user)\n print('create')\n status = open('timerstatus.txt','w')\n status.write('refreshing')\n status.close()\n times = wks.col_values(2)\n users = wks.col_values(5)\n bossData = []\n\n for i in range(len(bossnames)):\n if len(bossnames[i]) < 1:\n break\n bossData.append({\n 'bossname':bossnames[i],\n 'time':times[i],\n 'mapname':mapnames[i],\n 'channel':channels[i],\n 'user':users[i]\n })\n f = open('bossdata.json','w')\n f.write(json.dumps(bossData, sort_keys=True, indent=4, separators=(',', ': ')))\n f.close()\n status = open('timerstatus.txt','w')\n status.write('saving')\n status.close()\n print('save json')\n if fn == 'noarg':\n ctypes.windll.user32.MessageBoxA(0, \"Boss data has been saved to bossdata.json\", \"Boss Timer\", 1)\n print('exit')\n status = open('timerstatus.txt','w')\n status.write('complete')\n status.close()\n sys.exit()\n\n\nif __name__ == '__main__':\n freeze_support()\n print('parent')\n p = Process(target=access_spreadsheet)\n p.start()\n print('exit')\n os._exit(0)\n\n","repo_name":"axjv/Input-Switcher","sub_path":"bt/python/test.pyw","file_name":"test.pyw","file_ext":"pyw","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"55"} +{"seq_id":"41790542073","text":"\"\"\"File to calculate integrated heating\"\"\"\n\nimport copy as cp\nimport numpy as np\nimport scipy.integrate as spi\nimport astropy.units as u\n\nfrom .SimulationRunner.SimulationRunner import gen_UVB as uvb\n#import SimulationRunner.gen_UVB as uvb\n\ndef get_integrated_heating(z_min, z_max, TREECOOL, number_to_mass_density_ratios, hubble, omega_m):\n \"\"\"Calculate the integrated heating [eV] per unit [proton] mass. Number to mass density ratio in [1 / m_p]\"\"\"\n z = (10 ** TREECOOL[:, 0]) - 1.\n slice_array = (z >= z_min) * (z <= z_max)\n\n species_integrand = TREECOOL[:, 4:] * number_to_mass_density_ratios[:, 1:] / hubble_factor(\n z, hubble, omega_m)[:, np.newaxis].to(1. / u.s).value / (1. + z[:, np.newaxis])\n integrated_heating_per_species = (spi.trapz(species_integrand[slice_array], z[slice_array], axis=0) * u.erg).to(u.eV)\n print('Integrated heating [eV] per proton mass [HI, HeI, HeII] =', integrated_heating_per_species)\n\n return np.sum(integrated_heating_per_species)\n\ndef species_fraction_to_density_ratio(species_fractions, helium_mass_fraction):\n \"\"\"Convert species [HI, HeI, HeII] fractions to number to mass density ratios in [1 / m_p]\"\"\"\n density_ratio = cp.deepcopy(species_fractions)\n density_ratio[:, 1] *= 1. - helium_mass_fraction\n density_ratio[:, 2:] *= helium_mass_fraction / 2.\n return density_ratio\n\ndef get_species_fraction_simple_model(z, z_rei, delta_z_rei=0.5):\n \"\"\"Simple model (Planck \"tanh\" model) for species [HI, HeI, HeII] fractions\"\"\"\n y = lambda a: (1. + a) ** 1.5\n delta_y = 1.5 * ((1. + z_rei) ** 0.5) * delta_z_rei\n\n species_fractions = 1. - (0.5 * (1. + np.tanh((y(z_rei)[np.newaxis, :] - y(z)[:, np.newaxis]) / delta_y[np.newaxis, :])))\n species_fractions[:, 2] -= species_fractions[:, 1] #Correct HeII fraction\n return np.hstack((z.reshape(-1, 1), species_fractions))\n\ndef get_species_fraction_gen_UVB(z, z_rei):\n \"\"\"Simple model (as used in the gen_UVB module) for species [HI, HeI, HeII] fractions\"\"\"\n species_fractions = np.zeros((z.size, 3))\n for i in range(2):\n species_fractions[:, i] = 1. - uvb.myfQHII_2(z, z_rei[i])\n species_fractions[:, 2] = 1. - uvb.volume_filling_factor_HeIII(z, z_rei[2]) - species_fractions[:, 1]\n return np.hstack((z.reshape(-1, 1), species_fractions))\n\ndef _get_single_species_fraction_Onorbe_analytical(z, TREECOOL, recombination_rate, C_ionised_species, hubble, omega_b,\n helium_mass_fraction):\n \"\"\"Get one of the species [HI, HeI, HeII] fractions as predicted analytically (HI; HeI: eq. A15 in 1607.04218)\"\"\"\n number_density_H_physical = uvb.calc_nH(cosmo=[hubble, omega_b, None, None, 1. - helium_mass_fraction]) * ((1. + z) ** 3)\n chi = helium_mass_fraction / 4. / (1. - helium_mass_fraction)\n A = C_ionised_species * number_density_H_physical * recombination_rate * (1. + chi)\n return ((2. * A) + TREECOOL[:, 1] - np.sqrt((TREECOOL[:, 1] ** 2) + (4. * A * TREECOOL[:, 1]))) / 2. / A\n\ndef get_species_fraction_Onorbe_analytical(z, TREECOOL, hubble, omega_b, helium_mass_fraction, T0=2.e+4*u.K, z_rei_HeII=3.):\n \"\"\"Species [HI, HeI, HeII] fractions as predicted analytically (HI: eq. A15 in 1607.04218)\"\"\"\n species_fractions = np.zeros((z.size, 3))\n\n C_H_II = np.ones_like(z) * 1.5\n #C_H_II[z < 10.] = 2.\n species_fractions[:, 0] = _get_single_species_fraction_Onorbe_analytical(z, TREECOOL,\n uvb.calc_alphaB(T0=(T0.to(u.K)).value), C_H_II, hubble, omega_b, helium_mass_fraction)\n\n #species_fractions[:, 1] = cp.deepcopy(species_fractions[:, 0])\n C_He_II = cp.deepcopy(C_H_II)\n species_fractions[:, 1] = _get_single_species_fraction_Onorbe_analytical(z, TREECOOL,\n uvb.calc_alphaBHeII(T0=(T0.to(u.K)).value), C_He_II, hubble, omega_b, helium_mass_fraction)\n\n #species_fractions[:, 2] = get_species_fraction_gen_UVB(z, np.array([15., 15., z_rei_HeII]))[:, 3]\n species_fractions[:, 2] = 1. - species_fractions[:, 1] - uvb.volume_filling_factor_HeIII(z, z_rei_HeII)\n\n return np.hstack((z.reshape(-1, 1), species_fractions))\n\ndef hubble_factor(z, hubble, omega_m):\n \"\"\"Get the Hubble factor\"\"\"\n return hubble * np.sqrt((omega_m * ((1. + z) ** 3)) + (1. - omega_m)) * 100. * u.km / u.s / u.Mpc\n\ndef simulation_parameters_to_integrated_heating(z_range, TREECOOL, heat_amp, hubble, omega_m, omega_b,\n helium_mass_fraction, T0, z_rei_HeII=3.):\n \"\"\"Calculate the integrated heating [eV] per unit [proton] mass, given some simulation parameters\"\"\"\n print(z_range, heat_amp, hubble, omega_m, omega_b, helium_mass_fraction, T0, z_rei_HeII)\n TREECOOL[:, 4:] *= heat_amp\n z = (10 ** TREECOOL[:, 0]) - 1.\n\n species_fractions = get_species_fraction_Onorbe_analytical(z, TREECOOL, hubble, omega_b, helium_mass_fraction,\n T0=T0.to(u.K), z_rei_HeII=z_rei_HeII)\n number_to_mass_density_ratios = species_fraction_to_density_ratio(species_fractions, helium_mass_fraction)\n return get_integrated_heating(np.min(z_range), np.max(z_range), TREECOOL, number_to_mass_density_ratios, hubble, omega_m)\n\nif __name__ == \"__main__\":\n #TREECOOL = np.loadtxt('/Users/kwame/Software/SimulationRunner/SimulationRunner/TREECOOL_hm_2012')\n TREECOOL = np.loadtxt('/Users/kwame/Simulations/nCDM/nCDM_test_512/TREECOOL_Trei4e+04_HM12')\n heat_amp_factor = 1.\n omega_m = 0.3209 #0.308\n\n hubble = np.sqrt(0.14345 / omega_m) #0.678\n z_rei = np.array([15., 15., 3.]) #8., 8., 3.]) # HI, HeI, HeII\n z_min, z_max = (6., 13.)\n #z_min, z_max = (4.6, 13.)\n #z_min, z_max = (4.2, 12.)\n\n omega_b = 0.04950 #0.0482\n helium_mass_fraction = 0.241 #0.24\n\n TREECOOL[:, 4:] *= heat_amp_factor\n z = (10 ** TREECOOL[:, 0]) - 1.\n #species_fractions = get_species_fraction_Onorbe_analytical(z, TREECOOL, hubble, omega_b, helium_mass_fraction, T0=8070.*u.K)\n #get_species_fraction_gen_UVB(z, z_rei)\n #get_species_fraction_simple_model(z, z_rei, delta_z_rei=1.5)\n\n #number_to_mass_density_ratios = species_fraction_to_density_ratio(species_fractions, helium_mass_fraction)\n #integrated_heating = get_integrated_heating(z_min, z_max, TREECOOL, number_to_mass_density_ratios, hubble, omega_m)\n #print('Total integrated heating [eV] per proton mass =', integrated_heating)\n","repo_name":"keirkwame/lya_emulator","sub_path":"lyaemu/integrated_heating.py","file_name":"integrated_heating.py","file_ext":"py","file_size_in_byte":6415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"5902030873","text":"import random\nimport knowledge_base\nimport algorithms\nimport math\n\nimport logging\nfrom logging import debug, info, warning, error, exception, critical\n\nclass Agent(object):\n\n def __init__(self, knowledgeBase):\n self.knowledge = knowledgeBase\n\n def should_draw(self):\n ## get the top of the discard pile\n topCard = -1\n if(len(self.knowledge.discard_pile) > 0):\n topCard = self.knowledge.peek_discard()\n if(topCard >= 0):\n ## primary check if it is directly adjacent\n if(topCard in self.knowledge.getNumsAdjacentToRuns()):\n return True\n ## greedily find ordered index (least)\n orderedIndex = algorithms.closestValidFit(topCard, self.knowledge.rack)\n utility = -1\n if(algorithms.normal_or_relative(self.knowledge.rack) == 0):\n ## check happiness at that index\n utility = algorithms.getHappiness(topCard, orderedIndex)\n ## check if happy is greater than threshhold\n if(utility > knowledge_base.kHappy and utility > self.knowledge.happiness[orderedIndex]):\n return False\n else:\n return True\n else:\n utility = algorithms.getScore(self.knowledge.rack) - algorithms.getOrderedScore(self.knowledge.rack, topCard)\n if(utility > 0):\n return False\n else:\n return True\n else:\n return True\n\n def place_card(self, card):\n if(card in self.knowledge.getNumsAdjacentToRuns()):\n for i in range(0, len(self.knowledge.rack)-1):\n if(self.knowledge.rack[i] - card == 1):\n return i - 1\n elif(card - self.knowledge.rack[i] == 1):\n return i + 1\n return algorithms.closestValidFit(card, self.knowledge.rack)\n\nclass orderingAgent(Agent):\n def shouldDraw(self):\n #if(algorithms.adjacent_inversions(rack) == 0):\n #group cards.\n good_cards = self.knowledge.getNumsAdjacentToRuns()\n top_card = self.knowledge.peek_discard()\n if top_card in good_cards:\n return False\n elif(self.knowledge.happiness[self.knowledge.getIdealSlot(top_card)] <\n algorithms.getHappiness(top_card, self.knowledge.getIdealSlot(top_card)) or\n self.knowledge.impossibilities[self.knowledge.getIdealSlot(top_card)]):\n return False\n else:\n return True\n #else:\n # return False\n\n def place_card(self, card):\n #info(card/80.0, int(card/80.0 * 20))\n rack = self.knowledge.rack\n\n # Finish a run. The runs are sorted in order from \"best\" to \"worst\", so complete the first one.\n for run in self.knowledge.runs:\n if card == run[0]-1 and run[2] != 0:\n # We can insert this card at the beginning of the run\n return run[2]-1\n if card == run[1]+1 and run[3] != len(self.knowledge.rack):\n # We can insert this card at the end of the run\n return run[3]+1\n\n if(algorithms.adjacent_inversions(rack) == 0):\n # We're already in sorted order, so keep it that way.\n for loc in xrange(len(rack)):\n if rack[loc] > card:\n break\n # We can replace either loc or loc-1, except\n if loc == 0:\n return loc\n for run in self.knowledge.runs:\n if run[2] <= loc < run[3]:\n # loc conflicts with this run, so use loc-1\n return loc-1\n if run[2] <= loc-1 < run[3]:\n # loc-1 conflicts with this run, so use loc\n return loc\n else:\n # Not yet sorted\n currentSpot = self.knowledge.getIdealSlot(card)\n\n for k, r in enumerate(self.knowledge.runs):\n if r[2] <= currentSpot < r[3]:\n # This card collides with a run in the Ideal slot\n if card < r[0]:\n if r[2] != 0:\n newSpot = r[2] - 1\n delta = +1\n break\n else:\n return 0\n if card > r[3]:\n if r[3] != len(rack):\n newSpot = r[3]\n delta = -1\n break\n else:\n return r[3] - 1\n else:\n prev = -1\n while(0 <= currentSpot < 20 and self.knowledge.happiness[currentSpot] > (algorithms.getHappiness(card, currentSpot))):\n if(currentSpot == prev):\n break\n\n prev = currentSpot\n if (card > rack[currentSpot]):\n currentSpot += 1\n else:\n currentSpot -= 1\n\n if currentSpot == -1:\n currentSpot = 0\n if currentSpot == 20:\n currentSpot = 19\n\n return currentSpot\n\n if newSpot == currentSpot:\n return currentSpot\n\n for n, r in enumerate(self.knowledge.runs):\n if r[2] <= newSpot < r[3]:\n if k < n:\n return newSpot\n elif n < k:\n return newSpot + delta\n return newSpot\n\n\n #highest_wgo = 0\n #highest_idx = 0\n #for i in range(0, len(rack)):\n # if rack[i] > highest_wgo and rack[i] < card and self.knowledge.happiness[i] > .8:\n # highest_wgo = rack[i]\n # highest_idx = i\n #if (i is 0 and card > 15):\n #return i + 1\n","repo_name":"BryanAke/DeepBlue_CudaContest","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":5952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"32874598936","text":"# Embedded file name: scripts/client/gui/Scaleform/daapi/view/lobby/trainings/TrainingSettingsWindow.py\nimport ArenaType\nfrom account_helpers import gameplay_ctx\nfrom gui.Scaleform.daapi.view.lobby.trainings import formatters\nfrom gui.prb_control.context.prb_ctx import TrainingSettingsCtx\nfrom debug_utils import LOG_ERROR, LOG_CURRENT_EXCEPTION\nfrom gui.Scaleform.daapi.view.meta.TrainingWindowMeta import TrainingWindowMeta\nfrom gui.prb_control.prb_helpers import prbFunctionalProperty\nfrom gui.prb_control.prb_getters import getTrainingBattleRoundLimits\nfrom helpers import i18n\nfrom gui.shared import g_itemsCache\nfrom gui.shared import events, EVENT_BUS_SCOPE\n\nclass ArenasCache(object):\n\n def __init__(self):\n self.__cache = []\n for arenaTypeID, arenaType in ArenaType.g_cache.iteritems():\n if arenaType.explicitRequestOnly or not gameplay_ctx.isCreationEnabled(arenaType.gameplayName):\n continue\n try:\n nameSuffix = '' if arenaType.gameplayName == 'ctf' else i18n.makeString('#arenas:type/%s/name' % arenaType.gameplayName)\n self.__cache.append({'label': '%s - %s' % (arenaType.name, nameSuffix) if len(nameSuffix) else arenaType.name,\n 'name': arenaType.name,\n 'arenaType': nameSuffix,\n 'key': arenaTypeID,\n 'size': arenaType.maxPlayersInTeam,\n 'time': arenaType.roundLength / 60,\n 'description': '',\n 'icon': formatters.getMapIconPath(arenaType)})\n except Exception:\n LOG_ERROR('There is error while reading arenas cache', arenaTypeID, arenaType)\n LOG_CURRENT_EXCEPTION()\n continue\n\n self.__cache = sorted(self.__cache, key=lambda x: (x['label'].lower(), x['name'].lower()))\n\n @property\n def cache(self):\n return self.__cache\n\n\nclass TrainingSettingsWindow(TrainingWindowMeta):\n\n def __init__(self, ctx = None):\n super(TrainingSettingsWindow, self).__init__()\n self.__isCreateRequest = ctx.get('isCreateRequest', False)\n self.__arenasCache = ArenasCache()\n\n @prbFunctionalProperty\n def prbFunctional(self):\n return None\n\n def onWindowClose(self):\n self.destroy()\n\n def _populate(self):\n super(TrainingSettingsWindow, self)._populate()\n self.as_setDataS(self.getInfo(), self.getMapsData())\n\n def getMapsData(self):\n return self.__arenasCache.cache\n\n def getInfo(self):\n settings = TrainingSettingsCtx()\n if not self.__isCreateRequest:\n settings = settings.fetch(self.prbFunctional.getSettings())\n if g_itemsCache.isSynced():\n accountAttrs = g_itemsCache.items.stats.attributes\n else:\n accountAttrs = 0\n _, maxBound = getTrainingBattleRoundLimits(accountAttrs)\n info = {'description': settings.getComment(),\n 'timeout': settings.getRoundLen() / 60,\n 'arena': settings.getArenaTypeID(),\n 'privacy': not settings.isOpened(),\n 'create': self.__isCreateRequest,\n 'canMakeOpenedClosed': True,\n 'canChangeComment': True,\n 'canChangeArena': True,\n 'maxBattleTime': maxBound / 60}\n if not self.__isCreateRequest:\n permissions = self.prbFunctional.getPermissions()\n info['canMakeOpenedClosed'] = permissions.canMakeOpenedClosed()\n info['canChangeComment'] = permissions.canChangeComment()\n info['canChangeArena'] = permissions.canChangeArena()\n return info\n\n def updateTrainingRoom(self, arena, roundLength, isPrivate, comment):\n if self.__isCreateRequest:\n settings = TrainingSettingsCtx(isRequestToCreate=True)\n else:\n settings = TrainingSettingsCtx(isRequestToCreate=False)\n settings.setArenaTypeID(arena)\n settings.setRoundLen(roundLength * 60)\n settings.setOpened(not isPrivate)\n settings.setComment(comment)\n self.fireEvent(events.TrainingSettingsEvent(events.TrainingSettingsEvent.UPDATE_TRAINING_SETTINGS, ctx={'settings': settings}), scope=EVENT_BUS_SCOPE.LOBBY)","repo_name":"aevitas/wotsdk","sub_path":"res/scripts/client/gui/scaleform/daapi/view/lobby/trainingstrainingsettingswindow.py","file_name":"trainingstrainingsettingswindow.py","file_ext":"py","file_size_in_byte":4190,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"55"} +{"seq_id":"23290766533","text":"import numpy as np\nimport asciitable\nimport glob\nimport h5py\n\ngrid_corpus = 'G:/himanshu/grid_corpus/'\nalign_list = []\n\nalign_list = np.sort(glob.glob(grid_corpus + 's1' + '/align/*.align'))\ndata_label = set()\n\nfor j in range(0, len(align_list)):\n align = asciitable.read(align_list[j])\n\n for k in range(0, len(align)):\n if align[k][2] == 'sil':\n continue\n data_label.add(align[k][2])\n\nvocabulary = list(data_label)\n\n \n","repo_name":"Himanshu-1994/AVSR","sub_path":"src/distinct_words.py","file_name":"distinct_words.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"42320698028","text":"from .models import Boardlist,Board,User, BoardMember\nfrom django.http import Http404\n\n\nclass BoardPermissionMixin:\n\n def dispatch(self, *args, **kwargs):\n board_id = kwargs.get('id')\n board = Board.objects.get(id=board_id)\n members = BoardMember.objects.filter(board=board, member=self.request.user)\n\n if members.exists():\n return super().dispatch(self.request, *args, **kwargs)\n raise Http404","repo_name":"kreechan123/trello","sub_path":"list/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"21189505250","text":"import random\nimport requests\n\n\n# функция отвечает за получение координат определенного города\ndef get_spn(json_response):\n try:\n crds = \\\n json_response['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']\n lc = crds['boundedBy']['Envelope']['lowerCorner'].split()\n uc = crds['boundedBy']['Envelope']['upperCorner'].split()\n x = str(abs(float(uc[0]) - float(lc[0])) / 30)\n y = str(abs(float(uc[1]) - float(lc[1])) / 30)\n return [x, y]\n except Exception:\n return ['1', '1']\n\n\n# функция отвечает за создание request города\ndef get_response(town):\n try:\n toponym_to_find = town\n geocoder_api_server = \"http://geocode-maps.yandex.ru/1.x/\"\n geocoder_params = {\n \"apikey\": \"40d1649f-0493-4b70-98ba-98533de7710b\",\n \"geocode\": toponym_to_find,\n \"format\": \"json\"}\n response = requests.get(geocoder_api_server, params=geocoder_params)\n\n if not response:\n return None\n json_response = response.json()\n toponym = json_response[\"response\"][\"GeoObjectCollection\"][\"featureMember\"][0][\"GeoObject\"]\n toponym_coodrinates = toponym[\"Point\"][\"pos\"]\n toponym_longitude, toponym_lattitude = toponym_coodrinates.split(\" \")\n spn = get_spn(json_response)\n map_params = {\n \"ll\": \",\".join([toponym_longitude, toponym_lattitude]),\n \"spn\": \",\".join(spn),\n \"l\": \"map\"\n }\n map_api_server = \"http://static-maps.yandex.ru/1.x/\"\n return requests.get(map_api_server, params=map_params)\n except Exception:\n return None\n\n\n# функция отвечает за создание png файла определенного города\ndef do_map_file(town):\n response = get_response(town)\n map_file = \"static/img/map.png\"\n if response is not None:\n with open(map_file, \"wb\") as file:\n file.write(response.content)\n return map_file\n\n\n# функция отвечает за получение случайного города из списка\ndef get_random_town(last_town):\n with open('Town.txt', 'r', encoding='utf-8') as f:\n lst_towns = [town.strip() for town in f.readlines()]\n town = random.choice(lst_towns)\n while True:\n if last_town != town:\n break\n town = random.choice(lst_towns)\n return town\n\n\n# функция отвечает за получение города, подходящего под условие\ndef get_town_usl_word(a):\n f = open(\"Town.txt\", encoding='utf-8')\n s = [x.strip() for x in f.readlines()]\n d = []\n for i in s:\n if i.lower()[0] == a:\n d.append(i)\n return random.choice(d)\n\n\n# функция проверяет наличие определенного города в списке\ndef check_town_in_list(town):\n f1 = open(\"Town.txt\", encoding='utf-8')\n s1 = [x.strip() for x in f1.readlines()]\n if town.strip().capitalize() in s1:\n return True\n return False\n\n\n# функция проверяет наличие определенного города в списке\ndef check_town_in_selected_list(town):\n f1 = open(\"selected_towns.txt\", encoding='utf-8')\n s1 = [x.strip() for x in f1.readlines()]\n if town.strip().capitalize() not in s1:\n return True\n return False\n\n\n# функция убирает все выбранные города в списке\ndef clear_selected_towns():\n with open('selected_towns.txt', 'w') as f:\n pass\n\n\n# функция кладет выбранные города в список\ndef put_in_file_town(town):\n f1 = open(\"selected_towns.txt\", encoding='utf-8')\n s1 = [x.strip() for x in f1.readlines()]\n with open('selected_towns.txt', 'w') as f:\n for i in s1:\n f.write(f'{i}\\n')\n f.write(f'{town}\\n')\n\n\n# функция возвращает последнюю букву города\ndef get_last_letter(town):\n if town[-1] in 'ьйъы' and town[-2] in 'ьйъы':\n return town[-3]\n elif town[-1] in 'ьйъы':\n return town[-2]\n return town[-1]\n","repo_name":"Arslan123-Pp/web_project","sub_path":"town.py","file_name":"town.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"73289771692","text":"import jsonfield\nfrom batch_select.models import BatchManager\nfrom django.db import models\n\n\nclass Tag(models.Model):\n \"\"\"\n The model representing a tag on Tumblr\n \"\"\"\n objects = BatchManager()\n name = models.CharField(max_length=100, unique=True)\n\n\nclass Photo(models.Model):\n \"\"\"\n The model for a Tumblr Photo post containing one image\n \"\"\"\n objects = BatchManager()\n post_url = models.URLField(\n verify_exists=False,\n max_length=255,\n unique=True,\n help_text='The full, canonical, non-shortened URL for the image.'\n )\n note_count = models.IntegerField(blank=True, null=True)\n url = models.URLField(verify_exists=False, max_length=255)\n height = models.IntegerField(blank=True, null=True)\n width = models.IntegerField(blank=True, null=True)\n tags_json = jsonfield.JSONField(blank=True, null=True)\n tags = models.ManyToManyField(Tag, related_name='photos')\n date_posted = models.DateTimeField(blank=True, null=True)\n timestamp = models.IntegerField(blank=True, null=True)\n date_downloaded = models.DateTimeField(auto_now_add=True)\n","repo_name":"jjmalina/tumblrgifsfeed","sub_path":"app/gifs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"3842174075","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 28 10:20:48 2020\n\n@author: innse\n\"\"\"\n\nimport pandas as pd\nimport spacy\nfrom spacy import displacy\n\nimport nlplot\nimport plotly\nfrom plotly.subplots import make_subplots\n\nnlp = spacy.load('ja_ginza')\ndf_yuming = pd.read_pickle('../../data/lyrics/m.matsutouya/lyrics.pkl')\ndf_miyuki = pd.read_pickle('../../data/lyrics/m.nakajima/lyrics.pkl')\n\ndef make_words_list(text: str) -> list:\n rs = []\n doc = nlp(text)\n for sent in doc.sents:\n for token in sent:\n tag = token.tag_.split('-')[0]\n if tag in ['名詞','形容詞','動詞']:\n# if tag in ['名詞']:\n rs.append(token.lemma_)\n return rs\n\n\ndef show_displacy(text):\n doc = nlp(text)\n displacy.serve(doc, style='dep')\n\n \ndef make_n_gram_fig(npt_artist,ngram,title):\n return npt_artist.bar_ngram(\n title=title,\n xaxis_label='word_count',\n yaxis_label='word',\n ngram=ngram,\n top_n=50)\n\ndef make_n_gram_tree_map_fig(npt_artist,ngram,title):\n return npt_artist.treemap(\n title=title,\n ngram=ngram,\n top_n=50)\n\ndef make_word_cloud(npt_artist):\n return npt_artist.wordcloud()\n\ndef make_co_occurrence_nw(npt_artist):\n npt_artist.build_graph(min_edge_frequency=25)\n npt_artist.co_network(\n title='Co-occurrence network',\n )\n return npt_artist\n\ndef make_sunburst(npt_artist,title_text):\n npt_artist.build_graph(min_edge_frequency=25)\n npt_artist.co_network(\n title='Co-occurrence network',\n )\n\n return npt_artist.sunburst(title=title_text)\n\ndef show_fig_2in1(yuming_fig,miyuki_fig,title_text):\n trace1 = yuming_fig['data'][0]\n trace2 = miyuki_fig['data'][0]\n \n fig = make_subplots(rows=1, cols=2, subplot_titles=('#松任谷由実', '#中島みゆき'), shared_xaxes=False)\n fig.update_xaxes(title_text='word count', row=1, col=1)\n fig.update_xaxes(title_text='word count', row=1, col=2)\n\n fig.update_layout(height=1100, width=1900, title_text=title_text)\n fig.add_trace(trace1, row=1, col=1)\n fig.add_trace(trace2, row=1, col=2)\n # plotly.offline.plot(fig, filename='unigram.html', auto_open=False) \n fig.show()\n \n\ndef n_gram(npt_yuming,npt_miyuki):\n # unigram\n yuming_fig1 = make_n_gram_fig(npt_yuming,1,'yuming_unigram')\n miyuki_fig1 = make_n_gram_fig(npt_miyuki,1,'miyuki_unigram') \n show_fig_2in1(yuming_fig1,miyuki_fig1,title_text='unigram #松任谷由実 vs. #中島みゆき')\n\n # bigram\n yuming_fig2 = make_n_gram_fig(npt_yuming,2,'yuming_bigram')\n miyuki_fig2 = make_n_gram_fig(npt_miyuki,2,'miyuki_bigram') \n show_fig_2in1(yuming_fig2,miyuki_fig2,title_text='bigram #松任谷由実 vs. #中島みゆき')\n\n # # trigram\n # yuming_fig3 = make_n_gram_fig(npt_yuming,3,'yuming_bigram')\n # miyuki_fig3 = make_n_gram_fig(npt_miyuki,3,'miyuki_bigram') \n # show_fig_2in1(yuming_fig3,miyuki_fig3,title_text='trigram #松任谷由実 vs. #中島みゆき')\n \ndef n_gram_tree_map(npt_yuming,npt_miyuki):\n # unigram\n yuming_fig1 = make_n_gram_tree_map_fig(npt_yuming,1,'yuming_unigram')\n miyuki_fig1 = make_n_gram_tree_map_fig(npt_miyuki,1,'miyuki_unigram') \n plotly.io.show(yuming_fig1)\n plotly.io.show(miyuki_fig1)\n # show_fig_2in1(yuming_fig1,miyuki_fig1,title_text='unigram #松任谷由実 vs. #中島みゆき')\n\n # bigram\n yuming_fig2 = make_n_gram_tree_map_fig(npt_yuming,2,'yuming_bigram')\n miyuki_fig2 = make_n_gram_tree_map_fig(npt_miyuki,2,'miyuki_bigram') \n plotly.io.show(yuming_fig2)\n plotly.io.show(miyuki_fig2)\n # show_fig_2in1(yuming_fig2,miyuki_fig2,title_text='bigram #松任谷由実 vs. #中島みゆき')\n\ndef word_cloud(npt_yuming,npt_miyuki):\n make_word_cloud(npt_yuming)\n make_word_cloud(npt_miyuki)\n\ndef co_occurrence_nw(npt_yuming,npt_miyuki):\n make_co_occurrence_nw(npt_yuming)\n make_co_occurrence_nw(npt_miyuki)\n\ndef sunburst(npt_yuming,npt_miyuki):\n plotly.io.show(make_sunburst(npt_yuming,title_text='松任谷由実'))\n plotly.io.show(make_sunburst(npt_miyuki,title_text='中島みゆき'))\n \ndef main():\n df_yuming['words'] = df_yuming.lyric.apply(make_words_list)\n npt_yuming = nlplot.NLPlot(df_yuming, target_col='words')\n \n df_miyuki['words'] = df_miyuki.lyric.apply(make_words_list)\n npt_miyuki = nlplot.NLPlot(df_miyuki, target_col='words')\n \n n_gram(npt_yuming,npt_miyuki)\n n_gram_tree_map(npt_yuming,npt_miyuki)\n word_cloud(npt_yuming,npt_miyuki)\n co_occurrence_nw(npt_yuming,npt_miyuki)\n sunburst(npt_yuming,npt_miyuki)\nmain()","repo_name":"Katsutoshi-Inuga/qiita_2020_advent_cal_lyrics_nlp","sub_path":"src/nlp/nlp.py","file_name":"nlp.py","file_ext":"py","file_size_in_byte":4570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"2323381239","text":"import random\nimport numpy as np\nimport torch\nimport learn2learn as l2l\n\nfrom torch import nn, optim\nimport matplotlib.pyplot as plt\nimport skimage\nimport skimage.transform\nfrom skimage.color import rgb2gray\nfrom skimage.io import imread_collection\nfrom copy import deepcopy\nfrom utils import *\n\nways = 5\nshots = 5\nmeta_lr = 0.03\nfast_lr = 0.5\nmeta_batch_size = 32\nadaptation_steps = 1\nnum_iterations = 6000\ncuda = True\nseed = 42\nmeta_test_error = 0.0\nmeta_test_accuracy = 0.0\n\ntasksets = l2l.vision.benchmarks.get_tasksets('mini-imagenet',\n train_samples=2 * shots,\n train_ways=ways,\n test_samples=2 * shots,\n test_ways=ways,\n root='../data',\n)\n\ndevice = torch.device('cpu')\nif cuda and torch.cuda.device_count():\n torch.cuda.manual_seed(seed)\n device = torch.device('cuda')\n\nmodel = l2l.vision.models.MiniImagenetCNN(ways)\nmodel.load_state_dict(torch.load('../out/5-way5-shot/model5999'))\nmodel.to(device)\n\nmaml = l2l.algorithms.MAML(model, lr=fast_lr, first_order=False)\nloss = nn.CrossEntropyLoss(reduction='mean')\n\n\nfor task in range(meta_batch_size):\n # Compute meta-testing loss\n learner = maml.clone()\n batch = tasksets.test.sample()\n evaluation_error, evaluation_accuracy = fast_adapt(batch,\n learner,\n loss,\n adaptation_steps,\n shots,\n ways,\n device)\n meta_test_error += evaluation_error.item()\n meta_test_accuracy += evaluation_accuracy.item()\n\nprint('Meta Test Error', meta_test_error / meta_batch_size)\nprint('Meta Test Accuracy', meta_test_accuracy / meta_batch_size)\n\n\n","repo_name":"sayho93/l2l","sub_path":"test/miniImagenet.py","file_name":"miniImagenet.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"42731614363","text":"import cv2\nimport numpy as np\n\nimage = cv2.imread('../src/img/9/girasol.jpg')\n\nheight, width = image.shape[:2]\n\n# Coordenadas del píxel inicial (esquina superior izquierda del área a recortar)\nstart_row, start_col = int(height * 0.25), int(width * 0.25)\n\n# Coordenadas del píxel final (esquina inferior derecha)\nend_row, end_col = int(height * 0.75), int(width * 0.75)\n\n# Recortar\ncropped = image[start_row:end_row, start_col:end_col]\n\ncv2.imshow(\"Original\", image)\ncv2.waitKey(0)\ncv2.imshow(\"Recortada\", cropped)\ncv2.waitKey(0)\n\ncv2.destroyAllWindows()\n","repo_name":"dbetm/learning-opencv","sub_path":"13_Recortando/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"29883362104","text":"from ovh import Client as OVHClient\nfrom ovh.config import config\n\n\nclass Client(OVHClient):\n\n def __init__(self, project=None, region=None, sshkey=None, flavor=None, **kwargs):\n super().__init__(**kwargs)\n\n if project is None:\n project = config.get('kovhernetes', 'project')\n self._project = project\n\n if region is None:\n region = config.get('kovhernetes', 'region')\n self._region = region\n\n if sshkey is None:\n sshkey = config.get('kovhernetes', 'sshkey')\n self._sshkey = sshkey\n\n if flavor is None:\n flavor = config.get('kovhernetes', 'flavor')\n self._flavor = flavor\n\n def missing_params(self, params):\n config = {\n 'project': self._project,\n 'region': self._region,\n 'sshkey': self._sshkey,\n 'flavor': self._flavor\n }\n\n empty = []\n for p, v in config.items():\n if v is None:\n empty.append(p)\n\n return set(empty).intersection(params)\n","repo_name":"antoineco/kOVHernetes","sub_path":"kovh/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"55"} +{"seq_id":"31643079284","text":"from selenium import webdriver\r\nfrom browsers.browser import Browser\r\nfrom pages.login_page import LoginPage\r\nfrom pages.home_page import HomePage\r\nfrom pages.talents_training_tab import TalentsTraining\r\nimport time\r\nimport unittest\r\nfrom selenium.webdriver.support.ui import Select\r\n\r\n\r\nclass TestTalentsEvidenceTab(unittest.TestCase):\r\n\r\n @classmethod\r\n def setUpClass(cls):\r\n b = Browser()\r\n cls.driver = webdriver.Chrome(executable_path=b.chrome)\r\n cls.driver.maximize_window()\r\n cls.driver.implicitly_wait(20)\r\n\r\n def test_01_verify_all_elements_work(self):\r\n driver = self.driver\r\n driver.get(\"https://app.promytheus.net\")\r\n time.sleep(2)\r\n login = LoginPage(driver)\r\n login.login()\r\n\r\n # Click Edit icon on Talents Home Page for item 1\r\n home = HomePage(driver)\r\n time.sleep(3)\r\n home.click_talent_01_edit_icon()\r\n time.sleep(3)\r\n # Click Training tab link\r\n\r\n tr = TalentsTraining(driver)\r\n tr.click_training_tab_link()\r\n time.sleep(1)\r\n\r\n # Selecting through the dropdown menu for Training History\r\n ele = driver.find_element_by_xpath(tr.training_history_select_xpath)\r\n ele.click()\r\n time.sleep(1)\r\n ele.click()\r\n drop = Select(ele)\r\n drop.select_by_visible_text(\"None\")\r\n drop.select_by_visible_text(\"Less than a year\")\r\n drop.select_by_index(2)\r\n drop.select_by_value(\"MORE_2_YEARS\")\r\n drop.select_by_index(4)\r\n drop.select_by_index(5)\r\n drop.select_by_index(6)\r\n\r\n # Click Yes/No in Professionally Coached\r\n tr.click_prof_coached_yes()\r\n tr.click_prof_coached_no()\r\n tr.click_prof_coached_yes()\r\n\r\n # Under Professionally Coached, enter in text field\r\n tr.enter_name_coached_field(\"Testing\")\r\n time.sleep(1)\r\n tr.enter_success_level_coached_field(\"Testing\")\r\n time.sleep(1)\r\n # Click Sometimes/Intensive button Training Type\r\n tr.click_training_type_intensive()\r\n tr.click_training_type_sometimes()\r\n\r\n # Enter in the text field of School or College\r\n tr.enter_school_field(\"Testing\")\r\n time.sleep(1)\r\n tr.enter_success_level_field(\"Testing\")\r\n\r\n # Click Skill level radio buttons\r\n tr.click_beginner_skill_level_radio()\r\n tr.click_advanced_skill_level_radio()\r\n tr.click_pro_skill_level_radio()\r\n time.sleep(5)\r\n\r\n @classmethod\r\n def tearDownClass(cls):\r\n cls.driver.close()\r\n cls.driver.quit()\r\n print(\"-------------------- Test Complete --------------------\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n","repo_name":"GlebovAlex/Promytheus","sub_path":"Promytheus/tests/test_talent_form_training_tab.py","file_name":"test_talent_form_training_tab.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"38161882840","text":"import html\nimport logging\nimport requests\n\nfrom googletrans import Translator\n\nfrom src.base import IngrMatch, REQUEST_FAILED_MSG\n\n\nclass BaseScraper:\n NAME = None\n DIET = None\n WEB_URL = None\n REQUEST_URL = None\n\n PRECISE_SEARCH = False # True if search method enable to search precisely\n\n MAX_N_PAGES = 4 # while looping through pages (/page/n_page/...) MAX_N_PAGES is max n_page value\n TIMEOUT = 10\n\n def __init__(self):\n if self.WEB_URL is None:\n raise Exception(\"`WEB_URL` is None, must be a string.\")\n if self.REQUEST_URL is None:\n raise Exception(\"`REQUEST_URL` is None, must be a string.\")\n if self.DIET is None:\n raise NotImplementedError(\"`DIET` is None, must be MealTypes class property \")\n\n self.HTML_PARSER = \"html.parser\"\n self.HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0',\n 'Accept-Language': 'pl,en-US;q=0.7,en;q=0.3',\n 'Accept': 'application/json'}\n\n def __str__(self):\n return f\"{self.NAME}\"\n\n def get_recipes(self, ingrs:list, meal_types:list=None, ingrs_match:str=IngrMatch.FULL) -> dict:\n \"\"\"\n Main function, calls function returning recipes which\n fulfill the conditions or an empty website's dictionary\n \"\"\"\n try:\n return self.perform_get_recipes(ingrs, meal_types, ingrs_match)\n except Exception:\n logging.error(f\"Problem with: {self}\")\n return self.data_to_dict([])\n\n def perform_get_recipes(self, ingrs:list, meal_types:list=None, ingrs_match:str=IngrMatch.FULL, *args, **kwargs) -> dict:\n \"\"\" Main function to be programmed, returns recipes which fulfill the conditions \"\"\"\n raise NotImplementedError()\n\n def get_data_from_response(self, web_resp:str=None, ingrs:list=None, meal_types:list=None, *args, **kwargs):\n \"\"\" Returns data from website's response \"\"\"\n raise NotImplementedError()\n\n def get_url(self, ingrs:list, meal_types:list=None, ingrs_match:str=IngrMatch.FULL, web_url:str=None, *args, **kwargs) -> str:\n \"\"\" Returns url ready to be send to the website \"\"\"\n return web_url\n\n def add_params_to_url(self, params:list, url:str, delimiter:str= \",\", param_name:str=None, phrase_connector:str= \"-\") -> str:\n \"\"\" Adds parameters to the url \"\"\"\n if params is not None:\n if param_name:\n url += param_name\n for index, param in enumerate(params):\n if index != 0:\n url += delimiter\n param = str(param).replace(\" \", phrase_connector)\n url += param\n return url\n\n def meal_types_copy(self, meal_types:list=None) -> list or None:\n \"\"\" Returns meal_types copy or None if meal_types is None \"\"\"\n if isinstance(meal_types, list):\n return meal_types.copy()\n return None\n\n def get_meal_types_translated(self, meal_types:list, *args, **kwargs) -> list:\n \"\"\" Changes universally written meal_types to the website's specific form \"\"\"\n if meal_types:\n rv = []\n for group_type in meal_types:\n m_type = self.meal_type_trans(group_type)\n if m_type is not None:\n rv.extend(m_type)\n return rv\n else:\n return meal_types\n\n def get_response_from_request(self, url:str) -> requests.models.Response:\n \"\"\"\n Returns websites response (requests.models.Response object)\n or raise an exception if request failed\n \"\"\"\n response = requests.get(url, headers=self.HEADERS, timeout=self.TIMEOUT)\n\n if response.ok and len(response.text) != 0:\n self.add_request_log(\"debug\", response, url=self.WEB_URL)\n return response\n\n else:\n self.add_request_log(\"warning\", response)\n return REQUEST_FAILED_MSG\n # raise Exception(f\"Request failed, code: {response.status_code}, url {response.url}\")\n\n def get_response_from_request_with_404(self, url:str) -> requests.models.Response:\n \"\"\"\n Returns websites \"ok\" and 404 response (requests.models.Response object)\n or raise an exception if request failed\n \"\"\"\n response = requests.get(url, headers=self.HEADERS, timeout=self.TIMEOUT)\n\n if response.ok or response.status_code == 404:\n self.add_request_log(\"debug\", response, url=self.WEB_URL)\n return response\n\n else:\n self.add_request_log(\"warning\", response)\n return REQUEST_FAILED_MSG\n # raise Exception(f\"Request failed, code: {response.status_code}, url {response.url}\")\n\n def recipe_data_to_dict(self, title:str, link:str) -> dict:\n \"\"\" Returns dict with info about a recipe \"\"\"\n return {\"title\": title, \"link\": link}\n\n def data_to_dict(self, recipes) -> dict:\n \"\"\" Returns dict with info about a web and search \"\"\"\n return {\"web_name\": self.NAME,\n \"cuisine_type\": self.DIET,\n \"recipes\": recipes,\n \"n_recipes\": len(recipes)}\n\n def clean_data(self, data:dict) -> dict:\n \"\"\" Cleans titles from characters encoded with html \"\"\"\n replace = {\"\\xa0\": \" \", \"\": \"\", \"\": \"\"}\n if data[\"recipes\"]:\n for recipe in data[\"recipes\"]:\n\n for (key, val) in replace.items():\n recipe[\"title\"] = recipe[\"title\"].replace(key, val)\n recipe[\"title\"] = html.unescape(recipe[\"title\"])\n recipe[\"title\"] = recipe[\"title\"].strip()\n\n recipe[\"title\"] = self.more_title_cleaning(recipe[\"title\"])\n recipe[\"link\"] = self.more_link_cleaning(recipe[\"link\"])\n return data\n\n def meal_type_trans(self, meal_type:str=None) -> list or None:\n \"\"\"\n Should be a dictionary:\n key - MealTypes variable\n value - list of names [str] or ids [int] which represent the category on the website\n\n Exemplar:\n\n trans = {\n MealType.TO_BREAD: [1],\n MealType.DRINK: [2],\n MealType.DINNER: [3, 4],\n MealType.LUNCH: [5],\n MealType.BREAKFAST: [6],\n MealType.SOUP: [7],\n MealType.DESSERT: [8, 9, 10],\n MealType.SNACKS: None,\n }\n return trans.get(meal_type)\n \"\"\"\n\n raise NotImplementedError()\n\n def pl_en_translate(self, words:list) -> list:\n \"\"\" Translates list of ingredients from polish to english \"\"\"\n translator = Translator()\n translation = [translator.translate(word, src=\"pl\", dest=\"en\").text.lower() for word in words]\n return translation\n\n def more_title_cleaning(self, title:str=None) -> str:\n \"\"\" Modifies title in final data \"\"\"\n return title\n\n def more_link_cleaning(self, link:str=None) -> str:\n \"\"\" Modifies title in final data \"\"\"\n return link\n\n def add_request_log(self, levelname:str=\"info\", response:requests.models.Response=None,\n url:str=None) -> None:\n \"\"\" Adds logs to logger \"\"\"\n\n if levelname == \"debug\":\n logging.debug(f\"{response.status_code}, {response.elapsed.total_seconds()}, {url}\")\n elif levelname == \"warning\":\n logging.warning(f\"{response.status_code}, {response.elapsed.total_seconds()}, {response.url}\")\n else:\n logging.info(f\"{response}, {url}\")\n","repo_name":"CarolineOdair/Recipes-search-engine","sub_path":"src/base/base_scrapers/base_scraper.py","file_name":"base_scraper.py","file_ext":"py","file_size_in_byte":7584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"31776296147","text":"# coding: utf-8\n\"\"\"\nSimple to-do list plugin for Aspinwall\n\"\"\"\nfrom aspinwall_launcher.widgets import Widget\nfrom aspinwall_launcher.utils.dimmable import Dimmable\nfrom gi.repository import Adw, Gtk, Gio, GObject\ntranslatable = lambda message: message\n\nclass TodoItemBox(Gtk.Box, Dimmable):\n \"\"\"Represents a single to-do list item.\"\"\"\n __gtype_name__ = 'TodoItemBox'\n\n check_button = None\n remove_button = None\n\n def __init__(self, _parent):\n \"\"\"Initializes the to-do list item.\"\"\"\n super().__init__(orientation=Gtk.Orientation.HORIZONTAL, hexpand=True)\n _ = _parent.l\n self._parent = _parent\n self.add_css_class('dimmable')\n\n self.check_button = Gtk.CheckButton(hexpand=True, halign=Gtk.Align.START)\n self.append(self.check_button)\n\n self.remove_button = Gtk.Button.new_from_icon_name('list-remove')\n self.remove_button.set_halign(Gtk.Align.END)\n self.remove_button.set_tooltip_text(_('Remove task from list'))\n self.remove_button.add_css_class('flat')\n self.remove_button.connect('clicked', self.remove)\n self.append(self.remove_button)\n\n def bind_to_item(self, item):\n \"\"\"Binds to an item.\"\"\"\n self.item = item\n item.bind_property('name', self.check_button, 'label',\n GObject.BindingFlags.BIDIRECTIONAL | GObject.BindingFlags.SYNC_CREATE\n )\n item.bind_property('checked', self.check_button, 'active',\n GObject.BindingFlags.BIDIRECTIONAL | GObject.BindingFlags.SYNC_CREATE\n )\n item.connect('notify::checked', self.handle_checked)\n self.handle_checked()\n\n def handle_checked(self, *args):\n \"\"\"Dim the to-do list item when it's checked.\"\"\"\n if self.item.props.checked:\n self.dim()\n else:\n self.undim()\n # Workaround for issue where pressing the checkbox would trigger the\n # long-press gesture\n self.set_sensitive(False)\n self.set_sensitive(True)\n\n def remove(self, *args):\n \"\"\"Removes the item from the to-do list.\"\"\"\n self._parent.remove_item(self.item)\n\nclass TodoItem(GObject.Object):\n \"\"\"Represents the data for a to-do list item.\"\"\"\n __gtype_name__ = 'TodoItem'\n\n _name = ''\n _checked = False\n\n def __init__(self, item, todo_widget):\n super().__init__()\n self._todo_widget = todo_widget # keep the widget so that we can save\n self.set_property('name', item[1])\n self.set_property('checked', item[0])\n\n @GObject.Property(type=bool, default=False)\n def checked(self):\n \"\"\"Whether the item is ticked off or not.\"\"\"\n return self._checked\n\n @checked.setter\n def checked(self, value):\n self._checked = value\n self._todo_widget.save()\n\n @GObject.Property(type=str)\n def name(self):\n \"\"\"Whether the item is ticked off or not.\"\"\"\n return self._name\n\n @name.setter\n def name(self, value):\n self._name = value\n self._todo_widget.save()\n\nclass Todo(Widget):\n metadata = {\n \"name\": translatable(\"To-do list\"),\n \"icon\": 'view-list-symbolic',\n \"description\": translatable(\"Create a list of your current tasks\"),\n \"id\": \"org.dithernet.aspinwall.widgets.Todo\",\n \"tags\": translatable('notes,todo,to do,list'),\n \"author\": translatable(\"Aspinwall developers\"),\n \"url\": \"https://github.com/aspinwall-ui/aspinwall-launcher\",\n \"issue_tracker\": \"https://github.com/aspinwall-ui/aspinwall-launcher/issues\",\n \"version\": \"0.0.1\"\n }\n\n has_config = True\n hide_edit_button = True\n\n def __init__(self, instance=0):\n super().__init__(instance)\n _ = self.l\n\n self.content = Gtk.Box(hexpand=True, orientation=Gtk.Orientation.VERTICAL)\n\n # Load to-do list items from config\n self.todo_items = Gio.ListStore(item_type=TodoItem)\n for item in self.config['items']:\n item_object = TodoItem(item, self)\n self.todo_items.append(item_object)\n\n factory = Gtk.SignalListItemFactory()\n factory.connect('setup', self.list_setup)\n factory.connect('bind', self.list_bind)\n\n list_container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)\n list_scroll = Gtk.ScrolledWindow(\n height_request=230,\n hscrollbar_policy=Gtk.PolicyType.NEVER\n )\n list_scroll.set_child(list_container)\n\n add_box = Gtk.Box(spacing=6, hexpand=True)\n add_box.set_margin_bottom(6)\n\n self.new_item_entry = Gtk.Entry(placeholder_text=_('Type in your task...'), hexpand=True)\n self.new_item_entry.set_max_length(96)\n self.new_item_button = Gtk.Button(icon_name='list-add-symbolic', halign=Gtk.Align.END)\n self.new_item_button.connect('clicked', self.add_item)\n\n add_box.append(self.new_item_entry)\n add_box.append(self.new_item_button)\n self.content.append(add_box)\n\n self.no_items_status = Adw.StatusPage(\n title=_('No Tasks'),\n description=_('Start by adding a task in the text box above.'),\n icon_name='object-select-symbolic'\n )\n self.no_items_status.add_css_class('compact')\n list_container.append(self.no_items_status)\n\n self.list_view = Gtk.ListView(\n model=Gtk.SingleSelection(model=self.todo_items), factory=factory\n )\n list_container.append(self.list_view)\n\n self.todo_items.connect('items-changed', self.update_status)\n self.update_status()\n\n self.content.append(list_scroll)\n\n self.set_child(self.content)\n\n def update_status(self, *args):\n \"\"\"Shows/hides the 'no tasks' page as needed.\"\"\"\n if len(list(self.todo_items)) == 0:\n self.list_view.set_visible(False)\n self.no_items_status.set_visible(True)\n else:\n self.list_view.set_visible(True)\n self.no_items_status.set_visible(False)\n\n def save(self, *args):\n \"\"\"Saves the contents of the notepad.\"\"\"\n todo_items = []\n for item in self.todo_items:\n todo_items.append((item.props.checked, item.props.name))\n self.config['items'] = todo_items\n\n def add_item(self, *args):\n \"\"\"Adds an item using the data from the new item entry.\"\"\"\n buffer = self.new_item_entry.get_buffer()\n name = buffer.get_text()\n if name:\n item = [False, name]\n self.todo_items.insert(0, TodoItem(item, self))\n buffer.set_text('', 0)\n self.save()\n\n def remove_item(self, item):\n \"\"\"Removes an item from the to-do list.\"\"\"\n self.todo_items.remove(self.todo_items.find(item)[1])\n self.save()\n\n def list_setup(self, factory, list_item):\n \"\"\"Sets up the widget list.\"\"\"\n list_item.set_child(TodoItemBox(self))\n\n def list_bind(self, factory, list_item):\n \"\"\"Binds the list items in the widget list.\"\"\"\n item_box = list_item.get_child()\n item = list_item.get_item()\n item_box.bind_to_item(item)\n\n_widget_class = Todo\n","repo_name":"aspinwall-ui/aspinwall-launcher","sub_path":"widgets/org.dithernet.aspinwall.widgets.todo/__widget__.py","file_name":"__widget__.py","file_ext":"py","file_size_in_byte":7122,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"55"} +{"seq_id":"19882025366","text":"\"\"\"added user agent to video\n\nRevision ID: cfdf1799cca9\nRevises: c72049272947\nCreate Date: 2018-07-29 20:54:46.366151\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'cfdf1799cca9'\ndown_revision = 'c72049272947'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('video', sa.Column('user_agent', sa.JSON(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('video', 'user_agent')\n # ### end Alembic commands ###\n","repo_name":"louisguitton/personalityinterview.com","sub_path":"migrations/versions/cfdf1799cca9_added_user_agent_to_video.py","file_name":"cfdf1799cca9_added_user_agent_to_video.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"8639539026","text":"from math import factorial\n\nfac = [1, 1]\n\nfor i in range(2,10):\n fac.append(factorial(i))\n\ndef sumf(inp):\n t = inp\n res = 0\n while t:\n res += fac[t%10]\n t //= 10\n return res\n\n\ntotal = 0\nfor i in range(3, 1000000):\n if sumf(i) == i:\n total += i\nprint(total)\n","repo_name":"chuckkh/ProjectEuler","sub_path":"PE034.py","file_name":"PE034.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"4453121553","text":"import numpy as np\nimport os\nfrom sklearn.cluster import DBSCAN\nfrom scipy.spatial.distance import cdist\nfrom mlreco.utils import CSVData\n\ndef michel_reconstruction_noghost(cfg, data_blob, res, logdir, iteration):\n \"\"\"\n Very simple algorithm to reconstruct Michel clusters from UResNet semantic\n segmentation output.\n\n Parameters\n ----------\n data_blob: dict\n Input dictionary returned by iotools\n res: dict\n Results from the network, dictionary using `analysis_keys`\n cfg: dict\n Configuration\n idx: int\n Iteration number\n\n Notes\n -----\n Assumes 3D\n\n Input\n -----\n Requires the following analysis keys:\n - `segmentation` output of UResNet\n Requires the following input keys:\n - `input_data`\n - `segment_label`\n - `particles_label` to get detailed information such as energy.\n - `clusters_label` from `cluster3d_mcst` for true clusters informations\n\n Output\n ------\n Writes 2 CSV files:\n - `michel_reconstruction-*`\n - `michel_reconstruction2-*`\n \"\"\"\n method_cfg = cfg['post_processing']['michel_reconstruction_noghost']\n coords_col = method_cfg.get('coords_col', (1, 4))\n\n # Create output CSV\n store_per_iteration = True\n if method_cfg is not None and method_cfg.get('store_method',None) is not None:\n assert(method_cfg['store_method'] in ['per-iteration','per-event'])\n store_per_iteration = method_cfg['store_method'] == 'per-iteration'\n\n fout_reco,fout_true=None,None\n if store_per_iteration:\n fout_reco=CSVData(os.path.join(logdir, 'michel-reconstruction-reco-iter-%07d.csv' % iteration))\n fout_true=CSVData(os.path.join(logdir, 'michel-reconstruction-true-iter-%07d.csv' % iteration))\n\n # Loop over events\n for batch_id,data in enumerate(data_blob['input_data']):\n\n event_idx = data_blob['index' ][batch_id]\n\n if not store_per_iteration:\n fout_reco=CSVData(os.path.join(logdir, 'michel-reconstruction-reco-event-%07d.csv' % event_idx))\n fout_true=CSVData(os.path.join(logdir, 'michel-reconstruction-true-event-%07d.csv' % event_idx))\n\n # from input/labels\n label = data_blob['segment_label' ][batch_id][:,-1]\n #label_raw = data_blob['sparse3d_pcluster_semantics'][batch_id]\n clusters = data_blob['clusters_label' ][batch_id]\n particles = data_blob['particles_label'][batch_id]\n #true_ghost_mask = label < 5\n #data_masked = data[true_ghost_mask]\n #label_masked = label[true_ghost_mask]\n\n one_pixel = 2.8284271247461903\n one_pixel_dbscan = 5\n\n # Retrieve semantic labels corresponding to clusters\n #clusters_semantics = np.zeros((clusters.shape[0]))-1\n #for cluster_id in np.unique(clusters[:, -2]):\n # cluster_idx = clusters[:, -2] == cluster_id\n # coords = clusters[cluster_idx][:, :3]\n # d = cdist(coords, label_raw[:, :3])\n # semantic_id = np.bincount(label_raw[d.argmin(axis=1)[d.min(axis=1) 0:\n # Michel_clusters_id = np.unique(Michel_true_clusters[Michel_true_clusters>-1])\n # for Michel_id in Michel_clusters_id:\n # current_index = Michel_true_clusters == Michel_id\n # distances = cdist(Michel_coords[current_index], MIP_coords)\n # is_attached = np.min(distances) < 2.8284271247461903\n # # Match to MC Michel\n # distances2 = cdist(Michel_coords[current_index], Michel_start)\n # closest_mc = np.argmin(distances2, axis=1)\n # closest_mc_id = closest_mc[np.bincount(closest_mc).argmax()]\n\n # TODO how do we count events where there are no predictions but true?\n if MIP_coords_pred.shape[0] == 0 or Michel_coords_pred.shape[0] == 0:\n continue\n # print(\"Also predicted!\")\n # 2. Compute true and predicted clusters\n MIP_clusters = DBSCAN(eps=one_pixel_dbscan, min_samples=10).fit(MIP_coords_pred).labels_\n if np.count_nonzero(MIP_clusters>-1) == 0:\n continue\n Michel_pred_clusters = DBSCAN(eps=one_pixel_dbscan, min_samples=5).fit(Michel_coords_pred).labels_\n Michel_pred_clusters_id = np.unique(Michel_pred_clusters[Michel_pred_clusters>-1])\n # print(len(Michel_pred_clusters_id))\n # Loop over predicted Michel clusters\n for Michel_id in Michel_pred_clusters_id:\n current_index = Michel_pred_clusters == Michel_id\n # 3. Check whether predicted Michel is attached to a predicted MIP\n # and at the edge of the predicted MIP\n distances = cdist(Michel_coords_pred[current_index], MIP_coords_pred[MIP_clusters>-1])\n if distances.shape[0] == 0 or distances.shape[1] == 0:\n print(distances.shape, Michel_id, Michel_pred_clusters_id)\n # is_attached = np.min(distances) < 2.8284271247461903\n is_attached = np.min(distances) < 5\n is_edge = False # default\n # print(\"Min distance:\", np.min(distances))\n if is_attached:\n Michel_min, MIP_min = np.unravel_index(np.argmin(distances), distances.shape)\n MIP_id = MIP_clusters[MIP_clusters>-1][MIP_min]\n MIP_min_coords = MIP_coords_pred[MIP_clusters>-1][MIP_min]\n MIP_cluster_coords = MIP_coords_pred[MIP_clusters==MIP_id]\n ablated_cluster = MIP_cluster_coords[np.linalg.norm(MIP_cluster_coords-MIP_min_coords, axis=1)>15.0]\n if ablated_cluster.shape[0] > 0:\n new_cluster = DBSCAN(eps=one_pixel_dbscan, min_samples=5).fit(ablated_cluster).labels_\n is_edge = len(np.unique(new_cluster[new_cluster>-1])) == MIP_label\n else:\n is_edge = True\n # print(is_attached, is_edge)\n\n michel_pred_num_pix_true, michel_pred_sum_pix_true = -1, -1\n michel_true_num_pix, michel_true_sum_pix = -1, -1\n michel_true_energy = -1\n michel_true_num_pix_cluster = -1\n if is_attached and is_edge and Michel_coords.shape[0] > 0:\n # Distance from current Michel pred cluster to all true points\n distances = cdist(Michel_coords_pred[current_index], Michel_coords)\n closest_clusters = Michel_true_clusters[np.argmin(distances, axis=1)]\n closest_clusters_final = closest_clusters[(closest_clusters > -1) & (np.min(distances, axis=1) 0:\n # print(closest_clusters_final, np.bincount(closest_clusters_final), np.bincount(closest_clusters_final).argmax())\n # cluster id of closest true Michel cluster\n # we take the one that has most overlap\n # closest_true_id = closest_clusters_final[np.bincount(closest_clusters_final).argmax()]\n closest_true_id = np.bincount(closest_clusters_final).argmax()\n overlap_pixels_index = (closest_clusters == closest_true_id) & (np.min(distances, axis=1) -1:\n closest_true_index = label[predictions==Michel_label][current_index]==Michel_label\n # Intersection\n michel_pred_num_pix_true = 0\n michel_pred_sum_pix_true = 0.\n for v in data[(predictions==Michel_label).reshape((-1,)), ...][current_index]:\n count = int(np.any(np.all(v[coords_col[0]:coords_col[1]] == Michel_coords[Michel_true_clusters == closest_true_id], axis=1)))\n michel_pred_num_pix_true += count\n if count > 0:\n michel_pred_sum_pix_true += v[-1]\n\n michel_true_num_pix_cluster = np.count_nonzero(Michel_true_clusters == closest_true_id)\n michel_true_num_pix = particles[closest_true_id].num_voxels()\n michel_true_sum_pix = clusters[clusters[:, -1] == Michel_label][Michel_true_clusters == closest_true_id][:, -4].sum()\n # Register true energy\n # Match to MC Michel\n # distances2 = cdist(Michel_coords[Michel_true_clusters == closest_true_id], Michel_start)\n # closest_mc = np.argmin(distances2, axis=1)\n # closest_mc_id = closest_mc[np.bincount(closest_mc).argmax()]\n # michel_true_energy = Michel_particles[closest_mc_id, 7]\n michel_true_energy = particles[closest_true_id].energy_init()\n #print('michel true energy', particles[closest_true_id].energy_init(), particles[closest_true_id].pdg_code(), particles[closest_true_id].energy_deposit())\n # Record every predicted Michel cluster in CSV\n fout_reco.record(('batch_id', 'iteration', 'event_idx', 'pred_num_pix', 'pred_sum_pix',\n 'pred_num_pix_true', 'pred_sum_pix_true',\n 'true_num_pix', 'true_sum_pix',\n 'is_attached', 'is_edge', 'michel_true_energy', 'true_num_pix_cluster'),\n (batch_id, iteration, event_idx, np.count_nonzero(current_index),\n data[(predictions==Michel_label).reshape((-1,)), ...][current_index][:, -1].sum(),\n michel_pred_num_pix_true, michel_pred_sum_pix_true, michel_true_num_pix, michel_true_sum_pix,\n is_attached, is_edge, michel_true_energy, michel_true_num_pix_cluster))\n fout_reco.write()\n\n if not store_per_iteration:\n fout_reco.close()\n fout_true.close()\n\n if store_per_iteration:\n fout_reco.close()\n fout_true.close()\n","repo_name":"DeepLearnPhysics/lartpc_mlreco3d","sub_path":"analysis/post_processing/arxiv/analysis/michel_reconstruction_noghost.py","file_name":"michel_reconstruction_noghost.py","file_ext":"py","file_size_in_byte":13375,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"55"} +{"seq_id":"34558431464","text":"# create a class programmer for storing information a few programmers working at microsoft\n\nclass Programmer:\n company = \"Microsoft\"\n def __init__(self,name,age,salary):\n self.name = name\n self.age = age\n self.salary = salary\n \n def getInfo(self):\n print(f\"The name of employee is {self.name}\")\n print(f\"The age of employee is {self.age}\")\n print(f\"The salary of employee is {self.salary}\")\n \n\nshoeb = Programmer(\"Shoeb\",19,850000)\nshoeb.getInfo()\n\n ","repo_name":"shoeb18/Python","sub_path":"chapter 10 (oops)/09_pr01.py","file_name":"09_pr01.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"38141966075","text":"from flask import jsonify\nfrom sqlalchemy import Table, Column\nfrom sqlalchemy import Integer, String, DateTime, Numeric\nfrom sqlalchemy.dialects.mysql import ENUM\nfrom sqlalchemy import create_engine\nimport os\nimport ast\nfrom sqlalchemy import MetaData\n\nmetadata = MetaData()\n\ndef ceateTables(risks):\n\t\"\"\"Takes a list of objects representing risks and their fields.\n\tThen it creates a representation for these tables and creates them afterwards.\n\tAll the tables have a MetaData() object as foreign key,\n\tSo that each set of tables are seperate and possibly assigned to a specific user\"\"\"\n\n\t# Connect to database\n\t# engine = create_engine(\"sqlite:///test.db\", echo=True)\n\tengine = create_engine('mysql+mysqldb://root:123456@localhost/britecore')\n\n\n\t# Loop through risks and makes a table representation/describtion for each risk\n\tfor risk in risks:\n\t\tceateTableRepresentation(risk, metadata)\n\n\t# All table descriptions have 'metadata' as their foreign key. So, we simply create them all.\n\tmetadata.create_all(engine)\n\treturn \"Success!\"\n\ndef getTables():\n\t'''\n\t\tTakes metadata object and returns all tables' names, fields, data-types associated with the it.\n\t'''\n\n\t# Pulls all tables' data in alphabetic order\n\ttables = metadata.sorted_tables\n\n\t# We'll return this array\n\tall_tables_info=[]\n\n\t# Loop through all tables\n\tfor table in tables:\n\n\t\t# To hold each table's risk fields\n\t\ttable_fields=[]\n\n\t\t# Loop though columns (risk fields)\n\t\tfor column in table.columns:\n\t\t\t\n\t\t\t# Get the data type of the risk field\n\t\t\tdata_type = column.type\n\t\t\tif isinstance(data_type, ENUM):\n\t\t\t\tdata_type=ast.literal_eval(str(data_type)[4:].replace('(', '[').replace(')', ']'))\n\t\t\telse:\n\t\t\t\tdata_type = str(data_type)\n\n\t\t\t# Ignore the id column\n\t\t\tif column.name == 'id':\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\t# Push a 'dict' for each risk field\n\t\t\t\ttable_fields.append({'column_name': column.name, 'data_type': data_type})\n\n\t\t# Push a 'dict' record for each table\n\t\tall_tables_info.append({'table_name':table.name, 'fields':table_fields})\n\n\t# Return 'Response' object with all the risks' data (from the DB) to the API\n\treturn jsonify(all_tables_info)\n\n\ndef ceateTableRepresentation(risk, metadata):\n\t''' Takes a risk and returns a table describtion with metadata as foreign field'''\n\ttable_name = risk['risk_name'].replace(' ', '-').lower()+\"-table\" # This is not used. \n\ttable_display_name = risk['risk_name'].title()# to be displayed to user in the next page of UX\n\tfield_names = getFieldNames(risk['fields'])# Fetches all fields associated with the risk\n\tdata_types = getDataTypes(risk['fields'])# Fetches all data-types associated with each field\n\n\t# Creates Table object. No need to return as metadata has saved the object.\n\ttable = Table(table_display_name, metadata,\n\t\tColumn('id', Integer, primary_key=True),\n\t\t*(Column(field_name, data_type)\n\t\t\tfor field_name, data_type in zip(field_names, data_types)\n\t\t\t)\n\t\t)\n\ndef getFieldNames(fields):\n\treturn [field['field'].title() for field in fields]\n\n\n# 'text' => String(50)\n# 'number' => Numeric()\n# 'date' => DateTime\n# 'other' => ENUM\ndef getDataTypes(fields):\n\tdata_types = []\n\tfor field in fields:\n\t\ttypes_list = field['type']\n\t\tprint(\"FIELD types: \" + str(types_list))\n\t\tif isinstance(types_list, str):\n\t\t\tif types_list == 'text':\n\t\t\t\tdata_types.append(String(50))\n\t\t\telif types_list == 'number':\n\t\t\t\tdata_types.append(Numeric())\n\t\t\telif types_list == 'date':\n\t\t\t\tdata_types.append(DateTime)\n\t\t\telse:\n\t\t\t\tdata_types.append(ENUM(types_list[0]))\n\n\t\telse:\n\t\t\tdata_types.append(ENUM(*(types_list)))\n\treturn data_types\n\n# if __name__ == '__main__:':\n# \tapp.run(debug=True)","repo_name":"SethBuilder/britecore","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"33849360793","text":"from fastapi import FastAPI, File, UploadFile\nimport numpy as np\nfrom inference import Inference\n\ninferenceApi = FastAPI()\n\n@inferenceApi.get(\"/\")\ndef read_root():\n return {\"Message\": \"API - Monograph - Testing\"}\n\n# Realiza la inferencia\n@inferenceApi.post(\"/inference/\")\nasync def inference(version: str,data_test: dict):\n inference = Inference(version= version,data_test = data_test)\n result = inference.test()\n return result\n\n","repo_name":"nacholee748/ml2-mlops-monograph","sub_path":"monographInference/api_inference.py","file_name":"api_inference.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"39978846028","text":"\nimport math\nimport mesh\nimport pyglet\nfrom pyglet.gl import *\nfrom euclid import *\n\n\nclass Sphere(object):\n\tdef __init__(self, radius=1.0, numRings=16, numSegments=16):\n\t\tdef pointOnSphere(radius, phi, theta):\n\t\t\tu = radius * math.cos(phi)\n\t\t\tx = math.sqrt(radius * radius - u * u) * math.cos(theta)\n\t\t\ty = math.sqrt(radius * radius - u * u) * math.sin(theta)\n\t\t\tz = u\n\t\t\treturn (x, y, z)\n\t\tself.mesh = []\n\t\tself.vertices = []\n\t\tself.normals = []\n\t\tself.uvs = []\n\t\tself.indexes = []\n\t\tdeltaRingAngle = (math.pi / numRings)\n\t\tdeltaSegAngle = (2.0 * math.pi / numSegments)\n\t\toffset = 0\n\n\t\tfor ring in range(0, numRings+1):\n\t\t\tr0 = radius * math.sin(ring * deltaRingAngle)\n\t\t\ty0 = radius * math.cos(ring * deltaRingAngle)\n\t\t\tfor seg in range(0, numSegments+1):\n\t\t\t\tx0 = r0 * math.sin(seg * deltaSegAngle)\n\t\t\t\tz0 = r0 * math.cos(seg * deltaSegAngle)\n\t\t\t\tself.vertices.extend([x0, y0, z0])\n\t\t\t\tnormal = Vector3(x0, y0, z0)\n\t\t\t\tnormal.normalize()\n\t\t\t\tself.normals.extend(normal)\n\t\t\t\tself.uvs.extend([seg / float(numSegments),\n\t\t\t\t\t\t\t\t ring / float(numRings)])\n\t\t\t\tif (ring != numRings):\n\t\t\t\t\tself.indexes.append(offset + numSegments + 1)\n\t\t\t\t\tself.indexes.append(offset)\n\t\t\t\t\tself.indexes.append(offset + numSegments)\n\t\t\t\t\tself.indexes.append(offset + numSegments + 1)\n\t\t\t\t\tself.indexes.append(offset + 1)\n\t\t\t\t\tself.indexes.append(offset)\n\t\t\t\t\toffset = offset + 1\n\n\t\tself.radius = radius\n\t\tself.batch = None\n\t\tself.vertices = tuple(self.vertices)\n\t\tself.uvs = tuple(self.uvs)\n\t\tself.normals = tuple(self.normals)\n\t\tself.indexes = tuple(self.indexes)\n\t\treturn\n\n\tdef draw(self, shader):\n\t\tpositions = shader.attributes[b\"position\"][\"location\"]\n\t\tuvs = shader.attributes[b\"uv\"][\"location\"]\n\t\tvertattribs = \"%dg3f/static\" % positions\n\t\tuvattribs = \"%dg2f/static\" % uvs\n\t\tpyglet.graphics.draw_indexed(len(self.vertices) // 3, GL_TRIANGLES,\n\t\t\t\t\t\t\t\t\tself.indexes,\n\t\t\t\t\t\t\t\t\t(vertattribs, self.vertices), (uvattribs, self.uvs))\n\t\t\n\t\t\t\t \n\t\t\n","repo_name":"johnfredcee/pyglsl","sub_path":"sphere.py","file_name":"sphere.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"55"} +{"seq_id":"10194313229","text":"import json\nimport os\nfrom pathlib import Path\nfrom typing import Dict, Any, Optional\n\nimport toml\nfrom pydantic import BaseModel, ValidationError\n\nfrom .exceptions import ConfigurationError\nfrom .utils import backup_file\n\n\nclass CoverLetter(BaseModel):\n template_folder: str\n default_template: str\n default_output_folder: str\n is_sample: Optional[bool] = True\n\n\nclass Gmail(BaseModel):\n email: str\n token: str\n\n\nclass Database(BaseModel):\n folder: str\n file: str\n backup_folder: str\n\n\nclass Configuration(BaseModel):\n cover_letters: CoverLetter\n gmail: Gmail\n database: Database\n\n\nclass ConfigurationManager:\n\n def __init__(self, config_folder: Optional[Path] = None,\n config_filename: Optional[str] = None):\n if config_folder is None:\n self.config_folder = Path().home() / '.py_cover_letters'\n self.config_folder.mkdir(exist_ok=True)\n else:\n self.config_folder = config_folder\n if config_filename is None:\n self.config_file = self.config_folder / 'configuration.toml'\n else:\n self.config_file = self.config_folder / config_filename\n\n self.config_backup_folder = self.config_folder / 'backups'\n self.config_backup_folder.mkdir(exist_ok=True)\n\n self.username = os.getlogin()\n\n if not self.config_file.exists():\n tmp_config = self.get_sample_config()\n self.write_configuration(tmp_config)\n\n def get_sample_config(self) -> Dict[str, Any]:\n data = {'cover_letters': {'template_folder': str(self.config_folder / 'templates'),\n 'default_template': 'Cover Letter Template.docx',\n 'default_output_folder': str(Path(os.getcwd()) / 'output'),\n 'is_sample': True},\n 'gmail': {'email': f'{self.username}@gmail.com',\n 'token': 'SECRET'},\n 'database': {'folder': str(Path(os.getcwd()) / 'data'),\n 'file': 'cover_letters.xlsx',\n 'backup_folder': str(Path(os.getcwd()) / 'data' / 'backups')}\n }\n return data\n\n def prep_config(self):\n config = self.get_configuration_obj()\n folder = Path(config.database.folder)\n folder.mkdir(exist_ok=True)\n folder = Path(config.database.backup_folder)\n folder.mkdir(exist_ok=True)\n\n def write_configuration(self, config_data: Dict[str, Any], over_write: bool = False,\n is_sample: bool = False) -> None:\n if self.config_file.exists() and not over_write:\n raise Exception('Cannot overwrite config file.')\n with open(self.config_file, 'w') as f:\n toml.dump(config_data, f)\n\n def get_configuration(self) -> Dict[str, Any]:\n if not self.config_folder.exists():\n error_message = 'No configuration file found. Run py-cover-letters config.'\n raise ConfigurationError(error_message)\n\n with open(self.config_file, 'r') as f:\n configuration = toml.load(f)\n return configuration\n\n def get_configuration_obj(self) -> Configuration:\n config = self.get_configuration()\n config_obj = Configuration(**config)\n return config_obj\n\n def export_to_json(self, export_file: Path) -> None:\n config = self.get_configuration()\n with open(export_file, 'w') as f:\n json.dump(config, f)\n\n def is_valid(self, raise_error: bool = False) -> bool:\n try:\n self.get_configuration_obj()\n return True\n except ValidationError as e:\n error_msg = f'Configuration error. Type: {e.__class__.__name__} Error: {e}'\n if raise_error:\n raise ConfigurationError(error_msg)\n return False\n\n def backup(self) -> Path:\n backup_filename = backup_file(self.config_file, self.config_backup_folder)\n return backup_filename\n\n def delete(self) -> Path:\n backup_file = self.backup()\n self.config_file.unlink(missing_ok=True)\n return backup_file\n\n @classmethod\n def get_current(cls):\n config = cls()\n return config.get_configuration()\n","repo_name":"luiscberrocal/py_cover_letters","sub_path":"py_cover_letters/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"72365365292","text":"import pygame\nimport random\n\npygame.init()\n\nsize = [255, 300]\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption(\"Grids\")\nclock = pygame.time.Clock()\n\n#colors\nwhite = [255, 255, 255]\nblack = [0,0,0]\nred = [255, 0, 0]\n\n#variables\nwidth = 20\nheight = 20\nmargin = 5\n\n#2D array\ngrid = []\nfor row in range (10):\n\tgrid.append([])\n\tfor column in range (10):\n\t\tgrid[row].append(0)\n\ngrid_x = 0\ngrid_y = 0\n#functions\ndef gridPosition(xy):\n\tgrid_x = xy[0]/25\n\tgrid_y = xy[1]/25\n\tpos = [grid_X, grid_y]\n\treturn pos\n\n#font\nfont = pygame.font.Font(None, 25)\ntext = font.render(\"Save\", True, black)\nscreen.blit(text, [10, 263])\n\ndone = False\nwhile done == False:\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\tdone = True\n\t\tif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\tp = pygame.mouse.get_pos()\n\t\t\tif (p[1] < 250):\n\t\t\t\tprint(str(int(p[0]/25)) + \" \" + str(int(p[1]/25)))\n\t\t\t\tgrid[int(p[1]/25)][int(p[0]/25)] = 1\n\t\t\tif (p[0] > 5 and p[0] < 60 and p[1] > 260 and p[1] < 285):\n\t\t\t\tpygame.image.save(screen, \"screenshot.jpeg\")\n\tscreen.fill(black)\n\n\tfor column in range (0, 10):\n\t\tfor row in range (0, 10):\n\t\t\tcolor = white\n\t\t\tif grid[row][column] == 1:\n\t\t\t\tcolor = red\n\t\t\tpygame.draw.rect(screen, color, [column*width + column*margin + margin , row*margin + row*height + margin, width, height], 0)\n\t\t\tpygame.draw.rect(screen, color, [5, 260, 55, 25], 0)\n\t\t\tscreen.blit(text, [10, 263])\n\tpygame.display.flip()\n\tclock.tick(20)\n\n\npygame.quit()","repo_name":"epson121/pygame.examples","sub_path":"pygame course/array_backed_grids.py","file_name":"array_backed_grids.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"55"} +{"seq_id":"72012690093","text":"from dataclasses import dataclass\nfrom types import NoneType\nfrom expression_parser.parser.tokens import Token\nimport json\n\n\n\n@dataclass\nclass Node:\n value: Token\n\n def to_json(self):\n parse = lambda o: dict(type=o.__class__.__name__) | o.__dict__\n return json.dumps(parse(self), default=parse, indent=2)\n\n\nNodesTuple = tuple[Node, ...]\n\n@dataclass\nclass UnaryOperatorNode(Node):\n expression: (Node | NoneType)\n\n\n@dataclass\nclass BinaryOperatorNode(Node):\n left: (Node | NoneType)\n right: (Node | NoneType)\n\n\n@dataclass\nclass FunctionNode(Node):\n args: NodesTuple\n\n\n","repo_name":"Andrew1407/expression_parser","sub_path":"expression_parser/analyzer/tree_nodes.py","file_name":"tree_nodes.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"19366820555","text":"from onegov.activity import Period\nfrom onegov.chat import Message\nfrom onegov.org.models.message import TicketMessageMixin\n\n\nclass PeriodMessage(Message):\n\n __mapper_args__ = {\n 'polymorphic_identity': 'period'\n }\n\n def link(self, request):\n return request.class_link(Period, {'id': self.channel_id})\n\n @classmethod\n def create(cls, period, request, action):\n assert request.current_username, \"reserved for logged-in users\"\n\n return cls.bound_messages(request.session).add(\n channel_id=period.id.hex,\n owner=request.current_username,\n meta={\n 'title': period.title,\n 'action': action\n }\n )\n\n\nclass ActivityMessage(Message, TicketMessageMixin):\n\n __mapper_args__ = {\n 'polymorphic_identity': 'activity'\n }\n\n @classmethod\n def create(cls, ticket, request, action, extra_meta=None):\n return super().create(\n ticket, request, action=action, extra_meta=extra_meta)\n","repo_name":"OneGov/onegov-cloud","sub_path":"src/onegov/feriennet/models/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"55"} +{"seq_id":"23575470692","text":"import logging\nimport time\nimport threading\nfrom app.recommendations.recommendations import DateBasedRecommendation\n\n\nclass RecommendationBackGroundTask:\n def __init__(self, recom, interval=5):\n self.interval = interval\n self.recom = recom\n\n thread = threading.Thread(target=self.run, args=())\n thread.daemon = True\n thread.start()\n\n def run(self):\n from app.models import RecommendationAlarm\n from app import db\n while True:\n alarm = RecommendationAlarm.query.filter_by(task=self.recom.t_id).first()\n\n if self.recom.check():\n # logging.info(\"Creating alarm!\")\n if not alarm:\n alarm = RecommendationAlarm()\n alarm.task = self.recom.t_id\n alarm.message = self.recom.text\n alarm.severity = self.recom.severity\n\n db.session.add(alarm)\n db.session.commit()\n else:\n if not isinstance(self.recom, DateBasedRecommendation):\n if alarm:\n db.session.delete(alarm)\n db.session.commit()\n\n time.sleep(self.interval)\n","repo_name":"TheHolyWay/ficus-tracker-backend","sub_path":"ficus-tracker/app/recommendations/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"73173492010","text":"from django.contrib import messages\nfrom django.core.files.storage import FileSystemStorage\nfrom django.forms import model_to_dict\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom UserEntry.models import *\nfrom HomePage.models import *\nfrom Magazine.models import EventCode, EventSection, EventImages, MagazineUpload\nfrom WatchUser_EntryUser.filters import HeadPersonFilter\nimport datetime\n\n\n# Create your views here.\n\n\ndef CalCulateAge(request):\n td = datetime.datetime.now().date()\n members = FamilyMember.objects.all()\n memberlist = []\n for mem in members:\n bd = mem.M_BOD\n print(bd)\n age_years = int((td - bd).days / 365.25)\n memberlist.append({\"model\": model_to_dict(mem), 'age': age_years})\n\n print(memberlist)\n return render(request, 'AdminDashbord/CalculateAge.html', {'members': memberlist})\n\n\ndef BasicInfoHead(request):\n headpersons = FamilyHead.objects.all()\n male = FamilyMember.objects.filter(M_Sex='Male')\n Female = FamilyMember.objects.filter(M_Sex='FeMale')\n FeMale_Count = Female.count()\n Count_Male = male.count()\n Count_Family = headpersons.count()\n myFilter = HeadPersonFilter(request.GET, queryset=headpersons)\n headpersons = myFilter.qs\n return render(request, 'AdminDashbord/basic_InfoHead.html',\n {'FeMale_Count': FeMale_Count, 'Count_Male': Count_Male, 'HeadPerson': headpersons,\n 'myFilter': myFilter, 'Count_Family': Count_Family})\n\n\ndef Dashboard(request):\n return render(request, 'AdminDashbord/base_admin.html')\n\n\ndef ShowFamily(request, head_id):\n Head = FamilyHead.objects.filter(id=head_id)\n Member = FamilyMember.objects.all()\n return render(request, 'AdminDashbord/Show_Family.html', {'Head': Head, 'member': Member})\n\n\ndef FemaleInfo(request):\n female = FamilyMember.objects.filter(M_Sex='FeMale')\n return render(request, 'AdminDashbord/FemaleMemberList.html', {'member': female})\n\n\ndef MaleInfo(request):\n male = FamilyMember.objects.filter(M_Sex='Male')\n return render(request, 'AdminDashbord/MaleMemberList.html', {'member': male})\n\n\ndef MemHeadData(request):\n familyCode = FamilyHead.objects.all()\n familymember = FamilyMember.objects.all()\n contex = {'head': familyCode, 'member': familymember}\n print(contex)\n return render(request, 'AdminDashbord/MemHeadData.html', contex)\n\n\ndef AddFamilyMemberfFirstPageDirection(request):\n familycodes = FamilyCode.objects.all()\n return render(request, 'AdminDashbord/AddExtraMember.html', {'familycodes': familycodes})\n\n\ndef AddExtraFamilyMember(request):\n familycodes = FamilyCode.objects.all()\n if request.method == \"POST\":\n print(\"Value Submitted\")\n print(\"Value Submitted\")\n try:\n Mem_Name = request.POST.get('M_Name')\n Mem_Rel = request.POST.get('M_Relation_To_Head')\n M_BOD = request.POST.get('M_BOD')\n M_Study_Qualifications = request.POST.get('M_Study_Qualifications')\n M_Profession = request.POST.get('M_Profession')\n M_Marital_Status = request.POST.get('M_Marital_Status')\n M_Blood_Group = request.POST.get('M_Blood_Group')\n M_Phone_NO = request.POST.get('M_Phone_NO')\n M_Sex = request.POST.get('M_Sex')\n F_Code = request.POST.get('F_Code')\n Mem_Details = FamilyMember(M_Name=Mem_Name,\n M_Relation_To_Head=Mem_Rel,\n M_BOD=M_BOD, M_F_Code=F_Code,\n M_Study_Qualifications=M_Study_Qualifications,\n M_Profession=M_Profession,\n M_Marital_Status=M_Marital_Status,\n M_Blood_Group=M_Blood_Group,\n M_Phone_NO=M_Phone_NO, M_Sex=M_Sex)\n messages.success(request, \"Added Successfully\")\n Mem_Details.save()\n except Exception as e:\n print(e)\n messages.error(request, \"Failed to Add Student\")\n return render(request, 'AdminDashbord/AddExtraMember.html', {'familycodes': familycodes})\n else:\n return HttpResponse(\"

    Method Now Allowed

    \")\n\n\ndef DeleteHeadData(request, head_id):\n headData = FamilyHead.objects.get(id=head_id)\n headData.delete()\n messages.error(request, \"Deleted Successfully\")\n return HttpResponseRedirect(\"/FamilyHeadInfo\")\n\n\ndef DeleteMemberData(request, member_id):\n memberData = FamilyMember.objects.get(id=member_id)\n memberData.delete()\n messages.error(request, \"Deleted Successfully\")\n return HttpResponseRedirect(\"/FamilyHeadInfo\")\n\n\ndef EventImagesDashBoardHomePage(request):\n eventcode = EventCode.objects.all()\n return render(request, 'AdminDashbord/EventPhotosAndCoverPage.html', {'EventId': eventcode})\n\n\ndef EventCoverImagesPage(request):\n if request.method == 'POST':\n file = request.FILES[\"Event_Cover_Page\"]\n fs = FileSystemStorage()\n Event_Cover_Page = fs.save(file.name, file)\n Event_Cover_Title = request.POST.get('Event_Cover_Title')\n Event_Id = EventCode.objects.get(Event_Id=request.POST.get('Event_Id'))\n Re_Event_Id_Enter = request.POST.get('Re_Event_Id_Enter')\n EventCoverPage = EventSection(Event_Cover_Title=Event_Cover_Title, Event_Id=Event_Id,\n Event_Cover_Page=Event_Cover_Page, Re_Enter_Id=Re_Event_Id_Enter)\n EventCoverPage.save()\n return HttpResponseRedirect('/EventImagesDashBoardHomePage')\n else:\n return HttpResponse(\"

    Method Now Allowed

    \")\n\n\ndef EventPhotosPage(request):\n if request.method == 'POST':\n file = request.FILES[\"Upload_Image\"]\n fs = FileSystemStorage()\n Re_Event_Id_Enter = request.POST.get('Re_Event_Id_Enter')\n Upload_Image = fs.save(file.name, file)\n Event_Id = EventCode.objects.get(Event_Id=request.POST.get('Event_Id'))\n EventImage = EventImages(Upload_Image=Upload_Image, Event_Id=Event_Id, Re_Enter_Id=Re_Event_Id_Enter)\n EventImage.save()\n return HttpResponseRedirect('/EventImagesDashBoardHomePage')\n else:\n return HttpResponse(\"

    Method Now Allowed

    \")\n\n\ndef Eventcode(request):\n if request.method == 'POST':\n Event_Id = request.POST.get('Event_Code')\n eventcod = EventCode(Event_Id=Event_Id)\n eventcod.save()\n eventcod.clean()\n return HttpResponseRedirect('/EventImagesDashBoardHomePage')\n else:\n return HttpResponse(\"

    Method Now Allowed

    \")\n\n\ndef Magazineupload(request):\n return render(request, 'AdminDashbord/AddMagazine.html')\n\n\ndef SaveMagazineData(request):\n if request.method == 'POST':\n file = request.FILES[\"Magazine_Cover_Page\"]\n fs = FileSystemStorage()\n Magazine_Cover_Page = fs.save(file.name, file)\n Magazine_Cover_Title = request.POST.get('Magazine_Cover_Title')\n Magazine_Link = request.POST.get('Magazine_Link')\n MAgazine = MagazineUpload(Magazine_Cover_Page=Magazine_Cover_Page, Magazine_Cover_Title=Magazine_Cover_Title,\n Magazine_Link=Magazine_Link)\n MAgazine.save()\n return render(request, 'AdminDashbord/AddMagazine.html')\n\n\ndef BlogHomePage(request):\n return render(request, 'AdminDashbord/BlogDataFromAdmin.html')\n\n\ndef BlogHomePageDataSave(request):\n if request.method == 'POST':\n file = request.FILES[\"NewsImages\"]\n fs = FileSystemStorage()\n NewsImages = fs.save(file.name, file)\n BlogId = request.POST.get('BlogId')\n NewsTitle = request.POST.get('NewsTitle')\n NewsBlogNews = request.POST.get('NewsBlogNews')\n NewsThumbnailTitleNews = request.POST.get('NewsThumbnailTitleNews')\n NewsDate = request.POST.get('NewsDate')\n BlogNews = NewsAndEventsBlog(BlogId=BlogId,NewsImages=NewsImages, NewsTitle=NewsTitle, NewsBlogNews=NewsBlogNews, NewsThumbnailTitleNews=NewsThumbnailTitleNews, NewsDate=NewsDate)\n BlogNews.save()\n return HttpResponseRedirect('/BlogHomePage')\n else:\n return HttpResponse(\"

    Method Now Allowed

    \")\n","repo_name":"harshbarotb/DSAMAJ","sub_path":"AdminDashbord/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"28263067505","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.decomposition import PCA\nfrom scipy.signal import savgol_filter, find_peaks\n\nimport os\ndef test():\n return os.path.dirname(os.path.realpath(__file__))\n\ndef count_peaks(height=0.1):\n filename = \"/storage/self/primary/temp.csv\"\n\n with open(filename) as f:\n df = pd.read_csv(filename)\n\n #dataframe_acc = df.iloc[:, 2:5]\n #dataframe_gyro = df.iloc[:,5:7]\n\n pca = PCA(n_components=1)\n #acc_pca = pca.fit_transform(dataframe_acc)\n #gyro_pca = pca.fit_transform(dataframe_gyro)\n acc_pca = pca.fit_transform(df.iloc[:, 2:5])\n\n #acc_smooth = savgol_filter(acc_pca.flatten(), 1, 0) # window size 51, polynomial order 3\n data_smooth = savgol_filter(acc_pca.flatten(), 1, 0)\n\n indices = find_peaks(data_smooth, height=height)[0]\n threshold = 0.1\n try:\n threshold = np.min(data_smooth[indices]) * 0.3\n except Exception:\n pass\n if height > 0.1:\n threshold = min(threshold, height)\n threshold = max(threshold, 0.1)\n threshold = min(threshold, 0.2)\n return str(len(indices)) + \",\" + str(threshold)\n","repo_name":"castlefei/android","sub_path":"boarder/app/src/main/python/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"30458021296","text":"num = int(input(\"Digite qual tabuada você quer entre 1 e 10: \"))\n\n# Verifica se o número digitado está dentro do intervalo válido\nif num < 1 or num > 10:\n print(\"Número inválido. Digite um número entre 1 e 10.\")\nelse:\n # Loop for para gerar a tabuada\n for i in range(1, 11):\n print(num, \"x\", i, \"=\", num*i)\n \n \n\n","repo_name":"bkhenrique/faculdade-estacio","sub_path":"py/tabuada.py","file_name":"tabuada.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"657085076","text":"import glob\nimport logging\nimport os\nimport netCDF4\nimport numpy as np\n\n\n# Set up a logger\nlevel = logging.INFO\nlog = logging.getLogger(__name__)\nlog.setLevel(level)\n\n\ndef reduce_data(file_path, variable):\n \"\"\"\n Calculate the average of a netcdf file.\n\n :param file_path: Path to the netcdf file.\n :param variable: Variable to calculate the average.\n\n :return: Average of the netcdf variable.\n \"\"\"\n file_list = glob.glob(os.path.join(file_path, 'openmars*.nc'))\n\n data_list = []\n for fil in file_list:\n log.debug('Reading file: {}'.format(fil))\n with netCDF4.Dataset(fil, 'r') as nc_file:\n data = nc_file.variables[variable]\n log.debug(data)\n\n # Average over the time dimension for each dataset\n if data.DEPEND_0 == 'time':\n log.debug('Found time dimension')\n # We only care about ground level so take bottom\n # if there are multiple levels\n if data.DEPEND_1 == 'lev':\n log.debug('Found level dimension')\n data_list.append(np.average(data[:,0,:,:], axis=0))\n else:\n log.debug('Found no level dimension')\n data_list.append(np.average(data[:,:,:], axis=0))\n stats = {'avg': np.average(data_list, axis=0),\n 'median': np.median(data_list, axis=0),\n 'max': np.amax(data_list, axis=0),\n 'min': np.amin(data_list, axis=0),\n 'std': np.std(data_list, axis=0)}\n\n return stats\n\n\ndef average_all(file_path):\n \"\"\"\n average over all of the variables in an OpenMars file\n\n :param file_path: Path to the netcdf files for OpenMars.\n\n :return: stats on all of the files found in OpenMars.\n \"\"\"\n\n # Use the keys to iterate over the data we want to aggrigate\n data = {'ps':{},\n 'tsurf': {},\n 'dustcol': {},\n 'u': {},\n 'v': {}\n }\n\n for var in data.keys():\n log.debug('Working on variable: {}'.format(var))\n data[var] = reduce_data(file_path, var)\n\n return data\n\n\ndef new_file(file_path, data, file_name='avg_openmars.nc'):\n \"\"\"\n Aggrigates data from the openMars dataset\n \n :param file_path: Path to the netcdf files for OpenMars.\n :param file_name: Name of the new netcdf file.\n :param data: Dictionary of the data to be written to the new file.\n\n \"\"\"\n # Datums to put into the file\n dataum_to_use = ['avg', 'median', 'max', 'min', 'std']\n # Units to put into the groups\n units = {'ps': 'Pa',\n 'tsurf': 'K',\n 'dustcol': 'NU',\n 'u': 'm/s',\n 'v': 'm/s'\n }\n\n # Get the lat and long of one of the OpenMars files\n files = glob.glob(os.path.join(file_path, 'openmars*.nc'))\n log.info('Reading file: {}'.format(files[0]))\n with netCDF4.Dataset(files[0], 'r') as nc_file:\n lat = nc_file.variables['lat']\n lon = nc_file.variables['lon']\n\n #log.debug(lat)\n #log.info('Succussfully read in lat and long. Creating new netcdf file.')\n\n # Create the new netcdf file\n filename = os.path.join(file_path, file_name)\n with netCDF4.Dataset(filename, 'w', format='NETCDF4') as f:\n f.createDimension('lat', lat.shape[0])\n f.createDimension('lon', lon.shape[0])\n latitude = f.createVariable('lat', 'f4', ('lat',))\n longitude = f.createVariable('lon', 'f4', ('lon',))\n latitude[:] = lat[:]\n longitude[:] = lon[:]\n log.info(f)\n for var in data.keys():\n grp = f.createGroup(var)\n latitude = grp.createVariable('lat', 'f4', ('lat',))\n longitude = grp.createVariable('lon', 'f4', ('lon',))\n latitude[:] = lat[:]\n longitude[:] = lon[:]\n for datum in dataum_to_use:\n v = grp.createVariable(datum, 'f4', ('lat', 'lon'))\n v.units = units[var]\n log.debug(\"Data: {}\".format(data[var][datum]))\n v[:] = data[var][datum]\n log.debug(v)\n log.info(f)\n\n\ndef do_all(file_path):\n \"\"\"\n Do all of the steps to create a new netcdf file.\n\n :param file_path: Path to the netcdf files for OpenMars.\n\n \"\"\"\n log.info('Starting average_all')\n data = average_all(file_path)\n\n log.info('Starting new_file')\n new_file(file_path, data)\n\n\ndef plot(lon, lat, stats, var, title=None):\n import matplotlib.pyplot as plt\n fig = plt.figure(figsize=(14, 8))\n CS1 = plt.contourf(lon, lat, stats[var], 30, cmap = plt.cm.magma)\n cbar = plt.colorbar(CS1)\n plt.xticks(np.arange(-135,180,45), ('135$^\\circ$W','90$^\\circ$W','45$^\\circ$W','0$^\\circ$','45$^\\circ$E','90$^\\circ$E','135$^\\circ$E'), fontsize=16 )\n plt.xlabel(r'Longitude', fontsize=18)\n plt.yticks( np.arange(-60,90,30), ('60$^\\circ$S','30$^\\circ$S','0$^\\circ$','30$^\\circ$N','60$^\\circ$N'), fontsize=16 )\n plt.ylabel('Latitude', fontsize=18)\n plt.axis([-180., 175. -87.5, 87.5])\n if not title:\n plt.title(var, fontsize=20)\n else:\n plt.title(title, fontsize=20)\n plt.show()\n","repo_name":"mgoulish/mars-habitability-explorer","sub_path":"tools/open_mars/nc_tools.py","file_name":"nc_tools.py","file_ext":"py","file_size_in_byte":5244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"72199050412","text":"#!/usr/bin/python3\n\"\"\"N queens problem solver.\"\"\"\nimport sys\n\n\ndef solve_nqueens(n, chessboard, index: int = 0):\n \"\"\"Solves the N queens problem.\n Args:\n n: The size of the chessboard.\n \"\"\"\n if (index == n):\n return\n for col in range(n):\n if check_queen(chessboard, index, col):\n chessboard[index] = col\n if index == n - 1:\n print_nqueens(chessboard)\n solve_nqueens(n, chessboard, index + 1)\n chessboard[index] = None\n\n\ndef check_queen(chessboard, row: int, col: int):\n \"\"\"Checks if a queen can be placed at a given position.\n Args:\n chessboard: The chessboard.\n row: The row to check.\n col: The column to check.\n \"\"\"\n for i in range(len(chessboard)):\n if chessboard[i] is None:\n continue\n if chessboard[i] == col and i != row:\n return False\n if i != row and (chessboard[i] == col - (row - i) or\n chessboard[i] == col + (row - i)):\n return False\n return True\n\n\ndef print_nqueens(chessboard):\n \"\"\"Prints the chessboard.\n Args:\n chessboard: The chessboard.\"\"\"\n queens = []\n for row in range(len(chessboard)):\n queens.append([row, chessboard[row]])\n print(queens)\n\n\ndef nqueens():\n if len(sys.argv) != 2:\n print('Usage: nqueens N')\n sys.exit(1)\n try:\n n = int(sys.argv[1])\n except ValueError:\n print('N must be a number')\n sys.exit(1)\n\n if n < 4:\n print('N must be at least 4')\n sys.exit(1)\n\n chessboard = [None for row in range(n)]\n solve_nqueens(n, chessboard)\n\n\nif __name__ == '__main__':\n nqueens()\n","repo_name":"nboute/holbertonschool-interview","sub_path":"nqueens/0-nqueens.py","file_name":"0-nqueens.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"24580925444","text":"from PETWorks.arx import getAttributeNameByType\nfrom PETWorks.attributetypes import QUASI_IDENTIFIER\nimport pandas as pd\n\n\ndef _measureKAnonymity(anonymized: pd.DataFrame, qiNames: list[str]) -> int:\n \n suppressedValues = [\"*\"] * len(qiNames)\n \n anonymized = anonymized.loc[\n ~anonymized[qiNames].isin(suppressedValues).all(axis=1)\n ]\n\n anonymized.to_csv(\"ktest.csv\")\n \n return anonymized.groupby(qiNames).size().min()\n\n\ndef _validateKAnonymity(kValue: int, k: int) -> bool:\n return k <= kValue\n\n\ndef PETValidation(foo, anonymized, bar, attributeTypes, k):\n anonymized = pd.read_csv(anonymized, sep=\";\", skipinitialspace=True)\n qiNames = list(getAttributeNameByType(attributeTypes, QUASI_IDENTIFIER))\n\n kValue = int(_measureKAnonymity(anonymized, qiNames))\n fulFillKAnonymity = _validateKAnonymity(kValue, k)\n\n return {\"k\": k, \"fulfill k-anonymity\": fulFillKAnonymity, \"actual\": kValue}\n","repo_name":"LiangPPP/PET_test","sub_path":"PETWorks/kanonymity.py","file_name":"kanonymity.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"69986848811","text":"import json\n\ndef get_pos(pos):\n pos = pos.split(\" \")\n return int(pos[0]), int(pos[1])\n\nif __name__ == '__main__':\n vi_word = {}\n with open(\"./wiki_data/pos_1/en_pos.json\", 'r', encoding='utf8') as file:\n vi_word = json.load(file)\n vi_line = []\n vi_line_sum = []\n vi_line_sum.append(0)\n pre = 0\n with open(\"./wiki_data/pos_1/en.line\", 'r', encoding='utf8') as file:\n for line in file.readlines():\n vi_line.append(int(line.rstrip()))\n pre += int(line.rstrip())\n vi_line_sum.append(pre)\n \n vi = {}\n for key in vi_word.keys():\n pos = []\n for i in vi_word[key]:\n i_line, i_pos = get_pos(i)\n now_pos = vi_line_sum[i_line] + i_pos\n pos.append(now_pos)\n vi[key] = pos\n \n with open(\"./wiki_data/pos/en_pos.json\", 'w', encoding='utf8') as file:\n file.write(json.dumps(vi))","repo_name":"fzihao1999/Cross-lingual-Feature-Extraction","sub_path":"data/eval_pos.py","file_name":"eval_pos.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"55"} +{"seq_id":"20216319852","text":"from model.static.database import database\nfrom model.flyweight import Flyweight\n\nclass MarketGroup(Flyweight):\n def __init__(self, market_group_id):\n #prevents reinitializing\n if \"_inited\" in self.__dict__:\n return\n self._inited = None\n #prevents reinitializing\n\n self.market_group_id = market_group_id\n cursor = database.get_cursor(\n \"select * from invMarketGroups where marketGroupID={};\".format(\n self.market_group_id))\n row = cursor.fetchone()\n\n self.parent_group_id = row[\"parentGroupID\"]\n self.market_group_name = row[\"marketGroupName\"]\n self.description = row[\"description\"]\n self.graphics_id = row[\"graphicsID\"]\n self.has_types = row[\"hasTypes\"]\n\n cursor.close()\n\n self._parent_group = None\n\n def get_parent_group(self):\n \"\"\"Populates and returns the parent group\"\"\"\n if self._parent_group is None:\n from model.static.inv.group import Group\n self._parent_group = Group(self.parent_group_id)\n return self._parent_group\n","repo_name":"Iconik/eve-suite","sub_path":"src/model/static/inv/market_group.py","file_name":"market_group.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"12110820033","text":"from pathlib import Path\nimport numpy as np\nimport pandas as pd\nimport logging\nimport shutil\nimport uuid\nimport filecmp\nimport os\nimport webbrowser\nimport dcarte\nimport getpass\nfrom .utils import (load_yaml,\n write_yaml,\n update_yaml,\n merge_dicts,\n path_exists)\n\nsep = os.sep\n\ndef get_config(config_file : str = f'{sep}dcarte{sep}config.yaml',\n root: Path = Path('__file__').parent.absolute(),\n home: Path = Path('~').expanduser(),\n dcarte_home: Path = Path(dcarte.__file__).parent.absolute()) -> dict:\n \"\"\"get_config a function that returns or creates and returns a local config file\n\n\n Args:\n config_file (str, optional): [description]. Defaults to '/dcarte/config.yaml'.\n root (Path, optional): [description]. Defaults to Path('__file__').parent.absolute().\n home (Path, optional): [description]. Defaults to Path('~').expanduser().\n\n Returns:\n [dict]: containing all the configuration information neeeded for dcarte\n \"\"\"\n if path_exists(str(home)+config_file):\n if not check_config(home):\n create_config(home, root, dcarte_home,False)\n # check if any updated yaml version exists in the toolbox folder\n source_yaml = get_source_yaml(dcarte_home)\n compare_source_yaml(home,source_yaml) \n # load the main config yaml file\n cfg = load_yaml(str(home)+config_file)\n # Check if cfg file reflects all the datasets in home\n files = list(Path(f'{home}{sep}dcarte{sep}config{sep}').glob('*.yaml'))\n domains = pd.DataFrame(cfg['domains']).domain.unique()\n if domains.shape[0]!=len(files):\n reconstruct_domains(files,cfg)\n \n else:\n cfg = create_config(home, root, dcarte_home)\n os.environ['MINDER_TOKEN'] = cfg['token']\n cfg.pop('token', None)\n return cfg\n\n\ndef reconstruct_domains(files,cfg):\n domains = pd.DataFrame(cfg['domains'])\n for file in files:\n if not file.stem in domains.domain.unique():\n tmp = load_yaml(file)\n tmp = (pd.Series(tmp.keys()).\n rename('dataset').\n to_frame().\n assign(domain = file.stem ))\n domains = pd.concat([domains,tmp])\n cfg['domains'] = domains.drop_duplicates().to_dict('records')\n config_file = f\"{cfg['home']}{sep}dcarte{sep}config.yaml\"\n write_yaml(config_file, cfg)\n \ndef check_config(home:Path = Path('~').expanduser()):\n # go over the four directories and check that they exist \n checks = np.ones((5,))\n for i,p in enumerate([\"config\", \"data\",\"log\",\"recipes\"]):\n target = f\"{home}{sep}dcarte{sep}{p}\"\n if not Path(target).is_dir():\n Path(target).mkdir(parents=True, exist_ok=True)\n checks[i] = 0\n # if recipes is in data move it outside \n recipes = f\"{home}{sep}dcarte{sep}data{sep}recipes\"\n if Path(recipes).is_dir():\n target_dir = f\"{home}{sep}dcarte{sep}recipes{sep}\"\n shutil.copytree(recipes, target_dir, dirs_exist_ok=True)\n shutil.rmtree(recipes)\n if not path_exists(f\"{home}{sep}dcarte{sep}log{sep}monitor.log\"):\n checks[4] = 0\n return np.all(checks)\n\ndef update_config(new_dict:dict, home:Path = Path('~').expanduser()):\n \"\"\"update_config updates the central config file with data from new_dict\n\n Args:\n new_dict (dict): [description]\n home (Path, optional): [description]. Defaults to Path('~').expanduser().\n \"\"\"\n update_yaml(f\"{home}{sep}dcarte{sep}config.yaml\", new_dict)\n\ndef compare_source_yaml(home,source_yaml):\n try: \n files = list(Path(source_yaml).glob('*.yaml'))\n for source in files:\n target = f'{home}{sep}dcarte{sep}config{sep}{source.name}'\n if not path_exists(target): \n shutil.copyfile(source, target)\n elif not filecmp.cmp(source,target): \n shutil.copy2(source,target)\n except:\n raise Exception(\"Sorry, unable to copy base config yaml files\") \n return files\n\ndef get_source_yaml(dcarte_home:Path):\n source_yaml = None\n for p in Path(dcarte_home).rglob('source_yaml'):\n if p.is_dir():\n source_yaml = p.resolve()\n else:\n raise Exception(\"Sorry, unable to find base config yaml folder\") \n return source_yaml\n\ndef create_config(home:Path,root:Path, dcarte_home:Path,update_token:bool=True):\n \"\"\"create_config creates a baseline config file\n\n Args:\n home (Path): [description]\n root (Path): [description]\n\n Returns:\n [type]: [description]\n \"\"\"\n # Create dcarte folder at home to store config and data folders\n tmp = {}\n for p in [\"config\", \"data\",\"log\",\"recipes\"]:\n target = f\"{home}{sep}dcarte{sep}{p}\"\n Path(target).mkdir(parents=True, exist_ok=True)\n tmp[p] = target\n # copy yaml files from source_yaml to home/config\n source_yaml = get_source_yaml(dcarte_home)\n files = compare_source_yaml(home,source_yaml) \n # create a baseline config dict\n cfg = baseline_config(home,root,files)\n # open webpage and request user to copy token\n config_file = f\"{home}{sep}dcarte{sep}config.yaml\"\n if update_token:\n cfg['token'] = get_token()\n else:\n cfg['token'] = load_yaml(config_file)['token'] \n cfg['mac'] = get_mac()\n cfg = merge_dicts(cfg,tmp)\n log_output = f\"{cfg['log']}{sep}monitor.log\"\n cfg['log_output'] = log_output\n write_yaml(config_file, cfg)\n \n return cfg\n \ndef update_token() -> bool:\n cfg = get_config()\n cfg['token'] = get_token()\n write_yaml(f\"{cfg['home']}{sep}dcarte{sep}config.yaml\", cfg)\n os.environ['MINDER_TOKEN'] = cfg['token']\n cfg.pop('token', None)\n return True\n\n\ndef get_mac() -> str:\n \"\"\"get_mac return mac address of the compute node or computer\n\n Returns:\n str: [description]\n \"\"\"\n return hex(uuid.getnode())\n\n\ndef get_token() -> str:\n \"\"\"get_token opens the access-tokens website to create a unique REST token \n\n Returns:\n str: a token generated at https://research.minder.care/portal/access-tokens\n \"\"\"\n webbrowser.open('https://research.minder.care/portal/access-tokens')\n print('Please go to https://research.minder.care/portal/access-tokens to generate a token and copy it into the input bar')\n token = getpass.getpass(prompt='Token: ')\n return token\n \n\ndef baseline_config(home: Path, root: Path, files:list) -> dict:\n \"\"\"baseline_config create a baseline config dict \n\n Args:\n home (Path): [description]\n root (Path): [description]\n\n Returns:\n dict: [description]\n \"\"\"\n \n dataset_yamels = {file.stem:load_yaml(file) for file in files}\n datasets = [{'domain':domain, 'dataset': dataset} for domain, d in dataset_yamels.items() for dataset in d.keys()]\n headers = {'Accept': 'text/plain','Content-type': 'application/json',\"Connection\": \"keep-alive\",\"X-Azure-DebugInfo\": '1'}\n cfg = {\n 'compression': 'GZIP',\n 'data_folder': f\"{home}{sep}dcarte{sep}data\",\n 'domains': datasets,\n 'headers': headers,\n 'home': f'{home}',\n 'root': f'{root}',\n 'server': 'https://research.minder.care/api/export'\n }\n return cfg\n \n","repo_name":"alexcapstick/dcarte","sub_path":"dcarte/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":7381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"6"} +{"seq_id":"35800880696","text":"from numpy import linalg\nimport matplotlib.pyplot as plt\n\nimg = plt.imread('horse.jpg')\n\nimg_rescaled = img / 255\n\nimg_gray = img_rescaled @ [0.2126, 0.7152, 0.0722]\n\nif __name__ == '__main__':\n print(img_gray.shape)\n plt.imshow(img_gray, cmap=\"gray\")\n plt.show()\n","repo_name":"jetbrains-academy/Python-Libraries-NumPy","sub_path":"Projects/SVD/Grayscale/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"25185443871","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\nimport math\ndef calc(x):\n return str(math.log(abs(12*math.sin(int(x)))))\ntry: \n link = \"http://suninjuly.github.io/alert_accept.html\"\n browser = webdriver.Chrome()\n browser.get(link)\n\n button1 = browser.find_element(By.TAG_NAME, \"button\")\n button1.click()\n\n browser.switch_to.alert.accept()\n \n element = browser.find_element(By.ID, \"input_value\")\n x = element.text\n y = calc(x)\n element_1 = browser.find_element(By.ID, \"answer\")\n element_1.send_keys(y)\n\n\n # Отправляем заполненную форму\n button2 = browser.find_element(By.TAG_NAME, \"button\")\n button2.click()\n #.btn.btn-primary\nfinally:\n print(browser.switch_to.alert.text)\n # закрываем браузер после всех манипуляций\n browser.quit()\n","repo_name":"EdwardNors/auto_tests_selenium","sub_path":"auto-test/five.py","file_name":"five.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"42482108899","text":"from sympy import symbols, nextprime, primepi, randprime, solve\n\ndef mod_inverse(a, m):\n return pow(a, -1, m)\n\ndef split_secret_shamir(secret, t, n, participants):\n x = symbols('x')\n poly = sum(solve((secret + x - xi) * mod_inverse(x, n) for xi, si in participants) * si for xi, si in participants) % n\n\n shares = [(i, poly.evalf(subs={x: i}) % n) for i in range(1, n + 1)]\n\n return shares\n\n# Example usage\nsecret = 32227089 # Your secret\nt = 3 # Threshold\nn = 5 # Number of participants\nparticipants = [(1, 32227122), (2, 32227088), (3, 32227089), (4, secret), (5, secret)]\n\nresult_shamir = split_secret_shamir(secret, t, n, participants)\nprint(\"Padalinta paslaptis pagal Shamiro schemą:\")\nfor share in result_shamir:\n print(f\"Dalyvio {share[0]} dalis: {share[1]}\")\n","repo_name":"Dizgog/UNI_CODE","sub_path":"3_kursas/Kriptografija/14/pratybos.py","file_name":"pratybos.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"36766574512","text":"'''\r\n문제를 맞은 경우 그 문제의 점수는 그 문제까지 연속된 O의 개수가 된다.\r\n예를 들어, 10번 문제의 점수는 3이 된다.\r\n\"OOXXOXXOOO\"의 점수는 1+2+0+0+1+0+0+1+2+3 = 10점이다.\r\nOX퀴즈의 결과가 주어졌을 때, 점수를 구하는 프로그램을 작성하시오.\r\n\r\n5\r\nOOXXOXXOOO\r\nOOXXOOXXOO\r\nOXOXOXOXOXOXOX\r\nOOOOOOOOOO\r\nOOOOXOOOOXOOOOX\r\n\r\n10\r\n9\r\n7\r\n55\r\n30\r\n'''\r\nn = int(input())\r\nfor i in range(n):\r\n score_list = list(map(str, input()))\r\n score = 0\r\n sum_score = 0\r\n for ox in score_list:\r\n if ox == 'O':\r\n score += 1\r\n sum_score += score\r\n else:\r\n score = 0\r\n print(sum_score)","repo_name":"jiyoung-dev/Algorithm","sub_path":"Baekjoon/단계별(Python)/5단계_1차원배열/b8958_ox퀴즈.py","file_name":"b8958_ox퀴즈.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"32700997322","text":"#!/usr/bin/python\n# coding=utf-8\n\nimport Adafruit_ADS1x15\n\n# the Analog Digital converter object\nadc = Adafruit_ADS1x15.ADS1015()\n\n\"\"\" Gain 1 means, max a value of +4.096 Volt (+4,096 Volt in Europe) on the ADC channel, resulting in a 'value' of +2047. \"\"\"\nGAIN = 1\nvoltage = 0\n\n# read AD converter (battery voltage)\n# use channel 0 on IC\nvalue = adc.read_adc(0, gain=GAIN)\n\n# 13.44 Volt battery voltage resulted in 2,94 Volt on the ADC channel with my circuit (voltage divider w/ two resistors (39k + 11k)).\n# This resulted in a ADC 'value' of 1465.\n# The conversion factor for the battery voltage is then: 1465 / 13.44 = 109.00297619047619\n#\nvoltage = (value / 109.00297619047619)\nprint(\"Value: %d\" % value)\nprint(\"Battery: %.1f Volt\" % voltage)\n","repo_name":"markusk/minibot","sub_path":"test/battery.py","file_name":"battery.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"6"} +{"seq_id":"3561405499","text":"# -*- coding: utf-8 -*-\n\ndef process(index, prog):\n op = prog[index]\n if op is 99:\n return prog\n elif op is 1:\n pos1 = prog[index+1]\n pos2 = prog[index+2]\n pos3 = prog[index+3]\n prog[pos3] = prog[pos1] + prog[pos2]\n return process(index+4,prog)\n elif op is 2:\n pos1 = prog[index+1]\n pos2 = prog[index+2]\n pos3 = prog[index+3]\n prog[pos3] = prog[pos1] * prog[pos2]\n return process(index+4,prog)\n else:\n print(\"invalid op code\")\n \ndef part1():\n with open('input.txt') as fp:\n t = fp.readline()\n t = t.split(',')\n t = list(map(int,t))\n result = process(0,t)\n print(result[0])\n \ndef part2():\n for i in range(80):\n for j in range(100):\n with open('input.txt') as fp:\n t = fp.readline()\n t = t.split(',')\n t = list(map(int,t))\n t[1] = i\n t[2] = j\n result = process(0,t)\n if result[0] == 19690720:\n print(result[0],i,j,100*i+j)\n return\n#part1() \npart2()\n","repo_name":"IdrisTheDragon/AdventOfCode2019","sub_path":"02/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"16908865384","text":"#!/usr/bin/env python\n\nfrom operator import truediv\nfrom posixpath import expanduser\nfrom intervaltree import IntervalTree\nimport sys\nimport time\nimport glob\nimport subprocess\nimport os\n\nprint('READING INPUT FILES')\n\n# READ INPUT FILES\ncrispritzResultFile = sys.argv[1] # file with CRISPRitz results\nempiricalResults = sys.argv[2] # file with empirical results\n# annotationFile = sys.argv[3] # annotation file used to find nearest gene\n# guideFile = sys.argv[4] # real guide used in the search\noutputDir = sys.argv[3] # output file name\n# check = sys.argv[6].upper() # check if user input a GENCODE annotation file\n# genomeRelease = str(sys.argv[7]).strip() # genome used in the search phase\n# directory of vcf to perform haplotype count with more than one SVs in single target\n# vcfFileDirectory = sys.argv[8]\n\n# OPEN INPUT FILES AND PREPARE OUTPUT FILE\n# crispritz results file open\ninCrispritzResults = open(crispritzResultFile, 'r')\n# empirical-seq data open\ninEmpiricalResults = open(empiricalResults, 'r').readlines()\n# annotation data open\n# inAnnotationFile = open(annotationFile, 'r')\n# guide file\n# realguide = open(guideFile, 'r').readlines()\n# open outputDir to write results\noriginFileName = crispritzResultFile.split('/')[-1]\n# originFileName = originFileName[len(originFileName)-1]\noutFile = open(outputDir + '/' + originFileName +\n '.empirical_data.tsv', 'w')\n# outFile_name = outputDir+originFileName+'.integrated_results.tsv'\n\n\nempiricalTree = IntervalTree()\nempiricalList = list()\nempiricalDict = dict()\n\nsaveDict = {\n 'Spacer+PAM': 'NA',\n 'Chromosome': 'NA',\n 'Start_coordinate_(highest_CFD)': 'NA',\n 'Strand_(highest_CFD)': 'NA',\n 'Aligned_spacer+PAM_(highest_CFD)': 'NA',\n 'Aligned_protospacer+PAM_REF_(highest_CFD)': 'NA',\n 'Aligned_protospacer+PAM_ALT_(highest_CFD)': 'NA',\n 'PAM_(highest_CFD)': 'NA',\n 'Mismatches_(highest_CFD)': 'NA',\n 'Bulges_(highest_CFD)': 'NA',\n 'Mismatches+bulges_(highest_CFD)': 'NA',\n 'Bulge_type_(highest_CFD)': 'NA',\n 'REF/ALT_origin_(highest_CFD)': 'NA',\n 'PAM_creation_(highest_CFD)': 'NA',\n 'CFD_score_(highest_CFD)': 'NA',\n 'CFD_score_REF_(highest_CFD)': 'NA',\n 'CFD_score_ALT_(highest_CFD)': 'NA',\n 'CFD_risk_score_(highest_CFD)': 'NA',\n 'Variant_info_spacer+PAM_(highest_CFD)': 'NA',\n 'Variant_info_genome_(highest_CFD)': 'NA',\n 'Variant_MAF_(highest_CFD)': 'NA',\n 'Variant_rsID_(highest_CFD)': 'NA',\n 'Variant_samples_(highest_CFD)': 'NA',\n 'Not_found_in_REF': 'NA',\n 'Other_motifs': 'NA',\n 'Start_coordinate_(fewest_mm+b)': 'NA',\n 'Strand_(fewest_mm+b)': 'NA',\n 'Aligned_spacer+PAM_(fewest_mm+b)': 'NA',\n 'Aligned_protospacer+PAM_REF_(fewest_mm+b)': 'NA',\n 'Aligned_protospacer+PAM_ALT_(fewest_mm+b)': 'NA',\n 'PAM_(fewest_mm+b)': 'NA',\n 'Mismatches_(fewest_mm+b)': 'NA',\n 'Bulges_(fewest_mm+b)': 'NA',\n 'Mismatches+bulges_(fewest_mm+b)': 'NA',\n 'Bulge_type_(fewest_mm+b)': 'NA',\n 'REF/ALT_origin_(fewest_mm+b)': 'NA',\n 'PAM_creation_(fewest_mm+b)': 'NA',\n 'CFD_score_(fewest_mm+b)': 'NA',\n 'CFD_score_REF_(fewest_mm+b)': 'NA',\n 'CFD_score_ALT_(fewest_mm+b)': 'NA',\n 'CFD_risk_score_(fewest_mm+b)': 'NA',\n 'Variant_info_spacer+PAM_(fewest_mm+b)': 'NA',\n 'Variant_info_genome_(fewest_mm+b)': 'NA',\n 'Variant_MAF_(fewest_mm+b)': 'NA',\n 'Variant_rsID_(fewest_mm+b)': 'NA',\n 'Variant_samples_(fewest_mm+b)': 'NA',\n 'Annotation_GENCODE': 'NA',\n 'Annotation_closest_gene_name': 'NA',\n 'Annotation_closest_gene_ID': 'NA',\n 'Annotation_closest_gene_distance_(kb)': 'NA',\n 'Annotation_ENCODE': 'NA',\n 'Annotation_personal': 'NA'\n}\n\n\nstart_time = time.time()\n\nprint('CREATING INTERVAL TREES')\n\nfor count, line in enumerate(inEmpiricalResults):\n empList = line.strip().split('\\t')\n empList = [elem.strip() for elem in empList]\n # example row for empirical list\n # mand mand mand mand mand mand optional\n # chr10\t33753323\t33753346\t4\tCIRCLEseq\tOT1 aTtACAGcTGCaTTTATCACAGG\n empList.append(count)\n # adding empirical data to the tree\n empiricalTree[int(empList[1]):int(empList[2])] = empList\n # to save header\n saveDict[str(empList[4])] = 'NA'\n newkey = str(empList[4])+'_mm+bul'\n saveDict[newkey] = 'NA'\n # to save data of empirical\n empiricalDict[str(empList[4])] = 'NA'\n empiricalDict[newkey] = 'NA'\n\n# writing header in file\nsave = ''\nsave += '\\t'.join(list(saveDict.keys()))\nsave += '\\n'\noutFile.write(save)\n\nprint('INTEGRATING RESULTS')\n\nif 'Chromosome' in inCrispritzResults.readline():\n print('SKIP HEADER')\nelse:\n inCrispritzResults.seek(0)\n\nfor nline, line in enumerate(inCrispritzResults):\n target = line.strip().split('\\t')\n\n # for key in saveDict:\n # saveDict[key] = 'NA'\n\n for key in empiricalDict:\n empiricalDict[key] = 'NA'\n # valueDict[key] = 'NA'\n # lowestEmpirical = 100\n\n # read chr from target line\n # saveDict['Chromosome'] = target[1]\n\n # search empirical target using in-silico target position with a window\n foundEmpirical = sorted(empiricalTree[int(target[2])-4:int(target[2])+4])\n\n # search in the list of found empirical to extract data with same chr and save them\n for found in range(0, len(foundEmpirical)):\n empirical = foundEmpirical[found].data\n if str(target[1]) == str(empirical[0]):\n empiricalList.append(empirical[-1])\n empiricalDict[str(empirical[4])] = str(empirical[5])\n empiricalDict[str(empirical[4])+'_mm+bul'] = str(empirical[3])\n # valueDict[str(empirical[4])] = empirical[5]\n # empiricalDict[str(empirical[4])] = int(empirical[3])\n\n # update the empirical dict with found targets\n # for key in empiricalDict:\n # if int(empiricalDict[key]) < 50:\n # saveDict[key] = str(valueDict[key])\n # newkey = str(key)+'_mm+bul'\n # saveDict[newkey] = empiricalDict[key]\n # if int(empiricalDict[key]) < lowestEmpirical:\n # saveDict['lowest_empirical'] = str(empiricalDict[key])\n\n # save = str()\n # for key in saveDict:\n # save += str(saveDict[key])+'\\t'\n # save += '\\n'\n\n # save row of target with empirical data\n outFile.write('\\t'.join(target) + '\\t' +\n '\\t'.join(empiricalDict.values())+'\\n')\n\nprint('CHECKING MISSING RESULTS')\n\nnotFoundFile = open(outputDir + '/' + originFileName +\n '.empirical_not_found.tsv', 'w')\n\nfor count, line in enumerate(inEmpiricalResults):\n if count not in empiricalList:\n notFoundFile.write(line)\n\nprint(\"INTEGRATION COMPLETED IN: %s seconds\" % (time.time() - start_time))\n","repo_name":"pinellolab/CRISPRme","sub_path":"PostProcess/empirical_integrator.py","file_name":"empirical_integrator.py","file_ext":"py","file_size_in_byte":6686,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"6"} +{"seq_id":"7101943146","text":"import os\nimport shutil\nimport sys\nimport json\nimport requests\nfrom win10toast_click import ToastNotifier \n\nappdata = os.getenv('APPDATA')\njson_config = appdata + '/ModUpdater/config.json'\n\n\nif os.path.exists(json_config):\n pass\nelse:\n sys.exit\n\n\n#vars\ncurrent_version = 0.3\nMinecraft_folder = appdata + \"/.minecraft\"\nmod_folder = Minecraft_folder + \"/mods\"\nTEMP_folder = Minecraft_folder + \"/mods/TEMP\"\njson_preferences = appdata + '/ModUpdater/preferences.json'\nall_mods_json = appdata + '/ModUpdater/all_mods.json'\nupdated_mods = 0\n\n\ntoaster = ToastNotifier()\n\n\n#update vars\ndef update_vars(Minecraft_folder):\n mod_folder = Minecraft_folder + \"/mods\"\n TEMP_folder = Minecraft_folder + \"/mods/TEMP\"\n fabric_fileplace = TEMP_folder + \"/fabric_loader\"\n all_mods_json = appdata + '/ModUpdater/all_mods.json'\n return mod_folder, TEMP_folder, fabric_fileplace, all_mods_json\n\n\n\n#download and open config file as file_config\nresponse = requests.get(\"https://raw.githubusercontent.com/krunkske/Minecraft-mods-SMP/main/config/config.json\")\nwith open(json_config, 'wb') as f:\n f.write(response.content)\n\nwith open(json_config, 'r') as file_config:\n data_json_config = json.load(file_config)\n\n#open preferences file as file_pref\nwith open(json_preferences, 'r') as file_pref:\n data_json_pref = json.load(file_pref)\n\n\n\n#url vars\nmods_url = data_json_config[0]['Mods_url']\nconfig_url = data_json_config[0]['Config_url']\nall_mods_url = data_json_config[0]['all_mods_url']\n\n\n\n#get minecraft folder from pref\nif data_json_pref[0]['minecraft_folder'] != \"\": \n Minecraft_folder = data_json_pref[0]['minecraft_folder']\n mod_folder, TEMP_folder, fabric_fileplace, all_mods_json = update_vars(Minecraft_folder)\n\n#make temp dir bc something doesnt work\nif not os.path.exists(TEMP_folder):\n os.mkdir(TEMP_folder)\n\n#download and open All_mods.json\nresponse = requests.get(all_mods_url)\nwith open(all_mods_json, 'wb') as f:\n f.write(response.content)\n\nwith open(all_mods_json, 'r') as file_all_mods:\n data_json_all_mods = json.load(file_all_mods)\n\n\n\ndef download_and_install_mods():\n global updated_mods\n\n print(\"Downloading and uzipping files\")\n\n all_installed_mods = os.listdir(mod_folder)\n\n\n for file in data_json_all_mods:\n if file['name'] in all_installed_mods:\n pass\n #print(file['name'] + ' is installed')\n else:\n print(file[\"name\"])\n print(file['download_url'])\n response = requests.get(file['download_url'])\n with open(TEMP_folder + '/' + file['name'], 'wb') as f:\n f.write(response.content)\n \n all_files_in_temp = os.listdir(TEMP_folder)\n\n updated_mods = set()\n for mod in all_files_in_temp:\n if mod.endswith('.jar'):\n shutil.copy(TEMP_folder + '/' + mod, mod_folder)\n updated_mods.add(mod)\n\n \n\n #show popup\n toaster.show_toast(\n \"Your mods have been updated!\", # title\n str(len(updated_mods)) + \" mods have been installed\", # message\n duration=5, # for how many seconds toast should be visible; None = leave notification in Notification Center\n threaded=True, # True = run other code in parallel; False = code execution will wait till notification disappears \n )\n\n\n if os.path.isdir(TEMP_folder):\n print(\"Deleting TEMP folder\")\n shutil.rmtree(TEMP_folder)\n\ndef Newversion():\n #show popup\n toaster.show_toast(\n \"There is a new version available!\", # title\n \"Version \" + str(latest_version) + \" is availabe\", # message\n duration=5, # for how many seconds toast should be visible; None = leave notification in Notification Center\n threaded=False, # True = run other code in parallel; False = code execution will wait till notification disappears \n )\n\n\n#check if new version exists\nlatest_version = data_json_config[0]['latest_version']\n\n\nif float(latest_version) > float(current_version):\n Newversion()\n\n\ndownload_and_install_mods()\n\nif os.path.isdir(TEMP_folder):\n print(\"Deleting TEMP folder\")\n shutil.rmtree(TEMP_folder)\n","repo_name":"krunkske/Minecraft-mods-SMP","sub_path":"Scripts/AutoUpdateMods.pyw","file_name":"AutoUpdateMods.pyw","file_ext":"pyw","file_size_in_byte":4108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"32109269950","text":"a = [1, 3, 5, 2, 4]\n\ndef sort(a):\n\n a_length = len(a)\n\n for i in range(a_length):\n # note how we stop sorting the last element from the previous pass\n # because we know that every pass naturally passes the highest value to the back\n # the numbers \"bubble\" to the top\n # since a[N] is always going to be less than a[N+1]\n for j in range(a_length - i - 1):\n if a[j] > a[j+1]:\n a[j], a[j+1] = a[j+1], a[j]\n\nsort(a)\nprint(a)\n","repo_name":"hermetikos/algorithms-python","sub_path":"sort/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"20595163423","text":"from typing import TYPE_CHECKING, Callable\n\nfrom dependency_injector import containers, providers\n\nfrom internal.app.settings import GlobalSettings\nfrom internal.db.database import PostgresDatabase\nfrom internal.db.repositories.user import UserRepository\nfrom internal.pkg.auth import AuthJWT\nfrom internal.pkg.cache import RedisCache\n\nif TYPE_CHECKING:\n from internal.pkg.auth import Auth\n from internal.pkg.cache import Cache\n\n\nclass Container(containers.DeclarativeContainer):\n # Need for @inject\n wiring_config = containers.WiringConfiguration(modules=[\n \".api.v1.users\",\n \".api.v1.auth\",\n \".api.dependencies\",\n ])\n settings: Callable[..., GlobalSettings] = providers.ThreadLocalSingleton(\n GlobalSettings,\n )\n s = settings()\n\n cache: Callable[..., 'Cache'] = providers.ThreadLocalSingleton(\n RedisCache,\n host=s.REDIS_HOST,\n port=s.REDIS_PORT,\n )\n\n db: Callable[..., 'PostgresDatabase'] = providers.ThreadLocalSingleton(\n PostgresDatabase,\n db_url=s.ASYNC_DB_URL\n )\n\n auth: Callable[..., 'Auth'] = providers.Factory(\n AuthJWT,\n secret_key=s.SECRET_KEY,\n )\n\n user_repository: Callable[..., 'UserRepository'] = providers.Factory(\n UserRepository,\n context_async_session=db.provided.async_session,\n )\n","repo_name":"BakeNecko/sidus_heroes","sub_path":"internal/app/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"36777442105","text":"class Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n indgree = defaultdict(int)\n graph = defaultdict(list)\n\n for a, b in adjacentPairs:\n graph[a].append(b)\n graph[b].append(a)\n indgree[a] += 1\n indgree[b] += 1\n\n q = deque()\n for key in indgree:\n if indgree[key] == 1:\n q.append(key)\n indgree[key] -= 1\n break \n\n order = []\n while q:\n node = q.popleft()\n order.append(node)\n for val in graph[node]:\n if indgree[val] == 2:\n q.append(val)\n indgree[val] -= 2\n \n for key in indgree:\n if indgree[key] == 1:\n order.append(key)\n break\n\n return order","repo_name":"nathy-min/Competitive_Programming2","sub_path":"restore-the-array-from-adjacent-pairs.py","file_name":"restore-the-array-from-adjacent-pairs.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"36353487277","text":"import math\nfrom scipy.signal import lfilter\nimport numpy as np\nfrom scipy.signal.signaltools import lfilter\nfrom scipy.stats import linregress\nfrom datetime import timedelta\n# import matplotlib.pyplot as plt\n\n\n########################################################\n# automated extraction of the baseflow recession coefficient k as in Linsley, Kohler, Paulhus (1975) pg.230\n# ref: Linsley, R.K., M.A. Kohler, J.L.H. Paulhus, 1975. Hydrology for Engineers 2nd ed. McGraw-Hill. 482pp.\n########################################################\ndef recessionCoef(df):\n # collect recession dates\n d = df.to_dict('index')\n x, y = [], []\n for k,v in d.items():\n k1 = k + timedelta(days=1)\n if k1 in d: \n if v['Val'] > d[k1]['Val']: \n x.append(d[k1]['Val'])\n y.append(v['Val']) \n # xt = x.copy()\n # yt = y.copy()\n\n while True:\n lnreg = linregress(x,y)\n # print(lnreg)\n if lnreg.rvalue > 0.995: break\n rem = []\n for i in range(len(x)): \n if y[i] > lnreg.slope*x[i]: rem.append(i)\n if len(rem)==len(x): break\n for i in sorted(rem, reverse = True):\n del x[i]\n del y[i]\n\n x2 = np.vstack([x, np.zeros(len(x))]).T # x needs to be a column vector instead of a 1D vector for this https://numpy.org/doc/stable/reference/generated/numpy.linalg.lstsq.html\n a, _,_,_ = np.linalg.lstsq(x2, y, rcond=None) \n # print(1/a[0]) # =k\n # plt.scatter(xt, yt, alpha=0.5) \n # plt.plot(x2,a*x2,\"r\", alpha=0.75)\n # plt.xlabel(\"$Q_t$\")\n # plt.ylabel(\"$Q_{t-1}$\")\n # plt.show()\n return 1/a[0]\n\n\n########################################################\n# recession days\n# time (in days) after peak discharge from which quick flow ceases and total flow is entirely slow flow\n# ref: Linsley, R.K., M.A. Kohler, J.L.H. Paulhus, 1975. Hydrology for Engineers 2nd ed. McGraw-Hill. 482pp.\n########################################################\ndef Ndays(careaKM2): return 0.827 * careaKM2 ** 0.2\n\n\n########################################################\n# digital filter methods of automatic baseflow separation\n########################################################\ndef digitalFilter(v, a1, b0, b1, nPasses=1):\n if nPasses <= 1: return np.minimum(v, lfilter([b0,b1], [1.0,-a1], v, axis=0))\n f = v\n for i in range(nPasses):\n if (i+1) % 2 == 0: f = np.flip(f)\n f = lfilter([b0,b1], [1.0,-a1], f, axis=0)\n if (i+1) % 2 == 0: f = np.flip(f)\n f = np.minimum(v, f)\n return np.minimum(v,f)\n\n\n\n########################################################\n# UKIH\n########################################################\n# Institute of Hydrology, 1980. Low Flow Studies report. Wallingford, UK.\n# Piggott, A.R., S. Moin, C. Southam, 2005. A revised approach to the UKIH method for the calculation of baseflow. Hydrological Sciences Journal 50(5): 911-920.\ndef ukih(v, N):\n vvv = v\n for i in range(N):\n sukih = \"o\" + str(i)\n s = v.shift(-i, \"D\").rolling(str(N)+'D').min()\n s.rename(columns={'Val': sukih}, inplace=True)\n\n vv = v.merge(s, on='Date')\n vv[sukih] = np.where(vv['Val']==vv[sukih], vv[sukih], np.NaN) # turning point\n vv[sukih].interpolate(method = 'linear', inplace = True) # interpolate\n vvv = vvv.merge(vv[sukih], on='Date')\n\n vvv['n'] = vvv.iloc[:,-N:].min(axis=1)\n vvv['x'] = vvv.iloc[:,-N:].max(axis=1)\n vvv['m'] = vvv.iloc[:,-N:].median(axis=1)\n\n vvv['sweepingMin'] = vvv[['Val','n']].min(axis=1)\n vvv['sweepingMax'] = vvv[['Val','x']].min(axis=1)\n vvv['sweepingMedian'] = vvv[['Val','m']].min(axis=1)\n\n vvv.drop(vvv.iloc[:, 1:(N+4)], axis=1, inplace=True)\n\n # vvv[vvv.index.year>2015].plot(figsize=(20,10))\n # print(vvv)\n return vvv\n\n\n########################################################\n# HYSEP\n########################################################\n# Sloto, R.A. and M.Y. Crouse, 1996. HYSEP: A Computer Program for Streamflow Hydrograph Separation and Analysis U.S. Geological Survey Water-Resources Investigations Report 96-4040.\ndef hysep(v, N):\n twoNs = 2 * math.floor(N) + 1 # nearest odd integer\n twoNsm1 = (twoNs-1)/2\n\n s = v.rolling(str(twoNs)+'D').min()[twoNs-1::twoNs]\n s.rename(columns={'Val': 'FI'}, inplace=True)\n vv = v.merge(s, how='left', on='Date') \n vv['FI'].fillna(method=\"bfill\", inplace=True)\n\n s = v.rolling(str(twoNsm1)+'D').min()\n s.rename(columns={'Val': 'SI'}, inplace=True)\n vv = vv.merge(s, how='left', on='Date')\n\n vv['LM'] = np.where(vv['Val']==vv['SI'], vv['SI'], np.NaN) # turning point\n vv['LM'].interpolate(method = 'linear', inplace = True) # interpolate\n vv['LM'] = vv[['Val','LM']].min(axis=1)\n\n # print(vv)\n # vv[vv.index.year>2015].plot(figsize=(20,10))\n return vv\n\n\n########################################################\n# PART\n########################################################\n# Rutledge, A.T., 1998. Computer Programs for Describing the Recession of Ground-Water Discharge and for Estimating Mean Ground-Water Recharge and Discharge from Streamflow Records-Update, Water-Resources Investigation Report 98-4148.\ndef part(v, N, logdecline = .1):\n vvv = v.copy()\n for antereq in range(3):\n Npart = math.floor(N)+antereq # \"largest integer that is less than the result of equation 1\"\n arr = 'bf-'+str(Npart)\n vv = v.copy()\n\n s = v.rolling(str(Npart)+'D').min()\n s.rename(columns={'Val': arr}, inplace=True)\n vv = vv.merge(s, how='left', on='Date')\n vv[arr][vv['Val'] > vv[arr]] = np.NaN\n\n vv['o1'] = np.log10(vv['Val'])\n vv['o2'] = -vv['o1'].diff()\n\n vv[arr][vv['o2'] <0] = np.NaN\n \n vv[arr][vv['o2'] > logdecline] = np.NaN\n\n vv[arr].interpolate(method = 'linear', inplace = True) # interpolate\n \n vv[arr] = vv[['Val',arr]].min(axis=1)\n\n # print(vv)\n # vv[vv.index.year>2015].plot(figsize=(20,10))\n vvv = vvv.merge(vv[arr], how='left', on='Date')\n\n # print(vvv)\n # vvv[vvv.index.year>2015].plot(figsize=(20,10))\n return vvv\n\n\n\n########################################################\n# the \"Clarifica\" technique (a.k.a. Graham method); named in (Clarifica, 2002) as a \"forward and backward-step averaging approach.\"\n########################################################\ndef clarifica(v):\n # ref: Clarifica Inc., 2002. Water Budget in Urbanizing Watersheds: Duffins Creek Watershed. Report prepared for the Toronto and Region Conservation Authority.\n # Clarifica method baseflow, 5-day avg running, 6-day min running \n s = v.rolling('6D').min() # 6-day running minimum discharge \n s = s.rolling('5D').mean().shift(-1, \"D\") # 5-day running average (3 days previous, 1 day ahead)\n return np.minimum(np.asarray(v),np.asarray(s))\n\n\n########################################################\n# returns grand estimate of baseflow\n########################################################\ndef estimateBaseflow(df, dakm2, k):\n dfo = df.copy()\n\n ###\n # DIGITAL FILTER\n nPass = 1\n # Lyne, V. and M. Hollick, 1979. Stochastic time-variable rainfall-runoff modelling. Hydrology and Water Resources Symposium, Institution of Engineers Australia, Perth: 89-92.\n # k <- 0.925 # Ranges from 0.9 to 0.95 (Nathan and McMahon, 1990). \n a = k\n b = (1-k)/2\n c = (1-k)/2\n nPass = 3 # 3 passes commonly used (Chapman, 1999)\n dfo['LynnHollick'] = digitalFilter(df[['Val']].to_numpy(),a,b,c,nPass)\n\n # Chapman, T.G., 1991. Comment on the evaluation of automated techniques for base flow and recession analyses, by R.J. Nathan and T.A. McMahon. Water Resource Research 27(7): 1783-1784\n a = (3*k-1)/(3-k)\n b = (1-k)/(3-k)\n c = (1-k)/(3-k)\n dfo['Chapman91'] = digitalFilter(df[['Val']].to_numpy(),a,b,c,1)\n\n # Chapman, T.G. and A.I. Maxwell, 1996. Baseflow separation - comparison of numerical methods with tracer experiments. Institute Engineers Australia National Conference. Publ. 96/05, 539-545.\n a = k/(2-k)\n b = (1-k)/(2-k)\n c = 0\n dfo['ChapmanMaxwell'] = digitalFilter(df[['Val']].to_numpy(),a,b,c,1)\n\n # Boughton & Eckhardt\n # Boughton, W.C., 1993. A hydrograph-based model for estimating the water yield of ungauged catchments. Hydrology and Water Resources Symposium, Institution of Engineers Australia, Newcastle: 317-324.\n # Eckhardt, K., 2005. How to construct recursive digital filters for baseflow separation. Hydrological Processes 19, 507-515.\n bfimax = 0.8\n c = (1-k)*bfimax/(1-bfimax)\n a = k/(1+c)\n b = c/(1+c)\n c = 0\n dfo['BoughtonEckhardt'] = digitalFilter(df[['Val']].to_numpy(),a,b,c,1)\n\n # Jakeman, A.J. and Hornberger G.M., 1993. How much complexity is warranted in a rainfall-runoff model? Water Resources Research 29: 2637-2649.\n a = k\n c = (1-k)*bfimax/(1-bfimax)\n a = a/(1+c)\n b = c/(1+c)\n c = b * -math.exp(-1/k)\n dfo['JakemanHornberger'] = digitalFilter(df[['Val']].to_numpy(),a,b,c,1)\n\n # Tularam, A.G., Ilahee, M., 2008. Exponential Smoothing Method of Base Flow Separation and its Impact on Continuous Loss Estimates. American Journal of Environmental Sciences 4(2):136-144.\n a = k\n b = 1-a\n c = 0\n dfo['TularamIlahee'] = digitalFilter(df[['Val']].to_numpy(),a,b,c,1)\n\n ###\n # MOVING WINDOW\n N = math.ceil(Ndays(dakm2))\n\n # Institute of Hydrology, 1980. Low Flow Studies report. Wallingford, UK.\n # Piggott, A.R., S. Moin, C. Southam, 2005. A revised approach to the UKIH method for the calculation of baseflow. Hydrological Sciences Journal 50(5): 911-920.\n uk = ukih(df, N)\n dfo['sweepingMin'] = uk['sweepingMin']\n dfo['sweepingMax'] = uk['sweepingMax']\n dfo['sweepingMedian'] = uk['sweepingMedian']\n\n # Sloto, R.A. and M.Y. Crouse, 1996. HYSEP: A Computer Program for Streamflow Hydrograph Separation and Analysis U.S. Geological Survey Water-Resources Investigations Report 96-4040.\n sc = hysep(df, N)\n dfo['fixedInterval'] = sc['FI']\n dfo['slidingInterval'] = sc['SI']\n dfo['localMinimum'] = sc['LM']\n\n # Rutledge, A.T., 1998. Computer Programs for Describing the Recession of Ground-Water Discharge and for Estimating Mean Ground-Water Recharge and Discharge from Streamflow Records-Update, Water-Resources Investigation Report 98-4148.\n pt = part(df.copy(), N)\n dfo['part1'] = pt.iloc[:, -3]\n dfo['part2'] = pt.iloc[:, -2]\n dfo['part3'] = pt.iloc[:, -1]\n\n # Clarifica Inc., 2002. Water Budget in Urbanizing Watersheds: Duffins Creek Watershed. Report prepared for the Toronto and Region Conservation Authority.\n dfo['Clarifica'] = clarifica(df)\n\n nc = len(dfo.columns)\n dfo['min'] = dfo.iloc[:,1:nc].min(axis=1)\n dfo['max'] = dfo.iloc[:,1:nc].max(axis=1)\n dfo['median'] = dfo.iloc[:,1:nc].median(axis=1)\n\n return dfo.iloc[:, -1] # returning median","repo_name":"maseology/pyDrology","sub_path":"hydrographSeparation.py","file_name":"hydrographSeparation.py","file_ext":"py","file_size_in_byte":10912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"28888691546","text":"import time\n\nimport win32gui\nimport win32process\nimport psutil\nimport os\n\n\nclass Window:\n @staticmethod\n def __killProcess(pid):\n try:\n os.system(\"TASKKILL /PID \" + str(pid) + \" /F\")\n except Exception as e:\n print(e)\n\n @staticmethod\n def killWindow():\n \"\"\"\n Kills the foreground or selected window\n \"\"\"\n foreground_window = win32gui.GetForegroundWindow()\n pid = win32process.GetWindowThreadProcessId(foreground_window)[1]\n if Window.__checkBlacklist(pid):\n Window.__killProcess(pid)\n\n @staticmethod\n def __checkBlacklist(window_pid):\n for process in psutil.process_iter():\n name = process.name()\n pid = process.pid\n if window_pid == pid and name == \"explorer.exe\":\n return False\n return True\n\n @staticmethod\n def killSimilarWindows():\n \"\"\"\n Kills all windows that have the same process name\n \"\"\"\n\n fg_window = win32gui.GetForegroundWindow()\n fg_pid = win32process.GetWindowThreadProcessId(fg_window)[1]\n process_name = psutil.Process(fg_pid).name()\n\n for process in psutil.process_iter():\n name = process.name()\n pid = process.pid\n if name == process_name:\n # pids.append(pid)\n Window.__killProcess(pid)\n","repo_name":"NicoHeinola/SuperAltF4","sub_path":"window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"28244858950","text":"import time\nfrom operator import itemgetter\nimport click\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\ntorch.manual_seed(1234)\nnp.random.seed(3456)\ntorch.set_printoptions(precision=3, sci_mode=False)\n\n\n####\n\ndata_size = 1000\ntrain_split = 0.8\nb_size = 64\nstate_shape = (3, 80, 80)\nn_actions = 5\ntraining_steps = 100\nlr = 0.01\n\n####\n\n\nclass DataLoader():\n\n def __init__(self, inputs, targets):\n assert len(inputs) == len(targets)\n self.inputs = inputs\n self.targets = targets\n self.size = len(inputs)\n self.stream = np.arange(self.size)\n np.random.shuffle(self.stream)\n self.head = 0\n self.active = True\n \n def reset(self):\n np.random.shuffle(self.stream)\n self.head = 0\n self.active = True\n \n def get_batch(self, n):\n if not self.active:\n raise ValueError('DataLoader is not active; try reset.')\n \n b = self.stream[self.head: self.head + n]\n self.head += n\n if self.head >= self.size:\n self.active = False\n \n return torch.stack(itemgetter(*b)(self.inputs)), torch.stack(itemgetter(*b)(self.targets))\n\n\nclass Net(nn.Module):\n\n def __init__(self, state_shape, n_actions):\n super().__init__()\n\n self.state_shape = [1] + list(state_shape) # --> (batch, 3, w, h)\n self.n_actions = n_actions\n\n self.features = nn.Sequential(\n nn.Conv2d(3, 16, 8, 1),\n nn.Conv2d(16, 16, 4, 1)\n )\n\n self.proj = nn.Sequential(\n nn.Linear(self._n_features(), 64),\n nn.GELU(),\n nn.Linear(64, self.n_actions)\n )\n\n self.features.apply(self._module_init)\n self.proj.apply(self._module_init)\n \n def _n_features(self):\n return self.features(torch.zeros(self.state_shape)).view(-1).size(0)\n \n def _module_init(self, module):\n if isinstance(module, nn.Linear) or isinstance(module, nn.Conv2d):\n nn.init.normal_(module.weight, mean=0, std=0.2)\n if module.bias is not None:\n nn.init.zeros_(module.bias)\n \n def forward(self, x):\n x = self.features(x)\n x = self.proj(x.view(x.size(0), -1))\n return x\n\n\ndef evaluate(model, data_loader, device):\n data_loader.reset()\n losses = []\n while data_loader.active:\n x, y = data_loader.get_batch(512)\n x, y = x.squeeze(1), y.squeeze(1)\n x, y = x.to(device), y.to(device)\n q = model(x)\n loss = F.smooth_l1_loss(q, y)\n losses.append(loss.item() ** 0.5)\n return np.mean(losses)\n\n\ninputs = torch.randn(data_size, *state_shape)\ninputs = torch.tensor_split(inputs, data_size, dim=0)\ntargets = torch.ones(data_size, n_actions)\ntargets = torch.tensor_split(targets, data_size, dim=0)\n\nsplit = int(data_size * train_split)\ninputs_train = inputs[:split]\ninputs_val = inputs[split:]\ntargets_train = targets[:split]\ntargets_val = targets[split:]\n\ndata_loader_train = DataLoader(inputs_train, targets_train)\ndata_loader_val = DataLoader(inputs_val, targets_val)\n\nmodel = Net(state_shape, n_actions)\n\n\n@click.command()\n@click.option('--device', '-d', default='cpu', help=\"'cpu' or 'mps'\")\ndef worker(device):\n model.to(device)\n st = time.time()\n loss = evaluate(model, data_loader_val, device)\n print(f'initial loss: {round(loss, 3)}')\n\n optimizer = torch.optim.AdamW(model.parameters(), lr=lr)\n\n for k in range(training_steps):\n if not data_loader_train.active:\n data_loader_train.reset()\n \n x, y = data_loader_train.get_batch(b_size)\n x, y = x.squeeze(1), y.squeeze(1)\n x, y = x.to(device), y.to(device)\n q = model(x)\n loss = F.smooth_l1_loss(q, y)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if k % 10 == 0:\n loss = evaluate(model, data_loader_val, device)\n print(f'after step: {k} | loss: {round(loss, 3)}')\n\n loss = evaluate(model, data_loader_val, device)\n print(f'step {training_steps} | loss: {round(loss, 3)}')\n et = time.time()\n process_time = et - st\n print(f\"-----\\nTime: {round(process_time, 2)} seconds\\n-----\")\n\n\nif __name__ == '__main__':\n worker()\n","repo_name":"fatemi/mactest","sub_path":"mac_test.py","file_name":"mac_test.py","file_ext":"py","file_size_in_byte":4285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"25145583520","text":"\ndef produsScalar(v1,v2):\n suma=0\n #verificam daca au acelasi numar de elemente\n if(len(v1)==len(v2)):\n for i in range(0,len(v1)):\n #facem produsul scalar al vectorilor\n suma = suma + v1[i]*v2[i]\n return suma\n\n\nassert (produsScalar([0], [0]) == 0)\nassert (produsScalar([1,0,2,0,3], [1,2,0,3,1]) == 4)\nassert(produsScalar([1,0,2,0,3,1,0,70,9,0,43,0,12,0,0,0,7,0], [0,2,0,3,1,1,0,70,9,0,0,21,2,0,12,0,7,0]) == 5058)\n\n","repo_name":"DragosMoro/UBB-Computer-Science","sub_path":"Semester 4/Artificial Intelligence/Lab1/pb3.py","file_name":"pb3.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"34812192713","text":"from dockerize.file import File\nimport dockerize.rabbitmq.dockerfile_generator as generator\n\nclass Dockerfile(File):\n def __init__(self, version, plugins, config_file, tracing=False, tracing_directory=''):\n self.config = {\n 'version': version,\n 'plugins': plugins,\n 'config_file': config_file,\n 'tracing': tracing,\n 'tracing_directory': tracing_directory\n }\n\n def write(self, fp):\n fp.write(generator.generate(self.config))\n","repo_name":"akerouanton/docker-generator","sub_path":"lib/dockerize/rabbitmq/files/dockerfile.py","file_name":"dockerfile.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"6"} +{"seq_id":"24221931712","text":"#Write program to find binomal coeffi. value (ncr) by taking n and r as input using a function for factorial of a number.\r\n\r\n\r\n\r\ndef factorial(n):\r\n f=1\r\n if n==0 or n==1:\r\n return f\r\n \r\n for i in range(2 , n+1):\r\n f=f*i\r\n return f\r\n\r\nn1=int(input(\"Provide values of n \"))\r\nr1=int(input(\"Provide values for r \"))\r\nncr=(factorial(n1))/(factorial(n1-r1)*factorial(r1))\r\nprint(\"Binomial coefficient ncr for n={} and r={} is:{}\".format(n1,r1,ncr))\r\n\r\n","repo_name":"anonymousknight07/Programs","sub_path":"#Write program to find binomal coeffi. v.py","file_name":"#Write program to find binomal coeffi. v.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"73027810749","text":"import data_manager as data\nimport numpy as np\nimport tables as tb\nimport model as models\nfrom keras.models import load_model\nfrom keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint\n\nnp.random.seed(123)\n\nclass Batcher():\n def __init__(self,product_counts,reviewer_counts,ratings,sent_counts,word_counts,spell_ratios,pos_dist,tfidf,embeddings,helpfulness,n=1):\n self.product_counts = product_counts\n self.reviewer_counts = reviewer_counts\n self.ratings = ratings\n self.sent_counts = sent_counts\n self.word_counts = word_counts\n self.spell_ratios = spell_ratios\n self.pos_dist = pos_dist\n self.tfidf = tfidf\n self.embeddings = embeddings\n self.helpfulness = helpfulness\n self.n = n\n\n self.size = len(helpfulness)\n\n self.validation_split = np.sort(np.random.choice(self.size, int(self.size * 0.15)))\n self.train_split = [i for i in range(self.size) if i not in self.validation_split]\n\n self.train_steps = len(self.train_split) // n\n self.validation_steps = len(self.validation_split) // n\n\n self.current_train_index = 0\n self.current_valid_index = 0\n\n\n def get_items(self, indices):\n features = {\n \"product_counts\": np.array([self.product_counts[i] for i in indices]),\n \"reviewer_counts\": np.array([self.reviewer_counts[i] for i in indices]),\n \"ratings\": np.array([self.ratings[i] for i in indices]),\n \"sent_counts\": np.array([self.sent_counts[i] for i in indices]),\n \"word_counts\": np.array([self.word_counts[i] for i in indices]),\n \"spell_ratios\": np.array([self.spell_ratios[i] for i in indices]),\n \"pos_dist\": np.array([self.pos_dist[i] for i in indices]),\n \"tfidf\": np.array([self.tfidf[i] for i in indices]),\n \"embeddings\": np.array([self.embeddings[i] for i in indices])\n }\n targets = {\n \"helpfulness\": np.array([self.helpfulness[i] for i in indices])\n }\n return features, targets\n\n def train_gen(self):\n train_size = len(self.train_split)\n np.random.shuffle(self.train_split)\n while True:\n if self.current_train_index >= train_size - self.n:\n self.current_train_index = 0\n np.random.shuffle(self.train_split)\n indices = self.train_split[self.current_train_index:self.current_train_index + self.n]\n self.current_train_index += self.n\n yield self.get_items(indices)\n\n def validation_gen(self):\n validation_size = len(self.validation_split)\n while True:\n if self.current_valid_index >= validation_size - self.n:\n self.current_valid_index = 0\n indices = self.validation_split[self.current_valid_index:self.current_valid_index + self.n]\n self.current_valid_index += self.n\n yield self.get_items(indices)\n\n def reset(self):\n self.current_train_index = 0\n self.current_valid_index = 0\n\n\narr_file = tb.open_file(\"data/docvecs.hdf\", \"r\", filters=tb.Filters(complib='zlib', complevel=0))\nembeddings = arr_file.create_earray(arr_file.root, \"docvecs\")\ntfidf = data.get_pickle(\"data/tfidf.pkl\").toarray()\nproduct_counts = np.array(data.get_pickle(\"data/product_review_counts.pkl\"))\nreviewer_counts = np.array(data.get_pickle(\"data/reviewer_review_counts.pkl\"))\nratings = np.array(data.get_pickle(\"data/ratings_disc.pkl\"))\nsent_counts = np.array(data.get_pickle(\"data/sent_counts_norm.pkl\"))\nword_counts = np.array(data.get_pickle(\"data/word_counts_norm.pkl\"))\nspell_ratios = np.array(data.get_pickle(\"data/spelling_ratios.pkl\"))\npos_dist = np.array(data.get_pickle(\"data/tags_bow_norm.pkl\"))\nhelpfulness = np.array(data.get_pickle(\"data/labels_disc.pkl\"))\n\nbatch_size = 128\nbatcher = Batcher(product_counts, reviewer_counts, ratings, sent_counts, word_counts, spell_ratios, pos_dist, tfidf,\n embeddings, helpfulness, batch_size)\n\n\ndef train_cnn():\n #model = load_model(\"data/models/cnn_double_chkpt.h5\")\n model = models.model_cnn()\n model.summary()\n\n tensorboard = TensorBoard(log_dir='./cnn1_graph', histogram_freq=0, write_graph=True, write_images=True)\n checkpoint = ModelCheckpoint(\"data/models/cnn_chkpt.h5\", monitor='val_loss', save_best_only=True, verbose=1, mode=\"min\")\n stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=1, verbose=1)\n\n model.fit_generator(batcher.train_gen(),\n steps_per_epoch=batcher.train_steps,\n validation_data=batcher.validation_gen(),\n validation_steps=batcher.validation_steps,\n epochs=8,\n callbacks=[tensorboard, checkpoint, stopping])\n\n model.save(\"data/models/cnn1.h5\")\n batcher.reset()\n model = load_model(\"data/models/cnn_chkpt.h5\")\n eval = model.evaluate_generator(batcher.validation_gen(), steps=batcher.validation_steps)\n print(\"CNN\", eval)\n\n batcher.reset()\n\n\ndef train_lstm():\n #model = load_model(\"data/models/original.h5\")\n model = models.model_original()\n model.summary()\n\n tensorboard = TensorBoard(log_dir='./lstm1_graph', histogram_freq=0, write_graph=True, write_images=True)\n checkpoint = ModelCheckpoint(\"data/models/lstm_chkpt.h5\", monitor='val_loss', save_best_only=True, verbose=1, mode=\"min\")\n stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=1, verbose=1)\n\n model.fit_generator(batcher.train_gen(),\n steps_per_epoch=batcher.train_steps,\n validation_data=batcher.validation_gen(),\n validation_steps=batcher.validation_steps,\n epochs=8,\n callbacks=[tensorboard, checkpoint, stopping])\n\n model.save(\"data/models/lstm1.h5\")\n batcher.reset()\n model = load_model(\"data/models/lstm_chkpt.h5\")\n eval = model.evaluate_generator(batcher.validation_gen(), steps=batcher.validation_steps)\n print(\"LSTM\", eval)\n\n batcher.reset()\n\n\ndef train_baseline():\n #model = load_model(\"data/models/baseline.h5\")\n\n model = models.baseline()\n model.summary()\n\n tensorboard = TensorBoard(log_dir='./baseline1_graph', histogram_freq=0, write_graph=True, write_images=True)\n checkpoint = ModelCheckpoint(\"data/models/baseline_chkpt.h5\", monitor='val_loss', save_best_only=True, verbose=1, mode=\"min\")\n stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=1, verbose=1)\n\n model.fit_generator(batcher.train_gen(),\n steps_per_epoch=batcher.train_steps,\n validation_data=batcher.validation_gen(),\n validation_steps=batcher.validation_steps,\n epochs=8,\n callbacks=[tensorboard, checkpoint, stopping])\n\n model.save(\"data/models/baseline1.h5\")\n batcher.reset()\n model = load_model(\"data/models/baseline_chkpt.h5\")\n eval = model.evaluate_generator(batcher.validation_gen(), steps=batcher.validation_steps)\n print(\"BASELINE\", eval)\n\n batcher.reset()\n\n\nif __name__ == '__main__':\n train_baseline()\n train_lstm()\n train_cnn()","repo_name":"jgombac/amazon-helpfulness-classification","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"20649205412","text":"import pygad\nimport math\nimport time\n\nlabirynth = [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],\n [1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1],\n [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1],\n [1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1],\n [1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1],\n [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1],\n [1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1],\n [1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1],\n [1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1],\n [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1],\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n ]\n\n#definiujemy parametry chromosomu\ngene_space = [0, 1, 2, 3]\n\ndef fitness_func(solution, solution_idx):\n current_position = [1, 1]\n finish_position = [10, 10]\n for direction in solution:\n if direction == 0 and labirynth[current_position[0] - 1][current_position[1]] != 1:\n current_position = [current_position[0] - 1, current_position[1]]\n if direction == 1 and labirynth[current_position[0]][current_position[1] + 1] != 1:\n current_position = [current_position[0], current_position[1] + 1]\n if direction == 2 and labirynth[current_position[0] + 1][current_position[1]] != 1:\n current_position = [current_position[0] + 1, current_position[1]]\n if direction == 3 and labirynth[current_position[0]][current_position[1] - 1] != 1:\n current_position = [current_position[0], current_position[1] - 1]\n\n distance = math.sqrt((finish_position[0] - current_position[0]) ** 2 + (finish_position[1] - current_position[1]) ** 2)\n return -distance\n\nfitness_function = fitness_func\n\n#ile chromsomĂłw w populacji\n#ile genow ma chromosom\nsol_per_pop = 200\nnum_genes = 30\n\n#ile wylaniamy rodzicow do \"rozmanazania\" (okolo 50% populacji)\n#ile pokolen\n#ilu rodzicow zachowac (kilka procent)\nnum_parents_mating = 100\nnum_generations = 100\nkeep_parents = 10\n\n#jaki typ selekcji rodzicow?\n#sss = steady, rws=roulette, rank = rankingowa, tournament = turniejowa\nparent_selection_type = \"sss\"\n\n#w il =u punktach robic krzyzowanie?\ncrossover_type = \"single_point\"\n\n#mutacja ma dzialac na ilu procent genow?\n#trzeba pamietac ile genow ma chromosom\nmutation_type = \"random\"\nmutation_percent_genes = 4\n\n#inicjacja algorytmu z powyzszymi parametrami wpisanymi w atrybuty\nga_instance = pygad.GA(gene_space=gene_space,\n num_generations=num_generations,\n num_parents_mating=num_parents_mating,\n fitness_func=fitness_function,\n sol_per_pop=sol_per_pop,\n num_genes=num_genes,\n parent_selection_type=parent_selection_type,\n keep_parents=keep_parents,\n crossover_type=crossover_type,\n mutation_type=mutation_type,\n mutation_percent_genes=mutation_percent_genes,\n stop_criteria=[\"reach_0\"])\n\n#uruchomienie algorytmu\nstart = time.time()\nga_instance.run()\nend = time.time()\nprint(\"Algorythm ran for: \", end - start)\n\ntimes = [0.0989992618560791, 0.14099836349487305, 0.17300057411193848, 0.18200016021728516, 0.10799932479858398,\n 0.1470189094543457, 0.10000014305114746, 0.1640026569366455, 0.1900038719177246, 0.14800047874450684]\n\ntime_sum = 0\nfor time in times:\n time_sum += time\n\nprint(\"Average algorythm execution time after 10 runs: \", time_sum / 10)\n\n#podsumowanie: najlepsze znalezione rozwiazanie (chromosom+ocena)\nsolution, solution_fitness, solution_idx = ga_instance.best_solution()\nprint(\"Parameters of the best solution : {solution}\".format(solution=solution))\nprint(\"Fitness value of the best solution = {solution_fitness}\".format(solution_fitness=solution_fitness))\n\n\n#wyswietlenie wykresu: jak zmieniala sie ocena na przestrzeni pokolen\nga_instance.plot_fitness()","repo_name":"igorpustovoy/inteligencja_obliczeniowa","sub_path":"lab03/zad3.py","file_name":"zad3.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"44241683744","text":"class zoom_colorbar:\n \"\"\" a zoomable colorbar based on matplotlib colorbar\n (changes the color mapping of the image it is attached to)\n NOTE: also enables mouse zoom on image it is attached to.\n \"\"\"\n\n def __init__(self, im=None):\n \"\"\"if figure.image is not passed as parameter,\n use current image\"\"\"\n from pylab import colorbar, gci\n if im == None:\n im = gci()\n\n ax = im.axes\n cb = colorbar(im, ax=ax)\n self.colorbar_instance = cb\n canvas = ax.figure.canvas\n if not hasattr(canvas,'_colorbars'):\n canvas._colorbars = {}\n canvas._colorbars[cb.ax] = cb\n canvas.mpl_connect('scroll_event', self.onWheel)\n return\n\n def onWheel(self,event):\n \"\"\"\n Process mouse wheel as zoom events\n \"\"\"\n from matplotlib import colors\n\n ax = event.inaxes\n try:\n step = event.step\n except:\n if event.button == 'up':\n step = 1\n else:\n step = -1\n #print \"zoom\",step\n\n # Ick! Can't tell if the axes contains a colorbar.\n if hasattr(event.canvas,'_colorbars') and ax in event.canvas._colorbars:\n mappable = event.canvas._colorbars[ax].mappable\n # rescale colormap: the axes are already scaled to 0..1,\n # so use bal instead of pt for centering\n lo,hi = mappable.get_clim()\n if isinstance(mappable.norm, colors.LogNorm):\n vscale = 'log'\n else:\n vscale = 'linear'\n lo,hi = self._rescale(lo,hi,step,bal=event.ydata,scale=vscale)\n mappable.set_clim(lo,hi)\n\n elif ax != None:\n # Event occurred inside a plotting area\n lo,hi = ax.get_xlim()\n lo,hi = self._rescale(lo,hi,step,pt=event.xdata,scale=ax.get_xscale())\n ax.set_xlim((lo,hi))\n\n lo,hi = ax.get_ylim()\n lo,hi = self._rescale(lo,hi,step,pt=event.ydata,scale=ax.get_yscale())\n ax.set_ylim((lo,hi))\n else:\n # Check if zoom happens in the axes\n xdata,ydata = None,None\n x,y = event.x,event.y\n for ax in event.canvas.figure.get_axes():\n if ax.xaxis.contains(event):\n xdata,_ = ax.transAxes.inverted().transform_point((x,y))\n #print \"xaxis\",x,\"->\",xdata\n if ax.yaxis.contains(event):\n _,ydata = ax.transAxes.inverted().transform_point((x,y))\n #print \"yaxis\",y,\"->\",ydata\n if xdata is not None:\n lo,hi = ax.get_xlim()\n lo,hi = self._rescale(lo,hi,step,bal=xdata,scale=ax.get_xscale())\n ax.set_xlim((lo,hi))\n if ydata is not None:\n lo,hi = ax.get_ylim()\n lo,hi = self._rescale(lo,hi,step,bal=ydata,scale=ax.get_yscale())\n ax.set_ylim((lo,hi))\n\n event.canvas.draw_idle()\n\n def _rescale(self,lo,hi,step,pt=None,bal=None,scale='linear'):\n \"\"\"\n Rescale (lo,hi) by step, returning the new (lo,hi)\n The scaling is centered on pt, with positive values of step\n driving lo/hi away from pt and negative values pulling them in.\n If bal is given instead of point, it is already in [0,1] coordinates.\n\n This is a helper function for step-based zooming.\n \"\"\"\n # Convert values into the correct scale for a linear transformation\n # TODO: use proper scale transformers\n if scale=='log':\n lo,hi = math.log10(lo),math.log10(hi)\n if pt is not None: pt = math.log10(pt)\n\n # Compute delta from axis range * %, or 1-% if percent is negative\n if step > 0:\n delta = float(hi-lo)*step/100\n else:\n delta = float(hi-lo)*step/(100-step)\n\n # Add scale factor proportionally to the lo and hi values, preserving the\n # point under the mouse\n if bal is None:\n bal = float(pt-lo)/(hi-lo)\n lo = lo - bal*delta\n hi = hi + (1-bal)*delta\n\n # Convert transformed values back to the original scale\n if scale=='log':\n lo,hi = math.pow(10.,lo),math.pow(10.,hi)\n\n return (lo,hi)\n","repo_name":"reflectometry/osrefl","sub_path":"osrefl/viewers/zoom_colorbar.py","file_name":"zoom_colorbar.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"6"} +{"seq_id":"19154617272","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport shutil\n\n\nclass Grapher:\n def __init__(self, analyzer):\n self.analyzer = analyzer\n self.create_img_directory()\n\n def create_img_directory(self):\n if os.path.exists(self.analyzer.output_path + \"/img\"):\n shutil.rmtree(self.analyzer.output_path + \"/img\")\n if not os.path.exists(self.analyzer.output_path + \"/img\"):\n os.makedirs(self.analyzer.output_path + \"/img\")\n\n def run_all(self):\n self.gen_graph_for_words_per_sentence()\n self.gen_graph_for_usage_of_words()\n self.gen_graph_how_hard_do_i_suck()\n\n def gen_graph_for_words_per_sentence(self):\n fig, ax = plt.subplots()\n ax.plot(self.analyzer.words_per_sentence)\n ax.set(xlabel='sentence', ylabel='words', title='words per sentence')\n ax.grid()\n fig.savefig(self.analyzer.output_path + \"/img/words_per_sentence.png\")\n plt.show()\n\n def gen_graph_for_usage_of_words(self):\n xvals = []\n yvals = []\n counter = 0\n for key in self.analyzer.usage_of_words:\n if counter > 10:\n break\n xvals.append(key)\n yvals.append(self.analyzer.usage_of_words[key])\n counter += 1\n\n fig, ax = plt.subplots()\n ax.bar(xvals, yvals, align='center', alpha=0.5)\n ax.set(title='Usage per word (top 10)', ylabel='Usage (n times)')\n fig.savefig(self.analyzer.output_path + \"/img/usage_of_words.png\")\n plt.show()\n\n def gen_graph_how_hard_do_i_suck(self):\n with plt.xkcd():\n fig = plt.figure()\n ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_ylim([-30, 10])\n\n data = np.ones(100)\n data[70:] -= np.arange(30)\n\n ax.annotate('THE MOMENT THE\\n SCRIPT REALISES YOU\\n HAVE {0} DUPLICATES\\n IN YOUR TEXT.'.format(self.analyzer.duplicates), xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))\n\n ax.plot(data)\n\n ax.set_xlabel('TIME')\n ax.set_ylabel('QUALITY OF YOUR TEXT')\n fig.text(0.5, 0.05, '\"Text Quality\"', ha=\"center\")\n fig.savefig(self.analyzer.output_path + \"/img/suck.png\")\n fig.set_tight_layout(False)\n\n plt.show()\n","repo_name":"Supporterino/TextAnalyzer","sub_path":"lib/grapher.py","file_name":"grapher.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"6"} +{"seq_id":"3875398485","text":"from spectra.models import db\r\n\r\nclass Manager_salespeople(db.Model):\r\n __tablename__ = 'managers_salespeople'\r\n\r\n id = db.Column(db.Integer, primary_key=True)\n manager_id = db.Column(db.Integer)\n salesperson_id = db.Column(db.Integer)\r\n\r\n def __init__(self, manager_id, salesperson_id):\n self.manager_id = manager_id\n self.salesperson_id = salesperson_id\n\r\n def __repr__(self):\r\n return ''.format(self.complainer_id, self.user_id)\r\n","repo_name":"irubnich/spectra","sub_path":"spectra/models/managers_salespeople.py","file_name":"managers_salespeople.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"32480562539","text":"from __future__ import (absolute_import, division, print_function)\n\nimport sys\nimport presenter\nimport view\n\nimport unittest\nfrom mantid.py3compat import mock\n\nclass PresenterTest(unittest.TestCase):\n def setUp(self):\n self.view = mock.create_autospec(view.View)\n\n # mock view\n self.view.plotSignal = mock.Mock()\n self.view.getColour = mock.Mock(return_value=\"black\")\n self.view.getGridLines =mock.Mock(return_value=True)\n self.view.getFreq =mock.Mock(return_value=3.14)\n self.view.getPhase =mock.Mock(return_value=0.56)\n self.view.buttonPressed = mock.Mock()\n self.view.setTableRow = mock.Mock()\n self.view.addWidgetToTable = mock.Mock()\n self.view.addITemToTable = mock.Mock()\n\n self.presenter = presenter.Presenter(self.view)\n\n def test_updatePlot(self):\n self.presenter.updatePlot()\n assert(self.view.getColour.call_count == 1)\n assert(self.view.getGridLines.call_count == 1)\n assert(self.view.getFreq.call_count == 1)\n assert(self.view.getPhase.call_count == 1)\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"margauxln/pythonMVP","sub_path":"1er exo/presenter_test.py","file_name":"presenter_test.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"30133881902","text":"############### Blackjack Project #####################\n############### Our Blackjack House Rules #####################\n\n## The deck is unlimited in size. \n## There are no jokers. \n## The Jack/Queen/King all count as 10.\n## The the Ace can count as 11 or 1.\n## Use the following list as the deck of cards:\n## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n## The cards in the list have equal probability of being drawn.\n## Cards are not removed from the deck as they are drawn.\n## The computer is the dealer.\nfrom art import logo\nimport random\ndef deal_card():\n cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n return(random.choice(cards))\n\ndef game_play():\n print(logo)\n user_cards = []\n computer_cards = []\n user_score = 0\n computer_score = 0 \n\n user_cards.append(deal_card()) \n user_cards.append(deal_card()) \n user_score = sum(user_cards)\n print(f\"Your cards: {user_cards}, current score: {user_score}\")\n computer_cards.append(deal_card())\n computer_score = computer_cards[0]\n print(f\"Computer's first card: {computer_cards[0]}\")\n\n cards_continue = True\n while cards_continue:\n another_card = input(\"Type 'y' to get another card, type 'n' to pass: \").lower()\n if another_card == 'y':\n user_cards.append(deal_card())\n user_score += user_cards[-1]\n if user_score > 21 and 11 in user_cards:\n user_cards.remove(11)\n user_cards.append(1)\n user_score = sum(user_cards)\n print(f\"Your cards: {user_cards}, current score: {user_score}\")\n print(f\"Computer's first card: {computer_cards[0]}\")\n if another_card == 'n' or user_score > 21:\n cards_continue = False\n print(f\"Your final hand: {user_cards}, final score: {user_score}\")\n computer_cards.append(deal_card())\n computer_score += computer_cards[-1]\n while computer_score < 17:\n computer_cards.append(deal_card())\n computer_score += computer_cards[-1]\n if computer_score > 21 and 11 in computer_cards:\n computer_cards.remove(11)\n computer_cards.append(1)\n computer_score = sum(computer_cards)\n print(f\"Computer's final hand: {computer_cards}, final score: {computer_score}\")\n if user_score > 21:\n print(\"You went over. You lose!!!\")\n elif computer_score > 21:\n print(\"You win! computer went over.\")\n elif user_score > computer_score:\n print(\"You win\")\n elif user_score < computer_score:\n print(\"Computer wins! You lose\")\n else: \n print(\"its a draw\")\n\ngame_continue = True\nwhile game_continue:\n is_play = input(\"Do you want to play a game of Blackjack? Type 'y' or 'n': \").lower()\n if is_play == \"y\":\n game_play()\n else:\n game_continue = False\n","repo_name":"Divjot-kaur/python","sub_path":"blackjack game/blackjackgame_myversion.py","file_name":"blackjackgame_myversion.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"3690479765","text":"import numpy as np\nclass CSTRState:\n def __init__(self, volume, X, P, S):\n \"\"\"\n Define o volume da fase líquida e as concentrações\n de X, P e S no CSTR.\n \"\"\"\n self.volume = np.array([volume])\n self.X = np.array([X])\n self.P = np.array([P])\n self.S = np.array([S])","repo_name":"takenoto/pinn_la_casei_2023","sub_path":"domain/reactor/cstr_state.py","file_name":"cstr_state.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"17491718383","text":"import numpy as np\r\nimport pdb\r\n#####\r\n# author: Xiao Zhang\r\n#\r\n# Function Input \r\n# v M*N the value lies on grid point which is corresponding to the meshgrid coordinates \r\n# xq M1*N1 or M2 the query points x coordinates\r\n# yq M1*N1 or M2 the query points y coordinates\r\n# \r\n##########\r\n# Function Output\r\n# interpv , the interpolated value at querying coordinates xq, yq, it has the same size as xq and yq.\r\n##########\r\n# For project 1, v = Mag\r\n# xq and yq are the coordinates of the interpolated location, i.e the coordinates computed based on the gradient orientation.\r\n\r\ndef interp2(v, xq, yq):\r\n dim_input = 1\r\n\r\n if len(xq.shape) == 2 or len(yq.shape) == 2:\r\n dim_input = 2\r\n q_h = xq.shape[0]\r\n q_w = xq.shape[1]\r\n xq = xq.flatten()\r\n yq = yq.flatten()\r\n\r\n h = v.shape[0]\r\n w = v.shape[1]\r\n if xq.shape != yq.shape:\r\n raise 'query coordinates Xq Yq should have same shape'\r\n\r\n\r\n x_floor = np.floor(xq).astype(np.int32)\r\n y_floor = np.floor(yq).astype(np.int32)\r\n x_ceil = np.ceil(xq).astype(np.int32)\r\n y_ceil = np.ceil(yq).astype(np.int32)\r\n\r\n x_floor[x_floor<0] = 0\r\n y_floor[y_floor<0] = 0\r\n x_ceil[x_ceil<0] = 0\r\n y_ceil[y_ceil<0] = 0\r\n\r\n x_floor[x_floor>=w-1] = w-1\r\n y_floor[y_floor>=h-1] = h-1\r\n x_ceil[x_ceil>=w-1] = w-1\r\n y_ceil[y_ceil>=h-1] = h-1\r\n\r\n v1 = v[y_floor, x_floor]\r\n v2 = v[y_floor, x_ceil]\r\n v3 = v[y_ceil, x_floor]\r\n v4 = v[y_ceil, x_ceil]\r\n\r\n lh = yq - y_floor\r\n lw = xq - x_floor\r\n hh = 1 - lh\r\n hw = 1 - lw\r\n\r\n w1 = hh * hw\r\n w2 = hh * lw\r\n w3 = lh * hw\r\n w4 = lh * lw\r\n\r\n interp_val = v1 * w1 + w2 * v2 + w3 * v3 + w4 * v4\r\n\r\n if dim_input == 2:\r\n return interp_val.reshape(q_h,q_w)\r\n return interp_val","repo_name":"marissacomo/CIS581-Project3A","sub_path":"CIS581-Project3A/Submission/Video_Mosaicing/interp2.py","file_name":"interp2.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"73900789947","text":"from function import *\r\n\r\nstop = False\r\n\r\nwhile not stop:\r\n\r\n answer = input(\"Type 'encode' to encrypt, type 'decode' tp decrypt:\\n> \").lower().strip(\" \")\r\n message = input('Type your message:\\n> ').lower()\r\n shift = int(input('Type the shift number:\\n> '))\r\n shift = shift % 26\r\n\r\n ceasar(txt=message, shift_num=shift, direct=answer)\r\n\r\n # to end the while loop:\r\n if input(\"Type 'yes' if you want to go again. Otherwise type 'no'.\\n> \"\r\n ).lower() == 'no':\r\n print('Goodbye')\r\n stop = True\r\n else:\r\n continue\r\n","repo_name":"Onovez/Ceasar-Cipher","sub_path":"A000001 - Caesar Cipher/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"34140513054","text":"#################################################################################\r\n# #\r\n# CoinpAgent.py #\r\n# #\r\n# The software is licensed Creative Commons CC-BY-NC-SA. Under this agreement #\r\n# you are authorized to use, share on the same rights or edit this software #\r\n# for personnal purpose only. You are not allow to sell this software. #\r\n# #\r\n# Official Website : https://coinpaign.com #\r\n# Contact : romain.guihot@gmail.com\r\n\r\n# This module is installed in computers to be managed by Remote Administrator. #\r\n# Function: #\r\n# 1. Send some of computer-informations to Remote Administrator. #\r\n# information: Country, city, LAN IP, WAN IP, OS, User, CPU, RAM #\r\n# 2. Server operation for Reverse Shell #\r\n# #\r\n#################################################################################\r\n\r\nimport os\r\nimport socket\r\nimport platform\r\nimport psutil\r\n\r\nfrom urllib.request import urlopen\r\nimport json\r\nimport netifaces\r\nimport requests\r\nimport subprocess\r\nimport getpass\r\n\r\nimport cpuinfo\r\n\r\ndef server_program():\r\n\r\n # Getting WAN IP \r\n try:\r\n data = json.loads(urlopen(\"https://ip.seeip.org/jsonip\").read())\r\n except:\r\n data = json.loads(urlopen(\"http://ip.jsontest.com/\").read())\r\n wan = data[\"ip\"]\r\n \r\n # Getting CPU & User Session information \r\n os = platform.system()\r\n if os == \"Windows\":\r\n # Getting CPU Information\r\n cpuin = cpuinfo.cpu.info\r\n cpu = cpuin[0]['ProcessorNameString']\r\n # Getting User Session\r\n user = subprocess.check_output([\"WMIC\", \"ComputerSystem\", \"GET\", \"UserName\"], universal_newlines = True)\r\n _, username = user.strip().rsplit(\"\\n\", 1)\r\n Com_user = username.rsplit(\"\\\\\", 1)\r\n userSession = Com_user[1] \r\n if os == \"Linux\":\r\n # Getting CPU Information\r\n cpuin = cpuinfo.cpu.info\r\n cpu = cpuin[0]['model name']\r\n # Getting User Session\r\n userSession = getpass.getuser()\r\n \r\n # Getting Country & City\r\n ccdata = requests.get('https://ipinfo.io/'+wan+'/geo')\r\n content = ccdata.text\r\n obj = json.loads(content)\r\n city = obj['city']\r\n country = obj['country']\r\n \r\n # Getting CPU Core Number\r\n cpu_core = len(cpuin)\r\n \r\n # Getting RAM Size\r\n mem = psutil.virtual_memory()\r\n memory = mem.total\r\n \r\n # Getting Local IP\r\n interfaces = netifaces.interfaces()\r\n gws=netifaces.gateways()\r\n fg = gws['default']\r\n sg = fg[2]\r\n aa = sg[0].split('.')\r\n subnet = aa[0]+\".\"+aa[1]+\".\"+aa[2]\r\n \r\n UserIP = []\r\n ii = 0\r\n for i in interfaces: \r\n if i == 'lo':\r\n continue\r\n iface = netifaces.ifaddresses(i).get(netifaces.AF_INET)\r\n if iface != None:\r\n for j in iface:\r\n UserIP.append(j['addr'])\r\n ii = ii+1\r\n for ip in UserIP:\r\n sub = ip.split(\".\")\r\n subip = sub[0]+\".\"+sub[1]+\".\"+sub[2]\r\n if subip == subnet:\r\n host = ip\r\n\r\n \r\n # Sending data to Client\r\n port = 8085 # initiate port no above 1024\r\n cmd_send = country + \":\" + city + \":\" + str(host) + \"/\" + str(wan) + \":\" + str(userSession) + \":\" + \"Connected\" + \":\" + str(os) + \":\" + str(cpu) + \":\" + str(cpu_core) + \":\" + str(memory)\r\n print(cmd_send)\r\n server_socket = socket.socket() # get instance\r\n server_socket.bind((host, port)) # bind host address and port together\r\n\r\n while True: # receive data stream. it won't accept data packet greater than 1024 bytes\r\n # configure how many client the server can listen simultaneously\r\n server_socket.listen(10)\r\n conn, address = server_socket.accept() # accept new connection\r\n print(\"Connection Established From : \" + str(address))\r\n\r\n head = conn.recv(10240).decode()\r\n \r\n if head == \"1\": # Send server informaion to GUI\r\n conn.send(cmd_send.encode()) # send data to the client\r\n print(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\r\n if head == \"2\": # Reverse shelll request Processing\r\n key_cmd = \"\"\r\n while key_cmd.lower().strip() != 'exit':\r\n\r\n key_cmd = conn.recv(1024).decode() # receive instructions\r\n if key_cmd.lower().strip() != 'exit':\r\n if os == \"Linux\":\r\n if key_cmd.lower()[0:4] != 'ping':\r\n num = key_cmd.split(\" \")\r\n if len(num) == 2:\r\n if num[1] != '':\r\n key_cmd = \"ping -c 1 \" + num[1]\r\n\r\n cmd = subprocess.Popen(key_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)\r\n cmd_bytes = cmd.stdout.read() + cmd.stderr.read()\r\n cmd_str = str(os) + str(cmd_bytes)\r\n conn.send(cmd_str.encode())\r\n if os == \"Windows\":\r\n cmd_str = cmd_str.replace(\"\\\\r\\\\n\", \"\\n\")\r\n if os == \"Linux\":\r\n cmd_str = cmd_str.replace(\"\\\\n\", \"\\n\")\r\n print('Received From Controler : ' + key_cmd) # show in terminal\r\n print('Send To Controler : ' + cmd_str)\r\n\r\n conn.close() # close the connection\r\n\r\nif __name__ == '__main__':\r\n server_program()\r\n","repo_name":"romainvg/OCRP6","sub_path":"server/CoinpAgent.py","file_name":"CoinpAgent.py","file_ext":"py","file_size_in_byte":5849,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"6"} +{"seq_id":"34508854860","text":"\n# https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/discuss/1046953/Python-using-stacks\n\ndef remove_adjacent_duplicates(S):\n if not S:\n return S\n res = [S[0]]\n for curr in S[1:]: \n if res and curr == res[-1]:\n res.pop()\n else:\n res.append(curr)\n res = ''.join(res) \n return res\n\n\n\ndef removeDuplicates( S):\n \"\"\"\n :type S: str\n :rtype: str\n \"\"\"\n if not S: return s\n stack = []\n for ch in S:\n if stack and stack[-1]==ch: \n stack.pop()\n continue\n stack.append(ch)\n return \"\".join(stack)\n\n\n\nif __name__ == \"__main__\":\n s = 'acaaabbbacdddd'\n s = 'abccbccba'\n print(removeDuplicates(s))","repo_name":"ved93/deliberate-practice-challenges","sub_path":"code-everyday-challenge/n220_remove_adjacent_duplicate_pairs_leet.py","file_name":"n220_remove_adjacent_duplicate_pairs_leet.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"8665801594","text":"import os\nimport json\nfrom unittest import TestCase\nfrom unittest.mock import MagicMock, patch\n\nfrom me_articles_comments_likes_index import MeArticlesCommentsLikesIndex\nfrom tests_util import TestsUtil\n\n\nclass TestMeArticlesCommentsLikesIndex(TestCase):\n dynamodb = TestsUtil.get_dynamodb_client()\n\n @classmethod\n def setUpClass(cls):\n TestsUtil.set_all_tables_name_to_env()\n TestsUtil.delete_all_tables(cls.dynamodb)\n\n article_info_items = [\n {\n 'article_id': 'publicId0001',\n 'user_id': 'test01',\n 'status': 'public',\n 'sort_key': 1520150272000000\n },\n {\n 'article_id': 'publicId0002',\n 'user_id': 'test01',\n 'status': 'public',\n 'sort_key': 1520150272000000\n }\n ]\n TestsUtil.create_table(cls.dynamodb, os.environ['ARTICLE_INFO_TABLE_NAME'], article_info_items)\n\n cls.comment_items = [\n {\n 'comment_id': 'comment00001',\n 'article_id': 'publicId0001',\n 'user_id': 'test_user_01',\n 'sort_key': 1520150272000000,\n 'created_at': 1520150272,\n 'text': 'コメントの内容1'\n },\n {\n 'comment_id': 'comment00002',\n 'article_id': 'publicId0001',\n 'user_id': 'test_user_01',\n 'sort_key': 1520150272000001,\n 'created_at': 1520150272,\n 'text': 'コメントの内容2'\n },\n {\n 'comment_id': 'comment00003',\n 'article_id': 'publicId0001',\n 'user_id': 'test_user_02',\n 'sort_key': 1520150272000002,\n 'created_at': 1520150272,\n 'text': 'コメントの内容1'\n },\n {\n 'comment_id': 'comment00004',\n 'article_id': 'publicId0002',\n 'user_id': 'test_user_01',\n 'sort_key': 1520150272000004,\n 'created_at': 1520150272,\n 'text': 'コメントの内容4'\n },\n ]\n TestsUtil.create_table(cls.dynamodb, os.environ['COMMENT_TABLE_NAME'], cls.comment_items)\n\n comment_like_items = [\n {\n 'comment_id': 'comment00001',\n 'user_id': 'like_user_01',\n 'article_id': 'publicId0001',\n 'created_at': 1520150272\n },\n {\n 'comment_id': 'comment00001',\n 'user_id': 'like_user_02',\n 'article_id': 'publicId0001',\n 'created_at': 1520150272\n },\n {\n 'comment_id': 'comment00002',\n 'user_id': 'like_user_02',\n 'article_id': 'publicId0001',\n 'created_at': 1520150272\n },\n {\n 'comment_id': 'comment00003',\n 'user_id': 'like_user_01',\n 'article_id': 'publicId0001',\n 'created_at': 1520150272\n },\n {\n 'comment_id': 'comment00004',\n 'user_id': 'like_user_01',\n 'article_id': 'publicId0002',\n 'created_at': 1520150272\n }\n ]\n TestsUtil.create_table(cls.dynamodb, os.environ['COMMENT_LIKED_USER_TABLE_NAME'], comment_like_items)\n\n @classmethod\n def tearDownClass(cls):\n TestsUtil.delete_all_tables(cls.dynamodb)\n\n def assert_bad_request(self, params):\n response = MeArticlesCommentsLikesIndex(event=params, context={}, dynamodb=self.dynamodb).main()\n self.assertEqual(response['statusCode'], 400)\n\n def test_main_ok(self):\n params = {\n 'pathParameters': {\n 'article_id': 'publicId0001'\n },\n 'requestContext': {\n 'authorizer': {\n 'claims': {\n 'cognito:username': 'like_user_01'\n }\n }\n }\n }\n\n response = MeArticlesCommentsLikesIndex(event=params, context={}, dynamodb=self.dynamodb).main()\n\n expected_items = [self.comment_items[0]['comment_id'], self.comment_items[2]['comment_id']]\n\n self.assertEqual(response['statusCode'], 200)\n self.assertEqual(sorted(json.loads(response['body'])['comment_ids']), sorted(expected_items))\n\n def test_main_with_no_likes(self):\n params = {\n 'pathParameters': {\n 'article_id': 'publicId0002'\n },\n 'requestContext': {\n 'authorizer': {\n 'claims': {\n 'cognito:username': 'test_user_id02'\n }\n }\n }\n }\n\n response = MeArticlesCommentsLikesIndex(event=params, context={}, dynamodb=self.dynamodb).main()\n\n expected_items = []\n\n self.assertEqual(response['statusCode'], 200)\n self.assertEqual(json.loads(response['body'])['comment_ids'], expected_items)\n\n def test_call_validate_article_existence(self):\n params = {\n 'pathParameters': {\n 'article_id': 'publicId0001'\n }\n }\n\n mock_lib = MagicMock()\n with patch('me_articles_comments_likes_index.DBUtil', mock_lib):\n MeArticlesCommentsLikesIndex(event=params, context={}, dynamodb=self.dynamodb).main()\n args, kwargs = mock_lib.validate_article_existence.call_args\n\n self.assertTrue(mock_lib.validate_article_existence.called)\n self.assertTrue(args[0])\n self.assertTrue(args[1])\n self.assertEqual(kwargs['status'], 'public')\n\n def test_validation_article_id_none(self):\n params = {\n 'pathParameters': {\n 'article_id': None\n },\n 'requestContext': {\n 'authorizer': {\n 'claims': {\n 'cognito:username': 'test_user_id01'\n }\n }\n }\n }\n\n self.assert_bad_request(params)\n\n def test_validation_article_id_max(self):\n params = {\n 'pathParameters': {\n 'article_id': 'A' * 13\n },\n 'requestContext': {\n 'authorizer': {\n 'claims': {\n 'cognito:username': 'test_user_id01'\n }\n }\n }\n }\n\n self.assert_bad_request(params)\n","repo_name":"AlisProject/serverless-application","sub_path":"tests/handlers/me/articles/comments/likes/index/test_me_articles_comments_likes_index.py","file_name":"test_me_articles_comments_likes_index.py","file_ext":"py","file_size_in_byte":6639,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"6"} +{"seq_id":"24405526902","text":"import sublime\nimport sublime_plugin\nfrom .generic_shell import GenericShell\nfrom .QuickMenu.QuickMenu import QuickMenu\nfrom .macro import Macro\nfrom .progress import ThreadProgress\nfrom .settings import Settings\nfrom .unit_collections import UnitCollections\n\n\nTERMINALITY_VERSION = \"0.3.10\"\n\n\ndef plugin_loaded():\n Settings.reset()\n Settings.startup()\n print(\"[Terminality] v%s\" % (TERMINALITY_VERSION))\n\n\nclass TerminalityRunCommand(sublime_plugin.WindowCommand):\n def parse_list(self, in_list, macros):\n out_list = []\n for value in in_list:\n if isinstance(value, str):\n value = Macro.parse_macro(\n string=value,\n custom_macros=macros\n )\n elif (isinstance(value, list) or\n isinstance(value, tuple)):\n value = self.parse_list(value, macros)\n elif isinstance(value, dict):\n value = self.parse_dict(value, macros)\n out_list.append(value)\n return out_list\n\n def parse_dict(self, in_dict, macros):\n for key in in_dict:\n if isinstance(in_dict[key], str):\n in_dict[key] = Macro.parse_macro(\n string=in_dict[key],\n custom_macros=macros\n )\n elif (isinstance(in_dict[key], list) or\n isinstance(in_dict[key], tuple)):\n in_dict[key] = self.parse_list(in_dict[key], macros)\n elif isinstance(in_dict[key], dict):\n in_dict[key] = self.parse_dict(in_dict[key], macros)\n return in_dict\n\n def run(self, selector=None, action=None, arguments_title=None):\n if arguments_title is None or arguments_title == \"\":\n self.run_command(selector, action)\n return\n self.window.show_input_panel(\n caption=arguments_title + \":\",\n initial_text=\"\",\n on_done=lambda args: self.run_command(\n selector=selector,\n action=action,\n arguments=args\n ),\n on_change=None,\n on_cancel=None\n )\n\n def run_command(self, selector=None, action=None, arguments=None):\n execution_unit = None\n execution_units = UnitCollections.load_default_collections()\n # Global\n additional_execution_units = Settings.get_global(\n \"execution_units\",\n default=Settings.get_global(\n \"additional_execution_units\",\n default={}\n )\n )\n for sel in [x for x in [\"*\", selector] if x is not None]:\n if (sel in additional_execution_units and\n action in additional_execution_units[sel]):\n execution_unit = additional_execution_units[sel][action]\n if not isinstance(execution_unit, dict):\n continue\n # Local\n additional_execution_units = Settings.get_local(\n \"execution_units\",\n default=Settings.get_local(\n \"additional_execution_units\",\n default={}\n )\n )\n for sel in [x for x in [\"*\", selector] if x is not None]:\n if (sel in additional_execution_units and\n action in additional_execution_units[sel]):\n execution_unit = additional_execution_units[sel][action]\n if not isinstance(execution_unit, dict):\n continue\n elif (sel in execution_units and\n action in execution_units[sel]):\n execution_unit = execution_units[sel][action]\n if not isinstance(execution_unit, dict):\n continue\n if execution_unit is None:\n sublime.error_message(\"There is no such execution unit\")\n return\n if not isinstance(execution_unit, dict):\n if Settings.get(\"debug\"):\n print(\"Execution unit is ignored [%s][%s]\" % (selector, action))\n return\n command = None\n command_type = None\n for key in [\"command\", \"window_command\", \"view_command\"]:\n if key in execution_unit:\n command_type = key\n command = execution_unit[key]\n break\n if not command:\n sublime.error_message(\"No command to run\")\n return\n\n custom_macros = {}\n required_macros = []\n if \"macros\" in execution_unit:\n custom_macros = execution_unit[\"macros\"]\n if \"required\" in execution_unit:\n required_macros = execution_unit[\"required\"]\n if \"location\" not in execution_unit:\n execution_unit[\"location\"] = \"$working\"\n\n is_not_windows = sublime.platform() != \"windows\"\n command_script = [Macro.parse_macro(\n string=cmd,\n custom_macros=custom_macros,\n required=required_macros,\n escaped=is_not_windows,\n arguments=arguments\n ) for cmd in command.split(\" \")]\n\n if command_type == \"window_command\" or command_type == \"view_command\":\n args = {}\n if \"args\" in execution_unit:\n args = execution_unit[\"args\"]\n args = self.parse_dict(args, custom_macros)\n if command_type == \"window_command\":\n self.window.run_command(\" \".join(command_script), args)\n else:\n self.window.active_view().run_command(\n \" \".join(command_script),\n args\n )\n elif command_type == \"command\":\n working_dir = Macro.parse_macro(\n string=execution_unit[\"location\"],\n custom_macros=custom_macros,\n required=required_macros,\n arguments=arguments\n )\n if working_dir is None:\n sublime.error_message(\n \"Working directory is invalid\"\n )\n return\n\n if Settings.get(\"debug\"):\n print(\"Running \\\"%s\\\"\" % (\" \".join(command_script)))\n print(\"Working dir is \\\"%s\\\"\" % (working_dir))\n\n self.view = self.window.new_file()\n self.view.set_name(\"Running...\")\n self.view.set_scratch(True)\n if is_not_windows:\n command_script = \" \".join(command_script)\n shell = GenericShell(\n cmds=command_script,\n view=self.view,\n on_complete=lambda e, r, p: self.on_complete(\n e, r, p, execution_unit\n ),\n no_echo=(\"no_echo\" in execution_unit and\n execution_unit[\"no_echo\"]),\n read_only=(\"read_only\" in execution_unit and\n execution_unit[\"read_only\"])\n )\n shell.set_cwd(working_dir)\n shell.start()\n ThreadProgress(\n thread=shell,\n message=\"Running\",\n success_message=\"Terminal has been stopped\",\n set_status=self.set_status,\n view=self.view\n )\n elif Settings.get(\"debug\"):\n print(\"Invalid command type\")\n\n def on_complete(self, elapse_time, return_code, params, execution_unit):\n if return_code is not None:\n self.view.set_name(\n \"Terminal Ended (Return: {0}) [{1:.2f}s]\".format(\n return_code, elapse_time\n )\n )\n if (\"close_on_exit\" in execution_unit and\n execution_unit[\"close_on_exit\"]):\n self.view.window().focus_view(self.view)\n self.view.window().run_command(\"close\")\n sublime.set_timeout(lambda: self.set_status(), 3000)\n\n def set_status(self, status=None):\n for window in sublime.windows():\n for view in window.views():\n if status is None:\n view.erase_status(\"Terminality\")\n else:\n view.set_status(\"Terminality\", status)\n\n\nclass TerminalityCommand(sublime_plugin.WindowCommand):\n\n \"\"\"\n Command to show menu which use to run another command\n \"\"\"\n\n qm = None\n ready_retry = 0\n\n main_menu = {\n \"items\": [[\"Terminality\", \"v\" + TERMINALITY_VERSION]],\n \"actions\": [\"\"]\n }\n\n def get_execution_units(self, execution_units_map, selector):\n execution_units = {}\n # Default Execution Units\n for selector_name in [x for x in [\"*\", selector] if x is not None]:\n if selector_name in execution_units_map:\n for action in execution_units_map[selector_name]:\n execution_units[action] = execution_units_map[\n selector_name\n ][action]\n for selector_name in [x for x in [\"*\", selector] if x is not None]:\n # Global\n additional_execution_units = Settings.get_global(\n \"execution_units\",\n default=Settings.get_global(\n \"additional_execution_units\",\n default={}\n )\n )\n if selector_name in additional_execution_units:\n additional_execution_units = additional_execution_units[\n selector_name\n ]\n for key in additional_execution_units:\n if (key in execution_units and\n isinstance(additional_execution_units[key], dict)):\n for sub_key in additional_execution_units[key]:\n execution_units[key][\n sub_key\n ] = additional_execution_units[key][sub_key]\n else:\n execution_units[key] = additional_execution_units[key]\n if isinstance(additional_execution_units[key], dict):\n execution_units[key][\"selector\"] = selector\n # Local\n additional_execution_units = Settings.get_local(\n \"execution_units\",\n default=Settings.get_local(\n \"additional_execution_units\",\n default={}\n )\n )\n if selector_name in additional_execution_units:\n additional_execution_units = additional_execution_units[\n selector_name\n ]\n for key in additional_execution_units:\n if (key in execution_units and\n isinstance(additional_execution_units[key], dict)):\n for sub_key in additional_execution_units[key]:\n execution_units[key][\n sub_key\n ] = additional_execution_units[key][sub_key]\n else:\n execution_units[key] = additional_execution_units[key]\n if isinstance(additional_execution_units[key], dict):\n execution_units[key][\"selector\"] = selector\n if Settings.get(\"debug\") and not execution_units:\n print(\"Execution units is empty\")\n return execution_units\n\n def generate_menu(self, ask_arguments=False):\n menu = {\n \"items\": [], \"actions\": [],\n \"unsort_items\": []\n }\n execution_units_map = UnitCollections.load_default_collections()\n sel_name = None\n for selector in execution_units_map:\n if (len(self.window.active_view().find_by_selector(\n selector)) > 0):\n sel_name = selector\n break\n if not sel_name:\n for selector in Settings.get(\"execution_units\", {}):\n if (len(self.window.active_view().find_by_selector(\n selector)) > 0):\n sel_name = selector\n break\n for selector in Settings.get(\"additional_execution_units\", {}):\n if (len(self.window.active_view().find_by_selector(\n selector)) > 0):\n sel_name = selector\n break\n if Settings.get(\"debug\") and not sel_name:\n print(\"Selector is not found\")\n execution_units = self.get_execution_units(\n execution_units_map,\n sel_name\n )\n # Generate menu\n for action in execution_units:\n execution_unit = execution_units[action]\n if not isinstance(execution_unit, dict):\n continue\n if \"selector\" in execution_unit:\n selector_name = execution_unit[\"selector\"]\n else:\n selector_name = sel_name\n custom_macros = {}\n required_macros = []\n platforms = None\n arguments_title = None\n if ask_arguments:\n arguments_title = \"Arguments\"\n if \"arguments\" in execution_unit:\n arguments_title = execution_unit[\"arguments\"]\n if \"macros\" in execution_unit:\n custom_macros = execution_unit[\"macros\"]\n if \"required\" in execution_unit:\n required_macros = execution_unit[\"required\"]\n if \"platforms\" in execution_unit:\n platforms = execution_unit[\"platforms\"]\n action_name = Macro.parse_macro(\n string=action,\n custom_macros=custom_macros,\n required=required_macros,\n arguments=\"\" if ask_arguments else None\n )\n if platforms:\n matched = False\n current_platforms = [\n sublime.platform() + \"-\" + sublime.arch(),\n sublime.platform(),\n sublime.arch()\n ]\n for platform in current_platforms:\n if platform in platforms:\n matched = True\n break\n if not matched:\n continue\n if action_name is None:\n if Settings.get(\"debug\"):\n print(\"Required params is not completed\")\n continue\n if \"name\" in execution_unit:\n action_name = Macro.parse_macro(\n string=execution_unit[\"name\"],\n custom_macros=custom_macros,\n required=required_macros,\n arguments=\"\" if ask_arguments else None\n )\n order = action_name\n if \"order\" in execution_unit:\n order = execution_unit[\"order\"]\n dest = action_name + \" command\"\n if \"description\" in execution_unit:\n dest = Macro.parse_macro(\n string=execution_unit[\"description\"],\n custom_macros=custom_macros,\n required=required_macros,\n arguments=\"\" if ask_arguments else None\n )\n menu[\"unsort_items\"] += [[\n action_name,\n dest,\n {\n \"command\": \"terminality_run\",\n \"args\": {\n \"selector\": selector_name,\n \"action\": action,\n \"arguments_title\": arguments_title\n }\n },\n order\n ]]\n menu[\"unsort_items\"] = sorted(menu[\"unsort_items\"], key=lambda x: x[3])\n while menu[\"unsort_items\"]:\n menu[\"items\"].append(menu[\"unsort_items\"][0][:-2])\n menu[\"actions\"].append(menu[\"unsort_items\"][0][2])\n menu[\"unsort_items\"] = menu[\"unsort_items\"][1:]\n\n if (Settings.get(\"run_if_only_one_available\") and\n len(menu[\"items\"]) == 1):\n self.window.run_command(\n \"terminality_run\",\n menu[\"actions\"][0][\"args\"]\n )\n return None\n if len(menu[\"items\"]) <= 0 and Settings.get(\"show_nothing_if_nothing\"):\n return None\n menu[\"items\"] += self.main_menu[\"items\"]\n menu[\"actions\"] += self.main_menu[\"actions\"]\n return menu\n\n def run(self, arguments=False, menu=None, action=None, replaceMenu=None):\n \"\"\"\n Show menu to user, if ready\n \"\"\"\n if not Settings.ready():\n if self.ready_retry > 2:\n sublime.message_dialog(\n \"Terminality is starting up...\" +\n \"Please wait a few seconds and try again.\"\n )\n else:\n sublime.status_message(\n \"Terminality is starting up...\" +\n \"Please wait a few seconds and try again...\"\n )\n self.ready_retry += 1\n return\n if self.qm is None:\n self.qm = QuickMenu()\n if replaceMenu is not None:\n self.qm.setMenu(replaceMenu[\"name\"], replaceMenu[\"menu\"])\n return\n menu = self.generate_menu(arguments)\n if menu is None:\n return\n self.qm.setMenu(\"main\", menu)\n self.qm.show(window=self.window, menu=menu, action=action)\n","repo_name":"spywhere/Terminality","sub_path":"terminality.py","file_name":"terminality.py","file_ext":"py","file_size_in_byte":17453,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"6"} +{"seq_id":"26947969534","text":"import re\nimport string\nfrom itertools import chain\n\nfrom idc import GetStrucIdByName, Til2Idb, DelStruc\nfrom idaapi import BADNODE\n\nPTR_SIZE_BITS = {\n \"qword ptr\": 64,\n \"dword ptr\": 32,\n \"word ptr\": 16,\n \"byte ptr\": 8,\n}\n\ndef filter_objects(objects_list, **attrs):\n for object in objects_list:\n for attr_name, attr_value in attrs.items():\n if getattr(object, attr_name) != attr_value:\n break\n else:\n yield object\n\n\ndef find_object(objects_list, **attrs):\n try:\n return next(filter_objects(objects_list, **attrs))\n except StopIteration:\n return None\n\n\ndef filter_objects_ex(objects_list, **attrs):\n for object in objects_list:\n for attr_name, attr_value in attrs.items():\n if getattr(object, attr_name) != attr_value:\n break\n else:\n yield object\n raise StopIteration\n\n\ndef find_object_ex(objects_list, **attrs):\n return next(filter_objects(objects_list, **attrs))\n\n\ndef underscore_to_global(name):\n return 'g'+''.join(list(s.capitalize() for s in name.lower().split('_')))\n\n\ndef global_to_underscore(name):\n s = ''\n\n for c in name:\n if c in string.ascii_uppercase:\n s += '_'\n s += c.upper()\n\n return s[1:]\n\n\ndef is_structure_type(type):\n if type is None or type == \"\":\n return False\n\n sid = GetStrucIdByName(type)\n if sid != BADNODE:\n return True\n\n sid = Til2Idb(0, type)\n if sid != BADNODE:\n if DelStruc(sid) == 0:\n raise Exception('Bad structure type ID')\n return True\n\n return False\n\n\ndef strip_end(text, suffix):\n if suffix == \"\" or not text.endswith(suffix):\n return text\n return text[:-len(suffix)]\n\n","repo_name":"danse-macabre/ida-efitools","sub_path":"core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"6"} +{"seq_id":"37070520346","text":"import colorgram\nimport turtle as t\nimport random as r\n\nt.colormode(255)\nSC = t.Screen()\nCOL_COUNT = 24\nSQUARE_SIDE = 10\n\n\ndef extract_colors():\n colors = colorgram.extract('./img/hirst.jpg', COL_COUNT)\n rgb_colors = []\n for c in range(COL_COUNT):\n r = colors[c].rgb.r\n g = colors[c].rgb.g\n b = colors[c].rgb.b\n rgb_color = (r, g, b)\n rgb_colors.append(rgb_color)\n return rgb_colors\n\n\ndef draw(colors, size):\n tur = t.Turtle()\n tur.hideturtle()\n tur.penup()\n tur.goto(-200, -200)\n for i in range(size):\n for j in range(size):\n tur.dot(20, r.choice(colors))\n tur.forward(50)\n tur.setposition(-200, -200 + 50 * (i+1))\n\n\ndraw(extract_colors(), 10)\nSC.exitonclick()\n","repo_name":"Develtomas/python","sub_path":"day18/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"37555790918","text":"from django.db import models\n\n\nclass Menu(models.Model):\n name = models.CharField(verbose_name='Название', max_length=50)\n url = models.CharField(verbose_name='URL', max_length=200, blank=True)\n named_url = models.CharField(\n verbose_name='named_URL',\n max_length=200,\n blank=True,\n null=True,\n )\n childes = models.ManyToManyField(\n 'Menu',\n related_name='parents',\n blank=True,\n )\n\n class Meta:\n verbose_name = 'Пункт меню'\n verbose_name_plural = 'Пункты меню'\n ordering = 'name',\n\n def __str__(self):\n return self.name\n\n\nclass HeadMenu(models.Model):\n menu = models.OneToOneField(\n 'Menu',\n on_delete=models.CASCADE,\n primary_key=True,\n )\n title = models.SlugField(verbose_name='Название меню')\n\n class Meta:\n verbose_name = 'Меню'\n verbose_name_plural = 'Меню'\n\n def __str__(self):\n return self.title\n","repo_name":"Rabadan-Ibr/TemplateTestTask_2","sub_path":"traider_case/menu/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"4032047898","text":"from matplotlib import pyplot as plt\nimport math\nimport numpy as np\nimport os\nimport pandas as pd\nimport random\nimport time\nimport cntk\n\nimport constants\n\ndef inititalize_cntk():\n print('cntk Version = ',cntk.__version__)\n cntk.device.try_set_default_device(cntk.device.cpu())\n np.random.seed(0)\n cntk.cntk_py.set_fixed_random_seed(1)\n cntk.cntk_py.force_deterministic_algorithms()\n\ndef create_model():\n with cntk.layers.default_options(initial_state=0.1):\n return cntk.layers.Sequential([\n cntk.layers.Embedding(constants.emb_dim, name='embed'),\n cntk.layers.Recurrence(cntk.layers.LSTM(constants.hidden_dim), go_backwards=False),\n cntk.layers.Dense(constants.num_labels, name='classify')\n ])\n\ndef create_reader(path, is_training):\n return cntk.io.MinibatchSource(cntk.io.CTFDeserializer(path, cntk.io.StreamDefs(\n query = cntk.io.StreamDef(field='S0', shape=constants.vocab_size, is_sparse=True),\n intent_unused = cntk.io.StreamDef(field='S1', shape=constants.num_intents, is_sparse=True), \n slot_labels = cntk.io.StreamDef(field='S2', shape=constants.num_labels, is_sparse=True)\n )), randomize=is_training, max_sweeps = cntk.io.INFINITELY_REPEAT if is_training else 1)\n\ndef create_criterion_function(model, labels):\n ce = cntk.cross_entropy_with_softmax(model, labels)\n errs = cntk.classification_error (model, labels)\n return ce, errs # (model, labels) -> (loss, error metric)\n\ndef train_test(train_reader, test_reader, model_func, max_epochs=10):\n x = cntk.sequence.input_variable(constants.vocab_size)\n y = cntk.sequence.input_variable(constants.num_labels)\n\n model = model_func(x)\n \n loss, label_error = create_criterion_function(model, y)\n\n lr_per_minibatch = [lr * constants.minibatch_size for lr in constants.lr_per_sample]\n lr_schedule = cntk.learning_rate_schedule(lr_per_minibatch, cntk.UnitType.minibatch, constants.epoch_size)\n \n # Momentum schedule\n momentum_as_time_constant = cntk.momentum_as_time_constant_schedule(700)\n \n learner = cntk.adam(parameters=model.parameters,\n lr=lr_schedule,\n momentum=momentum_as_time_constant,\n gradient_clipping_threshold_per_sample=15, \n gradient_clipping_with_truncation=True)\n\n progress_printer = cntk.logging.ProgressPrinter(tag='Training', num_epochs=max_epochs)\n \n # Uncomment below for more detailed logging\n #progress_printer = ProgressPrinter(freq=100, first=10, tag='Training', num_epochs=max_epochs) \n\n trainer = cntk.Trainer(model, (loss, label_error), learner, progress_printer)\n\n cntk.logging.log_number_of_parameters(model)\n\n t = 0\n for epoch in range(max_epochs): # loop over epochs\n epoch_end = (epoch+1) * constants.epoch_size\n while t < epoch_end: # loop over minibatches on the epoch\n data = train_reader.next_minibatch(constants.minibatch_size, input_map={ # fetch minibatch\n x: train_reader.streams.query,\n y: train_reader.streams.slot_labels\n })\n trainer.train_minibatch(data) # update model with it\n t += data[y].num_samples # samples so far\n trainer.summarize_training_progress()\n \n while True:\n minibatch_size = 500\n data = test_reader.next_minibatch(minibatch_size, input_map={ # fetch minibatch\n x: test_reader.streams.query,\n y: test_reader.streams.slot_labels\n })\n if not data: # until we hit the end\n break\n trainer.test_minibatch(data)\n \n trainer.summarize_test_progress()\n\ndef do_train_test():\n z = create_model()\n train_reader = create_reader('atis.train.ctf', is_training=True)\n test_reader = create_reader('atis.test.ctf',is_training=False)\n train_test(train_reader, test_reader, z)\n\nif __name__ == '__main__':\n inititalize_cntk()\n do_train_test()","repo_name":"selvakumarjawahar/MachineLearningProjects","sub_path":"EdxDeepLearning/ATISDataTagging/trainandtestmodel.py","file_name":"trainandtestmodel.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"34559636571","text":"import argparse\nimport cv2 as cv\nimport glob\nimport natsort\nimport numpy as np\nimport os\nimport time\n\nimport matplotlib as mpl\nmpl.use('tkagg') # Hack to make mpl work with Big Sur\nimport matplotlib.pyplot as plt\n\nimport ballot_analysis.im_processing as im_proc\nimport ballot_analysis.plot_utils as plt_utils\n\n\ndef parse_args():\n \"\"\"\n Parse command line arguments for CLI.\n\n :return: namespace containing the arguments passed.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-i', '--input',\n type=str,\n required=True,\n help=\"Input directory path\",\n )\n parser.add_argument(\n '-d', '--debug',\n dest='debug',\n action='store_true',\n help=\"Create debug plots. Default: False\",\n )\n parser.set_defaults(debug=False)\n parser.add_argument(\n '--file_idx',\n type=int,\n default=None,\n help=\"Run only file with this index in a sorted list of files in dir\"\n )\n return parser.parse_args()\n\n\ndef ballot_analyzer(args):\n \"\"\"\n Detect columns and checked boxes in ballots by finding vertical and\n horizontal lines in an image that has been filtered with a Laplacian\n of Gaussian then thresholded.\n Only prototyping at this point, no results are saved except debug plots.\n Assumes that ballots can be upside down but that smaller rotations\n are negligible.\n It finds empty and filled ellipses using an empty and filled template,\n so it will fail to detect boxes that have been filled with 'x'es or\n checkmarks.\n\n :param args: Command line arguments\n input: Full path to directory containing scanned ballots\n debug: Create debug plots (only recommended if running one/few images)\n file_idx: If None, run all files, otherwise run only file with given idx\n \"\"\"\n input_dir = args.input\n debug = args.debug\n file_idx = args.file_idx\n # Create subdirectory where output is written\n output_dir = os.path.join(input_dir, 'analysis_debug')\n os.makedirs(output_dir, exist_ok=True)\n\n # Read template\n template = cv.imread('marker_template.png', cv.IMREAD_GRAYSCALE)\n template_filled = cv.imread('filled_template.png', cv.IMREAD_GRAYSCALE)\n template_shape = template.shape\n\n # Instantiate spot detectors and create filter\n max_detector = im_proc.make_max_detector()\n max_detector_filled = im_proc.make_max_detector(min_area=250)\n log_filter = im_proc.make_log_filter(sigma_gauss=5)\n\n file_names = natsort.natsorted(\n glob.glob(os.path.join(input_dir, '*original.png'),)\n )\n if file_idx is not None:\n assert 0 <= file_idx < len(file_names),\\\n \"File idx {} doesn't work\".format(file_idx)\n file_names = [file_names[file_idx]]\n\n for idx, file_name in enumerate(file_names):\n start_time = time.time()\n im_name = os.path.basename(file_name)[:-4]\n print(\"Analyzing idx: {}, name: {}\".format(idx, im_name))\n im = cv.imread(file_name)\n # Check if images are upside down by finding QR code\n try:\n rotate_180 = im_proc.find_qr(im=im, debug=debug)\n except AssertionError:\n print(\"Can't find QR for {}\".format(file_name))\n continue\n if rotate_180:\n im = np.rot90(im, 2)\n # Rotate image based on angle of bottom line in ballot\n im_gray = im_proc.get_angle_and_rotate(\n im,\n log_filter,\n debug,\n )\n if debug:\n plt.imshow(im_gray, cmap='gray'); plt.show()\n # Filter and threshold rotated image\n im_thresh = im_proc.filter_and_thresh(im_gray, log_filter)\n\n # Find horizontal and vertical lines\n im_hor = im_proc.find_lines(im_thresh, strel_len=200, do_vert=False)\n im_vert = im_proc.find_lines(im_thresh, strel_len=200, do_vert=True)\n\n # For plotting only\n im_boxes = np.array(cv.cvtColor(im_gray, cv.COLOR_GRAY2RGB))\n # Plot detected horizontal and vertical lines\n plt_utils.plot_hough_lines(im_hor, im_boxes, (255, 0, 0))\n plt_utils.plot_hough_lines(im_vert, im_boxes, (0, 255, 0))\n\n # Compress horizontal and vertical images to 1D profiles and\n # detect boxes as maxima\n try:\n peak_idxs = im_proc.get_vert_peaks(im_vert, debug=debug)\n except AssertionError as e:\n print(\"Failed to detect correct vertical lines\", e)\n # Write profile where error occurred\n plt_utils.write_debug_profile(im_vert, output_dir, im_name)\n continue\n\n # Pair boxes using vertical lines\n for col in range(peak_idxs.shape[0]):\n # Get horizontal lines profile for column\n coords_col = peak_idxs[col, :]\n im_column = im_hor[:, coords_col[0]: coords_col[1]]\n hor_peak_idxs = im_proc.get_hor_peaks(im_column, debug=debug)\n\n for row in range(hor_peak_idxs.shape[0]):\n coords_row = hor_peak_idxs[row, :]\n # Get left 20% of box (that's where the fill-in boxes are)\n col_width = coords_col[0] + int((coords_col[1] - coords_col[0]) / 5)\n im_markers = im_gray[coords_row[0]:coords_row[1], coords_col[0]:col_width]\n marker_shape = im_markers.shape\n if marker_shape[0] <= template_shape[0] or marker_shape[1] <= template_shape[1]:\n print(\"Image ROI too small for marker detection\")\n continue\n # Search for empty boxes with empty ellipse template\n im_conv = im_proc.conv_and_norm(im_markers, template)\n keypoints = max_detector.detect(im_conv)\n plt_utils.plot_boxes(\n im_boxes,\n keypoints,\n coords_col,\n coords_row,\n template_shape,\n (255, 255, 0),\n )\n # Search for filled in boxes with filled elliptical template\n im_conv_filled = im_proc.conv_and_norm(im_markers, template_filled)\n keypoints = max_detector_filled.detect(im_conv_filled)\n plt_utils.plot_boxes(\n im_boxes,\n keypoints,\n coords_col,\n coords_row,\n template_shape,\n (255, 0, 255),\n )\n # TODO: store box coordinates and filled/empty values\n\n print(\"Processing time: {:.3f} s\".format(time.time() - start_time))\n # Write debug image\n cv.imwrite(os.path.join(output_dir, im_name + \"_debug.png\"), im_boxes)\n if debug:\n plt.imshow(im_boxes); plt.show()\n\n\nif __name__ == '__main__':\n args = parse_args()\n ballot_analyzer(args)\n\n\n","repo_name":"votingworks/hmpb-interpret-experiments","sub_path":"ballot_reader.py","file_name":"ballot_reader.py","file_ext":"py","file_size_in_byte":6843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"41087163671","text":"# 처음 위치를 찾는 이진 탐색 메서드\ndef first(array, target, start, end):\n if start > end:\n return None\n \n mid = (start+end)//2\n\n # 해당 값을 가지는 원소 중에서 가장 왼쪽에 있는 경우에만 인덱스 반환\n if (mid == 0 or target > array[mid-1]) and array[mid] == target:\n return mid\n \n # 중간점의 값 보다 찾고자 하는 값이 작거나 같은 경우 왼쪽 확인\n elif array[mid] >= target:\n return first(array, target, start, mid-1)\n \n # 중간점의 값 보다 찾고자 하는 값이 큰 경우 오른쪽 확인\n else:\n return first(array, target, mid+1, end)\n \n# 마지막 위치를 찾는 이진 탐색 메서드\ndef last(array, target, start, end):\n if start > end:\n return None\n \n mid = (start+end)//2\n\n # 해당 값을 가지는 원소 중에서 가장 오른쪽에 있는 경우에만 인덱스 반환\n if (mid == n-1 or target < array[mid+1]) and array[mid] == target:\n return mid\n \n # 중간점의 값 보다 찾고자 하는 값이 작은 경우 왼쪽 확인\n elif array[mid] > target:\n return last(array, target, start, mid-1)\n \n # 중간점의 값 보다 찾고자 하는 값이 크거나 같은 경우 오른쪽 확인\n else:\n return last(array, target, mid+1, end)\n \nn, x = map(int, input().split())\narray = list(map(int, input().split()))\n\nleft_index = first(array, x, 0, n-1)\nright_index = last(array, x, 0, n-1)\n\n# x가 존재하지 않는다면 -1 출력\nif (left_index or right_index) == None:\n print(-1)\n# x가 존재하면 개수 출력\nelse:\n print(right_index-left_index+1)\n\n\n","repo_name":"Ahyun0326/Algorithm_study","sub_path":"이분탐색/정렬된 배열에서 특정 수의 개수 구하기.py","file_name":"정렬된 배열에서 특정 수의 개수 구하기.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"13959998621","text":"import unittest\nimport pyjxslt\nfrom dict_compare import dict_compare\nimport json\n\nxml1 = \"\"\"\n\n FOO\n BAR\n\"\"\"\n\nexpected_json = \"\"\"{\n \"doc\": {\n \"entry\": [\n {\n \"_content\": \"FOO\",\n \"id\": \"17\"\n },\n {\n \"_content\": \"BAR\",\n \"id\": \"42\"\n }\n ]\n }\n}\"\"\"\n\nbad_xml = \"\"\"\n\n FOO\n BAR\n\"\"\"\n\nxml_with_processing_instruction = \"\"\"\n\n\n\"\"\"\n\nexpected_pi = '{ \"data_table\": { \"id\": \"pht003897.v1\", \"study_id\": \"phs000722.v1\", \"participant_set\": \"1\" } }'\n\n\nexpected_bad = 'ERROR: Transformer exception: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 3; ' \\\n 'The element type \"doc\" must be terminated by the matching end-tag \"\".'\n\n\nclass XMLToJsonTestCase(unittest.TestCase):\n # Just a quick test as the actual transform is tested elsewhere. Our job is just to make sure\n # that we get what we expect through the gateway\n gw = pyjxslt.Gateway()\n if not gw.gateway_connected(reconnect=False):\n print(\"Gateway must be running on port 25333\")\n\n def compare_jsons(self, json1, json2):\n json1d = json.loads(json1)\n try:\n json2d = json.loads(json2)\n except json.JSONDecodeError as e:\n print(str(e))\n return False\n success, txt = dict_compare(json1d, json2d)\n if not success:\n print(txt)\n return success\n\n def test1(self):\n self.assertTrue(self.compare_jsons(expected_json, self.gw.to_json(xml1)))\n self.assertEqual(expected_bad, self.gw.to_json(bad_xml))\n self.assertTrue(self.compare_jsons(expected_pi, self.gw.to_json(xml_with_processing_instruction)))\n\n\nclass NoGatewayTestCase(unittest.TestCase):\n def test_gw_down(self):\n gw = pyjxslt.Gateway(port=23456) # a non-existent port\n self.assertIsNone(gw.to_json(xml1))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"cts2/pyjxslt","sub_path":"pyjxslt-python/tests/testXMLtoJSON.py","file_name":"testXMLtoJSON.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"6"} +{"seq_id":"11898363784","text":"#!/usr/bin/env python3\n\"\"\" obtain the HTML content of a particular URL \"\"\"\n\nimport redis\nimport requests\n\nredi = redis.Redis()\ncounter = 0\n\n\ndef get_page(url: str) -> str:\n \"\"\" ses the requests module to obtain the\n HTML content of a particular URL and returns it \"\"\"\n data = f\"count:{url}\"\n redi.set(data, counter)\n request_url = requests.get(url)\n redi.incr(data)\n redi.setex(data, 10, redi.get(data))\n return request_url.text\n\n\nif __name__ == \"__main__\":\n get_page('http://slowwly.robertomurray.co.uk')\n","repo_name":"jeanpierreba/holbertonschool-web_back_end","sub_path":"0x0B_redis_basic/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"6"} +{"seq_id":"35682321585","text":"#!usr/bin/env python3\n\n\"\"\"\nFile name: delaunay.py\nAuthor: Peter Maldonado\nDate created: 3/05/2019\nDate last modified: 3/11/2019\nPython Version: 3.7\n\nThis module contains the methods need to triangulate an image using Delaunay\nTriangulation as the underlying algorithm.\n\"\"\"\n\nimport argparse\nimport numpy as np\nfrom numpy.random import randint, uniform, choice\nimport matplotlib.pyplot as plt\nfrom scipy import ndimage as ndi\nfrom scipy.spatial import KDTree, Delaunay\nfrom scipy.signal import convolve2d\n\nimport skimage.restoration\nfrom skimage.color import rgb2gray, gray2rgb, rgb2lab\nfrom skimage.draw import polygon, polygon_perimeter, circle\nfrom skimage.feature import canny\nfrom skimage.filters import gaussian, scharr\nfrom skimage.filters.rank import entropy\nfrom skimage.io import imread, imsave, imshow\nfrom skimage.morphology import disk, dilation\nfrom skimage.restoration import denoise_bilateral\nfrom skimage.transform import pyramid_reduce\nfrom skimage.util import img_as_ubyte, invert, img_as_float64\n\nimport time\n\ndef visualize_sample(img, weights, sample_points):\n fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(8,3),\n sharex=True, sharey=True)\n ax1.imshow(img, cmap='gray')\n ax1.axis('off')\n\n ax2.imshow(weights, cmap='gray')\n ax2.axis('off')\n\n heatmap = gray2rgb(img_as_float64(weights))\n for point in sample_points:\n rr, cc = circle(point[0], point[1], 2, shape=weights.shape)\n heatmap[rr, cc, 0] = 1\n ax3.imshow(heatmap)\n ax3.axis('off')\n\n fig.tight_layout()\n\n plt.show()\n\ndef generate_sample_points(img, max_points):\n '''\n Generates samples points for triangulation of a given image.\n\n Parameters\n ----------\n img : np.array\n The image to sample.\n\n Returns\n -------\n list :\n The list of points to triangulate.\n '''\n width = img.shape[0]\n height = img.shape[1]\n n = min(round(height * width * args.rate), max_points)\n\n print(\"Preprocessing...\")\n t0 = time.perf_counter()\n if args.process == 'approx-canny':\n weights = approx_canny(img, args.blur)\n elif args.process == 'edge-entropy':\n weights = edge_entropy(img)\n t1 = time.perf_counter()\n if args.time:\n print(f\"Preprocess timer: {round(t1-t0, 3)} seconds.\")\n\n print(\"Sampling...\")\n t0 = time.perf_counter()\n if args.sample == 'threshold':\n threshold = args.threshold\n sample_points = threshold_sample(n, weights, threshold)\n elif args.sample == 'disk':\n sample_points = poisson_disk_sample(n, weights)\n t1 = time.perf_counter()\n if args.time:\n print(f\"Sample timer: {round(t1-t0, 3)} seconds.\")\n\n if args.debug:\n visualize_sample(img, weights, sample_points)\n corners = np.array([[0, 0], [0, height-1], [width-1, 0], [width-1, height-1]])\n return np.append(sample_points, corners, axis=0)\n\ndef approx_canny(img, blur):\n '''\n Weights pixels based on an approximate canny edge-detection algorithm.\n\n Parameters\n ----------\n img : ndarray\n Image to weight.\n blur : int\n Blur radius for pre-processing.\n\n Returns\n -------\n ndarray : \n Noramlized weight matrix for pixel sampling.\n '''\n edge_threshold = 3 / 256\n\n gray_img = rgb2gray(img)\n blur_filt = np.ones(shape=(2*blur+1, 2*blur+1)) / ((2*blur+1) ** 2)\n blurred = convolve2d(gray_img, blur_filt, mode='same', boundary='symm')\n edge_filt = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]])\n edge = convolve2d(blurred, edge_filt, mode='same', boundary='symm')\n for idx, val in np.ndenumerate(edge):\n if val < edge_threshold:\n edge[idx] = 0\n dense_filt = np.ones((3,3))\n dense = convolve2d(edge, dense_filt, mode='same', boundary='symm')\n dense /= np.amax(dense)\n\n if args.debug:\n fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(8,3),\n sharex=True, sharey=True)\n ax1.imshow(blurred)\n ax1.axis('off')\n\n ax2.imshow(edge)\n ax2.axis('off')\n\n ax3.imshow(dense)\n ax3.axis('off')\n\n fig.tight_layout()\n plt.show()\n return dense\n\ndef edge_entropy(img, bal=0.1):\n '''\n Weights pixels based on a weighted edge-detection and entropy balance.\n\n Parameters\n ----------\n img : ndarray\n Image to weight.\n bal : float (optional)\n How much to value entropy (bal) versus edge-detection (1 - bal)\n\n Returns\n -------\n ndarray : \n Noramlized weight matrix for pixel sampling.\n '''\n dn_img = skimage.restoration.denoise_tv_bregman(img, 0.1)\n img_gray = rgb2gray(dn_img)\n img_lab = rgb2lab(dn_img)\n\n entropy_img = gaussian(img_as_float64(dilation(entropy(img_as_ubyte(img_gray), disk(5)), disk(5))))\n edges_img = dilation(np.mean(np.array([scharr(img_lab[:,:,channel]) for channel in range(3)]), axis=0), disk(3))\n\n weight = (bal * entropy_img) + ((1 - bal) * edges_img)\n weight /= np.mean(weight)\n weight /= np.amax(weight)\n\n if args.debug:\n fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(8,3),\n sharex=True, sharey=True)\n ax1.imshow(entropy_img)\n ax1.axis('off')\n\n ax2.imshow(edges_img)\n ax2.axis('off')\n\n ax3.imshow(weight)\n ax3.axis('off')\n\n fig.tight_layout()\n plt.show()\n\n return weight\n\ndef poisson_disk_sample(n, weights, k=16):\n '''\n Performs weighted poisson disk sampling over a region.\n\n Algorithm based on \n https://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf\n\n Weighted approach inspired by\n https://codegolf.stackexchange.com/questions/50299/draw-an-image-as-a-voronoi-map\n\n Parameters\n ----------\n n : int\n The number of points to sample.\n weights : np.array\n Weights of grid to sample over. Assumes weights are normalized.\n k : int (optional)\n The number of attempts to sample an annulus before removing center.\n \n Returns\n -------\n ist :\n List of sampled points\n '''\n width = weights.shape[0]\n height = weights.shape[1]\n\n c = np.log10(width * height) / 2\n max_rad = min(width, height) / 4\n avg_rad = np.sqrt((height * width) / ((1 / c) * n * np.pi))\n min_rad = avg_rad / 4\n\n weights /= np.mean(weights)\n rads = np.clip(avg_rad / (weights + 0.01), min_rad, max_rad)\n if args.debug:\n print(f\"Weights: [{np.min(weights)}, {np.max(weights)}]\" \\\n f\" and Radii: [{rads.min()}, {rads.max()}]\")\n\n first = (randint(width), randint(height))\n queue = [first]\n sample_points = [first]\n tree = KDTree(sample_points)\n\n def in_bounds(point):\n return 0 <= point[0] < width and 0 <= point[1] < height\n\n def has_neighbor(new_point, rads, tree):\n return len(tree.query_ball_point(new_point, rads[new_point])) > 0\n\n while queue and len(sample_points) < n:\n idx = randint(len(queue))\n point = queue[idx]\n\n success = False\n for it in range(k):\n new_point = get_point_near(point, rads, max_rad)\n\n if (in_bounds(new_point) and not \n has_neighbor(new_point, rads, tree)):\n queue.append(new_point)\n sample_points.append(new_point)\n tree = KDTree(sample_points)\n success = True\n break\n\n if not success:\n queue.pop(idx)\n \n print(f\"Goal points: {n}\")\n print(f\"Generated {len(sample_points)} sample points with disk sampling.\")\n print(f\"{len(set(sample_points))} unique points.\")\n return np.array(list(sample_points))\n\ndef get_point_near(point, rads, max_rad):\n '''\n Randomly samples an annulus near a given point using a uniform \n distribution.\n\n Parameters\n ----------\n point : (int, int)\n The point to sample nearby.\n rads : np.array\n The lower bound for the random search.\n max_rad : int\n The upper bound for the random search.\n \n Returns\n -------\n (int, int) :\n The nearby point.\n '''\n rad = uniform(rads[point], max_rad)\n theta = uniform(0, 2 * np.pi)\n new_point = (point[0] + rad * np.cos(theta), \n point[1] + rad * np.sin(theta))\n return (int(new_point[0]), int(new_point[1]))\n\ndef threshold_sample(n, weights, threshold):\n '''\n Sample the weighted points uniformly above a certain threshold.\n\n Parameters\n ----------\n n : int\n The number of points to sample.\n weights : np.array\n Weights of grid to sample over. Assumes weights are normalized.\n threshold : float\n The threshold to ignore points\n\n Returns\n -------\n list :\n The list of points to triangulate.\n '''\n candidates = np.array([idx for idx, weight in np.ndenumerate(weights) if weight >= threshold])\n if candidates.shape[0] < n:\n raise ValueError(f\"Not enough candidate points for threshold {threshold}. \"\n f\"Only {candidates.shape[0]} available.\")\n\n print(f\"Generated {n} sample points with threshold sampling.\")\n return candidates[choice(candidates.shape[0], size=n, replace=False)]\n\ndef render(triangles, img, color_mode, fill_mode):\n '''\n Generates samples points for triangulation of a given image.\n\n Parameters\n ----------\n triangles : np.array\n The delaunay triangulation of the image\n img : np.array\n The image to create a low-polygon approximation.\n '''\n t0 = time.perf_counter()\n low_poly = np.empty(shape=(2 * img.shape[0], 2 * img.shape[1], img.shape[2]), dtype=np.uint8)\n\n for triangle in triangles:\n if fill_mode == 'wire':\n rr, cc = polygon_perimeter(2 * triangle[:,0], 2 * triangle[:,1], low_poly.shape)\n elif fill_mode == 'solid':\n rr, cc = polygon(2 * triangle[:,0], 2 * triangle[:,1], low_poly.shape)\n\n if color_mode == 'centroid':\n centroid = np.mean(triangle, axis=0, dtype=np.int32)\n color = img[tuple(centroid)]\n elif color_mode == 'mean':\n color = np.mean(img[polygon(triangle[:,0], triangle[:,1], img.shape)], axis=0)\n\n low_poly[rr,cc] = color\n t1 = time.perf_counter()\n if args.time:\n print(f\"Render timer: {round(t1-t0, 3)} seconds.\")\n\n fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(8,3),\n sharex=True, sharey=True)\n ax1.imshow(img)\n ax1.axis('off')\n\n low_poly = pyramid_reduce(low_poly, multichannel=True)\n ax2.imshow(low_poly)\n ax2.axis('off')\n\n fig.tight_layout()\n\n plt.show()\n\n if args.save:\n name = args.save_name if args.save_name is not None else f\"{args.img.replace('.jpg','')}_tri.png\"\n imsave(name, low_poly)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='''Perform delaunay triangulation \n on a given image to create a low-polygon approximation.''')\n parser.add_argument('img', help=\"The image to triangulate.\",\n type=str)\n parser.add_argument('-sample', help=\"Sampling method for candidate points.\",\n type=str, default=\"threshold\", choices=['disk', 'threshold'])\n parser.add_argument('-process', help=\"Pre-processing method to use.\",\n type=str, default='approx-canny', choices=['approx-canny', \n 'edge-entropy'])\n parser.add_argument('-color', help=\"Coloring method for rendering.\",\n type=str, default='centroid', choices=['centroid', 'mean'])\n parser.add_argument('-fill', help=\"Interior fill of the Delaunay mesh.\",\n type=str, default='solid', choices=['wire', 'solid'])\n parser.add_argument('-rate', help=\"Desired ratio of sample points to pixels.\",\n type=float, default=0.03)\n parser.add_argument('-blur', help=\"Blur radius for approximate canny.\",\n type=int, default=2)\n parser.add_argument('-threshold', help='Threshold for threshold sampling.',\n type=float, default=0.02)\n parser.add_argument('-max-points', help=\"Max number of sample points.\",\n type=int, default=5000)\n parser.add_argument('-seed', help=\"Seed for random number generation.\",\n type=int, default=None)\n parser.add_argument('-save-name', help=\"Filename for saved output.\",\n type=str, default=None)\n parser.add_argument('--save', action='store_true')\n parser.add_argument('--debug', action='store_true')\n parser.add_argument('--time', help=\"Display timer for each section.\",\n action='store_true')\n args = parser.parse_args()\n print(f\"Running {__name__} with arguments: {args}\")\n\n if args.seed is not None:\n np.random.seed(args.seed)\n print(f\"Using seed {np.random.get_state()[1][0]}.\")\n\n # Actually do the code thing\n img = imread(args.img)[:,:,:3]\n sample_points = generate_sample_points(img, args.max_points)\n print('Triangulating...')\n triangulation = Delaunay(sample_points)\n triangles = sample_points[triangulation.simplices]\n print('Rendering...')\n render(triangles, img, args.color, args.fill)","repo_name":"pmaldonado/PyTri","sub_path":"delaunay.py","file_name":"delaunay.py","file_ext":"py","file_size_in_byte":13391,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"6"} +{"seq_id":"37306201953","text":"import subprocess\r\n\r\npowerModes = {\"1\" : \"powercfg -SETACTIVE SCHEME_BALANCED\", \"2\" : \"powercfg -SETACTIVE SCHEME_MAX\", \"3\" : \"powercfg -SETACTIVE SCHEME_MIN\"}\r\n\r\nwhile True:\r\n choice = input(\"1 - Balance\\n2 - Power Saver\\n3 - High Performance \\n\")\r\n if choice.isalpha():\r\n print(\"Please enter a number!\")\r\n continue\r\n else:\r\n if choice == \"1\":\r\n subprocess.call(powerModes[\"1\"])\r\n print(\"Set power mode to 'Balanced'.\")\r\n break\r\n elif choice == \"2\":\r\n subprocess.call(powerModes[\"2\"])\r\n print(\"Set power mode to 'Power Saver'.\")\r\n break\r\n elif choice == \"3\":\r\n subprocess.call(powerModes[\"3\"])\r\n print(\"Set power mode to 'High Performance'.\")\r\n break\r\n else:\r\n print(\"Choose a Mode\")\r\n","repo_name":"muajk00b/windowsPowerModes","sub_path":"powermodes.py","file_name":"powermodes.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"11415035276","text":"from typing import Callable, List, Union, Optional, Dict, Tuple\nimport re\nimport spacy\nimport logging\nimport math\nfrom enum import Enum\nlogger = logging.getLogger(__name__)\n\n\ndef remove_excess_space(inp: str) -> str:\n return ' '.join(inp.split()).strip()\n\n\ndef get_spacy_model(model: str) -> spacy.language.Model:\n try:\n spacy_model = spacy.load(model)\n except OSError:\n logger.warning(\n f\"Spacy models '{model}' not found. Downloading and installing.\")\n spacy.cli.download(model)\n\n # Import the downloaded model module directly and load from there\n spacy_model_module = __import__(model)\n spacy_model = spacy_model_module.load()\n\n return spacy_model\n\n\nclass PreprocessorBase:\n \"\"\"Override the __call__ method in inherited class to change functionallity\"\"\"\n\n def __call__(self, q: str, o: str) -> Tuple[str, Dict]:\n \"\"\" Very basic preprocessor which concats question and option.\n\n Handles fill in the black type questions.\n \"\"\"\n\n if '_' in q: # FITB\n h = q.replace('_', o)\n else:\n h = q + ' ' + o\n h = remove_excess_space(h)\n meta = {'question': q, 'option': o}\n\n return h, meta\n\n\nPreprocessor = PreprocessorBase\n\ndots = re.compile(r\"[\\.\\'\\\"\\?, ]{2,}[\\w ]*\")\n\n\ndef remove_dots(inp: str) -> str:\n return dots.sub('.', inp)\n\n\nclass ConversionIssue(Enum):\n NONE = 'none'\n TOO_SHORT = 'too_short'\n TOO_LONG = 'too_long'\n COULD_NOT_FIX = 'could_not_fix'\n INVALID_QUESTION = 'invalid_question'\n INVALID_OPTION = 'invalid_option'\n MISSING_INFORMATION = 'missing_info'\n UNGRAMTICAL_RESULT = 'ungramatical_result'\n UNKNOWN = 'unknown'\n\n def __str__(self) -> str:\n return self.value\n\n\nclass PostprocessorBase:\n def __init__(self,\n lower_length_ratio: Optional[float] = None,\n upper_length_ratio: float = 1.3) -> None:\n self.lower_length_ratio = lower_length_ratio\n self.upper_length_ratio = upper_length_ratio\n\n def __call__(self, inp: str, meta: Dict) -> Tuple[str, Dict]:\n # if the list does not exists add an empty\n meta['conversion_issues'] = meta.get('conversion_issues', [])\n\n return inp, meta\n\n def _length_check(self, output: str, question: str,\n option: str) -> ConversionIssue:\n total_ratio = (len(output) / (len(question) + len(option)))\n\n if total_ratio > self.upper_length_ratio:\n # too long. Cut the output\n\n return ConversionIssue.TOO_LONG\n elif self.lower_length_ratio is None and len(output) < len(option):\n return ConversionIssue.TOO_SHORT\n elif self.lower_length_ratio is not None:\n if total_ratio < self.lower_length_ratio:\n return ConversionIssue.TOO_SHORT\n\n return ConversionIssue.NONE\n\n\nclass Postprocessor(PostprocessorBase):\n def __init__(self,\n sentence_splitter: str = 'period',\n cleaner: str = None,\n lower_length_ratio: float = None,\n upper_length_ratio: float = 1.3) -> None:\n self.sentence_splitter = sentence_splitter\n\n if cleaner == 'remove_dots':\n self.cleaner: Callable[[str], str] = remove_dots\n else:\n self.cleaner = lambda x: x\n\n if sentence_splitter == 'spacy':\n self.spacy_nlp = get_spacy_model('en_core_web_sm')\n else:\n self.spacy_nlp = None\n super().__init__(\n lower_length_ratio=lower_length_ratio,\n upper_length_ratio=upper_length_ratio)\n\n def _fix_too_short(self, all_sentences: List[str],\n meta: Dict) -> Tuple[str, bool]:\n next_ = 1\n could_not_fix = False\n current_output = all_sentences[0]\n # add sentences till legth is not too short\n max_tries = min(5, len(all_sentences))\n length_issue = ConversionIssue.TOO_SHORT\n\n if max_tries == 1:\n could_not_fix = True\n\n while length_issue == ConversionIssue.TOO_SHORT and (\n not could_not_fix):\n\n current_output = current_output + f\" {all_sentences[next_]}\"\n length_issue = self._length_check(current_output, meta['question'],\n meta['option'])\n next_ += 1\n\n if next_ >= max_tries:\n could_not_fix = True\n\n break\n\n return current_output, could_not_fix\n\n def __call__(self, inp: str, meta: Dict) -> Tuple[str, Dict]:\n cleaned = self.cleaner(inp)\n\n if self.sentence_splitter == 'spacy':\n sentences = [\n s.text.strip() for s in list(self.spacy_nlp(cleaned).sents)\n ]\n first_sent = (sentences[0]).strip()\n\n elif self.sentence_splitter == 'period':\n sentences = cleaned.split('.')\n first_sent = sentences[0]\n meta['all_sentences'] = sentences\n\n output = first_sent\n issues_encountered = []\n length_issue = self._length_check(output, meta['question'],\n meta['option'])\n\n if length_issue == ConversionIssue.TOO_SHORT:\n issues_encountered.append(length_issue)\n output, could_not_fix = self._fix_too_short(sentences, meta)\n\n if could_not_fix:\n issues_encountered.append(ConversionIssue.COULD_NOT_FIX)\n # check again\n length_issue = self._length_check(output, meta['question'],\n meta['option'])\n\n if length_issue == ConversionIssue.TOO_LONG:\n issues_encountered.append(length_issue)\n output = output[:int(\n math.ceil(self.upper_length_ratio *\n (len(meta['question']) + len(meta['option']))))]\n\n meta['conversion_issues'] = [\n str(issue) for issue in issues_encountered\n ]\n output = remove_excess_space(output)\n\n return output, meta\n","repo_name":"nli-for-qa/conversion","sub_path":"qa2nli/converters/processors.py","file_name":"processors.py","file_ext":"py","file_size_in_byte":6075,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"6"} +{"seq_id":"4654048278","text":"import numpy as np\nimport random\nimport math\n\nnumberOfNeurons = 8\n\ndef weightsPerVector(neuronVector):\n weights = np.zeros((numberOfNeurons , numberOfNeurons))\n for row in range(numberOfNeurons):\n for col in range(numberOfNeurons):\n if(row == col):\n weights[row][col] = 0\n else:\n weights[row][col] = neuronVector[row] * neuronVector[col]\n weights[col][row] = weights[row][col]\n return weights\n\ndef finalWeights(weights1 , weights2 , weights3):\n finalWeights = np.zeros((numberOfNeurons , numberOfNeurons))\n for row in range(numberOfNeurons):\n for col in range(numberOfNeurons):\n finalWeights[row][col] = (weights1[row][col] + weights2[row][col] + weights3[row][col]) / 8\n return finalWeights\n\ndef activation(finalWeights, inputVector):\n activations = np.zeros(numberOfNeurons)\n for index in range(numberOfNeurons):\n sum = 0\n opponent = 0\n while (opponent < 8):\n if (opponent == index):\n opponent = opponent + 1\n else:\n sum = sum + (finalWeights[index][opponent]* inputVector[opponent])\n opponent = opponent +1\n\n if (sum >= 0):\n activations[index] = 1\n elif ( sum <0):\n activations[index] = - 1 \n return activations\n\ndef run():\n iterations = 3\n iter = 0\n while(iter <= iterations):\n input1 = [ 1, -1 , 1 , -1 , 1, -1, -1 , 1]\n input2 = [1 , 1 , -1 , -1 , -1 , 1 , -1 , -1] \n input3 = [1 , 1, 1 , -1 , 1 , 1 , -1 , 1]\n weights1 = weightsPerVector(np.array(input1)) \n weights2 = weightsPerVector(np.array(input2)) \n weights3 = weightsPerVector(np.array(input3))\n final = finalWeights(weights1, weights2 , weights3)\n activations1 = activation(final , input1)\n activations2 = activation(final , input2)\n activations3 = activation(final , input3)\n iter = iter+1 \n print (activations1)\n print (activations2)\n print (activations3)\n\nrun()","repo_name":"ShivaBP/DD2437-ArtificialNeuralNetworks","sub_path":"Hopfield networks/Implementation/convergence.py","file_name":"convergence.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"20763764303","text":"def find(s):\n givenString = [char for char in s]\n givenStringLength = len(givenString)\n\n start = 0\n leftSide = ''\n\n for i in range(len(givenString)):\n leftSide += givenString[i]\n # print(f'LeftSide: {leftSide} Round {i+1} Repeats in rightSide {s.count(leftSide)} LeftSide length {len(leftSide)} RightSide length {len(givenString)} LeftSideLength * Repeats in rightSide {len(leftSide)*s.count(leftSide)}')\n\n matchFound = len(givenString) == len(leftSide) * s.count(leftSide)\n matchNotFound = not matchFound\n\n # Match found\n if matchFound:\n return len(leftSide)\n\n # Last round, no match\n isLastRound = ( i == len(givenString) - 1 )\n\n if matchNotFound and isLastRound:\n return len(givenString)\n\n\n\n\n\n\nif __name__ == \"__main__\":\n print(find(\"aaa\")) # 1\n print(find(\"abcd\")) # 4\n print(find(\"abcabcabcabc\")) # 3\n print(find(\"aybabtuaybabtu\")) # 7\n print(find(\"abcabca\")) # 7\n print(find('asdkhgasdkhgö'))","repo_name":"FUKA-INNOVATIONS/Algorithms-and-data-structures","sub_path":"tasks-python/Week-1/playground.py","file_name":"playground.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"18604444770","text":"import unittest\nfrom solana.rpc.async_api import AsyncClient\nfrom solana.keypair import Keypair\nfrom solana.publickey import PublicKey\nfrom pyaver.enums import SolanaNetwork\nfrom helpers.aver_client_setup_tests import aver_client_setup_tests\nfrom helpers.create_market_tests import create_init_market_smoke_tests\nfrom helpers.user_smoke_flow_tests import user_flow_smoke_tests\nfrom pyaver.aver_client import AverClient\nfrom pyaver.market import AverMarket\nfrom pyaver.constants import get_solana_endpoint\nfrom solana.rpc.types import TxOpts\nfrom solana.rpc.commitment import Confirmed\nimport base58 \n\n#####\n# This test is for the V1_1 upgrade\n# To use:\n# 1. Have a new program id (on V1.0) and input it below. Set Variable v1_1 to False\n# 2. Run the test. A new market should be created and read. Write down the market secret key\n# 3. Upgrade the same program id to V1.1 on chain\n# 4. Input the same market secret key to read from onchain on line 40.\n# 5. Run the test again with v1_1 as True. Now it should try to read the old market, upgrade it and read it again.\n# 6. If all this works without issues, V1_1 is successful\n#####\n\n#To run all code from an entirely new set of keypairs and markets, set this to True\nprogram_id = PublicKey('DfMQPAuAeECP7iSCwTKjbpzyx6X1HZT6rz872iYWA8St')\n\n#Set to TRUE if Public Key is on V1.1 - This will try to read and upgrade an old market and then read it again\n#Set to FALSE o/w - This will try to create a new market and read it\nv1_1 = True\n\nclass V1_1_Market_Test(unittest.IsolatedAsyncioTestCase):\n\n async def asyncSetUp(self):\n secret_key = base58.b58decode('3onYh3TSCg92X3kD9gD7RCZF1N8JFVSDp39eSkRswsQb5YwWuyMnzuCN2wuPb52XEnPzjVrCtkYe5Xo8Czd3CDyV')\n owner = Keypair.from_secret_key(secret_key)\n market = Keypair()\n market_authority = Keypair()\n\n if(v1_1):\n market = Keypair.from_secret_key(base58.b58decode('57DLck9gJaMkBpZ6hbj7XvPBCENyJ6rc6FucydqyKEEHtEtWM4umYfx3cFn8ztDEGFnue1vpyjAUgiSWuk1LT4tt'))\n else:\n print('-'*10)\n print('NEW MARKET IS BEING CREATED... NOTE DOWN SECRET KEY')\n print('Market: ', base58.b58encode(market.secret_key))\n print('Market pubkey: ', market.public_key)\n print('-'*10)\n\n network = SolanaNetwork.DEVNET\n opts = TxOpts(preflight_commitment=Confirmed)\n connection = AsyncClient(\n get_solana_endpoint(network),\n 'confirmed',\n timeout=30\n )\n client = await AverClient.load(connection, owner, opts, SolanaNetwork.DEVNET, [program_id])\n\n self.owner = owner\n self.client = client\n self.market = market\n self.market_authority = market_authority\n\n return await super().asyncSetUp()\n \n async def test_setup_tests(self):\n\n if(not v1_1):\n await create_init_market_smoke_tests(self.client, self.owner, 2, self.market, self.market_authority, program_id)\n market = await AverMarket.load(self.client, self.market.public_key)\n print('MARKET CREATED AND LOADED')\n print('MARKET STATE:')\n print(market.market_state)\n print('MARKET STORE STATE: ')\n print(market.market_store_state)\n print('-'*10)\n else:\n print('LOADING OLD MARKET')\n market = await AverMarket.load(self.client, self.market.public_key)\n print('MARKET CREATED AND LOADED')\n print('MARKET STATE:')\n print(market.market_state)\n print('MARKET STORE STATE: ')\n print(market.market_store_state)\n print('-'*10)\n\n print('UPGRADING MARKET BEGIN')\n sig = await market.update_market_state(self.client, self.owner, program_id)\n con = await self.client.provider.connection.confirm_transaction(sig['result'], Confirmed)\n print('MARKET UPGRADED')\n print('LOADING OLD MARKET')\n market = await AverMarket.load(self.client, self.market.public_key)\n print('MARKET CREATED AND LOADED')\n print('MARKET STATE:')\n print(market.market_state)\n print('MARKET STORE STATE: ')\n print(market.market_store_state)\n print('-'*10)\n\n\n\n async def asyncTearDown(self):\n await self.client.close()\n return await super().asyncTearDown()\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"AverBet/SDK","sub_path":"PY-SDK/admin/archive/v1_1_market_test.py","file_name":"v1_1_market_test.py","file_ext":"py","file_size_in_byte":4422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"72236542877","text":"\"\"\"\nIf the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.\n\nIf all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?\n\n\nNOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of \"and\" when writing out numbers is in compliance with British usage.\n\"\"\"\n\nwords = { 1:\"one\",\n 2:\"two\",\n 3:\"three\",\n 4:\"four\",\n 5:\"five\",\n 6:\"six\",\n 7:\"seven\",\n 8:\"eight\",\n 9:\"nine\",\n 10:\"ten\",\n 11:\"eleven\",\n 12:\"twelve\",\n 13:\"thirteen\",\n 14:\"fourteen\",\n 15:\"fifteen\",\n 16:\"sixteen\",\n 17:\"seventeen\",\n 18:\"eighteen\",\n 19:\"nineteen\",\n 20:\"twenty\",\n 30:\"thirty\",\n 40:\"forty\",\n 50:\"fifty\",\n 60:\"sixty\",\n 70:\"seventy\",\n 80:\"eighty\",\n 90:\"ninety\",\n }\n\ndef one(n):\n return len(words[int(n)])\n\ndef two(n):\n if n[0] == \"0\":\n return one(n[-1])\n elif (n[0] == \"1\") or ((n[0]!=\"0\") and (n[-1]==\"0\")):\n return len(words[int(\"\".join(n))])\n else:\n return len(words[int(\"\".join((n[0],\"0\")))]) + one(n[-1])\n\ndef three(n):\n if n[1]==n[2]==\"0\":\n return one(n[0]) + len(\"hundred\")\n else:\n return one(n[0]) + len(\"hundred\") + len(\"and\") + two(n[1:])\n\ndef getLength(number):\n # Max 1000\n number = list(str(number))\n length = 0\n print(number)\n\n if len(number)==3:\n return three(number)\n elif len(number)==2:\n return two(number)\n else:\n return one(number[0])\n\nif __name__ == \"__main__\":\n total = 0\n for i in range(1,1000):\n total += getLength(i)\n total += len(\"onethousand\")\n print(total)","repo_name":"jamesro/Project-Euler","sub_path":"Problem17.py","file_name":"Problem17.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"12327811284","text":"import numpy as np\nimport torch.nn as nn\nimport torch\nfrom analysis_settings import base_mask_size_, base_mask_height_width_\n\nclass Dynamic_MaskPair(nn.Module):\n\n def __init__(self, img_size=224, mask_size=224, upper_y=0, lower_y=0, upper_x=0, lower_x=0, base_mask_size=base_mask_size_, base_mask_height_width=base_mask_height_width_):\n super(Dynamic_MaskPair, self).__init__()\n self.episilon = 1e-12\n self.init_weights = 0.5\n self.img_size = img_size\n self.mask_size = mask_size\n self.upper_y = upper_y\n self.lower_y = lower_y\n self.upper_x = upper_x\n self.lower_x = lower_x\n self.base_mask_size = base_mask_size\n self.base_mask_height = base_mask_height_width[0]\n self.base_mask_width = base_mask_height_width[1]\n self.mask_batch = int((self.img_size/self.mask_size) * (self.img_size/self.mask_size))\n init_mask = np.full((1, self.base_mask_size, self.base_mask_size), self.init_weights)\n init_mask = init_mask.astype('float32')\n self.mask = nn.Parameter(torch.tensor(init_mask), requires_grad=True)\n\n def forward(self, x):\n upsample = nn.Upsample(size=(self.img_size, self.img_size), mode='bilinear', align_corners=True)\n real_mask = upsample(self.mask.unsqueeze(0))\n x = real_mask * x\n\n return x","repo_name":"ytpeng-tongji/MultipleDynamicMasks","sub_path":"dynamic_maskpair.py","file_name":"dynamic_maskpair.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"51"} +{"seq_id":"34145656151","text":"from pydantic import BaseModel\nfrom typing import Union, List\nfrom fastapi import APIRouter, Depends, HTTPException, status\nfrom fastapi.responses import JSONResponse\nfrom sqlalchemy import select, update, func\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom app.logic import utils\nfrom app.logic.consts import *\nfrom app.logic.queries import *\nfrom app.database import get_session\nfrom app.database.models import *\nfrom fastapi_jwt_auth import AuthJWT\nimport json\n\n\nclass ProductReviewIn(BaseModel):\n product_review_photo: Union[List[str], None]\n product_review_text: str\n product_review_grade: int\n\n\nclass ReactionIn(BaseModel):\n reaction: bool\n\n\nreviews = APIRouter()\n\n\n@reviews.post(\n \"/{product_id}/make_product_review/\",\n summary=\"WORKS: Create new product review, update grade_average for product. \"\n 'product_review_photo format is [\"URL1\", \"URL2\", ...] or empty [].',\n)\nasync def make_product_review(\n product_review: ProductReviewIn,\n product_id: int,\n Authorize: AuthJWT = Depends(),\n session: AsyncSession = Depends(get_session),\n):\n Authorize.jwt_required()\n user_email = json.loads(Authorize.get_jwt_subject())[\"email\"]\n seller_id = await Seller.get_seller_id_by_email(user_email)\n\n is_allowed = await session.execute(\n QUERY_IS_ALOWED_TO_REVIEW.format(seller_id=seller_id, product_id=product_id)\n )\n is_allowed = bool(is_allowed.scalar())\n if is_allowed:\n current_time = utils.get_moscow_datetime()\n grade_average = await session.execute(\n select(Product.grade_average).where(Product.id.__eq__(product_id))\n )\n grade_average = grade_average.scalar()\n if not grade_average:\n grade_average_new = product_review.product_review_grade\n else:\n review_count = await session.execute(\n select(func.count()).where(ProductReview.product_id.__eq__(product_id))\n )\n review_count = review_count.scalar()\n grade_average_new = round(\n (grade_average * review_count + product_review.product_review_grade)\n / (review_count + 1),\n 1,\n )\n await session.execute(\n update(Product)\n .where(Product.id.__eq__(product_id))\n .values(grade_average=grade_average_new)\n )\n await session.commit()\n review_data = ProductReview(\n product_id=product_id,\n seller_id=seller_id,\n text=product_review.product_review_text,\n grade_overall=product_review.product_review_grade,\n datetime=current_time,\n )\n session.add(review_data)\n await session.commit()\n product_review_id = await session.execute(\n select(ProductReview.id).where(ProductReview.product_id.__eq__(product_id))\n )\n product_review_id = product_review_id.scalar()\n if product_review.product_review_photo:\n for serial_number, image_url in enumerate(\n product_review.product_review_photo\n ):\n photo_review_data = ProductReviewPhoto(\n product_review_id=product_review_id,\n image_url=image_url,\n serial_number=serial_number,\n )\n session.add(photo_review_data)\n await session.commit()\n # need to make endpoint which checks added review\n await session.commit()\n return JSONResponse(\n status_code=status.HTTP_200_OK, content={\"result\": \"REVIEW_HAS_BEEN_SENT\"}\n )\n else:\n return HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail={\"result\": \"METHOD_NOT_ALLOWED\"},\n )\n\n\n@reviews.get(\n \"/{product_id}/show_product_review/\",\n summary=\"WORKS: get product_id, skip(def 0), limit(def 10), returns reviews\",\n)\nasync def get_10_product_reviews(\n product_id: int,\n skip: int = 0,\n limit: int = 10,\n session: AsyncSession = Depends(get_session),\n):\n if not isinstance(product_id, int):\n raise HTTPException(\n status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,\n detail=\"INVALID_PRODUCT_ID\",\n )\n if limit:\n quantity = f\"LIMIT {limit} OFFSET {skip}\"\n product_reviews = await session.execute(\n QUERY_FOR_REVIEWS.format(product_id=product_id, quantity=quantity)\n )\n else:\n quantity = \"\"\n product_reviews = await session.execute(\n QUERY_FOR_REVIEWS.format(product_id=product_id, quantity=quantity)\n )\n product_reviews = [dict(text) for text in product_reviews if product_reviews]\n\n # reactions = await session.execute(\n \n # )\n\n if product_reviews:\n return JSONResponse(status_code=status.HTTP_200_OK, content=product_reviews)\n else:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND, detail=\"REVIEWS_NOT_FOUND\"\n )\n\n\n@reviews.post(\n \"/{product_review_id}/product_review_reactions/\",\n summary=\"WORKS: query params(product_review_id and seller_id), body (reaction), insert reaction data\",\n)\nasync def make_reaction(\n product_review_id: int,\n reaction: ReactionIn,\n Authorize: AuthJWT = Depends(),\n session: AsyncSession = Depends(get_session),\n):\n Authorize.jwt_required()\n user_email = json.loads(Authorize.get_jwt_subject())[\"email\"]\n seller_id = await Seller.get_seller_id_by_email(user_email)\n is_product_review_exist = await session.execute(\n select(ProductReview.id).where(ProductReview.id.__eq__(product_review_id))\n )\n is_product_review_exist = is_product_review_exist.scalar()\n if not is_product_review_exist:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND, detail=\"REVIEW_NOT_FOUND\"\n )\n\n reaction_data = ProductReviewReaction(\n seller_id=seller_id,\n product_review_id=product_review_id,\n reaction=reaction.reaction,\n )\n session.add(reaction_data)\n await session.commit()\n return JSONResponse(\n status_code=status.HTTP_200_OK, content={\"status\": \"REACTION_HAS_BEEN_SENT\"}\n )\n","repo_name":"NikitaViktorov088/wb_platform","sub_path":"app/logic/routes/reviews.py","file_name":"reviews.py","file_ext":"py","file_size_in_byte":6177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"42249380725","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'blog'\nurlpatterns = [\n path('', views.BlogHomeView.as_view(), name='home'),\n path('create/', views.BlogCreateView.as_view(), name='blog-create'),\n path('blogs/', views.BlogListView.as_view(), name='blogs'),\n path('blog/', views.BlogDetailView.as_view(), name='blog-detail'),\n path('blogger/', views.BlogListbyAuthorView.as_view(), name='blogs-by-author'),\n path('blog//comment/', views.BlogCommentCreateView.as_view(), name='blog-comment'),\n]\n\nurlpatterns += [ \n # is identification for id field, \n # slug can also be used \n path('delete/', views.BlogDeleteView.as_view(), name='blog-delete'), \n path('comment//delete/', views.BlogCommentDeleteView.as_view(), name='blog-comment-delete'), \n]","repo_name":"slametsampon/smansa_gtg","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"27034670743","text":"###########\n# python csv2xml.py -dir Images -s CM2 -r 400x \n#\n#\n#\n#\n#############\n\nimport pandas as pd\nfrom yattag import Doc, indent\nimport argparse\nimport os\n\nparser = argparse.ArgumentParser(description='A test program.')\nparser.add_argument(\"-dir\", \"--data_dir\", help=\"Enter Path to data folder .\", default=\"data\")\nparser.add_argument(\"-s\", \"--slidenumber\", help=\"Enter the slide number.\", default=\"CM1\")\nparser.add_argument(\"-r\", \"--resolution\", help=\"1000x,400x,100x\", default=\"1000x\")\n\nargs = parser.parse_args()\nprint(args.resolution)\n\n\ndef create_xml(fname, box,path):\n\t#path = './'\n\n\tdoc, tag, text = Doc().tagtext()\n\n\twith tag('annotation'):\n\t with tag('folder'):\n\t \ttext('LabelledImages')\n\t with tag('filename'):\n\t \ttext(fname)\n\t with tag('path'):\n\t \ttext(path + fname)\n\t with tag('source'):\n\t \twith tag('database'):\n\t \t\ttext('Unknown')\n\t #with tag('size'):\n\t #with tag('width'):\n\t # text(width)\n\t #with tag('height'):\n\t # text(height)\n\t #with tag('depth'):\n\t # text(3)\n\t #with tag('segmented'):\n\t #\ttext(0)\n\n\t for b in box:\n\t \twith tag('size'):\n\t \twith tag('width'):\n\t \t\ttext(int(b[1]))\n\t \twith tag('height'):\n\t \t\ttext(int(b[2]))\n\t \twith tag('depth'):\n\t \t\ttext(3)\n\t \twith tag('segmented'):\n\t \t\ttext(0)\n\n\t \twith tag('object'):\n\t\t \twith tag('name'):\n\t\t \t\ttext(b[3].lower())\n\t\t \twith tag('pose'):\n\t\t \t\ttext('Unspecified')\n\t\t \twith tag('truncated'):\n\t\t \t\ttext(0)\n\t\t \twith tag('difficult'):\n\t\t \t\ttext(0)\n\t\t \twith tag('bndbox'):\n\t\t \t\twith tag('xmin'):\n\t\t \t\t\ttext(int(b[4]))\n\t\t \t\twith tag('ymin'):\n\t\t \t\t\ttext(int(b[5]))\n\t\t \t\twith tag('xmax'):\n\t\t \t\t\ttext(int(b[6]))\n\t\t \t\twith tag('ymax'):\n\t\t \t\t\ttext(int(b[7]))\n\tresult = indent(\n\t doc.getvalue(),\n\t indentation = ' '*4,\n\t newline = '\\r\\n'\n\t)\n\tfname = path+fname[:-4] + '.xml' #.split('.')[0] + '.xml'\n\t#print(fname)\n\tmyfile = open(fname, \"w\") \n\tmyfile.write(result)\n\tmyfile.close()\n\n# ***************************************************\n# Main function\n# ***************************************************\nimage_csv = os.path.join(os.getcwd(), args.data_dir + '/'+ args.slidenumber + '/' + args.resolution+ '/')\nprint('path to csv:',image_csv)\ndf = pd.read_csv(image_csv+ args.resolution + '_' + 'labels.csv')\n\nbox = []\nold_file = df.iloc[0,0]\nprint(len(df))\nfor i in range(0, len(df)):\n\tfname = df.iloc[i,0]\n\tif fname == old_file:\n\t\tbox.append([df.iloc[i,0],df.iloc[i,1],df.iloc[i,2],df.iloc[i,3],df.iloc[i,4], df.iloc[i,5], df.iloc[i,6], df.iloc[i,7]])\n\telse:\n\t\tcreate_xml(old_file, box,image_csv)\n\t\t#print('done:',i,old_file)\n\t\tbox = []\n\t\tbox.append([df.iloc[i,0],df.iloc[i,1],df.iloc[i,2],df.iloc[i,3],df.iloc[i,4], df.iloc[i,5], df.iloc[i,6], df.iloc[i,7]])\n\told_file = fname\ncreate_xml(old_file,box,image_csv)\nprint('done: Kill the waves')\n","repo_name":"Wajahat0/Annotation-Transfer-Across-the-Microscope","sub_path":"csv2xml.py","file_name":"csv2xml.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"6462016150","text":"import random, string\n\nfrom django.http import Http404, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom django.conf import settings\n\nfrom .process_views import process_get_amounts\nfrom ..forms import CheckoutForm\nfrom ..models import ProductInstance, Order, OrderItem\n\nimport razorpay\n\ndef order_checkout_start(request):\n if 'user_cart' in request.session.keys() and len(request.session['user_cart'].keys()) != 0:\n \n if request.method == 'GET':\n base_amount, additional_charges, payable_amount = process_get_amounts(request)\n form = CheckoutForm()\n cart_items = request.session['user_cart']\n\n cart_items_info = []\n for item in cart_items:\n cart_item_obj = {}\n product_instance = ProductInstance.objects.get(instance_id=item)\n cart_item_obj['product_name'] = product_instance.product.title\n cart_item_obj['product_size'] = product_instance.size\n cart_item_obj['instance_qty'] = cart_items[item]\n cart_item_obj['instance_total_price'] = cart_items[item] * float(product_instance.price)\n\n cart_items_info.append(cart_item_obj)\n\n # Passing amounts, and items only to display\n # Will retake the latest data in session before making payment\n return render(request, 'store/checkout_start.html', {\n 'base_amount': base_amount,\n 'additional_charges': additional_charges,\n 'payable_amount': payable_amount,\n 'cart_items_info': cart_items_info,\n 'form': form # Actually used in submission\n });\n\n elif request.method == 'POST':\n form = CheckoutForm(request.POST)\n if form.is_valid():\n customer_name = form.cleaned_data['customer_name']\n customer_phone_no = form.cleaned_data['customer_phone_no']\n customer_address = form.cleaned_data['customer_address']\n \n # Save sessions\n request.session['customer_name'] = customer_name\n request.session['customer_phone_no'] = customer_phone_no\n request.session['customer_address'] = customer_address\n\n return HttpResponseRedirect(reverse('checkout-confirm-1'))\n\n else:\n raise Http404\n\n else:\n raise Http404\n\n\ndef order_checkout_confirm_1(request):\n if ('user_cart' in request.session.keys() and len(request.session['user_cart'].keys()) != 0) and 'customer_name' in request.session.keys() and 'customer_phone_no' in request.session.keys() and 'customer_address' in request.session.keys():\n \n base_amount, additional_charges, payable_amount = process_get_amounts(request)\n\n cart_items = request.session['user_cart']\n customer_name = request.session['customer_name']\n customer_phone_no = request.session['customer_phone_no']\n customer_address = request.session['customer_address']\n\n cart_items_info = []\n for item in cart_items:\n cart_item_obj = {}\n product_instance = ProductInstance.objects.get(instance_id=item)\n cart_item_obj['product_name'] = product_instance.product.title\n cart_item_obj['product_size'] = product_instance.size\n cart_item_obj['instance_qty'] = cart_items[item]\n cart_item_obj['instance_total_price'] = cart_items[item] * float(product_instance.price)\n\n cart_items_info.append(cart_item_obj)\n\n request.session['confirmed_data'] = True\n\n return render(request, 'store/checkout_confirm.html', {\n 'base_amount': base_amount,\n 'additional_charges': additional_charges,\n 'payable_amount': payable_amount,\n 'cart_items_info' : cart_items_info,\n 'customer_name': customer_name,\n 'customer_phone_no': customer_phone_no,\n 'customer_address': customer_address,\n });\n\n else:\n raise Http404\n\n\ndef order_checkout_confirm_2(request):\n \n if ('user_cart' in request.session.keys() and len(request.session['user_cart'].keys()) != 0) and 'customer_name' in request.session.keys() and 'customer_phone_no' in request.session.keys() and 'customer_address' in request.session.keys() and ('confirmed_data' in request.session.keys() and request.session['confirmed_data'] == True):\n\n # Generate random string\n random_string = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(10))\n # Get amounts\n base_amount, additional_charges, payable_amount = process_get_amounts(request)\n # Customer details\n customer_name = request.session['customer_name']\n customer_phone_no = request.session['customer_phone_no']\n customer_address = request.session['customer_address']\n\n\n ## Make order\n order = Order(order_access_token=random_string, base_amount=base_amount, total_amount=payable_amount, customer_name=customer_name, customer_mobile_number=customer_phone_no, customer_address=customer_address)\n order.save() # save explicitly\n\n\n # Add all order items to it\n cart_items = request.session['user_cart']\n for item in cart_items:\n product_instance = ProductInstance.objects.get(instance_id=item)\n\n order_item = OrderItem(order=order, product_instance_id= product_instance.instance_id, quantity=cart_items[item])\n order_item.save() # save explicitly\n\n \n order_id = order.order_id\n payable_amount_paise = payable_amount * 100\n\n razorpay_key_id = settings.RAZORPAY_KED_ID\n\n return render(request, 'store/checkout_pay.html', {\n 'order_id': order_id,\n 'payable_amount_paise': payable_amount_paise,\n 'razorpay_key_id': razorpay_key_id,\n\n # Some additional info\n 'customer_name': customer_name,\n 'customer_phone_no': customer_phone_no,\n 'customer_address': customer_address\n })\n \n else:\n raise Http404\n\n\ndef order_checkout_end(request):\n\n if request.method == 'POST' and request.POST.get('correct_submit', None) and request.POST.get('razorpay_payment_id', None):\n\n # Initially clear session data\n request.session.clear() \n \n # collect payment id from automaitc form submit\n payment_id = request.POST.get('razorpay_payment_id', None)\n\n # get client\n client = razorpay.Client(auth=(settings.RAZORPAY_KED_ID, settings.RAZORPAY_KEY_SECRET))\n # get payment object\n resp_get_payment = client.payment.fetch(payment_id)\n\n # check that payment was authorized\n if resp_get_payment[\"status\"] == \"authorized\":\n\n paid_amount = resp_get_payment[\"amount\"]\n # description = resp_get_payment[\"description\"]\n # contact_no = resp_get_payment[\"contact\"]\n # total_charges = resp_get_payment[\"fee\"]\n # tax_charges = resp_get_payment[\"tax\"]\n # created_time = resp_get_payment[\"created_at\"]\n # address = resp_get_payment[\"notes\"]['address']\n order_id_str = resp_get_payment[\"notes\"]['dborderid']\n\n order_id = int(order_id_str)\n\n order = Order.objects.get(order_id=order_id)\n\n if float(order.total_amount)*100 == paid_amount:\n \n if order.is_payed == False:\n\n order.is_payed = True\n order.payment_id = payment_id\n order.save() # explicitly save\n\n # capture payment\n resp_capture_payment = client.payment.capture(payment_id, paid_amount)\n\n if resp_capture_payment[\"status\"] == \"captured\":\n \n order.is_captured = True\n order.save() # explicitly save\n\n return render(request, 'store/checkout_end.html', {\n 'order_id': order_id,\n 'order_access_token': order.order_access_token,\n 'order_success': True\n })\n\n else:\n print(\"Problem in capturing payment\")\n return render(request, 'store/checkout_end.html', {\n 'order_failure': True\n })\n\n else:\n print(\"Order is already payed\")\n return render(request, 'store/checkout_end.html', {\n 'order_failure': True\n })\n\n else:\n print(\"Payment amount mismatched\")\n return render(request, 'store/checkout_end.html', {\n 'order_failure': True\n })\n\n else:\n print(\"Payment was not authorised\")\n return render(request, 'store/checkout_end.html', {\n 'order_failure': True\n })\n\n else:\n raise Http404","repo_name":"abhishek-nigam/ecommerce-store-uniform","sub_path":"store/views/order_views.py","file_name":"order_views.py","file_ext":"py","file_size_in_byte":9177,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"51"} +{"seq_id":"74561910559","text":"from command.basic_command import ChaosBladeCommand\nfrom utils.k8s import get_all_src_names_dest_ips\n\n\nclass SvcSvcNetworkDelay(ChaosBladeCommand):\n def __init__(self, ip, src, dest, interface, time, duration, interval, namespace):\n \"\"\"Chaosblade k8s pod-network delay\n\n For example:\n create k8s pod-network delay\n --namespace default\n --names ts-admin-route-service-77cd6cf987-c4nm7,ts-admin-route-service-77cd6cf987-jr88g\n --interface eth0\n --destination-ip 10.244.107.213,10.244.107.232\n --time 500\n --kubeconfig ~/.kube/config\n\n :param ip: blade server ip (port: 9526). e.g., 10.176.122.154\n :param src: src service name used to obtain pod names. e.g., ts-admin-route-service\n :param dest: dest service name used to obatin pod ips. e.g., ts-station-service\n :param interface: network interface. e.g., eth0\n :param time: delay time (ms). e.g., 500\n :param duration: duration of the fault injection (s). e.g., 300\n :param interval: interval between current and next fault injections (s). e.g., 300\n :param namespace: k8s deployment namespace. e.g., default\n \"\"\"\n super(SvcSvcNetworkDelay, self).__init__(duration, interval)\n self.fault_type = 'svc-svc-network-delay'\n self.ip = ip\n self.src = src\n self.dest = dest\n self.interface = interface\n self.time = time\n self.namespace = namespace\n\n def __str__(self):\n return f'[svc-svc-network-delay] ip: {self.ip} src: {self.src} dest: {self.dest} ' \\\n f'interface: {self.interface} time: {self.time} namespace: {self.namespace}'\n\n def init(self):\n src_pod_names, dest_pod_names, dest_pod_ips = get_all_src_names_dest_ips(self.namespace, self.src, self.dest)\n self.cmd = f\"create k8s pod-network delay \" \\\n f\"--namespace {self.namespace} \" \\\n f\"--names {','.join(src_pod_names)} \" \\\n f\"--interface {self.interface} \" \\\n f\"--destination-ip {','.join(dest_pod_ips)} \" \\\n f\"--time {self.time} \" \\\n f\"--kubeconfig ~/.kube/config\"\n self.root_cause = f\"{self.src}({','.join(src_pod_names)}) {self.dest}({','.join(dest_pod_names)})\"\n\n\nclass SvcSvcNetworkDrop(ChaosBladeCommand):\n\n def __init__(self, ip, src, dest, interface, duration, interval, namespace):\n \"\"\"Chaosblade k8s container-network drop\n\n For example:\n create k8s container-network drop\n --namespace default\n --names ts-travel2-service-686c895647-s2jcx,ts-travel2-service-686c895647-tgd5d\n --container-names ts-travel2-service\n --destination-ip 10.244.169.152,10.244.195.193\n --network-traffic out\n --use-sidecar-container-network\n --kubeconfig ~/.kube/config\n\n :param ip: blade server ip (port: 9526). e.g., 10.176.122.154\n :param src: src service name used to obtain pod names. e.g., ts-travel2-service\n :param dest: dest service name used to obatin pod ips. e.g., ts-basic-service\n :param interface: network interface. e.g., eth0\n :param duration: duration of the fault injection (s). e.g., 300\n :param interval: interval between current and next fault injections (s). e.g., 300\n :param namespace: k8s deployment namespace. e.g., default\n \"\"\"\n super(SvcSvcNetworkDrop, self).__init__(duration, interval)\n self.fault_type = 'svc-svc-network-drop'\n self.ip = ip\n self.src = src\n self.dest = dest\n self.interface = interface\n self.namespace = namespace\n\n def __str__(self):\n return f'[svc-svc-network-drop] ip: {self.ip} src: {self.src} dest: {self.dest} ' \\\n f'interface: {self.interface} namespace: {self.namespace}'\n\n def init(self):\n src_pod_names, dest_pod_names, dest_pod_ips = get_all_src_names_dest_ips(self.namespace, self.src, self.dest)\n self.cmd = f\"create k8s container-network drop \" \\\n f\"--namespace {self.namespace} \" \\\n f\"--names {','.join(src_pod_names)} \" \\\n f\"--container-names {self.src} \" \\\n f\"--destination-ip {','.join(dest_pod_ips)} \" \\\n f\"--network-traffic out \" \\\n f\"--use-sidecar-container-network \" \\\n f\"--kubeconfig ~/.kube/config\"\n self.root_cause = f\"{self.src}({','.join(src_pod_names)}) {self.dest}({','.join(dest_pod_names)})\"\n","repo_name":"zbcdd/fault_injection","sub_path":"command/chaos_blade/svc_svc.py","file_name":"svc_svc.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"21802994650","text":"import Widget\n\nclass DynamoDB_Widget(Widget.Widget):\n\n def convert_content(self):\n new_content = dict()\n new_content['widgetId'] = {\n 'S' : self.content['widgetId']\n }\n\n new_content['owner'] = {\n 'S' : self.content['owner']\n }\n\n new_content['label'] = {\n 'S' : self.content['label']\n }\n\n new_content['description'] = {\n 'S' : self.content['description']\n }\n\n for attribute in self.content['otherAttributes']:\n new_content[attribute['name']] = {\n 'S' : attribute['value']\n \n }\n\n self.content = new_content\n\n\n def __init__(self, content):\n super().__init__(content)\n self.convert_content()\n\n def create_widget(self, client, destination):\n client.put_item(TableName=destination, Item=self.content)\n","repo_name":"daxinator22/cs5260-hw2-dax-thompson","sub_path":"consumer/DynamoDB_Widget.py","file_name":"DynamoDB_Widget.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"765489185","text":"from airflow.utils.decorators import apply_defaults\nfrom blocksec_plugin.contract_interaction_operator import ContractInteractionOperator\nfrom blocksec_plugin.abis import TELLOR_ABI\n\n\nclass TellorOracleOperator(ContractInteractionOperator):\n template_fields = ['request_id', 'price']\n\n @apply_defaults\n def __init__(self,\n request_id,\n price,\n *args,\n **kwargs):\n super().__init__(abi_json=TELLOR_ABI, *args, **kwargs)\n self.request_id = request_id\n self.price = price\n\n def execute(self, context):\n\n self.function = self.contract.functions.submitValue\n self.function_args = {\"_requestId\": int(self.request_id), \"_value\": int(self.price)}\n return super().execute(context)\n","repo_name":"Ricochet-Exchange/ricochet-keeper","sub_path":"dags/blocksec_plugin/tellor_oracle_operator.py","file_name":"tellor_oracle_operator.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"51"} +{"seq_id":"2246167408","text":"arr = list(map(int, input().split()))\r\nar = []\r\n\r\nfor i in range(len(arr)):\r\n x = arr.pop(i)\r\n y = sum(arr)\r\n arr.insert(i,x)\r\n ar.append(y)\r\n \r\nprint(min(ar),max(ar))","repo_name":"JoyTarafder/CSE211-Algorithms-Programming-Contest-Autumn-2022","sub_path":"H_-_Mini_Max_Sum.py","file_name":"H_-_Mini_Max_Sum.py","file_ext":"py","file_size_in_byte":182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"36262271888","text":"from .baseresource import BaseResource\n\n\nclass InningOne(BaseResource):\n class Meta(BaseResource.Meta):\n identifier = 'inning_one'\n attributes = {\n 'overs': 'overs',\n 'runs': 'runs',\n 'wickets': 'wickets'\n }\n\n\nclass Home(BaseResource):\n class Meta(BaseResource.Meta):\n identifier = 'home'\n attributes = {\n 'bookingPoints': 'booking_points',\n 'fullTimeScore': 'full_time_score',\n 'games': 'games',\n 'halfTimeScore': 'half_time_score',\n 'name': 'name',\n 'numberOfCards': 'number_of_cards',\n 'numberOfCorners': 'number_of_corners',\n 'numberOfCornersFirstHalf': 'number_of_corners_first_half',\n 'numberOfCornersSecondHalf': 'number_of_corners_second_half',\n 'numberOfRedCards': 'number_of_red_cards',\n 'numberOfYellowCards': 'number_of_yellow_cards',\n 'penaltiesScore': 'penalties_score',\n 'penaltiesSequence': 'penalties_sequence',\n 'score': 'score',\n 'sets': 'sets',\n 'highlight': 'highlight',\n 'aces': 'aces',\n 'doubleFaults': 'double_faults',\n 'gameSequence': 'game_sequence',\n 'isServing': 'is_serving',\n 'playerSeed': 'player_seed',\n 'serviceBreaks': 'service_breaks',\n }\n sub_resources = {\n 'inning1': InningOne\n }\n\n\nclass Away(BaseResource):\n class Meta(BaseResource.Meta):\n identifier = 'away'\n attributes = {\n 'bookingPoints': 'booking_points',\n 'fullTimeScore': 'full_time_score',\n 'games': 'games',\n 'halfTimeScore': 'half_time_score',\n 'name': 'name',\n 'numberOfCards': 'number_of_cards',\n 'numberOfCorners': 'number_of_corners',\n 'numberOfCornersFirstHalf': 'number_of_corners_first_half',\n 'numberOfCornersSecondHalf': 'number_of_corners_second_half',\n 'numberOfRedCards': 'number_of_red_cards',\n 'numberOfYellowCards': 'number_of_yellow_cards',\n 'penaltiesScore': 'penalties_score',\n 'penaltiesSequence': 'penalties_sequence',\n 'score': 'score',\n 'sets': 'sets',\n 'highlight': 'highlight',\n 'aces': 'aces',\n 'doubleFaults': 'double_faults',\n 'gameSequence': 'game_sequence',\n 'isServing': 'is_serving',\n 'playerSeed': 'player_seed',\n 'serviceBreaks': 'service_breaks',\n }\n sub_resources = {\n 'inning1': InningOne\n }\n\n\nclass Score(BaseResource):\n class Meta(BaseResource.Meta):\n identifier = 'score'\n attributes = {\n 'bookingPoints': 'booking_points',\n 'numberOfCards': 'number_of_cards',\n 'numberOfCorners': 'number_of_corners',\n 'numberOfCornersFirstHalf': 'number_of_corners_first_half',\n 'numberOfCornersSecondHalf': 'number_of_corners_second_half',\n 'numberOfRedCards': 'number_of_red_cards',\n 'numberOfYellowCards': 'number_of_yellow_cards'\n\n }\n sub_resources = {\n 'away': Away,\n 'home': Home,\n }\n\n\nclass UpdateDetail(BaseResource):\n class Meta(BaseResource.Meta):\n identifier = 'update_detail'\n attributes = {\n 'elapsedRegularTime': 'elapsed_regular_time',\n 'matchTime': 'match_time',\n 'type': 'type',\n 'updateId': 'update_id',\n 'updateTime': 'update_time',\n 'updateType': 'update_type',\n 'team': 'team',\n 'teamName': 'team_name',\n }\n datetime_attributes = (\n 'updateTime'\n )\n\n\nclass EventTimeline(BaseResource):\n class Meta(BaseResource.Meta):\n identifier = 'event_timeline'\n attributes = {\n 'eventId': 'event_id',\n 'elapsedRegularTime': 'elapsed_regular_time',\n 'eventTypeId': 'event_type_id',\n 'inPlayMatchStatus': 'in_play_match_status',\n 'status': 'status',\n 'timeElapsed': 'time_elapsed'\n\n }\n sub_resources = {\n 'score': Score,\n 'updateDetails': UpdateDetail,\n }\n\n\nclass FullTimeElapsed(BaseResource):\n class Meta(BaseResource.Meta):\n identifier = 'full_time_elapsed'\n attributes = {\n 'hour': 'hour',\n 'min': 'min',\n 'sec': 'sec'\n }\n\n\nclass StateOfBall(BaseResource):\n class Meta(BaseResource.Meta):\n identifier = 'state_of_ball'\n attributes = {\n 'appealId': 'appeal_id',\n 'appealTypeName': 'appeal_type_name',\n 'batsmanName': 'batsman_name',\n 'batsmanRuns': 'batsman_runs',\n 'bowlerName': 'bowler_name',\n 'bye': 'bye',\n 'dismissalTypeName': 'dismissal_type_name',\n 'legBye': 'leg_bye',\n 'noBall': 'no_ball',\n 'outcomeId': 'outcome_id',\n 'overBallNumber': 'over_ball_number',\n 'overNumber': 'over_number',\n 'referralOutcome': 'referral_outcome',\n 'wide': 'wide'\n }\n\n\nclass Scores(BaseResource):\n class Meta(BaseResource.Meta):\n identifier = 'scores'\n attributes = {\n 'eventId': 'event_id',\n 'elapsedRegularTime': 'elapsed_regular_time',\n 'elapsedAddedTime': 'elapsed_added_time',\n 'eventTypeId': 'event_type_id',\n 'matchStatus': 'match_status',\n 'timeElapsed': 'time_elapsed',\n 'timeElapsedSeconds': 'time_elapsed_seconds',\n 'status': 'status',\n 'currentDay': 'current_day',\n 'currentSet': 'current_set',\n 'description': 'description',\n 'matchType': 'match_type',\n 'currentGame': 'current_game',\n 'currentPoint': 'current_point'\n }\n sub_resources = {\n 'fullTimeElapsed': FullTimeElapsed,\n 'score': Score,\n 'stateOfBall': StateOfBall\n }\n","repo_name":"ElissandroMendes/betfairlightweight","sub_path":"betfairlightweight/resources/inplayserviceresources.py","file_name":"inplayserviceresources.py","file_ext":"py","file_size_in_byte":6159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"51"} +{"seq_id":"73132083998","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nlog = logging.getLogger(__name__)\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\n\n# Standard library imports\n\n# External imports\nfrom six import string_types\n\n# Bokeh imports\nfrom ..core.enums import HorizontalLocation, VerticalLocation\nfrom ..core.properties import Auto, Either, Enum, Int, Seq, Instance, String\nfrom ..models import GMapPlot, LinearAxis, MercatorTicker, MercatorTickFormatter, Range1d, Title, Tool\nfrom ..models import glyphs, markers\nfrom ..models.tools import Drag, Inspection, Scroll, Tap\nfrom ..util.options import Options\nfrom .helpers import _process_tools_arg, _process_active_tools, _glyph_function\n\n#-----------------------------------------------------------------------------\n# Globals and constants\n#-----------------------------------------------------------------------------\n\nDEFAULT_TOOLS = \"pan,wheel_zoom,reset,help\"\n\n__all__ = (\n 'GMap',\n 'GMapFigureOptions',\n 'gmap'\n)\n\n#-----------------------------------------------------------------------------\n# General API\n#-----------------------------------------------------------------------------\n\nclass GMap(GMapPlot):\n ''' A subclass of :class:`~bokeh.models.plots.Plot` that simplifies plot\n creation with default axes, grids, tools, etc.\n\n Args:\n google_api_key (str):\n Google requires an API key be supplied for maps to function. See:\n\n https://developers.google.com/maps/documentation/javascript/get-api-key\n\n map_options: (GMapOptions)\n Configuration specific to a Google Map\n\n In addition to all the Bokeh model property attributes documented below,\n the ``Figure`` initializer also accepts the following options, which can\n help simplify configuration:\n\n .. bokeh-options:: GMapFigureOptions\n :module: bokeh.plotting.figure\n\n '''\n\n __subtype__ = \"GMap\"\n __view_model__ = \"GMapPlot\"\n\n def __init__(self, **kw):\n\n if 'plot_width' in kw and 'width' in kw:\n raise ValueError(\"Figure called with both 'plot_width' and 'width' supplied, supply only one\")\n if 'plot_height' in kw and 'height' in kw:\n raise ValueError(\"Figure called with both 'plot_height' and 'height' supplied, supply only one\")\n if 'height' in kw:\n kw['plot_height'] = kw.pop('height')\n if 'width' in kw:\n kw['plot_width'] = kw.pop('width')\n\n opts = GMapFigureOptions(kw)\n\n title = kw.get(\"title\", None)\n if isinstance(title, string_types):\n kw['title'] = Title(text=title)\n\n super(GMap, self).__init__(x_range=Range1d(), y_range=Range1d(), **kw)\n\n xf = MercatorTickFormatter(dimension=\"lon\")\n xt = MercatorTicker(dimension=\"lon\")\n self.add_layout(LinearAxis(formatter=xf, ticker=xt), 'below')\n\n yf = MercatorTickFormatter(dimension=\"lat\")\n yt = MercatorTicker(dimension=\"lat\")\n self.add_layout(LinearAxis(formatter=yf, ticker=yt), 'left')\n\n tool_objs, tool_map = _process_tools_arg(self, opts.tools)\n self.add_tools(*tool_objs)\n _process_active_tools(self.toolbar, tool_map, opts.active_drag, opts.active_inspect, opts.active_scroll, opts.active_tap)\n\n annular_wedge = _glyph_function(glyphs.AnnularWedge)\n\n annulus = _glyph_function(glyphs.Annulus)\n\n arc = _glyph_function(glyphs.Arc)\n\n asterisk = _glyph_function(markers.Asterisk)\n\n bezier = _glyph_function(glyphs.Bezier)\n\n circle = _glyph_function(markers.Circle)\n\n circle_cross = _glyph_function(markers.CircleCross)\n\n circle_x = _glyph_function(markers.CircleX)\n\n cross = _glyph_function(markers.Cross)\n\n dash = _glyph_function(markers.Dash)\n\n diamond = _glyph_function(markers.Diamond)\n\n diamond_cross = _glyph_function(markers.DiamondCross)\n\n hbar = _glyph_function(glyphs.HBar)\n\n ellipse = _glyph_function(glyphs.Ellipse)\n\n image = _glyph_function(glyphs.Image)\n\n image_rgba = _glyph_function(glyphs.ImageRGBA)\n\n image_url = _glyph_function(glyphs.ImageURL)\n\n inverted_triangle = _glyph_function(markers.InvertedTriangle)\n\n line = _glyph_function(glyphs.Line)\n\n multi_line = _glyph_function(glyphs.MultiLine)\n\n multi_polygons = _glyph_function(glyphs.MultiPolygons)\n\n oval = _glyph_function(glyphs.Oval)\n\n patch = _glyph_function(glyphs.Patch)\n\n patches = _glyph_function(glyphs.Patches)\n\n quad = _glyph_function(glyphs.Quad)\n\n quadratic = _glyph_function(glyphs.Quadratic)\n\n ray = _glyph_function(glyphs.Ray)\n\n rect = _glyph_function(glyphs.Rect)\n\n segment = _glyph_function(glyphs.Segment)\n\n square = _glyph_function(markers.Square)\n\n square_cross = _glyph_function(markers.SquareCross)\n\n square_x = _glyph_function(markers.SquareX)\n\n text = _glyph_function(glyphs.Text)\n\n triangle = _glyph_function(markers.Triangle)\n\n vbar = _glyph_function(glyphs.VBar)\n\n wedge = _glyph_function(glyphs.Wedge)\n\n x = _glyph_function(markers.X)\n\ndef gmap(google_api_key, map_options, **kwargs):\n ''' Create a new :class:`~bokeh.plotting.gmap.GMap` for plotting.\n\n Args:\n google_api_key (str):\n Google requires an API key be supplied for maps to function. See:\n\n https://developers.google.com/maps/documentation/javascript/get-api-key\n\n map_options: (GMapOptions)\n Configuration specific to a Google Map\n\n In addition to the standard :class:`~bokeh.plotting.gmap.GMap` keyword\n arguments (e.g. ``plot_width`` or ``sizing_mode``), the following\n additional options can be passed as well:\n\n .. bokeh-options:: GMapFigureOptions\n :module: bokeh.plotting.gmap\n\n Returns:\n GMap\n\n '''\n\n return GMap(api_key=google_api_key, map_options=map_options, **kwargs)\n\n#-----------------------------------------------------------------------------\n# Dev API\n#-----------------------------------------------------------------------------\n\nclass GMapFigureOptions(Options):\n\n tools = Either(String, Seq(Either(String, Instance(Tool))), default=DEFAULT_TOOLS, help=\"\"\"\n Tools the plot should start with.\n \"\"\")\n\n x_minor_ticks = Either(Auto, Int, default=\"auto\", help=\"\"\"\n Number of minor ticks between adjacent x-axis major ticks.\n \"\"\")\n\n y_minor_ticks = Either(Auto, Int, default=\"auto\", help=\"\"\"\n Number of minor ticks between adjacent y-axis major ticks.\n \"\"\")\n\n x_axis_location = Enum(VerticalLocation, default=\"below\", help=\"\"\"\n Where the x-axis should be located.\n \"\"\")\n\n y_axis_location = Enum(HorizontalLocation, default=\"left\", help=\"\"\"\n Where the y-axis should be located.\n \"\"\")\n\n x_axis_label = String(default=\"\", help=\"\"\"\n A label for the x-axis.\n \"\"\")\n\n y_axis_label = String(default=\"\", help=\"\"\"\n A label for the y-axis.\n \"\"\")\n\n active_drag = Either(Auto, String, Instance(Drag), default=\"auto\", help=\"\"\"\n Which drag tool should initially be active.\n \"\"\")\n\n active_inspect = Either(Auto, String, Instance(Inspection), Seq(Instance(Inspection)), default=\"auto\", help=\"\"\"\n Which drag tool should initially be active.\n \"\"\")\n\n active_scroll = Either(Auto, String, Instance(Scroll), default=\"auto\", help=\"\"\"\n Which scroll tool should initially be active.\n \"\"\")\n\n active_tap = Either(Auto, String, Instance(Tap), default=\"auto\", help=\"\"\"\n Which tap tool should initially be active.\n \"\"\")\n\n#-----------------------------------------------------------------------------\n# Private API\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Code\n#-----------------------------------------------------------------------------\n","repo_name":"holzschu/Carnets","sub_path":"Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/plotting/gmap.py","file_name":"gmap.py","file_ext":"py","file_size_in_byte":7905,"program_lang":"python","lang":"en","doc_type":"code","stars":510,"dataset":"github-code","pt":"51"} +{"seq_id":"9031727301","text":"#!/usr/bin/env python3.4\n\n#\n# Usage: ./get_latests.py [-s splitter] [-v] url [item-name.ext]\n#\n\n#import requests\nimport urllib.request\nimport re\nimport sys\nimport argparse\n\nsplitter = '-'\nitem2n_ve = r\"(?P(.*)){splitter}(?P(.*))$\"\nve2v_e = r\"(?P((\\d+)((\\.(\\d+))*)))(?P(.*))\"\nne2n_e = r\"^(?P[^\\.]*)(?P\\..*)$\"\nitem_def = r\"\\S+)\\\">(?P\\S+)\"\n\ndef get_info(item):\n nve = re.match(item2n_ve.format(splitter=splitter), item)\n if nve:\n ver_ext = nve.group('ver_ext')\n ve = re.match(ve2v_e, ver_ext)\n if ve: # with extension\n return (nve.group('name'), ve.group('ver'), ve.group('ext'))\n else: # no extension\n return (nve.group('name'), '', '')\ndef get_latests(html):\n a = re.findall(item_def, html)\n latests = dict()\n for _ui, i in a:\n res = get_info(i)\n if res:\n n, v, e = res\n if latests.get((n, e), '0') < v:\n latests[(n, e)] = v\n\n return latests\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-s', '--splitter')\n parser.add_argument('-v', '--version', action='store_true', default=False)\n parser.add_argument('url')\n parser.add_argument('name_ext', nargs='?', default=False)\n args = parser.parse_args()\n \n# For requests \n # r = requests.get(url)\n # base_url = r.url\n # html = r.text\n\n# For urllib2\n r = urllib.request.urlopen(args.url)\n base_url = r.geturl()\n html = str(r.read())\n\n if args.name_ext:\n ne = re.match(ne2n_e, args.name_ext)\n name = ne.group('name')\n ext = ne.group('ext')\n latests = get_latests(html)\n for ne, v in latests.items():\n n, e = ne\n if n==name and e==ext:\n if args.version:\n print(v)\n else:\n print(base_url+n+args.splitter+v+e)\n\n else:\n latests = get_latests(html)\n for ne, v in latests.items():\n n, e = ne\n print(base_url+n+args.splitter+v+e)\n","repo_name":"lambd433/get_latests","sub_path":"get_latests.py","file_name":"get_latests.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"16103514114","text":"from ...helpers import LoggedInApplicationTest\nimport pytest\nimport mock\nimport csv\n\n\nclass TestDirectAwardView(LoggedInApplicationTest):\n def setup_method(self, method):\n super().setup_method(method)\n self.data_api_client_patch = mock.patch('app.main.views.direct_award.data_api_client', autospec=True)\n self.data_api_client = self.data_api_client_patch.start()\n\n def teardown_method(self, method):\n self.data_api_client_patch.stop()\n super().teardown_method(method)\n\n @pytest.mark.parametrize(\"role,expected_code\", [\n (\"admin\", 403),\n (\"admin-manager\", 403),\n (\"admin-ccs-category\", 200),\n (\"admin-ccs-sourcing\", 200),\n (\"admin-framework-manager\", 200),\n ])\n def test_outcomes_csv_download_permissions(self, role, expected_code):\n self.user_role = role\n response = self.client.get('/admin/direct-award/outcomes')\n actual_code = response.status_code\n assert actual_code == expected_code, \"Unexpected response {} for role {}\".format(actual_code, role)\n\n def test_outcomes_csv_download_content(self):\n self.user_role = 'admin-ccs-sourcing'\n find_direct_award_projects_result = {\n \"links\": {\n \"self\": \"http://localhost:5000/direct-award/projects?latest-first=1&user-id=19175\"\n },\n \"meta\": {\n \"total\": 20\n },\n \"projects\": [\n {\n \"active\": True,\n \"createdAt\": \"2018-06-22T10:41:31.281853Z\",\n \"downloadedAt\": None,\n \"id\": 731851428862851,\n \"lockedAt\": None,\n \"name\": \"gfgffd\",\n \"outcome\": {\n \"result\": \"cancelled\"\n },\n \"users\": [\n {\n \"active\": True,\n \"emailAddress\": \"buyer@example.com\",\n \"id\": 123,\n \"name\": \"A Buyer\",\n \"role\": \"buyer\"\n }\n ]\n },\n {\n \"active\": True,\n \"createdAt\": \"2018-06-19T13:36:37.557144Z\",\n \"downloadedAt\": \"2018-06-19T13:37:30.849304Z\",\n \"id\": 272774709812396,\n \"lockedAt\": \"2018-06-19T13:37:03.176398Z\",\n \"name\": \"22\",\n \"outcome\": {\n \"award\": {\n \"awardValue\": \"1234.00\",\n \"awardingOrganisationName\": \"123321\",\n \"endDate\": \"2020-12-12\",\n \"startDate\": \"2002-12-12\"\n },\n \"completed\": True,\n \"completedAt\": \"2018-06-19T13:37:59.713497Z\",\n \"id\": 680306864633356,\n \"result\": \"awarded\",\n \"resultOfDirectAward\": {\n \"archivedService\": {\n \"id\": 266018,\n \"service\": {\n \"id\": \"316684326093280\"\n }\n },\n \"project\": {\n \"id\": 272774709812396\n },\n \"search\": {\n \"id\": 3706\n }\n }\n },\n \"users\": [\n {\n \"active\": True,\n \"emailAddress\": \"buyer@example.com\",\n \"id\": 123,\n \"name\": \"A Buyer\",\n \"role\": \"buyer\"\n }\n ]\n }\n ]\n }\n\n get_archived_service_result = {\n 'services': {\n 'supplierId': 266018,\n 'supplierName': 'Somerford Associates Limited',\n 'serviceName': 'testServiceName'\n }\n }\n\n self.data_api_client.get_archived_service.return_value = get_archived_service_result\n self.data_api_client.find_direct_award_projects.return_value = find_direct_award_projects_result\n\n response = self.client.get('/admin/direct-award/outcomes')\n assert response.status_code == 200\n assert response.content_type == 'text/csv; charset=utf-8'\n response_data = str(response.data, 'utf-8').splitlines() # convert byte-string to string\n data = csv.reader(response_data)\n assert data # checks if CSV is valid\n\n rows = []\n for row in data:\n rows.append(row)\n\n # checks that only awarded outcomes are shown\n assert len(rows) == 2\n\n # checks headers\n assert rows[0] == [\n 'ID', 'Name', 'Submitted at', 'Result',\n 'Award service ID', 'Award service name',\n 'Award supplier id', 'Award supplier name',\n 'Award value', 'Awarding organisation name',\n 'Award start date', 'Award end date',\n 'User id', 'User name', 'User email'\n ]\n\n # checks results\n assert rows[1] == [\n '272774709812396', '22', '2018-06-19T13:37:59.713497Z', 'awarded',\n '316684326093280', 'testServiceName', '266018', 'Somerford Associates Limited',\n '1234.00', '123321', '2002-12-12', '2020-12-12',\n '123', 'A Buyer', 'buyer@example.com'\n ]\n","repo_name":"Tubbz-alt/digitalmarketplace-admin-frontend","sub_path":"tests/app/main/views/test_direct_award.py","file_name":"test_direct_award.py","file_ext":"py","file_size_in_byte":5708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"51"} +{"seq_id":"32570717682","text":"\"\"\"def pesquisa_binaria(A, item):\n somador = 0\n esquerda, direita = 0, len(A) - 1\n while esquerda <= direita:\n meio = (esquerda + direita) // 2\n if A[meio] <= item:\n somador = somador + 1\n A[meio] = 0\n return somador\n elif A[meio] > item:\n direita = meio - 1\n else: \n esquerda = meio + 1\n return -1\n\n\na = dict(enumerate([0]*1000, 1))\n\n\nlista = []\nlista2 = []\n\nlargura, comprimento = map(int, input().split())\n\nmatriz = [[int(x) for x in input(). split()] for i in range(largura)]\n\nhoras = int(input())\n\ninstantes = [int(z) for z in input().split()]\n\n\nfor inicio in range(largura):\n for inicio2 in range(comprimento):\n lista.append(int(matriz[inicio][inicio2]))\n\nlista.sort()\n\n\n\nfor cada in range(len(instantes)):\n f = instantes[cada]\n\n \n \n for cada_elemento in range(len(lista)):\n \n if lista[cada_elemento] <= f:\n \n lista2.append(lista[cada_elemento])\n \n\n print(len(lista2))\n lista2 = []\"\"\"\n \n\n\"\"\"\ndef pesquisa_binaria(A, item):\n somador = 0\n esquerda, direita = 0, len(A) - 1\n while esquerda <= direita:\n meio = (esquerda + direita) // 2\n if A[meio] <= item:\n somador = somador + 1\n A[meio] = 0\n return somador\n elif A[meio] > item:\n direita = meio - 1\n else: \n esquerda = meio + 1\n return -1\n\"\"\"\n\n\na = dict(enumerate([0]*1000, 1))\n\n\n\nlargura, comprimento = map(int, input().split())\n\n\n\nfor i in range(largura):\n for x in input().split():\n\t a[int(x)] += 1\n\n\nhoras = int(input())\n\ninstantes = [int(z) for z in input().split()]\n\nva = list(a.values())\n\nfor inst in instantes:\n soma = 0\n soma = sum(va[:inst])\n print(soma)","repo_name":"jeffersonraimon/Computacao-UFBA","sub_path":"MATA37-ILP 2021.2/JUDE/Lista 6 e Prova 6 - Ordenação e Busca Binária/lista6_H.py","file_name":"lista6_H.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"pt","doc_type":"code","stars":3,"dataset":"github-code","pt":"51"} +{"seq_id":"9519424375","text":"def main():\n testcases=int(input(''))\n\n lowerend = []\n higherend = []\n ys = [[]]\n for i in range(testcases):\n lowerend.append(int(input('')))\n higherend.append(int(input('')))\n\n for i in range(testcases):\n y=primer(higherend[i],lowerend[i])\n ys.append(y)\n for i in range(1,len(ys)):\n\n for j in range(len(ys[i])):\n print('{}'.format(ys[i][j]))\n\n\ndef primer(higherend,lowerend):\n x=[]\n\n y=list(range(2,higherend+1))\n for j in range(2,higherend+1):\n flag=0\n for k in range(2,j):\n if j % k == 0:\n flag = 1\n\n if flag == 1:\n x.append(j)\n break\n\n y = [t for t in y if t not in x and t>=lowerend]\n return y\n\n\nif __name__=='__main__':\n main()","repo_name":"Gunjack25/Python","sub_path":"PrimeNo..py","file_name":"PrimeNo..py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"14636014195","text":"import math\n\nn, a, b = (int(i) for i in input().split())\n\nx = b-a\nif ((x % 2) == 0):\n print(math.floor(x/2))\n exit()\nelse:\n print(min(a-1, n-b) + 1 + (b-a-1)//2)\n exit()\n","repo_name":"Ntakato/AtCoder","sub_path":"AGC041/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"32305410927","text":"import pygame\nimport os\nfrom board import Board\n\nPATH = os.path.abspath('.') + '/'\nboard = pygame.transform.scale(pygame.image.load(PATH + 'board.png'),(693,693))\nrect = (50, 50, 593, 592)\n\n\ndef redraw_gamewindow():\n global win, bo\n win.blit(board, (0, 0))\n bo.draw(win, board)\n pygame.display.update()\n\n\ndef click(pos):\n x = pos[0]\n y = pos[1]\n if rect[0] < x < rect[0] + rect[2]:\n if rect[1] < x < rect[1] + rect[3]:\n divX = x - rect[0]\n divY = y - rect[0]\n i = int(divX / (rect[2] / 8))\n j = int(divY / (rect[3] / 8))\n return i, j\n\n\ndef main():\n global bo\n bo = Board(8, 8)\n clock = pygame.time.Clock()\n run = True\n while run:\n clock.tick(10)\n redraw_gamewindow()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n quit()\n run = False\n pygame.quit()\n\n if event.type == pygame.MOUSEMOTION:\n pass\n if event.type == pygame.MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n i, j = click(pos)\n # bo.board[i][j].selected = True\n bo.select(i, j)\n\n\nwidth = 693\nheight = 693\nwin = pygame.display.set_mode((width, height), pygame.SCALED)\npygame.display.set_caption(\"Chess game\")\nmain()\n","repo_name":"Prome-theus/chessmultiplayer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"36209857164","text":"from flask import Flask, request, render_template\nfrom users_db import is_user_registered, add_user, count_users, init_db\nimport os\n\napp = Flask(__name__)\ninit_db()\n\n@app.route(\"/form\", methods=[\"POST\", \"GET\"])\ndef call_form():\n if request.method == \"POST\":\n result = request.form\n user = [result[\"name\"], result[\"email\"]]\n if is_user_registered(user):\n msg = \"Error! This contact is already in the list.\"\n list_size = f\"{count_users()}\"\n return render_template(\"index.html\", data={\"list_size\": list_size, \"msg\": msg})\n else:\n msg = \"Success! You have added a new contact to the list.\"\n add_user(user)\n list_size = f\"{count_users()}\"\n return render_template(\"index.html\", data={\"list_size\": list_size, \"msg\": msg})\n\n return render_template('form.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n\n","repo_name":"abir-hasan/PythonGround","sub_path":"web_science/assignment_4/simpleapp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"29674348829","text":"import os\nimport unittest\n\nimport ddt\nfrom selenium import webdriver\n\nfrom common.read_excel import ExcelUtil\nfrom pages.login_page import LoginPage, login_url\n\n# testdates = [\n# {\"user\":\"liuyuepeng\",\"psw\":\"123456789\",\"expect\":True},\n# {\"user\":\"liuyuepeng\",\"psw\":\"\",\"expect\":False},\n# {\"user\":\"liuyuepeng1\",\"psw\":\"1234567890\",\"expect\":False}\n# ]\n\ncurpath = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))#项目相关路径\nfilepath = os.path.join(curpath,\"common\",\"ceshishuju.xlsx\")#用项目相关路径+文件路径\n#print(filepath) #打印路径\n\n# filepath = r\"/Users/chabuduoxiansheng/PycharmProjects/练习/API/common/ceshishuju.xlsx\"\ndata = ExcelUtil(filepath)\ntestdates = data.dict_data()\n#print(testdates) 打印数据\n\n@ddt.ddt #增加ddt\nclass LonginCase(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.driver = webdriver.Chrome()\n cls.loginp = LoginPage(cls.driver)\n\n def setUp(self):\n self.driver.get(login_url) #打开网址\n\n def login_case(self,user,psw,expect):\n self.loginp.input_user(user)\n self.loginp.input_psw(psw)\n self.loginp.click_login_button()\n #断言\n #result = self.loginp.get_login_name()# 判断元素是否存在\n result = self.loginp.get_login_result(user) # 判断元素文本是否正确\n if expect == \"True\":expect_result = True\n else:expect_result = False\n print(\"测试结果:%s\"%result)\n self.assertTrue(result == expect)\n\n @ddt.data(*testdates) #传testdates中的参数\n #1.输入账号,输入密码,点击登录\n def test_01(self,data):\n #data1 = testdates[0]\n print(\"测试数据:%s\"%data)\n self.login_case(data[\"user\"],data[\"psw\"],data[\"expect\"])\n\n def tearDown(self):\n self.driver.delete_all_cookies() # 清空cookies\n self.driver.refresh() # 刷新\n\n @classmethod\n def tearDownClass(cls):\n cls.driver.quit()\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"fengzhihen521/python","sub_path":"web_autox/case/test_add_ddt1.py","file_name":"test_add_ddt1.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"15880163330","text":"class Solution:\n def isLongPressedName(self, name: str, typed: str) -> bool:\n\n\n def string_split(ss):\n ss_split = []\n s, e = 0, 0\n c = ss[0]\n while e < len(ss):\n if ss[e] == c:\n e += 1\n continue\n ss_split.append(ss[s:e])\n c = ss[e]\n s = e\n e += 1\n ss_split.append(ss[s:e])\n return ss_split\n\n name_split = string_split(name)\n typed_split = string_split(typed)\n if len(name_split) != len(typed_split):\n return False\n for i in range(len(name_split)):\n if not (name_split[i] in typed_split[i]):\n return False\n\n return True\n\n\nname = 'saeed'\ntyped = 'ssaaedd'\nss = Solution()\nprint(ss.isLongPressedName(name, typed))","repo_name":"zqlao/leetcode","sub_path":"Google/isLongPressedName.py","file_name":"isLongPressedName.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"30196160415","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport os\n\nTITANIC_PATH = os.path.join(\"datasets\", \"titanic\")\n\n\n# In[2]:\n\n\nimport pandas as pd\n\n##def load_titanic_data(filename, titanic_path=TITANIC_PATH):\n## csv_path = os.path.join(titanic_path, filename)\n## return pd.read_csv(csv_path)\n\n\n# In[3]:\n\n\ntrain_data = pd.read_csv(\"train.csv\")\ntest_data = pd.read_csv(\"test.csv\")\n##train_data = load_titanic_data(\"train.csv\")\n##test_data = load_titanic_data(\"test.csv\")\n\n\n# In[4]:\n\n\ntrain_data.head()\n\n\n# In[5]:\n\n\ntest_data.head()\n\n\n# In[6]:\n\n\ntrain_data.shape\n\n\n# In[7]:\n\n\ntrain_data[\"Survived\"].value_counts()\n\n\n# In[8]:\n\n\ntrain_data.describe()\n\n\n# In[9]:\n\n\ntrain_data.info()\n\n\n# In[10]:\n\n\ntest_data.shape\n\n\n# In[11]:\n\n\ntest_data.info()\n\n\n# In[12]:\n\n\ntrain_data.isnull().sum()\n\n\n# In[13]:\n\n\ntest_data.isnull().sum()\n\n\n# In[14]:\n\n\n#get_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n\n\n# In[15]:\n\n\nsns.countplot(data=train_data, x='Pclass', hue=\"Survived\")\n\n\n# In[17]:\n\n\nsns.pointplot(data=train_data, x='Pclass', y='Fare', hue=\"Survived\") \n\n\n# In[18]:\n\n\nsex_df = train_data.groupby(['Sex','Survived'])['Survived'].count().unstack('Survived')\nsex_df.plot(kind='bar', figsize=(7,4))\nplt.show()\n\n\n# In[19]:\n\n\nsns.countplot(data=train_data, x=\"Embarked\")\n\n\n# In[20]:\n\n\nsns.countplot(data=train_data, x=\"Embarked\", hue=\"Survived\")\n\n\n# In[21]:\n\n\nsns.distplot(train_data[\"Fare\"], hist=False)\n\n\n# In[22]:\n\n\ntrain_test_data = [train_data, test_data] # combining train and test dataset\n\nfor dataset in train_test_data:\n dataset['Title'] = dataset['Name'].str.extract(' ([A-Za-z]+)\\.', expand=False)\n\n\n# In[23]:\n\n\ntrain_data['Title'].value_counts()\n\n\n# In[24]:\n\n\ntest_data['Title'].value_counts()\n\n\n# In[25]:\n\n\ntitle_mapping = {\"Mr\": 0, \"Miss\": 1, \"Mrs\": 2, \n \"Master\": 3, \"Dr\": 3, \"Rev\": 3, \"Col\": 3, \"Major\": 3, \"Mlle\": 3,\"Countess\": 3,\n \"Ms\": 3, \"Lady\": 3, \"Jonkheer\": 3, \"Don\": 3, \"Dona\" : 3, \"Mme\": 3,\"Capt\": 3,\"Sir\": 3 }\nfor dataset in train_test_data:\n dataset['Title'] = dataset['Title'].map(title_mapping)\n\n\n# In[26]:\n\n\n# delete unnecessary feature from dataset\ntrain_data.drop('Name', axis=1, inplace=True)\ntest_data.drop('Name', axis=1, inplace=True)\n\n\n# In[27]:\n\n\n# fill missing age with median age for each title (Mr, Mrs, Miss, Others)\ntrain_data[\"Age\"].fillna(train_data.groupby(\"Title\")[\"Age\"].transform(\"median\"), inplace=True)\ntest_data[\"Age\"].fillna(test_data.groupby(\"Title\")[\"Age\"].transform(\"median\"), inplace=True)\n\n\n# In[28]:\n\n\ntrain_data.groupby(\"Title\")[\"Age\"].transform(\"median\")\n\n\n# In[29]:\n\n\nsns.distplot(train_data[\"Age\"],hist=False)\n\n\n# In[30]:\n\n\nperish=train_data[train_data['Survived'] == 0]\nsurvived =train_data[train_data['Survived']==1]\n\nsns.distplot(perish['Age'], hist=False, label=\"Perish\")\nsns.distplot(survived['Age'], hist=False, label=\"Survived\")\n\n\n# In[31]:\n\n\nsns.distplot(train_data['Fare'],hist=False)\n\n\n# In[32]:\n\n\nlow_fare = train_data[train_data['Fare'] < 100]\nprint(low_fare.shape)\nlow_fare.head(3)\n\n\n# In[33]:\n\n\nperish=low_fare[low_fare['Survived'] == 0]\nsurvived =low_fare[low_fare['Survived']==1]\n\nsns.distplot(perish['Fare'],hist=False, label=\"Perish\")\nsns.distplot(survived['Fare'],hist=False, label=\"Survived\")\n\n\n# In[34]:\n\n\nsns.lmplot(data=low_fare, x='Age',y=\"Fare\", hue=\"Survived\", fit_reg=False)\n\n\n# In[35]:\n\n\nfor dataset in train_test_data:\n dataset.loc[ dataset['Age'] <= 16, 'Age'] = 0,\n dataset.loc[(dataset['Age'] > 16) & (dataset['Age'] <= 26), 'Age'] = 1,\n dataset.loc[(dataset['Age'] > 26) & (dataset['Age'] <= 36), 'Age'] = 2,\n dataset.loc[(dataset['Age'] > 36) & (dataset['Age'] <= 62), 'Age'] = 3,\n dataset.loc[ dataset['Age'] > 62, 'Age'] = 4\n\n\n# In[36]:\n\n\nPclass1 = train_data[train_data['Pclass']==1]['Embarked'].value_counts()\nPclass2 = train_data[train_data['Pclass']==2]['Embarked'].value_counts()\nPclass3 = train_data[train_data['Pclass']==3]['Embarked'].value_counts()\ndf = pd.DataFrame([Pclass1, Pclass2, Pclass3])\ndf.index = ['1st class','2nd class', '3rd class']\ndf.plot(kind='bar',stacked=True, figsize=(10,5))\n\n\n# In[37]:\n\n\nfor dataset in train_test_data:\n dataset['Embarked'] = dataset['Embarked'].fillna('S')\n\n\n# In[38]:\n\n\nembarked_mapping = {\"S\": 0, \"C\": 1, \"Q\": 2}\nfor dataset in train_test_data:\n dataset['Embarked'] = dataset['Embarked'].map(embarked_mapping)\n\n\n# In[39]:\n\n\n# fill missing Fare with median fare for each Pclass\ntrain_data[\"Fare\"].fillna(train_data.groupby(\"Pclass\")[\"Fare\"].transform(\"median\"), inplace=True)\ntest_data[\"Fare\"].fillna(test_data.groupby(\"Pclass\")[\"Fare\"].transform(\"median\"), inplace=True)\n\n\n# In[40]:\n\n\nfor dataset in train_test_data:\n dataset.loc[ dataset['Fare'] <= 17, 'Fare'] = 0,\n dataset.loc[(dataset['Fare'] > 17) & (dataset['Fare'] <= 30), 'Fare'] = 1,\n dataset.loc[(dataset['Fare'] > 30) & (dataset['Fare'] <= 100), 'Fare'] = 2,\n dataset.loc[ dataset['Fare'] > 100, 'Fare'] = 3\n\n\n# In[41]:\n\n\nfor dataset in train_test_data:\n dataset['Cabin'] = dataset['Cabin'].str[:1]\n\n\n# In[42]:\n\n\nPclass1 = train_data[train_data['Pclass']==1]['Cabin'].value_counts()\nPclass2 = train_data[train_data['Pclass']==2]['Cabin'].value_counts()\nPclass3 = train_data[train_data['Pclass']==3]['Cabin'].value_counts()\ndf = pd.DataFrame([Pclass1, Pclass2, Pclass3])\ndf.index = ['1st class','2nd class', '3rd class']\ndf.plot(kind='bar',stacked=True, figsize=(10,5))\n\n\n# In[43]:\n\n\ncabin_mapping = {\"A\": 0, \"B\": 0.4, \"C\": 0.8, \"D\": 1.2, \"E\": 1.6, \"F\": 2, \"G\": 2.4, \"T\": 2.8}\nfor dataset in train_test_data:\n dataset['Cabin'] = dataset['Cabin'].map(cabin_mapping)\n\n\n# In[44]:\n\n\n# fill missing Fare with median fare for each Pclass\ntrain_data[\"Cabin\"].fillna(train_data.groupby(\"Pclass\")[\"Cabin\"].transform(\"median\"), inplace=True)\ntest_data[\"Cabin\"].fillna(test_data.groupby(\"Pclass\")[\"Cabin\"].transform(\"median\"), inplace=True)\n\n\n# In[45]:\n\n\n# delete unnecessary feature from dataset\ntrain_data.drop('Ticket', axis=1, inplace=True)\ntest_data.drop('Ticket', axis=1, inplace=True)\n\n\n# In[46]:\n\n\n# delete unnecessary feature from dataset\ntrain_data.drop('PassengerId', axis=1, inplace=True)\ntest_data.drop('PassengerId', axis=1, inplace=True)\n\n\n# In[47]:\n\n\ntrain_data.head()\n\n\n# In[48]:\n\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.utils import check_array\nfrom sklearn.preprocessing import LabelEncoder\nfrom scipy import sparse\n\nclass CategoricalEncoder(BaseEstimator, TransformerMixin):\n \"\"\"Encode categorical features as a numeric array.\n The input to this transformer should be a matrix of integers or strings,\n denoting the values taken on by categorical (discrete) features.\n The features can be encoded using a one-hot aka one-of-K scheme\n (``encoding='onehot'``, the default) or converted to ordinal integers\n (``encoding='ordinal'``).\n This encoding is needed for feeding categorical data to many scikit-learn\n estimators, notably linear models and SVMs with the standard kernels.\n Read more in the :ref:`User Guide `.\n Parameters\n ----------\n encoding : str, 'onehot', 'onehot-dense' or 'ordinal'\n The type of encoding to use (default is 'onehot'):\n - 'onehot': encode the features using a one-hot aka one-of-K scheme\n (or also called 'dummy' encoding). This creates a binary column for\n each category and returns a sparse matrix.\n - 'onehot-dense': the same as 'onehot' but returns a dense array\n instead of a sparse matrix.\n - 'ordinal': encode the features as ordinal integers. This results in\n a single column of integers (0 to n_categories - 1) per feature.\n categories : 'auto' or a list of lists/arrays of values.\n Categories (unique values) per feature:\n - 'auto' : Determine categories automatically from the training data.\n - list : ``categories[i]`` holds the categories expected in the ith\n column. The passed categories are sorted before encoding the data\n (used categories can be found in the ``categories_`` attribute).\n dtype : number type, default np.float64\n Desired dtype of output.\n handle_unknown : 'error' (default) or 'ignore'\n Whether to raise an error or ignore if a unknown categorical feature is\n present during transform (default is to raise). When this is parameter\n is set to 'ignore' and an unknown category is encountered during\n transform, the resulting one-hot encoded columns for this feature\n will be all zeros.\n Ignoring unknown categories is not supported for\n ``encoding='ordinal'``.\n Attributes\n ----------\n categories_ : list of arrays\n The categories of each feature determined during fitting. When\n categories were specified manually, this holds the sorted categories\n (in order corresponding with output of `transform`).\n Examples\n --------\n Given a dataset with three features and two samples, we let the encoder\n find the maximum value per feature and transform the data to a binary\n one-hot encoding.\n >>> from sklearn.preprocessing import CategoricalEncoder\n >>> enc = CategoricalEncoder(handle_unknown='ignore')\n >>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])\n ... # doctest: +ELLIPSIS\n CategoricalEncoder(categories='auto', dtype=<... 'numpy.float64'>,\n encoding='onehot', handle_unknown='ignore')\n >>> enc.transform([[0, 1, 1], [1, 0, 4]]).toarray()\n array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.],\n [ 0., 1., 1., 0., 0., 0., 0., 0., 0.]])\n See also\n --------\n sklearn.preprocessing.OneHotEncoder : performs a one-hot encoding of\n integer ordinal features. The ``OneHotEncoder assumes`` that input\n features take on values in the range ``[0, max(feature)]`` instead of\n using the unique values.\n sklearn.feature_extraction.DictVectorizer : performs a one-hot encoding of\n dictionary items (also handles string-valued features).\n sklearn.feature_extraction.FeatureHasher : performs an approximate one-hot\n encoding of dictionary items or strings.\n \"\"\"\n\n def __init__(self, encoding='onehot', categories='auto', dtype=np.float64,\n handle_unknown='error'):\n self.encoding = encoding\n self.categories = categories\n self.dtype = dtype\n self.handle_unknown = handle_unknown\n\n def fit(self, X, y=None):\n \"\"\"Fit the CategoricalEncoder to X.\n Parameters\n ----------\n X : array-like, shape [n_samples, n_feature]\n The data to determine the categories of each feature.\n Returns\n -------\n self\n \"\"\"\n\n if self.encoding not in ['onehot', 'onehot-dense', 'ordinal']:\n template = (\"encoding should be either 'onehot', 'onehot-dense' \"\n \"or 'ordinal', got %s\")\n raise ValueError(template % self.handle_unknown)\n\n if self.handle_unknown not in ['error', 'ignore']:\n template = (\"handle_unknown should be either 'error' or \"\n \"'ignore', got %s\")\n raise ValueError(template % self.handle_unknown)\n\n if self.encoding == 'ordinal' and self.handle_unknown == 'ignore':\n raise ValueError(\"handle_unknown='ignore' is not supported for\"\n \" encoding='ordinal'\")\n\n X = check_array(X, dtype=np.object, accept_sparse='csc', copy=True)\n n_samples, n_features = X.shape\n\n self._label_encoders_ = [LabelEncoder() for _ in range(n_features)]\n\n for i in range(n_features):\n le = self._label_encoders_[i]\n Xi = X[:, i]\n if self.categories == 'auto':\n le.fit(Xi)\n else:\n valid_mask = np.in1d(Xi, self.categories[i])\n if not np.all(valid_mask):\n if self.handle_unknown == 'error':\n diff = np.unique(Xi[~valid_mask])\n msg = (\"Found unknown categories {0} in column {1}\"\n \" during fit\".format(diff, i))\n raise ValueError(msg)\n le.classes_ = np.array(np.sort(self.categories[i]))\n\n self.categories_ = [le.classes_ for le in self._label_encoders_]\n\n return self\n\n def transform(self, X):\n \"\"\"Transform X using one-hot encoding.\n Parameters\n ----------\n X : array-like, shape [n_samples, n_features]\n The data to encode.\n Returns\n -------\n X_out : sparse matrix or a 2-d array\n Transformed input.\n \"\"\"\n X = check_array(X, accept_sparse='csc', dtype=np.object, copy=True)\n n_samples, n_features = X.shape\n X_int = np.zeros_like(X, dtype=np.int)\n X_mask = np.ones_like(X, dtype=np.bool)\n\n for i in range(n_features):\n valid_mask = np.in1d(X[:, i], self.categories_[i])\n\n if not np.all(valid_mask):\n if self.handle_unknown == 'error':\n diff = np.unique(X[~valid_mask, i])\n msg = (\"Found unknown categories {0} in column {1}\"\n \" during transform\".format(diff, i))\n raise ValueError(msg)\n else:\n # Set the problematic rows to an acceptable value and\n # continue `The rows are marked `X_mask` and will be\n # removed later.\n X_mask[:, i] = valid_mask\n X[:, i][~valid_mask] = self.categories_[i][0]\n X_int[:, i] = self._label_encoders_[i].transform(X[:, i])\n\n if self.encoding == 'ordinal':\n return X_int.astype(self.dtype, copy=False)\n\n mask = X_mask.ravel()\n n_values = [cats.shape[0] for cats in self.categories_]\n n_values = np.array([0] + n_values)\n indices = np.cumsum(n_values)\n\n column_indices = (X_int + indices[:-1]).ravel()[mask]\n row_indices = np.repeat(np.arange(n_samples, dtype=np.int32),\n n_features)[mask]\n data = np.ones(n_samples * n_features)[mask]\n\n out = sparse.csc_matrix((data, (row_indices, column_indices)),\n shape=(n_samples, indices[-1]),\n dtype=self.dtype).tocsr()\n if self.encoding == 'onehot-dense':\n return out.toarray()\n else:\n return out\n\n\n# In[49]:\n\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nclass DataFrameSelector(BaseEstimator, TransformerMixin):\n def __init__(self, attribute_names):\n self.attribute_names = attribute_names\n def fit(self, X, y=None):\n return self\n def transform(self, X):\n return X[self.attribute_names]\n\n\n# In[50]:\n\n\nfrom sklearn.pipeline import Pipeline\n#from sklearn.preprocessing import Imputer\nfrom sklearn.impute import SimpleImputer\n\nimputer = SimpleImputer(strategy=\"median\")\n\nnum_pipeline = Pipeline([\n (\"select_numeric\", DataFrameSelector([\"Age\", \"SibSp\", \"Parch\", \"Fare\"])),\n (\"imputer\", SimpleImputer(strategy=\"median\")),\n ])\n\n\n# In[51]:\n\n\nnum_pipeline.fit_transform(train_data)\n\n\n# In[53]:\n\n\nclass MostFrequentImputer(BaseEstimator, TransformerMixin):\n def fit(self, X, y=None):\n self.most_frequent_ = pd.Series([X[c].value_counts().index[0] for c in X],\n index=X.columns)\n return self\n def transform(self, X, y=None):\n return X.fillna(self.most_frequent_)\n\n\n# In[54]:\n\n\ncat_pipeline = Pipeline([\n (\"select_cat\", DataFrameSelector([\"Pclass\", \"Sex\", \"Embarked\"])),\n (\"imputer\", MostFrequentImputer()),\n (\"cat_encoder\", CategoricalEncoder(encoding='onehot-dense')),\n ])\n\n\n# In[55]:\n\n\n# from future_encoders import OneHotEncoder\nfrom sklearn.preprocessing import OneHotEncoder\n\ncat_pipeline = Pipeline([\n (\"select_cat\", DataFrameSelector([\"Pclass\", \"Sex\", \"Embarked\"])),\n (\"imputer\", MostFrequentImputer()),\n (\"cat_encoder\", OneHotEncoder(sparse=False)),\n ])\n\n\n# In[56]:\n\n\ncat_pipeline = Pipeline([\n (\"select_cat\", DataFrameSelector([\"Pclass\", \"Sex\", \"Embarked\"])),\n (\"imputer\", SimpleImputer(strategy='most_frequent')),\n (\"cat_encoder\", OneHotEncoder(sparse=False)),\n ])\n\n\n# In[57]:\n\n\ncat_pipeline.fit_transform(train_data)\n\n\n# In[58]:\n\n\nfrom sklearn.pipeline import FeatureUnion\npreprocess_pipeline = FeatureUnion(transformer_list=[\n (\"num_pipeline\", num_pipeline),\n (\"cat_pipeline\", cat_pipeline),\n ])\n\n\n# In[59]:\n\n\nfrom sklearn.compose import ColumnTransformer\n\nnum_pipeline = Pipeline([\n (\"imputer\", SimpleImputer(strategy=\"median\"))\n ])\n\ncat_pipeline = Pipeline([\n (\"imputer\", SimpleImputer(strategy='most_frequent')),\n (\"cat_encoder\", OneHotEncoder(sparse=False)),\n ])\n\npreprocess_pipeline = ColumnTransformer([\n (\"num_pipeline\", num_pipeline, [\"Age\", \"SibSp\", \"Parch\", \"Fare\"]),\n (\"cat_pipeline\", cat_pipeline, [\"Pclass\", \"Sex\", \"Embarked\"]),\n ])\n\n\n# In[60]:\n\n\nX_train = preprocess_pipeline.fit_transform(train_data)\nX_train\n\n\n# In[61]:\n\n\ny_train = train_data[\"Survived\"]\n\n\n# In[76]:\n\n\n# Importing Classifier Modules\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\n\nimport numpy as np\n\n\n# In[77]:\n\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nk_fold = KFold(n_splits=10, shuffle=True, random_state=0)\n\n\n# In[92]:\n\n\nknn_clf = KNeighborsClassifier(n_neighbors = 13)\nscoring = 'accuracy'\nknn_scores = cross_val_score(knn_clf, X_train, y_train, cv=k_fold, n_jobs=1, scoring=scoring)\nknn_scores.mean()\n\n\n# In[79]:\n\n\n# kNN Score\nround(np.mean(knn_scores)*100, 2)\n\n\n# In[91]:\n\n\ndecision_clf = DecisionTreeClassifier()\nscoring = 'accuracy'\ndecision_scores = cross_val_score(decision_clf, X_train, y_train, cv=k_fold, n_jobs=1, scoring=scoring)\ndecision_scores.mean()\n\n\n# In[81]:\n\n\n# decision tree Score\nround(np.mean(decision_scores)*100, 2)\n\n\n# In[82]:\n\n\nfrom sklearn.svm import SVC\n\nsvm_clf = SVC(gamma='auto')\nsvm_clf.fit(X_train, y_train)\n\n\n# In[83]:\n\n\nX_test = preprocess_pipeline.transform(test_data)\ny_pred = svm_clf.predict(X_test)\n\n\n# In[84]:\n\n\nfrom sklearn.model_selection import cross_val_score\n\nsvm_scores = cross_val_score(svm_clf, X_train, y_train, cv=10)\nsvm_scores.mean()\n\n\n# In[85]:\n\n\nfrom sklearn.ensemble import RandomForestClassifier\n\nforest_clf = RandomForestClassifier(n_estimators=10, random_state=42)\nforest_scores = cross_val_score(forest_clf, X_train, y_train, cv=10)\nforest_scores.mean()\n\n\n# In[89]:\n\n\nnb_clf = GaussianNB()\nscoring = 'accuracy'\nnb_scores = cross_val_score(nb_clf, X_train, y_train, cv=k_fold, n_jobs=1, scoring=scoring)\nnb_scores.mean()\n\n\n# In[87]:\n\n\n# Naive Bayes Score\nround(np.mean(nb_scores)*100, 2)\n\n\n# In[93]:\n\n\nplt.figure(figsize=(10, 6))\nplt.plot([1]*10, knn_scores, \".\")\nplt.plot([2]*10, decision_scores, \".\")\nplt.plot([3]*10, svm_scores, \".\")\nplt.plot([4]*10, forest_scores, \".\")\nplt.plot([5]*10, nb_scores, \".\")\nplt.boxplot([knn_scores, decision_scores, svm_scores, forest_scores, nb_scores], \n labels=(\"KNN\", \"Decision Tree\", \"SVM\", \"Random Forest\", \"Naive Bayes\"))\nplt.ylabel(\"Accuracy\", fontsize=14)\nplt.show()\n\n","repo_name":"ksy1231/Machine_Learning","sub_path":"Project_Software_Package/Titanic.py","file_name":"Titanic.py","file_ext":"py","file_size_in_byte":19503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"14015337048","text":"import os\nimport argparse\nimport logging\nfrom collections import Counter\n\nfrom tqdm import tqdm\nfrom gensim import utils\n\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n\ndef main(args):\n logging.info('preprocessing started.')\n rest = b''\n pbar = tqdm(desc='Reading corpus',\n total=os.path.getsize(args.corpus),\n unit='B', unit_scale=True, unit_divisor=1024)\n if args.uncased:\n args.entities = os.path.splitext(args.entities)[0] + '_uncased.txt'\n with utils.smart_open(args.corpus) as fin,\\\n open(args.entities, 'w', encoding='utf-8') as fout:\n lexicons = Counter()\n while True:\n text = rest + fin.read(8192) # avoid loading the entire file (=1 line) into RAM\n pbar.update(n=8192)\n pbar.set_postfix(text=text[:10])\n if text == rest: # EOF\n words = utils.to_unicode(text).split()\n for w in words:\n if w.startswith('DBPEDIA_ID/'):\n if args.uncased:\n w = w.lower() \n lexicons[w] += 1\n break\n last_token = text.rfind(b' ') # last token may have been split in two... keep for next iteration\n words, rest = (utils.to_unicode(text[:last_token]).split(),\n text[last_token:].strip()) if last_token >= 0 else ([], text)\n for w in words:\n if w.startswith('DBPEDIA_ID/'):\n if args.uncased:\n w = w.lower() \n lexicons[w] += 1\n for lexicon, freq in lexicons.most_common():\n fout.write(f'{lexicon}\\t{freq}\\n')\n\n logging.info(f'{len(lexicons)} entities identified and saved to {args.entities}.')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='corpus preprocessing')\n # Files\n parser.add_argument('--corpus', type=str, default='corpus/en_entity_text.txt',\n required=True)\n parser.add_argument('--entities', type=str, default='corpus/en_entity_lexicons.txt',\n help='entity names starts with DBPEDIA_ID/')\n parser.add_argument('--uncased', action='store_true', help='lower case')\n args = parser.parse_args()\n main(args)\n\n","repo_name":"Shuailong/EntityWord2Vec","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"71321712477","text":"# -*- coding: utf-8 -*-\n__all__ = (\"ROSField\", \"ROSMsgFormat\")\n\nimport re\nfrom typing import Any, Dict, List, Optional\n\nimport attr\nimport hashlib\nimport os\nimport re\nimport typing as t # noqa # This is a mypy workaround\nfrom abc import ABC, abstractmethod\nfrom io import BytesIO\nimport toposort\nfrom typing import (\n Any,\n BinaryIO,\n Collection,\n Dict,\n Generic,\n Iterator,\n List,\n Mapping,\n Optional,\n Set,\n Tuple,\n TypeVar,\n Union,\n)\n#from .base import Duration, is_builtin, Time\nimport msg\nimport base\n\nR_COMMENT = r\"(#.*)?\"\nR_BLANK = re.compile(f\"^\\s*{R_COMMENT}$\")\n\n@attr.s(frozen=True, str=False, slots=True, auto_attribs=True)\nclass Field:\n \"\"\"Provides an immutable description of a message field.\n\n Attributes\n ----------\n typ: str\n The name of the type used this field.\n name: str\n The name of this field.\n \"\"\"\n\n R_TYPE = r\"[a-zA-Z0-9_/]+(?:\\[(?:<=)?\\d*\\])?\"\n R_NAME = r\"[a-zA-Z0-9_/]+\"\n R_FIELD = re.compile(f\"^\\s*({R_TYPE})\\s+({R_NAME})\\s*{R_COMMENT}$\")\n\n typ: str\n name: str\n\n @classmethod\n def from_string(cls, package: str, line: str) -> \"Optional[Field]\":\n \"\"\"\n Produce a field from a string, checking first if it is a\n valid field, otherwise None.\n\n Parameters\n ----------\n package: str\n The name of the package that provides the field.\n line: str\n The line of text containing the field.\n\n Returns\n -------\n Optional[Field]\n A Field object if the line is a constant, None otherwise.\n \"\"\"\n m_field = cls.R_FIELD.match(line)\n\n if m_field:\n typ, name_field = m_field.group(1, 2)\n\n typ = cls._resolve_type(package, typ)\n\n field: Field = Field(typ, name_field)\n return field\n return None\n\n @classmethod\n def _resolve_type(cls, package: str, typ: str) -> str:\n # resolve the type of the field\n typ_resolved = typ\n base_typ = typ.partition(\"[\")[0]\n if typ == \"Header\":\n typ_resolved = \"std_msgs/Header\"\n elif \"/\" not in typ and not base.is_builtin(base_typ):\n typ_resolved = f\"{package}/{typ}\"\n\n if typ != typ_resolved:\n typ = typ_resolved\n return typ\n\n @property\n def length(self) -> Optional[int]:\n if not self.is_array:\n return None\n sz = self.typ.partition(\"[\")[2].partition(\"]\")[0]\n if sz == \"\":\n return None\n elif sz.startswith(\"<=\"):\n sz = sz[2:]\n return int(sz)\n\n @property\n def base_type(self) -> str:\n return self.typ.partition(\"[\")[0] if self.is_array else self.typ\n\n @property\n def base_typ(self) -> str:\n return self.base_type\n\n def __str__(self) -> str:\n return f\"{self.typ} {self.name}\"\n\n\n@attr.s(frozen=True, str=False, slots=True, auto_attribs=True)\nclass ROSField(Field):\n R_TYPE = (r\"[a-zA-Z_/][a-zA-Z0-9_/]*\"\n r\"(?P<=\\d+)?(?:\\[(?:<=)?\\d*\\])?\")\n R_DEFAULT_VALUE = r\"[^#]*\"\n R_FIELD = re.compile(f\"^\\s*(?P{R_TYPE})\"\n f\"\\s+(?P{Field.R_NAME})(?:\\s+)?\"\n f\"(?P{R_DEFAULT_VALUE}){R_COMMENT}\")\n REXP_TYPE = re.compile(R_TYPE)\n\n default_value: Optional[str]\n\n @classmethod\n def from_string(cls, package: str, line: str) -> Optional[\"ROSField\"]:\n m_field = cls.R_FIELD.match(line)\n if m_field:\n typ = m_field.group('type')\n name = m_field.group('name')\n typ = cls._resolve_type(package, typ)\n default_value = m_field.group('val')\n field = ROSField(typ,\n name,\n default_value if default_value else None)\n return field\n return None\n\n @classmethod\n def _resolve_type(cls, package: str, typ: str) -> str:\n\n # The string bounds (string<=123) will be removed to\n # help resolution of the type\n r_type_match = cls.REXP_TYPE.match(typ)\n if r_type_match and r_type_match.group('strbounds'):\n typ = typ.replace(r_type_match.group('strbounds'), '')\n return super()._resolve_type(package, typ)\n\n\nclass ROSMsgFormat(msg.MsgFormat[ROSField, msg.Constant]):\n\n @classmethod\n def from_string(\n cls, package: str, name: str, text: str\n ) -> \"ROSMsgFormat\":\n fields: List[ROSField] = []\n constants: List[Constant] = []\n\n for line in text.split(\"\\n\"):\n m_blank = R_BLANK.match(line)\n if m_blank:\n continue\n\n constant = Constant.from_string(line)\n field = ROSField.from_string(package, line)\n if constant:\n constants.append(constant)\n elif field:\n fields.append(field)\n\n return ROSMsgFormat(package=package,\n name=name,\n definition=text,\n fields=fields,\n constants=constants)\n\n\n\n\n@attr.s(frozen=True, slots=True, str=False, auto_attribs=True)\nclass Constant:\n \"\"\"Provides an immutable definition of a constant for a message format.\n\n Attributes\n ----------\n typ: str\n The name of the type used by this constant.\n name: str\n The name of this constant.\n value: Union[str, int, float]\n The value of this constant.\n \"\"\"\n\n R_STRING_CONSTANT = re.compile(\"^\\s*string\\s+(\\w+)\\s*=\\s*(.+)\\s*$\")\n R_OTHER_CONSTANT = re.compile(\"^\\s*(\\w+)\\s+(\\w+)\\s*=\\s*([^\\s]+).*$\")\n\n typ: str\n name: str\n value: Union[str, int, float]\n\n @classmethod\n def from_string(cls, line: str) -> \"Optional[Constant]\":\n \"\"\"\n Produce a constant from a string, checking first if it is a valid\n constant, otherwise None.\n\n Parameters\n ----------\n line: str\n The line of text containing the constant.\n\n Returns\n -------\n Optional[Constant]\n A Constant object if the line is a constant, None otherwise.\n \"\"\"\n m_string_constant = cls.R_STRING_CONSTANT.match(line)\n m_other_constant = cls.R_OTHER_CONSTANT.match(line)\n if m_string_constant:\n name_const, val = m_string_constant.group(1, 2)\n constant = Constant(\"string\", name_const, val)\n return constant\n elif m_other_constant:\n typ, name_const, val_str = m_other_constant.group(1, 2, 3)\n val = val_str # FIXME convert value\n constant = Constant(typ, name_const, val)\n return constant\n return None\n\n @staticmethod\n def from_dict(d: Dict[str, Any]) -> \"Constant\":\n return Constant(d[\"type\"], d[\"name\"], d[\"value\"])\n\n def to_dict(self) -> Dict[str, Any]:\n return {\"type\": self.typ, \"name\": self.name, \"value\": self.value}\n\n def __str__(self) -> str:\n return f\"{self.typ} {self.name}={str(self.value)}\"\n\nFIELD = TypeVar(\"FIELD\", bound=Field)\nCONSTANT = TypeVar(\"CONSTANT\", bound=Constant)\n\n@attr.s(frozen=True)\nclass MsgFormat(ABC, Generic[FIELD, CONSTANT]):\n \"\"\"Provides an immutable definition of a given ROS message format.\n\n Attributes\n ----------\n package: str\n The name of the package that defines this message format.\n name: str\n The unqualified name of the message format.\n definition: str\n The plaintext contents of the associated .msg file.\n fields: Sequence[FIELD]\n The fields that belong to this message format.\n constants: Sequence[CONSTANT]\n The named constants that belong to this message format.\n\n References\n ----------\n * http://wiki.ros.org/msg\n \"\"\"\n\n package: str = attr.ib()\n name: str = attr.ib()\n definition: str = attr.ib()\n fields: Tuple[FIELD, ...] = attr.ib(converter=msg.tuple_from_iterable)\n constants: Tuple[CONSTANT, ...] = attr.ib(converter=msg.tuple_from_iterable)\n\n @classmethod\n def toposort(cls, fmts: Collection[\"MsgFormat\"]) -> List[\"MsgFormat\"]:\n fn_to_fmt: Dict[str, MsgFormat] = {fmt.fullname: fmt for fmt in fmts}\n fn_to_deps: Dict[str, Set[str]] = {\n filename: {\n f.base_typ for f in fmt.fields if not base.is_builtin(f.base_typ)\n }\n for filename, fmt in fn_to_fmt.items()\n }\n toposorted = list(toposort(fn_to_deps))\n missing_packages: Set[str] = set(toposorted) - set(fn_to_fmt)\n if missing_packages:\n missing_package_name = next(iter(missing_packages))\n raise exc.PackageNotFound(missing_package_name)\n return [fn_to_fmt[filename] for filename in toposorted]\n\n\n @classmethod\n @abstractmethod\n def from_string(cls, package: str, name: str, text: str) -> \"MsgFormat\":\n \"\"\"Constructs a message format from its description.\n\n Parameters\n ----------\n package: str\n The name of the package that provides the file.\n filename: str\n The absolute path to the .msg file inside the given filesystem.\n text: str\n The message definition itself (e.g., the contents of a .msg file).\n\n Raises\n ------\n ParsingError\n If the description cannot be parsed.\n \"\"\"\n ...\n\n @staticmethod\n def sections_from_string(text: str) -> t.List[str]:\n sections: t.List[str] = [\"\"]\n section_index = 0\n for line in (ss.strip() for ss in text.split(\"\\n\")):\n if line.startswith(\"---\"):\n section_index += 1\n sections.append(\"\")\n else:\n sections[section_index] += f\"{line}\\n\"\n return sections\n\n def to_dict(self) -> Dict[str, Any]:\n d: Dict[str, Any] = {\n \"package\": self.package,\n \"name\": self.name,\n \"definition\": self.definition,\n }\n if self.fields:\n d[\"fields\"] = [f.to_dict() for f in self.fields]\n if self.constants:\n d[\"constants\"] = [c.to_dict() for c in self.constants]\n return d\n\n @property\n def fullname(self) -> str:\n \"\"\"The fully qualified name of this message format.\"\"\"\n return f\"{self.package}/{self.name}\"\n\n def flatten(\n self,\n name_to_format: Mapping[str, \"MsgFormat\"],\n ctx: Tuple[str, ...] = (),\n ) -> Iterator[Tuple[Tuple[str, ...], FIELD]]:\n for field in self.fields:\n if field.is_array or is_builtin(field.typ):\n yield (ctx, field)\n else:\n fmt = name_to_format[field.typ]\n yield from fmt.flatten(name_to_format, ctx + (field.name,))\n\n\n\n\n","repo_name":"MiguelTavares10/myrep","sub_path":"Parser/msg_ros.py","file_name":"msg_ros.py","file_ext":"py","file_size_in_byte":10765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"33267223118","text":"class SimpleGrid:\n def __init__(self, x, y, max_x_pix, max_y_pix, thickness=1, margins=1):\n self.grid = dict()\n self.max_rows = y\n self.max_columns = x\n cord_x = margins\n cord_y = margins\n x_add = (int(max_x_pix) - margins * 2) / x\n y_add = (int(max_y_pix) - margins * 2) / y\n self.x_max = x_add * x\n self.y_max = y_add * y\n first_1 = True\n for a in range(1, y + 1):\n if first_1 is True:\n first_1 = False\n else:\n cord_x = margins\n cord_y += y_add\n\n x_grid = {a: dict()}\n self.grid.update(x_grid)\n first_2 = True\n for b in range(1, x + 1):\n if first_2 is True:\n first_2 = False\n else:\n cord_x += x_add\n\n borders = {'top': (cord_y, cord_x), 'bottom': (cord_y + y_add - thickness, cord_x),\n 'left': (cord_y, cord_x), 'right': (cord_y, cord_x + x_add - thickness)}\n\n border_thickness = {'top': thickness, 'bottom': thickness,\n 'left': thickness, 'right': thickness}\n\n h = y_add\n w = x_add\n\n values = {'color': 0, 'values': 0, 'coordinates': [cord_y, cord_x],\n 'height': h, 'width': w,\n 'borders': borders, 'thickness': border_thickness}\n\n y_grid = {b: values}\n self.grid[a].update(y_grid)\n\n def size(self, x_cord, y_cord, x_size, y_size, p_cells):\n def verify_space():\n if sum_w > self.x_max and sum_h > self.y_max:\n raise 'No width space,' + ' ' + 'No height space'\n elif sum_w > self.x_max:\n raise 'No width space'\n elif sum_h > self.y_max:\n raise 'No height space'\n elif not sum_w > self.x_max and not sum_h > self.y_max:\n pass\n\n x_list = list()\n y_list = list()\n for y in range(1, self.max_rows):\n if self.grid[y][x_cord] not in p_cells and y != y_cord:\n y_list_add = [y, x_cord]\n y_list.append(y_list_add)\n\n for x in range(1, self.max_columns):\n if self.grid[y_cord][x] not in p_cells and x != x_cord:\n x_list_add = [y_cord, x]\n x_list.append(x_list_add)\n\n sum_w = self.grid[y_cord][x_cord]['width'] * len(x_list)\n sum_h = self.grid[y_cord][x_cord]['height'] * len(y_list)\n reduce_w = (sum_w - x_size) / len(x_list)\n reduce_h = (sum_h - y_size) / len(y_list)\n verify_space()\n\n for y in y_list:\n self.grid[y][x_cord]['width'] -= reduce_w\n\n for x in x_list:\n self.grid[y_cord][x]['height'] -= reduce_h\n\n self.grid[y_cord][x_cord]['height'] = y_size\n self.grid[y_cord][x_cord]['width'] = x_size\n\n\n\n\n\n\n\n","repo_name":"Pinklemonade33/MyVentory","sub_path":"simple_grid.py","file_name":"simple_grid.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"70865782558","text":"\"\"\"\nImport libraries/ packages.\n\"\"\"\nimport os\nimport sys\nimport random\nfrom termcolor import colored\nimport gspread\nfrom google.oauth2.service_account import Credentials\n\n\n# The scope was inspired by and borrowed from\n# Code Institute Love Sandwiches project\n# https://github.com/Code-Institute-Solutions/love-sandwiches-p4-sourcecode\nSCOPE = [\n \"https://www.googleapis.com/auth/spreadsheets\",\n \"https://www.googleapis.com/auth/drive.file\",\n \"https://www.googleapis.com/auth/drive\"\n ]\n\nCREDS = Credentials.from_service_account_file('creds.json')\nSCOPED_CREDS = CREDS.with_scopes(SCOPE)\nGSPREAD_CLIENT = gspread.authorize(SCOPED_CREDS)\nSHEET = GSPREAD_CLIENT.open('book_list')\n\n\"\"\"\nGlobal variables for app processes.\n\"\"\"\n\n\"\"\"\nVariables for sheet in the worksheet.\n\"\"\"\nLIST_ALL = SHEET.worksheet('main_list')\n\n\ndef welcome_message():\n \"\"\"\n A welcome message that provides the main menu of the application.\n \"\"\"\n clear_tmnl()\n print(\"Welcome to the Children's Book Picker\\n\")\n print(\"Please select an option below.\\n\")\n print(colored((\"(1) List All Books\"), \"green\"))\n print(colored((\"(2) Random Book Picker\"), \"green\"))\n print(colored((\"(3) Search\"), \"green\"))\n\n while True:\n welcome_message_ans = input(\"\\n\")\n if welcome_message_ans not in (\"1\", \"2\", \"3\"):\n print(colored((\"Invalid input. Please try again.\"), \"red\"))\n print(colored((\"Please choose an option between 1 and 3.\"), \"red\"))\n else:\n break\n return welcome_message_ans\n\n\ndef load_books():\n \"\"\"\n List all books in the spreadsheet.\n \"\"\"\n global headerSpreadsheet, numberOfBooks, numberOfColumns, \\\n title, author, illustrator, interest_level, \\\n reading_age, reading_stage, synopsis\n clear_tmnl()\n print(\"Please wait while books are being loaded...\")\n\n all_books = SHEET.worksheet('main_list')\n headerSpreadsheet = all_books.row_values(1)\n numberOfBooks = len(all_books.col_values(1))-1\n numberOfColumns = len(all_books.row_values(1))\n\n all_rows = []\n for ind in range(1, numberOfBooks):\n all_col = all_books.col_values(ind)\n all_rows.append(all_col[1:])\n title = all_rows[0]\n author = all_rows[1]\n \"\"\"\n To get the author, you can choose all the columns,\n including the header in row 1.\n To remove the first row in Python,\n we need to start counting at 0 instead of 1,\n and then remove row 0 according to that count.\n \"\"\"\n illustrator = all_rows[2]\n interest_level = all_rows[3]\n reading_age = all_rows[4]\n reading_stage = all_rows[5]\n synopsis = all_rows[6]\n\n print(\"Done loading books.\")\n\n\ndef print_book_list(index_print_list):\n \"\"\"\n The print_book_list function displays book titles\n and authors by using a list of indices as input.\n It shows the book titles on top,\n and displays a message when there are no results to show.\n \"\"\"\n clear_tmnl()\n print('\\n Book Title(s):\\n')\n if len(index_print_list) > 0:\n for ind in index_print_list:\n print(f\"{title[ind]} - {author[ind]}\")\n else:\n print(\"no results found\")\n\n\ndef random_book_message():\n \"\"\"\n This feature lets users pick a book at random from one of four categories:\n early childhood, middle childhood, late childhood, and adolescence.\n \"\"\"\n clear_tmnl()\n print(\"The Random Book Picker, \\n\")\n print(\"Chooses a book at random from the selected category, \\n\")\n print(\"Taking into account the child's\\n\")\n print(\"expected mental and developmental age. \\n\")\n print(\"Please select a category:\\n\")\n print(colored((\"(1) Early Childhood 0-5 years old\"), \"green\"))\n print(colored((\"(2) Middle Childhood 6-8 years old\"), \"green\"))\n print(colored((\"(3) Late Childhood 9-11 years old\"), \"green\"))\n print(colored((\"(4) Adolescence 12-15 years old\"), \"green\"))\n print(colored((\"(5) Any category\"), \"green\"))\n\n while True:\n random_book_picker_ans = input(\"\\n\")\n if random_book_picker_ans not in (\"1\", \"2\", \"3\", \"4\", \"5\"):\n print(colored((\"Invalid input.\"), \"red\"))\n print(colored((\"Please try again.\"), \"red\"))\n else:\n break\n print(colored((\"Choose from the options listed:\"), \"red\"))\n print(colored((\"Option 1 to 5.\"), \"red\"))\n\n return random_book_picker_ans\n\n\ndef search_string_within_info(search_string, information_to_search_from):\n \"\"\"\n This function looks for a specific word\n or phrase in a list of data\n and gives you a list of where it was found.\n \"\"\"\n index_print_list = []\n for index in range(len(information_to_search_from)):\n if search_string in information_to_search_from[index]:\n index_print_list.append(index)\n return index_print_list\n\n\ndef random_from_index_list(index_list):\n \"\"\"\n This function requires a list of indices as input.\n It will randomly select one of the indices and return it inside a new list.\n \"\"\"\n random_number = random.choice(index_list)\n random_number = [random_number]\n return random_number\n\n\ndef clear_tmnl():\n \"\"\"\n Clears the terminal when called.\n \"\"\"\n # (Credited in README.md to Tony118g)\n os.system(\"clear\")\n\n\ndef return_to_begin(running):\n \"\"\"\n The `return_to_begin` function shows a message\n with choices to go back to the main menu or exit the program.\n After that, it waits for the user to type either `0` to go back to\n the main menu or `x` to exit the program.\n \"\"\"\n print(colored((\"(0) Return to main menu\"), \"green\"))\n print(colored((\"(x) Quit program\"), \"red\"))\n\n while True:\n main_list_ans = input(\"\\n\")\n if main_list_ans not in (\"0\", \"x\"):\n print(colored((\"Invalid input.\"), \"red\"))\n print(colored((\"Please try again.\"), \"red\"))\n else:\n break\n print(colored((\"Choose 0 to return to the main\"), \"red\"))\n print(colored((\"or x to quit.\"), \"red\"))\n\n if main_list_ans == (\"0\"):\n return running\n if main_list_ans == (\"x\"):\n running = False\n return running\n\n\ndef main():\n \"\"\"\n The `main()` function starts the program,\n loads books, and runs other functions continuously until\n the user exits using the `return_to_begin()` function.\n \"\"\"\n load_books()\n running = True\n\n \"\"\"\"\n Runs the following functions continuously unless you quit it.\n \"\"\"\n\n while True:\n if not running:\n break\n loop()\n running = return_to_begin(running)\n\n\ndef loop():\n \"\"\"\n This function is the main loop of the application.\n It welcomes the user and prompts them to select\n an option from the main menu.\n Depending on the user's selection,\n it either prints a complete list of books,\n selects a random book from a specific category,\n or allows the user to search for books by entering a search term.\n It then prints the selected books to the console.\n \"\"\"\n # Welcome the user to the program\n welcome_message_ans = welcome_message()\n\n # Select the books you want to print\n if welcome_message_ans == (\"1\"): # List all books\n index_print_list = range(numberOfBooks)\n\n elif welcome_message_ans == (\"2\"): # Random book picker\n random_book_picker_ans = random_book_message()\n if random_book_picker_ans == (\"0\"):\n welcome_message()\n elif random_book_picker_ans == (\"1\"):\n searchword = \"early childhood\"\n elif random_book_picker_ans == (\"2\"):\n searchword = \"middle childhood\"\n elif random_book_picker_ans == (\"3\"):\n searchword = \"late childhood\"\n elif random_book_picker_ans == (\"4\"):\n searchword = \"adolescence\"\n elif random_book_picker_ans == (\"5\"):\n searchword = \"\"\n\n index_print_list = search_string_within_info(searchword, reading_stage)\n print(index_print_list)\n index_print_list = random_from_index_list(index_print_list)\n\n elif welcome_message_ans == (\"3\"): # Search for a term in title and author\n print(\"Type your search term below:\")\n searchword = input(\"\\n\") # Use input\n print(\"\")\n print(f\"Search term is '{searchword}'\")\n index_print_list_title = search_string_within_info(searchword, title)\n index_print_list_author = search_string_within_info(searchword, author)\n index_print_list = index_print_list_title + index_print_list_author\n\n # Selection is made, print all relevant books\n print_book_list(index_print_list)\n\n\nmain()\n","repo_name":"Blignaut24/Project-3-The-Children-s-Book-Picker","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":8550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"12634861370","text":"class Solution:\n def hammingDistance(self, x, y):\n \"\"\"\n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n distance = 0\n while x > 0 or y > 0:\n if x & 1 != y & 1:\n distance +=1\n\n if x:\n x = x >> 1\n if y:\n y = y >> 1\n\n return distance\n\n\n###############################################################\nimport unittest\n\n\nclass TestFunctions(unittest.TestCase):\n def test_1(self):\n s = Solution()\n self.assertEqual(2, s.hammingDistance(1, 4))\n self.assertEqual(0, s.hammingDistance(1, 1))\n self.assertEqual(0, s.hammingDistance(0, 0))\n self.assertEqual(0, s.hammingDistance(7, 7))\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"darraes/coding_questions","sub_path":"v2/_leet_code_/0461_hamming_distance.py","file_name":"0461_hamming_distance.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"14569810531","text":"import random\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom transformers import BartForConditionalGeneration, BartTokenizer\nfrom transformers.models.bart.modeling_bart import BartEncoder, BaseModelOutput, _expand_mask\nimport ipdb\n\nclass FinetuningBART(nn.Module):\n def __init__(self, config, debug=True):\n super().__init__()\n self.config = config\n self.tokenizer = BartTokenizer.from_pretrained(self.config.pretrained_model, cache_dir=self.config.cache_dir)\n self.model = BartForConditionalGeneration.from_pretrained(self.config.pretrained_model, cache_dir=self.config.cache_dir)\n self.debug = debug\n if self.debug:\n self.show_demo_examples = True\n \n def save(self, path):\n self.model.save_pretrained(path)\n \n def process_data(self, src_sents, tgt_sents=None):\n # encoder inputs\n input_texts = src_sents\n inputs = self.tokenizer(src_sents, return_tensors='pt', truncation=True, padding=True)\n \n enc_idxs = inputs['input_ids']\n enc_attn = inputs['attention_mask']\n \n enc_idxs = enc_idxs.cuda()\n enc_attn = enc_attn.cuda()\n \n if tgt_sents is None:\n return enc_idxs, enc_attn, None, None, None\n \n # decoder inputs\n output_texts = tgt_sents\n outputs = self.tokenizer(tgt_sents, return_tensors='pt', padding=True)\n \n batch_size = enc_idxs.size(0)\n padding = torch.ones((batch_size, 1), dtype=torch.long)\n padding[:] = self.tokenizer.eos_token_id\n dec_idxs = torch.cat((padding, outputs['input_ids']), dim=1)\n dec_attn = torch.cat((torch.ones((batch_size, 1), dtype=torch.long), outputs['attention_mask']), dim=1)\n \n # labels\n padding = torch.ones((batch_size, 1), dtype=torch.long)\n padding[:] = self.tokenizer.pad_token_id\n raw_lbl_idxs = torch.cat((dec_idxs[:, 1:], padding), dim=1)\n lbl_attn = torch.cat((dec_attn[:, 1:], torch.zeros((batch_size, 1), dtype=torch.long)), dim=1)\n lbl_idxs = raw_lbl_idxs.masked_fill(lbl_attn==0, -100) # ignore padding\n \n dec_idxs = dec_idxs.cuda()\n dec_attn = dec_attn.cuda()\n lbl_idxs = lbl_idxs.cuda()\n \n if self.show_demo_examples:\n print()\n for i in range(3):\n print(f\"IN:\\n {input_texts[i]}\")\n print(f\"OUT:\\n {output_texts[i]}\")\n self.show_demo_examples = False\n \n return enc_idxs, enc_attn, dec_idxs, dec_attn, lbl_idxs\n \n def forward(self, src_sents, tgt_sents):\n enc_idxs, enc_attn, dec_idxs, dec_attn, lbl_idxs = self.process_data(src_sents, tgt_sents)\n \n outputs = self.model(input_ids=enc_idxs, \n attention_mask=enc_attn, \n decoder_input_ids=dec_idxs, \n decoder_attention_mask=dec_attn, \n labels=lbl_idxs, \n return_dict=True)\n \n loss = outputs['loss']\n \n return loss\n \n def generate(self, src_sents, num_beams=4):\n \n self.eval()\n \n max_length = self.config.max_tgt_len\n \n enc_idxs, enc_attn, _, _, _ = self.process_data(src_sents)\n with torch.no_grad():\n outputs = self.model.generate(input_ids=enc_idxs, \n attention_mask=enc_attn, \n num_beams=num_beams, \n max_length=max_length)\n \n final_outputs = []\n for output in outputs:\n final_output = self.tokenizer.decode(output, skip_special_tokens=True, clean_up_tokenization_spaces=False)\n final_outputs.append(final_output.strip())\n \n self.train()\n \n return final_outputs\n\n","repo_name":"ej0cl6/Finetuning-BART","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"32881969516","text":"import hashlib\n\nclass Node:\n def __init__(self, value) -> None:\n self.value = value\n self.hash = hashlib.sha256(str(value).encode()).hexdigest()\n \n def __str__(self) -> str:\n return str(self.value)\n \n def __repr__(self) -> str:\n return self.__str__()\n\n def merge(self, node):\n return Node(self.hash + node.hash)\n\nclass MerkleTree:\n def __init__(self, node_type=Node, empty_node=Node(\"\")) -> None:\n self.node_type = node_type\n self.empty_node = empty_node\n\n def construct_tree(self, data_or_nodes):\n self.tree = self.hash(data_or_nodes)\n self.root = self.tree[-1]\n return self\n\n def hash(self, data_or_nodes): \n encoded = []\n for i in data_or_nodes:\n if isinstance(i, self.node_type):\n encoded.append(i)\n else:\n encoded.append(self.node_type(i))\n\n if len(encoded) == 1:\n return encoded\n\n if len(data_or_nodes) % 2 != 0:\n # Padding\n encoded.append(self.empty_node)\n i = 0\n print(encoded[i].merge(encoded[i + 1]))\n\n return [encoded] +\\\n self.hash([\n encoded[i].merge(encoded[i + 1])\n for i in range(0, len(data_or_nodes), 2)\n ])\n\nif __name__ == \"__main__\":\n tree = MerkleTree().construct_tree(\n [1, 2, 3, 4]\n )\n tree_modified = MerkleTree().construct_tree(\n [1, 2, 3, 5]\n )\n for v in tree.tree:\n print(v)\n\n assert (tree.root) != tree_modified.root\n","repo_name":"2xic-speedrun/distributed-ledger-playground","sub_path":"classics/MerkleTrees.py","file_name":"MerkleTrees.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"32445500829","text":"from typing import List, Union\n\nimport requests\nimport requests_cache\nimport json\nfrom os import getenv\nfrom functools import wraps\n\nfrom .exceptions import APIKeyError, InvalidDirectionError\nfrom .vehicles import Bus, Train\n\n_CACHE_EXPIRE = int(getenv('MARTA_CACHE_EXPIRE', 30))\n_BASE_URL = 'http://developer.itsmarta.com'\n_TRAIN_PATH = '/RealtimeTrain/RestServiceNextTrain/GetRealtimeArrivals'\n_BUS_PATH = '/BRDRestService/RestBusRealTimeService/GetAllBus'\n_BUS_ROUTE_PATH = '/BRDRestService/RestBusRealTimeService/GetBusByRoute/'\n\nrequests_cache.install_cache('marta_api_cache', backend='sqlite', expire_after=_CACHE_EXPIRE)\n\ndef require_api_key(func):\n \"\"\"\n Decorator to ensure an API key is present\n \"\"\"\n @wraps(func)\n def with_key(self, *args, **kwargs):\n if not kwargs.get('api_key'):\n if not self._api_key:\n raise APIKeyError()\n kwargs['api_key'] = self._api_key\n return func(self, *args, **kwargs)\n\n return with_key\n\ndef _convert_direction(user_direction: str, vehicle_type: str = 'bus') -> Union[str, None]:\n if not user_direction:\n return None\n if vehicle_type == 'bus':\n if user_direction.lower().startswith('n'):\n return 'Northbound'\n elif user_direction.lower().startswith('s'):\n return 'Southbound'\n elif user_direction.lower().startswith('e'):\n return 'Eastbound'\n elif user_direction.lower().startswith('w'):\n return 'Westbound'\n else:\n raise InvalidDirectionError(direction_provided=user_direction)\n elif vehicle_type == 'train':\n if user_direction.lower().startswith('n'):\n return 'N'\n elif user_direction.lower().startswith('s'):\n return 'S'\n elif user_direction.lower().startswith('e'):\n return 'E'\n elif user_direction.lower().startswith('w'):\n return 'W'\n else:\n raise InvalidDirectionError(direction_provided=user_direction)\n else:\n return user_direction\n\n\ndef _get_data(endpoint: str, api_key: str) -> dict:\n url = f'{_BASE_URL}{endpoint}?apikey={api_key}'\n response = requests.get(url)\n if response.status_code == 401 or response.status_code == 403:\n raise APIKeyError(f'Your API key seems to be invalid. Try visiting {url}.')\n return json.loads(response.text)\n\ndef _filter_response(response: dict, filters: dict) -> List[dict]:\n valid_items = []\n for item in response:\n valid = True\n for filter_key, filter_value in filters.items():\n if filter_value: # ignore if the filter value doesn't exist\n if not item.get(filter_key): # don't penalize if item doesn't have a filter_key\n pass\n elif str(item[filter_key]).lower() != str(filter_value).lower():\n # lower all values to avoid case issues\n valid = False\n if valid:\n valid_items.append(item)\n return valid_items\n\nclass MARTA:\n def __init__(self, api_key: str = None):\n self._api_key = api_key\n if not api_key:\n self._api_key = getenv('MARTA_API_KEY')\n\n @require_api_key\n def get_trains(self,\n line: str = None,\n station: str = None,\n destination: str = None,\n direction: str = None,\n api_key: str = None) -> List[Train]:\n \"\"\"\n Query API for train information\n\n :param line: Train line identifier filter (red, gold, green, or blue)\n :type line: str, optional\n :param station: train station filter\n :type station: str, optional\n :param destination: destination filter\n :type destination: str, optional\n :param direction: Direction train is heading (N, S, E, or W)\n :param api_key: API key to override environment variable\n :type api_key: str, optional\n :return: list of Train objects\n :rtype: List[Train]\n \"\"\"\n data = _get_data(endpoint=_TRAIN_PATH, api_key=api_key)\n filters = {\n 'LINE': line,\n 'DIRECTION': _convert_direction(user_direction=direction, vehicle_type='train'),\n 'STATION': station,\n 'DESTINATION': destination\n }\n matching_data = _filter_response(response=data, filters=filters)\n return [Train(t) for t in matching_data]\n\n @require_api_key\n def get_buses(self,\n route: int = None,\n stop_id: int = None,\n vehicle_id: int = None,\n time_point: str = None,\n direction: str = None,\n api_key: str = None) -> List[Bus]:\n \"\"\"\n Query API for bus information\n :param route: route number\n :type route: int, optional\n :param stop_id: Bus stop ID\n :type stop_id: int, optional\n :param vehicle_id: Bus ID\n :type vehicle_id: int, optional\n :param time_point:\n :type time_point: str, optional\n :param direction: Bus direction (Northbound, Southbound, Westbound or Eastbound)\n :type direction: str, optional\n :param api_key: API key to override environment variable\n :type api_key: str, optional\n :return: list of Bus objects\n \"\"\"\n\n if route:\n endpoint = f'{_BUS_ROUTE_PATH}/{route}'\n else:\n endpoint = f'{_BUS_PATH}'\n\n\n data = _get_data(endpoint=endpoint, api_key=api_key)\n filters = {\n 'STOPID': stop_id,\n 'VEHICLE': vehicle_id,\n 'TIMEPOINT': time_point,\n 'ROUTE': route,\n 'DIRECTION': _convert_direction(user_direction=direction, vehicle_type='bus')\n }\n matching_data = _filter_response(response=data, filters=filters)\n return [Bus(b) for b in matching_data]\n","repo_name":"itsmarta/marta-python","sub_path":"marta/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5914,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"51"} +{"seq_id":"28519020813","text":"from typing import List\n\"\"\"\n给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。\n岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。\n此外,你可以假设该网格的四条边均被水包围。\n示例 1:\n输入:grid = [\n [\"1\",\"1\",\"1\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"0\",\"0\"]\n]\n输出:1\n\"\"\"\n\n\n\n# 并查集\n# class Solution1:\n# def numIslands(self, grid: List[List[str]]) -> int:\n\n\n\n\n# 使用BFS遍历 找到所有的岛屿\nclass Solution2:\n def numIslands(self, grid: List[List[str]]) -> int:\n if not grid:\n return\n\n visited = set() # 帮助分辨岛屿,输出正确的岛屿数,储存坐标\n lands = 0\n rows, cols = len(grid), len(grid[0])\n\n def bfs(r, c): # 广度优先,从点扩大到整个岛屿找到所有相连部分\n visited.add((r, c))\n queue = [] # 完成bfs,dfs要借助存储结构 否则 递归\n queue.append((r, c))\n direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n while queue:\n row, col = queue.pop(0) # 作为队列先进先出,得到row和col是为了找相邻的点\n for dr, dc in direction:\n row, col = row + dr, col + dc\n if (row in range(rows) and\n col in range(cols) and\n grid[row][col] == '1' and\n (row, col) not in visited):\n visited.add((row, col))\n queue.append((row, col)) # 别忘了入栈找相邻的相邻的\n for r in range(rows):\n for c in range(cols):\n if (r, c) not in visited and grid[r][c] == '1':\n bfs(r, c)\n lands += 1\n return lands\n\n# bfs递归 使用#标记已经访问的点而不是存储结构,节省内存\nclass Solution3:\n def numIslands(self, grid: List[List[str]]) -> int:\n if not grid:\n return 0\n\n lands = 0\n for r in range(len(grid)):\n for c in range(len(grid[0])):\n if grid[r][c] == '1':\n self.dfs(grid, r, c)\n lands += 1\n return lands\n\n def dfs(self, grid, row, col):\n if (row < 0 or col < 0 or row >= len(grid)\n or col >= len(grid[0]) or grid[row][col] != '1'):\n return\n\n grid[row][col] = '#'\n self.dfs(grid, row + 1, col)\n self.dfs(grid, row, col + 1)\n self.dfs(grid, row - 1, col)\n self.dfs(grid, row, col - 1)\n","repo_name":"disjfjdizmfnkf/symmetrical-octo-happiness","sub_path":"图/200.岛屿数量.py","file_name":"200.岛屿数量.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"31985626416","text":"class Node:\n def __init__(self, data=None):\n self.data = data\n self.next = None\n\n def __repr__(self):\n return f\"Node({self.data})\"\n\n\nclass Stack:\n def __init__(self, max_size=-1):\n self.head = None\n self.max_size = max_size\n\n # def size(self):\n # return (self.max_size + 1)\n\n def push(self, data):\n if self.max_size == 0:\n raise Exception(\"Stack is overflow\")\n node = Node(data)\n if self.head is None:\n self.head = node\n else:\n node.next = self.head\n self.head = node\n\n def pop(self):\n if self.is_empty():\n raise Exception(\"Stack is empty\")\n else:\n value = self.head.data\n self.head = self.head.next\n self.max_size += 1\n return value\n\n def is_empty(self):\n return self.head is None\n\n def iter(self):\n current = self.head\n while current:\n if current.next is None:\n print(current, end='')\n break\n print(current, \"->\", end=' ')\n current = current.next\n\n def peak(self):\n if self.is_empty():\n raise Exception(\"Stack is empty\")\n else:\n value = self.head.data\n return value\n\n\nstack = Stack(max_size=3)\nstack.push(5)\nstack.push(6)\nstack.push(7)\nstack.iter()\n\n","repo_name":"Dnbesp/works","sub_path":"pythonOOP/class_work/16.10/16.10.py","file_name":"16.10.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"72390057437","text":"import json\nimport urllib.parse\nimport boto3\nimport csv\n\nprint('Loading function')\n\ns3 = boto3.client('s3')\ndynamodb = boto3.resource('dynamodb')\n\ndef lambda_handler(event, context):\n print(\"Received event: \" + json.dumps(event, indent=2))\n\n # Get the object from the event and show its content type\n bucket = event['Records'][0]['s3']['bucket']['name']\n key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')\n \n try:\n data_object = s3.get_object(Bucket=bucket, Key=key)\n # json_data = data['Body'].read()\n data = data_object['Body'].read().decode('utf-8').splitlines()\n\n lines = csv.reader(data)\n \n # Set up dynamodb access\n #table name\n table = dynamodb.Table('employees')\n \n for line in lines:\n #print complete line\n print(line)\n #inserting values into table\n response = table.put_item(\n Item={\n 'employeeId': line[0],\n 'EmployeeFname': line[1],\n 'EmployeeLnam': line[2]\n }\n )\n print(response)\n \n return {\"statusCode\": 200, \"body\": \"OK\"}\n \n \n except Exception as e:\n print(e)\n raise e\n \n","repo_name":"TejaswiNallavolu/AWS-workshop","sub_path":"EmployeeNameUpdater.py","file_name":"EmployeeNameUpdater.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"3910941164","text":"\"\"\"\nBase classes for test cases\n\nTests will usually inherit from one of these classes to have the controller\nand/or dataplane automatically set up.\n\"\"\"\nimport os\nimport ptf\nfrom ptf.base_tests import BaseTest\nfrom ptf import config\nimport ptf.testutils as testutils\nimport json\nimport socket\nimport time\n\n################################################################\n#\n# Thrift interface base tests\n#\n################################################################\n\nimport switch_sai_thrift.switch_sai_rpc as switch_sai_rpc\nfrom thrift.transport import TSocket\nfrom thrift.transport import TTransport\nfrom thrift.protocol import TBinaryProtocol\nimport sys\nimport paramiko\nfrom paramiko.ssh_exception import BadHostKeyException, AuthenticationException, SSHException\n\n# dictionary of interface_to_front_mapping with key 'src' or 'dst' and the ports for those target\ninterface_to_front_mapping = {}\n\nfrom switch import (sai_thrift_port_tx_enable, # noqa E402\n sai_thrift_port_tx_disable)\n\nDATA_PLANE_QUEUE_LIST = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\"]\nDEFAULT_QUEUE_SCHEDULER_CONFIG = {\"0\": \"scheduler.0\",\n \"1\": \"scheduler.0\",\n \"2\": \"scheduler.0\",\n \"3\": \"scheduler.1\",\n \"4\": \"scheduler.1\",\n \"5\": \"scheduler.0\",\n \"6\": \"scheduler.0\",\n \"7\": \"\"}\n\n\nclass ThriftInterface(BaseTest):\n\n def setUp(self):\n global interface_to_front_mapping\n\n BaseTest.setUp(self)\n\n self.test_params = testutils.test_params_get()\n\n # server is a list [ , , ... }\n if \"src_server\" in self.test_params:\n # server has format :\n src_server = self.test_params['src_server'].strip().split(\":\")\n self.src_server_ip = src_server[0]\n src_server_port = src_server[1]\n else:\n self.src_server_ip = 'localhost'\n src_server_port = 9092\n if \"dst_server\" in self.test_params:\n # server has format :\n dst_server = self.test_params['dst_server'].strip().split(\":\")\n self.dst_server_ip = dst_server[0]\n dst_server_port = dst_server[1]\n else:\n self.dst_server_ip = self.src_server_ip\n dst_server_port = src_server_port\n self.server = self.dst_server_ip\n self.original_dut_port_queue_scheduler_map = {}\n\n if \"port_map_file\" in self.test_params:\n user_input = self.test_params['port_map_file']\n interface_to_front_mapping['src'] = {}\n with open(user_input) as f:\n ptf_test_port_map = json.load(f)\n src_dut_index = self.test_params['src_dut_index']\n self.src_asic_index = self.test_params.get('src_asic_index', None)\n dst_dut_index = self.test_params['dst_dut_index']\n self.dst_asic_index = self.test_params.get('dst_asic_index', None)\n for a_ptf_port, a_ptf_port_info in ptf_test_port_map.items():\n if src_dut_index in a_ptf_port_info['target_dut'] and \\\n a_ptf_port_info['asic_idx'] == self.src_asic_index:\n interface_to_front_mapping['src'][a_ptf_port] = a_ptf_port_info['dut_port']\n if src_dut_index != dst_dut_index or self.src_asic_index != self.dst_asic_index:\n interface_to_front_mapping['dst'] = {}\n for a_ptf_port, a_ptf_port_info in ptf_test_port_map.items():\n if dst_dut_index in a_ptf_port_info['target_dut'] and \\\n a_ptf_port_info['asic_idx'] == self.dst_asic_index:\n interface_to_front_mapping['dst'][a_ptf_port] = a_ptf_port_info['dut_port']\n else:\n interface_to_front_mapping['dst'] = interface_to_front_mapping['src']\n elif \"port_map_file_ini\" in self.test_params:\n user_input = self.test_params['port_map_file_ini']\n interface_to_front_mapping['src'] = {}\n f = open(user_input, 'r')\n for line in f:\n if (len(line) > 0 and (line[0] == '#' or line[0] == ';' or line[0] == '/')):\n continue\n interface_front_pair = line.split(\"@\")\n interface_to_front_mapping['src'][interface_front_pair[0]] = interface_front_pair[1].strip()\n # src = dst on single ASIC device.\n # Copy the src to dst cause some function will read this key\n interface_to_front_mapping['dst'] = interface_to_front_mapping['src']\n f.close()\n else:\n exit(\"No ptf interface<-> switch front port mapping, please specify as parameter or in external file\")\n # dictionary with key 'src' or 'dst'\n self.clients = {}\n # Set up thrift client and contact server\n\n # Below are dictionaries with key dut_index, and value the value for dut at dut_index.\n self.src_transport = TSocket.TSocket(self.src_server_ip, src_server_port)\n self.src_transport = TTransport.TBufferedTransport(self.src_transport)\n self.src_protocol = TBinaryProtocol.TBinaryProtocol(self.src_transport)\n self.src_client = switch_sai_rpc.Client(self.src_protocol)\n self.src_transport.open()\n self.clients['src'] = self.src_client\n if self.src_server_ip == self.dst_server_ip and src_server_port == dst_server_port:\n # using the same client for dst as the src.\n self.dst_client = self.src_client\n else:\n # using different client for dst\n self.dst_transport = TSocket.TSocket(self.dst_server_ip, dst_server_port)\n self.dst_transport = TTransport.TBufferedTransport(self.dst_transport)\n self.dst_protocol = TBinaryProtocol.TBinaryProtocol(self.dst_transport)\n self.dst_client = switch_sai_rpc.Client(self.dst_protocol)\n self.dst_transport.open()\n self.clients['dst'] = self.dst_client\n\n self.platform_asic = self.test_params.get('platform_asic', None)\n\n def tearDown(self):\n if config[\"log_dir\"] is not None:\n self.dataplane.stop_pcap()\n BaseTest.tearDown(self)\n self.src_transport.close()\n if self.dst_client != self.src_client:\n self.dst_transport.close()\n\n def exec_cmd_on_dut(self, hostname, username, password, cmd):\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n if isinstance(cmd, list):\n cmd = ' '.join(cmd)\n\n stdOut = stdErr = []\n retValue = 1\n try:\n client.connect(hostname, username=username,\n password=password, allow_agent=False)\n si, so, se = client.exec_command(cmd, timeout=20)\n stdOut = so.readlines()\n stdErr = se.readlines()\n retValue = 0\n except AuthenticationException as authenticationException:\n print('SSH Authentication failure with message: %s' %\n authenticationException, file=sys.stderr)\n except SSHException as sshException:\n print('SSH Command failed with message: %s' %\n sshException, file=sys.stderr)\n except BadHostKeyException as badHostKeyException:\n print('SSH Authentication failure with message: %s' %\n badHostKeyException, file=sys.stderr)\n except socket.timeout as e:\n # The ssh session will timeout in case of a successful reboot\n print('Caught exception socket.timeout: {}, {}, {}'.format(\n repr(e), str(e), type(e)), file=sys.stderr)\n retValue = 255\n except Exception as e:\n print('Exception caught: {}, {}, type: {}'.format(\n repr(e), str(e), type(e)), file=sys.stderr)\n print(sys.exc_info(), file=sys.stderr)\n finally:\n client.close()\n\n return stdOut, stdErr, retValue\n\n def sai_thrift_port_tx_enable(\n self, client, asic_type, port_list, target='dst', last_port=True, enable_port_by_unblock_queue=True):\n count = 0\n if asic_type == 'mellanox' and enable_port_by_unblock_queue:\n self.enable_mellanox_egress_data_plane(port_list)\n else:\n sai_thrift_port_tx_enable(client, asic_type, port_list, target=target)\n if self.platform_asic and self.platform_asic == \"broadcom-dnx\" and last_port:\n # need to enable watchdog on the source asic using cint script\n cmd = \"bcmcmd -n {} \\\"BCMSAI credit-watchdog enable\\\"\".format(self.src_asic_index)\n stdOut, stdErr, retValue = self.exec_cmd_on_dut(self.src_server_ip,\n self.test_params['dut_username'],\n self.test_params['dut_password'],\n cmd)\n if retValue != 0 or 'Success rv = 0' not in stdOut[1]:\n # Retry credit-wd command max 3 times on failure\n while count < 3:\n print(\"Retrying credit_wd_enable\")\n time.sleep(5)\n stdOut, stdErr, retValue = self.exec_cmd_on_dut(self.src_server_ip,\n self.test_params['dut_username'],\n self.test_params['dut_password'],\n cmd)\n if stdOut and 'Success rv = 0' in stdOut[1]:\n break\n count += 1\n assert 'Success rv = 0' in stdOut[1] if stdOut else retValue == 0,\\\n \"enable wd failed '{}' on asic '{}' on '{}'\".format(cmd, self.src_asic_index, self.src_server_ip)\n\n def sai_thrift_port_tx_disable(self, client, asic_type, port_list, target='dst', disable_port_by_block_queue=True):\n count = 0\n if self.platform_asic and self.platform_asic == \"broadcom-dnx\":\n # need to enable watchdog on the source asic using cint script\n cmd = \"bcmcmd -n {} \\\"BCMSAI credit-watchdog disable\\\"\".format(self.src_asic_index)\n stdOut, stdErr, retValue = self.exec_cmd_on_dut(self.src_server_ip,\n self.test_params['dut_username'],\n self.test_params['dut_password'],\n cmd)\n if retValue != 0 or 'Success rv = 0' not in stdOut[1]:\n # Retry credit-wd command max 3 times on failure\n while count < 3:\n print(\"Retrying credit_wd_enable\")\n time.sleep(5)\n stdOut, stdErr, retValue = self.exec_cmd_on_dut(self.src_server_ip,\n self.test_params['dut_username'],\n self.test_params['dut_password'],\n cmd)\n if stdOut and 'Success rv = 0' in stdOut[1]:\n break\n count += 1\n assert 'Success rv = 0' in stdOut[1] if stdOut else retValue == 0, \\\n \"disable wd failed '{}' on asic '{}' on '{}'\".format(cmd, self.src_asic_index, self.src_server_ip)\n\n if asic_type == 'mellanox' and disable_port_by_block_queue:\n self.disable_mellanox_egress_data_plane(port_list)\n else:\n sai_thrift_port_tx_disable(client, asic_type, port_list, target=target)\n\n def disable_mellanox_egress_data_plane(self, ptf_port_list):\n self.original_dut_port_queue_scheduler_map = self.get_queue_scheduler_name(ptf_port_list)\n block_data_plane_scheduler_name = 'scheduler.block_data_plane'\n cmd_set_block_data_plane_scheduler = \\\n f'sonic-db-cli CONFIG_DB hset \"SCHEDULER|{block_data_plane_scheduler_name}\" \"type\" DWRR \"weight\" 15 \"pir\" 1'\n\n self.exec_cmd_on_dut(self.server, self.test_params['dut_username'], self.test_params['dut_password'],\n cmd_set_block_data_plane_scheduler)\n for ptf_port in ptf_port_list:\n dut_port = interface_to_front_mapping['dst'][str(ptf_port)]\n for q in DATA_PLANE_QUEUE_LIST:\n cmd_block_q = \\\n f\" sonic-db-cli CONFIG_DB hset 'QUEUE|{dut_port}|{q}' scheduler {block_data_plane_scheduler_name}\"\n self.exec_cmd_on_dut(\n self.server, self.test_params['dut_username'], self.test_params['dut_password'], cmd_block_q)\n\n def get_queue_scheduler_name(self, ptf_port_list):\n dut_port_queue_scheduler_map = {}\n for ptf_port in ptf_port_list:\n dut_port = interface_to_front_mapping['dst'][str(ptf_port)]\n dut_port_queue_scheduler_map[dut_port] = {}\n for q in DATA_PLANE_QUEUE_LIST:\n cmd_get_q_scheduler_name = f\"sonic-db-cli CONFIG_DB hget 'QUEUE|{dut_port}|{q}' scheduler\"\n scheduler_name, _, _ = self.exec_cmd_on_dut(\n self.server, self.test_params['dut_username'],\n self.test_params['dut_password'], cmd_get_q_scheduler_name)\n scheduler_name = scheduler_name[0].strip(\"\\n\")\n dut_port_queue_scheduler_map[dut_port][q] = scheduler_name\n return dut_port_queue_scheduler_map\n\n def enable_mellanox_egress_data_plane(self, ptf_port_list):\n for ptf_port in ptf_port_list:\n dut_port = interface_to_front_mapping['dst'][str(ptf_port)]\n for q in DATA_PLANE_QUEUE_LIST:\n scheduler_name = self.original_dut_port_queue_scheduler_map[dut_port][q] if \\\n self.original_dut_port_queue_scheduler_map else DEFAULT_QUEUE_SCHEDULER_CONFIG[q]\n cmd_set_q_scheduler = f\" sonic-db-cli CONFIG_DB hset 'QUEUE|{dut_port}|{q}' scheduler {scheduler_name}\"\n cmd_del_q_scheduler = f\" sonic-db-cli CONFIG_DB hdel 'QUEUE|{dut_port}|{q}' scheduler \"\n cmd_recover_q_scheduler_config = cmd_set_q_scheduler if scheduler_name else cmd_del_q_scheduler\n self.exec_cmd_on_dut(\n self.server, self.test_params['dut_username'],\n self.test_params['dut_password'], cmd_recover_q_scheduler_config)\n\n\nclass ThriftInterfaceDataPlane(ThriftInterface):\n \"\"\"\n Root class that sets up the thrift interface and dataplane\n \"\"\"\n\n def setUp(self):\n ThriftInterface.setUp(self)\n self.dataplane = ptf.dataplane_instance\n self.dataplane.flush()\n if config[\"log_dir\"] is not None:\n filename = os.path.join(config[\"log_dir\"], str(self)) + \".pcap\"\n self.dataplane.start_pcap(filename)\n\n def tearDown(self):\n if config[\"log_dir\"] is not None:\n self.dataplane.stop_pcap()\n ThriftInterface.tearDown(self)\n","repo_name":"sonic-net/sonic-mgmt","sub_path":"tests/saitests/py3/sai_base_test.py","file_name":"sai_base_test.py","file_ext":"py","file_size_in_byte":15432,"program_lang":"python","lang":"en","doc_type":"code","stars":161,"dataset":"github-code","pt":"51"} +{"seq_id":"73815437278","text":"import logging\nimport os\nfrom typing import List\n\nfrom packager import rx\nfrom packager.constants import (\n CHARACTER_LIMIT,\n DELIMITER_MULTILINE_GENERAL,\n DELIMITER_MULTILINE_END,\n DELIMITER_MULTILINE_START,\n DELIMITER_NEWLINE,\n)\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass Unpacker:\n def __init__(self, filename, dir_output_unpack, dir_input_repack, is_character_limit: bool = False):\n self.filename = filename\n # TODO: Change to os.sep\n self.filename_suffix = self.filename.split(\"\\\\\")[-1]\n self.dir_output_unpack = dir_output_unpack\n self.dir_input_repack = dir_input_repack\n\n # Character Limit Settings\n self.is_character_limit = is_character_limit\n self.output_file_partition = 0\n self.characters_written = 0\n\n def unpack(self):\n LOGGER.info(f\"|{self.filename_suffix}| - Unpacking...\")\n text_unpacked = []\n\n with open(self.filename, \"r\", encoding=\"windows-1251\") as input_fp:\n LOGGER.info(f\"|{self.filename_suffix}| Loading into memory...\")\n file_contents = input_fp.readlines()\n\n line_iter = enumerate(iter(file_contents), start=1)\n for idx, line in line_iter:\n match_simple = rx.XML_SIMPLE.search(line)\n match_multiline = rx.XML_MULTILINE_START.search(line)\n\n if match_simple:\n LOGGER.info(f\"|{self.filename_suffix}| [{idx}] Match - Simple\")\n text = self.process_simple_match(match_simple, idx)\n elif match_multiline:\n LOGGER.info(f\"|{self.filename_suffix}| [{idx}] Match - Multiline\")\n text = self.process_multiline_match(match_multiline, idx, line_iter)\n else:\n LOGGER.info(f\"|{self.filename_suffix}| [{idx}] Match - None\")\n continue\n\n text = self.post_process(text)\n\n if self.is_character_limit:\n # Write existing data to file if text will overflow character limit\n if self.characters_written + len(text) >= CHARACTER_LIMIT:\n self.write_to_file(text_unpacked)\n text_unpacked = []\n\n # Add Unpacked Text to Internal Memory Store & Update Characters Written\n text_unpacked.append(text)\n self.characters_written = self.characters_written + len(text)\n\n # Final flush of unpacked data\n if text_unpacked:\n self.write_to_file(text_unpacked)\n\n @staticmethod\n def process_simple_match(match, idx: int) -> str:\n processed_text = match.groups()[0] + \"\\n\"\n processed_text_prepended = f\"[{idx}] \" + processed_text\n return processed_text_prepended\n\n @staticmethod\n def process_multiline_match(match, idx: int, line_iter) -> str:\n # Handle Starting Line\n match_start = match.groups()[0]\n if match_start:\n prefix_start = f\"[{idx}]{DELIMITER_MULTILINE_START} \"\n line_to_parse_prepended = prefix_start + match.groups()[0]\n text = line_to_parse_prepended + \"\\n\"\n else:\n text = \"\"\n\n # Handle Body (Middle Line(s))\n idx, line_to_parse = next(line_iter)\n while not rx.XML_MULTILINE_END.search(line_to_parse):\n prefix_middle = f\"[{idx}]{DELIMITER_MULTILINE_GENERAL} \"\n line_to_parse_prepended = prefix_middle + line_to_parse\n text = text + line_to_parse_prepended\n idx, line_to_parse = next(line_iter)\n\n # Handle Ending Line\n match_end = rx.XML_MULTILINE_END.search(line_to_parse).groups()[0]\n if match_end:\n prefix_end = f\"[{idx}]{DELIMITER_MULTILINE_END} \"\n line_to_parse_prepended = prefix_end + match_end\n text = text + line_to_parse_prepended + \"\\n\"\n\n return text\n\n @staticmethod\n def post_process(text: str) -> str:\n # Replace text embedded \\n with delimiter to avoid munging by translator\n text = text.replace(\"\\\\n\", DELIMITER_NEWLINE + \" \")\n\n return text\n\n def write_to_file(self, file_contents_unpacked: List[str]):\n filename_no_ext = self.filename_suffix.split(\".\")[0]\n # Write File Contents to Unpacker Output Directory\n output_filename = f\"{self.dir_output_unpack}/{filename_no_ext}_unpacked.txt\"\n if self.is_character_limit:\n output_filename = output_filename.replace(\".txt\", f\"-{self.output_file_partition}.txt\")\n LOGGER.info(f\"File: {self.filename} - Writing: {output_filename} - Characters: {self.characters_written}...\")\n with open(output_filename, \"w\", encoding=\"windows-1251\") as output_fp:\n output_fp.writelines(file_contents_unpacked)\n LOGGER.info(f\"File: {self.filename_suffix} - Writing: {output_filename} - Successful\")\n\n self.output_file_partition = self.output_file_partition + 1\n self.characters_written = 0\n\n # Create Empty File w/ Proper Naming Scheme in Repacker Input Directory\n output_repack_filename = f\"{self.dir_input_repack}/{filename_no_ext}_translate.txt\"\n if self.is_character_limit:\n output_repack_filename = output_repack_filename.replace(\".txt\", f\"-{self.output_file_partition}.txt\")\n\n with open(output_repack_filename, \"w\"):\n pass\n","repo_name":"harris-christopher/stalker_translate","sub_path":"packager/unpacker.py","file_name":"unpacker.py","file_ext":"py","file_size_in_byte":5393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"16476428851","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport copy\nimport datetime\nimport os\nimport signal\nimport subprocess\nimport sys\nimport time\nfrom optparse import OptionGroup\n\nimport psutil\nfrom yelp_batch import BatchDaemon\nfrom yelp_batch.batch import batch_command_line_options\nfrom yelp_batch.batch import batch_configure\n\nfrom data_pipeline import __version__\nfrom data_pipeline._namespace_util import DBSourcedNamespace\nfrom data_pipeline.helpers.priority_refresh_queue import PriorityRefreshQueue\nfrom data_pipeline.schematizer_clientlib.models.refresh import RefreshStatus\nfrom data_pipeline.schematizer_clientlib.schematizer import get_schematizer\nfrom data_pipeline.servlib.config_util import load_package_config\nfrom data_pipeline.tools.copy_table_to_blackhole_table import FullRefreshRunner\nfrom data_pipeline.zookeeper import ZKLock\n\nSCHEMATIZER_POLL_FREQUENCY_SECONDS = 5\nCOMPLETE_STATUSES = {RefreshStatus.SUCCESS, RefreshStatus.FAILED}\nINACTIVE_STATUSES = {RefreshStatus.NOT_STARTED, RefreshStatus.PAUSED}\nDEFAULT_PER_SOURCE_THROUGHPUT_CAP = 50\nDEFAULT_TOTAL_THROUGHPUT_CAP = 1000\n\n\nclass RefreshJob(object):\n def __init__(\n self,\n refresh_id,\n cap,\n priority,\n status,\n source,\n throughput=0,\n last_throughput=0,\n pid=None\n ):\n self.refresh_id = refresh_id\n self.cap = cap\n self.priority = priority\n self.status = status\n self.source = source\n self.throughput = throughput\n self.last_throughput = last_throughput\n self.pid = pid\n\n def should_modify(self):\n \"\"\"A job should be modified rather than ran or paused if\n for some reason, a _running_ job's throughput has changed.\n If this happens for some reason, the job needs to be paused\n and restarted to get the proper throughput.\"\"\"\n return (self.status == RefreshStatus.IN_PROGRESS and\n self.throughput and\n self.last_throughput and\n self.last_throughput != self.throughput)\n\n def should_run(self):\n return (self.status in INACTIVE_STATUSES and\n self.throughput and\n not self.last_throughput)\n\n def should_pause(self):\n return (self.status == RefreshStatus.IN_PROGRESS and\n not self.throughput)\n\n def is_active(self):\n return self.pid is not None and self.status not in COMPLETE_STATUSES\n\n\nclass FullRefreshManager(BatchDaemon):\n \"\"\"\n A Daemon that monitors all refreshes on a given namespace that need to be run\n (getting this info from the schematizer), and allocates throughput on a per-source basis\n to do this without taxing other functionality. It runs the refreshes using FullRefreshRunner\n subprocesses. To create a refresh request, use FullRefreshJob.\n \"\"\"\n\n def __init__(self):\n super(FullRefreshManager, self).__init__()\n self.notify_emails = ['bam+batch@yelp.com']\n self.active_refresh_jobs = {}\n self.total_throughput_being_used = 0\n self.refresh_queue = PriorityRefreshQueue()\n self.last_updated_timestamp = None\n\n @property\n def schematizer(self):\n return get_schematizer()\n\n @property\n def version(self):\n \"\"\"Overriding this so we'll get the clientlib version number when\n the tailer is run with --version.\n \"\"\"\n return \"data_pipeline {}\".format(__version__)\n\n @batch_command_line_options\n def define_options(self, option_parser):\n opt_group = OptionGroup(option_parser, 'Full Refresh Manager Options')\n opt_group.add_option(\n '--cluster',\n dest='cluster',\n default='refresh_primary',\n help='Required: Specifies table cluster (default: %default).'\n )\n opt_group.add_option(\n '--database',\n dest='database',\n help='Specify the database to switch to after connecting to the '\n 'cluster.'\n )\n opt_group.add_option(\n '--config-path',\n dest='config_path',\n default='/nail/srv/configs/data_pipeline_tools.yaml',\n help='Config file path for the refresh manager. '\n '(default: %default)'\n )\n opt_group.add_option(\n '--dry-run',\n action=\"store_true\",\n default=False,\n dest=\"dry_run\",\n help=\"Will execute all refreshes as dry runs, will still affect \"\n \"the schematizer's records. (default: %default)\"\n )\n opt_group.add_option(\n '--per-source-throughput-cap',\n default=DEFAULT_PER_SOURCE_THROUGHPUT_CAP,\n dest=\"per_source_throughput_cap\",\n help=\"The cap that each source within the namespace is given. Any source in this \"\n \"namespace cannot have a throughput higher than this cap. (default: %default)\"\n )\n opt_group.add_option(\n '--total-throughput-cap',\n default=DEFAULT_TOTAL_THROUGHPUT_CAP,\n dest=\"total_throughput_cap\",\n help=\"The cap that the namespace gives in general. The cumulative running refreshes \"\n \"cannot have a throughput higher than this number. (default: %default)\"\n )\n return opt_group\n\n @batch_configure\n def _init_global_state(self):\n if self.options.database is None:\n raise ValueError(\"--database is required to be defined\")\n self.cluster = self.options.cluster\n self.database = self.options.database\n self.namespace = DBSourcedNamespace(\n cluster=self.cluster,\n database=self.database\n ).get_name()\n self.config_path = self.options.config_path\n self.dry_run = self.options.dry_run\n self.per_source_throughput_cap = self.options.per_source_throughput_cap\n self.total_throughput_cap = self.options.total_throughput_cap\n load_package_config(self.config_path)\n self.refresh_runner_path = self.get_refresh_runner_path()\n # Removing the cmd line arguments to prevent child process error.\n sys.argv = sys.argv[:1]\n\n def get_refresh_runner_path(self):\n return os.path.join(\n *(os.path.split(\n os.path.abspath(__file__)\n )[:-1] + (\"copy_table_to_blackhole_table.py\",))\n )\n\n def get_most_recent_topic(self, source_name, namespace_name):\n # TODO: DATAPIPE-1866\n # This should realistically be something like get_latest_topic_by_names\n # or something similar\n topics = self.schematizer.get_topics_by_criteria(\n source_name=source_name,\n namespace_name=namespace_name\n )\n return max(\n topics,\n key=lambda topic: topic.created_at\n )\n\n def get_primary_key_from_topic(self, topic):\n primary_keys = topic.primary_keys\n if primary_keys:\n # The refresh runner doesn't like composite keys, and gets by just fine using only one of them\n primary_key = primary_keys[0]\n else:\n # Fallback in case we get bad data from the schematizer\n # TODO: DATAPIPE-1988\n primary_key = 'id'\n return primary_key\n\n def get_refresh_args(self, job):\n # Important to grab fresh refresh here to get offset in case of\n # a paused job\n refresh = self.schematizer.get_refresh_by_id(\n job.refresh_id\n )\n args = [\n \"python\", self.refresh_runner_path,\n \"--cluster={}\".format(self.cluster),\n \"--database={}\".format(self.database),\n \"--table-name={}\".format(refresh.source_name),\n \"--offset={}\".format(refresh.offset),\n \"--config-path={}\".format(self.config_path),\n \"--avg-rows-per-second-cap={}\".format(job.throughput),\n \"--batch-size={}\".format(refresh.batch_size),\n \"--refresh-id={}\".format(job.refresh_id)\n ]\n if self.dry_run:\n args.append(\"--dry-run\")\n if refresh.filter_condition:\n args.append(\"--where=\\\"{}\\\"\".format(\n refresh.filter_condition\n ))\n if self.options.verbose:\n vs = \"v\" * self.options.verbose\n args.append(\"-{}\".format(vs))\n\n topic = self.get_most_recent_topic(\n refresh.source_name,\n refresh.namespace_name\n )\n primary_key = self.get_primary_key_from_topic(topic)\n args.append(\n \"--primary-key={}\".format(primary_key)\n )\n return args\n\n def run_job(self, job):\n if not job.last_throughput:\n self.refresh_queue.pop(job.source)\n\n args = self.get_refresh_args(job)\n self.log.info(\"Starting refresh with args: {}\".format(args))\n job.pid = subprocess.Popen(args).pid\n\n def pause_job(self, job):\n # This signal will cause the refresh runner to update\n # the job to paused\n os.kill(job.pid, signal.SIGTERM)\n job.pid = None\n\n def modify_job(self, job):\n pid = job.pid\n self.pause_job(job)\n os.waitpid(pid)\n self.run_job(job)\n\n def set_zombie_refresh_to_fail(self, refresh_job):\n current_pid = refresh_job.pid\n if current_pid is None:\n return\n\n p = psutil.Process(current_pid)\n if p.status() != psutil.STATUS_ZOMBIE:\n return\n\n refresh = self.schematizer.get_refresh_by_id(\n refresh_job.refresh_id\n )\n if refresh.status == RefreshStatus.IN_PROGRESS:\n # Must update manually (not relying on the signal),\n # as the process may not properly handle the signal\n # if it's a zombie\n self.schematizer.update_refresh(\n refresh_id=refresh_job.refresh_id,\n status=RefreshStatus.FAILED,\n offset=0\n )\n source = refresh_job.source\n del self.active_refresh_jobs[source]\n os.kill(current_pid, signal.SIGINT)\n\n def set_zombie_refreshes_to_fail(self):\n \"\"\"The manager sometimes gets in to situations where\n a worker becomes a zombie but the refresh stays 'IN_PROGRESS'.\n For these situations we want to correct the refresh status to failed.\n \"\"\"\n for source, refresh_job in self.active_refresh_jobs.iteritems():\n self.set_zombie_refresh_to_fail(refresh_job)\n\n def determine_refresh_candidates(self):\n refresh_candidates = self.refresh_queue.peek()\n self.log.debug(\"refresh_candidates: {}...\".format(\n refresh_candidates\n ))\n return refresh_candidates\n\n def get_last_updated_timestamp(self, requests):\n if not requests:\n return self.last_updated_timestamp\n max_time = max([request.updated_at for request in requests])\n return int(\n (max_time - datetime.datetime(1970, 1, 1, tzinfo=max_time.tzinfo)).total_seconds()\n )\n\n def get_refresh_candidates(self, updated_refreshes):\n requests = [\n ref for ref in updated_refreshes if ref.status in INACTIVE_STATUSES\n ]\n self.log.debug(\"Sending {} refresh requests to refresh_queue\".format(\n len(requests)\n ))\n self.refresh_queue.add_refreshes_to_queue(requests)\n return self.determine_refresh_candidates()\n\n def get_cap(self):\n cap_left = self.total_throughput_cap - self.total_throughput_being_used\n return min(cap_left, self.per_source_throughput_cap)\n\n def _sort_by_running_first(self, sources):\n return sorted(\n sources,\n key=lambda source:\n (0 if self.active_refresh_jobs[source].status == RefreshStatus.IN_PROGRESS\n else 1)\n )\n\n def _sort_by_descending_priority(self, sources):\n return sorted(\n sources,\n key=lambda source:\n self.active_refresh_jobs[source].priority,\n reverse=True\n )\n\n def sort_sources(self):\n source_names = self.active_refresh_jobs.keys()\n source_names = self._sort_by_running_first(\n source_names\n )\n return self._sort_by_descending_priority(\n source_names\n )\n\n def allocate_throughput_to_job(self, job, cap):\n job.last_throughput = job.throughput\n job.throughput = min(cap, job.cap)\n self.total_throughput_being_used += (\n job.throughput - job.last_throughput\n )\n\n def update_job_actions(self):\n to_run_jobs = []\n to_modify_jobs = []\n to_pause_jobs = []\n for source, refresh_job in self.active_refresh_jobs.iteritems():\n if refresh_job.should_run():\n to_run_jobs.append(refresh_job)\n elif refresh_job.should_modify():\n to_modify_jobs.append(refresh_job)\n elif refresh_job.should_pause():\n to_pause_jobs.append(refresh_job)\n self.log.debug(\"to_run: {}\".format(to_run_jobs))\n self.log.debug(\"to_modify: {}\".format(to_modify_jobs))\n self.log.debug(\"to_pause: {}\".format(to_pause_jobs))\n return to_run_jobs, to_modify_jobs, to_pause_jobs\n\n def reallocate_for_source(self, source):\n \"\"\"Rellocates available throughput to the currently running job\n in case more/less of it is available.\"\"\"\n available_cap = self.get_cap()\n running_job = self.active_refresh_jobs[source]\n self.allocate_throughput_to_job(running_job, available_cap)\n\n def run_all_job_actions(self, to_run_jobs, to_modify_jobs, to_pause_jobs):\n for job in to_pause_jobs:\n self.pause_job(job)\n for job in to_modify_jobs:\n self.modify_job(job)\n for job in to_run_jobs:\n self.run_job(job)\n\n def delete_inactive_jobs(self):\n self.active_refresh_jobs = {\n source: refresh_job for source, refresh_job\n in self.active_refresh_jobs.items()\n if refresh_job.is_active()\n }\n\n def _should_run_new_job(self, refresh_candidate):\n source = refresh_candidate.source_name\n running_job = self.active_refresh_jobs.get(source, None)\n return (not running_job or\n running_job.status in COMPLETE_STATUSES or\n running_job.priority < refresh_candidate.priority)\n\n def _remove_running_job(self, source):\n running_job = self.active_refresh_jobs[source]\n self.total_throughput_being_used -= running_job.throughput\n # Pause the current running job so that it will stop running,\n # it will be added to the queue automatically next step\n if running_job.status not in COMPLETE_STATUSES:\n self.pause_job(running_job)\n del self.active_refresh_jobs[source]\n\n def update_running_jobs_with_refresh(self, refresh_candidate):\n if self._should_run_new_job(refresh_candidate):\n source = refresh_candidate.source_name\n new_refresh_job = RefreshJob(\n refresh_id=refresh_candidate.refresh_id,\n cap=(refresh_candidate.avg_rows_per_second_cap or\n FullRefreshRunner.DEFAULT_AVG_ROWS_PER_SECOND_CAP),\n priority=refresh_candidate.priority,\n status=refresh_candidate.status,\n source=source\n )\n if source in self.active_refresh_jobs:\n self._remove_running_job(source)\n self.active_refresh_jobs[source] = new_refresh_job\n\n def update_running_jobs_with_refresh_candidates(self, refresh_candidates):\n for source, refresh in refresh_candidates.iteritems():\n self.log.debug(\"Constructing running refreshes for {}...\".format(\n source\n ))\n self.update_running_jobs_with_refresh(refresh)\n\n def reallocate_throughput(self):\n source_names = self.sort_sources()\n for source in source_names:\n self.log.debug(\"Reallocating for {}...\".format(\n source\n ))\n self.reallocate_for_source(source)\n\n def pause_all_running_jobs(self):\n for _, job in self.active_refresh_jobs.iteritems():\n # Need to check if there's an actual pid in case\n # interruption while we are adding jobs\n if job.pid is not None:\n self.pause_job(job)\n\n def get_refreshes_of_statuses(self, statuses):\n refreshes = []\n for status in statuses:\n refreshes += self.schematizer.get_refreshes_by_criteria(\n self.namespace,\n status,\n updated_after=self.last_updated_timestamp\n )\n return refreshes\n\n def get_updated_refreshes(self):\n # We have to do it this way until the schematizer\n # is fixed for this call\n # (TODO: DATAPIPE-2074)\n statuses = list(INACTIVE_STATUSES)\n if self.active_refresh_jobs:\n statuses += list(COMPLETE_STATUSES)\n statuses.append(RefreshStatus.IN_PROGRESS)\n return self.get_refreshes_of_statuses(statuses)\n\n def active_job_has_invalid_status(self, active_job, updated_refresh):\n return (active_job and\n active_job.refresh_id == updated_refresh.refresh_id and\n updated_refresh.status == RefreshStatus.NOT_STARTED)\n\n def validate_running_job_status(self, active_job, updated_refresh, updated_refreshes):\n if self.active_job_has_invalid_status(active_job, updated_refresh):\n self.log.warning(\n \"Discrepency found: active_job has not_started status in\"\n \" schematizer. Refresh ID: {} source_name: {}\"\n \". If this warning is found shortly after the refresh is started\"\n \" then it's most likely not an issue. \"\n \"Removing from updated_refreshes list...\".format(\n active_job.refresh_id, updated_refresh.source_name\n )\n )\n updated_refreshes.remove(updated_refresh)\n\n def update_refreshes_status(self, updated_refreshes):\n for updated_refresh in copy.copy(updated_refreshes):\n source = updated_refresh.source_name\n active_job = self.active_refresh_jobs.get(source)\n if not active_job or active_job.refresh_id != updated_refresh.refresh_id:\n continue\n active_job.status = updated_refresh.status\n self.validate_running_job_status(active_job, updated_refresh, updated_refreshes)\n\n def step(self):\n self.set_zombie_refreshes_to_fail()\n updated_refreshes = self.get_updated_refreshes()\n self.last_updated_timestamp = self.get_last_updated_timestamp(\n updated_refreshes\n )\n if self.active_refresh_jobs:\n self.update_refreshes_status(updated_refreshes)\n refresh_candidates = self.get_refresh_candidates(updated_refreshes)\n self.update_running_jobs_with_refresh_candidates(refresh_candidates)\n self.reallocate_throughput()\n to_run_jobs, to_modify_jobs, to_pause_jobs = self.update_job_actions()\n self.run_all_job_actions(to_run_jobs, to_modify_jobs, to_pause_jobs)\n self.delete_inactive_jobs()\n\n def run(self):\n with ZKLock(name=\"refresh_manager\", namespace=self.namespace):\n try:\n while True:\n self.step()\n if self._stopping:\n break\n self.log.debug(\n \"State of active_refresh_jobs: {}\".format(\n self.active_refresh_jobs\n )\n )\n time.sleep(SCHEMATIZER_POLL_FREQUENCY_SECONDS)\n finally:\n self.pause_all_running_jobs()\n\n\nif __name__ == '__main__':\n FullRefreshManager().start()\n","repo_name":"Yelp/data_pipeline","sub_path":"data_pipeline/tools/refresh_manager.py","file_name":"refresh_manager.py","file_ext":"py","file_size_in_byte":20014,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"51"} +{"seq_id":"73644616479","text":"import datetime\nimport time\nfrom typing import Optional, Tuple, List, Dict\n\nfrom art import tprint\n\nfrom src import google_sheets_worker, client\nfrom src.models import OrderModel, order_storage\nfrom src.schemas import OrderData, OrderStorageData, OrderStorageUpdateData, SendToTelegramData\nfrom src.utils import utils\nfrom config import logger\n\n\nclass Demon:\n TIME_RUN = 150 # restart every 150 seconds\n\n def __new__(cls):\n if not hasattr(cls, 'instance'):\n cls.instance = super(Demon, cls).__new__(cls)\n return cls.instance\n\n def __init__(self):\n self.last_check: Optional[datetime.datetime] = None\n\n def run(self):\n tprint(\"PARSER SCRIPT\", font=\"bulbhead\")\n while True:\n self.parser_script()\n if self.last_check is None or utils.is_yesterday(date=self.last_check):\n self.delivery_time_script()\n self.last_check = datetime.datetime.now()\n logger.error(\"BOT SLEEP!\")\n time.sleep(self.TIME_RUN)\n\n # <<<==================================>>> Worker Parser script <<<==============================================>>>\n\n @staticmethod\n def get_data() -> Tuple:\n logger.info(\"TAKING DATA\")\n new_data: List[OrderData] = google_sheets_worker.data_packaging(google_sheets_worker.get_data(all_data=[]))\n old_data: List[OrderData] = utils.convert_data(order_storage.read())\n if len(old_data) == 0:\n old_data: List[OrderData] = OrderModel.read()\n order_storage.create([\n OrderStorageData(\n _id=d._id,\n orderId=d.orderId,\n priceUSD=d.priceUSD,\n priceRUB=d.priceRUB,\n deliveryTime=d.deliveryTime,\n sentTelegram=False\n )\n for d in old_data\n ])\n if len(old_data) == 0:\n return new_data, None\n return new_data, old_data\n\n @staticmethod\n def get_cd_data(d1: List[Dict], d2: List[Dict], data: List[Dict]) -> List[Dict]:\n return utils.some_data(utils.get_ids(d1), utils.get_ids(d2), data=data)\n\n @staticmethod\n def get_update_data(new_data: List[Dict], old_data: List[Dict]):\n update_data = []\n for _id in utils.get_ids(new_data).intersection(utils.get_ids(old_data)):\n old = list(filter(lambda x: x.get(\"id\") == _id, old_data))[0]\n new = list(filter(lambda x: x.get(\"id\") == _id, new_data))[0]\n if old != new:\n update_data.append(new)\n return update_data\n\n @staticmethod\n def create_data(data: List[Dict]) -> Optional:\n if len(data) > 0:\n data_for_add = google_sheets_worker.data_packaging([list(d.values()) for d in data])\n status_sql = OrderModel.create(data_for_add)\n status_no_sql = order_storage.create(utils.convert_data_back(data_for_add))\n if status_sql and status_no_sql:\n logger.info(f\"CREATE DATA: SUCCESSFULLY! IDS: {utils.get_ids(data)}\")\n else:\n logger.error(f\"CREATE DATA: BAD! IDS: {utils.get_ids(data)}\")\n logger.error(f\"DON'T HAVE CREATE DATA\")\n\n @staticmethod\n def delete_data(data: List[Dict]) -> Optional:\n if len(data) > 0:\n data_for_delete = set(i.get(\"id\") for i in data)\n status_sql = OrderModel.delete(data_for_delete)\n status_no_sql = order_storage.delete(data_for_delete)\n if status_sql and status_no_sql:\n logger.info(f\"DELETE DATA: SUCCESSFULLY! IDS: {utils.get_ids(data)}\")\n else:\n logger.error(f\"DELETE DATA: BAD! IDS: {utils.get_ids(data)}\")\n logger.error(f\"DON'T HAVE DELETE DATA\")\n\n @staticmethod\n def update_data(data: List[Dict]) -> Optional:\n if len(data) > 0:\n data_for_update = google_sheets_worker.data_packaging([list(d.values()) for d in data])\n status_sql = OrderModel.update(data_for_update)\n status_no_sql = order_storage.update(utils.convert_data_to_update(utils.convert_data_back(data_for_update)))\n if status_sql and status_no_sql:\n logger.info(f\"UPDATE DATA: SUCCESSFULLY! IDS: {utils.get_ids(data)}\")\n else:\n logger.error(f\"UPDATE DATA: BAD! IDS: {utils.get_ids(data)}\")\n logger.error(f\"DON'T HAVE UPDATE DATA\")\n\n @staticmethod\n def parser_script() -> Optional:\n \"\"\"Parser | Google sheets => SQL DB\"\"\"\n logger.info(\"START NEW ITERATION\")\n new_data, old_data = Demon.get_data()\n if old_data is None:\n logger.info(\"INIT ORDERS\")\n OrderModel.create(data=new_data)\n order_storage.create(data=new_data)\n return None\n new_data: List[Dict] = [i.to_dict for i in new_data]\n old_data: List[Dict] = [i.to_dict for i in old_data]\n Demon.create_data(data=Demon.get_cd_data(new_data, old_data, new_data))\n Demon.delete_data(data=Demon.get_cd_data(old_data, new_data, old_data))\n Demon.update_data(data=Demon.get_update_data(new_data, old_data=old_data))\n\n # <<<==================================>>> Worker Parser script <<<==============================================>>>\n\n @staticmethod\n def delivery_time_script() -> Optional:\n all_data: List[OrderStorageData] = order_storage.read()\n update_data: List[OrderStorageUpdateData] = []\n for data in all_data:\n if not data.sentTelegram and utils.is_time(data.deliveryTime):\n logger.info(f\"DELIVERY PASSED. ORDER: {data.orderId}\")\n client.send_to_telegram(data=SendToTelegramData(\n orderId=data.orderId,\n deliveryTime=data.deliveryTime,\n priceUSD=data.priceUSD,\n priceRUB=data.priceRUB\n ))\n update_data.append(OrderStorageUpdateData(\n _id=data._id,\n sentTelegram=True,\n deliveryTime=data.deliveryTime,\n priceUSD=data.priceUSD\n ))\n order_storage.update(data=update_data)\n\n\nif __name__ == '__main__':\n \"\"\"Run script\"\"\"\n Demon().run()\n","repo_name":"xristxgod/PARSER-SCRIPT","sub_path":"demon/app/demon.py","file_name":"demon.py","file_ext":"py","file_size_in_byte":6293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"24941062491","text":"NETDEV_TYPE_UNKNOWN = 0\nNETDEV_TYPE_BRIDGE = 1\nNETDEV_TYPE_DEV = 2\nNETDEV_TYPE_NETWORK = 3\n\nclass netdev(object):\n \"\"\"Definition of an individual network device.\"\"\"\n\n def __init__(self, mac=\"auto\", type=NETDEV_TYPE_UNKNOWN,\n source=None, driver=None):\n \"\"\"\n @mac: either a MAC address, or \"auto\"\n @type: NETDEV_TYPE_*\n @source: bridge or net device, or network name\n @driver: device emulated for VM (e.g. vmxnet)\n \"\"\"\n self.mac = mac\n self.type = type\n self.source = source\n self.driver = driver\n","repo_name":"rlaager/python-virtinst","sub_path":"virtconv/netdevcfg.py","file_name":"netdevcfg.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"51"} +{"seq_id":"1578525470","text":"\nimport clipboard\n\n# Helper macros\ndef ti(s):\n return (int)(s)\n\ndef ts(i):\n return (str)(i)\n\ndef tii(ss):\n ret = []\n for i in ss:\n ret.append(ti(i))\n return ret\n\ndef tss(ii):\n ret = []\n for i in ii:\n ret.append(ts(i))\n return ret\n\n\n# Read input\nwith open(\"input.txt\", \"r\") as f:\n lines = f.readlines()\n n = len(lines)\n for i in range(n):\n lines[i] = lines[i].strip().split(\" \")\n\nres = 0\nm = {'byr': 0,\n 'iyr': 0,\n 'eyr': 0,\n 'hgt': 0,\n 'hcl': 0,\n 'ecl': 0,\n 'pid': 0,\n 'cid': 0}\nfor i in range(len(lines)):\n if lines[i] == ['']:\n v = True\n for i in m:\n if i == 'cid':\n continue\n v = v and m[i] == 1\n m[i] = 0\n if v:\n res += 1\n else:\n for j in lines[i]:\n m[j[0:3]] = 1\n\nprint(res)\nclipboard.copy(res)\n","repo_name":"willjhliang/advent-of-code","sub_path":"2020/day4/sol1.py","file_name":"sol1.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"1142355423","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nimport datetime\r\n\r\nimport mongoDB14 as mongoDB\r\n\r\nclass etherscamdbCrawler:\r\n def setDB(self):\r\n dbName = 'ws_datas'\r\n collectionName = 'etherscamdb_address'\r\n keyField = 'address' \r\n \r\n self.db = mongoDB.MongoConnector(dbName, collectionName)\r\n self.db.connect()\r\n self.db.setKeyField(keyField)\r\n \r\n def crawl(self):\r\n url = 'https://etherscamdb.info/api/scams/'\r\n req = requests.get(url)\r\n soup = req.json()\r\n \r\n for each in soup['result']:\r\n if 'addresses' in list(each.keys()):\r\n #print(each['addresses'])\r\n for item in each['addresses']:\r\n infor = {'address':item,\r\n 'dateScraped':datetime.datetime.now()\r\n }\r\n print(infor)\r\n self.db.insertOne(infor)\r\n\r\nif __name__==\"__main__\":\r\n c = etherscamdbCrawler()\r\n c.setDB() \r\n c.crawl()","repo_name":"krispediadot/blockchain-analysis","sub_path":"ethreum/etherscamdb.py","file_name":"etherscamdb.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"51"} +{"seq_id":"43450527474","text":"import random\nimport pandas as pd\nimport sys\n\ndef read_random_rows(file_path, seed, fraction=0.05):\n 'Ŗandomly sampling fraction of records from csv file into pandas dataframe based on: https://cmdlinetips.com/2022/07/randomly-sample-rows-from-a-big-csv-file/'\n random.seed(seed)\n if fraction < 1:\n return pd.read_csv(file_path, \n skiprows=lambda x: x > 0 and random.random() >=fraction)\n else:\n return pd.read_csv(file_path)\n \n\nif __name__ == \"__main__\":\n file_path = sys.argv[1]\n seed = 4321\n df = read_random_rows(file_path=file_path, seed=seed,fraction=1)\n print(df.describe())\n print(len(df))","repo_name":"omegatro/IGP_2023","sub_path":"modules/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"41152756369","text":"#\n# Title: BOJ 11866 요세푸스 문제 0\n# Theory : 구현, 자료 구조, 큐\n# Date: 23.05.13\n#\nfrom collections import deque\nimport sys\ninput = sys.stdin.readline\n\nn, k = map(int, input().split())\nQ = deque()\nfor i in range(n):\n Q.append(i+1)\nresult = []\nwhile Q:\n for i in range(k-1):\n Q.append(Q.popleft())\n result.append(Q.popleft())\n\nprint(\"<\", end=\"\")\nprint(\", \".join(map(str, result)), end=\"\")\nprint(\">\")\n","repo_name":"rlagkswn00/AlgorithmStudy","sub_path":"PythonAlgorithm/Class02+/11866.py","file_name":"11866.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"28777529807","text":"import networkx as nx\nimport sys\nimport random\nimport csv\n\ntest_file = open('inputGraph/Graph.csv', 'w')\nfile_writer = csv.writer(test_file)\n\nnumNodes = sys.argv[1]\nnumConnectivity = sys.argv[2]\n\nGC1 = nx.complete_graph(range(0,int(numNodes)), nx.DiGraph())\nfor i in range(len(list(GC1.edges))):\n file_writer.writerow([x for x in list(GC1.edges)[i]])\nGC2 = nx.complete_graph(range(int(numNodes),2*int(numNodes)), nx.DiGraph())\nfor i in range(len(list(GC2.edges))):\n file_writer.writerow([x for x in list(GC2.edges)[i]])\nGC3 = nx.complete_graph(range(2*int(numNodes),3*int(numNodes)), nx.DiGraph())\nfor i in range(len(list(GC3.edges))):\n file_writer.writerow([x for x in list(GC3.edges)[i]])\nGC4 = nx.complete_graph(range(3*int(numNodes),4*int(numNodes)), nx.DiGraph())\nfor i in range(len(list(GC4.edges))):\n file_writer.writerow([x for x in list(GC4.edges)[i]])\nGC5 = nx.complete_graph(range(4*int(numNodes),5*int(numNodes)), nx.DiGraph())\nfor i in range(len(list(GC5.edges))):\n file_writer.writerow([x for x in list(GC5.edges)[i]])\n\nconnectivityEdges= set()\n\nfor i in range(int(numConnectivity)):\n rs1 = random.choice(list(GC1.nodes()))\n rt2 = random.choice(list(GC2.nodes()))\n connectivityEdges.add((rs1, rt2))\n rs2 = random.choice(list(GC2.nodes()))\n rt3 = random.choice(list(GC3.nodes()))\n connectivityEdges.add((rs2, rt3))\n rs3 = random.choice(list(GC3.nodes()))\n rt4 = random.choice(list(GC4.nodes()))\n connectivityEdges.add((rs3, rt4))\n rs4 = random.choice(list(GC4.nodes()))\n rt5 = random.choice(list(GC5.nodes()))\n connectivityEdges.add((rs4, rt5))\n\nfor i in range(len(list(connectivityEdges))):\n file_writer.writerow([x for x in list(connectivityEdges)[i]])\n\nprint(len(connectivityEdges))\ntest_file.close()\n","repo_name":"ayushpandey8439/CALockBench","sub_path":"StressTest/Hierarchical-locks-Graph/graphGenerator.py","file_name":"graphGenerator.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"74909104157","text":"import tensorflow as tf\nimport numpy as np\nfrom numpy.random import RandomState\ndef main1():\n a = tf.constant([1, 2], name=\"a\")\n b = tf.constant([3, 4], name=\"b\")\n print(a + b)\n g = tf.Graph()\n #指定计算运行的设备\n with g.device('/gpu:0'):\n result = a + b\n print(result)\n #创建一个会话\n sess = tf.Session()\n with sess.as_default():\n print(result.eval())\n print(sess.run(result))\n\n\ndef main2():\n g1 = tf.Graph()\n with g1.as_default():\n #在计算图g1中定义变量“v”,并设置初始值为0\n v = tf.get_variable(\n \"v\",initializer=tf.zeros_initializer(),shape=[1]\n )\n\n g2 = tf.Graph()\n with g2.as_default():\n #在计算图g2中定义变量“v”,并设置初始值为0\n v = tf.get_variable(\n \"v\", initializer=tf.ones_initializer(), shape=[1]\n )\n\n #在计算图g1中读取变量“v”的取值\n with tf.Session(graph=g1) as sess:\n tf.initialize_all_variables().run()\n with tf.variable_scope(\"\",reuse=True):\n #在计算图g1中, 变量“v”的取值应该取为0,所以下面会输出[0.]\n print(sess.run(tf.get_variable(\"v\")))\n\n # 在计算图g1中读取变量“v”的取值\n with tf.Session(graph=g2) as sess:\n tf.initialize_all_variables().run()\n with tf.variable_scope(\"\", reuse=True):\n # 在计算图g2中, 变量“v”的取值应该取为1,所以下面会输出[1.]\n print(sess.run(tf.get_variable(\"v\")))\n\ndef main3():\n #声明一个(2,3)矩阵\n weights = tf.Variable(tf.random_normal([2,3],stddev=2))\n\ndef main4():\n w1 = tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))\n w2 = tf.Variable(tf.random_normal([3,1], stddev=1, seed=1))\n\n x = tf.constant([[0.7,0.9]])\n\n a = tf.matmul(x,w1)\n y = tf.matmul(a,w2)\n sess = tf.Session()\n\n # sess.run(w1.initializer)\n # sess.run(w2.initializer)\n #换另一种方式,一次性初始化所有变量\n sess.run(tf.initialize_all_variables())\n\n print(sess.run(y))\n sess.close()\n\n\ndef main5():\n w1 = tf.Variable(tf.random_normal([2,3],stddev=1))\n w2 = tf.Variable(tf.random_normal([3,1], stddev=1))\n #定义placeholder作为存放数据的地方,这里维度不一定要定义\n #如果维度是确定的,那么给出维度会降低出错的概率\n x = tf.placeholder(tf.float32,shape=(1,2),name=\"input\")\n a = tf.matmul(x,w1)\n y = tf.matmul(a,w2)\n sess = tf.Session()\n init_op = tf.initialize_all_variables()\n sess.run(init_op)\n\n print(sess.run(y,feed_dict={x:[[0.7,0.9]]}))\n\ndef main_test():\n #定义数据batch的大小\n batch_size = 8\n\n w1 = tf.Variable(tf.random_normal([2, 3], stddev=1,seed=1))\n w2 = tf.Variable(tf.random_normal([3, 1], stddev=1,seed=1))\n x = tf.placeholder(tf.float32,shape=(None,2),name=\"x-input\")\n y_ = tf.placeholder(tf.float32,shape=(None,1),name=\"y-input\")\n\n #定义神经网咯前向传播的过程\n a = tf.matmul(x,w1)\n y = tf.matmul(a,w2)\n\n #定义损失函数和反向传播的过程,\n cross_entropy = -tf.reduce_mean(\n y_ * tf.log(tf.clip_by_value(y,1e-10,1.0))\n )\n train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)\n\n #通过随机数生成一个模拟数据集\n rdm = RandomState(1)\n dataset_size = 128\n X = rdm.rand(dataset_size,2)\n Y = [[int(x1+x2<1)] for (x1,x2) in X]\n\n with tf.Session() as sess:\n init_op = tf.initialize_all_variables()\n sess.run(init_op)\n print(sess.run(w1))\n print(sess.run(w2))\n\n #训练的轮数\n STEPS = 5000\n for i in range(STEPS):\n #每次选取batch_size个样本进行训练\n start = (i*batch_size)%dataset_size\n end = min(start + batch_size,dataset_size)\n\n #通过选取的样本训练神经网络并更新参数\n sess.run(train_step,\n feed_dict={x:X[start:end],y_:Y[start:end]})\n if i % 1000 == 0:\n #每隔一段时间计算在所有数据上的交叉熵并输出\n total_cross_entropy = sess.run(\n cross_entropy,feed_dict={x:X,y_:Y}\n )\n print(\"After %d training step(s),cross entropy on all data is %g\"%(i,total_cross_entropy))\n\n print(sess.run(w1))\n print(sess.run(w2))\n\n\n\n\nif __name__ == \"__main__\":\n #main1()\n #main2()\n #main3( )\n #main4 ()\n #main5()\n main_test()","repo_name":"lhtlht/my_tensorflow","sub_path":"part3.py","file_name":"part3.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"51"} +{"seq_id":"23984385676","text":"#This file is where we will define our paths to our different webpages. This will be the urls for our views\n#I.E if im on google, the path url for the settings is different than the path for the search, this page determines those paths\nfrom django.urls import path\nfrom . import views #Calls the views file\n\napp_name = 'blog'\n\nurlpatterns = [\n path('', views.all_blogs, name='all_blogs'),\n path('/', views.detail, name='detail'),\n]\n\n#acess views then go to the index\n\n","repo_name":"mic4x/My_Portfolio","sub_path":"portfolio_site/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"586940592","text":"n1 = int(input())\nlist1 = []\nleft = 0\nright = 0\nfor i in range(n1):\n x = input().split()\n temp = []\n for j in x:\n temp.append(int(j))\n left += temp[0]\n right += temp[1]\n\ncount = 0 \nif n1 - left> left - 0:\n count += left\nelif left > n1 - left:\n count+= n1 - left\nelse:\n count += left\n\nif n1 - right> right - 0:\n count += right\nelif right > n1 - right:\n count+= n1 - right\nelse:\n count += right\n\nprint(count)\n","repo_name":"UdhayaShan1/CodeForces","sub_path":"248A - Cupboards.py","file_name":"248A - Cupboards.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"57"} +{"seq_id":"23966731213","text":"\nfrom typing import List, Dict\n\nimport datetime\n\n\ndef convert_to_dynamodb_documents(\n user_id: int, # id юзера - от 1 до 1_000_000\n day: datetime.date, # день, за который нужно записать данные в базу\n activity_scores: List[int] # список ровно из 2880 значений activity_scores,\n # каждая из которых записана с интервалом в 30 секунд\n # с начала дня по UTC\n) -> List[Dict]:\n \"\"\"\n Храним блоками по 4 часа.\n Т.к. значения в интервале от 1 до 99, мы можем упаковать 2 значения в одно двухбайтовое число.\n Итого, за час ожидаем 1440 (2880 / 2) значений в списке, объем хранимых данных на 4-х часовой блок:\n 3 байта на id + 5 байт на timestamp + (1 + 1440 * 2 + 1440 + 3) * 4 на список = 17304 байт\n с округлением вверх получаем блок в 17Кб.\n Оценка стоимости запросов:\n запись: 102 WRU = 17 WRU (17 КБ) * 6 документов\n чтение: 25 RRU\n 1 час: 5 RRU (17 КБ) - выбираем из 4-х часового куска нужный диапазон.\n 12 часов: - в худшем случае нам потребуется выбрать четыре 4-х часовых диапазона (если повезет, то три)\n 4 документа * 5 (17 КБ / 4 КБ с округлением вверх) RRU = 20 RRU\n Итого (на 1 млн пользователей): 102 * 1.25 + 25 * 0.25 = 133.75\n :param user_id:\n :param day:\n :param activity_scores:\n :return:\n \"\"\"\n result = []\n for i in range(6): # Шесть 4-х часовых блоков\n _t = int(day.strftime(\"%s\")) + 3600 * 4 * i\n result.append(\n {\n 'u': user_id,\n 't': _t,\n 'v': [\n activity_scores[i] * 128 + activity_scores[i + 1] # упаковываем 2 значения в одно\n for i in range(2880 * 4 * i, 2880 * 4 * (i + 1), 2)\n ],\n }\n )\n return result\n","repo_name":"mkhaykin/convert","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"34541247705","text":"from __future__ import absolute_import\n\nimport os\nimport shlex\nimport time\n\nfrom mig.shared.base import client_id_dir\nfrom mig.shared.defaults import any_state, keyword_auto, valid_trigger_actions, \\\n valid_trigger_changes, keyword_all\nfrom mig.shared.functional import validate_input_and_cert, REJECT_UNSET\nfrom mig.shared.handlers import safe_handler, get_csrf_limit\nfrom mig.shared.init import initialize_main_variables, find_entry\nfrom mig.shared.safeinput import valid_path_pattern\nfrom mig.shared.validstring import valid_user_path\nfrom mig.shared.vgrid import init_vgrid_script_add_rem, vgrid_is_trigger, \\\n vgrid_is_trigger_owner, vgrid_list_subvgrids, vgrid_add_triggers, \\\n vgrid_triggers\nfrom mig.shared import returnvalues\n\n\ndef signature():\n \"\"\"Signature of the main function\"\"\"\n\n defaults = {'vgrid_name': REJECT_UNSET,\n 'rule_id': [keyword_auto],\n 'path': [''],\n 'changes': [any_state],\n 'action': [keyword_auto],\n 'arguments': [''],\n 'rate_limit': [''],\n 'settle_time': [''],\n 'match_files': ['True'],\n 'match_dirs': ['False'],\n 'match_recursive': ['False'],\n 'rank': [''],\n }\n return ['', defaults]\n\n\ndef main(client_id, user_arguments_dict):\n \"\"\"Main function used by front end\"\"\"\n\n (configuration, logger, output_objects, op_name) = \\\n initialize_main_variables(client_id, op_header=False)\n client_dir = client_id_dir(client_id)\n defaults = signature()[1]\n title_entry = find_entry(output_objects, 'title')\n label = \"%s\" % configuration.site_vgrid_label\n title_entry['text'] = \"Add/Update %s Trigger\" % label\n output_objects.append({'object_type': 'header', 'text':\n 'Add/Update %s Trigger' % label})\n (validate_status, accepted) = validate_input_and_cert(\n user_arguments_dict,\n defaults,\n output_objects,\n client_id,\n configuration,\n allow_rejects=False,\n typecheck_overrides={'path': valid_path_pattern},\n )\n if not validate_status:\n return (accepted, returnvalues.CLIENT_ERROR)\n\n # NOTE: strip leftmost slashes from all fields used in file paths to avoid\n # interference with os.path.join calls. Furthermore we strip and normalize\n # the path variable first to make sure it does not point outside the vgrid.\n # In practice any such directory traversal attempts will generally be moot\n # since the grid_events daemon only starts a listener for each top-level\n # vgrid and in there only reacts to events that match trigger rules from\n # that particular vgrid. Thus only subvgrid access to parent vgrids might\n # be a concern and still of limited consequence.\n # NOTE: merge multi args into one string and split again to get flat array\n rule_id = accepted['rule_id'][-1].strip()\n vgrid_name = accepted['vgrid_name'][-1].strip().lstrip(os.sep)\n path = os.path.normpath(accepted['path'][-1].strip()).lstrip(os.sep)\n changes = [i.strip() for i in ' '.join(accepted['changes']).split()]\n action = accepted['action'][-1].strip()\n arguments = [i.strip() for i in\n shlex.split(' '.join(accepted['arguments']))]\n rate_limit = accepted['rate_limit'][-1].strip()\n settle_time = accepted['settle_time'][-1].strip()\n match_files = accepted['match_files'][-1].strip() == 'True'\n match_dirs = accepted['match_dirs'][-1].strip() == 'True'\n match_recursive = accepted['match_recursive'][-1].strip() == 'True'\n rank_str = accepted['rank'][-1]\n try:\n rank = int(rank_str)\n except ValueError:\n rank = None\n\n logger.debug(\"addvgridtrigger with args: %s\" % user_arguments_dict)\n\n if not safe_handler(configuration, 'post', op_name, client_id,\n get_csrf_limit(configuration), accepted):\n output_objects.append(\n {'object_type': 'error_text', 'text': '''Only accepting\nCSRF-filtered POST requests to prevent unintended updates'''\n })\n return (output_objects, returnvalues.CLIENT_ERROR)\n\n # Please note that base_dir must end in slash to avoid access to other\n # user dirs when own name is a prefix of another user name\n\n base_dir = os.path.abspath(os.path.join(configuration.user_home,\n client_dir)) + os.sep\n\n # we just use a high res timestamp as automatic rule_id\n\n if rule_id == keyword_auto:\n rule_id = \"%d\" % (time.time() * 1E8)\n\n if action == keyword_auto:\n action = valid_trigger_actions[0]\n\n if any_state in changes:\n changes = valid_trigger_changes\n\n logger.info(\"addvgridtrigger %s\" % vgrid_name)\n\n # Validity of user and vgrid names is checked in this init function so\n # no need to worry about illegal directory traversal through variables\n\n (ret_val, msg, ret_variables) = \\\n init_vgrid_script_add_rem(vgrid_name, client_id,\n rule_id, 'trigger',\n configuration)\n if not ret_val:\n output_objects.append({'object_type': 'error_text', 'text': msg})\n return (output_objects, returnvalues.CLIENT_ERROR)\n elif msg:\n\n # In case of warnings, msg is non-empty while ret_val remains True\n\n output_objects.append({'object_type': 'warning', 'text': msg})\n\n # if we get here user is either vgrid owner or allowed to add rule\n\n # don't add if already in vgrid or parent vgrid - but update if owner\n\n update_id = None\n if vgrid_is_trigger(vgrid_name, rule_id, configuration):\n if vgrid_is_trigger_owner(vgrid_name, rule_id, client_id,\n configuration):\n update_id = 'rule_id'\n else:\n output_objects.append(\n {'object_type': 'error_text', 'text':\n '%s is already a trigger owned by somebody else in the %s' %\n (rule_id, label)})\n return (output_objects, returnvalues.CLIENT_ERROR)\n\n # don't add if already in subvgrid\n\n (list_status, subvgrids) = vgrid_list_subvgrids(vgrid_name,\n configuration)\n if not list_status:\n output_objects.append({'object_type': 'error_text', 'text':\n 'Error getting list of sub%ss: %s' %\n (label, subvgrids)})\n return (output_objects, returnvalues.SYSTEM_ERROR)\n for subvgrid in subvgrids:\n if vgrid_is_trigger(subvgrid, rule_id, configuration, recursive=False):\n output_objects.append({'object_type': 'error_text', 'text':\n '''%(rule_id)s is already in a\nsub-%(vgrid_label)s (%(subvgrid)s). Please remove the trigger from the\nsub-%(vgrid_label)s and try again''' % {'rule_id': rule_id,\n 'subvgrid': subvgrid,\n 'vgrid_label': label}})\n return (output_objects, returnvalues.CLIENT_ERROR)\n\n if not action in valid_trigger_actions:\n output_objects.append(\n {'object_type': 'error_text', 'text':\n \"invalid action value %s\" % action})\n return (output_objects, returnvalues.CLIENT_ERROR)\n\n if keyword_all in changes:\n changes = valid_trigger_changes\n for change in changes:\n if not change in valid_trigger_changes:\n output_objects.append(\n {'object_type': 'error_text', 'text':\n \"found invalid change value %s\" % change})\n return (output_objects, returnvalues.CLIENT_ERROR)\n\n # Check if we should load saved trigger for rank change or update\n\n rule_dict = None\n if rank is not None or update_id is not None:\n (load_status, all_triggers) = vgrid_triggers(vgrid_name, configuration)\n if not load_status:\n output_objects.append({\n 'object_type': 'error_text', 'text':\n 'Failed to load triggers for %s: %s' %\n (vgrid_name, all_triggers)})\n return (output_objects, returnvalues.SYSTEM_ERROR)\n for saved_dict in all_triggers:\n if saved_dict['rule_id'] == rule_id:\n rule_dict = saved_dict\n break\n if rule_dict is None:\n output_objects.append({\n 'object_type': 'error_text', 'text':\n 'No such trigger %s for %s: %s' % (rule_id, vgrid_name,\n all_triggers)})\n return (output_objects, returnvalues.CLIENT_ERROR)\n elif not path:\n # New trigger with missing path\n output_objects.append(\n {'object_type': 'error_text', 'text':\n 'Either path or rank must be set.'})\n return (output_objects, returnvalues.CLIENT_ERROR)\n elif action == \"submit\" and not arguments:\n # New submit trigger with missing mrsl arguments\n output_objects.append(\n {'object_type': 'error_text', 'text': '''Submit triggers must give\na job description file path as argument.'''})\n return (output_objects, returnvalues.CLIENT_ERROR)\n\n # Handle create and update (i.e. new, update all or just refresh mRSL)\n\n if rank is None:\n\n # IMPORTANT: we save the job template contents to avoid potential abuse\n # Otherwise someone else in the VGrid could tamper with the template\n # and make the next trigger execute arbitrary code on behalf of the\n # rule owner.\n\n templates = []\n\n # Merge current and saved values\n\n req_dict = {'rule_id': rule_id,\n 'vgrid_name': vgrid_name,\n 'path': path,\n 'changes': changes,\n 'run_as': client_id,\n 'action': action,\n 'arguments': arguments,\n 'rate_limit': rate_limit,\n 'settle_time': settle_time,\n 'match_files': match_files,\n 'match_dirs': match_dirs,\n 'match_recursive': match_recursive,\n 'templates': templates\n }\n if rule_dict is None:\n rule_dict = req_dict\n else:\n for field in user_arguments_dict:\n if field in req_dict:\n rule_dict[field] = req_dict[field]\n\n # Now refresh template contents\n\n if rule_dict['action'] == \"submit\":\n for rel_path in rule_dict['arguments']:\n # IMPORTANT: path must be expanded to abs for proper chrooting\n abs_path = os.path.abspath(os.path.join(base_dir, rel_path))\n try:\n if not valid_user_path(configuration, abs_path, base_dir,\n True):\n logger.warning(\n '%s tried to %s restricted path %s ! (%s)'\n % (client_id, op_name, abs_path, rel_path))\n raise ValueError('invalid submit path argument: %s'\n % rel_path)\n temp_fd = open(abs_path)\n templates.append(temp_fd.read())\n temp_fd.close()\n except Exception as err:\n logger.error(\"read submit argument file %s failed: %s\" %\n (abs_path, err))\n output_objects.append(\n {'object_type': 'error_text', 'text':\n 'failed to read submit argument file \"%s\"' % rel_path\n })\n return (output_objects, returnvalues.CLIENT_ERROR)\n\n # Save updated template contents here\n rule_dict['templates'] = templates\n\n # Add to list and pickle\n\n (add_status, add_msg) = vgrid_add_triggers(configuration, vgrid_name,\n [rule_dict], update_id, rank)\n if not add_status:\n logger.error('%s failed to add/update trigger: %s' % (client_id,\n add_msg))\n output_objects.append({'object_type': 'error_text', 'text': '%s' %\n add_msg})\n return (output_objects, returnvalues.SYSTEM_ERROR)\n\n if rank is not None:\n logger.info('%s moved trigger %s to %d' % (client_id, rule_id, rank))\n output_objects.append({'object_type': 'text', 'text':\n 'moved %s trigger %s to position %d' %\n (vgrid_name, rule_id, rank)})\n elif update_id:\n logger.info('%s updated trigger: %s' % (client_id, rule_dict))\n output_objects.append(\n {'object_type': 'text', 'text':\n 'Existing trigger %s successfully updated in %s %s!' %\n (rule_id, vgrid_name, label)})\n else:\n logger.info('%s added new trigger: %s' % (client_id, rule_dict))\n output_objects.append(\n {'object_type': 'text', 'text':\n 'New trigger %s successfully added to %s %s!' %\n (rule_id, vgrid_name, label)})\n\n output_objects.append({'object_type': 'link', 'destination':\n 'vgridworkflows.py?vgrid_name=%s' % vgrid_name,\n 'text': 'Back to workflows for %s' % vgrid_name})\n return (output_objects, returnvalues.OK)\n","repo_name":"ucphhpc/migrid-sync","sub_path":"mig/shared/functionality/addvgridtrigger.py","file_name":"addvgridtrigger.py","file_ext":"py","file_size_in_byte":13536,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"57"} +{"seq_id":"35449327144","text":"from django.shortcuts import redirect\nimport stripe\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\n# This is your test secret API key.\nstripe.api_key = 'sk_test_51M1BvtESeOfTGQ8nrACOvoHmcEFeS4vIvxhCISfskv9uU7ScEv1ALpHKvOxNdXRskW5b86apJlMk0dgzuWF0KOK900TkYzC6Tc'\n\n\nYOUR_DOMAIN = 'http://localhost:3000'\n\nclass CreatePaymentView(APIView):\n authentication_classes = []\n permission_classes = []\n # serializer_class = VerifySerializer\n\n def post(self, request):\n # serializer = self.serializer_class(data=request.data)\n # if serializer.is_valid():\n try:\n checkout_session = stripe.checkout.Session.create(\n line_items=[\n {\n \"price_data\":{\n \"currency\": \"usd\",\n \"unit_amount\": 20 * 100,\n \"product_data\": {\n \"name\": \"abc\",\n \"description\": \"test description\",\n\n }\n\n },\n \"quantity\": 2,\n },\n ],\n payment_method_types=[\"card\",],\n mode='payment',\n success_url=YOUR_DOMAIN + '?success=true',\n cancel_url=YOUR_DOMAIN + '?canceled=true',\n )\n except Exception as e:\n return Response({\"error\": str(e)}, status=status.HTTP_400_BAD_REQUEST)\n return redirect(checkout_session.url)\n\n # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n\n\n\n","repo_name":"sunday-ucheawaji/ecommerce","sub_path":"payment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"1157936202","text":"from typing import List\n\nfrom numpy import array, float_\n\n\ndef list2array(inputList: List) -> array:\n \"\"\"\n Converts list() to numpy.array()\n :param inputList: list()\n :return: numpy.array()\n \"\"\"\n if inputList is None:\n raise ValueError\n else:\n return array(inputList, dtype=float_)\n","repo_name":"Yuriy-Garev/unilim-crack-prop","sub_path":"_models/helpers/data_type_converter.py","file_name":"data_type_converter.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"36565900413","text":"import streamlit as st\nimport pandas as pd\nimport pickle\nimport xgboost as xgb\nimport numpy as np\n\n#\nst.write(\"\"\"# House Price Prediction\nThis app predicts the house price in **Ames, Iowa**\"\"\")\nst.write('---')\n\nst.sidebar.header(\"Specify Your Parameters\")\n\n# customed features input function\ndef user_input_features():\n yearbuilt = st.sidebar.slider(\"Year Built\", min_value=1800, max_value=2024, value=2000, step=1)\n grlivarea = st.sidebar.slider(\"Above ground living space square feet\", min_value=300, max_value=7000, value=2000, step=100)\n garagecars = st.sidebar.slider(\"Garage size (Fit how many cars?)\", min_value=0, max_value=4, value=2, step=1)\n centralair = st.sidebar.slider('Central air conditioning? Yes->\"1\"; No->\"0', min_value=0, max_value=1, value=1)\n totalbsmtsf = st.sidebar.slider(\"Total square feet of basement area\", min_value=0, max_value=7000, value=500, step=100)\n bsmtfinsf1 = st.sidebar.slider(\"Good Living Quarters square feet\", min_value=0, max_value=7000, value=500, step=100)\n firstflrsf = st.sidebar.slider(\"First Floor square feet\", min_value=300, max_value=1200, value=500, step=100)\n lotarea = st.sidebar.slider(\"Lot size in square feet\", min_value=1300, max_value=8000, value=3000, step=100)\n masvnrarea = st.sidebar.slider(\"Masonry veneer area in square feet\", min_value=0, max_value=500, value=100, step=10)\n garageyrblt = st.sidebar.slider(\"Year garage was built\", min_value=1800, max_value=2024, value=2000, step=1)\n\n data = {\n \"yearbuilt\": yearbuilt,\n \"grlivarea\": grlivarea,\n \"garagecars\": garagecars,\n \"centralair=y\": centralair,\n \"totalbsmtsf\": totalbsmtsf,\n \"bsmtfinsf1\": bsmtfinsf1,\n \"1stflrsf\": firstflrsf,\n \"lotarea\": lotarea,\n \"masvnrarea\": masvnrarea,\n \"garageyrblt\": garageyrblt\n }\n\n features = pd.DataFrame(data, index=[0])\n return features\n\ndf = user_input_features()\n# main panel\nst.header(\"Specify Your Parameters\")\nst.write(df)\nst.write(\"---\")\n\n# load model\nmodle_file = \"model.bin\"\n\nwith open(modle_file, \"rb\") as f_in:\n dv, model = pickle.load(f_in)\n\ndef predict():\n X = dv.transform(df.to_dict(orient=\"records\"))\n dx = xgb.DMatrix(X, feature_names=dv.get_feature_names_out().tolist())\n prediction = model.predict(dx)\n price = np.expm1(prediction)[0]\n result = {\n \"price\": float(price)\n }\n\n return result[\"price\"]\n\nst.subheader(\"Estimated house price\")\nst.write(\"👇👇👇👇👇👇👇👇👇👇\")\nst.write(predict())\nst.write(\"👆👆👆👆👆👆👆👆👆👆\")","repo_name":"sarah-zhan/house_price_prediction","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"16814656047","text":"from ulab.numpy import array, zeros, eye, ones\nfrom snippets import numpy\n\na = array([[1, 1]])\nb = array([[2]])\nc = array(\n [[3, 3],\n [3, 3],\n [3, 3]])\nd = array(\n [[4],\n [4],\n [4]])\nprint(numpy.block([[a, b], [c, d]]))\na = zeros((2, 3))\nb = eye(2) * 2\nc = eye(3) * 5\nd = ones((3, 2))\nprint(numpy.block([[a, b], [c, d]]))\n","repo_name":"v923z/micropython-ulab","sub_path":"snippets/tests/numpy/lib/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":363,"dataset":"github-code","pt":"57"} +{"seq_id":"10276565382","text":"## \\file\n## \\ingroup tutorial_roofit\n## \\notebook\n## Addition and convolution: fitting and plotting in sub ranges\n##\n## \\macro_image\n## \\macro_code\n## \\macro_output\n##\n## \\date February 2018\n## \\authors Clemens Lange, Wouter Verkerke (C++ version)\n\nfrom __future__ import print_function\nimport ROOT\n\n# Set up model\n# ---------------------\n\n# Construct observables x\nx = ROOT.RooRealVar(\"x\", \"x\", -10, 10)\n\n# Construct gaussx(x,mx,1)\nmx = ROOT.RooRealVar(\"mx\", \"mx\", 0, -10, 10)\ngx = ROOT.RooGaussian(\"gx\", \"gx\", x, mx, 1.0)\n\n# px = 1 (flat in x)\npx = ROOT.RooPolynomial(\"px\", \"px\", x)\n\n# model = f*gx + (1-f)px\nf = ROOT.RooRealVar(\"f\", \"f\", 0.0, 1.0)\nmodel = ROOT.RooAddPdf(\"model\", \"model\", [gx, px], [f])\n\n# Generated 10000 events in (x,y) from pdf model\nmodelData = model.generate({x}, 10000)\n\n# Fit full range\n# ---------------------------\n\n# Fit pdf to all data\nr_full = model.fitTo(modelData, Save=True, PrintLevel=-1)\n\n# Fit partial range\n# ----------------------------------\n\n# Define \"signal\" range in x as [-3,3]\nx.setRange(\"signal\", -3, 3)\n\n# Fit pdf only to data in \"signal\" range\nr_sig = model.fitTo(modelData, Save=True, Range=\"signal\", PrintLevel=-1)\n\n# Plot/print results\n# ---------------------------------------\n\n# Make plot frame in x and add data and fitted model\nframe = x.frame(Title=\"Fitting a sub range\")\nmodelData.plotOn(frame)\nmodel.plotOn(frame, Range=\"Full\", LineColor=\"r\", LineStyle=\"--\") # Add shape in full ranged dashed\nmodel.plotOn(frame) # By default only fitted range is shown\n\n# Print fit results\nprint(\"result of fit on all data \")\nr_full.Print()\nprint(\"result of fit in in signal region (note increased error on signal fraction)\")\nr_sig.Print()\n\n# Draw frame on canvas\nc = ROOT.TCanvas(\"rf203_ranges\", \"rf203_ranges\", 600, 600)\nROOT.gPad.SetLeftMargin(0.15)\nframe.GetYaxis().SetTitleOffset(1.4)\nframe.Draw()\n\nc.SaveAs(\"rf203_ranges.png\")\n","repo_name":"root-project/root","sub_path":"tutorials/roofit/rf203_ranges.py","file_name":"rf203_ranges.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","stars":2290,"dataset":"github-code","pt":"57"} +{"seq_id":"9265873200","text":"from urllib.request import Request, urlopen\nfrom urllib.parse import unquote\nfrom bs4 import BeautifulSoup\nfrom tqdm import tqdm\nimport concurrent.futures\nfrom hashlib import md5\nfrom random import choice\n\n\ndef get_links(file: str):\n url = 'https://ru.wikipedia.org/wiki/%D0%A1%D0%BB%D1%83%D0%B6%D0%B5%D0%B1%D0%BD%D0%B0%D1%8F:%D0%A1%D0%BB%D1%83%D1%87%D0%B0%D0%B9%D0%BD%D0%B0%D1%8F_%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0'\n\n res = open(file, 'w', encoding='utf8')\n\n for i in tqdm(range(100)):\n html = urlopen(url).read().decode('utf8')\n soup = BeautifulSoup(html, 'html.parser')\n links = soup.find_all('a')\n\n for l in links:\n href = l.get('href')\n if href and href.startswith('http') and 'wiki' not in href:\n print(href, file=res)\n\n\ndef load_url(url, timeout):\n try:\n request = Request(\n url,\n headers={'User-Agent': 'Mozilla/5.0 (Windows NT 9.0; Win65; x64; rv:97.0) Gecko/20105107 Firefox/92.0'},\n )\n resp = urlopen(request, timeout=timeout)\n code = resp.code\n resp.close()\n return code\n except Exception as e:\n return [url, e]\n\n\ndef open_links(file: str):\n links = open(file, encoding='utf8').read().split('\\n')\n\n with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:\n future_to_url = {executor.submit(load_url, url, 5) for url in links}\n for future in concurrent.futures.as_completed(future_to_url):\n print(future.result())\n\n\ndef generate_coin():\n while True:\n s = \"\".join([choice(\"0123456789\") for i in range(50)])\n h = md5(s.encode('utf8')).hexdigest()\n if h.endswith(\"00000\"):\n return [s, h]\n\n\ndef find_coins(needed: int):\n with concurrent.futures.ProcessPoolExecutor(max_workers=100) as executor:\n tasks = [executor.submit(generate_coin) for i in range(needed)]\n for task in concurrent.futures.as_completed(tasks):\n print(task.result())\n\n\nif __name__ == '__main__':\n find_coins(5)\n","repo_name":"SiyovushShuk/parallelizm","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"32052863206","text":"#PF-Assgn-52\r\n\r\n#This verification is based on string match.\r\n\r\ndef sum_of_numbers(list_of_num,filter_func=None):\r\n sum = 0\r\n leng = len(list_of_num)\r\n count = 0\r\n count1 = 0\r\n\r\n if filter_func == None:\r\n while count != leng:\r\n w = list_of_num[count]\r\n sum = sum + w\r\n count = count + 1\r\n else:\r\n final_list = filter_func(list_of_num)\r\n leng1 = len(final_list)\r\n while count1 != leng1:\r\n w = final_list[count1]\r\n sum = sum + w\r\n count1 = count1 + 1\r\n\r\n return sum\r\n\r\ndef even(data):\r\n leng = len(data)\r\n count = 0\r\n final_list = []\r\n while count != leng:\r\n if (data[count]%2) == 0:\r\n final_list = final_list + [data[count]]\r\n count = count + 1\r\n return final_list\r\n\r\ndef odd(data):\r\n leng = len(data)\r\n count = 0\r\n final_list = []\r\n while count != leng:\r\n if (data[count] % 2) != 0:\r\n final_list = final_list + [data[count]]\r\n count = count + 1\r\n return final_list\r\n\r\n\r\n\r\nsample_data = range(1,11)\r\nfinal_data = list(sample_data)\r\n\r\n\r\nprint(sum_of_numbers(final_data,None))\r\nprint(sum_of_numbers(sample_data,odd))","repo_name":"arpan-k09/INFOSYS-PYTHON-PROG","sub_path":"odd_even.py","file_name":"odd_even.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"57"} +{"seq_id":"4159518836","text":"\n###\n# some program related to clash catalogs\nfrom os.path import *\nimport numpy as np\nfrom os.path import *\nfrom matplotlib import pyplot as plt\nfrom pylab import ion\nfrom glob import glob\nimport pdb\nimport string,sys\nfrom program import printlog\n\n###################################################################################################\ndef savecat(data,index,fname,nodata=0): \n '''\n saving the GSD data.\n if nodata is set, \n '''\n keys = ['cluster', 'ID', 'x','y','RA','DEC',\\\n 'f225w','f225we','f275w','f275we','f336w','f336we','f390w','f390we',\\\n 'f435w','f435we','f475w','f475we','f606w','f606we','f625w','f625we','f775w','f775we','f814w','f814we','f850lp','f850lpe',\\\n 'f105w','f105we','f110w','f110we','f125w','f125we','f140w','f140we','f160w','f160we'] \n keys_format = '%6s %5i %5i %5i %10.7f %10.7f '+' %11.5f %11.5f'*16\n keys_format = keys_format.split()\n formats={}\n for key,form in zip(keys,keys_format):\n formats[key]=form\n #print 'Saving %s' %(fname)\n #pdb.set_trace()\n if nodata!=0:\n txt ='# '\n else:\n txt = ''\n for key in keys:\n if index>=0:\n txt += formats[key] %(data[key][index]) \n else:\n txt += formats[key] %(data[key]) \n txt +=' '\n printlog(txt,fname)\n","repo_name":"XingxingHuang/xingpy","sub_path":"usage/clash_utils/catio.py","file_name":"catio.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"57"} +{"seq_id":"70349359217","text":"from os.path import dirname, join\nfrom itertools import combinations \n\ncurrent_dir = dirname(__file__)\nfile_path = join(current_dir, \"./9.txt\")\n\nwith open(file_path) as file:\n\tnum = [int(x) for x in file.read().split()]\n\ndef findPairs(lst, K): \n return [pair for pair in combinations(lst, 2) if sum(pair) == int(K)] \n\nfor i in range(25,len(num)):#looking for a range consists of 25 numbers\n if not findPairs(num[i-25:i],int(num[i])):\n print(num[i])\n ","repo_name":"enderax/adventofcode","sub_path":"2020/9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"24781701815","text":"import cv2\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.imagenet_utils import preprocess_input\nfrom models.pspnet_modified import modified_pspnet\n#from models.pspnet_deconv import modified_pspnet\n#from models.pspnet_drn import create_pspnet_drn\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\nTRAINED_MODEL_PATH = ''\nDATA_PATH = './data/CO_Louisville_1965'\nMAP_NAME = 'CO_Louisville_1965_degeo.png'\nMAP_PATH = os.path.join(DATA_PATH, MAP_NAME)\nWIN_SIZE = 320\nNB_CLASSES = 2\nSTRIDE = 50\nrow_start, row_end = 595, 12145#535, 10915#742, 12310#705, 12277\ncol_start, col_end = 1305, 10195#588, 8550#1175, 10078#1340, 10245\nSAVE_MODEL_DIR = './trained_models/'#'./logs'#\nTRAINED_MODEL_NAME = 'louisville_railroads_1965_pspnetdeconv.hdf5'#'louisville_railroads_1965_pspnetdrn.hdf5'\nSAVE_MODEL_PATH = os.path.join(SAVE_MODEL_DIR, TRAINED_MODEL_NAME)\nPREDICTION_NAME = 'louisville_railroads_1965_pspnetdeconv.png'\nPREDICTION_PATH = os.path.join(DATA_PATH, PREDICTION_NAME)\n\ndef dice_coef(y_true, y_pred, smooth=1):\n \"\"\"\n Dice = (2*|X & Y|)/ (|X|+ |Y|)\n = 2*sum(|A*B|)/(sum(A^2)+sum(B^2))\n ref: https://arxiv.org/pdf/1606.04797v1.pdf\n \"\"\"\n intersection = K.sum(K.abs(y_true * y_pred), axis=-1)\n return (2. * intersection + smooth) / (K.sum(K.square(y_true),-1) + K.sum(K.square(y_pred),-1) + smooth)\n\ndef dice_coef_loss(y_true, y_pred):\n return 1-dice_coef(y_true, y_pred)\n\nmodel = modified_pspnet(WIN_SIZE, NB_CLASSES)\n#model = create_pspnet_drn((WIN_SIZE,WIN_SIZE,3), NB_CLASSES)\nmodel.summary()\nmodel.load_weights(SAVE_MODEL_PATH)\n\nmap_img = cv2.imread(MAP_PATH)\npred_map = np.zeros((map_img.shape[0], map_img.shape[1]))\n\ncount = 0\nfor row in range(row_start, row_end-WIN_SIZE, STRIDE):\n for col in range(col_start, col_end-WIN_SIZE, STRIDE):\n sub_img = map_img[row:row+WIN_SIZE, col:col+WIN_SIZE].astype('float64')\n x_test = preprocess_input(np.array([sub_img]))\n res = model.predict(x_test)[0]\n pred = np.argmax(np.squeeze(res), axis=-1).astype(np.uint8)\n #pred_map[row:row+WIN_SIZE, col:col+WIN_SIZE] = pred*255.0\n pred_map[row:row+WIN_SIZE, col:col+WIN_SIZE] = np.logical_or(pred_map[row:row+WIN_SIZE, col:col+WIN_SIZE], pred)\n count += 1\n if count % 1000 == 0:\n print(\"************************\"+str(count)+\"************************\")\n \ncv2.imwrite(PREDICTION_PATH, pred_map*255.0)\n","repo_name":"spatial-computing/railroad-recognition","sub_path":"pipeline/semantic_segmentation/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"57"} +{"seq_id":"26224913713","text":"from typing import List\n\n\"\"\"\n给你一个整数数组 nums,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。\n\n\n示例 1:\n\n输入: [2,3,-2,4]\n输出: 6\n解释:子数组 [2,3] 有最大乘积 6。\n示例 2:\n\n输入: [-2,0,-1]\n输出: 0\n解释:结果不能为 2, 因为 [-2,-1] 不是子数组。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/maximum-product-subarray\n著作权归领扣网络所���。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\n\n\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n \"\"\"\n 求数组中子区间的最大乘积,\n 因为负数乘以负数,会变成正数,所以解这题的时候我们需要维护两个变量,当前的最大值,以及最小值,\n 最小值可能为负数,但没准下一步乘以一个负数,当前的最大值就变成最小值,而最小值则变成最大值了\n\n 对于同样的动归方程,需要求其最大值和最小值\n :param nums:\n :return:\n \"\"\"\n max_res = [nums[0]] * (len(nums))\n min_res = [nums[0]] * (len(nums))\n\n for i in range(1, len(nums)):\n max_res[i] = max(\n max_res[i - 1] * nums[i], min_res[i - 1] * nums[i], nums[i]\n )\n min_res[i] = min(\n max_res[i - 1] * nums[i], min_res[i - 1] * nums[i], nums[i]\n )\n\n return max(max_res)\n \"\"\"\n 思考:\n 1. 是否可以使用双指针来做:可能因为负数的原因,双指针无法记录负数\n \"\"\"\n\nnums = [2, 3, -2, 4]\ndemo = Solution()\nprint(demo.maxProduct(nums))\n","repo_name":"hsbzzhz/leetcode","sub_path":"DP/152. 乘积最大子数组.py","file_name":"152. 乘积最大子数组.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"24588436006","text":"\"\"\"add last columns to posts\n\nRevision ID: fa88d08874ea\nRevises: 72e3594966dd\nCreate Date: 2023-08-01 15:04:24.355677\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = \"fa88d08874ea\"\ndown_revision = \"72e3594966dd\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n op.add_column(\n \"posts\",\n sa.Column(\"published\", sa.Boolean(), nullable=False, server_default=\"True\"),\n )\n op.add_column(\n \"posts\",\n sa.Column(\n \"created_at\",\n sa.TIMESTAMP(timezone=True),\n nullable=False,\n server_default=sa.text(\"NOW()\"),\n ),\n )\n\n\ndef downgrade() -> None:\n op.drop_column(\"posts\", column_name=\"published\")\n op.drop_column(\"posts\", column_name=\"created_at\")\n","repo_name":"ramziourari/fast-api-tutorial","sub_path":"alembic/versions/fa88d08874ea_add_last_columns_to_posts.py","file_name":"fa88d08874ea_add_last_columns_to_posts.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"3471529812","text":"from flask import Flask, render_template, request, session, redirect, url_for, send_file\r\nimport os\r\nimport uuid\r\nimport hashlib\r\nimport pymysql.cursors\r\nfrom functools import wraps\r\nimport time\r\n\r\n#Finstagram base made using provided sample code from dannnylin\r\n\r\napp = Flask(__name__)\r\napp.secret_key = \"super secret key\"\r\nIMAGES_DIR = os.path.join(os.getcwd(), \"images\")\r\n\r\nconnection = pymysql.connect(host=\"localhost\",\r\n user=\"root\",\r\n password=\"\",\r\n db=\"finstagram\",\r\n charset=\"utf8mb4\",\r\n port=3306,\r\n cursorclass=pymysql.cursors.DictCursor,\r\n autocommit=True)\r\n\r\nSALT = 'cs3083'\r\n\r\ndef login_required(f):\r\n @wraps(f)\r\n def dec(*args, **kwargs):\r\n if not \"username\" in session:\r\n return redirect(url_for(\"login\"))\r\n return f(*args, **kwargs)\r\n return dec\r\n\r\n@app.route(\"/\")\r\ndef index():\r\n if \"username\" in session:\r\n return redirect(url_for(\"home\"))\r\n return render_template(\"index.html\")\r\n\r\n@app.route(\"/home\")\r\n@login_required\r\ndef home():\r\n return render_template(\"home.html\", username=session[\"username\"])\r\n\r\n@app.route(\"/upload\", methods=[\"GET\"])\r\n@login_required\r\ndef upload():\r\n return render_template(\"upload.html\")\r\n\r\n#These methods show all the pictures of a user not shared to all followers and allows them to\r\n#pick an available group to share it too\r\n@app.route(\"/images\", methods=[\"GET\"])\r\n@login_required\r\ndef images():\r\n query = \"SELECT * FROM photo WHERE photoPoster=%s AND allFollowers=%s\"\r\n groupQuery = \"SELECT DISTINCT groupName, owner_username FROM BelongTo WHERE member_username=%s\"\r\n currentUser=session[\"username\"]\r\n try:\r\n with connection.cursor() as cursor:\r\n cursor.execute(query, (currentUser, False))\r\n data = cursor.fetchall()\r\n if (not data):\r\n error = \"You don't currently have any photos that aren't shared with all followers\"\r\n return render_template('home.html', error=error)\r\n with connection.cursor() as cursor:\r\n cursor.execute(groupQuery, (currentUser))\r\n groupData=cursor.fetchall()\r\n if (not groupData):\r\n error = \"You are not currently part of any groups\"\r\n return render_template('home.html', error=error)\r\n return render_template(\"images.html\", images=data, groups=groupData)\r\n except pymysql.err.IntegrityError:\r\n error = \"An error has occured, please try again later\"\r\n return render_template(\"home.html\", error=error)\r\n\r\n@app.route(\"/sharePhoto\", methods=[\"POST\"])\r\n@login_required\r\ndef sharePhoto():\r\n if request.form:\r\n requestData = request.form\r\n requestData = request.form\r\n groupOwner = (requestData[\"groupName\"].split(\",\"))[1]\r\n groupName = (requestData[\"groupName\"].split(\",\"))[0]\r\n photoID = requestData[\"photoID\"]\r\n\r\n try:\r\n with connection.cursor() as cursor:\r\n query = \"INSERT INTO SharedWith (groupOwner, groupName, photoID) VALUES (%s, %s, %s)\"\r\n cursor.execute(query, (groupOwner, groupName, photoID))\r\n except pymysql.err.IntegrityError:\r\n error = \"This photo was already shared with %s\" % (groupName)\r\n return render_template('home.html', error=error)\r\n\r\n error = \"Photo has been successfully shared with %s\" % (groupName)\r\n return render_template('home.html', error=error)\r\n\r\n error = \"An error has occurred. Please try again.\"\r\n return render_template(\"home.html\", error=error)\r\n\r\n@app.route(\"/image/\", methods=[\"GET\"])\r\ndef image(image_name):\r\n image_location = os.path.join(IMAGES_DIR, image_name)\r\n if os.path.isfile(image_location):\r\n return send_file(image_location, mimetype=\"image/jpg\")\r\n\r\n@app.route(\"/login\", methods=[\"GET\"])\r\ndef login():\r\n return render_template(\"login.html\")\r\n\r\n@app.route(\"/register\", methods=[\"GET\"])\r\ndef register():\r\n return render_template(\"register.html\")\r\n\r\n@app.route(\"/loginAuth\", methods=[\"POST\"])\r\ndef loginAuth():\r\n if request.form:\r\n requestData = request.form\r\n username = requestData[\"username\"]\r\n plaintextPasword = requestData[\"password\"] + SALT\r\n hashedPassword = hashlib.sha256(plaintextPasword.encode(\"utf-8\")).hexdigest()\r\n\r\n with connection.cursor() as cursor:\r\n query = \"SELECT * FROM person WHERE username = %s AND password = %s\"\r\n cursor.execute(query, (username, hashedPassword))\r\n data = cursor.fetchone()\r\n if data:\r\n session[\"username\"] = username\r\n return redirect(url_for(\"home\"))\r\n\r\n error = \"Incorrect username or password.\"\r\n return render_template(\"login.html\", error=error)\r\n\r\n error = \"An unknown error has occurred. Please try again.\"\r\n return render_template(\"login.html\", error=error)\r\n\r\n\r\n@app.route(\"/registerAuth\", methods=[\"POST\"])\r\ndef registerAuth():\r\n if request.form:\r\n requestData = request.form\r\n username = requestData[\"username\"]\r\n plaintextPasword = requestData[\"password\"] + SALT\r\n hashedPassword = hashlib.sha256(plaintextPasword.encode(\"utf-8\")).hexdigest()\r\n firstName = requestData[\"fname\"]\r\n lastName = requestData[\"lname\"]\r\n bio = requestData[\"bio\"]\r\n\r\n try:\r\n with connection.cursor() as cursor:\r\n query = \"INSERT INTO person (username, password, firstName, lastName, bio) VALUES (%s, %s, %s, %s, %s)\"\r\n cursor.execute(query, (username, hashedPassword, firstName, lastName, bio))\r\n except pymysql.err.IntegrityError:\r\n error = \"%s is already taken.\" % (username)\r\n return render_template('register.html', error=error)\r\n\r\n return redirect(url_for(\"login\"))\r\n\r\n error = \"An error has occurred. Please try again.\"\r\n return render_template(\"register.html\", error=error)\r\n\r\n#These are my methods for makiing a Friendgroup\r\n\r\n#This method creates the html forms entering a groupname and description\r\n@app.route(\"/createGroup\", methods=[\"GET\"])\r\ndef createGroup():\r\n return render_template(\"createGroup.html\")\r\n\r\n#This method handles processing the data sent by these forms and creates a group\r\n@app.route(\"/makeGroup\", methods=[\"POST\"])\r\n@login_required\r\ndef makeGroup():\r\n if request.form:\r\n requestData = request.form\r\n groupOwner = session[\"username\"]\r\n groupName = requestData[\"groupName\"]\r\n description = requestData[\"description\"]\r\n\r\n try:\r\n with connection.cursor() as cursor:\r\n query = \"INSERT INTO Friendgroup (groupOwner, groupName, description) VALUES (%s, %s, %s)\"\r\n cursor.execute(query, (groupOwner, groupName, description))\r\n query2 = \"INSERT INTO BelongTo (member_username, owner_username, groupName) VALUES (%s, %s, %s)\"\r\n cursor.execute(query2, (groupOwner, groupOwner, groupName))\r\n except pymysql.err.IntegrityError:\r\n error = \"%s is already taken.\" % (groupName)\r\n return render_template('createGroup.html', error=error)\r\n\r\n error = \"Group %s has been successfully made.\" % (groupName)\r\n return render_template('createGroup.html', error=error)\r\n\r\n error = \"An error has occurred. Please try again.\"\r\n return render_template(\"createGroup.html\", error=error)\r\n\r\n#my methods to add someone to a Friendgroup\r\n\r\n#This method shows all the groups the current user owns and\r\n#creates the html forms for adding another user to this group\r\n#redirects user back to home if user isnt part of any groups\r\n@app.route(\"/addFriend\", methods=[\"GET\"])\r\n@login_required\r\ndef addFriend():\r\n query = \"SELECT DISTINCT groupName, owner_username FROM BelongTo WHERE member_username=%s\"\r\n currentUser = session[\"username\"]\r\n with connection.cursor() as cursor:\r\n cursor.execute(query, (currentUser))\r\n data = cursor.fetchall()\r\n if (not data):\r\n error = \"You need to be part of a group first\"\r\n return render_template(\"home.html\", error=error)\r\n return render_template(\"addFriend.html\", groups=data)\r\n\r\n#This method handles the form processing for adding someone to a Friendgroup\r\n@app.route(\"/addMember\", methods=[\"POST\"])\r\n@login_required\r\ndef addMember():\r\n if request.form:\r\n requestData = request.form\r\n owner_username = (requestData[\"groupName\"].split(\",\"))[1]\r\n groupName = (requestData[\"groupName\"].split(\",\"))[0]\r\n member_username = requestData[\"member_username\"]\r\n\r\n #originally had checking code here but that was made redundant after changing database engine to InnoDB, no foreign key issues now\r\n try:\r\n with connection.cursor() as cursor:\r\n\r\n query = \"INSERT INTO BelongTo (member_username, owner_username, groupName) VALUES (%s, %s, %s)\"\r\n cursor.execute(query, (member_username, owner_username, groupName))\r\n\r\n except pymysql.err.IntegrityError:\r\n error = \"%s is already in the group %s made by %s or does not exist.\" % (member_username, groupName, owner_username)\r\n return render_template(\"addFriend.html\", error=error)\r\n\r\n error = \"%s has been added to group %s made by %s\" % (member_username, groupName, owner_username)\r\n return render_template(\"home.html\", error=error)\r\n\r\n error = \"An error has occurred. Please try again.\"\r\n return render_template(\"addFriend.html\", error=error)\r\n\r\n#These are my methods for sending someone a follow request and for the and for the followed user to manage that request\r\n\r\n#This creates the html forms\r\n@app.route(\"/follow\", methods=[\"GET\"])\r\ndef follow():\r\n return render_template(\"follow.html\")\r\n\r\n#This method proccesses the form and validates any query for sending a follow request\r\n@app.route(\"/sendFollow\", methods=[\"POST\"])\r\n@login_required\r\ndef sendFollow():\r\n if request.form:\r\n requestData = request.form\r\n username_followed = requestData[\"username_followed\"]\r\n username_follower = session[\"username\"]\r\n followstatus = False\r\n\r\n try:\r\n with connection.cursor() as cursor:\r\n query = \"SELECT * FROM Follow WHERE username_followed=%s AND username_follower=%s\"\r\n cursor.execute(query, (username_follower, username_followed))\r\n exist = cursor.fetchall()\r\n if exist:\r\n error = \"There is already an existing follow request from %s or you are already following each other.\" % (username_followed)\r\n return render_template(\"follow.html\", error=error)\r\n query = \"INSERT INTO Follow (username_followed, username_follower, followstatus) VALUES (%s, %s, %s)\"\r\n cursor.execute(query, (username_followed, username_follower, followstatus))\r\n\r\n except pymysql.err.IntegrityError:\r\n error = \"%s does not exist or follow request already sent.\" % (username_followed)\r\n return render_template(\"follow.html\", error=error)\r\n\r\n return redirect(url_for(\"home\"))\r\n\r\n#Abstracted pages for accepting and rejecting follows (easier to code)\r\n#accept and reject display current follow requests and renders forms to choose requests\r\n@app.route(\"/accept\", methods=[\"GET\"])\r\n@login_required\r\ndef accept():\r\n query = \"SELECT * FROM Follow WHERE username_followed=%s AND followstatus=False\"\r\n currentUser = session[\"username\"]\r\n with connection.cursor() as cursor:\r\n cursor.execute(query, (currentUser))\r\n data = cursor.fetchall()\r\n if (not data):\r\n error = \"You need to recieve a follow request first\"\r\n return render_template(\"home.html\", error=error)\r\n return render_template(\"accept.html\", requests=data)\r\n\r\n@app.route(\"/reject\", methods=[\"GET\"])\r\n@login_required\r\ndef reject():\r\n query = \"SELECT * FROM Follow WHERE username_followed=%s AND followstatus=False\"\r\n currentUser = session[\"username\"]\r\n with connection.cursor() as cursor:\r\n cursor.execute(query, (currentUser))\r\n data = cursor.fetchall()\r\n if (not data):\r\n error = \"You need to recieve a follow request first\"\r\n return render_template(\"home.html\", error=error)\r\n return render_template(\"reject.html\", requests=data)\r\n\r\n#The accept/rejectFollow methods processes the forms and updates the tables\r\n@app.route(\"/acceptFollow\", methods=[\"POST\"])\r\n@login_required\r\ndef acceptFollow():\r\n if request.form:\r\n requestData = request.form\r\n username_follower = requestData[\"username_follower\"]\r\n username_followed = session[\"username\"]\r\n followstatus = True\r\n\r\n try:\r\n with connection.cursor() as cursor:\r\n query = \"UPDATE Follow SET followstatus=%s WHERE username_followed=%s AND username_follower=%s\"\r\n cursor.execute(query, (followstatus, username_followed, username_follower))\r\n\r\n except pymysql.err.IntegrityError:\r\n error = \"An error has occurred. Please try again.\"\r\n return render_template(\"home.html\", error=error)\r\n\r\n error = \"Follow request from %s was accepted\" % (username_follower)\r\n return render_template(\"home.html\", error=error)\r\n\r\n error = \"An error has occurred. Please try again.\"\r\n return render_template(\"home.html\", error=error)\r\n\r\n@app.route(\"/rejectFollow\", methods=[\"POST\"])\r\n@login_required\r\ndef rejectFollow():\r\n if request.form:\r\n requestData = request.form\r\n username_follower = requestData[\"username_follower\"]\r\n username_followed = session[\"username\"]\r\n\r\n try:\r\n with connection.cursor() as cursor:\r\n query = \"DELETE FROM Follow WHERE username_follower=%s AND username_followed=%s\"\r\n cursor.execute(query, (username_follower, username_followed))\r\n\r\n except pymysql.err.IntegrityError:\r\n error = \"An error has occurred. Please try again.\"\r\n return render_template(\"home.html\", error=error)\r\n\r\n error = \"Follow request from %s was rejected\" % (username_follower)\r\n return render_template(\"home.html\", error=error)\r\n\r\n error = \"An error has occurred. Please try again.\"\r\n return render_template(\"home.html\", error=error)\r\n\r\n#function to see other people's photos and additional info like id, time, likes, etc.\r\n@app.route(\"/gallery\", methods=[\"GET\"])\r\n@login_required\r\ndef gallery():\r\n #3 queries to get the visible photos, tags, and Likes\r\n #select everything from likes and tags and use the jinja template in gallery.html to display the right values\r\n photoQuery = \"SELECT DISTINCT photoID, postingdate, caption, photoPoster, filepath, firstName, lastName FROM photo INNER JOIN person ON person.username = photo.photoPoster WHERE photoPoster IN (SELECT username_followed FROM follow WHERE followstatus = 1 AND username_follower=%s) OR photoID IN ( SELECT photoID FROM sharedwith NATURAL JOIN belongto WHERE member_username=%s) ORDER BY postingdate DESC\"\r\n tagQuery = \"SELECT * FROM tagged NATURAL JOIN person WHERE tagstatus=True\"\r\n likeQuery = \"SELECT * FROM likes NATURAL JOIN person\"\r\n currentUser=session[\"username\"]\r\n\r\n with connection.cursor() as cursor:\r\n cursor.execute(photoQuery, (currentUser, currentUser))\r\n photos=cursor.fetchall()\r\n\r\n cursor.execute(tagQuery)\r\n tags=cursor.fetchall()\r\n\r\n cursor.execute(likeQuery)\r\n likes=cursor.fetchall()\r\n\r\n return render_template(\"gallery.html\", photos=photos, likes=likes, tags=tags)\r\n\r\n\r\n\r\n\r\n\r\n\r\n@app.route(\"/logout\", methods=[\"GET\"])\r\ndef logout():\r\n session.pop(\"username\")\r\n return redirect(\"/\")\r\n\r\n#redesigned upload image so that if you dont pick allfollowers, there is another\r\n#function that lets you choose which group gets to see the chosen photo\r\n@app.route(\"/uploadImage\", methods=[\"POST\"])\r\n@login_required\r\ndef upload_image():\r\n if request.files:\r\n requestData = request.form\r\n image_file = request.files.get(\"imageToUpload\", \"\")\r\n image_name = image_file.filename\r\n filepath = os.path.join(IMAGES_DIR, image_name)\r\n image_file.save(filepath)\r\n caption=requestData[\"caption\"]\r\n photoPoster=session[\"username\"]\r\n if (requestData[\"status\"] == \"True\"):\r\n allFollowers=True\r\n else:\r\n allFollowers=False\r\n photoQuery = \"INSERT INTO photo (postingdate, filePath, allFollowers, caption, photoPoster) VALUES (%s, %s, %s, %s, %s)\"\r\n with connection.cursor() as cursor:\r\n cursor.execute(photoQuery, (time.strftime('%Y-%m-%d %H:%M:%S'), image_name, allFollowers, caption, photoPoster))\r\n if (allFollowers):\r\n searchQuery = \"SELECT DISTINCT groupName, owner_username FROM BelongTo WHERE member_username=%s\"\r\n cursor.execute(searchQuery, (photoPoster))\r\n groups=cursor.fetchall()\r\n idQuery = \"SELECT MAX(photoID) as id FROM photo\"\r\n cursor.execute(idQuery)\r\n photoID = cursor.fetchone()[\"id\"]\r\n sharedQuery = \"INSERT INTO SharedWith (groupOwner, groupName, photoID) VALUES (%s, %s, %s)\"\r\n for group in groups:\r\n groupName=group[\"groupName\"]\r\n groupOwner=group[\"owner_username\"]\r\n cursor.execute(sharedQuery, (groupOwner, groupName, photoID))\r\n\r\n message = \"Image has been successfully uploaded.\"\r\n return render_template(\"upload.html\", message=message)\r\n else:\r\n message = \"Failed to upload image.\"\r\n return render_template(\"upload.html\", message=message)\r\n\r\nif __name__ == \"__main__\":\r\n if not os.path.isdir(\"images\"):\r\n os.mkdir(IMAGES_DIR)\r\n app.run(debug=True)\r\n","repo_name":"TasNehal/Finstagram","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":17904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"11427008513","text":"from django.test import TestCase\nfrom lxml import etree\n\nfrom ESSArch_Core.configuration.models import EventType\nfrom ESSArch_Core.ip.models import EventIP, InformationPackage\n\n\nclass EventIPManagerTestCase(TestCase):\n def setUp(self):\n self.id_val = '01994642-17c6-474e-923f-1b58fb137f30'\n self.event_type = EventType.objects.create(\n eventType=10, eventDetail='Testing type',\n category=EventType.CATEGORY_INFORMATION_PACKAGE,\n )\n self.time = '2017-06-05 15:54:33.521858+00:00'\n self.user = 'essuser'\n self.objid = 'foo'\n\n self.root = etree.fromstring('''\n \n \n \n ESS\n {id_val}\n \n {event_type}\n {time}\n \n Parsing detail\n \n \n 0\n \n Updated status\n \n \n \n ESS\n {user}\n \n \n ESS\n {objid}\n \n \n \n '''.format(id_val=self.id_val, event_type=self.event_type.eventType,\n time=self.time, user=self.user, objid=self.objid,))\n\n self.el = self.root.xpath(\"./*[local-name()='event']\")[0]\n\n def test_parse(self):\n event = EventIP.objects.from_premis_element(self.el)\n\n self.assertEqual(event.eventIdentifierValue, self.id_val)\n self.assertEqual(event.eventType.eventType, self.event_type.eventType)\n self.assertEqual(event.eventDateTime, self.time)\n self.assertEqual(event.eventOutcome, \"0\")\n self.assertEqual(event.eventOutcomeDetailNote, \"Updated status\")\n self.assertEqual(event.linkingAgentIdentifierValue, self.user)\n self.assertEqual(event.linkingObjectIdentifierValue, self.objid)\n\n def test_parse_existing_ip(self):\n ip = InformationPackage.objects.create(object_identifier_value=self.objid)\n event = EventIP.objects.from_premis_element(self.el)\n\n self.assertEqual(event.linkingObjectIdentifierValue, str(ip.pk))\n","repo_name":"ESSolutions/ESSArch","sub_path":"ESSArch_Core/ip/tests/test_events.py","file_name":"test_events.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"57"} +{"seq_id":"26019927639","text":"'''\ndecode_request\n'''\n# 代理服务器产生的请求文件地址\nTIDY_REQ_DATA_KEY = 'tidy_req_data'\n#指定的手机型号没有req data\nNO_REQ_DATA = '该手机尚未发起任务请求'\n\n'''\ndecode_response\n'''\n\n'''\njudge_response\n'''\n# 请求超时代理IP 和 物理网络均有可能\nTIME_OUT_ERROR = 'Read timed out'\n# getappmsgext请求频繁 需要等待5分钟\nGETAPPMSGEXT_FREQ_ERROR = {\"base_resp\":{\"ret\":301,\"errmsg\":\"default\"}}\n# getappmsgext请求参数不对 需要重新点击 直到成功 其中就包括了appmsg_token参数过期的问题\nGETAPPMSGEXT_PARAM_ERROR = {'advertisement_info': [], 'reward_head_imgs': []}\n# 加载历史消息请求参数过期 生命周几可能只有10分钟\nGET_LOAD_ALL_OUT_OF_DATE = \"失效的验证页面\"\n# 加载跟多历史消息错误\nGET_LOAD_MORE_ERROR = {'base_resp': {'ret': -3, 'errmsg': 'no session', 'cookie_count': 1}, 'ret': -3, 'errmsg': 'no session', 'cookie_count': 1}\n# 获取历史消息达到每日限制 每日限制大约在1000到2000之间,可能需要限制24小时,请更换main微信并重启\nGET_LOAD_MORE_FREQ_ERROR = {'ret': -6, 'errmsg': 'unknown error'}\n\n\n'''\nact_request\n'''\nTIME_OUT = 10 #requests请求超时时间\nREQUEST_DONE = \"请求完成\" # 请求完成\nREQUEST_ERROR = \"请求时出现错误\" # 请求出现错误\nREQUEST_SELF_ERROR = \"执行请求本身发生错误 一般发生在网络不同请求超时或者代理IP无效\"\nDEFAULT_PROXY = '127.0.0.1:1080'\n'''\nprocess_response\n'''\n# 获取文章阅读信息的间隔时间\nCRAWLER_DELAY = 2.0\nCRAWLER_FINISHED = \"所有文章爬取完毕\"\n\n\nTEST_MODE = False\n","repo_name":"wonderfulsuccess/inwork","sub_path":"crawler/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"71656216178","text":"# -*- coding: utf-8 -\n\nimport os\nimport sys\n\nfrom setuptools import setup, find_packages\nfrom setuptools.command.test import test as TestCommand\n\n# read dev requirements\nfname = os.path.join(os.path.dirname(__file__), 'requirements.txt')\nwith open(fname) as f:\n tests_require = [l.strip() for l in f.readlines()]\n\nif sys.version_info[:2] < (2, 7):\n tests_require.append('unittest2')\n\n\nclass PyTestCommand(TestCommand):\n user_options = [\n (\"cov\", None, \"measure coverage\")\n ]\n\n def initialize_options(self):\n TestCommand.initialize_options(self)\n self.cov = None\n\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = ['tests']\n if self.cov:\n self.test_args += ['--cov']\n self.test_suite = True\n\n def run_tests(self):\n import pytest\n errno = pytest.main(self.test_args)\n sys.exit(errno)\n\nsetup(\n name='rabbit2ev',\n description='Bind RabbitMq messages with custom plugin',\n author='Ezequiel Lovelle',\n author_email='ezequiellovelle@gmail.com',\n license='MIT',\n zip_safe=False,\n packages=find_packages(exclude=['tests']),\n include_package_data=True,\n tests_require=tests_require,\n cmdclass={'test': PyTestCommand},\n)\n","repo_name":"lovelle/rabbit2ev","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"57"} +{"seq_id":"74243768819","text":"import discord\nfrom discord.ext import tasks\nfrom .messenger import Channel\nimport base65536\nimport asyncio\nimport threading\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\nclass MyClient(discord.Client):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.recv_packets = asyncio.Queue()\n\n async def on_connect(self):\n print('Connected')\n\n async def on_ready(self):\n print('Discord client ready')\n self.channel_obj = await self.fetch_channel(self.parent.channel)\n\n async def on_message(self, message):\n print(message)\n if message.channel.id == self.channel_obj.id:\n try:\n data = base65536.decode(message.content)\n print('Received data over Discord', data)\n except:\n print('Received garbage', repr(message.content))\n return\n await self.recv_packets.put(data)\n\n async def recv(self) -> bytes:\n return await self.recv_packets.get()\n\n async def send_data(self, data: bytes): \n print('Sending over Discord', data)\n data = base65536.encode(data)\n await self.channel_obj.send(data)\n\n\nclass DiscordChannel(Channel):\n \"\"\"\n Class that sends messages to a Discord text channel.\n It encodes binary data in Base65536.\n \"\"\"\n\n @staticmethod\n def MAX_MTU() -> int:\n \"\"\"\n Base65536 encodes every two bytes as a single character,\n and Discord allows 2000 characters by default,\n so the MTU is 4000 bytes.\n \"\"\"\n return 4000\n\n\n def __init__(self, token: str, channel: int):\n \"\"\"\n token is the Discord bot token.\n\n channel is the ID of a text channel that the bot has access to.\n \"\"\"\n\n print('Start init DiscordChannel')\n\n self.token = token\n self.channel = channel\n self.queued_packets = []\n self.queued_packets_lock = threading.Lock()\n\n intents = discord.Intents.none()\n intents.messages = True\n self.client = MyClient(intents=intents)\n self.client.parent = self\n\n asyncio.create_task(self.client.start(self.token))\n\n\n async def send(self, data: bytes):\n await self.client.send_data(data)\n\n async def recv(self) -> bytes:\n return await self.client.recv()\n\n","repo_name":"danya02/ip-over-messenger","sub_path":"src/discord_messenger.py","file_name":"discord_messenger.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"8489434232","text":"import logging\nfrom .statistics_service_pb2 import RecordPlaybackStartedResponse, GetNumberOfPlaysResponse, PlayStats\nfrom . import statistics_service_pb2_grpc\nfrom common.common_types_conversions import UUID_to_grpc, grpc_to_UUID\n\n\ndef VideoPlaybackStatsModel_to_PlayStats(stats):\n return PlayStats(video_id=UUID_to_grpc(stats.video_id), views=stats.views)\n\ndef VideoPlaybackStatsModelList_to_GetNumberOfPlaysResponse(stats):\n response = GetNumberOfPlaysResponse()\n if isinstance(stats, (list,)): # most preferred way to check if it's list\n response.stats.extend(map(VideoPlaybackStatsModel_to_PlayStats, stats))\n elif stats is not None: # single result\n response.stats.extend([VideoPlaybackStatsModel_to_PlayStats(stats)])\n return response\n\nclass StatisticsServiceServicer(statistics_service_pb2_grpc.StatisticsServiceServicer):\n \"\"\"Provides methods that implement functionality of the Statistics Service.\"\"\"\n\n def __init__(self, grpc_server, statistics_service):\n logging.debug(\"StatisticsServiceServicer started\")\n self.statistics_service = statistics_service\n statistics_service_pb2_grpc.add_StatisticsServiceServicer_to_server(self, grpc_server)\n\n def RecordPlaybackStarted(self, request, context):\n \"\"\"Record that playback started for a given video\n \"\"\"\n logging.debug(\">>> StatisticsService:RecordPlaybackStarted: \")\n logging.debug(request)\n self.statistics_service.record_playback_started(grpc_to_UUID(request.video_id))\n return RecordPlaybackStartedResponse()\n\n\n def GetNumberOfPlays(self, request, context):\n \"\"\"Get the number of plays for a given video or set of videos\n \"\"\"\n logging.debug(\">>> StatisticsService:GetNumberOfPlays: \")\n logging.debug(request)\n result = self.statistics_service.get_number_of_plays(list(map(grpc_to_UUID, request.video_ids)))\n return VideoPlaybackStatsModelList_to_GetNumberOfPlaysResponse(result)\n\n\n\n","repo_name":"KillrVideo/killrvideo-python","sub_path":"killrvideo/statistics/statistics_service_grpc.py","file_name":"statistics_service_grpc.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"57"} +{"seq_id":"30527418068","text":"import os\nimport random\nimport time\n \n \ndef main():\n os.system('cls')\n game_mode = menu()\n os.system('cls')\n player = random.randint(1, 2)\n tic = 'X'\n game_board = get_empty_board()\n if game_mode == 1:\n pl_vs_pl(game_board, player, tic)\n elif game_mode == 2:\n rAI_vs_rAI(game_board, player, tic)\n elif game_mode == 3:\n game_board = get_empty_board()\n pl_vs_rAI(game_board, player, tic)\n elif game_mode == 4:\n pl_vs_uAI(game_board, player, tic)\n get_winning_player(game_board)\n \n \n# game menu\ndef menu():\n title()\n print(\"1. Human vs Human\")\n print(\"\")\n print(\"2. Random AI vs Random AI\")\n print(\"\")\n print(\"3. Human vs Random AI\")\n print(\"\")\n print(\"4. Human vs Unbeatable AI\")\n print(\"\")\n print(\"Quit?\")\n print(\"\")\n choice = player_input(\"Choose your gamemode: \")\n if choice.isdigit() and int(choice) >= 1 and int(choice) <= 4:\n return int(choice)\n else:\n os.system('cls')\n print(\"Invalid gamemode choice!\")\n menu()\n \n \n# different game modes:\n\n# player vs player\ndef pl_vs_pl(board, player, tic):\n while get_winning_player(board) == None:\n title()\n if is_board_full(board):\n print(\"It's a tie!\")\n break\n else:\n display_board(board)\n if player == 1:\n tic = 'X'\n print('Gracz 1')\n elif player == 2:\n tic = \"O\"\n print(\"Gracz 2\")\n move = ()\n move = get_human_coordinate(board)\n make_a_move(move, board, tic)\n player += 1\n if player == 3:\n player = 1\n os.system('cls')\n \n \n# random Ai vs random Ai\ndef rAI_vs_rAI(board, player, tic):\n while get_winning_player(board) == None:\n title()\n if is_board_full(board):\n print(\"It's a tie!\")\n break\n else:\n display_board(board)\n if player == 1:\n tic = \"X\"\n print(\"CPU 1 making a move...\")\n move = ()\n move = get_random_ai_coordinate(board)\n time.sleep(2)\n make_a_move(move, board, tic)\n elif player == 2:\n tic = \"O\"\n print(\"CPU 2 making a move...\")\n move = ()\n move = get_random_ai_coordinate(board)\n time.sleep(2)\n make_a_move(move, board, tic)\n player += 1\n if player == 3:\n player = 1\n os.system('cls')\n \n \n# player vs random Ai\ndef pl_vs_rAI(board, player, tic):\n player = random.randint(1, 2)\n while get_winning_player(board) == None:\n title()\n if is_board_full(board):\n print(\"It's a tie!\")\n break\n else:\n display_board(board)\n # human_cpu = random.randint(1,2)\n if player == 1:\n tic = \"X\"\n print(\"Gracz 1\")\n move = ()\n move = get_human_coordinate(board)\n make_a_move(move, board, tic)\n elif player == 2:\n tic = \"O\"\n print(\"CPU\")\n move = ()\n move = get_random_ai_coordinate(board)\n time.sleep(2)\n make_a_move(move, board, tic)\n \n player += 1\n if player == 3:\n player = 1\n os.system('cls')\n \n \n# player vs unbeatable Ai\ndef pl_vs_uAI(board, player, tic):\n while get_winning_player(board) == None:\n title()\n if is_board_full(board):\n print(\"It's a tie!\")\n break\n else:\n display_board(board)\n if player == 1:\n tic = \"X\"\n print(\"Gracz 1\")\n move = ()\n move = get_human_coordinate(board)\n make_a_move(move, board, tic)\n elif player == 2:\n tic = \"O\"\n print(\"CPU\")\n move = ()\n move = get_unbeatable_ai_coordinates(board, tic)\n make_a_move(move, board, tic)\n player += 1\n if player == 3:\n player = 1\n os.system('cls')\n \n \n# player input and quit\ndef player_input(prefix):\n a = input(prefix)\n if str(a).upper() == 'QUIT':\n print(\"Dziękujemy za grę.\")\n print('')\n exit()\n else:\n return a\n \n \n# ask where to put X/O\ndef get_human_coordinate(board):\n input_coordinates = player_input(\n \"Chose row and column (A1, B2...): \").upper()\n coordinates = list(input_coordinates)\n rows = {'A': 0, 'B': 1, 'C': 2}\n column = {'1': 0, '2': 1, '3': 2}\n try:\n row = int(rows[coordinates[0]])\n col = int(column[coordinates[1]])\n except (IndexError, KeyError):\n print(\"Invalid move\")\n return get_human_coordinate(board)\n if board[row][col] == '.':\n player_move = (row, col)\n return player_move\n else:\n print(\"Invalid move\")\n return get_human_coordinate(board)\n \n \ndef make_a_move(player_move, board, x_o):\n (row, col) = player_move\n if board[row][col] == \".\":\n board[row][col] = x_o\n else:\n print(\"Invalid move\")\n \n \n# prepares an empty game board\ndef get_empty_board():\n empty_board = [['.', '.', '.',], ['.', '.', '.',], ['.', '.', '.',]]\n return empty_board\n \n \n# checks if anyone won\ndef get_winning_player(board):\n row = []\n column = []\n diagonal = []\n rl_diagonal = []\n if check_horizontal(board, row) != None:\n os.system('cls')\n title()\n return check_horizontal(board, row)\n elif check_vertical(board, column) != None:\n os.system('cls')\n title()\n return check_vertical(board, row)\n elif check_diagonal(board, diagonal, rl_diagonal) != None:\n os.system('cls')\n title()\n return check_diagonal(board, diagonal, rl_diagonal)\n else:\n return None\n \n \n# wining conditions\ndef check_horizontal(board, row):\n for i in range(3):\n row = board[i]\n if all(item == 'X' for item in row):\n display_board(board)\n print('X has won!')\n return 'X has won!'\n elif all(item == 'O' for item in row):\n display_board(board)\n print('O has won')\n return 'O has won'\n \n \ndef check_vertical(board, column):\n for i in range(3):\n column = []\n for j in range(3):\n column.append(board[j][i])\n if all(item == 'X' for item in column):\n display_board(board)\n print('X has won')\n return 'X has won'\n elif all(item == 'O' for item in column):\n display_board(board)\n print('O has won')\n return '0 has won'\n \n \ndef check_diagonal(board, diagonal, rl_diagonal):\n for i, j in zip(range(3), reversed(range(3))):\n diagonal.append(board[i][i])\n rl_diagonal.append(board[i][j])\n if all(item == 'X' for item in diagonal):\n display_board(board)\n print('X has won')\n return 'X has won'\n elif all(item == 'O' for item in diagonal):\n print('O has won')\n return '0 has won'\n if all(item == 'X' for item in rl_diagonal):\n display_board(board)\n print('X has won')\n return 'X has won'\n elif all(item == 'O' for item in rl_diagonal):\n print('O has won')\n return 'O has won'\n \n \n# checks for tie\ndef is_board_full(board):\n for i in range(3):\n if '.' in board[i]:\n return False\n return True\n \n# AI\n# Random Ai\ndef get_random_ai_coordinate(board):\n row = random.randint(0, 2)\n col = random.randint(0, 2)\n if board[row][col] == '.':\n cpu_move = (row, col)\n return cpu_move\n else:\n return get_random_ai_coordinate(board)\n \n# unbeatable Ai\ndef get_unbeatable_ai_coordinates(board, x_o):\n temp_board = board\n for i in range(3):\n for j in range(3):\n if temp_board[i][j] == '.':\n uAI_coordinates = (i, j)\n temp_board[i][j] = 'X'\n if get_winning_player(temp_board) != None:\n temp_board[i][j] = 'O'\n return uAI_coordinates\n else:\n temp_board[i][j] = '.'\n if board[1][1] == \".\":\n uAI_coordinates = (1, 1)\n return uAI_coordinates\n for i in range(3):\n for j in range(3):\n if temp_board[i][j] == '.':\n uAI_coordinates = (i, j)\n temp_board[i][j] = x_o\n if get_winning_player(temp_board) != None:\n return uAI_coordinates\n else:\n temp_board[i][j] = '.'\n if board[0][0] == \".\":\n uAI_coordinates = (0, 0)\n return uAI_coordinates\n elif board[0][2] == \".\":\n uAI_coordinates = (0, 2)\n return uAI_coordinates\n elif board[2][0] == \".\":\n uAI_coordinates = (2, 0)\n return uAI_coordinates\n elif board[2][2] == \".\":\n uAI_coordinates = (2, 2)\n return uAI_coordinates\n \n else:\n return get_random_ai_coordinate(board)\n \n# graphics\ndef title():\n print('\\n' +\n ' ________________ _________ ______ __________ ______\\n' +\n ' /_ __/ _/ ____/ /_ __/ | / ____/ /_ __/ __ \\\\/ ____/\\n' +\n ' / / / // / / / / /| |/ / / / / / / / __/ \\n' +\n ' / / _/ // /___ / / / ___ / /___ / / / /_/ / /___ \\n' +\n '/_/ /___/\\\\____/ /_/ /_/ |_\\\\____/ /_/ \\\\____/_____/ \\n')\n \n \n# displayes edited board with curent game\ndef display_board(board):\n row_1 = \"A\" + \\\n \"| {} | {} | {} |\".format(board[0][0], board[0][1], board[0][2])\n row_2 = \"B\" + \\\n \"| {} | {} | {} |\".format(board[1][0], board[1][1], board[1][2])\n row_3 = \"C\" + \\\n \"| {} | {} | {} |\".format(board[2][0], board[2][1], board[2][2])\n print('')\n one_two_three = ' 1 2 3'\n separetor = \"----+---+----\"\n print(one_two_three.center(55))\n print(separetor.center(55))\n print(row_1.center(55))\n print(separetor.center(55))\n print(row_2.center(55))\n print(separetor.center(55))\n print(row_3.center(55))\n print(separetor.center(55))\n print('')\n \n \nmain()","repo_name":"kaitekitos/tic_tac_toe_group4","sub_path":"tic_tac_toe_final_group4.py","file_name":"tic_tac_toe_final_group4.py","file_ext":"py","file_size_in_byte":10253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"11927727798","text":"'''\nВам дано описание пирамиды из кубиков в формате XML.\nКубики могут быть трех цветов: красный (red), зеленый (green) и синий (blue).\nДля каждого к��бика известны его цвет, и известны кубики, расположенные прямо под ним.\n\nВведем понятие ценности для кубиков. Самый верхний кубик, соответствующий корню XML\nдокумента имеет ценность 1. Кубики, расположенные прямо под ним, имеют ценность 2.\nКубики, расположенные прямо под нижележащими кубиками, имеют ценность 3. И т. д.\n\nЦенность цвета равна сумме ценностей всех кубиков этого цвета.\n\nВыведите через пробел три числа: ценности красного, зеленого и синего цветов.\n\n'''\n\nfrom xml.etree import ElementTree\n\n# with open('cubes.xml', 'w') as f:\n# f.write(input())\n\ndef recurcionForCubes(el, root, value):\n value += 1\n dict_value[el.attrib['color']] += [value]\n for child in el:\n if child in el:\n recurcionForCubes(child, el, value)\n\n# tree = ElementTree.parse('cubes.xml')\n# root = tree.getroot()\n\n# или просто считывая через строку:\nroot = ElementTree.fromstring(input())\n\ndict_value = {'red':[0], 'green':[0], 'blue':[0]}\ndict_value[root.attrib['color']] += [1]\n\n# без рекурсии, пробегая сразу итератором. Жаль, нельзя его использовать здесь.\n# for el in root.iter('cube'):\n# if el.attrib['color'] == 'red':\n# val_red += 1\n# if el.attrib['color'] == 'green':\n# val_green += 1\n# if el.attrib['color'] == 'blue':\n# val_blue += 1\n\nfor el in root:\n value = 1\n recurcionForCubes(el, root, value)\nprint('{} {} {}'.format(sum(dict_value['red']), sum(dict_value['green']), sum(dict_value['blue'])))\n\n# tree.write('cubes.xml')\n","repo_name":"JuliaGofman/XML_with_graphes-double2-","sub_path":"pyramid_of_cubes.py","file_name":"pyramid_of_cubes.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"43409594038","text":"import sys\nroot_folder = '../../code'\nsys.path.append(root_folder)\nfrom net_architecture.nasnet_4x_geohash_SE_mobile import NAS_U_Net #pylint:disable = E0401\nfrom training_tool.train_model import train_segmentation_model #pylint:disable = E0401\nfrom training_tool.loss_function import dice_coef_loss #pylint:disable = E0401\nfrom data_loader.dataloader_geohash_nasnet import InriaDataLoaderGeohashNASNet#pylint:disable = E0401\n\nfrom utils.keras_config import set_keras_config,get_available_gpus_num #pylint:disable = E0401,E0611\nfrom training_tool.lr_tricks import LearningRateFinder,CyclicCosineRestart #pylint:disable = E0401,E0611\n\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = \"2\"\n\nsplit_train_image_folder = os.path.join('../../','dataset','split_random','train','image')\nsplit_train_label_folder = os.path.join('../../','dataset','split_random','train','label')\nsplit_valid_image_folder = os.path.join('../../','dataset','split_random','valid','image')\nsplit_valid_label_folder = os.path.join('../../','dataset','split_random','valid','label')\n\n\npath_to_train_image = split_train_image_folder\npath_to_train_labels = split_train_label_folder \npath_to_valid_image = split_valid_image_folder\npath_to_valid_labels = split_valid_label_folder\n\n\nweights_path =None\n#weights_path = 'check_point_0/epoch_0059_weights.h5py'\n#weights_path = 'check_point_1/epoch_0050_weights.h5py'\n#weights_path = 'check_point_2/epoch_0195_weights.h5py'\n#weights_path = 'check_point_3/epoch_0087_weights.h5py'\n#weights_path = 'check_point_1/best_model-0020.hdf5'\n#weights_path = 'check_point_2/best_model-0293.hdf5'\n#weights_path = 'check_point_3/best_model-0001.hdf5'\n#weights_path = 'check_point_4/best_model-0005.hdf5'\n\nif weights_path is None:\n use_warmup=True\nelse:\n use_warmup=False\n\nlr_callback = CyclicCosineRestart(lr_min=1e-6,lr_max = 1e-4,\n number_of_batches=640,number_of_epochs=100,\n use_warmup=use_warmup)\n#lr_callback = LearningRateFinder(number_of_batches=100)\ntrain_segmentation_model( NAS_U_Net,\n InriaDataLoaderGeohashNASNet,\n path_to_train_image,\n path_to_train_labels, \n path_to_valid_image,\n path_to_valid_labels,\n weights_path = weights_path,\n num_gpu= 1,\n workers = 8,\n batch_size = 16,\n learning_rate = 1e-4,\n checkpoint_dir = 'check_point',\n no_epochs = 405,\n train_input_size = (512,512),\n valid_input_size = (512,512),\n train_input_stride = (512,512),\n # train_input_stride = (256,256),\n valid_input_stride = (512,512),\n geohash_precision=20,\n custom_callback =lr_callback,\n loss_weights = None,\n custom_loss = None,\n # custom_loss = dice_coef_loss,\n )\n","repo_name":"yangnaisen/GeohashNet","sub_path":"inria_GeohashNet/train_config/nasnet_mobile_SE_lastgeohash_20/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"57"} +{"seq_id":"16923132991","text":"import matplotlib.pyplot as plt\nfrom matplotlib import gridspec\nimport numpy as np\nfrom sklearn.svm import SVC\nfrom scipy.io import loadmat\n\n\ndef svm_ex6_ng():\n \"\"\" Run support vector machines.\n Example from Andrew Ng's coursera course\n \"\"\"\n\n # =====================\n # load data\n\n # dataset = loadmat('data/ex6data1.mat')\n # dataset = loadmat('data/ex6data2.mat')\n dataset = loadmat('data/ex6data3.mat')\n print(dataset.keys())\n\n X = dataset['X']\n y = dataset['y']\n print('X:', X.shape, X[0, :])\n\n # =====================\n # init plotting\n gs = gridspec.GridSpec(2, 2)\n cur_img_index = 0\n fig = plt.figure(figsize=(10, 8), facecolor='white')\n\n # =====================\n # plot image\n\n pos = (y == 1).ravel() # returns 1D array\n neg = (y == 0).ravel()\n\n fig.add_subplot(gs[cur_img_index])\n cur_img_index += 1\n plt.scatter(X[pos, 0], X[pos, 1], color='red', marker='x', label='pos')\n plt.scatter(X[neg, 0], X[neg, 1], color='black', marker='o', label='neg')\n plt.xlabel('X1')\n plt.ylabel('X2')\n plt.legend()\n\n # =====================\n # linear SVM\n\n # 1.\n # svm = SVC(C=1.0, kernel='linear')\n\n # 2. gaussian kernel function (rbf)\n sigma = 0.1\n g = 1/(2*(sigma**2))\n svm = SVC(C=1.0, kernel='rbf', gamma=g)\n\n svm.fit(X, y.ravel())\n\n # =====================\n # plot SVM\n fig.add_subplot(gs[cur_img_index])\n cur_img_index += 1\n\n plot_svc(svm, X, y)\n\n plt.show()\n\n\ndef plot_svc(svc, X, y, h=0.01, pad=0.25):\n \"\"\"Plot SVC\"\"\"\n\n x_min, x_max = X[:, 0].min()-pad, X[:, 0].max()+pad\n y_min, y_max = X[:, 1].min()-pad, X[:, 1].max()+pad\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n\n Z = svc.predict(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n\n plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.2)\n\n pos = (y == 1).ravel() # returns 1D array\n neg = (y == 0).ravel()\n plt.scatter(X[pos, 0], X[pos, 1], color='red', marker='x', label='pos')\n plt.scatter(X[neg, 0], X[neg, 1], color='black', marker='o', label='neg')\n\n # Support vectors indicated in plot by vertical lines\n # sv = svc.support_vectors_\n # plt.scatter(sv[:,0], sv[:,1], c='k', marker='|', s=100, linewidths='1')\n\n plt.xlim(x_min, x_max)\n plt.ylim(y_min, y_max)\n plt.xlabel('X1')\n plt.ylabel('X2')\n plt.show()\n print('Number of support vectors: ', svc.support_.size)\n\n\nsvm_ex6_ng()\n","repo_name":"johanna-b/machine_learning_examples","sub_path":"6_SVM_sklearn.py","file_name":"6_SVM_sklearn.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"70289727857","text":"import math\r\n\r\n\r\n# function to help with methods Maby seperate file\r\ndef matMul(a, b):\r\n \"\"\"multiply mat a X vector b\"\"\"\r\n result = []\r\n if len(a[0]) != len(b):\r\n print(\"columns of b must equal to vector a \")\r\n return\r\n\r\n for i in range(len(a)):\r\n seg = 0\r\n for j in range(len(a[0])):\r\n seg += a[i][j] * b[j]\r\n result.append(seg)\r\n\r\n return result\r\n\r\n\r\ndef mult(v, k):\r\n \"\"\"multiply vector v by number k\"\"\"\r\n result = []\r\n for i in range(len(v)):\r\n result.append(v[i]*k)\r\n return result\r\n\r\n\r\ndef projection(dot):\r\n \"\"\" recive a dot with 3 axis and return a dot with 2 axis after calculating \r\n the dot projection on axis z\"\"\"\r\n distance = 2\r\n z = 1 / (distance - dot[2])\r\n\r\n proMat = [\r\n [z, 0, 0],\r\n [0, z, 0]\r\n ]\r\n dot = matMul(proMat, dot)\r\n return dot\r\n\r\n\r\ndef vecAdd(a, b):\r\n \"\"\" Reciving two vectors return the added vector a+b\"\"\"\r\n newVec = []\r\n for i in range(len(a)):\r\n newVec.append(a[i]+b[i])\r\n return newVec\r\n\r\n\r\ndef vecSub(a, b):\r\n \"\"\" Reciving two vectors return the subbed vector a-b\"\"\"\r\n newVec = []\r\n for i in range(len(a)):\r\n newVec.append(a[i]-b[i])\r\n return newVec\r\n","repo_name":"itaibenjy/3D-Rubiks-Cube","sub_path":"myMath.py","file_name":"myMath.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"21168448083","text":"import pdb\n\nfrom fastapi import APIRouter\nfrom fastapi import Depends,UploadFile,Form,File\nfrom typing import List\nfrom app.schemas import CreateProduct, EditProduct, EditImage, GetProduct, ProductList, DeleteProduct\nfrom app.services import create_product,edit_product,delete_product,list_product,get_product\nfrom sqlalchemy.orm import Session\nfrom core.config import engine, SessionLocal, get_db\n\nproduct_app = APIRouter()\n\n\n@product_app.post(\"/create_product\")\nasync def create_level(files: List[UploadFile]=File(...),data: CreateProduct=Depends(), db: Session = Depends(get_db)):\n try:\n response = create_product(db, data,files)\n return {\"status\": True, \"result\": response}\n except Exception as e:\n print(f\"exceptions are {e}\")\n return {\"status\": False, \"result\": \"something went wrong\"}\n\n\n@product_app.post(\"/edit_product\")\nasync def edit_level(data: EditProduct, db: Session = Depends(get_db)):\n try:\n response = edit_product(db, data)\n return {\"status\": True, \"result\": response}\n except Exception as e:\n print(f\"exceptions are {e}\")\n return {\"status\": False, \"result\": \"something went wrong\"}\n\n\n@product_app.post(\"/get_product\")\nasync def get_level(data: GetProduct, db: Session = Depends(get_db)):\n try:\n pdb.set_trace()\n response = get_product(db, data)\n return {\"status\": True, \"result\": response}\n except Exception as e:\n print(f\"exceptions are {e}\")\n return {\"status\": False, \"result\": \"something went wrong\"}\n\n\n@product_app.delete(\"/delete_product\")\nasync def delete_level(data: DeleteProduct, db: Session = Depends(get_db)):\n try:\n response = delete_product(db, data)\n return {\"status\": True, \"result\": response}\n except Exception as e:\n print(f\"exceptions are {e}\")\n return {\"status\": False, \"result\": \"something went wrong\"}\n\n\n@product_app.post(\"/list_product\")\nasync def list_level(data: ProductList, db: Session = Depends(get_db)):\n try:\n response = list_product(db, data)\n return {\"status\": True, \"result\": response}\n except Exception as e:\n print(f\"exceptions are {e}\")\n return {\"status\": False, \"result\": \"something went wrong\"}\n","repo_name":"satya36-cpu/new-python-code","sub_path":"zaps/product/app/views/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"34671817553","text":"import requests #pip3 install requests\nimport obj_maker \nimport pickle\n\nfrom nltk.stem import SnowballStemmer\nfrom nltk.tokenize import WordPunctTokenizer #pip3 install nltk\nfrom bs4 import BeautifulSoup #pip install beautifulsoup4\n\n\ndef readJavaDocumentationAndPreprocessing():\n\n destination_file= \"./processed_data/doc_data_preprocessed\"\n doc_path=\"./data/java_docs/api/\"\n head_file_path=\"allclasses-noframe.html\"\n \n soup = BeautifulSoup(open(doc_path+head_file_path), 'html.parser',from_encoding='utf-8') #pip install html5lib\n\n with open(\"Scrapping_output.txt\", 'w') as f: \n f.write(soup.prettify())\n\n\n all_java_classes=soup.find_all(\"li\")\n #print(soup.prettify())\n\n array_of_classes = []\n for x in all_java_classes:\n array_of_classes.append(str(x))\n\n content = str(all_java_classes)\n\n with open(\"Scrapping_output_with_class_name.txt\", 'w') as f: \n f.write(content)\n\n\n all_api=[]\n\n for _class in all_java_classes :\n class_link = _class.a['href']\n class_name=_class.get_text()\n package_name=_class.a['title'].split(' ')[-1]\n\n class_soup= BeautifulSoup(open(doc_path+class_link,'r', errors='ignore'),\"html.parser\", from_encoding='utf-8' )\n\n class_block= class_soup.find('div' , class_='block')\n\n if class_block is None:\n continue \n\n tonkenizer=WordPunctTokenizer()\n\n class_description=tonkenizer.tokenize(class_block.get_text().lower())\n\n class_object = obj_maker.obj_maker(package_name,class_name,class_description )\n\n methods_block_heading =class_block.find('h3', string='Method Detail')\n\n if methods_block_heading is not None:\n \n methods_block=class_block.find('h3', string='Method Detail').parent\n\n for method in methods_block.find_all('h4') :\n\n _block= method.parent.find('div',class_='block')\n\n if _block is None:\n continue\n \n class_object.method.append(method.get_text())\n class_object.methods_description_in_raw_text.append(_block.get_text())\n class_object.methods_description_split_into_words.append(tokenizer.tokenize(_block.get_text()).lower())\n class_object.methods_descriptions_stemmed.append(\n [SnowballStemmer('english').stem(word) for word in method_description]\n )\n all_api.append(class_object)\n\n pickle.dump(all_api,open(destination_file,\"wb\"))\n\n\nif __name__ == \"__main__\":\n\n readJavaDocumentationAndPreprocessing()\n\n javaDocs=pickle.load(open(\"./processed_data/doc_data_preprocessed\",\"rb\"))\n count=0\n\n for con in javaDocs:\n if \"xception\" in con.class_name:\n print(con.class_name)\n print(con.class_description)\n count += 1\n else:\n continue\n print(count)\n \n\n","repo_name":"mohibul75/Cra_Solver","sub_path":"web_scraping.py","file_name":"web_scraping.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"70849363380","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n# @Time : 2019-02-8\n# @Author : evi\n# @Comment : 查找在个人信息中出现但是未在家庭信息中出现的 fid\n# @File : PeopleNotInFam.py\n\nimport sys\nimport pandas as pd\nimport json\n\ntry:\n familyInfoFile = sys.argv[1]\n peopleInfoFile = sys.argv[2]\n fidColName = sys.argv[3]\n exportJsonFile = sys.argv[4]\nexcept:\n print('Error: Arg Ill')\n exit(-1)\n\nprint('Reading %s...'%familyInfoFile)\nFamData = pd.read_csv(familyInfoFile, low_memory=False, encoding='GBK')\nprint('Reading %s finished'%familyInfoFile)\n\nprint('Reading %s...'%peopleInfoFile)\nPeopleData = pd.read_csv(peopleInfoFile, low_memory=False, encoding='GBK')\nprint('Reading %s finished'%peopleInfoFile)\n\nFidsNotInFamilyData = []\n\nprint('Data Converting...')\nUniqFidsInPeople = list(set(PeopleData[fidColName]))\nUniqFidsInFamily = list(set(FamData[fidColName]))\n\nprint('Looking for missing fids...')\nfor fid in UniqFidsInPeople:\n if not fid in UniqFidsInFamily and not fid in FidsNotInFamilyData:\n FidsNotInFamilyData.append(fid)\nFidsNotInFamilyData.sort()\n\nprint('共计 %d 个 fid 在 个人信息中出现而未在家庭信息中出现'%len(FidsNotInFamilyData))\n\nprint('家庭信息中含有 %d 个 fid,'%len(UniqFidsInFamily))\nprint('个人信息中含有 %d 个 fid,'%len(UniqFidsInPeople))\n\nprint('数据校验...')\nif len(FidsNotInFamilyData) == len(UniqFidsInPeople) - len(UniqFidsInFamily):\n print('数据校验成功')\n with open(exportJsonFile, 'w+') as fp:\n fp.write(json.dumps(FidsNotInFamilyData))\n print('保存 fid 到文件 %s'%exportJsonFile)\nelse:\n print('数据校验错误: 家庭信息数据中含有个人信息数据中未出现的 fid')","repo_name":"luokuis/Jan22.20-58","sub_path":"src/PeopleNotInFam.py","file_name":"PeopleNotInFam.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"74570700978","text":"from os.path import join, isfile\nfrom os import listdir\nimport csv\nfrom text_preprocessing import *\nfrom word_context_matrix import *\nfrom similarity_metrics import *\n\n# Get list of N most similars for word\ndef get_top_n_similars(word, matrix, sim_metric, reverse_flag = True):\n if not token2index.get(word):\n print(\"Error! The word doesn't exist in corpus!\")\n word_vector = matrix.getrow(token2index[word]).toarray()[0]\n similar_tokens = []\n for token_index in token2index.values():\n token_vector = matrix.getrow(token_index).toarray()[0]\n similarity = sim_metric(word_vector, token_vector)\n similar_tokens.append((token_index, similarity))\n similar_tokens.sort(key=lambda x: x[1], reverse = reverse_flag)\n return [(index2token[token_index], similarity) for token_index, similarity in similar_tokens[:TOP_N]]\n\n\n# Compare model results for wordsim words with gold standard values\ndef compare_with_wordsim(matrix, sim_metric):\n with open('data/wordsim_similarity_goldstandard.txt') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter='\\t')\n result = []\n for row in csv_reader:\n word1 = row[0].lower()\n word2 = row[1].lower()\n wordsim_similarity = row[2]\n # check if both words from wordsim exist in model dictionary\n if token2index.get(word1) and token2index.get(word2):\n v1 = matrix.getrow(token2index[word1]).toarray()[0]\n v2 = matrix.getrow(token2index[word2]).toarray()[0]\n model_similarity = sim_metric(v1, v2)\n result.append((word1, word2, wordsim_similarity, model_similarity))\n return result\n\n# Build tokenized and lemmatized wordsim_corpus without stop words\ncorpus = []\ndocument_name_list = [f for f in listdir(CORPUS_PATH) if isfile(join(CORPUS_PATH, f))]\nfor name in document_name_list:\n with open(join(CORPUS_PATH, name), 'r') as doc:\n text = doc.read()\n sentences = tokenize_text(text)\n for sentence in sentences:\n lemmas = lemmatize_text(sentence)\n preprocessed_sentence = remove_stop_words(lemmas)\n if len(preprocessed_sentence) < 2:\n continue\n corpus.append(preprocessed_sentence)\n\n# Form corpus vocabulary\ncorpus_vocabulary = set()\nfor document in corpus:\n corpus_vocabulary.update(document)\n\n# Build dicts to optimize memory usage\ntoken2index = {token: index for index, token in enumerate(corpus_vocabulary)}\nindex2token = {index: token for token, index in token2index.items()}\n# print(\"token2index\", token2index)\n# print(\"index2token\", index2token)\n\n# Build word context dictionary\nskipgram_counts = build_skipgrams(corpus, token2index)\n# Build word context matrix using csr-matrix\nword_context_matrix = build_word_context_matrix(skipgram_counts)\n\n# Build SPPMI (smoothed positive pointwise mutual information) matrix\nskipgrams_amount = word_context_matrix.sum() # sum over all values of matrix\nsum_over_words = np.array(word_context_matrix.sum(axis=0)).flatten() # array of sum over words for context\nsum_over_contexts = np.array(word_context_matrix.sum(axis=1)).flatten() # array of sum over contexts for word\nsppmi_matrix = build_sppmi_matrix(skipgrams_amount, sum_over_words, sum_over_contexts, skipgram_counts)\n\n# Adjust execution mode of the model\nsim_metric = None\nreverse_flag = True\nmetric_name = ''\nif METRIC == '1':\n sim_metric = calc_cosine_similarity\n metric_name = \"cos_sim\"\nelif METRIC == '2':\n sim_metric = calc_Kullback_Leibler_divergence\n reverse_flag = False\n metric_name = \"KL_div\"\nelif METRIC == '3':\n sim_metric = calc_Jensen_Shannon_divergence\n reverse_flag = False\n metric_name = \"JS_div\"\nelse:\n print(\"Error! Chosen metric doesn't exist!\")\n exit(1)\n\nprint('Vocab size is: ', len(corpus_vocabulary))\nif MODE == \"SEARCH_SIMILARS\":\n res = get_top_n_similars(WORD, sppmi_matrix, sim_metric, reverse_flag)\n print(res)\n # Save results as csv\n print(\"Save results as csv\")\n # for top N similars search\n with open('data/results/similars/{0}_{1}.csv'.format(WORD, metric_name), 'w') as out:\n sim_words_out = csv.writer(out)\n sim_words_out.writerow(['word', 'sim_value'])\n for word, sim_value in res:\n sim_words_out.writerow([word, sim_value])\n\nelif MODE == \"WORDSIM_ANALYSIS\":\n res = compare_with_wordsim(sppmi_matrix, sim_metric)\n # Save results as csv\n print(\"Save results as csv\")\n # for wordsim analysis\n with open('data/results/wordsim_analysis_{0}.csv'.format(metric_name), 'w') as out:\n analysis_out = csv.writer(out)\n analysis_out.writerow(['word1', 'word2', 'golden_value', 'model_value'])\n for word1, word2, golden_value, model_value in res:\n analysis_out.writerow([word1, word2, golden_value, model_value])\nelse:\n print(\"Error! Chosen mode doesn't exist!\")\n exit(1)\n\n","repo_name":"Dashezunka/word-vectors-similarity","sub_path":"word_embeddings.py","file_name":"word_embeddings.py","file_ext":"py","file_size_in_byte":4931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"17919089351","text":"import discord\nfrom discord.ext import commands\nimport os\nimport time\nimport praw\nimport urllib3\n\n\nred = praw.Reddit(\n client_id=os.getenv('cid'),\n client_secret=os.getenv('csecret'),\n user_agent=\"discord:RemBotv1.0:(By /u/rKeWdAiNt)\"\n )\n\nclient = commands.Bot(command_prefix = '.')\n\n@client.event\nasync def on_ready():\n print(red.read_only)\n\n@client.command()\nasync def add(ctx, num1: float, num2: float):\n await ctx.send(num1 + num2)\n\n@client.command()\nasync def sub(ctx, num1: float, num2: float):\n await ctx.send(num1 - num2)\n\n@client.command()\nasync def mult(ctx, num1: float, num2: float):\n await ctx.sent (num1 * num2)\n\n@client.command()\nasync def reddit(ctx, subr: str, toptype: str, num: int):\n if num > 10 or num < 1:\n await ctx.send(\"Number has to be 1 ~ 10!\")\n elif (toptype != \"hot\" and toptype != \"new\" and toptype != \"top\"):\n await ctx.send(\"The input has to be \\\"top\\\", \\\"new\\\", or \\\"hot\\\"!\")\n elif (toptype == \"top\"):\n for submission in red.subreddit(subr).top(limit=num):\n embedVar = discord.Embed(title=\"Title\", description=submission.title, color=0xadd8e6)\n embedVar.add_field(name=\"URL\", value=\"[Submission Link](https://reddit.com\"+submission.permalink+\")\", inline=False)\n embedVar.set_image(url=submission.url)\n await ctx.send(embed=embedVar)\n elif (toptype == \"new\"):\n for submission in red.subreddit(subr).new(limit=num):\n embedVar = discord.Embed(title=\"Title\", description=submission.title, color=0xadd8e6)\n embedVar.add_field(name=\"URL\", value=\"[Submission Link](https://reddit.com\"+submission.permalink+\")\", inline=False)\n embedVar.set_image(url=submission.url)\n await ctx.send(embed=embedVar)\n elif (toptype == \"hot\"):\n for submission in red.subreddit(subr).hot(limit=num):\n embedVar = discord.Embed(title=\"Title\", description=submission.title, color=0xadd8e6)\n embedVar.add_field(name=\"URL\", value=\"[Submission Link](https://reddit.com\"+submission.permalink+\")\", inline=False)\n embedVar.set_image(url=submission.url)\n await ctx.send(embed=embedVar)\n else:\n await ctx.send(\"Input is \\\".reddit subreddit type(top, new, hot) number\\\"\")\n\n@client.event\nasync def on_message(message):\n if message.author.id == 234002911632293890 or message.author.id == 385909824623476740:\n await message.channel.send(\"quiet tuna\")\n await message.delete()\n \n\nclient.run(os.getenv('TOKEN'))","repo_name":"KwanYoon/RemBot","sub_path":"rembot.py","file_name":"rembot.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"7916076929","text":"e=float(input(\"Equity : \"))\r\nd=float(input(\"Debt : \"))\r\ntc=float(input(\"Tax Rate : \"))\r\nt=e+d\r\n\r\n# Cost of Equity \r\nprint(\"How do you want Equity Valued ?\")\r\nprint(\" 1.Dividend Capitalization Model\")\r\nprint(\" 2.Capital Asset Pricing Model(CAPM)\")\r\nopt=input()\r\nif opt==\"1\" :\r\n do=float(input(\"Dividend per Share (DPS) : \"))\r\n eo=float(input(\"Earnings per Share (EPS) : \"))\r\n gd=float(input(\"Growth rate of Dividends : \"))\r\n ke=(do/eo)+(gd/100)\r\nelse:\r\n rm=float(input(\"Market Risk Premium : \"))\r\n rf=float(input(\"Risk free rate : \"))\r\n beta=float(input(\"Beta : \"))\r\n ke=(rf/100)+beta*((rm-rf)/100)\r\nke=ke\r\n# Cost of Debt\r\nif opt==\"1\":\r\n rf=float(input(\"Risk free rate : \"))\r\ncs=float(input(\"Credit Spread : \"))\r\nkd=((rf+cs)*(100-tc))/100\r\n\r\n# Weighted Average Cost of Capital\r\nwacc=(e/t)*ke+(d/t)*kd\r\n\r\n# Output\r\nprint(\" \")\r\nprint(\" \")\r\nprint(\" Weighted Average Cost of Capital\")\r\nprint(\" --------------------------------\")\r\nprint(\" \")\r\nprint(\"Cost of Equity : \",ke)\r\nprint(\"Cost of Debt : \",kd)\r\nprint(\"Weighted Average Cost of Capital : \",wacc)\r\n","repo_name":"yakhil5/fm","sub_path":"WACC.py","file_name":"WACC.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"33056216","text":"import os\nimport sys\nimport utils\nimport joblib\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom enum import Enum\nfrom pprint import pprint\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.decomposition import PCA\nfrom sklearn import metrics\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn import preprocessing, feature_selection\nfrom sklearn.model_selection import (\n cross_val_score,\n cross_val_predict,\n GridSearchCV,\n StratifiedKFold,\n LeaveOneOut\n)\n\nCATEGORIES = {\n \"Happy\": 0,\n \"Chill\": 0,\n \"Sad/Sentimental\": 1,\n \"Bops\": 2,\n \"Madness\": 2\n}\n\nFEATURES = [\"danceability\", \"energy\", \"key\",\n \"loudness\", \"mode\", \"speechiness\",\n \"acousticness\", \"instrumentalness\",\n \"liveness\", \"valence\", \"tempo\", \"explicit\"]\n\nCONTINUOUS = [\"danceability\", \"energy\",\n \"speechiness\", \"acousticness\",\n \"liveness\", \"valence\", \"tempo\"]\n\nclass ModelType(Enum):\n GradientBoosting = \"gbt\"\n NeuralNetwork = \"nn\"\n KNearestNeighbors = \"knn\"\n SupportVector = \"svm\"\n\n\nclass PlaylistClassifier():\n def __init__(self, model_type: ModelType):\n input_path = os.path.join(\"data\", \"playlist_features.json\")\n self.features = pd.read_json(input_path)\n\n self.model_type = model_type\n self.X = self.features[FEATURES]\n self.y = self.features[\"playlist\"].map(CATEGORIES)\n self.model_path = \\\n os.path.join(\"prediction\", \"models\", self.model_type.value)\n\n def train(self):\n pipe, param_grid = {\n ModelType.GradientBoosting: self._get_gbt_pipeline(),\n ModelType.NeuralNetwork: self._get_nn_pipeline(),\n ModelType.KNearestNeighbors: self._get_knn_pipeline(),\n ModelType.SupportVector: self._get_svm_pipeline()\n }[self.model_type]\n\n # Perform exhaustive grid search to find the best model\n search = GridSearchCV(pipe, param_grid, cv=10,\n n_jobs=-1, verbose=2,\n scoring=\"f1_macro\")\n search = search.fit(self.X, self.y)\n clf = search.best_estimator_\n\n # Just to see what were the optimal hyperparameters\n print(\"\\n\\nAccuracy: %0.2f \" % (search.best_score_))\n print(clf[-2])\n print(clf[-1])\n\n # Save best model to disk\n clf = clf.fit(self.X, self.y)\n utils.makedirs(self.model_path)\n joblib.dump(clf, self.model_path)\n\n def stats(self):\n clf = self._load_model()\n y_pred = cross_val_predict(clf, self.X, self.y, cv=10)\n\n confusion_matrix = metrics.confusion_matrix(self.y, y_pred, normalize='true')\n report = metrics.classification_report(self.y, y_pred)\n print(report)\n\n labels = self._get_label_names()\n fig = plt.figure(figsize=(13, 6))\n ax = sns.heatmap(confusion_matrix, annot=True, fmt=\"0.2f\",\n cmap=\"YlGnBu\", vmin=0.0, vmax=1.0,\n xticklabels=labels, yticklabels=labels)\n ax.set_xlabel(\"Predicted Class\")\n ax.set_ylabel(\"Actual Class\")\n plt.yticks(rotation=0)\n plt.title(\"Confusion Matrix\")\n basename = os.path.basename(self.model_path)\n plt.savefig(os.path.join(\"prediction\", f\"confusion_{basename}.png\"))\n plt.close()\n\n def misclassified(self):\n clf = self._load_model()\n y_pred = cross_val_predict(clf, self.X, self.y, cv=10)\n classes = self._get_label_names()\n\n X = self.features.copy()\n X[\"pred\"] = [classes[label] for label in y_pred]\n X[\"actual\"] = [classes[label] for label in self.y]\n X = X[X[\"pred\"] != X[\"actual\"]]\n X = X[[\"name\", \"pred\", \"actual\"]]\n X = X.sort_values(by=[\"actual\", \"pred\"])\n\n pd.set_option('display.max_rows', len(X))\n pd.set_option('display.max_colwidth', None)\n print(X.to_string())\n\n def pca(self):\n # Only do PCA on continuous variables. Categorical\n # values like `key` are misleading since they make\n # it seem like values are really spread out.\n X = self.X[CONTINUOUS]\n X = PCA(n_components=3).fit_transform(X)\n\n classes = self._get_label_names()\n labels = [classes[label] for label in self.y]\n\n plot_df = pd.DataFrame({\n \"PC 1\": X[:,0],\n \"PC 2\": X[:,1],\n \"PC 3\": X[:,2],\n \"cluster\": labels\n })\n g = sns.PairGrid(plot_df, hue=\"cluster\", palette=\"coolwarm\")\n g = g.map(sns.scatterplot, linewidths=0.75, edgecolor=\"w\", s=40)\n g = g.add_legend()\n g.fig.set_size_inches(10, 10)\n g.fig.subplots_adjust(top=0.9)\n g.fig.suptitle(\"PCA on Playlist Dataset\", fontsize=16)\n plt.savefig(os.path.join(\"prediction\", \"pca.png\"))\n plt.close()\n\n def _load_model(self):\n return joblib.load(self.model_path)\n\n def _get_label_names(self):\n labels_map = {}\n\n for k, v in CATEGORIES.items():\n labels_map.setdefault(v, []).append(k)\n\n return [\"/\".join(classes)\n for label, classes\n in labels_map.items()]\n\n def _get_gbt_pipeline(self):\n without_key = [feature for feature in FEATURES if feature != \"key\"]\n\n pipe = Pipeline([\n (\"transform\", ColumnTransformer([\n (\"scale\",\n preprocessing.MinMaxScaler(),\n without_key),\n (\"key_category\",\n preprocessing.OneHotEncoder(handle_unknown=\"ignore\"),\n [\"key\"])\n ], remainder=\"passthrough\")),\n # (\"select\", feature_selection.SelectKBest()),\n (\"model\", GradientBoostingClassifier(n_iter_no_change=5,\n max_features=\"auto\"))\n ])\n\n param_grid = {\n # \"select__k\": [5, 6, 7, 8, 9, 10, 11],\n \"model__n_estimators\": [75, 100, 125, 150, 200, 250, 300],\n \"model__max_leaf_nodes\": [2, 3, 4],\n \"model__max_depth\": [1, 2, 3, 4],\n \"model__subsample\": [0.5, 0.75, 1.0]\n }\n\n return pipe, param_grid\n\n def _get_nn_pipeline(self):\n without_key = [feature for feature in FEATURES if feature != \"key\"]\n\n pipe = Pipeline([\n (\"transform\", ColumnTransformer([\n (\"scale\",\n preprocessing.StandardScaler(),\n without_key),\n (\"key_category\",\n preprocessing.OneHotEncoder(handle_unknown=\"ignore\"),\n [\"key\"])\n ], remainder=\"passthrough\")),\n (\"select\", feature_selection.SelectKBest()),\n (\"model\", MLPClassifier(solver=\"adam\", max_iter=5000,\n early_stopping=True))\n ])\n\n param_grid = {\n \"select__k\": [4, 5, 6, 7, 8],\n \"model__alpha\": 10.0 ** -np.arange(5, 12),\n \"model__hidden_layer_sizes\": [(500,), (500, 100), (500, 500)],\n \"model__activation\": [\"relu\", \"tanh\"],\n \"model__learning_rate_init\": 10.0 ** -np.arange(1, 6)\n }\n\n return pipe, param_grid\n\n def _get_knn_pipeline(self):\n pipe = Pipeline([\n (\"scale\", preprocessing.MinMaxScaler()),\n (\"select\", feature_selection.SelectKBest()),\n (\"model\", KNeighborsClassifier(weights=\"uniform\"))\n ])\n\n param_grid = {\n \"select__k\": [4, 6, 8, 10],\n \"model__n_neighbors\": [1, 2, 5, 8, 10, 15, 20, 30],\n \"model__leaf_size\": [2, 5, 10, 30, 50]\n }\n\n return pipe, param_grid\n\n def _get_svm_pipeline(self):\n pipe = Pipeline([\n (\"scale\", preprocessing.MinMaxScaler()),\n (\"select\", feature_selection.SelectKBest()),\n (\"model\", SVC(kernel=\"poly\", max_iter=-1, break_ties=True, probability=True))\n ])\n\n param_grid = {\n \"select__k\": [4, 5, 6, 8, \"all\"],\n \"model__degree\": [3, 4, 5, 6],\n \"model__C\": [0.0001, 0.001, 0.01, 0.1, 1.0, 10.0],\n \"model__gamma\": [\"scale\", \"auto\"]\n }\n\n return pipe, param_grid\n\nif __name__ == \"__main__\":\n command = sys.argv[1]\n model_type = None if len(sys.argv) < 3 else sys.argv[2]\n model_type = ModelType(model_type)\n classifier = PlaylistClassifier(model_type)\n\n if command == \"train\":\n classifier.train()\n elif command == \"stats\":\n classifier.stats()\n elif command == \"wrong\":\n classifier.misclassified()\n elif command == \"pca\":\n classifier.pca()\n","repo_name":"SChakravorti21/Kpop-Analysis","sub_path":"prediction/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"36680104430","text":"\"\"\"various helper functions for the tutorial\"\"\"\n\n\ndef rigid(node, **kwargs):\n \"\"\"build a rigid object under node 'parent'\"\"\"\n\n name = kwargs.get('name', 'unnamed')\n\n position = kwargs.get('position', None )\n velocity = kwargs.get('velocity', None )\n\n mass = kwargs.get('mass', 1.0)\n\n mesh = kwargs.get('mesh', None)\n template = kwargs.get('template', 'Rigid')\n\n parent = node.createChild(name)\n \n dofs = parent.createObject('MechanicalObject',\n name = 'dofs',\n template = template)\n\n if position: dofs.position = position\n if velocity: dofs.velocity = velocity\n\n mass = parent.createObject('UniformMass',\n name = 'mass',\n template = template,\n totalMass = mass)\n if mesh:\n \n # visual\n visual = parent.createChild('visual')\n model = visual.createObject('OglModel',\n name = 'model',\n fileMesh = mesh)\n \n mapping = visual.createObject('RigidMapping',\n name = 'mapping')\n\n # collision\n collision = parent.createChild('collision')\n\n loader = collision.createObject('MeshObjLoader',\n name = 'loader',\n filename = mesh)\n \n dofs = collision.createObject('MechanicalObject',\n name = 'dofs',\n position = '@loader.position')\n\n mapping = collision.createObject('RigidMapping')\n topology = collision.createObject('MeshTopology', \n name = 'topology',\n triangles = '@loader.triangles')\n \n model = collision.createObject('TriangleModel', \n name = 'model')\n\n return parent\n\ndef cat(x):\n if type(x) is list:\n return ' '.join(map(cat, x))\n else: return str(x)\n\n\ndef local_frame(node, **kwargs):\n\n source = kwargs.get('source', 0)\n coords = kwargs['coords']\n\n name = kwargs.get('name', 'unnamed')\n template = kwargs.get('template', 'Rigid')\n\n frame = node.createChild(name)\n\n dofs = frame.createObject('MechanicalObject',\n name = 'dofs',\n template = template)\n\n mapping = frame.createObject('AssembledRigidRigidMapping',\n name = 'mapping',\n template = '{0},{1}'.format(template, template) )\n\n \n mapping.source = str(source) + ' ' + cat(coords)\n\n\n return frame\n\n\ndef joint_dofs(node, parent_path, child_path, **kwargs):\n \"\"\"path are relative to node\"\"\"\n \n name = kwargs.get('name', 'unnamed')\n\n res = node.createChild(name)\n dofs = res.createObject('MechanicalObject',\n name = 'dofs',\n template = 'Vec6')\n mapping = res.createObject('RigidJointMultiMapping',\n name = 'mapping',\n template = 'Rigid,Vec6',\n input = '@../{} @../{}'.format(parent_path, child_path),\n output = '@dofs',\n pairs = '0 0')\n\n return res\n\ndef joint(node, parent_path, child_path, **kwargs):\n fixed = kwargs.get('fixed', None)\n compliance = kwargs.get('compliance', 0)\n \n res = joint_dofs(node, parent_path, child_path, **kwargs)\n if fixed:\n constraints = res.createChild('constraints')\n dofs = constraints.createObject('MechanicalObject',\n name = 'dofs',\n template = 'Vec1')\n\n mapping = constraints.createObject('MaskMapping',\n dofs = cat(fixed))\n \n ff = constraints.createObject('UniformCompliance',\n compliance = compliance)\n\n return res\n\n\ndef setup( node, **kwargs ):\n\n # load plugin\n plugin = node.createObject('RequiredPlugin',\n pluginName = 'Compliant')\n\n\n style = node.createObject('VisualStyle')\n style.displayFlags = 'showBehavior showCollisionModels hideMapping hideVisual'\n\n # these are from the Compliant plugin\n ode = node.createObject('CompliantImplicitSolver')\n num = node.createObject('SequentialSolver',\n iterations = 50,\n precision = 0)\n\n # these are from the pouf plugin\n # ode = node.createObject('pouf_solver')\n # num = node.createObject('pouf.pgs',\n # iterations = 50,\n # precision = 0)\n\n\n dt = kwargs.get('dt', 1e-2)\n node.dt = dt\n\n animate = kwargs.get('animate', True)\n node.animate = animate\n","repo_name":"maxime-tournier/sofa-tutorial","sub_path":"toolbox.py","file_name":"toolbox.py","file_ext":"py","file_size_in_byte":5024,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"57"} +{"seq_id":"21995655228","text":"\r\nfrom random import seed, randrange\r\nimport sys\r\n\r\n\r\ndim = 10\r\n\r\n\r\ndef display_grid():\r\n for row in grid:\r\n print(' ', *row)\r\n\r\n\r\n# Returns the number of shapes we have discovered and \"coloured\".\r\n# We \"colour\" the first shape we find by replacing all the 1s\r\n# that make it with 2. We \"colour\" the second shape we find by\r\n# replacing all the 1s that make it with 3.\r\ndef colour_shapes():\r\n global color,res\r\n res=grid\r\n color=1\r\n for i in range(dim):\r\n for j in range(dim):\r\n if(res[i][j]==1):\r\n color+=1\r\n dfs(i,j,color)\r\n return res\r\n # Replace pass above with your code\r\n\r\n\r\ndef max_number_of_spikes(nb_of_shapes):\r\n ans=[0 for i in range(color+1)]\r\n for i in range(dim):\r\n for j in range(dim):\r\n if(nb_of_shapes[i][j]!=0):\r\n tmp=0\r\n if(i>0 and nb_of_shapes[i-1][j]!=0):\r\n tmp+=1\r\n if(j>0 and nb_of_shapes[i][j-1]!=0):\r\n tmp+=1\r\n if(i0 and grid[x-1][y]==1):\r\n dfs(x-1,y,c)\r\n if(y>0 and grid[x][y-1]==1):\r\n dfs(x,y-1,c)\r\n if(xКомманды:\r\n/show - информация об аккаунте \r\n/edit - изменить добавленные каналы\r\n/add - добавить аккаунт\r\n \"\"\", parse_mode=\"HTML\")\r\n\r\n\r\n@dp.message_handler(commands=['add'])\r\nasync def add_account(message):\r\n await message.answer(\"Отправь сессию\")\r\n await CalcStates.session.set()\r\n\r\n\r\n@dp.message_handler(content_types=['document'], state=CalcStates.session)\r\nasync def get_session(message, state: FSMContext):\r\n try:\r\n sessions = get_files(f'./session/{message.from_user.id}', '.session')\r\n if not await download_sessions(message,\r\n f'./session/{message.from_user.id}/{message.from_user.id}_{len(sessions) + 1}'\r\n f'.session'):\r\n return await message.answer('Пришлите сессию с расширением \".session\"!')\r\n except FileNotFoundError:\r\n if not await download_sessions(message,\r\n f'./session/{message.from_user.id}/{message.from_user.id}.session'):\r\n return await message.answer('Пришлите сессию с расширением \".session\"!')\r\n # await download_sessions(message, f'./session/{message.from_user.id}/{message.from_user.id}.session')\r\n await state.update_data(session=f'{message.from_user.id}')\r\n await message.answer(\"Отправь api_id от сессии\")\r\n await CalcStates.api_id.set()\r\n\r\n\r\n@dp.message_handler(state=CalcStates.api_id)\r\nasync def get_api_id(message, state: FSMContext):\r\n await state.update_data(api_id=message.text)\r\n await message.answer(\"Отправь api_hash от сессии\")\r\n await CalcStates.api_hash.set()\r\n\r\n\r\n@dp.message_handler(state=CalcStates.api_hash)\r\nasync def get_api_hash(message, state: FSMContext):\r\n await state.update_data(api_hash=message.text)\r\n await message.answer(\"Отправь промт\")\r\n await CalcStates.promt.set()\r\n\r\n\r\n@dp.message_handler(state=CalcStates.promt)\r\nasync def get_promt(message, state: FSMContext):\r\n await state.update_data(promt=message.text)\r\n await message.answer(\"После скольки сообщений отправить аккаунт в сон?\")\r\n await CalcStates.sleep.set()\r\n\r\n\r\n@dp.message_handler(state=CalcStates.sleep)\r\nasync def get_sleep(message, state: FSMContext):\r\n await state.update_data(sleep=message.text)\r\n await message.answer(\"Скинь txt файл со списком каналов\")\r\n await CalcStates.channels.set()\r\n\r\n\r\n@dp.message_handler(content_types=['document'], state=CalcStates.channels)\r\nasync def get_channels(message, state: FSMContext):\r\n if os.path.splitext(message.document.file_name)[1] != '.txt':\r\n return await message.answer('Пришлите сессию с расширением \".txt\"!')\r\n await message.document.download(destination_file=f\"./channels/{message.from_user.id}_channels.txt\")\r\n async with async_open(f'./channels/{message.from_user.id}_channels.txt', mode='r') as file:\r\n channels = await file.read()\r\n await state.update_data(channels=channels.splitlines())\r\n await message.answer(\"Отправьте ipv4 SOCK55 прокси в формате:\\nip:port:username:password\")\r\n await CalcStates.proxy.set()\r\n\r\n\r\n@dp.message_handler(state=CalcStates.proxy)\r\nasync def get_proxy(message, state: FSMContext):\r\n await state.update_data(proxy=message.text)\r\n await message.answer(\"Сколько задержку между комментированием?\")\r\n await CalcStates.time_.set()\r\n\r\n\r\n@dp.message_handler(state=CalcStates.time_)\r\nasync def get_time_(message, state: FSMContext):\r\n await state.update_data(time_=message.text)\r\n await message.answer(\"Хотите поменять имя с фамилией аккаунта? Для этого напишите имя фамилия(через пробел), \"\r\n \"или напишите -(если не хотите изменять)\")\r\n await CalcStates.name.set()\r\n\r\n\r\n@dp.message_handler(state=CalcStates.name)\r\nasync def set_name_(message, state: FSMContext):\r\n if message.text != \"-\":\r\n data = await state.get_data()\r\n session = data.get(\"session\")\r\n result = await set_name(session, message.text)\r\n await message.answer(result)\r\n await message.answer(\"Хотите поменять фото аккаунта? напишите -, если не хотите изменять\")\r\n await CalcStates.photo.set()\r\n\r\n\r\n@dp.message_handler(content_types=['photo', 'text'], state=CalcStates.photo)\r\nasync def set_photo_(message, state: FSMContext):\r\n if message.text != \"-\":\r\n file_info = await bot.get_file(message.photo[-1].file_id)\r\n file_ext = file_info.file_path.split(\".\")[-1]\r\n await message.photo[-1].download(f\"./photo/{message.from_user.id}.{file_ext}\")\r\n # await bot.download_file(message.photo.path, destination=f\"./photo/{message.from_user.id}.jpg\")\r\n data = await state.get_data()\r\n session = data.get(\"session\")\r\n result = await set_photo(session)\r\n await message.answer(result)\r\n await message.answer(\"Хотите поменять описание аккаунта? напишите -, если не хотите изменять\")\r\n await CalcStates.description.set()\r\n\r\n\r\n@dp.message_handler(state=CalcStates.description)\r\nasync def set_description_(message, state: FSMContext):\r\n data = await state.get_data()\r\n session = data.get(\"session\")\r\n channels = data.get(\"channels\")\r\n sleep = data.get(\"sleep\")\r\n time_ = data.get(\"time_\")\r\n api_id = data.get(\"api_id\")\r\n api_hash = data.get(\"api_hash\")\r\n promt = data.get(\"promt\")\r\n proxy = data.get('proxy')\r\n if message.text != \"-\":\r\n result = await set_description(session, message.text)\r\n await message.answer(result)\r\n\r\n await message.answer(\"Подождите, добавляю в группы...\")\r\n try:\r\n configs = get_files(f'./config/{message.from_user.id}/', '.ini')\r\n sessions = get_files(f'./session/{message.from_user.id}/', '.session')\r\n await state.update_data(sessions=len(sessions))\r\n await state.update_data(configs=len(configs))\r\n async with async_open(f'./config/{message.from_user.id}/config_{message.from_user.id}_{len(configs) + 1}.ini',\r\n mode='w+') as configfile:\r\n await configfile.write(\r\n f\"[SETTINGS]\\nname_session = {f'{session}_{len(sessions)}'}\\napi_id = {api_id}\\napi_hash = {api_hash}\\n\"\r\n f\"promt = {promt}\\nloop_account = {sleep}\\ntime = {time_}\\nproxy = {proxy}\")\r\n path_ = f\"./config/{message.from_user.id}/config_{message.from_user.id}_{len(configs) + 1}.ini\"\r\n await joined_channels(session + f\"/{session}_{len(sessions)}\", channels)\r\n except (FileNotFoundError, FileExistsError):\r\n os.makedirs(f'./config/{message.from_user.id}/')\r\n await state.update_data(configs=0)\r\n async with async_open(f'./config/{message.from_user.id}/config_{message.from_user.id}_1.ini',\r\n mode='w+') as configfile:\r\n await configfile.write(f\"[SETTINGS]\\nname_session = {session}_1\\napi_id = {api_id}\\napi_hash = {api_hash}\\n\"\r\n f\"promt = {promt}\\nloop_account = {sleep}\\ntime = {time_}\\nproxy = {proxy}\")\r\n path_ = f\"./config/{message.from_user.id}/config_{message.from_user.id}_1.ini\"\r\n await joined_channels(session + f\"/{session}_1\", channels)\r\n await state.finish()\r\n config.read(path_, encoding=\"UTF-8\")\r\n process = multiprocessing.Process(target=run_async_function,\r\n args=(config['SETTINGS']['name_session'],\r\n config['SETTINGS']['api_id'],\r\n config['SETTINGS']['api_hash'],\r\n config['SETTINGS']['proxy'],\r\n config['SETTINGS']['time'],\r\n config['SETTINGS']['loop_account'],\r\n config['SETTINGS']['promt']))\r\n process.start()\r\n await message.answer('Хотите ли вы добавить ещё сессии? '\r\n 'Напишите \"-\" если нет, любой другой ответ будет воспринят за согласие')\r\n await CalcStates.answer_user.set()\r\n\r\n\r\n@dp.message_handler(state=CalcStates.answer_user)\r\nasync def get_answer_user(message, state: FSMContext):\r\n await state.update_data(answer_user=message.text)\r\n if message.text != '-':\r\n await message.answer('Пришлите сессию')\r\n await CalcStates.session.set()\r\n else:\r\n await message.answer('Готово')\r\n await state.finish()\r\n\r\n\r\n@dp.message_handler(commands=['edit'])\r\nasync def edit_channels(message):\r\n await message.answer('Пришли новый список каналов в txt файле')\r\n await CalcStates.update_channels.set()\r\n\r\n\r\n@dp.message_handler(content_types=['document'], state=CalcStates.update_channels)\r\nasync def get_new_channels(message, state: FSMContext):\r\n await message.document.download(destination_file=f\"./channels/{message.from_user.id}_channels.txt\")\r\n async with async_open(f'./channels/{message.from_user.id}_channels.txt', mode='r') as file:\r\n channels = await file.read()\r\n await message.answer('Список каналов изменён')\r\n await state.finish()\r\n await joined_channels(message.from_user.id, channels.splitlines())\r\n\r\n\r\n@dp.message_handler(commands=['show'])\r\nasync def show_account(message):\r\n try:\r\n info = \"----------------Запущенные аккаунты----------------\\n\"\r\n for i in get_file(f\"./config/{message.from_user.id}/\"):\r\n config.read(f\"./config/{message.from_user.id}/{i}\")\r\n info += config['SETTINGS']['name_session'] + \" - Аккаунт\\n\" + config['SETTINGS']['proxy'] + \" - proxy\\n\\n\"\r\n await message.answer(info)\r\n except TypeError:\r\n await message.answer(\"У тебя ничего не запущено :(\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n executor.start_polling(dispatcher=dp,\r\n skip_updates=True)\r\n","repo_name":"CCLIX259/botgpt","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"18929388920","text":"__author__ = 'leena'\n\nfrom . import app, celeryd\nfrom .sender import publish_msg, subscribe_msg\n\n\n@celeryd.task(priority=0)\ndef transform_data(source_q, dest_q):\n if isinstance(source_q, list) and isinstance(dest_q, list):\n for source, dest in zip(source_q, dest_q):\n app.logger.info(\"{source} > {dest}\".format(source=source, dest=dest))\n publish_msg(source, dest)\n else:\n publish_msg(source_q, dest_q)\n\n\n@celeryd.task(priority=1)\ndef subscribe_data():\n subscribe_msg()\n\n","repo_name":"abdullah-chhatra/bazzinga","sub_path":"libapp/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"23869463564","text":"\r\n__name__ = [\"utils\"]\r\n\r\n\r\n##################################################################\r\n#\r\n# lists and collections utility functions:\r\n#\r\n#\r\n\r\ndef is_item_list( item ):\r\n return ( isinstance(item, list) or \\\r\n isinstance(item, tuple) )\r\n\r\n \r\n\r\ndef is_item_in_sub_lists( list_, item ):\r\n if (not is_item_list(list_) ) and \\\r\n (not is_item_list(item) ):\r\n raise TypeError()\r\n else:\r\n bol = False\r\n for i in list_:\r\n bol2 = False\r\n if is_item_list(i):\r\n if len(i) == len(item):\r\n blst = list()\r\n bol2 = True\r\n for j in range(0, len(i)):\r\n blst.append( i[j] == item[j] )\r\n for j in range(0, len(i)):\r\n if blst[j] == False:\r\n bol2 = False\r\n if bol2 == True:\r\n bol = bol2\r\n return bol\r\n \r\ndef is_item_in_list( list_, item ):\r\n if not is_item_list(list_):\r\n raise TypeError()\r\n elif not is_item_list(item):\r\n return item in list_\r\n else:\r\n return is_item_in_sub_lists(list_, item)\r\n\r\n#\r\n#\r\n################################################################\r\n\r\n\r\n################################################################\r\n#\r\n# String/Collection Generator Fuctions:\r\n#\r\n\r\ndef gen_str( n, chars ):\r\n \"\"\" generate all possible n length strings of chars \"\"\"\r\n \"\"\" - uses recursion - \"\"\"\r\n if is_item_list(chars) and isinstance(n,int):\r\n res = list()\r\n if n == 1:\r\n for i in chars:\r\n t = list()\r\n t.append(i)\r\n res.append(t)\r\n elif n > 1:\r\n t1 = gen_str( n-1, chars )\r\n for i in chars:\r\n for j in t1:\r\n t = list()\r\n t.append(i)\r\n t.extend(j)\r\n res.append(t)\r\n return res\r\n else:\r\n raise TypeError()\r\n\r\ndef gen_str1( n , chars ):\r\n \"\"\" generate all possible n length strings of chars \"\"\"\r\n \"\"\" - does not use recursion - \"\"\"\r\n if is_item_list(chars) and isinstance(n,int):\r\n res = list()\r\n for i in range(0, n):\r\n if i == 0:\r\n for j in chars:\r\n t = list()\r\n t.append(j)\r\n res.append(t)\r\n else:\r\n tmp = list()\r\n for j in chars:\r\n for k in res:\r\n t = list()\r\n t.extend(k)\r\n t.append(j)\r\n tmp.append(t)\r\n res = tmp\r\n return res\r\n else:\r\n raise TypeError()\r\n\r\ndef gen_list( max_chars, pos_chars, min_chars = 1 ):\r\n result = list()\r\n if not is_item_list(pos_chars) or not isinstance(max_chars,int) \\\r\n or not isinstance(min_chars,int):\r\n raise TypeError()\r\n elif min_chars > 0 and max_chars > min_chars:\r\n for i in range(min_chars, max_chars + 1):\r\n tmp = gen_str1(i, pos_chars)\r\n result.extend(tmp)\r\n return result\r\n else:\r\n raise ValueError()\r\n\r\ndef gen_replace_str( n , inp, repl ):\r\n \"\"\" generate all possible replacement strings of inp using repl \"\"\"\r\n \"\"\" - uses recursion - \"\"\"\r\n if is_item_list(inp) and isinstance(n,int) \\\r\n and isinstance(repl,dict):\r\n res = list()\r\n chars = repl[ inp[ n ] ]\r\n if n == 0:\r\n for i in chars:\r\n t = list()\r\n t.append(i)\r\n res.append(t)\r\n elif n > 0:\r\n t1 = gen_replace_str( n - 1, inp, repl )\r\n for i in chars:\r\n for j in t1:\r\n t = list()\r\n t.append(i)\r\n t.extend(j)\r\n res.append(t)\r\n return res\r\n else:\r\n raise TypeError()\r\n \r\n\r\n\r\ndef gen_replace_str1( inp, repl ):\r\n \"\"\" generate all possible replacement strings of inp using repl \"\"\"\r\n \"\"\" - does not use recursion - \"\"\"\r\n if is_item_list(inp) and isinstance(repl,dict):\r\n res = list()\r\n for i in range(0, len(inp) ):\r\n chars = repl[ inp[ i ] ]\r\n if i == 0:\r\n for j in chars:\r\n t = list()\r\n t.append(j)\r\n res.append(t)\r\n else:\r\n tmp = list()\r\n for j in chars:\r\n for k in res:\r\n t = list()\r\n t.extend(k)\r\n t.append(j)\r\n tmp.append(t)\r\n res = tmp\r\n return res\r\n else:\r\n raise TypeError()\r\n\r\n\r\ndef gen_actual(list_, repl_map):\r\n \"\"\" WARNING!!! this fuction may use A LOT of memory \"\"\"\r\n \"\"\" and may crash python!!!\"\"\"\r\n results = list()\r\n for i in list_:\r\n j = gen_replace_str1( i, repl_map )\r\n results.extend(j)\r\n return results\r\n\r\ndef gen_actual_file(list_, repl_map, path, encoding_='utf-8'):\r\n results = 0\r\n f = open(path, \"w\", encoding=encoding_)\r\n for i in list_:\r\n t1 = gen_replace_str1( i, repl_map )\r\n for j in t1:\r\n print(j, file=f)\r\n results += 1\r\n return results\r\n\r\n\r\n\r\n\r\n#\r\n#\r\n################################################################\r\n\r\n","repo_name":"shlomo-Kallner/coventreiya","sub_path":"old/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"71327921137","text":"# loading packages\n\nimport pandas as pd\nimport numpy as np\n\n#\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\n#\n\nimport seaborn as sns\nimport plotly.express as px\n\n#\n\nimport os\nimport random\nimport re\nimport math\nimport time\n\nfrom tqdm import tqdm\nfrom tqdm.keras import TqdmCallback\n\n\nfrom pandas_summary import DataFrameSummary\n\nimport warnings\n\n\nwarnings.filterwarnings('ignore') # Disabling warnings for clearer outputs\n\n\n\nseed_val = 42\nrandom.seed(seed_val)\nnp.random.seed(seed_val)\n# Setting color palette.\norange_black = [\n '#fdc029', '#df861d', '#FF6347', '#aa3d01', '#a30e15', '#800000', '#171820'\n]\n\n# Setting plot styling.\nplt.style.use('ggplot')\n# Setting file paths for our notebook:\n\nbase_path = '/kaggle/input/siim-isic-melanoma-classification'\ntrain_img_path = '/kaggle/input/siim-isic-melanoma-classification/jpeg/train/'\ntest_img_path = '/kaggle/input/siim-isic-melanoma-classification/jpeg/test/'\nimg_stats_path = '/kaggle/input/melanoma2020imgtabular'\n\ntrain = pd.read_csv(os.path.join(base_path, 'train.csv'))\ntest = pd.read_csv(os.path.join(base_path, 'test.csv'))\nsample = pd.read_csv(os.path.join(base_path, 'sample_submission.csv'))\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nimport efficientnet.tfkeras as efn\nfrom kaggle_datasets import KaggleDatasets\n\ntf.random.set_seed(seed_val)\n# Loading image storage buckets\n\nGCS_PATH = KaggleDatasets().get_gcs_path('melanoma-384x384')\nfilenames_train = np.array(tf.io.gfile.glob(GCS_PATH + '/train*.tfrec'))\nfilenames_test = np.array(tf.io.gfile.glob(GCS_PATH + '/test*.tfrec'))\n# Setting TPU as main device for training, if you get warnings while working with tpu's ignore them.\n\nDEVICE = 'TPU'\nif DEVICE == 'TPU':\n print('connecting to TPU...')\n try: \n tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n print('Running on TPU ', tpu.master())\n except ValueError:\n print('Could not connect to TPU')\n tpu = None\n\n if tpu:\n try:\n print('Initializing TPU...')\n tf.config.experimental_connect_to_cluster(tpu)\n tf.tpu.experimental.initialize_tpu_system(tpu)\n strategy = tf.distribute.experimental.TPUStrategy(tpu)\n print('TPU initialized')\n except _:\n print('Failed to initialize TPU!')\n else:\n DEVICE = 'GPU'\n\nif DEVICE != 'TPU':\n print('Using default strategy for CPU and single GPU')\n strategy = tf.distribute.get_strategy()\n\nif DEVICE == 'GPU':\n print('Num GPUs Available: ',\n len(tf.config.experimental.list_physical_devices('GPU')))\n\nprint('REPLICAS: ', strategy.num_replicas_in_sync)\nAUTO = tf.data.experimental.AUTOTUNE\ncfg = dict(\n batch_size=64,\n img_size=384,\n \n lr_start=0.00001,\n lr_max=0.00000125,\n lr_min=0.000001,\n lr_rampup=5,\n lr_sustain=0,\n lr_decay=0.8,\n epochs=15,\n \n transform_prob=1.0,\n rot=180.0,\n shr=2.0,\n hzoom=8.0,\n wzoom=8.0,\n hshift=8.0,\n wshift=8.0,\n \n optimizer='adam',\n label_smooth_fac=0.05,\n tta_steps=20\n \n )\ndef get_mat(rotation, shear, height_zoom, width_zoom, height_shift,\n width_shift):\n \n ''' Settings for image preparations '''\n\n # CONVERT DEGREES TO RADIANS\n rotation = math.pi * rotation / 180.\n shear = math.pi * shear / 180.\n\n # ROTATION MATRIX\n c1 = tf.math.cos(rotation)\n s1 = tf.math.sin(rotation)\n one = tf.constant([1], dtype='float32')\n zero = tf.constant([0], dtype='float32')\n rotation_matrix = tf.reshape(\n tf.concat([c1, s1, zero, -s1, c1, zero, zero, zero, one], axis=0),\n [3, 3])\n\n # SHEAR MATRIX\n c2 = tf.math.cos(shear)\n s2 = tf.math.sin(shear)\n shear_matrix = tf.reshape(\n tf.concat([one, s2, zero, zero, c2, zero, zero, zero, one], axis=0),\n [3, 3])\n\n # ZOOM MATRIX\n zoom_matrix = tf.reshape(\n tf.concat([\n one / height_zoom, zero, zero, zero, one / width_zoom, zero, zero,\n zero, one\n ],\n axis=0), [3, 3])\n\n # SHIFT MATRIX\n shift_matrix = tf.reshape(\n tf.concat(\n [one, zero, height_shift, zero, one, width_shift, zero, zero, one],\n axis=0), [3, 3])\n\n return K.dot(K.dot(rotation_matrix, shear_matrix),\n K.dot(zoom_matrix, shift_matrix))\n\n\ndef transform(image, cfg):\n \n ''' This function takes input images of [: , :, 3] sizes and returns them as randomly rotated, sheared, shifted and zoomed. '''\n\n DIM = cfg['img_size']\n XDIM = DIM % 2 # fix for size 331\n\n rot = cfg['rot'] * tf.random.normal([1], dtype='float32')\n shr = cfg['shr'] * tf.random.normal([1], dtype='float32')\n h_zoom = 1.0 + tf.random.normal([1], dtype='float32') / cfg['hzoom']\n w_zoom = 1.0 + tf.random.normal([1], dtype='float32') / cfg['wzoom']\n h_shift = cfg['hshift'] * tf.random.normal([1], dtype='float32')\n w_shift = cfg['wshift'] * tf.random.normal([1], dtype='float32')\n\n # GET TRANSFORMATION MATRIX\n m = get_mat(rot, shr, h_zoom, w_zoom, h_shift, w_shift)\n\n # LIST DESTINATION PIXEL INDICES\n x = tf.repeat(tf.range(DIM // 2, -DIM // 2, -1), DIM)\n y = tf.tile(tf.range(-DIM // 2, DIM // 2), [DIM])\n z = tf.ones([DIM * DIM], dtype='int32')\n idx = tf.stack([x, y, z])\n\n # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n idx2 = K.dot(m, tf.cast(idx, dtype='float32'))\n idx2 = K.cast(idx2, dtype='int32')\n idx2 = K.clip(idx2, -DIM // 2 + XDIM + 1, DIM // 2)\n\n # FIND ORIGIN PIXEL VALUES\n idx3 = tf.stack([DIM // 2 - idx2[0, ], DIM // 2 - 1 + idx2[1, ]])\n d = tf.gather_nd(image, tf.transpose(idx3))\n\n return tf.reshape(d, [DIM, DIM, 3])\n\ndef prepare_image(img, cfg=None, augment=True):\n \n ''' This function loads the image, resizes it, casts a tensor to a new type float32 in our case, transforms it using the function just above, then applies the augmentations.'''\n \n img = tf.image.decode_jpeg(img, channels=3)\n img = tf.image.resize(img, [cfg['img_size'], cfg['img_size']],\n antialias=True)\n img = tf.cast(img, tf.float32) / 255.0\n\n if augment:\n if cfg['transform_prob'] > tf.random.uniform([1], minval=0, maxval=1):\n img = transform(img, cfg)\n\n img = tf.image.random_flip_left_right(img)\n img = tf.image.random_saturation(img, 0.7, 1.3)\n img = tf.image.random_contrast(img, 0.8, 1.2)\n img = tf.image.random_brightness(img, 0.1)\n\n return img\ndef read_labeled_tfrecord(example):\n LABELED_TFREC_FORMAT = {\n 'image': tf.io.FixedLenFeature([], tf.string),\n 'image_name': tf.io.FixedLenFeature([], tf.string),\n 'patient_id': tf.io.FixedLenFeature([], tf.int64),\n 'sex': tf.io.FixedLenFeature([], tf.int64),\n 'age_approx': tf.io.FixedLenFeature([], tf.int64),\n 'anatom_site_general_challenge': tf.io.FixedLenFeature([], tf.int64),\n 'diagnosis': tf.io.FixedLenFeature([], tf.int64),\n 'target': tf.io.FixedLenFeature([], tf.int64),\n 'width': tf.io.FixedLenFeature([], tf.int64),\n 'height': tf.io.FixedLenFeature([], tf.int64)\n }\n\n example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n return example['image'], example['target']\n\n\ndef read_unlabeled_tfrecord(example):\n UNLABELED_TFREC_FORMAT = {\n 'image': tf.io.FixedLenFeature([], tf.string),\n 'image_name': tf.io.FixedLenFeature([], tf.string),\n 'patient_id': tf.io.FixedLenFeature([], tf.int64),\n 'sex': tf.io.FixedLenFeature([], tf.int64),\n 'age_approx': tf.io.FixedLenFeature([], tf.int64),\n 'anatom_site_general_challenge': tf.io.FixedLenFeature([], tf.int64),\n }\n example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n return example['image'], example['image_name']\n\ndef count_data_items(filenames):\n n = [\n int(re.compile(r'-([0-9]*)\\.').search(filename).group(1))\n for filename in filenames\n ]\n return np.sum(n)\ndef getTrainDataset(files, cfg, augment=True, shuffle=True):\n \n ''' This function reads the tfrecord train images, shuffles them, apply augmentations to them and prepares the data for training. '''\n \n ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)\n ds = ds.cache()\n\n if shuffle:\n opt = tf.data.Options()\n opt.experimental_deterministic = False\n ds = ds.with_options(opt)\n\n ds = ds.map(read_labeled_tfrecord, num_parallel_calls=AUTO)\n ds = ds.repeat()\n if shuffle:\n ds = ds.shuffle(2048)\n ds = ds.map(lambda img, label:\n (prepare_image(img, augment=augment, cfg=cfg), label),\n num_parallel_calls=AUTO)\n ds = ds.batch(cfg['batch_size'] * strategy.num_replicas_in_sync)\n ds = ds.prefetch(AUTO)\n return ds\n\ndef getTestDataset(files, cfg, augment=False, repeat=False):\n \n ''' This function reads the tfrecord test images and prepares the data for predicting. '''\n \n ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)\n ds = ds.cache()\n if repeat:\n ds = ds.repeat()\n ds = ds.map(read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n ds = ds.map(lambda img, idnum:\n (prepare_image(img, augment=augment, cfg=cfg), idnum),\n num_parallel_calls=AUTO)\n ds = ds.batch(cfg['batch_size'] * strategy.num_replicas_in_sync)\n ds = ds.prefetch(AUTO)\n return ds\n\ndef get_model():\n \n ''' This function gets the layers inclunding efficientnet ones. '''\n \n model_input = tf.keras.Input(shape=(cfg['img_size'], cfg['img_size'], 3),\n name='img_input')\n\n dummy = tf.keras.layers.Lambda(lambda x: x)(model_input)\n\n x = efn.EfficientNetB3(include_top=False, # USE WHICHEVER YOU WANT HERE\n weights='noisy-student',\n input_shape=(cfg['img_size'], cfg['img_size'], 3),\n pooling='avg')(dummy) \n x = tf.keras.layers.Dense(1, activation='sigmoid')(x)\n \n model = tf.keras.Model(model_input, x)\n model.summary()\n return model\ndef compileNewModel(cfg, model):\n \n ''' Configuring the model with losses and metrics. ''' \n\n with strategy.scope():\n model.compile(optimizer=cfg['optimizer'],\n loss=[\n tf.keras.losses.BinaryCrossentropy(\n label_smoothing=cfg['label_smooth_fac'])\n ],\n metrics=[tf.keras.metrics.AUC(name='auc')])\n return model\n\ndef getLearnRateCallback(cfg):\n \n ''' Using callbacks for learning rate adjustments. '''\n \n lr_start = cfg['lr_start']\n lr_max = cfg['lr_max'] * strategy.num_replicas_in_sync * cfg['batch_size']\n lr_min = cfg['lr_min']\n lr_rampup = cfg['lr_rampup']\n lr_sustain = cfg['lr_sustain']\n lr_decay = cfg['lr_decay']\n\n def lrfn(epoch):\n if epoch < lr_rampup:\n lr = (lr_max - lr_start) / lr_rampup * epoch + lr_start\n elif epoch < lr_rampup + lr_sustain:\n lr = lr_max\n else:\n lr = (lr_max - lr_min) * lr_decay**(epoch - lr_rampup -\n lr_sustain) + lr_min\n return lr\n\n lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=False)\n return lr_callback\n\ndef learnModel(model, ds_train, stepsTrain, cfg, ds_val=None, stepsVal=0):\n \n ''' Fitting things together for training '''\n \n callbacks = [getLearnRateCallback(cfg)]\n\n history = model.fit(ds_train,\n validation_data=ds_val,\n verbose=1,\n steps_per_epoch=stepsTrain,\n validation_steps=stepsVal,\n epochs=cfg['epochs'],\n callbacks=callbacks)\n\n return history\nds_train = getTrainDataset(\n filenames_train, cfg).map(lambda img, label: (img, label))#(label, label, label, label)))\nstepsTrain = count_data_items(filenames_train) / \\\n (cfg['batch_size'] * strategy.num_replicas_in_sync)\nwith strategy.scope():\n model = get_model()\n\nmodel = compileNewModel(cfg, model)\nhistory = learnModel(model, ds_train, stepsTrain, cfg)\ncfg['optimizer']='sgd'\nwith strategy.scope():\n model1 = get_model()\n\nmodel1 = compileNewModel(cfg, model1)\nhistory1 = learnModel(model1, ds_train, stepsTrain, cfg)\nimport tensorflow as tf\nfrom tensorflow.python.keras.optimizer_v2.optimizer_v2 import OptimizerV2\n\n\nclass AdaBound(OptimizerV2):\n \"\"\"AdaBound optimizer.\n Default parameters follow those provided in the original paper.\n # Arguments\n learning_rate: float >= 0. Learning rate.\n final_learning_rate: float >= 0. Final learning rate.\n beta_1: float, 0 < beta < 1. Generally close to 1.\n beta_2: float, 0 < beta < 1. Generally close to 1.\n gamma: float >= 0. Convergence speed of the bound function.\n epsilon: float >= 0. Fuzz factor. If `None`, defaults to `K.epsilon()`.\n decay: float >= 0. Learning rate decay over each update.\n weight_decay: Weight decay weight.\n amsbound: boolean. Whether to apply the AMSBound variant of this\n algorithm.\n # References\n - [Adaptive Gradient Methods with Dynamic Bound of Learning Rate]\n (https://openreview.net/forum?id=Bkg3g2R9FX)\n - [Adam - A Method for Stochastic Optimization]\n (https://arxiv.org/abs/1412.6980v8)\n - [On the Convergence of Adam and Beyond]\n (https://openreview.net/forum?id=ryQu7f-RZ)\n \"\"\"\n def __init__(self,\n learning_rate=0.001,\n final_learning_rate=0.1,\n beta_1=0.9,\n beta_2=0.999,\n gamma=1e-3,\n epsilon=None,\n weight_decay=0.0,\n amsbound=False,\n name='AdaBound', **kwargs):\n super(AdaBound, self).__init__(name, **kwargs)\n\n self._set_hyper('learning_rate', kwargs.get('learning_rate', learning_rate))\n self._set_hyper('final_learning_rate', kwargs.get('final_learning_rate', final_learning_rate))\n self._set_hyper('beta_1', beta_1)\n self._set_hyper('beta_2', beta_2)\n self._set_hyper('decay', self._initial_decay)\n self._set_hyper('gamma', gamma)\n self.epsilon = epsilon or tf.keras.backend.epsilon()\n self.amsbound = amsbound\n self.weight_decay = weight_decay\n self.base_lr = learning_rate\n\n def _create_slots(self, var_list):\n for var in var_list:\n self.add_slot(var, 'm')\n self.add_slot(var, 'v')\n self.add_slot(var, 'vhat')\n\n def _resource_apply_dense(self, grad, var):\n var_dtype = var.dtype.base_dtype\n lr_t = self._decayed_lr(var_dtype)\n\n m = self.get_slot(var, 'm')\n v = self.get_slot(var, 'v')\n vhat = self.get_slot(var, 'vhat')\n\n beta_1_t = self._get_hyper('beta_1', var_dtype)\n beta_2_t = self._get_hyper('beta_2', var_dtype)\n\n gamma = self._get_hyper('gamma')\n final_lr = self._get_hyper('final_learning_rate')\n\n epsilon_t = tf.convert_to_tensor(self.epsilon, var_dtype)\n base_lr_t = tf.convert_to_tensor(self.base_lr)\n t = tf.cast(self.iterations + 1, var_dtype)\n\n # Applies bounds on actual learning rate\n step_size = lr_t * (tf.math.sqrt(1. - tf.math.pow(beta_2_t, t)) /\n (1. - tf.math.pow(beta_1_t, t)))\n\n final_lr = final_lr * lr_t / base_lr_t\n lower_bound = final_lr * (1. - 1. / (gamma * t + 1.))\n upper_bound = final_lr * (1. + 1. / (gamma * t))\n\n # apply weight decay\n if self.weight_decay != 0.:\n grad += self.weight_decay * var\n\n # Compute moments\n m_t = (beta_1_t * m) + (1. - beta_1_t) * grad\n v_t = (beta_2_t * v) + (1. - beta_2_t) * tf.math.square(grad)\n\n if self.amsbound:\n vhat_t = tf.math.maximum(vhat, v_t)\n denom = (tf.math.sqrt(vhat_t) + epsilon_t)\n else:\n vhat_t = vhat\n denom = (tf.math.sqrt(v_t) + self.epsilon)\n\n # Compute the bounds\n step_size_p = step_size * tf.ones_like(denom)\n step_size_p_bound = step_size_p / denom\n bounded_lr_t = m_t * tf.math.minimum(tf.math.maximum(step_size_p_bound,\n lower_bound), upper_bound)\n\n # Setup updates\n m_t = tf.compat.v1.assign(m, m_t)\n vhat_t = tf.compat.v1.assign(vhat, vhat_t)\n\n with tf.control_dependencies([m_t, v_t, vhat_t]):\n p_t = var - bounded_lr_t\n param_update = tf.compat.v1.assign(var, p_t)\n\n return tf.group(*[param_update, m_t, v_t, vhat_t])\n\n def _resource_apply_sparse(self, grad, handle, indices):\n raise NotImplementedError(\"Sparse data is not supported yet\")\n\n def get_config(self):\n config = super(AdaBound, self).get_config()\n config.update({\n 'learning_rate': self._serialize_hyperparameter('learning_rate'),\n 'final_learning_rate': self._serialize_hyperparameter('final_learning_rate'),\n 'decay': self._serialize_hyperparameter('decay'),\n 'beta_1': self._serialize_hyperparameter('beta_1'),\n 'beta_2': self._serialize_hyperparameter('beta_2'),\n 'gamma': self._serialize_hyperparameter('gamma'),\n 'epsilon': self.epsilon,\n 'weight_decay': self.weight_decay,\n 'amsbound': self.amsbound,\n })\n return config\ncfg['optimizer'] = AdaBoundaBoundaBoost(amsbound=False)\nwith strategy.scope():\n model2 = get_model()\n\nmodel2 = compileNewModel(cfg, model2)\nhistory2 = learnModel(model2, ds_train, stepsTrain, cfg)\ncfg['optimizer'] = 'adam'\ncfg['epochs'] = 25\nwith strategy.scope():\n model2 = get_model()\n\nmodel2 = compileNewModel(cfg, model2)\nhistory2 = learnModel(model2, ds_train, stepsTrain, cfg)\ncfg['epochs'] = 1\nhistory2 = learnModel(model2, ds_train, stepsTrain, cfg)\nauc = history2.history['auc']\nloss = history2.history['loss']\nepochs_range = range(cfg['epochs'])\n\nplt.figure(figsize=(12, 6))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, auc, label='adam')\n\nplt.legend(loc='lower right')\nplt.title('Training and AUC')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='adam')\n\nplt.legend(loc='upper right')\nplt.title('Training Loss')\nplt.show()\nauc = history.history['auc']\nloss = history.history['loss']\nauc1 = history1.history['auc']\nloss1 = history1.history['loss']\nauc2 = history2.history['auc']\nloss2 = history2.history['loss']\nepochs_range = range(cfg['epochs'])\n\nplt.figure(figsize=(12, 6))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, auc, label='adam')\nplt.plot(epochs_range, auc1, label='sgd')\nplt.plot(epochs_range, auc2, label='adabound')\n\nplt.legend(loc='lower right')\nplt.title('Training and AUC')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='adam')\nplt.plot(epochs_range, loss1, label='sgd')\nplt.plot(epochs_range, loss2, label='adabound')\n\nplt.legend(loc='upper right')\nplt.title('Training Loss')\nplt.show()\ncfg['batch_size'] = 95\nsteps = count_data_items(filenames_test) / \\\n (cfg['batch_size'] * strategy.num_replicas_in_sync)\nz = np.zeros((cfg['batch_size'] * strategy.num_replicas_in_sync))\nds_testAug = getTestDataset(\n filenames_test, cfg, augment=True,\n repeat=True).map(lambda img, label: (img, z))#(z, z, z, z)))\nprobs = model2.predict(ds_testAug, verbose=1, steps=steps * cfg['tta_steps'])\nprobs = np.stack(probs)\nprobs = probs[:, :count_data_items(filenames_test) * cfg['tta_steps']]\nprobs = np.stack(np.split(probs, cfg['tta_steps']), axis=1)\nprobs = np.mean(probs, axis=1)\n\ntest = pd.read_csv(os.path.join(base_path, 'test.csv'))\ny_test_sorted = np.zeros((1, probs.shape[1]))\ntest = test.reset_index()\ntest = test.set_index('image_name')\n\n\nds_test = getTestDataset(filenames_test, cfg)\n\nimage_names = np.array([img_name.numpy().decode(\"utf-8\") \n for img, img_name in iter(ds_test.unbatch())])\nfor i in range(1):\n submission = pd.DataFrame(dict(\n image_name = image_names,\n target = probs[:,0]))\n\n submission = submission.sort_values('image_name') \n submission.to_csv('effnetsB.csv', index=False)","repo_name":"aorursy/new-nb-8","sub_path":"vardan98_single-effnet-testing.py","file_name":"vardan98_single-effnet-testing.py","file_ext":"py","file_size_in_byte":20474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"4536369005","text":"\"\"\"increase_campaign_description_field\n\nRevision ID: c714da18fbbc\nRevises: 2ee06a00e2ca\nCreate Date: 2021-08-19 09:13:57.564654\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c714da18fbbc'\ndown_revision = '2ee06a00e2ca'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.alter_column('campaign', 'description', type_=sa.String, existing_type=sa.TEXT)\n\n\ndef downgrade():\n op.alter_column('campaign', 'description', type_=sa.TEXT, existing_type=sa.String)\n","repo_name":"juanoubi6/printmob-backend","sub_path":"alembic/versions/c714da18fbbc_increase_campaign_description_field.py","file_name":"c714da18fbbc_increase_campaign_description_field.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"11566678564","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\n#here we will not split data set on training and test set because csv fajl that we have\n#is very small so we will work with entire dataset\ndataset = pd.read_csv(\"Position_Salaries.csv\") \nX = dataset.iloc[ :, 1:-1 ].values\nY = dataset.iloc[ :, -1 ].values\n\n\n#feature scaling \n#in SVR we will have to apply feature scalling, because here we dont have coeficients\n#like in linear, multiple and polynomial regression which would allow us not to do \n#scaling, so here we have to do it ourself\n\n#here we will have to do feature scaling on both input and output variable, \n#because salary output variable is in much bigger range then position input variable\n\n#also one reminder if we split data set in test and trening set, we should alwas do \n#feature scaling AFTER spliting set on training and test because test values should\n#not be affected by training values, and that would be the case if we did feature scaling\n#on whole dataset.\n\n\nprint(X)\nprint(Y)\n#here we see that X is two dimentional array, where y is one dimentional array\n#and function that we will use for scaling espexts as input values in two dimentional\n#array format, so we will have to transform Y in two dimentional format first \n#for that we will use reshape function that takes number of rows that we want new transfromted object to have\n#as first paramatere and then number of columns that we want that new transformed object to have\nY = Y.reshape(len(Y), 1) \n\nprint(Y)\n\n#we will use standardisation for feature scaling \nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX = sc_X.fit_transform(X)\n\n#we are not going to use same objet of StandarScaler to scale X input matrix and output Y\n#and reson for that is because when we do this fit on X matrix it will calcute and put\n#mean and standard deviation values of X in sc ojbect, and we dont want to use that values\n#for Y, but we want to calcute mean and standard devation of Y values \nsc_Y = StandardScaler()\nY = sc_Y.fit_transform(Y)\n\nprint(X)\nprint(Y)\n\n\n\n#training SVR model on whole dataset because we didnt split data set on training and test set\n#here in SVR and also in SVM with classifictaion that we will do later, we have kernels\n#which can either learn some linear relathionships and that is linear kernel or non linear relathionships\n#in data set which are non linear kernel, and in SVR we use Radial Basis Kernel and that is this 'rbf'\nfrom sklearn.svm import SVR\nregressor = SVR(kernel='rbf')\n\n#now we have empy SVR model, and now we will train that model\nregressor.fit(X, np.ravel(Y)) \n\n#predicting the results\n#because we did scale Y before, when we run predict method it will predict\n#values in that scale, but we want real prediction with real values not scaled\n#so we will have to reverse the scaling to get predicted values in the original range\n\n#so beacuse our model is learned based on scaled values we will have to scale input values\n#so that prediction will be valid and that is why we are calling scaler sc_X.transform()\n#and we will put value in double brackets [[]] because this function for scaling expexts 2d array\n#and then we will apply reverse scalling to get predicted values in original scale with inverse_transform() and reshape()\nsc_Y.inverse_transform(regressor.predict(sc_X.transform([[6.5]])).reshape(-1,1)) \n\n\n#visualising the SVR results \n#because X and Y values are scaled values, we need to reverse that scaling to original values so plot would be nicer\n#and when we ploting prediction we will not need to scale values for X because they are alredy scaled so we will just insert X \nplt.scatter(sc_X.inverse_transform(X),sc_Y.inverse_transform(Y), color = \"red\")\nplt.plot(sc_X.inverse_transform(X), sc_Y.inverse_transform(regressor.predict(X).reshape(-1,1)) , color=\"blue\")\nplt.title(\"SVR \")\nplt.xlabel(\"Position level\") \nplt.ylabel(\"Salary\") \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"marceta99/MachineLearningPy","sub_path":"Regression/SupportVectorRegression.py","file_name":"SupportVectorRegression.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"19911860179","text":"import ensembl_rest\nimport argparse\nimport subprocess\nimport string\nfrom prettytable import PrettyTable\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-s', help='species')\nparser.add_argument('-g', help='gene')\nparser.add_argument('-p', help='parameter file name')\nparser.add_argument('-t', help='thermal path')\nparser.add_argument('-v', help='verbose output', action='store_true')\nargs = parser.parse_args()\n\nif args.s is None:\n input_species = input('\\nInput species name (e.g. zebrafish): ')\nelse:\n input_species = args.s\n\nif args.g is None:\n input_gene = input('\\nInput gene name (e.g. wnt10a): ')\nelse:\n input_gene = args.g\n\nif args.p is None:\n parameter_file = 'parameters.txt'\nelse:\n parameter_file = args.p\n\ngene = ensembl_rest.symbol_lookup(input_species, input_gene, params={'expand': True})\n\nsplice_count = len(gene['Transcript'])\n\nprint('\\nSpecies:', gene['species'])\nprint('Genome:', gene['assembly_name'])\nprint('Gene name:', gene['display_name'])\nprint('Description:', gene['description'])\nprint('Gene ID:', gene['id'])\nprint('Strand direction:', gene['strand'])\nprint('Splice varaints:', splice_count)\n\nexon_variants = []\nfor sv in range(splice_count):\n summary = gene['Transcript'][sv]\n exon_count = len(summary['Exon'])\n print('\\nSplice variant', sv + 1, '(' + summary['display_name'] + ') has', exon_count, 'exons')\n\n summary['location'] = []\n for x in range(exon_count):\n variant = summary['Exon'][x]\n if args.v:\n print('Exon', str(x + 1) + ':', variant['start'] - gene['start'], '-', variant['end'] - gene['start'])\n summary['location'].append((variant['start'] - gene['start'], variant['end'] - gene['start']))\n\n exon_variants.append(summary)\n\n\ndef exon_values(exon):\n values = set()\n for i, item in enumerate(exon['location']):\n for i in range(item[0], item[1] + 1):\n values.add(i)\n return values\n\n\nwhole_sequence = ensembl_rest.sequence_id(gene['id'])['seq']\nif gene['strand'] == -1:\n whole_sequence = whole_sequence[::-1]\n\n\ndef find_overlaps(variants):\n if splice_count > 1:\n exons = iter(variants)\n values = exon_values(next(exons))\n for exon in exons:\n values.intersection_update(exon_values(exon))\n\n sorted_values = sorted(list(values))\n ranges = []\n for value in sorted_values:\n if ranges and value == ranges[-1][1] + 1:\n ranges[-1] = (ranges[-1][0], value)\n else:\n ranges.append((value, value))\n else:\n ranges = variants[0]['location']\n\n search_sequence = []\n for i in range(len(ranges)):\n start = ranges[i][0]\n end = ranges[i][1]\n if gene['strand'] == 1:\n search_sequence.append(whole_sequence[start:end + 1])\n else:\n search_sequence.append(whole_sequence[start:end + 1][::-1])\n if splice_count > 1:\n search_sequence.reverse()\n\n if splice_count > 1:\n if len(search_sequence) > 0:\n print('\\nFound', len(search_sequence), 'overlapping sequences')\n else:\n print('\\nError: found 0 overlapping sequences')\n indices = [int(i) - 1 for i in input('Manually select splice variants to find overlaps for (e.g. 1,5,12): ').replace(' ', '').split(',')]\n selected_elements = [exon_variants[index] for index in indices]\n search_sequence = find_overlaps(selected_elements)\n return search_sequence\n\n\nsearch_sequence = find_overlaps(exon_variants)\n\nfor i, item in enumerate(search_sequence):\n print('\\nExon', i + 1)\n print(item)\n\nwith open(parameter_file, 'r') as file:\n in_file = file.read().rstrip()\n\n\nprimer_params = {\n 'Primer min size': ['PRIMER_MIN_SIZE='],\n 'Primer opt size': ['PRIMER_OPT_SIZE='],\n 'Primer max size': ['PRIMER_MAX_SIZE='],\n 'Primer min Tm': ['PRIMER_MIN_TM='],\n 'Primer opt Tm': ['PRIMER_OPT_TM='],\n 'Primer max Tm': ['PRIMER_MAX_TM='],\n 'Product size range': ['PRIMER_PRODUCT_SIZE_RANGE='],\n}\n\nfor key, value in primer_params.items():\n original_value = in_file.split(value[0])[1].split('\\n')[0]\n primer_params[key].extend((original_value, original_value))\n\n\ndef selectionMenu():\n parameterList = PrettyTable(['Index', 'Parameter', 'Value'])\n\n for index, (key, value) in enumerate(primer_params.items()):\n parameterList.add_row([index + 1, key, value[1]])\n print('\\nPrimer search parameters:')\n print(parameterList)\n\n response = input('\\nEnter index to edit parameter (or press return): ').lower()\n if response in string.ascii_lowercase:\n return\n else:\n field = list(primer_params)[int(response) - 1]\n value = input(field + ': ')\n primer_params[field][1] = value\n selectionMenu()\n\n\nselectionMenu()\n\njoined_sequence = ''.join(search_sequence)\nif args.v:\n print('\\nSequence sent to primer3:')\n print(joined_sequence)\n\nfor value in primer_params.values():\n in_file = in_file.replace(value[0] + value[2], value[0] + value[1])\n\nin_file = in_file.replace('SEQUENCE_TEMPLATE=', 'SEQUENCE_TEMPLATE=' + joined_sequence)\n\nif args.t is not None:\n config_text = 'PRIMER_THERMODYNAMIC_PARAMETERS_PATH='\n original_value = in_file.split(config_text)[1].split('\\n')[0]\n in_file = in_file.replace(config_text + original_value, config_text + args.t)\n\noutput = subprocess.run(['primer3_core'], stdout=subprocess.PIPE, input=in_file, encoding='ascii')\noutput = output.stdout.replace('\\n', '=').split('=')\n\npair_count = int(output[output.index('PRIMER_PAIR_NUM_RETURNED') + 1])\n\nprint('\\nFound', pair_count, 'primer pairs')\n\n\ndef result_parser(side, i, s_string):\n if side == 1:\n return output[output.index('PRIMER_PAIR_' + str(i) + s_string) + 1]\n else:\n return output[output.index('PRIMER_' + side + '_' + str(i) + s_string) + 1]\n\n\npairs = []\nfor i in range(pair_count):\n primers = {}\n primers['product_size'] = result_parser(1, i, '_PRODUCT_SIZE')\n primers['compl_any'] = result_parser(1, i, '_COMPL_ANY_TH')\n primers['compl_end'] = result_parser(1, i, '_COMPL_END_TH')\n for index, side in enumerate(['LEFT', 'RIGHT']):\n primers[index] = {}\n position = result_parser(side, i, '').split(',')\n primers[index]['start'] = position[0]\n primers[index]['length'] = position[1]\n primers[index]['sequence'] = result_parser(side, i, '_SEQUENCE')\n primers[index]['tm'] = result_parser(side, i, '_TM')\n primers[index]['self_binding_any'] = result_parser(side, i, '_SELF_ANY_TH')\n primers[index]['any_hairpin'] = result_parser(side, i, '_HAIRPIN_TH')\n primers[index]['end_stability'] = result_parser(side, i, '_END_STABILITY')\n primers[index]['gc_percent'] = result_parser(side, i, '_GC_PERCENT')\n pairs.append(primers)\n\nfor index in reversed(range(pair_count)):\n print('\\n\\nPrimer pair', index + 1)\n print('---------------------')\n print('Gene name:', gene['display_name'])\n print('Species:', gene['species'])\n print('Product size:', pairs[index]['product_size'])\n print('Any compl :', pairs[index]['compl_any'])\n print('End compl :', pairs[index]['compl_end'])\n primerList = PrettyTable(['Primer', 'Length', 'Tm', 'GC%', 'Self-binding', 'Hairpin', 'End Stability', 'Sequence'])\n for i, side in enumerate(['Left', 'Right']):\n dict = pairs[index][i]\n primerList.add_row([side, dict['length'], dict['tm'], dict['gc_percent'], dict['self_binding_any'], dict['any_hairpin'], dict['end_stability'], dict['sequence']])\n print(primerList)\n","repo_name":"phenotypic/Primer-Designer","sub_path":"designer.py","file_name":"designer.py","file_ext":"py","file_size_in_byte":7596,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"57"} +{"seq_id":"20483756931","text":"from __future__ import annotations\n\n\nclass Point:\n def __init__(self, x, y, a, b):\n self.a = a\n self.b = b\n self.x = x\n self.y = y\n\n # Coding point at infinity\n if x is None and y is None:\n return\n if y ** 2 != x ** 3 + a * x + b:\n raise ValueError(\"({}, {}) is not on the curve\".format(x, y))\n\n def __eq__(self, other: Point) -> bool:\n return self.a == other.a and self.b == other.b and self.x == other.x and self.y == other.y\n\n def __add__(self, other: Point) -> Point:\n if self.a != other.a and self.b != other.b:\n raise ValueError(\"Points ({}, {}) are not on the same curve\".format(self, other))\n\n # self.x being \"None\" means that self is the point at infinity, \n # or the additive identity. Thus, we return other.\n if self.x is None:\n return other\n\n # other.x being \"None\" means that other is the point at infinity, \n # or the additive identity. Thus, we return self.\n if other.x is None:\n return self\n\n # When two points are additive inverses (that is, they have the same x but \n # a different y, causing a vertical line) we should return the point at infinity.\n if self.x == other.x and self.y != other.y:\n return self.__class__(None, None, self.a, self.b)\n\n # Point Addition for When x1 != x2\n if self.x != other.x:\n # s is the slope of the line passing from P1 and P2\n s = (other.y - self.y) / (other.x - self.x)\n x3 = s ** 2 - self.x - other.x\n y3 = s * (self.x - x3) - self.y\n\n # Point addition when P1 == P2, meaning that the point\n # is tangent to the elliptical curve\n if self == other:\n\n if self.y == 0 * self.x:\n # We cannot simply compare y == 0 (scalar), since\n # if we are using finite fields instead of real numbers,\n # the 0 value must also be a finite field. Mutiplying 0\n # to an other finite field (like self.x) makes this zero\n # coparison work both in real and finite fields\n\n # Special case when the tangent is a vertical line,\n # with undefined slope. The addition will return the\n # Point at infinity\n return self.__class__(None, None, self.a, self.b)\n\n # s is the slope of the tangent point P1 == P2 in the curve\n s = (3 * (self.x ** 2) + self.a) / (2 * self.y)\n x3 = s ** 2 - 2 * self.x\n y3 = s * (self.x - x3) - self.y\n\n return self.__class__(x3, y3, self.a, self.b)\n\n def __rmul__(self, coefficient):\n \"\"\"\n Multiplication with binary expansion that allows us\n to perform multiplications in log2(n) loops\n \"\"\"\n coef = coefficient\n current = self\n result = self.__class__(None, None, self.a, self.b)\n while coef:\n if coef & 1:\n result += current\n current += current\n coef >>= 1\n return result\n\n def __repr__(self):\n return \"Point_{}_{}_({}, {})\".format(self.x, self.y, self.a, self.b)\n","repo_name":"alch/python-bitcoin","sub_path":"bc/point.py","file_name":"point.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"57"} +{"seq_id":"12306872539","text":"from kafka import KafkaProducer\n#Greg - before starting - pip install slackclient\n\nfrom slack import AsyncWebClient as wc\n\n#Greg -- please change to the Ip of your KAFKA cluster and port please\nproducer = KafkaProducer(bootstrap_servers = 'localhost:9092')\n#Greg -- Please use your Oauth token\ntk = \"PLEASE HARD CODE YOUR TOKEN HERE\"\nchan = wc(tk)\nmessage_list = chan.api_call(\"channels.history\", channel=\"random\", oldest=0, count=\"1000\")\nfor m in message_list[\"messages\"]:\n producer.send('random', m)\n producer.flush(30)","repo_name":"meetreks/SaiStudyAll","sub_path":"SaiStudy - Hack2020_prod.py","file_name":"SaiStudy - Hack2020_prod.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"36314019645","text":"from Adafruit_MotorHAT import Adafruit_MotorHAT\n\nimport widget\n\n\nclass AutoGaugeWidget(widget.Widget):\n \"\"\"Automotive gauge stepper motor. Small dual-coil stepper that can travel\n ~315 degrees with 600 steps. Send a numeric value from 0-100 to move the\n dial to the specified percent along its entire range of movement.\n \"\"\"\n\n def __init__(self, motor_id, invert='False'):\n \"\"\"Create an instance of the auto stepper motor. Must provide a motor_id\n parameter with the motor ID from the motor HAT (sent as a string). Can\n optionally provide:\n - invert: Set to True to reverse the forward/backward direction. Set\n this if the motor spins the wrong way when going forward/backward.\n \"\"\"\n # Create stepper motor driver.\n self._mh = Adafruit_MotorHAT()\n self._stepper = self._mh.getStepper(600, int(motor_id))\n self._forward = Adafruit_MotorHAT.FORWARD\n self._backward = Adafruit_MotorHAT.BACKWARD\n if self.parse_bool(invert):\n # Invert forward/backward directions\n self._forward, self._backward = self._backward, self._forward\n # Rotate forward 600 times to get back into a known 0/home state.\n for i in range(600):\n \tself._stepper.oneStep(self._backward, Adafruit_MotorHAT.DOUBLE)\n self._steps = 0\n\n def set_value(self, value):\n \"\"\"Set the value of the gauge. Must pass in a string with a floating\n point value in the range 0-100. The dial will be moved to the specified\n percent location along its range of movement (about 315 degrees).\n \"\"\"\n # Convert the value to a float percentage.\n value = float(value)\n if value < 0.0 or value > 100.0:\n raise RuntimeError('Value must be in range of 0-100!')\n # Figure out how many forward or backward steps need to occur to move\n # to the specified position.\n new_steps = value/100.0*600.0\n delta = int(new_steps - self._steps)\n direction = self._backward if delta < 0 else self._forward\n # Move the required number of steps and update the current step location.\n for i in range(abs(delta)):\n self._stepper.oneStep(direction, Adafruit_MotorHAT.DOUBLE)\n self._steps = new_steps\n","repo_name":"adafruit/Pi_Physical_Dashboard","sub_path":"auto_gauge.py","file_name":"auto_gauge.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"57"} +{"seq_id":"29434944510","text":"import dgl\nimport unittest\nimport os\nfrom dgl.data import CitationGraphDataset\nfrom dgl.distributed.sampling import sample_neighbors\nfrom dgl.distributed import partition_graph, load_partition, load_partition_book\nimport sys\nimport multiprocessing as mp\nimport numpy as np\nimport backend as F\nimport time\nfrom utils import get_local_usable_addr\nfrom pathlib import Path\n\nfrom dgl.distributed import DistGraphServer, DistGraph\n\n\ndef start_server(rank, tmpdir, disable_shared_mem):\n import dgl\n g = DistGraphServer(rank, \"rpc_sampling_ip_config.txt\", 1, \"test_sampling\",\n tmpdir / 'test_sampling.json', disable_shared_mem=disable_shared_mem)\n g.start()\n\n\ndef start_client(rank, tmpdir, disable_shared_mem):\n import dgl\n gpb = None\n if disable_shared_mem:\n _, _, _, gpb = load_partition(tmpdir / 'test_sampling.json', rank)\n dist_graph = DistGraph(\"rpc_sampling_ip_config.txt\", \"test_sampling\", gpb=gpb)\n sampled_graph = sample_neighbors(dist_graph, [0, 10, 99, 66, 1024, 2008], 3)\n dgl.distributed.shutdown_servers()\n dgl.distributed.finalize_client()\n return sampled_graph\n\n\ndef check_rpc_sampling(tmpdir, num_server):\n ip_config = open(\"rpc_sampling_ip_config.txt\", \"w\")\n for _ in range(num_server):\n ip_config.write('{} 1\\n'.format(get_local_usable_addr()))\n ip_config.close()\n\n g = CitationGraphDataset(\"cora\")[0]\n g.readonly()\n print(g.idtype)\n num_parts = num_server\n num_hops = 1\n\n partition_graph(g, 'test_sampling', num_parts, tmpdir,\n num_hops=num_hops, part_method='metis', reshuffle=False)\n\n pserver_list = []\n ctx = mp.get_context('spawn')\n for i in range(num_server):\n p = ctx.Process(target=start_server, args=(i, tmpdir, num_server > 1))\n p.start()\n time.sleep(1)\n pserver_list.append(p)\n\n time.sleep(3)\n sampled_graph = start_client(0, tmpdir, num_server > 1)\n print(\"Done sampling\")\n for p in pserver_list:\n p.join()\n\n src, dst = sampled_graph.edges()\n assert sampled_graph.number_of_nodes() == g.number_of_nodes()\n assert np.all(F.asnumpy(g.has_edges_between(src, dst)))\n eids = g.edge_ids(src, dst)\n assert np.array_equal(\n F.asnumpy(sampled_graph.edata[dgl.EID]), F.asnumpy(eids))\n\n@unittest.skipIf(os.name == 'nt', reason='Do not support windows yet')\n@unittest.skipIf(dgl.backend.backend_name == 'tensorflow', reason='Not support tensorflow for now')\ndef test_rpc_sampling():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n tmpdirname = \"/tmp/sampling\"\n check_rpc_sampling(Path(tmpdirname), 2)\n\ndef check_rpc_sampling_shuffle(tmpdir, num_server):\n ip_config = open(\"rpc_sampling_ip_config.txt\", \"w\")\n for _ in range(num_server):\n ip_config.write('{} 1\\n'.format(get_local_usable_addr()))\n ip_config.close()\n \n g = CitationGraphDataset(\"cora\")[0]\n g.readonly()\n num_parts = num_server\n num_hops = 1\n\n partition_graph(g, 'test_sampling', num_parts, tmpdir,\n num_hops=num_hops, part_method='metis', reshuffle=True)\n\n pserver_list = []\n ctx = mp.get_context('spawn')\n for i in range(num_server):\n p = ctx.Process(target=start_server, args=(i, tmpdir, num_server > 1))\n p.start()\n time.sleep(1)\n pserver_list.append(p)\n\n time.sleep(3)\n sampled_graph = start_client(0, tmpdir, num_server > 1)\n print(\"Done sampling\")\n for p in pserver_list:\n p.join()\n\n orig_nid = F.zeros((g.number_of_nodes(),), dtype=F.int64)\n orig_eid = F.zeros((g.number_of_edges(),), dtype=F.int64)\n for i in range(num_server):\n part, _, _, _ = load_partition(tmpdir / 'test_sampling.json', i)\n orig_nid[part.ndata[dgl.NID]] = part.ndata['orig_id']\n orig_eid[part.edata[dgl.EID]] = part.edata['orig_id']\n\n src, dst = sampled_graph.edges()\n src = orig_nid[src]\n dst = orig_nid[dst]\n assert sampled_graph.number_of_nodes() == g.number_of_nodes()\n assert np.all(F.asnumpy(g.has_edges_between(src, dst)))\n eids = g.edge_ids(src, dst)\n eids1 = orig_eid[sampled_graph.edata[dgl.EID]]\n assert np.array_equal(F.asnumpy(eids1), F.asnumpy(eids))\n\n# Wait non shared memory graph store\n@unittest.skipIf(os.name == 'nt', reason='Do not support windows yet')\n@unittest.skipIf(dgl.backend.backend_name == 'tensorflow', reason='Not support tensorflow for now')\ndef test_rpc_sampling_shuffle():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n tmpdirname = \"/tmp/sampling\"\n check_rpc_sampling_shuffle(Path(tmpdirname), 2)\n check_rpc_sampling_shuffle(Path(tmpdirname), 1)\n\nif __name__ == \"__main__\":\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n tmpdirname = \"/tmp/sampling\"\n check_rpc_sampling_shuffle(Path(tmpdirname), 1)\n check_rpc_sampling_shuffle(Path(tmpdirname), 2)\n check_rpc_sampling(Path(tmpdirname), 2)\n check_rpc_sampling(Path(tmpdirname), 1)\n","repo_name":"xc15071347094/dgl","sub_path":"tests/distributed/test_distributed_sampling.py","file_name":"test_distributed_sampling.py","file_ext":"py","file_size_in_byte":5032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"57"} +{"seq_id":"18648383317","text":"from cv2 import cv2\nimport numpy as np\nimport time\nfrom pynput import mouse, keyboard\nimport pyautogui\n\n\nclass imgRecognize():\n def __init__(self):\n self.tries = 0\n\n def waitForScreen(self, obj):\n while True:\n if pyautogui.locateOnScreen(\"img/{}.png\".format(str(obj)), confidence=0.9, grayscale=True): # Region\n time.sleep(0.5)\n\n coords = pyautogui.locateOnScreen(\"img/{}.png\".format(str(obj)), confidence=0.9, grayscale=True)\n pyautogui.click(coords)\n break\n else:\n time.sleep(0.3)\n\n self.tries += 1\n print(str(self.tries))\n\n if self.tries > 50:\n break\n return self.tries\n\n\n def locateAll(self):\n time.sleep(2)\n img1 = pyautogui.screenshot(\"my_screenshotExBarr.png\")\n while True:\n time.sleep(2)\n print('Ally:') \n for pos in pyautogui.locateAllOnScreen(\"img/{}.png\".format(str(\"Enemy_Flashes\"))):\n print(pos)\n \n print(\"Enemy:\")\n for pos in pyautogui.locateAllOnScreen(\"img/{}.png\".format(str(\"Ally_Flashes\"))):\n print(pos)\n \n def click(self):\n for i in range(5):\n time.sleep(2)\n pyautogui.click(1001, 320)\n\n def checkLaneSlots(self, objects): # Where objs is a list of objects.\n for obj in objects:\n # Check Slot1 of every object.\n if (pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Ally_Flashes\")), confidence=0.8, region=obj.Slot1Region)):\n obj.Slot1 = \"Flash\"\n print(\"Found Flash Slot1\")\n elif (pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Enemy_Heal\")), confidence=0.8, region=obj.Slot1Region)):\n obj.Slot1 = \"Heal\"\n print(\"Found Heal Slot1\")\n elif (pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Enemy_Exhaust\")), confidence=0.8, region=obj.Slot1Region)):\n obj.Slot1 = \"Exhaust\"\n print(\"Found Exhaust Slot1\")\n elif (pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Enemy_Ignite\")), confidence=0.8, region=obj.Slot1Region)):\n obj.Slot1 = \"Ignite\"\n print(\"Found Ignite Slot1\")\n elif (pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Enemy_Barrier\")), confidence=0.8, region=obj.Slot1Region)):\n obj.Slot1 = \"Barrier\"\n print(\"Found Barrier Slot1\")\n elif (pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Enemy_TP\")), confidence=0.8, region=obj.Slot1Region)):\n obj.Slot1 = \"Teleport\"\n print(\"Found Teleport Slot1\")\n else:\n print(\"Did not find spells.\")\n\n # Check Slot 2 of every object.\n if (pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Ally_Flashes\")), confidence=0.8, region=obj.Slot2Region)):\n obj.Slot2 = \"Flash\"\n elif (pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Enemy_Heal\")), confidence=0.8, region=obj.Slot2Region)):\n obj.Slot2 = \"Heal\"\n elif (pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Enemy_Exhaust\")), confidence=0.8, region=obj.Slot2Region)):\n obj.Slot2 = \"Exhaust\"\n elif (pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Enemy_Ignite\")), confidence=0.8, region=obj.Slot2Region)):\n obj.Slot2 = \"Ignite\"\n elif (pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Enemy_Barrier\")), confidence=0.8, region=obj.Slot2Region)):\n obj.Slot2 = \"Barrier\"\n elif (pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Enemy_TP\")), confidence=0.8, region=obj.Slot2Region)):\n obj.Slot2 = \"Teleport\"\n else:\n pass\n\n\n #if (pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Ally_Flashes\")), confidence=0.9, region=obj.Slot1Region) and\n #pyautogui.locateOnScreen(\"img/{}.png\".format(str(\"Ally_Flashes\")), confidence=0.9, region=obj.Slot2Region)):\n # return True","repo_name":"Quorafied/LOL_Tracker","sub_path":"imageRecognition.py","file_name":"imageRecognition.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"57"} +{"seq_id":"23110205621","text":"from fontTools.misc import sstruct\nfrom fontTools.misc.fixedTools import (\n fixedToFloat as fi2fl,\n floatToFixed as fl2fi,\n floatToFixedToStr as fl2str,\n strToFixedToFloat as str2fl,\n)\nfrom fontTools.misc.textTools import bytesjoin, safeEval\nfrom fontTools.ttLib import TTLibError\nfrom . import DefaultTable\nfrom . import otTables\nimport struct\nimport logging\n\n\nlog = logging.getLogger(__name__)\n\nfrom .otBase import BaseTTXConverter\n\n\nclass table__a_v_a_r(BaseTTXConverter):\n \"\"\"Axis Variations Table\n\n This class represents the ``avar`` table of a variable font. The object has one\n substantive attribute, ``segments``, which maps axis tags to a segments dictionary::\n\n >>> font[\"avar\"].segments # doctest: +SKIP\n {'wght': {-1.0: -1.0,\n 0.0: 0.0,\n 0.125: 0.11444091796875,\n 0.25: 0.23492431640625,\n 0.5: 0.35540771484375,\n 0.625: 0.5,\n 0.75: 0.6566162109375,\n 0.875: 0.81927490234375,\n 1.0: 1.0},\n 'ital': {-1.0: -1.0, 0.0: 0.0, 1.0: 1.0}}\n\n Notice that the segments dictionary is made up of normalized values. A valid\n ``avar`` segment mapping must contain the entries ``-1.0: -1.0, 0.0: 0.0, 1.0: 1.0``.\n fontTools does not enforce this, so it is your responsibility to ensure that\n mappings are valid.\n \"\"\"\n\n dependencies = [\"fvar\"]\n\n def __init__(self, tag=None):\n super().__init__(tag)\n self.segments = {}\n\n def compile(self, ttFont):\n axisTags = [axis.axisTag for axis in ttFont[\"fvar\"].axes]\n if not hasattr(self, \"table\"):\n self.table = otTables.avar()\n if not hasattr(self.table, \"Reserved\"):\n self.table.Reserved = 0\n self.table.Version = (getattr(self, \"majorVersion\", 1) << 16) | getattr(\n self, \"minorVersion\", 0\n )\n self.table.AxisCount = len(axisTags)\n self.table.AxisSegmentMap = []\n for axis in axisTags:\n mappings = self.segments[axis]\n segmentMap = otTables.AxisSegmentMap()\n segmentMap.PositionMapCount = len(mappings)\n segmentMap.AxisValueMap = []\n for key, value in sorted(mappings.items()):\n valueMap = otTables.AxisValueMap()\n valueMap.FromCoordinate = key\n valueMap.ToCoordinate = value\n segmentMap.AxisValueMap.append(valueMap)\n self.table.AxisSegmentMap.append(segmentMap)\n return super().compile(ttFont)\n\n def decompile(self, data, ttFont):\n super().decompile(data, ttFont)\n assert self.table.Version >= 0x00010000\n self.majorVersion = self.table.Version >> 16\n self.minorVersion = self.table.Version & 0xFFFF\n axisTags = [axis.axisTag for axis in ttFont[\"fvar\"].axes]\n for axis in axisTags:\n self.segments[axis] = {}\n for axis, segmentMap in zip(axisTags, self.table.AxisSegmentMap):\n segments = self.segments[axis] = {}\n for segment in segmentMap.AxisValueMap:\n segments[segment.FromCoordinate] = segment.ToCoordinate\n\n def toXML(self, writer, ttFont):\n writer.simpletag(\n \"version\",\n major=getattr(self, \"majorVersion\", 1),\n minor=getattr(self, \"minorVersion\", 0),\n )\n writer.newline()\n axisTags = [axis.axisTag for axis in ttFont[\"fvar\"].axes]\n for axis in axisTags:\n writer.begintag(\"segment\", axis=axis)\n writer.newline()\n for key, value in sorted(self.segments[axis].items()):\n key = fl2str(key, 14)\n value = fl2str(value, 14)\n writer.simpletag(\"mapping\", **{\"from\": key, \"to\": value})\n writer.newline()\n writer.endtag(\"segment\")\n writer.newline()\n if getattr(self, \"majorVersion\", 1) >= 2:\n if self.table.VarIdxMap:\n self.table.VarIdxMap.toXML(writer, ttFont, name=\"VarIdxMap\")\n if self.table.VarStore:\n self.table.VarStore.toXML(writer, ttFont)\n\n def fromXML(self, name, attrs, content, ttFont):\n if not hasattr(self, \"table\"):\n self.table = otTables.avar()\n if not hasattr(self.table, \"Reserved\"):\n self.table.Reserved = 0\n if name == \"version\":\n self.majorVersion = safeEval(attrs[\"major\"])\n self.minorVersion = safeEval(attrs[\"minor\"])\n self.table.Version = (getattr(self, \"majorVersion\", 1) << 16) | getattr(\n self, \"minorVersion\", 0\n )\n elif name == \"segment\":\n axis = attrs[\"axis\"]\n segment = self.segments[axis] = {}\n for element in content:\n if isinstance(element, tuple):\n elementName, elementAttrs, _ = element\n if elementName == \"mapping\":\n fromValue = str2fl(elementAttrs[\"from\"], 14)\n toValue = str2fl(elementAttrs[\"to\"], 14)\n if fromValue in segment:\n log.warning(\n \"duplicate entry for %s in axis '%s'\", fromValue, axis\n )\n segment[fromValue] = toValue\n else:\n super().fromXML(name, attrs, content, ttFont)\n","repo_name":"catboost/catboost","sub_path":"contrib/python/fonttools/fontTools/ttLib/tables/_a_v_a_r.py","file_name":"_a_v_a_r.py","file_ext":"py","file_size_in_byte":5376,"program_lang":"python","lang":"en","doc_type":"code","stars":7463,"dataset":"github-code","pt":"57"} +{"seq_id":"38903217204","text":"import logging\nfrom collections import OrderedDict\n\nimport torch.nn as nn\nimport torch.utils.model_zoo as model_zoo\nimport torchvision.models.densenet as _model\nfrom torchvision.models.densenet import _DenseBlock, _Transition, model_urls\n\nimport model\n\n\nclass DenseNet(_model.DenseNet):\n def __init__(self, config_channels, anchors, num_cls, growth_rate=32, block_config=(6, 12, 24, 16), num_init_features=64, bn_size=4, drop_rate=0):\n nn.Module.__init__(self)\n\n # First convolution\n self.features = nn.Sequential(OrderedDict([\n ('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)),\n ('norm0', nn.BatchNorm2d(num_init_features)),\n ('relu0', nn.ReLU(inplace=True)),\n ('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),\n ]))\n\n # Each denseblock\n num_features = num_init_features\n for i, num_layers in enumerate(block_config):\n block = _DenseBlock(num_layers=num_layers, num_input_features=num_features, bn_size=bn_size, growth_rate=growth_rate, drop_rate=drop_rate)\n self.features.add_module('denseblock%d' % (i + 1), block)\n num_features = num_features + num_layers * growth_rate\n if i != len(block_config) - 1:\n trans = _Transition(num_input_features=num_features, num_output_features=num_features // 2)\n self.features.add_module('transition%d' % (i + 1), trans)\n num_features = num_features // 2\n\n # Final batch norm\n self.features.add_module('norm5', nn.BatchNorm2d(num_features))\n self.features.add_module('conv', nn.Conv2d(num_features, model.output_channels(len(anchors), num_cls), 1))\n\n # init\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n m.weight = nn.init.kaiming_normal(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def forward(self, x):\n return self.features(x)\n\n\ndef densenet121(config_channels, anchors, num_cls, **kwargs):\n model = DenseNet(config_channels, anchors, num_cls, num_init_features=64, growth_rate=32, block_config=(6, 12, 24, 16), **kwargs)\n if config_channels.config.getboolean('model', 'pretrained'):\n url = model_urls['densenet121']\n logging.info('use pretrained model: ' + url)\n state_dict = model.state_dict()\n for key, value in model_zoo.load_url(url).items():\n if key in state_dict:\n state_dict[key] = value\n model.load_state_dict(state_dict)\n return model\n\n\ndef densenet169(config_channels, anchors, num_cls, **kwargs):\n model = DenseNet(config_channels, anchors, num_cls, num_init_features=64, growth_rate=32, block_config=(6, 12, 32, 32), **kwargs)\n if config_channels.config.getboolean('model', 'pretrained'):\n url = model_urls['densenet169']\n logging.info('use pretrained model: ' + url)\n state_dict = model.state_dict()\n for key, value in model_zoo.load_url(url).items():\n if key in state_dict:\n state_dict[key] = value\n model.load_state_dict(state_dict)\n return model\n\n\ndef densenet201(config_channels, anchors, num_cls, **kwargs):\n model = DenseNet(config_channels, anchors, num_cls, num_init_features=64, growth_rate=32, block_config=(6, 12, 48, 32), **kwargs)\n if config_channels.config.getboolean('model', 'pretrained'):\n url = model_urls['densenet201']\n logging.info('use pretrained model: ' + url)\n state_dict = model.state_dict()\n for key, value in model_zoo.load_url(url).items():\n if key in state_dict:\n state_dict[key] = value\n model.load_state_dict(state_dict)\n return model\n\n\ndef densenet161(config_channels, anchors, num_cls, **kwargs):\n model = DenseNet(config_channels, anchors, num_cls, num_init_features=96, growth_rate=48, block_config=(6, 12, 36, 24), **kwargs)\n if config_channels.config.getboolean('model', 'pretrained'):\n url = model_urls['densenet161']\n logging.info('use pretrained model: ' + url)\n state_dict = model.state_dict()\n for key, value in model_zoo.load_url(url).items():\n if key in state_dict:\n state_dict[key] = value\n model.load_state_dict(state_dict)\n return model\n","repo_name":"ruiminshen/yolo2-pytorch","sub_path":"model/densenet.py","file_name":"densenet.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","stars":434,"dataset":"github-code","pt":"57"} +{"seq_id":"7618307385","text":"import os\nfrom tqdm import tqdm\nimport numpy as np\nimport random\nfrom distfit import distfit\nimport pandas as pd\nfrom sklearn.neighbors import KernelDensity\nfrom sklearn.model_selection import GridSearchCV\n\n \n# define the class for inspection of the input folder and generation of files list.\n# The extension as argument allows identifying specific files (.csv, .xlsx, .pdf, etc)\n# and making a list of those than can be called with the 'target_files' method\n#==============================================================================\n#==============================================================================\n#==============================================================================\nclass DataSetFinder:\n \n \"\"\" \n DatasetFinder(path, ext)\n \n Creates a list of files with given extension from the argument path, if the\n list is empty because no files were found, then the emtpy_folder variable is\n set to True\n \n Keyword arguments:\n \n path (str): path of the folder that has to be scanned for files \n ext (str): the target files extension (.csv, .jpeg, .pdf, etc)\n \n Returns:\n \n None \n \n \"\"\"\n def __init__(self, path): \n self.path = path\n extensions = ('.csv', '.xlsx')\n os.chdir(path)\n self.all_files = os.listdir(path)\n self.target_files = [f for f in self.all_files if f.endswith(extensions)] \n \n \n# define class for generation of synthetic values\n#==============================================================================\n#==============================================================================\n#==============================================================================\nclass DataGenerator:\n \n \"\"\" \n DataGenerator()\n \n Defines the ensembles of generator methods to produce syntethic dataframes,\n based on the original set of data. Different methodologies include CDF sampling,\n data fitting with standard distribution models and KDE models. Dataseries are\n generated as disjointed distributions.\n \n \"\"\" \n \n # generator of synthetic numbers based on CDF sampling\n #==========================================================================\n def CDF_generator(self, dataframe, num_val, pbar):\n \n \"\"\" \n CDF_generator(dataframe, num_val):\n \n Generates synthetic numbers using the CDF of the original dataframe as input,\n and sampling randomly to reproduce the reference distribution (disjointed).\n \n \n Keyword arguments: \n \n dataframe (pd.dataframe): dataframe of real numbers (original dataframe)\n num_val (int): number of synthetic values to be generated (int)\n \n Returns: \n \n fake_list (list): list of lists with synthetic data\n \n \"\"\" \n dataframe_numeric = dataframe.select_dtypes(include = np.number)\n fake_list = []\n real_list = []\n for id, col in enumerate(dataframe_numeric.columns): \n array = dataframe_numeric[col].values\n real_list.append(array)\n x = np.sort(array)\n n = x.size\n y = np.arange(1, n+1)/n\n synth_cols = []\n for num in range(num_val):\n randomizer = random.random()\n numy = np.interp(randomizer, y, x)\n synth_cols.append(numy)\n fake_list.append(synth_cols)\n pbar.update(id + 1, max=dataframe_numeric.shape[1])\n fake_df = pd.DataFrame(fake_list).T\n fake_df.columns = dataframe_numeric.columns\n \n return fake_df \n \n \n # generator of synthetic numbers based on theoretical distribution fitting\n #--------------------------------------------------------------------------\n def dist_fitter(self, dataframe, num_val, pbar):\n \n \"\"\" \n dist_fitter(dataframe, num_val):\n \n Generates synthetic numbers by fitting theoretical models to the original\n dataframe and generating new distribution with the best fitting model, based\n on the distift package. \n \n Keyword arguments: \n \n dataframe (pd.dataframe): dataframe of real numbers (original dataframe)\n num_val (int): number of synthetic values to be generated (int)\n \n Returns: \n \n fake_list (list): list of lists with synthetic data\n \n \"\"\"\n dataframe_numeric = dataframe.select_dtypes(include = np.number)\n fake_list = []\n real_list = []\n for id, col in enumerate(dataframe_numeric.columns): \n array = dataframe_numeric[col].values\n real_list.append(array)\n model= distfit(bound='both')\n model.fit_transform(array, verbose = 0)\n Xgen = model.generate(n = num_val).round(0)\n fake_list.append(Xgen)\n pbar.update(id + 1, max=dataframe_numeric.shape[1])\n \n fake_df = pd.DataFrame(fake_list).T\n fake_df.columns = dataframe_numeric.columns\n \n return fake_df \n \n # generator of synthetic numbers based on Kernel models (KDE)\n #--------------------------------------------------------------------------\n def KDE_generator(self, dataframe, num_val, seed):\n \n \"\"\" \n KDE_generator(dataframe, num_val, seed):\n \n Generates synthetic numbers using the Kernel methodologies of neighbour\n numbers. The bandwidth is selected through an initialization process (may\n take long time to finish). \n \n Keyword arguments: \n dataframe (pd.dataframe): dataframe of real numbers (original dataframe)\n seed (int): seed for random number generation\n num_val (int): number of synthetic values to be generated (int)\n \n Returns: \n fake_list (list): list of lists with synthetic data\n \n \"\"\"\n self.rand = np.random.RandomState(seed)\n self.dist_list = ['uniform','normal','exponential',\n 'lognormal','chisquare','beta']\n self.kernels = ['cosine', 'epanechnikov', 'exponential', \n 'gaussian', 'linear', 'tophat'] \n self.dataframe_numeric = self.dataframe.select_dtypes(include = np.number)\n self.fake_list = []\n self.real_list = []\n for col in tqdm(self.dataframe_numeric.columns): \n array = self.dataframe_numeric[col].values \n self.real_list.append(array) \n grid = GridSearchCV(KernelDensity(),\n {'bandwidth': np.linspace(0.1, 1.0, 30)},\n cv=20) \n grid.fit(array[:, None])\n kde = grid.best_estimator_\n synth_array = kde.sample(num_val, random_state=seed)\n self.fake_list.append(synth_array)\n \n return self.fake_list \n \n \n","repo_name":"CTCycle/SimpleTableGenerator","sub_path":"modules/components/data_classes.py","file_name":"data_classes.py","file_ext":"py","file_size_in_byte":7092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"9192734733","text":"for i in range(int(input())):\r\n l1 = {}\r\n l2 = {}\r\n ans = []\r\n ans_found = True\r\n for j in range(int(input())):\r\n a, b = [int(x) for x in input().split()]\r\n if (a not in l2.keys() and b not in l2.keys()):\r\n l1[a] = True\r\n l1[b] = True\r\n ans.append(\"1\")\r\n elif (a not in l1.keys() and b not in l1.keys()):\r\n l2[a] = True\r\n l2[b] = True\r\n ans.append(\"2\")\r\n else:\r\n ans_found = False\r\n if ans_found:\r\n print(\"\".join(ans))\r\n else:\r\n print(-1)\r\n\r\n\r\n\r\n","repo_name":"The-Dankest/competitive-programming","sub_path":"Online Judges/CodeForces/Round E58 D2/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"} +{"seq_id":"33846165221","text":"import requests\nfrom bs4 import BeautifulSoup\nimport bs4\nimport re\nimport json\nfrom pyecharts import Map, Geo\n\naqilist = [] # 储存城市AQI\nclist = [] # 储存城市链接\ncnlist = [] # 储存城市名字\ncwlink = [] # 异常链接\n\n\ndef get_all_city(): # 爬取\n url = \"https://ncov.dxy.cn/ncovh5/view/pneumonia\"\n try:\n kv = {'user-agent': 'Mozilla/5.0'} # 伪装成浏览器,headers\n r = requests.get(url, headers=kv)\n r.raise_for_status()\n r.encoding = r.apparent_encoding\n except:\n print(\"失败\")\n demo = r.text\n soup = BeautifulSoup(demo, \"html.parser\")\n area_information = re.search(r'\\[(.*)\\]', str(soup.find('script', attrs={'id': 'getAreaStat'})))\n area_information = json.loads(area_information.group(0))\n\n cities = []\n nums = []\n\n for area in area_information:\n for city in area['cities']:\n print(city['cityName'] + '确诊',city['confirmedCount'])\n cities.append(city['cityName'])\n nums.append(city['confirmedCount'])\n print(\"----\")\n print(\"****************************************************************\")\n\n geo = Geo(\"全国\", \"data\", title_color=\"#fff\", title_pos=\"center\", width=1200, height=600, background_color='#404a59')\n\n # type=\"effectScatter\", is_random=True, effect_scale=5 使点具有发散性\n geo.add(\"肺炎\", cities, nums, type=\"scatter\", symbol = \"circle\" ,is_random=True, effect_scale=10, visual_range=[0, 200],visual_text_color=\"#fff\",\n trail_length = 0.4 ,symbol_size=10, is_visualmap=True, is_roam=True,geo_normal_color=\"#323c48\",geo_emphasis_color='#2a033d')\n geo.render(path=\"./肺炎.html\")\n\n\ndef main():\n get_all_city()\n\n\nmain()\n","repo_name":"Perseus1993/AirQuality","sub_path":"crwal.py","file_name":"crwal.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"57"}